@gtrabanco/agentic-workflow 0.1.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.
@@ -0,0 +1,358 @@
1
+ /**
2
+ * Tests for agwo edit — typed file services SDK.
3
+ *
4
+ * Uses node:test with temp directories for isolation.
5
+ * Covers: UnitDoc, Roadmap, Changelog, Budgets, Manifest, receipts, CLI smoke.
6
+ */
7
+
8
+ import { describe, it, before, after } from "node:test";
9
+ import { strictEqual, ok, throws } from "node:assert";
10
+ import { mkdtempSync, writeFileSync, readFileSync, rmSync, existsSync, mkdirSync } from "node:fs";
11
+ import { tmpdir } from "node:os";
12
+ import { join } from "node:path";
13
+ import { spawn } from "node:child_process";
14
+
15
+ // ── SDK imports ──────────────────────────────────────────────────────────
16
+ import { create, setSection, evidence_addRow, progress_logEntry, validate } from "../src/edit/UnitDoc.mjs";
17
+ import { rowUpsert, annotate } from "../src/edit/Roadmap.mjs";
18
+ import { rowAdd } from "../src/edit/Changelog.mjs";
19
+ import { ceilingRebase } from "../src/edit/Budgets.mjs";
20
+ import { skillAdd, skillRemove } from "../src/edit/Manifest.mjs";
21
+
22
+ // ── Test fixtures ────────────────────────────────────────────────────────
23
+
24
+ let tmpDir;
25
+ let unitDir;
26
+ let specPath;
27
+
28
+ before(() => {
29
+ tmpDir = mkdtempSync(join(tmpdir(), "agwo-edit-"));
30
+ unitDir = join(tmpDir, "docs", "features", "61-test-slug");
31
+ mkdirSync(unitDir, { recursive: true });
32
+ specPath = join(unitDir, "SPEC.md");
33
+ });
34
+
35
+ after(() => {
36
+ if (tmpDir && existsSync(tmpDir)) {
37
+ rmSync(tmpDir, { recursive: true, force: true });
38
+ }
39
+ });
40
+
41
+ // ── UnitDoc tests ────────────────────────────────────────────────────────
42
+
43
+ describe("UnitDoc", () => {
44
+ it("create produces 13 sections in order", () => {
45
+ const receipt = create(unitDir, "61-test-slug");
46
+ strictEqual(receipt.ok, true);
47
+ strictEqual(receipt.service, "unitDoc");
48
+ strictEqual(receipt.op, "create");
49
+
50
+ const content = readFileSync(specPath, "utf8");
51
+ const sections = [
52
+ "Objective", "Why", "User outcome", "Acceptance criteria",
53
+ "Non-goals", "Future cost", "Applicable tests",
54
+ "Known pre-existing issues", "Tasks", "Evidence",
55
+ "Progress log", "Next", "References",
56
+ ];
57
+
58
+ // All 13 sections must exist in order
59
+ let lastIdx = -1;
60
+ for (const section of sections) {
61
+ const idx = content.indexOf(`## ${section}`);
62
+ ok(idx !== -1, `Section "${section}" not found`);
63
+ ok(idx > lastIdx, `Section "${section}" out of order`);
64
+ lastIdx = idx;
65
+ }
66
+ });
67
+
68
+ it("setSection refuses an unknown section", () => {
69
+ throws(() => {
70
+ setSection(specPath, "UnknownSection", "body");
71
+ }, /Unknown section/);
72
+ });
73
+
74
+ it("setSection updates an existing section", () => {
75
+ const receipt = setSection(specPath, "Objective", "New objective body");
76
+ strictEqual(receipt.ok, true);
77
+
78
+ const content = readFileSync(specPath, "utf8");
79
+ ok(content.includes("New objective body"));
80
+ });
81
+
82
+ it("evidence.addRow writes the exact column shape", () => {
83
+ const receipt = evidence_addRow(specPath, {
84
+ ac: "AC-14",
85
+ command: "bun test edit.test.mjs",
86
+ exitDigest: "sha256:abc123",
87
+ output: "2 tests passed",
88
+ verifiedBy: "test-agent",
89
+ });
90
+ strictEqual(receipt.ok, true);
91
+
92
+ const content = readFileSync(specPath, "utf8");
93
+ ok(content.includes("| AC-14"));
94
+ ok(content.includes("| bun test edit.test.mjs"));
95
+ ok(content.includes("| sha256:abc123"));
96
+ ok(content.includes("| 2 tests passed"));
97
+ ok(content.includes("| test-agent |"));
98
+ });
99
+
100
+ it("progress entry with a bad timestamp is refused", () => {
101
+ throws(() => {
102
+ progress_logEntry(specPath, {
103
+ ts: "not-a-timestamp",
104
+ what: "did something",
105
+ ref: "abc123",
106
+ next: "do more",
107
+ });
108
+ }, /Progress entry does not match/);
109
+ });
110
+
111
+ it("progress entry with valid format succeeds", () => {
112
+ const receipt = progress_logEntry(specPath, {
113
+ ts: "2026-09-22 14:30",
114
+ what: "implemented agwo edit",
115
+ ref: "abc123def",
116
+ next: "write tests",
117
+ });
118
+ strictEqual(receipt.ok, true);
119
+
120
+ const content = readFileSync(specPath, "utf8");
121
+ ok(content.includes("2026-09-22 14:30 — implemented agwo edit → abc123def — next: write tests"));
122
+ });
123
+
124
+ it("validate returns violations for missing sections", () => {
125
+ const content = "# Test\n\n## Objective\n\nOnly one section";
126
+ const result = validate(content);
127
+ strictEqual(result.ok, false);
128
+ ok(result.violations.length > 0);
129
+ ok(result.violations.some((v) => v.includes("Why")));
130
+ });
131
+ });
132
+
133
+ // ── Roadmap tests ────────────────────────────────────────────────────────
134
+
135
+ describe("Roadmap", () => {
136
+ let roadmapPath;
137
+
138
+ before(() => {
139
+ roadmapPath = join(tmpDir, "ROADMAP.md");
140
+ const content = `# Roadmap
141
+
142
+ | NN | slug | status | depends-on | description |
143
+ |---|---|---|---|---|
144
+ `;
145
+ writeFileSync(roadmapPath, content, "utf8");
146
+ });
147
+
148
+ it("rowUpsert inserts a new row", () => {
149
+ const receipt = rowUpsert(roadmapPath, {
150
+ nn: "61",
151
+ slug: "adaptive-unit-lane",
152
+ status: "active",
153
+ dependsOn: "",
154
+ description: "Adaptive unit lane implementation",
155
+ });
156
+ strictEqual(receipt.ok, true);
157
+
158
+ const updated = readFileSync(roadmapPath, "utf8");
159
+ ok(updated.includes("| 61 | adaptive-unit-lane |"));
160
+ });
161
+
162
+ it("rowUpsert updates the same NN without duplicating", () => {
163
+ const receipt = rowUpsert(roadmapPath, {
164
+ nn: "61",
165
+ slug: "adaptive-unit-lane-v2",
166
+ status: "completed",
167
+ dependsOn: "",
168
+ description: "Updated description",
169
+ });
170
+ strictEqual(receipt.ok, true);
171
+
172
+ const content = readFileSync(roadmapPath, "utf8");
173
+ const count = content.split("| 61 |").length - 1;
174
+ strictEqual(count, 1);
175
+ });
176
+
177
+ it("annotate appends to the description", () => {
178
+ annotate(roadmapPath, "61", "Added annotation note");
179
+ const content = readFileSync(roadmapPath, "utf8");
180
+ ok(content.includes("— Added annotation note"));
181
+ });
182
+ });
183
+
184
+ // ── Changelog tests ──────────────────────────────────────────────────────
185
+
186
+ describe("Changelog", () => {
187
+ it("changelog row lands inside the named section's table", () => {
188
+ const changelogPath = join(tmpDir, "CHANGELOG.md");
189
+ const content = `# Changelog
190
+
191
+ #### \`unit-doc\`
192
+
193
+ | Version | Date | Type | What changed |
194
+ |---|---|---|---|
195
+
196
+ #### \`roadmap\`
197
+
198
+ | Version | Date | Type | What changed |
199
+ |---|---|---|---|
200
+ `;
201
+ writeFileSync(changelogPath, content, "utf8");
202
+
203
+ const receipt = rowAdd(changelogPath, "unit-doc", {
204
+ version: "0.1.0",
205
+ date: "2026-09-22",
206
+ type: "feature",
207
+ what: "Added agwo edit typed file services",
208
+ });
209
+ strictEqual(receipt.ok, true);
210
+
211
+ const updated = readFileSync(changelogPath, "utf8");
212
+ // The row should appear under unit-doc section, not roadmap
213
+ const parts = updated.split("#### `unit-doc`");
214
+ ok(parts.length >= 2);
215
+ const unitDocContent = parts[1];
216
+ const roadmapIdx = unitDocContent.indexOf("#### `roadmap`");
217
+ const unitDocOnly = roadmapIdx === -1 ? unitDocContent : unitDocContent.slice(0, roadmapIdx);
218
+ ok(unitDocOnly.includes("| 0.1.0 | 2026-09-22 | feature | Added agwo edit"));
219
+ });
220
+ });
221
+
222
+ // ── Budgets tests ────────────────────────────────────────────────────────
223
+
224
+ describe("Budgets", () => {
225
+ let budgetPath;
226
+
227
+ before(() => {
228
+ budgetPath = join(tmpDir, "budgets.json");
229
+ const content = JSON.stringify({
230
+ routes: {
231
+ "execute-phase": { estimateMax: 1000, linesMax: 500, sources: {} },
232
+ },
233
+ }, null, 2);
234
+ writeFileSync(budgetPath, content, "utf8");
235
+ });
236
+
237
+ it("budgets shrink without growth source is refused", () => {
238
+ const receipt = ceilingRebase(budgetPath, "execute-phase", 500, 250, "");
239
+ strictEqual(receipt.ok, false);
240
+ });
241
+
242
+ it("budgets shrink WITH growth source succeeds", () => {
243
+ const receipt = ceilingRebase(budgetPath, "execute-phase", 500, 250, "Optimization: reduced scope");
244
+ strictEqual(receipt.ok, true);
245
+
246
+ const content = readFileSync(budgetPath, "utf8");
247
+ const data = JSON.parse(content);
248
+ strictEqual(data.routes["execute-phase"].estimateMax, 500);
249
+ strictEqual(data.routes["execute-phase"].linesMax, 250);
250
+ strictEqual(data.routes["execute-phase"].sources.ceilingRebase, "Optimization: reduced scope");
251
+ });
252
+ });
253
+
254
+ // ── Manifest tests ───────────────────────────────────────────────────────
255
+
256
+ describe("Manifest", () => {
257
+ let pluginJsonPath;
258
+
259
+ before(() => {
260
+ pluginJsonPath = join(tmpDir, ".claude-plugin", "plugin.json");
261
+ mkdirSync(join(pluginJsonPath, ".."), { recursive: true });
262
+ const data = { skills: [] };
263
+ writeFileSync(pluginJsonPath, JSON.stringify(data, null, 2), "utf8");
264
+ });
265
+
266
+ it("manifest add keeps alphabetical order", () => {
267
+ skillAdd(pluginJsonPath, "zebra-skill", { description: "Z" });
268
+ skillAdd(pluginJsonPath, "alpha-skill", { description: "A" });
269
+ skillAdd(pluginJsonPath, "middle-skill", { description: "M" });
270
+
271
+ const content = readFileSync(pluginJsonPath, "utf8");
272
+ const parsed = JSON.parse(content);
273
+ const names = parsed.skills.map((s) => s.name);
274
+ strictEqual(names.length, 3);
275
+ strictEqual(names[0], "alpha-skill");
276
+ strictEqual(names[1], "middle-skill");
277
+ strictEqual(names[2], "zebra-skill");
278
+ });
279
+
280
+ it("manifest add refuses duplicate", () => {
281
+ throws(() => {
282
+ skillAdd(pluginJsonPath, "alpha-skill", { description: "duplicate" });
283
+ }, /already exists/);
284
+ });
285
+
286
+ it("manifest remove keeps alphabetical order", () => {
287
+ skillRemove(pluginJsonPath, "middle-skill");
288
+
289
+ const content = readFileSync(pluginJsonPath, "utf8");
290
+ const parsed = JSON.parse(content);
291
+ const names = parsed.skills.map((s) => s.name);
292
+ strictEqual(names.length, 2);
293
+ strictEqual(names[0], "alpha-skill");
294
+ strictEqual(names[1], "zebra-skill");
295
+ });
296
+ });
297
+
298
+ // ── Receipt tests ────────────────────────────────────────────────────────
299
+
300
+ describe("Receipts", () => {
301
+ it("receipts carry matching sha256 digests", () => {
302
+ const receipt = setSection(specPath, "Why", "New reason");
303
+ strictEqual(typeof receipt.before, "string");
304
+ strictEqual(typeof receipt.after, "string");
305
+ strictEqual(receipt.before.length, 8); // sha256 prefix is 8 chars
306
+ strictEqual(receipt.after.length, 8);
307
+ // Content changed so digests differ
308
+ strictNotEqual(receipt.before, receipt.after);
309
+ });
310
+ });
311
+
312
+ // ── CLI smoke test ───────────────────────────────────────────────────────
313
+
314
+ describe("CLI smoke", () => {
315
+ it("spawn bin/agwo.mjs unit-doc create --json parses", (t, done) => {
316
+ const testDir = mkdtempSync(join(tmpdir(), "agwo-cli-"));
317
+ const testUnitDir = join(testDir, "docs", "features", "cli-test");
318
+ mkdirSync(testUnitDir, { recursive: true });
319
+
320
+ const agwoPath = join(process.cwd(), "bin", "agwo.mjs");
321
+
322
+ const proc = spawn("node", [agwoPath, "unit-doc", "cli-test", "create", "--json"], {
323
+ cwd: testDir,
324
+ timeout: 10000,
325
+ });
326
+
327
+ let stdout = "";
328
+ let stderr = "";
329
+
330
+ proc.stdout.on("data", (data) => { stdout += data.toString(); });
331
+ proc.stderr.on("data", (data) => { stderr += data.toString(); });
332
+
333
+ proc.on("close", (code) => {
334
+ try {
335
+ strictEqual(code, 0);
336
+ const parsed = JSON.parse(stdout);
337
+ strictEqual(parsed.ok, true);
338
+ strictEqual(parsed.service, "unitDoc");
339
+ strictEqual(parsed.op, "create");
340
+ // Cleanup
341
+ rmSync(testDir, { recursive: true, force: true });
342
+ done();
343
+ } catch (e) {
344
+ rmSync(testDir, { recursive: true, force: true });
345
+ done(e);
346
+ }
347
+ });
348
+
349
+ proc.on("error", (e) => {
350
+ rmSync(testDir, { recursive: true, force: true });
351
+ done(e);
352
+ });
353
+ });
354
+ });
355
+
356
+ function strictNotEqual(a, b) {
357
+ if (a === b) throw new Error(`Expected ${a} !== ${b}`);
358
+ }
@@ -0,0 +1,326 @@
1
+ // Shared throwaway-repo fixture matrix for the turn-contract suites.
2
+ //
3
+ // The engine suite, the two-engine parity suite, and the grammar conformance
4
+ // test all drive the SAME matrix so a per-box outcome and the receipt grammar
5
+ // are asserted once and reused (D-52-9 proportionality, no combinatorial
6
+ // flag x state sweep). Everything lives in one temp directory; `gh` is a
7
+ // PATH-stub because no suite contacts a forge.
8
+
9
+ import { spawnSync } from "node:child_process";
10
+ import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
11
+ import os from "node:os";
12
+ import path from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+
15
+ const here = path.dirname(fileURLToPath(import.meta.url));
16
+ export const REPO_ROOT = path.resolve(here, "..", "..", "..");
17
+ export const ENGINE = path.join(REPO_ROOT, "packages/agentic-workflow/bin/turn-contract.mjs");
18
+ export const SHIM = path.join(REPO_ROOT, "template/.agentic-workflow/hooks/turn-contract.sh");
19
+
20
+ const GIT_CONFIG = ["-c", "user.email=t@example.com", "-c", "user.name=test", "-c", "commit.gpgsign=false"];
21
+
22
+ export function git(cwd, ...args) {
23
+ const r = spawnSync("git", [...GIT_CONFIG, "-C", cwd, ...args], { encoding: "utf8" });
24
+ if (r.status !== 0) throw new Error(`git ${args.join(" ")} in ${cwd} failed: ${r.stderr}`);
25
+ return r.stdout.trimEnd();
26
+ }
27
+
28
+ function gitInit(dir, branch) {
29
+ const r = spawnSync("git", ["init", "-q", "-b", branch, dir], { encoding: "utf8" });
30
+ if (r.status !== 0) throw new Error(`git init ${dir} failed: ${r.stderr}`);
31
+ }
32
+
33
+ function newRepo(root, name, branch) {
34
+ const dir = path.join(root, name);
35
+ gitInit(dir, branch);
36
+ writeFileSync(path.join(dir, "README.md"), "base\n");
37
+ git(dir, "add", "README.md");
38
+ git(dir, "commit", "-qm", "base");
39
+ return dir;
40
+ }
41
+
42
+ export { newRepo, commitFile };
43
+
44
+ function commitFile(dir, rel, content) {
45
+ const target = path.join(dir, rel);
46
+ mkdirSync(path.dirname(target), { recursive: true });
47
+ writeFileSync(target, content);
48
+ git(dir, "add", rel);
49
+ git(dir, "commit", "-qm", `add ${rel}`);
50
+ }
51
+
52
+ function bareRemote(root, dir, branch) {
53
+ const bare = path.join(root, `${path.basename(dir)}-remote.git`);
54
+ const r = spawnSync("git", ["init", "-q", "--bare", bare], { encoding: "utf8" });
55
+ if (r.status !== 0) throw new Error(`git init --bare failed: ${r.stderr}`);
56
+ git(dir, "remote", "add", "origin", bare);
57
+ git(dir, "push", "-qu", "origin", branch);
58
+ }
59
+
60
+ function unitBranch(root, name, branch, acceptance = "frozen") {
61
+ const dir = newRepo(root, name, "main");
62
+ git(dir, "checkout", "-q", "-b", branch);
63
+ // Feature 61: the unit document is the frozen surface at HEAD.
64
+ commitFile(dir, `docs/features/${branch.split("/")[1]}/SPEC.md`, `unit doc\n`);
65
+ return dir;
66
+ }
67
+
68
+ function ghStub(root) {
69
+ const dir = path.join(root, "bin");
70
+ mkdirSync(dir, { recursive: true });
71
+ const file = path.join(dir, "gh");
72
+ writeFileSync(
73
+ file,
74
+ [
75
+ "#!/usr/bin/env bash",
76
+ "# PATH-stub for gh. `pr list --head <branch>` answers with $GH_STUB_JSON (the",
77
+ "# pull requests of that branch); `pr view <arg>` answers with",
78
+ "# $GH_STUB_VIEW_JSON — real gh reads an all-numeric argument as a PR NUMBER",
79
+ "# and exits nonzero when no pull request matches the branch.",
80
+ "# $GH_STUB_EXIT forces a failure exit from either invocation;",
81
+ "# $GH_STUB_VIEW_EXIT forces one from `pr view` only (the real 'no PR for",
82
+ "# this branch' answer, which is what makes a missing PR",
83
+ "# indistinguishable from an unreachable gh in the pre-F9 query).",
84
+ 'case "$1 $2" in',
85
+ ' "pr list")\n printf \'%s\\n\' "${GH_STUB_JSON:-[]}"\n exit_code="${GH_STUB_EXIT:-0}"\n ;;',
86
+ ' "pr view")\n printf \'%s\\n\' "${GH_STUB_VIEW_JSON:-}"\n exit_code="${GH_STUB_VIEW_EXIT:-${GH_STUB_EXIT:-0}}"\n ;;',
87
+ " *) exit 3 ;;",
88
+ "esac",
89
+ '[ "$exit_code" -eq 0 ] || exit "$exit_code"',
90
+ "",
91
+ ].join("\n"),
92
+ );
93
+ chmodSync(file, 0o755);
94
+ return dir;
95
+ }
96
+
97
+ function buildFixtures(root) {
98
+ const fx = {};
99
+
100
+ // Unit-shaped, clean, no upstream -> the ok path.
101
+ fx.ok = unitBranch(root, "ok", "feat/ok");
102
+
103
+ // On the default branch.
104
+ fx.default = newRepo(root, "default", "main");
105
+
106
+ // Not a repository at all.
107
+ fx.notrepo = path.join(root, "notrepo");
108
+ mkdirSync(fx.notrepo, { recursive: true });
109
+
110
+ // Branch with no own commit.
111
+ fx.nocommits = newRepo(root, "nocommits", "main");
112
+ git(fx.nocommits, "checkout", "-q", "-b", "feat/none");
113
+
114
+ // Unborn branch, zero commits anywhere (dev scenario verifier:empty-repo).
115
+ fx.empty = path.join(root, "empty");
116
+ gitInit(fx.empty, "feature/x");
117
+
118
+ // Unit branch exists but the unit doc is absent at HEAD.
119
+ fx.missing = newRepo(root, "missing", "main");
120
+ git(fx.missing, "checkout", "-q", "-b", "feat/missing");
121
+ commitFile(fx.missing, "docs/features/missing/.gitkeep", "");
122
+
123
+ // Not unit-shaped -> box2 not applicable.
124
+ fx.plain = newRepo(root, "plain", "main");
125
+ git(fx.plain, "checkout", "-q", "-b", "chore/plain");
126
+ commitFile(fx.plain, "note.txt", "x\n");
127
+
128
+ // Unit path exists as a regular FILE, not a directory -> the unit directory
129
+ // does not exist, so box2 is not-applicable (ED-52-2) in BOTH engines
130
+ // (F5, review cycle 2).
131
+ fx.unitfile = newRepo(root, "unitfile", "main");
132
+ git(fx.unitfile, "checkout", "-q", "-b", "feat/unitfile");
133
+ commitFile(fx.unitfile, "docs/features/unitfile", "not a directory\n");
134
+
135
+ // Dirty tree.
136
+ fx.dirty = unitBranch(root, "dirty", "feat/dirty");
137
+ writeFileSync(path.join(fx.dirty, "README.md"), "base\ndirty\n");
138
+
139
+ // Pushed branch plus one local commit -> ahead of remote.
140
+ fx.ahead = unitBranch(root, "ahead", "feat/ahead");
141
+ bareRemote(root, fx.ahead, "feat/ahead");
142
+ commitFile(fx.ahead, "extra.txt", "local only\n");
143
+
144
+ // Dirty AND ahead simultaneously -> dirty wins inside box5.
145
+ fx.dirtyahead = unitBranch(root, "dirtyahead", "feat/dirtyahead");
146
+ bareRemote(root, fx.dirtyahead, "feat/dirtyahead");
147
+ commitFile(fx.dirtyahead, "extra.txt", "local only\n");
148
+ writeFileSync(path.join(fx.dirtyahead, "README.md"), "base\ndirty\n");
149
+
150
+ // Dirty tree with spaces / unicode filenames (dev scenario).
151
+ fx.unicode = unitBranch(root, "unicode", "feat/unicode");
152
+ writeFileSync(path.join(fx.unicode, "a b.txt"), "x\n");
153
+ writeFileSync(path.join(fx.unicode, "café.txt"), "x\n");
154
+
155
+ // Pushed branch with an upstream -> box4 exercises the gh stub.
156
+ fx.b4 = unitBranch(root, "b4", "feat/b4");
157
+ bareRemote(root, fx.b4, "feat/b4");
158
+
159
+ // Corrupt index: `git status` itself errors while branch/rev-list still
160
+ // answer -> box5 must fail closed, never print a fake ok (F1, review cycle 1).
161
+ fx.corrupt = unitBranch(root, "corrupt", "feat/corrupt");
162
+ writeFileSync(path.join(fx.corrupt, ".git/index"), "not a git index\n");
163
+
164
+ // Listing past the engine's 1 MiB read cap and past the shim's pipe buffer:
165
+ // both truncate, and both must still fail closed (F6, fold cycle 2). Long
166
+ // path segments keep the fixture cheap — 320 files ≈ 1.2 MB of porcelain.
167
+ fx.bigstatus = unitBranch(root, "bigstatus", "feat/bigstatus");
168
+ const longDir = Array.from({ length: 19 }, () => "d".repeat(200)).join("/");
169
+ commitFile(fx.bigstatus, `${longDir}/tracked.txt`, "x\n");
170
+ for (let i = 0; i < 320; i += 1) writeFileSync(path.join(fx.bigstatus, longDir, `f${i}`), "x\n");
171
+
172
+ // Repo-local `status.showUntrackedFiles=no` must not hide an untracked file
173
+ // from box5 (F8, fold cycle 3).
174
+ fx.hidden = unitBranch(root, "hidden", "feat/hidden");
175
+ git(fx.hidden, "config", "status.showUntrackedFiles", "no");
176
+ writeFileSync(path.join(fx.hidden, "untracked.txt"), "x\n");
177
+
178
+ // All-numeric branch name: a bare `gh pr view <branch>` argument is read by
179
+ // gh as a PR NUMBER, so box4 would judge the unrelated PR that shares the
180
+ // name instead of this branch (F11, fold cycle 3).
181
+ fx.numeric = newRepo(root, "numeric", "main");
182
+ git(fx.numeric, "checkout", "-q", "-b", "123");
183
+ commitFile(fx.numeric, "note.txt", "x\n");
184
+ bareRemote(root, fx.numeric, "123");
185
+
186
+ // Engine-only: the phase-lint clause of box2 (the shim cannot run it).
187
+ fx.lintfail = unitBranch(root, "lintfail", "feat/lintfail");
188
+ commitFile(fx.lintfail, "docs/features/lintfail/TASKS.md", "# TASKS\n");
189
+ commitFile(fx.lintfail, "scripts/phase-lint.mjs", "process.exit(1);\n");
190
+ fx.lintpass = unitBranch(root, "lintpass", "feat/lintpass");
191
+ commitFile(fx.lintpass, "docs/features/lintpass/TASKS.md", "# TASKS\n");
192
+ commitFile(fx.lintpass, "scripts/phase-lint.mjs", "process.exit(0);\n");
193
+
194
+ return fx;
195
+ }
196
+
197
+ function baseEnv(ghDir) {
198
+ return {
199
+ ...process.env,
200
+ PATH: `${ghDir}:${process.env.PATH}`,
201
+ AGENTIC_WORKFLOW_RUNTIME: "node",
202
+ };
203
+ }
204
+
205
+ export function makeContext() {
206
+ const root = mkdtempSync(path.join(os.tmpdir(), "tc-fixtures-"));
207
+ const ghDir = ghStub(root);
208
+ const fx = buildFixtures(root);
209
+ return {
210
+ root,
211
+ ghDir,
212
+ fx,
213
+ cleanup: () => rmSync(root, { recursive: true, force: true }),
214
+ runEngine(cwd, args = [], env = {}) {
215
+ const r = spawnSync(process.execPath, [ENGINE, ...args], {
216
+ cwd,
217
+ encoding: "utf8",
218
+ env: { ...baseEnv(ghDir), ...env },
219
+ });
220
+ return { code: r.status, stdout: r.stdout, stderr: r.stderr };
221
+ },
222
+ runShim(cwd, args = [], env = {}) {
223
+ const r = spawnSync("bash", [SHIM, ...args], {
224
+ cwd,
225
+ encoding: "utf8",
226
+ env: { ...baseEnv(ghDir), ...env },
227
+ });
228
+ return { code: r.status, stdout: r.stdout, stderr: r.stderr };
229
+ },
230
+ };
231
+ }
232
+
233
+ // The shared matrix for BOTH engines (no phase-lint fixture: that clause is
234
+ // engine-only, ED-52-3).
235
+ export function receiptCases(ctx) {
236
+ const head = git(ctx.fx.b4, "rev-parse", "HEAD");
237
+ return [
238
+ { name: "box1 default branch", dir: ctx.fx.default, code: 1, line: "TURN-CONTRACT fail box1: branch-default" },
239
+ { name: "box1 not a repo", dir: ctx.fx.notrepo, code: 1, line: "TURN-CONTRACT fail box1: not-a-repo" },
240
+ { name: "box2 unit-doc missing", dir: ctx.fx.missing, code: 1, line: "TURN-CONTRACT fail box2: unit-doc-missing" },
241
+ { name: "box2 not applicable", dir: ctx.fx.plain, code: 0, line: "TURN-CONTRACT ok" },
242
+ { name: "box2 unit path is a file", dir: ctx.fx.unitfile, code: 0, line: "TURN-CONTRACT ok" },
243
+ { name: "box3 no commits", dir: ctx.fx.nocommits, code: 1, line: "TURN-CONTRACT fail box3: no-commits" },
244
+ { name: "box3 empty repo", dir: ctx.fx.empty, code: 1, line: "TURN-CONTRACT fail box3: no-commits" },
245
+ { name: "box4 not applicable", dir: ctx.fx.ok, code: 0, line: "TURN-CONTRACT ok" },
246
+ { name: "box4 no upstream", dir: ctx.fx.ok, args: ["--finished"], code: 1, line: "TURN-CONTRACT fail box4: pr-not-open" },
247
+ {
248
+ name: "box4 gh unreachable",
249
+ dir: ctx.fx.b4,
250
+ args: ["--finished"],
251
+ env: { GH_STUB_EXIT: "1" },
252
+ code: 1,
253
+ line: "TURN-CONTRACT fail box4: pr-unreachable",
254
+ },
255
+ {
256
+ name: "box4 no PR for the branch",
257
+ dir: ctx.fx.b4,
258
+ args: ["--finished"],
259
+ // The branch is pushed and has no PR: `pr list` answers that with exit 0
260
+ // and an empty result; the pre-F9 query (`pr view`) exits nonzero for the
261
+ // same state, which is why it reports a missing PR as pr-unreachable.
262
+ env: { GH_STUB_JSON: "[]", GH_STUB_VIEW_EXIT: "1" },
263
+ code: 1,
264
+ line: "TURN-CONTRACT fail box4: pr-not-open",
265
+ },
266
+ {
267
+ name: "box4 merged PR is not an open PR",
268
+ dir: ctx.fx.b4,
269
+ args: ["--finished"],
270
+ env: {
271
+ GH_STUB_JSON: JSON.stringify([{ headRefOid: head, state: "MERGED" }]),
272
+ GH_STUB_VIEW_JSON: JSON.stringify({ headRefOid: head, state: "MERGED" }),
273
+ },
274
+ code: 1,
275
+ line: "TURN-CONTRACT fail box4: pr-not-open",
276
+ },
277
+ {
278
+ name: "box4 head mismatch",
279
+ dir: ctx.fx.b4,
280
+ args: ["--finished"],
281
+ env: { GH_STUB_JSON: JSON.stringify([{ headRefOid: "0".repeat(40), state: "OPEN" }]) },
282
+ code: 1,
283
+ line: "TURN-CONTRACT fail box4: pr-head-mismatch",
284
+ },
285
+ {
286
+ name: "box4 open PR at HEAD",
287
+ dir: ctx.fx.b4,
288
+ args: ["--finished"],
289
+ env: { GH_STUB_JSON: JSON.stringify([{ headRefOid: head, state: "OPEN" }]) },
290
+ code: 0,
291
+ line: "TURN-CONTRACT ok",
292
+ },
293
+ {
294
+ name: "box4 numeric branch is not a PR number",
295
+ dir: ctx.fx.numeric,
296
+ args: ["--finished"],
297
+ env: {
298
+ GH_STUB_JSON: "[]",
299
+ GH_STUB_VIEW_JSON: JSON.stringify({ headRefOid: "0".repeat(40), state: "OPEN" }),
300
+ },
301
+ code: 1,
302
+ line: "TURN-CONTRACT fail box4: pr-not-open",
303
+ },
304
+ { name: "box5 dirty tree", dir: ctx.fx.dirty, code: 1, line: "TURN-CONTRACT fail box5: dirty-tree" },
305
+ { name: "box5 ahead of remote", dir: ctx.fx.ahead, code: 1, line: "TURN-CONTRACT fail box5: ahead-of-remote" },
306
+ { name: "box5 dirty precedes ahead", dir: ctx.fx.dirtyahead, code: 1, line: "TURN-CONTRACT fail box5: dirty-tree" },
307
+ { name: "box5 unicode/space names", dir: ctx.fx.unicode, code: 1, line: "TURN-CONTRACT fail box5: dirty-tree" },
308
+ {
309
+ name: "box5 ignores status.showUntrackedFiles=no",
310
+ dir: ctx.fx.hidden,
311
+ code: 1,
312
+ line: "TURN-CONTRACT fail box5: dirty-tree",
313
+ },
314
+ { name: "box5 unreadable status fails closed", dir: ctx.fx.corrupt, code: 1, line: "TURN-CONTRACT fail box5: dirty-tree" },
315
+ { name: "box5 huge listing fails closed", dir: ctx.fx.bigstatus, code: 1, line: "TURN-CONTRACT fail box5: dirty-tree" },
316
+ { name: "clean feature branch", dir: ctx.fx.ok, code: 0, line: "TURN-CONTRACT ok" },
317
+ ];
318
+ }
319
+
320
+ // Engine-only cases: the phase-lint clause of box2.
321
+ export function engineOnlyCases(ctx) {
322
+ return [
323
+ { name: "box2 phase-lint failed", dir: ctx.fx.lintfail, code: 1, line: "TURN-CONTRACT fail box2: phase-lint-failed" },
324
+ { name: "box2 phase-lint green", dir: ctx.fx.lintpass, code: 0, line: "TURN-CONTRACT ok" },
325
+ ];
326
+ }