diff --git a/.agents/skills/ael/references/loop-deliver.md b/.agents/skills/ael/references/loop-deliver.md index ba39f5f..2390370 100644 --- a/.agents/skills/ael/references/loop-deliver.md +++ b/.agents/skills/ael/references/loop-deliver.md @@ -1,14 +1,14 @@ # Stage 8: Delivery - After Judge PASS (and `verify --final` if verification was `--related`), run the `after_pass` hook, then the Stage 8 adapter from `.ai-engineering-loop/adapter.md`. -- Before any push, run `npx ai-engineering-loop doctor`: `✗ adapter-*` (unknown `adapter_type`, missing spec) must be fixed; `! adapter-*` (gh/glab not logged in, configured type differs from the detected one) needs a human look. `deliver` repeats this check: UNATTENDED stops before writing, ASSISTED only warns. +- Code changed after PASS: `run --reopen --run --reason `, then redo the loop. Never abandon. +- Before any push, run `npx ai-engineering-loop doctor`: `✗ adapter-*` (unknown `adapter_type`, missing spec) must be fixed; `! adapter-*` (gh/glab logged out, configured type differs from detected) needs a human look. `deliver` repeats this check: UNATTENDED stops before writing, ASSISTED only warns. - The PR/MR body includes `Steps to Reproduce & Testing (QA)`; bugfix placeholders must not stay empty. Disclose any `budget record --unavailable`. - Preview remote payloads; never include context packs, usage ledgers, raw logs, or credentials. - ASSISTED: never infer approval. When the human says yes, record it at once: `npx ai-engineering-loop deliver --run --approve --by `. After commit, push and PR/MR, finish with `deliver --run --destination --summary --approve --by ` (writes `delivery.json` with `humanApproved: true`, runs `gate delivery`). -- Long form: `node status --run `, `node approve delivery-approval --yes --by --run ` for each READY approval node, write `RUN_DIR/delivery.json`, then `gate delivery`. If the gate says a node is not READY, follow its prerequisite hint; never bypass approval. +- Long form: `node status --run `, `node approve delivery-approval --yes --by --run ` for each READY approval node, write `RUN_DIR/delivery.json`, then `gate delivery`. Node not READY: follow its prerequisite hint; never bypass approval. - Commit before `deliver` (its receipt binds `HEAD`; videos/screenshots: `--evidence AC-N=`, required for `crossComponent` and rubric ACs). Paste `RUN_DIR/receipt.md` into the PR/MR Receipt section unchanged; ❌ stays ❌ (`docs pr-receipt`). -- Only the delivery gate completes the run. It also mines lessons for the next Run. -- Worktree Run: after `deliver`, continue in `cleanup.mainCheckout` (Stage 9). +- Only the delivery gate completes the run. Worktree Run: then continue in `cleanup.mainCheckout`. - After the PR is open, `npx ai-engineering-loop pr babysit --run ` polls with backoff. Failing checks start a T0 or T1 fix on that same branch and push it. Ready to merge, or changes requested, stops for a human. Merge stays with the human (`docs run-isolation`). ## Report header (execution mode) diff --git a/.agents/skills/ael/references/loop-judge.md b/.agents/skills/ael/references/loop-judge.md index 902b861..e411d06 100644 --- a/.agents/skills/ael/references/loop-judge.md +++ b/.agents/skills/ael/references/loop-judge.md @@ -6,6 +6,7 @@ Read when `gate review` says `judgeRequired`, on T2, or when acting on findings. - Judge context: only run-summary.md, verification-summary.json (or verification.json), open-findings.json/findings.json, and the Goal hash; it reads the full diff only if those contradict each other. Judge prompt includes "at most 4 tool calls; ledger and contract only; skip css; do not re-review the whole diff". - Spawn a fresh sibling Judge, wait, `budget record`, write `RUN_DIR/verdict.json` with `modelTier` and any `judgeFindings`, then `gate judge`. A gate failure overrides optimistic prose. - ITERATE under the recipe cap: fix in the parent, re-verify, spawn a **new** DA (never resume the previous child). At the cap or NO_PROGRESS, ESCALATE to the human. +- Code changed after PASS (DA fixes, test fixes): `run --reopen --run --reason ` starts a new iteration; `gate maker` refuses to overwrite a judged diff (`docs iteration-policy`). ## Acting on findings (DA during ITERATE, or human MR/PR comments) diff --git a/.claude/skills/ael/references/loop-deliver.md b/.claude/skills/ael/references/loop-deliver.md index ba39f5f..2390370 100644 --- a/.claude/skills/ael/references/loop-deliver.md +++ b/.claude/skills/ael/references/loop-deliver.md @@ -1,14 +1,14 @@ # Stage 8: Delivery - After Judge PASS (and `verify --final` if verification was `--related`), run the `after_pass` hook, then the Stage 8 adapter from `.ai-engineering-loop/adapter.md`. -- Before any push, run `npx ai-engineering-loop doctor`: `✗ adapter-*` (unknown `adapter_type`, missing spec) must be fixed; `! adapter-*` (gh/glab not logged in, configured type differs from the detected one) needs a human look. `deliver` repeats this check: UNATTENDED stops before writing, ASSISTED only warns. +- Code changed after PASS: `run --reopen --run --reason `, then redo the loop. Never abandon. +- Before any push, run `npx ai-engineering-loop doctor`: `✗ adapter-*` (unknown `adapter_type`, missing spec) must be fixed; `! adapter-*` (gh/glab logged out, configured type differs from detected) needs a human look. `deliver` repeats this check: UNATTENDED stops before writing, ASSISTED only warns. - The PR/MR body includes `Steps to Reproduce & Testing (QA)`; bugfix placeholders must not stay empty. Disclose any `budget record --unavailable`. - Preview remote payloads; never include context packs, usage ledgers, raw logs, or credentials. - ASSISTED: never infer approval. When the human says yes, record it at once: `npx ai-engineering-loop deliver --run --approve --by `. After commit, push and PR/MR, finish with `deliver --run --destination --summary --approve --by ` (writes `delivery.json` with `humanApproved: true`, runs `gate delivery`). -- Long form: `node status --run `, `node approve delivery-approval --yes --by --run ` for each READY approval node, write `RUN_DIR/delivery.json`, then `gate delivery`. If the gate says a node is not READY, follow its prerequisite hint; never bypass approval. +- Long form: `node status --run `, `node approve delivery-approval --yes --by --run ` for each READY approval node, write `RUN_DIR/delivery.json`, then `gate delivery`. Node not READY: follow its prerequisite hint; never bypass approval. - Commit before `deliver` (its receipt binds `HEAD`; videos/screenshots: `--evidence AC-N=`, required for `crossComponent` and rubric ACs). Paste `RUN_DIR/receipt.md` into the PR/MR Receipt section unchanged; ❌ stays ❌ (`docs pr-receipt`). -- Only the delivery gate completes the run. It also mines lessons for the next Run. -- Worktree Run: after `deliver`, continue in `cleanup.mainCheckout` (Stage 9). +- Only the delivery gate completes the run. Worktree Run: then continue in `cleanup.mainCheckout`. - After the PR is open, `npx ai-engineering-loop pr babysit --run ` polls with backoff. Failing checks start a T0 or T1 fix on that same branch and push it. Ready to merge, or changes requested, stops for a human. Merge stays with the human (`docs run-isolation`). ## Report header (execution mode) diff --git a/.claude/skills/ael/references/loop-judge.md b/.claude/skills/ael/references/loop-judge.md index 902b861..e411d06 100644 --- a/.claude/skills/ael/references/loop-judge.md +++ b/.claude/skills/ael/references/loop-judge.md @@ -6,6 +6,7 @@ Read when `gate review` says `judgeRequired`, on T2, or when acting on findings. - Judge context: only run-summary.md, verification-summary.json (or verification.json), open-findings.json/findings.json, and the Goal hash; it reads the full diff only if those contradict each other. Judge prompt includes "at most 4 tool calls; ledger and contract only; skip css; do not re-review the whole diff". - Spawn a fresh sibling Judge, wait, `budget record`, write `RUN_DIR/verdict.json` with `modelTier` and any `judgeFindings`, then `gate judge`. A gate failure overrides optimistic prose. - ITERATE under the recipe cap: fix in the parent, re-verify, spawn a **new** DA (never resume the previous child). At the cap or NO_PROGRESS, ESCALATE to the human. +- Code changed after PASS (DA fixes, test fixes): `run --reopen --run --reason ` starts a new iteration; `gate maker` refuses to overwrite a judged diff (`docs iteration-policy`). ## Acting on findings (DA during ITERATE, or human MR/PR comments) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8b1a59..3533725 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,12 @@ All notable changes to this project are documented here. Versions follow [Semant ## Unreleased +- **Fixed:** AEL could deliver code the Judge never saw. `verify` recorded evidence against the gated `diff.patch` hash while it ran on the working tree, so a fix made after `gate maker` was verified but never reviewed; and `deliver` never compared the commit with the judged diff, so code added after Judge PASS and committed was delivered. `verify`, `gate verification` and `gate delivery` now compare the Run's change (from the commit the Run started on to the working tree, committed or not) with `diff.patch` and refuse with `DIFF_DRIFT`, naming the files and `run --reopen`. The same change committed or uncommitted still matches. +- **Fixed:** `gate maker --from-git` diffed against `HEAD`, so a change committed before the Maker gate failed with "found no changes against HEAD" and no WHY/FIX. It now diffs against the Run's starting commit; when there really is no change, the error says why and what to do. +- **Added:** bench sandbox scenario `rework` (deliver refuses unjudged code after PASS, `run --reopen`, loop again, deliver). + +- **Fixed:** a Run stuck after Judge PASS when the code changed afterwards (for example test fixes for Devil's Advocate findings). `gate maker --from-git` overwrote the judged `diff.patch`, the Run could not take a new Maker diff, and `deliver` failed, so the only way out was `run --abandon`. Now `gate maker --from-git` refuses to overwrite a gated diff and names the new command `run --reopen --run --reason `, which starts a new iteration: the gated diff, evidence, ledger, verdict and approval move to `runs//iterations//`, and Maker, verification, review, Judge and delivery run again on the new diff, so the delivered diff is still the judged diff. The verification and stale-artifact gate errors name the same command. See `docs iteration-policy`. + - **Fixed:** DOT delivery could let GitLab close the card on merge. The adapter now says delivery never closes the card: commits and MR text reference the issue only as `Refs #`, `Related to #` or the bare URL, never after `Closes`/`Fixes`/`Resolves`/`Implements`, and never via `glab issue close`. The Coreview fix-commit template no longer reads `resolve <...>`. A test scans every DOT adapter file for closing keywords. - **Fixed:** an approved delivery kept showing as waiting for minutes. The agent recorded your approval only in its last `deliver` call, after committing, pushing and opening the PR, so Studio and the notification kept asking. `deliver --run --approve --by ` without a destination now records the approval at once (approval nodes, `delivery.json` with `approvedAt`; repeatable), and the delivery stage tells the agent to run it the moment you say yes; the full `deliver` still finishes the Run. Before, that call approved the nodes and then failed asking for `--destination`. diff --git a/adapters/dot/coreview.md b/adapters/dot/coreview.md index 697a34a..9f68077 100644 --- a/adapters/dot/coreview.md +++ b/adapters/dot/coreview.md @@ -73,7 +73,7 @@ Every Coreview comment must be categorized into one of two paths: ``` 3. Commit and push the fix to the branch: ```bash - git commit -m "fix(coreview): resolve " + git commit -m "fix(coreview): " git push origin ``` 4. Cherry-pick the new fix commit to all other active environment branches (`main`, `staging`). diff --git a/adapters/dot/gitlab.md b/adapters/dot/gitlab.md index 2440dcb..92da82f 100644 --- a/adapters/dot/gitlab.md +++ b/adapters/dot/gitlab.md @@ -25,6 +25,14 @@ flowchart TD Triage --> Ready[Move card to Ready to review: Step 4] ``` +### Delivery never closes the card + +DOT delivery never closes the card: it only moves it to "Ready to review" (Step 4), and closing stays with humans. GitLab closes an issue by itself when a commit or MR description that reaches the default branch puts a closing keyword (`Closes`, `Fixes`, `Resolves`, `Implements`, any tense) before an issue reference or issue URL. So in commit messages, MR titles and MR descriptions: + +- Reference the issue only as `Refs #`, `Related to #`, or the bare issue URL (as in the MR template's `## Issue` section). +- Never put a closing keyword before an issue reference, and never run `glab issue close`. +- `fix(#300): ...` and `Refs #300` are fine; a closing keyword followed by `#300` is not. + --- ## 3. Step 1: Git Context & Remote Repository Inspection diff --git a/adapters/dot/skills/dot-dev-workflow/SKILL.md b/adapters/dot/skills/dot-dev-workflow/SKILL.md index bfc5b68..af2faab 100644 --- a/adapters/dot/skills/dot-dev-workflow/SKILL.md +++ b/adapters/dot/skills/dot-dev-workflow/SKILL.md @@ -59,6 +59,8 @@ git commit -m "(): " 2. Create a GitLab issue if none is linked (`glab issue create` with module title, scope checkboxes, `Steps to Reproduce & Testing (QA)` from `adapters/dot/gitlab.md`, expectation table, label `Ready to Test`). On a bugfix, do not leave those placeholders empty. +Delivery never closes the card; closing stays with humans. GitLab closes an issue on merge to the default branch when a commit or MR text puts `Closes`, `Fixes`, `Resolves` or `Implements` before an issue reference. Reference the issue only as `Refs #`, `Related to #` or the bare issue URL, and never run `glab issue close`. + 3. Open **one** MR (`glab mr create` onto the live integration base from the topic-branch rules above; description links the issue). Issue and MR descriptions must include `Steps to Reproduce & Testing (QA)` (reproduce + how to test). On a bugfix, do not leave those placeholders empty. Do not cherry-pick to `staging` or `develop` unless the user named those branches this turn. Chat `setuju` is not propagate. Do not open three MRs. --- diff --git a/bench/sandbox/README.md b/bench/sandbox/README.md index 5d46f0b..d84fe79 100644 --- a/bench/sandbox/README.md +++ b/bench/sandbox/README.md @@ -22,6 +22,7 @@ Needs Docker, git and npm on the host. The `gh-logged-out` image downloads the ` | `no-identity` | Node + git | no `user.name` / `user.email` | | `gh-missing` | Node + git | GitHub remote, `gh` not installed | | `gh-logged-out` | Node + git + gh | GitHub remote, `gh` not logged in | +| `rework` | Node + git | code changed after Judge PASS: deliver refuses, `run --reopen`, loop again | | `cli-errors` | Node + git | typos, missing arguments, Run conflicts | | `empty-folder` | Node only | bare `ael` in an empty folder | | `host-stale` | Node + git | `~/.claude` exists, skill never installed | diff --git a/bench/sandbox/scenario.sh b/bench/sandbox/scenario.sh index 6d65ec4..c7b2d21 100755 --- a/bench/sandbox/scenario.sh +++ b/bench/sandbox/scenario.sh @@ -233,6 +233,25 @@ gh-missing|gh-logged-out) expect_out deliver-warns-adapter 'adapter-auth' ;; +rework) + # The delivered diff is the judged diff: drift after gate maker or after PASS + # is refused and names `run --reopen`, which re-runs the loop on the new diff. + identity; sample_app + c ael init; expect_rc init 0 + git add -A && git commit -qm ael-init + drive_to_pass + echo 'exports.boom = () => { throw new Error("unjudged"); };' >> src/math.js + git add -A src test && git commit -qm "add subtract" + c ael deliver --destination pr --summary "add subtract" --approve --by newbie; expect_rc_not0 deliver-refuses-unjudged; expect_out deliver-names-reopen 'run --reopen' + c ael gate maker --from-git; expect_rc_not0 maker-keeps-judged-diff; expect_out maker-names-reopen 'run --reopen' + c ael run --reopen --reason "boom after PASS" --json; expect_rc reopen 0; expect_out reopen-iteration '"iteration": ?2' + c ael gate maker --from-git; expect_rc gate-maker-2 0 + c ael verify; expect_rc verify-2 0; expect_out verify-2-state 'VERIFIED' + c ael review-pack --json; expect_rc review-pack-2 0 + c ael review ingest --child-id da-2 --file /tmp/da.json --json; expect_rc review-ingest-2 0; expect_out judged-pass-2 'JUDGED_PASS' + c ael deliver --destination pr --summary "add subtract" --approve --by newbie; expect_rc deliver-2 0; expect_out delivered 'DELIVERED' + ;; + cli-errors) identity; sample_app c ael int diff --git a/bin/ai-engineering-loop.js b/bin/ai-engineering-loop.js index 954df6e..21efdd6 100755 --- a/bin/ai-engineering-loop.js +++ b/bin/ai-engineering-loop.js @@ -1561,6 +1561,34 @@ function handleWorktree() { } } +// `run --reopen --run --reason [--by ] [--json]`: a Run +// between the Maker gate and delivery whose change must be reworked (e.g. test +// fixes for DA findings after the Judge passed) starts a new iteration. The +// gated diff, evidence, ledger, verdict and approval move to iterations//; +// every gate runs again on the new diff. +function handleRunReopen() { + const json = process.argv.includes('--json'); + try { + const target = argValue('--run') ? loadRun(CWD, argValue('--run')) : getCurrentRun(CWD); + if (!target) throw Object.assign(new Error('No current run to reopen.'), { code: 'INVALID_USAGE', why: 'Reopen works on an existing Run.', fix: '`ai-engineering-loop status` lists the Run; pass --run .' }); + const options = { reason: argValue('--reason'), actor: argValue('--by') || 'agent' }; + const result = target.workflow + ? require('../lib/workflow-runtime.js').reopenWorkflowRun(CWD, { runId: target.runId, ...options }) + : require('../lib/gates.js').reopenRun(CWD, target.runId, options); + const { run } = result; + appendRunLifecycle(CWD, run.runId, { type: 'PHASE_COMPLETED', phase: 'reopen', actor: options.actor, status: 'PASSED', message: `Run reopened for iteration ${run.iteration}: ${run.history.at(-1).reason}` }); + const next = `ai-engineering-loop gate maker --from-git --run ${run.runId}`; + if (json) console.log(JSON.stringify({ ok: true, runId: run.runId, state: run.state, iteration: run.iteration, from: target.state, archived: result.archiveDir, moved: result.moved, next })); + else { + log.success(`✓ Run ${run.runId} reopened (${target.state} -> ${run.state}), iteration ${run.iteration}`); + if (result.moved.length) console.log(`- Iteration ${target.iteration} evidence kept in ${result.archiveDir}: ${result.moved.join(', ')}`); + console.log(`- Next: \`${next}\`, then verify, Devil's Advocate, Judge and deliver again.`); + } + } catch (err) { + stageJsonError(err, json, 'REOPEN_FAILED'); + } +} + function handleRunAbandon() { const json = process.argv.includes('--json'); const yes = process.argv.includes('--yes'); @@ -1648,7 +1676,7 @@ function reproIntake() { return fromIssue ? issueRepro.readIssue(CWD, fromIssue) : issueRepro.readReportFile(CWD, fromReport); } -const RUN_FLAGS = new Set(['--new', '--json', '--worktree', '--abandon', '--yes', '--force-live', '--help', '-h']); +const RUN_FLAGS = new Set(['--new', '--json', '--worktree', '--abandon', '--reopen', '--yes', '--force-live', '--help', '-h']); const RUN_VALUED = ['--mode', '--recipe', '--tier', '--tier-reason', '--from-issue', '--from-report', '--run', '--reason', '--by', '--base']; function rejectUnknownRunFlags(runArgs) { @@ -1682,6 +1710,7 @@ function rejectUnknownRunFlags(runArgs) { function handleRun() { if (process.argv.includes('--abandon')) return handleRunAbandon(); + if (process.argv.includes('--reopen')) return handleRunReopen(); const runJson = process.argv.includes('--json'); try { rejectUnknownRunFlags(process.argv.slice(3)); @@ -2387,24 +2416,26 @@ function recordImpactDrift(runId) { function captureMakerDiff(run) { if (run.mode === 'UNATTENDED') throw new Error('--from-git is not allowed in UNATTENDED; use `sandbox capture`.'); require('../lib/git-readiness.js').assertGitReady(CWD); - const { execFileSync } = require('child_process'); - const exclude = ':(exclude).ai-engineering-loop'; - const git = (args, allowExit1 = false) => { - try { - return execFileSync('git', args, { cwd: CWD, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 }); - } catch (e) { - if (allowExit1 && e.status === 1) return e.stdout; - throw e; - } - }; - let diff = git(['diff', '--binary', 'HEAD', '--', '.', exclude]); - const aelOnlyIgnore = (file) => file === '.gitignore' && (readFileSafe(path.join(CWD, file)) || '').trim().replace(/\/+$/, '') === '.ai-engineering-loop'; - const untracked = git(['ls-files', '--others', '--exclude-standard', '-z', '--', '.', exclude]).split('\0').filter(Boolean).filter((file) => !aelOnlyIgnore(file)); - for (const file of untracked) diff += git(['diff', '--binary', '--no-index', '--', '/dev/null', file], true); - if (!diff.trim()) throw new Error('--from-git found no changes against HEAD.'); + const gates = require('../lib/gates.js'); + gates.assertMakerDiffWritable(run); + let capture; + try { + capture = require('../lib/change-diff.js').captureChangeDiff(CWD, run); + } catch (err) { + if (err.code !== 'BASE_REVISION_MISSING') throw err; + throw Object.assign(err, { code: 'GATE_FAILED', why: 'The Maker diff is measured from the commit the Run started on.', fix: `Fetch or restore commit ${String(run.startedRevision).slice(0, 12)}, then retry; or start a new Run.` }); + } + if (!capture.text.trim()) { + const base = capture.base.source === 'startedRevision' ? `the Run's starting commit ${capture.base.revision.slice(0, 12)}` : 'HEAD'; + throw Object.assign(new Error(`--from-git found no changes against ${base}.`), { + code: 'GATE_FAILED', + why: 'The Maker gate binds review to the change since the Run started (committed or not), and there is none.', + fix: `Make the change first (files outside .ai-engineering-loop/), then \`gate maker --from-git --run ${run.runId}\`.` + }); + } const target = path.join(CWD, '.ai-engineering-loop', 'runs', run.runId, 'diff.patch'); - fs.writeFileSync(target, diff); - return { path: path.relative(CWD, target).split(path.sep).join('/'), files: untracked.length }; + fs.writeFileSync(target, capture.text); + return { path: path.relative(CWD, target).split(path.sep).join('/'), files: capture.untracked.length }; } function reviewLedgerBinding(run) { @@ -2473,7 +2504,7 @@ function handleGate() { } } } catch (err) { - const retryHint = targetRunId && gate && err.code === 'GATE_FAILED' + const retryHint = targetRunId && gate && err.code === 'GATE_FAILED' && !(gate === 'maker' && String(err.fix || '').includes('run --reopen')) ? `After correcting the reported issue, retry: npx ai-engineering-loop gate ${gate} --run ${targetRunId}` : null; const details = [...(err.details || []), ...(retryHint ? [retryHint] : [])]; @@ -4223,6 +4254,9 @@ async function handleVerify() { if (!result.ok) process.exitCode = 1; return; } + // The working tree must still be the gated diff; otherwise the evidence + // would be bound to code nobody verifies or reviews. + require('../lib/gates.js').assertNoDiffDrift(CWD, loadRun(CWD, runId), 'verify'); if (final) { const target = loadRun(CWD, runId); if (target.state !== 'JUDGED_PASS') throw Object.assign(new Error(`verify --final needs a Judge PASS (state is ${target.state})`), { code: 'INVALID_STATE' }); @@ -5378,6 +5412,9 @@ Commands: --abandon [--run ] --reason --by [--yes] [--force-live] [--json] close a stale run as CANCELLED (kept on disk) and release current.json; ASSISTED asks to confirm, UNATTENDED needs --yes from a human + --reopen [--run ] --reason [--by ] [--json] + rework a gated change (e.g. test fixes after Judge PASS): new iteration, + gated diff and evidence move to iterations//, every gate runs again state Inspect the current run ledger --run target a non-current run --json print the complete machine-readable ledger diff --git a/core/iteration-policy.md b/core/iteration-policy.md index 88b48c5..e4bc831 100644 --- a/core/iteration-policy.md +++ b/core/iteration-policy.md @@ -111,3 +111,16 @@ To maintain continuity across sub-agent calls or tool invocations, each iteratio 3. **Cumulative Code Diff**: Total changes relative to base branch. 4. **Deterministic Run Results**: Exit codes and timestamped test outcomes. 5. **No-Progress Hash**: Signatures of active findings for stagnation detection. + +--- + +## 6. Rework after the Maker gate (`run --reopen`) + +The change sometimes has to move after its diff is gated: test fixes for Devil's Advocate findings after the Judge passed, or a fix during verification. The gated diff is bound by hash to the verification evidence, the Finding Ledger, the verdict and the delivery receipt, so a new diff needs all of them again. + +- `gate maker --from-git` only writes `diff.patch` while the Run is `GOAL_FROZEN`. From `MAKER_COMPLETE`, `VERIFIED`, `REVIEWED` or `JUDGED_PASS` it refuses, leaves the judged `diff.patch` untouched, and its `fix` names the reopen command. +- `ai-engineering-loop run --reopen --run --reason "" [--by ] [--json]` moves the Run back to `GOAL_FROZEN` as iteration N+1. `diff.patch`, `verification*.json`, `findings.json`, `verdict.json`, `delivery.json` and the receipt move to `runs//iterations//`; the matching state artifacts are dropped. In a workflow Run the Maker node and every node after it (verification, review, Judge, delivery approval, delivery) reset to PENDING. The history entry is `run-reopen` with the reason and the state it left. +- Then run the loop again: `gate maker --from-git`, `verify`, a fresh Devil's Advocate, Judge, human approval, `deliver`. Delivery checks the new diff hash, so the delivered diff is always the judged diff. +- The Run's change is everything between `startedRevision` (the commit the Run started on) and the working tree, committed or not, plus untracked files, excluding `.ai-engineering-loop/`. `gate maker --from-git` captures that, so a change committed before the Maker gate is still captured. +- `verify`, `gate verification` and `gate delivery` compare the Run's change with the gated `diff.patch` and refuse with `DIFF_DRIFT` (naming each file and `run --reopen`) when they differ. The comparison keeps only what changed per file (added and removed lines, modes, binary data), so the same change committed, staged or untracked still matches. Untracked files the gated diff does not name are left to the clean-state check until they are committed. UNATTENDED Runs, whose diff comes from `sandbox capture`, are not compared. If `startedRevision` is no longer in the repository the gates refuse and say so. +- Reopen is refused (with `why`/`fix`) before the Maker gate and on finished Runs (`DELIVERED`, `ESCALATED`, `REPORTED`, `CANCELLED`). It needs `--reason`. It never skips a gate, so agents use it instead of `run --abandon`. diff --git a/lib/change-diff.js b/lib/change-diff.js new file mode 100644 index 0000000..81bc797 --- /dev/null +++ b/lib/change-diff.js @@ -0,0 +1,144 @@ +'use strict'; + +// The Run's change as git sees it: everything between the Run's starting +// revision and the working tree (committed or not), plus untracked files, +// excluding .ai-engineering-loop/. `gate maker --from-git` writes it to +// diff.patch; `verify`, `gate verification` and `gate delivery` compare it with +// the gated diff.patch so the code that is verified, reviewed, judged and +// delivered is the same change. + +const fs = require('fs'); +const path = require('path'); +const { execFileSync } = require('child_process'); + +const EXCLUDE = ':(exclude).ai-engineering-loop'; + +function git(rootDir, args, allowExit1 = false) { + try { + return execFileSync('git', args, { cwd: rootDir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], maxBuffer: 64 * 1024 * 1024 }); + } catch (err) { + if (allowExit1 && err.status === 1) return err.stdout; + throw err; + } +} + +function isGitWorkTree(rootDir) { + try { + return git(rootDir, ['rev-parse', '--is-inside-work-tree']).trim() === 'true'; + } catch { + return false; + } +} + +// The base the change is measured from: the Run's starting revision when git +// still knows it, else HEAD (legacy Runs without one). +function changeBase(rootDir, run) { + const started = String(run?.startedRevision || ''); + if (/^[0-9a-f]{7,64}$/.test(started)) { + try { + git(rootDir, ['cat-file', '-e', `${started}^{commit}`]); + return { revision: started, source: 'startedRevision' }; + } catch { + return { revision: started, source: 'missing' }; + } + } + return { revision: 'HEAD', source: 'HEAD' }; +} + +function readFileSafe(file) { + try { + return fs.readFileSync(file, 'utf8'); + } catch { + return null; + } +} + +// { text, untracked: [paths], base } +function captureChangeDiff(rootDir, run) { + const base = changeBase(rootDir, run); + if (base.source === 'missing') { + const err = new Error(`The Run's starting revision ${base.revision.slice(0, 12)} is not in this repository`); + err.code = 'BASE_REVISION_MISSING'; + throw err; + } + let text = git(rootDir, ['diff', '--binary', base.revision, '--', '.', EXCLUDE]); + const aelOnlyIgnore = (file) => file === '.gitignore' + && (readFileSafe(path.join(rootDir, file)) || '').trim().replace(/\/+$/, '') === '.ai-engineering-loop'; + const untracked = git(rootDir, ['ls-files', '--others', '--exclude-standard', '-z', '--', '.', EXCLUDE]) + .split('\0').filter(Boolean).filter((file) => !aelOnlyIgnore(file)); + for (const file of untracked) text += git(rootDir, ['diff', '--binary', '--no-index', '--', '/dev/null', file], true); + return { text, untracked, base }; +} + +// path -> canonical change text. Keeps only what the change does (mode +// lines, binary payloads, added and removed lines), so the same change +// compares equal whether it is committed, staged, untracked, or written with +// a different context size. +function normalizeDiff(text) { + const files = new Map(); + let current = null; + let binary = false; + const pathOf = (header) => { + const match = /^diff --git a\/(.+?) b\/(.+)$/.exec(header); + return match ? match[2] : header; + }; + for (const line of String(text || '').split('\n')) { + if (line.startsWith('diff --git ')) { + current = { path: pathOf(line), lines: [] }; + files.set(current.path, current); + binary = false; + continue; + } + if (!current) continue; + if (line.startsWith('+++ ')) { + const target = line.slice(4).replace(/^b\//, ''); + if (target !== '/dev/null' && target !== current.path) { + files.delete(current.path); + current.path = target; + files.set(target, current); + } + continue; + } + if (line.startsWith('--- ') || line.startsWith('index ') || line.startsWith('@@')) continue; + if (line === 'GIT binary patch') { + binary = true; + current.lines.push(line); + continue; + } + if (binary) { + if (line.trim()) current.lines.push(line); + continue; + } + if (/^(new file mode|deleted file mode|old mode|new mode|rename from|rename to|Binary files) /.test(line)) { + current.lines.push(line); + continue; + } + if (line.startsWith('+') || line.startsWith('-')) current.lines.push(line); + } + const result = new Map(); + for (const [file, entry] of files) result.set(file, entry.lines.join('\n')); + return result; +} + +// null when there is nothing to compare (no git, no gated diff, UNATTENDED +// whose diff comes from the sandbox); otherwise { changed: [paths], base }. +// Untracked files the gated diff does not name are left to the clean-state +// check: people keep scratch files, and committing one makes it tracked, so +// it is compared then. +function diffDrift(rootDir, run) { + const gated = run?.artifacts?.diff?.path; + if (!gated || run.mode === 'UNATTENDED' || !isGitWorkTree(rootDir)) return null; + const judged = normalizeDiff(readFileSafe(path.join(rootDir, gated)) || ''); + const capture = captureChangeDiff(rootDir, run); + const current = normalizeDiff(capture.text); + const untracked = new Set(capture.untracked); + const changed = []; + for (const [file, body] of current) { + if (!judged.has(file) && untracked.has(file)) continue; + if (judged.get(file) !== body) changed.push(file); + } + for (const file of judged.keys()) if (!current.has(file)) changed.push(file); + return { changed: [...new Set(changed)].sort(), base: capture.base }; +} + +module.exports = { EXCLUDE, changeBase, captureChangeDiff, normalizeDiff, diffDrift, isGitWorkTree }; diff --git a/lib/cli-args.js b/lib/cli-args.js index 357bd29..f39fd80 100644 --- a/lib/cli-args.js +++ b/lib/cli-args.js @@ -20,6 +20,8 @@ const WRITER_COMMANDS = Object.freeze({ projects: { flags: ['--json'], valued: ['--root', '--depth'], positionals: null }, // `run --abandon` (issue #46) is a writer; plain `run` takes free text. 'run:abandon': { flags: ['--abandon', '--yes', '--json', '--force-live'], valued: ['--run', '--reason', '--by'], positionals: [] }, + // `run --reopen` starts a new iteration of a gated Run (post-PASS rework). + 'run:reopen': { flags: ['--reopen', '--json'], valued: ['--run', '--reason', '--by'], positionals: [] }, bench: { flags: ['--json', '--sandbox-home'], valued: ['--host', '--model', '--scenario', '--repeat', '--bin', '--mode', '--timeout', '--host-arg', '--without'], @@ -63,6 +65,7 @@ function beforeSeparator(args) { // `run --abandon ...` is checked as its own writer command. function effectiveCommand(command, rest) { if (command === 'run' && beforeSeparator(rest).includes('--abandon')) return 'run:abandon'; + if (command === 'run' && beforeSeparator(rest).includes('--reopen')) return 'run:reopen'; if (command === 'bench' && beforeSeparator(rest)[0] === 'compare') return 'bench:compare'; return command; } diff --git a/lib/gates.js b/lib/gates.js index 24646fc..05ff8b4 100644 --- a/lib/gates.js +++ b/lib/gates.js @@ -40,7 +40,8 @@ const { getGitRevision, loadRun, runsDir, - transitionRun + transitionRun, + REOPENABLE_STATES } = require('./run-state.js'); const { assertModeAllowed @@ -116,7 +117,10 @@ function assertArtifactCurrent(rootDir, run, name) { } const filePath = path.join(rootDir, artifact.path); if (hashFile(filePath) !== artifact.sha256) { - throw gateError(`${name} artifact changed after its gate; rerun the owning stage`, [], { why: 'Gated artifacts are frozen by hash; a silent edit would invalidate later evidence.', fix: `Re-run the stage that owns ${name}, or restore the gated version.` }); + const nextStep = REOPENABLE_STATES.has(run.state) + ? `Restore the gated ${name}, or rework the change in a new iteration: \`${reopenCommand(run.runId)}\`, then \`gate maker --from-git --run ${run.runId}\`.` + : `Re-run the stage that owns ${name}, or restore the gated version.`; + throw gateError(`${name} artifact changed after its gate; rerun the owning stage`, [], { why: 'Gated artifacts are frozen by hash; a silent edit would invalidate later evidence.', fix: nextStep }); } } @@ -576,6 +580,120 @@ function archiveIterationEvidence(rootDir, run) { } } +// `run --reopen` (post-PASS rework): the change must be reworked after the +// Maker gate, e.g. test fixes for Devil's Advocate findings after the Judge +// passed. The Run goes back to GOAL_FROZEN as a new iteration; the gated diff, +// evidence, ledger, verdict and delivery approval move to iterations// and +// must all be earned again, so the delivered diff is always the judged diff. +const REOPEN_ARCHIVE = [...ITERATION_EVIDENCE, GATE_FILES.review, GATE_FILES.judge, GATE_FILES.maker, GATE_FILES.delivery, 'receipt.json', 'receipt.md']; +const REOPEN_DROPS = ['diff', 'sandboxEvidence', 'verification', 'findings', 'verdict', 'delivery']; + +function reopenCommand(runId) { + return `ai-engineering-loop run --reopen --run ${runId} --reason ""`; +} + +// `gate maker --from-git` writes diff.patch; only a Run waiting for its Maker +// diff may have it overwritten. Called before anything is written. +function assertMakerDiffWritable(run) { + if (run.state === RUN_STATES.GOAL_FROZEN) return; + if (REOPENABLE_STATES.has(run.state)) { + throw gateError(`Maker diff is already gated (${run.state}); diff.patch was not overwritten`, [], { + why: 'Verification, review and the Judge are bound to the gated diff hash. A changed working tree needs a new iteration so the delivered diff is the judged diff.', + fix: `Run \`${reopenCommand(run.runId)}\`, then \`gate maker --from-git --run ${run.runId}\`.` + }); + } + if (run.state === RUN_STATES.STARTED) { + throw gateError('Maker gate needs a frozen Goal Contract; diff.patch was not written', [], { + why: 'The Maker diff is reviewed against frozen acceptance criteria.', + fix: `Freeze the Goal first: \`ai-engineering-loop goal freeze --latest --run ${run.runId} --by \`.` + }); + } + throw gateError(`Run ${run.runId} is ${run.state}; diff.patch was not overwritten`, [], { + why: 'A finished Run keeps its gated diff as the record of what was delivered or decided.', + fix: 'Start a new Run for further changes: `ai-engineering-loop run ""`.' + }); +} + +function reopenPlan(rootDir, runId, { reason, actor = 'agent' } = {}) { + const run = resolveRun(rootDir, runId); + const cleanReason = String(reason || '').trim(); + if (!cleanReason || cleanReason.length > 500) { + throw gateError('run --reopen needs --reason (1-500 characters)', [], { + why: 'The reason is the record of why the judged change was reworked.', + fix: reopenCommand(run.runId) + }); + } + if (!REOPENABLE_STATES.has(run.state)) { + const nextStep = run.state === RUN_STATES.GOAL_FROZEN + ? `Nothing to reopen: make the change, then \`gate maker --from-git --run ${run.runId}\`.` + : (run.state === RUN_STATES.STARTED + ? `Freeze the Goal and finish the Maker first: \`ai-engineering-loop status\` shows the next step.` + : 'Start a new Run for further changes: `ai-engineering-loop run ""`.'); + throw gateError(`Run ${run.runId} is ${run.state}; only a Run between the Maker gate and delivery can be reopened`, [], { + why: 'Reopen starts a new iteration for a gated change; a Run without a gated diff, or a finished Run, has none to rework.', + fix: nextStep + }); + } + return { run, reason: cleanReason, actor }; +} + +function archiveForReopen(rootDir, run) { + const runDir = path.join(runsDir(rootDir), run.runId); + const target = path.join(runDir, 'iterations', String(run.iteration || 1)); + const moved = []; + for (const name of REOPEN_ARCHIVE) { + const from = path.join(runDir, name); + if (!fs.existsSync(from)) continue; + fs.mkdirSync(target, { recursive: true, mode: 0o700 }); + fs.renameSync(from, path.join(target, name)); + moved.push(name); + } + return { archiveDir: path.relative(rootDir, target).split(path.sep).join('/'), moved }; +} + +function reopenTransition(plan) { + return { + gate: 'run-reopen', + reason: plan.reason, + reopen: true, + incrementIteration: true, + dropArtifacts: REOPEN_DROPS, + historyMetadata: { actor: plan.actor, reopenedFrom: plan.run.state } + }; +} + +// The code being verified or delivered must be the gated (and, at delivery, +// judged) diff. Compares the Run's change (startedRevision..working tree, +// committed or not) with diff.patch; see lib/change-diff.js. +function assertNoDiffDrift(rootDir, run, stage) { + let drift; + try { + drift = require('./change-diff.js').diffDrift(rootDir, run); + } catch (cause) { + if (cause.code !== 'BASE_REVISION_MISSING') throw cause; + throw gateError(`${stage} refused: ${cause.message}`, [], { + why: 'The change is measured from the commit the Run started on; without it AEL cannot prove the code matches the gated diff.', + fix: `Fetch or restore commit ${String(run.startedRevision).slice(0, 12)} (e.g. \`git fetch\`), then retry; or start a new Run: \`ai-engineering-loop run ""\`.` + }); + } + if (!drift || !drift.changed.length) return; + const shown = drift.changed.slice(0, 10); + throw gateError(`${stage} refused: the code differs from the gated diff.patch (DIFF_DRIFT)`, + [...shown.map((file) => `${file}: changed since \`gate maker\``), ...(drift.changed.length > shown.length ? [`... ${drift.changed.length - shown.length} more`] : [])], + { + why: 'Verification, the Devil\'s Advocate and the Judge are bound to the gated diff. Code that changed after `gate maker` (committed or not) was never verified or reviewed.', + fix: `Run \`${reopenCommand(run.runId)}\`, then \`gate maker --from-git --run ${run.runId}\` and the loop again. Or restore the gated code.` + }); +} + +// Non-workflow Runs; workflow Runs use workflow-runtime.reopenWorkflowRun. +function reopenRun(rootDir, runId, options = {}) { + const plan = reopenPlan(rootDir, runId, options); + const archived = archiveForReopen(rootDir, plan.run); + const run = transitionRun(rootDir, plan.run.runId, RUN_STATES.GOAL_FROZEN, reopenTransition(plan)); + return { run, ...archived }; +} + function applyGate(rootDir, gate, { runId, transitionOptions = {} } = {}) { if (!Object.hasOwn(GATE_FILES, gate)) { throw gateError(`Unknown gate: ${gate}. Use ${Object.keys(GATE_FILES).join('|')}`, [], { why: 'Only the listed stages exist.', fix: `Use one of: ${Object.keys(GATE_FILES).join(', ')}.` }); @@ -669,8 +787,9 @@ function applyGate(rootDir, gate, { runId, transitionOptions = {} } = {}) { const diffPath = artifactPath(rootDir, run.runId, GATE_FILES.maker); const diffHash = hashFile(diffPath); if (run.artifacts.diff?.sha256 !== diffHash) { - throw gateError('Maker diff changed after its gate; run the Maker gate again', [], { why: 'Verification evidence is bound to the gated diff hash; a new diff needs new evidence.', fix: 'Run `gate maker --from-git --run `, then `verify` again.' }); + throw gateError('Maker diff changed after its gate; start a new iteration', [], { why: 'Verification evidence is bound to the gated diff hash; a new diff needs new evidence.', fix: `Run \`${reopenCommand(run.runId)}\`, then \`gate maker --from-git --run ${run.runId}\` and \`verify\` again.` }); } + assertNoDiffDrift(rootDir, run, 'Verification gate'); const { filePath, value } = readJsonArtifact(rootDir, run.runId, GATE_FILES.verification); const check = validateVerificationBundle(value, run, diffHash, getGitRevision(rootDir)); if (!check.valid) throw gateError('Verification gate failed', check.errors, { why: 'Review only starts on green, diff-bound, complete command evidence.', fix: 'Fix the listed problems (re-run `verify` on the current diff), then retry.' }); @@ -817,6 +936,7 @@ function applyGate(rootDir, gate, { runId, transitionOptions = {} } = {}) { assertArtifactCurrent(rootDir, run, 'verification'); assertArtifactCurrent(rootDir, run, 'findings'); assertArtifactCurrent(rootDir, run, 'verdict'); + assertNoDiffDrift(rootDir, run, 'Delivery gate'); const { filePath, value } = readJsonArtifact(rootDir, run.runId, GATE_FILES.delivery); requireRunMetadata(value, run, 'delivery'); const deliveryErrors = []; @@ -866,5 +986,12 @@ module.exports = { validateVerdictDocument, judgeRequirement, expectedJudgeVerdict, - applyGate + applyGate, + reopenCommand, + assertMakerDiffWritable, + assertNoDiffDrift, + reopenPlan, + archiveForReopen, + reopenTransition, + reopenRun }; diff --git a/lib/run-state.js b/lib/run-state.js index e328192..c4a2b3d 100644 --- a/lib/run-state.js +++ b/lib/run-state.js @@ -38,6 +38,11 @@ const ALLOWED_TRANSITIONS = Object.freeze({ CANCELLED: [] }); +// `run --reopen`: a Run between the Maker gate and delivery may go back to +// GOAL_FROZEN for a new iteration when its change must be reworked (e.g. test +// fixes after the Judge passed). Only the reopen command passes `reopen: true`. +const REOPENABLE_STATES = new Set(['MAKER_COMPLETE', 'VERIFIED', 'REVIEWED', 'JUDGED_PASS']); + const TERMINAL_STATES = new Set([ RUN_STATES.REPORTED, RUN_STATES.DELIVERED, @@ -398,6 +403,7 @@ function transitionRunLocked( statePatch = {}, historyMetadata = {}, dropArtifacts = [], + reopen = false, now = new Date() } = {} ) { @@ -407,7 +413,8 @@ function transitionRunLocked( err.code = 'UNKNOWN_RUN_STATE'; throw err; } - if (!ALLOWED_TRANSITIONS[run.state].includes(to)) { + const reopening = reopen === true && to === RUN_STATES.GOAL_FROZEN && REOPENABLE_STATES.has(run.state); + if (!reopening && !ALLOWED_TRANSITIONS[run.state].includes(to)) { const err = new Error(`Invalid transition: ${run.state} -> ${to}`); err.code = 'INVALID_TRANSITION'; throw err; @@ -451,6 +458,7 @@ module.exports = { RUN_MODES, ALLOWED_TRANSITIONS, TERMINAL_STATES, + REOPENABLE_STATES, runsDir, assertRunId, runStatePath, diff --git a/lib/workflow-runtime.js b/lib/workflow-runtime.js index b94d66f..f8495c9 100644 --- a/lib/workflow-runtime.js +++ b/lib/workflow-runtime.js @@ -1129,6 +1129,45 @@ function cancelWorkflowRun( }); } +// `run --reopen`: the Run goes back to GOAL_FROZEN as a new iteration. The +// Maker node and everything after it (verification, review, Judge, delivery +// approval and delivery) are reset, so each gate runs again on the new diff. +function reopenWorkflowRun(rootDir, { runId, reason, actor = 'agent', now = new Date() } = {}) { + const resolved = resolveRunId(rootDir, runId); + if (!ACTOR_ID.test(String(actor))) { + throw runtimeError('Reopen actor must be a short account identifier', 'INVALID_RUN_ACTOR'); + } + return withWorkflowLock(rootDir, resolved, () => { + let workflow = loadWorkflow(rootDir, resolved); + const gates = require('./gates.js'); + const plan = gates.reopenPlan(rootDir, resolved, { reason: redactSecrets(String(reason || '')).text, actor: String(actor) }); + const maker = workflow.plan.nodes.find((node) => node.legacyGate === 'maker'); + if (!maker) throw runtimeError('Workflow has no Maker node', 'GATE_NOT_IN_WORKFLOW'); + const archived = gates.archiveForReopen(rootDir, plan.run); + workflow.run = transitionRun(rootDir, resolved, RUN_STATES.GOAL_FROZEN, { ...gates.reopenTransition(plan), now }); + let changes = []; + for (const nodeId of descendants(workflow.plan, maker.id)) { + const current = workflow.state.nodes[nodeId]; + const replacement = { + status: NODE_STATES.PENDING, + attempts: current.attempts, + reason: 'reset by run --reopen', + activity: null, + ...(current.loopGroupId ? { loopGroupId: current.loopGroupId, loopIteration: current.loopIteration } : {}), + updatedAt: now.toISOString() + }; + workflow.state.nodes[nodeId] = replacement; + changes.push({ nodeId, from: current.status, node: replacement }); + } + const loopChanges = (workflow.plan.loopGroups || []) + .filter((group) => (group.nodeIds || []).includes(maker.id) && workflow.state.loopGroups[group.id]?.status === 'EXITED') + .map((group) => loopChange(workflow, group.id, { status: 'RUNNING' }, now)); + changes = changes.concat(refreshNodes(workflow.plan, workflow.state, workflow.run)); + workflow = commitChanges(rootDir, workflow, 'RUN_REOPENED', changes, { actor: plan.actor, reason: plan.reason }, now, true, loopChanges); + return { run: workflow.run, workflow, ...archived }; + }); +} + function unfreezeWorkflowGoal(rootDir, { runId, transitionOptions, now = new Date() } = {}) { const resolved = resolveRunId(rootDir, runId); return withWorkflowLock(rootDir, resolved, () => { @@ -1206,6 +1245,7 @@ module.exports = { loadWorkflow, workflowStatus, cancelWorkflowRun, + reopenWorkflowRun, unfreezeWorkflowGoal, startWorkflowExecution, startWorkflowNode, diff --git a/schemas/workflow-event.schema.json b/schemas/workflow-event.schema.json index 596d152..084fbbc 100644 --- a/schemas/workflow-event.schema.json +++ b/schemas/workflow-event.schema.json @@ -27,6 +27,7 @@ "LOOP_LIMIT_EXITED", "LOOP_RUN_STOPPED", "GOAL_UNFROZEN", + "RUN_REOPENED", "WORKFLOW_EXECUTION_STARTED" ] }, diff --git a/scripts/sandbox-e2e.sh b/scripts/sandbox-e2e.sh index 0a335db..beba912 100755 --- a/scripts/sandbox-e2e.sh +++ b/scripts/sandbox-e2e.sh @@ -26,7 +26,7 @@ scenario_image() { *) echo git ;; esac } -ALL=(happy quick no-git non-git-folder no-commit no-identity gh-missing gh-logged-out cli-errors empty-folder host-stale old-node registry) +ALL=(happy quick no-git non-git-folder no-commit no-identity gh-missing gh-logged-out rework cli-errors empty-folder host-stale old-node registry) REF="" SOURCE=tarball diff --git a/skill-src/ael/references/loop-deliver.md b/skill-src/ael/references/loop-deliver.md index ba39f5f..2390370 100644 --- a/skill-src/ael/references/loop-deliver.md +++ b/skill-src/ael/references/loop-deliver.md @@ -1,14 +1,14 @@ # Stage 8: Delivery - After Judge PASS (and `verify --final` if verification was `--related`), run the `after_pass` hook, then the Stage 8 adapter from `.ai-engineering-loop/adapter.md`. -- Before any push, run `npx ai-engineering-loop doctor`: `✗ adapter-*` (unknown `adapter_type`, missing spec) must be fixed; `! adapter-*` (gh/glab not logged in, configured type differs from the detected one) needs a human look. `deliver` repeats this check: UNATTENDED stops before writing, ASSISTED only warns. +- Code changed after PASS: `run --reopen --run --reason `, then redo the loop. Never abandon. +- Before any push, run `npx ai-engineering-loop doctor`: `✗ adapter-*` (unknown `adapter_type`, missing spec) must be fixed; `! adapter-*` (gh/glab logged out, configured type differs from detected) needs a human look. `deliver` repeats this check: UNATTENDED stops before writing, ASSISTED only warns. - The PR/MR body includes `Steps to Reproduce & Testing (QA)`; bugfix placeholders must not stay empty. Disclose any `budget record --unavailable`. - Preview remote payloads; never include context packs, usage ledgers, raw logs, or credentials. - ASSISTED: never infer approval. When the human says yes, record it at once: `npx ai-engineering-loop deliver --run --approve --by `. After commit, push and PR/MR, finish with `deliver --run --destination --summary --approve --by ` (writes `delivery.json` with `humanApproved: true`, runs `gate delivery`). -- Long form: `node status --run `, `node approve delivery-approval --yes --by --run ` for each READY approval node, write `RUN_DIR/delivery.json`, then `gate delivery`. If the gate says a node is not READY, follow its prerequisite hint; never bypass approval. +- Long form: `node status --run `, `node approve delivery-approval --yes --by --run ` for each READY approval node, write `RUN_DIR/delivery.json`, then `gate delivery`. Node not READY: follow its prerequisite hint; never bypass approval. - Commit before `deliver` (its receipt binds `HEAD`; videos/screenshots: `--evidence AC-N=`, required for `crossComponent` and rubric ACs). Paste `RUN_DIR/receipt.md` into the PR/MR Receipt section unchanged; ❌ stays ❌ (`docs pr-receipt`). -- Only the delivery gate completes the run. It also mines lessons for the next Run. -- Worktree Run: after `deliver`, continue in `cleanup.mainCheckout` (Stage 9). +- Only the delivery gate completes the run. Worktree Run: then continue in `cleanup.mainCheckout`. - After the PR is open, `npx ai-engineering-loop pr babysit --run ` polls with backoff. Failing checks start a T0 or T1 fix on that same branch and push it. Ready to merge, or changes requested, stops for a human. Merge stays with the human (`docs run-isolation`). ## Report header (execution mode) diff --git a/skill-src/ael/references/loop-judge.md b/skill-src/ael/references/loop-judge.md index 902b861..e411d06 100644 --- a/skill-src/ael/references/loop-judge.md +++ b/skill-src/ael/references/loop-judge.md @@ -6,6 +6,7 @@ Read when `gate review` says `judgeRequired`, on T2, or when acting on findings. - Judge context: only run-summary.md, verification-summary.json (or verification.json), open-findings.json/findings.json, and the Goal hash; it reads the full diff only if those contradict each other. Judge prompt includes "at most 4 tool calls; ledger and contract only; skip css; do not re-review the whole diff". - Spawn a fresh sibling Judge, wait, `budget record`, write `RUN_DIR/verdict.json` with `modelTier` and any `judgeFindings`, then `gate judge`. A gate failure overrides optimistic prose. - ITERATE under the recipe cap: fix in the parent, re-verify, spawn a **new** DA (never resume the previous child). At the cap or NO_PROGRESS, ESCALATE to the human. +- Code changed after PASS (DA fixes, test fixes): `run --reopen --run --reason ` starts a new iteration; `gate maker` refuses to overwrite a judged diff (`docs iteration-policy`). ## Acting on findings (DA during ITERATE, or human MR/PR comments) diff --git a/tests/dot-no-auto-close.test.js b/tests/dot-no-auto-close.test.js new file mode 100644 index 0000000..76ff56f --- /dev/null +++ b/tests/dot-no-auto-close.test.js @@ -0,0 +1,46 @@ +'use strict'; + +// DOT delivery must never close the card. GitLab closes an issue on merge to +// the default branch when a commit message or MR description says +// "Closes #n", "Fixes #n", "Resolves #n" or "Implements #n". The DOT adapter +// moves the card to "Ready to review" and leaves closing to humans. + +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('fs'); +const path = require('path'); + +const ROOT = path.join(__dirname, '..'); +const DOT = path.join(ROOT, 'adapters/dot'); +const read = (rel) => fs.readFileSync(path.join(ROOT, rel), 'utf8').replace(/\r\n?/g, '\n'); + +function markdownFiles(dir) { + return fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = path.join(dir, entry.name); + if (entry.isDirectory()) return markdownFiles(full); + return entry.name.endsWith('.md') ? [full] : []; + }); +} + +// GitLab's default closing pattern, followed by an issue reference, an issue +// URL, or a template placeholder an agent would fill with one. +const CLOSING = /\b(?:clos(?:e[sd]?|ing)|fix(?:e[sd]|ing)?|resolv(?:e[sd]?|ing)|implement(?:s|ed|ing)?):? +(?:issues? +)?(?:[\w.\/-]*#\d|#<|<|https?:\/\/\S*\/issues\/)/i; + +test('no DOT template or example uses a GitLab closing keyword', () => { + const hits = []; + for (const file of markdownFiles(DOT)) { + const lines = fs.readFileSync(file, 'utf8').split(/\r?\n/); + lines.forEach((line, i) => { + if (CLOSING.test(line)) hits.push(`${path.relative(ROOT, file)}:${i + 1}: ${line.trim()}`); + }); + } + assert.deepStrictEqual(hits, [], `closing keywords would auto-close the card on merge:\n${hits.join('\n')}`); +}); + +test('gitlab.md and the DOT workflow skill forbid closing the card', () => { + for (const rel of ['adapters/dot/gitlab.md', 'adapters/dot/skills/dot-dev-workflow/SKILL.md']) { + const text = read(rel); + assert.match(text, /never closes the card/i, `${rel}: states the no-close rule`); + assert.match(text, /`Refs #`/, `${rel}: names the safe reference form`); + } +}); diff --git a/tests/rework-after-pass.test.js b/tests/rework-after-pass.test.js new file mode 100644 index 0000000..daa088d --- /dev/null +++ b/tests/rework-after-pass.test.js @@ -0,0 +1,228 @@ +'use strict'; + +// The delivered diff is the judged diff. +// A Run at JUDGED_PASS whose working tree changes afterwards (for example test +// fixes for Devil's Advocate findings) must not get stuck. `gate maker +// --from-git` refuses to overwrite the judged diff and names `run --reopen`, +// which starts a new iteration so the new diff is verified, reviewed and +// judged before delivery. The judged diff hash stays the delivered diff hash. + +const test = require('node:test'); +const assert = require('node:assert'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const crypto = require('crypto'); +const { spawnSync, execFileSync } = require('child_process'); + +const CLI = path.join(__dirname, '..', 'bin', 'ai-engineering-loop.js'); + +function setupRepo() { + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ael-rework-home-')); + const repo = fs.mkdtempSync(path.join(os.tmpdir(), 'ael-rework-')); + const env = { ...process.env, HOME: home, USERPROFILE: home, AEL_HOME: home, AEL_GOAL_FREEZE_OK: '1' }; + const git = (...args) => execFileSync('git', args, { cwd: repo, stdio: 'pipe', encoding: 'utf8' }); + const commit = (message) => { + git('add', '-A'); + git('-c', 'user.email=a@b.c', '-c', 'user.name=t', 'commit', '-qm', message, '--allow-empty'); + }; + git('init', '-q'); + fs.mkdirSync(path.join(repo, 'src')); + fs.writeFileSync(path.join(repo, 'src/list.js'), 'module.exports = (items) => items.slice(0, 10);\n'); + fs.writeFileSync(path.join(repo, 'package.json'), '{"name":"demo","scripts":{"test":"node --version"}}\n'); + commit('init'); + const cli = (...args) => spawnSync(process.execPath, [CLI, ...args], { cwd: repo, env, encoding: 'utf8' }); + assert.strictEqual(cli('init').status, 0); + commit('ctx'); + return { repo, cli, commit }; +} + +function ok(result, label) { + assert.strictEqual(result.status, 0, `${label}: ${result.stdout}\n${result.stderr}`); + return result; +} + +const sha256 = (file) => crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex'); +const readState = (runDir) => JSON.parse(fs.readFileSync(path.join(runDir, 'state.json'), 'utf8')); + +// maker (from git) -> verify -> empty ledger -> review -> judge. +function makeAndJudge({ repo, cli }, runId, runDir) { + ok(cli('gate', 'maker', '--from-git', '--run', runId), 'gate maker --from-git'); + ok(cli('verify', '--run', runId, '--cmd', 'node --version', '--json'), 'verify'); + fs.writeFileSync( + path.join(repo, '.ai-engineering-loop/tasks/claimed-vs-reality.md'), + '| AC | Claimed | Reality from command log |\n|---|---|---|\n| AC-1 | paginated | node --version exit 0 |\n' + ); + const diffHash = readState(runDir).artifacts.diff.sha256; + fs.writeFileSync(path.join(runDir, 'findings.json'), JSON.stringify({ schemaVersion: 1, runId, diffHash, findings: [] })); + ok(cli('gate', 'review', '--run', runId, '--json'), 'gate review'); + ok(cli('gate', 'judge', '--run', runId), 'gate judge'); + return diffHash; +} + +function freezeGoal({ repo, cli }, runId) { + fs.writeFileSync(path.join(repo, '.ai-engineering-loop', 'goal-draft.json'), JSON.stringify({ + schemaVersion: 1, + runId, + objective: 'Paginate the list', + restatement: { problem: 'The list shows only the first page.', doneWhen: 'A caller can request page 2.', failIf: 'Page 2 is empty while rows remain.', unknowns: 'None.' }, + acceptanceCriteria: [{ id: 'AC-1', statement: 'returns page 2', evidenceRequired: 'node --version exit 0', failureCases: ['page beyond end returns empty'] }] + })); + ok(cli('goal', 'draft', '--json', '--run', runId, '--file', '.ai-engineering-loop/goal-draft.json', '--revision', '0'), 'goal draft'); + ok(cli('goal', 'freeze', '--json', '--latest', '--run', runId, '--by', 'human'), 'goal freeze'); +} + +function runToPass(ctx) { + const { repo, cli } = ctx; + const run = JSON.parse(ok(cli('run', '--json', 'Add pagination to the list'), 'run').stdout); + const runDir = path.join(repo, '.ai-engineering-loop/runs', run.runId); + freezeGoal(ctx, run.runId); + fs.writeFileSync(path.join(repo, 'src/list.js'), 'module.exports = (items, page = 1) => items.slice((page - 1) * 10, page * 10);\n'); + const judgedHash = makeAndJudge(ctx, run.runId, runDir); + assert.strictEqual(readState(runDir).state, 'JUDGED_PASS'); + return { runId: run.runId, runDir, judgedHash }; +} + +test('gate maker --from-git after JUDGED_PASS keeps the judged diff and names run --reopen', () => { + const ctx = setupRepo(); + const { runId, runDir, judgedHash } = runToPass(ctx); + // DA-01 test fix lands after the Judge passed. + fs.writeFileSync(path.join(ctx.repo, 'src/list.js'), 'module.exports = (items, page = 1) => items.slice(Math.max(page - 1, 0) * 10, page * 10);\n'); + + const refused = ctx.cli('gate', 'maker', '--from-git', '--run', runId, '--json'); + assert.notStrictEqual(refused.status, 0, 'gate maker must refuse once the diff is judged'); + assert.strictEqual(sha256(path.join(runDir, 'diff.patch')), judgedHash, 'the judged diff.patch is not overwritten'); + const body = JSON.parse(refused.stdout); + assert.match(body.fix, new RegExp(`run --reopen --run ${runId} --reason`), 'fix names the reopen command'); + assert.ok(body.why, 'error carries why'); + assert.strictEqual(readState(runDir).state, 'JUDGED_PASS'); +}); + +test('run --reopen starts a new iteration and the reworked diff reaches DELIVERED', () => { + const ctx = setupRepo(); + const { runId, runDir, judgedHash } = runToPass(ctx); + fs.writeFileSync(path.join(ctx.repo, 'src/list.js'), 'module.exports = (items, page = 1) => items.slice(Math.max(page - 1, 0) * 10, page * 10);\n'); + + const noReason = ctx.cli('run', '--reopen', '--run', runId, '--json'); + assert.notStrictEqual(noReason.status, 0, 'reopen needs a reason'); + assert.strictEqual(readState(runDir).state, 'JUDGED_PASS'); + + const reopened = JSON.parse(ok(ctx.cli('run', '--reopen', '--run', runId, '--reason', 'DA-01..DA-03 test fixes', '--json'), 'reopen').stdout); + assert.strictEqual(reopened.state, 'GOAL_FROZEN'); + assert.strictEqual(reopened.iteration, 2); + assert.match(reopened.next, new RegExp(`gate maker --from-git --run ${runId}`)); + const state = readState(runDir); + for (const name of ['diff', 'verification', 'findings', 'verdict']) { + assert.strictEqual(state.artifacts[name], undefined, `${name} must be re-earned`); + } + assert.strictEqual(state.history.at(-1).gate, 'run-reopen'); + const archived = path.join(runDir, 'iterations', '1'); + for (const name of ['verification.json', 'findings.json', 'verdict.json', 'diff.patch']) { + assert.ok(fs.existsSync(path.join(archived, name)), `iteration 1 keeps ${name}`); + } + assert.strictEqual(sha256(path.join(archived, 'diff.patch')), judgedHash); + + const reworkedHash = makeAndJudge(ctx, runId, runDir); + assert.notStrictEqual(reworkedHash, judgedHash); + ctx.commit('work'); + ok(ctx.cli('deliver', '--run', runId, '--destination', 'pr', '--summary', 'paginate', '--approve', '--by', 'human', '--json'), 'deliver'); + const delivered = readState(runDir); + assert.strictEqual(delivered.state, 'DELIVERED'); + assert.strictEqual(delivered.artifacts.diff.sha256, reworkedHash, 'the delivered diff is the re-judged diff'); +}); + +test('run --reopen refuses runs that are not between Maker and delivery', () => { + const ctx = setupRepo(); + const run = JSON.parse(ok(ctx.cli('run', '--json', 'Add pagination to the list'), 'run').stdout); + const refused = ctx.cli('run', '--reopen', '--run', run.runId, '--reason', 'nothing judged yet', '--json'); + assert.notStrictEqual(refused.status, 0); + const body = JSON.parse(refused.stdout); + assert.ok(body.why && body.fix, 'refusal carries why and fix'); +}); + +// Gap 1a: verify must not record evidence for code that is not the gated diff. +test('verify refuses when the code changed after gate maker (DIFF_DRIFT) and names run --reopen', () => { + const ctx = setupRepo(); + const run = JSON.parse(ok(ctx.cli('run', '--json', 'Add pagination to the list'), 'run').stdout); + const runDir = path.join(ctx.repo, '.ai-engineering-loop/runs', run.runId); + freezeGoal(ctx, run.runId); + fs.writeFileSync(path.join(ctx.repo, 'src/list.js'), 'module.exports = (items, page = 1) => items.slice(page * 10);\n'); + ok(ctx.cli('gate', 'maker', '--from-git', '--run', run.runId), 'gate maker'); + const gated = sha256(path.join(runDir, 'diff.patch')); + // The agent fixes the bug without re-gating. + fs.writeFileSync(path.join(ctx.repo, 'src/list.js'), 'module.exports = (items, page = 1) => items.slice((page - 1) * 10, page * 10);\n'); + const refused = ctx.cli('verify', '--run', run.runId, '--cmd', 'node --version', '--json'); + assert.notStrictEqual(refused.status, 0, 'verify must refuse drifted code'); + const body = JSON.parse(refused.stdout); + assert.match(body.error, /DIFF_DRIFT/); + assert.ok(body.why); + assert.match(body.fix, new RegExp(`run --reopen --run ${run.runId}`)); + assert.ok(body.details.some((line) => line.startsWith('src/list.js')), 'names the drifted file'); + assert.strictEqual(readState(runDir).state, 'MAKER_COMPLETE'); + assert.strictEqual(sha256(path.join(runDir, 'diff.patch')), gated); +}); + +// Gap 1b: deliver must compare what is committed with the judged diff. +test('deliver refuses committed code the Judge never saw', () => { + const ctx = setupRepo(); + const { runId, runDir } = runToPass(ctx); + fs.appendFileSync(path.join(ctx.repo, 'src/list.js'), 'module.exports.boom = () => { throw new Error("unjudged"); };\n'); + ctx.commit('add pagination'); + const refused = ctx.cli('deliver', '--run', runId, '--destination', 'pr', '--summary', 'x', '--approve', '--by', 'human', '--json'); + assert.notStrictEqual(refused.status, 0, 'deliver must refuse unjudged committed code'); + const body = JSON.parse(refused.stdout); + assert.match(body.error, /DIFF_DRIFT/); + assert.match(body.fix, new RegExp(`run --reopen --run ${runId}`)); + assert.strictEqual(readState(runDir).state, 'JUDGED_PASS'); +}); + +// Gap 4: a change committed before the Maker gate is still the Run's change. +test('gate maker --from-git diffs against the Run start, so an early commit is captured', () => { + const ctx = setupRepo(); + const run = JSON.parse(ok(ctx.cli('run', '--json', 'Add pagination to the list'), 'run').stdout); + const runDir = path.join(ctx.repo, '.ai-engineering-loop/runs', run.runId); + freezeGoal(ctx, run.runId); + const empty = ctx.cli('gate', 'maker', '--from-git', '--run', run.runId, '--json'); + assert.notStrictEqual(empty.status, 0); + const emptyBody = JSON.parse(empty.stdout); + assert.ok(emptyBody.why && emptyBody.fix, 'no-change error carries why and fix'); + fs.writeFileSync(path.join(ctx.repo, 'src/list.js'), 'module.exports = (items, page = 1) => items.slice((page - 1) * 10, page * 10);\n'); + fs.writeFileSync(path.join(ctx.repo, 'src/page.js'), 'module.exports = 10;\n'); + ctx.commit('wip'); + ok(ctx.cli('gate', 'maker', '--from-git', '--run', run.runId), 'gate maker after an early commit'); + const diff = fs.readFileSync(path.join(runDir, 'diff.patch'), 'utf8'); + assert.match(diff, /page - 1/); + assert.match(diff, /src\/page\.js/); + ok(ctx.cli('verify', '--run', run.runId, '--cmd', 'node --version', '--json'), 'verify on the committed change'); + assert.strictEqual(readState(runDir).state, 'VERIFIED'); +}); + +// The Judge ITERATE path keeps working: fix, re-gate maker, verify. +test('after a Judge ITERATE the fixed code is re-gated and verified', () => { + const ctx = setupRepo(); + const run = JSON.parse(ok(ctx.cli('run', '--json', 'Add pagination to the list'), 'run').stdout); + const runDir = path.join(ctx.repo, '.ai-engineering-loop/runs', run.runId); + freezeGoal(ctx, run.runId); + fs.writeFileSync(path.join(ctx.repo, 'src/list.js'), 'module.exports = (items, page) => items.slice((page - 1) * 10, page * 10);\n'); + ok(ctx.cli('gate', 'maker', '--from-git', '--run', run.runId), 'gate maker'); + ok(ctx.cli('verify', '--run', run.runId, '--cmd', 'node --version', '--json'), 'verify'); + fs.writeFileSync( + path.join(ctx.repo, '.ai-engineering-loop/tasks/claimed-vs-reality.md'), + '| AC | Claimed | Reality from command log |\n|---|---|---|\n| AC-1 | paginated | node --version exit 0 |\n' + ); + const diffHash = readState(runDir).artifacts.diff.sha256; + fs.writeFileSync(path.join(runDir, 'findings.json'), JSON.stringify({ schemaVersion: 1, runId: run.runId, diffHash, findings: [{ + id: 'DA-01', location: 'src/list.js:1', failureScenario: 'page undefined returns empty list', evidence: 'slice(NaN) is empty', + severity: 'HIGH', validity: 'VALID', disposition: 'STRONG', concreteAlternativeDiff: '- (items, page)\n+ (items, page = 1)' + }] })); + ok(ctx.cli('gate', 'review', '--run', run.runId, '--json'), 'gate review'); + fs.writeFileSync(path.join(runDir, 'verdict.json'), JSON.stringify({ schemaVersion: 1, runId: run.runId, verdict: 'ITERATE', reason: 'DA-01 valid HIGH', action: 'default page', modelTier: 'STRONG_MODEL' })); + ok(ctx.cli('gate', 'judge', '--run', run.runId), 'gate judge ITERATE'); + assert.strictEqual(readState(runDir).state, 'GOAL_FROZEN'); + fs.writeFileSync(path.join(ctx.repo, 'src/list.js'), 'module.exports = (items, page = 1) => items.slice((page - 1) * 10, page * 10);\n'); + ok(ctx.cli('gate', 'maker', '--from-git', '--run', run.runId), 'gate maker iteration 2'); + ok(ctx.cli('verify', '--run', run.runId, '--cmd', 'node --version', '--json'), 'verify iteration 2'); + const state = readState(runDir); + assert.strictEqual(state.state, 'VERIFIED'); + assert.strictEqual(state.iteration, 2); +});