@aviaratech/ai-delivery 0.3.37 → 0.3.39

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 (172) hide show
  1. package/README.md +14 -18
  2. package/dist/agent.d.ts +0 -4
  3. package/dist/agent.js +1 -8
  4. package/dist/agent.js.map +2 -2
  5. package/dist/cli.js +2 -72
  6. package/dist/cli.js.map +2 -2
  7. package/dist/cliResult.js +2 -14
  8. package/dist/cliResult.js.map +2 -2
  9. package/dist/cliResult.test.js +0 -74
  10. package/dist/cliResult.test.js.map +2 -2
  11. package/dist/config/deliveryConfig.d.ts +0 -6
  12. package/dist/config/deliveryConfig.js +2 -35
  13. package/dist/config/deliveryConfig.js.map +2 -2
  14. package/dist/config/deliveryConfig.test.js +1 -25
  15. package/dist/config/deliveryConfig.test.js.map +2 -2
  16. package/dist/contributorChecks.test.js +5 -3
  17. package/dist/contributorChecks.test.js.map +2 -2
  18. package/dist/delivery/common.d.ts +0 -14
  19. package/dist/delivery/common.js +1 -44
  20. package/dist/delivery/common.js.map +2 -2
  21. package/dist/directoryIndependent.test.js +2 -24
  22. package/dist/directoryIndependent.test.js.map +2 -2
  23. package/dist/dispatch.js +0 -46
  24. package/dist/dispatch.js.map +3 -3
  25. package/dist/fixtures/inertTarget.js +3 -5
  26. package/dist/fixtures/inertTarget.js.map +2 -2
  27. package/dist/fixtures/recordedGitHubFlows.d.ts +0 -72
  28. package/dist/fixtures/recordedGitHubFlows.js +1 -57
  29. package/dist/fixtures/recordedGitHubFlows.js.map +2 -2
  30. package/dist/git.d.ts +0 -6
  31. package/dist/git.js +0 -15
  32. package/dist/git.js.map +2 -2
  33. package/dist/github/client.js +0 -3
  34. package/dist/github/client.js.map +2 -2
  35. package/dist/github/commandIdentityPolicy.js +0 -1
  36. package/dist/github/commandIdentityPolicy.js.map +2 -2
  37. package/dist/github/issueHistory.d.ts +0 -6
  38. package/dist/github/issueHistory.js +0 -39
  39. package/dist/github/issueHistory.js.map +2 -2
  40. package/dist/github/nativeIssueMetadata.d.ts +0 -10
  41. package/dist/github/nativeIssueMetadata.js +1 -33
  42. package/dist/github/nativeIssueMetadata.js.map +3 -3
  43. package/dist/github/projectDelivery.d.ts +0 -34
  44. package/dist/github/projectDelivery.js +0 -211
  45. package/dist/github/projectDelivery.js.map +2 -2
  46. package/dist/github/repo.d.ts +0 -8
  47. package/dist/github/repo.js +0 -72
  48. package/dist/github/repo.js.map +2 -2
  49. package/dist/issue.js +22 -17
  50. package/dist/issue.js.map +2 -2
  51. package/dist/issue63Routes.test.js +1 -72
  52. package/dist/issue63Routes.test.js.map +2 -2
  53. package/dist/issueInfoReadback.test.js +59 -1
  54. package/dist/issueInfoReadback.test.js.map +2 -2
  55. package/dist/issueIntake.test.js +12 -0
  56. package/dist/issueIntake.test.js.map +2 -2
  57. package/dist/issueJournal.d.ts +0 -9
  58. package/dist/issueJournal.js +10 -76
  59. package/dist/issueJournal.js.map +2 -2
  60. package/dist/issueJournal.test.js +1 -108
  61. package/dist/issueJournal.test.js.map +2 -2
  62. package/dist/issueTracking.test.js +0 -48
  63. package/dist/issueTracking.test.js.map +2 -2
  64. package/dist/lifecycle.test.js +12 -48
  65. package/dist/lifecycle.test.js.map +2 -2
  66. package/dist/logger.d.ts +0 -4
  67. package/dist/logger.js +0 -31
  68. package/dist/logger.js.map +2 -2
  69. package/dist/mcp/tools.d.ts +2 -618
  70. package/dist/mcp/tools.js +8 -34
  71. package/dist/mcp/tools.js.map +2 -2
  72. package/dist/pluginAuthProbe.js +0 -3
  73. package/dist/pluginAuthProbe.js.map +2 -2
  74. package/dist/pluginDoctor.test.js +1 -1
  75. package/dist/pluginDoctor.test.js.map +2 -2
  76. package/dist/pluginInstaller.js +0 -3
  77. package/dist/pluginInstaller.js.map +2 -2
  78. package/dist/pluginInstaller.test.js +3 -19
  79. package/dist/pluginInstaller.test.js.map +2 -2
  80. package/dist/pluginPackaging.test.js +1 -118
  81. package/dist/pluginPackaging.test.js.map +2 -2
  82. package/dist/pr.d.ts +2 -73
  83. package/dist/pr.js +27 -220
  84. package/dist/pr.js.map +3 -3
  85. package/dist/pr.test.js +11 -304
  86. package/dist/pr.test.js.map +2 -2
  87. package/dist/prAssociation.test.js +112 -22
  88. package/dist/prAssociation.test.js.map +2 -2
  89. package/dist/prDispatch.test.js +4 -11
  90. package/dist/prDispatch.test.js.map +2 -2
  91. package/dist/releaseWorkflow.test.js +0 -1
  92. package/dist/releaseWorkflow.test.js.map +2 -2
  93. package/dist/review.d.ts +0 -82
  94. package/dist/review.js +3 -94
  95. package/dist/review.js.map +2 -2
  96. package/dist/review.test.js +2 -4
  97. package/dist/review.test.js.map +2 -2
  98. package/dist/services/agentReadinessService.d.ts +0 -1
  99. package/dist/services/agentReadinessService.js.map +2 -2
  100. package/dist/stdoutRegression.test.js +3 -22
  101. package/dist/stdoutRegression.test.js.map +2 -2
  102. package/dist/targetPolicyDiscovery.test.js +0 -86
  103. package/dist/targetPolicyDiscovery.test.js.map +2 -2
  104. package/dist/targetPolicyEntrypoints.test.js +1 -54
  105. package/dist/targetPolicyEntrypoints.test.js.map +2 -2
  106. package/dist/targetRepositoryExecution.test.js +1 -49
  107. package/dist/targetRepositoryExecution.test.js.map +2 -2
  108. package/dist/terminalMessages.d.ts +0 -10
  109. package/dist/terminalMessages.js +1 -31
  110. package/dist/terminalMessages.js.map +2 -2
  111. package/dist/toolOutput.js +0 -2
  112. package/dist/toolOutput.js.map +2 -2
  113. package/dist/toolOutput.test.js +15 -1
  114. package/dist/toolOutput.test.js.map +2 -2
  115. package/dist/verification.d.ts +1 -186
  116. package/dist/verification.js +29 -587
  117. package/dist/verification.js.map +3 -3
  118. package/dist/verificationGate.test.js +4 -90
  119. package/dist/verificationGate.test.js.map +2 -2
  120. package/dist/version.d.ts +0 -6
  121. package/dist/version.js +2 -39
  122. package/dist/version.js.map +2 -2
  123. package/package.json +1 -1
  124. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  125. package/plugins/ai-delivery/plugin.json +1 -1
  126. package/plugins/ai-delivery/runtime/dist/cli.js +118 -162
  127. package/plugins/ai-delivery/runtime/package.json +1 -1
  128. package/dist/boardReconcile.test.d.ts +0 -1
  129. package/dist/boardReconcile.test.js +0 -1746
  130. package/dist/boardReconcile.test.js.map +0 -7
  131. package/dist/delivery/delivery.test.d.ts +0 -1
  132. package/dist/delivery/delivery.test.js +0 -560
  133. package/dist/delivery/delivery.test.js.map +0 -7
  134. package/dist/delivery/evidence.d.ts +0 -92
  135. package/dist/delivery/evidence.js +0 -139
  136. package/dist/delivery/evidence.js.map +0 -7
  137. package/dist/delivery/legacy.d.ts +0 -8
  138. package/dist/delivery/legacy.js +0 -65
  139. package/dist/delivery/legacy.js.map +0 -7
  140. package/dist/delivery/policy.d.ts +0 -252
  141. package/dist/delivery/policy.js +0 -221
  142. package/dist/delivery/policy.js.map +0 -7
  143. package/dist/delivery/stage.d.ts +0 -179
  144. package/dist/delivery/stage.js +0 -242
  145. package/dist/delivery/stage.js.map +0 -7
  146. package/dist/deliveryBoard.d.ts +0 -74
  147. package/dist/deliveryBoard.js +0 -644
  148. package/dist/deliveryBoard.js.map +0 -7
  149. package/dist/deliveryBoard.test.d.ts +0 -1
  150. package/dist/deliveryBoard.test.js +0 -649
  151. package/dist/deliveryBoard.test.js.map +0 -7
  152. package/dist/deliveryHealth.test.d.ts +0 -1
  153. package/dist/deliveryHealth.test.js +0 -191
  154. package/dist/deliveryHealth.test.js.map +0 -7
  155. package/dist/fixtures/deliveryBoardReplay.d.ts +0 -56
  156. package/dist/fixtures/deliveryBoardReplay.js +0 -617
  157. package/dist/fixtures/deliveryBoardReplay.js.map +0 -7
  158. package/dist/genericCompatibility.test.d.ts +0 -1
  159. package/dist/genericCompatibility.test.js +0 -66
  160. package/dist/genericCompatibility.test.js.map +0 -7
  161. package/dist/services/boardReconcileService.d.ts +0 -1204
  162. package/dist/services/boardReconcileService.js +0 -1445
  163. package/dist/services/boardReconcileService.js.map +0 -7
  164. package/dist/services/deliveryHealthService.d.ts +0 -84
  165. package/dist/services/deliveryHealthService.js +0 -204
  166. package/dist/services/deliveryHealthService.js.map +0 -7
  167. package/dist/services/legacyIssueMigration.d.ts +0 -46
  168. package/dist/services/legacyIssueMigration.js +0 -299
  169. package/dist/services/legacyIssueMigration.js.map +0 -7
  170. package/dist/utils/filesystem.d.ts +0 -1
  171. package/dist/utils/filesystem.js +0 -5
  172. package/dist/utils/filesystem.js.map +0 -7
