mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-02 16:58:52 +01:00
<!-- entire-trail-link-start --> https://entire.com/gh/paperclipai/-/trails/205/changes/paperclip/205 <!-- entire-trail-link-end --> ## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - Agents receive selected company skills before each turn. > - Imported skills can need files from the whole source repository. > - The current path stores those files in Postgres and reads large JSON payloads during preparation. > - This pull request stores verified packages in the configured file or object store and keeps preparation queries small. > - It also converts old rows automatically and restores missing files from the exact saved commit. > - The result reduces database traffic while preserving skill versions and repository dependencies. ## Linked Issues or Issue Description **What existing behavior does this improve?** Company skill import, version storage, and preparation before agent turns. **Current behavior** Repository snapshot bodies live in JSONB. Skill preparation can read those bodies again even when the files already exist on disk. Historical packages and native assets also need a bounded cleanup path. **Proposed behavior** Store package archives and manifests through the existing storage service. Keep version identities, receipts, hashes, and recovery metadata in Postgres. Convert legacy rows after the stored package passes read-back verification. A missing package can use legacy bytes or its exact Git commit under current repository authorization. No separate data-migration command is required. **Reason and benefit** The warm path sends no repository bodies through SQL and reads no object bytes. Cleanup runs through the existing deadline coordinator. Current versions, active runs, explicit pins, and authored content retain their protection. **Breaking changes** The normal application schema upgrade is required. Single-version and skill-file responses keep their existing shape. Version lists, current-version summaries, and test-run version summaries now contain file names and kinds without file bodies. Diff and restore fetch selected versions through the existing single-version endpoint. Older server builds must not write after conversion unless they support the new package format. The storage override and rollback limits are documented in `doc/skill-package-storage.md`. **Additional context** Related work: #15731 preserves repository dependencies; #17923 changes version-cache scheduling; #18080 changes delivery to remote Codex homes. This change owns package persistence, acquisition, and expiry. It does not replace those delivery or scheduler changes. ## What Changed - Add company-scoped archive receipts, exact-commit recovery recipes, migration deadlines, and a durable object-deletion queue. - Add bounded archive upload, read-back verification, extraction, concurrent request coalescing, and verified local caches. - Convert old snapshots and versions automatically. Keep legacy bytes when verification fails. - Recover missing files through current source authorization and the original commit. Validate repository identity, file hashes, modes, and the aggregate hash. - Expire unused recoverable Git packages and native assets after 30 days. Preserve active pins and the durable copy of authored or unproven content. - Keep warm preparation queries metadata-only. Bound file digest caches and avoid repeated body hashing when file identities are unchanged. - Extend the existing storage contract with cancellation. Register package work with the existing coordinator. Optional conversion retries retain the original bytes and may wait for ingress without blocking sleep. - Add regression tests, operating guidance, a deep trace, benchmark receipts, and an optional maintenance command. ## Verification ### Final master integration and review repair — October 29, 2026 Current head: `a6065424249e763dfeac37161f1b52a9f25bd9b7`. Commit `f8bbdd3dbd` resolves the conflicts with master `76a796e964`; the final two commits repair the Apex deletion findings below. - Keep both package-maintenance and version-retention notifications in their write transactions. - Keep the shared run-pin predicate and master's controller-lease deadline metadata. Package expiry reads the updated protected-version result. - Preserve every master migration entry. Generate migration **0415 (`0415_zippy_zemo.sql`)** after master's 0414. Its skill SQL is byte-for-byte unchanged from the previously tested idempotent migration. Retain only the five newest schema snapshots. Migration numbering and safety checks pass. - Repair failed file/folder deletion: preserve a complete temporary subtree until transaction commit, restore on upload or SQL failure, and restore callback failures before releasing the mutation lock. Both PostgreSQL regressions reproduced missing files before the fix and now pass. They cover binary data, executable permissions, empty folders, unlisted files, unchanged database/version rows, successful retry after upload-claim expiry, and historical reads. - Reconcile lost commit replies under the same advisory and row locks. Check the saved version and source identity before restoring. Keep committed deletions intact and preserve backups when the database outcome is unknown or a newer edit exists. Four real-PostgreSQL outcome tests pass; the prior code failed three of them. - Full workspace typecheck and production build pass on the final commit. All **204** focused PostgreSQL package/cache/retention/authoring and filesystem-boundary tests pass, with none skipped. - Apex review **18 passes 5/5**, with zero new comments on the exact final head. All **34** review conversations are resolved. - [Final-head CI](https://github.com/paperclipai/paperclip/actions/runs/40914116508) completes successfully on attempt 2. The head has **55 successful checks**, two neutral reports, two skipped checks, and a successful Snyk status. No checks are pending or failing. All eight browser shards pass. - Runner Vitest 2/2 timed out once in the unchanged ACPX controller-replacement fixture. The same job passed on the preceding commit. One unchanged CI retry passes all five ACPX recovery cases, **2,253** Runner package cases and **126** native server integration cases; their standard one and five skips remain. The initial timeout's root cause is not established. Local diagnosis also hit the fixture's eight-second session.open timeout with an authenticated Runner; no local Runner pass is claimed. - Both full local `pnpm test:run` attempts were stopped when Apex identified deletion defects and source repair became necessary; neither is claimed as a passing full local run. The final **204** focused tests, full workspace typecheck, and production build pass. Full-suite acceptance uses the final-head CI jobs. The superseded merge-head CI included runners terminated by shutdown signals; each source repair started a new full run. - Auto-merge is enabled for squash merge. The final head is conflict-free and all checks pass. GitHub's active master ruleset still requires a code-owner approval for the dependency files. The existing review requests are with `devinfoley`, `nickyleach`, and `forgottendev`; no policy bypass was used. - The earlier hosted stress and full native receipts below remain tied to `a2e597d800`; they are not relabeled as a deployment of this final integration. The earlier local PostgreSQL startup failure remains recorded below; PostgreSQL ran successfully for this integration verification. ### Full native skill execution — October 29, 2026 The full native-agent acceptance gap is closed on candidate `a2e597d800eb989d565780e7aa947d5368676444`. Two qualifying native turns used OpenAI API / `gpt-5.4-mini` in real Daytona sandboxes, on the same disposable hosted TEST tenant as the stress test. A follow-up on the same task consumed a newly saved skill version. The task text asked for the assigned skill workflow. It did not contain the proof nonce or expected receipt. The assigned authored skill contained a Python verifier and a random package-local nonce. The agent read the actual installed skill files and executed that verifier against the imported, automatically converted 1,360-file repository package. It checked the repository file count and reference/binary bytes, and directly executed the repository's executable probe. Independent verification matched the emitted JSON to the nonce and expected byte hashes. The agent persisted the same receipt as its task response; native finalization committed, workspace finalization succeeded, and task state became Done. | Qualifying turn | End-to-end run time | Recorded skills.prepare | Repository files | Binary hex | Shell receipt SHA-256 | |---|---:|---:|---:|---|---| | Initial task | 47.881 s | 1822 ms | 1360 | `00ff07800a` | `a1deb30dc095f2306c7aa9cc5ec396da12c68961cf5b809f4d7c20f7fc68493b` | | Corrected follow-up, new nonce/version | 37.974 s | 377 ms | 1360 | `00ff07800a` | `dbcdc33fa1376b4edc136feae1cdf770560a73292467e93619efdda20e4282a7` | Both successful shell receipts reported `probe: STRESS18082` and `assetSha256: e8ea7a2f15f7bb3b332a46adbef848465884c8996595aa234748befd544d1f3a`. Their proof nonces, selected version IDs and receipt hashes differed, and both ran on the same task. These are observed timings, not latency SLOs; they include real provider work. The service stress-test timings remain a separate measurement boundary. Earlier failures remain in the evidence: - The original five-minute Daytona allocation timeout never reached model execution. After normal owned-stack restore, its durable cleanup record was `expired` / `success`. The cause of that original allocation timeout remains unknown; a later success establishes recovery only. - Initial continuation setup used unsupported generic agent-update fields and returned HTTP 409 before dispatch. Setup was corrected to use the supported skill-assignment and versioned instruction commands. - The intervening completed native turn read repository bytes and ran the probe, but omitted the verifier JSON under the older test agent's overly-specific instruction file. Its strict receipt validator failed; it is not counted as a qualifying turn. Correcting the test agent's instruction file and sending an explicit task-scoped wake produced the qualifying follow-up above. - The pinned application's immutable rate card omits `gpt-5.4-mini`, so completed usage triggered the normal block-on-unpriced budget policy. Supported append-only accounting corrections estimated the three completed runs using the [official OpenAI model rate card](https://developers.openai.com/api/docs/models/gpt-5.4-mini): $0.75 input, $0.075 cached input, $4.50 output per million tokens, assuming standard processing. Estimates totaled 12.482655 cents. Original usage and missing-price records are preserved; the $1 hard stop and unpriced-usage guard stayed active. - Model shell attempts included a missing `xxd` command and incorrect guessed file paths. Those failed calls and subsequent successful actual verifier calls remain visible in complete event streams. No zero-tool-error claim is made. No product source changed during this continuation. The previously measured contention, cold-start and memory limits remain. The later merge resolution is covered by the separate integration checks above; these hosted receipts qualify their recorded candidate. ### Hosted stress test — October 29, 2026 **Hosted acceptance:** full native-agent execution and a changed-skill follow-up pass on the recorded hosted candidate. The final integration section above records the subsequent conflict resolution and its separate checks. Tested baseline `929e840595c8933ca485ac7a2e99413e1e11ca64` and this exact candidate sequentially on one disposable TEST tenant, with external Neon PostgreSQL and actual S3. The fixture contained **1,360 files / 22.4 MB / ten skills sharing one repository**. Measurements cover deployed skill-preparation and native-context services in an adjacent diagnostic process, not a complete agent turn. The container had **24 vCPU / 24 GB**. | Warm workload | Median before → after | p95 before → after | DB returned value bytes/preparation before → after | |---|---:|---:|---:| | One skill, serial | 1,060 → 125 ms | 1,303 → 155 ms | 22,610,389 → 1,771 | | One skill, four concurrent | 4,415 → 297 ms | 5,143 → 328 ms | 22,610,389 → 1,771 | | Ten skills, serial | 5,723 → 535 ms | 6,057 → 600 ms | 224,739,030 → 10,671 | | Ten skills, four concurrent | 24,410 → 1,986 ms | 24,833 → 2,221 ms | 224,739,030 → 10,671 | - Candidate warm preparation performed **zero S3 GETs**. Ordinary-pool queries fell from 16 to 9 for one skill and 61 to 9 for ten, excluding dedicated lock connections. DB numbers measure returned values before Drizzle decoding, not wire bytes. Baseline/candidate sample counts were 30/100, 32/100, 5/50 and 8/48 respectively; the small baseline ten-skill samples are comparative evidence, not SLO estimates. - **Application-UID soak:** 800 ten-skill preparations over 10.3 minutes, four workers paced by 2.5 seconds; **zero failures**, median **559 ms**, p95 **775 ms**, p99 **910 ms**, zero warm S3 reads. All 726 accompanying health/company-list requests returned HTTP 200. Their end-to-end p95 was 569/502 ms, including network latency. The probe overlaps most of the soak. Soak DB-response capture was limited to its first 60 seconds. - **Important remaining costs:** an unpaced 16-way ten-skill burst had p95 **8.32 seconds** because company-level preparation serializes. Cold preparation took approximately **1.1–2.5 seconds** for one skill and **7.4–10.0 seconds** for ten. Ten-skill diagnostic RSS remained about **1.17 GiB** (baseline 1.18 GiB), and the soak peaked at **1.35 GiB**. A concurrent whole-container sample was 3.45 GB. This does not establish suitability for a small-memory host or eliminate per-entrypoint native asset duplication. - **Upgrade without a manual data migration passed:** legacy snapshot JSON shrank from 22,465,691 bytes to `[]`, with a stored package and zero pending conversions. - **Recovery passed:** sixteen concurrent cold requests coalesced into two S3 GETs; full bytes/binary/executable modes matched; same-size corruption repaired; an injected storage failure preserved warm access and failed cold access safely. A disabled public-Git source denied recovery, and after the actual five-minute backoff its exact SHA reconstructed all 229 files. Cross-company descriptor access was denied. Private-Git credential revocation was not tested. - **Retention passed:** reclaimed 27,754,496 allocated cache bytes, deleted an unreferenced package row and both objects, preserved aged authored history, and expired/reacquired reconstructible Git content. A version pinned by the failed native run was correctly retained. Only owned fixture timestamps were aged. - **Browser UI passed:** authored skill creation, saved edit surviving reload, version history, and restoration of earlier content. - **Initial native attempt (superseded by the qualifying turns above):** one real run failed at Daytona allocation after five minutes (`setup_failed`), before any model execution. Provider cleanup also reported failure. That attempt does not count as a passing native turn. Its receipt and all evidence remain preserved; its cleanup later recorded success after normal restoration. - Initial A/B commands ran as SSH root. Diagnostic-owned lock/cache permissions caused one setup HTTP 500 and the first UID-1000 soak to fail; exact fixture paths were repaired. The final soak, retention and recovery ran as application UID 1000. A fresh UID-1000 one-skill batch also passed (30 samples, median 116 ms, p95 321 ms, 1,771 DB value bytes/preparation). Earlier harness-export, SSH, npm provenance, backoff and UI-wait failures remain recorded alongside their successful retries. - Private evidence includes raw timings, assertions, HTTP probes, screenshots and failure/cleanup receipts. Initial failed-campaign cleanup suspended and retained the owned TEST tenant and released the shared QA account lease at **15:22:41 UTC**. The tenant was subsequently resumed under its existing ownership for the native execution qualification above. Final cleanup completed at **15:53:09 UTC**: the account lease is released and the tenant is suspended/retained under the original October 30, 12:24:52 UTC retention deadline. Its separate stack lease remains held; no active or pending-cleanup environment lease remained. The original retention window is deliberately preserved even after successful continuation. - Earlier hosted-tested head: `a2e597d800eb989d565780e7aa947d5368676444`, integrated with master `929e840595`. The earlier merge conflicts were resolved at this head. [Current-head CI](https://github.com/paperclipai/paperclip/actions/runs/40884087629) passed; all checks are complete with 55 successes, two neutral reports, two skips, and no failures. [Apex review 15](https://github.com/paperclipai/paperclip/pull/18082#issuecomment-6480257258) passed 5/5 with zero findings on this exact head. All review conversations are resolved. - Ten real-filesystem boundary cases and server typecheck pass locally for the security fix. Coverage includes cache roots, descendants, individual files, symlink aliases, recursive ancestors, a future concurrent cache fill, and allowed sibling directories. [Current-head private-project integration tests](https://github.com/paperclipai/paperclip/actions/runs/40884087629/job/123483306405) passed all 29 cases, including authorized and unauthorized imports of a cached private package. Full typecheck, build, server suites, all eight browser shards, and Runner checks passed in current-head CI. Local database tests could not run because PostgreSQL could not initialize; this limitation is recorded below. - The earlier generated migration preserved the newest five snapshots. The final integration renumbers its unchanged SQL to 0415. Migration safety/numbering checks pass. Its SQL is byte-for-byte identical to the previously verified idempotent skill migration; repeated application on this latest schema was blocked by the same local database startup failure. - The broader verification before the final migration-only rebase passed 1,025 package, lifecycle, remote-launch, native-session, and asset-retention tests, 52 focused UI tests, full workspace typecheck/build, token gates, and map checks. The linked complete CI run passed before the latest focused fixes. - A disposable MinIO instance passed multipart upload, verified read-back, and cold restoration of an 18 MB archive. - Twenty warm samples with a synthetic 1,349-file, 22.8 MB repository retained five metadata queries and zero object reads. Median preparation was 256 ms for one selected skill and 691 ms for ten, with 5 ms emulated network delay each way. These are local measurements, not production latency guarantees. - No production instance was changed. Earlier verification failures and their disposition are retained below. <details> <summary>Earlier failures, review findings, fixes, and rerun evidence</summary> - The first CI pass found a stale inventory-span expectation and a missing repository-read span. Both are fixed; all three observability tests pass. One browser test copied page text into its YAML parser after reload; its first unchanged-head retry passed, but the race recurred after rebasing. The test now waits for the renamed URL and completed reload before copying the editor, retaining its original assertions. The earlier full local suite did not complete cleanly: it reported setup timeouts and assertions, while isolated relevant reruns passed. The complete current-head CI run closes that broad verification gap. No production instance was changed. - The first Apex review scored 2/5 and identified six issues. The fixes protect authored history even when it shares an in-flight Git upload, recheck upload expiry during orphan deletion, bound failed-upload cleanup, retain per-version kind/encoding metadata, add sanitized failure diagnostics, and correct the migration guide. The final focused run passes all 140 tests; the preceding eight-file run passed all 149 tests, including local storage and S3 diagnostics. Server typecheck and migration safety/numbering checks pass after the fixes. The second Apex review scored 1/5 and found unbounded maintenance storage calls and mismatched package/Git batch limits. Those are fixed with a 30-second cancellable cleanup deadline, shared 100 MiB/10,000-file scanner and storage limits, and bounded Git read batches. The proposed manual lockfile edit was rejected with evidence of the enforced CI-owned lockfile policy. All 19 storage/recovery unit tests and server typechecking pass. The new database-backed cleanup/conversion tests were locally skipped because the host exhausted its PostgreSQL semaphore capacity (confirmed directly by initdb). That gap is closed by current-head CI: [package-store tests](https://github.com/paperclipai/paperclip/actions/runs/40771320775/job/123109300889) pass all 18 cases and [package-worker tests](https://github.com/paperclipai/paperclip/actions/runs/40771320775/job/123109301157) pass all 7, with no skips in either suite. The corrected YAML browser shard passes. A separate planning-fixture test failed its cleanup DELETE with an activity-log foreign key violation after its behavior assertions passed; its one unchanged-head retry passed. The third Apex review scored 1/5 and identified a one-slot pool deadlock, projected path limits, cleanup holding the preparation lock during archive reads, and a publication/expiry race. These are fixed with transaction-local reads, prefix-aware bounds, isolated verification, and shared package row locks with a publication grace. The separate Paperclip review also found stale historical inspection, eager history downloads, and conversion retries blocking sleep. Those are fixed. Local PostgreSQL capacity recovered: the new database regressions ran, including the one-slot fork, paused storage during a warm turn, and a locked publication during expiry. The expanded run passed 144/145 tests; its remaining assertion still expected file bodies from the version list and was updated to fetch the selected version. The corrected company-skill suite passes all 81 tests, and the final package/projection run passes all 27. All 52 focused UI tests pass after updating their query-provider fixtures; the first UI run exposed a fixture remount, and the follow-up exposed an editing syntax error, both corrected. Full workspace typecheck and build, token gates, and map checks pass. The sandbox initially blocked the build tool’s local IPC socket; the authorized build rerun passed. Master then claimed migration 0401. The branch is rebased onf8226b0515, the unchanged SQL is regenerated as 0402, and repeated application passed twice on the combined schema. Post-rebase workspace typecheck passes. All 1,025 package, lifecycle, remote-launch, native-session, and asset-retention tests pass on the combined head. All CI checks passed for head 9d80a3b52d. The fourth Apex review scored 3/5 and found a save/edit lock-order cycle, a retry retaining an uncommitted source ID in its recovery recipe, and a summary read racing conversion. Commit b7d9237c6a fixes all three. The new concurrency and retry tests pass within all 61 package/source tests, and server typecheck passes. Master then claimed migration 0402. The branch is now rebased on65fa1cd617and the unchanged SQL is regenerated as 0403. All 68 package, source, and worker regressions, server typecheck, migration safety/numbering, and repeated migration application pass on current head62553671a0. Subsequent verification and review outcomes are recorded below. - The fifth Apex review scored 4/5 and found cached version reads unnecessarily depending on object storage and conversion reads missing the coordinator cancellation signal. Commit1eb90d80befixes both: cached reads verify bytes without the preparation lock; manifest and archive reads carry cancellation through conversion. The first focused run passed 70/71 tests, including all three new cases, but the existing diagnostic test observed no warning. Its fixture now sets an explicitly expired migration deadline; the final worker suite passes all nine cases. Server typecheck passes. - The sixth Apex review scored 4/5 with one finding: concurrent cached inventories were unbounded. Commit4b7589e14cgives cached inventories and previews a two-reader/32-waiter limit independent of cold storage. The first expanded pressure test observed a third reader before the preview path had the same bound; both paths now share the local limit. All 73 focused cases pass, followed by all 29 package cases after the final overload adjustment; server typecheck passes. The separate Paperclip review found no must-fix or should-fix issues. Its optional suggestion to persist durability verification was considered: cleanup intentionally verifies current external bytes before discarding the last local authored copy, and the missing-object regression requires that check. Shared-package eviction happens on cold fills with at most two attempts and a ten-second budget. - The seventh Apex review reached 5/5 with one remaining P2: timeout-bearing manifest reads bypassed request coalescing. The security review also found repeated archive acquisition after a cold administrative read. Commit79a80a39d2shares manifest loads with per-caller cancellation and cancels the underlying work when the last caller leaves; coalesces identical cold version/file requests; and publishes verified restored packages into the shared cache. Publication uses a short nonblocking lock, while eviction verification runs outside it. The first expanded run passed 73/74 tests and exposed a missing originating DB for cache publication inside read-only inspection; transaction readers now pass that owner explicitly, keeping metadata on the transaction. The corrected run passed 75/75. A final eviction test initially expected the shared package to remain after only its separate runtime projection was reused; it now explicitly accesses the shared package during verification. All 32 final package tests pass, including independent caller cancellation, one acquisition across concurrent/repeated reads, and warm preparation during stalled eviction verification. Server typecheck passes. - The eighth Apex review scored 4/5 with one finding: decoded cold inventories outlived the storage semaphore while waiting for cleanup. Commit9d7921d1ecadds a separate two-response/32-waiter lifetime bound held through cleanup, preserving the independent warm-read queue and forwarding cancellation through eviction verification. The new regression pauses cleanup after two responses decode, verifies a third archive stays queued, and completes warm preparation before releasing cleanup. All 77 package/source/worker cases and server typecheck pass. On the preceding head, serialized server shard 6/9 was interrupted with “The operation was canceled” after 57 seconds of tests; the log contains no failing assertion. Fresh latest-head CI reruns that shard along with the other gates. - The ninth Apex review scored 4/5 with one P1: cold responses could own both permits while waiting on a one-slot ordinary database pool held by a queued transaction reader. Commita94f0e409freads caller-scoped metadata before admission and isolates all acquisition/cleanup SQL on a private connection. The new real-PostgreSQL regression reproduces the deadlock against the previous head and passes with the fix; all 78 focused cases and server typecheck pass. The previous CI run completed with 54 successful checks, including both formerly interrupted/stuck serialized shards. - The tenth Apex review scored 4/5 with one P1: preloading legacy bodies before admission could retain many full repositories in queued requests. Commit276e353a37removes that preload and also bounds legacy manifest derivation/fallback, using private connections inside the I/O slot. All 80 focused tests pass; the final synchronized package suite passes all 36 tests and server typecheck passes. - Apex review 11 returned 5/5 with zero comments on276e353a37. While it ran, master8bc051245fadded migration 0403, creating a metadata conflict. Merge commite1783764d9integrates master and generates 0404_clumsy_leo.sql; its skill SQL is byte-for-byte identical to the previously verified migration. The combined schema passes migration safety/numbering, repeated SQL application twice, all 80 focused PostgreSQL tests, full workspace typecheck, and full build. The precedinga94f0e409fCI run was superseded and cancelled while its final runner job was active; no old-head success is claimed for that run. - Final acceptance: Apex review 12 returned 5/5 with zero comments one1783764d9. All 28 review threads are resolved. The final head has 55 successful checks, two neutral reports, two skipped checks, and no pending or failing checks; the PR workflow completed successfully. Superseded run 40789121902 was cancelled to free its workflow slot for the final head; normal cancellation did not finish promptly, so force cancellation completed it. - October 29 conflict resolution (867c00673b): master929e840595added installed-selection reuse and bundled relocation, routine cleanup notifications, a hardened YAML copy helper, and migrations through 0413. The merge retains those behaviors together with package read scoping and the public-selection fast path; restricted selections still reauthorize and the full row read rechecks scope. Generated migration 0414 retains the existing SQL unchanged. Workspace typecheck/build and migration checks pass. Local database verification is unavailable: initdb reports semget / “could not create semaphores: No space left on device”; all 168 cases skipped, and repeated migration application failed at startup. Docker returned HTTP 500 during container creation, so no Docker test pass is claimed. Current-head CI must close this gap. - Apex review 14 scored 3/5 with one P1: a local import could copy cached private package files into a company-wide skill. Commita2e597d800rejects cache trees and ancestors through a canonical filesystem boundary, including aliases and ancestors checked before a concurrent fill. Ten local filesystem tests and server typecheck pass. The existing private-project integration case now rejects package-cache imports for both authorized and unauthorized users. The preceding merge commit’s complete CI run passed, and logs confirm all 168 locally skipped cases executed successfully: package store 36, sources 35, package worker 9, runtime selection 4, observability 3, authoring 81. - Apex review 15 returned 5/5 with zero new findings ona2e597d800. The separate Paperclip review found no must-fix or should-fix issues. Its optional suggestions were considered: unexpected filesystem cleanup failures remain visible, the durable marker cannot replace checking that bytes still exist before deleting a last local authored copy, and administrative history batching remains outside the pre-turn optimization. The cache-path literal centralization suggestion is also optional; the current producer and guard use the same directory, covered by the new integration regression. All review conversations are resolved. - Earlier October 29 CI/Apex acceptance:a2e597d800was mergeable at that check, Apex review 15 passed 5/5 with zero findings, and all review conversations were resolved. The hosted verification above records the later acceptance limits and renewed conflicts. Workflow 40884087629 completed successfully, with 55 successful checks, two neutral reports, two skips, and no pending or failed checks. The project-skill-sources job log confirms all 29 cases ran and passed, closing the latest integration gap. The preceding merge workflow also confirmed all 168 focused database cases ran and passed. No local PostgreSQL or Docker pass is claimed. </details> ## Risks - First use after eviction can require storage or Git access. Revoked grants, removed sources, and unreachable commits can prevent reconstruction. Recovery never substitutes a newer commit. - Historical packages without a proven recipe keep durable bytes. Cleanup favors retention when a run pin cannot be interpreted safely. - New uploads and conversion use bounded work and persisted retries. Large initial conversions still add temporary storage and database load. - Optional cleanup can wait until the next server wake. Supported notifications assume one owning server process. - Per-entrypoint native tree duplication and cold preparation cost remain. The final ten-skill cold sample took 47.6 seconds on the shared host. - Generic authored edits can still hold an existing edit transaction while a package uploads. - Explicit file/folder deletion uses temporary disk space for rollback. An uncertain commit with a changed skill or unavailable database retains that backup and logs its location for recovery. ## Model Used OpenAI Codex, GPT-6 family, with reasoning, repository tools, code execution, and tests. The exact served model ID and context window are not exposed in this session. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
459 lines
29 KiB
Markdown
459 lines
29 KiB
Markdown
# Automatic idle sleep safety
|
|
|
|
`GET /api/instance/task-drain?idleSleepSafety=1&ownerId=<owner>` adds an
|
|
instance-wide `idleSleepSafety` report for instance administrators and signed
|
|
Cloud control callers. Ordinary task drains keep their existing behavior.
|
|
Company members and agents cannot read this report.
|
|
|
|
## Hosting protocol
|
|
|
|
1. Hold external admission at the hosting layer. Queue user requests for wake or
|
|
abort sleep when activity arrives. Do not send traffic into an instance that
|
|
is being stopped.
|
|
2. Send `POST /api/instance/task-drain` with
|
|
`{ "purpose": "idle", "ttlMs": 120000 }`. Idle holds require a TTL from 5 to
|
|
300 seconds. Save the returned `ownerId` and `expiresAt`. An existing drain
|
|
returns 409. An unsupported purpose must leave automatic sleep disabled.
|
|
3. Poll the report with that exact owner. Only
|
|
`{ "version": 1, "backgroundWork": "none" }` permits ordinary idle sleep. The
|
|
optional routine protocol below requires a durable host alarm as well. Require the same
|
|
`ownerId`, `draining: true`, zero run/wake counters, and enough remaining TTL
|
|
for the provider stop. `present`, `unknown`, missing fields, or errors must
|
|
keep the instance awake. Do not interpret `quiescent` alone as authorization.
|
|
4. Revalidate the same hold immediately before stopping the instance. Keep
|
|
external admission closed through the provider stop. Never use an old report
|
|
after a restart, expired hold, changed owner, or failed validation.
|
|
5. If sleep is abandoned, send `DELETE /api/instance/task-drain?ownerId=<owner>`.
|
|
A missing or stale owner cannot release another controller's idle hold. The
|
|
TTL clears an abandoned hold if the controller loses its response.
|
|
|
|
An idle hold rejects new tenant HTTP requests and WebSocket upgrades with 503
|
|
and `Retry-After: 1`. Health checks and authenticated task-drain control remain
|
|
available. Ordinary deploy drains do not enable this HTTP gate. The host must
|
|
handle retry/wake at its ingress before enabling automatic sleep.
|
|
Health and control mutations remain tracked through completion, including
|
|
signed bootstrap writes. Only the task-drain read skips request tracking.
|
|
Its authentication finishes under a separate work token before entering the
|
|
report, so it counts concurrent writes without blocking on its own scan.
|
|
|
|
A matched static UI file served by the admitted, handler-tracked application finishes its request
|
|
tracking when its response ends or closes, including a match found after the
|
|
client has already disconnected. Unfinished middleware promises remain tracked.
|
|
Routers share this application scope. A mounted Express application has hidden
|
|
handler promises, so it keeps the existing conservative hold after an aborted
|
|
download until the application itself completes the response. An application
|
|
without installed handler tracking keeps the same conservative hold. Missing files
|
|
continue through the normal fallback and error handlers; they do not exempt
|
|
other GET requests or callback-only application work.
|
|
|
|
## Budget and agent lifecycle work
|
|
|
|
Budget accounting commits its charge, admission block, and enforcement generation
|
|
before returning to its caller. Cancellation delivery runs separately through the
|
|
delivery coordinator, using the existing policy version pair and committed run
|
|
Stop records. It can finish already-admitted stops during drain, but cannot start
|
|
another paid turn. A provider still stopping, an unacknowledged Stop, a pending
|
|
policy generation, and unresolved accounting remain sleep blockers.
|
|
|
|
Agent lifecycle uses the same transaction-aware coordinator. Hire approval,
|
|
configuration invalidation, manual commands, and computed agent budget holds
|
|
register work before their transaction writes. Company status transitions register
|
|
inherited-hold projection; changing a company name, description, or logo does not.
|
|
Projection selects only agents whose company pause/archive hold differs from the
|
|
committed company state, in pages of 100 under one company accounting transaction
|
|
per page. Pause/archive transactions also persist pausing operations for agents
|
|
with cancellable runs, reading only those involved agents in batches. Immediate
|
|
reactivation can remove an inherited hold but cannot erase an owed Stop; new
|
|
provider work waits for lifecycle readiness. Archive activity counts describe
|
|
requested pauses and cancellations, not completed provider termination. Agent
|
|
and project budget changes never enumerate company peers.
|
|
|
|
Startup recovers pending lifecycle operations and inherited-hold mismatches.
|
|
Thereafter notifications and stored retry/lease deadlines drive work. Stable ready,
|
|
paused, rejected, and terminated history does not trigger recurring policy scans.
|
|
Pending phases and inherited-hold mismatches block sleep. Lifecycle execution can
|
|
verify configurations or resume queued work, so it waits while admission is
|
|
draining or the instance is in warm standby; its durable obligation is retained.
|
|
A future in-process retry timer does not grant permission to sleep.
|
|
|
|
These notifications cover the existing single-active-writer ownership model.
|
|
Independent SQL writers and additional processes need an explicit wake protocol;
|
|
process-local notifications do not provide cross-replica delivery. Worker quiet
|
|
alone is not evidence that the host or database actually suspended.
|
|
|
|
## Scheduled routine wake protocol
|
|
|
|
Historical failed ephemeral leases and terminal custom-image setup sessions can
|
|
become idle only after the host observes deletion of their exact provider
|
|
resource. Cloud checks bounded batches on already-awake instances, outside the
|
|
readiness path. The optional `environmentInspectLease` plugin RPC is read-only:
|
|
it must never reconnect, start, stop, or destroy an allocation. Older workers
|
|
without this method remain conservative. Daytona accepts its SDK's typed
|
|
not-found response; authentication and transport failures are not deletion
|
|
proof. Setup checks require the recorded provider-config fingerprint; lease
|
|
checks use the recorded plugin and scoped config, never a replacement binding.
|
|
For legacy secret references without a version manifest, only an unrotated
|
|
initial version with a matching resolved-value hash establishes credential
|
|
identity. Rotated/mutable credentials and ambient Daytona keys defer proof;
|
|
not-found under another account cannot establish historical cleanup. Inspection
|
|
also rejects an ambient API endpoint override when no endpoint was recorded.
|
|
The manager permits at most two outstanding inspection RPCs across workers.
|
|
Caller timeouts retain their slots until the actual worker reply or exit;
|
|
timeouts cannot accumulate additional provider reads in later sweeps.
|
|
|
|
Host-owned verification metadata binds the company, environment, resource,
|
|
provider handle, optional run, and exact row version. Concurrent resume,
|
|
replacement, cleanup, or configuration changes invalidate verification.
|
|
Provider-supplied metadata cannot supply this marker. Inspection preserves
|
|
failure outcomes and history and does not create a run-continuation receipt.
|
|
Normal setup cancellation and timeout preserve the host's recorded config
|
|
fingerprint and RPC company scope for later read-only verification.
|
|
Retained allocations, unfinished runs/accounting/retries, export intents and
|
|
live setup credentials continue to block sleep.
|
|
|
|
Pending human-only connection setup can wait asleep when no active enabled
|
|
connection of the requested purpose exists. Available access reblocks sleep so
|
|
the existing reconciliation path can run; answering a setup card continues to
|
|
use the normal admission and wake path.
|
|
The delivery worker uses the same passive-wait proof to release its local
|
|
admission hold. On an already-awake instance it keeps its existing five-second
|
|
maintenance cadence, without creating a wake alarm. This catches newly available
|
|
access even when its write does not notify the connection queue. Pending real
|
|
deliveries and their downstream wake requests still block sleep.
|
|
An owned drain pauses passive-only maintenance before it admits tracked work,
|
|
so a slow pre-sleep backup can finish with an unchanged generation. New producer
|
|
notifications still preempt the maintenance timer and invalidate that backup.
|
|
|
|
An unconfigured Slack draft can also wait for browser setup when its matching
|
|
channel connection is disabled and still a draft. It must have no provider
|
|
identity, prior activation/activity, or setup error. Partially configured,
|
|
enabled, foreign, and other-provider endpoints remain blockers; accepted chat
|
|
deliveries retain their independent checks.
|
|
An optional Slack slash-command name is configuration only and does not create
|
|
background work. Other setup fields still retain their blockers.
|
|
|
|
Cloud also reconciles missed routine issue-status hooks in bounded batches on
|
|
awake instances. Exact company/routine/issue/run ownership and row locks are
|
|
required. The normal routine service records completion or transient failure
|
|
from the current issue status; a resumed issue can use its existing continuation
|
|
rules. This repairs stale handoff bookkeeping without exempting unprocessed
|
|
routine runs or consuming deferred comment requests.
|
|
Lock contention and retryable transaction failures defer only that candidate;
|
|
other repairs continue, and later sweeps retry the deferred row.
|
|
|
|
Verified signed Cloud control callers may opt into
|
|
`GET /api/instance/task-drain?idleSleepSafety=1&scheduledWake=1&ownerId=<owner>`.
|
|
Tenant tokens, browser instance administrators, local implicit actors, and agents
|
|
cannot request this extension. Ordinary reports retain their existing behavior.
|
|
|
|
If all other background-work checks pass, active routines may return
|
|
`idleSleepSafety: { version: 2, backgroundWork: "none", scheduledWake }`.
|
|
The proof has `version: 1`, `kind: "routines"`, a SHA-256 `generation`, and the
|
|
earliest `nextWakeAt` across every company. Only enabled, unarchived schedule
|
|
triggers with valid cron, timezone and future `next_run_at` qualify. Unsupported
|
|
triggers, setup work, due work, unknown states and more than 10,000 active
|
|
triggers keep the instance awake. Inactive triggers do not create obligations.
|
|
Active routines without enabled triggers have no timed work. Definitions are
|
|
read in the same repeatable-read transaction as the other durable checks.
|
|
|
|
The host must commit one durable alarm for the exact stack under its live sleep
|
|
lease before stopping compute. It must then re-read the same owned report and
|
|
require the exact generation and deadline. Generation binds the process, hold
|
|
owner and routine/trigger catalog, so restart or schedule edits invalidate it.
|
|
No routine definitions or tenant identifiers appear in the proof. Failure to
|
|
persist or validate the alarm abandons sleep. Cloud acknowledges persistence
|
|
inside its controller; this report alone never authorizes scheduled sleep.
|
|
|
|
Cloud must start waking early enough for measured startup latency and retry
|
|
failed or missed wakes across controller restart. After wake, the existing
|
|
routine scheduler owns execution, atomic claims and catch-up rules. Local
|
|
scheduling is unchanged for self-hosted instances and whenever Cloud declines
|
|
sleep. This first extension covers routines only. Agent timers, plugin jobs,
|
|
retries, integrations and unsupported queues retain their existing blockers.
|
|
All mutations must enter through the host admission/wake path. Independent
|
|
database writers are outside this single-process protocol.
|
|
|
|
Verify a full scheduled sleep/wake/execution cycle on staging before enabling
|
|
this host capability. The [tests](../server/src/__tests__/idle-sleep-safety.test.ts)
|
|
cover ownership, future deadlines, changed generations and conservative fallback.
|
|
|
|
## Passive issues and scheduled monitors
|
|
|
|
Signed Cloud control callers can request `scheduledWake=2` to include issue
|
|
monitoring alongside routines. Earlier hosts requesting `scheduledWake=1`
|
|
retain the routine-only rules, including the conservative open-issue check.
|
|
Browser administrators and tenant credentials cannot request either extension.
|
|
|
|
With the second capability, backlog tasks, unassigned todo tasks, explicit
|
|
blocked tasks and human-owned tasks may be passive records. Their presence
|
|
alone does not require compute. An assigned onboarding first task is also
|
|
passive with an idle assignee before its first run, user-authored comment or user-resolved opening
|
|
card. This uses the same awaiting-user predicate as recovery; a seeded greeting
|
|
does not start work. User input still enters through the host wake path.
|
|
Execution locks, automated pending review,
|
|
conversation state, unknown state and dependency repair remain blockers. A
|
|
blocked task whose blockers have all finished stays awake for reconciliation.
|
|
Enabled task watchdogs and unsupported recovery keep their existing checks.
|
|
Incoming changes still require the hosting admission and wake path.
|
|
|
|
An active issue monitor needs a saved future `monitor_next_check_at` matching
|
|
its validated execution policy, a company-scoped agent, no outstanding dispatch
|
|
claim, and remaining attempts and timeout. Due, malformed, quota-recovery,
|
|
unowned and inconsistent monitors keep the workspace awake. Inspection does
|
|
not clear schedules, advance attempts or dispatch an agent.
|
|
|
|
The combined report uses `version: 2` and a scheduled proof with `version: 1`
|
|
and `kind: "routines_and_issue_monitors"`. Its deadline is the earliest required
|
|
routine or monitor time across all companies. Its generation binds the current
|
|
process, idle owner and inspected catalogs. Hosts must acknowledge this known
|
|
proof kind, persist the alarm and validate the unchanged owned report before
|
|
stopping compute. Existing hosts reject the new kind. Monitor dispatch and
|
|
startup catch-up continue through the existing scheduler and atomic claims;
|
|
self-hosted scheduling is unchanged. This capability does not cover all future
|
|
work in the instance: every other safety check continues to apply.
|
|
|
|
## Retry history
|
|
|
|
Retry promotion keeps `scheduled_retry_at` on a run for inspection. That date
|
|
is consumed history when the run is terminal, has a finish time at or after the
|
|
retry date, and has no accounting work pending. The idle report uses the same
|
|
proof for failed ephemeral leases, coalesced wakes, and acknowledged question
|
|
responses. A live retry child still blocks through the instance-wide run check.
|
|
Unfinished runs, retry dates after the finish time, and pending accounting stay
|
|
awake. The inspection does not clear dates or change retry scheduling.
|
|
|
|
## Retained local workspaces
|
|
|
|
Local directories for primary projects and Git worktrees do not require an
|
|
awake process by themselves. The report permits their retained rows only in
|
|
known modes and states, with no runtime configuration, service state, commands,
|
|
pending reopen, or cleanup already eligible. Saved environment references alone
|
|
are passive. Shared workspaces with a project workspace remain blockers because
|
|
they can inherit runtime configuration. Unfamiliar providers, strategies,
|
|
configuration and malformed metadata also remain blockers.
|
|
|
|
This does not delete files, alter retention, or clear workspace records. Future
|
|
cleanup eligibility is an earliest allowed time; eligible cleanup can wait for
|
|
the next wake. Due cleanup, unfinished operations, runtime leases and runtime
|
|
services still keep the instance awake through their separate checks. The host
|
|
must keep workspace storage attached across sleep and preserve its backup policy.
|
|
|
|
## Accepted work and cleanup
|
|
|
|
HTTP admission is installed before body parsing, authentication, webhooks and
|
|
MCP ingress. The Express adapter tracks handler promises in nested routers and
|
|
error middleware. Sending a response or losing the client does not complete an
|
|
async handler. A callback-only handler that abandons its response without ending it remains a
|
|
sleep blocker. An async route that settles after a disconnect releases its
|
|
request token; normal cancellation does not permanently block sleep. New routes must be registered before this adapter is installed.
|
|
Fire-and-forget work must have durable queue state or use `trackIdleWork`; a
|
|
response is never a substitute for tracking that work.
|
|
Accepted live-event WebSocket authentication remains counted until its promise
|
|
settles, including after the raw socket closes. Detached startup reconciliation
|
|
for built-in agents, managed homes and persisted runtime services also remains
|
|
counted after readiness until its writes settle.
|
|
|
|
Scheduler work already in flight remains counted until its promise settles.
|
|
Idle holds pause new scheduler admissions. Database backup promises remain
|
|
counted through success or failure. Configured periodic backups block sleep by
|
|
default. The opt-in checkpoint mode below preserves a final backup instead of
|
|
running the timer while asleep. A generation counter invalidates a
|
|
scan if tracked work both starts and finishes during inspection. Reports remain
|
|
unknown until startup recovery and HTTP tracking are installed.
|
|
|
|
Terminal workspace recovery also registers a local sleep probe. Incomplete
|
|
startup pages and failed recovery remain blockers until a successful pass.
|
|
Active cleanup and unresolved producer transactions retain their admission holds.
|
|
Cooldown and inspection-backoff timers are maintenance hints over retained domain
|
|
rows. They can wait for the next wake and are restored at startup; they do not
|
|
create external alarm coverage or exempt other persisted work from this report.
|
|
|
|
### Backup checkpoints for idle instances
|
|
|
|
`PAPERCLIP_DB_BACKUP_IDLE_CHECKPOINT_ENABLED=1` opts an instance with automatic
|
|
backups enabled into this mode. Keep its database and persistent backup volume
|
|
attached across sleep. All writers must use the instance's admission protocol;
|
|
this mode cannot cover independent writers to the same database.
|
|
On managed instances, checkpoint-enabled safety reads require a verified signed
|
|
Cloud control actor. Tenant instance-admin elevation does not grant platform
|
|
backup authority. Self-hosted instance administrators retain operator access.
|
|
|
|
Each owned safety read first checks local work, plugin drains and durable work.
|
|
Known local blockers return before opening a database transaction. If every
|
|
other check passes, the server takes a fresh backup with the existing backup
|
|
engine and the retention policy from Instance Settings. It reads the full gzip
|
|
archive, checks its trailer and nonempty content, and syncs the archive and
|
|
directory before returning `none`. The final pre-stop revalidation takes another
|
|
fresh backup. Reads can therefore take longer; the host must bound its request
|
|
and still leave enough lease time for a confirmed provider stop.
|
|
|
|
There is no cached backup exemption. Failed, concurrent or untracked backups,
|
|
other work during the scan, changed owners and expired holds cannot authorize
|
|
sleep. Client timeouts do not clear the backup's in-flight token. Slow backups
|
|
may retain an awake instance until a later sleep attempt.
|
|
|
|
A durable `.idle-backup-wake-required` marker is written before the dump.
|
|
No recurring duplicate archives are produced while the instance is asleep.
|
|
The last pre-sleep archive and existing history stay on persistent storage;
|
|
no retention pruning runs during sleep. On restart, the server attempts a fresh
|
|
backup before enabling idle eligibility, then resumes the normal interval.
|
|
Only a verified new backup clears the marker. Failure keeps it for the next
|
|
scheduled retry. Disabling automatic backups explicitly still disables this
|
|
startup backup. Disabling only checkpoint mode restores the sleep blocker and
|
|
continues to honor an existing restart marker.
|
|
|
|
This does not replace filesystem backups, encryption-key recovery or off-provider
|
|
disaster recovery. Validate restoration of a staging checkpoint before enabling
|
|
the flag on customer instances.
|
|
|
|
The report inspects accounting and sandbox-cleanup spools directly. Any entry,
|
|
including malformed JSON, temporary files and failed write probes, blocks sleep.
|
|
Read errors and invalid spool paths return unknown. Recovery readers that skip
|
|
bad records cannot certify an empty spool.
|
|
|
|
An orphan cleanup token starts before its spool write and remains held through
|
|
buffering, queue splices, flush retries and buffer overflow. It ends only after
|
|
the database owns cleanup. Queued usage receipts stay counted until capture
|
|
settles. If receipt capture and the database failure fence both fail, a token
|
|
continues to block sleep until the failure fence is durably written. A query
|
|
that updates zero rows does not clear that debt. Unrecoverable cleanup requires
|
|
operator reconciliation; this API does not discard it to save compute.
|
|
|
|
## Persisted work and limits
|
|
|
|
The report checks all companies in one bounded read-only database transaction.
|
|
Queued and orphaned runs, timers, retries, accounting debt, unfinished issues,
|
|
cleanup, active routines, integrations, external ingress credentials, and plugin
|
|
work block sleep. Completed ordinary run history does not. Less common work
|
|
sources conservatively block on any retained records. Active issue watchdogs
|
|
block sleep even when their watched issue is complete and no review has started.
|
|
Missing migrations, malformed configuration and database errors produce unknown
|
|
without exposing SQL or tenant data.
|
|
|
|
Active `runtime_auth` connections with purpose `ai` are saved credentials, not
|
|
independent workers. Their saved configuration does not block sleep. Login
|
|
sessions and runs still pass the existing durable checks. Detached subscription
|
|
observations and quota reads remain counted through their actual completion,
|
|
including token refresh after a quota response times out. Credential-recovery
|
|
journals, partial writes and probes block sleep across restart. Empty company
|
|
directories left after successful recovery do not; invalid paths and read
|
|
failures remain unknown. Credentials and connection records are retained.
|
|
Disabled draft connections and saved outbound HTTP MCP connections have no
|
|
independent listener. They can permit sleep while accepted calls and credential
|
|
work still pass the other fences. MCP connections with a retained GitHub
|
|
webhook binding, local stdio processes, channels, and other active transports
|
|
remain blockers until their inbound work has a supported wake contract.
|
|
|
|
With the issue-scheduling capability, pending questions, confirmations,
|
|
checkbox confirmations and task suggestions can be passive waits. Their
|
|
producer must have finished without retry or accounting debt. The response
|
|
audience and continuation policy stay unchanged. Unknown pending siblings,
|
|
foreign-company records and unfinished producers block sleep. A resolved card
|
|
does not make an otherwise runnable issue passive. The schedule generation
|
|
includes response identity and audience, including when only a routine owns
|
|
the next alarm.
|
|
Merge confirmations remain blockers because GitHub polling can accept them
|
|
without a human response and does not yet have a durable wake contract.
|
|
|
|
Known board escalation actions for stranded work, missing disposition and a
|
|
lost review path can also be passive. They require a blocked source in the same
|
|
company, board ownership, no automatic wake, no monitor or timeout, and no live
|
|
execution binding. The action remains visible and unresolved. Other recovery
|
|
causes and autonomous owners remain blockers.
|
|
|
|
A failed ephemeral lease is history only with successful cleanup, a release
|
|
timestamp, and an exact provider termination receipt bound to its company, run,
|
|
lease and resource. Its run must be finished without retry or accounting debt.
|
|
Pending cleanup claims and export/stop-and-retain intents still block. Failure
|
|
labels or cleanup success without that proof do not authorize sleep. Lease
|
|
history is retained; this check performs no provider teardown or data updates.
|
|
A released local ephemeral bookkeeping lease needs no remote termination
|
|
receipt when its exact run has finished and both its provider and environment
|
|
are local. It must have no provider resource reference or pending cleanup,
|
|
export or retention intent. Unknown drivers and remote resources still block.
|
|
|
|
Finished login-session history permits sleep only after its promotion claim is
|
|
cleared and any retained provider reference has a matching released, expired,
|
|
or verified failed ephemeral lease with successful cleanup and a release
|
|
timestamp in the same company and environment. The failed lease must satisfy
|
|
the same termination and run checks above. Missing cleanup evidence,
|
|
`cleanup_pending`, and live login flows
|
|
remain blockers. A finished coalesced wake is history only when its exact
|
|
company/agent's linked run has finished without retry or accounting debt.
|
|
Image-setup history still blocks: promotion can succeed before teardown is
|
|
confirmed, so a terminal label does not prove that its provider resource is gone.
|
|
|
|
Completed question-answer deliveries permit sleep only after acknowledgement
|
|
and completion of their exact target run in the same company, without retry or
|
|
accounting debt. A fallback without a target run requires its exact question's
|
|
finished durable wake receipt in the same company. A coalesced fallback also
|
|
requires its exact company/agent's linked run to finish without retry or
|
|
accounting debt. The question-history index covers every wake status.
|
|
Pending deliveries, missing
|
|
completion evidence, and unfinished handoffs still block. Failed deliveries
|
|
without a pending target are history; other work checks still apply.
|
|
|
|
Processed connector-event receipts with a processing timestamp are idempotency
|
|
history. Delivered connection-intent outboxes also permit sleep once their
|
|
exact accepted wakes finish. A system-retired connection card parked behind a
|
|
pending response keeps its undelivered outbox intact; the normal response path
|
|
resumes delivery. Pending event application, unfinished wakes and all other
|
|
execution checks still block. None of these exceptions fabricates completion
|
|
or removes a durable receipt.
|
|
|
|
Enabled plugins require the current worker's verified idle drain. A version
|
|
label does not prove that arbitrary worker code has no background activity.
|
|
No plugin approval or configuration bypass is supported. Scheduled and
|
|
externally triggered work needs a durable host wake mechanism before it can
|
|
permit sleep.
|
|
|
|
This is a single-process admission protocol. A restart clears the owner. The
|
|
host must serialize sleep with deploy/wake operations and bind its final check
|
|
to the instance it stops. An unexpected restart after the final check can still
|
|
race an external provider stop; a process-local report cannot fence that remote
|
|
operation by itself. Multiple replicas require shared fencing. The protocol
|
|
does not make existing in-memory-only debt survive an unplanned process crash.
|
|
|
|
Related public PR #13413 adds runtime-service controller requirements and uses
|
|
the same `purpose: "idle"` / `ownerId` vocabulary. This report conservatively
|
|
blocks all retained runtime-service state instead of approving such services.
|
|
|
|
## Muse maintenance
|
|
|
|
Muse maintenance uses the shared delivery coordinator. Startup reconstructs
|
|
existing work and marks incomplete receiver evidence once. Pairing, OAuth grant
|
|
attachment/revocation/replay, qualification changes and new assignments notify
|
|
the coordinator before their transaction writes. Nested writes wake it only
|
|
after the outer transaction settles; uncertain outcomes retain the normal hold.
|
|
|
|
Unrevoked qualifications schedule their saved expiration time. An instance with
|
|
no Muse bindings, or with idle bindings and no qualification deadline, performs
|
|
no recurring maintenance SQL after startup. Failed reconciliation retries in
|
|
five seconds. Offered, claimed, accepted and not-yet-finalized settled assignments
|
|
retain that five-second recovery cadence until settlement; this covers terminal
|
|
run writers even when their direct reconciliation path fails. Retained finalized
|
|
assignment history does not keep that cadence running. Direct SQL or independent
|
|
process writers require explicit integration; startup still reconstructs state.
|
|
|
|
Warm standby prevents maintenance SQL. An idle drain pauses ordinary dispatch
|
|
and passive deadlines through the shared coordinator. Startup and notifications
|
|
received during drain retain a memory-only wake until a sweep can run. The wait
|
|
does not query the database. Producer uncertainty and
|
|
outstanding assignment recovery retain its existing admission rules. Shutdown
|
|
awaits the worker before flushing the receiver. The receiver's separate batching
|
|
timer remains; an empty buffer performs no database work. Existing Muse durable
|
|
sleep blockers, external worker stop evidence, and ingress requirements remain
|
|
unchanged. This change establishes database quiet for inactive Muse, not host
|
|
sleep eligibility for a configured Muse connection.
|
|
|
|
## Skill package maintenance
|
|
|
|
The package delivery worker automatically converts legacy snapshots and versions.
|
|
Legacy contents remain authoritative until conversion is verified. Unfinished or
|
|
failed conversions, including rows retained while package storage is disabled,
|
|
may wait for the next ingress wake and do not block idle sleep. Their persisted
|
|
retry dates and package/object/native-asset retention timestamps are earliest
|
|
maintenance eligibility, not promised delivery deadlines. Workers reconstruct persisted rows and filesystem
|
|
access leases on startup, and use the existing coordinator's drain/standby/shutdown
|
|
controls. No external Cloud alarm or provider suspension is established by these tests.
|