From 717403809eddedb679d9fc0063f2d514ab7cc5d3 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:39:34 +0100 Subject: [PATCH 1/6] Preserve passing receipts across late check checkpoints Architecture-Review: document which completed receipts a checkpoint may replace. Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 5 +++-- src/loopzero/cli.py | 9 +++++++-- tests/test_cli.py | 20 ++++++++++++++++++++ 3 files changed, 30 insertions(+), 4 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index bfe286f2..9e50b205 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -481,8 +481,9 @@ stage is retried after success or uncertain launch. Only the coordinator writes the authoritative `checks.json` receipt. Writers lock the task state directory while rechecking HEAD and atomically replacing the receipt from a synced sibling temporary file. Successful keyed stages are checkpointed in the same receipt -for reuse. The checkpoint cannot satisfy readiness before final worktree -validation. Runners cannot select stages or mint receipts. Stage admission +for reuse. A checkpoint cannot replace a clean pass for the same head and +settings or satisfy readiness before final worktree validation. Completed +failures still replace passes. Runners cannot select stages or mint receipts. Stage admission belongs to the runner: the outer `loopzero check` must not hold a heavy slot when a runner is configured. Without a runner, the existing local execution path is unchanged. diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 46a93e29..1cf1b68b 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -359,7 +359,7 @@ def _lock_task_state(wt: Path) -> Iterator[None]: os.close(fd) -def _save_report(wt: Path, report: CheckReport) -> str | None: +def _save_report(wt: Path, report: CheckReport, *, checkpoint_checks: tuple[str, ...] | None = None) -> str | None: """Publish the receipt or return the current HEAD if the result is stale.""" path = wt / CHECKS_FILE payload = { @@ -375,6 +375,11 @@ def _save_report(wt: Path, report: CheckReport) -> str | None: current_head = worktree.head(wt) if report.head != current_head: return current_head + saved = _load_report(wt) if checkpoint_checks is not None else None + if (saved is not None and saved.ok and not saved.dirty and saved.head == report.head + and saved.settings_sha256 == report.settings_sha256 + and tuple(result.command for result in saved.results) == checkpoint_checks): + return None _write_json_atomically(path, payload) return None @@ -598,7 +603,7 @@ def cmd_check(args: argparse.Namespace) -> int: report = sandbox.run_checks(config, wt, progress=lambda command: print( f"running: {command}", flush=True), status=lambda message: print(message, flush=True), - checkpoint=lambda partial: _save_report(wt, partial)) + checkpoint=lambda partial: _save_report(wt, partial, checkpoint_checks=config.checks)) except sandbox.SandboxUnavailable as exc: print(f"sandbox unavailable: {exc}", file=sys.stderr) return 2 diff --git a/tests/test_cli.py b/tests/test_cli.py index 3421662b..037c073b 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -10,6 +10,7 @@ import subprocess import sys from dataclasses import replace +from functools import partial from pathlib import Path from types import SimpleNamespace from unittest.mock import Mock @@ -4763,3 +4764,22 @@ def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys): assert "unverified" not in draft assert f"Recorded for `{head[:12]}`\n- `echo ok`: exit 0" in draft assert "Manual validation evidence." in draft + + +def test_late_checkpoint_preserves_completed_pass(wt, head): + cfg = config.load(wt / "workflow.toml") + passed = CheckReport(head, False, tuple(CheckResult(c, 0, 0, "", input_key="key") for c in cfg.checks), + cli.sandbox.settings_fingerprint(cfg, wt)) + save = partial(cli._save_report, wt) + checkpoint = cli.sandbox._checkpoint_success + checkpoint(partial(save, checkpoint_checks=cfg.checks), passed, {}, ()) + assert cli._load_report(wt).results[0].input_key == "key" + save(passed) + checkpoint(partial(save, checkpoint_checks=cfg.checks), passed, {}, ()) + assert cli._current_check_report(wt, cfg, head) == passed + failed = replace(passed, results=(replace(passed.results[0], exit_code=1),)) + save(failed) + assert cli._load_report(wt) == failed + save(passed) + checkpoint(partial(save, checkpoint_checks=cfg.checks[:1]), replace(passed, results=passed.results[:1]), {}, ()) + assert not cli._load_report(wt).ok From e03566dc3eab05604d30b90b45bae976f6d9303a Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 03:49:24 +0100 Subject: [PATCH 2/6] Persist observed check failures before final validation Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 7 ++++--- src/loopzero/cli.py | 3 ++- src/loopzero/sandbox.py | 20 +++++++++++++------- tests/test_cli.py | 35 ++++++++++++++++++++++++++++++++++- 4 files changed, 53 insertions(+), 12 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 9e50b205..128e3f52 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -481,9 +481,10 @@ stage is retried after success or uncertain launch. Only the coordinator writes the authoritative `checks.json` receipt. Writers lock the task state directory while rechecking HEAD and atomically replacing the receipt from a synced sibling temporary file. Successful keyed stages are checkpointed in the same receipt -for reuse. A checkpoint cannot replace a clean pass for the same head and -settings or satisfy readiness before final worktree validation. Completed -failures still replace passes. Runners cannot select stages or mint receipts. Stage admission +for reuse. A successful stage checkpoint preserves a clean pass for the same +head, settings, and commands. A failed stage replaces a prior pass immediately. +Final worktree validation is required before publishing a pass. Runners cannot +select stages or mint receipts. Stage admission belongs to the runner: the outer `loopzero check` must not hold a heavy slot when a runner is configured. Without a runner, the existing local execution path is unchanged. diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 1cf1b68b..5c0624eb 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -375,7 +375,8 @@ def _save_report(wt: Path, report: CheckReport, *, checkpoint_checks: tuple[str, current_head = worktree.head(wt) if report.head != current_head: return current_head - saved = _load_report(wt) if checkpoint_checks is not None else None + unfinished = checkpoint_checks is not None and report.results[-1] is sandbox.INCOMPLETE_CHECK + saved = _load_report(wt) if unfinished else None if (saved is not None and saved.ok and not saved.dirty and saved.head == report.head and saved.settings_sha256 == report.settings_sha256 and tuple(result.command for result in saved.results) == checkpoint_checks): diff --git a/src/loopzero/sandbox.py b/src/loopzero/sandbox.py index a358d56f..7db4d228 100644 --- a/src/loopzero/sandbox.py +++ b/src/loopzero/sandbox.py @@ -193,7 +193,7 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO result = replace(result, input_key=key) if index >= len(preparations) or result.exit_code: results.append(result) - _checkpoint_success( + _checkpoint_stage( checkpoint, CheckReport(head, dirty, tuple(results), settings_sha256), previous, commands[index + 1:], ) @@ -218,15 +218,21 @@ def run_checks(config: Config, worktree: Path, *, timeout: float = DEFAULT_TIMEO return CheckReport(head=head, dirty=dirty, results=tuple(results), settings_sha256=settings_sha256) -def _checkpoint_success(checkpoint: Callable[[CheckReport], None] | None, - report: CheckReport, previous: dict[str, CheckResult], - remaining: tuple[str, ...]) -> None: +INCOMPLETE_CHECK = CheckResult("", 1, 0.0, "") + + +def _checkpoint_stage(checkpoint: Callable[[CheckReport], None] | None, + report: CheckReport, previous: dict[str, CheckResult], + remaining: tuple[str, ...]) -> None: + if checkpoint is None: + return stage = report.results[-1] - if checkpoint is not None and stage.input_key and stage.exit_code == 0: + if stage.exit_code: + checkpoint(report) + elif stage.input_key: # Even the last stage leaves a nonpassing receipt until final validation. - incomplete = CheckResult("", 1, 0.0, "") unvisited = tuple(previous[command] for command in remaining if command in previous) - checkpoint(replace(report, results=(*report.results, *unvisited, incomplete))) + checkpoint(replace(report, results=(*report.results, *unvisited, INCOMPLETE_CHECK))) def _previous(config: Config, worktree: Path, settings_sha256: str) -> dict[str, CheckResult]: diff --git a/tests/test_cli.py b/tests/test_cli.py index 037c073b..de496d04 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -4766,12 +4766,45 @@ def test_pr_marks_legacy_same_head_check_unverified(wt, gh, capsys): assert "Manual validation evidence." in draft +def test_ready_rejects_check_interrupted_after_a_failed_stage(wt, head, gh, capsys, monkeypatch): + settings = wt / ".loopzero" / "workflow.toml" + settings.write_text(WORKFLOW.replace("test -f README.md", "test ! -e .loopzero/fail")) + args = ["--config", str(settings)] + assert cli.main([*args, "check"]) == 0 + (wt / ".loopzero" / "fail").touch() + run_one, git_check = cli.sandbox._run_one, cli.sandbox._git + failed = False + + def observe_stage(*stage_args): + nonlocal failed + result = run_one(*stage_args) + failed = result.exit_code != 0 + return result + + def interrupt_final_validation(*git_args): + if failed: + raise KeyboardInterrupt + return git_check(*git_args) + + with monkeypatch.context() as patch: + patch.setattr(cli.sandbox, "_run_one", observe_stage) + patch.setattr(cli.sandbox, "_git", interrupt_final_validation) + assert cli.main([*args, "check"]) == 130 + + assert failed + arm_approved_pr_with_check_result( + gh, head, wt, "success", isDraft=False, readiness={"local_exit": None}, + ) + assert cli.main([*args, "ready"]) == 1 + assert "not ready: run loopzero check at this head" in capsys.readouterr().out + + def test_late_checkpoint_preserves_completed_pass(wt, head): cfg = config.load(wt / "workflow.toml") passed = CheckReport(head, False, tuple(CheckResult(c, 0, 0, "", input_key="key") for c in cfg.checks), cli.sandbox.settings_fingerprint(cfg, wt)) save = partial(cli._save_report, wt) - checkpoint = cli.sandbox._checkpoint_success + checkpoint = cli.sandbox._checkpoint_stage checkpoint(partial(save, checkpoint_checks=cfg.checks), passed, {}, ()) assert cli._load_report(wt).results[0].input_key == "key" save(passed) From 6712072debf467a1927db16ee5bba8921223c9ab Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 04:01:00 +0100 Subject: [PATCH 3/6] Keep an initial failed check from changing its own worktree status Co-Authored-By: Codex --- docs/ARCHITECTURE.md | 2 +- src/loopzero/cli.py | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 128e3f52..a39cf1af 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -482,7 +482,7 @@ the authoritative `checks.json` receipt. Writers lock the task state directory while rechecking HEAD and atomically replacing the receipt from a synced sibling temporary file. Successful keyed stages are checkpointed in the same receipt for reuse. A successful stage checkpoint preserves a clean pass for the same -head, settings, and commands. A failed stage replaces a prior pass immediately. +head, settings, and commands. A failed stage replaces an existing receipt immediately. Final worktree validation is required before publishing a pass. Runners cannot select stages or mint receipts. Stage admission belongs to the runner: the outer `loopzero check` diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 5c0624eb..5d3f625b 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -376,6 +376,8 @@ def _save_report(wt: Path, report: CheckReport, *, checkpoint_checks: tuple[str, if report.head != current_head: return current_head unfinished = checkpoint_checks is not None and report.results[-1] is sandbox.INCOMPLETE_CHECK + if checkpoint_checks is not None and not unfinished and not path.exists(): + return None saved = _load_report(wt) if unfinished else None if (saved is not None and saved.ok and not saved.dirty and saved.head == report.head and saved.settings_sha256 == report.settings_sha256 From 9884adb61cb7e7c50ede9cb7c32826b901001cec Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:33:34 +0100 Subject: [PATCH 4/6] Remove repeated wording from core delivery skills Architecture-Review: unchanged; the same delivery rules and evidence requirements remain in their existing skills and contract references. Co-Authored-By: Codex --- core/skills/implement/SKILL.md | 70 +++++++++++++------------------- core/skills/plan/SKILL.md | 32 ++++++--------- core/skills/refine-code/SKILL.md | 27 +++++------- core/skills/work-issue/SKILL.md | 39 +++++++----------- core/skills/write-tests/SKILL.md | 27 +++++------- 5 files changed, 76 insertions(+), 119 deletions(-) diff --git a/core/skills/implement/SKILL.md b/core/skills/implement/SKILL.md index fd485570..d4566e9d 100644 --- a/core/skills/implement/SKILL.md +++ b/core/skills/implement/SKILL.md @@ -29,28 +29,20 @@ observations, trade-offs and limits in Notes or human Validation. Primary review requires a completed passing `loopzero check` receipt at the pushed head. Focused or ongoing checks are intermediate. Follow the [receipt reuse rules](../../CONTRACT.md#gate-execution-and-delivery-priority). -Run commands expected to take more than about two minutes detached as in -[Long-running jobs](../../../docs/DELEGATION.md#long-running-jobs). -Follow [wait and output](../../../docs/DELEGATION.md#briefs-and-ownership) -and [caps](../../../docs/DELEGATION.md#coordinator-rollover). Set -`runLimit 1` for thread reads. Do not end the turn, settle or -report done while a job you started has no `LOG.exit`, unless the unit is gone -and you report the job as killed and the result as failed. If the turn must -end, first schedule a one-shot wakeup (T3 `schedule:{type:once,runAt:}`) -that reads `LOG.exit` and resumes the delivery step it feeds. +Follow [long-running jobs](../../../docs/DELEGATION.md#long-running-jobs) for commands +expected to exceed about two minutes, and the [wait/output](../../../docs/DELEGATION.md#briefs-and-ownership) +and [caps](../../../docs/DELEGATION.md#coordinator-rollover) rules. Set `runLimit 1` on thread reads. +Hold the turn open until your job has `LOG.exit` or the unit is gone and you report it killed and failed. +If you must yield, first schedule a one-shot T3 wakeup (`schedule:{type:once,runAt:}`) +to read `LOG.exit` and resume its delivery step. -Treat /tmp as disposable: only running-command logs, build output and browser -runs belong there. Keep receipts, evidence, review artifacts and handoffs on the -PR or issue, or in the durable scratch your repository's instructions name. Make -task checkouts as worktrees of an existing clone, not new clones. At task finish, -hand leftover worktrees and generated files to the periodic retention job named -in host or repository instructions (such as `scratch-retention`), without waiting -or scheduling wakeups. When verifying or operating that job, follow -[Leftover cleanup](../../../docs/DELEGATION.md#leftover-cleanup). -If no job is named or any condition is unproved, preserve the leftovers -and report cleanup to the owner. Successful `loopzero merge` already performs its -own cleanup under the delivery contract. For a confirmed-abandoned task outside -the job's scope, give the owner the +Use worktrees of an existing clone. Keep receipts, evidence, review artifacts and handoffs on the PR, +issue or named durable scratch. Reserve `/tmp` for running-command logs, builds and browser runs. +Successful merge already runs contract cleanup. Hand leftovers to the named periodic retention job +(such as `scratch-retention`) without waiting or scheduling wakeups. +Follow [Leftover cleanup](../../../docs/DELEGATION.md#leftover-cleanup) when verifying or operating it. +With no named job or unproved conditions, preserve leftovers and report cleanup to the owner. +For confirmed-abandoned tasks outside its scope, give the owner the [manual worktree procedure](../../../SETUP.md#removing-an-abandoned-task-worktree). Follow the contract's [delivery steps](../../CONTRACT.md#the-six-steps) and @@ -60,27 +52,21 @@ Before the check and draft push for primary review, rebase your own commits onto `[repo].base` (default `main`). For a stack, follow [stacked delivery](../../../docs/DELEGATION.md#stacked-delivery). Leave base merges out of a branch awaiting its delta. -For base or check-script changes after review, follow the -[Review budget](../../CONTRACT.md#review-budget). -Preserve the primary for the delta and the delta for post-review fixes. +After review, follow the [Review budget](../../CONTRACT.md#review-budget) for base or check-script +changes. Keep the primary as the delta's base and reserve the delta for post-review fixes. -Never bypass the sandbox, change the check list or enable `[checks].network` to pass checks. -Report base failures without working around them. If a deterministic out-of-scope -defect requires a workaround, use a follow-up PR for a small test-only fix or file an `urgent` issue naming the -blocked PR. Commit yourself, never from checks, hooks or scripts. Update task and -PR before adding paths required by acceptance, and get scope decisions before -expanding proof seams or ownership. On interruption, preserve an adoptable diff -and report remaining acceptance, checks and findings per the contract. +Run checks with unchanged sandbox, check list and network settings. Report base failures as found. +For a deterministic out-of-scope defect requiring a workaround, use a follow-up PR for a small +test-only fix or file an `urgent` issue naming the blocked PR. Commit yourself, outside checks, hooks +and scripts. Update task and PR before adding paths required by acceptance. Obtain scope decisions +before expanding proof seams or ownership. On interruption, preserve an adoptable diff and use the +contract to report outstanding acceptance, checks and findings. -A host or runner change that alters what jobs see (ports, env vars, paths, -services, labels) goes live only after the repository change consuming it is on -main, or stays compatible with current main; prove it with one green run of the -affected job on the changed host before enabling it for every runner. Before -parking a PR behind another, confirm that one does not wait on yours; never hold -two PRs on each other. A failure outside the contract's owner queue route goes -with its last-green comparison to [diagnose](../diagnose/SKILL.md) at -once; recording it is not handing it over. +Keep host and runner changes to ports, env, paths, services or labels compatible with current main, +or wait for the consuming change to land. Prove the affected job on the changed host with one green +run before enabling it for all runners. Check for mutual dependencies before parking a PR. +Immediately hand failures outside the contract's owner queue route and their last-green comparison +to [diagnose](../diagnose/SKILL.md). -To requeue, unless a merge-authority hold applies, post `@mergifyio queue` as the -whole PR comment from the same login; `loopzero merge --wait` never requeues -by itself. +To requeue without a merge-authority hold, post `@mergifyio queue` as the whole PR comment from the +same login. Requeueing requires that comment even after `loopzero merge --wait`. diff --git a/core/skills/plan/SKILL.md b/core/skills/plan/SKILL.md index d723bde1..c96db412 100644 --- a/core/skills/plan/SKILL.md +++ b/core/skills/plan/SKILL.md @@ -8,25 +8,19 @@ description: Plan outcome-sized tasks with observable acceptance, ownership, pat Read [the contract](../../CONTRACT.md), repository guidance, the issue/task and relevant code. Use [delegation guidance](../../../docs/DELEGATION.md) for executors. -Before slicing, restate the ask in one precise sentence and check it against the -issue or request. Size each task to one outcome someone can accept, or one -failure family, in one PR by default. Every PR pays a fixed check, review and -queue cost: keep tests, generated files, docs and related cleanup with their -change, and batch queued, non-urgent chores of one risk class and area, never -into a risky change or ahead of an urgent fix. Split an outcome only at a named -seam. The seam must be separate rollout or rollback, a measurement that could -change the design, a higher risk class (a destructive migration, a trust -boundary), separate ownership or a diff too wide to review reliably. Scale -planning depth to the cost of reversing a choice later: spend planning on -persisted state, CLI or config interfaces, trust boundaries, public APIs and -shared abstractions—asking "if this assumption changes after merge, what -existing state or callers must still work?" (use a compact state table when -transitions matter)—and settle cheap, reversible choices during implementation. -When a cheap observation on real data or the real environment could change the design -or its target, sequence that observation first and derive targets from it. Give -each task an objective, observable acceptance, affected paths, owners, governing -constraints and proving `workflow.toml` checks. Add checks only when existing -checks cannot cover behavior. +Restate the ask in one precise sentence and check it against the issue or request. Size work to one +independently acceptable outcome or failure family in one PR by default. Keep tests, generated files, docs and related +cleanup with their change to amortize checks, review and queueing. Batch non-urgent queued chores in +the same area and risk class, away from risky changes and behind urgent fixes. Split only at a named seam: +separate rollout or rollback, a design-changing measurement, higher risk (such as destructive migration +or a trust boundary), separate ownership or a diff too wide for reliable review. +Match planning depth to the cost of reversal. For persisted state, CLI/config interfaces, trust +boundaries, public APIs and shared abstractions, identify state and callers that must survive changes +to assumptions after merge. Use compact state tables for material transitions and settle cheap, +reversible choices during implementation. Make cheap design- or target-changing observations on real +data or environments first and derive targets from them. Record each task's objective, observable +acceptance, paths, owners, constraints and proving `workflow.toml` checks. Add checks only where existing +checks cannot cover the behavior. When authorized to file slices from an active goal or planned blueprint, use its tracking issue as the parent. Give each task a plain issue title and diff --git a/core/skills/refine-code/SKILL.md b/core/skills/refine-code/SKILL.md index 23729273..7d1c70af 100644 --- a/core/skills/refine-code/SKILL.md +++ b/core/skills/refine-code/SKILL.md @@ -5,29 +5,22 @@ description: Simplify a named or current-task diff, or delete evidenced dead cod # Refine Code -Simplify the user-named or current-task diff while preserving observable behavior -and public contracts. Follow [the contract](../../CONTRACT.md) in the outer task's -worktree; confirm branch and task before editing. Prefer clear names, control -flow and established local patterns without unrelated cleanup or compatibility -layers. +Preserve observable behavior and public contracts in the user-named or current-task diff. +Confirm task and branch in the outer worktree and follow [the contract](../../CONTRACT.md). +Use clear names, control flow and local patterns. Keep cleanup and compatibility layers within scope. Treat concurrency, exception timing, transactions, ordering, query predicates, persistence, isolation, serialization, public imports, API shape and assertions as semantic until equivalence is demonstrated. Route new behavior, abstraction boundaries or weakened tests to [implement](../implement/SKILL.md). -Deletion of code outside the current task diff requires explicit requester -commissioning; an audit finding ([code health](../../../docs/CODE-HEALTH.md)) -is a lead, not a commission. Choose a clean rollback commit before a deletion -batch; if any check fails, restore the whole batch to it before debugging. - -For deletion, establish that supported consumers, including dynamic entry points, -registries, reflection, plugins, configuration, generated consumers and public -exports, do not reach the code. Inspect base and current tree; local edits cannot -prove base unreachability. Lint and coverage alone do not prove deadness, nor does -one dead symbol prove its module dead. Preserve uncertain candidates and explain -why. Keep removal recoverable in Git and validate affected runtime, build, -packaging, deployment and documentation boundaries. +Deletion outside the task diff needs explicit commissioning. Treat [code health](../../../docs/CODE-HEALTH.md) +findings as leads. Select a clean rollback commit and restore the whole batch before debugging any failed check. +Verify in the base and current trees that supported consumers cannot reach removed code. Check dynamic entry +points, registries, reflection, plugins, configuration, generated consumers and public exports. +Lint, coverage, post-edit searches and one dead symbol alone do not prove base or module unreachability. +Explain and preserve uncertain candidates. Keep removals recoverable in Git and validate affected runtime, +build, packaging, deployment and docs boundaries. Explain the clarity gain and any apparently behavioral edit. Run focused success and relevant failure/cancellation tests and [contract checks](../../CONTRACT.md#blockers); record evidence and diff --git a/core/skills/work-issue/SKILL.md b/core/skills/work-issue/SKILL.md index 73e4ae31..1da6506d 100644 --- a/core/skills/work-issue/SKILL.md +++ b/core/skills/work-issue/SKILL.md @@ -5,23 +5,16 @@ description: Own full delivery of a live GitHub issue through verified merge and # Work Issue -Use [the contract](../../CONTRACT.md); the issue owns intake context, the PR owns -delivery evidence. Read live issue acceptance, comments, artifacts and linked -work. Before pickup, reconcile prior and partial deliveries, branches and -competing PRs with the issue's [dispatch authority](../../../docs/DELEGATION.md#team-roles). -Verify remote identity before mutation and connected environment before -relying on production claims. Before presenting counts, censuses or states for -a decision or requesting production-change approval, follow -[evidence for approval](reference.md#evidence-for-approval). -Before continuing an existing branch or PR, follow -[inherited-work guidance](reference.md#inherited-work). - -Retain an inherited task worktree or use `loopzero start `. -Record observable acceptance and the issue link. Deliver through -[implement](../implement/SKILL.md). Follow the linked safeguards for -[API shape changes](reference.md#api-shape-changes), -[seeded browser state or changed prerequisites](reference.md#fresh-stack-proof), -and [implementation or repairs without a base merge queue](reference.md#integration-without-a-queue). +Follow [the contract](../../CONTRACT.md). The issue owns intake and the PR owns delivery evidence. +Read live acceptance, comments, artifacts and linked work. Reconcile prior and partial deliveries, +branches and competing PRs before pickup with the [dispatch authority](../../../docs/DELEGATION.md#team-roles). +Verify remote identity before mutation and connected environment before production claims. +Use [approval evidence](reference.md#evidence-for-approval) for decision counts, censuses or states +and production-change approval. Use [inherited-work guidance](reference.md#inherited-work) before resuming. +Keep the inherited worktree or use `loopzero start `. Record observable acceptance and link +the issue. Deliver through [implement](../implement/SKILL.md), applying the safeguards for +[API shape](reference.md#api-shape-changes), [changed stack prerequisites or seeded browser state](reference.md#fresh-stack-proof) +and [implementation or repairs without a merge queue](reference.md#integration-without-a-queue). Before review, update docs as needed and record changes or evidence that none are needed. Before publication, inspect the issue and links for its lifecycle blueprint and @@ -43,10 +36,8 @@ Follow the linked safeguards when [partial delivery auto-closes the issue](refer for [findings after completed acceptance](reference.md#late-findings), and for [monitoring after shipped acceptance or deferred work](reference.md#monitoring-and-deferred-work). -Open the return with one plain sentence: what changed for the owner and whether -anything is needed from them. Then return evidence, PR/head or landed SHA, -remaining acceptance and next-action owner -with command or trigger to the dispatch authority on the issue/PR or through the -parent. Reconcile conflicts and scope-expanding or reserved choices with that -owner. Continue only an already commissioned successor after recording this -item's evidence and rechecking live state in a fresh task worktree. +Use [Reporting](../../CONTRACT.md#reporting) and open with one plain sentence covering owner impact +and any action needed. Send evidence, PR/head or landed SHA, outstanding acceptance and next-action +owner with command or trigger to dispatch authority on the issue/PR or through the parent. +Reconcile conflicts and scope-expanding or reserved choices with that owner. Continue only an +already commissioned successor after recording this item's evidence and rechecking live state in a fresh worktree. diff --git a/core/skills/write-tests/SKILL.md b/core/skills/write-tests/SKILL.md index 76a72e29..34910544 100644 --- a/core/skills/write-tests/SKILL.md +++ b/core/skills/write-tests/SKILL.md @@ -10,24 +10,17 @@ Follow [the contract](../../CONTRACT.md). Do not change product behavior merely to increase coverage; route product repairs to [implement](../implement/SKILL.md) and observed failures to [diagnose](../diagnose/SKILL.md). -Choose the cheapest faithful public boundary: unit tests for deterministic logic, -integration tests for real storage/adapters and end-to-end tests for journeys -that need the assembled system. Report missing seams rather than extracting -production code solely for testing convenience. Use independent oracles for -outputs, transitions and effects; mock calls, snapshots, internal steps or copied -implementation calculations alone are insufficient. +Choose the cheapest faithful public boundary: unit for deterministic logic, integration for real +storage/adapters, and end to end for assembled journeys. Report missing seams without extracting code +just for test convenience. Use independent oracles for outputs, transitions and effects. Mock calls, +snapshots, internal steps and copied calculations are insufficient alone. -Cover material success, denial/isolation, validation, transitions and failures. -Follow repository conventions with minimal, deterministic, isolated fixtures, -using the real producer where cheap and otherwise matching the consumed fields -and behavior of its public interface while avoiding shared mutable state, -timing tolerance and duplicate cases. For bug fixes, -observe the regression test fail on pre-fix code; only when that is impossible, -explain the oracle and its limits. Infrastructure failures do not demonstrate -regression detection. -A new or changed test blocks other changes only through the consumer's -admission rule; established critical assertions stay blocking. -Coverage-only tests may pass existing code. +Cover material success, denial/isolation, validation, transitions and failures. Follow repo conventions +with minimal deterministic, isolated fixtures. Prefer cheap real producers or match the public fields +and behavior consumed, avoiding shared mutable state, timing tolerance and duplicate cases. +For a bug fix, observe failure on pre-fix code. If impossible, explain the oracle and its limits. +Infrastructure failure cannot prove regression detection. New or changed tests block only through the +consumer's admission rule. Established critical assertions remain blocking. Coverage-only tests may pass existing code. Run focused and affected neighboring tests, then [contract delivery checks](../../CONTRACT.md#blockers). Record commands, results and limits in task Notes. From 77dbc45932cf67c2a82a5ac3d2d54dc69ba51105 Mon Sep 17 00:00:00 2001 From: eowca <4008965+eowca@users.noreply.github.com> Date: Thu, 26 Nov 2026 15:41:20 +0100 Subject: [PATCH 5/6] Preserve the qualifiers flagged in primary review Architecture-Review: unchanged; this restores the existing rule wording without changing delivery architecture. Co-Authored-By: Codex --- core/skills/implement/SKILL.md | 13 +++++++------ core/skills/refine-code/SKILL.md | 4 ++-- core/skills/work-issue/SKILL.md | 4 ++-- core/skills/write-tests/SKILL.md | 2 +- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/core/skills/implement/SKILL.md b/core/skills/implement/SKILL.md index d4566e9d..c913abc9 100644 --- a/core/skills/implement/SKILL.md +++ b/core/skills/implement/SKILL.md @@ -32,14 +32,14 @@ Focused or ongoing checks are intermediate. Follow the [receipt reuse rules](../ Follow [long-running jobs](../../../docs/DELEGATION.md#long-running-jobs) for commands expected to exceed about two minutes, and the [wait/output](../../../docs/DELEGATION.md#briefs-and-ownership) and [caps](../../../docs/DELEGATION.md#coordinator-rollover) rules. Set `runLimit 1` on thread reads. -Hold the turn open until your job has `LOG.exit` or the unit is gone and you report it killed and failed. +Do not end the turn, settle or report done before `LOG.exit` unless the unit is gone and you report it killed and failed. If you must yield, first schedule a one-shot T3 wakeup (`schedule:{type:once,runAt:}`) to read `LOG.exit` and resume its delivery step. Use worktrees of an existing clone. Keep receipts, evidence, review artifacts and handoffs on the PR, issue or named durable scratch. Reserve `/tmp` for running-command logs, builds and browser runs. -Successful merge already runs contract cleanup. Hand leftovers to the named periodic retention job -(such as `scratch-retention`) without waiting or scheduling wakeups. +Merge already runs contract cleanup. At task finish, hand leftover worktrees and generated files to the periodic +retention job named in host or repo instructions, without waiting or scheduling wakeups. Follow [Leftover cleanup](../../../docs/DELEGATION.md#leftover-cleanup) when verifying or operating it. With no named job or unproved conditions, preserve leftovers and report cleanup to the owner. For confirmed-abandoned tasks outside its scope, give the owner the @@ -55,7 +55,8 @@ Leave base merges out of a branch awaiting its delta. After review, follow the [Review budget](../../CONTRACT.md#review-budget) for base or check-script changes. Keep the primary as the delta's base and reserve the delta for post-review fixes. -Run checks with unchanged sandbox, check list and network settings. Report base failures as found. +Never bypass the sandbox, change the check list or enable `[checks].network` to pass checks. +Report base failures without working around them. For a deterministic out-of-scope defect requiring a workaround, use a follow-up PR for a small test-only fix or file an `urgent` issue naming the blocked PR. Commit yourself, outside checks, hooks and scripts. Update task and PR before adding paths required by acceptance. Obtain scope decisions @@ -64,9 +65,9 @@ contract to report outstanding acceptance, checks and findings. Keep host and runner changes to ports, env, paths, services or labels compatible with current main, or wait for the consuming change to land. Prove the affected job on the changed host with one green -run before enabling it for all runners. Check for mutual dependencies before parking a PR. +run before enabling it for all runners. Before parking a PR, verify it does not wait on yours. Never park both on each other. Immediately hand failures outside the contract's owner queue route and their last-green comparison -to [diagnose](../diagnose/SKILL.md). +to [diagnose](../diagnose/SKILL.md). A log entry alone does not hand over the failure. To requeue without a merge-authority hold, post `@mergifyio queue` as the whole PR comment from the same login. Requeueing requires that comment even after `loopzero merge --wait`. diff --git a/core/skills/refine-code/SKILL.md b/core/skills/refine-code/SKILL.md index 7d1c70af..260514cb 100644 --- a/core/skills/refine-code/SKILL.md +++ b/core/skills/refine-code/SKILL.md @@ -7,14 +7,14 @@ description: Simplify a named or current-task diff, or delete evidenced dead cod Preserve observable behavior and public contracts in the user-named or current-task diff. Confirm task and branch in the outer worktree and follow [the contract](../../CONTRACT.md). -Use clear names, control flow and local patterns. Keep cleanup and compatibility layers within scope. +Use clear names, control flow and local patterns without unrelated cleanup or compatibility layers. Treat concurrency, exception timing, transactions, ordering, query predicates, persistence, isolation, serialization, public imports, API shape and assertions as semantic until equivalence is demonstrated. Route new behavior, abstraction boundaries or weakened tests to [implement](../implement/SKILL.md). -Deletion outside the task diff needs explicit commissioning. Treat [code health](../../../docs/CODE-HEALTH.md) +Deletion outside the task diff requires explicit commissioning by the requester. Treat [code health](../../../docs/CODE-HEALTH.md) findings as leads. Select a clean rollback commit and restore the whole batch before debugging any failed check. Verify in the base and current trees that supported consumers cannot reach removed code. Check dynamic entry points, registries, reflection, plugins, configuration, generated consumers and public exports. diff --git a/core/skills/work-issue/SKILL.md b/core/skills/work-issue/SKILL.md index 1da6506d..3d31a77d 100644 --- a/core/skills/work-issue/SKILL.md +++ b/core/skills/work-issue/SKILL.md @@ -10,7 +10,7 @@ Read live acceptance, comments, artifacts and linked work. Reconcile prior and p branches and competing PRs before pickup with the [dispatch authority](../../../docs/DELEGATION.md#team-roles). Verify remote identity before mutation and connected environment before production claims. Use [approval evidence](reference.md#evidence-for-approval) for decision counts, censuses or states -and production-change approval. Use [inherited-work guidance](reference.md#inherited-work) before resuming. +and production-change approval. Use [inherited-work guidance](reference.md#inherited-work) before continuing an existing branch or PR. Keep the inherited worktree or use `loopzero start `. Record observable acceptance and link the issue. Deliver through [implement](../implement/SKILL.md), applying the safeguards for [API shape](reference.md#api-shape-changes), [changed stack prerequisites or seeded browser state](reference.md#fresh-stack-proof) @@ -40,4 +40,4 @@ Use [Reporting](../../CONTRACT.md#reporting) and open with one plain sentence co and any action needed. Send evidence, PR/head or landed SHA, outstanding acceptance and next-action owner with command or trigger to dispatch authority on the issue/PR or through the parent. Reconcile conflicts and scope-expanding or reserved choices with that owner. Continue only an -already commissioned successor after recording this item's evidence and rechecking live state in a fresh worktree. +already commissioned successor after recording this item's evidence and rechecking live state in a fresh task worktree. diff --git a/core/skills/write-tests/SKILL.md b/core/skills/write-tests/SKILL.md index 34910544..ac0a01bc 100644 --- a/core/skills/write-tests/SKILL.md +++ b/core/skills/write-tests/SKILL.md @@ -18,7 +18,7 @@ snapshots, internal steps and copied calculations are insufficient alone. Cover material success, denial/isolation, validation, transitions and failures. Follow repo conventions with minimal deterministic, isolated fixtures. Prefer cheap real producers or match the public fields and behavior consumed, avoiding shared mutable state, timing tolerance and duplicate cases. -For a bug fix, observe failure on pre-fix code. If impossible, explain the oracle and its limits. +For a bug fix, observe the regression test fail on pre-fix code. If impossible, explain the oracle and its limits. Infrastructure failure cannot prove regression detection. New or changed tests block only through the consumer's admission rule. Established critical assertions remain blocking. Coverage-only tests may pass existing code. From 5240ad605d39a80c6d5cee33fbac3a253af85f52 Mon Sep 17 00:00:00 2001 From: Codex Date: Thu, 26 Nov 2026 15:45:27 +0100 Subject: [PATCH 6/6] Serialize Mergify queue requests and reconcile transient replies Architecture-Review: unchanged; admission uses the existing worktree lock and the existing marker proof, with confirmed HTTP rate limits preserving the transport diagnostic. Co-Authored-By: Codex --- src/loopzero/cli.py | 45 +++++++++++++++++++++-------------------- src/loopzero/github.py | 6 ++++-- src/loopzero/mergify.py | 6 +++++- tests/test_cli.py | 45 +++++++++++++++++++++++++++++++++++++++++ tests/test_mergify.py | 17 +++++++++++++++- 5 files changed, 93 insertions(+), 26 deletions(-) diff --git a/src/loopzero/cli.py b/src/loopzero/cli.py index 758e24b5..9d87c54b 100644 --- a/src/loopzero/cli.py +++ b/src/loopzero/cli.py @@ -1723,29 +1723,30 @@ def _merge_with_mergify( assert queue is not None if not readiness.ready: return _follow_blocked_mergify(config, pr, readiness, queue, deadline) - requested, confirmed_marker = mergify.markers( - config.repo, pr.number, pr.head_sha, queue - ) - state = mergify.membership(config.repo, pr.number, queue, deadline) - if sha := github.merged_sha( - config.repo, pr.number, expected_head=pr.head_sha, check_hold=not requested and state is None, - ): - return sha - confirmed = state is not None - if confirmed and not confirmed_marker: - _require_receipt(wt, config, pr.head_sha) - mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue) - if not confirmed and confirmed_marker: - closed: list[github.GhError] = [] - if sha := _mergify_departure(config, pr, queue, closed, confirmed=True): + with worktree.lock_local_state(wt): + requested, confirmed_marker = mergify.markers( + config.repo, pr.number, pr.head_sha, queue + ) + state = mergify.membership(config.repo, pr.number, queue, deadline) + if sha := github.merged_sha( + config.repo, pr.number, expected_head=pr.head_sha, check_hold=not requested and state is None, + ): return sha - raise closed[0] - if not confirmed and not requested: - _prequeue_size_budget(wt, config, pr, readiness, project=admit_by is None) - if admit_by is not None and time.monotonic() > admit_by: - raise _AdmissionDeadline - _require_receipt(wt, config, pr.head_sha) - mergify.request(config.repo, pr.number, pr.head_sha, queue) + confirmed = state is not None + if confirmed and not confirmed_marker: + _require_receipt(wt, config, pr.head_sha) + mergify.mark_confirmed(config.repo, pr.number, pr.head_sha, queue) + if not confirmed and confirmed_marker: + closed: list[github.GhError] = [] + if sha := _mergify_departure(config, pr, queue, closed, confirmed=True): + return sha + raise closed[0] + if not confirmed and not requested: + _prequeue_size_budget(wt, config, pr, readiness, project=admit_by is None) + if admit_by is not None and time.monotonic() > admit_by: + raise _AdmissionDeadline + _require_receipt(wt, config, pr.head_sha) + mergify.request(config.repo, pr.number, pr.head_sha, queue) if deadline is not None: return _wait_for_mergify(config, pr, max(0.0, deadline - time.monotonic()), confirmed) state_name = "confirmed in" if confirmed else "requested from" diff --git a/src/loopzero/github.py b/src/loopzero/github.py index 314f77bb..1713ce20 100644 --- a/src/loopzero/github.py +++ b/src/loopzero/github.py @@ -68,9 +68,10 @@ class GhError(Exception): def __init__(self, command: tuple[str, ...], tail: str, *, - token: str = "", guidance: str = "") -> None: + token: str = "", guidance: str = "", confirmed_rate_limit: bool = False) -> None: self.command = tuple(_redact_tokens(arg, token) for arg in command) self.tail = _redact_tokens(tail, token) + guidance + self.confirmed_rate_limit = confirmed_rate_limit command_text = _redact_tokens(" ".join(command), token) super().__init__(f"{command_text} failed: {self.tail.strip()[-600:]}") @@ -411,7 +412,8 @@ def _gh(*args: str, cwd: Path | None = None, timeout: float = 120, raise GhAuth(error_command, detail.rstrip(), token=selected, guidance=f"\n{GH_AUTH_REMEDY}") guidance = _pr_list_error_guidance(args, done.stderr, bool(read_only and selected and token is None)) error = GhUnavailable if transient else GhError - raise error(error_command, detail, token=selected, guidance=guidance) + raise error(error_command, detail, token=selected, guidance=guidance, + confirmed_rate_limit=rate_limited and status in {"403", "429"}) def _rest_rate_limit(headers: dict[str, str]) -> str: diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 709d5604..3aa8c60a 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -401,7 +401,11 @@ def markers(repo: str, number: int, head: str, queue: str) -> tuple[bool, bool]: def request(repo: str, number: int, head: str, queue: str) -> None: body = f"@mergifyio queue\n\n{_marker(REQUEST, head, queue)}" # Mergify deprecates naming the queue - github._api(f"repos/{repo}/issues/{number}/comments", {"body": body}) + try: + github._api(f"repos/{repo}/issues/{number}/comments", {"body": body}) + except (github.GhError, github.ProcTimeout, OSError) as exc: + if getattr(exc, "confirmed_rate_limit", False) or not markers(repo, number, head, queue)[0]: + raise def mark_confirmed(repo: str, number: int, head: str, queue: str) -> None: diff --git a/tests/test_cli.py b/tests/test_cli.py index 466e6377..6ad565b6 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -3919,6 +3919,51 @@ def test_mergify_merge_requests_once_for_behind_head( else: assert "queue configuration is unverified" in err +@pytest.mark.parametrize(("accepted", "transient"), [(True, False), (False, False), (True, True)]) +def test_overlapping_mergify_command_after_lost_reply(wt, gh, monkeypatch, accepted, transient): + head = arm_mergify_pr(wt, gh) + pr = github.PR(7, URL, head, "main", False, "OPEN", "MERGEABLE") + settings = config.load_trusted(wt) + monkeypatch.setattr(cli, "_context", lambda *_args, **_kwargs: (wt, settings)) + monkeypatch.setattr(cli, "_pr_readiness", lambda *_args, **_kwargs: (pr, github.Readiness(True, ()))) + monkeypatch.setattr(mergify, "membership", lambda *_: None) + monkeypatch.setattr(github, "merged_sha", lambda *_args, **_kwargs: None) + endpoint = f"repos/{REPO}/issues/7/comments" + gh.respond(f"api {endpoint}", []) + gh.respond(f"api {endpoint} --method POST", {}) + writing, overlap = Event(), Event() + original_api, flock = github._api, cli.fcntl.flock + + def lock(fd, operation): + if writing.is_set(): + overlap.set() + return flock(fd, operation) + + def transport(path, payload, **kwargs): + if path != endpoint: + return original_api(path, payload, **kwargs) + if not writing.is_set(): + writing.set() + assert overlap.wait(10), "second merge did not reach admission" + if accepted: + original_api(path, payload, **kwargs) + gh.respond(f"api {path}", [{"user": {"login": LOGIN}, "body": payload["body"]}]) + if transient: + raise github.GhUnavailable(("GitHub API request",), "HTTP 502") + raise github.ProcTimeout("lost Mergify command reply") + return original_api(path, payload, **kwargs) + + monkeypatch.setattr(cli.fcntl, "flock", lock) + monkeypatch.setattr(github, "_api", transport) + with ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(cli.main, ["merge"]) + assert writing.wait(10), "first merge did not reach the command POST" + second = pool.submit(cli.main, ["merge"]) + assert first.result(timeout=15) == (0 if accepted else 1) + assert second.result(timeout=15) == 0 + assert len([c for c in gh.calls if "--input" in c and c["argv"][1] == endpoint]) == 1 + + @pytest.mark.parametrize("command", ["ready", "status"]) @pytest.mark.parametrize("merge_state", ["CLEAN", "BEHIND"]) diff --git a/tests/test_mergify.py b/tests/test_mergify.py index f8a35f1f..34ea4d59 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -15,7 +15,7 @@ import pytest -from loopzero import mergify +from loopzero import github, mergify def response(payload: object) -> io.BytesIO: @@ -273,3 +273,18 @@ def arm(timer, seconds): signal.raise_signal(signal.SIGALRM) assert signal.getsignal(signal.SIGALRM) is handler assert signal.getitimer(signal.ITIMER_REAL) == (0, 0) + + +@pytest.mark.parametrize("response", [ + 'HTTP/2 429 Too Many Requests\n\n{}', + 'HTTP/2 403 Forbidden\nX-RateLimit-Remaining: 0\n\n{}', + 'HTTP/2 403 Forbidden\n\n{"message":"API rate limit exceeded"}', +]) +def test_rate_limited_queue_post_does_not_reconcile(monkeypatch, response): + monkeypatch.setattr(github, "run", lambda *_a, **_k: SimpleNamespace( + exit_code=1, stdout=response, stderr="", + )) + monkeypatch.setattr(mergify, "markers", lambda *_: pytest.fail("read markers after rate-limited POST")) + with pytest.raises(github.GhUnavailable) as exc: + mergify.request("acme/widgets", 7, "a" * 40, "main") + assert exc.value.confirmed_rate_limit