@@ -1,414 +1,13 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
- import { randomUUID } from "node:crypto";
3
2
  import { createRequire, findPackageJSON } from "node:module";
4
3
  import { types } from "node:util";
5
- import {
6
- existsSync,
7
- unlinkSync,
8
- lstatSync,
9
- mkdirSync,
10
- rmdirSync,
11
- renameSync,
12
- readFileSync,
13
- readlinkSync,
14
- readdirSync,
15
- realpathSync,
16
- statfsSync
17
- } from "node:fs";
18
- import { dirname, join, resolve, sep } from "node:path";
4
+ import { existsSync, readFileSync, readdirSync, realpathSync, statfsSync } from "node:fs";
5
+ import { dirname, join } from "node:path";
19
6
  import { fileURLToPath } from "node:url";
20
7
  import { z } from "zod";
21
- import { assertPrivateFile } from "./delivery/common.js";
22
- import { digestBytes, digestValue, writeRepositoryCommandOutput } from "./delivery/legacy.js";
8
+ import { digestBytes, digestValue, writeCreateOnly } from "./delivery/common.js";
23
9
  import { DeliveryError } from "./errors.js";
24
10
  import { gitCommonDir } from "./git.js";
25
- import { writePrivateJsonFileAtomically } from "./utils/atomicJson.js";
26
- const ResourceSummarySchema = z.strictObject({
27
- bounds: z.strictObject({
28
- maxAggregateRssBytes: z.number().int().positive().safe(),
29
- maxNewOutputBytes: z.number().int().positive().safe().optional(),
30
- minFreeDiskBytes: z.number().int().positive().safe(),
31
- outputRoots: z.array(z.string().min(1)).min(1).optional()
32
- }),
33
- maxSampledAggregateRssBytes: z.number().int().nonnegative().safe().nullable(),
34
- maxSampledNewOutputBytes: z.number().int().nonnegative().safe().nullable(),
35
- minSampledFreeDiskBytes: z.number().int().nonnegative().safe().nullable(),
36
- observation: z.literal("sampled"),
37
- outputBaselineId: z.string().regex(/^sha256:[a-f0-9]{64}$/u).optional(),
38
- processCoverage: z.literal("observed-processes-only"),
39
- sampleCount: z.number().int().nonnegative().safe()
40
- }).superRefine((value, ctx) => {
41
- if (value.maxSampledAggregateRssBytes !== null && value.maxSampledAggregateRssBytes > value.bounds.maxAggregateRssBytes || value.maxSampledNewOutputBytes !== null && value.bounds.maxNewOutputBytes !== void 0 && value.maxSampledNewOutputBytes > value.bounds.maxNewOutputBytes || value.minSampledFreeDiskBytes !== null && value.minSampledFreeDiskBytes < value.bounds.minFreeDiskBytes || value.sampleCount > 0 && (value.maxSampledAggregateRssBytes === null || value.minSampledFreeDiskBytes === null) || value.bounds.maxNewOutputBytes !== void 0 && value.sampleCount > 0 && value.maxSampledNewOutputBytes === null || value.bounds.maxNewOutputBytes !== void 0 !== (value.outputBaselineId !== void 0))
42
- ctx.addIssue({ code: "custom", message: "Resource samples do not satisfy their declared bounds." });
43
- });
44
- const OUTPUT_GATE_ENV = "AI_DELIVERY_OUTPUT_OBSERVATION_GATE";
45
- const GateOwnerSchema = z.strictObject({ pid: z.number().int().positive(), identity: z.string().min(1) });
46
- const OutputGateSchema = z.strictObject({ directory: z.string().min(1), id: z.uuid(), owner: GateOwnerSchema });
47
- const GateClaimSchema = z.strictObject({
48
- gateId: z.uuid(),
49
- id: z.uuid(),
50
- kind: z.enum(["scan", "fixture"]),
51
- owner: GateOwnerSchema
52
- });
53
- function gateOwner(snapshot = processSnapshot()) {
54
- const owner = snapshot.get(process.pid);
55
- if (!owner) throw new DeliveryError("Filesystem observation gate owner is unavailable.");
56
- return { pid: owner.pid, identity: owner.identity };
57
- }
58
- function assertGateDirectory(path) {
59
- const metadata = lstatSync(path);
60
- if (!metadata.isDirectory() || (metadata.mode & 63) !== 0 || realpathSync(path) !== path)
61
- throw new DeliveryError("Filesystem observation gate directory is invalid.");
62
- }
63
- function readOutputGate(value) {
64
- try {
65
- const gate = OutputGateSchema.parse(JSON.parse(value));
66
- assertOutputGate(gate);
67
- return gate;
68
- } catch (error) {
69
- throw new DeliveryError(
70
- "Filesystem observation gate capability is invalid or stale: " + (error instanceof Error ? error.message : String(error))
71
- );
72
- }
73
- }
74
- function gateOwnerAlive(owner, snapshot = processSnapshot()) {
75
- const current = snapshot.get(owner.pid);
76
- return current?.identity === owner.identity && !current.status.startsWith("Z");
77
- }
78
- function assertOutputGate(gate, abandoned = false) {
79
- assertGateDirectory(gate.directory);
80
- const manifest = OutputGateSchema.parse(
81
- JSON.parse(assertPrivateFile(join(gate.directory, "gate.json")).toString("utf8"))
82
- );
83
- const snapshot = processSnapshot();
84
- let actor = snapshot.get(process.pid);
85
- const ancestors = /* @__PURE__ */ new Set();
86
- while (actor && actor.pid !== gate.owner.pid && !ancestors.has(actor.pid)) {
87
- ancestors.add(actor.pid);
88
- actor = snapshot.get(actor.ppid);
89
- }
90
- if (digestValue(manifest) !== digestValue(gate) || (abandoned ? gateOwnerAlive(gate.owner, snapshot) : !gateOwnerAlive(gate.owner, snapshot) || actor?.identity !== gate.owner.identity))
91
- throw new DeliveryError(
92
- "Filesystem observation gate ownership changed, was abandoned or is not an inherited ancestor."
93
- );
94
- return snapshot;
95
- }
96
- function readGateClaim(gate, path) {
97
- const claim = GateClaimSchema.parse(JSON.parse(assertPrivateFile(path).toString("utf8")));
98
- if (claim.gateId !== gate.id) throw new DeliveryError("Filesystem observation gate claim belongs to another run.");
99
- return claim;
100
- }
101
- function gateScanRequests(gate, snapshot) {
102
- const directory = join(gate.directory, "requests");
103
- assertGateDirectory(directory);
104
- const requests = readdirSync(directory);
105
- if (requests.length > 1024 || requests.some((name) => !/^[a-f0-9-]{36}\.json$/u.test(name)))
106
- throw new DeliveryError("Filesystem observation gate scan requests are invalid.");
107
- const live = [];
108
- const currentSnapshot = snapshot ?? processSnapshot();
109
- for (const name of requests) {
110
- let claim;
111
- try {
112
- claim = readGateClaim(gate, join(directory, name));
113
- } catch (error) {
114
- if (error.code === "ENOENT") continue;
115
- throw error;
116
- }
117
- if (claim.kind !== "scan" || name !== claim.id + ".json" || !gateOwnerAlive(claim.owner, currentSnapshot))
118
- throw new DeliveryError("Filesystem observation gate scan request was abandoned.");
119
- live.push(name);
120
- }
121
- return live;
122
- }
123
- function removeGateClaim(gate, path, claim) {
124
- if (digestValue(readGateClaim(gate, path)) !== digestValue(claim))
125
- throw new DeliveryError("Filesystem observation gate claim changed before release.");
126
- unlinkSync(path);
127
- }
128
- async function withOutputGateLock(gate, kind, operation, signal) {
129
- if (!gate) return operation();
130
- const ownerSnapshot = assertOutputGate(gate);
131
- const claim = { gateId: gate.id, id: randomUUID(), kind, owner: gateOwner(ownerSnapshot) };
132
- const request = kind === "scan" ? join(gate.directory, "requests", claim.id + ".json") : void 0;
133
- const lock = join(gate.directory, "held");
134
- const holder = join(lock, "owner.json");
135
- if (request) {
136
- const staging = join(gate.directory, claim.id + ".pending");
137
- writePrivateJsonFileAtomically(staging, claim);
138
- renameSync(staging, request);
139
- }
140
- let acquired;
141
- let incompleteSince;
142
- let fixtureWait;
143
- const release = () => {
144
- if (!acquired) return;
145
- const metadata = lstatSync(lock);
146
- if (!metadata.isDirectory() || metadata.dev !== acquired.dev || metadata.ino !== acquired.ino)
147
- throw new DeliveryError("Filesystem observation gate lock changed before release.");
148
- if (readdirSync(lock).join(",") !== "owner.json")
149
- throw new DeliveryError("Filesystem observation gate lock has unrelated metadata.");
150
- removeGateClaim(gate, holder, claim);
151
- rmdirSync(lock);
152
- acquired = void 0;
153
- };
154
- try {
155
- for (; ; ) {
156
- if (signal?.aborted) throw new DeliveryError("Filesystem observation gate wait cancelled.");
157
- const currentSnapshot = assertOutputGate(gate);
158
- const requests = gateScanRequests(gate, currentSnapshot);
159
- if (kind === "scan" || requests.length === 0) {
160
- let created = false;
161
- try {
162
- mkdirSync(lock, { mode: 448 });
163
- created = true;
164
- } catch (error) {
165
- if (error.code !== "EEXIST") throw error;
166
- }
167
- if (created) {
168
- const metadata = lstatSync(lock);
169
- acquired = { dev: metadata.dev, ino: metadata.ino };
170
- writePrivateJsonFileAtomically(holder, claim);
171
- if (kind === "scan" || gateScanRequests(gate).length === 0) return await operation();
172
- release();
173
- }
174
- }
175
- if (existsSync(lock)) {
176
- try {
177
- assertGateDirectory(lock);
178
- const current = readGateClaim(gate, holder);
179
- incompleteSince = void 0;
180
- if (!gateOwnerAlive(current.owner))
181
- throw new DeliveryError("Filesystem observation gate fixture or scanner was abandoned.");
182
- if (kind === "scan" && current.kind === "fixture") {
183
- if (fixtureWait?.claimId !== current.id) fixtureWait = { claimId: current.id, since: Date.now() };
184
- if (Date.now() - fixtureWait.since > 5e3)
185
- throw new DeliveryError(
186
- "Filesystem-negative fixture did not release a waiting output scan within 5 seconds; reader or teardown is stalled."
187
- );
188
- } else fixtureWait = void 0;
189
- } catch (error) {
190
- if (error.code !== "ENOENT") throw error;
191
- incompleteSince ??= Date.now();
192
- if (Date.now() - incompleteSince > 2e3)
193
- throw new DeliveryError("Filesystem observation gate owner publication is incomplete.");
194
- }
195
- }
196
- await new Promise((resolve2) => setTimeout(resolve2, 100));
197
- }
198
- } finally {
199
- try {
200
- release();
201
- } finally {
202
- if (request) removeGateClaim(gate, request, claim);
203
- }
204
- }
205
- }
206
- async function withVerificationFilesystemFixture(operation) {
207
- const capability = process.env[OUTPUT_GATE_ENV];
208
- return withOutputGateLock(capability === void 0 ? void 0 : readOutputGate(capability), "fixture", operation);
209
- }
210
- class OutputObservationError extends DeliveryError {
211
- cause;
212
- code;
213
- constructor(message, path, cause) {
214
- const code = cause.code;
215
- super(
216
- `${message} Path ${JSON.stringify(path)} (${code ?? "unknown errno"}): ${cause instanceof Error ? cause.message : String(cause)}`
217
- );
218
- this.code = code;
219
- this.cause = cause;
220
- }
221
- }
222
- function scanOutputRoots(roots, links, commandRunning = false, onMissingTarget) {
223
- const files = /* @__PURE__ */ new Map();
224
- const observedLinks = /* @__PURE__ */ new Map();
225
- const visit = (path) => {
226
- let metadata;
227
- try {
228
- metadata = lstatSync(path);
229
- } catch (error) {
230
- if (error.code === "ENOENT") return;
231
- throw new OutputObservationError("Filesystem output lstat failed.", path, error);
232
- }
233
- if (metadata.isSymbolicLink()) {
234
- let link;
235
- try {
236
- link = readlinkSync(path);
237
- } catch (error) {
238
- throw new OutputObservationError("Filesystem output readlink failed.", path, error);
239
- }
240
- const identity = digestValue({
241
- device: metadata.dev,
242
- inode: metadata.ino,
243
- changed: metadata.ctimeMs,
244
- modified: metadata.mtimeMs,
245
- link
246
- });
247
- let target;
248
- let missing = false;
249
- try {
250
- target = realpathSync(path);
251
- } catch (error) {
252
- const failure = new OutputObservationError(
253
- "Filesystem output observation encountered a broken or cyclic symbolic link.",
254
- path,
255
- error
256
- );
257
- const previous2 = links.get(path);
258
- if (previous2 !== void 0 && previous2.identity !== identity)
259
- throw new DeliveryError(`Filesystem output alias identity changed. Path ${JSON.stringify(path)}.`);
260
- if (!commandRunning || failure.code !== "ENOENT" || previous2?.identity !== identity) throw failure;
261
- let lexical = resolve(dirname(path), link);
262
- let ancestor = lexical;
263
- const expanded = /* @__PURE__ */ new Set([path]);
264
- for (; ; ) {
265
- try {
266
- target = join(realpathSync(ancestor), lexical.slice(ancestor.length));
267
- break;
268
- } catch (ancestorError) {
269
- if (ancestorError.code !== "ENOENT" || dirname(ancestor) === ancestor)
270
- throw new OutputObservationError(
271
- "Filesystem output ancestor resolution failed.",
272
- ancestor,
273
- ancestorError
274
- );
275
- let ancestorMetadata;
276
- try {
277
- ancestorMetadata = lstatSync(ancestor);
278
- } catch (metadataError) {
279
- if (metadataError.code !== "ENOENT")
280
- throw new OutputObservationError("Filesystem output ancestor lstat failed.", ancestor, metadataError);
281
- }
282
- if (ancestorMetadata?.isSymbolicLink()) {
283
- let ancestorLink, currentAncestor;
284
- try {
285
- ancestorLink = readlinkSync(ancestor);
286
- currentAncestor = lstatSync(ancestor);
287
- } catch (aliasError) {
288
- throw new OutputObservationError("Filesystem output ancestor alias read failed.", ancestor, aliasError);
289
- }
290
- const ancestorIdentity = digestValue({
291
- device: ancestorMetadata.dev,
292
- inode: ancestorMetadata.ino,
293
- changed: ancestorMetadata.ctimeMs,
294
- modified: ancestorMetadata.mtimeMs,
295
- link: ancestorLink
296
- });
297
- const previousAncestor = links.get(ancestor);
298
- if (previousAncestor === void 0) throw failure;
299
- if (expanded.has(ancestor) || previousAncestor.identity !== ancestorIdentity || !currentAncestor.isSymbolicLink() || currentAncestor.dev !== ancestorMetadata.dev || currentAncestor.ino !== ancestorMetadata.ino || currentAncestor.ctimeMs !== ancestorMetadata.ctimeMs || currentAncestor.mtimeMs !== ancestorMetadata.mtimeMs)
300
- throw new DeliveryError(
301
- `Filesystem output ancestor alias identity changed. Path ${JSON.stringify(ancestor)}.`
302
- );
303
- expanded.add(ancestor);
304
- lexical = join(resolve(dirname(ancestor), ancestorLink), lexical.slice(ancestor.length));
305
- ancestor = lexical;
306
- continue;
307
- }
308
- ancestor = dirname(ancestor);
309
- }
310
- }
311
- if (target !== previous2.target)
312
- throw new DeliveryError(`Filesystem output alias target identity changed. Path ${JSON.stringify(path)}.`);
313
- missing = true;
314
- onMissingTarget?.(failure.message);
315
- }
316
- const previous = links.get(path);
317
- if (previous?.missing && (previous.identity !== identity || previous.target !== target))
318
- throw new DeliveryError(
319
- `Filesystem output alias identity changed after target absence. Path ${JSON.stringify(path)}.`
320
- );
321
- if (!roots.some((root) => target === root || target.startsWith(`${root}${sep}`))) {
322
- throw new DeliveryError(
323
- `Filesystem output observation encountered an escaping symbolic link. Path ${JSON.stringify(path)} resolves to ${JSON.stringify(target)}.`
324
- );
325
- }
326
- let current;
327
- try {
328
- current = lstatSync(path);
329
- } catch (error) {
330
- if (commandRunning && error.code === "ENOENT" && previous?.identity === identity)
331
- return;
332
- throw new OutputObservationError("Filesystem output alias identity readback failed.", path, error);
333
- }
334
- if (!current.isSymbolicLink() || current.dev !== metadata.dev || current.ino !== metadata.ino || current.ctimeMs !== metadata.ctimeMs || current.mtimeMs !== metadata.mtimeMs)
335
- throw new DeliveryError(
336
- `Filesystem output alias identity changed during observation. Path ${JSON.stringify(path)}.`
337
- );
338
- observedLinks.set(path, { identity, target, missing });
339
- return;
340
- }
341
- if (metadata.isDirectory()) {
342
- let names;
343
- try {
344
- names = readdirSync(path);
345
- } catch (error) {
346
- if (error.code === "ENOENT") return;
347
- throw new OutputObservationError("Filesystem output readdir failed.", path, error);
348
- }
349
- for (const name of names) visit(join(path, name));
350
- return;
351
- }
352
- if (!metadata.isFile() && !metadata.isSocket() || !Number.isSafeInteger(metadata.size)) {
353
- throw new DeliveryError(
354
- `Filesystem output observation encountered an unsupported file. Path ${JSON.stringify(path)}.`
355
- );
356
- }
357
- files.set(path, metadata.isSocket() ? 0 : metadata.size);
358
- if (files.size > 1e6) throw new DeliveryError("Filesystem output observation exceeded its file limit.");
359
- };
360
- for (const root of roots) {
361
- if (existsSync(root) && realpathSync(root) !== root)
362
- throw new DeliveryError("Filesystem output roots must not be symbolic links.");
363
- visit(root);
364
- }
365
- links.clear();
366
- for (const [path, link] of observedLinks) links.set(path, link);
367
- return files;
368
- }
369
- async function positiveNewOutputBytes(baseline, signal, commandRunning = false, onUnavailable) {
370
- let files;
371
- let firstFailure;
372
- let lastFailure;
373
- let firstFailureAt;
374
- const assertObservationWindow = () => {
375
- if (firstFailureAt !== void 0 && Date.now() - firstFailureAt >= 1e3) {
376
- throw new DeliveryError(
377
- `Filesystem output observation remained unavailable for 1 second. First observation: ${firstFailure.message} Last observation: ${lastFailure.message}`
378
- );
379
- }
380
- };
381
- for (; ; ) {
382
- if (signal?.aborted) throw new DeliveryError("Filesystem output observation cancelled.");
383
- assertObservationWindow();
384
- try {
385
- files = await withOutputGateLock(
386
- baseline.gate,
387
- "scan",
388
- () => scanOutputRoots(baseline.roots, baseline.links, commandRunning, onUnavailable),
389
- signal
390
- );
391
- assertObservationWindow();
392
- break;
393
- } catch (error) {
394
- if (!commandRunning || !(error instanceof OutputObservationError) || error.code !== "ENOENT") throw error;
395
- lastFailure = error;
396
- if (firstFailure === void 0) {
397
- firstFailureAt = Date.now();
398
- firstFailure = error;
399
- onUnavailable?.(error.message);
400
- }
401
- assertObservationWindow();
402
- await new Promise((resolve2) => setTimeout(resolve2, 25));
403
- }
404
- }
405
- let bytes = 0;
406
- for (const [path, size] of files) {
407
- bytes += Math.max(0, size - (baseline.files.get(path) ?? 0));
408
- if (!Number.isSafeInteger(bytes)) throw new DeliveryError("Filesystem output observation overflowed.");
409
- }
410
- return bytes;
411
- }
412
11
  function availableDiskBytes(path) {
413
12
  let existing = path;
414
13
  for (; ; ) {
@@ -421,14 +20,9 @@ function availableDiskBytes(path) {
421
20
  }
422
21
  }
423
22
  }
