@aviaratech/ai-delivery 0.3.23 → 0.3.24

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 (112) hide show
  1. package/CONTRIBUTING.md +9 -0
  2. package/README.md +56 -447
  3. package/dist/agent.d.ts +5 -11
  4. package/dist/agent.js +4 -8
  5. package/dist/agent.js.map +1 -1
  6. package/dist/cli.js +12 -107
  7. package/dist/cli.js.map +1 -1
  8. package/dist/config/deliveryConfig.d.ts +44 -55
  9. package/dist/config/deliveryConfig.js +85 -88
  10. package/dist/config/deliveryConfig.js.map +1 -1
  11. package/dist/config/deliveryConfig.test.js +13 -5
  12. package/dist/config/deliveryConfig.test.js.map +1 -1
  13. package/dist/delivery/common.js +7 -2
  14. package/dist/delivery/common.js.map +1 -1
  15. package/dist/delivery/delivery.test.js +2 -3
  16. package/dist/delivery/delivery.test.js.map +1 -1
  17. package/dist/delivery/index.d.ts +0 -6
  18. package/dist/delivery/index.js +0 -3
  19. package/dist/delivery/index.js.map +1 -1
  20. package/dist/delivery/legacy.d.ts +8 -0
  21. package/dist/delivery/legacy.js +5 -0
  22. package/dist/delivery/legacy.js.map +1 -0
  23. package/dist/delivery/policy.js +2 -13
  24. package/dist/delivery/policy.js.map +1 -1
  25. package/dist/directoryIndependent.test.d.ts +1 -0
  26. package/dist/directoryIndependent.test.js +262 -0
  27. package/dist/directoryIndependent.test.js.map +1 -0
  28. package/dist/dispatch.d.ts +29 -3
  29. package/dist/dispatch.js +160 -457
  30. package/dist/dispatch.js.map +1 -1
  31. package/dist/genericCompatibility.test.js +0 -35
  32. package/dist/genericCompatibility.test.js.map +1 -1
  33. package/dist/git.js +10 -3
  34. package/dist/git.js.map +1 -1
  35. package/dist/gitProcess.d.ts +6 -0
  36. package/dist/gitProcess.js +56 -0
  37. package/dist/gitProcess.js.map +1 -0
  38. package/dist/github/discovery.d.ts +1 -0
  39. package/dist/github/discovery.js +1 -1
  40. package/dist/github/discovery.js.map +1 -1
  41. package/dist/github/discovery.test.js +25 -20
  42. package/dist/github/discovery.test.js.map +1 -1
  43. package/dist/github/nativeIssueMetadata.d.ts +2 -2
  44. package/dist/github/nativeIssueMetadata.js.map +1 -1
  45. package/dist/github/projectDelivery.d.ts +1 -1
  46. package/dist/github/projectDelivery.js.map +1 -1
  47. package/dist/github/repo.d.ts +7 -1
  48. package/dist/github/repo.js +58 -2
  49. package/dist/github/repo.js.map +1 -1
  50. package/dist/issue.d.ts +11 -6
  51. package/dist/issue.js +136 -319
  52. package/dist/issue.js.map +1 -1
  53. package/dist/issueJournal.d.ts +1 -1
  54. package/dist/lifecycle.test.js +40 -7371
  55. package/dist/lifecycle.test.js.map +1 -1
  56. package/dist/logger.js +4 -4
  57. package/dist/logger.js.map +1 -1
  58. package/dist/mcp/tools.d.ts +26 -42
  59. package/dist/mcp/tools.js +33 -42
  60. package/dist/mcp/tools.js.map +1 -1
  61. package/dist/pluginInstaller.d.ts +1 -1
  62. package/dist/pluginPackaging.test.js +129 -0
  63. package/dist/pluginPackaging.test.js.map +1 -1
  64. package/dist/pr.d.ts +66 -114
  65. package/dist/pr.js +288 -1108
  66. package/dist/pr.js.map +1 -1
  67. package/dist/pr.test.js +295 -237
  68. package/dist/pr.test.js.map +1 -1
  69. package/dist/releaseReconciliation.test.d.ts +1 -0
  70. package/dist/releaseReconciliation.test.js +314 -0
  71. package/dist/releaseReconciliation.test.js.map +1 -0
  72. package/dist/review.d.ts +37 -7
  73. package/dist/review.js +106 -45
  74. package/dist/review.js.map +1 -1
  75. package/dist/review.test.js +30 -71
  76. package/dist/review.test.js.map +1 -1
  77. package/dist/services/agentReadinessService.d.ts +1 -1
  78. package/dist/services/agentReadinessService.js +2 -0
  79. package/dist/services/agentReadinessService.js.map +1 -1
  80. package/dist/services/deliveryAdmission.d.ts +4 -4
  81. package/dist/services/deliveryAdmission.js.map +1 -1
  82. package/dist/setup.test.js +10 -5
  83. package/dist/setup.test.js.map +1 -1
  84. package/dist/start.test.d.ts +1 -0
  85. package/dist/start.test.js +72 -0
  86. package/dist/start.test.js.map +1 -0
  87. package/dist/stdoutRegression.test.d.ts +1 -0
  88. package/dist/stdoutRegression.test.js +326 -0
  89. package/dist/stdoutRegression.test.js.map +1 -0
  90. package/dist/verification.d.ts +1 -27
  91. package/dist/verification.js +5 -1332
  92. package/dist/verification.js.map +1 -1
  93. package/dist/worktree.d.ts +1 -31
  94. package/dist/worktree.js +5 -200
  95. package/dist/worktree.js.map +1 -1
  96. package/dist/worktreeTransition.d.ts +1 -1
  97. package/dist/worktreeTransition.js +10 -5
  98. package/dist/worktreeTransition.js.map +1 -1
  99. package/dist/worktreeTransition.test.js +2 -3
  100. package/dist/worktreeTransition.test.js.map +1 -1
  101. package/package.json +1 -1
  102. package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
  103. package/plugins/ai-delivery/README.md +3 -3
  104. package/plugins/ai-delivery/plugin.json +1 -1
  105. package/plugins/ai-delivery/runtime/dist/cli.js +50 -59
  106. package/plugins/ai-delivery/runtime/package.json +1 -1
  107. package/plugins/ai-delivery/skills/intake-create/SKILL.md +1 -1
  108. package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +14 -21
  109. package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +12 -23
  110. package/dist/services/deliveryRecordService.d.ts +0 -47
  111. package/dist/services/deliveryRecordService.js +0 -199
  112. package/dist/services/deliveryRecordService.js.map +0 -1
@@ -1,19 +1,15 @@
1
1
  import { spawn, spawnSync } from 'node:child_process';
2
- import { createHash, randomUUID } from 'node:crypto';
2
+ import { randomUUID } from 'node:crypto';
3
3
  import { createRequire } from 'node:module';
4
- import { closeSync, existsSync, fsyncSync, fstatSync, openSync, unlinkSync, lstatSync, mkdirSync, rmdirSync, renameSync, readFileSync, readSync, readlinkSync, readdirSync, realpathSync, statfsSync, } from 'node:fs';
5
- import { basename, dirname, join, resolve, sep } from 'node:path';
4
+ import { closeSync, existsSync, fsyncSync, openSync, unlinkSync, lstatSync, mkdirSync, rmdirSync, renameSync, readFileSync, readlinkSync, readdirSync, realpathSync, statfsSync, } from 'node:fs';
5
+ import { dirname, join, resolve, sep } from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
7
  import { z } from 'zod';
8
- import { loadDeliveryConfig } from './config/deliveryConfig.js';
9
8
  import { assertPrivateFile } from './delivery/common.js';
10
9
  import { readRepositoryCommandOutput } from './delivery/stage.js';
11
- import { classifyRepositoryExactRange, assertRepositoryClassificationCurrent, createRepositoryDeliveryEvidence, createRepositoryStageAggregate, createRepositoryStageInput, createRepositoryStageReceipt, digestBytes, digestValue, assertRepositoryStageProof, loadRepositoryStageCheckpoint, loadSelectedRepositoryPolicy, RepositoryClassificationReceiptSchema, RepositoryStageAggregateSchema, RepositoryStageReceiptSchema, writeRepositoryCommandOutput, writeRepositoryDeliveryEvidence, writeRepositoryStageAggregate, writeRepositoryStageCheckpoint, } from './delivery/index.js';
10
+ import { createRepositoryStageAggregate, digestBytes, digestValue, RepositoryClassificationReceiptSchema, RepositoryStageAggregateSchema, RepositoryStageReceiptSchema, writeRepositoryCommandOutput, } from './delivery/legacy.js';
12
11
  import { DeliveryError } from './errors.js';
13
- import { createDeliveryGitHubClients } from './github/client.js';
14
- import { assertClean, changedPaths, coordinate, defaultBaseRef, git, gitCommonDir, gitRoot } from './git.js';
15
- import { assertAiDeliveryWorktreeOwner, getIssueWorktreeStrict } from './services/worktreeRegistry.js';
16
- import { assertDeliveryRuntimeAdmitted } from './services/deliveryAdmission.js';
12
+ import { gitCommonDir, gitRoot } from './git.js';
17
13
  import { withLock } from './utils/lockfile.js';
18
14
  import { ensurePrivateDirectoryDurably, writePrivateJsonFileAtomically } from './utils/atomicJson.js';
19
15
  const ResourceSummarySchema = z
@@ -50,63 +46,6 @@ const ResourceSummarySchema = z
50
46
  (value.bounds.maxNewOutputBytes !== undefined) !== (value.outputBaselineId !== undefined))
51
47
  ctx.addIssue({ code: 'custom', message: 'Resource samples do not satisfy their declared bounds.' });
52
48
  });
