From 20060e964194d8aa572c887ad1fc8512a36210b6 Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Wed, 2 Dec 2026 09:25:36 +0100 Subject: [PATCH 1/4] feat(resolve): prepare local resolution before publication --- docs/execution-plan.md | 4 +++ docs/review-cycle.md | 13 ++++++++ docs/role-workspace-policy.md | 6 ++++ docs/skills.md | 2 +- docs/workflows.md | 4 +-- scripts/cycle_cli.py | 4 +-- scripts/cycle_dispatch.py | 8 +++++ scripts/cycle_loop.py | 50 +++++++++++++++++++++++++++++ scripts/cycle_session.py | 30 +++++++++++++++-- scripts/cycle_status.py | 5 ++- scripts/execution_plan.py | 2 +- scripts/run_cycle.py | 24 +++++++++++--- scripts/telemetry.py | 2 +- skills/cc-resolve-comments/SKILL.md | 16 +++++++-- tests/test_execution_plan.py | 2 +- tests/test_run_cycle.py | 17 +++++++--- 16 files changed, 166 insertions(+), 23 deletions(-) diff --git a/docs/execution-plan.md b/docs/execution-plan.md index 15986660..6c5b267f 100644 --- a/docs/execution-plan.md +++ b/docs/execution-plan.md @@ -138,6 +138,10 @@ The verification contract contains: The configured test command is `configured-test` and required. Every check linked to a criterion is required. An agent can add checks and promote an obligation; it cannot remove or demote an existing one. +- A resolver may return `LOCAL_PREPARED` when explicitly run with + `--local-only`. This records a local candidate after required local checks; + it does not mark the change request remotely resolved or satisfy review, CI, + or merge controls. - `results`: append-only check ID, verified HEAD, `pass|fail|unverified`, evidence, cause and attempts. Unexecuted results carry an explicit cause; a null HEAD is permitted only for an unverified result whose target is unknown. diff --git a/docs/review-cycle.md b/docs/review-cycle.md index 66c45208..efeb0a7a 100644 --- a/docs/review-cycle.md +++ b/docs/review-cycle.md @@ -148,6 +148,19 @@ stage verifies both the remote branch ref and PR head before claiming success; the runtime blocks completion when the claimed SHA differs from the PR head. See [the publication path](role-workspace-policy.md#github-upload-from-a-writing-stage). +### Local resolution preparation + +For an existing change request, `--from resolve --pr --local-only` runs +resolution in an explicitly selected linked worktree without writing remote +comments or pushing. The resolver reports `LOCAL_PREPARED`, the full candidate SHA and tree, +and the frozen verification evidence. The runtime compares the SHA and tree to +the worktree and runs the required verification barrier before returning that +status. Inspect the candidate before publishing it. `LOCAL_PREPARED` records +local work only; it is not `RESOLVED` and does not satisfy review, provider CI, +or merge requirements. Resume with `--from resolve` without `--local-only`; +the runtime reuses the recorded candidate and instructs the stage to retry only +publication, not resolution. + ## CI policy A cycle runs under one of two CI policies, set by `ci.policy` in `.code-cycle.yml`, by `--ci-policy` for one `run_cycle.py` run, or by `ci_policy=` for one orchestrator invocation. The override wins. diff --git a/docs/role-workspace-policy.md b/docs/role-workspace-policy.md index 15c9073e..eb3127f8 100644 --- a/docs/role-workspace-policy.md +++ b/docs/role-workspace-policy.md @@ -116,6 +116,12 @@ same upload after a failure; it creates no new commit. On resume, reuse an existing success publication rather than duplicating it. Bitbucket and Orca transport recovery are not verified by this GitHub native path. +`--local-only` is also available for an explicit `resolve` resume. That path +uses the existing linked worktree, grants the resolve role no publication +permissions, and suppresses remote triage and progress comment writes. It records a +local `LOCAL_PREPARED` result after required checks and candidate SHA/tree +validation. It does not publish or imply remote completion. + ## Publication audit The cycle never merges, force-pushes or deletes refs. A stage's command table diff --git a/docs/skills.md b/docs/skills.md index ba1e1a37..021ba00c 100644 --- a/docs/skills.md +++ b/docs/skills.md @@ -124,7 +124,7 @@ Acts on review feedback. 2. fixes valid findings with the smallest change, reproduces each original problem, and verifies each fix; 3. then runs `cc-code-review` on the new diff, security triage again, and `cc-verify`; 4. commits, pushes, replies in threads, and publishes a summary. -- **Statuses:** `RESOLVED`, `PARTIALLY_RESOLVED`, `BLOCKED`, `FAILED`. +- **Statuses:** `LOCAL_PREPARED` (explicit local-only resolve preparation), `RESOLVED`, `PARTIALLY_RESOLVED`, `BLOCKED`, `FAILED`. - **CI failures:** under the `parallel` CI policy it may be told, by SHA and count, that required checks failed on the reviewed head; it diagnoses them beside the findings, never as findings. - **Parallel policy:** reviews its fix delta from the latest trusted review receipt (or the accumulated diff when that base is unusable), verifies locally, publishes, and reads checks once without waiting. `strict` keeps the accumulated review and CI wait. See [CI policy](review-cycle.md#ci-policy). - **Never:** declares approval, or changes code just to silence a review. diff --git a/docs/workflows.md b/docs/workflows.md index 055aaa44..9e166d86 100644 --- a/docs/workflows.md +++ b/docs/workflows.md @@ -282,7 +282,7 @@ From a toolkit checkout: `python3 scripts/run_cycle.py …` | `--ci-timeout` | `ci.timeout`, else `900` seconds | How long the `parallel` CI gate waits for one SHA | | `--cwd` | current directory | Where the executor runs and `.code-cycle.yml` is read | | `code_cycle.worktree_dir` | `.worktree` | Repository-relative base for persistent worker worktrees; review clones remain temporary and outside it | -| `--local-only` | off | Rehearsal: implement only, no publishing; requires `--workspace current` and a linked worktree in `--cwd` | +| `--local-only` | off | No publishing; use for an implementation rehearsal or `--from resolve --pr ` local preparation. Requires `--workspace current` and a linked worktree in `--cwd` | | `--timeout` | adapter default (21600 s / 6 h) | Maximum time for one dispatch. `--detach` only avoids the launching host's task limit; it does not change this per-dispatch timeout. | | `--detach` | off | Start the cycle in its own session and return at once, printing its process ID, a log path, and a `cycle_status.py --line --cursor-file ` command. Use it whenever an agent or another host that limits a task's time launches the cycle | | `--verbose` | off | Print stage starts, changed progress, and stage results as they happen; the final report is always printed | @@ -312,7 +312,7 @@ when the environment still cannot verify. Changed inputs use ordinary plan reconciliation. Hotfix additionally requires test-first reproduction and focused regression proof; see [Verification](verification.md). -**Local-only rehearsal:** `--cwd /path/to/linked-worktree --workspace current --local-only` refuses the live repository. The explicit `current` policy is required so workspace selection cannot create another task worktree. It runs implementation only, adds a no-publish boundary to the prompt, marks each row `local_only`, and ends with `HUMAN_INTERVENTION` because there is no PR to review. It is a policy, not a network sandbox. +**Local-only work:** `--cwd /path/to/linked-worktree --workspace current --local-only` refuses the live repository. The explicit `current` policy is required so workspace selection cannot create another task worktree. With the default start it runs an implementation rehearsal and ends with `HUMAN_INTERVENTION`. With `--from resolve --pr ` it applies resolution fixes and required local verification without writing remote triage or success comments or pushing, checks the reported candidate SHA/tree against the worktree, and ends `LOCAL_PREPARED`. Inspect this candidate before publishing it; `LOCAL_PREPARED` does not mean remotely resolved or merge-ready. This is a policy, not a network sandbox. Implementation workflows use a task-specific linked Git worktree by default. diff --git a/scripts/cycle_cli.py b/scripts/cycle_cli.py index 1a1e50c0..26d66f61 100644 --- a/scripts/cycle_cli.py +++ b/scripts/cycle_cli.py @@ -110,8 +110,8 @@ def main(api: Any, argv: list[str] | None = None) -> int: help="workspace policy: task worktree by default, or current checkout") parser.add_argument("--local-only", action="store_true", help=("run only in the explicit --cwd linked worktree " - "with --workspace current; " - "stop after implementation without publishing")) + "with --workspace current; either rehearse implementation " + "or prepare a resolution locally without publishing")) parser.add_argument("--timeout", type=int, default=None, help="seconds one dispatch may take") parser.add_argument("--detach", action="store_true", diff --git a/scripts/cycle_dispatch.py b/scripts/cycle_dispatch.py index 49f2512f..0e66f571 100644 --- a/scripts/cycle_dispatch.py +++ b/scripts/cycle_dispatch.py @@ -815,6 +815,14 @@ def advance(self: Any, role: str, instruction: str = "", *, if unpublished is None: synchronized = self.api.synchronize_worktree(change_request_id, self.cwd, target_head=target_head) else: + instruction += ( + " A durable local resolution candidate is already recorded for this " + "change request. Do not rerun resolution or recreate its commit. " + "Reconcile the current PR head and worktree, preserve the recorded " + "candidate, and retry only its normal fast-forward publication. If " + "the candidate, branch, tree, or PR ancestry differs, stop and name " + "the mismatch without force-pushing or publishing a recovery ref." + ) synchronized = self.api.synchronize_worktree( change_request_id, self.cwd, target_head=target_head, unpublished_heads=unpublished) except self.api.WorktreeSyncError as error: diff --git a/scripts/cycle_loop.py b/scripts/cycle_loop.py index 70de5bc1..a51d1608 100644 --- a/scripts/cycle_loop.py +++ b/scripts/cycle_loop.py @@ -107,6 +107,10 @@ def edit_comment(comment_id: str, body: str) -> None: "approved comment repair failed or could not be verified; use manual repair") return self.stop(reason, reported=reported, stop_reason="triage_repair_blocked") if self.start_from in self.api.RESUMES: + if self.start_from == "resolve" and self.state.change_request_id: + stopped = self.lock_change_request(self.state.change_request_id) + if stopped is not None: + return stopped stopped = self.seed_history() if stopped is not None: return stopped @@ -393,6 +397,52 @@ def reader() -> str | None: escalation_finding_ids=escalation_ids) if stopped is not None: return stopped + if self.local_only: + # Local resolution is a prepared candidate, not a remotely + # applied RESOLVED result or a merge-readiness decision. + barrier = self.verification_barrier() + if barrier is not None: + return barrier + head = (resolved.payload or {}).get("head_sha") + tree = (resolved.payload or {}).get("tree_sha") + local_head = self.api._git_line(self.cwd, ["rev-parse", "HEAD"], 30) + local_tree = self.api._git_line(self.cwd, ["rev-parse", "HEAD^{tree}"], 30) + branch = self.api._git_line(self.cwd, ["branch", "--show-current"], 30) + plan = self.plan_receipt or {} + plan_matches = all( + (resolved.payload or {}).get(key) == plan.get(key) + for key in ("plan_id", "revision", "digest") + ) + if (head != local_head or tree != local_tree + or not isinstance(head, str) or not self.api.FULL_SHA.fullmatch(head) + or not isinstance(tree, str) or not self.api.FULL_SHA.fullmatch(tree) + or not branch or not self.api._clean_worktree(self.cwd) + or not plan_matches): + return self.stop( + "local resolution candidate SHA/tree or execution-plan receipt do not " + "match the clean named worktree and frozen plan; " + "keep the work and inspect it before publication", "BLOCKED", + reported=resolved, stop_reason="candidate_mismatch") + try: + remote_head = self.api.probe_change_request( + self.repo_id, self.state.change_request_id, self.cwd).head_sha + unpublished = (self.state.history_store.unpublished_heads( + self.repo_id, self.state.change_request_id, self.cwd, branch, + remote_head or "") if self.state.history_store is not None else None) + except (self.api.CycleDriverError, self.api.sqlite3.Error, + self.api.HistoryError) as error: + return self.stop( + f"could not reconcile the local candidate with its change request: {error}; " + "the candidate is retained for inspection", "BLOCKED", + reported=resolved, stop_reason="publication_reconciliation") + if not remote_head or unpublished != (remote_head, head): + return self.stop( + "local candidate has no matching durable unpublished-head record; " + "keep the work and inspect its state before publication", "BLOCKED", + reported=resolved, stop_reason="candidate_state_missing") + return self.stop( + f"local resolution prepared at {head}; inspect the candidate before publication", + "LOCAL_PREPARED", reported=resolved, stop_reason="local_prepared") after_head = (resolved.payload or {}).get("head_sha") if review_head is not None and after_head is not None and after_head == review_head: return self.stop("resolution left the reviewed HEAD unchanged; open findings retain " diff --git a/scripts/cycle_session.py b/scripts/cycle_session.py index 659166b7..f8695957 100644 --- a/scripts/cycle_session.py +++ b/scripts/cycle_session.py @@ -196,7 +196,11 @@ def __init__(self, api: Any, options: dict[str, Any]): self.remote, self.tracking = self.api.GitHubHistoryRemote(self.cwd), True else: self.remote, self.tracking = self.api.ReaderRemote(self.api.read_change_request_comments, self.cwd), False - self.tracking = self.tracking and not self.local_only + # A local resolve still needs the per-PR writer lock and findings + # history, but does not publish: the dispatcher removes publication + # permissions for the local-only role. + self.tracking = self.tracking and ( + not self.local_only or self.start_from == "resolve") self.state.history_store = self.api.CycleHistoryStore(self.telemetry.path) self.state.history_lock = None self.state.pending_recovery = None @@ -224,9 +228,31 @@ def journal_result(self, role, outcome, reported, attempt_id) -> None: # owns this reference and accepts a new implementation's validated ID # only after its existing continuation and publication checks below. self.journal.change_request_id = self.state.change_request_id + correlation = {"head_sha": payload.get("head_sha")} + if role == "resolve" and reported.status == "LOCAL_PREPARED": + plan = self.plan_receipt or {} + verification = self.state.verification_plan + checks = ([check.to_dict() for check in verification.checks] + if verification is not None else []) + reported_tests = payload.get("tests") + results = (reported_tests.get("checks", []) + if isinstance(reported_tests, dict) else []) + correlation["local_candidate"] = { + "head_sha": payload.get("head_sha"), + "tree_sha": payload.get("tree_sha"), + "plan_id": plan.get("plan_id"), + "revision": plan.get("revision"), + "digest": plan.get("digest"), + "environment": { + "executor": outcome.result.executor if outcome.result else None, + "profile": outcome.decision.profile if outcome.decision else None, + }, + "checks": checks, + "results": results, + } self.journal.record("stage_result", role=role, stage_seq=self.recorder.stage_seq, attempt_id=attempt_id, component="runtime", status=reported.status, - detail=reported.reason, correlation={"head_sha": payload.get("head_sha")}) + detail=reported.reason, correlation=correlation) transport = (outcome.result.artifacts if outcome.result else {}).get("publication_transport", []) for event in transport if isinstance(transport, list) else []: if not isinstance(event, dict): diff --git a/scripts/cycle_status.py b/scripts/cycle_status.py index 2eec940f..3ced2eaa 100644 --- a/scripts/cycle_status.py +++ b/scripts/cycle_status.py @@ -101,7 +101,10 @@ def _usage_summary(result) -> str | None: "APPROVED", "COMPLETED", "IMPLEMENTED", "READY_FOR_MANUAL_MERGE", "RESOLVED", "SUCCEEDED", "SUCCESS", "CI_PASSED", } -_WARNING_RESULTS = {"CHANGES_REQUESTED", "NEEDS_REFINEMENT", "PARTIALLY_RESOLVED", "VERIFICATION_INCOMPLETE"} +_WARNING_RESULTS = { + "CHANGES_REQUESTED", "NEEDS_REFINEMENT", "PARTIALLY_RESOLVED", + "LOCAL_PREPARED", "VERIFICATION_INCOMPLETE", +} _BLOCKED_RESULTS = {"BLOCKED", "HUMAN_INTERVENTION", "INTERRUPTED", "STOPPED"} _FAILURE_RESULTS = {"CONTRACT_VIOLATION", "ERROR", "FAILED"} diff --git a/scripts/execution_plan.py b/scripts/execution_plan.py index e620d8d4..0487296d 100644 --- a/scripts/execution_plan.py +++ b/scripts/execution_plan.py @@ -159,7 +159,7 @@ class ControlDefinition: "resolve", "resolve", "Resolve valid review findings", "ORCHESTRATION_RESULT", WorkspacePolicy.WORKSPACE_WRITE, True, ("comment", "push_branch"), "cc-resolve-comments", - completes_with=frozenset({"RESOLVED", "PARTIALLY_RESOLVED"}), + completes_with=frozenset({"RESOLVED", "PARTIALLY_RESOLVED", "LOCAL_PREPARED"}), ), StageDefinition( "rereview", "rereview", "Verify fixes and review the current change", diff --git a/scripts/run_cycle.py b/scripts/run_cycle.py index 83361715..c25facab 100644 --- a/scripts/run_cycle.py +++ b/scripts/run_cycle.py @@ -230,8 +230,8 @@ # and the CLI invocation, so a later operator can tell a safe rehearsal from a # run that was allowed to publish changes. LOCAL_ONLY_REQUEST = ( - "Safety boundary: work only in the supplied cwd linked worktree. This local-only " - "cycle stops after implementation; keep all changes local, and do not push, " + "Safety boundary: work only in the supplied cwd linked worktree. Keep all " + "changes local, and do not push, " "merge, publish issue or review comments, or create a pull request." ) @@ -1293,6 +1293,19 @@ def compose(role: str, repo_id: str, task_id: str, instruction: str = "", parts.append(f"The supplied per-dispatch TMPDIR is `{temporary_directory}`.") if local_only: parts.append(LOCAL_ONLY_REQUEST) + if role == "resolve": + parts.append( + "Prepare the resolution locally for inspection. Report LOCAL_PREPARED, " + "not RESOLVED: the pull request has not received this candidate. " + "Commit the verified candidate on the existing working branch, " + "but do not upload it or publish comments. " + "Include the exact candidate SHA and tree, verification check identities " + "and results, safe environment metadata (executor, profile, platform, " + "and tool versions; never secret values), and the plan receipt's exact " + "plan_id, revision, and digest fields." + ) + elif role == "implement": + parts.append("This local-only rehearsal stops after implementation.") parts.append(STRUCTURED_REQUEST) prompt = " ".join(parts) if journal_context: @@ -1867,9 +1880,9 @@ def validate_start(start_from: str, change_request_id: str | None, if not safe_reference(change_request_id): raise CycleDriverError( "--pr must be a change-request reference: letters, digits and #._:/-") - if local_only: + if local_only and start_from != "resolve": raise CycleDriverError( - f"--local-only stops after implementation; it cannot resume from {start_from}") + f"--local-only can resume a local resolution, but not from {start_from}") #: What an implementation told to continue is told, in addition to its task. @@ -3098,7 +3111,8 @@ def execution_of(args, config: dict[str, Any]) -> ResolvedExecution: invocation = invocation_settings( execution_profile=getattr(args, "execution_profile", None), objective=getattr(args, "objective", None), - local_only=getattr(args, "local_only", False), + local_only=(getattr(args, "local_only", False) + and getattr(args, "start_from", "implement") == "implement"), stages=getattr(args, "stage", None) or (), issue_review=getattr(args, "issue_review", None), ) diff --git a/scripts/telemetry.py b/scripts/telemetry.py index bbab87a8..083a835f 100644 --- a/scripts/telemetry.py +++ b/scripts/telemetry.py @@ -277,7 +277,7 @@ def is_jev_model(value) -> bool: })), "status": ("token", frozenset({ "APPROVED", "CHANGES_REQUESTED", "BLOCKED", "FAILED", "RESOLVED", - "PARTIALLY_RESOLVED", "IMPLEMENTED", "READY_FOR_MANUAL_MERGE", + "PARTIALLY_RESOLVED", "LOCAL_PREPARED", "IMPLEMENTED", "READY_FOR_MANUAL_MERGE", "HUMAN_INTERVENTION", "VERIFICATION_INCOMPLETE", "IN_PROGRESS", "READY", "NEEDS_REFINEMENT", AWAITING_CI_STATUS, })), diff --git a/skills/cc-resolve-comments/SKILL.md b/skills/cc-resolve-comments/SKILL.md index 95e2d5f0..3edb00b5 100644 --- a/skills/cc-resolve-comments/SKILL.md +++ b/skills/cc-resolve-comments/SKILL.md @@ -280,7 +280,7 @@ When orchestrated: - if this skill is the complete dispatch task, send exactly one `worker_done` after constructing the final result, with both IDs and a short summary; - use worker outcome `failed` only for functional status `FAILED`; use - `succeeded` for `RESOLVED`, `PARTIALLY_RESOLVED`, and `BLOCKED`. + `succeeded` for `LOCAL_PREPARED`, `RESOLVED`, `PARTIALLY_RESOLVED`, and `BLOCKED`. Never put host-specific orchestration commands on the manual path, and do not dispatch a rereview. @@ -825,8 +825,15 @@ gh api graphql -F threadId= -f query='mutation($threadId: ID!) { reso The first reads the change request's threads, the second replies in one, and the third resolves one. On another code host, use its configured tooling. -Finish with a change-request summary that groups applied fixes, debated or rejected -comments, verification results, CI state when available and residual risks — +When the caller explicitly requests a local preparation with no publication, +finish after resolution and local verification without pushing, commenting, or +resolving remote threads. Report `LOCAL_PREPARED`, with the exact candidate SHA +and tree, frozen check identities and results, environment, and plan digest. +This status means the candidate is ready for inspection; it does not mean the +change request is resolved or merge-ready. + +Otherwise, finish with a change-request summary that groups applied fixes, +debated or rejected comments, verification results, CI state when available and residual risks — plus the `ORCHESTRATION_RESULT` block collapsed inside a `
` element, **only when that block is enabled** and it is not going to the response instead (see *Where the block goes*). Publish that summary on the change request while @@ -869,6 +876,9 @@ END_ORCHESTRATION_RESULT Use these functional statuses: +- `LOCAL_PREPARED`: local resolution and required local verification finished, + with no remote publication; the candidate needs inspection and a separate + publication step; - `RESOLVED`: every finding is resolved or justified as not applicable, all required verification passed, and required commit/push work completed; - `PARTIALLY_RESOLVED`: the skill completed useful resolution work but at least diff --git a/tests/test_execution_plan.py b/tests/test_execution_plan.py index a197f9c4..e7a2fa43 100644 --- a/tests/test_execution_plan.py +++ b/tests/test_execution_plan.py @@ -44,7 +44,7 @@ def test_catalog_snapshot_and_compatibility_adapters(self) -> None: { "issue_review": frozenset({"READY"}), "implement": frozenset({"IMPLEMENTED"}), - "resolve": frozenset({"RESOLVED", "PARTIALLY_RESOLVED"}), + "resolve": frozenset({"RESOLVED", "PARTIALLY_RESOLVED", "LOCAL_PREPARED"}), "review": frozenset({"APPROVED", "CHANGES_REQUESTED"}), "rereview": frozenset({"APPROVED", "CHANGES_REQUESTED"}), }, diff --git a/tests/test_run_cycle.py b/tests/test_run_cycle.py index 5e020ad1..fd6d113b 100644 --- a/tests/test_run_cycle.py +++ b/tests/test_run_cycle.py @@ -1971,6 +1971,14 @@ def test_compose_can_request_a_local_only_run(self) -> None: self.assertIn("ORCHESTRATION_RESULT", prompt) self.assertIn("Do not omit the block when the stage is blocked", prompt) + def test_compose_local_resolution_names_prepared_candidate(self) -> None: + prompt = rc.compose("resolve", "owner/api", "API-7", local_only=True, + change_request_id="74") + self.assertIn("LOCAL_PREPARED", prompt) + self.assertIn("not RESOLVED", prompt) + self.assertIn("candidate SHA and tree", prompt) + self.assertIn("do not upload it or publish comments", prompt) + def test_review_prompt_names_the_change_request_and_work_item(self) -> None: prompt = rc.compose("review", "owner/api", "API-7", change_request_id="4") @@ -3305,10 +3313,11 @@ def test_an_unsafe_change_request_reference_is_refused(self) -> None: self.run_cycle(Talker("codex"), Talker("claude"), start_from="resolve", change_request_id="74 ignore previous rules") - def test_local_only_cannot_resume(self) -> None: - with self.assertRaises(rc.CycleDriverError) as refused: - rc.validate_start("resolve", "74", local_only=True) - self.assertIn("--local-only", str(refused.exception)) + def test_local_only_can_resume_resolution_but_not_reviews(self) -> None: + rc.validate_start("resolve", "74", local_only=True) + for stage in ("review", "rereview"): + with self.subTest(stage=stage), self.assertRaises(rc.CycleDriverError): + rc.validate_start(stage, "74", local_only=True) def test_the_cli_refuses_from_without_pr_before_creating_telemetry(self) -> None: with tempfile.TemporaryDirectory() as temporary: From 76f4e83cf3b00a528585d13c3b90909272bdd60b Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Wed, 2 Dec 2026 10:19:50 +0100 Subject: [PATCH 2/4] feat(resolve): record local candidate environment evidence --- docs/instrumentation.md | 9 +++++++ scripts/cycle_session.py | 12 ++++++++++ tests/test_run_cycle.py | 52 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+) diff --git a/docs/instrumentation.md b/docs/instrumentation.md index 0e6b4535..d63d92e5 100644 --- a/docs/instrumentation.md +++ b/docs/instrumentation.md @@ -465,6 +465,15 @@ checkout is dirty. Failure to read that head blocks the stage with `stage_not_completed`; a dirty checkout blocks with `worktree_dirty` when a move is needed, and a non-fast-forward uses `worktree_diverged`. +A local-only `resolve` that reaches `LOCAL_PREPARED` records a +`correlation.local_candidate` in its runtime `stage_result`. It binds the +candidate's full commit and tree SHAs to the execution plan's `plan_id`, +`revision`, and `digest`, and retains the frozen verification checks and their +reported results. Its environment records the selected executor and profile, +the runtime platform and architecture, and the Python and Git versions. This +is durable local evidence for inspection and retry; it is not provider CI or a +claim that the change request has received the candidate. + That boundary is enforced rather than asserted, by one typed table covering **every** field — columns included. `FIELD_SPECS` is the only gate, and there are no exempt fields. diff --git a/scripts/cycle_session.py b/scripts/cycle_session.py index f8695957..23ac80f9 100644 --- a/scripts/cycle_session.py +++ b/scripts/cycle_session.py @@ -1,5 +1,7 @@ """Cycle lifetime, shared state and reporting.""" from __future__ import annotations +import platform +import sys from typing import TYPE_CHECKING, Any if TYPE_CHECKING: from .cycle_journal import events as journal_events @@ -246,6 +248,16 @@ def journal_result(self, role, outcome, reported, attempt_id) -> None: "environment": { "executor": outcome.result.executor if outcome.result else None, "profile": outcome.decision.profile if outcome.decision else None, + "platform": { + "system": sys.platform, + "release": platform.release(), + "machine": platform.machine(), + }, + "tool_versions": { + "python": sys.version.split()[0], + "git": self.api._git_line(self.cwd, ["--version"], 30) + if self.cwd else None, + }, }, "checks": checks, "results": results, diff --git a/tests/test_run_cycle.py b/tests/test_run_cycle.py index fd6d113b..eac84f5b 100644 --- a/tests/test_run_cycle.py +++ b/tests/test_run_cycle.py @@ -904,6 +904,58 @@ def test_an_unidentified_check_is_not_recorded_as_declined(self): "answer": "deny"}, "a" * 40) self.assertEqual(["verify:y"], list(session.state.declined_checks)) + def test_local_prepared_candidate_records_runtime_environment(self): + from cycle_session import CycleSession + + class Journal: + def __init__(self): + self.entries = [] + + def record(self, *args, **kwargs): + self.entries.append((args, kwargs)) + + session = object.__new__(CycleSession) + session.api = rc + session.cwd = str(ROOT) + session.repo_id = "owner/api" + session.plan_receipt = {"plan_id": "plan-1", "revision": 3, "digest": "d" * 64} + check = {"id": "configured-test", "command": "python3 -m unittest discover -s tests"} + session.state = type("State", (), { + "change_request_id": "74", + "verification_plan": type("Verification", (), {"checks": [ + type("Check", (), {"to_dict": lambda self: check})() + ]})(), + })() + session.recorder = type("Recorder", (), {"stage_seq": 2})() + session.journal = Journal() + session.note_declined_check = lambda *_args: None + reported = type("Reported", (), { + "status": "LOCAL_PREPARED", + "reason": "local candidate prepared", + "payload": { + "head_sha": "a" * 40, + "tree_sha": "b" * 40, + "tests": {"checks": [{"id": "configured-test", "result": "pass"}]}, + }, + "runtime": {}, + })() + outcome = type("Outcome", (), { + "result": type("Stage", (), {"executor": "codex", "artifacts": {}})(), + "decision": type("Decision", (), {"profile": "cheap_coder"})(), + })() + + session.journal_result("resolve", outcome, reported, "attempt-1") + + candidate = session.journal.entries[0][1]["correlation"]["local_candidate"] + environment = candidate["environment"] + self.assertEqual("codex", environment["executor"]) + self.assertEqual("cheap_coder", environment["profile"]) + self.assertEqual(sys.platform, environment["platform"]["system"]) + self.assertEqual(sys.version.split()[0], environment["tool_versions"]["python"]) + self.assertIn("git version", environment["tool_versions"]["git"]) + self.assertEqual([check], candidate["checks"]) + self.assertEqual([{"id": "configured-test", "result": "pass"}], candidate["results"]) + def test_null_tests_payload_preserves_previous_outcome(self): payload = {"status": "IMPLEMENTED", "tests": None} verification = self.plan().verification From 6eb2cbe3b562884025450d9afa119e058365bfbf Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Wed, 2 Dec 2026 11:16:16 +0100 Subject: [PATCH 3/4] fix(resolve): validate local prepared results --- docs/workflows.md | 2 +- scripts/cycle_dispatch.py | 9 +++++- scripts/cycle_loop.py | 13 ++++++++ tests/test_run_cycle.py | 67 +++++++++++++++++++++++++++++++++++++-- 4 files changed, 86 insertions(+), 5 deletions(-) diff --git a/docs/workflows.md b/docs/workflows.md index 9e166d86..92296613 100644 --- a/docs/workflows.md +++ b/docs/workflows.md @@ -355,7 +355,7 @@ python3 ~/.code-cycle/runtime/run_cycle.py --task 72 --pr 74 --from review # python3 ~/.code-cycle/runtime/run_cycle.py --task 72 --pr 74 --from rereview # rereview first, then loop ``` -The stages before `--from` are skipped. The rest run with the same routing, recording, and `--max-iterations` as a full cycle. `resolve` and `rereview` rely on the pull request's comments carrying the previous review; the stage recovers those findings through `review.trusted_authors`. Before anything is dispatched, the driver refuses `--from` without `--pr`, `--pr` without a resuming `--from`, and `--local-only` with a resume. It then reads the pull request with `gh` and stops with the reason unless it is open, its head branch still exists, and `--cwd` has that branch checked out at the pull request's head commit, so a stale or unpushed checkout is never reviewed or fixed in its place. Only GitHub pull requests can be resumed. A resumed run is a **new cycle** with its own `cycle_id`, and every row carries `started_from`, so its review never counts as a first pass. +The stages before `--from` are skipped. The rest run with the same routing, recording, and `--max-iterations` as a full cycle. `resolve` and `rereview` rely on the pull request's comments carrying the previous review; the stage recovers those findings through `review.trusted_authors`. Before anything is dispatched, the driver refuses `--from` without `--pr` and `--pr` without a resuming `--from`. `--local-only` may resume only `resolve`; it requires `--workspace current` and a linked worktree, and it prepares a local candidate without publishing. For normal resumes, the driver reads the pull request with `gh` and stops with the reason unless it is open, its head branch still exists, and `--cwd` has that branch checked out at the pull request's head commit, so a stale or unpushed checkout is never reviewed or fixed in its place. Only GitHub pull requests can be resumed. A resumed run is a **new cycle** with its own `cycle_id`, and every row carries `started_from`, so its review never counts as a first pass. **Issue review:** in the default `auto` mode, a new cycle first runs `cc-issue-review` read-only and implements only on a confirmed `READY`. `NEEDS_REFINEMENT` stops before any code work and prints one `decisions` line, the first question, and the path of a decisions record holding the other questions and the findings, evidence, and proposed issue edits; nothing is posted to the work item. `--issue-review off` or `issue_review.mode: off` restores the original flow. See [Review lifecycle → Issue review](review-cycle.md#issue-review-before-implementation). diff --git a/scripts/cycle_dispatch.py b/scripts/cycle_dispatch.py index 0e66f571..da2198cc 100644 --- a/scripts/cycle_dispatch.py +++ b/scripts/cycle_dispatch.py @@ -272,7 +272,7 @@ def run(self: Any, role: str, instruction: str = "", *, self.report.stages.append(outcome) attempt_id = (outcome.result.artifacts.get("dispatch_attempt_id") if outcome.result is not None else None) - if publishes: + if publishes and not self.local_only: self.expect_publication(role, change_request_id, attempt_id) if (role == "resolve" and change_request_id and isinstance(attempt_id, str) and resolve_start_head and self.state.history_store is not None): @@ -869,6 +869,13 @@ def advance(self: Any, role: str, instruction: str = "", *, return reported, stopped # Only a stage the audit let through can have been reconciled (#364). self.record_reconciliation(role, reported, outcome) + if (role == "resolve" and reported.status == "LOCAL_PREPARED" + and not self.local_only): + return reported, self.stop( + "LOCAL_PREPARED is valid only for an explicitly local-only resolve; " + "the candidate was not accepted as a completed resolution", + "BLOCKED", reported=reported, + stop_reason="stage_not_completed") if role == "resolve" and outcome.decision is not None: self.state.previous_resolve_target = outcome.decision.target self.state.previous_resolve_used_fallback = outcome.decision.used_fallback diff --git a/scripts/cycle_loop.py b/scripts/cycle_loop.py index a51d1608..b9ad481a 100644 --- a/scripts/cycle_loop.py +++ b/scripts/cycle_loop.py @@ -398,6 +398,19 @@ def reader() -> str | None: if stopped is not None: return stopped if self.local_only: + if resolved.status != "LOCAL_PREPARED": + return self.stop( + "local-only resolution must report LOCAL_PREPARED; " + "the reported result is not a prepared candidate", + "BLOCKED", reported=resolved, + stop_reason="stage_not_completed") + unresolved = (resolved.payload or {}).get("unresolved_findings") + if not isinstance(unresolved, list) or unresolved: + return self.stop( + "local-only resolution must report an empty unresolved_findings list " + "before the candidate can be prepared", + "BLOCKED", reported=resolved, + stop_reason="stage_not_completed") # Local resolution is a prepared candidate, not a remotely # applied RESOLVED result or a merge-readiness decision. barrier = self.verification_barrier() diff --git a/tests/test_run_cycle.py b/tests/test_run_cycle.py index eac84f5b..052eb331 100644 --- a/tests/test_run_cycle.py +++ b/tests/test_run_cycle.py @@ -950,6 +950,10 @@ def record(self, *args, **kwargs): environment = candidate["environment"] self.assertEqual("codex", environment["executor"]) self.assertEqual("cheap_coder", environment["profile"]) + self.assertEqual("a" * 40, candidate["head_sha"]) + self.assertEqual("b" * 40, candidate["tree_sha"]) + self.assertEqual({"plan_id": "plan-1", "revision": 3, "digest": "d" * 64}, { + key: candidate[key] for key in ("plan_id", "revision", "digest")}) self.assertEqual(sys.platform, environment["platform"]["system"]) self.assertEqual(sys.version.split()[0], environment["tool_versions"]["python"]) self.assertIn("git version", environment["tool_versions"]["git"]) @@ -1241,6 +1245,54 @@ def dispatch(inner, target, task, **kw): class PublicationCompletionTests(RunCycleTestCase): + def test_local_prepared_is_rejected_outside_local_only_resolution(self) -> None: + resolver = Talker("codex", block("LOCAL_PREPARED", head_sha="a" * 40, + tree_sha="b" * 40)) + reviewer = Talker("claude", APPROVED) + + report = self.run_cycle(resolver, reviewer, start_from="resolve", + change_request_id="7") + + self.assertEqual("BLOCKED", report.status, report.explain()) + self.assertEqual("stage_not_completed", report.stop_reason) + self.assertEqual(["resolve"], [stage.role for stage in report.stages]) + self.assertEqual([], reviewer.dispatched) + + def test_local_only_resolve_keeps_outbox_empty_when_status_is_not_prepared(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + fixture = WorktreeSynchronizationTests() + checkout = fixture.linked_worktree(Path(temporary)) + resolver = Talker("codex", block("PARTIALLY_RESOLVED", head_sha="a" * 40)) + reviewer = Talker("claude", APPROVED) + + report = self.run_cycle(resolver, reviewer, start_from="resolve", + change_request_id="7", cwd=str(checkout), + local_only=True) + + self.assertEqual("BLOCKED", report.status, report.explain()) + self.assertEqual("stage_not_completed", report.stop_reason) + self.assertEqual([], reviewer.dispatched) + history = rc.CycleHistoryStore(self.store.path) + self.assertEqual([], history.pending_publications("owner/api", "7", "resolve")) + + def test_local_prepared_with_open_findings_is_not_accepted(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + fixture = WorktreeSynchronizationTests() + checkout = fixture.linked_worktree(Path(temporary)) + resolver = Talker("codex", block( + "LOCAL_PREPARED", head_sha="a" * 40, + unresolved_findings=[{"id": "REV-001", "severity": "medium", + "status": "open", "blocks_approval": True}])) + reviewer = Talker("claude", APPROVED) + + report = self.run_cycle(resolver, reviewer, start_from="resolve", + change_request_id="7", cwd=str(checkout), + local_only=True) + + self.assertEqual("BLOCKED", report.status, report.explain()) + self.assertIn("empty unresolved_findings list", report.stopped_because) + self.assertEqual([], reviewer.dispatched) + def test_completion_normalizes_supported_change_request_references(self): class PublishingTalker(Talker): requires_publication_preflight = True @@ -1270,7 +1322,7 @@ def probe(repo, request, cwd): def test_exited_resolver_commit_is_attributed_for_resume(self): with tempfile.TemporaryDirectory() as temporary: fixture = WorktreeSynchronizationTests() - _, _, checkout = fixture.checkout_pair(Path(temporary)) + checkout = fixture.linked_worktree(Path(temporary)) old = fixture.git(checkout, "rev-parse", "HEAD") class CommittingTalker(Talker): @@ -1282,12 +1334,13 @@ def dispatch(self, target, task, **kw): report = self.run_cycle(CommittingTalker("codex", block("BLOCKED", reason="push failed")), Talker("claude", APPROVED), cwd=str(checkout), - start_from="resolve", change_request_id="7") + start_from="resolve", change_request_id="7", local_only=True) new = fixture.git(checkout, "rev-parse", "HEAD") self.assertNotEqual(old, new, report.explain()) history = rc.CycleHistoryStore(self.store.path) self.assertEqual((old, new), history.unpublished_heads( - "owner/api", "7", str(checkout), "main", old)) + "owner/api", "7", str(checkout), "local-resolve", old)) + self.assertEqual([], history.pending_publications("owner/api", "7", "resolve")) def test_claimed_unpushed_commit_blocks_before_review_or_success_verdict(self): class PublishingTalker(Talker): @@ -3937,6 +3990,14 @@ def checkout_pair(self, root: Path) -> tuple[Path, Path, Path]: self.git(checkout, "config", "user.email", "cycle-test@example.invalid") return bare, seed, checkout + def linked_worktree(self, root: Path) -> Path: + _, _, checkout = self.checkout_pair(root) + linked = root / "linked" + self.git(checkout, "worktree", "add", "-b", "local-resolve", str(linked), "main") + self.git(linked, "config", "user.name", "Cycle Test") + self.git(linked, "config", "user.email", "cycle-test@example.invalid") + return linked + def test_fast_forwards_clean_worktree_and_reports_full_shas(self) -> None: with tempfile.TemporaryDirectory() as temporary: _, seed, checkout = self.checkout_pair(Path(temporary)) From 0f8ad3dc8dc4c410aad37cda8b84dc2bfe8831b0 Mon Sep 17 00:00:00 2001 From: datacas <4690232+datacas@users.noreply.github.com> Date: Wed, 2 Dec 2026 12:43:46 +0100 Subject: [PATCH 4/4] Fix local resolution candidate validation --- docs/execution-plan.md | 7 +- docs/instrumentation.md | 11 +- docs/review-cycle.md | 19 ++-- scripts/cycle_loop.py | 16 ++- scripts/cycle_session.py | 3 + scripts/telemetry.py | 3 + tests/test_run_cycle.py | 233 ++++++++++++++++++++++++++++++++++++++- tests/test_telemetry.py | 16 +++ 8 files changed, 288 insertions(+), 20 deletions(-) diff --git a/docs/execution-plan.md b/docs/execution-plan.md index 6c5b267f..dc724fa1 100644 --- a/docs/execution-plan.md +++ b/docs/execution-plan.md @@ -140,8 +140,11 @@ The verification contract contains: obligation; it cannot remove or demote an existing one. - A resolver may return `LOCAL_PREPARED` when explicitly run with `--local-only`. This records a local candidate after required local checks; - it does not mark the change request remotely resolved or satisfy review, CI, - or merge controls. + its full SHA and tree must match the clean worktree, and its `plan_id`, + `revision`, and `digest` must match the frozen receipt given to the resolver. + A missing or mismatched receipt blocks with the candidate retained. This does + not mark the change request remotely resolved or satisfy review, CI, or merge + controls. - `results`: append-only check ID, verified HEAD, `pass|fail|unverified`, evidence, cause and attempts. Unexecuted results carry an explicit cause; a null HEAD is permitted only for an unverified result whose target is unknown. diff --git a/docs/instrumentation.md b/docs/instrumentation.md index d63d92e5..98a76f99 100644 --- a/docs/instrumentation.md +++ b/docs/instrumentation.md @@ -721,9 +721,14 @@ failed during a publishing stage, whoever caused it), `publication_unverified` (schema 24: the audited refs or change-request state could not be read; see *Publication audit* in `role-workspace-policy.md`), `verification_unverified` (schema 25: required check evidence, criteria coverage, or security audit -completion is unverified; generic CI success cannot clear it), `worktree_dirty`, or -`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 +completion is unverified; generic CI success cannot clear it), `local_prepared` +(a local-only resolve prepared a verified candidate), `candidate_mismatch` (the +reported candidate SHA, tree, plan, or checkout did not match local state), +`candidate_state_missing` (the candidate has no durable unpublished record), +`publication_reconciliation` (the remote publication state could not be safely +reconciled), `worktree_dirty`, or `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`, or, for a quota stop of a writing stage (#503), `checkpoint_handoff` (handed to the fallback from a diff --git a/docs/review-cycle.md b/docs/review-cycle.md index efeb0a7a..cfeeff13 100644 --- a/docs/review-cycle.md +++ b/docs/review-cycle.md @@ -152,14 +152,17 @@ See [the publication path](role-workspace-policy.md#github-upload-from-a-writing For an existing change request, `--from resolve --pr --local-only` runs resolution in an explicitly selected linked worktree without writing remote -comments or pushing. The resolver reports `LOCAL_PREPARED`, the full candidate SHA and tree, -and the frozen verification evidence. The runtime compares the SHA and tree to -the worktree and runs the required verification barrier before returning that -status. Inspect the candidate before publishing it. `LOCAL_PREPARED` records -local work only; it is not `RESOLVED` and does not satisfy review, provider CI, -or merge requirements. Resume with `--from resolve` without `--local-only`; -the runtime reuses the recorded candidate and instructs the stage to retry only -publication, not resolution. +comments or pushing. The resolver reports `LOCAL_PREPARED`, the full candidate +SHA and tree, the frozen plan receipt, and verification evidence. The runtime +checks the SHA and tree against the clean named worktree, requires the +`plan_id`, `revision`, and `digest` to match the receipt given to the resolver, +and runs the required verification barrier before returning that status. A +missing or mismatched plan receipt blocks while retaining the candidate for +inspection. Inspect the candidate before publishing it. `LOCAL_PREPARED` +records local work only; it is not `RESOLVED` and does not satisfy review, +provider CI, or merge requirements. Resume with `--from resolve` without +`--local-only`; the runtime reuses the recorded candidate and instructs the +stage to retry only publication, not resolution. ## CI policy diff --git a/scripts/cycle_loop.py b/scripts/cycle_loop.py index b9ad481a..951692dd 100644 --- a/scripts/cycle_loop.py +++ b/scripts/cycle_loop.py @@ -421,10 +421,18 @@ def reader() -> str | None: local_head = self.api._git_line(self.cwd, ["rev-parse", "HEAD"], 30) local_tree = self.api._git_line(self.cwd, ["rev-parse", "HEAD^{tree}"], 30) branch = self.api._git_line(self.cwd, ["branch", "--show-current"], 30) - plan = self.plan_receipt or {} - plan_matches = all( - (resolved.payload or {}).get(key) == plan.get(key) - for key in ("plan_id", "revision", "digest") + plan = getattr(self, "local_candidate_plan_receipt", None) + digest = plan.get("digest") if isinstance(plan, dict) else None + plan_matches = ( + isinstance(plan, dict) + and isinstance(plan.get("plan_id"), str) + and bool(plan["plan_id"]) + and type(plan.get("revision")) is int + and plan["revision"] > 0 + and isinstance(digest, str) + and self.api.re.fullmatch(r"[a-f0-9]{64}", digest) is not None + and all((resolved.payload or {}).get(key) == plan[key] + for key in ("plan_id", "revision", "digest")) ) if (head != local_head or tree != local_tree or not isinstance(head, str) or not self.api.FULL_SHA.fullmatch(head) diff --git a/scripts/cycle_session.py b/scripts/cycle_session.py index 23ac80f9..1d5f7f39 100644 --- a/scripts/cycle_session.py +++ b/scripts/cycle_session.py @@ -233,6 +233,9 @@ def journal_result(self, role, outcome, reported, attempt_id) -> None: correlation = {"head_sha": payload.get("head_sha")} if role == "resolve" and reported.status == "LOCAL_PREPARED": plan = self.plan_receipt or {} + self.local_candidate_plan_receipt = { + key: plan.get(key) for key in ("plan_id", "revision", "digest") + } verification = self.state.verification_plan checks = ([check.to_dict() for check in verification.checks] if verification is not None else []) diff --git a/scripts/telemetry.py b/scripts/telemetry.py index 083a835f..c91faddd 100644 --- a/scripts/telemetry.py +++ b/scripts/telemetry.py @@ -172,6 +172,9 @@ def is_jev_model(value) -> bool: "publication_violation", "publication_unverified", "suspected_external_change", "review_target_changed", "verification_unverified", + # Local-only resolution candidate validation. + "local_prepared", "candidate_mismatch", "candidate_state_missing", + "publication_reconciliation", }) #: Who ran the review a cycle closed on (schema 22); `review_contract` defines them. diff --git a/tests/test_run_cycle.py b/tests/test_run_cycle.py index 052eb331..a40216f2 100644 --- a/tests/test_run_cycle.py +++ b/tests/test_run_cycle.py @@ -1293,6 +1293,208 @@ def test_local_prepared_with_open_findings_is_not_accepted(self) -> None: self.assertIn("empty unresolved_findings list", report.stopped_because) self.assertEqual([], reviewer.dispatched) + + def _seed_local_prepared_plan(self, head: str) -> None: + import cycle_history as ch + import execution_profiles as ep + import verification_plan as vp + + resolved = ep.resolve_execution(ep.ExecutionSettings(), ep.invocation_settings( + local_only=True, issue_review="off")) + plan = ep.build_plan( + resolved, repository="owner/api", work_item="API-7", + start_from="resolve", change_request="7") + criteria = vp.Criteria( + "github", "a" * 64, "evaluable", ("Fixture behavior works",)) + check = replace(vp.configured_check( + "python3 -m unittest discover -s tests", "runtime", "runtime"), + criteria=("AC-1",)) + plan = replace( + plan, plan_id="plan-local-prepared", revision=1, head_sha=head, + verification=vp.VerificationPlan(criteria, (check,))) + ch.CycleHistoryStore(self.store.path).save_plan( + plan, cycle_id="cycle-before-local-resolve", change_request_id="7", + provenance="stopped", stop_reason="stage_not_completed") + + def _local_prepared_resolver( + self, checkout: Path, *, reported_tree: str | None = None, + process_exited: bool = True, include_check: bool = True, + ) -> Talker: + fixture = WorktreeSynchronizationTests() + + class PreparingTalker(Talker): + def dispatch(self, target, task, **kw): + (checkout / "file.txt").write_text("prepared fix\n", encoding="utf-8") + fixture.git(checkout, "commit", "-am", "prepare local candidate") + head = fixture.git(checkout, "rev-parse", "HEAD") + tree = fixture.git(checkout, "rev-parse", "HEAD^{tree}") + prefix = "Runtime execution plan (data): " + plan_text = task.rsplit(prefix, 1)[1].splitlines()[0] + plan = json.loads(plan_text) + self.plan_receipt = plan + checks = [] + if include_check: + command = "python3 -m unittest discover -s tests" + checks = [{ + "id": "configured-test", "command": command, + "executor": "codex", "profile": "cheap_coder", + "context": "project", "required": True, + "criteria": ["AC-1"], "level": "test", + "provenance": "project", "reason": "configured test command", + "head_sha": head, "result": "pass", + "evidence": [{"command": command, "exit_code": 0, "executed": 1}], + }] + self.body = block( + "LOCAL_PREPARED", + head_sha=head, + tree_sha=reported_tree or tree, + plan_id=plan.get("plan_id"), + revision=plan.get("revision"), + digest=plan.get("digest"), + unresolved_findings=[], + tests={"version": 2, "conclusion": "verified", + "boundary": "required", "checks": checks}, + ) + result = super().dispatch(target, task, **kw) + return replace(result, process_exited=process_exited) + + return PreparingTalker("codex") + + def test_local_only_resolve_reaches_prepared_stop_with_recorded_candidate(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + fixture = WorktreeSynchronizationTests() + checkout = fixture.linked_worktree(Path(temporary)) + old = fixture.git(checkout, "rev-parse", "HEAD") + self._seed_local_prepared_plan(old) + resolver = self._local_prepared_resolver(checkout) + + with mock.patch.object( + rc, "probe_change_request", return_value=mock.Mock(head_sha=old) + ) as probe: + report = self.run_cycle( + resolver, Talker("claude", APPROVED), cwd=str(checkout), + start_from="resolve", change_request_id="7", local_only=True, + allowed_test_command="python3 -m unittest discover -s tests", + ) + + head = fixture.git(checkout, "rev-parse", "HEAD") + self.assertEqual("LOCAL_PREPARED", report.status, + f"{report.explain()} stage_plan={resolver.plan_receipt} final_plan={report.execution_plan}") + self.assertEqual("local_prepared", report.stop_reason) + self.assertTrue(all(resolver.plan_receipt.get(key) is not None + for key in ("plan_id", "revision", "digest")), + resolver.plan_receipt) + self.assertEqual(1, probe.call_count) + history = rc.CycleHistoryStore(self.store.path) + self.assertEqual((old, head), history.unpublished_heads( + "owner/api", "7", str(checkout), "local-resolve", old)) + self.assertEqual([], history.pending_publications("owner/api", "7", "resolve")) + + + def test_local_prepared_candidate_without_frozen_plan_is_retained_and_blocked(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + fixture = WorktreeSynchronizationTests() + checkout = fixture.linked_worktree(Path(temporary)) + old = fixture.git(checkout, "rev-parse", "HEAD") + resolver = self._local_prepared_resolver(checkout, include_check=False) + + with mock.patch.object( + rc, "probe_change_request", return_value=mock.Mock(head_sha=old) + ): + report = self.run_cycle( + resolver, Talker("claude", APPROVED), cwd=str(checkout), + start_from="resolve", change_request_id="7", local_only=True, + ) + + head = fixture.git(checkout, "rev-parse", "HEAD") + self.assertEqual("BLOCKED", report.status, report.explain()) + self.assertEqual("candidate_mismatch", report.stop_reason) + self.assertNotEqual(old, head) + history = rc.CycleHistoryStore(self.store.path) + self.assertEqual((old, head), history.unpublished_heads( + "owner/api", "7", str(checkout), "local-resolve", old)) + self.assertEqual([], history.pending_publications("owner/api", "7", "resolve")) + + def test_local_prepared_candidate_with_mismatching_tree_is_retained_and_blocked(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + fixture = WorktreeSynchronizationTests() + checkout = fixture.linked_worktree(Path(temporary)) + old = fixture.git(checkout, "rev-parse", "HEAD") + self._seed_local_prepared_plan(old) + resolver = self._local_prepared_resolver(checkout, reported_tree="f" * 40) + + with mock.patch.object( + rc, "probe_change_request", return_value=mock.Mock(head_sha=old) + ): + report = self.run_cycle( + resolver, Talker("claude", APPROVED), cwd=str(checkout), + start_from="resolve", change_request_id="7", local_only=True, + allowed_test_command="python3 -m unittest discover -s tests", + ) + + head = fixture.git(checkout, "rev-parse", "HEAD") + self.assertEqual("BLOCKED", report.status, report.explain()) + self.assertEqual("candidate_mismatch", report.stop_reason) + self.assertNotEqual(old, head) + history = rc.CycleHistoryStore(self.store.path) + self.assertEqual((old, head), history.unpublished_heads( + "owner/api", "7", str(checkout), "local-resolve", old)) + self.assertEqual([], history.pending_publications("owner/api", "7", "resolve")) + + def test_local_prepared_candidate_without_unpublished_record_is_retained_and_blocked(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + fixture = WorktreeSynchronizationTests() + checkout = fixture.linked_worktree(Path(temporary)) + old = fixture.git(checkout, "rev-parse", "HEAD") + self._seed_local_prepared_plan(old) + resolver = self._local_prepared_resolver(checkout, process_exited=False) + + with mock.patch.object( + rc, "probe_change_request", return_value=mock.Mock(head_sha=old) + ): + report = self.run_cycle( + resolver, Talker("claude", APPROVED), cwd=str(checkout), + start_from="resolve", change_request_id="7", local_only=True, + allowed_test_command="python3 -m unittest discover -s tests", + ) + + head = fixture.git(checkout, "rev-parse", "HEAD") + self.assertEqual("BLOCKED", report.status, report.explain()) + self.assertEqual("candidate_state_missing", report.stop_reason) + self.assertNotEqual(old, head) + history = rc.CycleHistoryStore(self.store.path) + self.assertIsNone(history.unpublished_heads( + "owner/api", "7", str(checkout), "local-resolve", old)) + self.assertEqual([], history.pending_publications("owner/api", "7", "resolve")) + + + def test_local_prepared_candidate_reconciliation_failure_is_retained_and_blocked(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + fixture = WorktreeSynchronizationTests() + checkout = fixture.linked_worktree(Path(temporary)) + old = fixture.git(checkout, "rev-parse", "HEAD") + self._seed_local_prepared_plan(old) + resolver = self._local_prepared_resolver(checkout) + + with mock.patch.object( + rc, "probe_change_request", + side_effect=rc.CycleDriverError("change-request read failed"), + ): + report = self.run_cycle( + resolver, Talker("claude", APPROVED), cwd=str(checkout), + start_from="resolve", change_request_id="7", local_only=True, + allowed_test_command="python3 -m unittest discover -s tests", + ) + + head = fixture.git(checkout, "rev-parse", "HEAD") + self.assertEqual("BLOCKED", report.status, report.explain()) + self.assertEqual("publication_reconciliation", report.stop_reason) + self.assertNotEqual(old, head) + history = rc.CycleHistoryStore(self.store.path) + self.assertEqual((old, head), history.unpublished_heads( + "owner/api", "7", str(checkout), "local-resolve", old)) + self.assertEqual([], history.pending_publications("owner/api", "7", "resolve")) + def test_completion_normalizes_supported_change_request_references(self): class PublishingTalker(Talker): requires_publication_preflight = True @@ -1320,6 +1522,30 @@ def probe(repo, request, cwd): self.assertEqual("7", observed.call_args_list[0].args[1]) def test_exited_resolver_commit_is_attributed_for_resume(self): + with tempfile.TemporaryDirectory() as temporary: + fixture = WorktreeSynchronizationTests() + _, _, checkout = fixture.checkout_pair(Path(temporary)) + old = fixture.git(checkout, "rev-parse", "HEAD") + + class CommittingTalker(Talker): + def dispatch(self, target, task, **kw): + (checkout / "file.txt").write_text("unpublished fix\n", encoding="utf-8") + fixture.git(checkout, "commit", "-am", "fix") + result = super().dispatch(target, task, **kw) + return replace(result, process_exited=True) + + report = self.run_cycle( + CommittingTalker("codex", block("BLOCKED", reason="push failed")), + Talker("claude", APPROVED), cwd=str(checkout), + start_from="resolve", change_request_id="7") + new = fixture.git(checkout, "rev-parse", "HEAD") + self.assertNotEqual(old, new, report.explain()) + history = rc.CycleHistoryStore(self.store.path) + self.assertEqual((old, new), history.unpublished_heads( + "owner/api", "7", str(checkout), "main", old)) + + + def test_exited_local_only_resolver_commit_is_attributed_for_resume(self): with tempfile.TemporaryDirectory() as temporary: fixture = WorktreeSynchronizationTests() checkout = fixture.linked_worktree(Path(temporary)) @@ -1332,9 +1558,10 @@ def dispatch(self, target, task, **kw): result = super().dispatch(target, task, **kw) return replace(result, process_exited=True) - report = self.run_cycle(CommittingTalker("codex", block("BLOCKED", reason="push failed")), - Talker("claude", APPROVED), cwd=str(checkout), - start_from="resolve", change_request_id="7", local_only=True) + report = self.run_cycle( + CommittingTalker("codex", block("BLOCKED", reason="push failed")), + Talker("claude", APPROVED), cwd=str(checkout), + start_from="resolve", change_request_id="7", local_only=True) new = fixture.git(checkout, "rev-parse", "HEAD") self.assertNotEqual(old, new, report.explain()) history = rc.CycleHistoryStore(self.store.path) diff --git a/tests/test_telemetry.py b/tests/test_telemetry.py index f6c4a249..ba392d70 100644 --- a/tests/test_telemetry.py +++ b/tests/test_telemetry.py @@ -97,6 +97,22 @@ def test_a_token_field_is_a_closed_vocabulary_not_short_text(self) -> None: self.store.record_stage("repo", "t1", "implement", security_gate_half="deterministic") self.assertEqual("deterministic", self.store.rows()[0]["payload"]["security_gate_half"]) + + def test_local_resolution_stop_reasons_are_recordable(self) -> None: + reasons = ( + "local_prepared", + "candidate_mismatch", + "candidate_state_missing", + "publication_reconciliation", + ) + for index, reason in enumerate(reasons): + self.store.record_stage( + "repo", f"local-resolution-{index}", "resolve", stop_reason=reason + ) + + rows = self.store.rows("repo") + self.assertEqual(reasons, tuple(row["payload"]["stop_reason"] for row in rows)) + def test_each_kind_accepts_only_its_own_shape(self) -> None: bad = {"findings_high": 1.5, "cost_usd": "0.10", "security_audit_ran": 1, "iterations": True}