@warpgogol/forge 10.0.0 → 10.1.1

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 (136) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/bin/cli.ts +17 -0
  3. package/dist/bin/cli.js +17 -0
  4. package/dist/bin/cli.js.map +1 -1
  5. package/dist/os/rfc/probe-batch.d.ts.map +1 -1
  6. package/dist/os/rfc/probe-batch.js +13 -6
  7. package/dist/os/rfc/probe-batch.js.map +1 -1
  8. package/dist/src/contract/core-nodes.d.ts +8 -0
  9. package/dist/src/contract/core-nodes.d.ts.map +1 -0
  10. package/dist/src/contract/core-nodes.js +101 -0
  11. package/dist/src/contract/core-nodes.js.map +1 -0
  12. package/dist/src/contract/evaluator.d.ts +48 -0
  13. package/dist/src/contract/evaluator.d.ts.map +1 -0
  14. package/dist/src/contract/evaluator.js +158 -0
  15. package/dist/src/contract/evaluator.js.map +1 -0
  16. package/dist/src/contract/evidence-store.d.ts +17 -0
  17. package/dist/src/contract/evidence-store.d.ts.map +1 -0
  18. package/dist/src/contract/evidence-store.js +113 -0
  19. package/dist/src/contract/evidence-store.js.map +1 -0
  20. package/dist/src/contract/executors/zero-deps.d.ts +3 -0
  21. package/dist/src/contract/executors/zero-deps.d.ts.map +1 -0
  22. package/dist/src/contract/executors/zero-deps.js +88 -0
  23. package/dist/src/contract/executors/zero-deps.js.map +1 -0
  24. package/dist/src/contract/fingerprint.d.ts +34 -0
  25. package/dist/src/contract/fingerprint.d.ts.map +1 -0
  26. package/dist/src/contract/fingerprint.js +153 -0
  27. package/dist/src/contract/fingerprint.js.map +1 -0
  28. package/dist/src/contract/graph.d.ts +23 -0
  29. package/dist/src/contract/graph.d.ts.map +1 -0
  30. package/dist/src/contract/graph.js +158 -0
  31. package/dist/src/contract/graph.js.map +1 -0
  32. package/dist/src/contract/migration-map.d.ts +51 -0
  33. package/dist/src/contract/migration-map.d.ts.map +1 -0
  34. package/dist/src/contract/migration-map.js +130 -0
  35. package/dist/src/contract/migration-map.js.map +1 -0
  36. package/dist/src/contract/types.d.ts +108 -0
  37. package/dist/src/contract/types.d.ts.map +1 -0
  38. package/dist/src/contract/types.js +23 -0
  39. package/dist/src/contract/types.js.map +1 -0
  40. package/dist/src/integration/drain.d.ts +37 -0
  41. package/dist/src/integration/drain.d.ts.map +1 -0
  42. package/dist/src/integration/drain.js +235 -0
  43. package/dist/src/integration/drain.js.map +1 -0
  44. package/dist/src/integration/enqueue.d.ts +30 -0
  45. package/dist/src/integration/enqueue.d.ts.map +1 -0
  46. package/dist/src/integration/enqueue.js +64 -0
  47. package/dist/src/integration/enqueue.js.map +1 -0
  48. package/dist/src/integration/gitops.d.ts +33 -0
  49. package/dist/src/integration/gitops.d.ts.map +1 -0
  50. package/dist/src/integration/gitops.js +128 -0
  51. package/dist/src/integration/gitops.js.map +1 -0
  52. package/dist/src/integration/lease.d.ts +16 -0
  53. package/dist/src/integration/lease.d.ts.map +1 -0
  54. package/dist/src/integration/lease.js +140 -0
  55. package/dist/src/integration/lease.js.map +1 -0
  56. package/dist/src/integration/materialize.d.ts +7 -0
  57. package/dist/src/integration/materialize.d.ts.map +1 -0
  58. package/dist/src/integration/materialize.js +34 -0
  59. package/dist/src/integration/materialize.js.map +1 -0
  60. package/dist/src/integration/store.d.ts +21 -0
  61. package/dist/src/integration/store.d.ts.map +1 -0
  62. package/dist/src/integration/store.js +131 -0
  63. package/dist/src/integration/store.js.map +1 -0
  64. package/dist/src/integration/types.d.ts +71 -0
  65. package/dist/src/integration/types.d.ts.map +1 -0
  66. package/dist/src/integration/types.js +18 -0
  67. package/dist/src/integration/types.js.map +1 -0
  68. package/dist/src/onboarding/init.d.ts.map +1 -1
  69. package/dist/src/onboarding/init.js +4 -0
  70. package/dist/src/onboarding/init.js.map +1 -1
  71. package/dist/src/onboarding/upgrade.d.ts.map +1 -1
  72. package/dist/src/onboarding/upgrade.js +77 -2
  73. package/dist/src/onboarding/upgrade.js.map +1 -1
  74. package/dist/src/sdk/cli-bridge.d.ts +26 -0
  75. package/dist/src/sdk/cli-bridge.d.ts.map +1 -0
  76. package/dist/src/sdk/cli-bridge.js +89 -0
  77. package/dist/src/sdk/cli-bridge.js.map +1 -0
  78. package/dist/src/sdk/context.d.ts +13 -0
  79. package/dist/src/sdk/context.d.ts.map +1 -0
  80. package/dist/src/sdk/context.js +128 -0
  81. package/dist/src/sdk/context.js.map +1 -0
  82. package/dist/src/sdk/hooks.d.ts +14 -0
  83. package/dist/src/sdk/hooks.d.ts.map +1 -0
  84. package/dist/src/sdk/hooks.js +35 -0
  85. package/dist/src/sdk/hooks.js.map +1 -0
  86. package/dist/src/sdk/loader.d.ts +26 -0
  87. package/dist/src/sdk/loader.d.ts.map +1 -0
  88. package/dist/src/sdk/loader.js +170 -0
  89. package/dist/src/sdk/loader.js.map +1 -0
  90. package/dist/src/sdk/scan.d.ts +16 -0
  91. package/dist/src/sdk/scan.d.ts.map +1 -0
  92. package/dist/src/sdk/scan.js +126 -0
  93. package/dist/src/sdk/scan.js.map +1 -0
  94. package/dist/src/sdk/skills-gen.d.ts +27 -0
  95. package/dist/src/sdk/skills-gen.d.ts.map +1 -0
  96. package/dist/src/sdk/skills-gen.js +87 -0
  97. package/dist/src/sdk/skills-gen.js.map +1 -0
  98. package/dist/src/sdk/types.d.ts +141 -0
  99. package/dist/src/sdk/types.d.ts.map +1 -0
  100. package/dist/src/sdk/types.js +34 -0
  101. package/dist/src/sdk/types.js.map +1 -0
  102. package/dist/src/utils/gitignore-entry.d.ts +3 -0
  103. package/dist/src/utils/gitignore-entry.d.ts.map +1 -0
  104. package/dist/src/utils/gitignore-entry.js +24 -0
  105. package/dist/src/utils/gitignore-entry.js.map +1 -0
  106. package/dist/src/utils/verifier-git.d.ts.map +1 -1
  107. package/dist/src/utils/verifier-git.js +18 -2
  108. package/dist/src/utils/verifier-git.js.map +1 -1
  109. package/os/rfc/probe-batch.ts +13 -6
  110. package/package.json +17 -1
  111. package/src/contract/core-nodes.ts +111 -0
  112. package/src/contract/evaluator.ts +207 -0
  113. package/src/contract/evidence-store.ts +119 -0
  114. package/src/contract/executors/zero-deps.ts +92 -0
  115. package/src/contract/fingerprint.ts +176 -0
  116. package/src/contract/graph.ts +181 -0
  117. package/src/contract/migration-map.ts +174 -0
  118. package/src/contract/types.ts +125 -0
  119. package/src/integration/drain.ts +323 -0
  120. package/src/integration/enqueue.ts +92 -0
  121. package/src/integration/gitops.ts +174 -0
  122. package/src/integration/lease.ts +144 -0
  123. package/src/integration/materialize.ts +40 -0
  124. package/src/integration/store.ts +153 -0
  125. package/src/integration/types.ts +79 -0
  126. package/src/onboarding/init.ts +4 -0
  127. package/src/onboarding/upgrade.ts +84 -1
  128. package/src/sdk/cli-bridge.ts +94 -0
  129. package/src/sdk/context.ts +135 -0
  130. package/src/sdk/hooks.ts +51 -0
  131. package/src/sdk/loader.ts +187 -0
  132. package/src/sdk/scan.ts +132 -0
  133. package/src/sdk/skills-gen.ts +104 -0
  134. package/src/sdk/types.ts +158 -0
  135. package/src/utils/gitignore-entry.ts +24 -0
  136. package/src/utils/verifier-git.ts +17 -2