53
- const ResourceStageCheckpointSchema = z.strictObject({
54
- checkpointId: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
55
- receipt: RepositoryStageReceiptSchema,
56
- resources: ResourceSummarySchema,
57
- schemaVersion: z.literal('ai-delivery.resource-stage@1'),
58
- });
59
- function resourceStagePath(common, stageInput) {
60
- return join(common, 'ai-delivery', 'resource-stages@1', `${stageInput.inputId.slice(7)}.json`);
61
- }
62
- function loadResourceStageCheckpoint(common, repoRoot, stageInput, bounds, baselineId) {
63
- let raw;
64
- try {
65
- raw = JSON.parse(readFileSync(resourceStagePath(common, stageInput), 'utf8'));
66
- }
67
- catch (error) {
68
- if (error.code === 'ENOENT')
69
- return undefined;
70
- throw new DeliveryError('Resource stage checkpoint is corrupt.');
71
- }
72
- const checkpoint = ResourceStageCheckpointSchema.parse(raw);
73
- const { checkpointId, ...content } = checkpoint;
74
- if (checkpointId !== digestValue(content) ||
75
- checkpoint.receipt.input.inputId !== stageInput.inputId ||
76
- digestValue(checkpoint.resources.bounds) !== digestValue(bounds) ||
77
- checkpoint.resources.outputBaselineId !== baselineId ||
78
- checkpoint.resources.sampleCount === 0)
79
- throw new DeliveryError('Resource stage checkpoint is corrupt or belongs to another input.');
80
- assertRepositoryStageProof({ gitCommonDir: common, receipt: checkpoint.receipt, repoRoot });
81
- return checkpoint;
82
- }
83
- function writeResourceStageCheckpoint(common, receipt, resources) {
84
- if (resources.sampleCount === 0)
85
- throw new DeliveryError('Completed bounded stage lacks resource samples.');
86
- const content = {
87
- receipt,
88
- resources: ResourceSummarySchema.parse(resources),
89
- schemaVersion: 'ai-delivery.resource-stage@1',
90
- };
91
- writePrivateJsonFileAtomically(resourceStagePath(common, receipt.input), {
92
- ...content,
93
- checkpointId: digestValue(content),
94
- });
95
- }
96
- function mergeResourceSummary(target, source) {
97
- target.sampleCount += source.sampleCount;
98
- if (!Number.isSafeInteger(target.sampleCount))
99
- throw new DeliveryError('Resource sample count overflowed.');
100
- if (source.maxSampledAggregateRssBytes !== null) {
101
- target.maxSampledAggregateRssBytes = Math.max(target.maxSampledAggregateRssBytes ?? 0, source.maxSampledAggregateRssBytes);
102
- }
103
- if (source.maxSampledNewOutputBytes !== null) {
104
- target.maxSampledNewOutputBytes = Math.max(target.maxSampledNewOutputBytes ?? 0, source.maxSampledNewOutputBytes);
105
- }
106
- if (source.minSampledFreeDiskBytes !== null) {
107
- target.minSampledFreeDiskBytes = Math.min(target.minSampledFreeDiskBytes ?? source.minSampledFreeDiskBytes, source.minSampledFreeDiskBytes);
108
- }
109
- }
110
49
  function assertResourceBounds(bounds) {
111
50
  const limits = [
112
51
  ['maxAggregateRssBytes', bounds.maxAggregateRssBytes],
@@ -376,23 +315,6 @@ async function withOutputObservationGate(root, enabled, operation) {
376
315
  retireOutputGate(gate);
377
316
  }
378
317
  }
379
- const OutputBaselineCheckpointSchema = z.strictObject({
380
- baselineId: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
381
- files: z.array(z.tuple([z.string().min(1), z.number().int().nonnegative().safe()])),
382
- inputId: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
383
- roots: z.array(z.string().min(1)).min(1),
384
- schemaVersion: z.literal('ai-delivery.output-baseline@1'),
385
- });
386
- const OutputBaselineStateSchema = z.strictObject({
387
- baselineId: z
388
- .string()
389
- .regex(/^sha256:[a-f0-9]{64}$/u)
390
- .optional(),
391
- inputId: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
392
- schemaVersion: z.literal('ai-delivery.output-baseline-state@1'),
393
- stateId: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
394
- status: z.enum(['preparing', 'complete']),
395
- });
396
318
  class OutputObservationError extends DeliveryError {
397
319
  cause;
398
320
  code;
@@ -564,83 +486,6 @@ function scanOutputRoots(roots, links, commandRunning = false, onMissingTarget)
564
486
  links.set(path, link);
565
487
  return files;
566
488
  }
567
- async function outputBaseline(repoRoot, common, classificationReceiptId, bounds, gate, signal) {
568
- if (bounds.outputRoots === undefined)
569
- return undefined;
570
- const roots = bounds.outputRoots.map((path) => resolve(repoRoot, path)).sort();
571
- const links = new Map();
572
- for (let i = 1; i < roots.length; i++) {
573
- if (roots[i] === roots[i - 1] || roots[i].startsWith(`${roots[i - 1]}${sep}`)) {
574
- throw new DeliveryError('Filesystem output roots must not overlap.');
575
- }
576
- }
577
- const inputId = digestValue({
578
- bounds: { ...bounds, outputRoots: roots },
579
- classificationReceiptId,
580
- resourceRunner: digestBytes(readFileSync(fileURLToPath(import.meta.url))),
581
- });
582
- const path = join(common, 'ai-delivery', 'output-baselines@1', `${inputId.slice(7)}.json`);
583
- const statePath = join(common, 'ai-delivery', 'output-baselines@1', `${inputId.slice(7)}.state.json`);
584
- const writeState = (status, baselineId) => {
585
- const content = {
586
- inputId,
587
- schemaVersion: 'ai-delivery.output-baseline-state@1',
588
- status,
589
- ...(baselineId === undefined ? {} : { baselineId }),
590
- };
591
- writePrivateJsonFileAtomically(statePath, { ...content, stateId: digestValue(content) });
592
- };
593
- let state;
594
- try {
595
- state = OutputBaselineStateSchema.parse(JSON.parse(readFileSync(statePath, 'utf8')));
596
- }
597
- catch (error) {
598
- if (error.code !== 'ENOENT') {
599
- throw new DeliveryError('Filesystem output baseline state is corrupt.');
600
- }
601
- }
602
- if (state === undefined) {
603
- if (existsSync(path))
604
- throw new DeliveryError('Filesystem output baseline state is missing.');
605
- writeState('preparing');
606
- }
607
- else {
608
- const { stateId, ...content } = state;
609
- if (stateId !== digestValue(content) ||
610
- state.inputId !== inputId ||
611
- (state.status === 'complete') !== (state.baselineId !== undefined))
612
- throw new DeliveryError('Filesystem output baseline state is corrupt.');
613
- }
614
- let checkpoint;
615
- if (state?.status !== 'complete') {
616
- const content = {
617
- files: [...(await withOutputGateLock(gate, 'scan', () => scanOutputRoots(roots, links), signal))].sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)),
618
- inputId,
619
- roots,
620
- schemaVersion: 'ai-delivery.output-baseline@1',
621
- };
622
- checkpoint = { ...content, baselineId: digestValue(content) };
623
- writePrivateJsonFileAtomically(path, checkpoint);
624
- writeState('complete', checkpoint.baselineId);
625
- }
626
- else {
627
- try {
628
- checkpoint = OutputBaselineCheckpointSchema.parse(JSON.parse(readFileSync(path, 'utf8')));
629
- }
630
- catch {
631
- throw new DeliveryError('Filesystem output baseline checkpoint is missing or corrupt.');
632
- }
633
- }
634
- const { baselineId, ...content } = checkpoint;
635
- if (baselineId !== digestValue(content) ||
636
- (state?.status === 'complete' && state.baselineId !== baselineId) ||
637
- checkpoint.inputId !== inputId ||
638
- digestValue(checkpoint.roots) !== digestValue(roots) ||
639
- checkpoint.files.some(([file], index) => (index > 0 && file <= checkpoint.files[index - 1][0]) ||
640
- !roots.some((root) => file === root || file.startsWith(`${root}${sep}`))))
641
- throw new DeliveryError('Filesystem output baseline checkpoint is corrupt or belongs to another input.');
642
- return { baselineId, roots, files: new Map(checkpoint.files), links, ...(gate === undefined ? {} : { gate }) };
643
- }
644
489
  async function positiveNewOutputBytes(baseline, signal, commandRunning = false, onUnavailable) {
645
490
  let files;
646
491
  let firstFailure;
@@ -1151,21 +996,6 @@ export async function withWorktreeTransitionWriterLease(input, operation) {
1151
996
  return result;
1152
997
  }, input, gitCommonDir(repository));
1153
998
  }
1154
- function primaryRoot(worktreeRoot) {
1155
- const common = gitCommonDir(worktreeRoot);
1156
- if (basename(common) !== '.git')
1157
- throw new DeliveryError('Expected a conventional non-bare Git repository.');
1158
- return dirname(common);
1159
- }
1160
- function assertRegisteredIssue(worktreeRoot, issueNumber, allowMerged = false) {
1161
- const row = getIssueWorktreeStrict(issueNumber, primaryRoot(worktreeRoot));
1162
- if (row.path !== worktreeRoot ||
1163
- row.branch !== `issue/${issueNumber}` ||
1164
- (row.status !== 'active' && row.status !== 'pr-published' && !(allowMerged && row.status === 'merged'))) {
1165
- throw new DeliveryError('Verification requires the exact registered issue worktree.');
1166
- }
1167
- assertClean(worktreeRoot);
1168
- }
1169
999
  function worktreeDigest(root) {
1170
1000
  return digestValue(resolve(root));
1171
1001
  }
