@warpgogol/forge 9.4.1 → 9.5.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.
Files changed (109) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/bin/cli.ts +152 -11
  3. package/dist/bin/cli.js +125 -5
  4. package/dist/bin/cli.js.map +1 -1
  5. package/dist/os/flow/dirty-classify.d.ts +7 -0
  6. package/dist/os/flow/dirty-classify.d.ts.map +1 -1
  7. package/dist/os/flow/dirty-classify.js +11 -0
  8. package/dist/os/flow/dirty-classify.js.map +1 -1
  9. package/dist/os/flow/flow.module.d.ts.map +1 -1
  10. package/dist/os/flow/flow.module.js +3 -2
  11. package/dist/os/flow/flow.module.js.map +1 -1
  12. package/dist/os/flow/handlers/flow-check.d.ts.map +1 -1
  13. package/dist/os/flow/handlers/flow-check.js +9 -9
  14. package/dist/os/flow/handlers/flow-check.js.map +1 -1
  15. package/dist/os/flow/handlers/flow-integrate.d.ts.map +1 -1
  16. package/dist/os/flow/handlers/flow-integrate.js +59 -26
  17. package/dist/os/flow/handlers/flow-integrate.js.map +1 -1
  18. package/dist/os/flow/handlers/flow-open.d.ts.map +1 -1
  19. package/dist/os/flow/handlers/flow-open.js +14 -19
  20. package/dist/os/flow/handlers/flow-open.js.map +1 -1
  21. package/dist/os/flow/index.d.ts +1 -0
  22. package/dist/os/flow/index.d.ts.map +1 -1
  23. package/dist/os/flow/index.js +5 -3
  24. package/dist/os/flow/index.js.map +1 -1
  25. package/dist/os/flow/preflight.d.ts +24 -0
  26. package/dist/os/flow/preflight.d.ts.map +1 -1
  27. package/dist/os/flow/preflight.js +354 -10
  28. package/dist/os/flow/preflight.js.map +1 -1
  29. package/dist/os/flow/registry.d.ts +2 -2
  30. package/dist/os/gate-run/detach.d.ts +27 -0
  31. package/dist/os/gate-run/detach.d.ts.map +1 -0
  32. package/dist/os/gate-run/detach.js +85 -0
  33. package/dist/os/gate-run/detach.js.map +1 -0
  34. package/dist/os/gate-run/gate-run.module.d.ts +3 -0
  35. package/dist/os/gate-run/gate-run.module.d.ts.map +1 -0
  36. package/dist/os/gate-run/gate-run.module.js +23 -0
  37. package/dist/os/gate-run/gate-run.module.js.map +1 -0
  38. package/dist/os/gate-run/index.d.ts +7 -0
  39. package/dist/os/gate-run/index.d.ts.map +1 -0
  40. package/dist/os/gate-run/index.js +5 -0
  41. package/dist/os/gate-run/index.js.map +1 -0
  42. package/dist/os/gate-run/record.d.ts +47 -0
  43. package/dist/os/gate-run/record.d.ts.map +1 -0
  44. package/dist/os/gate-run/record.js +157 -0
  45. package/dist/os/gate-run/record.js.map +1 -0
  46. package/dist/os/gate-run/status.d.ts +41 -0
  47. package/dist/os/gate-run/status.d.ts.map +1 -0
  48. package/dist/os/gate-run/status.js +142 -0
  49. package/dist/os/gate-run/status.js.map +1 -0
  50. package/dist/os/gate-run/types.d.ts +47 -0
  51. package/dist/os/gate-run/types.d.ts.map +1 -0
  52. package/dist/os/gate-run/types.js +24 -0
  53. package/dist/os/gate-run/types.js.map +1 -0
  54. package/dist/os/rfc/evidence-annotation.d.ts +26 -0
  55. package/dist/os/rfc/evidence-annotation.d.ts.map +1 -0
  56. package/dist/os/rfc/evidence-annotation.js +52 -0
  57. package/dist/os/rfc/evidence-annotation.js.map +1 -0
  58. package/dist/os/rfc/handlers/fixed-inputs.d.ts.map +1 -1
  59. package/dist/os/rfc/handlers/fixed-inputs.js +7 -1
  60. package/dist/os/rfc/handlers/fixed-inputs.js.map +1 -1
  61. package/dist/os/rfc/handlers/implement-stamp.d.ts.map +1 -1
  62. package/dist/os/rfc/handlers/implement-stamp.js +21 -28
  63. package/dist/os/rfc/handlers/implement-stamp.js.map +1 -1
  64. package/dist/os/rfc/handlers/validate-rules.d.ts.map +1 -1
  65. package/dist/os/rfc/handlers/validate-rules.js +127 -7
  66. package/dist/os/rfc/handlers/validate-rules.js.map +1 -1
  67. package/dist/os/rfc/rfc.module.d.ts.map +1 -1
  68. package/dist/os/rfc/rfc.module.js +3 -2
  69. package/dist/os/rfc/rfc.module.js.map +1 -1
  70. package/dist/src/cli-flags.d.ts.map +1 -1
  71. package/dist/src/cli-flags.js +6 -0
  72. package/dist/src/cli-flags.js.map +1 -1
  73. package/dist/src/types.d.ts +7 -0
  74. package/dist/src/types.d.ts.map +1 -1
  75. package/dist/src/types.js +2 -8
  76. package/dist/src/types.js.map +1 -1
  77. package/os/flow/dirty-classify.ts +13 -0
  78. package/os/flow/flow.module.ts +3 -2
  79. package/os/flow/handlers/flow-check.ts +17 -18
  80. package/os/flow/handlers/flow-integrate.ts +75 -35
  81. package/os/flow/handlers/flow-open.ts +24 -31
  82. package/os/flow/index.ts +5 -7
  83. package/os/flow/preflight.ts +351 -9
  84. package/os/flow/tests/flow-integrate.preflight.test.ts +26 -5
  85. package/os/flow/tests/flow-integrate.test.ts +68 -2
  86. package/os/flow/tests/lockfile-induced.test.ts +328 -0
  87. package/os/gate-run/detach.ts +106 -0
  88. package/os/gate-run/gate-run.module.ts +25 -0
  89. package/os/gate-run/index.ts +16 -0
  90. package/os/gate-run/record.ts +194 -0
  91. package/os/gate-run/status.ts +168 -0
  92. package/os/gate-run/tests/gate-run-detach.test.ts +144 -0
  93. package/os/gate-run/tests/gate-run-record.test.ts +200 -0
  94. package/os/gate-run/types.ts +73 -0
  95. package/os/rfc/evidence-annotation.ts +61 -0
  96. package/os/rfc/handlers/fixed-inputs.test.ts +70 -0
  97. package/os/rfc/handlers/fixed-inputs.ts +11 -1
  98. package/os/rfc/handlers/implement-stamp.ts +25 -28
  99. package/os/rfc/handlers/list-create.test.ts +14 -5
  100. package/os/rfc/handlers/validate-evidence-shape.test.ts +218 -0
  101. package/os/rfc/handlers/validate-probe-meta.test.ts +71 -0
  102. package/os/rfc/handlers/validate-rules.ts +169 -17
  103. package/os/rfc/handlers/validate-transient-probes.test.ts +222 -0
  104. package/os/rfc/rfc-0000-template.md +10 -10
  105. package/os/rfc/rfc.module.ts +3 -2
  106. package/package.json +17 -1
  107. package/skills/fo/fo-session-retro/SKILL.md +4 -2
  108. package/src/cli-flags.ts +7 -0
  109. package/src/types.ts +9 -8
