@aviaratech/ai-delivery 0.3.35 → 0.3.37

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 (301) hide show
  1. package/CONTRIBUTING.md +12 -206
  2. package/README.md +56 -554
  3. package/dist/agent.d.ts +1 -3
  4. package/dist/agent.js +74 -16
  5. package/dist/agent.js.map +7 -1
  6. package/dist/agentReadiness.test.js +73 -67
  7. package/dist/agentReadiness.test.js.map +7 -1
  8. package/dist/boardReconcile.test.js +1651 -1590
  9. package/dist/boardReconcile.test.js.map +7 -1
  10. package/dist/build.test.js +130 -0
  11. package/dist/build.test.js.map +7 -0
  12. package/dist/callerErrors.test.js +91 -0
  13. package/dist/callerErrors.test.js.map +7 -0
  14. package/dist/cli.js +389 -517
  15. package/dist/cli.js.map +7 -1
  16. package/dist/cliResult.d.ts +2 -2
  17. package/dist/cliResult.js +42 -45
  18. package/dist/cliResult.js.map +7 -1
  19. package/dist/cliResult.test.js +424 -369
  20. package/dist/cliResult.test.js.map +7 -1
  21. package/dist/config/deliveryConfig.d.ts +288 -14
  22. package/dist/config/deliveryConfig.js +472 -390
  23. package/dist/config/deliveryConfig.js.map +7 -1
  24. package/dist/config/deliveryConfig.test.js +773 -649
  25. package/dist/config/deliveryConfig.test.js.map +7 -1
  26. package/dist/contributorChecks.test.js +1694 -916
  27. package/dist/contributorChecks.test.js.map +7 -1
  28. package/dist/currentConsumer.test.js +819 -737
  29. package/dist/currentConsumer.test.js.map +7 -1
  30. package/dist/currentTrackingScenario.test.js +499 -479
  31. package/dist/currentTrackingScenario.test.js.map +7 -1
  32. package/dist/delivery/common.js +160 -172
  33. package/dist/delivery/common.js.map +7 -1
  34. package/dist/delivery/delivery.test.js +509 -431
  35. package/dist/delivery/delivery.test.js.map +7 -1
  36. package/dist/delivery/evidence.d.ts +2 -2
  37. package/dist/delivery/evidence.js +133 -120
  38. package/dist/delivery/evidence.js.map +7 -1
  39. package/dist/delivery/index.js +7 -2
  40. package/dist/delivery/index.js.map +7 -1
  41. package/dist/delivery/legacy.js +65 -5
  42. package/dist/delivery/legacy.js.map +7 -1
  43. package/dist/delivery/policy.d.ts +10 -10
  44. package/dist/delivery/policy.js +211 -238
  45. package/dist/delivery/policy.js.map +7 -1
  46. package/dist/delivery/stage.d.ts +18 -18
  47. package/dist/delivery/stage.js +220 -235
  48. package/dist/delivery/stage.js.map +7 -1
  49. package/dist/deliveryBoard.d.ts +74 -0
  50. package/dist/deliveryBoard.js +644 -0
  51. package/dist/deliveryBoard.js.map +7 -0
  52. package/dist/deliveryBoard.test.js +649 -0
  53. package/dist/deliveryBoard.test.js.map +7 -0
  54. package/dist/deliveryHealth.test.js +179 -155
  55. package/dist/deliveryHealth.test.js.map +7 -1
  56. package/dist/dependencyCompatibility.test.js +154 -140
  57. package/dist/dependencyCompatibility.test.js.map +7 -1
  58. package/dist/directoryIndependent.test.js +417 -383
  59. package/dist/directoryIndependent.test.js.map +7 -1
  60. package/dist/dispatch.d.ts +16 -11
  61. package/dist/dispatch.js +316 -354
  62. package/dist/dispatch.js.map +7 -1
  63. package/dist/errors.d.ts +3 -3
  64. package/dist/errors.js +103 -96
  65. package/dist/errors.js.map +7 -1
  66. package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
  67. package/dist/fixtures/deliveryBoardReplay.js +617 -0
  68. package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
  69. package/dist/fixtures/discovery.d.ts +63 -23
  70. package/dist/fixtures/discovery.js +96 -90
  71. package/dist/fixtures/discovery.js.map +7 -1
  72. package/dist/fixtures/inertEntrypointChild.js +57 -56
  73. package/dist/fixtures/inertEntrypointChild.js.map +7 -1
  74. package/dist/fixtures/inertEntrypoints.d.ts +1 -1
  75. package/dist/fixtures/inertEntrypoints.js +321 -276
  76. package/dist/fixtures/inertEntrypoints.js.map +7 -1
  77. package/dist/fixtures/inertTarget.d.ts +78 -7
  78. package/dist/fixtures/inertTarget.js +769 -691
  79. package/dist/fixtures/inertTarget.js.map +7 -1
  80. package/dist/fixtures/issue63.d.ts +4 -3
  81. package/dist/fixtures/issue63.js +260 -274
  82. package/dist/fixtures/issue63.js.map +7 -1
  83. package/dist/fixtures/issueProjectItems.d.ts +20 -0
  84. package/dist/fixtures/issueProjectItems.js +15 -0
  85. package/dist/fixtures/issueProjectItems.js.map +7 -0
  86. package/dist/fixtures/readView.d.ts +120 -0
  87. package/dist/fixtures/readView.js +172 -0
  88. package/dist/fixtures/readView.js.map +7 -0
  89. package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
  90. package/dist/fixtures/recordedGitHubFlows.js +109 -0
  91. package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
  92. package/dist/genericCompatibility.test.js +64 -55
  93. package/dist/genericCompatibility.test.js.map +7 -1
  94. package/dist/git.d.ts +0 -3
  95. package/dist/git.js +59 -76
  96. package/dist/git.js.map +7 -1
  97. package/dist/gitProcess.d.ts +1 -1
  98. package/dist/gitProcess.js +58 -53
  99. package/dist/gitProcess.js.map +7 -1
  100. package/dist/github/client.d.ts +2 -2
  101. package/dist/github/client.js +484 -379
  102. package/dist/github/client.js.map +7 -1
  103. package/dist/github/commandIdentityPolicy.js +42 -52
  104. package/dist/github/commandIdentityPolicy.js.map +7 -1
  105. package/dist/github/discovery.d.ts +1 -0
  106. package/dist/github/discovery.js +197 -215
  107. package/dist/github/discovery.js.map +7 -1
  108. package/dist/github/discovery.test.js +223 -177
  109. package/dist/github/discovery.test.js.map +7 -1
  110. package/dist/github/issueHistory.d.ts +2 -2
  111. package/dist/github/issueHistory.js +117 -125
  112. package/dist/github/issueHistory.js.map +7 -1
  113. package/dist/github/machineAuth.d.ts +1 -1
  114. package/dist/github/machineAuth.js +126 -117
  115. package/dist/github/machineAuth.js.map +7 -1
  116. package/dist/github/machineAuth.test.js +755 -639
  117. package/dist/github/machineAuth.test.js.map +7 -1
  118. package/dist/github/nativeIssueMetadata.js +286 -273
  119. package/dist/github/nativeIssueMetadata.js.map +7 -1
  120. package/dist/github/projectDelivery.d.ts +18 -2
  121. package/dist/github/projectDelivery.js +615 -557
  122. package/dist/github/projectDelivery.js.map +7 -1
  123. package/dist/github/relationships.js +433 -389
  124. package/dist/github/relationships.js.map +7 -1
  125. package/dist/github/repo.d.ts +1 -0
  126. package/dist/github/repo.js +123 -96
  127. package/dist/github/repo.js.map +7 -1
  128. package/dist/index.js +3 -3
  129. package/dist/index.js.map +7 -1
  130. package/dist/issue.d.ts +40 -9
  131. package/dist/issue.js +2102 -1742
  132. package/dist/issue.js.map +7 -1
  133. package/dist/issue63History.test.js +40 -42
  134. package/dist/issue63History.test.js.map +7 -1
  135. package/dist/issue63Routes.test.js +154 -143
  136. package/dist/issue63Routes.test.js.map +7 -1
  137. package/dist/issueBatchUpdate.test.js +989 -885
  138. package/dist/issueBatchUpdate.test.js.map +7 -1
  139. package/dist/issueBlockerGuard.test.js +262 -226
  140. package/dist/issueBlockerGuard.test.js.map +7 -1
  141. package/dist/issueContract.d.ts +23 -4
  142. package/dist/issueContract.js +416 -395
  143. package/dist/issueContract.js.map +7 -1
  144. package/dist/issueContract.test.d.ts +4 -3
  145. package/dist/issueContract.test.js +358 -321
  146. package/dist/issueContract.test.js.map +7 -1
  147. package/dist/issueDates.test.js +235 -233
  148. package/dist/issueDates.test.js.map +7 -1
  149. package/dist/issueInfoReadback.test.js +304 -190
  150. package/dist/issueInfoReadback.test.js.map +7 -1
  151. package/dist/issueIntake.test.js +1938 -1732
  152. package/dist/issueIntake.test.js.map +7 -1
  153. package/dist/issueJournal.d.ts +40 -19
  154. package/dist/issueJournal.js +229 -138
  155. package/dist/issueJournal.js.map +7 -1
  156. package/dist/issueJournal.test.js +605 -422
  157. package/dist/issueJournal.test.js.map +7 -1
  158. package/dist/issueRollup.test.d.ts +1 -0
  159. package/dist/issueRollup.test.js +476 -0
  160. package/dist/issueRollup.test.js.map +7 -0
  161. package/dist/issueTracking.test.js +1059 -989
  162. package/dist/issueTracking.test.js.map +7 -1
  163. package/dist/issueWriteRecovery.test.d.ts +1 -0
  164. package/dist/issueWriteRecovery.test.js +260 -0
  165. package/dist/issueWriteRecovery.test.js.map +7 -0
  166. package/dist/lifecycle.test.js +112 -441
  167. package/dist/lifecycle.test.js.map +7 -1
  168. package/dist/logger.js +80 -74
  169. package/dist/logger.js.map +7 -1
  170. package/dist/mcp/index.js +116 -94
  171. package/dist/mcp/index.js.map +7 -1
  172. package/dist/mcp/tools.d.ts +252 -310
  173. package/dist/mcp/tools.js +235 -342
  174. package/dist/mcp/tools.js.map +7 -1
  175. package/dist/pluginAuthProbe.js +63 -52
  176. package/dist/pluginAuthProbe.js.map +7 -1
  177. package/dist/pluginAuthProbe.test.js +85 -62
  178. package/dist/pluginAuthProbe.test.js.map +7 -1
  179. package/dist/pluginCredentials.test.js +282 -259
  180. package/dist/pluginCredentials.test.js.map +7 -1
  181. package/dist/pluginDoctor.test.js +653 -588
  182. package/dist/pluginDoctor.test.js.map +7 -1
  183. package/dist/pluginInstaller.d.ts +7 -5
  184. package/dist/pluginInstaller.js +1173 -1229
  185. package/dist/pluginInstaller.js.map +7 -1
  186. package/dist/pluginInstaller.test.js +1842 -1423
  187. package/dist/pluginInstaller.test.js.map +7 -1
  188. package/dist/pluginPackaging.test.js +417 -413
  189. package/dist/pluginPackaging.test.js.map +7 -1
  190. package/dist/pr.d.ts +114 -131
  191. package/dist/pr.js +1314 -1327
  192. package/dist/pr.js.map +7 -1
  193. package/dist/pr.test.js +967 -653
  194. package/dist/pr.test.js.map +7 -1
  195. package/dist/prAssociation.test.js +2419 -1788
  196. package/dist/prAssociation.test.js.map +7 -1
  197. package/dist/prDispatch.test.js +123 -89
  198. package/dist/prDispatch.test.js.map +7 -1
  199. package/dist/readView.d.ts +184 -0
  200. package/dist/readView.js +218 -0
  201. package/dist/readView.js.map +7 -0
  202. package/dist/readView.test.d.ts +1 -0
  203. package/dist/readView.test.js +146 -0
  204. package/dist/readView.test.js.map +7 -0
  205. package/dist/releaseReconciliation.test.js +267 -288
  206. package/dist/releaseReconciliation.test.js.map +7 -1
  207. package/dist/releaseWorkflow.test.js +2493 -422
  208. package/dist/releaseWorkflow.test.js.map +7 -1
  209. package/dist/review.d.ts +738 -2
  210. package/dist/review.js +601 -348
  211. package/dist/review.js.map +7 -1
  212. package/dist/review.test.js +1218 -812
  213. package/dist/review.test.js.map +7 -1
  214. package/dist/reviewSubmit.test.d.ts +1 -0
  215. package/dist/reviewSubmit.test.js +747 -0
  216. package/dist/reviewSubmit.test.js.map +7 -0
  217. package/dist/services/agentReadinessService.js +42 -37
  218. package/dist/services/agentReadinessService.js.map +7 -1
  219. package/dist/services/blockerGuardService.js +188 -188
  220. package/dist/services/blockerGuardService.js.map +7 -1
  221. package/dist/services/boardReconcileService.d.ts +125 -125
  222. package/dist/services/boardReconcileService.js +1295 -1421
  223. package/dist/services/boardReconcileService.js.map +7 -1
  224. package/dist/services/deliveryHealthService.js +197 -199
  225. package/dist/services/deliveryHealthService.js.map +7 -1
  226. package/dist/services/legacyIssueMigration.js +263 -277
  227. package/dist/services/legacyIssueMigration.js.map +7 -1
  228. package/dist/stagedChecks.test.js +396 -194
  229. package/dist/stagedChecks.test.js.map +7 -1
  230. package/dist/start.test.js +99 -95
  231. package/dist/start.test.js.map +7 -1
  232. package/dist/stdoutRegression.test.js +321 -358
  233. package/dist/stdoutRegression.test.js.map +7 -1
  234. package/dist/targetPolicyDiscovery.test.js +141 -143
  235. package/dist/targetPolicyDiscovery.test.js.map +7 -1
  236. package/dist/targetPolicyEntrypoints.test.js +308 -269
  237. package/dist/targetPolicyEntrypoints.test.js.map +7 -1
  238. package/dist/targetPolicyLocal.test.js +580 -1051
  239. package/dist/targetPolicyLocal.test.js.map +7 -1
  240. package/dist/targetPolicyRoutes.test.js +274 -281
  241. package/dist/targetPolicyRoutes.test.js.map +7 -1
  242. package/dist/targetRepositoryExecution.test.d.ts +1 -0
  243. package/dist/targetRepositoryExecution.test.js +451 -0
  244. package/dist/targetRepositoryExecution.test.js.map +7 -0
  245. package/dist/terminalMessages.js +41 -35
  246. package/dist/terminalMessages.js.map +7 -1
  247. package/dist/toolOutput.d.ts +2 -0
  248. package/dist/toolOutput.js +36 -0
  249. package/dist/toolOutput.js.map +7 -0
  250. package/dist/toolOutput.test.d.ts +1 -0
  251. package/dist/toolOutput.test.js +240 -0
  252. package/dist/toolOutput.test.js.map +7 -0
  253. package/dist/utils/atomicJson.d.ts +0 -2
  254. package/dist/utils/atomicJson.js +81 -77
  255. package/dist/utils/atomicJson.js.map +7 -1
  256. package/dist/utils/filesystem.d.ts +0 -8
  257. package/dist/utils/filesystem.js +5 -19
  258. package/dist/utils/filesystem.js.map +7 -1
  259. package/dist/utils/lockfile.js +68 -71
  260. package/dist/utils/lockfile.js.map +7 -1
  261. package/dist/verification.d.ts +1 -54
  262. package/dist/verification.js +976 -1941
  263. package/dist/verification.js.map +7 -1
  264. package/dist/verificationGate.test.js +127 -117
  265. package/dist/verificationGate.test.js.map +7 -1
  266. package/dist/version.js +45 -24
  267. package/dist/version.js.map +7 -1
  268. package/package.json +9 -8
  269. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  270. package/plugins/ai-delivery/README.md +47 -156
  271. package/plugins/ai-delivery/plugin.json +1 -1
  272. package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +238 -44
  273. package/plugins/ai-delivery/runtime/dist/cli.js +351 -115
  274. package/plugins/ai-delivery/runtime/package.json +1 -1
  275. package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
  276. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
  277. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
  278. package/dist/investigationCompletion.test.js +0 -728
  279. package/dist/investigationCompletion.test.js.map +0 -1
  280. package/dist/services/deliveryAdmission.d.ts +0 -49
  281. package/dist/services/deliveryAdmission.js +0 -165
  282. package/dist/services/deliveryAdmission.js.map +0 -1
  283. package/dist/services/worktreeRegistry.d.ts +0 -434
  284. package/dist/services/worktreeRegistry.js +0 -1248
  285. package/dist/services/worktreeRegistry.js.map +0 -1
  286. package/dist/setup.d.ts +0 -60
  287. package/dist/setup.js +0 -585
  288. package/dist/setup.js.map +0 -1
  289. package/dist/setup.test.js +0 -3329
  290. package/dist/setup.test.js.map +0 -1
  291. package/dist/worktree.d.ts +0 -28
  292. package/dist/worktree.js +0 -188
  293. package/dist/worktree.js.map +0 -1
  294. package/dist/worktreeTransition.d.ts +0 -211
  295. package/dist/worktreeTransition.js +0 -1037
  296. package/dist/worktreeTransition.js.map +0 -1
  297. package/dist/worktreeTransition.test.js +0 -1191
  298. package/dist/worktreeTransition.test.js.map +0 -1
  299. /package/dist/{investigationCompletion.test.d.ts → build.test.d.ts} +0 -0
  300. /package/dist/{setup.test.d.ts → callerErrors.test.d.ts} +0 -0
  301. /package/dist/{worktreeTransition.test.d.ts → deliveryBoard.test.d.ts} +0 -0