@@ -1234,11 +1064,6 @@ export function retainedWorktreeTransitionDependencyManifests(distDirectory) {
1234
1064
  export function readWorktreeTransitionRun(bytes) {
1235
1065
  return parseRun(JSON.parse(bytes.toString('utf8')));
1236
1066
  }
1237
- function manifestPath(common, headSha, root) {
1238
- return root === undefined
1239
- ? join(common, 'ai-delivery', 'runs', `${headSha}.json`)
1240
- : join(common, 'ai-delivery', 'runs@2', worktreeDigest(root).slice(7), `${headSha}.json`);
1241
- }
1242
1067
  function parseRun(value) {
1243
1068
  if (typeof value !== 'object' || value === null || Array.isArray(value))
1244
1069
  throw new DeliveryError('Invalid run manifest.');
@@ -1276,50 +1101,6 @@ function parseRun(value) {
1276
1101
  throw new DeliveryError('Run manifest identity or aggregate is invalid.');
1277
1102
  return { ...content, completedAt: input.completedAt, manifestId: input.manifestId };
1278
1103
  }
1279
- function loadRun(common, headSha, root, historical = false) {
1280
- let raw;
1281
- try {
1282
- raw = JSON.parse(readFileSync(manifestPath(common, headSha, root), 'utf8'));
1283
- }
1284
- catch (error) {
1285
- if (!historical || error.code !== 'ENOENT')
1286
- throw new DeliveryError('Exact-head worktree verification run is missing or corrupt; verify with the current producer.');
1287
- raw = JSON.parse(readFileSync(manifestPath(common, headSha), 'utf8'));
1288
- }
1289
- const run = parseRun(raw);
1290
- if (run.classification.head.sha !== headSha ||
1291
- (run.writer !== undefined &&
1292
- (run.writer.worktreeDigest !== worktreeDigest(root) ||
1293
- (!historical && run.writer.producerDigest !== producerDigest()))) ||
1294
- (!historical && run.writer === undefined))
1295
- throw new DeliveryError('Verification run belongs to another writer or producer.');
1296
- const expectedEnvironment = historical ? undefined : verificationEnvironmentDigest(root, run.resources);
1297
- if (expectedEnvironment !== undefined &&
1298
- run.stageReceipts.some((receipt) => receipt.input.environmentDigest !== expectedEnvironment))
1299
- throw new DeliveryError('Verification stage environment belongs to a foreign worktree or producer.');
1300
- return run;
1301
- }
1302
- function stageEnvironmentDigest(root, producer = producerDigest()) {
1303
- return digestValue({
1304
- arch: process.arch,
1305
- node: process.version,
1306
- path: process.env.PATH ?? '',
1307
- platform: process.platform,
1308
- worktreeDigest: worktreeDigest(root),
1309
- producerDigest: producer,
1310
- });
1311
- }
1312
- function verificationEnvironmentDigest(root, resources, producer = producerDigest()) {
1313
- const environment = stageEnvironmentDigest(root, producer);
1314
- return resources === undefined
1315
- ? environment
1316
- : digestValue({
1317
- environment,
1318
- ...(resources.outputBaselineId === undefined ? {} : { outputBaselineId: resources.outputBaselineId }),
1319
- resourceBounds: resources.bounds,
1320
- resourceRunner: digestBytes(readFileSync(fileURLToPath(import.meta.url))),
1321
- });
1322
- }
1323
1104
  function reportVerificationProgress(input) {
1324
1105
  process.stderr.write(`ai-delivery.verify ${JSON.stringify(input)}\n`);
1325
1106
  }
@@ -1622,359 +1403,6 @@ export function runStageCommand(repoRoot, argv, abortSignal, onRunning, resource
1622
1403
  });
1623
1404
  });
1624
1405
  }
