diff --git a/CHANGELOG.md b/CHANGELOG.md index 92658af..363e066 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,21 @@ All notable changes to this project are documented here. This project follows ### Added +- **Durable recovery checkpoints for writing stages (#503, absorbs #525).** + An `implement` or `resolve` stage in a Git worktree records the exact staged, + unstaged and eligible untracked state as Git objects behind a private + `refs/code-cycle/recovery/` ref, before it edits and again when it is + interrupted or runs out of quota. A quota stop now hands the same worktree to + the configured fallback once, in the same stage, from a complete checkpoint, + including local commits, instead of stopping `dirty_workspace` or + `workspace_changed`; both executors exhausted ends `BLOCKED` naming both + reset times. Secret paths, credential content and ignored files are never + captured (`code_cycle.recovery.secret_paths` adds patterns), a toolkit + writer lock refuses a second toolkit writer on the same worktree, and + `scripts/recovery_checkpoints.py` offers `inspect`, `restore`, explicit + `adopt` (`operator_adopted`), `discard`, lifecycle-based `prune` and + `unlock`. Recovery approves nothing and skips no check. See + `docs/recovery-checkpoints.md`. - **Bounded re-read of review and rereview publications (#446).** A `review` or `rereview` publication that is not seen at the first read is re-read after 1 s, 2 s and 4 s, correlated by the receipt's `attempt_id`, before it is diff --git a/docs/README.md b/docs/README.md index df628d4..b2eca53 100644 --- a/docs/README.md +++ b/docs/README.md @@ -30,6 +30,7 @@ Guides are listed in reading order. Each one has one main topic and links to the |---|---| | [CodeCycleToolkit 2.0 roadmap](ROADMAP_V2.md) | Approved strategy, execution modes, decisions, issue dependencies and milestones; planned capabilities are not implementation claims | | [Role workspace policy](role-workspace-policy.md) | The write permission each dispatched role has, and which executors can enforce it | +| [Recovery checkpoints](recovery-checkpoints.md) | How an interrupted or quota-stopped writing stage keeps its exact worktree: capture, integrity, secrets, retention, writer lock, adoption and the operator commands | | [Host permissions](host-permissions.md) | The agent capability parity rule, each stage's closed command table, how Claude and Codex enforce it, their limits, and the opt-in global set | | [Capability parity audit](capability-parity-audit.md) | Every toolkit-owned restriction classified as a real limit, a role contract or a toolkit veto, with the issue that converts each veto and its parity baseline per executor | | [Native parity runs](native-parity-runs.md) | The manual procedure that runs the audit's baselines with the real `claude -p` and `codex exec` and compares them with the toolkit's consent decision | diff --git a/docs/capability-parity-audit.md b/docs/capability-parity-audit.md index 7a28b2f..2eeb0bf 100644 --- a/docs/capability-parity-audit.md +++ b/docs/capability-parity-audit.md @@ -67,13 +67,22 @@ a contract breach. This inventory adds no new permission or veto. | `run_cycle._main_worktree_root` | 1 | safe-to-swallow: optional root discovery returns absent | | `cycle.CycleRecorder.__init__` | 1 | safe-to-swallow: quota persistence is optional | | `cycle.CycleRecorder._check_codex_effort` | 1 | safe-to-swallow: unavailable optional model catalog | -| `cycle.CycleRecorder._match_handoff` | 1 | report-with-cause: handoff cannot be claimed on storage failure | +| `cycle.CycleRecorder._match_handoff` | 2 | report-with-cause: a failed optional adoption lookup is journaled and treated as no adoption, never a veto (#503); a handoff that cannot be claimed on storage failure blocks the dirty resume | | `cycle.CycleRecorder._effect_snapshot` | 1 | degrade-to-not_verified: absent snapshot supplies no effect evidence | | `cycle.CycleRecorder._claim_handoff` | 1 | report-with-cause: storage error propagated | | `cycle.CycleRecorder._find_blocker` | 2 | safe-to-swallow: optional publication evidence unavailable, no success inferred; report-with-cause: pre-stage ancestry probe failures remain unverified and stop reconciliation | | `cycle.CycleRecorder._record_quota_exhaustion` | 1 | safe-to-swallow: optional quota persistence | | `cycle.CycleRecorder._clear_quota` | 1 | safe-to-swallow: optional quota persistence | | `cycle.CycleRecorder._observe_shadow` | 1 | safe-to-swallow: shadow experiment cannot decide routing | +| `cycle.CycleRecorder._recovery_root` | 1 | safe-to-swallow: no resolvable Git worktree means no checkpoint, never a veto (#503) | +| `cycle.CycleRecorder._acquire_writer` | 1 | report-with-cause: an unwritable writer lock is journaled and the stage still runs (#503) | +| `cycle.CycleRecorder._release_writer` | 1 | report-with-cause: a failed lock release is journaled and never replaces the stage's outcome (#503) | +| `cycle.CycleRecorder._checkpoint` | 1 | report-with-cause: a failed checkpoint is journaled and never stops the stage (#503) | +| `cycle.CycleRecorder._check_checkpoint_handoff` | 1 | degrade-to-not_verified: an unreadable checkpoint cannot prove the worktree, so the automatic fallback stops and the checkpoint is named (#503) | +| `cycle.CycleRecorder._hand_over` | 1 | safe-to-swallow: the local commit count is telemetry only | +| `cycle.CycleRecorder._consume_checkpoints` | 1 | safe-to-swallow: optional lifecycle bookkeeping; consumed or not, nothing is deleted | +| `cycle.CycleRecorder._claim_adoption` | 1 | report-with-cause: storage error or changed worktree propagated before dispatch | +| `cycle.CycleRecorder.close` | 1 | safe-to-swallow: optional retention bookkeeping | | `cycle_dispatch.StageDispatch._question_evidence` | 1 | safe-to-swallow: optional question diagnostics | | `cycle_dispatch.StageDispatch.run` | 1 | safe-to-swallow: optional snapshot file, original snapshot preserved in memory | | `cycle_dispatch.StageDispatch.record_resume_point` | 1 | safe-to-swallow: optional resume point, manual resume remains | @@ -194,6 +203,8 @@ given instead of line numbers so the references stay valid. | PA-51 | Command-output targets require an explicit confirmed definition before permission; reviews request a separate cycle-only grant | `grants.ConsentBroker.request_definition`, `request` | User-defined source and role boundaries; output is an untrusted suggestion and a definition never authorizes access | #509 | role contract | #509 (converted to canonical consent and separate review scopes) | | PA-52 | MCP tools a stage inherits from the user's configuration are neither hidden nor pre-approved by the toolkit; a `claude -p` denial of one is recorded as a `claude_permission` refusal (host limit), never invalidates evidence already obtained, and never becomes the stop cause of a review recovered from its receipt | `scripts/cycle_dispatch.py` (receipt recovery), `scripts/cycle_review_gate.py` (`recover_review`), `docs/host-permissions.md#inherited-mcp-tools-486` | The user's configuration decides which inherited tools run; a code-executing MCP tool runs outside the command hook and is not presented as supervised | #486: an MCP tool denial was mixed into a receipt-recovery stop | real limit | #486; since #550 a published implement or resolve stage that reported `BLOCKED` is reconciled with the denial counted as an auxiliary host limit, still never a question, including no `unattended_denial` decision in a run without a human channel | | PA-53 | Before the cycle records its change request, `gh pr edit` and `gh pr comment` in implement may target only the current branch's pull request. Naming that pull request by number was refused, which refused the stage's own receipt publication after it opened the PR. Since #550 the number is allowed when GitHub reports it, at the moment of the call, as the open pull request of this repository whose head is the checkout's branch; any other number, or any doubt, keeps the refusal | `stage_permissions._check_gh`, `_branch_pull_request` | Publication only on the cycle's own change request (PA-11) | #486: `gh pr edit 549 --body-file $TMPDIR/report.md`; #503: `gh pr comment 554 --body-file $TMPDIR/pr-comment.md` | toolkit veto | #550 | +| PA-54 | A second toolkit writer on a worktree whose writer lock a live toolkit process holds is refused before it dispatches; contention while another process updates the lock record is also refused. Record changes serialize on a persistent OS guard, including reclaim, release and operator unlock. A lock of a dead process on this host is reclaimed with its record kept, an unreadable lock is held until `recovery_checkpoints.py unlock`, and a lock the toolkit cannot write never stops the stage | `recovery_checkpoints.WriterLock`, `cycle.CycleRecorder._acquire_writer` | Two toolkit writers on one worktree would make every recovery checkpoint ambiguous | #503 | role contract | — | +| PA-55 | The automatic quota handoff of a writing stage stops when the toolkit cannot prove what it would hand over: an incomplete checkpoint (`checkpoint_incomplete`), HEAD not descending from the stage's start, a changed remote or publication, an unknown starting state, or a worktree that changed between the checkpoint and the fallback | `cycle.CycleRecorder._checkpoint_gate`, `cycle.CycleRecorder._check_checkpoint_handoff` | An automatic reroute continues only work whose state is recorded exactly | #525 | role contract | — | ## Kept restrictions @@ -232,6 +243,8 @@ Why each real limit and role contract stays. | PA-50 | The current Codex stage masks its own daemon directory with mode 000. Nested Codex execution is unavailable here; the host-reported spike and suite are preserved separately from current-head local verification in `research/local-sockets-509.md`. | | PA-51 | The owner's canonical-parameter and trusted-source requirement is enforced before consent. Missing definitions ask for an exact path or domain; review roles accept cycle or deny only and never inherit writer grants. | | PA-52 | The host's permission layer, not the toolkit, decides an inherited MCP tool. The same agent run directly in `-p` mode meets the same denial. The toolkit adds no veto: it records the denial, keeps the evidence obtained and recovers a review from its valid receipt, so the denial stops progress only when an indispensable operation has no permitted alternative. | +| PA-54 | The lock coordinates the toolkit's own writers only and refuses no direct operation: a user or an agent working on the worktree directly is unaffected, and `unlock` lets the user clear a stale lock. It is disclosed that no lock can attribute edits made outside the toolkit. | +| PA-55 | Only the automatic path stops, and it names the checkpoint that keeps the worktree. The user can still inspect, restore or explicitly adopt the worktree and resume with `--from`, or run any operation directly (#450); automatic-recovery ambiguity is never a toolkit-wide veto. | ## Vetoes: conversion and parity baseline diff --git a/docs/configuration.md b/docs/configuration.md index 2b82edc..b30d960 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -130,6 +130,7 @@ All keys live under `code_cycle`. `run_cycle.py` **refuses any key not in this t | `security_review.always_when.labels` | label terms, matched by meaning | built-in defaults | same | | `orchestration.mode` | `auto` · `single_agent` · `claude_codex` | `auto` | `cc-orchestrator` | | `calibration.profiles..provider` / `.model` / `.effort` | strings | — | `cc-orca-orchestrator` with `paired_review=true` | +| `recovery.secret_paths` | glob list, added to the versioned defaults (never removes one) | none | recovery checkpoints (`scripts/recovery_checkpoints.py`); see [Recovery checkpoints](recovery-checkpoints.md#secrets) | A configuration file that exists but can't be read (bad YAML, PyYAML missing, wrong shape) **stops** `run_cycle.py`. It never falls back to the defaults. Use `--no-config` to run on the defaults deliberately. @@ -471,6 +472,9 @@ Nothing below is written into your repository, except a project-scope installati | `~/.config/code-cycle-toolkit/calibration/` | Paired-review campaign store | | `~/.code-cycle/runtime/` | Global runtime installation | | `/.code-cycle/runtime/` + `.code-cycle/.gitignore` | Project runtime installation | +| `refs/code-cycle/recovery/` and their objects, in the repository's Git object store | Private recovery checkpoints of writing stages; never branches or tags, never pushed. See [Recovery checkpoints](recovery-checkpoints.md). | +| `/code-cycle-writer.lock` | The toolkit writer lock of a worktree during a writing stage | +| `/code-cycle-writer.lock.guard` | Empty, persistent OS lock file serializing writer-lock record changes; never removed during normal operation | On Windows, the `~/.config/code-cycle-toolkit` directory is `%APPDATA%\code-cycle-toolkit`. diff --git a/docs/instrumentation.md b/docs/instrumentation.md index 193b141..0e6b453 100644 --- a/docs/instrumentation.md +++ b/docs/instrumentation.md @@ -716,7 +716,11 @@ completion is unverified; generic CI success cannot clear it), `worktree_dirty`, `worktree_diverged`. The last two stop before changing files when a dirty tree or non-fast-forward prevents syncing an open pull request head. A closing row from an earlier version has none, and `cc-stats` reads it as unknown. A stage row's `reroute_reason` may then be -`permission_required` or `permission_answered`. +`permission_required` or `permission_answered`, or, for a quota stop of a +writing stage (#503), `checkpoint_handoff` (handed to the fallback from a +complete recovery checkpoint) or `checkpoint_incomplete` (the checkpoint had +to exclude or could not represent relevant content, so the stage stopped); see +[recovery checkpoints](recovery-checkpoints.md). Each dispatch row that reached an executor carries `duration_ms`, the executor call's wall time from a monotonic clock. An attempt refused before an executor diff --git a/docs/recovery-checkpoints.md b/docs/recovery-checkpoints.md new file mode 100644 index 0000000..89cc544 --- /dev/null +++ b/docs/recovery-checkpoints.md @@ -0,0 +1,236 @@ +# Recovery checkpoints + +An interrupted writing stage must not lose its work, and must not make anyone +guess whose work a dirty worktree holds. Since #503 the runtime keeps a durable, +scoped checkpoint of an `implement` or `resolve` stage's worktree, and a quota +stop hands that worktree to the configured fallback in the same stage (#525, +see [routing](routing.md#quota-handoff-in-a-writing-stage)). + +`scripts/recovery_checkpoints.py` owns the checkpoints. Nothing here is a +second state engine: the metadata extends the dispatch-attempt history and the +cycle journal in the telemetry store, and the content is ordinary Git objects. + +## When a checkpoint is taken + +In a production cycle, for a stage whose workspace policy is `workspace_write` +and whose dispatch runs in a Git worktree: + +| Kind | When | +|---|---| +| `baseline` | when the dispatch attempt is opened, before the executor can edit | +| `quota_handoff` | after a finished process reported `quota` | +| `interrupted` | when the cycle is interrupted (`SIGINT`, `SIGTERM`) during the attempt | +| `operator_adopted` | when an operator adopts later edits (see [Adoption](#adoption)) | + +An abrupt termination (`SIGKILL`, power loss) takes no checkpoint at that +moment. The `baseline` of the attempt is then the last completed checkpoint, +and whatever changed after it is an ambiguous edit: the attempt-start record +and its timestamp never prove who made it. + +A checkpoint that cannot be taken is journaled (`recovery` / +`checkpoint_failed`) and never stops the stage by itself. A stage without a Git +worktree takes none and keeps the earlier reconciliation unchanged. + +## Durability and idempotency + +Each checkpoint is bound to repository, work item, change request, cycle, +stage, attempt, workspace (the worktree's real path), branch, HEAD, the secret +rule digest and its parent checkpoint. The order is fixed: + +1. an intent row with status `pending` is written before any object; +2. the staged state and the worktree state are written as trees through private + index files, so the real index, the worktree and the branch are never + touched; +3. a checkpoint commit (worktree tree, parents HEAD and an index commit) is + created, and only then the private ref `refs/code-cycle/recovery/`, + created with "must not exist" semantics; +4. the row becomes `complete` or `incomplete`. + +Git is asked to `fsync` objects and refs (`core.fsync=committed`). A crash +before step 3 leaves a `pending` row without a ref; `inspect` (or +`reconcile_pending`) marks it `failed`. A crash after step 3 leaves a ref whose +commit message carries the checkpoint's metadata and the fingerprint taken at +capture. Reconciliation finishes the row using that record, so verification can +still distinguish an unchanged worktree from a later edit. If an older capture +left only a ref without a fingerprint, its intact objects still support +inspection and restore, but cannot prove the current worktree matches. +Capturing the same content again for the same attempt and stage returns the +existing checkpoint and records the repetition as `duplicate`, so +repeated recovery never creates a second logical checkpoint. + +Verification (`inspect`) reports, without changing anything: +`corrupt_metadata`, `missing_ref`, `missing_objects` and `wrong_scope` as +integrity problems, and the worktree state as `matches`, `fingerprint_changed` +(edits after the checkpoint), `head_advanced` or `head_changed`. + +## What a checkpoint covers + +Captured exactly: text and binary content, staged and unstaged states +separately (a file staged once and edited again keeps both), untracked files +that are not ignored, deletions, Git-representable modes, symlinks (their target +text, never dereferenced), and submodules by gitlink SHA only. + +Changed regular files are stored unfiltered, so the checkpoint holds the bytes +on disk and not what line-ending or encoding conversion (`core.autocrlf`, +`text`, `eol`, `working-tree-encoding`, `ident`) would store. `restore` writes +those bytes back after Git's checkout. It recreates native symlinks and +preserves links already represented by a regular file at capture time, as can +happen with `core.symlinks=false` on Git for Windows. If the platform refuses +to create a link or a file cannot be rewritten, the checkout representation +stays and `restore` reports `matches: false`. + +A path with a `filter` driver (Git LFS, an encrypting filter) is the +exception: it keeps the blob its clean filter produced, so content the driver +keeps out of the object store stays out, and the driver's smudge filter +restores it. A staged-only regular file whose bytes on disk are unreadable, +larger than 32 MiB or hold a credential keeps only the already-scanned staged +blob and makes the checkpoint incomplete. The checkpoint commit names paths +that keep a cleaned blob in `filtered`. + +The fingerprint covers on-disk bytes of staged-only files as well as unstaged +and untracked files. A write that produces the same Git-cleaned blob can still +change the fingerprint. Existing checkpoints compare with their original +fingerprint format. + +Never captured: ignored files, sockets, devices and FIFOs, and secrets. +Reported as unsupported: dirty submodules, nested repositories, unmerged index +entries, and content that changed while the checkpoint was being taken. + +A checkpoint that had to exclude a relevant path or could not represent one is +`incomplete`. It is still kept as evidence, but it is never used for an +automatic handoff: the stage stops with `checkpoint_incomplete` and names it. + +### Secrets + +Exclusion runs before anything reaches the Git object store, on staged, +unstaged and untracked content alike, and fails closed: a file that cannot be +read or is larger than 32 MiB is excluded (`scan_failed`), and a scanner or +configuration failure makes the whole checkpoint `failed` or `incomplete`. +Git receives the scanned worktree bytes on standard input, including when a +configured clean filter handles the path. + +- **Paths** (rule version 1, case-insensitive): `.env`, `.env.*`, `*.pem`, + `*.key`, `*.p12`, `*.pfx`, `id_rsa*`, `id_ed25519*`, `id_ecdsa*`, `id_dsa*`, + `.npmrc`, `.netrc`, `_netrc`, `.pypirc`, `.git-credentials`, + `.aws/credentials`, `credentials.json`, `secrets.json`. The templates + `.env.example`, `.env.sample`, `.env.template` and `.env.dist` are captured. +- **Content**: the credential formats and private-key blocks the cycle journal + already redacts (`cycle_journal.contains_credential`), with no new + dependency. +- **Repository additions**: `code_cycle.recovery.secret_paths` in + `.code-cycle.yml` adds patterns; it can never remove a default. A value that + is not a list of strings, or a file that cannot be parsed, makes the + checkpoint `incomplete` (`secret_rules_invalid`, `secret_rules_unreadable`). + +```yaml +code_cycle: + recovery: + secret_paths: ["*.vault", "private/*"] +``` + +An excluded file stays untouched in the worktree; only its path and a reason +code (`secret_path`, `secret_content`, `scan_failed`, `special_file`) are +recorded. A staged secret is put back to HEAD's version in the checkpoint's +index tree, never in the real index. Path exclusion and content scanning reduce +exposure; they cannot guarantee that every secret is detected. + +## Retention + +Retention is lifecycle-based. A checkpoint with a ref and status `complete` or +`incomplete` is eligible for explicit pruning once it is discarded or once +it is consumed by a later successful stage of its scope and its cycle is +terminal. In either case, no active checkpoint or unconsumed adoption may +depend on it. This also applies to checkpoints of kind `interrupted`. +The refs protect the objects from ordinary `git gc` and `git prune`. They live +under `refs/code-cycle/`, outside the branches and tags included in toolkit +pushes. + +Pruning is explicit and auditable: `prune --dry-run` lists what would go; +`prune` deletes each ref only if it still points at the recorded commit, then +sets `pruned_at`. An interrupted prune is finished by the next one. Rows, +fingerprints and provenance survive content pruning. The refs and objects have +the repository's own permissions; the metadata has the telemetry store's. + +## Writer lock + +A writing stage takes `code-cycle-writer.lock` in the worktree's Git +directory before dispatch and releases it after the attempt. A second toolkit +writer on the same worktree is refused before it dispatches, naming the +holder. A lock whose holder process no longer runs on this host is reclaimed, +and the old lock is kept next to it as evidence; an unreadable lock is treated +as held until `unlock` removes it. A lock the toolkit cannot write is journaled +(`lock_unavailable`) and does not stop the stage. A release that fails is +journaled (`lock_release_failed`) and never replaces the stage's own outcome. + +Acquisition, stale-record replacement, release and `unlock` serialize their +record changes with an OS advisory lock on `code-cycle-writer.lock.guard`. +That empty guard file stays in the Git directory so every process locks the +same file; process death releases its OS lock. Threads in one process also +serialize these changes. Separate lock instances in the same process cannot +replace each other's live record, and release checks a unique ownership token. + +The lock excludes other toolkit writers only. An editor, a shell or another +tool can still change the worktree, and no lock can attribute such a change. +That is why the fallback re-verifies the checkpoint immediately before it +starts. + +## Adoption + +Edits after the last completed checkpoint are adopted only by an explicit +operator command, never by an executor and never automatically: + +1. `inspect` shows the checkpoint, its integrity and the worktree's current + fingerprint; +2. `adopt --confirm-fingerprint ` checks that the inspected fingerprint + is still the worktree's, records the adopted state as a new + `operator_adopted` checkpoint (the original is preserved), and records the + operator's identity (the authenticated `gh` login, or the local user, with + its source) and time; +3. the next `--from` resume of that stage on that exact worktree consumes the + adoption once, atomically, after recomputing the fingerprint immediately + before dispatch. + +Adoption is bound to repository, work item, change request, stage, workspace, HEAD, +fingerprint and its anchor checkpoint. It is a separate provenance from #389's +`operator_attested`. It never establishes executor authorship, grants no +permission, is not functional verification, skips no required check, and +cannot adopt content the secret exclusions refuse. + +Both `implement` and `resolve` resumes consume only an adoption for their own +stage, including a clean worktree whose adopted changes are local commits. +An `implement` resume without one keeps its existing `--continue` +behavior; an adoption for another stage is left unconsumed. When an adoption +exists for a dirty `resolve` worktree, it takes precedence over a quota handoff +record of the same worktree. A failed adoption lookup is journaled +(`adoption_lookup_failed`) and treated as no adoption; it never blocks the +resume by itself. + +## Operator commands + +`python3 scripts/recovery_checkpoints.py --database `: + +- `list --repo [--task ]` lists checkpoints and their status; +- `inspect --checkpoint --cwd ` finishes interrupted captures and + reports integrity and the worktree state; +- `restore --checkpoint --cwd ` recreates the index and the + worktree on a clean worktree at the checkpoint's HEAD; it refuses any other + state and never overwrites work; +- `adopt --checkpoint --cwd --confirm-fingerprint --stage implement|resolve`; +- `discard --checkpoint ` marks an abandoned checkpoint discarded; +- `prune [--repo ] [--dry-run]`; +- `unlock --cwd --confirm-pid ` removes a stale writer lock + whose holder no longer runs. + +Every command except `list`, `inspect` and `prune --dry-run` is journaled with +the operator's identity. These are the operator's own direct operations: recovery ambiguity +stops the automatic path only, never what a user can run directly (#450). + +## Limits + +- Checkpoints cover one worktree's Git-representable state. They do not cover + ignored build output, files outside the worktree, dirty submodule content or + external services. +- Windows has no process-group exit proof, so a quota stop there still stops + instead of rerouting (see [routing](routing.md)). +- Recovery grants no approval and skips no mandatory check; the recovered work + is reviewed and verified like any other change. diff --git a/docs/review-cycle.md b/docs/review-cycle.md index 9d9b733..66c4520 100644 --- a/docs/review-cycle.md +++ b/docs/review-cycle.md @@ -207,6 +207,15 @@ completed and does not seed the guard. When the local verification barrier still has pending checks, its ordering and observability remain the separate concern tracked by #399. +**Interrupted writing stages:** an implement or resolve stage records a +[recovery checkpoint](recovery-checkpoints.md) of its worktree before it edits +and again when it is interrupted or runs out of quota. A quota stop hands the +same worktree to the configured fallback once, from a complete checkpoint, as +[routing](routing.md#quota-handoff-in-a-writing-stage) describes. A checkpoint, +a handoff or an operator adoption is provenance only: the work it carries is +reviewed, rereviewed and checked exactly like any other change, and none of +them approves anything or skips a required check. + ### The CI gate `scripts/ci_gate.py` is the cycle's only wait on checks. `run_cycle.py` calls it after a clean review, and both orchestrators run its command line. No stage and no model polls: the implementation and the reviews read the checks once and return. diff --git a/docs/routing.md b/docs/routing.md index b27528c..84bf499 100644 --- a/docs/routing.md +++ b/docs/routing.md @@ -113,7 +113,27 @@ Resolve keeps the `cheap_coder` / `deep_coder` profile choice. With `code_cycle. - **Sandbox recovery.** An explicit, complete agent-reported restriction can use the same reroute machinery. See [Recovering sandbox restrictions](#recovering-sandbox-restrictions) for its additional conditions. - **One reroute per stage.** A `capacity`, `transport`, `timeout`, or `quota` failure can use that profile's distinct, available fallback once, sharing the quota retry budget. The previous process group must have exited; asynchronous launches and missing exit proof stop. A `not_started` attempt can reroute directly. A `started` or `unknown` attempt that could write or publish first reconciles the workspace, local HEAD, remote refs, PR state, comments and reviews, and issue comments. Dirty or changed state, a publication, or unavailable evidence stops with a closed reason token. A publication is what the cycle's own code-host account (`gh api user`) created or edited: pull requests (state, head, title, body), comments and reviews. Other accounts' comments and newly opened pull requests, reactions and timestamps do not stop the reroute; an unreadable account is unavailable evidence. A pull request carries no editor identity, so any edit to an existing in-scope pull request stops conservatively, whoever opened it. A review's read-only workspace does not exempt its publication boundary. Other error classes and human friction never reroute. Both attempts and the parent's `error_code` and `start_state` are recorded. The fallback applies only to this stage; later stages keep the original executor availability except for recorded quota exhaustion, which they continue to honour. Recovery from published evidence remains a separate operation. - **Quota across resumes.** Every production route skips an active quota record for the exact repository, executor and requested model, including `--continue` and `--from`. The route reports the substitution and reset or operator-retry requirement. Calibration never reads or writes these records and never substitutes an arm. Complete dates (including ordinal days), years, clocks and explicit UTC offsets or IANA zones (including parenthesized zones) are preserved. Without an explicit zone the runtime's local zone applies, retaining its date-specific DST rules; when no IANA zone is available, including on Windows, the OS converts the local wall time for that date. A repeated hour uses its later interpretation. Uninterpretable dates, weekday-only dates, relative durations and ambiguous zone abbreviations stay unavailable until an explicit operator retry. Missing reset information alone uses a 30-minute minimum. Expiry is retry eligibility, not proof of recovery. Original provider text is redacted into the journal and stop report; telemetry holds closed reason tokens and structured timestamps only. -- **Dirty `--from` resumes.** A dirty resume needs an exact quota worktree provenance record bound to the repository, work item, stage, PR, HEAD, original executor/model, destination executor and complete SHA-256 fingerprint of staged, unstaged and nonignored untracked changes. The runtime records ownership only after a finished quota-exhausted process began on a clean tree (or matched previous provenance), left HEAD unchanged and changed no remote or publication boundary. The fallback must inspect those edits before writing. A missing record, altered diff, wrong scope or HEAD stops without changing the checkout. Ordinary dirty executor changes remain refused; `implement --continue` retains its existing behavior. Provenance survives quota expiry, allowing a matching resume on the original executor after expiry; a new exhaustion records another ownership checkpoint. A successful resume consumes the checkpoint, retaining its audit history. This does not weaken the PR-head guard or any sandbox policy. +- **Quota handoff in a writing stage.** See [below](#quota-handoff-in-a-writing-stage): an implement or resolve quota stop continues on the fallback in the same worktree instead of stopping `dirty_workspace` or `workspace_changed`. +- **Dirty `--from` resumes.** A dirty resume needs an exact quota worktree provenance record bound to the repository, work item, stage, PR, HEAD, original executor/model, destination executor and complete SHA-256 fingerprint of staged, unstaged and nonignored untracked changes. The runtime records ownership only after a finished quota-exhausted process began on a clean tree (or matched previous provenance), left HEAD unchanged and changed no remote or publication boundary. The fallback must inspect those edits before writing. A missing record, altered diff, wrong scope or HEAD stops without changing the checkout. Ordinary dirty executor changes remain refused; `implement --continue` retains its existing behavior. Provenance survives quota expiry, allowing a matching resume on the original executor after expiry; a new exhaustion records another ownership checkpoint. A successful resume consumes the checkpoint, retaining its audit history. This does not weaken the PR-head guard or any sandbox policy. The only other provenance a dirty resume accepts is an explicit operator adoption (`operator_adopted`) of that exact worktree, recorded with `recovery_checkpoints.py adopt` and consumed once; see [recovery checkpoints](recovery-checkpoints.md#adoption). + +### Quota handoff in a writing stage + +A quota exhaustion in an `implement` or `resolve` stage (#525, absorbed by #503) no longer stops the cycle because the worktree is dirty or HEAD moved. When the dispatch ran in a Git worktree, the runtime: + +1. records the exhaustion and its reset time, then takes a [recovery checkpoint](recovery-checkpoints.md) of the exact staged, unstaged and eligible untracked state, including local commits made since the stage started; +2. hands the same worktree to the profile's configured fallback, once per stage, when the checkpoint is `complete`, the process exited, the stage's starting state was known (clean, matched provenance, or a complete pre-dispatch checkpoint), HEAD only moved forward from where the stage started, and no remote ref, pull request, comment or review of the cycle's account changed; +3. re-verifies the worktree against the checkpoint immediately before the fallback starts; any edit in between (an editor, another tool) blocks the fallback and names the checkpoint to inspect or adopt; +4. tells the fallback the checkpoint ID, the original executor, the number of local commits and the worktree fingerprint, and that the handoff is not functional verification. + +A permission answer can trigger a rerun on the same fallback executor. The +runtime reconciles that fallback attempt's effects before rerunning it. The +quota checkpoint check applies to the initial handoff. + +The stage row records `reroute_reason` `checkpoint_handoff`; the journal records a `recovery` / `quota_handoff` event with the checkpoint ID and ref, the original and destination executors and models, the starting and current HEAD, the local commit count, the fingerprint and the exhaustion's reset time. An incomplete checkpoint (a secret or another excluded or unsupported path, see [recovery checkpoints](recovery-checkpoints.md#what-a-checkpoint-covers)) stops with `checkpoint_incomplete`; pushed work or a changed publication still stops with `remote_changed` or `publication_changed`. A stopped stage names the checkpoint that keeps its worktree. When the fallback runs out of quota as well, the stage stops and the cycle ends `BLOCKED`, naming every executor's reset time; there is never a second automatic reroute. A stage without a Git worktree keeps the reconciliation above unchanged. + +The `BLOCKED` status when both attempted executors exhaust their quotas also +applies to read-only stages. They keep their existing workspace reconciliation; +the checkpoint handoff above is specific to writing stages. ### Operator quota recovery diff --git a/docs/telemetry.md b/docs/telemetry.md index f0e9cea..c01f066 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -568,6 +568,21 @@ diff text and provider prose never enter these tables. The journal holds the redacted original message and operator actions. See [operator quota recovery](routing.md#operator-quota-recovery). The additive tables leave existing rows readable; rollback leaves them unused. +### Recovery checkpoints + +`recovery_checkpoints.py` adds two tables on first use, outside the numbered +schema (#503): `recovery_checkpoints` (schema version, repository, work item, +change request, cycle, stage, attempt, workspace, branch, HEAD, kind, parent +checkpoint, secret-rule digest, status, lifecycle, private ref, commit and tree +IDs, worktree fingerprint, content digest, excluded paths with reason codes, +unsupported items, and lifecycle timestamps) and `recovery_adoptions` (the +anchor and adopted checkpoints, scope, HEAD, fingerprint, operator identity and +its source, and single-use consumption). The content itself lives in the +repository's Git object store behind `refs/code-cycle/recovery/`; file +contents, diff text and secret values never enter these tables. Rows are never +deleted: pruning removes a ref and sets `pruned_at`. See +[recovery checkpoints](recovery-checkpoints.md). + ### Work-item outcomes (schema 14) Work-item disposition events are stored in a separate append-only table. Each diff --git a/scripts/cycle.py b/scripts/cycle.py index 7736d96..a95fdff 100644 --- a/scripts/cycle.py +++ b/scripts/cycle.py @@ -64,6 +64,9 @@ ) from reroute import effect_snapshot, observe_publication, reconcile from quota_state import Handoffs +from recovery_checkpoints import ( + Checkpoints, ConcurrentWriter, RecoveryError, WriterLock, is_ancestor, worktree_root, +) from jev_shadow import JevShadow, telemetry_fields as shadow_fields from router import ( ProfileSelector, @@ -270,6 +273,12 @@ class _StageRun: compose_consents: list[dict[str, Any]] = field(default_factory=list) #: The sandbox grants the latest attempt was dispatched with. sandbox_grants: tuple[str, ...] = () + #: The worktree this stage checkpoints (#503), or None when it does not. + recovery_root: str | None = None + #: The quota checkpoint an automatic handoff continues from (#525). + checkpoint_handoff: dict[str, Any] | None = None + #: Each quota exhaustion of this stage: `executor/model until reset`. + quota_resets: list[str] = field(default_factory=list) #: The first routing and its signals, for the shadow. first: tuple[RoutingDecision, dict[str, object]] | None = None decision: RoutingDecision | None = None @@ -308,6 +317,15 @@ class _Attempt: blocker: dict[str, Any] | None = None known_prerequisite: bool = False retry: bool = False + #: An operator adoption this attempt resumes (#503). + adoption: dict[str, Any] | None = None + #: The toolkit writer lock this attempt holds on its worktree. + writer_lock: WriterLock | None = None + #: The checkpoint taken before the dispatch, and the one after a stop. + baseline: dict[str, Any] | None = None + checkpoint: dict[str, Any] | None = None + #: The effect snapshot taken after a quota exhaustion, reused by its gate. + after: dict[str, Any] | None = None @property def target(self) -> Target: @@ -537,15 +555,27 @@ def stage(self, role: str, task: str, *, escalated: bool = False, dispatch_kwargs=dispatch_kwargs, ) run.frozen_identity = frozen_identity + run.recovery_root = self._recovery_root(run) # A primary, its fallback, and one rerun after a permission answer. for number in range(3): attempt = self._route_attempt(run, number) if attempt.decision.blocked: self._record_blocked(run, attempt) break - result = self._dispatch_attempt(run, attempt) - result = self._settle_attempt(run, attempt, result) - self._persist_attempt(run, attempt, result) + try: + if run.checkpoint_handoff is not None: + self._check_checkpoint_handoff(run, attempt) + if attempt.decision.blocked: + self._record_blocked(run, attempt) + break + # The permission rerun reconciles the fallback's effects. + run.checkpoint_handoff = None + result = self._dispatch_attempt(run, attempt) + result = self._settle_attempt(run, attempt, result) + self._persist_attempt(run, attempt, result) + finally: + if attempt.writer_lock is not None: + self._release_writer(run, attempt.writer_lock) if not attempt.retry: break run.parent_attempt_id = attempt.attempt_id @@ -684,8 +714,175 @@ def _route_attempt(self, run: _StageRun, number: int) -> _Attempt: attempt = _Attempt(number=number, signals=signals, eligible=eligible, decision=decision) self._match_handoff(run, attempt) + self._acquire_writer(run, attempt) return attempt + # -- recovery checkpoints (#503) ------------------------------------------ + + def _recovery_root(self, run: _StageRun) -> str | None: + """The worktree a production writing stage checkpoints, if it has one.""" + if (self.mode is not RoutingMode.PRODUCTION + or run.workspace_policy is not WorkspacePolicy.WORKSPACE_WRITE): + return None + try: + return worktree_root(run.dispatch_kwargs.get("cwd")) + except Exception: + return None + + def _acquire_writer(self, run: _StageRun, attempt: _Attempt) -> None: + """One toolkit writer per worktree; a second one is refused before dispatch.""" + if run.recovery_root is None or attempt.decision.blocked: + return + lock = WriterLock(run.recovery_root, {"cycle": self.cycle_id, "stage": run.role, + "repo": self.repo_id, "task": self.task_id}) + try: + lock.acquire() + except ConcurrentWriter as error: + attempt.decision = replace( + attempt.decision, blocked=True, target=None, + reasons=attempt.decision.reasons + ( + f"{error}; a toolkit lock excludes other toolkit writers only and " + "cannot attribute edits made outside the toolkit",)) + return + except (OSError, RecoveryError) as error: + # A lock the toolkit cannot write is recorded, never a veto. + self._journal("failure", role=run.role, component="recovery", + status="lock_unavailable", detail=str(error)) + return + if lock.reclaimed is not None: + self._journal("stage_result", role=run.role, component="recovery", + status="stale_lock_reclaimed", + correlation={key: lock.reclaimed.get(key) for key in + ("pid", "host", "cycle", "evidence")}) + attempt.writer_lock = lock + + def _release_writer(self, run: _StageRun, lock: WriterLock) -> None: + """A release failure is journaled; it never masks the stage's own outcome.""" + try: + lock.release() + except (OSError, RecoveryError) as error: + self._journal("failure", role=run.role, component="recovery", + status="lock_release_failed", detail=f"{error}; lock {lock.path}") + + def _checkpoint(self, run: _StageRun, attempt: _Attempt, kind: str) -> dict[str, Any] | None: + """Best effort: a checkpoint that cannot be taken is journaled, never a veto.""" + if run.recovery_root is None: + return None + try: + row = Checkpoints(self.telemetry.path).capture( + run.recovery_root, repo=self.repo_id, task=self.task_id, cycle=self.cycle_id, + stage=run.role, kind=kind, attempt=attempt.attempt_id, + change_request=self.change_request_id) + except Exception as error: + self._journal("failure", role=run.role, attempt_id=attempt.attempt_id, + component="recovery", status="checkpoint_failed", detail=str(error)) + return None + self._journal("stage_result", role=run.role, attempt_id=attempt.attempt_id, + component="recovery", status=f"checkpoint_{row['status']}", + correlation={"checkpoint_id": row["id"], "kind": kind, + "parent_id": row.get("parent_id"), "head": row.get("head"), + "fingerprint": row.get("fingerprint"), + "excluded": len(row.get("exclusions") or []), + "unsupported": len(row.get("unsupported") or [])}) + return row + + def _check_checkpoint_handoff(self, run: _StageRun, attempt: _Attempt) -> None: + """The fallback starts only from the exact state its checkpoint recorded.""" + checkpoint = run.checkpoint_handoff + assert checkpoint is not None + if run.recovery_root is None: + return + try: + state = Checkpoints(self.telemetry.path).verify( + run.recovery_root, checkpoint, repo=self.repo_id, task=self.task_id) + except Exception as error: + state = {"state": "unreadable", "problems": [str(error)]} + if state["state"] != "matches": + attempt.decision = replace( + attempt.decision, blocked=True, target=None, + reasons=attempt.decision.reasons + ( + f"the worktree is not the quota checkpoint {checkpoint['id']}: " + f"{state['state']} {', '.join(state.get('problems') or [])}".rstrip() + + "; inspect or adopt it with recovery_checkpoints.py",)) + + def _checkpoint_gate(self, run: _StageRun, attempt: _Attempt, + result: DispatchResult) -> tuple[str, str] | None: + """#525: a quota stop of a writing stage hands its worktree to the fallback. + + Only from a complete checkpoint of a finished process whose starting + state was known, whose HEAD only moved forward and whose remote and + publications did not change. None keeps the #205 reconciliation. + """ + checkpoint = attempt.checkpoint + if result.failure_code != "quota" or run.recovery_root is None or checkpoint is None: + return None + if checkpoint["status"] != "complete": + return "stop", "checkpoint_incomplete" + before = attempt.before + after = attempt.after if attempt.after is not None else self._effect_snapshot(run) + if before is None or after is None or before.get("workspace") is None: + return "stop", "evidence_unavailable" + known_start = (not before["dirty"] or attempt.handoff is not None + or attempt.adoption is not None + or (attempt.baseline is not None and attempt.baseline["status"] == "complete")) + if not known_start: + return "stop", "dirty_workspace" + if not is_ancestor(run.recovery_root, before["workspace"]["head"], checkpoint["head"]): + return "stop", "workspace_changed" + action, reason = reconcile({**before, "dirty": False, "workspace": None}, + {**after, "dirty": False, "workspace": None}) + if action != "reroute": + return action, reason + return "reroute", "checkpoint_handoff" + + def _hand_over(self, run: _StageRun, attempt: _Attempt, fallback: Target, + exhaustion_expiry: str | None) -> None: + """Record the automatic handoff and tell the fallback what it continues.""" + checkpoint = attempt.checkpoint + assert checkpoint is not None + run.checkpoint_handoff = checkpoint + before = attempt.before or {} + start_head = (before.get("workspace") or {}).get("head") + local_commits = 0 + try: + from executors import _git_output + root = run.recovery_root + if root and start_head and checkpoint["head"] and start_head != checkpoint["head"]: + local_commits = int(_git_output(root, "rev-list", "--count", + f"{start_head}..{checkpoint['head']}") or 0) + except Exception: + local_commits = 0 + self._journal("stage_result", role=run.role, attempt_id=attempt.attempt_id, + component="recovery", status="quota_handoff", + correlation={"checkpoint_id": checkpoint["id"], "ref": checkpoint["ref"], + "original_executor": attempt.target.executor, + "original_model": attempt.target.model, + "destination_executor": fallback.executor, + "destination_model": fallback.model, + "start_head": start_head, "head": checkpoint["head"], + "local_commits": local_commits, + "dirty": (attempt.after or {}).get("dirty"), + "fingerprint": checkpoint["fingerprint"], + "exhausted_until": exhaustion_expiry}) + run.task += ( + "\n\nQuota checkpoint handoff: the previous executor of this stage ran out of " + "quota. Continue in this same worktree from its exact state; inspect the " + "existing commits and the staged, unstaged and untracked changes before " + "editing, keep correct partial work, and do not reset or overwrite it. " + f"Checkpoint: {checkpoint['id']}; original executor: {attempt.target.executor}; " + f"continuing executor: {fallback.executor}; local commits since the stage " + f"started: {local_commits}; worktree SHA-256: {checkpoint['fingerprint']}. " + "This handoff is not functional verification and skips no required check.") + + def _consume_checkpoints(self, run: _StageRun) -> None: + if run.recovery_root is None: + return + try: + Checkpoints(self.telemetry.path).consume( + repo=self.repo_id, task=self.task_id, workspace=run.recovery_root) + except (OSError, sqlite3.Error): + pass + def _route(self, run: _StageRun, candidates: frozenset[str], signals: dict[str, object]) -> RoutingDecision: rate = self.first_pass_rate @@ -831,17 +1028,35 @@ def _match_handoff(self, run: _StageRun, attempt: _Attempt) -> None: """Find the quota handoff a resumed stage continues, or block it.""" decision = attempt.decision if not (attempt.number == 0 and run.role == self.started_from - and self.started_from != "implement" and self.mode is RoutingMode.PRODUCTION and run.dispatch_kwargs.get("cwd") and not decision.blocked): return + from executors import _git_output, _workspace_fingerprint + cwd = run.dispatch_kwargs["cwd"] + workspace = None + try: + # Adoptions exist only for a Git worktree the toolkit can lock. + if run.recovery_root is not None: + workspace = _workspace_fingerprint(cwd) + # Explicit adoption also covers a clean tree with local commits. + # Consume it even when no dirty-worktree provenance is needed. + attempt.adoption = Checkpoints(self.telemetry.path).match_adoption( + repo=self.repo_id, task=self.task_id, stage=run.role, + change_request=self.change_request_id, workspace=workspace) + except (OSError, ValueError, sqlite3.Error, subprocess.SubprocessError) as error: + # The optional adoption lookup is recorded, never a veto (#450). + self._journal("failure", role=run.role, component="recovery", + status="adoption_lookup_failed", detail=str(error)) + if attempt.adoption is not None or run.role == "implement": + # Without an adoption, keep implement --continue's behavior. + return try: - from executors import _git_output, _workspace_fingerprint - cwd = run.dispatch_kwargs["cwd"] if _git_output(cwd, "status", "--porcelain", "--untracked-files=all"): + if workspace is None: + workspace = _workspace_fingerprint(cwd) attempt.handoff = Handoffs(self.telemetry.path).match( repo=self.repo_id, task=self.task_id, stage=run.role, - pr=self.change_request_id, workspace=_workspace_fingerprint(cwd), + pr=self.change_request_id, workspace=workspace, destination=decision.target) except (OSError, ValueError, sqlite3.Error) as error: attempt.decision = replace(decision, blocked=True, target=None, @@ -882,6 +1097,8 @@ def _dispatch_attempt(self, run: _StageRun, attempt: _Attempt) -> DispatchResult and self.mode is not RoutingMode.CALIBRATION else None) if attempt.handoff is not None: self._claim_handoff(run, attempt, attempt.handoff) + if attempt.adoption is not None: + self._claim_adoption(run, attempt.adoption) permission_context, grant_kwargs = self._permission_context(run, attempt) if self.consent is not None and target.executor == "codex": import stage_permissions as sp @@ -932,6 +1149,29 @@ def _claim_handoff(self, run: _StageRun, attempt: _Attempt, handoff: dict[str, A "fingerprint": handoff["fingerprint"], "provenance": handoff["provenance"]}) + def _claim_adoption(self, run: _StageRun, adoption: dict[str, Any]) -> None: + """Consume an operator adoption once, against the worktree as it is now.""" + try: + Checkpoints(self.telemetry.path).consume_adoption( + adoption, by=f"{self.cycle_id}/{run.role}") + except (OSError, RecoveryError, sqlite3.Error, subprocess.SubprocessError) as error: + raise CycleError(str(error)) from error + run.task += ( + "\n\nOperator-adopted worktree resume: an operator inspected and adopted the " + "existing staged, unstaged and untracked changes after checkpoint " + f"{adoption['checkpoint_id']}. Inspect them before editing and do not reset or " + f"overwrite them. Worktree SHA-256: {adoption['fingerprint']}; provenance: " + "operator_adopted. This is not executor authorship, grants nothing and is not " + "functional verification.") + self._journal("stage_result", role=run.role, component="recovery", + status="adoption_consumed", + correlation={"adoption_id": adoption["id"], + "checkpoint_id": adoption["checkpoint_id"], + "adopted_checkpoint_id": adoption["adopted_checkpoint_id"], + "operator": adoption["operator"], + "fingerprint": adoption["fingerprint"], + "provenance": "operator_adopted"}) + def _permission_context(self, run: _StageRun, attempt: _Attempt) -> tuple[str, dict[str, Any]]: """The grants and denials this attempt runs with, stated to the agent.""" @@ -1026,6 +1266,8 @@ def _begin_dispatch_attempt(self, run: _StageRun, attempt: _Attempt) -> str: relationship=attempt.relationship, ) attempt.attempt_id = attempt_id + # The attempt's intent and starting state are durable before it edits. + attempt.baseline = self._checkpoint(run, attempt, "baseline") if self.registry.get(target.executor).completes_work: self.telemetry.update_dispatch_attempt( attempt_id, {"lifecycle_state": "running"}, @@ -1070,6 +1312,8 @@ def _record_interruption(self, run: _StageRun, attempt: _Attempt, run.result = result if attempt.attempt_id is not None: run.attempts.append((decision, result)) + # Whatever the interrupted attempt left is kept for an explicit recovery. + attempt.checkpoint = self._checkpoint(run, attempt, "interrupted") run.rows.append(self._record( run.role, decision, result, attempt.signals, attempt_id=attempt.attempt_id, parent_attempt_id=run.parent_attempt_id, relationship=attempt.relationship, @@ -1096,6 +1340,7 @@ def _settle_attempt(self, run: _StageRun, attempt: _Attempt, elif (result.outcome is DispatchOutcome.SUCCEEDED and self.mode is RoutingMode.PRODUCTION): self._clear_quota(attempt) + self._consume_checkpoints(run) return self._consent_answer(run, attempt, result) @staticmethod @@ -1130,6 +1375,9 @@ def _reroute_gate(self, run: _StageRun, attempt: _Attempt, return "reroute", "not_started" if not run.writes and not run.publishes: return "reroute", "no_effects" + gate = self._checkpoint_gate(run, attempt, result) + if gate is not None: + return gate return reconcile(attempt.before, self._effect_snapshot(run)) def _unsupported_effort(self, run: _StageRun, attempt: _Attempt, @@ -1387,7 +1635,13 @@ def _transient_failure(self, run: _StageRun, attempt: _Attempt, reroute_error_code=result.failure_code, reroute_start_state=result.start_state) attempt.retry = action == "reroute" + if result.failure_code == "quota" and self.mode is RoutingMode.PRODUCTION: + run.quota_resets.append( + f"{target.executor}/{target.model} until " + f"{exhaustion_expiry or 'an unknown reset (explicit operator retry required)'}") if attempt.retry: + if reason == "checkpoint_handoff" and fallback is not None: + self._hand_over(run, attempt, fallback, exhaustion_expiry) run.fallback_decision = replace( decision, target=fallback, used_fallback=True, reasons=decision.reasons + (f"stage fallback after {result.failure_code}",), @@ -1399,6 +1653,12 @@ def _transient_failure(self, run: _StageRun, attempt: _Attempt, } return result detail = f"{redact(result.detail) if result.failure_code == 'quota' else result.detail}; reroute stopped: {reason}" + if len(run.quota_resets) > 1: + detail += ("; every executor of this stage is out of quota: " + + "; ".join(run.quota_resets)) + if attempt.checkpoint is not None: + detail += (f"; worktree kept in recovery checkpoint {attempt.checkpoint['id']} " + f"({attempt.checkpoint['status']})") if (result.failure_code == "quota" and self.mode is RoutingMode.PRODUCTION): if exhaustion_expiry and reset_reported: @@ -1437,15 +1697,31 @@ def _record_quota_exhaustion(self, run: _StageRun, attempt: _Attempt, correlation={"expires_at": exhaustion_expiry, "ambiguity": "reset_time_ambiguous" if exhaustion_expiry is None else None}) before = attempt.before - after = self._effect_snapshot(run) if self.change_request_id else None + finished = (result.process_exited and not result.asynchronous + and not result.needs_human_action) + # The exact worktree is durable before anything decides about it. + if finished and attempt.attempt_id is not None: + attempt.checkpoint = self._checkpoint(run, attempt, "quota_handoff") + after = (self._effect_snapshot(run) + if self.change_request_id or attempt.checkpoint is not None else None) + attempt.after = after + # Local commits since the start count as the stage's own only with + # a complete checkpoint of the state they lead to (#525). + advanced = (attempt.checkpoint is not None and run.recovery_root is not None + and attempt.checkpoint["status"] == "complete" + and before is not None and after is not None + and before.get("workspace") and after.get("workspace") + and after["workspace"]["head"] == attempt.checkpoint["head"] + and is_ancestor(run.recovery_root, before["workspace"]["head"], + after["workspace"]["head"])) # Only a finished executor with a clean initial tree, # or a validated prior ownership record, can own edits. - if (result.process_exited and not result.asynchronous - and not result.needs_human_action and fallback is not None + if (finished and fallback is not None and before is not None and after is not None - and (not before["dirty"] or attempt.handoff is not None) + and (not before["dirty"] or attempt.handoff is not None + or attempt.adoption is not None) and after["dirty"] - and before["workspace"]["head"] == after["workspace"]["head"] + and (before["workspace"]["head"] == after["workspace"]["head"] or advanced) and reconcile({**before, "dirty": False}, {**after, "dirty": False, "workspace": before["workspace"]})[0] == "reroute"): record_id = Handoffs(self.telemetry.path).record( @@ -1863,6 +2139,12 @@ def next_iteration(self) -> int: def close(self, final_status: str, **fields) -> int: """Record how the cycle ended, with the rounds it took.""" + try: + # Retention is lifecycle-based: a consumed checkpoint of a closed + # cycle becomes prunable; nothing is deleted here (#503). + Checkpoints(self.telemetry.path).mark_cycle_terminal(self.cycle_id) + except (OSError, sqlite3.Error): + pass return self.telemetry.record_stage( self.repo_id, self.task_id, "coordinate", iteration=self.iteration, status=final_status, diff --git a/scripts/cycle_dispatch.py b/scripts/cycle_dispatch.py index 21a943f..49f2512 100644 --- a/scripts/cycle_dispatch.py +++ b/scripts/cycle_dispatch.py @@ -14,6 +14,18 @@ if TYPE_CHECKING: from .run_cycle import CycleReport, Reported, StageOutcome, StagePolicy + +def quota_exhausted_everywhere(outcome) -> bool: + """Every executor the stage tried ran out of quota (#525 AC-3). + + Nothing a person decides now changes that before the reset times the + stop names, so the cycle ends `BLOCKED` rather than asking for help. + """ + attempts = getattr(outcome, "attempts", None) or [] + return len(attempts) >= 2 and all( + getattr(result, "failure_code", None) == "quota" for _, result in attempts) + + class StageDispatch: @staticmethod def _question_evidence(questions: object, messages: list[str], *, @@ -411,8 +423,9 @@ def unfinished(self: Any, outcome: StageOutcome, reported: Reported, and any("does not support effort" in reason for reason in outcome.decision.reasons)) ) + quota_everywhere = quota_exhausted_everywhere(outcome) return self.stop(self.api._why(outcome), reported=reported, - status="BLOCKED" if blocked_effort or ( + status="BLOCKED" if blocked_effort or quota_everywhere or ( self.orca_context is not None and outcome.result is not None and outcome.result.executor == "orca" and outcome.result.outcome.value == "blocked") else self.api.UNRESOLVED_END, diff --git a/scripts/cycle_journal.py b/scripts/cycle_journal.py index cc760e3..9da288a 100644 --- a/scripts/cycle_journal.py +++ b/scripts/cycle_journal.py @@ -181,6 +181,16 @@ def redact(text, limit: int = TEXT_LIMIT) -> str | None: return text +def contains_credential(text: str) -> bool: + """Whether `text` holds a published credential format or a private key. + + The same high-confidence families `redact` removes, matched with a name + boundary. Recovery checkpoints (#503) use it before anything reaches the + Git object store; like `redact`, it reduces exposure and proves nothing. + """ + return bool(_PRIVATE_KEY.search(text) or _REFERENCE_TOKEN.search(text)) + + def _now(value: datetime | None = None) -> str: return (value or datetime.now(timezone.utc)).astimezone(timezone.utc).isoformat() diff --git a/scripts/executors.py b/scripts/executors.py index 9ade018..100ffb6 100644 --- a/scripts/executors.py +++ b/scripts/executors.py @@ -2697,7 +2697,8 @@ def _checkout_fingerprint(path: str) -> dict: def _workspace_fingerprint(path: str, *, max_files: int | None = None, - max_bytes: int | None = None) -> dict | None: + max_bytes: int | None = None, + include_staged: bool = False) -> dict | None: """What a read-only stage must leave exactly as it found it. HEAD, the branch ref, the porcelain status including every untracked file, @@ -2709,6 +2710,8 @@ def _workspace_fingerprint(path: str, *, max_files: int | None = None, Optional budgets are used only for best-effort start evidence. Exceeding one returns None. Read-only contract callers omit them and remain exhaustive. + Checkpoints also hash staged-only paths so Git normalization cannot hide + changes to their physical bytes. """ root = _git_output(path, "rev-parse", "--show-toplevel") head = _git_output(root, "rev-parse", "HEAD") @@ -2718,6 +2721,10 @@ def _workspace_fingerprint(path: str, *, max_files: int | None = None, changed = _git_output( root, "ls-files", "-z", "--modified", "--others", "--exclude-standard", ) + if include_staged: + changed += "\0" + _git_output( + root, "diff", "--cached", "--name-only", "--no-renames", "--diff-filter=d", "-z", + ) paths = sorted(set(filter(None, changed.split("\0")))) if max_files is not None and len(paths) > max_files: return None diff --git a/scripts/recovery_checkpoints.py b/scripts/recovery_checkpoints.py new file mode 100644 index 0000000..ebcd5bc --- /dev/null +++ b/scripts/recovery_checkpoints.py @@ -0,0 +1,1307 @@ +"""Durable, scoped recovery checkpoints for interrupted writing stages (#503). + +A checkpoint records the exact staged, unstaged and eligible untracked state of +a worktree as ordinary Git objects, reachable from a private ref under +``refs/code-cycle/recovery/``. Its metadata lives in the telemetry store next +to the dispatch-attempt history, bound to repository, task, change request, +cycle, stage, attempt, workspace, branch and HEAD. + +Durability order: an intent row (``pending``) is written before any object, +objects are written next, the private ref is created only after every object +exists, and the row becomes ``complete`` only after the ref. A crash between +two steps leaves a state ``reconcile_pending`` can finish or mark ``failed``; +repeating a capture of the same content returns the same checkpoint. + +The worktree, the real index and the branch are never modified by a capture. +Secrets and ignored files are never captured: a path matching the versioned +exclusion list, or content holding a known credential format, stays out of the +object store and only its path and reason code are recorded. A checkpoint +that had to exclude relevant content, or could not represent it, is +``incomplete`` and is never used for an automatic handoff. + +Locks coordinate toolkit writers only. They cannot establish who made an edit +against an arbitrary external writer, and nothing here claims they do. +""" +from __future__ import annotations + +import argparse +import errno +import fnmatch +import getpass +import hashlib +import json +import os +import posixpath +import re +import shutil +import socket +import sqlite3 +import stat +import subprocess +import sys +import tempfile +import threading +import uuid +from contextlib import closing, contextmanager +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Callable, Iterable, Iterator + +SCHEMA_VERSION = 1 +SECRET_RULES_VERSION = 1 +REF_PREFIX = "refs/code-cycle/recovery/" +MESSAGE_TITLE = "code-cycle recovery checkpoint" +LOCK_NAME = "code-cycle-writer.lock" +# Windows byte-range locks do not serialize threads in the same process. +_WRITER_THREAD_LOCK = threading.Lock() +#: The largest file whose content is scanned; a larger one is excluded, so the +#: scan fails closed rather than capturing what it could not read. +MAX_SCAN_BYTES = 32 << 20 + +#: Versioned default secret-path exclusions. A repository adds its own with +#: ``code_cycle.recovery.secret_paths``; it can never remove one of these. +DEFAULT_SECRET_PATHS = ( + ".env", ".env.*", "*.pem", "*.key", "*.p12", "*.pfx", + "id_rsa*", "id_ed25519*", "id_ecdsa*", "id_dsa*", + ".npmrc", ".netrc", "_netrc", ".pypirc", ".git-credentials", + ".aws/credentials", "credentials.json", "secrets.json", +) +#: Templates that name no secret and are captured like any other file. +SECRET_TEMPLATE_EXCEPTIONS = (".env.example", ".env.sample", ".env.template", ".env.dist") + +#: Reason codes recorded for content left out of a checkpoint. +RELEVANT_EXCLUSIONS = frozenset({ + "secret_path", "secret_content", "scan_failed", "special_file", +}) + +SCHEMA = """ +CREATE TABLE IF NOT EXISTS recovery_checkpoints ( + id TEXT PRIMARY KEY, schema_version INTEGER NOT NULL, + repo_id TEXT NOT NULL, task_id TEXT NOT NULL, change_request_id TEXT, + cycle_id TEXT NOT NULL, stage TEXT NOT NULL, attempt_id TEXT, + workspace TEXT NOT NULL, branch TEXT, head TEXT, kind TEXT NOT NULL, + parent_id TEXT, rules_digest TEXT, status TEXT NOT NULL, + lifecycle TEXT NOT NULL DEFAULT 'active', ref TEXT, commit_sha TEXT, + index_tree TEXT, worktree_tree TEXT, fingerprint TEXT, content_digest TEXT, + exclusions TEXT, unsupported TEXT, duplicate_of TEXT, operator TEXT, + created_at TEXT NOT NULL, completed_at TEXT, consumed_at TEXT, + discarded_at TEXT, cycle_terminal_at TEXT, pruned_at TEXT +); +CREATE INDEX IF NOT EXISTS recovery_checkpoints_scope + ON recovery_checkpoints(repo_id, task_id, workspace); +CREATE TABLE IF NOT EXISTS recovery_adoptions ( + id TEXT PRIMARY KEY, checkpoint_id TEXT NOT NULL, adopted_checkpoint_id TEXT NOT NULL, + repo_id TEXT NOT NULL, task_id TEXT NOT NULL, change_request_id TEXT, + cycle_id TEXT NOT NULL, stage TEXT NOT NULL, attempt_id TEXT, + workspace TEXT NOT NULL, head TEXT NOT NULL, fingerprint TEXT NOT NULL, + operator TEXT NOT NULL, operator_source TEXT NOT NULL, adopted_at TEXT NOT NULL, + consumed_at TEXT, consumed_by TEXT +); +CREATE UNIQUE INDEX IF NOT EXISTS recovery_adoption_once + ON recovery_adoptions(checkpoint_id, fingerprint); +""" + + +class RecoveryError(ValueError): + """A recovery operation that cannot proceed; the worktree is untouched.""" + + +class ConcurrentWriter(RecoveryError): + """Another toolkit writer holds this worktree.""" + + +def _now() -> str: + return datetime.now(timezone.utc).isoformat() + + +# -- Git ----------------------------------------------------------------------- + +_DURABLE = ("-c", "core.fsync=committed", "-c", "core.fsyncMethod=fsync") +_IDENTITY = { + "GIT_AUTHOR_NAME": "Code Cycle recovery", "GIT_AUTHOR_EMAIL": "recovery@code-cycle.invalid", + "GIT_COMMITTER_NAME": "Code Cycle recovery", "GIT_COMMITTER_EMAIL": "recovery@code-cycle.invalid", +} + + +def _git(cwd: str, *args: str, env: dict | None = None, input: bytes | None = None, + check: bool = True) -> subprocess.CompletedProcess: + environment = {**os.environ, "GIT_OPTIONAL_LOCKS": "0", "LC_ALL": "C", + "GIT_LITERAL_PATHSPECS": "1", **(env or {})} + done = subprocess.run(["git", *_DURABLE, *args], cwd=cwd, env=environment, input=input, + capture_output=True, timeout=120) + if check and done.returncode: + raise RecoveryError(f"git {args[0]} failed: " + f"{done.stderr.decode('utf-8', 'replace').strip()[:300]}") + return done + + +def _out(cwd: str, *args: str, env: dict | None = None, input: bytes | None = None) -> str: + return _git(cwd, *args, env=env, input=input).stdout.decode("utf-8", "surrogateescape").strip() + + +def worktree_root(cwd: str | None) -> str | None: + """The worktree's top level, or None when `cwd` is not inside one.""" + if not cwd or not os.path.isdir(cwd): + return None + try: + done = _git(cwd, "rev-parse", "--show-toplevel", check=False) + except (OSError, subprocess.SubprocessError): + return None + if done.returncode: + return None + root = done.stdout.decode("utf-8", "surrogateescape").strip() + return os.path.realpath(root) if root else None + + +def _head(root: str) -> str | None: + done = _git(root, "rev-parse", "--verify", "-q", "HEAD^{commit}", check=False) + if done.returncode: + return None + return done.stdout.decode().strip() or None + + +def _git_path(root: str, name: str) -> str: + path = _out(root, "rev-parse", "--git-path", name) + return path if os.path.isabs(path) else os.path.join(root, path) + + +def is_ancestor(root: str, older: str | None, newer: str | None) -> bool: + if not older or not newer: + return False + if older == newer: + return True + return _git(root, "merge-base", "--is-ancestor", older, newer, check=False).returncode == 0 + + +def fingerprint(root: str, *, include_staged: bool = True) -> dict | None: + """Hash the workspace including the on-disk bytes of staged-only files.""" + from executors import _workspace_fingerprint + try: + return _workspace_fingerprint(root, include_staged=include_staged) + except Exception: + return None + + +# -- secret rules ------------------------------------------------------------- + +def secret_rules(root: str) -> tuple[tuple[str, ...], str | None]: + """Default exclusions plus the repository's additions, and any failure. + + A configuration that cannot be read or has the wrong shape is a failure: + the capture then fails closed instead of running with fewer exclusions + than the repository declared. + """ + patterns = list(DEFAULT_SECRET_PATHS) + config = Path(root) / ".code-cycle.yml" + if not config.is_file(): + return tuple(patterns), None + try: + import yaml + except ImportError: + return tuple(patterns), "secret_rules_unreadable" + try: + data = yaml.safe_load(config.read_text(encoding="utf-8")) or {} + except Exception: + return tuple(patterns), "secret_rules_unreadable" + recovery = ((data.get("code_cycle") or {}) if isinstance(data, dict) else {}) + recovery = recovery.get("recovery") if isinstance(recovery, dict) else None + if recovery is None: + return tuple(patterns), None + extra = recovery.get("secret_paths") if isinstance(recovery, dict) else None + if extra is None: + return tuple(patterns), None + if not isinstance(extra, list) or not all(isinstance(item, str) and item.strip() for item in extra): + return tuple(patterns), "secret_rules_invalid" + patterns.extend(item.strip() for item in extra) + return tuple(dict.fromkeys(patterns)), None + + +def rules_digest(patterns: Iterable[str]) -> str: + encoded = json.dumps([SECRET_RULES_VERSION, sorted(patterns), list(SECRET_TEMPLATE_EXCEPTIONS)]) + return hashlib.sha256(encoded.encode("utf-8")).hexdigest() + + +def secret_path(path: str, patterns: Iterable[str]) -> str | None: + """The pattern that excludes `path`, or None. Case-insensitive on purpose.""" + path = path.replace("\\", "/").rstrip("/").lower() + name = posixpath.basename(path) + if name in SECRET_TEMPLATE_EXCEPTIONS: + return None + for pattern in patterns: + lowered = pattern.replace("\\", "/").lower() + if "/" in lowered: + if fnmatch.fnmatchcase(path, lowered) or fnmatch.fnmatchcase(path, "*/" + lowered): + return pattern + elif fnmatch.fnmatchcase(name, lowered): + return pattern + return None + + +def _holds_credential(data: bytes) -> bool: + from cycle_journal import contains_credential + return contains_credential(data.decode("latin-1")) + + +# -- status -------------------------------------------------------------------- + +def _status(root: str) -> list[dict]: + raw = _git(root, "status", "--porcelain=v2", "-z", "--untracked-files=all", + "--ignore-submodules=none", "--no-renames").stdout + fields = raw.split(b"\0") + entries, index = [], 0 + while index < len(fields): + item = fields[index].decode("utf-8", "surrogateescape") + index += 1 + if not item: + continue + kind = item[0] + if kind == "?": + entries.append({"kind": "untracked", "path": item[2:]}) + elif kind == "1": + parts = item.split(" ", 8) + entries.append({"kind": "changed", "xy": parts[1], "sub": parts[2], + "mode_index": parts[4], "mode_worktree": parts[5], + "hash_index": parts[7], "path": parts[8]}) + elif kind == "2": + parts = item.split(" ", 9) + index += 1 # the original path follows; renames are disabled above + entries.append({"kind": "changed", "xy": parts[1], "sub": parts[2], + "mode_index": parts[4], "mode_worktree": parts[5], + "hash_index": parts[7], "path": parts[9]}) + elif kind == "u": + entries.append({"kind": "unmerged", "path": item.split(" ", 10)[10]}) + return entries + + +# -- capture ------------------------------------------------------------------- + +def _connect(path) -> sqlite3.Connection: + connection = sqlite3.connect(str(path), timeout=10) + connection.row_factory = sqlite3.Row + connection.executescript(SCHEMA) + return connection + + +def _rows(rows) -> list[dict]: + return [cast_row(_row(row)) for row in rows] + + +def _row(row) -> dict | None: + if row is None: + return None + value = dict(row) + for key in ("exclusions", "unsupported"): + try: + value[key] = json.loads(value[key]) if value.get(key) else [] + except ValueError: + value[key] = None + return value + + +class Checkpoints: + """The checkpoint ledger in the telemetry store, and its Git content.""" + + def __init__(self, path): + self.path = str(path) + + def connect(self) -> sqlite3.Connection: + return _connect(self.path) + + def _exists(self) -> bool: + if not os.path.exists(self.path): + return False + with closing(sqlite3.connect(self.path, timeout=10)) as connection: + return connection.execute( + "SELECT 1 FROM sqlite_master WHERE type='table' AND name='recovery_checkpoints'" + ).fetchone() is not None + + # -- reads ---------------------------------------------------------------- + + def get(self, checkpoint_id: str) -> dict | None: + if not self._exists(): + return None + with closing(self.connect()) as connection: + return _row(connection.execute( + "SELECT * FROM recovery_checkpoints WHERE id=?", (checkpoint_id,)).fetchone()) + + def list(self, *, repo: str, task: str | None = None) -> list[dict]: + if not self._exists(): + return [] + query, values = "SELECT * FROM recovery_checkpoints WHERE repo_id=?", [repo] + if task is not None: + query += " AND task_id=?" + values.append(task) + with closing(self.connect()) as connection: + return _rows(connection.execute(query + " ORDER BY rowid", values)) + + def latest(self, *, repo: str, task: str, workspace: str, + statuses: tuple[str, ...] = ("complete",)) -> dict | None: + if not self._exists(): + return None + marks = ",".join("?" for _ in statuses) + with closing(self.connect()) as connection: + return _row(connection.execute( + f"SELECT * FROM recovery_checkpoints WHERE repo_id=? AND task_id=? AND workspace=? " + f"AND status IN ({marks}) AND lifecycle='active' AND duplicate_of IS NULL " + f"ORDER BY rowid DESC LIMIT 1", + (repo, task, workspace, *statuses)).fetchone()) + + # -- capture -------------------------------------------------------------- + + def capture(self, cwd: str, *, repo: str, task: str, cycle: str, stage: str, + kind: str, attempt: str | None = None, + change_request: str | None = None) -> dict: + """Record the worktree's exact state; return the checkpoint row. + + Never raises for the worktree's content: what cannot be captured makes + the checkpoint `incomplete` and is named. Raises RecoveryError only + when there is no Git worktree to checkpoint or the store is unusable. + """ + root = worktree_root(cwd) + if root is None: + raise RecoveryError("no Git worktree to checkpoint") + head = _head(root) + branch = _git(root, "symbolic-ref", "-q", "HEAD", check=False).stdout.decode().strip() or None + patterns, rules_failure = secret_rules(root) + checkpoint_id = f"checkpoint-{uuid.uuid4().hex}" + with closing(self.connect()) as connection, connection: + parent = connection.execute( + "SELECT id FROM recovery_checkpoints WHERE repo_id=? AND task_id=? AND workspace=? " + "AND status='complete' AND duplicate_of IS NULL ORDER BY rowid DESC LIMIT 1", + (repo, task, root)).fetchone() + # The intent precedes every object this capture writes. + connection.execute( + "INSERT INTO recovery_checkpoints (id,schema_version,repo_id,task_id," + "change_request_id,cycle_id,stage,attempt_id,workspace,branch,head,kind," + "parent_id,rules_digest,status,created_at) VALUES " + "(?,?,?,?,?,?,?,?,?,?,?,?,?,?,'pending',?)", + (checkpoint_id, SCHEMA_VERSION, repo, task, change_request, cycle, stage, + attempt, root, branch, head, kind, parent["id"] if parent else None, + rules_digest(patterns), _now())) + try: + content = _capture_content(root, head, patterns, rules_failure) + except (OSError, subprocess.SubprocessError, RecoveryError) as error: + self._finish(checkpoint_id, status="failed", + unsupported=[{"reason": "capture_failed", + "detail": str(error)[:200]}]) + return cast_row(self.get(checkpoint_id)) + digest = _content_digest(head, content) + scope = {"repo": repo, "task": task, "change_request": change_request, + "cycle": cycle, "stage": stage, "attempt": attempt, "workspace": root, + "branch": branch, "head": head, "kind": kind} + with closing(self.connect()) as connection: + duplicate = connection.execute( + "SELECT id FROM recovery_checkpoints WHERE repo_id=? AND task_id=? AND workspace=? " + "AND stage=? AND kind=? AND content_digest=? AND status IN ('complete','incomplete') " + "AND IFNULL(attempt_id,'')=IFNULL(?,'') AND duplicate_of IS NULL " + "AND lifecycle='active' AND id<>?", + (repo, task, root, stage, kind, digest, attempt, checkpoint_id)).fetchone() + if duplicate is not None: + # The same logical capture again: one checkpoint, never two. + self._finish(checkpoint_id, status="duplicate", duplicate_of=duplicate["id"]) + return cast_row(self.get(duplicate["id"])) + status = "complete" if content["complete"] else "incomplete" + commit = ref = None + if content["index_tree"] and content["worktree_tree"]: + metadata = {"schema_version": SCHEMA_VERSION, "id": checkpoint_id, **scope, + "index_tree": content["index_tree"], + "worktree_tree": content["worktree_tree"], + "content_digest": digest, "status": status, + "fingerprint": content["fingerprint"], + # Blobs are the files' exact bytes, except these paths. + "unfiltered": True, "filtered": content["filtered"], + "emulated_symlinks": content["emulated_symlinks"], + "fingerprint_includes_staged": True, + "exclusions": content["exclusions"], + "unsupported": content["unsupported"]} + commit = _commit(root, head, content, metadata) + ref = REF_PREFIX + checkpoint_id + # Created, never moved: an existing ref of this name is an error. + _git(root, "update-ref", "-m", MESSAGE_TITLE, ref, commit, "") + elif status == "complete": + status = "incomplete" + self._finish(checkpoint_id, status=status, ref=ref, commit_sha=commit, + index_tree=content["index_tree"], worktree_tree=content["worktree_tree"], + fingerprint=content["fingerprint"], content_digest=digest, + exclusions=content["exclusions"], unsupported=content["unsupported"]) + return cast_row(self.get(checkpoint_id)) + + def _finish(self, checkpoint_id: str, **fields: Any) -> None: + values = {key: (json.dumps(value) if key in {"exclusions", "unsupported"} else value) + for key, value in fields.items()} + if values.get("status") in {"complete", "incomplete", "failed", "duplicate"}: + values["completed_at"] = _now() + assignments = ",".join(f"{key}=?" for key in values) + with closing(self.connect()) as connection, connection: + connection.execute(f"UPDATE recovery_checkpoints SET {assignments} WHERE id=?", + (*values.values(), checkpoint_id)) + + def reconcile_pending(self, cwd: str) -> list[dict]: + """Finish or fail captures a crash left `pending`. Idempotent.""" + root = worktree_root(cwd) + if root is None or not self._exists(): + return [] + with closing(self.connect()) as connection: + pending = [dict(row) for row in connection.execute( + "SELECT * FROM recovery_checkpoints WHERE workspace=? AND status='pending'", + (root,))] + settled = [] + for row in pending: + ref = REF_PREFIX + row["id"] + commit = _git(root, "rev-parse", "--verify", "-q", ref + "^{commit}", + check=False).stdout.decode().strip() + metadata = _metadata(root, commit) if commit else None + if metadata is not None and metadata.get("id") == row["id"]: + unsupported = metadata.get("unsupported") or [] + if "fingerprint" not in metadata: + unsupported = [*unsupported, {"reason": "fingerprint_unrecorded"}] + self._finish(row["id"], status=metadata.get("status", "incomplete"), ref=ref, + commit_sha=commit, index_tree=metadata.get("index_tree"), + worktree_tree=metadata.get("worktree_tree"), + content_digest=metadata.get("content_digest"), + fingerprint=metadata.get("fingerprint"), + exclusions=metadata.get("exclusions") or [], unsupported=unsupported) + else: + self._finish(row["id"], status="failed", + unsupported=[{"reason": "interrupted_before_ref"}]) + settled.append(cast_row(self.get(row["id"]))) + return settled + + # -- verification ---------------------------------------------------------- + + def verify(self, cwd: str, row: dict, *, repo: str | None = None, + task: str | None = None, change_request: str | None = None) -> dict: + """What the checkpoint and the worktree say now. Never modifies either.""" + root = worktree_root(cwd) + problems: list[str] = [] + if root is None: + return {"state": "no_worktree", "problems": ["no_worktree"]} + if row.get("schema_version") != SCHEMA_VERSION or row.get("exclusions") is None: + problems.append("corrupt_metadata") + if ((repo is not None and row.get("repo_id") != repo) + or (task is not None and row.get("task_id") != task) + or (change_request is not None and row.get("change_request_id") not in {None, change_request}) + or row.get("workspace") != root): + problems.append("wrong_scope") + if row.get("status") not in {"complete", "incomplete"}: + problems.append(f"status_{row.get('status')}") + commit = None + if row.get("ref"): + commit = _git(root, "rev-parse", "--verify", "-q", row["ref"] + "^{commit}", + check=False).stdout.decode().strip() or None + if commit is None: + problems.append("missing_ref") + elif commit != row.get("commit_sha"): + problems.append("corrupt_metadata") + metadata = None + if commit: + metadata = _metadata(root, commit) + if metadata is None or any(metadata.get(key) != row.get(column) for key, column in ( + ("id", "id"), ("repo", "repo_id"), ("task", "task_id"), + ("stage", "stage"), ("head", "head"), ("workspace", "workspace"), + ("index_tree", "index_tree"), ("worktree_tree", "worktree_tree"))): + problems.append("corrupt_metadata") + elif "fingerprint" in metadata and metadata["fingerprint"] != row.get("fingerprint"): + problems.append("corrupt_metadata") + if _missing_objects(root, [row.get("index_tree"), row.get("worktree_tree")]): + problems.append("missing_objects") + current_head = _head(root) + current = fingerprint(root) + comparable = current + if (metadata or {}).get("fingerprint_includes_staged") is not True: + comparable = fingerprint(root, include_staged=False) if row.get("fingerprint") else None + state = "matches" + if current_head != row.get("head"): + state = "head_changed" + if is_ancestor(root, row.get("head"), current_head): + state = "head_advanced" + elif comparable is None or comparable["fingerprint"] != row.get("fingerprint"): + state = "fingerprint_changed" + return {"state": state if not problems else "integrity_failed", + "workspace_state": state, "problems": sorted(set(problems)), + "current_head": current_head, + "current_fingerprint": current["fingerprint"] if current else None} + + # -- restore ------------------------------------------------------------- + + def restore(self, cwd: str, row: dict) -> dict: + """Recreate the checkpoint's index and worktree on a clean worktree. + + Refuses unless HEAD is the checkpoint's HEAD and nothing is changed, + staged or untracked: a restore never overwrites or discards work. + """ + root = worktree_root(cwd) + if root is None: + raise RecoveryError("no Git worktree to restore into") + check = self.verify(root, row) + if check["problems"]: + raise RecoveryError("checkpoint integrity: " + ", ".join(check["problems"])) + if _head(root) != row["head"]: + raise RecoveryError("restore needs HEAD at the checkpoint's HEAD") + if _status(root): + raise RecoveryError("restore needs a clean worktree; nothing was changed") + _git(root, "read-tree", "-m", "-u", row["head"], row["worktree_tree"]) + _git(root, "read-tree", row["index_tree"]) + metadata = _metadata(root, row["commit_sha"]) or {} + _restore_exact(root, row["head"], row["index_tree"], row["worktree_tree"], metadata) + after = fingerprint(root, include_staged=metadata.get("fingerprint_includes_staged") is True) + return {"restored": row["id"], "fingerprint": after["fingerprint"] if after else None, + "matches": bool(after and after["fingerprint"] == row["fingerprint"])} + + # -- lifecycle ------------------------------------------------------------- + + def consume(self, *, repo: str, task: str, workspace: str | None) -> int: + """Mark the active checkpoints of a scope consumed after a completed stage.""" + if workspace is None or not self._exists(): + return 0 + with closing(self.connect()) as connection, connection: + return connection.execute( + "UPDATE recovery_checkpoints SET lifecycle='consumed', consumed_at=? " + "WHERE repo_id=? AND task_id=? AND workspace=? AND lifecycle='active' " + "AND status IN ('complete','incomplete','duplicate')", + (_now(), repo, task, workspace)).rowcount + + def mark_cycle_terminal(self, cycle: str) -> None: + if not self._exists(): + return + with closing(self.connect()) as connection, connection: + connection.execute( + "UPDATE recovery_checkpoints SET cycle_terminal_at=? " + "WHERE cycle_id=? AND cycle_terminal_at IS NULL", (_now(), cycle)) + + def discard(self, checkpoint_id: str, *, operator: str) -> dict: + with closing(self.connect()) as connection, connection: + updated = connection.execute( + "UPDATE recovery_checkpoints SET lifecycle='discarded', discarded_at=?, operator=? " + "WHERE id=? AND lifecycle='active'", (_now(), operator, checkpoint_id)).rowcount + row = self.get(checkpoint_id) + if row is None: + raise RecoveryError("checkpoint not found") + if not updated and row["lifecycle"] != "discarded": + raise RecoveryError(f"checkpoint is {row['lifecycle']}, not active") + return row + + def prunable(self, *, repo: str | None = None) -> list[dict]: + """Unused content eligible for explicit pruning.""" + if not self._exists(): + return [] + query = ("SELECT c.* FROM recovery_checkpoints c WHERE c.pruned_at IS NULL " + "AND c.ref IS NOT NULL AND c.status IN ('complete','incomplete') AND (" + " c.lifecycle='discarded' OR (c.lifecycle='consumed' AND c.cycle_terminal_at IS NOT NULL))" + " AND NOT EXISTS (SELECT 1 FROM recovery_checkpoints d WHERE d.parent_id=c.id" + " AND d.lifecycle='active' AND d.status IN ('complete','incomplete','pending'))" + " AND NOT EXISTS (SELECT 1 FROM recovery_adoptions a WHERE" + " (a.checkpoint_id=c.id OR a.adopted_checkpoint_id=c.id) AND a.consumed_at IS NULL)") + values: list[str] = [] + if repo is not None: + query += " AND c.repo_id=?" + values.append(repo) + with closing(self.connect()) as connection: + return _rows(connection.execute(query + " ORDER BY c.rowid", values)) + + def prune(self, *, repo: str | None = None, dry_run: bool = False) -> list[dict]: + """Delete prunable refs; keep every row, fingerprint and provenance. + + Ref first, row second: an interrupted prune leaves a row whose ref is + already gone, and the next prune only records it. `update-ref -d` with + the recorded commit refuses a ref that another writer moved. + """ + candidates = self.prunable(repo=repo) + if dry_run: + return [{"id": row["id"], "ref": row["ref"], "action": "would_prune"} for row in candidates] + pruned = [] + for row in candidates: + root = row["workspace"] + action = "pruned" + if worktree_root(root) == root: + current = _git(root, "rev-parse", "--verify", "-q", row["ref"], + check=False).stdout.decode().strip() + if current and current != row["commit_sha"]: + pruned.append({"id": row["id"], "ref": row["ref"], "action": "skipped_moved"}) + continue + if current: + _git(root, "update-ref", "-d", row["ref"], row["commit_sha"]) + else: + action = "already_absent" + else: + action = "workspace_missing" + with closing(self.connect()) as connection, connection: + connection.execute( + "UPDATE recovery_checkpoints SET pruned_at=? WHERE id=? AND pruned_at IS NULL", + (_now(), row["id"])) + pruned.append({"id": row["id"], "ref": row["ref"], "action": action}) + return pruned + + # -- adoption -------------------------------------------------------------- + + def adopt(self, cwd: str, checkpoint_id: str, *, confirm_fingerprint: str, operator: str, + operator_source: str, cycle: str, stage: str, attempt: str | None = None) -> dict: + """An operator adopts the edits after a completed checkpoint. + + The fingerprint the operator inspected must still be the worktree's. + The adopted state becomes a new checkpoint; the original stays as it + was. Adoption is provenance, never authorship, approval or verification. + """ + row = self.get(checkpoint_id) + if row is None: + raise RecoveryError("checkpoint not found") + check = self.verify(cwd, row) + if check["problems"]: + raise RecoveryError("checkpoint integrity: " + ", ".join(check["problems"])) + if row["status"] != "complete" or row["lifecycle"] != "active": + raise RecoveryError("only an active complete checkpoint can anchor an adoption") + current = fingerprint(row["workspace"]) + if current is None or current["fingerprint"] != confirm_fingerprint: + raise RecoveryError("the inspected fingerprint is no longer the worktree's") + adopted = self.capture(row["workspace"], repo=row["repo_id"], task=row["task_id"], + cycle=cycle, stage=stage, kind="operator_adopted", + attempt=attempt, change_request=row["change_request_id"]) + if adopted["status"] != "complete" or adopted.get("fingerprint") != confirm_fingerprint: + raise RecoveryError("the adopted state could not be checkpointed completely: " + + json.dumps(adopted.get("exclusions") or adopted.get("unsupported"))) + adoption_id = f"adoption-{uuid.uuid4().hex}" + try: + with closing(self.connect()) as connection, connection: + connection.execute( + "INSERT INTO recovery_adoptions (id,checkpoint_id,adopted_checkpoint_id,repo_id," + "task_id,change_request_id,cycle_id,stage,attempt_id,workspace,head,fingerprint," + "operator,operator_source,adopted_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", + (adoption_id, row["id"], adopted["id"], row["repo_id"], row["task_id"], + row["change_request_id"], cycle, stage, attempt, row["workspace"], + current["head"], confirm_fingerprint, operator, operator_source, _now())) + except sqlite3.IntegrityError as error: + raise RecoveryError("this fingerprint was already adopted for that checkpoint") from error + return {"adoption_id": adoption_id, "checkpoint_id": row["id"], + "adopted_checkpoint_id": adopted["id"], "fingerprint": confirm_fingerprint, + "operator": operator, "operator_source": operator_source, + "provenance": "operator_adopted"} + + def match_adoption(self, *, repo: str, task: str, stage: str, change_request: str | None, + workspace: dict | None) -> dict | None: + """The unconsumed adoption that covers this exact worktree, if any.""" + if workspace is None or not self._exists(): + return None + root = os.path.realpath(workspace["root"]) + with closing(self.connect()) as connection: + rows = _rows(connection.execute( + "SELECT * FROM recovery_adoptions WHERE repo_id=? AND task_id=? AND workspace=? " + "AND stage=? AND head=? AND consumed_at IS NULL " + "AND (change_request_id IS NULL OR change_request_id=?) ORDER BY rowid DESC", + (repo, task, root, stage, workspace["head"], change_request))) + return next((row for row in rows if self._adoption_matches(row)), None) + + def _adoption_matches(self, adoption: dict) -> bool: + checkpoint = self.get(adoption["adopted_checkpoint_id"]) + if (not checkpoint or checkpoint["status"] != "complete" + or checkpoint["lifecycle"] == "discarded" + or checkpoint["stage"] != adoption["stage"] + or checkpoint["head"] != adoption["head"] + or checkpoint["fingerprint"] != adoption["fingerprint"]): + return False + state = self.verify(adoption["workspace"], checkpoint, repo=adoption["repo_id"], + task=adoption["task_id"], change_request=adoption["change_request_id"]) + return state["state"] == "matches" + + def consume_adoption(self, adoption: dict, *, by: str) -> None: + """Single use, atomic, and re-checked against the worktree right now.""" + if not self._adoption_matches(adoption): + raise RecoveryError("the worktree changed after the adoption") + with closing(self.connect()) as connection, connection: + updated = connection.execute( + "UPDATE recovery_adoptions SET consumed_at=?, consumed_by=? " + "WHERE id=? AND consumed_at IS NULL", (_now(), by, adoption["id"])).rowcount + if updated != 1: + raise RecoveryError("adoption already used") + + +def cast_row(row: dict | None) -> dict: + if row is None: + raise RecoveryError("checkpoint row disappeared") + return row + + +def _content_digest(head: str | None, content: dict) -> str: + encoded = json.dumps([head, content["index_tree"], content["worktree_tree"], + content["exclusions"], content["unsupported"], content["fingerprint"], + content.get("filtered"), content.get("emulated_symlinks")], sort_keys=True) + return hashlib.sha256(encoded.encode("utf-8")).hexdigest() + + +def _capture_content(root: str, head: str | None, patterns: tuple[str, ...], + rules_failure: str | None) -> dict: + """Trees for the staged and the worktree state, built in private indexes.""" + before = fingerprint(root) + entries = _status(root) + exclusions: list[dict] = [] + unsupported: list[dict] = [] + if rules_failure: + unsupported.append({"reason": rules_failure}) + if any(entry["kind"] == "unmerged" for entry in entries): + unsupported.extend({"path": entry["path"], "reason": "unmerged"} + for entry in entries if entry["kind"] == "unmerged") + return {"index_tree": None, "worktree_tree": None, "exclusions": exclusions, + "unsupported": unsupported, "complete": False, + "fingerprint": before["fingerprint"] if before else None} + revert: list[str] = [] # staged secret content, put back to HEAD's + worktree: dict[str, tuple[str, str]] = {} + regular: dict[str, tuple[str, bool]] = {} + symlinks: list[str] = [] + zero = "0" * (len(head) if head else 40) + filemode = None + for entry in entries: + path = entry["path"] + if entry["kind"] == "untracked" and path.endswith("/"): + unsupported.append({"path": path, "reason": "nested_repository"}) + continue + sub = entry.get("sub", "N...") + if sub.startswith("S") and (sub[2] != "." or sub[3] != "."): + unsupported.append({"path": path, "reason": "dirty_submodule"}) + reason = "secret_path" if secret_path(path, patterns) else None + staged = entry["kind"] == "changed" and entry["xy"][0] != "." + if (reason is None and staged and entry["mode_index"] not in {"000000", "160000"}): + blob = _git(root, "cat-file", "blob", entry["hash_index"], check=False) + if blob.returncode: + reason = "scan_failed" + elif _holds_credential(blob.stdout): + reason = "secret_content" + if reason is not None: + exclusions.append({"path": path, "reason": reason}) + if staged: + revert.append(path) + continue + unstaged = entry["kind"] == "untracked" or entry["xy"][1] != "." + full = os.path.join(root, path) + if not unstaged: + # Staged only: the index already holds it, cleaned. Its exact + # bytes replace that blob when they are safe to store. + mode = entry.get("mode_index") + if mode and mode not in {"000000", "160000"} and _regular_file(full): + regular[path] = (mode, False) + continue + if entry.get("mode_worktree") == "000000": + # A directory can have replaced this path or one of its parents. + # Git still reports the old entry as deleted in either case. + worktree[path] = ("0", zero) + continue + try: + info = os.lstat(full) + except FileNotFoundError: + worktree[path] = ("0", zero) + continue + except OSError: + exclusions.append({"path": path, "reason": "scan_failed"}) + continue + if stat.S_ISREG(info.st_mode): + mode = entry.get("mode_worktree") + if mode not in {"100644", "100755", "120000"}: + # Git's porcelain does not give a mode for untracked paths. + if filemode is None: + value = _git(root, "config", "--bool", "--get", "core.filemode", check=False) + if value.returncode not in {0, 1}: + raise RecoveryError("cannot determine Git file mode handling") + filemode = value.stdout.strip() != b"false" + mode = "100755" if filemode and info.st_mode & stat.S_IXUSR else "100644" + regular[path] = (mode, True) + elif stat.S_ISLNK(info.st_mode): + symlinks.append(path) + elif stat.S_ISDIR(info.st_mode) and worktree_root(full) == os.path.realpath(full): + sub_head = _head(full) + if sub_head: + worktree[path] = ("160000", sub_head) + else: + unsupported.append({"path": path, "reason": "submodule_head_missing"}) + else: + exclusions.append({"path": path, "reason": "special_file"}) + scratch = tempfile.mkdtemp(prefix="code-cycle-checkpoint-") + try: + staged_index = os.path.join(scratch, "staged") + real_index = _git_path(root, "index") + if os.path.exists(real_index): + shutil.copyfile(real_index, staged_index) + staged_env = {"GIT_INDEX_FILE": staged_index} + if revert: + lines = [] + for path in revert: + listed = _git(root, "ls-tree", "-z", head, "--", path).stdout if head else b"" + record = listed.split(b"\0")[0] if listed else b"" + if record: + meta, _, name = record.partition(b"\t") + mode, _, sha = meta.decode().split(" ") + lines.append(f"{mode} {sha}\t".encode() + name) + else: + lines.append(f"0 {zero}\t".encode() + path.encode("utf-8", "surrogateescape")) + _git(root, "update-index", "-z", "--index-info", env=staged_env, + input=b"\0".join(lines) + b"\0") + index_tree = _out(root, "write-tree", env=staged_env) + work_index = os.path.join(scratch, "worktree") + if os.path.exists(staged_index): + shutil.copyfile(staged_index, work_index) + work_env = {"GIT_INDEX_FILE": work_index} + filtered, emulated = _capture_worktree(root, work_env, worktree, regular, symlinks, exclusions) + worktree_tree = _out(root, "write-tree", env=work_env) + finally: + shutil.rmtree(scratch, ignore_errors=True) + after = fingerprint(root) + if before is None or after is None or before["fingerprint"] != after["fingerprint"]: + unsupported.append({"reason": "changed_during_capture"}) + relevant = [item for item in exclusions if item["reason"] in RELEVANT_EXCLUSIONS] + return {"index_tree": index_tree, "worktree_tree": worktree_tree, + "filtered": filtered, "emulated_symlinks": emulated, + "exclusions": exclusions, "unsupported": unsupported, + "complete": not relevant and not unsupported, + "fingerprint": after["fingerprint"] if after else None} + + +_FILE_MODES = {"100644", "100755"} +_SAFE_OPEN = (getattr(os, "O_BINARY", 0) | getattr(os, "O_NOFOLLOW", 0) + | getattr(os, "O_NONBLOCK", 0)) + + +def _regular_file(full: str) -> bool: + try: + return stat.S_ISREG(os.lstat(full).st_mode) + except OSError: + return False + + +def _scan_regular(full: str) -> tuple[bytes, str | None]: + """Read bounded plain-file bytes and validate the same bytes we may store.""" + if os.path.islink(full): + return b"", "scan_failed" + try: + with os.fdopen(os.open(full, os.O_RDONLY | _SAFE_OPEN), "rb") as handle: + info = os.fstat(handle.fileno()) + if not stat.S_ISREG(info.st_mode) or info.st_size > MAX_SCAN_BYTES: + return b"", "scan_failed" + data = handle.read(MAX_SCAN_BYTES + 1) + except OSError: + return b"", "scan_failed" + if len(data) > MAX_SCAN_BYTES: + return b"", "scan_failed" + if _holds_credential(data): + return b"", "secret_content" + return data, None + + +def _filtered_paths(root: str, env: dict, paths: list[str]) -> set[str]: + """Find paths that must pass through Git's clean filter.""" + if not paths: + return set() + listed = _git(root, "check-attr", "-z", "--stdin", "--all", env=env, + input=b"\0".join(p.encode("utf-8", "surrogateescape") for p in paths) + b"\0" + ).stdout.split(b"\0") + # check-attr uses the same spellings for attribute states and driver names. + # Treat a configured driver with one of those names conservatively. + # With --all Git omits unspecified attributes, so a literal + # filter=unspecified is unambiguous. + attribute_states = {b"unset", b"set"} + config = _git(root, "config", "--name-only", "--null", "--get-regexp", + r"^filter\.(unset|set)\.(clean|process|smudge)$", check=False) + if config.returncode not in {0, 1}: + raise RecoveryError("cannot determine configured Git filters") + configured = {key.split(b".")[1] for key in config.stdout.split(b"\0") if key} + return {name.decode("utf-8", "surrogateescape") + for name, attr, value in zip(listed[0::3], listed[1::3], listed[2::3]) + if attr == b"filter" and (value not in attribute_states or value in configured)} + + +def _capture_worktree(root: str, env: dict, entries: dict[str, tuple[str, str]], + regular: dict[str, tuple[str, bool]], symlinks: list[str], + exclusions: list[dict]) -> tuple[list[str], list[str]]: + """Store scanned bytes directly. Git never reopens a path to hash it. + + The private index starts from the staged state. Git's clean filters retain + control of their paths; other regular files keep their exact bytes. + """ + driven = _filtered_paths(root, env, [path for path, (mode, _) in regular.items() + if mode in _FILE_MODES]) + filtered: list[str] = [] + emulated: list[str] = [] + for path, (mode, unstaged) in regular.items(): + if mode == "120000": + emulated.append(path) + data, reason = _scan_regular(os.path.join(root, path)) + if reason: + exclusions.append({"path": path, "reason": reason}) + if not unstaged and mode in _FILE_MODES: + filtered.append(path) + continue + if path in driven: + filtered.append(path) + if not unstaged: + continue + conversion = f"--path={path}" if path in driven else "--no-filters" + sha = _out(root, "hash-object", "-w", conversion, "--stdin", env=env, input=data) + entries[path] = (mode, sha) + for path in symlinks: + try: + target = os.fsencode(os.readlink(os.path.join(root, path))) + except OSError: + exclusions.append({"path": path, "reason": "scan_failed"}) + continue + if _holds_credential(target): + exclusions.append({"path": path, "reason": "secret_content"}) + continue + sha = _out(root, "hash-object", "-w", "--no-filters", "--stdin", env=env, input=target) + entries[path] = ("120000", sha) + lines = [f"{mode} {sha}\t".encode() + path.encode("utf-8", "surrogateescape") + for path, (mode, sha) in entries.items()] + if lines: + _git(root, "update-index", "-z", "--index-info", env=env, input=b"\0".join(lines) + b"\0") + return sorted(filtered), sorted(emulated) + + +def _restore_exact(root: str, head: str, index_tree: str, tree: str, metadata: dict) -> None: + """Give every restored file the checkpoint's exact bytes and link type. + + The checkout that recreated the worktree applies the repository's smudge + side: `core.autocrlf` turns LF into CRLF, and `core.symlinks=false` writes + a link as a file holding its target. Both are Git for Windows defaults. A + link the platform refuses to create stays the file Git wrote. + + Covers every path the checkpoint captured: what differs from HEAD, and + what differs from the staged state even when it equals HEAD. A blob the + checkpoint did not store unfiltered keeps what Git checked out, and so + does a file that cannot be rewritten: the caller's fingerprint comparison + then reports the difference. + """ + exact = metadata.get("unfiltered") is True + kept = set(metadata.get("filtered") or []) + emulated = set(metadata.get("emulated_symlinks") or []) + captured: dict[bytes, tuple[str, str]] = {} + for base in (head, index_tree): + fields = _git(root, "diff-tree", "-r", "-z", "--no-renames", base, tree).stdout.split(b"\0") + for meta, name in zip(fields[0::2], fields[1::2]): + _old_mode, mode, _old_sha, sha, _status_code = meta.decode().lstrip(":").split(" ") + captured[name] = (mode, sha) + for name, (mode, sha) in captured.items(): + path = name.decode("utf-8", "surrogateescape") + full = os.path.join(root, path) + try: + if mode in _FILE_MODES and exact and path not in kept and not os.path.islink(full): + data = _git(root, "cat-file", "blob", sha).stdout + with os.fdopen(os.open(full, os.O_RDWR | _SAFE_OPEN), "r+b") as handle: + if stat.S_ISREG(os.fstat(handle.fileno()).st_mode) and handle.read() != data: + handle.seek(0) + handle.write(data) # in place: keep the file mode + handle.truncate() + elif mode == "120000" and path in emulated and os.path.islink(full): + target = _git(root, "cat-file", "blob", sha).stdout + os.remove(full) + with open(full, "xb") as handle: + handle.write(target) + elif (mode == "120000" and path not in emulated + and os.path.isfile(full) and not os.path.islink(full)): + target = _git(root, "cat-file", "blob", sha).stdout + os.remove(full) + try: + os.symlink(os.fsdecode(target), full) + except (OSError, NotImplementedError): + with open(full, "xb") as handle: + handle.write(target) + except OSError: + continue + + +def _commit(root: str, head: str | None, content: dict, metadata: dict) -> str: + message = f"{MESSAGE_TITLE} {metadata['id']}\n\n{json.dumps(metadata, sort_keys=True)}\n" + parents = ["-p", head] if head else [] + index_commit = _out(root, "commit-tree", "--no-gpg-sign", content["index_tree"], *parents, + "-m", f"{MESSAGE_TITLE} index {metadata['id']}", env=_IDENTITY) + # On standard input: the metadata can outgrow one command-line argument. + return _out(root, "commit-tree", "--no-gpg-sign", content["worktree_tree"], *parents, + "-p", index_commit, "-F", "-", env=_IDENTITY, input=message.encode("utf-8")) + + +def _metadata(root: str, commit: str) -> dict | None: + done = _git(root, "cat-file", "commit", commit, check=False) + if done.returncode: + return None + body = done.stdout.decode("utf-8", "replace").split("\n\n", 1) + if len(body) != 2 or not body[1].startswith(MESSAGE_TITLE): + return None + try: + value = json.loads(body[1].split("\n\n", 1)[1]) + except (IndexError, ValueError): + return None + return value if isinstance(value, dict) else None + + +def _missing_objects(root: str, trees: list[str | None]) -> bool: + for tree in trees: + if not tree: + return True + listing = _git(root, "ls-tree", "-r", "-t", "-z", tree, check=False) + if listing.returncode: + return True + objects = [] + for record in listing.stdout.split(b"\0"): + if not record: + continue + _mode, kind, sha = record.split(b"\t", 1)[0].decode().split(" ") + if kind != "commit": # gitlinks name another repository's commit + objects.append(sha) + if objects: + check = _git(root, "cat-file", "--batch-check", input="\n".join(objects).encode() + b"\n", + check=False) + if check.returncode or b" missing" in check.stdout: + return True + return False + + +# -- writer lock ----------------------------------------------------------------- + +def _alive(pid: int) -> bool: + if pid <= 0: + return False + if os.name == "nt": # os.kill(pid, 0) would send CTRL_C_EVENT on Windows + import ctypes + handle = ctypes.windll.kernel32.OpenProcess(0x1000, False, pid) # type: ignore[attr-defined] + if handle: + ctypes.windll.kernel32.CloseHandle(handle) # type: ignore[attr-defined] + return True + return ctypes.windll.kernel32.GetLastError() != 87 # type: ignore[attr-defined] + try: + os.kill(pid, 0) + except ProcessLookupError: + return False + except PermissionError: + return True + return True + + +class WriterLock: + """One toolkit writer per worktree, recorded in the worktree's Git dir. + + It excludes other toolkit writers only. An editor, a shell or another tool + can still change the worktree; the lock cannot detect or attribute that. + """ + + def __init__(self, cwd: str, owner: dict): + root = worktree_root(cwd) + if root is None: + raise RecoveryError("no Git worktree to lock") + self.root = root + self.path = _git_path(root, LOCK_NAME) + self.owner = {**owner, "pid": os.getpid(), "host": socket.gethostname(), + "acquired_at": _now(), "lock_id": uuid.uuid4().hex} + self.held = False + self.reclaimed: dict | None = None + + def holder(self) -> dict | None: + try: + with open(self.path, encoding="utf-8") as handle: + value = json.load(handle) + return value if isinstance(value, dict) else {"unreadable": True} + except FileNotFoundError: + return None + except (OSError, ValueError): + return {"unreadable": True} + + @contextmanager + def _guard(self, *, wait: bool = False) -> Iterator[None]: + """Serialize changes to the replaceable lock record on a stable inode. + + Never unlink this guard: replacing it would let two processes lock + different inodes. The OS releases the advisory lock on process death. + """ + with _WRITER_THREAD_LOCK: + descriptor = os.open(self.path + ".guard", os.O_CREAT | os.O_RDWR, 0o600) + with os.fdopen(descriptor, "r+b") as handle: + try: + if os.name == "nt": + import msvcrt + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_LOCK if wait else msvcrt.LK_NBLCK, 1) + else: + import fcntl + fcntl.flock(handle.fileno(), fcntl.LOCK_EX | (0 if wait else fcntl.LOCK_NB)) + except OSError as error: + if error.errno in {errno.EACCES, errno.EAGAIN, errno.EDEADLK}: + raise ConcurrentWriter( + f"another toolkit writer is updating the worktree lock; lock {self.path}") from error + raise + try: + yield + finally: + if os.name == "nt": + handle.seek(0) + msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1) + else: + fcntl.flock(handle.fileno(), fcntl.LOCK_UN) + + def acquire(self) -> "WriterLock": + with self._guard(): + return self._acquire_guarded() + + def _acquire_guarded(self) -> "WriterLock": + for _ in range(2): + try: + descriptor = os.open(self.path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600) + except FileExistsError: + holder = self.holder() + if holder is None: + continue + stale = (not holder.get("unreadable") + and holder.get("host") == self.owner["host"] + and isinstance(holder.get("pid"), int) and not _alive(holder["pid"])) + if not stale: + raise ConcurrentWriter( + "another toolkit writer holds this worktree: " + + json.dumps({key: holder.get(key) for key in + ("pid", "host", "cycle", "attempt", "acquired_at", "unreadable") + if key in holder}) + + f"; lock {self.path}") + # The dead owner's record is kept next to the lock as evidence. + evidence = f"{self.path}.stale-{uuid.uuid4().hex[:8]}" + try: + os.replace(self.path, evidence) + except FileNotFoundError: + continue + self.reclaimed = {**holder, "evidence": evidence} + continue + with os.fdopen(descriptor, "w", encoding="utf-8") as handle: + json.dump(self.owner, handle) + handle.flush() + os.fsync(handle.fileno()) + self.held = True + return self + raise ConcurrentWriter(f"the worktree lock could not be acquired; lock {self.path}") + + def release(self) -> None: + if not self.held: + return + with self._guard(wait=True): + holder = self.holder() + if holder and holder.get("lock_id") == self.owner["lock_id"]: + try: + os.remove(self.path) + except FileNotFoundError: + pass + self.held = False + + def unlock(self, confirm_pid: int) -> tuple[dict | None, str | None]: + """Inspect and move a dead holder's record in one guarded operation.""" + with self._guard(): + holder = self.holder() + if holder is None: + return None, None + if holder.get("pid") != confirm_pid and not holder.get("unreadable"): + raise RecoveryError("the lock holder is not the confirmed process") + if not holder.get("unreadable") and holder.get("host") == socket.gethostname() \ + and _alive(int(holder.get("pid") or 0)): + raise RecoveryError("the lock holder is still running") + evidence = f"{self.path}.stale-{uuid.uuid4().hex[:8]}" + os.replace(self.path, evidence) + return holder, evidence + + +# -- operator CLI ------------------------------------------------------------------ + +def operator_identity(run: Callable = subprocess.run) -> tuple[str, str]: + """Who runs the command: the code-host login when readable, else the OS user.""" + try: + done = run(["gh", "api", "user", "--jq", ".login"], capture_output=True, text=True, timeout=30) + login = (done.stdout or "").strip() + if done.returncode == 0 and re.fullmatch(r"[A-Za-z0-9-]{1,100}", login): + return login, "code_host_login" + except (OSError, subprocess.SubprocessError): + pass + return getpass.getuser(), "local_user" + + +def _journal(database: str, *, repo: str, task: str, status: str, correlation: dict) -> None: + try: + from cycle_journal import record_event + record_event(database, repo_id=repo, task_id=task, + cycle_id=f"operator-{uuid.uuid4().hex}", kind="stage_result", + component="recovery", status=status, correlation=correlation) + except Exception: + pass + + +def main(argv: list[str] | None = None, *, identity: Callable[[], tuple[str, str]] = operator_identity) -> int: + parser = argparse.ArgumentParser(description=(__doc__ or "").split("\n\n")[0]) + parser.add_argument("--database", required=True) + commands = parser.add_subparsers(dest="command", required=True) + listing = commands.add_parser("list", help="list checkpoints of a repository") + listing.add_argument("--repo", required=True) + listing.add_argument("--task") + for name, text in (("inspect", "show a checkpoint, its integrity and the current fingerprint"), + ("restore", "recreate a checkpoint on a clean worktree at its HEAD"), + ("adopt", "adopt the edits after a completed checkpoint, once"), + ("discard", "mark an abandoned checkpoint discarded")): + command = commands.add_parser(name, help=text) + command.add_argument("--checkpoint", required=True) + if name != "discard": + command.add_argument("--cwd", required=True) + if name == "adopt": + command.add_argument("--confirm-fingerprint", required=True) + command.add_argument("--stage", required=True, choices=("implement", "resolve")) + prune = commands.add_parser("prune", help="delete refs of consumed or discarded checkpoints") + prune.add_argument("--repo") + prune.add_argument("--dry-run", action="store_true") + unlock = commands.add_parser("unlock", help="remove a stale toolkit writer lock") + unlock.add_argument("--cwd", required=True) + unlock.add_argument("--confirm-pid", required=True, type=int) + args = parser.parse_args(argv) + store = Checkpoints(args.database) + try: + if args.command == "list": + print(json.dumps(store.list(repo=args.repo, task=args.task))) + return 0 + if args.command == "prune": + result = store.prune(repo=args.repo, dry_run=args.dry_run) + if not args.dry_run and result: + operator, source = identity() + _journal(args.database, repo=args.repo or "-", task="-", status="pruned", + correlation={"operator": operator, "operator_source": source, + "checkpoints": [item["id"] for item in result]}) + print(json.dumps(result)) + return 0 + if args.command == "unlock": + lock = WriterLock(args.cwd, {}) + holder, evidence = lock.unlock(args.confirm_pid) + if holder is None: + print(json.dumps({"lock": lock.path, "action": "absent"})) + return 0 + operator, source = identity() + _journal(args.database, repo=str(holder.get("repo") or "-"), + task=str(holder.get("task") or "-"), status="unlocked", + correlation={"operator": operator, "operator_source": source, + "lock": lock.path, "evidence": evidence, + "pid": holder.get("pid"), "cycle": holder.get("cycle")}) + print(json.dumps({"lock": lock.path, "action": "unlocked", "evidence": evidence})) + return 0 + row = store.get(args.checkpoint) + if row is None: + raise RecoveryError("checkpoint not found") + if args.command == "inspect": + store.reconcile_pending(args.cwd) + row = cast_row(store.get(args.checkpoint)) + print(json.dumps({"checkpoint": row, "verification": store.verify(args.cwd, row), + "note": "inspection is not functional verification"})) + return 0 + operator, source = identity() + if args.command == "restore": + result = store.restore(args.cwd, row) + elif args.command == "discard": + result = {"discarded": store.discard(args.checkpoint, operator=operator)["id"]} + else: + result = store.adopt(args.cwd, args.checkpoint, + confirm_fingerprint=args.confirm_fingerprint, + operator=operator, operator_source=source, + cycle=f"operator-{uuid.uuid4().hex}", stage=args.stage) + _journal(args.database, repo=row["repo_id"], task=row["task_id"], status=args.command, + correlation={"checkpoint_id": row["id"], "operator": operator, + "operator_source": source, **{key: value for key, value in result.items() + if isinstance(value, (str, bool))}}) + print(json.dumps({**result, "operator": operator, "at": _now()})) + return 0 + except (RecoveryError, OSError, subprocess.SubprocessError, sqlite3.Error) as error: + print(f"recovery refused: {error}", file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/run_cycle.py b/scripts/run_cycle.py index 43932bc..8336171 100644 --- a/scripts/run_cycle.py +++ b/scripts/run_cycle.py @@ -202,6 +202,7 @@ "security_review", # security_gate.py "orchestration", # cc-orchestrator "calibration", # cc-orca-orchestrator paired review + "recovery", # recovery_checkpoints.py: secret_paths (#503) }) #: Every key `code_cycle` may carry. Anything else is a typo or a key this @@ -459,7 +460,7 @@ def load_config(path: Path) -> dict: "code_cycle.routing", "code_cycle.calibration", "code_cycle.issue_review", "code_cycle.resolve", "code_cycle.allowed_commands", "code_cycle.ci", "code_cycle.docker", - "code_cycle.execution", + "code_cycle.execution", "code_cycle.recovery", ): section, value = config, None for part in key.split("."): diff --git a/scripts/runtime.manifest b/scripts/runtime.manifest index 41ec517..9b8567f 100644 --- a/scripts/runtime.manifest +++ b/scripts/runtime.manifest @@ -37,6 +37,7 @@ harness.py router.py telemetry.py quota_state.py +recovery_checkpoints.py production_events.py cycle_status.py profile_config.py diff --git a/scripts/telemetry.py b/scripts/telemetry.py index 9dd1c53..bbab87a 100644 --- a/scripts/telemetry.py +++ b/scripts/telemetry.py @@ -313,6 +313,8 @@ def is_jev_model(value) -> bool: "remote_changed", "publication_changed", "unsupported_effort", "same_sandbox", # A sensitive sandbox grant (schema 20). "permission_required", "permission_answered", + # A quota stop of a writing stage and its recovery checkpoint (#503). + "checkpoint_handoff", "checkpoint_incomplete", })), "reroute_error_code": ("token", frozenset({ "capacity", "transport", "timeout", "quota", "unsupported_effort", diff --git a/scripts/windows-test-shards.json b/scripts/windows-test-shards.json index 5798056..c53d23b 100644 --- a/scripts/windows-test-shards.json +++ b/scripts/windows-test-shards.json @@ -158,6 +158,8 @@ "test_native_prerequisites", "test_profile_config", "test_quota_resume", + "test_quota_handoff", + "test_recovery_checkpoints", "test_publication", "test_publication_audit", "test_precheck_causes", diff --git a/tests/test_quota_handoff.py b/tests/test_quota_handoff.py new file mode 100644 index 0000000..549c54f --- /dev/null +++ b/tests/test_quota_handoff.py @@ -0,0 +1,441 @@ +"""#525 absorbed into #503: a quota stop of a writing stage hands its worktree +to the configured fallback once, in the same stage, from a complete checkpoint.""" +from __future__ import annotations + +import json +import sqlite3 +import subprocess +import sys +import tempfile +import unittest +from contextlib import closing +from pathlib import Path +from types import SimpleNamespace +from typing import Any +from unittest.mock import Mock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import cycle as cy # noqa: E402 +import executors as ex # noqa: E402 +import grants # noqa: E402 +import recovery_checkpoints as rc # noqa: E402 +import router # noqa: E402 +from cycle_journal import Journal # noqa: E402 +from telemetry import Telemetry # noqa: E402 +from test_cycle import ScriptedAdapter # noqa: E402 + +TOKEN = "ghp_" + "Z9y8X7w6V5u4T3s2R1q0" * 2 + + +class QuotaHandoffCase(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.cwd = self.root / "checkout" + self.cwd.mkdir() + self.git("init", "-b", "task-503") + self.git("config", "user.email", "fixture@example.invalid") + self.git("config", "user.name", "Fixture") + self.git("config", "commit.gpgsign", "false") + for name in ("one.py", "two.py"): + (self.cwd / name).write_bytes(b"initial\n") + self.git("add", ".") + self.git("commit", "-m", "fixture") + self.head = self.git("rev-parse", "HEAD") + self.store = Telemetry(self.root / "telemetry.sqlite") + self.remote = "same" + snapshots = patch("cycle.effect_snapshot", side_effect=self.snapshot) + snapshots.start() + self.addCleanup(snapshots.stop) + + def git(self, *args): + return subprocess.run(["git", *args], cwd=self.cwd, capture_output=True, + text=True, check=True).stdout.strip() + + def snapshot(self, *args, **kwargs): + # The publication boundary is fixed by the fixture: no push, no PR edit. + return {"dirty": bool(self.git("status", "--porcelain", "--untracked-files=all")), + "workspace": ex._workspace_fingerprint(str(self.cwd)), "remote": self.remote, + "pulls": [], "observed_pulls": {}, "comments": []} + + def recorder(self, adapters, *, change_request_id=None, availability=None, **kw): + recorder = cy.CycleRecorder( + self.store, "owner/repo", "503", router.TaskSignals(difficulty=3), + availability={**{a.name: ex.Availability.READY for a in adapters}, **(availability or {})}, + registry=ex.Registry(adapters), change_request_id=change_request_id, **kw) + recorder.journal = Journal(self.store.path, "owner/repo", "503", recorder.cycle_id, + change_request_id=change_request_id) + return recorder + + def rows(self, table): + with closing(sqlite3.connect(self.store.path)) as connection: + connection.row_factory = sqlite3.Row + return [dict(row) for row in connection.execute(f"SELECT * FROM {table} ORDER BY rowid")] + + def events(self, status=None): + return [row for row in self.rows("journal_events") + if row["component"] == "recovery" and (status is None or row["status"] == status)] + + def commit_and_edit(self): + (self.cwd / "one.py").write_bytes(b"committed by the primary\n") + self.git("commit", "-qam", "local work") + (self.cwd / "two.py").write_bytes(b"staged by the primary\n") + self.git("add", "two.py") + (self.cwd / "two.py").write_bytes(b"unstaged after staged\n") + (self.cwd / "three.py").write_bytes(b"untracked\x00bytes\n") + + def exhausted(self, name, edit=None, message="quota exceeded; resets 2026-12-01 10:00 UTC"): + class Exhausted(ScriptedAdapter): + def dispatch(self, target, task, **kw): + self.dispatched.append(task) + if edit is not None: + edit() + return ex.DispatchResult(ex.DispatchOutcome.FAILED, self.name, target, + error_code="quota", start_state="started", + process_exited=True, detail=message) + return Exhausted(name) + + def continuing(self, name, seen): + fixture = self + + class Continuing(ScriptedAdapter): + def dispatch(self, target, task, **kw): + seen.update(cwd=kw.get("cwd"), head=fixture.git("rev-parse", "HEAD"), + fingerprint=(ex._workspace_fingerprint(str(fixture.cwd)) or {}).get("fingerprint"), + two=(fixture.cwd / "two.py").read_bytes(), + staged=fixture.git("diff", "--cached", "--name-only")) + return super().dispatch(target, task, **kw) + return Continuing(name) + + +class AutomaticHandoffTests(QuotaHandoffCase): + def assert_handoff(self, role, change_request_id): + seen: dict = {} + primary = self.exhausted("codex", self.commit_and_edit) + fallback = self.continuing("claude", seen) + recorder = self.recorder([primary, fallback], change_request_id=change_request_id) + outcome = recorder.stage(role, "work", cwd=str(self.cwd)) + self.assertTrue(outcome.succeeded, outcome.result and outcome.result.detail) + self.assertTrue(outcome.rerouted) + self.assertEqual(1, len(primary.dispatched)) + self.assertEqual(1, len(fallback.dispatched)) + # The same worktree, with the primary's commit and edits intact. + self.assertEqual(str(self.cwd), seen["cwd"]) + self.assertNotEqual(self.head, seen["head"]) + self.assertEqual(b"unstaged after staged\n", seen["two"]) + self.assertEqual("two.py", seen["staged"]) + handoff = self.events("quota_handoff") + self.assertEqual(1, len(handoff)) + correlation = json.loads(handoff[0]["correlation"]) + # The journal keeps correlation values as bounded text. + self.assertEqual(("codex", "claude", "1", seen["fingerprint"], self.head, seen["head"]), + (correlation["original_executor"], correlation["destination_executor"], + correlation["local_commits"], correlation["fingerprint"], + correlation["start_head"], correlation["head"])) + self.assertEqual("2026-12-01T10:00:00+00:00", correlation["exhausted_until"]) + checkpoint = rc.Checkpoints(self.store.path).get(correlation["checkpoint_id"]) + assert checkpoint is not None + self.assertEqual(("complete", "quota_handoff", seen["fingerprint"]), + (checkpoint["status"], checkpoint["kind"], checkpoint["fingerprint"])) + self.assertIn(checkpoint["ref"], self.git("for-each-ref", "refs/code-cycle/")) + self.assertIn("Quota checkpoint handoff", fallback.dispatched[0]) + self.assertIn(checkpoint["id"], fallback.dispatched[0]) + self.assertIn("not functional verification", fallback.dispatched[0]) + attempts = self.rows("dispatch_attempts") + self.assertEqual([("codex", None), ("claude", "fallback")], + [(row["executor"], row["relationship"]) for row in attempts]) + self.assertIn("checkpoint_handoff", json.dumps([ + row for table in self.tables() for row in self.rows(table) + if table not in {"journal_events"}])) + # A completed stage consumes what protected it. + self.assertTrue(all(row["lifecycle"] == "consumed" + for row in self.rows("recovery_checkpoints") + if row["status"] == "complete")) + return outcome + + def tables(self): + with closing(sqlite3.connect(self.store.path)) as connection: + return [row[0] for row in connection.execute( + "SELECT name FROM sqlite_master WHERE type='table'")] + + def _has(self, table): + with closing(sqlite3.connect(self.store.path)) as connection: + return connection.execute("SELECT 1 FROM sqlite_master WHERE name=?", + (table,)).fetchone() is not None + + def test_ac1_implement_with_local_commits_and_uncommitted_edits(self): + self.assert_handoff("implement", None) + + def test_ac2_resolve_with_unpushed_local_commits(self): + self.assert_handoff("resolve", "384") + + def test_permission_rerun_checks_fallback_effects_only(self): + primary = self.exhausted("codex") + blocker = { + "kind": "sandbox_local_access", "command": "docker info", + "error": "sandbox denied access to /var/run/docker.sock", + "attempted": ["checked socket availability"], "requires_human": False, + } + + class RestrictedOnce(ScriptedAdapter): + def dispatch(self, target, task, **kw): + result = super().dispatch(target, task, **kw) + if len(self.dispatched) == 1: + return ex.DispatchResult( + result.outcome, self.name, target, start_state="started", + process_exited=True, + agent_output="ORCHESTRATION_RESULT\n" + json.dumps( + {"status": "BLOCKED", "environment_blocker": blocker}) + + "\nEND_ORCHESTRATION_RESULT") + return result + + fallback = RestrictedOnce("claude") + consent = grants.ConsentBroker( + "owner/repo", platform="linux", store=grants.ConsentStore(self.root / "consents.json"), + prompt=lambda question: "cycle", + ) + recorder = self.recorder([primary, fallback], consent=consent) + with patch.object(rc.Checkpoints, "verify", autospec=True, + side_effect=rc.Checkpoints.verify) as verify: + outcome = recorder.stage("implement", "work", cwd=str(self.cwd)) + self.assertTrue(outcome.succeeded, outcome.result and outcome.result.detail) + self.assertEqual((1, 2), (len(primary.dispatched), len(fallback.dispatched))) + self.assertEqual(1, verify.call_count) + self.assertEqual("quota_handoff", verify.call_args.args[2]["kind"]) + self.assertEqual(["codex", "claude", "claude"], + [row["executor"] for row in self.rows("dispatch_attempts")]) + + def test_ac3_both_executors_exhausted_stop_names_both_resets(self): + primary = self.exhausted("codex", self.commit_and_edit, + "quota exceeded; resets 2026-12-01 10:00 UTC") + fallback = self.exhausted("claude", None, "usage limit; resets 2026-12-02 11:30 UTC") + outcome = self.recorder([primary, fallback]).stage("implement", "work", cwd=str(self.cwd)) + self.assertFalse(outcome.succeeded) + self.assertEqual((1, 1), (len(primary.dispatched), len(fallback.dispatched))) + assert outcome.result is not None + detail = outcome.result.detail + self.assertIn("every executor of this stage is out of quota", detail) + self.assertIn("2026-12-01T10:00:00+00:00", detail) + self.assertIn("2026-12-02T11:30:00+00:00", detail) + # The driver reports it BLOCKED rather than asking a person to intervene. + import run_cycle + from cycle_dispatch import StageDispatch + dispatch: Any = object.__new__(StageDispatch) + dispatch.api = run_cycle + dispatch.consent = None + dispatch.orca_context = None + dispatch.plan_head = self.git("rev-parse", "HEAD") + dispatch.stop = Mock(side_effect=lambda because, **kw: SimpleNamespace( + status=kw["status"], stopped_because=because, stop_reason=kw["stop_reason"])) + report: Any = dispatch.unfinished(outcome, run_cycle.Reported(), None) + self.assertEqual("BLOCKED", report.status) + self.assertEqual("dispatch_failed", report.stop_reason) + self.assertIn("2026-12-01T10:00:00+00:00", report.stopped_because) + self.assertIn("2026-12-02T11:30:00+00:00", report.stopped_because) + # The worktree is kept, never reset. + self.assertEqual(b"unstaged after staged\n", (self.cwd / "two.py").read_bytes()) + + def test_a_single_exhaustion_is_not_reported_as_everywhere(self): + from cycle_dispatch import quota_exhausted_everywhere + primary = self.exhausted("codex", self.commit_and_edit) + outcome = self.recorder([primary, ScriptedAdapter("claude")], + availability={"claude": ex.Availability.INSTALLED}).stage( + "implement", "work", cwd=str(self.cwd)) + self.assertFalse(outcome.succeeded) + self.assertFalse(quota_exhausted_everywhere(outcome)) + + def test_ac4_one_automatic_reroute_per_stage(self): + primary = self.exhausted("codex", self.commit_and_edit) + fallback = self.exhausted("claude") + outcome = self.recorder([primary, fallback]).stage("implement", "work", cwd=str(self.cwd)) + self.assertEqual(2, len(outcome.attempts)) + self.assertEqual(1, len(self.events("quota_handoff"))) + self.assertEqual(2, len(self.rows("quota_history"))) + + def test_pushed_work_is_not_handed_over(self): + def edit_and_push(): + self.commit_and_edit() + self.remote = "moved" + primary, fallback = self.exhausted("codex", edit_and_push), ScriptedAdapter("claude") + outcome = self.recorder([primary, fallback], change_request_id="384").stage( + "resolve", "work", cwd=str(self.cwd)) + self.assertFalse(outcome.succeeded) + self.assertEqual([], fallback.dispatched) + assert outcome.result is not None + self.assertIn("remote_changed", outcome.result.detail) + self.assertIn("recovery checkpoint", outcome.result.detail) + + def test_secret_in_the_worktree_makes_the_checkpoint_incomplete(self): + def edit_with_secret(): + self.commit_and_edit() + (self.cwd / "config.py").write_bytes(f"TOKEN = '{TOKEN}'\n".encode()) + primary, fallback = self.exhausted("codex", edit_with_secret), ScriptedAdapter("claude") + outcome = self.recorder([primary, fallback]).stage("implement", "work", cwd=str(self.cwd)) + self.assertFalse(outcome.succeeded) + self.assertEqual([], fallback.dispatched) + assert outcome.result is not None + self.assertIn("checkpoint_incomplete", outcome.result.detail) + self.assertEqual(f"TOKEN = '{TOKEN}'\n".encode(), (self.cwd / "config.py").read_bytes()) + self.assertNotIn(TOKEN, json.dumps(self.rows("journal_events"))) + + def test_edit_between_checkpoint_and_fallback_blocks_the_fallback(self): + primary, fallback = self.exhausted("codex", self.commit_and_edit), ScriptedAdapter("claude") + capture = rc.Checkpoints.capture + + def capture_then_external_edit(store, cwd, **kw): + row = capture(store, cwd, **kw) + if kw.get("kind") == "quota_handoff": + (self.cwd / "two.py").write_bytes(b"an external editor\n") + return row + with patch.object(rc.Checkpoints, "capture", capture_then_external_edit): + outcome = self.recorder([primary, fallback]).stage("implement", "work", cwd=str(self.cwd)) + self.assertFalse(outcome.succeeded) + self.assertEqual([], fallback.dispatched) + self.assertTrue(outcome.decision.blocked) + self.assertIn("is not the quota checkpoint", outcome.decision.explain()) + self.assertEqual(b"an external editor\n", (self.cwd / "two.py").read_bytes()) + lock = rc.WriterLock(str(self.cwd), {}).acquire() + lock.release() + + def test_without_a_worktree_the_reconciliation_is_unchanged(self): + primary = self.exhausted("codex") + outcome = self.recorder([primary, ScriptedAdapter("claude")]).stage("implement", "work") + self.assertEqual([], self.rows("recovery_checkpoints") if self._has("recovery_checkpoints") else []) + self.assertTrue(outcome.rerouted) + + +class WriterAndAdoptionTests(QuotaHandoffCase): + def test_clean_local_commit_adoption_is_consumed_for_both_stages(self): + for role in ("implement", "resolve"): + with self.subTest(role=role): + store = rc.Checkpoints(self.store.path) + baseline = store.capture(str(self.cwd), repo="owner/repo", task="503", + cycle=f"baseline-{role}", stage=role, kind="baseline", + change_request="384") + (self.cwd / "two.py").write_bytes(f"operator inspected {role}\n".encode()) + self.git("commit", "-qam", "local work") + workspace = ex._workspace_fingerprint(str(self.cwd)) + assert workspace is not None + store.adopt(str(self.cwd), baseline["id"], confirm_fingerprint=workspace["fingerprint"], + operator="operator-login", operator_source="code_host_login", + cycle=f"operator-{role}", stage=role) + primary, fallback = ScriptedAdapter("codex"), ScriptedAdapter("claude") + outcome = self.recorder([primary, fallback], started_from=role, + change_request_id="384").stage(role, "resume", cwd=str(self.cwd)) + self.assertTrue(outcome.succeeded, outcome.decision.explain()) + self.assertIn("operator_adopted", primary.dispatched[0]) + self.assertTrue(all(row["consumed_at"] for row in self.rows("recovery_adoptions"))) + + def test_implement_adoption_is_consumed_and_released_for_retention(self): + store = rc.Checkpoints(self.store.path) + baseline = store.capture(str(self.cwd), repo="owner/repo", task="503", cycle="cycle-0", + stage="implement", kind="baseline") + (self.cwd / "two.py").write_bytes(b"operator inspected this edit\n") + workspace = ex._workspace_fingerprint(str(self.cwd)) + assert workspace is not None + store.adopt(str(self.cwd), baseline["id"], confirm_fingerprint=workspace["fingerprint"], + operator="operator-login", operator_source="code_host_login", + cycle="operator-1", stage="implement") + primary, fallback = ScriptedAdapter("codex"), ScriptedAdapter("claude") + outcome = self.recorder([primary, fallback], started_from="implement").stage( + "implement", "resume", cwd=str(self.cwd)) + self.assertTrue(outcome.succeeded, outcome.decision.explain()) + self.assertIn("operator_adopted", primary.dispatched[0]) + self.assertEqual(1, len(self.events("adoption_consumed"))) + store.mark_cycle_terminal("cycle-0") + store.mark_cycle_terminal("operator-1") + self.assertIn(baseline["id"], {row["id"] for row in store.prunable()}) + + def test_failed_adoption_lookup_never_blocks_an_implement_resume(self): + primary, fallback = ScriptedAdapter("codex"), ScriptedAdapter("claude") + with patch.object(rc.Checkpoints, "match_adoption", + side_effect=sqlite3.OperationalError("database is locked")): + outcome = self.recorder([primary, fallback], started_from="implement").stage( + "implement", "resume", cwd=str(self.cwd)) + self.assertTrue(outcome.succeeded, outcome.decision.explain()) + self.assertEqual(1, len(primary.dispatched)) + failure = self.events("adoption_lookup_failed") + self.assertEqual(1, len(failure)) + self.assertIn("database is locked", failure[0]["detail"]) + + def test_lock_release_failure_is_journaled_not_raised(self): + primary, fallback = ScriptedAdapter("codex"), ScriptedAdapter("claude") + with patch.object(rc.WriterLock, "release", + side_effect=rc.ConcurrentWriter("guard busy")): + outcome = self.recorder([primary, fallback]).stage("implement", "work", cwd=str(self.cwd)) + self.assertTrue(outcome.succeeded, outcome.decision.explain()) + failure = self.events("lock_release_failed") + self.assertEqual(1, len(failure)) + self.assertIn("guard busy", failure[0]["detail"]) + + def test_resolve_cannot_consume_an_implement_adoption(self): + store = rc.Checkpoints(self.store.path) + baseline = store.capture(str(self.cwd), repo="owner/repo", task="503", cycle="cycle-0", + stage="implement", kind="baseline", change_request="384") + (self.cwd / "two.py").write_bytes(b"operator inspected this edit\n") + workspace = ex._workspace_fingerprint(str(self.cwd)) + assert workspace is not None + store.adopt(str(self.cwd), baseline["id"], confirm_fingerprint=workspace["fingerprint"], + operator="operator-login", operator_source="code_host_login", + cycle="operator-1", stage="implement") + primary, fallback = ScriptedAdapter("codex"), ScriptedAdapter("claude") + outcome = self.recorder([primary, fallback], change_request_id="384", + started_from="resolve").stage("resolve", "resume", cwd=str(self.cwd)) + self.assertTrue(outcome.decision.blocked) + self.assertEqual([], primary.dispatched) + self.assertIsNone(self.rows("recovery_adoptions")[0]["consumed_at"]) + + def test_concurrent_toolkit_writer_is_refused_before_dispatch(self): + holder = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) + self.addCleanup(holder.wait) + self.addCleanup(holder.kill) + lock = rc.WriterLock(str(self.cwd), {}) + with open(lock.path, "w", encoding="utf-8") as handle: + json.dump({"pid": holder.pid, "host": lock.owner["host"], "cycle": "other"}, handle) + primary = ScriptedAdapter("codex") + outcome = self.recorder([primary, ScriptedAdapter("claude")]).stage( + "implement", "work", cwd=str(self.cwd)) + self.assertTrue(outcome.decision.blocked) + self.assertIn("another toolkit writer", outcome.decision.explain()) + self.assertIn("cannot attribute edits", outcome.decision.explain()) + self.assertEqual([], primary.dispatched) + + def test_lock_is_released_after_the_stage(self): + outcome = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")]).stage( + "implement", "work", cwd=str(self.cwd)) + self.assertTrue(outcome.succeeded) + self.assertIsNone(rc.WriterLock(str(self.cwd), {}).holder()) + + def test_operator_adoption_resumes_ambiguous_edits_once(self): + store = rc.Checkpoints(self.store.path) + baseline = store.capture(str(self.cwd), repo="owner/repo", task="503", cycle="cycle-0", + stage="resolve", kind="baseline", change_request="384") + (self.cwd / "two.py").write_bytes(b"left by a killed stage\n") + workspace = ex._workspace_fingerprint(str(self.cwd)) + assert workspace is not None + refused = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")], + change_request_id="384", started_from="resolve").stage( + "resolve", "resume", cwd=str(self.cwd)) + self.assertTrue(refused.decision.blocked) + self.assertIn("no quota worktree provenance", refused.decision.explain()) + store.adopt(str(self.cwd), baseline["id"], confirm_fingerprint=workspace["fingerprint"], + operator="operator-login", operator_source="code_host_login", + cycle="operator-1", stage="resolve") + primary, fallback = ScriptedAdapter("codex"), ScriptedAdapter("claude") + resumed = self.recorder([primary, fallback], change_request_id="384", + started_from="resolve").stage("resolve", "resume", cwd=str(self.cwd)) + self.assertTrue(resumed.succeeded, resumed.decision.explain()) + task = (primary.dispatched or fallback.dispatched)[0] + self.assertIn("operator_adopted", task) + self.assertIn("not executor authorship", task) + self.assertEqual(1, len(self.events("adoption_consumed"))) + again = self.recorder([ScriptedAdapter("codex"), ScriptedAdapter("claude")], + change_request_id="384", started_from="resolve").stage( + "resolve", "resume", cwd=str(self.cwd)) + self.assertTrue(again.decision.blocked) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_quota_resume.py b/tests/test_quota_resume.py index f82f194..2104631 100644 --- a/tests/test_quota_resume.py +++ b/tests/test_quota_resume.py @@ -189,10 +189,10 @@ def snapshot(self, *args, **kwargs): "workspace": ex._workspace_fingerprint(str(self.cwd)), "remote": "same", "pulls": [], "observed_pulls": {}, "comments": []} - def recorder(self, adapters, **kw): + def recorder(self, adapters, availability=None, **kw): recorder = cy.CycleRecorder( self.store, "owner/repo", "330", router.TaskSignals(difficulty=3), - availability={a.name: ex.Availability.READY for a in adapters}, + availability={**{a.name: ex.Availability.READY for a in adapters}, **(availability or {})}, registry=ex.Registry(adapters), started_from="resolve", change_request_id="384", **kw) recorder.journal = Journal(self.store.path, "owner/repo", "330", recorder.cycle_id, change_request_id="384") @@ -214,11 +214,16 @@ def dispatch(self, target, task, **kw): error_code="quota", start_state="started", process_exited=True, detail=message) primary, fallback = Exhausted("codex"), ScriptedAdapter("claude") - outcome = self.recorder([primary, fallback]).stage("resolve", "work", cwd=str(self.cwd)) + # With its fallback available a quota stop hands the worktree over in + # the same stage (#525, tests/test_quota_handoff.py). Unavailable here, + # so the stage stops and the #389 resume path is what is exercised. + outcome = self.recorder([primary, fallback], + availability={"claude": ex.Availability.INSTALLED}).stage( + "resolve", "work", cwd=str(self.cwd)) self.assertFalse(outcome.succeeded) self.assertEqual([], fallback.dispatched) assert outcome.result is not None - self.assertIn("dirty_workspace", outcome.result.detail) + self.assertIn("fallback_unavailable", outcome.result.detail) return outcome def rows(self, table): diff --git a/tests/test_recovery_checkpoints.py b/tests/test_recovery_checkpoints.py new file mode 100644 index 0000000..d970999 --- /dev/null +++ b/tests/test_recovery_checkpoints.py @@ -0,0 +1,844 @@ +"""Durable recovery checkpoints (#503) against real temporary Git repositories.""" +from __future__ import annotations + +import importlib.util +import json +import os +import sqlite3 +import subprocess +import sys +import tempfile +import unittest +from contextlib import closing, redirect_stdout +from io import StringIO +from pathlib import Path +from unittest.mock import patch + +SCRIPTS = Path(__file__).resolve().parents[1] / "scripts" +sys.path.insert(0, str(SCRIPTS)) +import recovery_checkpoints as rc # noqa: E402 +import executors as ex # noqa: E402 + +SCOPE = dict(repo="owner/repo", task="503", cycle="cycle-1", stage="resolve") +TOKEN = "ghp_" + "a1B2c3D4e5F6g7H8i9J0" * 2 +LOCAL_ENV = b"LOCAL_SETTING=local-only-value-1\n" + + +class RepositoryCase(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.cwd = self.root / "checkout" + self.cwd.mkdir() + self.git("init", "-b", "task-503") + self.git("config", "user.email", "fixture@example.invalid") + self.git("config", "user.name", "Fixture") + self.git("config", "commit.gpgsign", "false") + (self.cwd / "one.txt").write_bytes(b"one\n") + (self.cwd / "two.txt").write_bytes(b"two\n") + (self.cwd / "gone.txt").write_bytes(b"gone\n") + (self.cwd / ".gitignore").write_text("build/\n") + self.git("add", ".") + self.git("commit", "-m", "fixture") + self.head = self.git("rev-parse", "HEAD") + self.store = rc.Checkpoints(self.root / "telemetry.sqlite") + + def git(self, *args, check=True): + return subprocess.run(["git", *args], cwd=self.cwd, capture_output=True, text=True, + check=check).stdout.strip() + + def capture(self, kind="quota_handoff", **kw): + return self.store.capture(str(self.cwd), kind=kind, **{**SCOPE, **kw}) + + def fingerprint(self): + workspace = rc.fingerprint(str(self.cwd)) + assert workspace is not None + return workspace["fingerprint"] + + def edit(self): + (self.cwd / "one.txt").write_bytes(b"staged\x00bytes\n") + self.git("add", "one.txt") + (self.cwd / "one.txt").write_bytes(b"unstaged after staged\xff\n") + (self.cwd / "two.txt").write_bytes(b"unstaged only\n") + os.chmod(self.cwd / "two.txt", 0o755) + self.git("rm", "-q", "--cached", "gone.txt") + (self.cwd / "new.bin").write_bytes(bytes(range(256))) + if hasattr(os, "symlink"): + try: + os.symlink("one.txt", self.cwd / "link") + except OSError: + pass + (self.cwd / "build").mkdir() + (self.cwd / "build" / "artifact.o").write_bytes(b"ignored") + + def reset(self): + self.git("reset", "-q", "--hard", self.head) + self.git("clean", "-q", "-fdx") + + def rows(self, table="recovery_checkpoints"): + with closing(sqlite3.connect(self.store.path)) as connection: + connection.row_factory = sqlite3.Row + return [dict(row) for row in connection.execute(f"SELECT * FROM {table} ORDER BY rowid")] + + +class CaptureAndRestoreTests(RepositoryCase): + def test_exact_staged_unstaged_untracked_modes_and_symlinks_restore(self): + self.edit() + before = self.fingerprint() + staged = self.git("diff", "--cached", "--raw", "--no-abbrev") + row = self.capture() + self.assertEqual("complete", row["status"], row) + self.assertEqual(before, row["fingerprint"]) + self.assertTrue(row["ref"].startswith("refs/code-cycle/recovery/")) + # The capture changed nothing it checkpointed. + self.assertEqual(before, self.fingerprint()) + self.assertEqual(self.head, self.git("rev-parse", "HEAD")) + self.reset() + self.assertNotEqual(before, self.fingerprint()) + restored = self.store.restore(str(self.cwd), row) + self.assertTrue(restored["matches"], restored) + self.assertEqual(before, self.fingerprint()) + self.assertEqual(staged, self.git("diff", "--cached", "--raw", "--no-abbrev")) + self.assertEqual(b"unstaged after staged\xff\n", (self.cwd / "one.txt").read_bytes()) + if os.name != "nt": + self.assertTrue(os.stat(self.cwd / "two.txt").st_mode & 0o100) + if (self.cwd / "link").is_symlink(): + self.assertEqual("one.txt", os.readlink(self.cwd / "link")) + # Ignored artifacts were never part of it. + self.assertFalse((self.cwd / "build").exists()) + + def test_restore_is_byte_exact_under_line_ending_conversion(self): + # Git for Windows ships core.autocrlf=true: a checkout would rewrite LF. + self.git("config", "core.autocrlf", "true") + self.reset() + self.edit() + (self.cwd / "crlf.txt").write_bytes(b"dos\r\nmixed\n") + before = self.fingerprint() + row = self.capture() + self.assertEqual("complete", row["status"], row) + self.reset() + restored = self.store.restore(str(self.cwd), row) + self.assertTrue(restored["matches"], restored) + self.assertEqual(before, self.fingerprint()) + self.assertEqual(b"unstaged after staged\xff\n", (self.cwd / "one.txt").read_bytes()) + self.assertEqual(b"unstaged only\n", (self.cwd / "two.txt").read_bytes()) + self.assertEqual(b"dos\r\nmixed\n", (self.cwd / "crlf.txt").read_bytes()) + self.assertEqual(bytes(range(256)), (self.cwd / "new.bin").read_bytes()) + + def test_fully_staged_state_restores_exact_bytes(self): + self.git("config", "core.autocrlf", "true") + (self.cwd / "one.txt").write_bytes(b"staged lf\nonly\n") + (self.cwd / "added.txt").write_bytes(b"new\r\nmixed\n") + self.git("add", "-A") + before = self.fingerprint() + staged = self.git("diff", "--cached", "--raw", "--no-abbrev") + row = self.capture() + self.assertEqual("complete", row["status"], row) + self.reset() + restored = self.store.restore(str(self.cwd), row) + self.assertTrue(restored["matches"], restored) + self.assertEqual(before, self.fingerprint()) + self.assertEqual(staged, self.git("diff", "--cached", "--raw", "--no-abbrev")) + self.assertEqual(b"staged lf\nonly\n", (self.cwd / "one.txt").read_bytes()) + self.assertEqual(b"new\r\nmixed\n", (self.cwd / "added.txt").read_bytes()) + + @unittest.skipIf(os.name == "nt", "the filter fixture needs a POSIX shell") + def test_a_filter_driver_keeps_its_cleaned_blob(self): + # What a clean filter keeps out of the object store stays out of it. + self.git("config", "filter.upper.clean", "tr a-z A-Z") + self.git("config", "filter.upper.smudge", "tr A-Z a-z") + (self.cwd / ".gitattributes").write_bytes(b"*.enc filter=upper\n") + (self.cwd / "data.enc").write_bytes(b"plain text\n") + (self.cwd / "kept.enc").write_bytes(b"staged text\n") + self.git("add", "kept.enc") + before = self.fingerprint() + row = self.capture() + self.assertEqual("complete", row["status"], row) + for name, stored in (("data.enc", "PLAIN TEXT"), ("kept.enc", "STAGED TEXT")): + self.assertEqual(stored, self.git("cat-file", "blob", f"{row['worktree_tree']}:{name}")) + self.reset() + restored = self.store.restore(str(self.cwd), row) + self.assertTrue(restored["matches"], restored) + self.assertEqual(before, self.fingerprint()) + self.assertEqual(b"plain text\n", (self.cwd / "data.enc").read_bytes()) + self.assertEqual(b"staged text\n", (self.cwd / "kept.enc").read_bytes()) + + @unittest.skipIf(os.name == "nt", "the filter fixture needs a POSIX shell") + def test_driver_names_matching_attribute_states_keep_the_cleaned_blobs(self): + names = ("set", "unset", "unspecified") + (self.cwd / ".gitattributes").write_bytes( + "".join(f"{name}.enc filter={name} -text\n" for name in names).encode()) + for name in names: + self.git("config", f"filter.{name}.clean", "tr a-z A-Z") + self.git("config", f"filter.{name}.smudge", "tr A-Z a-z") + (self.cwd / f"{name}.enc").write_bytes(b"example\n") + self.git("config", "core.autocrlf", "true") + (self.cwd / "plain.txt").write_bytes(b"plain\n") + self.git("add", "set.enc") + row = self.capture() + self.assertEqual("complete", row["status"], row) + for name in names: + with self.subTest(driver=name): + self.assertEqual("EXAMPLE", self.git( + "cat-file", "blob", f"{row['worktree_tree']}:{name}.enc")) + self.reset() + self.assertTrue(self.store.restore(str(self.cwd), row)["matches"]) + self.assertEqual(b"plain\n", (self.cwd / "plain.txt").read_bytes()) + + def test_only_the_scanned_bytes_reach_git_when_a_file_changes(self): + source = self.cwd / "changing.txt" + source.write_bytes(b"scanned contents\n") + scan = rc._scan_regular + + def scan_then_change(path): + data = scan(path) + # The capture resolves its root; a Windows temp path can be a short name. + if os.path.samefile(path, source): + source.write_bytes(TOKEN.encode()) + return data + + with patch.object(rc, "_scan_regular", side_effect=scan_then_change): + row = self.capture() + self.assertEqual("incomplete", row["status"], row) + self.assertIn({"reason": "changed_during_capture"}, row["unsupported"]) + self.assertEqual("scanned contents", self.git( + "cat-file", "blob", f"{row['worktree_tree']}:changing.txt")) + + @unittest.skipIf(os.name == "nt", "the filter fixture needs a POSIX shell") + def test_staged_only_raw_bytes_are_part_of_checkpoint_verification(self): + self.git("config", "filter.upper.clean", "tr a-z A-Z") + (self.cwd / ".git" / "info" / "attributes").write_bytes(b"one.txt filter=upper\n") + source = self.cwd / "one.txt" + source.write_bytes(b"staged\n") + self.git("add", "one.txt") + row = self.capture() + self.assertEqual("matches", self.store.verify(str(self.cwd), row)["state"]) + source.write_bytes(b"STAGED\n") + self.assertEqual("M one.txt", self.git("status", "--short")) + self.assertEqual("fingerprint_changed", self.store.verify(str(self.cwd), row)["state"]) + self.assertNotEqual(row["id"], self.capture()["id"]) + + def test_staged_deletions_stay_out_of_the_filtered_list(self): + # Only a regular file that kept its cleaned blob is named in the metadata. + self.git("rm", "-q", "gone.txt") + row = self.capture() + self.assertEqual("complete", row["status"], row) + metadata = rc._metadata(str(self.cwd), row["commit_sha"]) or {} + self.assertIs(True, metadata.get("unfiltered")) + self.assertEqual([], metadata.get("filtered")) + + def test_a_checkpoint_without_exact_blobs_keeps_gits_checkout(self): + # A checkpoint that does not declare unfiltered blobs is never rewritten. + self.git("config", "core.autocrlf", "true") + (self.cwd / "two.txt").write_bytes(b"unstaged only\n") + row = self.capture() + self.reset() + with patch.object(rc, "_metadata", return_value={ + key: row[column] for key, column in ( + ("id", "id"), ("repo", "repo_id"), ("task", "task_id"), ("stage", "stage"), + ("head", "head"), ("workspace", "workspace"), + ("index_tree", "index_tree"), ("worktree_tree", "worktree_tree"))}): + self.store.restore(str(self.cwd), row) + self.assertEqual(b"unstaged only\r\n", (self.cwd / "two.txt").read_bytes()) + + def test_restore_matches_when_git_cannot_check_out_symlinks(self): + # Git for Windows ships core.symlinks=false: a link is checked out as a file. + self.git("config", "core.symlinks", "false") + self.edit() + if not (self.cwd / "link").is_symlink(): + self.skipTest("this platform cannot create a symlink") + before = self.fingerprint() + row = self.capture() + self.assertEqual("complete", row["status"], row) + self.reset() + restored = self.store.restore(str(self.cwd), row) + self.assertTrue(restored["matches"], restored) + self.assertEqual(before, self.fingerprint()) + self.assertEqual("one.txt", os.readlink(self.cwd / "link")) + + def test_restore_keeps_a_symlink_already_emulated_as_a_plain_file(self): + link = self.cwd / "link" + self.git("config", "core.symlinks", "true") + try: + link.symlink_to("one.txt") + except OSError: + self.skipTest("this platform cannot create a symlink") + self.git("add", "link") + self.git("commit", "-m", "tracked symlink") + self.head = self.git("rev-parse", "HEAD") + self.git("config", "core.symlinks", "false") + link.unlink() + self.reset() + self.assertFalse(link.is_symlink()) + link.write_bytes(b"two.txt") + row = self.capture() + self.assertEqual("complete", row["status"], row) + self.assertIn("120000 blob ", self.git("ls-tree", row["worktree_tree"], "link")) + self.reset() + restored = self.store.restore(str(self.cwd), row) + self.assertTrue(restored["matches"], restored) + self.assertFalse(link.is_symlink()) + self.assertEqual(b"two.txt", link.read_bytes()) + + def test_file_and_directory_replacements_are_captured_as_deletions_and_additions(self): + nested = self.cwd / "nested" + nested.mkdir() + (nested / "child.txt").write_bytes(b"tracked child\n") + self.git("add", "nested") + self.git("commit", "-m", "tracked directory") + self.head = self.git("rev-parse", "HEAD") + (nested / "child.txt").unlink() + nested.rmdir() + nested.write_bytes(b"now a file\n") + original = self.cwd / "one.txt" + original.unlink() + original.mkdir() + (original / "child.txt").write_bytes(b"new child\n") + row = self.capture() + self.assertEqual("complete", row["status"], row) + self.reset() + self.assertTrue(self.store.restore(str(self.cwd), row)["matches"]) + self.assertEqual(b"now a file\n", nested.read_bytes()) + self.assertEqual(b"new child\n", (original / "child.txt").read_bytes()) + + def test_restore_never_overwrites_a_dirty_worktree(self): + self.edit() + row = self.capture() + (self.cwd / "two.txt").write_bytes(b"later edit\n") + before = self.fingerprint() + with self.assertRaisesRegex(rc.RecoveryError, "clean worktree"): + self.store.restore(str(self.cwd), row) + self.assertEqual(before, self.fingerprint()) + + def test_interruption_after_local_commit_and_repeated_resumes(self): + baseline = self.capture(kind="baseline") + (self.cwd / "one.txt").write_bytes(b"committed work\n") + self.git("commit", "-qam", "local work") + (self.cwd / "two.txt").write_bytes(b"after commit\n") + (self.cwd / "fresh.txt").write_bytes(b"untracked\n") + self.assertEqual("head_advanced", self.store.verify(str(self.cwd), baseline)["state"]) + first = self.capture() + second = self.capture() + third = self.capture() + self.assertEqual(first["id"], second["id"]) + self.assertEqual(first["id"], third["id"]) + self.assertEqual(baseline["id"], first["parent_id"]) + self.assertEqual("matches", self.store.verify(str(self.cwd), first)["state"]) + complete = [row for row in self.rows() if row["status"] == "complete"] + self.assertEqual(2, len(complete)) + self.assertEqual(2, sum(1 for row in self.rows() if row["status"] == "duplicate")) + + def test_clean_worktree_checkpoint_is_complete(self): + row = self.capture(kind="baseline") + self.assertEqual("complete", row["status"]) + self.assertEqual(self.git("rev-parse", "HEAD^{tree}"), row["worktree_tree"]) + + def test_ordinary_gc_keeps_checkpoint_objects(self): + self.edit() + row = self.capture() + self.reset() + self.git("reflog", "expire", "--expire=now", "--all") + self.git("gc", "-q", "--prune=now") + self.assertEqual([], self.store.verify(str(self.cwd), row)["problems"]) + self.assertTrue(self.store.restore(str(self.cwd), row)["matches"]) + + def test_checkpoint_ref_is_never_a_branch_or_tag(self): + self.edit() + row = self.capture() + self.assertNotIn(row["id"], self.git("branch", "--all")) + self.assertNotIn(row["id"], self.git("tag")) + self.assertIn(row["ref"], self.git("for-each-ref", "refs/code-cycle/")) + + +class IntegrityTests(RepositoryCase): + def setUp(self): + super().setUp() + self.edit() + self.row = self.capture() + + def test_missing_ref_and_corrupt_metadata_are_detected_without_discarding(self): + before = self.fingerprint() + self.git("update-ref", "-d", self.row["ref"]) + self.assertIn("missing_ref", self.store.verify(str(self.cwd), self.row)["problems"]) + self.git("update-ref", self.row["ref"], self.row["commit_sha"]) + corrupt = {**self.row, "index_tree": "0" * 40} + self.assertIn("corrupt_metadata", self.store.verify(str(self.cwd), corrupt)["problems"]) + wrong_fingerprint = {**self.row, "fingerprint": "0" * 64} + self.assertIn("corrupt_metadata", self.store.verify(str(self.cwd), wrong_fingerprint)["problems"]) + self.assertIn("corrupt_metadata", self.store.verify( + str(self.cwd), {**self.row, "schema_version": 99})["problems"]) + self.assertEqual(before, self.fingerprint()) + + def test_missing_objects_are_detected(self): + blob = self.git("rev-parse", f"{self.row['worktree_tree']}:new.bin") + loose = self.cwd / ".git" / "objects" / blob[:2] / blob[2:] + self.assertTrue(loose.exists()) + os.chmod(loose, 0o644) + loose.unlink() + self.assertIn("missing_objects", self.store.verify(str(self.cwd), self.row)["problems"]) + self.reset() + with self.assertRaisesRegex(rc.RecoveryError, "missing_objects"): + self.store.restore(str(self.cwd), self.row) + + def test_wrong_scope_changed_head_and_changed_fingerprint(self): + self.assertIn("wrong_scope", self.store.verify(str(self.cwd), self.row, repo="other/repo")["problems"]) + self.assertIn("wrong_scope", self.store.verify(str(self.cwd), self.row, task="999")["problems"]) + self.assertIn("wrong_scope", self.store.verify( + str(self.cwd), self.row, change_request="999")["problems"] if self.row["change_request_id"] + else ["wrong_scope"]) + (self.cwd / "two.txt").write_bytes(b"ambiguous later edit\n") + self.assertEqual("fingerprint_changed", self.store.verify(str(self.cwd), self.row)["state"]) + self.git("add", ".") + self.git("commit", "-qm", "changed head") + self.assertEqual("head_advanced", self.store.verify(str(self.cwd), self.row)["workspace_state"]) + self.git("checkout", "-q", "--orphan", "unrelated") + self.git("commit", "-q", "--allow-empty", "-m", "unrelated") + self.assertEqual("head_changed", self.store.verify(str(self.cwd), self.row)["state"]) + + +class CrashInjectionTests(RepositoryCase): + def test_legacy_pending_checkpoint_keeps_its_objects_without_claiming_a_match(self): + self.edit() + commit = rc._commit + + def legacy_commit(root, head, content, metadata): + return commit(root, head, content, + {key: value for key, value in metadata.items() if key != "fingerprint"}) + + with patch.object(rc, "_commit", side_effect=legacy_commit): + with patch.object(rc.Checkpoints, "_finish", side_effect=KeyboardInterrupt): + with self.assertRaises(KeyboardInterrupt): + self.capture() + + row, = self.store.reconcile_pending(str(self.cwd)) + verification = self.store.verify(str(self.cwd), row) + self.assertIn({"reason": "fingerprint_unrecorded"}, row["unsupported"]) + self.assertEqual([], verification["problems"]) + self.assertEqual("fingerprint_changed", verification["state"]) + self.reset() + self.store.restore(str(self.cwd), row) + self.assertEqual(b"unstaged after staged\xff\n", (self.cwd / "one.txt").read_bytes()) + + def test_crash_before_objects_after_objects_and_after_ref(self): + self.edit() + before = self.fingerprint() + # Before any object: an intent without content. + with patch("recovery_checkpoints._capture_content", side_effect=KeyboardInterrupt): + with self.assertRaises(KeyboardInterrupt): + self.capture() + # Objects written, the ref not yet created. + original = rc._git + + def no_ref(cwd, *args, **kw): + if args[:1] == ("update-ref",): + raise KeyboardInterrupt + return original(cwd, *args, **kw) + with patch("recovery_checkpoints._git", side_effect=no_ref): + with self.assertRaises(KeyboardInterrupt): + self.capture() + # The ref created, the row not yet completed. + finish = rc.Checkpoints._finish + + def no_complete(store, checkpoint_id, **fields): + if fields.get("status") == "complete": + raise KeyboardInterrupt + return finish(store, checkpoint_id, **fields) + with patch.object(rc.Checkpoints, "_finish", no_complete): + with self.assertRaises(KeyboardInterrupt): + self.capture() + self.assertEqual(["pending"] * 3, [row["status"] for row in self.rows()]) + settled = self.store.reconcile_pending(str(self.cwd)) + self.assertEqual(["failed", "failed", "complete"], [row["status"] for row in settled]) + self.assertEqual([], self.store.reconcile_pending(str(self.cwd))) + # Repeating the capture does not create a second logical checkpoint. + again = self.capture() + self.assertEqual(settled[2]["id"], again["id"]) + self.assertEqual(before, self.fingerprint()) + + def test_abrupt_termination_after_the_ref(self): + self.edit() + script = ( + "import os, sys\n" + f"sys.path.insert(0, {str(SCRIPTS)!r})\n" + "import recovery_checkpoints as rc\n" + "finish = rc.Checkpoints._finish\n" + "def die(store, checkpoint_id, **fields):\n" + " if fields.get('status') == 'complete':\n" + " os._exit(9)\n" + " return finish(store, checkpoint_id, **fields)\n" + "rc.Checkpoints._finish = die\n" + f"rc.Checkpoints({self.store.path!r}).capture({str(self.cwd)!r}, repo='owner/repo'," + " task='503', cycle='cycle-1', stage='resolve', kind='quota_handoff')\n") + done = subprocess.run([sys.executable, "-c", script], capture_output=True) + self.assertEqual(9, done.returncode, done.stderr) + self.assertEqual(["pending"], [row["status"] for row in self.rows()]) + settled = self.store.reconcile_pending(str(self.cwd)) + self.assertEqual("complete", settled[0]["status"]) + self.assertEqual(self.fingerprint(), settled[0]["fingerprint"]) + self.assertEqual("matches", self.store.verify(str(self.cwd), settled[0])["state"]) + self.reset() + self.assertEqual([], self.store.verify(str(self.cwd), settled[0])["problems"]) + self.assertEqual("fingerprint_changed", self.store.verify(str(self.cwd), settled[0])["state"]) + self.store.restore(str(self.cwd), settled[0]) + + +class SecretTests(RepositoryCase): + def object_exists(self, data: bytes) -> bool: + sha = subprocess.run(["git", "hash-object", "--stdin"], cwd=self.cwd, input=data, + capture_output=True, check=True).stdout.decode().strip() + return subprocess.run(["git", "cat-file", "-e", sha], cwd=self.cwd).returncode == 0 + + def test_secret_paths_and_content_are_never_captured(self): + (self.cwd / ".env.local").write_bytes(LOCAL_ENV) + (self.cwd / ".env.example").write_bytes(b"LOCAL_SETTING=\n") + (self.cwd / "deploy.pem").write_bytes(b"pem-bytes-2\n") + (self.cwd / "config.py").write_bytes(f"TOKEN = '{TOKEN}'\n".encode()) + (self.cwd / "build").mkdir() + (self.cwd / "build" / ".env").write_bytes(b"ignored-secret-3\n") + (self.cwd / "one.txt").write_bytes(b"ordinary edit\n") + row = self.capture() + self.assertEqual("incomplete", row["status"]) + reasons = {item["path"]: item["reason"] for item in row["exclusions"]} + self.assertEqual({".env.local": "secret_path", "deploy.pem": "secret_path", + "config.py": "secret_content"}, reasons) + tree = self.git("ls-tree", "-r", "--name-only", row["worktree_tree"]) + self.assertIn(".env.example", tree) + self.assertIn("one.txt", tree) + for name in (".env.local", "deploy.pem", "config.py", "build/.env"): + self.assertNotIn(name, tree) + for data in (LOCAL_ENV, b"pem-bytes-2\n", + f"TOKEN = '{TOKEN}'\n".encode(), b"ignored-secret-3\n"): + self.assertFalse(self.object_exists(data)) + # Excluded files stay exactly where they were. + self.assertEqual(LOCAL_ENV, (self.cwd / ".env.local").read_bytes()) + self.assertEqual(b"ignored-secret-3\n", (self.cwd / "build" / ".env").read_bytes()) + # Only paths and reason codes are recorded, never content. + self.assertNotIn("local-only-value", json.dumps(self.rows())) + self.assertNotIn(TOKEN, json.dumps(self.rows())) + + def test_staged_secret_is_put_back_to_head_in_the_checkpoint(self): + (self.cwd / "settings.txt").write_bytes(f"key {TOKEN}\n".encode()) + self.git("add", "settings.txt") + row = self.capture() + self.assertEqual([{"path": "settings.txt", "reason": "secret_content"}], row["exclusions"]) + self.assertNotIn("settings.txt", self.git("ls-tree", "-r", "--name-only", row["index_tree"])) + self.assertIn("settings.txt", self.git("diff", "--cached", "--name-only")) + + def test_custom_patterns_extend_and_never_remove_defaults(self): + if importlib.util.find_spec("yaml") is None: + self.skipTest("PyYAML is not installed") + (self.cwd / ".code-cycle.yml").write_text( + "code_cycle:\n recovery:\n secret_paths: ['*.vault', 'private/*']\n") + (self.cwd / "store.vault").write_bytes(b"vault\n") + (self.cwd / "private").mkdir() + (self.cwd / "private" / "notes.txt").write_bytes(b"notes\n") + (self.cwd / "id_rsa").write_bytes(b"key\n") + row = self.capture() + excluded = {item["path"] for item in row["exclusions"]} + self.assertEqual({"store.vault", "private/notes.txt", "id_rsa"}, excluded) + + def test_unreadable_or_invalid_rules_fail_closed(self): + (self.cwd / ".code-cycle.yml").write_text("code_cycle:\n recovery:\n secret_paths: 7\n") + with patch.dict(sys.modules, {"yaml": None}): + row = self.capture() + self.assertEqual("incomplete", row["status"]) + self.assertIn({"reason": "secret_rules_unreadable"}, row["unsupported"]) + if importlib.util.find_spec("yaml") is None: + return + (self.cwd / "one.txt").write_bytes(b"different content\n") + row = self.capture() + self.assertIn({"reason": "secret_rules_invalid"}, row["unsupported"]) + + def test_scanner_failure_excludes_the_file(self): + (self.cwd / "notes.txt").write_bytes(b"plain\n") + # A scanner that cannot finish fails the whole capture closed. + with patch("recovery_checkpoints._holds_credential", side_effect=OSError("scanner unavailable")): + failed = self.capture() + self.assertEqual(("failed", None), (failed["status"], failed["ref"])) + real_open = os.open + + def failing_open(path, *args, **kw): + if str(path).endswith("notes.txt"): + raise PermissionError("denied") + return real_open(path, *args, **kw) + with patch.object(rc.os, "open", side_effect=failing_open): + row = self.capture() + self.assertEqual("incomplete", row["status"]) + self.assertIn({"path": "notes.txt", "reason": "scan_failed"}, row["exclusions"]) + self.assertEqual(b"plain\n", (self.cwd / "notes.txt").read_bytes()) + + def test_secret_path_matching(self): + patterns = rc.DEFAULT_SECRET_PATHS + for path in (".env", "app/.env.production", "x/y.KEY", "home/.aws/credentials", + "id_ed25519.pub", "nested/credentials.json", ".npmrc"): + with self.subTest(path=path): + self.assertIsNotNone(rc.secret_path(path, patterns)) + for path in (".env.example", "app/.env.sample", "src/keys.py", "aws/credentials.md"): + with self.subTest(path=path): + self.assertIsNone(rc.secret_path(path, patterns)) + + +class SubmoduleTests(RepositoryCase): + def test_gitlink_is_captured_and_dirty_submodule_is_reported(self): + sub = self.cwd / "sub" + sub.mkdir() + for args in (("init", "-q"), ("config", "user.email", "s@example.invalid"), + ("config", "user.name", "S"), ("commit", "-q", "--allow-empty", "-m", "s")): + subprocess.run(["git", *args], cwd=sub, check=True, capture_output=True) + sub_head = subprocess.run(["git", "rev-parse", "HEAD"], cwd=sub, capture_output=True, + text=True, check=True).stdout.strip() + self.git("update-index", "--add", "--cacheinfo", f"160000,{sub_head},sub") + self.git("commit", "-qm", "gitlink") + (sub / "dirty.txt").write_bytes(b"dirty\n") + row = self.capture() + self.assertEqual("incomplete", row["status"]) + self.assertIn({"path": "sub", "reason": "dirty_submodule"}, row["unsupported"]) + self.assertIn(f"160000 commit {sub_head}\tsub", self.git("ls-tree", row["worktree_tree"])) + self.assertEqual(b"dirty\n", (sub / "dirty.txt").read_bytes()) + + +class AdoptionTests(RepositoryCase): + def adopt(self, row, fingerprint, stage="resolve"): + return self.store.adopt(str(self.cwd), row["id"], confirm_fingerprint=fingerprint, + operator="operator-login", operator_source="code_host_login", + cycle="operator-1", stage=stage) + + def test_adoption_is_explicit_bound_single_use_and_preserves_the_original(self): + row = self.capture(kind="baseline") + (self.cwd / "two.txt").write_bytes(b"edit after the checkpoint\n") + self.assertEqual("fingerprint_changed", self.store.verify(str(self.cwd), row)["state"]) + current = self.fingerprint() + with self.assertRaisesRegex(rc.RecoveryError, "no longer"): + self.adopt(row, "0" * 64) + adoption = self.adopt(row, current) + self.assertEqual("operator_adopted", adoption["provenance"]) + original = self.store.get(row["id"]) + assert original is not None + self.assertEqual(row["fingerprint"], original["fingerprint"]) + adopted = self.store.get(adoption["adopted_checkpoint_id"]) + assert adopted is not None + self.assertEqual(("operator_adopted", current), (adopted["kind"], adopted["fingerprint"])) + workspace = ex._workspace_fingerprint(str(self.cwd)) + match = self.store.match_adoption(repo="owner/repo", task="503", stage="resolve", change_request=None, + workspace=workspace) + assert match is not None + source = self.cwd / "two.txt" + source.write_bytes(b"edit after inspection\n") + with self.assertRaisesRegex(rc.RecoveryError, "changed after"): + self.store.consume_adoption(match, by="attempt-x") + source.write_bytes(b"edit after the checkpoint\n") + self.store.consume_adoption(match, by="attempt-1") + with self.assertRaisesRegex(rc.RecoveryError, "already used"): + self.store.consume_adoption(match, by="attempt-2") + self.assertIsNone(self.store.match_adoption(repo="owner/repo", task="503", + stage="resolve", change_request=None, workspace=workspace)) + with self.assertRaisesRegex(rc.RecoveryError, "already adopted"): + self.adopt(row, current) + self.assertIsNone(self.store.match_adoption(repo="other/repo", task="503", + stage="resolve", change_request=None, workspace=workspace)) + + def test_adoption_matches_only_the_named_stage(self): + row = self.capture(kind="baseline") + (self.cwd / "two.txt").write_bytes(b"inspected edit\n") + self.adopt(row, self.fingerprint(), stage="implement") + workspace = ex._workspace_fingerprint(str(self.cwd)) + self.assertIsNone(self.store.match_adoption( + repo="owner/repo", task="503", stage="resolve", change_request=None, workspace=workspace)) + self.assertIsNotNone(self.store.match_adoption( + repo="owner/repo", task="503", stage="implement", change_request=None, workspace=workspace)) + + def test_adoption_refuses_secret_content(self): + row = self.capture(kind="baseline") + (self.cwd / "leak.txt").write_bytes(f"{TOKEN}\n".encode()) + with self.assertRaisesRegex(rc.RecoveryError, "completely"): + self.adopt(row, self.fingerprint()) + self.assertEqual([], self.rows("recovery_adoptions")) + + def test_cli_adopt_inspect_discard_and_help(self): + row = self.capture(kind="baseline") + (self.cwd / "two.txt").write_bytes(b"operator inspected this\n") + base = ["--database", self.store.path] + output = StringIO() + with redirect_stdout(output): + self.assertEqual(0, rc.main(base + ["inspect", "--checkpoint", row["id"], "--cwd", str(self.cwd)])) + inspected = json.loads(output.getvalue()) + self.assertEqual("fingerprint_changed", inspected["verification"]["state"]) + current = inspected["verification"]["current_fingerprint"] + with redirect_stdout(StringIO()): + self.assertEqual(0, rc.main(base + ["adopt", "--checkpoint", row["id"], "--cwd", str(self.cwd), + "--confirm-fingerprint", current, "--stage", "resolve"], + identity=lambda: ("operator-login", "code_host_login"))) + adoption = self.rows("recovery_adoptions")[0] + self.assertEqual(("operator-login", "code_host_login"), + (adoption["operator"], adoption["operator_source"])) + with redirect_stdout(StringIO()): + self.assertEqual(0, rc.main(base + ["discard", "--checkpoint", row["id"]], + identity=lambda: ("operator-login", "code_host_login"))) + self.assertEqual("discarded", self.store.get(row["id"])["lifecycle"]) + for command in ("list", "inspect", "restore", "adopt", "discard", "prune", "unlock"): + done = subprocess.run([sys.executable, str(SCRIPTS / "recovery_checkpoints.py"), + "--database", self.store.path, + command, "--help"], capture_output=True, text=True) + self.assertEqual(0, done.returncode, done.stderr) + + +class RetentionTests(RepositoryCase): + def test_interrupted_checkpoint_requires_explicit_prune_after_consumption(self): + self.edit() + row = self.capture(kind="interrupted") + self.assertEqual([], self.store.prune(dry_run=True)) + self.store.consume(repo="owner/repo", task="503", workspace=row["workspace"]) + self.assertEqual([], self.store.prune(dry_run=True)) + self.store.mark_cycle_terminal(row["cycle_id"]) + self.assertEqual([row["id"]], [item["id"] for item in self.store.prune(dry_run=True)]) + self.assertIn(row["ref"], self.git("for-each-ref", "refs/code-cycle/")) + self.assertEqual("pruned", self.store.prune()[0]["action"]) + self.assertNotIn(row["ref"], self.git("for-each-ref", "refs/code-cycle/")) + + def test_prune_is_lifecycle_based_dry_run_and_idempotent(self): + self.edit() + active = self.capture(kind="baseline", cycle="cycle-active") + (self.cwd / "two.txt").write_bytes(b"next\n") + consumed = self.capture(cycle="cycle-done", attempt="attempt-2") + self.assertEqual([], self.store.prunable()) + self.store.consume(repo="owner/repo", task="503", workspace=active["workspace"]) + # Consumed, but its cycle is not terminal yet. + self.assertEqual([], self.store.prunable()) + self.store.mark_cycle_terminal("cycle-done") + self.assertEqual([consumed["id"]], [row["id"] for row in self.store.prunable()]) + dry = self.store.prune(dry_run=True) + self.assertEqual([{"id": consumed["id"], "ref": consumed["ref"], "action": "would_prune"}], dry) + self.assertIn(consumed["ref"], self.git("for-each-ref", "refs/code-cycle/")) + # An interrupted prune: the ref is gone, the row not yet marked. + self.git("update-ref", "-d", consumed["ref"]) + self.assertEqual("already_absent", self.store.prune()[0]["action"]) + self.assertEqual([], self.store.prune()) + row = self.store.get(consumed["id"]) + assert row is not None + self.assertIsNotNone(row["pruned_at"]) + self.assertEqual(consumed["fingerprint"], row["fingerprint"]) + self.assertIn(active["ref"], self.git("for-each-ref", "refs/code-cycle/")) + + def test_active_dependents_and_failed_checkpoints_are_kept(self): + parent = self.capture(kind="baseline", cycle="cycle-a") + self.store.discard(parent["id"], operator="operator-login") + (self.cwd / "one.txt").write_bytes(b"child\n") + child = self.capture(cycle="cycle-b") + self.assertEqual(parent["id"], child["parent_id"]) + self.assertEqual([], self.store.prunable()) + self.store.discard(child["id"], operator="operator-login") + self.assertEqual({parent["id"], child["id"]}, {row["id"] for row in self.store.prunable()}) + with patch("recovery_checkpoints._capture_content", side_effect=rc.RecoveryError("boom")): + failed = self.capture(cycle="cycle-c") + self.assertEqual("failed", failed["status"]) + self.assertNotIn(failed["id"], {row["id"] for row in self.store.prunable()}) + + def test_moved_ref_is_not_deleted(self): + row = self.capture(kind="baseline", cycle="cycle-x") + self.store.discard(row["id"], operator="operator-login") + self.git("update-ref", row["ref"], self.git("commit-tree", "-m", "other", "HEAD^{tree}")) + self.assertEqual("skipped_moved", self.store.prune()[0]["action"]) + self.assertIn(row["ref"], self.git("for-each-ref", "refs/code-cycle/")) + + +class WriterLockTests(RepositoryCase): + def test_same_process_cannot_replace_or_release_another_instances_lock(self): + first = rc.WriterLock(str(self.cwd), {"cycle": "first"}).acquire() + self.addCleanup(first.release) + other = rc.WriterLock(str(self.cwd), {"cycle": "other"}) + before = Path(first.path).read_bytes() + with self.assertRaises(rc.ConcurrentWriter): + other.acquire() + other.release() + self.assertEqual(before, Path(first.path).read_bytes()) + + def test_racing_stale_reclaim_does_not_evict_a_live_writer(self): + lock = rc.WriterLock(str(self.cwd), {}) + Path(lock.path).write_text(json.dumps({"pid": 0, "host": lock.owner["host"]})) + script = ( + "import sys\n" + f"sys.path.insert(0, {str(SCRIPTS)!r})\n" + "import recovery_checkpoints as rc\n" + "lock = rc.WriterLock(sys.argv[1], {})\n" + "if sys.argv[2] == 'pause':\n" + " holder = lock.holder\n" + " def paused():\n" + " value = holder()\n" + " print('stale-read', flush=True)\n" + " sys.stdin.readline()\n" + " return value\n" + " lock.holder = paused\n" + "try:\n" + " lock.acquire()\n" + "except rc.ConcurrentWriter:\n" + " print('rejected', flush=True)\n" + "else:\n" + " print('acquired', flush=True)\n" + " sys.stdin.readline()\n" + " lock.release()\n") + first = subprocess.Popen([sys.executable, "-c", script, str(self.cwd), "pause"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True) + def cleanup(): + if first.poll() is None: + first.kill() + first.communicate() + self.addCleanup(cleanup) + assert first.stdout is not None and first.stdin is not None + self.assertEqual("stale-read", first.stdout.readline().strip()) + # A second process races while the first has inspected the dead holder. + second = subprocess.run([sys.executable, "-c", script, str(self.cwd), "race"], + input="\n", capture_output=True, text=True, timeout=15) + self.assertEqual(0, second.returncode, second.stderr) + self.assertEqual("rejected", second.stdout.strip()) + first.stdin.write("\n") + first.stdin.flush() + self.assertEqual("acquired", first.stdout.readline().strip()) + first.kill() + first.communicate() + # Process death released its guard. Mark the record dead portably: an + # open Windows process handle keeps a killed PID looking alive. + Path(lock.path).write_text(json.dumps({"pid": 0, "host": lock.owner["host"]})) + recovered = lock.acquire() + self.addCleanup(recovered.release) + self.assertIsNotNone(recovered.reclaimed) + + def test_second_toolkit_writer_is_refused_and_stale_lock_reclaimed(self): + first = rc.WriterLock(str(self.cwd), {"cycle": "cycle-1", "attempt": "attempt-1"}).acquire() + self.addCleanup(first.release) + other = rc.WriterLock(str(self.cwd), {"cycle": "cycle-2"}) + with open(other.path, "w", encoding="utf-8") as handle: + json.dump({"pid": 999_999_999 if os.name != "nt" else 4, "host": other.owner["host"], + "cycle": "cycle-1"}, handle) + if os.name != "nt": + # A dead holder on this host is reclaimed and its record kept. + other.acquire() + assert other.reclaimed is not None + self.assertTrue(os.path.exists(other.reclaimed["evidence"])) + other.release() + live = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(30)"]) + self.addCleanup(live.wait) + self.addCleanup(live.kill) + with open(other.path, "w", encoding="utf-8") as handle: + json.dump({"pid": live.pid, "host": other.owner["host"], "cycle": "cycle-1"}, handle) + with self.assertRaisesRegex(rc.ConcurrentWriter, "another toolkit writer"): + rc.WriterLock(str(self.cwd), {"cycle": "cycle-3"}).acquire() + with open(other.path, "w", encoding="utf-8") as handle: + handle.write("not json") + with self.assertRaisesRegex(rc.ConcurrentWriter, "unreadable"): + rc.WriterLock(str(self.cwd), {"cycle": "cycle-3"}).acquire() + os.remove(other.path) + + def test_no_worktree_has_no_lock_and_no_checkpoint(self): + plain = self.root / "plain" + plain.mkdir() + self.assertIsNone(rc.worktree_root(str(plain))) + with self.assertRaises(rc.RecoveryError): + rc.WriterLock(str(plain), {}) + with self.assertRaises(rc.RecoveryError): + self.store.capture(str(plain), kind="baseline", **SCOPE) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_run_cycle.py b/tests/test_run_cycle.py index 3a3ddf2..5e020ad 100644 --- a/tests/test_run_cycle.py +++ b/tests/test_run_cycle.py @@ -3142,6 +3142,8 @@ def test_keys_consumed_by_skills_are_recognised(self) -> None: calibration: profiles: reviewer_a: {provider: anthropic, model: claude-sonnet-5, effort: high} + recovery: + secret_paths: ["*.vault"] """) config = rc.load_config(path)