@@ -1,2043 +1,1078 @@
1
- import { spawn, spawnSync } from 'node:child_process';
2
- import { randomUUID } from 'node:crypto';
3
- import { createRequire, findPackageJSON } from 'node:module';
4
- import { types } from 'node:util';
5
- import { closeSync, existsSync, fsyncSync, openSync, unlinkSync, lstatSync, mkdirSync, rmdirSync, renameSync, readFileSync, readlinkSync, readdirSync, realpathSync, statfsSync, } from 'node:fs';
6
- import { dirname, join, resolve, sep } from 'node:path';
7
- import { fileURLToPath } from 'node:url';
8
- import { z } from 'zod';
9
- import { assertPrivateFile } from './delivery/common.js';
10
- import { readRepositoryCommandOutput } from './delivery/stage.js';
11
- import { createRepositoryStageAggregate, digestBytes, digestValue, RepositoryClassificationReceiptSchema, RepositoryStageAggregateSchema, RepositoryStageReceiptSchema, writeRepositoryCommandOutput, } from './delivery/legacy.js';
12
- import { DeliveryError } from './errors.js';
13
- import { gitCommonDir, gitRoot } from './git.js';
14
- import { withLock } from './utils/lockfile.js';
15
- import { ensurePrivateDirectoryDurably, writePrivateJsonFileAtomically } from './utils/atomicJson.js';
16
- const ResourceSummarySchema = z
17
- .strictObject({
18
- bounds: z.strictObject({
19
- maxAggregateRssBytes: z.number().int().positive().safe(),
20
- maxNewOutputBytes: z.number().int().positive().safe().optional(),
21
- minFreeDiskBytes: z.number().int().positive().safe(),
22
- outputRoots: z.array(z.string().min(1)).min(1).optional(),
23
- }),
24
- maxSampledAggregateRssBytes: z.number().int().nonnegative().safe().nullable(),
25
- maxSampledNewOutputBytes: z.number().int().nonnegative().safe().nullable(),
26
- minSampledFreeDiskBytes: z.number().int().nonnegative().safe().nullable(),
27
- observation: z.literal('sampled'),
28
- outputBaselineId: z
29
- .string()
30
- .regex(/^sha256:[a-f0-9]{64}$/u)
31
- .optional(),
32
- processCoverage: z.literal('observed-processes-only'),
33
- sampleCount: z.number().int().nonnegative().safe(),
34
- })
35
- .superRefine((value, ctx) => {
36
- if ((value.maxSampledAggregateRssBytes !== null &&
37
- value.maxSampledAggregateRssBytes > value.bounds.maxAggregateRssBytes) ||
38
- (value.maxSampledNewOutputBytes !== null &&
39
- value.bounds.maxNewOutputBytes !== undefined &&
40
- value.maxSampledNewOutputBytes > value.bounds.maxNewOutputBytes) ||
41
- (value.minSampledFreeDiskBytes !== null && value.minSampledFreeDiskBytes < value.bounds.minFreeDiskBytes) ||
42
- (value.sampleCount > 0 &&
43
- (value.maxSampledAggregateRssBytes === null || value.minSampledFreeDiskBytes === null)) ||
44
- (value.bounds.maxNewOutputBytes !== undefined &&
45
- value.sampleCount > 0 &&
46
- value.maxSampledNewOutputBytes === null) ||
47
- (value.bounds.maxNewOutputBytes !== undefined) !== (value.outputBaselineId !== undefined))
48
- ctx.addIssue({ code: 'custom', message: 'Resource samples do not satisfy their declared bounds.' });
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { createRequire, findPackageJSON } from "node:module";
4
+ 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";
19
+ import { fileURLToPath } from "node:url";
20
+ import { z } from "zod";
21
+ import { assertPrivateFile } from "./delivery/common.js";
22
+ import { digestBytes, digestValue, writeRepositoryCommandOutput } from "./delivery/legacy.js";
23
+ import { DeliveryError } from "./errors.js";
24
+ 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." });
49
43
  });
50
- function assertResourceBounds(bounds) {
51
- const limits = [
52
- ['maxAggregateRssBytes', bounds.maxAggregateRssBytes],
53
- ['minFreeDiskBytes', bounds.minFreeDiskBytes],
54
- ];
55
- if (bounds.maxNewOutputBytes !== undefined)
56
- limits.push(['maxNewOutputBytes', bounds.maxNewOutputBytes]);
57
- for (const [name, value] of limits) {
58
- if (!Number.isSafeInteger(value) || value <= 0)
59
- throw new DeliveryError(`Invalid ${name} resource bound.`);
60
- }
61
- if ((bounds.maxNewOutputBytes === undefined) !== (bounds.outputRoots === undefined)) {
62
- throw new DeliveryError('Filesystem output limit and output roots must be supplied together.');
63
- }
64
- if (bounds.outputRoots !== undefined &&
65
- (bounds.outputRoots.length === 0 || bounds.outputRoots.some((path) => !path))) {
66
- throw new DeliveryError('Filesystem output roots must be nonempty paths.');
67
- }
68
- if (process.platform === 'win32')
69
- throw new DeliveryError('Resource observation requires POSIX process support.');
70
- }
71
- const OUTPUT_GATE_ENV = 'AI_DELIVERY_OUTPUT_OBSERVATION_GATE';
44
+ const OUTPUT_GATE_ENV = "AI_DELIVERY_OUTPUT_OBSERVATION_GATE";
72
45
  const GateOwnerSchema = z.strictObject({ pid: z.number().int().positive(), identity: z.string().min(1) });
73
46
  const OutputGateSchema = z.strictObject({ directory: z.string().min(1), id: z.uuid(), owner: GateOwnerSchema });
74
47
  const GateClaimSchema = z.strictObject({
75
- gateId: z.uuid(),
76
- id: z.uuid(),
77
- kind: z.enum(['scan', 'fixture']),
78
- owner: GateOwnerSchema,
48
+ gateId: z.uuid(),
49
+ id: z.uuid(),
50
+ kind: z.enum(["scan", "fixture"]),
51
+ owner: GateOwnerSchema
79
52
  });
80
53
  function gateOwner(snapshot = processSnapshot()) {
81
- const owner = snapshot.get(process.pid);
82
- if (!owner)
83
- throw new DeliveryError('Filesystem observation gate owner is unavailable.');
84
- return { pid: owner.pid, identity: owner.identity };
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 };
85
57
  }
86
58
  function assertGateDirectory(path) {
87
- const metadata = lstatSync(path);
88
- if (!metadata.isDirectory() || (metadata.mode & 0o077) !== 0 || realpathSync(path) !== path)
89
- throw new DeliveryError('Filesystem observation gate directory is invalid.');
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.");
90
62
  }
91
63
  function readOutputGate(value) {
92
- try {
93
- const gate = OutputGateSchema.parse(JSON.parse(value));
94
- assertOutputGate(gate);
95
- return gate;
96
- }
97
- catch (error) {
98
- throw new DeliveryError('Filesystem observation gate capability is invalid or stale: ' +
99
- (error instanceof Error ? error.message : String(error)));
100
- }
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
+ }
101
73
  }
102
74
  function gateOwnerAlive(owner, snapshot = processSnapshot()) {
103
- const current = snapshot.get(owner.pid);
104
- return current?.identity === owner.identity && !current.status.startsWith('Z');
75
+ const current = snapshot.get(owner.pid);
76
+ return current?.identity === owner.identity && !current.status.startsWith("Z");
105
77
  }
106
78
  function assertOutputGate(gate, abandoned = false) {
107
- assertGateDirectory(gate.directory);
108
- const manifest = OutputGateSchema.parse(JSON.parse(assertPrivateFile(join(gate.directory, 'gate.json')).toString('utf8')));
109
- const snapshot = processSnapshot();
110
- let actor = snapshot.get(process.pid);
111
- const ancestors = new Set();
112
- while (actor && actor.pid !== gate.owner.pid && !ancestors.has(actor.pid)) {
113
- ancestors.add(actor.pid);
114
- actor = snapshot.get(actor.ppid);
115
- }
116
- if (digestValue(manifest) !== digestValue(gate) ||
117
- (abandoned
118
- ? gateOwnerAlive(gate.owner, snapshot)
119
- : !gateOwnerAlive(gate.owner, snapshot) || actor?.identity !== gate.owner.identity))
120
- throw new DeliveryError('Filesystem observation gate ownership changed, was abandoned or is not an inherited ancestor.');
121
- return snapshot;
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;
122
95
  }
123
96
  function readGateClaim(gate, path) {
124
- const claim = GateClaimSchema.parse(JSON.parse(assertPrivateFile(path).toString('utf8')));
125
- if (claim.gateId !== gate.id)
126
- throw new DeliveryError('Filesystem observation gate claim belongs to another run.');
127
- return claim;
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;
128
100
  }
129
101
  function gateScanRequests(gate, snapshot) {
130
- const directory = join(gate.directory, 'requests');
131
- assertGateDirectory(directory);
132
- const requests = readdirSync(directory);
133
- if (requests.length > 1024 || requests.some((name) => !/^[a-f0-9-]{36}\.json$/u.test(name)))
134
- throw new DeliveryError('Filesystem observation gate scan requests are invalid.');
135
- const live = [];
136
- const currentSnapshot = snapshot ?? processSnapshot();
137
- for (const name of requests) {
138
- let claim;
139
- try {
140
- claim = readGateClaim(gate, join(directory, name));
141
- }
142
- catch (error) {
143
- if (error.code === 'ENOENT')
144
- continue;
145
- throw error;
146
- }
147
- if (claim.kind !== 'scan' || name !== claim.id + '.json' || !gateOwnerAlive(claim.owner, currentSnapshot))
148
- throw new DeliveryError('Filesystem observation gate scan request was abandoned.');
149
- live.push(name);
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;
150
116
  }
151
- return live;
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;
152
122
  }
153
123
  function removeGateClaim(gate, path, claim) {
154
- if (digestValue(readGateClaim(gate, path)) !== digestValue(claim))
155
- throw new DeliveryError('Filesystem observation gate claim changed before release.');
156
- unlinkSync(path);
124
+ if (digestValue(readGateClaim(gate, path)) !== digestValue(claim))
125
+ throw new DeliveryError("Filesystem observation gate claim changed before release.");
126
+ unlinkSync(path);
157
127
  }
158
128
  async function withOutputGateLock(gate, kind, operation, signal) {
159
- if (!gate)
160
- return operation();
161
- // Self identity belongs to this same synchronous ownership check, before any claim publication.
162
- const ownerSnapshot = assertOutputGate(gate);
163
- const claim = { gateId: gate.id, id: randomUUID(), kind, owner: gateOwner(ownerSnapshot) };
164
- const request = kind === 'scan' ? join(gate.directory, 'requests', claim.id + '.json') : undefined;
165
- const lock = join(gate.directory, 'held');
166
- const holder = join(lock, 'owner.json');
167
- if (request) {
168
- const staging = join(gate.directory, claim.id + '.pending');
169
- writePrivateJsonFileAtomically(staging, claim);
170
- renameSync(staging, request);
171
- }
172
- let acquired;
173
- let incompleteSince;
174
- let fixtureWait;
175
- const release = () => {
176
- if (!acquired)
177
- return;
178
- const metadata = lstatSync(lock);
179
- if (!metadata.isDirectory() || metadata.dev !== acquired.dev || metadata.ino !== acquired.ino)
180
- throw new DeliveryError('Filesystem observation gate lock changed before release.');
181
- if (readdirSync(lock).join(',') !== 'owner.json')
182
- throw new DeliveryError('Filesystem observation gate lock has unrelated metadata.');
183
- removeGateClaim(gate, holder, claim);
184
- rmdirSync(lock);
185
- acquired = undefined;
186
- };
187
- try {
188
- for (;;) {
189
- if (signal?.aborted)
190
- throw new DeliveryError('Filesystem observation gate wait cancelled.');
191
- const currentSnapshot = assertOutputGate(gate);
192
- const requests = gateScanRequests(gate, currentSnapshot);
193
- if (kind === 'scan' || requests.length === 0) {
194
- let created = false;
195
- try {
196
- mkdirSync(lock, { mode: 0o700 });
197
- created = true;
198
- }
199
- catch (error) {
200
- if (error.code !== 'EEXIST')
201
- throw error;
202
- }
203
- if (created) {
204
- const metadata = lstatSync(lock);
205
- acquired = { dev: metadata.dev, ino: metadata.ino };
206
- writePrivateJsonFileAtomically(holder, claim);
207
- // A scan may queue between the fixture's request check and atomic lock acquisition.
208
- if (kind === 'scan' || gateScanRequests(gate).length === 0)
209
- return await operation();
210
- release();
211
- }
212
- }
213
- if (existsSync(lock)) {
214
- try {
215
- assertGateDirectory(lock);
216
- const current = readGateClaim(gate, holder);
217
- incompleteSince = undefined;
218
- if (!gateOwnerAlive(current.owner))
219
- throw new DeliveryError('Filesystem observation gate fixture or scanner was abandoned.');
220
- if (kind === 'scan' && current.kind === 'fixture') {
221
- if (fixtureWait?.claimId !== current.id)
222
- fixtureWait = { claimId: current.id, since: Date.now() };
223
- // A negative reader that blocks prevents strict output observation; terminate this command, never steal its live lease.
224
- if (Date.now() - fixtureWait.since > 5000)
225
- throw new DeliveryError('Filesystem-negative fixture did not release a waiting output scan within 5 seconds; reader or teardown is stalled.');
226
- }
227
- else
228
- fixtureWait = undefined;
229
- }
230
- catch (error) {
231
- if (error.code !== 'ENOENT')
232
- throw error;
233
- incompleteSince ??= Date.now();
234
- // A concrete publication failure, never an elapsed fixture-work allowance or stale-lock takeover.
235
- if (Date.now() - incompleteSince > 2000)
236
- throw new DeliveryError('Filesystem observation gate owner publication is incomplete.');
237
- }
238
- }
239
- await new Promise((resolve) => setTimeout(resolve, 100));
240
- }
241
- }
242
- finally {
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;
243
161
  try {
244
- release();
162
+ mkdirSync(lock, { mode: 448 });
163
+ created = true;
164
+ } catch (error) {
165
+ if (error.code !== "EEXIST") throw error;
245
166
  }
246
- finally {
247
- if (request)
248
- removeGateClaim(gate, request, claim);
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();
249
173
  }
250
- }
251
- }
252
- /** Run a real filesystem-negative fixture between strict scans; the callback must clean it up before returning. */
253
- export async function withVerificationFilesystemFixture(operation) {
254
- const capability = process.env[OUTPUT_GATE_ENV];
255
- return withOutputGateLock(capability === undefined ? undefined : readOutputGate(capability), 'fixture', operation);
256
- }
257
- function retireOutputGate(gate, abandoned = false) {
258
- assertOutputGate(gate, abandoned);
259
- const requests = join(gate.directory, 'requests');
260
- const held = join(gate.directory, 'held');
261
- if (readdirSync(gate.directory).some((name) => !['gate.json', 'requests', 'held'].includes(name)))
262
- throw new DeliveryError('Filesystem observation gate has unrelated or incomplete metadata.');
263
- if (existsSync(held)) {
264
- assertGateDirectory(held);
265
- if (readdirSync(held).join(',') !== 'owner.json')
266
- throw new DeliveryError('Filesystem observation gate lock has unrelated metadata.');
267
- const claim = readGateClaim(gate, join(held, 'owner.json'));
268
- if (gateOwnerAlive(claim.owner))
269
- throw new DeliveryError('Filesystem observation gate still has a live holder.');
270
- removeGateClaim(gate, join(held, 'owner.json'), claim);
271
- rmdirSync(held);
272
- }
273
- for (const name of readdirSync(requests)) {
274
- if (!/^[a-f0-9-]{36}\.json$/u.test(name))
275
- throw new DeliveryError('Filesystem observation gate has unrelated metadata.');
276
- const path = join(requests, name);
277
- const claim = readGateClaim(gate, path);
278
- if (claim.kind !== 'scan' || name !== claim.id + '.json')
279
- throw new DeliveryError('Filesystem observation gate has unrelated scan metadata.');
280
- if (gateOwnerAlive(claim.owner))
281
- throw new DeliveryError('Filesystem observation gate still has a live scan request.');
282
- removeGateClaim(gate, path, claim);
283
- }
284
- rmdirSync(requests);
285
- if (digestValue(JSON.parse(assertPrivateFile(join(gate.directory, 'gate.json')).toString('utf8'))) !==
286
- digestValue(gate))
287
- throw new DeliveryError('Filesystem observation gate changed before retirement.');
288
- unlinkSync(join(gate.directory, 'gate.json'));
289
- rmdirSync(gate.directory);
290
- }
291
- function boundedOperationCause(operationFailure, prior) {
292
- let detail = 'kind=UNKNOWN';
293
- // Neither arbitrary thrown values nor their cause graphs are a diagnostic serialization contract.
294
- if (!types.isProxy(operationFailure) && types.isNativeError(operationFailure)) {
295
- detail = 'kind=Error';
296
- const descriptor = Object.getOwnPropertyDescriptor(operationFailure, 'message');
297
- const message = descriptor && 'value' in descriptor ? descriptor.value : undefined;
298
- if (typeof message === 'string' && message.length <= 4096) {
299
- detail += `; messageDigest=${digestBytes(Buffer.from(message))}`;
300
- const exit = /^Selected policy stage command failed \(exit (\d{1,3})\)\. Command exit \1\./u.exec(message);
301
- if (exit !== null && Number(exit[1]) <= 255)
302
- detail += `; exit=${Number(exit[1])}`;
303
- if (message.startsWith('Owned process resource observation failed. ')) {
304
- const code = /"errorCode":"(ETIMEDOUT|EACCES|EPERM|ENOENT|ENOBUFS|EAGAIN|ENOMEM|EIO|EINVAL|other)"/u.exec(message);
305
- detail += `; observation=${code?.[1] ?? 'UNKNOWN'}`;
306
- try {
307
- const metadata = JSON.parse(message
308
- .slice('Owned process resource observation failed. '.length)
309
- .replace(/ Output-gate retirement: wrappedOperation=(?:completed|failed)\.$/u, ''));
310
- if (metadata !== null && typeof metadata === 'object' && !Array.isArray(metadata)) {
311
- const numbers = ['elapsedMs', 'stdoutBytes', 'completeLines'].map((key) => {
312
- const field = Object.getOwnPropertyDescriptor(metadata, key);
313
- return field && 'value' in field ? field.value : undefined;
314
- });
315
- if (numbers.every((value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0))
316
- detail += `; elapsedMs=${numbers[0]}; stdoutBytes=${numbers[1]}; completeLines=${numbers[2]}`;
317
- }
318
- }
319
- catch {
320
- // Malformed diagnostic metadata must not replace the original retirement failure.
321
- }
322
- }
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.");
323
194
  }
195
+ }
196
+ await new Promise((resolve2) => setTimeout(resolve2, 100));
324
197
  }
325
- return new Error(`Wrapped operation failed. ${detail}`, prior === undefined ? undefined : { cause: prior.value });
326
- }
327
- function retireOutputGateAfterOperation(gate, operationCompleted, operationFailure) {
198
+ } finally {
328
199
  try {
329
- retireOutputGate(gate);
330
- }
331
- catch (error) {
332
- if (error instanceof ProcessSnapshotError)
333
- error.message += ` Output-gate retirement: wrappedOperation=${operationCompleted ? 'completed' : 'failed'}.`;
334
- if (!operationCompleted && !types.isProxy(error) && types.isNativeError(error)) {
335
- const prior = Object.getOwnPropertyDescriptor(error, 'cause');
336
- // An inaccessible/non-writable existing cause must retain its original behavior and precedence.
337
- if ((prior === undefined && Object.isExtensible(error)) ||
338
- (prior !== undefined && 'value' in prior && (prior.configurable || prior.writable))) {
339
- Object.defineProperty(error, 'cause', {
340
- configurable: prior?.configurable ?? true,
341
- enumerable: prior?.enumerable ?? false,
342
- writable: prior?.writable ?? true,
343
- value: boundedOperationCause(operationFailure, prior),
344
- });
345
- }
346
- }
347
- // Keep the original retirement error, its existing cause lineage, and its primary precedence.
348
- throw error;
200
+ release();
201
+ } finally {
202
+ if (request) removeGateClaim(gate, request, claim);
349
203
  }
204
+ }
350
205
  }
