architecture-harness 0.20.3 → 0.21.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/cli/bash-command-guard.mjs +28 -5
- package/src/cli/bash-command-guard.test.mjs +100 -0
- package/src/cli/bash-edit-guard.mjs +19 -16
- package/src/cli/bash-edit-guard.test.mjs +19 -0
- package/src/cli/ci-state.mjs +17 -9
- package/src/cli/ci-state.test.mjs +15 -1
- package/src/cli/codex-implement.mjs +109 -0
- package/src/cli/codex-implement.test.mjs +175 -0
- package/src/cli/cost-stop.mjs +98 -0
- package/src/cli/cost-stop.test.mjs +149 -0
- package/src/cli/dispatch-guard.mjs +3 -3
- package/src/cli/dispatch-guard.test.mjs +14 -6
- package/src/cli/dispatch-reminder.mjs +25 -7
- package/src/cli/dispatch-reminder.test.mjs +69 -3
- package/src/cli/git-read.mjs +28 -3
- package/src/cli/git-read.test.mjs +31 -1
- package/src/cli/ledger.mjs +50 -3
- package/src/cli/ledger.test.mjs +46 -0
- package/src/cli/powershell-command.mjs +8 -13
- package/src/cli/powershell-command.test.mjs +11 -1
- package/src/cli/qc.mjs +8 -1
- package/src/cli/report-stop.test.mjs +2 -1
- package/src/cli/review-gate.mjs +224 -0
- package/src/cli/review-gate.test.mjs +334 -0
- package/src/cli/shell-command.mjs +65 -9
- package/src/cli/shell-command.test.mjs +21 -1
- package/src/cli/skill-guard.mjs +56 -0
- package/src/cli/skill-guard.test.mjs +87 -0
- package/src/cli/stop-gate.test.mjs +80 -0
- package/src/cli/task-gate-review.test.mjs +225 -0
- package/src/cli/task-gate.mjs +35 -11
- package/src/cli/task-gate.test.mjs +6 -5
- package/src/cli/test-brief.mjs +12 -0
- package/src/cli/transcript-usage.mjs +28 -0
- package/src/cli/transcript-usage.test.mjs +9 -0
- package/src/cli/workflow-hooks.test.mjs +38 -0
- package/src/cli/workflow-settings.mjs +14 -3
- package/src/cli/workflow-settings.test.mjs +24 -0
- package/src/config.mjs +13 -0
- package/templates/docs/enforcement.md +11 -0
package/package.json
CHANGED
|
@@ -46,6 +46,12 @@ const NESTED = Object.fromEntries([
|
|
|
46
46
|
]);
|
|
47
47
|
|
|
48
48
|
export const programName = (word) => path.basename(word ?? "").toLowerCase().replace(/\.exe$/, "");
|
|
49
|
+
/** Git reads the repository from these settings, wherever the command spells them. */
|
|
50
|
+
const REPOSITORY_SETTING = /GIT_DIR|GIT_COMMON_DIR|GIT_WORK_TREE|core\.worktree|core\.bare/i;
|
|
51
|
+
/** A shell variable or command substitution in a path: `$K`, `${K}`, `$env:K`, `$(cmd)`, a backtick, or `%K%`. */
|
|
52
|
+
const UNEXPANDED = /[$`]|%[A-Za-z_][^%\s]*%/;
|
|
53
|
+
const WORKTREE_ADD = /\bworktree\s+add\b/i;
|
|
54
|
+
const EXPLICIT_DIR = /--git-dir|--work-tree|GIT_DIR|GIT_COMMON_DIR|GIT_WORK_TREE|core\.worktree|core\.bare/i;
|
|
49
55
|
const isNoVerify = (arg) => arg.length >= NO_VERIFY_MIN && NO_VERIFY.startsWith(arg);
|
|
50
56
|
|
|
51
57
|
/** True when a commit or push names `--no-verify`, or a commit names `-n` alone or in a flag cluster. */
|
|
@@ -142,9 +148,13 @@ const REASONS = {
|
|
|
142
148
|
"a hand run of a hook script writes a lease or a ledger record under a made-up session id, and that lease blocks later " +
|
|
143
149
|
"edits in the worktree for hours. Test a hook only through its own suite (`node --test`), in temporary folders.",
|
|
144
150
|
explicitDir:
|
|
145
|
-
"`--git-dir`, `GIT_DIR`, `--work-tree`, and `
|
|
146
|
-
"so this guard cannot tell which repository gets the worktree.
|
|
151
|
+
"`--git-dir`, `GIT_DIR`, `GIT_COMMON_DIR`, `--work-tree`, `GIT_WORK_TREE`, `core.worktree`, and `core.bare` make git read the repository from a path it resolves " +
|
|
152
|
+
"after every `-C`, so this guard cannot tell which repository gets the worktree. It looks for them in the whole command, in any order. " +
|
|
153
|
+
"Run `git worktree add` from inside the target repository instead: " +
|
|
147
154
|
"use `-C <repository>`, `cd <repository>`, or `Set-Location <repository>`, and drop the git directory and work tree settings.",
|
|
155
|
+
variable:
|
|
156
|
+
"a `-C`, `cd`, or `Set-Location` path holds a variable the guard cannot expand (`$K`, `${K}`, `$env:K`, `%K%`, or a command substitution), " +
|
|
157
|
+
"so it cannot tell which repository gets the worktree. Write the path literally.",
|
|
148
158
|
worktree:
|
|
149
159
|
"a worktree lives in the worktree folder of the main checkout, so git ignores it and `qc worktree remove` finds it. " +
|
|
150
160
|
"Run `npx qc worktree add <name> <branch>` from the repository, or give `git worktree add` a path one level under that folder.",
|
|
@@ -172,17 +182,30 @@ function folderFor(place, from) {
|
|
|
172
182
|
export function violations(command, parse = segmentsOf, place = null, refused = []) {
|
|
173
183
|
const segments = parse(command);
|
|
174
184
|
const found = new Set();
|
|
185
|
+
const scoped = Boolean(place) && (place.scoped === true || REPOSITORY_SETTING.test(command));
|
|
175
186
|
let cwd = place?.cwd;
|
|
187
|
+
// A move into a path with a variable leaves the repository unknown, until a literal absolute path names it again.
|
|
188
|
+
let unknown = place?.unknown === true;
|
|
176
189
|
for (const segment of segments) {
|
|
177
190
|
const moved = place ? MOVES.get(parse)?.(segment) : null;
|
|
178
|
-
if (moved != null
|
|
191
|
+
if (moved != null && UNEXPANDED.test(moved)) {
|
|
192
|
+
unknown = true;
|
|
193
|
+
} else if (moved != null) {
|
|
194
|
+
cwd = resolveFrom(cwd, moved, parse);
|
|
195
|
+
if (path.isAbsolute(spelledPath(moved, parse))) unknown = false;
|
|
196
|
+
}
|
|
179
197
|
const git = gitCall(segment);
|
|
180
198
|
if (git && skipsHooks(git)) found.add("hooks");
|
|
181
199
|
if (git && setsHooksPath(git)) found.add("hooksPath");
|
|
182
200
|
const added = place && git?.sub === "worktree" ? worktreeAddPath(git.args) : null;
|
|
183
|
-
|
|
201
|
+
// A subexpression after `-C` ends the git segment, so the `worktree add` after it never parses as git.
|
|
202
|
+
if (place && git?.sub === null && git.dirs.some((dir) => !dir || UNEXPANDED.test(dir)) && WORKTREE_ADD.test(command)) found.add("variable");
|
|
203
|
+
if (place && git?.sub === null && WORKTREE_ADD.test(command) && EXPLICIT_DIR.test(command)) found.add("explicitDir");
|
|
204
|
+
if (added !== null && (scoped || git.explicitDir)) {
|
|
184
205
|
// The session is guarded, because `place` exists only then.
|
|
185
206
|
found.add("explicitDir");
|
|
207
|
+
} else if (added !== null && (unknown || git.dirs.some((dir) => UNEXPANDED.test(dir)))) {
|
|
208
|
+
found.add("variable");
|
|
186
209
|
} else if (added !== null) {
|
|
187
210
|
const from = git.dirs.filter(Boolean).reduce((dir, next) => resolveFrom(dir, next, parse), cwd);
|
|
188
211
|
const folder = folderFor(place, from);
|
|
@@ -192,7 +215,7 @@ export function violations(command, parse = segmentsOf, place = null, refused =
|
|
|
192
215
|
}
|
|
193
216
|
}
|
|
194
217
|
const nested = nestedCommand(segment);
|
|
195
|
-
if (nested) for (const key of violations(nested.command, nested.parse, place && { ...place, cwd }, refused)) found.add(key);
|
|
218
|
+
if (nested) for (const key of violations(nested.command, nested.parse, place && { ...place, cwd, scoped, unknown }, refused)) found.add(key);
|
|
196
219
|
}
|
|
197
220
|
if (!segments.some(runsTests) && segments.some(runsHookScript)) found.add("script");
|
|
198
221
|
return Object.keys(REASONS).filter((key) => found.has(key));
|
|
@@ -353,3 +353,103 @@ test("a worktree add in a repository with no qc.config.json is not guarded", (t)
|
|
|
353
353
|
}
|
|
354
354
|
assert.equal(decide(bash(ws.plain, "git worktree add ../x")), null, "a session in it is not guarded either");
|
|
355
355
|
});
|
|
356
|
+
|
|
357
|
+
test("a worktree add is refused when its command text sets GIT_DIR, GIT_WORK_TREE, core.worktree, or core.bare in any segment", (t) => {
|
|
358
|
+
const ws = twoRepos(t);
|
|
359
|
+
const kit = ws.slash(ws.kit);
|
|
360
|
+
for (const command of [
|
|
361
|
+
`export GIT_DIR=${kit}/.git; git worktree add .worktree/x`,
|
|
362
|
+
`export GIT_WORK_TREE=${kit}; cd ${kit} && git worktree add .worktree/x`,
|
|
363
|
+
`env GIT_DIR=${kit}/.git bash -c 'cd ${kit}'; git worktree add .worktree/x`,
|
|
364
|
+
`git worktree add .worktree/x; export GIT_DIR=${kit}/.git`,
|
|
365
|
+
`export GIT_DIR=${kit}/.git; bash -c 'git worktree add .worktree/x'`,
|
|
366
|
+
`bash -c 'export GIT_DIR=${kit}/.git'; git worktree add .worktree/x`,
|
|
367
|
+
`git -c core.worktree=${kit} worktree add .worktree/x`,
|
|
368
|
+
`git -c core.bare=true worktree add .worktree/x`,
|
|
369
|
+
`git config core.worktree ${kit} && git worktree add .worktree/x`,
|
|
370
|
+
`set GIT_DIR=${kit}/.git && git worktree add .worktree/x`,
|
|
371
|
+
`export git_dir=${kit}/.git; git worktree add .worktree/x`,
|
|
372
|
+
`export GIT_COMMON_DIR=${kit}/.git; git worktree add .worktree/x`,
|
|
373
|
+
"git -c core.worktree=$(pwd) worktree add ../out",
|
|
374
|
+
"git --git-dir=$(pwd)/.git worktree add ../out",
|
|
375
|
+
"git --work-tree=$(pwd) worktree add ../out",
|
|
376
|
+
]) {
|
|
377
|
+
explicitDirReason(decide(bash(ws.adopted, command)));
|
|
378
|
+
}
|
|
379
|
+
for (const command of [
|
|
380
|
+
`$env:GIT_DIR = "${kit}/.git"; git worktree add .worktree/x`,
|
|
381
|
+
`$env:GIT_WORK_TREE = "${kit}"; Set-Location ${kit}; git worktree add .worktree/x`,
|
|
382
|
+
`git -c core.worktree=${kit} worktree add .worktree/x`,
|
|
383
|
+
`$env:git_dir="${kit}/.git"; git worktree add .worktree/x`,
|
|
384
|
+
]) {
|
|
385
|
+
explicitDirReason(decide(powershell(ws.adopted, command)));
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
test("a worktree add with none of those settings still passes, and so does a mention without a worktree add", (t) => {
|
|
390
|
+
const ws = twoRepos(t);
|
|
391
|
+
const kit = ws.slash(ws.kit);
|
|
392
|
+
assert.equal(decide(bash(ws.adopted, "git worktree add .worktree/x")), null);
|
|
393
|
+
assert.equal(decide(bash(ws.adopted, `export GIT_DIR=${kit}/.git; git status`)), null);
|
|
394
|
+
assert.equal(decide(bash(ws.adopted, `git -c core.bare=true status`)), null);
|
|
395
|
+
assert.equal(decide(bash(ws.plain, `export GIT_DIR=${kit}/.git; git worktree add ../x`)), null, "a repository with no qc.config.json is not guarded");
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
/** The refusal for a path that holds an unexpanded variable: it says to write the path literally. */
|
|
399
|
+
const variableReason = (output) => {
|
|
400
|
+
const reason = reasonOf(output) ?? "";
|
|
401
|
+
assert.match(reason, /literally/, reason);
|
|
402
|
+
assert.match(reason, /variable/, reason);
|
|
403
|
+
return reason;
|
|
404
|
+
};
|
|
405
|
+
|
|
406
|
+
test("a worktree add after a -C, cd, or Set-Location path with an unexpanded variable is refused, and the reason says to write the path literally", (t) => {
|
|
407
|
+
const ws = twoRepos(t);
|
|
408
|
+
const kit = ws.slash(ws.kit);
|
|
409
|
+
for (const command of [
|
|
410
|
+
"git -C $K worktree add .worktree/x",
|
|
411
|
+
"git -C ${K} worktree add .worktree/x",
|
|
412
|
+
`git -C "$HOME/kit" worktree add .worktree/x`,
|
|
413
|
+
"cd $K && git worktree add .worktree/x",
|
|
414
|
+
"cd ${K}/sub && git worktree add .worktree/x",
|
|
415
|
+
"cd $(git rev-parse --show-toplevel) && git worktree add .worktree/x",
|
|
416
|
+
`bash -c 'cd $K && git worktree add .worktree/x'`,
|
|
417
|
+
"cd %K% && git worktree add .worktree/x",
|
|
418
|
+
`cd $K; cd sub; git worktree add .worktree/x`,
|
|
419
|
+
"cd `pwd` && git worktree add .worktree/x",
|
|
420
|
+
"cd $(pwd)/sub && git worktree add .worktree/x",
|
|
421
|
+
"pushd $(pwd) && git worktree add .worktree/x",
|
|
422
|
+
"git -C $(git rev-parse --show-toplevel) worktree add ../out",
|
|
423
|
+
"git -C `pwd` worktree add ../out",
|
|
424
|
+
]) {
|
|
425
|
+
variableReason(decide(bash(ws.adopted, command)));
|
|
426
|
+
}
|
|
427
|
+
for (const command of [
|
|
428
|
+
"Set-Location $env:K; git worktree add .worktree/x",
|
|
429
|
+
"Set-Location $K; git worktree add .worktree/x",
|
|
430
|
+
"git -C $env:K worktree add .worktree/x",
|
|
431
|
+
"cd %K%; git worktree add .worktree/x",
|
|
432
|
+
"Set-Location (Join-Path $K 'sub'); git worktree add .worktree/x",
|
|
433
|
+
"Push-Location ($env:K + '\\sub'); git worktree add .worktree/x",
|
|
434
|
+
"Set-Location -Path (Join-Path $K sub); git worktree add .worktree/x",
|
|
435
|
+
"Set-Location -LiteralPath (Get-Location); git worktree add .worktree/x",
|
|
436
|
+
"cd (Resolve-Path ..); git worktree add .worktree/x",
|
|
437
|
+
"Set-Location $(Join-Path $K sub); git worktree add .worktree/x",
|
|
438
|
+
"git -C (Join-Path $K 'x') worktree add ../out",
|
|
439
|
+
"git -C $(Get-Location) worktree add ../out",
|
|
440
|
+
]) {
|
|
441
|
+
variableReason(decide(powershell(ws.adopted, command)));
|
|
442
|
+
}
|
|
443
|
+
// A literal path after the variable names the repository again.
|
|
444
|
+
assert.equal(decide(bash(ws.adopted, `cd $K; cd ${kit} && git worktree add .worktree/x`)), null);
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
test("a variable in a path of a command that adds no worktree, or in the worktree path alone, is no refusal for it", (t) => {
|
|
448
|
+
const ws = twoRepos(t);
|
|
449
|
+
for (const command of ["cd $K && git status", "git -C $K worktree list", "cd $HOME && ls", "git worktree add .worktree/$NAME"]) {
|
|
450
|
+
assert.doesNotMatch(reasonOf(decide(bash(ws.adopted, command))) ?? "", /literally/, command);
|
|
451
|
+
}
|
|
452
|
+
const plain = ws.slash(ws.plain);
|
|
453
|
+
assert.equal(decide(bash(ws.plain, "cd $K && git worktree add ../x")), null, "a repository with no qc.config.json is not guarded");
|
|
454
|
+
assert.equal(decide(bash(ws.adopted, `git -C ${plain} worktree add ../x`)), null);
|
|
455
|
+
});
|
|
@@ -144,25 +144,28 @@ export async function report(call, projectRoot) {
|
|
|
144
144
|
const findings = [];
|
|
145
145
|
const isMainSession = !(typeof call.agent_id === "string" && call.agent_id !== "");
|
|
146
146
|
for (const root of checkoutsOf(cwd, command, dialect)) findings.push(...(await findingsIn(root, manifest, project, isMainSession)));
|
|
147
|
-
|
|
147
|
+
const unresolved = dialect.unresolvedGitDirs(command);
|
|
148
|
+
if (findings.length === 0 && unresolved.length === 0) return null;
|
|
148
149
|
|
|
149
150
|
const listed = findings.slice(0, MAX_LISTED).map((line) => `- ${line}`);
|
|
150
151
|
if (findings.length > MAX_LISTED) listed.push(`- and ${findings.length - MAX_LISTED} more`);
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
152
|
+
const lines = [];
|
|
153
|
+
if (findings.length > 0) {
|
|
154
|
+
lines.push("Bash edit guard: the checkout holds uncommitted changes that the swarm rules do not allow.", ...listed);
|
|
155
|
+
lines.push(
|
|
156
|
+
findings.some((line) => line.includes(CONTROLLER_RULE))
|
|
157
|
+
? "Dispatch an implementer for a change outside the controller paths. Revert a change only if you made it by mistake. The guard does not revert anything."
|
|
158
|
+
: "Revert a change only if your work order made it and should not have. " +
|
|
159
|
+
"For any other change, stop and tell the orchestrator. The guard does not revert anything.",
|
|
160
|
+
);
|
|
161
|
+
}
|
|
162
|
+
if (unresolved.length > 0) {
|
|
163
|
+
lines.push(
|
|
164
|
+
`Bash edit guard: the command names a git directory with no work tree (${unresolved.join(", ")}), ` +
|
|
165
|
+
"so the guard cannot tell which checkout it changed. Run `git status` in that repository.",
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
return { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: lines.join("\n") } };
|
|
166
169
|
}
|
|
167
170
|
|
|
168
171
|
async function readStdin() {
|
|
@@ -136,3 +136,22 @@ test("porcelain output names each changed path, and both sides of a rename", ()
|
|
|
136
136
|
const status = [" M src/a.ts", "?? docs/new file.md", "R lib/new.ts", "lib/old.ts", ""].join("\u0000");
|
|
137
137
|
assert.deepEqual(changedPaths(status), ["src/a.ts", "docs/new file.md", "lib/new.ts", "lib/old.ts"]);
|
|
138
138
|
});
|
|
139
|
+
|
|
140
|
+
test("a --work-tree directory is a checkout the command could have changed", async (t) => {
|
|
141
|
+
const ws = workspace(t);
|
|
142
|
+
ws.put(ws.linked, "docs/b.md");
|
|
143
|
+
const slash = (dir) => dir.replaceAll("\\", "/");
|
|
144
|
+
const output = await report(bash(ws.outside, `git --work-tree=${slash(ws.linked)} checkout -- docs`), ws.linked);
|
|
145
|
+
assert.match(contextOf(output), /docs\/b\.md: outside the work order's declared paths/);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
test("a git dir with no work tree is reported as unresolved, not dropped", async (t) => {
|
|
149
|
+
const ws = workspace(t);
|
|
150
|
+
const slash = (dir) => dir.replaceAll("\\", "/");
|
|
151
|
+
const text = contextOf(await report(bash(ws.outside, `git --git-dir=${slash(ws.primary)}/.git checkout main`), ws.linked));
|
|
152
|
+
assert.match(text, /git directory with no work tree/);
|
|
153
|
+
assert.ok(text.includes(`${slash(ws.primary)}/.git`), text);
|
|
154
|
+
assert.match(text, /cannot tell which checkout/);
|
|
155
|
+
const withTree = await report(bash(ws.outside, `git --git-dir=${slash(ws.primary)}/.git --work-tree=${slash(ws.outside)} checkout main`), ws.linked);
|
|
156
|
+
assert.doesNotMatch(contextOf(withTree), /git directory with no work tree/);
|
|
157
|
+
});
|
package/src/cli/ci-state.mjs
CHANGED
|
@@ -24,23 +24,31 @@ export function notGreenReason(runs) {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
/**
|
|
27
|
-
*
|
|
28
|
-
* unknown: gh fails
|
|
27
|
+
* What CI says about `sha`: `reason` names a run that failed or still runs, as `CI on <short sha>: <why>`.
|
|
28
|
+
* `unknown` says why nothing is known: no sha, no `origin`, a gh that fails or times out, a reply that does not parse, or no check runs.
|
|
29
29
|
* `gh` and `origin` replace the real reads, for a test.
|
|
30
30
|
*/
|
|
31
|
-
export function
|
|
32
|
-
|
|
31
|
+
export function ciState(sha, cwd, { gh = runGh, origin = originOf } = {}) {
|
|
32
|
+
const unknown = (why) => ({ reason: null, unknown: why });
|
|
33
|
+
if (typeof sha !== "string" || sha === "") return unknown("there is no commit to ask about");
|
|
33
34
|
const repo = origin(cwd, ORIGIN_TIMEOUT_MS);
|
|
34
|
-
if (repo === null) return
|
|
35
|
+
if (repo === null) return unknown("the checkout has no readable origin");
|
|
35
36
|
const out = gh(["api", `repos/${repo}/commits/${sha}/check-runs?per_page=100`], { cwd, timeoutMs: GH_TIMEOUT_MS });
|
|
36
|
-
if (out === null) return
|
|
37
|
+
if (out === null) return unknown("gh failed or timed out");
|
|
37
38
|
let runs;
|
|
38
39
|
try {
|
|
39
40
|
runs = JSON.parse(out)?.check_runs;
|
|
40
41
|
} catch {
|
|
41
|
-
return
|
|
42
|
+
return unknown("gh answered with text that is not JSON");
|
|
42
43
|
}
|
|
43
|
-
if (!Array.isArray(runs)) return
|
|
44
|
+
if (!Array.isArray(runs)) return unknown("gh answered with no check_runs list");
|
|
45
|
+
if (runs.length === 0) return unknown(`${short(sha)} has no check runs`);
|
|
44
46
|
const why = notGreenReason(runs);
|
|
45
|
-
return why === null ? null : `CI on ${short(sha)}: ${why}
|
|
47
|
+
return { reason: why === null ? null : `CI on ${short(sha)}: ${why}`, unknown: null };
|
|
46
48
|
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* @returns the reason CI on `sha` is not green, as `CI on <short sha>: <why>`, or null when it is green or
|
|
52
|
+
* unknown. `ciState` tells those two apart.
|
|
53
|
+
*/
|
|
54
|
+
export const ciNotGreen = (sha, cwd, deps) => ciState(sha, cwd, deps).reason;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { strict as assert } from "node:assert";
|
|
2
2
|
import { test } from "node:test";
|
|
3
|
-
import { ciNotGreen, notGreenReason } from "./ci-state.mjs";
|
|
3
|
+
import { ciNotGreen, ciState, notGreenReason } from "./ci-state.mjs";
|
|
4
4
|
|
|
5
5
|
const SHA = "a".repeat(40);
|
|
6
6
|
const run = (name, status, conclusion = null) => ({ name, status, conclusion });
|
|
@@ -60,3 +60,17 @@ test("ciNotGreen bounds its reads so the whole gate stays under the hook's 10 se
|
|
|
60
60
|
assert.ok(originTimeout > 0 && originTimeout <= 1000, `origin timeout ${originTimeout}`);
|
|
61
61
|
assert.ok(ghOptions.timeoutMs + originTimeout < 5000);
|
|
62
62
|
});
|
|
63
|
+
|
|
64
|
+
test("ciState separates a head that is not green, a green head, and a head it cannot read", () => {
|
|
65
|
+
const origin = () => "o/r";
|
|
66
|
+
const state = (gh, from = origin) => ciState(SHA, "/c", { gh, origin: from });
|
|
67
|
+
assert.deepEqual(state(() => reply(run("a", "completed", "success"))), { reason: null, unknown: null });
|
|
68
|
+
assert.match(state(() => reply(run("build", "in_progress"))).reason, /^CI on aaaaaaa: build is in_progress/);
|
|
69
|
+
assert.match(state(() => reply()).unknown, /no check runs/);
|
|
70
|
+
assert.match(state(() => null).unknown, /gh/);
|
|
71
|
+
assert.match(state(() => "not json").unknown, /gh/);
|
|
72
|
+
assert.match(state(() => "{}").unknown, /gh/);
|
|
73
|
+
assert.match(state(() => reply(), () => null).unknown, /origin/);
|
|
74
|
+
assert.match(ciState("", "/c", { gh: () => null, origin }).unknown, /no commit/);
|
|
75
|
+
for (const answer of [state(() => null), state(() => reply())]) assert.equal(answer.reason, null);
|
|
76
|
+
});
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// `qc codex-implement`: run one brief through `codex exec` as an implementer, and start a fresh session
|
|
2
|
+
// after each stop until the progress file says it is done. It never calls Claude; exit 2 hands the brief back.
|
|
3
|
+
|
|
4
|
+
import { spawn } from "node:child_process";
|
|
5
|
+
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync } from "node:fs";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
|
|
8
|
+
export const DONE_MARKER = "ALL TASKS DONE";
|
|
9
|
+
const DEFAULT_MAX_RUNS = 12;
|
|
10
|
+
const TAIL_CHARS = 4000;
|
|
11
|
+
const LIMIT = /usage limit|spend cap|rate limit|hit your limit/i;
|
|
12
|
+
|
|
13
|
+
const USAGE =
|
|
14
|
+
"usage: qc codex-implement --brief <file> --worktree <path> --progress <file> [--log <file>] [--max-runs <n>]\n" +
|
|
15
|
+
"exit 0 every task done, 1 bad input or no codex, 2 a Codex usage or spend limit, 3 out of runs";
|
|
16
|
+
|
|
17
|
+
const FLAGS = { "--brief": "brief", "--worktree": "worktree", "--progress": "progress", "--log": "log", "--max-runs": "maxRuns" };
|
|
18
|
+
|
|
19
|
+
/** @returns the settings with resolved paths; throws an Error naming the bad or missing flag. */
|
|
20
|
+
export function parseArgs(argv) {
|
|
21
|
+
const found = {};
|
|
22
|
+
for (let index = 0; index < argv.length; index += 2) {
|
|
23
|
+
const key = FLAGS[argv[index]];
|
|
24
|
+
if (!key) throw new Error(`unknown argument ${argv[index]}`);
|
|
25
|
+
if (argv[index + 1] === undefined) throw new Error(`${argv[index]} needs a value`);
|
|
26
|
+
found[key] = argv[index + 1];
|
|
27
|
+
}
|
|
28
|
+
for (const flag of ["--brief", "--worktree", "--progress"]) if (!found[FLAGS[flag]]) throw new Error(`${flag} is required`);
|
|
29
|
+
const maxRuns = found.maxRuns === undefined ? DEFAULT_MAX_RUNS : Number(found.maxRuns);
|
|
30
|
+
if (!Number.isInteger(maxRuns) || maxRuns < 1) throw new Error(`--max-runs must be a positive integer, got ${found.maxRuns}`);
|
|
31
|
+
const progress = path.resolve(found.progress);
|
|
32
|
+
return {
|
|
33
|
+
brief: path.resolve(found.brief),
|
|
34
|
+
worktree: path.resolve(found.worktree),
|
|
35
|
+
progress,
|
|
36
|
+
log: path.resolve(found.log ?? `${progress}.log`),
|
|
37
|
+
maxRuns,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const isDone = (progress) => existsSync(progress) && readFileSync(progress, "utf8").includes(DONE_MARKER);
|
|
42
|
+
|
|
43
|
+
function continuationNote(progress) {
|
|
44
|
+
return (
|
|
45
|
+
`\n\n---\nThis may be a fresh session that continues earlier work. Read \`git log --oneline\` and \`git status --short\` ` +
|
|
46
|
+
`in the worktree, and the progress file ${progress}. Continue from the first unfinished task.`
|
|
47
|
+
);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Runs one codex process with no shell and a closed stdin, appends its output to the log, and resolves with the exit status and the output tail. */
|
|
51
|
+
function spawnRun({ command, args, env, log }, codexCommand) {
|
|
52
|
+
const [bin, ...prefix] = codexCommand;
|
|
53
|
+
mkdirSync(path.dirname(log), { recursive: true });
|
|
54
|
+
const start = existsSync(log) ? statSync(log).size : 0;
|
|
55
|
+
const fd = openSync(log, "a");
|
|
56
|
+
return new Promise((resolve, reject) => {
|
|
57
|
+
const child = spawn(bin, [...prefix, ...args], { env, stdio: ["ignore", fd, fd], windowsHide: true });
|
|
58
|
+
child.on("error", (error) => {
|
|
59
|
+
closeSync(fd);
|
|
60
|
+
reject(error);
|
|
61
|
+
});
|
|
62
|
+
child.on("close", (status) => {
|
|
63
|
+
closeSync(fd);
|
|
64
|
+
const text = readFileSync(log, "utf8");
|
|
65
|
+
resolve({ status, tail: Buffer.from(text).subarray(Math.max(start, Buffer.byteLength(text) - TAIL_CHARS)).toString("utf8") });
|
|
66
|
+
});
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* @param run `({ command, args, env, log }) => Promise<{ status, tail }>`; the default spawns `codexCommand`.
|
|
72
|
+
* @returns the exit code: 0 done, 1 bad input or no codex, 2 a limit, 3 out of runs.
|
|
73
|
+
*/
|
|
74
|
+
export async function runCodexImplement(argv, { run, codexCommand = ["codex"], env = process.env, say = (line) => console.error(line) } = {}) {
|
|
75
|
+
let settings;
|
|
76
|
+
try {
|
|
77
|
+
settings = parseArgs(argv);
|
|
78
|
+
} catch (error) {
|
|
79
|
+
say(`qc codex-implement: ${error.message}\n${USAGE}`);
|
|
80
|
+
return 1;
|
|
81
|
+
}
|
|
82
|
+
const execute = run ?? ((call) => spawnRun(call, codexCommand));
|
|
83
|
+
const prompt = readFileSync(settings.brief, "utf8") + continuationNote(settings.progress);
|
|
84
|
+
const args = ["exec", "-s", "danger-full-access", "-C", settings.worktree, prompt];
|
|
85
|
+
for (let count = 1; count <= settings.maxRuns; count += 1) {
|
|
86
|
+
if (isDone(settings.progress)) return finish(say, `done after ${count - 1} run(s)`, 0);
|
|
87
|
+
let result;
|
|
88
|
+
try {
|
|
89
|
+
result = await execute({ command: codexCommand[0], args, env: { ...env, QC_ROLE: "implementer" }, log: settings.log });
|
|
90
|
+
} catch (error) {
|
|
91
|
+
return finish(say, `codex did not run: ${error.message}`, 1);
|
|
92
|
+
}
|
|
93
|
+
say(`qc codex-implement: run ${count} ended with status ${result.status}`);
|
|
94
|
+
if (isDone(settings.progress)) return finish(say, `done after ${count} run(s)`, 0);
|
|
95
|
+
if (reportsLimit(result.tail ?? "", prompt)) return finish(say, "Codex reports a usage or spend limit: dispatch the same brief to a Claude sdd-implementer", 2);
|
|
96
|
+
}
|
|
97
|
+
return finish(say, `out of runs: ${settings.maxRuns} runs and the progress file is not done`, 3);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A limit line counts only when Codex wrote it, not when the log echoes a line of the prompt. */
|
|
101
|
+
function reportsLimit(tail, prompt) {
|
|
102
|
+
const echoed = new Set(prompt.split(/\r?\n/).map((line) => line.trim()).filter(Boolean));
|
|
103
|
+
return tail.split(/\r?\n/).some((line) => LIMIT.test(line) && !echoed.has(line.trim()));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function finish(say, message, code) {
|
|
107
|
+
say(`qc codex-implement: ${message}`);
|
|
108
|
+
return code;
|
|
109
|
+
}
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { appendFileSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import os from "node:os";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { test } from "node:test";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
import { DONE_MARKER, parseArgs, runCodexImplement } from "./codex-implement.mjs";
|
|
9
|
+
|
|
10
|
+
const QC = fileURLToPath(new URL("./qc.mjs", import.meta.url));
|
|
11
|
+
|
|
12
|
+
function setup(t, { progress = "" } = {}) {
|
|
13
|
+
const dir = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-codex-implement-")));
|
|
14
|
+
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
|
15
|
+
const files = { dir, brief: path.join(dir, "brief.md"), progress: path.join(dir, "progress.md"), worktree: path.join(dir, "wt") };
|
|
16
|
+
writeFileSync(files.brief, "# Brief\n\nDo task one.\n");
|
|
17
|
+
writeFileSync(files.progress, progress);
|
|
18
|
+
const argv = ["--brief", files.brief, "--worktree", files.worktree, "--progress", files.progress];
|
|
19
|
+
return { ...files, argv };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const quiet = () => {};
|
|
23
|
+
|
|
24
|
+
test("a progress file that already says ALL TASKS DONE exits 0 with no run", async (t) => {
|
|
25
|
+
const { argv } = setup(t, { progress: `task 1 committed\n${DONE_MARKER}\n` });
|
|
26
|
+
let calls = 0;
|
|
27
|
+
const code = await runCodexImplement(argv, { run: async () => (calls += 1), say: quiet });
|
|
28
|
+
assert.equal(code, 0);
|
|
29
|
+
assert.equal(calls, 0);
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
test("a run passes exec, the sandbox, the worktree and one prompt, with QC_ROLE=implementer", async (t) => {
|
|
33
|
+
const { argv, brief, progress, worktree } = setup(t);
|
|
34
|
+
const seen = [];
|
|
35
|
+
const run = async (call) => {
|
|
36
|
+
seen.push(call);
|
|
37
|
+
appendFileSync(progress, `${DONE_MARKER}\n`);
|
|
38
|
+
return { status: 0, tail: "ok" };
|
|
39
|
+
};
|
|
40
|
+
assert.equal(await runCodexImplement(argv, { run, say: quiet }), 0);
|
|
41
|
+
assert.equal(seen.length, 1);
|
|
42
|
+
const [call] = seen;
|
|
43
|
+
assert.equal(call.command, "codex");
|
|
44
|
+
assert.deepEqual(call.args.slice(0, 5), ["exec", "-s", "danger-full-access", "-C", worktree]);
|
|
45
|
+
assert.equal(call.args.length, 6);
|
|
46
|
+
assert.equal(call.env.QC_ROLE, "implementer");
|
|
47
|
+
assert.ok(call.args[5].startsWith(readFileSync(brief, "utf8")));
|
|
48
|
+
assert.match(call.args[5], /git log --oneline/);
|
|
49
|
+
assert.match(call.args[5], /git status --short/);
|
|
50
|
+
assert.match(call.args[5], /first unfinished task/);
|
|
51
|
+
assert.ok(call.args[5].includes(progress));
|
|
52
|
+
assert.equal(call.log, `${progress}.log`);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
test("a fresh session starts after a stop with the progress file not done", async (t) => {
|
|
56
|
+
const { argv, progress } = setup(t);
|
|
57
|
+
let calls = 0;
|
|
58
|
+
const run = async () => {
|
|
59
|
+
calls += 1;
|
|
60
|
+
if (calls === 2) appendFileSync(progress, `${DONE_MARKER}\n`);
|
|
61
|
+
return { status: 0, tail: "context large, notes written" };
|
|
62
|
+
};
|
|
63
|
+
assert.equal(await runCodexImplement(argv, { run, say: quiet }), 0);
|
|
64
|
+
assert.equal(calls, 2);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("a usage or spend limit in the output tail exits 2 and stops restarting", async (t) => {
|
|
68
|
+
const { argv } = setup(t);
|
|
69
|
+
for (const message of ["You've hit your usage limit.", "Spend cap reached", "429 Rate Limit exceeded", "you HIT YOUR LIMIT"]) {
|
|
70
|
+
let calls = 0;
|
|
71
|
+
const run = async () => {
|
|
72
|
+
calls += 1;
|
|
73
|
+
return { status: 1, tail: `stack\n${message}\n` };
|
|
74
|
+
};
|
|
75
|
+
assert.equal(await runCodexImplement(argv, { run, say: quiet }), 2, message);
|
|
76
|
+
assert.equal(calls, 1, message);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
test("--max-runs bounds the restarts and exits 3, with a default of 12", async (t) => {
|
|
81
|
+
const { argv } = setup(t);
|
|
82
|
+
let calls = 0;
|
|
83
|
+
const run = async () => ((calls += 1), { status: 0, tail: "stopped" });
|
|
84
|
+
assert.equal(await runCodexImplement([...argv, "--max-runs", "3"], { run, say: quiet }), 3);
|
|
85
|
+
assert.equal(calls, 3);
|
|
86
|
+
calls = 0;
|
|
87
|
+
assert.equal(await runCodexImplement(argv, { run, say: quiet }), 3);
|
|
88
|
+
assert.equal(calls, 12);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("a run that finishes the brief on its last allowed run exits 0, not 3", async (t) => {
|
|
92
|
+
const { argv, progress } = setup(t);
|
|
93
|
+
const run = async () => (appendFileSync(progress, DONE_MARKER), { status: 0, tail: "" });
|
|
94
|
+
assert.equal(await runCodexImplement([...argv, "--max-runs", "1"], { run, say: quiet }), 0);
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
test("a codex binary that does not start exits 1 with the reason", async (t) => {
|
|
98
|
+
const { argv } = setup(t);
|
|
99
|
+
const said = [];
|
|
100
|
+
const run = async () => {
|
|
101
|
+
throw new Error("spawn codex ENOENT");
|
|
102
|
+
};
|
|
103
|
+
assert.equal(await runCodexImplement(argv, { run, say: (line) => said.push(line) }), 1);
|
|
104
|
+
assert.match(said.join("\n"), /ENOENT/);
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
test("a missing or malformed argument exits 1 and names it", async (t) => {
|
|
108
|
+
const { argv } = setup(t);
|
|
109
|
+
const said = [];
|
|
110
|
+
const run = async () => assert.fail("no run");
|
|
111
|
+
for (const bad of [[], argv.slice(2), [...argv, "--max-runs", "0"], [...argv, "--max-runs", "x"], [...argv, "--nope", "1"]]) {
|
|
112
|
+
assert.equal(await runCodexImplement(bad, { run, say: (line) => said.push(line) }), 1, bad.join(" "));
|
|
113
|
+
}
|
|
114
|
+
assert.match(said.join("\n"), /--brief/);
|
|
115
|
+
assert.match(said.join("\n"), /--max-runs/);
|
|
116
|
+
assert.match(said.join("\n"), /--nope/);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("parseArgs reads the flags, resolves the paths, and puts the log beside the progress file", () => {
|
|
120
|
+
const parsed = parseArgs(["--brief", "b.md", "--worktree", "w", "--progress", "p/progress.md", "--log", "x.log", "--max-runs", "5"]);
|
|
121
|
+
assert.equal(parsed.maxRuns, 5);
|
|
122
|
+
assert.equal(parsed.log, path.resolve("x.log"));
|
|
123
|
+
assert.equal(parsed.brief, path.resolve("b.md"));
|
|
124
|
+
assert.equal(parseArgs(["--brief", "b", "--worktree", "w", "--progress", "p/q.md"]).log, `${path.resolve("p/q.md")}.log`);
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
test("the default runner spawns without a shell, closes stdin, and appends output to the log", async (t) => {
|
|
128
|
+
const { dir, argv, progress, brief } = setup(t);
|
|
129
|
+
const fake = path.join(dir, "fake-codex.mjs");
|
|
130
|
+
writeFileSync(
|
|
131
|
+
fake,
|
|
132
|
+
[
|
|
133
|
+
'import { appendFileSync } from "node:fs";',
|
|
134
|
+
"let input = '';",
|
|
135
|
+
"for await (const chunk of process.stdin) input += chunk;",
|
|
136
|
+
"console.log(JSON.stringify({ args: process.argv.slice(2), role: process.env.QC_ROLE, input }));",
|
|
137
|
+
`if (process.env.FAKE_MODE === "limit") console.error("You have hit your usage limit");`,
|
|
138
|
+
`else appendFileSync(${JSON.stringify(progress)}, ${JSON.stringify(`${DONE_MARKER}
|
|
139
|
+
`)});`,
|
|
140
|
+
].join("\n"),
|
|
141
|
+
);
|
|
142
|
+
const log = path.join(dir, "run.log");
|
|
143
|
+
const done = await runCodexImplement([...argv, "--log", log], { codexCommand: [process.execPath, fake], say: quiet });
|
|
144
|
+
assert.equal(done, 0);
|
|
145
|
+
const line = JSON.parse(readFileSync(log, "utf8").trim().split("\n")[0]);
|
|
146
|
+
assert.equal(line.role, "implementer");
|
|
147
|
+
assert.equal(line.input, "");
|
|
148
|
+
assert.deepEqual(line.args.slice(0, 3), ["exec", "-s", "danger-full-access"]);
|
|
149
|
+
assert.ok(line.args[5].startsWith(readFileSync(brief, "utf8")));
|
|
150
|
+
|
|
151
|
+
writeFileSync(progress, "");
|
|
152
|
+
process.env.FAKE_MODE = "limit";
|
|
153
|
+
t.after(() => delete process.env.FAKE_MODE);
|
|
154
|
+
assert.equal(await runCodexImplement([...argv, "--log", log], { codexCommand: [process.execPath, fake], say: quiet }), 2);
|
|
155
|
+
assert.ok(readFileSync(log, "utf8").split("\n").filter((entry) => entry.startsWith("{")).length >= 2, "the log is appended, not replaced");
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
test("qc codex-implement is wired, and prints usage errors with exit 1", () => {
|
|
159
|
+
const result = spawnSync(process.execPath, [QC, "codex-implement"], { encoding: "utf8" });
|
|
160
|
+
assert.equal(result.status, 1);
|
|
161
|
+
assert.match(result.stderr, /--brief/);
|
|
162
|
+
assert.match(spawnSync(process.execPath, [QC], { encoding: "utf8" }).stdout, /qc codex-implement/);
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
test("a limit word that only echoes the brief is not a limit", async (t) => {
|
|
166
|
+
const { argv, brief } = setup(t);
|
|
167
|
+
writeFileSync(brief, "# Brief\n\nIf you hit a usage limit, stop and write notes.\n");
|
|
168
|
+
let calls = 0;
|
|
169
|
+
const run = async () => {
|
|
170
|
+
calls += 1;
|
|
171
|
+
return { status: 1, tail: "user\nIf you hit a usage limit, stop and write notes.\nexec failed\n" };
|
|
172
|
+
};
|
|
173
|
+
assert.equal(await runCodexImplement([...argv, "--max-runs", "2"], { run, say: quiet }), 3);
|
|
174
|
+
assert.equal(calls, 2);
|
|
175
|
+
});
|