424
- function freeDiskBytes(repoRoot, baseline) {
425
- const roots = baseline === void 0 ? [repoRoot] : [repoRoot, ...baseline.roots];
426
- const minimum = roots.reduce((value, path) => {
427
- const available = availableDiskBytes(path);
428
- return available < value ? available : value;
429
- }, BigInt(Number.MAX_SAFE_INTEGER));
430
- if (minimum > BigInt(Number.MAX_SAFE_INTEGER)) throw new DeliveryError("Free disk observation overflowed.");
431
- return Number(minimum);
23
+ function freeDiskBytes(repoRoot) {
24
+ const available = availableDiskBytes(repoRoot);
25
+ return Number(available < BigInt(Number.MAX_SAFE_INTEGER) ? available : BigInt(Number.MAX_SAFE_INTEGER));
432
26
  }
433
27
  class ProcessSnapshotError extends DeliveryError {
434
28
  }
@@ -521,7 +115,7 @@ function observeOwnedProcesses(state, snapshot) {
521
115
  state.sampled = true;
522
116
  return [...selected.values()];
523
117
  }
524
- function sampleOwnedTree(state, repoRoot, bounds, baseline, newOutputBytes, controllerRssBytes = 0, includeControllerTree = false) {
118
+ function sampleOwnedTree(state, repoRoot, bounds, controllerRssBytes = 0, includeControllerTree = false) {
525
119
  const snapshot = processSnapshot();
526
120
  const owned = observeOwnedProcesses(state, snapshot);
527
121
  const controller = includeControllerTree ? controllerTreeRssBytes(snapshot, new Set(owned.map((member) => member.pid))) : controllerRssBytes;
@@ -531,25 +125,9 @@ function sampleOwnedTree(state, repoRoot, bounds, baseline, newOutputBytes, cont
531
125
  if (rssBytes > bounds.maxAggregateRssBytes) {
532
126
  throw new DeliveryError(`Owned aggregate RSS ${rssBytes} exceeded limit ${bounds.maxAggregateRssBytes}.`);
533
127
  }
534
- const available = freeDiskBytes(repoRoot, baseline);
128
+ const available = freeDiskBytes(repoRoot);
535
129
  if (available < bounds.minFreeDiskBytes)
536
130
  throw new DeliveryError(`Free disk fell below limit ${bounds.minFreeDiskBytes}.`);
537
- if (newOutputBytes !== void 0 && !Number.isSafeInteger(newOutputBytes)) {
538
- throw new DeliveryError("Filesystem output observation overflowed.");
539
- }
540
- if (baseline !== void 0 && bounds.maxNewOutputBytes !== void 0) {
541
- if (newOutputBytes !== void 0 && newOutputBytes > bounds.maxNewOutputBytes) {
542
- throw new DeliveryError(
543
- `Positive new filesystem output ${newOutputBytes} exceeded limit ${bounds.maxNewOutputBytes}.`
544
- );
545
- }
546
- }
547
- return {
548
- aggregateRssBytes: rssBytes,
549
- freeDiskBytes: available,
550
- ...newOutputBytes === void 0 ? {} : { newOutputBytes },
551
- ownedProcessCount: owned.length
552
- };
553
131
  }
554
132
  function controllerTreeRssBytes(snapshot = processSnapshot(), excluded = /* @__PURE__ */ new Set()) {
555
133
  const controller = snapshot.get(process.pid);
@@ -589,7 +167,7 @@ async function confirmOwnedCleanup(state) {
589
167
  });
590
168
  if (!groupAlive && !trackedAlive) return;
591
169
  if (Date.now() >= deadline) throw new DeliveryError("Owned process cleanup did not release every sampled process.");
592
- await new Promise((resolve2) => setTimeout(resolve2, 100));
170
+ await new Promise((resolve) => setTimeout(resolve, 100));
593
171
  }
594
172
  }
595
173
  function terminateOwnedProcesses(state) {
@@ -693,15 +271,18 @@ function producerDigest(root = dirname(fileURLToPath(import.meta.url))) {
693
271
  function retainedWorktreeTransitionProducerDigest(distDirectory) {
694
272
  return producerDigest(realpathSync(distDirectory));
695
273
  }
696
- function retainedWorktreeTransitionDependencyManifests(distDirectory) {
697
- return producerContent(realpathSync(distDirectory)).dependencies.map(([source, digest]) => ({ source, digest }));
274
+ function writeCommandOutput(bytes, commonDir) {
275
+ const digest = digestBytes(bytes);
276
+ const path = join(commonDir, "ai-delivery", "verification@1", "command-output", `${digest.slice(7)}.bin`);
277
+ writeCreateOnly(path, bytes, digest);
278
+ return digest;
698
279
  }
699
- function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds, baseline, onResourceSample, writer, execution) {
280
+ function runStageCommand(repoRoot, argv, abortSignal, resourceBounds, writer, execution) {
700
281
  const [executable, ...args] = argv;
701
282
  if (!executable) throw new DeliveryError("Policy selected an empty stage command.");
702
283
  if (abortSignal?.aborted) throw new DeliveryError("Selected policy stage command cancelled.");
703
284
  writer?.starting();
704
- return new Promise((resolve2, reject) => {
285
+ return new Promise((resolve, reject) => {
705
286
  const child = spawn(
706
287
  "/bin/sh",
707
288
  [
@@ -715,12 +296,7 @@ function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds,
715
296
  cwd: execution?.cwd ?? repoRoot,
716
297
  detached: process.platform !== "win32",
717
298
  stdio: ["pipe", "pipe", "pipe"],
718
- ...baseline?.gate === void 0 && execution === void 0 ? {} : {
719
- env: {
720
- ...execution?.environment ?? process.env,
721
- ...baseline?.gate === void 0 ? {} : { [OUTPUT_GATE_ENV]: JSON.stringify(baseline.gate) }
722
- }
723
- }
299
+ ...execution === void 0 ? {} : { env: execution.environment }
724
300
  }
725
301
  );
726
302
  const stdout = [];
@@ -729,32 +305,25 @@ function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds,
729
305
  let outputBytes = 0;
730
306
  let retainedOutputBytes = 0;
731
307
  const outputLimit = execution?.maxCapturedOutputBytes ?? 8 * 1024 * 1024;
732
- let sampledOutputBytes = 0;
733
308
  let failure;
734
309
  let cleanupFailure;
735
310
  let writerFailure;
736
311
  let closed = false;
737
312
  let settled = false;
738
313
  let commandReleased = false;
739
- let firstOutputObservationFailure;
740
- let lastOutputObservationFailure;
741
- let pendingOutput;
742
- const scanCancellation = new AbortController();
743
314
  const failedOutput = () => {
744
- const observation = firstOutputObservationFailure === void 0 ? "" : ` First filesystem observation: ${firstOutputObservationFailure} Last filesystem observation: ${lastOutputObservationFailure}`;
745
315
  try {
746
316
  const bytes = Buffer.concat([...stdout, ...stderr]);
747
317
  if (execution?.failedOutput) return execution.failedOutput(bytes);
748
- return ` Command output ${writeRepositoryCommandOutput({ bytes, gitCommonDir: gitCommonDir(repoRoot) })}.${observation}`;
318
+ return ` Command output ${writeCommandOutput(bytes, gitCommonDir(repoRoot))}.`;
749
319
  } catch (error) {
750
- return ` Command output persistence failed (${error instanceof Error ? error.message : String(error)}).${observation}`;
320
+ return ` Command output persistence failed (${error instanceof Error ? error.message : String(error)}).`;
751
321
  }
752
322
  };
753
323
  let closeTimer;
754
324
  let exitPipeTimer;
755
325
  let resourceTimer;
756
326
  const clearWatchers = () => {
757
- clearInterval(progressTimer);
758
327
  if (resourceTimer !== void 0) clearInterval(resourceTimer);
759
328
  if (closeTimer !== void 0) clearTimeout(closeTimer);
760
329
  if (exitPipeTimer !== void 0) clearTimeout(exitPipeTimer);
@@ -792,7 +361,6 @@ function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds,
792
361
  const stop = (reason) => {
793
362
  if (failure !== void 0) return;
794
363
  failure = reason;
795
- scanCancellation.abort();
796
364
  killOwned();
797
365
  if (!closed) {
798
366
  closeTimer = setTimeout(() => {
@@ -814,7 +382,7 @@ function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds,
814
382
  const capture = (chunks, chunk) => {
815
383
  outputBytes += chunk.length;
816
384
  execution?.onCaptured?.(outputBytes);
817
- if (execution !== void 0 && resourceBounds?.maxNewOutputBytes !== void 0 && outputBytes + sampledOutputBytes > resourceBounds.maxNewOutputBytes) {
385
+ if (execution !== void 0 && resourceBounds?.maxNewOutputBytes !== void 0 && outputBytes > resourceBounds.maxNewOutputBytes) {
818
386
  stop("source-phase captured output exceeded remaining cumulative allowance");
819
387
  return;
820
388
  }
@@ -856,53 +424,18 @@ function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds,
856
424
  if (owned === void 0) throw new DeliveryError("Owned process identity is unavailable on this platform.");
857
425
  observeOwnedProcesses(owned, processSnapshot());
858
426
  writer?.observed(owned);
859
- if (resourceBounds !== void 0) {
860
- const result = sampleOwnedTree(
427
+ if (resourceBounds !== void 0)
428
+ sampleOwnedTree(
861
429
  owned,
862
430
  repoRoot,
863
431
  resourceBounds,
864
- baseline,
865
- void 0,
866
432
  execution === void 0 ? 0 : process.memoryUsage().rss,
867
433
  execution?.includeControllerTree
868
434
  );
869
- onResourceSample?.(result);
870
- onRunning?.(outputBytes, result);
435
+ if (!closed && failure === void 0 && !commandReleased) {
436
+ commandReleased = true;
437
+ child.stdin.end("run\n");
871
438
  }
872
- if (closed || pendingOutput !== void 0) return;
873
- pendingOutput = (async () => {
874
- if (resourceBounds !== void 0 && baseline !== void 0) {
875
- const bytes = await positiveNewOutputBytes(
876
- baseline,
877
- scanCancellation.signal,
878
- commandReleased,
879
- (reason) => {
880
- firstOutputObservationFailure ??= reason;
881
- lastOutputObservationFailure = reason;
882
- onRunning?.(outputBytes, void 0, reason);
883
- }
884
- );
885
- if (failure !== void 0) return;
886
- sampledOutputBytes = bytes;
887
- const result = sampleOwnedTree(
888
- owned,
889
- repoRoot,
890
- resourceBounds,
891
- baseline,
892
- bytes + (execution === void 0 ? 0 : outputBytes),
893
- execution === void 0 ? 0 : process.memoryUsage().rss,
894
- execution?.includeControllerTree
895
- );
896
- onResourceSample?.(result);
897
- onRunning?.(outputBytes, result);
898
- }
899
- if (failure === void 0 && !commandReleased) {
900
- commandReleased = true;
901
- child.stdin.end("run\n");
902
- }
903
- })().catch((error) => stop(error instanceof Error ? error.message : String(error))).finally(() => {
904
- pendingOutput = void 0;
905
- });
906
439
  } catch (error) {
907
440
  stop(error instanceof Error ? error.message : String(error));
908
441
  }
@@ -911,8 +444,6 @@ function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds,
911
444
  resourceTimer = setInterval(sample, 1e3);
912
445
  resourceTimer.unref();
913
446
  });
914
- const progressTimer = setInterval(() => onRunning?.(outputBytes), 5e3);
915
- progressTimer.unref();
916
447
  const onAbort = () => stop("cancelled");
917
448
  const onSigint = () => stop("cancelled by SIGINT");
918
449
  const onSigterm = () => stop("cancelled by SIGTERM");
@@ -923,22 +454,16 @@ function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds,
923
454
  const handleClose = async (code, signal) => {
924
455
  closed = true;
925
456
  if (settled) return;
926
- await pendingOutput;
927
457
  if (failure === void 0 && owned !== void 0) {
928
458
  try {
929
- if (resourceBounds !== void 0) {
930
- const sample = sampleOwnedTree(
459
+ if (resourceBounds !== void 0)
460
+ sampleOwnedTree(
931
461
  owned,
932
462
  repoRoot,
933
463
  resourceBounds,
934
- baseline,
935
- baseline === void 0 ? void 0 : await positiveNewOutputBytes(baseline, scanCancellation.signal) + (execution === void 0 ? 0 : outputBytes),
936
464
  execution === void 0 ? 0 : process.memoryUsage().rss,
937
465
  execution?.includeControllerTree
938
466
  );
939
- onResourceSample?.(sample);
940
- onRunning?.(outputBytes, sample);
941
- }
942
467
  if (!owned.sampled) throw new DeliveryError("Owned process resource observation was unavailable.");
943
468
  const remaining = observeOwnedProcesses(owned, processSnapshot());
944
469
  if (remaining.length > 0) throw new DeliveryError("A sampled owned descendant survived command exit.");
@@ -975,7 +500,7 @@ function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds,
975
500
  }
976
501
  writer?.idle();
977
502
  settled = true;
978
- resolve2(execution?.stdoutOnly ? Buffer.concat(stdout) : Buffer.concat([...stdout, ...stderr], outputBytes));
503
+ resolve(execution?.stdoutOnly ? Buffer.concat(stdout) : Buffer.concat([...stdout, ...stderr], outputBytes));
979
504
  };
980
505
  child.once("close", (code, signal) => {
981
506
  void handleClose(code, signal).catch((error) => {
@@ -985,94 +510,11 @@ function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds,
985
510
  });
986
511
  });
987
512
  }
988
- const SourceDigest = z.string().regex(/^sha256:[a-f0-9]{64}$/u);
989
- const SourceSha = z.string().regex(/^[a-f0-9]{40}$/u);
990
- const SourceArtifactSchema = z.strictObject({ path: z.string().min(1), digest: SourceDigest });
991
- const SourceFileSchema = SourceArtifactSchema.extend({
992
- device: z.number().int().nonnegative().safe(),
993
- inode: z.number().int().nonnegative().safe(),
994
- uid: z.number().int().nonnegative().safe(),
995
- mode: z.number().int().nonnegative().safe()
996
- });
997
- const SourceCommandSchema = z.strictObject({
998
- argv: z.array(z.string()).min(1),
999
- cwd: z.string().min(1),
1000
- executable: SourceFileSchema
1001
- });
1002
- const SourceSnapshotSchema = z.strictObject({
1003
- head: SourceSha,
1004
- indexTree: SourceSha,
1005
- branch: z.string().min(1),
1006
- configDigest: SourceDigest,
1007
- dirty: z.array(z.strictObject({ path: z.string().min(1), digest: SourceDigest.nullable() }))
1008
- });
1009
- const SourceBoundsSchema = z.strictObject({
1010
- maxAggregateRssBytes: z.number().int().positive().safe(),
1011
- maxNewOutputBytes: z.number().int().positive().safe(),
1012
- minFreeDiskBytes: z.number().int().positive().safe(),
1013
- outputRoots: z.array(z.string().min(1)).min(1)
1014
- });
1015
- const SourceReconciliationSchema = z.strictObject({
1016
- phaseId: SourceDigest,
1017
- recordId: SourceDigest,
1018
- baselineId: SourceDigest.optional(),
1019
- authorizationDigest: SourceDigest
1020
- });
1021
- const IssueSourcePhaseInputSchema = z.strictObject({
1022
- repoRoot: z.string().min(1),
1023
- issueNumber: z.number().int().positive().safe(),
1024
- identity: z.string().min(1),
1025
- rowDigest: SourceDigest,
1026
- controller: z.strictObject({
1027
- head: SourceSha,
1028
- configDigest: SourceDigest,
1029
- admissionId: SourceDigest,
1030
- runtimeEntryPath: z.string().min(1),
1031
- packageVersion: z.string().min(1),
1032
- archiveDigest: SourceDigest
1033
- }),
1034
- source: SourceSnapshotSchema.extend({
1035
- path: z.string().min(1),
1036
- effect: z.discriminatedUnion("kind", [
1037
- z.strictObject({ kind: z.literal("preserve") }),
1038
- z.strictObject({
1039
- kind: z.literal("commitOnce"),
1040
- parent: SourceSha,
1041
- tree: SourceSha,
1042
- configDigest: SourceDigest.optional()
1043
- })
1044
- ])
1045
- }),
1046
- caller: SourceArtifactSchema,
1047
- authorization: SourceArtifactSchema,
1048
- inputs: z.array(SourceArtifactSchema),
1049
- commands: z.array(SourceCommandSchema).min(1),
1050
- commandGraphDigest: SourceDigest,
1051
- environment: z.strictObject({ digest: SourceDigest, overrides: z.record(z.string(), z.string().nullable()) }),
1052
- bounds: SourceBoundsSchema,
1053
- completionArtifacts: z.array(z.string().min(1)),
1054
- reconciliation: SourceReconciliationSchema.optional()
1055
- });
1056
- const SourcePhaseCommandResultSchema = z.strictObject({
1057
- index: z.number().int().nonnegative().safe(),
1058
- outputDigest: SourceDigest.nullable(),
1059
- outputBytes: z.number().int().nonnegative().safe(),
1060
- status: z.enum(["complete", "failed"])
1061
- });
1062
- const IssueSourcePhaseReceiptSchema = z.strictObject({
1063
- status: z.literal("complete"),
1064
- phaseId: SourceDigest,
1065
- recordId: SourceDigest,
1066
- source: SourceSnapshotSchema,
1067
- commands: z.array(SourcePhaseCommandResultSchema)
1068
- });
1069
513
  export {
1070
514
  confirmOwnedCleanup,
1071
515
  processSnapshot,
1072
- retainedWorktreeTransitionDependencyManifests,
1073
516
  retainedWorktreeTransitionProducerDigest,
1074
517
  runStageCommand,
1075
- terminateOwnedProcesses,
1076
- withVerificationFilesystemFixture
518
+ terminateOwnedProcesses
1077
519
  };
1078
520
  //# sourceMappingURL=verification.js.map