351
- async function withOutputObservationGate(root, enabled, operation) {
352
- const inherited = process.env[OUTPUT_GATE_ENV];
353
- if (inherited !== undefined)
354
- return operation(readOutputGate(inherited));
355
- if (!enabled)
356
- return operation(undefined);
357
- const id = randomUUID();
358
- const namespace = join(gitCommonDir(root), 'ai-delivery', 'output-observation', worktreeDigest(root).slice(7));
359
- ensurePrivateDirectoryDurably(namespace);
360
- // The existing writer has recovered and confirmed old command quiescence before this operation.
361
- for (const priorId of readdirSync(namespace)) {
362
- z.uuid().parse(priorId);
363
- const path = join(namespace, priorId);
364
- assertGateDirectory(path);
365
- const prior = OutputGateSchema.parse(JSON.parse(assertPrivateFile(join(path, 'gate.json')).toString('utf8')));
366
- if (prior.id !== priorId || prior.directory !== path || gateOwnerAlive(prior.owner))
367
- throw new DeliveryError('Prior filesystem observation gate is live or has conflicting ownership.');
368
- retireOutputGate(prior, true);
369
- }
370
- const directory = join(namespace, id);
371
- ensurePrivateDirectoryDurably(join(directory, 'requests'));
372
- const gate = { directory, id, owner: gateOwner() };
373
- writePrivateJsonFileAtomically(join(directory, 'gate.json'), gate);
374
- let operationCompleted = false;
375
- let operationFailure;
376
- try {
377
- const value = await operation(gate);
378
- operationCompleted = true;
379
- return value;
380
- }
381
- catch (error) {
382
- operationFailure = error;
383
- throw error;
384
- }
385
- finally {
386
- retireOutputGateAfterOperation(gate, operationCompleted, operationFailure);
387
- }
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);
388
209
  }
389
210
  class OutputObservationError extends DeliveryError {
390
- cause;
391
- code;
392
- constructor(message, path, cause) {
393
- const code = cause.code;
394
- super(`${message} Path ${JSON.stringify(path)} (${code ?? 'unknown errno'}): ${cause instanceof Error ? cause.message : String(cause)}`);
395
- this.code = code;
396
- this.cause = cause;
397
- }
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
+ }
398
221
  }
399
222
  function scanOutputRoots(roots, links, commandRunning = false, onMissingTarget) {
400
- const files = new Map();
401
- const observedLinks = new Map();
402
- const visit = (path) => {
403
- let metadata;
404
- try {
405
- metadata = lstatSync(path);
406
- }
407
- catch (error) {
408
- if (error.code === 'ENOENT')
409
- return;
410
- throw new OutputObservationError('Filesystem output lstat failed.', path, error);
411
- }
412
- if (metadata.isSymbolicLink()) {
413
- let link;
414
- try {
415
- link = readlinkSync(path);
416
- }
417
- catch (error) {
418
- throw new OutputObservationError('Filesystem output readlink failed.', path, error);
419
- }
420
- const identity = digestValue({
421
- device: metadata.dev,
422
- inode: metadata.ino,
423
- changed: metadata.ctimeMs,
424
- modified: metadata.mtimeMs,
425
- link,
426
- });
427
- let target;
428
- let missing = false;
429
- try {
430
- target = realpathSync(path);
431
- }
432
- catch (error) {
433
- const failure = new OutputObservationError('Filesystem output observation encountered a broken or cyclic symbolic link.', path, error);
434
- const previous = links.get(path);
435
- if (previous !== undefined && previous.identity !== identity)
436
- throw new DeliveryError(`Filesystem output alias identity changed. Path ${JSON.stringify(path)}.`);
437
- if (!commandRunning || failure.code !== 'ENOENT' || previous?.identity !== identity)
438
- throw failure;
439
- // A validated alias contributes no physical file bytes. Resolve the missing suffix through
440
- // its current existing ancestor, so an ancestor retarget cannot hide an escaping output.
441
- let lexical = resolve(dirname(path), link);
442
- let ancestor = lexical;
443
- const expanded = new Set([path]);
444
- for (;;) {
445
- try {
446
- target = join(realpathSync(ancestor), lexical.slice(ancestor.length));
447
- break;
448
- }
449
- catch (ancestorError) {
450
- if (ancestorError.code !== 'ENOENT' || dirname(ancestor) === ancestor)
451
- throw new OutputObservationError('Filesystem output ancestor resolution failed.', ancestor, ancestorError);
452
- let ancestorMetadata;
453
- try {
454
- ancestorMetadata = lstatSync(ancestor);
455
- }
456
- catch (metadataError) {
457
- if (metadataError.code !== 'ENOENT')
458
- throw new OutputObservationError('Filesystem output ancestor lstat failed.', ancestor, metadataError);
459
- }
460
- if (ancestorMetadata?.isSymbolicLink()) {
461
- let ancestorLink, currentAncestor;
462
- try {
463
- ancestorLink = readlinkSync(ancestor);
464
- currentAncestor = lstatSync(ancestor);
465
- }
466
- catch (aliasError) {
467
- throw new OutputObservationError('Filesystem output ancestor alias read failed.', ancestor, aliasError);
468
- }
469
- const ancestorIdentity = digestValue({
470
- device: ancestorMetadata.dev,
471
- inode: ancestorMetadata.ino,
472
- changed: ancestorMetadata.ctimeMs,
473
- modified: ancestorMetadata.mtimeMs,
474
- link: ancestorLink,
475
- });
476
- const previousAncestor = links.get(ancestor);
477
- if (previousAncestor === undefined)
478
- throw failure;
479
- if (expanded.has(ancestor) ||
480
- previousAncestor.identity !== ancestorIdentity ||
481
- !currentAncestor.isSymbolicLink() ||
482
- currentAncestor.dev !== ancestorMetadata.dev ||
483
- currentAncestor.ino !== ancestorMetadata.ino ||
484
- currentAncestor.ctimeMs !== ancestorMetadata.ctimeMs ||
485
- currentAncestor.mtimeMs !== ancestorMetadata.mtimeMs)
486
- throw new DeliveryError(`Filesystem output ancestor alias identity changed. Path ${JSON.stringify(ancestor)}.`);
487
- expanded.add(ancestor);
488
- lexical = join(resolve(dirname(ancestor), ancestorLink), lexical.slice(ancestor.length));
489
- ancestor = lexical;
490
- continue;
491
- }
492
- ancestor = dirname(ancestor);
493
- }
494
- }
495
- if (target !== previous.target)
496
- throw new DeliveryError(`Filesystem output alias target identity changed. Path ${JSON.stringify(path)}.`);
497
- missing = true;
498
- onMissingTarget?.(failure.message);
499
- }
500
- const previous = links.get(path);
501
- if (previous?.missing && (previous.identity !== identity || previous.target !== target))
502
- throw new DeliveryError(`Filesystem output alias identity changed after target absence. Path ${JSON.stringify(path)}.`);
503
- if (!roots.some((root) => target === root || target.startsWith(`${root}${sep}`))) {
504
- throw new DeliveryError(`Filesystem output observation encountered an escaping symbolic link. Path ${JSON.stringify(path)} resolves to ${JSON.stringify(target)}.`);
505
- }
506
- let current;
507
- try {
508
- current = lstatSync(path);
509
- }
510
- catch (error) {
511
- // A previously validated alias removed during this visit has no physical payload.
512
- // Continue the complete current scan, publishing no identity for the vanished alias.
513
- if (commandRunning && error.code === 'ENOENT' && previous?.identity === identity)
514
- return;
515
- throw new OutputObservationError('Filesystem output alias identity readback failed.', path, error);
516
- }
517
- if (!current.isSymbolicLink() ||
518
- current.dev !== metadata.dev ||
519
- current.ino !== metadata.ino ||
520
- current.ctimeMs !== metadata.ctimeMs ||
521
- current.mtimeMs !== metadata.mtimeMs)
522
- throw new DeliveryError(`Filesystem output alias identity changed during observation. Path ${JSON.stringify(path)}.`);
523
- observedLinks.set(path, { identity, target, missing });
524
- // Observe physical targets through their declared root only, never traverse aliases.
525
- return;
526
- }
527
- if (metadata.isDirectory()) {
528
- let names;
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;
529
276
  try {
530
- names = readdirSync(path);
277
+ ancestorMetadata = lstatSync(ancestor);
278
+ } catch (metadataError) {
279
+ if (metadataError.code !== "ENOENT")
280
+ throw new OutputObservationError("Filesystem output ancestor lstat failed.", ancestor, metadataError);
531
281
  }
532
- catch (error) {
533
- if (error.code === 'ENOENT')
534
- return;
535
- throw new OutputObservationError('Filesystem output readdir failed.', path, error);
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;
536
307
  }
537
- for (const name of names)
538
- visit(join(path, name));
539
- return;
308
+ ancestor = dirname(ancestor);
309
+ }
540
310
  }
541
- if ((!metadata.isFile() && !metadata.isSocket()) || !Number.isSafeInteger(metadata.size)) {
542
- throw new DeliveryError(`Filesystem output observation encountered an unsupported file. Path ${JSON.stringify(path)}.`);
543
- }
544
- // Unix IPC endpoints store no regular-file payload, but still count toward the scan's entry limit.
545
- files.set(path, metadata.isSocket() ? 0 : metadata.size);
546
- if (files.size > 1_000_000)
547
- throw new DeliveryError('Filesystem output observation exceeded its file limit.');
548
- };
549
- for (const root of roots) {
550
- if (existsSync(root) && realpathSync(root) !== root)
551
- throw new DeliveryError('Filesystem output roots must not be symbolic links.');
552
- visit(root);
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
+ );
553
356
  }
554
- // Publish alias identities only with the complete physical-file scan that validated them.
555
- links.clear();
556
- for (const [path, link] of observedLinks)
557
- links.set(path, link);
558
- return files;
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;
559
368
  }
560
369
  async function positiveNewOutputBytes(baseline, signal, commandRunning = false, onUnavailable) {
561
- let files;
562
- let firstFailure;
563
- let lastFailure;
564
- let firstFailureAt;
565
- const assertObservationWindow = () => {
566
- if (firstFailureAt !== undefined && Date.now() - firstFailureAt >= 1_000) {
567
- throw new DeliveryError(`Filesystem output observation remained unavailable for 1 second. First observation: ${firstFailure.message} Last observation: ${lastFailure.message}`);
568
- }
569
- };
570
- for (;;) {
571
- if (signal?.aborted)
572
- throw new DeliveryError('Filesystem output observation cancelled.');
573
- assertObservationWindow();
574
- try {
575
- files = await withOutputGateLock(baseline.gate, 'scan', () => scanOutputRoots(baseline.roots, baseline.links, commandRunning, onUnavailable), signal);
576
- assertObservationWindow();
577
- break;
578
- }
579
- catch (error) {
580
- // Unvalidated aliases still prevent a complete scan. Retry only during a command,
581
- // with the stall window starting at the first failed scan, not before that scan.
582
- if (!commandRunning || !(error instanceof OutputObservationError) || error.code !== 'ENOENT')
583
- throw error;
584
- lastFailure = error;
585
- if (firstFailure === undefined) {
586
- firstFailureAt = Date.now();
587
- firstFailure = error;
588
- onUnavailable?.(error.message);
589
- }
590
- assertObservationWindow();
591
- await new Promise((resolve) => setTimeout(resolve, 25));
592
- }
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
+ );
593
379
  }
594
- let bytes = 0;
595
- for (const [path, size] of files) {
596
- bytes += Math.max(0, size - (baseline.files.get(path) ?? 0));
597
- if (!Number.isSafeInteger(bytes))
598
- throw new DeliveryError('Filesystem output observation overflowed.');
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));
599
403
  }
600
- return bytes;
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;
601
411
  }
602
412
  function availableDiskBytes(path) {
603
- let existing = path;
604
- for (;;) {
605
- try {
606
- const disk = statfsSync(existing, { bigint: true });
607
- return disk.bavail * disk.bsize;
608
- }
609
- catch (error) {
610
- if (error.code !== 'ENOENT' || dirname(existing) === existing)
611
- throw error;
612
- existing = dirname(existing);
613
- }
413
+ let existing = path;
414
+ for (; ; ) {
415
+ try {
416
+ const disk = statfsSync(existing, { bigint: true });
417
+ return disk.bavail * disk.bsize;
418
+ } catch (error) {
419
+ if (error.code !== "ENOENT" || dirname(existing) === existing) throw error;
420
+ existing = dirname(existing);
614
421
  }
422
+ }
615
423
  }
616
424
  function freeDiskBytes(repoRoot, baseline) {
617
- const roots = baseline === undefined ? [repoRoot] : [repoRoot, ...baseline.roots];
618
- const minimum = roots.reduce((value, path) => {
619
- const available = availableDiskBytes(path);
620
- return available < value ? available : value;
621
- }, BigInt(Number.MAX_SAFE_INTEGER));
622
- if (minimum > BigInt(Number.MAX_SAFE_INTEGER))
623
- throw new DeliveryError('Free disk observation overflowed.');
624
- return Number(minimum);
625
- }
626
- function assertDiskHeadroom(repoRoot, bounds, baseline) {
627
- if (freeDiskBytes(repoRoot, baseline) < bounds.minFreeDiskBytes) {
628
- throw new DeliveryError(`Free disk fell below limit ${bounds.minFreeDiskBytes}.`);
629
- }
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);
630
432
  }
631
433
  class ProcessSnapshotError extends DeliveryError {
632
434
  }