@@ -0,0 +1,323 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ On-demand drain worker (Werkstatt RFC-1647) — strict FIFO, single logical writer:
5
+ lease, rebase-materialize the frozen unit onto the current head, evaluate the
6
+ candidate tree through the contract graph, integrate or refuse, loop until the
7
+ queue is empty, exit. Never a daemon. Idempotent recovery: lease expiry plus
8
+ state-machine re-entry; integration verified by commit existence before
9
+ re-creation — no orphan states.
10
+ </purpose>
11
+ <non-goals>
12
+ <item>No parallelism, no speculative pre-evaluation — strict FIFO v1.</item>
13
+ </non-goals>
14
+ <CHANGE_SUMMARY>
15
+ <item>RFC-1647 (WP-4): initial drain worker.</item>
16
+ </CHANGE_SUMMARY>
17
+ */
18
+
19
+ import { evaluateGraph, type EvaluationReport } from "../contract/evaluator.ts";
20
+ import type { ContractGraph } from "../contract/graph.ts";
21
+ import type { EvidenceStore } from "../contract/evidence-store.ts";
22
+ import type { Executor } from "../contract/evaluator.ts";
23
+ import type { ChangeUnit } from "../contract/types.ts";
24
+
25
+ import {
26
+ commitExists,
27
+ commitTreeEquals,
28
+ integrateCandidate,
29
+ replayChainOntoHead,
30
+ resolveRef,
31
+ type GitExec,
32
+ defaultGitExec,
33
+ } from "./gitops.ts";
34
+ import { invokeLifecycleHook, type HookInvocationError } from "../sdk/hooks.ts";
35
+ import type { LoadedPlugin } from "../sdk/loader.ts";
36
+ import { acquireLease, type LeaseHandle } from "./lease.ts";
37
+ import type { QueueStore } from "./store.ts";
38
+ import { isTerminal, type IntegrationUnit, type QueueJournalEntry } from "./types.ts";
39
+
40
+ /** Bound on infra-failure requeues before terminal refusal — poison-pill protection. */
41
+ export const MAX_INFRA_REQUEUE_ATTEMPTS = 5;
42
+
43
+ export interface DrainOptions {
44
+ store: QueueStore;
45
+ repoDir: string;
46
+ governedRef: string;
47
+ graph: ContractGraph;
48
+ evidenceStore: EvidenceStore;
49
+ executors: Record<string, Executor>;
50
+ git?: GitExec;
51
+ /** Test hook — a drain that evaluates without an evidence store round trip. */
52
+ treeMaterializer?: (repoDir: string, treeDigest: string) => string;
53
+ /** Active plugins — lifecycle hooks fire around integration when present. */
54
+ plugins?: LoadedPlugin[];
55
+ /** Collector — afterIntegrate errors surface here (post-hoc, cannot veto). */
56
+ hookErrors?: HookInvocationError[];
57
+ }
58
+
59
+ export interface DrainReport {
60
+ status: "drained" | "drain-in-progress" | "empty";
61
+ processed: Array<{ unitId: string; terminal: string }>;
62
+ }
63
+
64
+ function journal(store: QueueStore, entry: Omit<QueueJournalEntry, "schema" | "at">): void {
65
+ store.appendJournal({
66
+ schema: "forge:queue-journal/v1",
67
+ at: new Date().toISOString(),
68
+ ...entry,
69
+ });
70
+ }
71
+
72
+ function transition(
73
+ store: QueueStore,
74
+ unit: IntegrationUnit,
75
+ state: IntegrationUnit["state"],
76
+ actor: string,
77
+ ): void {
78
+ unit.state = state;
79
+ store.writeUnit(unit);
80
+ journal(store, {
81
+ unitId: unit.id,
82
+ transition: state.status === "evaluating" ? "evaluating" : (state.status as QueueJournalEntry["transition"]),
83
+ actor,
84
+ detail: state.status === "refused" ? { nodeId: state.reason.nodeId, summary: state.reason.summary } : undefined,
85
+ });
86
+ }
87
+
88
+ /**
89
+ * Re-entry normalization: a unit in non-terminal state after lease expiry is
90
+ * either already landed (verify by commit existence — idempotency by
91
+ * verification, not assumption) or safely reprocessable. Returns true when the
92
+ * unit still needs processing.
93
+ */
94
+ function normalizeForReentry(
95
+ git: GitExec,
96
+ store: QueueStore,
97
+ repoDir: string,
98
+ unit: IntegrationUnit,
99
+ governedRef: string,
100
+ actor: string,
101
+ ): boolean {
102
+ if (isTerminal(unit.state)) return false;
103
+ if (unit.state.status === "evaluating") {
104
+ // Did the in-flight integration actually land? The governed ref tip equality
105
+ // is the verification — tree digest preimage, never assumption.
106
+ try {
107
+ const tip = resolveRef(git, repoDir, governedRef);
108
+ if (commitExists(git, repoDir, tip) && commitTreeEquals(git, repoDir, tip, unit.treeDigest)) {
109
+ transition(store, unit, { status: "integrated", commitSha: tip, evidenceKey: "recovered-by-verification" }, actor);
110
+ return false;
111
+ }
112
+ } catch {
113
+ // unverifiable — fall through to requeue
114
+ }
115
+ unit.attempts += 1;
116
+ transition(store, unit, { status: "queued" }, actor);
117
+ }
118
+ return true;
119
+ }
120
+
121
+ async function processUnit(
122
+ options: DrainOptions,
123
+ lease: LeaseHandle,
124
+ unit: IntegrationUnit,
125
+ ): Promise<void> {
126
+ const { store, repoDir, governedRef, graph, evidenceStore, executors } = options;
127
+ const git = options.git ?? defaultGitExec;
128
+ const actor = `drain:${lease.lease.leaseId}`;
129
+
130
+ transition(store, unit, { status: "evaluating", leaseId: lease.lease.leaseId, since: new Date().toISOString() }, actor);
131
+
132
+ // Rebase-materialize against the ACTUAL current head — the single-writer
133
+ // guarantee makes this stable inside the drain.
134
+ const headSha = resolveRef(git, repoDir, governedRef);
135
+ const replay = replayChainOntoHead(git, repoDir, headSha, unit.commitChain);
136
+
137
+ if (!replay.ok) {
138
+ // Terminal conflicted — the owning session rebases and re-enqueues a NEW unit.
139
+ transition(store, unit, { status: "conflicted", conflictingPaths: replay.conflictingPaths }, actor);
140
+ return;
141
+ }
142
+
143
+ // The graph evaluates the candidate tree — the exact content that would
144
+ // integrate, never the session's private tree.
145
+ const changeUnit: ChangeUnit = {
146
+ id: `unit-${unit.id}`,
147
+ treeDigest: replay.candidateTree,
148
+ baseRef: governedRef,
149
+ createdAt: new Date().toISOString(),
150
+ frozenRefs: { [governedRef]: headSha },
151
+ metadata: { integrationUnit: unit.id },
152
+ };
153
+ const treeRoot = options.treeMaterializer
154
+ ? options.treeMaterializer(repoDir, replay.candidateTree)
155
+ : repoDir;
156
+
157
+ let report: EvaluationReport;
158
+ try {
159
+ report = await evaluateGraph({
160
+ graph,
161
+ store: evidenceStore,
162
+ changeUnit,
163
+ executors,
164
+ treeRoot,
165
+ });
166
+ } catch (err) {
167
+ // Evaluation infrastructure failure is NOT a verdict — requeue for a later drain.
168
+ // Bounded: a poison-pill unit must not hang the queue forever — after the bound,
169
+ // terminal refusal carries the error as evidence of an unhealthy system.
170
+ unit.attempts += 1;
171
+ if (unit.attempts > MAX_INFRA_REQUEUE_ATTEMPTS) {
172
+ transition(
173
+ store,
174
+ unit,
175
+ {
176
+ status: "refused",
177
+ reason: {
178
+ nodeId: "core.integration.infra",
179
+ summary: `evaluation infrastructure failed ${unit.attempts} times: ${err instanceof Error ? err.message : String(err)}`,
180
+ violations: 0,
181
+ },
182
+ evidenceKey: "",
183
+ },
184
+ actor,
185
+ );
186
+ return;
187
+ }
188
+ transition(store, unit, { status: "queued" }, actor);
189
+ return;
190
+ }
191
+
192
+ if (!report.blockingPassed) {
193
+ const blocking = report.nodes.find((n) => {
194
+ const node = graph.nodes[n.nodeId];
195
+ return node?.severity === "blocking" && n.verdict.status !== "pass" && n.verdict.status !== "uncacheable-pass";
196
+ });
197
+ const violations =
198
+ blocking?.verdict.status === "fail" ? blocking.verdict.violations.length : 1;
199
+ transition(
200
+ store,
201
+ unit,
202
+ {
203
+ status: "refused",
204
+ reason: {
205
+ nodeId: blocking?.nodeId ?? "core.unknown",
206
+ summary:
207
+ blocking?.verdict.status === "error"
208
+ ? `executor error: ${blocking.verdict.message}`
209
+ : `${violations} blocking violation(s)`,
210
+ violations,
211
+ },
212
+ evidenceKey: blocking?.evidenceKey ?? "",
213
+ },
214
+ actor,
215
+ );
216
+ return;
217
+ }
218
+
219
+ // Lifecycle veto — beforeIntegrate hooks execute against the green candidate.
220
+ // A throwing hook means the integration environment cannot vouch: the unit
221
+ // requeues under the same bounded infra semantics as evaluation failures —
222
+ // never a silent skip, never an unbounded hang.
223
+ if (options.plugins && options.plugins.length > 0) {
224
+ const before = await invokeLifecycleHook(options.plugins, "beforeIntegrate", {
225
+ unitId: unit.id,
226
+ data: { candidateCommit: replay.candidateCommit, governedRef },
227
+ });
228
+ if (before.errors.length > 0) {
229
+ unit.attempts += 1;
230
+ if (unit.attempts > MAX_INFRA_REQUEUE_ATTEMPTS) {
231
+ transition(
232
+ store,
233
+ unit,
234
+ {
235
+ status: "refused",
236
+ reason: {
237
+ nodeId: "core.integration.hooks",
238
+ summary: `beforeIntegrate hook failed ${unit.attempts} times: ${before.errors.map((e) => `${e.pluginId}: ${e.error}`).join("; ")}`,
239
+ violations: 0,
240
+ },
241
+ evidenceKey: "",
242
+ },
243
+ actor,
244
+ );
245
+ return;
246
+ }
247
+ transition(store, unit, { status: "queued" }, actor);
248
+ return;
249
+ }
250
+ }
251
+
252
+ // Green evaluation — integrate the candidate into the governed ref (single write point).
253
+ integrateCandidate(git, repoDir, governedRef, replay.candidateCommit);
254
+ transition(
255
+ store,
256
+ unit,
257
+ {
258
+ status: "integrated",
259
+ commitSha: replay.candidateCommit,
260
+ evidenceKey: report.nodes.find((n) => n.evidenceKey)?.evidenceKey ?? "",
261
+ },
262
+ actor,
263
+ );
264
+
265
+ // afterIntegrate is post-hoc notification — errors cannot veto a landed unit,
266
+ // so they surface loudly in the drain report instead.
267
+ if (options.plugins && options.plugins.length > 0) {
268
+ const after = await invokeLifecycleHook(options.plugins, "afterIntegrate", {
269
+ unitId: unit.id,
270
+ outcome: "integrated",
271
+ data: { commitSha: replay.candidateCommit, governedRef },
272
+ });
273
+ if (after.errors.length > 0) {
274
+ options.hookErrors = [...(options.hookErrors ?? []), ...after.errors];
275
+ }
276
+ }
277
+ }
278
+
279
+ /**
280
+ * Drain the queue once, strict FIFO, exiting when empty. A second concurrent
281
+ * drain reports drain-in-progress and exits 0 — it never double-processes.
282
+ */
283
+ export async function drainQueue(options: DrainOptions): Promise<DrainReport> {
284
+ const git = options.git ?? defaultGitExec;
285
+ const lease = acquireLease(options.store.queueDir);
286
+ if (!lease) {
287
+ return { status: "drain-in-progress", processed: [] };
288
+ }
289
+
290
+ const processed: Array<{ unitId: string; terminal: string }> = [];
291
+ try {
292
+ for (;;) {
293
+ lease.heartbeat(); // per-unit boundary — fresh heartbeat each iteration
294
+ const live = options.store
295
+ .units()
296
+ .filter((u) => !isTerminal(u.state))
297
+ .sort((a, b) => a.enqueuedAt.localeCompare(b.enqueuedAt) || a.id.localeCompare(b.id));
298
+
299
+ if (live.length === 0) {
300
+ store_checkpoint(options.store);
301
+ return { status: processed.length > 0 ? "drained" : "empty", processed };
302
+ }
303
+
304
+ const unit = live[0]!;
305
+ if (!normalizeForReentry(git, options.store, options.repoDir, unit, options.governedRef, `drain:${lease.lease.leaseId}`)) {
306
+ continue;
307
+ }
308
+ await processUnit(options, lease, unit);
309
+ const final = options.store.readUnit(unit.id);
310
+ processed.push({ unitId: unit.id, terminal: final?.state.status ?? "unknown" });
311
+ }
312
+ } finally {
313
+ lease.release();
314
+ }
315
+ }
316
+
317
+ function store_checkpoint(store: QueueStore): void {
318
+ try {
319
+ store.checkpoint();
320
+ } catch {
321
+ // checkpoint failure never blocks a drain verdict
322
+ }
323
+ }
@@ -0,0 +1,92 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Enqueue path + read-only observability surfaces (Werkstatt RFC-1647) — sessions
5
+ freeze their work into immutable units and enqueue atomically; queue state is
6
+ inspectable at all times through read-only surfaces consuming frozen state only.
7
+ The conflicted-recovery contract names itself verbatim: the owning session
8
+ rebases onto the current head and re-enqueues a NEW unit — units are immutable,
9
+ re-enqueue is a new id.
10
+ </purpose>
11
+ <non-goals>
12
+ <item>No drain triggers as daemons — enqueueing commands may trigger an on-demand drain.</item>
13
+ </non-goals>
14
+ <CHANGE_SUMMARY>
15
+ <item>RFC-1647 (WP-4): initial enqueue + observability.</item>
16
+ </CHANGE_SUMMARY>
17
+ */
18
+
19
+ import { randomBytes } from "node:crypto";
20
+
21
+ import type { QueueStore } from "./store.ts";
22
+ import { isTerminal, type IntegrationUnit, type QueueJournalEntry } from "./types.ts";
23
+
24
+ /** uuidv7-style time-ordered id — millisecond prefix keeps FIFO sort stable. */
25
+ export function newUnitId(now = Date.now()): string {
26
+ const timeHex = now.toString(16).padStart(12, "0");
27
+ const rand = randomBytes(8).toString("hex");
28
+ return `${timeHex}-${rand}`;
29
+ }
30
+
31
+ export interface EnqueueInput {
32
+ treeDigest: string;
33
+ baseRef: string;
34
+ sessionId: string;
35
+ worktreePath: string;
36
+ governanceIds: string[];
37
+ commitChain: string[];
38
+ }
39
+
40
+ /** Freeze-and-enqueue: the unit either exists complete in the queue or not at all. */
41
+ export function enqueueUnit(store: QueueStore, input: EnqueueInput): IntegrationUnit {
42
+ const unit: IntegrationUnit = {
43
+ schema: "forge:integration-unit/v1",
44
+ id: newUnitId(),
45
+ treeDigest: input.treeDigest,
46
+ baseRef: input.baseRef,
47
+ source: {
48
+ sessionId: input.sessionId,
49
+ worktreePath: input.worktreePath,
50
+ governanceIds: input.governanceIds,
51
+ },
52
+ commitChain: input.commitChain,
53
+ enqueuedAt: new Date().toISOString(),
54
+ state: { status: "queued" },
55
+ attempts: 0,
56
+ };
57
+ store.enqueue(unit);
58
+ return unit;
59
+ }
60
+
61
+ export interface QueueView {
62
+ units: Array<{
63
+ id: string;
64
+ status: string;
65
+ enqueuedAt: string;
66
+ sessionId: string;
67
+ terminal: boolean;
68
+ }>;
69
+ journalTail: QueueJournalEntry[];
70
+ liveLease: boolean;
71
+ }
72
+
73
+ /** Read-only queue state — consumes frozen records and the append-only journal only. */
74
+ export function inspectQueue(store: QueueStore, journalTailLines = 20): QueueView {
75
+ const units = store.units().map((u) => ({
76
+ id: u.id,
77
+ status: u.state.status,
78
+ enqueuedAt: u.enqueuedAt,
79
+ sessionId: u.source.sessionId,
80
+ terminal: isTerminal(u.state),
81
+ }));
82
+ const journal = store.journal();
83
+ return {
84
+ units,
85
+ journalTail: journal.slice(-journalTailLines),
86
+ liveLease: false, // lease state is operational, not evidence — callers may probe separately
87
+ };
88
+ }
89
+
90
+ /** Verbatim recovery path named in every conflicted terminal — the agent contract. */
91
+ export const CONFLICTED_RECOVERY_INSTRUCTION =
92
+ "This unit is terminally conflicted and is never retried in place. The owning session rebases its worktree onto the current head, resolves the named paths, freezes the result as a NEW unit and re-enqueues it — units are immutable, re-enqueue is a new id.";
@@ -0,0 +1,174 @@
1
+ /*
2
+ <MODULE_CONTRACT>
3
+ <purpose>
4
+ Git operations substrate for the integration queue (Werkstatt RFC-1647) — pure
5
+ plumbing, no worktrees: commit-chain replay via merge-tree --write-tree with the
6
+ replayed commit's parent as merge-base (exact cherry-pick semantics), commit
7
+ materialization via commit-tree into the repo's own object store. Squash is
8
+ forbidden: the chain replays commit-by-commit preserving messages, authorship
9
+ and governance trailers. Objects never leave the main object store, so the
10
+ candidate survives independent of any scratch lifetime.
11
+ </purpose>
12
+ <non-goals>
13
+ <item>No evaluation or verdict logic — git mechanics only.</item>
14
+ </non-goals>
15
+ <CHANGE_SUMMARY>
16
+ <item>RFC-1647 (WP-4): plumbing-only — merge-tree/commit-tree, zero worktrees.</item>
17
+ </CHANGE_SUMMARY>
18
+ */
19
+
20
+ import { execFileSync, spawnSync } from "node:child_process";
21
+
22
+ export interface GitExec {
23
+ (args: string[], cwd: string): string;
24
+ }
25
+
26
+ export const defaultGitExec: GitExec = (args, cwd) =>
27
+ execFileSync("git", args, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] });
28
+
29
+ export function resolveRef(git: GitExec, repoDir: string, ref: string): string {
30
+ return git(["rev-parse", ref], repoDir).trim();
31
+ }
32
+
33
+ export function treeOfCommit(git: GitExec, repoDir: string, commitSha: string): string {
34
+ return git(["rev-parse", `${commitSha}^{tree}`], repoDir).trim();
35
+ }
36
+
37
+ export function commitExists(git: GitExec, repoDir: string, sha: string): boolean {
38
+ try {
39
+ git(["cat-file", "-e", sha], repoDir);
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+
46
+ export function commitTreeEquals(git: GitExec, repoDir: string, sha: string, treeDigest: string): boolean {
47
+ try {
48
+ return treeOfCommit(git, repoDir, sha) === treeDigest;
49
+ } catch {
50
+ return false;
51
+ }
52
+ }
53
+
54
+ export interface ReplayResult {
55
+ ok: true;
56
+ candidateCommit: string;
57
+ candidateTree: string;
58
+ replayedCount: number;
59
+ }
60
+
61
+ export interface ReplayConflict {
62
+ ok: false;
63
+ conflictingPaths: string[];
64
+ atCommit: string;
65
+ }
66
+
67
+ interface MergeTreeOutcome {
68
+ conflicted: boolean;
69
+ tree: string | null;
70
+ conflictedPaths: string[];
71
+ }
72
+
73
+ /**
74
+ * One merge-tree execution, exit status as the conflict signal. Output format:
75
+ * first line the tree oid; on conflict a section of conflicted-file records
76
+ * whose lines carry the path as the last whitespace-separated token.
77
+ */
78
+ function runMergeTree(repoDir: string, base: string, ours: string, theirs: string): MergeTreeOutcome {
79
+ const res = spawnSync("git", ["merge-tree", "--write-tree", "--merge-base", base, ours, theirs], {
80
+ cwd: repoDir,
81
+ encoding: "utf8",
82
+ });
83
+ const out = res.stdout ?? "";
84
+ const lines = out.split("\n");
85
+ const tree = lines[0]?.trim() || null;
86
+ const conflicted = res.status !== 0;
87
+ const conflictedPaths = conflicted
88
+ ? [
89
+ ...new Set(
90
+ lines
91
+ .slice(1)
92
+ .map((l) => l.trim())
93
+ .filter((l) => /^\d+ \d+ [0-9a-f]{7,40} \d+\t?.+/i.test(l) || l.includes("\t"))
94
+ .map((l) => l.split(/\s+/).pop() ?? "")
95
+ .filter(Boolean),
96
+ ),
97
+ ]
98
+ : [];
99
+ return { conflicted, tree, conflictedPaths };
100
+ }
101
+
102
+ function commitMeta(git: GitExec, repoDir: string, commit: string): { message: string; authorName: string; authorEmail: string; authorDate: string } {
103
+ const sep = "@@META@@";
104
+ const message = git(["log", "-1", "--format=%B", commit], repoDir);
105
+ const meta = git(["log", "-1", `--format=${sep}%an${sep}%ae${sep}%aI`, commit], repoDir).trim().split(sep).filter(Boolean);
106
+ return {
107
+ message: message.trimEnd(),
108
+ authorName: meta[1] ?? "integration-queue",
109
+ authorEmail: meta[2] ?? "queue@localhost",
110
+ authorDate: meta[3] ?? new Date().toISOString(),
111
+ };
112
+ }
113
+
114
+ /**
115
+ * Rebase-materialize: replay the chain commit-by-commit onto the current head
116
+ * using merge-tree with the commit's parent as merge-base — exact cherry-pick
117
+ * tree semantics, no worktree, no checkout. Each step materializes its own
118
+ * commit object (never squashed). First conflict stops the replay and names
119
+ * the conflicting paths per-commit.
120
+ */
121
+ export function replayChainOntoHead(
122
+ git: GitExec,
123
+ repoDir: string,
124
+ headSha: string,
125
+ commitChain: string[],
126
+ ): ReplayResult | ReplayConflict {
127
+ let tip = headSha;
128
+ let replayed = 0;
129
+
130
+ for (const commit of commitChain) {
131
+ const parent = git(["rev-parse", `${commit}^`], repoDir).trim();
132
+ const outcome = runMergeTree(repoDir, parent, tip, commit);
133
+ if (outcome.conflicted || !outcome.tree) {
134
+ return {
135
+ ok: false,
136
+ conflictingPaths: outcome.conflictedPaths.length > 0 ? outcome.conflictedPaths : ["(conflict — paths unparsed)"],
137
+ atCommit: commit,
138
+ };
139
+ }
140
+
141
+ const meta = commitMeta(git, repoDir, commit);
142
+ const env = {
143
+ ...process.env,
144
+ GIT_AUTHOR_NAME: meta.authorName,
145
+ GIT_AUTHOR_EMAIL: meta.authorEmail,
146
+ GIT_AUTHOR_DATE: meta.authorDate,
147
+ GIT_COMMITTER_NAME: meta.authorName,
148
+ GIT_COMMITTER_EMAIL: meta.authorEmail,
149
+ };
150
+ const newCommit = execFileSync("git", ["commit-tree", outcome.tree, "-p", tip, "-m", meta.message], {
151
+ cwd: repoDir,
152
+ encoding: "utf8",
153
+ env,
154
+ }).trim();
155
+ tip = newCommit;
156
+ replayed += 1;
157
+ }
158
+
159
+ const candidateTree = treeOfCommit(git, repoDir, tip);
160
+ return { ok: true, candidateCommit: tip, candidateTree, replayedCount: replayed };
161
+ }
162
+
163
+ /**
164
+ * Integrate the candidate into the governed ref — the single write point.
165
+ * update-ref is atomic; the candidate commits already live in this object store.
166
+ */
167
+ export function integrateCandidate(
168
+ git: GitExec,
169
+ repoDir: string,
170
+ governedRef: string,
171
+ candidateCommit: string,
172
+ ): void {
173
+ git(["update-ref", governedRef, candidateCommit], repoDir);
174
+ }