@@ -0,0 +1,328 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>ADR-0130 (F-0201): the induced-change lockfile shapes —
4
+ importer-materialize with `optional: true` removals and `key:` → `key: {}`
5
+ collapses on reachable snapshots, and importer-prune with inverse induced
6
+ additions — classify into their tolerated classes instead of `work`, while
7
+ a real content change (a version bump) stays `work`.</purpose>
8
+ <non-goals>
9
+ <item>No integrate-level restore coverage — the foreign-open-mission restore
10
+ path itself is covered in the preflight/integrate suites; these tests pin
11
+ the classification boundary the sweep depends on.</item>
12
+ </non-goals>
13
+ </MODULE_CONTRACT>
14
+ <CHANGE_SUMMARY>
15
+ <item>ADR-0130: induced-change lockfile classifiers — materialize BFS reachability + prune induced additions</item>
16
+ <item>ADR-0130: induced-change lockfile classifiers — BFS reachability for optional-flag removals, collapse pairs, induced packages/snapshots additions</item>
17
+ </CHANGE_SUMMARY>
18
+ */
19
+
20
+ import { describe, expect, it, afterEach } from "vitest";
21
+ import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
22
+ import { tmpdir } from "node:os";
23
+ import { join } from "node:path";
24
+
25
+ import { ambientIo } from "../../../src/utils/io.ts";
26
+ import {
27
+ classifyLockfileMaterializeExtended,
28
+ classifyLockfilePruneIdsExtended,
29
+ } from "../preflight.ts";
30
+
31
+ const dirs: string[] = [];
32
+ afterEach(async () => {
33
+ for (const dir of dirs.splice(0)) {
34
+ await rm(dir, { recursive: true, force: true });
35
+ }
36
+ });
37
+
38
+ // Fixture cut from commit 9fc5be128 (importer materialize + induced removals):
39
+ // HEAD lacks the mission importer; the working file gains it plus
40
+ // `optional: true` removals and a `buffer-from` collapse on reachable snapshots.
41
+ const HEAD_MATERIALIZE = `lockfileVersion: '9.0'
42
+
43
+ importers:
44
+
45
+ .:
46
+ dependencies:
47
+ yaml:
48
+ specifier: ^2.9.1
49
+ version: 2.9.1
50
+
51
+ packages:
52
+
53
+ yaml@2.9.1:
54
+ resolution: {integrity: sha1}
55
+
56
+ buffer-from@1.1.2:
57
+ resolution: {integrity: sha2}
58
+
59
+ buffer-crc32@0.2.13:
60
+ resolution: {integrity: sha3}
61
+
62
+ snapshots:
63
+
64
+ yaml@2.9.1: {}
65
+
66
+ buffer-crc32@0.2.13:
67
+ optional: true
68
+
69
+ buffer-from@1.1.2:
70
+ optional: true
71
+ `;
72
+
73
+ const DIFF_MATERIALIZE = `diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
74
+ index aaa..bbb 100644
75
+ --- a/pnpm-lock.yaml
76
+ +++ b/pnpm-lock.yaml
77
+ @@ -5,7 +5,15 @@ importers:
78
+ .:
79
+ dependencies:
80
+ yaml:
81
+ specifier: ^2.9.1
82
+ version: 2.9.1
83
+
84
+ + missions/site-m000001/workpiece:
85
+ + dependencies:
86
+ + buffer-from:
87
+ + specifier: ^1.1.2
88
+ + version: 1.1.2
89
+ + buffer-crc32:
90
+ + specifier: ^0.2.13
91
+ + version: 0.2.13
92
+ +
93
+ packages:
94
+ @@ -22,10 +30,9 @@ snapshots:
95
+
96
+ yaml@2.9.1: {}
97
+
98
+ buffer-crc32@0.2.13:
99
+ - optional: true
100
+
101
+ - buffer-from@1.1.2:
102
+ - optional: true
103
+ + buffer-from@1.1.2: {}
104
+
105
+ `;
106
+
107
+ const WORK_MATERIALIZE = `lockfileVersion: '9.0'
108
+
109
+ importers:
110
+
111
+ .:
112
+ dependencies:
113
+ yaml:
114
+ specifier: ^2.9.1
115
+ version: 2.9.1
116
+
117
+ missions/site-m000001/workpiece:
118
+ dependencies:
119
+ buffer-from:
120
+ specifier: ^1.1.2
121
+ version: 1.1.2
122
+ buffer-crc32:
123
+ specifier: ^0.2.13
124
+ version: 0.2.13
125
+
126
+ packages:
127
+
128
+ yaml@2.9.1:
129
+ resolution: {integrity: sha1}
130
+
131
+ buffer-from@1.1.2:
132
+ resolution: {integrity: sha2}
133
+
134
+ buffer-crc32@0.2.13:
135
+ resolution: {integrity: sha3}
136
+
137
+ snapshots:
138
+
139
+ yaml@2.9.1: {}
140
+
141
+ buffer-crc32@0.2.13:
142
+
143
+ buffer-from@1.1.2: {}
144
+ `;
145
+
146
+ // Fixture cut from commit 391abcfaf (importer prune + induced additions):
147
+ // HEAD carries the mission importer; the working file drops it and gains
148
+ // `optional: true`/`transitivePeerDependencies`/snapshot entries.
149
+ const HEAD_PRUNE = `lockfileVersion: '9.0'
150
+
151
+ importers:
152
+
153
+ .:
154
+ dependencies:
155
+ yaml:
156
+ specifier: ^2.9.1
157
+ version: 2.9.1
158
+
159
+ missions/site-m000001/workpiece:
160
+ dependencies:
161
+ buffer-from:
162
+ specifier: ^1.1.2
163
+ version: 1.1.2
164
+
165
+ packages:
166
+
167
+ yaml@2.9.1:
168
+ resolution: {integrity: sha1}
169
+
170
+ buffer-from@1.1.2:
171
+ resolution: {integrity: sha2}
172
+
173
+ snapshots:
174
+
175
+ yaml@2.9.1: {}
176
+
177
+ buffer-from@1.1.2: {}
178
+ `;
179
+
180
+ const DIFF_PRUNE = `diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
181
+ index ccc..ddd 100644
182
+ --- a/pnpm-lock.yaml
183
+ +++ b/pnpm-lock.yaml
184
+ @@ -9,7 +9,4 @@ importers:
185
+ specifier: ^2.9.1
186
+ version: 2.9.1
187
+
188
+ - missions/site-m000001/workpiece:
189
+ - dependencies:
190
+ - buffer-from:
191
+ - specifier: ^1.1.2
192
+ - version: 1.1.2
193
+
194
+ packages:
195
+ @@ -25,6 +22,13 @@ snapshots:
196
+
197
+ yaml@2.9.1: {}
198
+
199
+ - buffer-from@1.1.2: {}
200
+ + buffer-from@1.1.2:
201
+ + optional: true
202
+ +
203
+ + buffer-crc32@0.2.13:
204
+ + dependencies:
205
+ + x: 1.0.0
206
+ + transitivePeerDependencies:
207
+ + - prettier
208
+ + optional: true
209
+
210
+ `;
211
+
212
+ const DIFF_VERSION_BUMP = `diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
213
+ index eee..fff 100644
214
+ --- a/pnpm-lock.yaml
215
+ +++ b/pnpm-lock.yaml
216
+ @@ -5,6 +5,11 @@ importers:
217
+ .:
218
+ dependencies:
219
+ yaml:
220
+ - specifier: ^2.9.1
221
+ - version: 2.9.1
222
+ + specifier: ^3.0.0
223
+ + version: 3.0.0
224
+ +
225
+ + missions/site-m000001/workpiece:
226
+ + dependencies:
227
+ + buffer-from:
228
+ + specifier: ^1.1.2
229
+ + version: 1.1.2
230
+ +
231
+ packages:
232
+ `;
233
+
234
+ describe("classifyLockfileMaterializeExtended — ADR-0130", () => {
235
+ it("the 9fc5be128 shape (importer add + optional removals + collapse) classifies importer-materialize", () => {
236
+ expect(
237
+ classifyLockfileMaterializeExtended(DIFF_MATERIALIZE, HEAD_MATERIALIZE, WORK_MATERIALIZE),
238
+ ).toEqual(["site-m000001"]);
239
+ });
240
+
241
+ it("an `optional: true` removal on an unreachable snapshot keeps the diff unattributed", () => {
242
+ // drop buffer-crc32 from the mission's deps — its optional removal is
243
+ // then outside the added importers' closure.
244
+ const narrowed = WORK_MATERIALIZE.replace(
245
+ ` buffer-crc32:
246
+ specifier: ^0.2.13
247
+ version: 0.2.13
248
+ `,
249
+ "",
250
+ );
251
+ expect(
252
+ classifyLockfileMaterializeExtended(DIFF_MATERIALIZE, HEAD_MATERIALIZE, narrowed),
253
+ ).toBeNull();
254
+ });
255
+ });
256
+
257
+ describe("classifyLockfilePruneIdsExtended — ADR-0130", () => {
258
+ it("the 391abcfaf shape (importer prune + induced additions) returns the pruned ids", () => {
259
+ expect(classifyLockfilePruneIdsExtended(DIFF_PRUNE, HEAD_PRUNE)).toEqual(["site-m000001"]);
260
+ });
261
+
262
+ it("a version-string change inside the diff keeps the diff unattributed", () => {
263
+ expect(classifyLockfilePruneIdsExtended(DIFF_VERSION_BUMP, HEAD_MATERIALIZE)).toBeNull();
264
+ expect(
265
+ classifyLockfileMaterializeExtended(DIFF_VERSION_BUMP, HEAD_MATERIALIZE, WORK_MATERIALIZE),
266
+ ).toBeNull();
267
+ });
268
+ });
269
+
270
+ describe("classifyDirt — induced shapes (ADR-0130)", () => {
271
+ it("the 391abcfaf shape against a foreign open mission classifies foreign-open-mission (restored, not swept)", async () => {
272
+ const { classifyDirt } = await import("../preflight.ts");
273
+ const repo = await mkdtemp(join(tmpdir(), "dirt-"));
274
+ dirs.push(repo);
275
+ // classifyDirt reads the working lockfile through io — content is
276
+ // irrelevant for the prune direction (only HEAD text + diff are used).
277
+ await writeFile(join(repo, "pnpm-lock.yaml"), HEAD_PRUNE);
278
+ const runGit = async (_cwd: string, _io: unknown, args: string[]) => {
279
+ const joined = args.join(" ");
280
+ if (joined.includes("diff")) return { exitCode: 0, stdout: DIFF_PRUNE, stderr: "" };
281
+ if (joined.includes("show")) return { exitCode: 0, stdout: HEAD_PRUNE, stderr: "" };
282
+ return { exitCode: 0, stdout: "", stderr: "" };
283
+ };
284
+ const verdict = await classifyDirt(
285
+ repo,
286
+ ambientIo,
287
+ [" M pnpm-lock.yaml"],
288
+ { runGit: runGit as never },
289
+ [],
290
+ async (ids) =>
291
+ ids.map((missionId) => ({
292
+ missionId,
293
+ existsHere: false,
294
+ existsInCheckout: ["/repo@auto/foreign"],
295
+ missionOpen: true,
296
+ })),
297
+ );
298
+ expect(verdict.tolerated).toEqual([
299
+ {
300
+ path: "pnpm-lock.yaml",
301
+ class: "foreign-open-mission",
302
+ missionIds: ["site-m000001"],
303
+ },
304
+ ]);
305
+ expect(verdict.unattributed).toEqual([]);
306
+ });
307
+
308
+ it("the 9fc5be128 shape with an open mission classifies importer-materialize", async () => {
309
+ const { classifyDirt } = await import("../preflight.ts");
310
+ const repo = await mkdtemp(join(tmpdir(), "dirt-"));
311
+ dirs.push(repo);
312
+ await writeFile(join(repo, "pnpm-lock.yaml"), WORK_MATERIALIZE);
313
+ // the mission must read as open — openMissionsIn globs missions/*/mission.yaml
314
+ await mkdir(join(repo, "missions/site-m000001"), { recursive: true });
315
+ await writeFile(join(repo, "missions/site-m000001/mission.yaml"), 'state: "open"\n');
316
+ const runGit = async (_cwd: string, _io: unknown, args: string[]) => {
317
+ const joined = args.join(" ");
318
+ if (joined.includes("diff")) return { exitCode: 0, stdout: DIFF_MATERIALIZE, stderr: "" };
319
+ if (joined.includes("show")) return { exitCode: 0, stdout: HEAD_MATERIALIZE, stderr: "" };
320
+ return { exitCode: 0, stdout: "", stderr: "" };
321
+ };
322
+ const verdict = await classifyDirt(repo, ambientIo, [" M pnpm-lock.yaml"], {
323
+ runGit: runGit as never,
324
+ });
325
+ expect(verdict.tolerated).toEqual([{ path: "pnpm-lock.yaml", class: "importer-materialize" }]);
326
+ expect(verdict.unattributed).toEqual([]);
327
+ });
328
+ });
@@ -0,0 +1,106 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1568 — detach mechanics: the parent re-spawns the same CLI
4
+ entrypoint with `--detach` stripped, stdio routed to the run's log file,
5
+ `WERKSTATT_GATE_RUN_ID` in env so the child adopts the parent's record,
6
+ then prints the pointer block and exits 0.</purpose>
7
+ <non-goals>
8
+ <item>No output mirroring — detached output lives only in the log file.</item>
9
+ <item>No waiting on the gate itself — only a ≤2 s heartbeat on the child's
10
+ first record write, so an unspawnable child surfaces before the parent
11
+ returns.</item>
12
+ </non-goals>
13
+ </MODULE_CONTRACT>
14
+ <CHANGE_SUMMARY>
15
+ <item>RFC-1568: step 3 — detachSelf with injected SpawnLike</item>
16
+ <item>RFC-1568: durable gate-run records, --detach mechanics, and forge CLI wiring</item>
17
+ </CHANGE_SUMMARY>
18
+ */
19
+
20
+ // kernel-io-lint IO-01 carve-out (RFC-1568 / DNA-105): a detached gate is the
21
+ // "genuinely long-lived child process" class the spawn carve-out exists for.
22
+ // The spawner stays injectable — unit tests never spawn real gates.
23
+ import { spawn as nodeSpawn } from "node:child_process";
24
+ import { closeSync, openSync } from "node:fs";
25
+ import { join } from "node:path";
26
+
27
+ import type { GateRunRecord, SpawnLike } from "./types.ts";
28
+ import { gateRunsDir } from "./record.ts";
29
+
30
+ export const GATE_RUN_ID_ENV = "WERKSTATT_GATE_RUN_ID";
31
+ /** How long the parent waits for the child's first record write. */
32
+ export const HEARTBEAT_WAIT_MS = 2_000;
33
+
34
+ export interface DetachResult {
35
+ pid: number;
36
+ logPath: string;
37
+ runId: string;
38
+ }
39
+
40
+ /**
41
+ * Re-spawn the current CLI detached. `entry` is process.argv[1] of the
42
+ * running host (`forge` bin or `werkstatt` bin); `argv` carries the command
43
+ * and its flags minus `--detach` — for the kernel host it MUST keep the
44
+ * leading `run` token so the child re-enters the same dispatch path.
45
+ */
46
+ export async function detachSelf(input: {
47
+ entry: string;
48
+ argv: string[];
49
+ record: GateRunRecord;
50
+ commonGitDir: string;
51
+ spawn?: SpawnLike;
52
+ /** Reads the record back for the heartbeat — injected in tests. */
53
+ recordExists?: (runId: string) => Promise<boolean>;
54
+ }): Promise<DetachResult> {
55
+ const doSpawn: SpawnLike = input.spawn ?? (nodeSpawn as unknown as SpawnLike);
56
+ const logPath = join(gateRunsDir(input.commonGitDir), `${input.record.runId}.log`);
57
+ const logFd = openSync(logPath, "a");
58
+ try {
59
+ // process.execArgv forwards the host's loader flags (--import tsx, …) —
60
+ // a bare `node entry.ts` dies with ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX.
61
+ const child = doSpawn(process.execPath, [...process.execArgv, input.entry, ...input.argv], {
62
+ detached: true,
63
+ stdio: ["ignore", logFd, logFd],
64
+ env: { ...process.env, [GATE_RUN_ID_ENV]: input.record.runId },
65
+ });
66
+ child.unref();
67
+ const pid = child.pid;
68
+ if (pid === undefined) {
69
+ throw new Error("spawn returned no pid");
70
+ }
71
+
72
+ // ≤2 s heartbeat — the child adopts the record by rewriting it with its
73
+ // own pid; if that write never lands the parent reports the spawn
74
+ // failure instead of leaving an untrackable process.
75
+ if (input.recordExists !== undefined) {
76
+ const deadline = Date.now() + HEARTBEAT_WAIT_MS;
77
+ while (Date.now() < deadline) {
78
+ if (await input.recordExists(input.record.runId)) break;
79
+ await new Promise((r) => setTimeout(r, 50));
80
+ }
81
+ }
82
+ return { pid, logPath, runId: input.record.runId };
83
+ } finally {
84
+ try {
85
+ closeSync(logFd);
86
+ } catch {
87
+ // fd already closed — nothing to do
88
+ }
89
+ }
90
+ }
91
+
92
+ /** Pretty pointer block printed by the parent before exiting. */
93
+ export function detachPointerLines(
94
+ result: DetachResult,
95
+ commonGitDir: string,
96
+ statusCommand: string,
97
+ ): string[] {
98
+ const relLog = result.logPath.startsWith(commonGitDir)
99
+ ? `.git/${result.logPath.slice(commonGitDir.length + 1)}`
100
+ : result.logPath;
101
+ return [
102
+ `[gate-run] started ${result.runId} (pid ${result.pid})`,
103
+ ` log: ${relLog}`,
104
+ ` status: ${statusCommand} --id ${result.runId}`,
105
+ ];
106
+ }
@@ -0,0 +1,25 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1568 — forge module registration for `gate.run.status`. A forge
4
+ module so both hosts (standalone `forge` CLI + `werkstatt run` kernel) see
5
+ the command through their existing forge-module loading.</purpose>
6
+ </MODULE_CONTRACT>
7
+ <CHANGE_SUMMARY>
8
+ <item>RFC-1568: step 4 — gate-run module</item>
9
+ <item>RFC-1568: durable gate-run records, --detach mechanics, and forge CLI wiring</item>
10
+ </CHANGE_SUMMARY>
11
+ */
12
+
13
+ import type { ForgeModule } from "../../src/forge-module.ts";
14
+
15
+ export async function createForgeGateRunModule(): Promise<ForgeModule> {
16
+ const { gateRunStatusCommand } = await import("./status.ts");
17
+ return {
18
+ name: "forge-gate-run",
19
+ version: "0.1.0",
20
+ runtime: "autonomous",
21
+ declarations: [],
22
+ commands: [gateRunStatusCommand],
23
+ pipelines: [],
24
+ };
25
+ }
@@ -0,0 +1,16 @@
1
+ export { createForgeGateRunModule } from "./gate-run.module.ts";
2
+ export {
3
+ GATE_RUN_RETENTION,
4
+ GATE_RUNS_DIR,
5
+ classifyGateRun,
6
+ finishGateRun,
7
+ gateRunsDir,
8
+ listGateRuns,
9
+ repoRelativeCwd,
10
+ saveGateRun,
11
+ startGateRun,
12
+ } from "./record.ts";
13
+ export { GATE_RUN_ID_ENV, HEARTBEAT_WAIT_MS, detachPointerLines, detachSelf } from "./detach.ts";
14
+ export type { DetachResult } from "./detach.ts";
15
+ export { GATE_RUN_RULES, GATE_RUN_SCHEMA } from "./types.ts";
16
+ export type { GateRunRecord, GateRunStatus, SpawnLike, SpawnLikeChild } from "./types.ts";
@@ -0,0 +1,194 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>RFC-1568 — gate-run record lifecycle: start/finish writes (atomic
4
+ via fs-atomic), list, and liveness classification. Records live at
5
+ `<git common dir>/forge/gate-runs/` — shared across worktrees, never
6
+ committed. `lost` is derived at read time through `holderIsDead`, never
7
+ persisted.</purpose>
8
+ <non-goals>
9
+ <item>No command dispatch — hosts wrap execute() with these helpers.</item>
10
+ <item>No process management — a running record whose holder dies stays on
11
+ disk; classify reports it `lost`.</item>
12
+ </non-goals>
13
+ </MODULE_CONTRACT>
14
+ <CHANGE_SUMMARY>
15
+ <item>RFC-1568: step 2 — record lifecycle, classifyGateRun, retention</item>
16
+ <item>RFC-1568: durable gate-run records, --detach mechanics, and forge CLI wiring</item>
17
+ </CHANGE_SUMMARY>
18
+ */
19
+
20
+ import { hostname } from "node:os";
21
+ import { join, relative } from "node:path";
22
+ import { randomBytes } from "node:crypto";
23
+
24
+ import type { WorkspaceIO } from "../../src/types.ts";
25
+ import { writeFileAtomic } from "../../src/utils/fs-atomic.ts";
26
+ import { currentBootId, holderIsDead } from "../core/lock-holder.ts";
27
+ import type { GateRunRecord, GateRunStatus } from "./types.ts";
28
+ import { GATE_RUN_SCHEMA } from "./types.ts";
29
+
30
+ export const GATE_RUNS_DIR = "forge/gate-runs";
31
+ /** Newest records kept per command — running records are never deleted. */
32
+ export const GATE_RUN_RETENTION = 50;
33
+
34
+ export function gateRunsDir(commonGitDir: string): string {
35
+ return join(commonGitDir, GATE_RUNS_DIR);
36
+ }
37
+
38
+ function makeRunId(command: string): string {
39
+ const stamp = new Date()
40
+ .toISOString()
41
+ .replace(/[-:]/g, "")
42
+ .replace(/\.\d+Z$/, "Z");
43
+ return `gr-${stamp}-${command}-${randomBytes(2).toString("hex")}`;
44
+ }
45
+
46
+ function recordPath(commonGitDir: string, runId: string): string {
47
+ return join(gateRunsDir(commonGitDir), `${runId}.json`);
48
+ }
49
+
50
+ /** Atomic record persist — the only write path for gate-run files. */
51
+ export async function saveGateRun(
52
+ commonGitDir: string,
53
+ record: GateRunRecord,
54
+ io: WorkspaceIO,
55
+ ): Promise<void> {
56
+ const dir = gateRunsDir(commonGitDir);
57
+ await io.mkdir(dir);
58
+ await writeFileAtomic(recordPath(commonGitDir, record.runId), JSON.stringify(record, null, 2));
59
+ }
60
+
61
+ /**
62
+ * Retention — delete records+logs beyond the newest GATE_RUN_RETENTION per
63
+ * command. `status: running` records are exempt: the 51st queued run must
64
+ * not erase visibility of a still-running gate.
65
+ */
66
+ async function applyRetention(
67
+ commonGitDir: string,
68
+ command: string,
69
+ io: WorkspaceIO,
70
+ ): Promise<void> {
71
+ const runs = await listGateRuns(commonGitDir, io, { command });
72
+ const deletable = runs.filter((r) => r.status !== "running").slice(GATE_RUN_RETENTION);
73
+ for (const stale of deletable) {
74
+ try {
75
+ await io.rm(recordPath(commonGitDir, stale.runId));
76
+ if (stale.logPath) {
77
+ await io.rm(join(gateRunsDir(commonGitDir), `${stale.runId}.log`));
78
+ }
79
+ } catch {
80
+ // retention is best-effort — a busy file system never blocks the gate
81
+ }
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Start a gate run. The detached child re-invokes with `input.runId` set
87
+ * (WERKSTATT_GATE_RUN_ID) and adopts the parent's record instead of creating
88
+ * a second one — its own pid overwrites the parent's.
89
+ */
90
+ export async function startGateRun(input: {
91
+ commonGitDir: string;
92
+ command: string;
93
+ argv: string[];
94
+ cwd: string;
95
+ detached: boolean;
96
+ io: WorkspaceIO;
97
+ /** child of a detached parent passes the parent's run id. */
98
+ runId?: string;
99
+ missionId?: string;
100
+ }): Promise<GateRunRecord> {
101
+ const runId = input.runId ?? makeRunId(input.command);
102
+ const record: GateRunRecord = {
103
+ schema: GATE_RUN_SCHEMA,
104
+ runId,
105
+ command: input.command,
106
+ argv: input.argv,
107
+ cwd: input.cwd,
108
+ detached: input.detached,
109
+ pid: process.pid,
110
+ host: hostname(),
111
+ bootId: currentBootId(),
112
+ startedAt: new Date().toISOString(),
113
+ status: "running",
114
+ ...(input.missionId ? { missionId: input.missionId } : {}),
115
+ };
116
+ await saveGateRun(input.commonGitDir, record, input.io);
117
+ if (input.runId === undefined) {
118
+ // retention is a start-side concern — never on the adopting child write.
119
+ await applyRetention(input.commonGitDir, input.command, input.io);
120
+ }
121
+ return record;
122
+ }
123
+
124
+ /** Final write — endedAt, exit code, summary, optional gate-report pointer. */
125
+ export async function finishGateRun(
126
+ commonGitDir: string,
127
+ record: GateRunRecord,
128
+ result: { exitCode: number; summary?: string; reportPath?: string },
129
+ io: WorkspaceIO,
130
+ ): Promise<void> {
131
+ const finished: GateRunRecord = {
132
+ ...record,
133
+ endedAt: new Date().toISOString(),
134
+ exitCode: result.exitCode,
135
+ status: result.exitCode === 0 ? "succeeded" : "failed",
136
+ ...(result.summary ? { summary: result.summary } : {}),
137
+ ...(result.reportPath ? { reportPath: result.reportPath } : {}),
138
+ };
139
+ await saveGateRun(commonGitDir, finished, io);
140
+ }
141
+
142
+ /**
143
+ * Newest-first listing. Corrupt records are skipped with a warn through
144
+ * `io` — a torn write must never break the status command.
145
+ */
146
+ export async function listGateRuns(
147
+ commonGitDir: string,
148
+ io: WorkspaceIO,
149
+ filter?: { command?: string; limit?: number },
150
+ ): Promise<GateRunRecord[]> {
151
+ const dir = gateRunsDir(commonGitDir);
152
+ let names: Awaited<ReturnType<WorkspaceIO["readdir"]>>;
153
+ try {
154
+ names = await io.readdir(dir);
155
+ } catch {
156
+ return [];
157
+ }
158
+ const out: GateRunRecord[] = [];
159
+ for (const entry of names) {
160
+ if (!entry.name.endsWith(".json")) continue;
161
+ try {
162
+ const parsed = JSON.parse(await io.readFile(join(dir, entry.name))) as GateRunRecord;
163
+ if (parsed.schema !== GATE_RUN_SCHEMA || typeof parsed.runId !== "string") continue;
164
+ if (filter?.command !== undefined && parsed.command !== filter.command) continue;
165
+ out.push(parsed);
166
+ } catch {
167
+ // corrupt record — skip, never throw (RFC-1568 tolerance rule)
168
+ }
169
+ }
170
+ out.sort((a, b) => b.startedAt.localeCompare(a.startedAt));
171
+ return filter?.limit !== undefined ? out.slice(0, filter.limit) : out;
172
+ }
173
+
174
+ /**
175
+ * running → lost when the holder is dead under the same liveness rule the
176
+ * flow locks use (same-host pid probe + boot id). Never writes — the record
177
+ * on disk keeps `status: running`.
178
+ */
179
+ export function classifyGateRun(
180
+ record: GateRunRecord,
181
+ ownBootId: string | undefined = currentBootId(),
182
+ ): GateRunStatus {
183
+ if (record.status !== "running") return record.status;
184
+ if (holderIsDead({ pid: record.pid, host: record.host, bootId: record.bootId }, ownBootId)) {
185
+ return "lost";
186
+ }
187
+ return "running";
188
+ }
189
+
190
+ /** The `cwd` field — relative to the common dir's parent (repo root) when possible. */
191
+ export function repoRelativeCwd(commonGitDir: string, cwd: string): string {
192
+ const rel = relative(join(commonGitDir, ".."), cwd);
193
+ return rel === "" || rel.startsWith("..") ? cwd : rel;
194
+ }