633
- export function processSnapshot() {
634
- const psPath = existsSync('/usr/bin/ps') ? '/usr/bin/ps' : '/bin/ps';
635
- const started = performance.now();
636
- const result = spawnSync(psPath, ['-A', '-o', 'pid=,ppid=,pgid=,rss=,stat=,lstart='], {
637
- encoding: 'utf8',
638
- env: { ...process.env, LC_ALL: 'C' },
639
- maxBuffer: 4 * 1024 * 1024,
640
- timeout: 1_000,
641
- });
642
- if (result.status !== 0 || result.error || result.signal || !result.stdout.endsWith('\n')) {
643
- const elapsedMs = Math.round(performance.now() - started);
644
- const stdout = typeof result.stdout === 'string' ? result.stdout : '';
645
- let completeLines = 0;
646
- for (let index = 0; index < stdout.length; index++)
647
- if (stdout.charCodeAt(index) === 10)
648
- completeLines++;
649
- const code = result.error?.code;
650
- const signal = result.signal;
651
- // Only fixed labels, bounded numbers and completeness flags leave this observation.
652
- const metadata = {
653
- status: Number.isSafeInteger(result.status) ? result.status : null,
654
- errorCode: code === undefined
655
- ? null
656
- : ['EACCES', 'EPERM', 'ETIMEDOUT', 'ENOENT', 'ENOBUFS', 'EAGAIN', 'ENOMEM', 'EIO', 'EINVAL'].includes(code)
657
- ? code
658
- : 'other',
659
- signal: signal === null
660
- ? null
661
- : ['SIGTERM', 'SIGKILL', 'SIGINT', 'SIGABRT', 'SIGSEGV', 'SIGBUS', 'SIGHUP', 'SIGQUIT', 'SIGPIPE'].includes(signal)
662
- ? signal
663
- : 'other',
664
- stdoutPresent: typeof result.stdout === 'string',
665
- stdoutTerminated: typeof result.stdout === 'string' && result.stdout.endsWith('\n'),
666
- elapsedMs,
667
- stdoutBytes: Buffer.byteLength(stdout),
668
- completeLines,
669
- };
670
- throw new ProcessSnapshotError(`Owned process resource observation failed. ${JSON.stringify(metadata)}`);
671
- }
672
- const snapshot = new Map();
673
- for (const line of result.stdout.trim().split('\n')) {
674
- const match = /^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/u.exec(line.trim());
675
- if (!match)
676
- throw new DeliveryError('Owned process resource observation is ambiguous.');
677
- const observed = {
678
- pid: Number(match[1]),
679
- ppid: Number(match[2]),
680
- pgid: Number(match[3]),
681
- rssBytes: Number(match[4]) * 1_024,
682
- status: match[5],
683
- identity: match[6],
684
- };
685
- if (!Number.isSafeInteger(observed.pid) ||
686
- observed.pid <= 0 ||
687
- !Number.isSafeInteger(observed.ppid) ||
688
- !Number.isSafeInteger(observed.pgid) ||
689
- !Number.isSafeInteger(observed.rssBytes) ||
690
- snapshot.has(observed.pid))
691
- throw new DeliveryError('Owned process resource observation is ambiguous.');
692
- snapshot.set(observed.pid, observed);
693
- }
694
- return snapshot;
435
+ function processSnapshot() {
436
+ const psPath = existsSync("/usr/bin/ps") ? "/usr/bin/ps" : "/bin/ps";
437
+ const started = performance.now();
438
+ const result = spawnSync(psPath, ["-A", "-o", "pid=,ppid=,pgid=,rss=,stat=,lstart="], {
439
+ encoding: "utf8",
440
+ // The absolute observer needs no author tokens, App keys or preload selectors.
441
+ env: { LC_ALL: "C" },
442
+ maxBuffer: 4 * 1024 * 1024,
443
+ timeout: 1e3
444
+ });
445
+ if (result.status !== 0 || result.error || result.signal || !result.stdout.endsWith("\n")) {
446
+ const elapsedMs = Math.round(performance.now() - started);
447
+ const stdout = typeof result.stdout === "string" ? result.stdout : "";
448
+ let completeLines = 0;
449
+ for (let index = 0; index < stdout.length; index++) if (stdout.charCodeAt(index) === 10) completeLines++;
450
+ const code = result.error?.code;
451
+ const signal = result.signal;
452
+ const metadata = {
453
+ status: Number.isSafeInteger(result.status) ? result.status : null,
454
+ errorCode: code === void 0 ? null : ["EACCES", "EPERM", "ETIMEDOUT", "ENOENT", "ENOBUFS", "EAGAIN", "ENOMEM", "EIO", "EINVAL"].includes(code) ? code : "other",
455
+ signal: signal === null ? null : ["SIGTERM", "SIGKILL", "SIGINT", "SIGABRT", "SIGSEGV", "SIGBUS", "SIGHUP", "SIGQUIT", "SIGPIPE"].includes(
456
+ signal
457
+ ) ? signal : "other",
458
+ stdoutPresent: typeof result.stdout === "string",
459
+ stdoutTerminated: typeof result.stdout === "string" && result.stdout.endsWith("\n"),
460
+ elapsedMs,
461
+ stdoutBytes: Buffer.byteLength(stdout),
462
+ completeLines
463
+ };
464
+ throw new ProcessSnapshotError(`Owned process resource observation failed. ${JSON.stringify(metadata)}`);
465
+ }
466
+ const snapshot = /* @__PURE__ */ new Map();
467
+ for (const line of result.stdout.trim().split("\n")) {
468
+ const match = /^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/u.exec(line.trim());
469
+ if (!match) throw new DeliveryError("Owned process resource observation is ambiguous.");
470
+ const observed = {
471
+ pid: Number(match[1]),
472
+ ppid: Number(match[2]),
473
+ pgid: Number(match[3]),
474
+ rssBytes: Number(match[4]) * 1024,
475
+ status: match[5],
476
+ identity: match[6]
477
+ };
478
+ if (!Number.isSafeInteger(observed.pid) || observed.pid <= 0 || !Number.isSafeInteger(observed.ppid) || !Number.isSafeInteger(observed.pgid) || !Number.isSafeInteger(observed.rssBytes) || snapshot.has(observed.pid))
479
+ throw new DeliveryError("Owned process resource observation is ambiguous.");
480
+ snapshot.set(observed.pid, observed);
481
+ }
482
+ return snapshot;
695
483
  }
696
484
  function observeOwnedProcesses(state, snapshot) {
697
- const root = snapshot.get(state.rootPid);
698
- if (state.rootIdentity === undefined) {
699
- if (root === undefined || root.status.startsWith('Z') || root.pgid !== state.rootPid) {
700
- throw new DeliveryError('Owned process identity could not be established before the command exited.');
701
- }
702
- state.rootIdentity = root.identity;
703
- state.tracked.set(root.pid, root);
704
- }
705
- else if (root !== undefined && root.identity !== state.rootIdentity) {
706
- throw new DeliveryError('Owned process identity changed during verification.');
485
+ const root = snapshot.get(state.rootPid);
486
+ if (state.rootIdentity === void 0) {
487
+ if (root === void 0 || root.status.startsWith("Z") || root.pgid !== state.rootPid) {
488
+ throw new DeliveryError("Owned process identity could not be established before the command exited.");
707
489
  }
708
- const selected = new Map();
709
- for (const [pid, previous] of state.tracked) {
710
- const current = snapshot.get(pid);
711
- if (current === undefined || current.status.startsWith('Z'))
712
- state.tracked.delete(pid);
713
- else if (current.identity !== previous.identity) {
714
- throw new DeliveryError('Tracked process identity changed during verification.');
715
- }
716
- else
717
- selected.set(pid, current);
490
+ state.rootIdentity = root.identity;
491
+ state.tracked.set(root.pid, root);
492
+ } else if (root !== void 0 && root.identity !== state.rootIdentity) {
493
+ throw new DeliveryError("Owned process identity changed during verification.");
494
+ }
495
+ const selected = /* @__PURE__ */ new Map();
496
+ for (const [pid, previous] of state.tracked) {
497
+ const current = snapshot.get(pid);
498
+ if (current === void 0 || current.status.startsWith("Z")) state.tracked.delete(pid);
499
+ else if (current.identity !== previous.identity) {
500
+ throw new DeliveryError("Tracked process identity changed during verification.");
501
+ } else selected.set(pid, current);
502
+ }
503
+ for (const member of snapshot.values()) {
504
+ if (!member.status.startsWith("Z") && member.pgid === state.rootPid) selected.set(member.pid, member);
505
+ }
506
+ const children = /* @__PURE__ */ new Map();
507
+ for (const member of snapshot.values()) {
508
+ const siblings = children.get(member.ppid) ?? [];
509
+ siblings.push(member);
510
+ children.set(member.ppid, siblings);
511
+ }
512
+ const pending = [...selected.values()];
513
+ for (const parent of pending)
514
+ for (const child of children.get(parent.pid) ?? []) {
515
+ if (!child.status.startsWith("Z") && !selected.has(child.pid)) {
516
+ selected.set(child.pid, child);
517
+ pending.push(child);
518
+ }
718
519
  }
719
- for (const member of snapshot.values()) {
720
- if (!member.status.startsWith('Z') && member.pgid === state.rootPid)
721
- selected.set(member.pid, member);
722
- }
723
- const children = new Map();
724
- for (const member of snapshot.values()) {
725
- const siblings = children.get(member.ppid) ?? [];
726
- siblings.push(member);
727
- children.set(member.ppid, siblings);
728
- }
729
- const pending = [...selected.values()];
730
- for (const parent of pending)
731
- for (const child of children.get(parent.pid) ?? []) {
732
- if (!child.status.startsWith('Z') && !selected.has(child.pid)) {
733
- selected.set(child.pid, child);
734
- pending.push(child);
735
- }
736
- }
737
- for (const member of selected.values())
738
- state.tracked.set(member.pid, member);
739
- state.sampled = true;
740
- return [...selected.values()];
520
+ for (const member of selected.values()) state.tracked.set(member.pid, member);
521
+ state.sampled = true;
522
+ return [...selected.values()];
741
523
  }
742
524
  function sampleOwnedTree(state, repoRoot, bounds, baseline, newOutputBytes, controllerRssBytes = 0, includeControllerTree = false) {
743
- const snapshot = processSnapshot();
744
- const owned = observeOwnedProcesses(state, snapshot);
745
- const controller = includeControllerTree
746
- ? controllerTreeRssBytes(snapshot, new Set(owned.map((member) => member.pid)))
747
- : controllerRssBytes;
748
- const rssBytes = owned.reduce((total, member) => total + member.rssBytes, controller);
749
- if (!Number.isSafeInteger(rssBytes))
750
- throw new DeliveryError('Owned aggregate RSS is outside the safe integer range.');
751
- if (rssBytes > bounds.maxAggregateRssBytes) {
752
- throw new DeliveryError(`Owned aggregate RSS ${rssBytes} exceeded limit ${bounds.maxAggregateRssBytes}.`);
753
- }
754
- const available = freeDiskBytes(repoRoot, baseline);
755
- if (available < bounds.minFreeDiskBytes)
756
- throw new DeliveryError(`Free disk fell below limit ${bounds.minFreeDiskBytes}.`);
757
- if (newOutputBytes !== undefined && !Number.isSafeInteger(newOutputBytes)) {
758
- throw new DeliveryError('Filesystem output observation overflowed.');
759
- }
760
- if (baseline !== undefined && bounds.maxNewOutputBytes !== undefined) {
761
- if (newOutputBytes !== undefined && newOutputBytes > bounds.maxNewOutputBytes) {
762
- throw new DeliveryError(`Positive new filesystem output ${newOutputBytes} exceeded limit ${bounds.maxNewOutputBytes}.`);
763
- }
525
+ const snapshot = processSnapshot();
526
+ const owned = observeOwnedProcesses(state, snapshot);
527
+ const controller = includeControllerTree ? controllerTreeRssBytes(snapshot, new Set(owned.map((member) => member.pid))) : controllerRssBytes;
528
+ const rssBytes = owned.reduce((total, member) => total + member.rssBytes, controller);
529
+ if (!Number.isSafeInteger(rssBytes))
530
+ throw new DeliveryError("Owned aggregate RSS is outside the safe integer range.");
531
+ if (rssBytes > bounds.maxAggregateRssBytes) {
532
+ throw new DeliveryError(`Owned aggregate RSS ${rssBytes} exceeded limit ${bounds.maxAggregateRssBytes}.`);
533
+ }
534
+ const available = freeDiskBytes(repoRoot, baseline);
535
+ if (available < bounds.minFreeDiskBytes)
536
+ 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
+ );
764
545
  }
765
- return {
766
- aggregateRssBytes: rssBytes,
767
- freeDiskBytes: available,
768
- ...(newOutputBytes === undefined ? {} : { newOutputBytes }),
769
- ownedProcessCount: owned.length,
770
- };
546
+ }
547
+ return {
548
+ aggregateRssBytes: rssBytes,
549
+ freeDiskBytes: available,
550
+ ...newOutputBytes === void 0 ? {} : { newOutputBytes },
551
+ ownedProcessCount: owned.length
552
+ };
771
553
  }
772
- /** Accounting includes the caller's tree; containment remains restricted to the recorded command. */
773
- function controllerTreeRssBytes(snapshot = processSnapshot(), excluded = new Set()) {
774
- const controller = snapshot.get(process.pid);
775
- if (controller === undefined || controller.status.startsWith('Z'))
776
- throw new DeliveryError('Runtime setup controller resource observation is unavailable.');
777
- const selected = new Set([process.pid]);
778
- let bytes = process.memoryUsage().rss;
779
- for (const pid of selected)
780
- for (const member of snapshot.values())
781
- if (member.ppid === pid && !member.status.startsWith('Z') && !selected.has(member.pid)) {
782
- selected.add(member.pid);
783
- if (!excluded.has(member.pid))
784
- bytes += member.rssBytes;
785
- }
786
- if (!Number.isSafeInteger(bytes))
787
- throw new DeliveryError('Controller aggregate RSS observation overflowed.');
788
- return bytes;
554
+ function controllerTreeRssBytes(snapshot = processSnapshot(), excluded = /* @__PURE__ */ new Set()) {
555
+ const controller = snapshot.get(process.pid);
556
+ if (controller === void 0 || controller.status.startsWith("Z"))
557
+ throw new DeliveryError("Runtime setup controller resource observation is unavailable.");
558
+ const selected = /* @__PURE__ */ new Set([process.pid]);
559
+ let bytes = process.memoryUsage().rss;
560
+ for (const pid of selected)
561
+ for (const member of snapshot.values())
562
+ if (member.ppid === pid && !member.status.startsWith("Z") && !selected.has(member.pid)) {
563
+ selected.add(member.pid);
564
+ if (!excluded.has(member.pid)) bytes += member.rssBytes;
565
+ }
566
+ if (!Number.isSafeInteger(bytes)) throw new DeliveryError("Controller aggregate RSS observation overflowed.");
567
+ return bytes;
789
568
  }
790
- export async function confirmOwnedCleanup(state) {
791
- if (!state.sampled || state.rootIdentity === undefined) {
792
- throw new DeliveryError('Owned process cleanup cannot be verified without a root identity.');
793
- }
794
- const deadline = Date.now() + 2_000;
795
- for (;;) {
796
- const snapshot = processSnapshot();
797
- const root = snapshot.get(state.rootPid);
798
- if (root !== undefined && root.identity !== state.rootIdentity) {
799
- throw new DeliveryError('Owned process group identity changed before cleanup readback.');
800
- }
801
- const groupAlive = [...snapshot.values()].some((member) => member.pgid === state.rootPid && !member.status.startsWith('Z'));
802
- const trackedAlive = [...state.tracked.values()].some((previous) => {
803
- const current = snapshot.get(previous.pid);
804
- if (current === undefined || current.status.startsWith('Z'))
805
- return false;
806
- if (current.identity !== previous.identity)
807
- throw new DeliveryError('Tracked process identity changed before cleanup readback.');
808
- return true;
809
- });
810
- if (!groupAlive && !trackedAlive)
811
- return;
812
- if (Date.now() >= deadline)
813
- throw new DeliveryError('Owned process cleanup did not release every sampled process.');
814
- await new Promise((resolve) => setTimeout(resolve, 100));
815
- }
816
- }
817
- /** Signal only birth identities established by this command, including observed detached children. */
818
- export function terminateOwnedProcesses(state) {
819
- if (!state.sampled || state.rootIdentity === undefined)
820
- throw new DeliveryError('Owned process identity is unknown.');
569
+ async function confirmOwnedCleanup(state) {
570
+ if (!state.sampled || state.rootIdentity === void 0) {
571
+ throw new DeliveryError("Owned process cleanup cannot be verified without a root identity.");
572
+ }
573
+ const deadline = Date.now() + 2e3;
574
+ for (; ; ) {
821
575
  const snapshot = processSnapshot();
822
576
  const root = snapshot.get(state.rootPid);
823
- if (root !== undefined && root.identity !== state.rootIdentity)
824
- throw new DeliveryError('Owned process group identity changed before cleanup.');
825
- const alive = [...state.tracked.values()].flatMap((previous) => {
826
- const current = snapshot.get(previous.pid);
827
- if (current === undefined || current.status.startsWith('Z'))
828
- return [];
829
- if (current.identity !== previous.identity)
830
- throw new DeliveryError('Tracked process identity changed before cleanup.');
831
- return [current];
577
+ if (root !== void 0 && root.identity !== state.rootIdentity) {
578
+ throw new DeliveryError("Owned process group identity changed before cleanup readback.");
579
+ }
580
+ const groupAlive = [...snapshot.values()].some(
581
+ (member) => member.pgid === state.rootPid && !member.status.startsWith("Z")
582
+ );
583
+ const trackedAlive = [...state.tracked.values()].some((previous) => {
584
+ const current = snapshot.get(previous.pid);
585
+ if (current === void 0 || current.status.startsWith("Z")) return false;
586
+ if (current.identity !== previous.identity)
587
+ throw new DeliveryError("Tracked process identity changed before cleanup readback.");
588
+ return true;
832
589
  });
833
- const group = [...snapshot.values()].filter((member) => member.pgid === state.rootPid && !member.status.startsWith('Z'));
834
- if (group.length > 0 && !alive.some((member) => member.pgid === state.rootPid))
835
- throw new DeliveryError('Owned process group has no surviving recorded identity; cleanup is ambiguous.');
836
- const signal = (pid) => {
590
+ if (!groupAlive && !trackedAlive) return;
591
+ if (Date.now() >= deadline) throw new DeliveryError("Owned process cleanup did not release every sampled process.");
592
+ await new Promise((resolve2) => setTimeout(resolve2, 100));
593
+ }
594
+ }
595
+ function terminateOwnedProcesses(state) {
596
+ if (!state.sampled || state.rootIdentity === void 0) throw new DeliveryError("Owned process identity is unknown.");
597
+ const snapshot = processSnapshot();
598
+ const root = snapshot.get(state.rootPid);
599
+ if (root !== void 0 && root.identity !== state.rootIdentity)
600
+ throw new DeliveryError("Owned process group identity changed before cleanup.");
601
+ const alive = [...state.tracked.values()].flatMap((previous) => {
602
+ const current = snapshot.get(previous.pid);
603
+ if (current === void 0 || current.status.startsWith("Z")) return [];
604
+ if (current.identity !== previous.identity)
605
+ throw new DeliveryError("Tracked process identity changed before cleanup.");
606
+ return [current];
607
+ });
608
+ const group = [...snapshot.values()].filter(
609
+ (member) => member.pgid === state.rootPid && !member.status.startsWith("Z")
610
+ );
611
+ if (group.length > 0 && !alive.some((member) => member.pgid === state.rootPid))
612
+ throw new DeliveryError("Owned process group has no surviving recorded identity; cleanup is ambiguous.");
613
+ const signal = (pid) => {
614
+ try {
615
+ process.kill(pid, "SIGKILL");
616
+ } catch (error) {
617
+ const code = error.code;
618
+ if (code === "ESRCH") return;
619
+ if (code !== "EPERM") throw error;
620
+ const readback = processSnapshot();
621
+ if (pid < 0) {
622
+ const currentRoot = readback.get(state.rootPid);
623
+ if (currentRoot !== void 0 && currentRoot.identity !== state.rootIdentity)
624
+ throw new DeliveryError("Owned process group identity changed during cleanup signal readback.");
625
+ if ([...readback.values()].some((member) => member.pgid === state.rootPid && !member.status.startsWith("Z")))
626
+ throw error;
627
+ } else {
628
+ const current = readback.get(pid);
629
+ if (current !== void 0 && current.identity !== state.tracked.get(pid)?.identity)
630
+ throw new DeliveryError("Tracked process identity changed during cleanup signal readback.");
631
+ if (current !== void 0 && !current.status.startsWith("Z")) throw error;
632
+ }
633
+ }
634
+ };
635
+ if (group.length > 0) signal(-state.rootPid);
636
+ for (const member of alive.reverse()) signal(member.pid);
637
+ }
638
+ function producerContent(root) {
639
+ const code = [];
640
+ const collect = (directory) => {
641
+ for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
642
+ const path = join(directory, entry.name);
643
+ if (entry.isDirectory()) collect(path);
644
+ else if (entry.isFile() && entry.name.endsWith(".js") && !entry.name.endsWith(".test.js"))
645
+ code.push({ path: path.slice(root.length + 1), digest: digestBytes(readFileSync(path)) });
646
+ }
647
+ };
648
+ collect(root);
649
+ const dependencies = /* @__PURE__ */ new Map();
650
+ const collectDependencies = (manifestPath) => {
651
+ if (dependencies.has(manifestPath)) return;
652
+ const bytes = readFileSync(manifestPath);
653
+ const manifest = z.object({ dependencies: z.record(z.string(), z.string()).optional() }).parse(JSON.parse(bytes.toString("utf8")));
654
+ dependencies.set(manifestPath, digestBytes(bytes));
655
+ const require2 = createRequire(manifestPath);
656
+ for (const name of Object.keys(manifest.dependencies ?? {}).sort()) {
657
+ let resolved;
658
+ try {
659
+ resolved = require2.resolve(`${name}/package.json`);
660
+ } catch {
837
661
  try {
838
- process.kill(pid, 'SIGKILL');
662
+ resolved = require2.resolve(name);
663
+ } catch (error) {
664
+ if (!types.isNativeError(error) || Reflect.get(error, "code") !== "ERR_PACKAGE_PATH_NOT_EXPORTED")
665
+ throw error;
666
+ const manifest2 = findPackageJSON(name, manifestPath);
667
+ if (!manifest2) throw error;
668
+ resolved = manifest2;
839
669
  }
840
- catch (error) {
841
- const code = error.code;
842
- if (code === 'ESRCH')
843
- return;
844
- if (code !== 'EPERM')
845
- throw error;
846
- // macOS can return EPERM when the last group member exits after our snapshot.
847
- // Accept only fresh absence/zombie proof; a live target remains a cleanup failure.
848
- const readback = processSnapshot();
849
- if (pid < 0) {
850
- const currentRoot = readback.get(state.rootPid);
851
- if (currentRoot !== undefined && currentRoot.identity !== state.rootIdentity)
852
- throw new DeliveryError('Owned process group identity changed during cleanup signal readback.');
853
- if ([...readback.values()].some((member) => member.pgid === state.rootPid && !member.status.startsWith('Z')))
854
- throw error;
855
- }
856
- else {
857
- const current = readback.get(pid);
858
- if (current !== undefined && current.identity !== state.tracked.get(pid)?.identity)
859
- throw new DeliveryError('Tracked process identity changed during cleanup signal readback.');
860
- if (current !== undefined && !current.status.startsWith('Z'))
861
- throw error;
862
- }
670
+ }
671
+ let directory = dirname(resolved);
672
+ for (; ; ) {
673
+ const path = join(directory, "package.json");
674
+ if (existsSync(path)) {
675
+ const candidate = z.object({ name: z.string().optional() }).parse(JSON.parse(readFileSync(path, "utf8")));
676
+ if (candidate.name === name) {
677
+ collectDependencies(path);
678
+ break;
679
+ }
863
680
  }
864
- };
865
- if (group.length > 0)
866
- signal(-state.rootPid);
867
- for (const member of alive.reverse())
868
- signal(member.pid);
869
- }
870
- const ProcessIdentitySchema = z.strictObject({ pid: z.number().int().positive(), identity: z.string().min(1) });
871
- const WriterStateSchema = z
872
- .strictObject({
873
- schemaVersion: z.literal('ai-delivery.verification-writer@1'),
874
- writerId: z.uuid(),
875
- worktreeDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
876
- owner: ProcessIdentitySchema,
877
- command: z.union([
878
- z.strictObject({ phase: z.literal('idle') }),
879
- z.strictObject({ phase: z.literal('starting') }),
880
- z.strictObject({
881
- phase: z.literal('running'),
882
- root: ProcessIdentitySchema,
883
- tracked: z.array(z.strictObject({ ...ProcessIdentitySchema.shape, pgid: z.number().int().positive() })),
884
- }),
885
- ]),
886
- stateId: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
887
- })
888
- .superRefine((state, ctx) => {
889
- const { stateId, ...content } = state;
890
- if (stateId !== digestValue(content))
891
- ctx.addIssue({ code: 'custom', message: 'Writer state is corrupt.' });
892
- });
893
- /** @internal Read-only closure check shared by inspection and the locked transition lease. */
894
- export function assertWorktreeTransitionWriterQuiescent(worktreePath, bytes) {
895
- if (bytes === undefined)
896
- return;
897
- const previous = WriterStateSchema.parse(JSON.parse(bytes.toString('utf8')));
898
- if (previous.worktreeDigest !== worktreeDigest(worktreePath))
899
- throw new DeliveryError('Verification writer belongs to another worktree.');
900
- const snapshot = processSnapshot();
901
- const owner = snapshot.get(previous.owner.pid);
902
- if (owner?.identity === previous.owner.identity && !owner.status.startsWith('Z'))
903
- throw new DeliveryError('A live verification writer still owns this worktree.');
904
- if (previous.command.phase === 'starting')
905
- throw new DeliveryError('Interrupted writer has unknown command ownership; reconcile before retrying.');
906
- if (previous.command.phase === 'running') {
907
- const identities = [previous.command.root, ...previous.command.tracked];
908
- const groups = new Set([previous.command.root.pid, ...previous.command.tracked.map((member) => member.pgid)]);
909
- if (identities.some((member) => snapshot.has(member.pid)) ||
910
- [...snapshot.values()].some((member) => groups.has(member.pgid)))
911
- throw new DeliveryError('Transition requires identity-bound command and process-group absence.');
681
+ const parent = dirname(directory);
682
+ if (parent === directory) throw new DeliveryError(`Producer dependency identity is unavailable for ${name}.`);
683
+ directory = parent;
684
+ }
912
685
  }
686
+ };
687
+ collectDependencies(join(dirname(root), "package.json"));
688
+ return { code, dependencies: [...dependencies].sort(([a], [b]) => a.localeCompare(b)) };
913
689
  }
914
- async function withVerificationWriter(root, operation, transition, commonDirectory, refuseUnresolvedSourcePhase = false) {
915
- const digest = worktreeDigest(root);
916
- const path = join(commonDirectory ?? gitCommonDir(root), 'ai-delivery', 'writers@1', `${digest.slice(7)}.json`);
917
- ensurePrivateDirectoryDurably(dirname(path));
918
- return withLock(path, {
919
- projectRoot: root,
920
- timeout: 200,
921
- ...(transition?.onLockReleaseError === undefined ? {} : { onReleaseError: transition.onLockReleaseError }),
922
- ...(transition?.onLockCompromised === undefined ? {} : { onCompromised: transition.onLockCompromised }),
923
- operation: async () => {
924
- await assertNoUnsealedSourcePhase(commonDirectory ?? gitCommonDir(root), digest, refuseUnresolvedSourcePhase);
925
- const snapshot = processSnapshot();
926
- const owner = snapshot.get(process.pid);
927
- if (owner === undefined || owner.status.startsWith('Z'))
928
- throw new DeliveryError('Verification writer identity is unknown.');
929
- let previousBytes;
930
- if (transition) {
931
- try {
932
- lstatSync(path);
933
- previousBytes = assertPrivateFile(path);
934
- }
935
- catch (error) {
936
- if (error.code !== 'ENOENT')
937
- throw error;
938
- }
939
- }
940
- else if (existsSync(path))
941
- previousBytes = assertPrivateFile(path);
942
- if (transition)
943
- assertWorktreeTransitionWriterQuiescent(root, previousBytes);
944
- if (previousBytes !== undefined && !transition) {
945
- const previous = WriterStateSchema.parse(JSON.parse(previousBytes.toString('utf8')));
946
- if (previous.worktreeDigest !== digest)
947
- throw new DeliveryError('Verification writer belongs to another worktree.');
948
- const priorOwner = snapshot.get(previous.owner.pid);
949
- if (priorOwner?.identity === previous.owner.identity && !priorOwner.status.startsWith('Z'))
950
- throw new DeliveryError('A live verification writer still owns this worktree.');
951
- if (previous.command.phase === 'starting')
952
- throw new DeliveryError('Interrupted writer has unknown command ownership; reconcile before retrying.');
953
- if (previous.command.phase === 'running') {
954
- const state = {
955
- rootPid: previous.command.root.pid,
956
- rootIdentity: previous.command.root.identity,
957
- sampled: true,
958
- tracked: new Map(previous.command.tracked.map((member) => [member.pid, { ...member, ppid: 0, rssBytes: 0, status: '' }])),
959
- };
960
- terminateOwnedProcesses(state);
961
- await confirmOwnedCleanup(state);
962
- reportVerificationProgress({
963
- state: 'recovered',
964
- stageId: 'writer',
965
- completedStages: 0,
966
- reusedStages: 0,
967
- remainingStages: 0,
968
- elapsedMs: 0,
969
- reason: 'Recorded interrupted command cleanup confirmed; compatible completed stages remain available.',
970
- });
971
- }
972
- }
973
- if (transition) {
974
- await transition.beforeClaim({
975
- previousBytes: previousBytes === undefined ? undefined : Buffer.from(previousBytes),
976
- owner: { pid: owner.pid, identity: owner.identity },
977
- });
978
- }
979
- let state = {
980
- schemaVersion: 'ai-delivery.verification-writer@1',
981
- writerId: transition?.writerId ?? randomUUID(),
982
- worktreeDigest: digest,
983
- owner: { pid: owner.pid, identity: owner.identity },
984
- command: { phase: 'idle' },
985
- };
986
- const persist = (command) => {
987
- state = { ...state, command };
988
- writePrivateJsonFileAtomically(path, { ...state, stateId: digestValue(state) });
989
- };
990
- if (transition) {
991
- const bytes = Buffer.from(`${JSON.stringify({ ...state, stateId: digestValue(state) }, null, 2)}\n`);
992
- await transition.recordClaim(Buffer.from(bytes));
993
- let actual;
994
- try {
995
- lstatSync(path);
996
- actual = assertPrivateFile(path);
997
- }
998
- catch (error) {
999
- if (error.code !== 'ENOENT')
1000
- throw error;
1001
- }
1002
- if ((actual === undefined) !== (previousBytes === undefined) ||
1003
- (actual !== undefined && previousBytes !== undefined && !actual.equals(previousBytes)))
1004
- throw new DeliveryError('Writer changed after transition intent preservation.');
1005
- }
1006
- persist({ phase: 'idle' });
1007
- const writer = {
1008
- starting: () => persist({ phase: 'starting' }),
1009
- observed: (owned) => {
1010
- if (owned.rootIdentity === undefined)
1011
- throw new DeliveryError('Cannot persist an unknown command owner.');
1012
- persist({
1013
- phase: 'running',
1014
- root: { pid: owned.rootPid, identity: owned.rootIdentity },
1015
- tracked: [...owned.tracked.values()].map(({ pid, identity, pgid }) => ({ pid, identity, pgid })),
1016
- });
1017
- },
1018
- idle: () => persist({ phase: 'idle' }),
1019
- assertQuiescent: () => {
1020
- const current = WriterStateSchema.parse(JSON.parse(assertPrivateFile(path).toString('utf8')));
1021
- if (current.writerId !== state.writerId || current.command.phase !== 'idle')
1022
- throw new DeliveryError('Verification writer command quiescence is not confirmed.');
1023
- },
1024
- };
1025
- const releaseWriter = async () => {
1026
- const bytes = assertPrivateFile(path);
1027
- const current = WriterStateSchema.parse(JSON.parse(bytes.toString('utf8')));
1028
- if (current.writerId !== state.writerId)
1029
- throw new DeliveryError('Verification writer ownership changed.');
1030
- if (current.command.phase === 'idle') {
1031
- if (transition) {
1032
- await transition.recordRelease(Buffer.from(bytes));
1033
- if (!assertPrivateFile(path).equals(bytes))
1034
- throw new DeliveryError('Writer changed before recorded release.');
1035
- }
1036
- unlinkSync(path);
1037
- if (transition) {
1038
- const descriptor = openSync(dirname(path), 'r');
1039
- try {
1040
- fsyncSync(descriptor);
1041
- }
1042
- finally {
1043
- closeSync(descriptor);
1044
- }
1045
- try {
1046
- lstatSync(path);
1047
- }
1048
- catch (error) {
1049
- if (error.code !== 'ENOENT')
1050
- throw error;
1051
- await transition.afterRelease?.();
1052
- return;
1053
- }
1054
- throw new DeliveryError('Writer absence is not confirmed after recorded release.');
1055
- }
1056
- }
1057
- };
1058
- try {
1059
- await transition?.afterClaim?.(Buffer.from(assertPrivateFile(path)));
1060
- return await operation(writer);
1061
- }
1062
- finally {
1063
- await releaseWriter();
1064
- }
1065
- },
1066
- });
1067
- }
1068
- /** @internal Hold the existing writer lock while reading a sealed transition; never claim or recover its slot. */
1069
- export async function withWorktreeTransitionWriterAbsent(repoRoot, worktreePath, operation) {
1070
- const path = join(gitCommonDir(repoRoot), 'ai-delivery', 'writers@1', `${worktreeDigest(worktreePath).slice(7)}.json`);
1071
- return withLock(path, {
1072
- projectRoot: repoRoot,
1073
- timeout: 200,
1074
- operation: async () => {
1075
- await assertNoUnsealedSourcePhase(gitCommonDir(repoRoot), worktreeDigest(worktreePath));
1076
- try {
1077
- lstatSync(path);
1078
- }
1079
- catch (error) {
1080
- if (error.code !== 'ENOENT')
1081
- throw error;
1082
- return operation();
1083
- }
1084
- throw new DeliveryError('Sealed transition writer absence postcondition drifted.');
1085
- },
1086
- });
690
+ function producerDigest(root = dirname(fileURLToPath(import.meta.url))) {
691
+ return digestValue(producerContent(root));
1087
692
  }
1088
- /** @internal Check-only lease for the explicit transition owner; never recovers or signals old commands. */
1089
- export async function withWorktreeTransitionWriterLease(input, operation) {
1090
- z.uuid().parse(input.writerId);
1091
- const repository = gitRoot(input.repoRoot);
1092
- const subject = input.worktreePath === undefined ? repository : resolve(input.worktreePath);
1093
- return withVerificationWriter(subject, async (writer) => {
1094
- writer.assertQuiescent();
1095
- const result = await operation();
1096
- writer.assertQuiescent();
1097
- return result;
1098
- }, input, gitCommonDir(repository));
693
+ function retainedWorktreeTransitionProducerDigest(distDirectory) {
694
+ return producerDigest(realpathSync(distDirectory));
1099
695
  }
1100
- function worktreeDigest(root) {
1101
- return digestValue(resolve(root));
696
+ function retainedWorktreeTransitionDependencyManifests(distDirectory) {
697
+ return producerContent(realpathSync(distDirectory)).dependencies.map(([source, digest]) => ({ source, digest }));
1102
698
  }
1103
- function producerContent(root) {
1104
- const code = [];
1105
- const collect = (directory) => {
1106
- for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
1107
- const path = join(directory, entry.name);
1108
- if (entry.isDirectory())
1109
- collect(path);
1110
- else if (entry.isFile() && entry.name.endsWith('.js') && !entry.name.endsWith('.test.js'))
1111
- code.push({ path: path.slice(root.length + 1), digest: digestBytes(readFileSync(path)) });
699
+ function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds, baseline, onResourceSample, writer, execution) {
700
+ const [executable, ...args] = argv;
701
+ if (!executable) throw new DeliveryError("Policy selected an empty stage command.");
702
+ if (abortSignal?.aborted) throw new DeliveryError("Selected policy stage command cancelled.");
703
+ writer?.starting();
704
+ return new Promise((resolve2, reject) => {
705
+ const child = spawn(
706
+ "/bin/sh",
707
+ [
708
+ "-c",
709
+ 'IFS= read -r ready || exit 125; [ "$ready" = run ] || exit 125; exec "$@" </dev/null',
710
+ "ai-delivery-command",
711
+ executable,
712
+ ...args
713
+ ],
714
+ {
715
+ cwd: execution?.cwd ?? repoRoot,
716
+ detached: process.platform !== "win32",
717
+ 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
+ }
1112
723
  }
724
+ }
725
+ );
726
+ const stdout = [];
727
+ const stderr = [];
728
+ const owned = process.platform === "win32" || child.pid === void 0 ? void 0 : { rootPid: child.pid, sampled: false, tracked: /* @__PURE__ */ new Map() };
729
+ let outputBytes = 0;
730
+ let retainedOutputBytes = 0;
731
+ const outputLimit = execution?.maxCapturedOutputBytes ?? 8 * 1024 * 1024;
732
+ let sampledOutputBytes = 0;
733
+ let failure;
734
+ let cleanupFailure;
735
+ let writerFailure;
736
+ let closed = false;
737
+ let settled = false;
738
+ let commandReleased = false;
739
+ let firstOutputObservationFailure;
740
+ let lastOutputObservationFailure;
741
+ let pendingOutput;
742
+ const scanCancellation = new AbortController();
743
+ const failedOutput = () => {
744
+ const observation = firstOutputObservationFailure === void 0 ? "" : ` First filesystem observation: ${firstOutputObservationFailure} Last filesystem observation: ${lastOutputObservationFailure}`;
745
+ try {
746
+ const bytes = Buffer.concat([...stdout, ...stderr]);
747
+ if (execution?.failedOutput) return execution.failedOutput(bytes);
748
+ return ` Command output ${writeRepositoryCommandOutput({ bytes, gitCommonDir: gitCommonDir(repoRoot) })}.${observation}`;
749
+ } catch (error) {
750
+ return ` Command output persistence failed (${error instanceof Error ? error.message : String(error)}).${observation}`;
751
+ }
1113
752
  };
1114
- collect(root);
1115
- const dependencies = new Map();
1116
- const collectDependencies = (manifestPath) => {
1117
- if (dependencies.has(manifestPath))
1118
- return;
1119
- const bytes = readFileSync(manifestPath);
1120
- const manifest = z
1121
- .object({ dependencies: z.record(z.string(), z.string()).optional() })
1122
- .parse(JSON.parse(bytes.toString('utf8')));
1123
- dependencies.set(manifestPath, digestBytes(bytes));
1124
- const require = createRequire(manifestPath);
1125
- for (const name of Object.keys(manifest.dependencies ?? {}).sort()) {
1126
- let resolved;
1127
- try {
1128
- resolved = require.resolve(`${name}/package.json`);
1129
- }
1130
- catch {
1131
- try {
1132
- resolved = require.resolve(name);
1133
- }
1134
- catch (error) {
1135
- if (!types.isNativeError(error) || Reflect.get(error, 'code') !== 'ERR_PACKAGE_PATH_NOT_EXPORTED')
1136
- throw error;
1137
- const manifest = findPackageJSON(name, manifestPath);
1138
- if (!manifest)
1139
- throw error;
1140
- resolved = manifest;
1141
- }
1142
- }
1143
- let directory = dirname(resolved);
1144
- for (;;) {
1145
- const path = join(directory, 'package.json');
1146
- if (existsSync(path)) {
1147
- const candidate = z.object({ name: z.string().optional() }).parse(JSON.parse(readFileSync(path, 'utf8')));
1148
- if (candidate.name === name) {
1149
- collectDependencies(path);
1150
- break;
1151
- }
1152
- }
1153
- const parent = dirname(directory);
1154
- if (parent === directory)
1155
- throw new DeliveryError(`Producer dependency identity is unavailable for ${name}.`);
1156
- directory = parent;
1157
- }
753
+ let closeTimer;
754
+ let exitPipeTimer;
755
+ let resourceTimer;
756
+ const clearWatchers = () => {
757
+ clearInterval(progressTimer);
758
+ if (resourceTimer !== void 0) clearInterval(resourceTimer);
759
+ if (closeTimer !== void 0) clearTimeout(closeTimer);
760
+ if (exitPipeTimer !== void 0) clearTimeout(exitPipeTimer);
761
+ abortSignal?.removeEventListener("abort", onAbort);
762
+ process.removeListener("SIGINT", onSigint);
763
+ process.removeListener("SIGTERM", onSigterm);
764
+ };
765
+ const killOwned = () => {
766
+ if (child.pid === void 0) return;
767
+ if (owned?.sampled) {
768
+ try {
769
+ observeOwnedProcesses(owned, processSnapshot());
770
+ } catch (error) {
771
+ cleanupFailure ??= error instanceof Error ? error.message : String(error);
1158
772
  }
773
+ try {
774
+ writer?.observed(owned);
775
+ } catch (error) {
776
+ writerFailure ??= error instanceof Error ? error.message : String(error);
777
+ }
778
+ try {
779
+ terminateOwnedProcesses(owned);
780
+ } catch (error) {
781
+ cleanupFailure ??= error instanceof Error ? error.message : String(error);
782
+ }
783
+ } else {
784
+ try {
785
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
786
+ if (commandReleased) cleanupFailure ??= "owned process identity was not observed before cleanup";
787
+ } catch (error) {
788
+ cleanupFailure ??= error instanceof Error ? error.message : String(error);
789
+ }
790
+ }
1159
791
  };
1160
- collectDependencies(join(dirname(root), 'package.json'));
1161
- return { code, dependencies: [...dependencies].sort(([a], [b]) => a.localeCompare(b)) };
1162
- }
1163
- function producerDigest(root = dirname(fileURLToPath(import.meta.url))) {
1164
- return digestValue(producerContent(root));
1165
- }
1166
- /** @internal Retained public code is hashed as data; it is never imported or executed. */
1167
- export function retainedWorktreeTransitionProducerDigest(distDirectory) {
1168
- return producerDigest(realpathSync(distDirectory));
1169
- }
1170
- /** @internal Preserve the same dependency manifests that participate in the existing producer digest. */
1171
- export function retainedWorktreeTransitionDependencyManifests(distDirectory) {
1172
- return producerContent(realpathSync(distDirectory)).dependencies.map(([source, digest]) => ({ source, digest }));
1173
- }
1174
- /** @internal Original manifests validate as history and cannot authorize current verification. */
1175
- export function readWorktreeTransitionRun(bytes) {
1176
- return parseRun(JSON.parse(bytes.toString('utf8')));
1177
- }
1178
- function parseRun(value) {
1179
- if (typeof value !== 'object' || value === null || Array.isArray(value))
1180
- throw new DeliveryError('Invalid run manifest.');
1181
- const input = value;
1182
- const classification = RepositoryClassificationReceiptSchema.parse(input.classification);
1183
- const aggregate = RepositoryStageAggregateSchema.parse(input.aggregate);
1184
- const stageReceipts = RepositoryStageReceiptSchema.array().parse(input.stageReceipts);
1185
- if (!['ai-delivery.run@1', 'ai-delivery.run@2', 'ai-delivery.run@3'].includes(String(input.schemaVersion)))
1186
- throw new DeliveryError('Run manifest schema version is unsupported.');
1187
- if (input.schemaVersion === 'ai-delivery.run@1' && input.resources !== undefined)
1188
- throw new DeliveryError('Historical run manifest has unexpected resource evidence.');
1189
- const resources = input.resources === undefined ? undefined : ResourceSummarySchema.parse(input.resources);
1190
- if (input.schemaVersion === 'ai-delivery.run@2' && resources === undefined)
1191
- throw new DeliveryError('Historical bounded run lacks resource evidence.');
1192
- const writer = input.schemaVersion === 'ai-delivery.run@3'
1193
- ? z
1194
- .strictObject({
1195
- worktreeDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
1196
- producerDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
1197
- })
1198
- .parse(input.writer)
1199
- : undefined;
1200
- const content = {
1201
- aggregate,
1202
- classification,
1203
- completedAt: input.completedAt,
1204
- ...(resources === undefined ? {} : { resources }),
1205
- ...(writer === undefined ? {} : { writer }),
1206
- schemaVersion: input.schemaVersion,
1207
- stageReceipts,
792
+ const stop = (reason) => {
793
+ if (failure !== void 0) return;
794
+ failure = reason;
795
+ scanCancellation.abort();
796
+ killOwned();
797
+ if (!closed) {
798
+ closeTimer = setTimeout(() => {
799
+ if (settled || closed) return;
800
+ settled = true;
801
+ clearWatchers();
802
+ child.stdout.destroy();
803
+ child.stderr.destroy();
804
+ child.unref();
805
+ execution?.onCleanupFailure?.("Owned command pipes did not close; descendant cleanup could not be verified.");
806
+ reject(
807
+ new DeliveryError(
808
+ `Selected policy stage command failed (${failure}).${failedOutput()}${writerFailure === void 0 ? "" : ` Writer state persistence failed (${writerFailure}).`} Owned process cleanup failed (owned command pipes did not close; descendant cleanup could not be verified).`
809
+ )
810
+ );
811
+ }, 2e3);
812
+ }
1208
813
  };
1209
- if (typeof input.completedAt !== 'string' ||
1210
- input.manifestId !== digestValue(content) ||
1211
- createRepositoryStageAggregate({ classification, receipts: stageReceipts }).aggregateId !== aggregate.aggregateId)
1212
- throw new DeliveryError('Run manifest identity or aggregate is invalid.');
1213
- return { ...content, completedAt: input.completedAt, manifestId: input.manifestId };
1214
- }
1215
- function reportVerificationProgress(input) {
1216
- process.stderr.write(`ai-delivery.verify ${JSON.stringify(input)}\n`);
1217
- }
1218
- export function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds, baseline, onResourceSample, writer, execution) {
1219
- const [executable, ...args] = argv;
1220
- if (!executable)
1221
- throw new DeliveryError('Policy selected an empty stage command.');
1222
- if (abortSignal?.aborted)
1223
- throw new DeliveryError('Selected policy stage command cancelled.');
1224
- writer?.starting();
1225
- return new Promise((resolve, reject) => {
1226
- // The shell waits for our ownership receipt, then exec preserves its PID, birth identity and process group.
1227
- const child = spawn('/bin/sh', [
1228
- '-c',
1229
- 'IFS= read -r ready || exit 125; [ "$ready" = run ] || exit 125; exec "$@" </dev/null',
1230
- 'ai-delivery-command',
1231
- executable,
1232
- ...args,
1233
- ], {
1234
- cwd: execution?.cwd ?? repoRoot,
1235
- detached: process.platform !== 'win32',
1236
- stdio: ['pipe', 'pipe', 'pipe'],
1237
- ...(baseline?.gate === undefined && execution === undefined
1238
- ? {}
1239
- : {
1240
- env: {
1241
- ...(execution?.environment ?? process.env),
1242
- ...(baseline?.gate === undefined ? {} : { [OUTPUT_GATE_ENV]: JSON.stringify(baseline.gate) }),
1243
- },
1244
- }),
1245
- });
1246
- const stdout = [];
1247
- const stderr = [];
1248
- const owned = process.platform === 'win32' || child.pid === undefined
1249
- ? undefined
1250
- : { rootPid: child.pid, sampled: false, tracked: new Map() };
1251
- let outputBytes = 0;
1252
- let retainedOutputBytes = 0;
1253
- const outputLimit = execution?.maxCapturedOutputBytes ?? 8 * 1024 * 1024;
1254
- let sampledOutputBytes = 0;
1255
- let failure;
1256
- let cleanupFailure;
1257
- let writerFailure;
1258
- let closed = false;
1259
- let settled = false;
1260
- let commandReleased = false;
1261
- let firstOutputObservationFailure;
1262
- let lastOutputObservationFailure;
1263
- let pendingOutput;
1264
- const scanCancellation = new AbortController();
1265
- const failedOutput = () => {
1266
- const observation = firstOutputObservationFailure === undefined
1267
- ? ''
1268
- : ` First filesystem observation: ${firstOutputObservationFailure} Last filesystem observation: ${lastOutputObservationFailure}`;
1269
- try {
1270
- const bytes = Buffer.concat([...stdout, ...stderr]);
1271
- if (execution?.failedOutput)
1272
- return execution.failedOutput(bytes);
1273
- return ` Command output ${writeRepositoryCommandOutput({ bytes, gitCommonDir: gitCommonDir(repoRoot) })}.${observation}`;
1274
- }
1275
- catch (error) {
1276
- return ` Command output persistence failed (${error instanceof Error ? error.message : String(error)}).${observation}`;
1277
- }
1278
- };
1279
- let closeTimer;
1280
- let exitPipeTimer;
1281
- let resourceTimer;
1282
- const clearWatchers = () => {
1283
- clearInterval(progressTimer);
1284
- if (resourceTimer !== undefined)
1285
- clearInterval(resourceTimer);
1286
- if (closeTimer !== undefined)
1287
- clearTimeout(closeTimer);
1288
- if (exitPipeTimer !== undefined)
1289
- clearTimeout(exitPipeTimer);
1290
- abortSignal?.removeEventListener('abort', onAbort);
1291
- process.removeListener('SIGINT', onSigint);
1292
- process.removeListener('SIGTERM', onSigterm);
1293
- };
1294
- const killOwned = () => {
1295
- if (child.pid === undefined)
1296
- return;
1297
- if (owned?.sampled) {
1298
- try {
1299
- observeOwnedProcesses(owned, processSnapshot());
1300
- }
1301
- catch (error) {
1302
- cleanupFailure ??= error instanceof Error ? error.message : String(error);
1303
- }
1304
- try {
1305
- writer?.observed(owned);
1306
- }
1307
- catch (error) {
1308
- writerFailure ??= error instanceof Error ? error.message : String(error);
1309
- }
1310
- // Durable state failure cannot prevent identity-checked termination of known-owned processes.
1311
- try {
1312
- terminateOwnedProcesses(owned);
1313
- }
1314
- catch (error) {
1315
- cleanupFailure ??= error instanceof Error ? error.message : String(error);
1316
- }
1317
- }
1318
- else {
1319
- try {
1320
- // The still-owned direct child is the only safe signal target before identity observation.
1321
- if (child.exitCode === null && child.signalCode === null)
1322
- child.kill('SIGKILL');
1323
- if (commandReleased)
1324
- cleanupFailure ??= 'owned process identity was not observed before cleanup';
1325
- }
1326
- catch (error) {
1327
- cleanupFailure ??= error instanceof Error ? error.message : String(error);
1328
- }
1329
- }
1330
- };
1331
- const stop = (reason) => {
1332
- if (failure !== undefined)
1333
- return;
1334
- failure = reason;
1335
- scanCancellation.abort();
1336
- killOwned();
1337
- if (!closed) {
1338
- closeTimer = setTimeout(() => {
1339
- if (settled || closed)
1340
- return;
1341
- settled = true;
1342
- clearWatchers();
1343
- child.stdout.destroy();
1344
- child.stderr.destroy();
1345
- child.unref();
1346
- execution?.onCleanupFailure?.('Owned command pipes did not close; descendant cleanup could not be verified.');
1347
- reject(new DeliveryError(`Selected policy stage command failed (${failure}).${failedOutput()}${writerFailure === undefined ? '' : ` Writer state persistence failed (${writerFailure}).`} Owned process cleanup failed (owned command pipes did not close; descendant cleanup could not be verified).`));
1348
- }, 2_000);
1349
- }
1350
- };
1351
- const capture = (chunks, chunk) => {
1352
- outputBytes += chunk.length;
1353
- execution?.onCaptured?.(outputBytes);
1354
- if (execution !== undefined &&
1355
- resourceBounds?.maxNewOutputBytes !== undefined &&
1356
- outputBytes + sampledOutputBytes > resourceBounds.maxNewOutputBytes) {
1357
- stop('source-phase captured output exceeded remaining cumulative allowance');
1358
- return;
1359
- }
1360
- if (outputBytes > outputLimit) {
1361
- const remaining = outputLimit - retainedOutputBytes;
1362
- if (remaining > 0) {
1363
- chunks.push(Buffer.from(chunk.subarray(0, remaining)));
1364
- retainedOutputBytes += Math.min(remaining, chunk.length);
1365
- }
1366
- stop(execution?.maxCapturedOutputBytes === undefined
1367
- ? 'captured output exceeded 8 MiB'
1368
- : `captured output exceeded ${outputLimit} bytes`);
1369
- return;
1370
- }
1371
- chunks.push(chunk);
1372
- retainedOutputBytes += chunk.length;
1373
- };
1374
- child.stdout.on('data', (chunk) => capture(stdout, chunk));
1375
- child.stderr.on('data', (chunk) => capture(stderr, chunk));
1376
- child.stdout.once('error', (error) => stop(error.message));
1377
- child.stderr.once('error', (error) => stop(error.message));
1378
- child.stdin.once('error', (error) => stop(error.message));
1379
- child.once('error', (error) => {
1380
- if (child.pid === undefined)
1381
- writer?.idle();
1382
- stop(error.message);
1383
- });
1384
- child.once('exit', (code, signal) => {
1385
- if (code !== 0 || signal !== null)
1386
- stop(`exit ${String(code)}${signal === null ? '' : ` signal ${signal}`}`);
1387
- else if (!closed) {
1388
- exitPipeTimer = setTimeout(() => {
1389
- if (!closed)
1390
- stop('owned command pipes did not close after direct child exit');
1391
- }, 1_000);
1392
- }
1393
- });
1394
- child.once('spawn', () => {
1395
- const sample = () => {
1396
- if (failure !== undefined || child.pid === undefined)
1397
- return;
1398
- try {
1399
- if (owned === undefined)
1400
- throw new DeliveryError('Owned process identity is unavailable on this platform.');
1401
- observeOwnedProcesses(owned, processSnapshot());
1402
- writer?.observed(owned);
1403
- if (resourceBounds !== undefined) {
1404
- const result = sampleOwnedTree(owned, repoRoot, resourceBounds, baseline, undefined, execution === undefined ? 0 : process.memoryUsage().rss, execution?.includeControllerTree);
1405
- onResourceSample?.(result);
1406
- onRunning?.(outputBytes, result);
1407
- }
1408
- if (closed || pendingOutput !== undefined)
1409
- return;
1410
- pendingOutput = (async () => {
1411
- if (resourceBounds !== undefined && baseline !== undefined) {
1412
- const bytes = await positiveNewOutputBytes(baseline, scanCancellation.signal, commandReleased, (reason) => {
1413
- firstOutputObservationFailure ??= reason;
1414
- lastOutputObservationFailure = reason;
1415
- onRunning?.(outputBytes, undefined, reason);
1416
- });
1417
- if (failure !== undefined)
1418
- return;
1419
- sampledOutputBytes = bytes;
1420
- const result = sampleOwnedTree(owned, repoRoot, resourceBounds, baseline, bytes + (execution === undefined ? 0 : outputBytes), execution === undefined ? 0 : process.memoryUsage().rss, execution?.includeControllerTree);
1421
- onResourceSample?.(result);
1422
- onRunning?.(outputBytes, result);
1423
- }
1424
- if (failure === undefined && !commandReleased) {
1425
- commandReleased = true;
1426
- child.stdin.end('run\n');
1427
- }
1428
- })()
1429
- .catch((error) => stop(error instanceof Error ? error.message : String(error)))
1430
- .finally(() => {
1431
- pendingOutput = undefined;
1432
- });
1433
- }
1434
- catch (error) {
1435
- stop(error instanceof Error ? error.message : String(error));
1436
- }
1437
- };
1438
- sample();
1439
- resourceTimer = setInterval(sample, 1_000);
1440
- resourceTimer.unref();
1441
- });
1442
- const progressTimer = setInterval(() => onRunning?.(outputBytes), 5_000);
1443
- progressTimer.unref();
1444
- const onAbort = () => stop('cancelled');
1445
- const onSigint = () => stop('cancelled by SIGINT');
1446
- const onSigterm = () => stop('cancelled by SIGTERM');
1447
- abortSignal?.addEventListener('abort', onAbort, { once: true });
1448
- process.once('SIGINT', onSigint);
1449
- process.once('SIGTERM', onSigterm);
1450
- if (abortSignal?.aborted)
1451
- onAbort();
1452
- const handleClose = async (code, signal) => {
1453
- closed = true;
1454
- if (settled)
1455
- return;
1456
- await pendingOutput;
1457
- if (failure === undefined && owned !== undefined) {
1458
- try {
1459
- if (resourceBounds !== undefined) {
1460
- const sample = sampleOwnedTree(owned, repoRoot, resourceBounds, baseline, baseline === undefined
1461
- ? undefined
1462
- : (await positiveNewOutputBytes(baseline, scanCancellation.signal)) +
1463
- (execution === undefined ? 0 : outputBytes), execution === undefined ? 0 : process.memoryUsage().rss, execution?.includeControllerTree);
1464
- onResourceSample?.(sample);
1465
- onRunning?.(outputBytes, sample);
1466
- }
1467
- if (!owned.sampled)
1468
- throw new DeliveryError('Owned process resource observation was unavailable.');
1469
- const remaining = observeOwnedProcesses(owned, processSnapshot());
1470
- if (remaining.length > 0)
1471
- throw new DeliveryError('A sampled owned descendant survived command exit.');
1472
- }
1473
- catch (error) {
1474
- stop(error instanceof Error ? error.message : String(error));
814
+ const capture = (chunks, chunk) => {
815
+ outputBytes += chunk.length;
816
+ execution?.onCaptured?.(outputBytes);
817
+ if (execution !== void 0 && resourceBounds?.maxNewOutputBytes !== void 0 && outputBytes + sampledOutputBytes > resourceBounds.maxNewOutputBytes) {
818
+ stop("source-phase captured output exceeded remaining cumulative allowance");
819
+ return;
820
+ }
821
+ if (outputBytes > outputLimit) {
822
+ const remaining = outputLimit - retainedOutputBytes;
823
+ if (remaining > 0) {
824
+ chunks.push(Buffer.from(chunk.subarray(0, remaining)));
825
+ retainedOutputBytes += Math.min(remaining, chunk.length);
826
+ }
827
+ stop(
828
+ execution?.maxCapturedOutputBytes === void 0 ? "captured output exceeded 8 MiB" : `captured output exceeded ${outputLimit} bytes`
829
+ );
830
+ return;
831
+ }
832
+ chunks.push(chunk);
833
+ retainedOutputBytes += chunk.length;
834
+ };
835
+ child.stdout.on("data", (chunk) => capture(stdout, chunk));
836
+ child.stderr.on("data", (chunk) => capture(stderr, chunk));
837
+ child.stdout.once("error", (error) => stop(error.message));
838
+ child.stderr.once("error", (error) => stop(error.message));
839
+ child.stdin.once("error", (error) => stop(error.message));
840
+ child.once("error", (error) => {
841
+ if (child.pid === void 0) writer?.idle();
842
+ stop(error.message);
843
+ });
844
+ child.once("exit", (code, signal) => {
845
+ if (code !== 0 || signal !== null) stop(`exit ${String(code)}${signal === null ? "" : ` signal ${signal}`}`);
846
+ else if (!closed) {
847
+ exitPipeTimer = setTimeout(() => {
848
+ if (!closed) stop("owned command pipes did not close after direct child exit");
849
+ }, 1e3);
850
+ }
851
+ });
852
+ child.once("spawn", () => {
853
+ const sample = () => {
854
+ if (failure !== void 0 || child.pid === void 0) return;
855
+ try {
856
+ if (owned === void 0) throw new DeliveryError("Owned process identity is unavailable on this platform.");
857
+ observeOwnedProcesses(owned, processSnapshot());
858
+ writer?.observed(owned);
859
+ if (resourceBounds !== void 0) {
860
+ const result = sampleOwnedTree(
861
+ owned,
862
+ repoRoot,
863
+ resourceBounds,
864
+ baseline,
865
+ void 0,
866
+ execution === void 0 ? 0 : process.memoryUsage().rss,
867
+ execution?.includeControllerTree
868
+ );
869
+ onResourceSample?.(result);
870
+ onRunning?.(outputBytes, result);
871
+ }
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);
1475
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);
1476
898
  }
1477
- if (failure !== undefined || code !== 0 || signal !== null) {
1478
- const reason = failure ?? `exit ${String(code)}${signal === null ? '' : ` signal ${signal}`}`;
1479
- let cleanupConfirmed = child.pid === undefined || !commandReleased;
1480
- if (owned !== undefined && owned.sampled) {
1481
- try {
1482
- await confirmOwnedCleanup(owned);
1483
- cleanupConfirmed = true;
1484
- }
1485
- catch (error) {
1486
- cleanupFailure ??= error instanceof Error ? error.message : String(error);
1487
- }
1488
- }
1489
- if (cleanupConfirmed) {
1490
- try {
1491
- writer?.idle();
1492
- }
1493
- catch (error) {
1494
- writerFailure ??= error instanceof Error ? error.message : String(error);
1495
- }
1496
- }
1497
- settled = true;
1498
- if (cleanupFailure !== undefined)
1499
- execution?.onCleanupFailure?.(cleanupFailure);
1500
- reject(new DeliveryError(`Selected policy stage command failed (${reason}). Command exit ${String(code)}${signal === null ? '' : ` signal ${signal}`}.${failedOutput()}${writerFailure === undefined ? '' : ` Writer state persistence failed (${writerFailure}).`}${cleanupFailure === undefined ? '' : ` Owned process cleanup failed (${cleanupFailure}).`}`));
1501
- return;
899
+ if (failure === void 0 && !commandReleased) {
900
+ commandReleased = true;
901
+ child.stdin.end("run\n");
1502
902
  }
903
+ })().catch((error) => stop(error instanceof Error ? error.message : String(error))).finally(() => {
904
+ pendingOutput = void 0;
905
+ });
906
+ } catch (error) {
907
+ stop(error instanceof Error ? error.message : String(error));
908
+ }
909
+ };
910
+ sample();
911
+ resourceTimer = setInterval(sample, 1e3);
912
+ resourceTimer.unref();
913
+ });
914
+ const progressTimer = setInterval(() => onRunning?.(outputBytes), 5e3);
915
+ progressTimer.unref();
916
+ const onAbort = () => stop("cancelled");
917
+ const onSigint = () => stop("cancelled by SIGINT");
918
+ const onSigterm = () => stop("cancelled by SIGTERM");
919
+ abortSignal?.addEventListener("abort", onAbort, { once: true });
920
+ process.once("SIGINT", onSigint);
921
+ process.once("SIGTERM", onSigterm);
922
+ if (abortSignal?.aborted) onAbort();
923
+ const handleClose = async (code, signal) => {
924
+ closed = true;
925
+ if (settled) return;
926
+ await pendingOutput;
927
+ if (failure === void 0 && owned !== void 0) {
928
+ try {
929
+ if (resourceBounds !== void 0) {
930
+ const sample = sampleOwnedTree(
931
+ owned,
932
+ repoRoot,
933
+ resourceBounds,
934
+ baseline,
935
+ baseline === void 0 ? void 0 : await positiveNewOutputBytes(baseline, scanCancellation.signal) + (execution === void 0 ? 0 : outputBytes),
936
+ execution === void 0 ? 0 : process.memoryUsage().rss,
937
+ execution?.includeControllerTree
938
+ );
939
+ onResourceSample?.(sample);
940
+ onRunning?.(outputBytes, sample);
941
+ }
942
+ if (!owned.sampled) throw new DeliveryError("Owned process resource observation was unavailable.");
943
+ const remaining = observeOwnedProcesses(owned, processSnapshot());
944
+ if (remaining.length > 0) throw new DeliveryError("A sampled owned descendant survived command exit.");
945
+ } catch (error) {
946
+ stop(error instanceof Error ? error.message : String(error));
947
+ }
948
+ }
949
+ if (failure !== void 0 || code !== 0 || signal !== null) {
950
+ const reason = failure ?? `exit ${String(code)}${signal === null ? "" : ` signal ${signal}`}`;
951
+ let cleanupConfirmed = child.pid === void 0 || !commandReleased;
952
+ if (owned !== void 0 && owned.sampled) {
953
+ try {
954
+ await confirmOwnedCleanup(owned);
955
+ cleanupConfirmed = true;
956
+ } catch (error) {
957
+ cleanupFailure ??= error instanceof Error ? error.message : String(error);
958
+ }
959
+ }
960
+ if (cleanupConfirmed) {
961
+ try {
1503
962
  writer?.idle();
1504
- settled = true;
1505
- resolve(execution?.stdoutOnly ? Buffer.concat(stdout) : Buffer.concat([...stdout, ...stderr], outputBytes));
1506
- };
1507
- child.once('close', (code, signal) => {
1508
- void handleClose(code, signal)
1509
- .catch((error) => {
1510
- settled = true;
1511
- reject(error);
1512
- })
1513
- .finally(clearWatchers);
1514
- });
963
+ } catch (error) {
964
+ writerFailure ??= error instanceof Error ? error.message : String(error);
965
+ }
966
+ }
967
+ settled = true;
968
+ if (cleanupFailure !== void 0) execution?.onCleanupFailure?.(cleanupFailure);
969
+ reject(
970
+ new DeliveryError(
971
+ `Selected policy stage command failed (${reason}). Command exit ${String(code)}${signal === null ? "" : ` signal ${signal}`}.${failedOutput()}${writerFailure === void 0 ? "" : ` Writer state persistence failed (${writerFailure}).`}${cleanupFailure === void 0 ? "" : ` Owned process cleanup failed (${cleanupFailure}).`}`
972
+ )
973
+ );
974
+ return;
975
+ }
976
+ writer?.idle();
977
+ settled = true;
978
+ resolve2(execution?.stdoutOnly ? Buffer.concat(stdout) : Buffer.concat([...stdout, ...stderr], outputBytes));
979
+ };
980
+ child.once("close", (code, signal) => {
981
+ void handleClose(code, signal).catch((error) => {
982
+ settled = true;
983
+ reject(error);
984
+ }).finally(clearWatchers);
1515
985
  });
986
+ });
1516
987
  }
1517
988
  const SourceDigest = z.string().regex(/^sha256:[a-f0-9]{64}$/u);
1518
989
  const SourceSha = z.string().regex(/^[a-f0-9]{40}$/u);
1519
990
  const SourceArtifactSchema = z.strictObject({ path: z.string().min(1), digest: SourceDigest });
1520
991
  const SourceFileSchema = SourceArtifactSchema.extend({
1521
- device: z.number().int().nonnegative().safe(),
1522
- inode: z.number().int().nonnegative().safe(),
1523
- uid: z.number().int().nonnegative().safe(),
1524
- mode: z.number().int().nonnegative().safe(),
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()
1525
996
  });
1526
997
  const SourceCommandSchema = z.strictObject({
1527
- argv: z.array(z.string()).min(1),
1528
- cwd: z.string().min(1),
1529
- executable: SourceFileSchema,
998
+ argv: z.array(z.string()).min(1),
999
+ cwd: z.string().min(1),
1000
+ executable: SourceFileSchema
1530
1001
  });
1531
1002
  const SourceSnapshotSchema = z.strictObject({
1532
- head: SourceSha,
1533
- indexTree: SourceSha,
1534
- branch: z.string().min(1),
1535
- configDigest: SourceDigest,
1536
- dirty: z.array(z.strictObject({ path: z.string().min(1), digest: SourceDigest.nullable() })),
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() }))
1537
1008
  });
1538
1009
  const SourceBoundsSchema = z.strictObject({
1539
- maxAggregateRssBytes: z.number().int().positive().safe(),
1540
- maxNewOutputBytes: z.number().int().positive().safe(),
1541
- minFreeDiskBytes: z.number().int().positive().safe(),
1542
- outputRoots: z.array(z.string().min(1)).min(1),
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)
1543
1014
  });
1544
1015
  const SourceReconciliationSchema = z.strictObject({
1545
- phaseId: SourceDigest,
1546
- recordId: SourceDigest,
1547
- baselineId: SourceDigest.optional(),
1548
- authorizationDigest: SourceDigest,
1016
+ phaseId: SourceDigest,
1017
+ recordId: SourceDigest,
1018
+ baselineId: SourceDigest.optional(),
1019
+ authorizationDigest: SourceDigest
1549
1020
  });
1550
1021
  const IssueSourcePhaseInputSchema = z.strictObject({
1551
- repoRoot: z.string().min(1),
1552
- issueNumber: z.number().int().positive().safe(),
1553
- identity: z.string().min(1),
1554
- rowDigest: SourceDigest,
1555
- controller: z.strictObject({
1556
- head: SourceSha,
1557
- configDigest: SourceDigest,
1558
- admissionId: SourceDigest,
1559
- runtimeEntryPath: z.string().min(1),
1560
- packageVersion: z.string().min(1),
1561
- archiveDigest: SourceDigest,
1562
- }),
1563
- source: SourceSnapshotSchema.extend({
1564
- path: z.string().min(1),
1565
- effect: z.discriminatedUnion('kind', [
1566
- z.strictObject({ kind: z.literal('preserve') }),
1567
- z.strictObject({
1568
- kind: z.literal('commitOnce'),
1569
- parent: SourceSha,
1570
- tree: SourceSha,
1571
- configDigest: SourceDigest.optional(),
1572
- }),
1573
- ]),
1574
- }),
1575
- caller: SourceArtifactSchema,
1576
- authorization: SourceArtifactSchema,
1577
- inputs: z.array(SourceArtifactSchema),
1578
- commands: z.array(SourceCommandSchema).min(1),
1579
- commandGraphDigest: SourceDigest,
1580
- environment: z.strictObject({ digest: SourceDigest, overrides: z.record(z.string(), z.string().nullable()) }),
1581
- bounds: SourceBoundsSchema,
1582
- completionArtifacts: z.array(z.string().min(1)),
1583
- reconciliation: SourceReconciliationSchema.optional(),
1584
- });
1585
- const SourceBindingSchema = IssueSourcePhaseInputSchema.omit({ environment: true }).extend({
1586
- environmentDigest: SourceDigest,
1587
- });
1588
- const SourcePhaseBaselineSchema = z.strictObject({
1589
- roots: z.array(z.string().min(1)).min(1),
1590
- files: z.array(z.tuple([z.string(), z.number().int().nonnegative().safe()])),
1591
- links: z.array(z.tuple([z.string(), z.strictObject({ identity: z.string(), target: z.string(), missing: z.boolean() })])),
1592
- baselineId: SourceDigest,
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()
1593
1055
  });
1594
1056
  const SourcePhaseCommandResultSchema = z.strictObject({
1595
- index: z.number().int().nonnegative().safe(),
1596
- outputDigest: SourceDigest.nullable(),
1597
- outputBytes: z.number().int().nonnegative().safe(),
1598
- status: z.enum(['complete', 'failed']),
1599
- });
1600
- const SourcePhaseResultSchema = z.strictObject({
1601
- source: SourceSnapshotSchema,
1602
- artifacts: z.array(SourceFileSchema),
1603
- newOutputBytes: z.number().int().nonnegative().safe(),
1604
- writerReleased: z.literal(true),
1605
- lockReleased: z.literal(true),
1057
+ index: z.number().int().nonnegative().safe(),
1058
+ outputDigest: SourceDigest.nullable(),
1059
+ outputBytes: z.number().int().nonnegative().safe(),
1060
+ status: z.enum(["complete", "failed"])
1606
1061
  });
1607
- const SourcePhaseRecordSchema = z
1608
- .strictObject({
1609
- schemaVersion: z.literal('ai-delivery.source-phase@1'),
1610
- phaseId: SourceDigest,
1611
- recordId: SourceDigest,
1612
- worktreeDigest: SourceDigest,
1613
- bindingDigest: SourceDigest,
1614
- authorizationDigest: SourceDigest,
1615
- status: z.enum(['preparing', 'intent', 'complete', 'failed-quiescent', 'rejected-before-work', 'unresolved']),
1616
- writerId: z.uuid(),
1617
- binding: SourceBindingSchema.optional(),
1618
- baseline: SourcePhaseBaselineSchema.optional(),
1619
- allocation: SourceBoundsSchema.optional(),
1620
- owner: z.strictObject({ pid: z.number().int().positive().safe(), identity: z.string().min(1) }),
1621
- bootstrapFiles: z.array(z.tuple([z.string(), z.number().int().nonnegative().safe()])),
1622
- bootstrapBytes: z.number().int().nonnegative().safe(),
1623
- capturedBytes: z.number().int().nonnegative().safe(),
1624
- nextCommandIndex: z.number().int().nonnegative().safe(),
1625
- commands: z.array(SourcePhaseCommandResultSchema),
1626
- claimDigest: SourceDigest.optional(),
1627
- releaseDigest: SourceDigest.optional(),
1628
- preparationArtifact: SourceFileSchema.optional(),
1629
- writerArtifact: SourceFileSchema.optional(),
1630
- producerDigest: SourceDigest.optional(),
1631
- actor: z
1632
- .strictObject({
1633
- identity: z.string().min(1),
1634
- actorLogin: z.string().min(1),
1635
- credentialIdentity: z.string().min(1),
1636
- })
1637
- .optional(),
1638
- retainedArtifacts: z.array(SourceFileSchema).optional(),
1639
- retainedPredecessors: z.array(z.strictObject({ phaseId: SourceDigest, recordId: SourceDigest })),
1640
- reconciliation: SourceReconciliationSchema.optional(),
1641
- result: SourcePhaseResultSchema.optional(),
1642
- failure: z
1643
- .strictObject({
1644
- operation: z.string().optional(),
1645
- accounting: z.string().optional(),
1646
- cleanup: z.string().optional(),
1647
- writerRelease: z.string().optional(),
1648
- lockRelease: z.string().optional(),
1649
- })
1650
- .optional(),
1651
- })
1652
- .superRefine((record, context) => {
1653
- const { recordId, ...content } = record;
1654
- if (recordId !== digestValue(content) || record.phaseId !== record.bindingDigest)
1655
- context.addIssue({ code: 'custom', message: 'Source-phase record identity is invalid.' });
1656
- if (record.binding !== undefined && digestValue(record.binding) !== record.bindingDigest)
1657
- context.addIssue({ code: 'custom', message: 'Source-phase input binding is invalid.' });
1658
- if (record.baseline !== undefined) {
1659
- const { baselineId, ...baseline } = record.baseline;
1660
- if (baselineId !== digestValue(baseline))
1661
- context.addIssue({ code: 'custom', message: 'Source-phase baseline is invalid.' });
1662
- }
1663
- if (record.status === 'rejected-before-work' &&
1664
- (record.commands.length !== 0 || record.nextCommandIndex !== 0 || record.capturedBytes !== 0))
1665
- context.addIssue({ code: 'custom', message: 'Rejected source-phase input cannot contain executed work.' });
1666
- if (record.status === 'complete' &&
1667
- (record.result === undefined ||
1668
- record.baseline === undefined ||
1669
- record.binding === undefined ||
1670
- record.failure !== undefined))
1671
- context.addIssue({ code: 'custom', message: 'Source-phase completion is incomplete.' });
1672
- if (record.status === 'complete' &&
1673
- (record.commands.length !== record.binding?.commands.length ||
1674
- record.nextCommandIndex !== record.commands.length ||
1675
- record.commands.some((command, index) => command.index !== index || command.status !== 'complete')))
1676
- context.addIssue({
1677
- code: 'custom',
1678
- message: 'Source-phase completion does not contain its exact successful command graph.',
1679
- });
1680
- });
1681
- async function assertNoUnsealedSourcePhase(common, subject, refuseUnresolved = false) {
1682
- const directory = join(common, 'ai-delivery', 'receipts', 'source-phase@1', subject.slice(7));
1683
- let names;
1684
- try {
1685
- const stat = lstatSync(directory);
1686
- if (!stat.isDirectory() || stat.isSymbolicLink())
1687
- throw new DeliveryError('Source-phase admission metadata is not a canonical directory.');
1688
- names = readdirSync(directory);
1689
- }
1690
- catch (error) {
1691
- if (error.code === 'ENOENT')
1692
- return;
1693
- throw error;
1694
- }
1695
- if (names.length > 100_000)
1696
- throw new DeliveryError('Source-phase admission exceeded its entry bound.');
1697
- for (const name of names) {
1698
- const record = SourcePhaseRecordSchema.parse(JSON.parse(assertPrivateFile(join(directory, name)).toString('utf8')));
1699
- if (record.worktreeDigest !== subject || name !== `${record.phaseId.slice(7)}.json`)
1700
- throw new DeliveryError('Source-phase admission record belongs to another input or worktree.');
1701
- if (record.status === 'preparing' || record.status === 'intent')
1702
- throw new DeliveryError('An unsealed source phase still excludes another worktree writer.');
1703
- if (refuseUnresolved && record.status === 'unresolved')
1704
- throw new DeliveryError('Unresolved source phase requires owning reconciliation before another attempt.');
1705
- await new Promise((resolve) => setImmediate(resolve));
1706
- }
1707
- }
1708
1062
  const IssueSourcePhaseReceiptSchema = z.strictObject({
1709
- status: z.literal('complete'),
1710
- phaseId: SourceDigest,
1711
- recordId: SourceDigest,
1712
- source: SourceSnapshotSchema,
1713
- commands: z.array(SourcePhaseCommandResultSchema),
1063
+ status: z.literal("complete"),
1064
+ phaseId: SourceDigest,
1065
+ recordId: SourceDigest,
1066
+ source: SourceSnapshotSchema,
1067
+ commands: z.array(SourcePhaseCommandResultSchema)
1714
1068
  });
1715
- const RuntimeOutputLedgerSchema = z
1716
- .strictObject({
1717
- schemaVersion: z.literal('ai-delivery.runtime-output@1'),
1718
- stageId: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
1719
- worktreeDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
1720
- producerDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
1721
- limit: z
1722
- .number()
1723
- .int()
1724
- .positive()
1725
- .safe()
1726
- .max(8 * 1024 ** 2),
1727
- outputs: z
1728
- .array(z.strictObject({
1729
- digest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
1730
- bytes: z
1731
- .number()
1732
- .int()
1733
- .nonnegative()
1734
- .safe()
1735
- .max(8 * 1024 ** 2),
1736
- status: z.enum(['reserved', 'complete']),
1737
- }))
1738
- .max(4096),
1739
- contentDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
1740
- })
1741
- .superRefine((value, context) => {
1742
- const { contentDigest, ...content } = value;
1743
- if (contentDigest !== digestValue(content) ||
1744
- new Set(value.outputs.map((output) => output.digest)).size !== value.outputs.length ||
1745
- value.outputs.reduce((total, output) => total + output.bytes, 0) > value.limit)
1746
- context.addIssue({
1747
- code: 'custom',
1748
- message: 'Runtime retained-output ledger is corrupt.',
1749
- });
1750
- });
1751
- /** @internal Runtime setup shares the existing writer, ownership handshake and bounded command runner. */
1752
- export async function withRuntimeSetupWriter(root, operation, scope) {
1753
- const cancellation = new AbortController();
1754
- const signal = scope?.signal === undefined ? cancellation.signal : AbortSignal.any([scope.signal, cancellation.signal]);
1755
- let failure;
1756
- let baseline;
1757
- let captured = 0;
1758
- const started = Date.now();
1759
- const guard = () => {
1760
- if (failure !== undefined)
1761
- throw failure;
1762
- if (signal.aborted)
1763
- throw new DeliveryError('Runtime setup cancelled.');
1764
- const rss = scope === undefined ? 0 : controllerTreeRssBytes();
1765
- if (scope !== undefined) {
1766
- if (rss > scope.bounds.maxAggregateRssBytes)
1767
- throw new DeliveryError(`Controller aggregate RSS ${rss} exceeded limit ${scope.bounds.maxAggregateRssBytes}.`);
1768
- assertDiskHeadroom(root, scope.bounds, baseline);
1769
- }
1770
- return rss;
1771
- };
1772
- if (scope !== undefined) {
1773
- assertResourceBounds(scope.bounds);
1774
- if (!Number.isSafeInteger(scope.maxCapturedOutputBytes) ||
1775
- scope.maxCapturedOutputBytes <= 0 ||
1776
- scope.maxCapturedOutputBytes > 8 * 1024 ** 2)
1777
- throw new DeliveryError('Invalid runtime setup captured-output bound; maximum is 8 MiB.');
1778
- guard();
1779
- }
1780
- root = gitRoot(root);
1781
- return withVerificationWriter(root, async (writer) => withOutputObservationGate(root, scope !== undefined, async (scopeGate) => {
1782
- let ledger;
1783
- let ledgerPath;
1784
- const common = gitCommonDir(root);
1785
- const saveLedger = () => {
1786
- if (ledger === undefined || ledgerPath === undefined)
1787
- throw new DeliveryError('Runtime output allowance is unbound.');
1788
- const { contentDigest: _previous, ...content } = ledger;
1789
- ledger = RuntimeOutputLedgerSchema.parse({
1790
- ...content,
1791
- contentDigest: digestValue(content),
1792
- });
1793
- if (Buffer.byteLength(JSON.stringify(ledger, null, 2)) > 1024 ** 2)
1794
- throw new DeliveryError('Runtime retained-output ledger exceeds its evidence bound.');
1795
- writePrivateJsonFileAtomically(ledgerPath, ledger);
1796
- };
1797
- const assertOutput = (output) => {
1798
- try {
1799
- const bytes = readRepositoryCommandOutput({
1800
- gitCommonDir: common,
1801
- digest: output.digest,
1802
- expectedBytes: output.bytes,
1803
- });
1804
- if (bytes.length !== output.bytes)
1805
- throw new DeliveryError('Runtime retained-output evidence size changed.');
1806
- return true;
1807
- }
1808
- catch (error) {
1809
- if (output.status === 'reserved' && error.code === 'ENOENT')
1810
- return false;
1811
- throw error;
1812
- }
1813
- };
1814
- const bindCapturedOutput = (stageId) => {
1815
- if (scope === undefined)
1816
- return;
1817
- if (ledger !== undefined)
1818
- throw new DeliveryError('Runtime output allowance is already bound.');
1819
- const identity = {
1820
- stageId,
1821
- worktreeDigest: worktreeDigest(root),
1822
- producerDigest: producerDigest(),
1823
- limit: scope.maxCapturedOutputBytes,
1824
- };
1825
- ledgerPath = join(common, 'ai-delivery', 'verification@1', 'runtime-output', identity.worktreeDigest.slice(7), `${stageId.slice(7)}.json`);
1826
- let retained;
1827
- try {
1828
- retained = assertPrivateFile(ledgerPath, { maxBytes: 1024 ** 2 });
1829
- }
1830
- catch (error) {
1831
- if (error.code !== 'ENOENT')
1832
- throw error;
1833
- }
1834
- if (retained !== undefined) {
1835
- ledger = RuntimeOutputLedgerSchema.parse(JSON.parse(retained.toString('utf8')));
1836
- if (ledger.stageId !== identity.stageId ||
1837
- ledger.worktreeDigest !== identity.worktreeDigest ||
1838
- ledger.producerDigest !== identity.producerDigest ||
1839
- ledger.limit !== identity.limit)
1840
- throw new DeliveryError('Runtime retained-output ledger belongs to an incompatible stage or controller.');
1841
- let recovered = false;
1842
- for (const output of ledger.outputs) {
1843
- if (assertOutput(output) && output.status === 'reserved') {
1844
- output.status = 'complete';
1845
- recovered = true;
1846
- }
1847
- }
1848
- if (recovered)
1849
- saveLedger();
1850
- }
1851
- else {
1852
- const content = {
1853
- schemaVersion: 'ai-delivery.runtime-output@1',
1854
- ...identity,
1855
- outputs: [],
1856
- };
1857
- ledger = RuntimeOutputLedgerSchema.parse({
1858
- ...content,
1859
- contentDigest: digestValue(content),
1860
- });
1861
- saveLedger();
1862
- }
1863
- };
1864
- const remainingOutput = () => {
1865
- if (scope === undefined)
1866
- return 8 * 1024 ** 2;
1867
- if (ledger === undefined)
1868
- throw new DeliveryError('Runtime output allowance is unbound.');
1869
- return ledger.limit - ledger.outputs.reduce((total, output) => total + output.bytes, 0);
1870
- };
1871
- const persistFailedOutput = (bytes) => {
1872
- if (ledger === undefined)
1873
- throw new DeliveryError('Runtime output allowance is unbound.');
1874
- const digest = digestBytes(bytes);
1875
- const prior = ledger.outputs.find((output) => output.digest === digest);
1876
- if (prior !== undefined) {
1877
- if (prior.bytes !== bytes.length || !assertOutput(prior))
1878
- throw new DeliveryError('Runtime retained-output reservation is unresolved; identical output cannot be rewritten.');
1879
- return ` Command output ${digest}.`;
1880
- }
1881
- if (bytes.length > remainingOutput())
1882
- throw new DeliveryError('Runtime retained-output allowance exceeded.');
1883
- const output = {
1884
- digest,
1885
- bytes: bytes.length,
1886
- status: 'reserved',
1887
- };
1888
- ledger.outputs.push(output);
1889
- saveLedger();
1890
- writeRepositoryCommandOutput({ bytes, gitCommonDir: common });
1891
- if (!assertOutput(output))
1892
- throw new DeliveryError('Runtime retained-output publication is unresolved.');
1893
- ledger.outputs[ledger.outputs.length - 1].status = 'complete';
1894
- saveLedger();
1895
- return ` Command output ${digest}.`;
1896
- };
1897
- if (scope !== undefined) {
1898
- const paths = [...(scope.bounds.outputRoots ?? []), join(gitCommonDir(root), 'ai-delivery')]
1899
- .map((path) => resolve(root, path))
1900
- .sort();
1901
- const roots = paths.filter((path, index) => !paths.slice(0, index).some((prior) => path === prior || path.startsWith(`${prior}${sep}`)));
1902
- const links = new Map();
1903
- const files = await withOutputGateLock(scopeGate, 'scan', () => scanOutputRoots(roots, links), signal);
1904
- baseline = {
1905
- roots,
1906
- links,
1907
- files,
1908
- baselineId: digestValue([...files]),
1909
- ...(scopeGate === undefined ? {} : { gate: scopeGate }),
1910
- };
1911
- }
1912
- const checkResources = async () => {
1913
- const rss = guard();
1914
- if (scope === undefined || baseline === undefined)
1915
- return;
1916
- const newOutputBytes = captured + (await positiveNewOutputBytes(baseline, signal));
1917
- guard();
1918
- if (newOutputBytes > scope.bounds.maxNewOutputBytes)
1919
- throw new DeliveryError(`Runtime setup output ${newOutputBytes} exceeded limit ${scope.bounds.maxNewOutputBytes}.`);
1920
- reportVerificationProgress({
1921
- state: 'running',
1922
- stageId: 'runtime-setup',
1923
- completedStages: 0,
1924
- reusedStages: 0,
1925
- remainingStages: 1,
1926
- elapsedMs: Date.now() - started,
1927
- capturedOutputBytes: captured,
1928
- sampledAggregateRssBytes: rss,
1929
- sampledFreeDiskBytes: freeDiskBytes(root, baseline),
1930
- sampledNewOutputBytes: newOutputBytes,
1931
- });
1932
- };
1933
- await checkResources();
1934
- const timer = scope === undefined
1935
- ? undefined
1936
- : setInterval(() => {
1937
- try {
1938
- guard();
1939
- }
1940
- catch (error) {
1941
- failure ??= error instanceof Error ? error : new DeliveryError(String(error));
1942
- cancellation.abort();
1943
- }
1944
- }, 1_000);
1945
- timer?.unref();
1946
- try {
1947
- const result = await operation({
1948
- assertQuiescent: () => writer.assertQuiescent(),
1949
- bindCapturedOutput,
1950
- checkResources,
1951
- signal,
1952
- run: async (argv, bounds, commandSignal, environment, cwd) => {
1953
- await checkResources();
1954
- assertResourceBounds(bounds);
1955
- const roots = bounds.outputRoots?.map((path) => resolve(root, path)).sort();
1956
- if (roots !== undefined) {
1957
- for (let i = 1; i < roots.length; i++)
1958
- if (roots[i] === roots[i - 1] || roots[i].startsWith(`${roots[i - 1]}${sep}`))
1959
- throw new DeliveryError('Filesystem output roots must not overlap.');
1960
- }
1961
- const run = async (gate) => {
1962
- const remaining = remainingOutput();
1963
- if (remaining <= 0)
1964
- throw new DeliveryError('Runtime retained-output allowance is exhausted; installer was not started.');
1965
- const links = new Map();
1966
- const files = roots === undefined
1967
- ? undefined
1968
- : await withOutputGateLock(gate, 'scan', () => scanOutputRoots(roots, links), signal);
1969
- const commandBaseline = roots === undefined || files === undefined
1970
- ? undefined
1971
- : {
1972
- roots,
1973
- files,
1974
- links,
1975
- baselineId: digestValue([...files]),
1976
- ...(gate === undefined ? {} : { gate }),
1977
- };
1978
- assertDiskHeadroom(root, bounds, commandBaseline);
1979
- let commandCaptured = 0;
1980
- const output = await runStageCommand(root, argv, commandSignal === undefined ? signal : AbortSignal.any([signal, commandSignal]), (capturedOutputBytes, sample, reason) => reportVerificationProgress({
1981
- state: 'running',
1982
- stageId: 'runtime-setup:install',
1983
- completedStages: 0,
1984
- reusedStages: 0,
1985
- remainingStages: 1,
1986
- elapsedMs: Date.now() - started,
1987
- capturedOutputBytes,
1988
- ...(reason === undefined ? {} : { reason }),
1989
- ...(sample === undefined
1990
- ? {}
1991
- : {
1992
- sampledAggregateRssBytes: sample.aggregateRssBytes,
1993
- sampledFreeDiskBytes: sample.freeDiskBytes,
1994
- sampledNewOutputBytes: sample.newOutputBytes,
1995
- }),
1996
- }), bounds, commandBaseline, undefined, writer, scope === undefined && environment === undefined && cwd === undefined
1997
- ? undefined
1998
- : {
1999
- environment: environment ?? process.env,
2000
- ...(cwd === undefined ? {} : { cwd }),
2001
- ...(scope === undefined
2002
- ? {}
2003
- : {
2004
- maxCapturedOutputBytes: remaining,
2005
- includeControllerTree: true,
2006
- failedOutput: persistFailedOutput,
2007
- }),
2008
- onCaptured: (bytes) => {
2009
- captured += bytes - commandCaptured;
2010
- commandCaptured = bytes;
2011
- },
2012
- });
2013
- await checkResources();
2014
- return output;
2015
- };
2016
- return scope === undefined ? withOutputObservationGate(root, roots !== undefined, run) : run(scopeGate);
2017
- },
2018
- });
2019
- await checkResources();
2020
- reportVerificationProgress({
2021
- state: 'completed',
2022
- stageId: 'runtime-setup',
2023
- completedStages: 1,
2024
- reusedStages: 0,
2025
- remainingStages: 0,
2026
- elapsedMs: Date.now() - started,
2027
- });
2028
- return result;
2029
- }
2030
- catch (error) {
2031
- if (failure !== undefined)
2032
- throw new DeliveryError(`${failure.message} Runtime setup operation failed (${error instanceof Error ? error.message : String(error)}).`);
2033
- if (signal.aborted)
2034
- throw new DeliveryError(`Runtime setup cancelled. ${error instanceof Error ? error.message : String(error)}`);
2035
- throw error;
2036
- }
2037
- finally {
2038
- if (timer !== undefined)
2039
- clearInterval(timer);
2040
- }
2041
- }));
2042
- }
2043
- //# sourceMappingURL=verification.js.map
1069
+ export {
1070
+ confirmOwnedCleanup,
1071
+ processSnapshot,
1072
+ retainedWorktreeTransitionDependencyManifests,
1073
+ retainedWorktreeTransitionProducerDigest,
1074
+ runStageCommand,
1075
+ terminateOwnedProcesses,
1076
+ withVerificationFilesystemFixture
1077
+ };
1078
+ //# sourceMappingURL=verification.js.map