1625
- export async function verifyIssue(input) {
1626
- const root = gitRoot(input.repoRoot);
1627
- return withVerificationWriter(root, (writer) => withOutputObservationGate(root, input.resourceBounds?.outputRoots !== undefined, (gate) => verifyIssueOwned(input, writer, gate)));
1628
- }
1629
- async function verifyIssueOwned(input, writer, gate) {
1630
- const assertNotCancelled = () => {
1631
- if (input.signal?.aborted)
1632
- throw new DeliveryError('Verification cancelled.');
1633
- };
1634
- assertNotCancelled();
1635
- const root = gitRoot(input.repoRoot);
1636
- if (input.resourceBounds !== undefined)
1637
- assertResourceBounds(input.resourceBounds);
1638
- assertRegisteredIssue(root, input.issueNumber);
1639
- const common = gitCommonDir(root);
1640
- if (existsSync(join(common, 'ai-delivery', 'merges', String(input.issueNumber), `${coordinate(root).sha}.json`))) {
1641
- throw new DeliveryError('Commit continuation work before verifying an already-merged issue head; retain its receipts.');
1642
- }
1643
- const loaded = await loadDeliveryConfig(root, input.personalAuth === undefined ? {} : { personalAuth: input.personalAuth });
1644
- const selected = await loadSelectedRepositoryPolicy({
1645
- repoRoot: root,
1646
- policySourcePath: loaded.config.policy.module,
1647
- });
1648
- const base = coordinate(root, defaultBaseRef(root, loaded.remote));
1649
- const head = coordinate(root);
1650
- const classification = classifyRepositoryExactRange({
1651
- base,
1652
- changedPaths: changedPaths(root, base.sha, head.sha),
1653
- configDigest: loaded.configDigest,
1654
- head,
1655
- policy: selected.policy,
1656
- policySourcePath: loaded.config.policy.module,
1657
- repoRoot: root,
1658
- repository: loaded.config.repository,
1659
- });
1660
- const baseline = input.resourceBounds === undefined
1661
- ? undefined
1662
- : await outputBaseline(root, common, classification.receiptId, input.resourceBounds, gate, input.signal);
1663
- if (input.resourceBounds !== undefined)
1664
- assertDiskHeadroom(root, input.resourceBounds, baseline);
1665
- const receipts = [];
1666
- const admitted = new Set(input.admittedResourceClasses ?? ['source_only']);
1667
- const startedAtMs = Date.now();
1668
- let reusedStages = 0;
1669
- let completedCommands = 0;
1670
- let reusedCommands = 0;
1671
- let lastCompletedAtMs = startedAtMs;
1672
- const totalCommands = classification.requiredStages.reduce((total, stage) => total + stage.commands.length, 0);
1673
- const report = (progress) => {
1674
- const elapsedMs = Date.now() - startedAtMs;
1675
- reportVerificationProgress({
1676
- ...progress,
1677
- completedCommands,
1678
- remainingCommands: totalCommands - completedCommands,
1679
- reusedCommands,
1680
- executedCommandsPerSecond: elapsedMs === 0 ? 0 : ((completedCommands - reusedCommands) * 1000) / elapsedMs,
1681
- lastCompletedWorkAgeMs: Date.now() - lastCompletedAtMs,
1682
- });
1683
- };
1684
- const normalizedBounds = input.resourceBounds === undefined
1685
- ? undefined
1686
- : {
1687
- maxAggregateRssBytes: input.resourceBounds.maxAggregateRssBytes,
1688
- minFreeDiskBytes: input.resourceBounds.minFreeDiskBytes,
1689
- ...(input.resourceBounds.maxNewOutputBytes === undefined
1690
- ? {}
1691
- : { maxNewOutputBytes: input.resourceBounds.maxNewOutputBytes }),
1692
- ...(baseline === undefined ? {} : { outputRoots: baseline.roots }),
1693
- };
1694
- const emptyResources = () => ({
1695
- bounds: normalizedBounds,
1696
- maxSampledAggregateRssBytes: null,
1697
- maxSampledNewOutputBytes: null,
1698
- minSampledFreeDiskBytes: null,
1699
- observation: 'sampled',
1700
- ...(baseline === undefined ? {} : { outputBaselineId: baseline.baselineId }),
1701
- processCoverage: 'observed-processes-only',
1702
- sampleCount: 0,
1703
- });
1704
- const resources = normalizedBounds === undefined ? undefined : emptyResources();
1705
- const producer = producerDigest();
1706
- const environmentDigest = verificationEnvironmentDigest(root, resources, producer);
1707
- let stageResources;
1708
- const recordResourceSample = (sample) => {
1709
- if (resources === undefined)
1710
- return;
1711
- const measured = {
1712
- ...emptyResources(),
1713
- sampleCount: 1,
1714
- maxSampledAggregateRssBytes: sample.aggregateRssBytes,
1715
- maxSampledNewOutputBytes: sample.newOutputBytes ?? null,
1716
- minSampledFreeDiskBytes: sample.freeDiskBytes,
1717
- };
1718
- mergeResourceSummary(resources, measured);
1719
- if (stageResources !== undefined)
1720
- mergeResourceSummary(stageResources, measured);
1721
- };
1722
- for (const stage of classification.requiredStages) {
1723
- assertNotCancelled();
1724
- const stageInput = createRepositoryStageInput({
1725
- classification,
1726
- environmentDigest,
1727
- semanticInputs: stage.semanticInputs ??
1728
- stage.semanticInputKeys.map((key) => ({
1729
- digest: digestValue({ key, evidenceId: classification.policyEvidence.evidenceId }),
1730
- key,
1731
- })),
1732
- stageId: stage.id,
1733
- upstream: stage.dependsOn.map((stageId) => {
1734
- const receipt = receipts.find((value) => value.input.stageId === stageId);
1735
- if (!receipt)
1736
- throw new DeliveryError(`Missing upstream stage '${stageId}'.`);
1737
- return { receiptId: receipt.receiptId, stageId };
1738
- }),
1739
- });
1740
- let cached = loadRepositoryStageCheckpoint({
1741
- classification,
1742
- configDigest: loaded.configDigest,
1743
- gitCommonDir: common,
1744
- policySourcePath: loaded.config.policy.module,
1745
- repoRoot: root,
1746
- stageInput,
1747
- });
1748
- if (normalizedBounds !== undefined) {
1749
- const measured = loadResourceStageCheckpoint(common, root, stageInput, normalizedBounds, baseline?.baselineId);
1750
- if (measured !== undefined) {
1751
- if (cached === undefined) {
1752
- writeRepositoryStageCheckpoint({ gitCommonDir: common, receipt: measured.receipt, repoRoot: root });
1753
- cached = loadRepositoryStageCheckpoint({
1754
- classification,
1755
- configDigest: loaded.configDigest,
1756
- gitCommonDir: common,
1757
- policySourcePath: loaded.config.policy.module,
1758
- repoRoot: root,
1759
- stageInput,
1760
- });
1761
- }
1762
- if (cached?.receiptId !== measured.receipt.receiptId) {
1763
- throw new DeliveryError('Resource stage checkpoint disagrees with its stage receipt.');
1764
- }
1765
- mergeResourceSummary(resources, measured.resources);
1766
- }
1767
- else if (cached !== undefined) {
1768
- throw new DeliveryError('Bounded stage receipt lacks its resource checkpoint.');
1769
- }
1770
- }
1771
- if (cached) {
1772
- receipts.push(cached);
1773
- reusedStages += 1;
1774
- completedCommands += cached.commands.length;
1775
- reusedCommands += cached.commands.length;
1776
- lastCompletedAtMs = Date.now();
1777
- report({
1778
- state: 'reused',
1779
- stageId: stage.id,
1780
- completedStages: receipts.length,
1781
- remainingStages: classification.requiredStages.length - receipts.length,
1782
- reusedStages,
1783
- elapsedMs: Date.now() - startedAtMs,
1784
- });
1785
- continue;
1786
- }
1787
- assertNotCancelled();
1788
- if (!admitted.has(stage.resourceClass)) {
1789
- throw new DeliveryError(`Stage '${stage.id}' requires explicit ${stage.resourceClass} admission.`);
1790
- }
1791
- stageResources = normalizedBounds === undefined ? undefined : emptyResources();
1792
- const startedAt = new Date().toISOString();
1793
- const commands = [];
1794
- for (const command of stage.commands) {
1795
- const commandStartedAtMs = Date.now();
1796
- if (input.resourceBounds !== undefined)
1797
- assertDiskHeadroom(root, input.resourceBounds, baseline);
1798
- const progress = (capturedOutputBytes, sample, reason) => report({
1799
- state: 'running',
1800
- stageId: stage.id,
1801
- commandLabel: command.label,
1802
- completedStages: receipts.length,
1803
- remainingStages: classification.requiredStages.length - receipts.length,
1804
- reusedStages,
1805
- elapsedMs: Date.now() - startedAtMs,
1806
- capturedOutputBytes,
1807
- ...(reason === undefined ? {} : { reason }),
1808
- commandElapsedMs: Date.now() - commandStartedAtMs,
1809
- ...(sample === undefined
1810
- ? {}
1811
- : {
1812
- sampledAggregateRssBytes: sample.aggregateRssBytes,
1813
- sampledFreeDiskBytes: sample.freeDiskBytes,
1814
- ...(sample.newOutputBytes === undefined ? {} : { sampledNewOutputBytes: sample.newOutputBytes }),
1815
- ownedProcessCount: sample.ownedProcessCount,
1816
- ...(baseline !== undefined && sample.newOutputBytes === undefined
1817
- ? { reason: 'waiting for strict filesystem output scan' }
1818
- : {}),
1819
- }),
1820
- });
1821
- progress(0);
1822
- let bytes;
1823
- try {
1824
- bytes = await runStageCommand(root, command.argv, input.signal, progress, input.resourceBounds, baseline, recordResourceSample, writer);
1825
- }
1826
- catch (error) {
1827
- report({
1828
- state: 'failed',
1829
- stageId: stage.id,
1830
- commandLabel: command.label,
1831
- completedStages: receipts.length,
1832
- remainingStages: classification.requiredStages.length - receipts.length,
1833
- reusedStages,
1834
- elapsedMs: Date.now() - startedAtMs,
1835
- reason: error instanceof Error ? error.message : String(error),
1836
- });
1837
- throw error;
1838
- }
1839
- assertNotCancelled();
1840
- completedCommands += 1;
1841
- lastCompletedAtMs = Date.now();
1842
- commands.push({
1843
- exitCode: 0,
1844
- label: command.label,
1845
- outputDigest: writeRepositoryCommandOutput({ bytes, gitCommonDir: common }),
1846
- });
1847
- }
1848
- const artifacts = stage.attestationKey === undefined
1849
- ? []
1850
- : classification.policyEvidence.artifacts
1851
- .filter((artifact) => artifact.path === stage.attestationKey)
1852
- .map((artifact) => ({ digest: artifact.digest, path: artifact.path }));
1853
- if (stage.attestationKey !== undefined && artifacts.length === 0) {
1854
- throw new DeliveryError(`Selected attestation '${stage.attestationKey}' lacks a bound artifact.`);
1855
- }
1856
- const receipt = createRepositoryStageReceipt({
1857
- artifacts,
1858
- classification,
1859
- commands,
1860
- completedAt: new Date().toISOString(),
1861
- stageInput,
1862
- startedAt,
1863
- });
1864
- assertNotCancelled();
1865
- if (stageResources !== undefined)
1866
- writeResourceStageCheckpoint(common, receipt, stageResources);
1867
- writeRepositoryStageCheckpoint({ gitCommonDir: common, receipt, repoRoot: root });
1868
- stageResources = undefined;
1869
- receipts.push(receipt);
1870
- lastCompletedAtMs = Date.now();
1871
- report({
1872
- state: 'completed',
1873
- stageId: stage.id,
1874
- completedStages: receipts.length,
1875
- remainingStages: classification.requiredStages.length - receipts.length,
1876
- reusedStages,
1877
- elapsedMs: Date.now() - startedAtMs,
1878
- });
1879
- }
1880
- assertNotCancelled();
1881
- if (baseline !== undefined && input.resourceBounds !== undefined) {
1882
- const bytes = await positiveNewOutputBytes(baseline, input.signal);
1883
- if (bytes > input.resourceBounds.maxNewOutputBytes)
1884
- throw new DeliveryError('Positive new filesystem output ' + bytes + ' exceeded limit ' + input.resourceBounds.maxNewOutputBytes + '.');
1885
- assertDiskHeadroom(root, input.resourceBounds, baseline);
1886
- recordResourceSample({
1887
- aggregateRssBytes: 0,
1888
- freeDiskBytes: freeDiskBytes(root, baseline),
1889
- newOutputBytes: bytes,
1890
- ownedProcessCount: 0,
1891
- });
1892
- }
1893
- assertNotCancelled();
1894
- assertRepositoryClassificationCurrent({
1895
- classification,
1896
- configDigest: loaded.configDigest,
1897
- policySourcePath: loaded.config.policy.module,
1898
- repoRoot: root,
1899
- });
1900
- if (coordinate(root).sha !== head.sha || coordinate(root, defaultBaseRef(root, loaded.remote)).sha !== base.sha)
1901
- throw new DeliveryError('Verification source changed during execution; classify and resume the current source.');
1902
- if (producerDigest() !== producer)
1903
- throw new DeliveryError('Verification producer changed during execution.');
1904
- const aggregate = createRepositoryStageAggregate({ classification, receipts });
1905
- writeRepositoryStageAggregate({ gitCommonDir: common, aggregate });
1906
- const content = {
1907
- aggregate,
1908
- classification,
1909
- completedAt: new Date().toISOString(),
1910
- ...(resources === undefined ? {} : { resources: ResourceSummarySchema.parse(resources) }),
1911
- schemaVersion: 'ai-delivery.run@3',
1912
- writer: { worktreeDigest: worktreeDigest(root), producerDigest: producer },
1913
- stageReceipts: receipts,
1914
- };
1915
- const run = { ...content, manifestId: digestValue(content) };
1916
- writePrivateJsonFileAtomically(manifestPath(common, head.sha, root), run);
1917
- return run;
1918
- }
1919
- export async function createIssuePhaseEvidence(input) {
1920
- const root = gitRoot(input.repoRoot);
1921
- assertRegisteredIssue(root, input.issueNumber);
1922
- const loaded = await loadDeliveryConfig(root, input.personalAuth === undefined ? {} : { personalAuth: input.personalAuth });
1923
- const selected = await loadSelectedRepositoryPolicy({
1924
- repoRoot: root,
1925
- policySourcePath: loaded.config.policy.module,
1926
- });
1927
- const run = loadRun(gitCommonDir(root), coordinate(root).sha, root);
1928
- const evidence = createRepositoryDeliveryEvidence({
1929
- aggregate: run.aggregate,
1930
- ...(input.approval === undefined ? {} : { approval: input.approval }),
1931
- approvalRoles: {
1932
- authorIdentity: loaded.config.roles.author.identity,
1933
- reviewerIdentity: loaded.config.roles.reviewer.identity,
1934
- },
1935
- classification: run.classification,
1936
- configDigest: loaded.configDigest,
1937
- currentBase: coordinate(root, run.classification.base.sha),
1938
- currentHead: coordinate(root),
1939
- gitCommonDir: gitCommonDir(root),
1940
- ...(input.mergeReadback === undefined ? {} : { mergeReadback: input.mergeReadback }),
1941
- phase: input.phase,
1942
- policy: selected.policy,
1943
- policySourcePath: loaded.config.policy.module,
1944
- repoRoot: root,
1945
- stageReceipts: run.stageReceipts,
1946
- });
1947
- writeRepositoryDeliveryEvidence({ evidence, gitCommonDir: gitCommonDir(root) });
1948
- return evidence;
1949
- }
1950
- export function loadVerifiedRun(repoRoot, issueNumber) {
1951
- const root = gitRoot(repoRoot);
1952
- assertRegisteredIssue(root, issueNumber, true);
1953
- const historical = getIssueWorktreeStrict(issueNumber, primaryRoot(root)).status === 'merged';
1954
- return loadRun(gitCommonDir(root), coordinate(root).sha, root, historical);
1955
- }
1956
- /** @internal Preservation-only read; the continuation owner validates custody and terminal lineage. */
1957
- export function loadHistoricalMergedRun(repoRoot, headSha) {
1958
- const root = gitRoot(repoRoot);
1959
- const common = gitCommonDir(root);
1960
- const run = loadRun(common, headSha, root, true);
1961
- const current = manifestPath(common, headSha, root);
1962
- return { run, path: existsSync(current) ? current : manifestPath(common, headSha) };
1963
- }
1964
- /** Recover an exact merged run after worktree removal interrupted terminal recording. */
1965
- export function loadRemovedMergedRun(primaryRepoRoot, issueNumber) {
1966
- const root = gitRoot(primaryRepoRoot);
1967
- const row = getIssueWorktreeStrict(issueNumber, root);
1968
- if (row.status !== 'merged' || row.path !== join(root, '.worktrees', `issue-${issueNumber}`)) {
1969
- throw new DeliveryError('Removed-run recovery requires the exact registered merged issue.');
1970
- }
1971
- const headSha = git(root, 'rev-parse', `refs/heads/${row.branch}`);
1972
- const run = loadRun(gitCommonDir(root), headSha, row.path, true);
1973
- if (run.classification.head.sha !== headSha) {
1974
- throw new DeliveryError('Recovered merged run disagrees with the registered branch.');
1975
- }
1976
- return run;
1977
- }
1978
1406
  const SourceDigest = z.string().regex(/^sha256:[a-f0-9]{64}$/u);
1979
1407
  const SourceSha = z.string().regex(/^[a-f0-9]{40}$/u);
1980
1408
  const SourceArtifactSchema = z.strictObject({ path: z.string().min(1), digest: SourceDigest });
@@ -2173,761 +1601,6 @@ const IssueSourcePhaseReceiptSchema = z.strictObject({
2173
1601
  source: SourceSnapshotSchema,
2174
1602
  commands: z.array(SourcePhaseCommandResultSchema),
2175
1603
  });
2176
- function sourceFile(path) {
2177
- const stat = lstatSync(path);
2178
- if (!stat.isFile() || realpathSync(path) !== path)
2179
- throw new DeliveryError('Source-phase artifact must be a canonical regular file.');
2180
- const descriptor = openSync(path, 'r');
2181
- const hash = createHash('sha256');
2182
- try {
2183
- const buffer = Buffer.alloc(64 * 1024);
2184
- let bytes;
2185
- while ((bytes = readSync(descriptor, buffer, 0, buffer.length, null)) > 0)
2186
- hash.update(buffer.subarray(0, bytes));
2187
- const current = fstatSync(descriptor);
2188
- const named = lstatSync(path);
2189
- if (current.dev !== stat.dev ||
2190
- current.ino !== stat.ino ||
2191
- current.size !== stat.size ||
2192
- current.mode !== stat.mode ||
2193
- current.uid !== stat.uid ||
2194
- current.mtimeMs !== stat.mtimeMs ||
2195
- current.ctimeMs !== stat.ctimeMs ||
2196
- named.dev !== current.dev ||
2197
- named.ino !== current.ino ||
2198
- realpathSync(path) !== path)
2199
- throw new DeliveryError('Source-phase artifact changed during identity-bound hashing.');
2200
- }
2201
- finally {
2202
- closeSync(descriptor);
2203
- }
2204
- return {
2205
- path,
2206
- digest: `sha256:${hash.digest('hex')}`,
2207
- device: stat.dev,
2208
- inode: stat.ino,
2209
- uid: stat.uid,
2210
- mode: stat.mode,
2211
- };
2212
- }
2213
- function sourceDirty(root) {
2214
- const paths = [
2215
- ...new Set([
2216
- ...git(root, 'diff', '--cached', '--name-only', '-z').split('\0'),
2217
- ...git(root, 'ls-files', '-m', '-o', '--exclude-standard', '-z').split('\0'),
2218
- ].filter(Boolean)),
2219
- ].sort();
2220
- return paths.map((path) => {
2221
- const absolute = resolve(root, path);
2222
- if (!absolute.startsWith(`${root}${sep}`))
2223
- throw new DeliveryError('Source-phase dirty path escapes the worktree.');
2224
- try {
2225
- lstatSync(absolute);
2226
- }
2227
- catch (error) {
2228
- if (error.code === 'ENOENT')
2229
- return { path, digest: null };
2230
- throw error;
2231
- }
2232
- return { path, digest: sourceFile(absolute).digest };
2233
- });
2234
- }
2235
- function sourceReceipt(record) {
2236
- if (record.status !== 'complete' || record.result === undefined)
2237
- throw new DeliveryError('Source phase is not complete.');
2238
- return IssueSourcePhaseReceiptSchema.parse({
2239
- status: 'complete',
2240
- phaseId: record.phaseId,
2241
- recordId: record.recordId,
2242
- source: record.result.source,
2243
- commands: record.commands,
2244
- });
2245
- }
2246
- /** Run an authorized, frozen source graph under the registered issue's existing writer fence. */
2247
- export async function withIssueSourcePhase(supplied, operation) {
2248
- const { signal, ...values } = supplied;
2249
- const input = IssueSourcePhaseInputSchema.parse(values);
2250
- assertResourceBounds(input.bounds);
2251
- if (signal?.aborted)
2252
- throw new DeliveryError('Source phase cancelled before preparation.');
2253
- const root = gitRoot(input.repoRoot);
2254
- if (root !== input.repoRoot ||
2255
- root !== primaryRoot(root) ||
2256
- realpathSync(input.source.path) !== input.source.path ||
2257
- gitCommonDir(root) !== gitCommonDir(input.source.path))
2258
- throw new DeliveryError('Source phase requires canonical primary controller and issue worktree roots.');
2259
- const row = getIssueWorktreeStrict(input.issueNumber, root);
2260
- assertAiDeliveryWorktreeOwner(row, root);
2261
- if (!row.identity ||
2262
- row.path !== input.source.path ||
2263
- row.branch !== input.source.branch ||
2264
- !['active', 'pr-published'].includes(row.status) ||
2265
- digestValue(row) !== input.rowDigest)
2266
- throw new DeliveryError('Source phase disagrees with the exact registered issue owner.');
2267
- const environment = { ...process.env };
2268
- delete environment[OUTPUT_GATE_ENV];
2269
- for (const [name, value] of Object.entries(input.environment.overrides)) {
2270
- if (name === OUTPUT_GATE_ENV)
2271
- throw new DeliveryError('Source phase cannot supply an output observer capability.');
2272
- if (value === null)
2273
- delete environment[name];
2274
- else
2275
- environment[name] = value;
2276
- }
2277
- Object.freeze(environment);
2278
- const { environment: _environment, ...bound } = input;
2279
- const binding = SourceBindingSchema.parse({ ...bound, environmentDigest: input.environment.digest });
2280
- const phaseId = digestValue(binding);
2281
- const subject = worktreeDigest(row.path);
2282
- const common = gitCommonDir(root);
2283
- const directory = join(common, 'ai-delivery', 'receipts', 'source-phase@1', subject.slice(7));
2284
- const path = join(directory, `${phaseId.slice(7)}.json`);
2285
- const writerPath = join(common, 'ai-delivery', 'writers@1', `${subject.slice(7)}.json`);
2286
- const roots = input.bounds.outputRoots.map((value) => resolve(root, value)).sort();
2287
- if (roots.some((value, index) => index > 0 && (value === roots[index - 1] || value.startsWith(`${roots[index - 1]}${sep}`))))
2288
- throw new DeliveryError('Source-phase output roots must not overlap.');
2289
- for (const required of [
2290
- directory,
2291
- writerPath,
2292
- join(common, 'ai-delivery', 'receipts'),
2293
- join(common, 'ai-delivery', 'output-observation', subject.slice(7)),
2294
- ]) {
2295
- if (!roots.some((value) => required === value || required.startsWith(`${value}${sep}`)))
2296
- throw new DeliveryError('Source-phase roots must account for writer, observer and SDK receipt metadata.');
2297
- }
2298
- const cancelled = new AbortController();
2299
- const combined = signal === undefined ? cancelled.signal : AbortSignal.any([signal, cancelled.signal]);
2300
- let record;
2301
- let baseline;
2302
- let reused = false;
2303
- let created = false;
2304
- let entered = false;
2305
- let startedCommand = false;
2306
- let validated = false;
2307
- let writerReleased = false;
2308
- let lockFailure;
2309
- let releaseFailure;
2310
- let operationFailure;
2311
- let accountingFailure;
2312
- let cleanupFailure;
2313
- let active;
2314
- let expired = false;
2315
- let captured = 0;
2316
- let bootstrapCharge = 0;
2317
- let previousBootstrap = 0;
2318
- let writerBootstrap = 0;
2319
- let predecessorChain = [];
2320
- let accountingBounds = input.bounds;
2321
- let protocolFailure;
2322
- let commandFailure;
2323
- const attempted = new Set();
2324
- let finalSource;
2325
- let artifacts = [];
2326
- let newBytes = 0;
2327
- const writerId = randomUUID();
2328
- const started = Date.now();
2329
- const message = (error) => (error instanceof Error ? error.message : String(error));
2330
- const persist = () => {
2331
- if (record === undefined)
2332
- throw new DeliveryError('Source-phase intent is unavailable.');
2333
- const { recordId: _recordId, ...content } = record;
2334
- record = SourcePhaseRecordSchema.parse({ ...content, recordId: digestValue(content) });
2335
- writePrivateJsonFileAtomically(path, record);
2336
- };
2337
- const readRecord = (file) => {
2338
- const value = SourcePhaseRecordSchema.parse(JSON.parse(assertPrivateFile(file).toString('utf8')));
2339
- if (value.worktreeDigest !== subject || basename(file) !== `${value.phaseId.slice(7)}.json`)
2340
- throw new DeliveryError('Source-phase record belongs to another input or worktree.');
2341
- return value;
2342
- };
2343
- const assertArtifact = (artifact) => {
2344
- if (sourceFile(artifact.path).digest !== artifact.digest)
2345
- throw new DeliveryError('Frozen source-phase input artifact changed.');
2346
- };
2347
- const sourceState = async (allowFinal = false) => {
2348
- const head = git(row.path, 'rev-parse', 'HEAD');
2349
- const branch = git(row.path, 'branch', '--show-current');
2350
- const dirty = sourceDirty(row.path);
2351
- const candidate = await loadDeliveryConfig(row.path);
2352
- const configDigest = head === input.source.head || input.source.effect.kind !== 'commitOnce'
2353
- ? input.source.configDigest
2354
- : (input.source.effect.configDigest ?? input.source.configDigest);
2355
- if (branch !== input.source.branch || candidate.configDigest !== configDigest)
2356
- throw new DeliveryError('Source-phase candidate branch or configuration changed.');
2357
- if (head === input.source.head) {
2358
- if (git(row.path, 'diff', '--cached', '--name-only', input.source.indexTree) !== '' ||
2359
- digestValue(dirty) !== digestValue(input.source.dirty))
2360
- throw new DeliveryError('Source-phase frozen index or dirty source changed.');
2361
- return { head, branch, indexTree: input.source.indexTree, configDigest: candidate.configDigest, dirty };
2362
- }
2363
- if (!allowFinal)
2364
- throw new DeliveryError('Source phase requires its exact initial source before new work.');
2365
- if (input.source.effect.kind !== 'commitOnce' ||
2366
- input.source.effect.parent !== input.source.head ||
2367
- git(row.path, 'rev-list', '--parents', '-n', '1', head) !== `${head} ${input.source.effect.parent}` ||
2368
- git(row.path, 'rev-parse', 'HEAD^{tree}') !== input.source.effect.tree ||
2369
- git(row.path, 'diff', '--cached', '--name-only', head) !== '' ||
2370
- dirty.length !== 0)
2371
- throw new DeliveryError('Source-phase commit does not match its exact parent, tree and clean postconditions.');
2372
- return { head, branch, indexTree: input.source.effect.tree, configDigest: candidate.configDigest, dirty };
2373
- };
2374
- let actor;
2375
- const validate = async (allowFinal = false) => {
2376
- const currentRow = getIssueWorktreeStrict(input.issueNumber, root);
2377
- assertAiDeliveryWorktreeOwner(currentRow, root);
2378
- const configuration = await loadDeliveryConfig(root);
2379
- const admission = await assertDeliveryRuntimeAdmitted({
2380
- repoRoot: root,
2381
- runtimeEntryPath: input.controller.runtimeEntryPath,
2382
- configuration,
2383
- });
2384
- if (dirname(realpathSync(input.controller.runtimeEntryPath)) !== dirname(realpathSync(fileURLToPath(import.meta.url))))
2385
- throw new DeliveryError('Source-phase executing SDK installation is not the selected admitted runtime.');
2386
- if (digestValue(currentRow) !== input.rowDigest ||
2387
- currentRow.identity !== row.identity ||
2388
- configuration.config.roles.author.identity !== input.identity ||
2389
- git(root, 'rev-parse', 'HEAD') !== input.controller.head ||
2390
- configuration.configDigest !== input.controller.configDigest ||
2391
- admission.admissionId !== input.controller.admissionId ||
2392
- admission.sourceArchiveSha256 !== input.controller.archiveDigest ||
2393
- admission.packageVersion !== input.controller.packageVersion ||
2394
- digestValue(environment) !== input.environment.digest ||
2395
- digestValue(input.commands) !== input.commandGraphDigest)
2396
- throw new DeliveryError('Source-phase controller, selected runtime, actor or command environment binding changed.');
2397
- const clients = await createDeliveryGitHubClients({
2398
- config: configuration.config,
2399
- identity: input.identity,
2400
- role: 'author',
2401
- env: environment,
2402
- });
2403
- if (clients.role !== 'author' || clients.authenticatedAuthor === undefined)
2404
- throw new DeliveryError('Source-phase configured author authentication is unavailable.');
2405
- const authenticated = await clients.authenticatedAuthor();
2406
- if (!authenticated.actorLogin || !authenticated.credentialIdentity)
2407
- throw new DeliveryError('Source-phase configured author identity readback is incomplete.');
2408
- const currentActor = { identity: input.identity, ...authenticated };
2409
- if (actor !== undefined && digestValue(actor) !== digestValue(currentActor))
2410
- throw new DeliveryError('Source-phase authenticated author changed.');
2411
- actor = currentActor;
2412
- for (const artifact of [input.caller, input.authorization, ...input.inputs])
2413
- assertArtifact(artifact);
2414
- for (const command of input.commands) {
2415
- if (command.cwd !== row.path ||
2416
- command.argv[0] !== command.executable.path ||
2417
- digestValue(sourceFile(command.executable.path)) !== digestValue(command.executable))
2418
- throw new DeliveryError('Source-phase command or executable identity changed.');
2419
- }
2420
- await sourceState(allowFinal);
2421
- };
2422
- const observe = async (finishing = false) => {
2423
- if (baseline === undefined)
2424
- throw new DeliveryError('Source-phase output baseline is unavailable.');
2425
- assertDiskHeadroom(row.path, accountingBounds, baseline);
2426
- newBytes = bootstrapCharge + captured + (await positiveNewOutputBytes(baseline, finishing ? undefined : combined));
2427
- if (newBytes > accountingBounds.maxNewOutputBytes)
2428
- throw new DeliveryError('Source-phase cumulative output exceeded its original allowance.');
2429
- if (process.memoryUsage().rss > accountingBounds.maxAggregateRssBytes)
2430
- throw new DeliveryError('Source-phase controller RSS exceeded its bound.');
2431
- };
2432
- try {
2433
- await withVerificationWriter(row.path, async (writer) => {
2434
- try {
2435
- ensurePrivateDirectoryDurably(directory);
2436
- if (created && record !== undefined) {
2437
- record.binding = binding;
2438
- record.allocation = input.bounds;
2439
- }
2440
- const names = readdirSync(directory);
2441
- if (names.length > 100_000)
2442
- throw new DeliveryError('Source-phase record observation exceeded its entry bound.');
2443
- const history = names
2444
- .map((name) => readRecord(join(directory, name)))
2445
- .filter((value) => value.phaseId !== phaseId);
2446
- if (history.some((value) => ['preparing', 'intent', 'unresolved'].includes(value.status)))
2447
- throw new DeliveryError('Unresolved source phase requires owning reconciliation before another attempt.');
2448
- const previous = input.reconciliation === undefined
2449
- ? undefined
2450
- : history.find((value) => value.phaseId === input.reconciliation?.phaseId && value.recordId === input.reconciliation.recordId);
2451
- const failed = history.filter((value) => ['failed-quiescent', 'rejected-before-work'].includes(value.status) &&
2452
- !history.some((later) => later.retainedPredecessors.some((retained) => retained.phaseId === value.phaseId && retained.recordId === value.recordId)));
2453
- predecessorChain = [];
2454
- const visiting = new Set();
2455
- const retained = new Set();
2456
- const retain = (value) => {
2457
- if (visiting.has(value))
2458
- throw new DeliveryError('Source-phase predecessor cycle is invalid.');
2459
- if (retained.has(value))
2460
- return;
2461
- visiting.add(value);
2462
- predecessorChain.push(value);
2463
- for (const link of value.retainedPredecessors) {
2464
- const predecessor = history.find((candidate) => candidate.phaseId === link.phaseId && candidate.recordId === link.recordId);
2465
- if (predecessor === undefined)
2466
- throw new DeliveryError('Source-phase retained predecessor is unavailable.');
2467
- retain(predecessor);
2468
- }
2469
- visiting.delete(value);
2470
- retained.add(value);
2471
- };
2472
- for (const value of failed)
2473
- retain(value);
2474
- if (record !== undefined && created)
2475
- record.retainedPredecessors = failed.map(({ phaseId: retainedPhaseId, recordId }) => ({
2476
- phaseId: retainedPhaseId,
2477
- recordId,
2478
- }));
2479
- previousBootstrap = predecessorChain.reduce((sum, value) => sum + value.bootstrapBytes, 0);
2480
- captured = predecessorChain.reduce((sum, value) => sum + value.capturedBytes, 0);
2481
- const allocations = predecessorChain.map((value) => {
2482
- if (value.allocation === undefined)
2483
- throw new DeliveryError('Source-phase retained predecessor lacks its original allocation.');
2484
- return value.allocation;
2485
- });
2486
- const allocation = { ...(allocations[0] ?? input.bounds) };
2487
- for (const value of allocations) {
2488
- allocation.maxAggregateRssBytes = Math.min(allocation.maxAggregateRssBytes, value.maxAggregateRssBytes);
2489
- allocation.maxNewOutputBytes = Math.min(allocation.maxNewOutputBytes, value.maxNewOutputBytes);
2490
- allocation.minFreeDiskBytes = Math.max(allocation.minFreeDiskBytes, value.minFreeDiskBytes);
2491
- }
2492
- accountingBounds = {
2493
- ...allocation,
2494
- maxAggregateRssBytes: Math.min(allocation.maxAggregateRssBytes, input.bounds.maxAggregateRssBytes),
2495
- maxNewOutputBytes: Math.min(allocation.maxNewOutputBytes, input.bounds.maxNewOutputBytes),
2496
- minFreeDiskBytes: Math.max(allocation.minFreeDiskBytes, input.bounds.minFreeDiskBytes),
2497
- };
2498
- const priorBaselines = predecessorChain.flatMap((value) => value.baseline === undefined ? [] : [value.baseline]);
2499
- const prior = priorBaselines[0];
2500
- if (created && record !== undefined) {
2501
- record.allocation = allocation;
2502
- if (prior !== undefined) {
2503
- record.baseline = prior;
2504
- baseline = {
2505
- roots: prior.roots,
2506
- files: new Map(prior.files),
2507
- links: new Map(prior.links),
2508
- baselineId: prior.baselineId,
2509
- };
2510
- for (const retained of [...predecessorChain, record])
2511
- for (const [file, size] of retained.bootstrapFiles)
2512
- baseline.files.set(file, Math.max(baseline.files.get(file) ?? 0, size));
2513
- }
2514
- bootstrapCharge = previousBootstrap + record.bootstrapBytes;
2515
- }
2516
- if (allocations.some((value) => digestValue(value.outputRoots) !== digestValue(allocation.outputRoots))) {
2517
- accountingFailure = 'Source-phase retained original output roots disagree.';
2518
- throw new DeliveryError(accountingFailure);
2519
- }
2520
- if (input.bounds.maxNewOutputBytes > allocation.maxNewOutputBytes ||
2521
- input.bounds.maxAggregateRssBytes > allocation.maxAggregateRssBytes ||
2522
- input.bounds.minFreeDiskBytes < allocation.minFreeDiskBytes ||
2523
- digestValue(input.bounds.outputRoots) !== digestValue(allocation.outputRoots))
2524
- throw new DeliveryError('Source-phase reconciliation cannot increase its original resource allowance.');
2525
- if (failed.length > 0 &&
2526
- (previous === undefined ||
2527
- !predecessorChain.includes(previous) ||
2528
- input.reconciliation?.authorizationDigest !== input.authorization.digest))
2529
- throw new DeliveryError('A failed source phase requires exact authorized retained-output reconciliation.');
2530
- if (input.reconciliation !== undefined && (previous === undefined || !predecessorChain.includes(previous)))
2531
- throw new DeliveryError('Source-phase reconciliation does not name its exact terminal predecessor.');
2532
- if (prior !== undefined &&
2533
- (priorBaselines.some((value) => value.baselineId !== prior.baselineId) ||
2534
- input.reconciliation?.baselineId !== prior.baselineId ||
2535
- digestValue(prior.roots) !== digestValue(roots)))
2536
- throw new DeliveryError('Source-phase reconciliation cannot replace its original output baseline.');
2537
- for (const retained of predecessorChain.filter((value) => value.status === 'failed-quiescent')) {
2538
- const old = retained.binding;
2539
- if (old === undefined ||
2540
- digestValue(old.controller) !== digestValue(input.controller) ||
2541
- digestValue(old.source) !== digestValue(input.source) ||
2542
- old.repoRoot !== root ||
2543
- old.issueNumber !== input.issueNumber ||
2544
- old.rowDigest !== input.rowDigest ||
2545
- old.identity !== input.identity ||
2546
- old.inputs.some((artifact) => !input.inputs.some((current) => digestValue(current) === digestValue(artifact))))
2547
- throw new DeliveryError('Source-phase reconciliation requires compatible source/runtime and retained frozen inputs.');
2548
- for (const artifact of [old.caller, old.authorization, ...old.inputs])
2549
- assertArtifact(artifact);
2550
- }
2551
- if (predecessorChain.some((retained) => retained.retainedArtifacts?.some((artifact) => digestValue(sourceFile(artifact.path)) !== digestValue(artifact))))
2552
- throw new DeliveryError('Source-phase retained output artifact identity changed before reconciliation.');
2553
- await validate(!created);
2554
- const executionProducer = producerDigest();
2555
- if (predecessorChain.some((value) => value.status === 'failed-quiescent' &&
2556
- (value.producerDigest !== executionProducer || digestValue(value.actor) !== digestValue(actor))))
2557
- throw new DeliveryError('Source-phase reconciliation requires its original authenticated actor and producer.');
2558
- if (!created) {
2559
- record = readRecord(path);
2560
- if (record.status !== 'complete' ||
2561
- record.bindingDigest !== phaseId ||
2562
- record.producerDigest !== executionProducer ||
2563
- record.baseline === undefined ||
2564
- record.result === undefined)
2565
- throw new DeliveryError('Existing source phase is incomplete or belongs to another producer.');
2566
- if (digestValue(actor) !== digestValue(record.actor) ||
2567
- digestValue(await sourceState(true)) !== digestValue(record.result.source) ||
2568
- record.result.artifacts.some((artifact) => digestValue(sourceFile(artifact.path)) !== digestValue(artifact)))
2569
- throw new DeliveryError('Completed source-phase source or artifacts changed.');
2570
- reused = true;
2571
- return;
2572
- }
2573
- validated = true;
2574
- if (record === undefined)
2575
- throw new DeliveryError('Source phase lacks preparation intent.');
2576
- record.binding = binding;
2577
- record.producerDigest = executionProducer;
2578
- record.actor = actor;
2579
- await withOutputObservationGate(row.path, true, async (gate) => {
2580
- const gatePath = gate === undefined ? undefined : join(gate.directory, 'gate.json');
2581
- if (gatePath !== undefined) {
2582
- const gateBytes = lstatSync(gatePath).size;
2583
- record.bootstrapBytes += gateBytes;
2584
- record.bootstrapFiles.push([gatePath, gateBytes]);
2585
- }
2586
- bootstrapCharge = previousBootstrap + record.bootstrapBytes;
2587
- const links = new Map();
2588
- const files = prior === undefined
2589
- ? await withOutputGateLock(gate, 'scan', () => scanOutputRoots(roots, links), combined)
2590
- : new Map(prior.files);
2591
- if (prior !== undefined)
2592
- for (const [name, alias] of prior.links)
2593
- links.set(name, alias);
2594
- const content = { roots, files: [...files], links: [...links] };
2595
- const persistedBaseline = prior ?? { ...content, baselineId: digestValue(content) };
2596
- baseline = {
2597
- roots,
2598
- files,
2599
- links,
2600
- baselineId: persistedBaseline.baselineId,
2601
- ...(gate === undefined ? {} : { gate }),
2602
- };
2603
- record.baseline = persistedBaseline;
2604
- for (const retained of [...predecessorChain, record])
2605
- for (const [file, size] of retained.bootstrapFiles)
2606
- baseline.files.set(file, Math.max(baseline.files.get(file) ?? 0, size));
2607
- record.status = 'intent';
2608
- persist();
2609
- await observe();
2610
- let callbackFailure;
2611
- let callbackRejected = false;
2612
- const run = (index) => {
2613
- if (expired)
2614
- return Promise.reject(new DeliveryError('Source-phase command capability has expired.'));
2615
- if (!Number.isSafeInteger(index) ||
2616
- index !== record.nextCommandIndex ||
2617
- attempted.has(index) ||
2618
- active !== undefined ||
2619
- index >= input.commands.length) {
2620
- protocolFailure = 'Source-phase commands must be ordered, single-use and awaited.';
2621
- cancelled.abort(new DeliveryError(protocolFailure));
2622
- return Promise.reject(new DeliveryError(protocolFailure));
2623
- }
2624
- attempted.add(index);
2625
- const command = input.commands[index];
2626
- active = (async () => {
2627
- let commandCaptured = 0;
2628
- try {
2629
- await validate(true);
2630
- await observe();
2631
- writer.assertQuiescent();
2632
- startedCommand = true;
2633
- const output = await runStageCommand(command.cwd, command.argv, combined, (bytes, sample, reason) => reportVerificationProgress({
2634
- state: 'running',
2635
- stageId: 'source-phase',
2636
- completedStages: index,
2637
- remainingStages: input.commands.length - index,
2638
- reusedStages: 0,
2639
- elapsedMs: Date.now() - started,
2640
- capturedOutputBytes: bytes,
2641
- ...(sample === undefined ? {} : { sampledNewOutputBytes: sample.newOutputBytes }),
2642
- ...(reason === undefined ? {} : { reason }),
2643
- }), { ...input.bounds, maxNewOutputBytes: input.bounds.maxNewOutputBytes - bootstrapCharge - captured }, baseline, undefined, writer, {
2644
- environment,
2645
- onCaptured: (bytes) => {
2646
- commandCaptured = bytes;
2647
- },
2648
- onCleanupFailure: (reason) => {
2649
- cleanupFailure = reason;
2650
- },
2651
- });
2652
- record.commands.push({
2653
- index,
2654
- outputDigest: digestBytes(output),
2655
- outputBytes: output.length,
2656
- status: 'complete',
2657
- });
2658
- record.nextCommandIndex += 1;
2659
- return output;
2660
- }
2661
- catch (error) {
2662
- commandFailure = message(error);
2663
- record.commands.push({ index, outputDigest: null, outputBytes: commandCaptured, status: 'failed' });
2664
- throw error;
2665
- }
2666
- finally {
2667
- captured += commandCaptured;
2668
- record.capturedBytes += commandCaptured;
2669
- active = undefined;
2670
- persist();
2671
- }
2672
- })();
2673
- return active;
2674
- };
2675
- entered = true;
2676
- try {
2677
- if (actor === undefined)
2678
- throw new DeliveryError('Source-phase authenticated author is unavailable.');
2679
- const source = await sourceState();
2680
- await operation(Object.freeze({
2681
- phaseId,
2682
- signal: combined,
2683
- source: Object.freeze({
2684
- ...source,
2685
- dirty: Object.freeze(source.dirty.map((entry) => Object.freeze(entry))),
2686
- }),
2687
- controller: Object.freeze({ ...input.controller }),
2688
- actor: Object.freeze({ ...actor }),
2689
- inputs: Object.freeze([input.caller, input.authorization, ...input.inputs].map((artifact) => Object.freeze({ ...artifact }))),
2690
- run,
2691
- }));
2692
- }
2693
- catch (error) {
2694
- callbackRejected = true;
2695
- callbackFailure = error;
2696
- }
2697
- expired = true;
2698
- if (active !== undefined) {
2699
- protocolFailure = 'Source-phase callback settled with an unawaited command.';
2700
- cancelled.abort(new DeliveryError(protocolFailure));
2701
- await active.catch(() => undefined);
2702
- }
2703
- if (callbackRejected)
2704
- throw callbackFailure;
2705
- if (protocolFailure !== undefined)
2706
- throw new DeliveryError(protocolFailure);
2707
- if (commandFailure !== undefined)
2708
- throw new DeliveryError(commandFailure);
2709
- if (combined.aborted)
2710
- throw new DeliveryError('Source phase cancelled.');
2711
- if (record.nextCommandIndex !== input.commands.length)
2712
- throw new DeliveryError('Source-phase callback did not complete its frozen graph.');
2713
- await validate(true);
2714
- finalSource = await sourceState(true);
2715
- if (input.source.effect.kind === 'commitOnce' && finalSource.head === input.source.head)
2716
- throw new DeliveryError('Source phase did not publish its required commit.');
2717
- artifacts = input.completionArtifacts.map(sourceFile);
2718
- writer.assertQuiescent();
2719
- await observe();
2720
- }).finally(() => {
2721
- if (baseline !== undefined)
2722
- delete baseline.gate;
2723
- });
2724
- }
2725
- catch (error) {
2726
- operationFailure = message(error);
2727
- }
2728
- finally {
2729
- expired = true;
2730
- if (active !== undefined) {
2731
- cancelled.abort(new DeliveryError('Source phase is releasing its command capability.'));
2732
- await active.catch((error) => {
2733
- operationFailure ??= message(error);
2734
- });
2735
- }
2736
- if (created && baseline !== undefined) {
2737
- try {
2738
- await observe(true);
2739
- }
2740
- catch (error) {
2741
- accountingFailure = message(error);
2742
- }
2743
- }
2744
- }
2745
- }, {
2746
- repoRoot: root,
2747
- worktreePath: row.path,
2748
- writerId,
2749
- beforeClaim: ({ previousBytes }) => {
2750
- if (previousBytes !== undefined)
2751
- throw new DeliveryError('Source phase requires an absent writer; it never recovers a prior command.');
2752
- },
2753
- recordClaim: (bytes) => {
2754
- ensurePrivateDirectoryDurably(directory);
2755
- if (existsSync(path))
2756
- return;
2757
- created = true;
2758
- writerBootstrap = bytes.length;
2759
- const content = {
2760
- schemaVersion: 'ai-delivery.source-phase@1',
2761
- phaseId,
2762
- bindingDigest: phaseId,
2763
- authorizationDigest: input.authorization.digest,
2764
- worktreeDigest: subject,
2765
- status: 'preparing',
2766
- writerId,
2767
- bootstrapBytes: bytes.length,
2768
- allocation: input.bounds,
2769
- capturedBytes: 0,
2770
- nextCommandIndex: 0,
2771
- owner: JSON.parse(bytes.toString('utf8')).owner,
2772
- bootstrapFiles: [],
2773
- commands: [],
2774
- retainedPredecessors: [],
2775
- claimDigest: digestBytes(bytes),
2776
- ...(input.reconciliation === undefined ? {} : { reconciliation: input.reconciliation }),
2777
- };
2778
- record = { ...content, recordId: digestValue(content) };
2779
- persist();
2780
- record.preparationArtifact = sourceFile(path);
2781
- record.bootstrapFiles.push([path, lstatSync(path).size]);
2782
- for (let index = 0; index < 4; index++) {
2783
- const size = Buffer.byteLength(`${JSON.stringify(record, null, 2)}\n`);
2784
- record.bootstrapFiles[0] = [path, size];
2785
- record.bootstrapBytes = writerBootstrap + size;
2786
- }
2787
- persist();
2788
- },
2789
- afterClaim: () => {
2790
- if (record !== undefined && created)
2791
- record.writerArtifact = sourceFile(writerPath);
2792
- },
2793
- recordRelease: (bytes) => {
2794
- if (record !== undefined && !reused)
2795
- record.releaseDigest = digestBytes(bytes);
2796
- },
2797
- afterRelease: () => {
2798
- writerReleased = true;
2799
- },
2800
- onLockReleaseError: (error) => {
2801
- lockFailure = message(error);
2802
- },
2803
- onLockCompromised: (error) => {
2804
- lockFailure = message(error);
2805
- cancelled.abort(error);
2806
- },
2807
- }, common, true);
2808
- }
2809
- catch (error) {
2810
- releaseFailure = message(error);
2811
- }
2812
- if (reused &&
2813
- record !== undefined &&
2814
- writerReleased &&
2815
- lockFailure === undefined &&
2816
- releaseFailure === undefined &&
2817
- operationFailure === undefined)
2818
- return sourceReceipt(record);
2819
- if (record === undefined || !created)
2820
- throw new DeliveryError(operationFailure ?? releaseFailure ?? 'Source-phase ownership could not be established.');
2821
- const failures = {
2822
- ...(operationFailure === undefined ? {} : { operation: operationFailure }),
2823
- ...(accountingFailure === undefined ? {} : { accounting: accountingFailure }),
2824
- ...(cleanupFailure === undefined ? {} : { cleanup: cleanupFailure }),
2825
- ...(writerReleased && releaseFailure === undefined
2826
- ? {}
2827
- : { writerRelease: releaseFailure ?? 'Writer absence was not confirmed.' }),
2828
- ...(lockFailure === undefined ? {} : { lockRelease: lockFailure }),
2829
- };
2830
- const quiescent = writerReleased && releaseFailure === undefined && lockFailure === undefined && cleanupFailure === undefined;
2831
- let unchanged = false;
2832
- if (validated) {
2833
- try {
2834
- await validate(finalSource !== undefined);
2835
- unchanged = (await sourceState(finalSource !== undefined)).head === input.source.head;
2836
- if (finalSource !== undefined &&
2837
- (existsSync(writerPath) ||
2838
- artifacts.some((artifact) => digestValue(sourceFile(artifact.path)) !== digestValue(artifact))))
2839
- throw new DeliveryError('Source-phase writer absence or completion artifact changed before sealing.');
2840
- }
2841
- catch (error) {
2842
- unchanged = false;
2843
- if (finalSource !== undefined)
2844
- failures.operation ??= message(error);
2845
- }
2846
- }
2847
- const successful = Object.keys(failures).length === 0 && finalSource !== undefined;
2848
- record.status = successful
2849
- ? 'complete'
2850
- : !entered && !startedCommand && quiescent && accountingFailure === undefined
2851
- ? 'rejected-before-work'
2852
- : quiescent && unchanged && accountingFailure === undefined && baseline !== undefined
2853
- ? 'failed-quiescent'
2854
- : 'unresolved';
2855
- if (successful && finalSource !== undefined)
2856
- record.result = {
2857
- source: finalSource,
2858
- artifacts,
2859
- newOutputBytes: newBytes,
2860
- writerReleased: true,
2861
- lockReleased: true,
2862
- };
2863
- else
2864
- record.failure = failures;
2865
- if (record.status === 'failed-quiescent' && baseline !== undefined) {
2866
- try {
2867
- const files = scanOutputRoots(baseline.roots, new Map());
2868
- record.retainedArtifacts = [...files]
2869
- .filter(([file, bytes]) => file !== path && bytes > (baseline.files.get(file) ?? 0))
2870
- .map(([file]) => sourceFile(file));
2871
- }
2872
- catch (error) {
2873
- record.status = 'unresolved';
2874
- record.failure = { ...failures, accounting: message(error) };
2875
- }
2876
- }
2877
- if (baseline !== undefined) {
2878
- try {
2879
- await observe(true);
2880
- const originalSize = baseline.files.get(path) ?? 0;
2881
- const currentGrowth = Math.max(0, lstatSync(path).size - originalSize);
2882
- const observed = newBytes;
2883
- let projected = observed;
2884
- for (let index = 0; index < 4; index++) {
2885
- if (record.result !== undefined)
2886
- record.result.newOutputBytes = projected;
2887
- const { recordId: _recordId, ...content } = record;
2888
- record.recordId = digestValue(content);
2889
- projected =
2890
- observed -
2891
- currentGrowth +
2892
- Math.max(0, Buffer.byteLength(`${JSON.stringify(record, null, 2)}\n`) - originalSize);
2893
- }
2894
- if (projected > accountingBounds.maxNewOutputBytes)
2895
- throw new DeliveryError('Source-phase final receipt exceeds its original output allowance.');
2896
- if (record.result !== undefined)
2897
- record.result.newOutputBytes = projected;
2898
- }
2899
- catch (error) {
2900
- record.status = 'unresolved';
2901
- delete record.result;
2902
- record.failure = { ...failures, accounting: message(error) };
2903
- }
2904
- }
2905
- else {
2906
- for (let index = 0; index < 4; index++) {
2907
- const size = Buffer.byteLength(`${JSON.stringify(record, null, 2)}\n`);
2908
- record.bootstrapFiles[0] = [path, size];
2909
- record.bootstrapBytes =
2910
- writerBootstrap + size + record.bootstrapFiles.slice(1).reduce((sum, [, bytes]) => sum + bytes, 0);
2911
- }
2912
- if (previousBootstrap + record.bootstrapBytes + captured > accountingBounds.maxNewOutputBytes) {
2913
- record.status = 'unresolved';
2914
- record.failure = {
2915
- ...failures,
2916
- accounting: 'Retained rejected bootstrap exceeded the original output allowance.',
2917
- };
2918
- for (let index = 0; index < 4; index++) {
2919
- const size = Buffer.byteLength(`${JSON.stringify(record, null, 2)}\n`);
2920
- record.bootstrapFiles[0] = [path, size];
2921
- record.bootstrapBytes =
2922
- writerBootstrap + size + record.bootstrapFiles.slice(1).reduce((sum, [, bytes]) => sum + bytes, 0);
2923
- }
2924
- }
2925
- }
2926
- persist();
2927
- if (record.status !== 'complete')
2928
- throw new DeliveryError(`Source phase ${record.status}: ${operationFailure ?? accountingFailure ?? releaseFailure ?? lockFailure ?? failures.operation ?? 'postconditions failed'}.`, path);
2929
- return sourceReceipt(record);
2930
- }
2931
1604
  const RuntimeOutputLedgerSchema = z
2932
1605
  .strictObject({
2933
1606
  schemaVersion: z.literal('ai-delivery.runtime-output@1'),