@aviaratech/ai-delivery 0.3.35 → 0.3.36
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.
- package/CONTRIBUTING.md +12 -206
- package/README.md +57 -554
- package/dist/agent.d.ts +0 -2
- package/dist/agent.js +76 -16
- package/dist/agent.js.map +7 -1
- package/dist/agentReadiness.test.js +73 -67
- package/dist/agentReadiness.test.js.map +7 -1
- package/dist/boardReconcile.test.js +1651 -1590
- package/dist/boardReconcile.test.js.map +7 -1
- package/dist/build.test.js +130 -0
- package/dist/build.test.js.map +7 -0
- package/dist/callerErrors.test.js +105 -0
- package/dist/callerErrors.test.js.map +7 -0
- package/dist/cli.js +402 -515
- package/dist/cli.js.map +7 -1
- package/dist/cliResult.d.ts +2 -2
- package/dist/cliResult.js +42 -45
- package/dist/cliResult.js.map +7 -1
- package/dist/cliResult.test.js +424 -369
- package/dist/cliResult.test.js.map +7 -1
- package/dist/config/deliveryConfig.d.ts +288 -14
- package/dist/config/deliveryConfig.js +472 -390
- package/dist/config/deliveryConfig.js.map +7 -1
- package/dist/config/deliveryConfig.test.js +773 -649
- package/dist/config/deliveryConfig.test.js.map +7 -1
- package/dist/contributorChecks.test.js +1694 -916
- package/dist/contributorChecks.test.js.map +7 -1
- package/dist/currentConsumer.test.js +819 -737
- package/dist/currentConsumer.test.js.map +7 -1
- package/dist/currentTrackingScenario.test.js +499 -479
- package/dist/currentTrackingScenario.test.js.map +7 -1
- package/dist/delivery/common.js +160 -172
- package/dist/delivery/common.js.map +7 -1
- package/dist/delivery/delivery.test.js +509 -431
- package/dist/delivery/delivery.test.js.map +7 -1
- package/dist/delivery/evidence.d.ts +2 -2
- package/dist/delivery/evidence.js +133 -120
- package/dist/delivery/evidence.js.map +7 -1
- package/dist/delivery/index.js +7 -2
- package/dist/delivery/index.js.map +7 -1
- package/dist/delivery/legacy.js +65 -5
- package/dist/delivery/legacy.js.map +7 -1
- package/dist/delivery/policy.d.ts +10 -10
- package/dist/delivery/policy.js +211 -238
- package/dist/delivery/policy.js.map +7 -1
- package/dist/delivery/stage.d.ts +18 -18
- package/dist/delivery/stage.js +220 -235
- package/dist/delivery/stage.js.map +7 -1
- package/dist/deliveryBoard.d.ts +74 -0
- package/dist/deliveryBoard.js +644 -0
- package/dist/deliveryBoard.js.map +7 -0
- package/dist/deliveryBoard.test.js +649 -0
- package/dist/deliveryBoard.test.js.map +7 -0
- package/dist/deliveryHealth.test.js +179 -155
- package/dist/deliveryHealth.test.js.map +7 -1
- package/dist/dependencyCompatibility.test.js +154 -140
- package/dist/dependencyCompatibility.test.js.map +7 -1
- package/dist/directoryIndependent.test.js +417 -383
- package/dist/directoryIndependent.test.js.map +7 -1
- package/dist/dispatch.d.ts +16 -11
- package/dist/dispatch.js +329 -353
- package/dist/dispatch.js.map +7 -1
- package/dist/errors.d.ts +3 -3
- package/dist/errors.js +103 -96
- package/dist/errors.js.map +7 -1
- package/dist/fixtures/deliveryBoardReplay.d.ts +56 -0
- package/dist/fixtures/deliveryBoardReplay.js +617 -0
- package/dist/fixtures/deliveryBoardReplay.js.map +7 -0
- package/dist/fixtures/discovery.d.ts +59 -19
- package/dist/fixtures/discovery.js +96 -90
- package/dist/fixtures/discovery.js.map +7 -1
- package/dist/fixtures/inertEntrypointChild.js +57 -56
- package/dist/fixtures/inertEntrypointChild.js.map +7 -1
- package/dist/fixtures/inertEntrypoints.d.ts +1 -1
- package/dist/fixtures/inertEntrypoints.js +321 -276
- package/dist/fixtures/inertEntrypoints.js.map +7 -1
- package/dist/fixtures/inertTarget.d.ts +78 -7
- package/dist/fixtures/inertTarget.js +769 -691
- package/dist/fixtures/inertTarget.js.map +7 -1
- package/dist/fixtures/issue63.d.ts +4 -3
- package/dist/fixtures/issue63.js +260 -274
- package/dist/fixtures/issue63.js.map +7 -1
- package/dist/fixtures/issueProjectItems.d.ts +20 -0
- package/dist/fixtures/issueProjectItems.js +15 -0
- package/dist/fixtures/issueProjectItems.js.map +7 -0
- package/dist/fixtures/readView.d.ts +120 -0
- package/dist/fixtures/readView.js +172 -0
- package/dist/fixtures/readView.js.map +7 -0
- package/dist/fixtures/recordedGitHubFlows.d.ts +120 -0
- package/dist/fixtures/recordedGitHubFlows.js +109 -0
- package/dist/fixtures/recordedGitHubFlows.js.map +7 -0
- package/dist/genericCompatibility.test.js +64 -55
- package/dist/genericCompatibility.test.js.map +7 -1
- package/dist/git.js +73 -67
- package/dist/git.js.map +7 -1
- package/dist/gitProcess.d.ts +1 -1
- package/dist/gitProcess.js +58 -53
- package/dist/gitProcess.js.map +7 -1
- package/dist/github/client.d.ts +2 -2
- package/dist/github/client.js +484 -379
- package/dist/github/client.js.map +7 -1
- package/dist/github/commandIdentityPolicy.js +44 -52
- package/dist/github/commandIdentityPolicy.js.map +7 -1
- package/dist/github/discovery.d.ts +1 -0
- package/dist/github/discovery.js +197 -215
- package/dist/github/discovery.js.map +7 -1
- package/dist/github/discovery.test.js +223 -177
- package/dist/github/discovery.test.js.map +7 -1
- package/dist/github/issueHistory.d.ts +2 -2
- package/dist/github/issueHistory.js +117 -125
- package/dist/github/issueHistory.js.map +7 -1
- package/dist/github/machineAuth.d.ts +1 -1
- package/dist/github/machineAuth.js +126 -117
- package/dist/github/machineAuth.js.map +7 -1
- package/dist/github/machineAuth.test.js +755 -639
- package/dist/github/machineAuth.test.js.map +7 -1
- package/dist/github/nativeIssueMetadata.js +286 -273
- package/dist/github/nativeIssueMetadata.js.map +7 -1
- package/dist/github/projectDelivery.d.ts +18 -2
- package/dist/github/projectDelivery.js +615 -557
- package/dist/github/projectDelivery.js.map +7 -1
- package/dist/github/relationships.js +433 -389
- package/dist/github/relationships.js.map +7 -1
- package/dist/github/repo.d.ts +1 -0
- package/dist/github/repo.js +123 -96
- package/dist/github/repo.js.map +7 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +7 -1
- package/dist/issue.d.ts +40 -9
- package/dist/issue.js +2102 -1742
- package/dist/issue.js.map +7 -1
- package/dist/issue63History.test.js +40 -42
- package/dist/issue63History.test.js.map +7 -1
- package/dist/issue63Routes.test.js +154 -143
- package/dist/issue63Routes.test.js.map +7 -1
- package/dist/issueBatchUpdate.test.js +989 -885
- package/dist/issueBatchUpdate.test.js.map +7 -1
- package/dist/issueBlockerGuard.test.js +262 -226
- package/dist/issueBlockerGuard.test.js.map +7 -1
- package/dist/issueContract.d.ts +23 -4
- package/dist/issueContract.js +416 -395
- package/dist/issueContract.js.map +7 -1
- package/dist/issueContract.test.d.ts +4 -3
- package/dist/issueContract.test.js +358 -321
- package/dist/issueContract.test.js.map +7 -1
- package/dist/issueDates.test.js +235 -233
- package/dist/issueDates.test.js.map +7 -1
- package/dist/issueInfoReadback.test.js +304 -190
- package/dist/issueInfoReadback.test.js.map +7 -1
- package/dist/issueIntake.test.js +1945 -1732
- package/dist/issueIntake.test.js.map +7 -1
- package/dist/issueJournal.d.ts +40 -19
- package/dist/issueJournal.js +229 -138
- package/dist/issueJournal.js.map +7 -1
- package/dist/issueJournal.test.js +605 -422
- package/dist/issueJournal.test.js.map +7 -1
- package/dist/issueRollup.test.d.ts +1 -0
- package/dist/issueRollup.test.js +476 -0
- package/dist/issueRollup.test.js.map +7 -0
- package/dist/issueTracking.test.js +1059 -989
- package/dist/issueTracking.test.js.map +7 -1
- package/dist/issueWriteRecovery.test.d.ts +1 -0
- package/dist/issueWriteRecovery.test.js +260 -0
- package/dist/issueWriteRecovery.test.js.map +7 -0
- package/dist/lifecycle.test.js +112 -441
- package/dist/lifecycle.test.js.map +7 -1
- package/dist/logger.js +80 -74
- package/dist/logger.js.map +7 -1
- package/dist/mcp/index.js +116 -94
- package/dist/mcp/index.js.map +7 -1
- package/dist/mcp/tools.d.ts +264 -286
- package/dist/mcp/tools.js +267 -340
- package/dist/mcp/tools.js.map +7 -1
- package/dist/pluginAuthProbe.js +63 -52
- package/dist/pluginAuthProbe.js.map +7 -1
- package/dist/pluginAuthProbe.test.js +85 -62
- package/dist/pluginAuthProbe.test.js.map +7 -1
- package/dist/pluginCredentials.test.js +282 -259
- package/dist/pluginCredentials.test.js.map +7 -1
- package/dist/pluginDoctor.test.js +653 -588
- package/dist/pluginDoctor.test.js.map +7 -1
- package/dist/pluginInstaller.d.ts +7 -5
- package/dist/pluginInstaller.js +1173 -1229
- package/dist/pluginInstaller.js.map +7 -1
- package/dist/pluginInstaller.test.js +1842 -1423
- package/dist/pluginInstaller.test.js.map +7 -1
- package/dist/pluginPackaging.test.js +460 -409
- package/dist/pluginPackaging.test.js.map +7 -1
- package/dist/pr.d.ts +132 -94
- package/dist/pr.js +1521 -1323
- package/dist/pr.js.map +7 -1
- package/dist/pr.test.js +1678 -632
- package/dist/pr.test.js.map +7 -1
- package/dist/prAssociation.test.js +2419 -1788
- package/dist/prAssociation.test.js.map +7 -1
- package/dist/prDispatch.test.js +150 -89
- package/dist/prDispatch.test.js.map +7 -1
- package/dist/readView.d.ts +183 -0
- package/dist/readView.js +217 -0
- package/dist/readView.js.map +7 -0
- package/dist/readView.test.d.ts +1 -0
- package/dist/readView.test.js +119 -0
- package/dist/readView.test.js.map +7 -0
- package/dist/releaseReconciliation.test.js +267 -288
- package/dist/releaseReconciliation.test.js.map +7 -1
- package/dist/releaseWorkflow.test.js +2493 -422
- package/dist/releaseWorkflow.test.js.map +7 -1
- package/dist/review.d.ts +738 -2
- package/dist/review.js +601 -348
- package/dist/review.js.map +7 -1
- package/dist/review.test.js +1218 -812
- package/dist/review.test.js.map +7 -1
- package/dist/reviewSubmit.test.d.ts +1 -0
- package/dist/reviewSubmit.test.js +747 -0
- package/dist/reviewSubmit.test.js.map +7 -0
- package/dist/services/agentReadinessService.js +42 -37
- package/dist/services/agentReadinessService.js.map +7 -1
- package/dist/services/blockerGuardService.js +188 -188
- package/dist/services/blockerGuardService.js.map +7 -1
- package/dist/services/boardReconcileService.d.ts +125 -125
- package/dist/services/boardReconcileService.js +1295 -1421
- package/dist/services/boardReconcileService.js.map +7 -1
- package/dist/services/deliveryAdmission.js +131 -154
- package/dist/services/deliveryAdmission.js.map +7 -1
- package/dist/services/deliveryHealthService.js +197 -199
- package/dist/services/deliveryHealthService.js.map +7 -1
- package/dist/services/legacyIssueMigration.js +263 -277
- package/dist/services/legacyIssueMigration.js.map +7 -1
- package/dist/services/worktreeRegistry.d.ts +27 -119
- package/dist/services/worktreeRegistry.js +765 -1182
- package/dist/services/worktreeRegistry.js.map +7 -1
- package/dist/stagedChecks.test.js +396 -194
- package/dist/stagedChecks.test.js.map +7 -1
- package/dist/start.test.js +99 -95
- package/dist/start.test.js.map +7 -1
- package/dist/stdoutRegression.test.js +353 -352
- package/dist/stdoutRegression.test.js.map +7 -1
- package/dist/targetPolicyDiscovery.test.js +141 -143
- package/dist/targetPolicyDiscovery.test.js.map +7 -1
- package/dist/targetPolicyEntrypoints.test.js +308 -269
- package/dist/targetPolicyEntrypoints.test.js.map +7 -1
- package/dist/targetPolicyLocal.test.js +580 -1051
- package/dist/targetPolicyLocal.test.js.map +7 -1
- package/dist/targetPolicyRoutes.test.js +305 -281
- package/dist/targetPolicyRoutes.test.js.map +7 -1
- package/dist/targetRepositoryExecution.test.d.ts +1 -0
- package/dist/targetRepositoryExecution.test.js +463 -0
- package/dist/targetRepositoryExecution.test.js.map +7 -0
- package/dist/terminalMessages.js +41 -35
- package/dist/terminalMessages.js.map +7 -1
- package/dist/toolOutput.d.ts +2 -0
- package/dist/toolOutput.js +36 -0
- package/dist/toolOutput.js.map +7 -0
- package/dist/toolOutput.test.d.ts +1 -0
- package/dist/toolOutput.test.js +240 -0
- package/dist/toolOutput.test.js.map +7 -0
- package/dist/utils/atomicJson.js +84 -76
- package/dist/utils/atomicJson.js.map +7 -1
- package/dist/utils/filesystem.js +15 -18
- package/dist/utils/filesystem.js.map +7 -1
- package/dist/utils/lockfile.js +68 -71
- package/dist/utils/lockfile.js.map +7 -1
- package/dist/verification.d.ts +1 -19
- package/dist/verification.js +1020 -1939
- package/dist/verification.js.map +7 -1
- package/dist/verificationGate.test.js +127 -117
- package/dist/verificationGate.test.js.map +7 -1
- package/dist/version.js +23 -24
- package/dist/version.js.map +7 -1
- package/dist/worktree.d.ts +3 -15
- package/dist/worktree.js +97 -177
- package/dist/worktree.js.map +7 -1
- package/package.json +9 -8
- package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
- package/plugins/ai-delivery/README.md +47 -156
- package/plugins/ai-delivery/plugin.json +1 -1
- package/plugins/ai-delivery/runtime/dist/THIRD-PARTY-NOTICES.md +238 -44
- package/plugins/ai-delivery/runtime/dist/cli.js +358 -115
- package/plugins/ai-delivery/runtime/package.json +1 -1
- package/plugins/ai-delivery/skills/intake-create/SKILL.md +14 -78
- package/plugins/ai-delivery/skills/pr-handoff/SKILL.md +35 -36
- package/plugins/ai-delivery/skills/worktree-lifecycle/SKILL.md +14 -15
- package/dist/investigationCompletion.test.js +0 -728
- package/dist/investigationCompletion.test.js.map +0 -1
- package/dist/setup.d.ts +0 -60
- package/dist/setup.js +0 -585
- package/dist/setup.js.map +0 -1
- package/dist/setup.test.js +0 -3329
- package/dist/setup.test.js.map +0 -1
- package/dist/worktreeTransition.d.ts +0 -211
- package/dist/worktreeTransition.js +0 -1037
- package/dist/worktreeTransition.js.map +0 -1
- package/dist/worktreeTransition.test.js +0 -1191
- package/dist/worktreeTransition.test.js.map +0 -1
- /package/dist/{investigationCompletion.test.d.ts → build.test.d.ts} +0 -0
- /package/dist/{setup.test.d.ts → callerErrors.test.d.ts} +0 -0
- /package/dist/{worktreeTransition.test.d.ts → deliveryBoard.test.d.ts} +0 -0
package/dist/verification.js
CHANGED
|
@@ -1,2043 +1,1124 @@
|
|
|
1
|
-
import { spawn, spawnSync } from
|
|
2
|
-
import { randomUUID } from
|
|
3
|
-
import { createRequire, findPackageJSON } from
|
|
4
|
-
import { types } from
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
.
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
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 {
|
|
23
|
+
digestBytes,
|
|
24
|
+
digestValue,
|
|
25
|
+
writeRepositoryCommandOutput
|
|
26
|
+
} from "./delivery/legacy.js";
|
|
27
|
+
import { DeliveryError } from "./errors.js";
|
|
28
|
+
import { gitCommonDir } from "./git.js";
|
|
29
|
+
import { writePrivateJsonFileAtomically } from "./utils/atomicJson.js";
|
|
30
|
+
const ResourceSummarySchema = z.strictObject({
|
|
31
|
+
bounds: z.strictObject({
|
|
32
|
+
maxAggregateRssBytes: z.number().int().positive().safe(),
|
|
33
|
+
maxNewOutputBytes: z.number().int().positive().safe().optional(),
|
|
34
|
+
minFreeDiskBytes: z.number().int().positive().safe(),
|
|
35
|
+
outputRoots: z.array(z.string().min(1)).min(1).optional()
|
|
36
|
+
}),
|
|
37
|
+
maxSampledAggregateRssBytes: z.number().int().nonnegative().safe().nullable(),
|
|
38
|
+
maxSampledNewOutputBytes: z.number().int().nonnegative().safe().nullable(),
|
|
39
|
+
minSampledFreeDiskBytes: z.number().int().nonnegative().safe().nullable(),
|
|
40
|
+
observation: z.literal("sampled"),
|
|
41
|
+
outputBaselineId: z.string().regex(/^sha256:[a-f0-9]{64}$/u).optional(),
|
|
42
|
+
processCoverage: z.literal("observed-processes-only"),
|
|
43
|
+
sampleCount: z.number().int().nonnegative().safe()
|
|
44
|
+
}).superRefine((value, ctx) => {
|
|
45
|
+
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))
|
|
46
|
+
ctx.addIssue({ code: "custom", message: "Resource samples do not satisfy their declared bounds." });
|
|
49
47
|
});
|
|
50
|
-
|
|
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';
|
|
48
|
+
const OUTPUT_GATE_ENV = "AI_DELIVERY_OUTPUT_OBSERVATION_GATE";
|
|
72
49
|
const GateOwnerSchema = z.strictObject({ pid: z.number().int().positive(), identity: z.string().min(1) });
|
|
73
50
|
const OutputGateSchema = z.strictObject({ directory: z.string().min(1), id: z.uuid(), owner: GateOwnerSchema });
|
|
74
51
|
const GateClaimSchema = z.strictObject({
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
52
|
+
gateId: z.uuid(),
|
|
53
|
+
id: z.uuid(),
|
|
54
|
+
kind: z.enum(["scan", "fixture"]),
|
|
55
|
+
owner: GateOwnerSchema
|
|
79
56
|
});
|
|
80
57
|
function gateOwner(snapshot = processSnapshot()) {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
return { pid: owner.pid, identity: owner.identity };
|
|
58
|
+
const owner = snapshot.get(process.pid);
|
|
59
|
+
if (!owner) throw new DeliveryError("Filesystem observation gate owner is unavailable.");
|
|
60
|
+
return { pid: owner.pid, identity: owner.identity };
|
|
85
61
|
}
|
|
86
62
|
function assertGateDirectory(path) {
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
63
|
+
const metadata = lstatSync(path);
|
|
64
|
+
if (!metadata.isDirectory() || (metadata.mode & 63) !== 0 || realpathSync(path) !== path)
|
|
65
|
+
throw new DeliveryError("Filesystem observation gate directory is invalid.");
|
|
90
66
|
}
|
|
91
67
|
function readOutputGate(value) {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
68
|
+
try {
|
|
69
|
+
const gate = OutputGateSchema.parse(JSON.parse(value));
|
|
70
|
+
assertOutputGate(gate);
|
|
71
|
+
return gate;
|
|
72
|
+
} catch (error) {
|
|
73
|
+
throw new DeliveryError(
|
|
74
|
+
"Filesystem observation gate capability is invalid or stale: " + (error instanceof Error ? error.message : String(error))
|
|
75
|
+
);
|
|
76
|
+
}
|
|
101
77
|
}
|
|
102
78
|
function gateOwnerAlive(owner, snapshot = processSnapshot()) {
|
|
103
|
-
|
|
104
|
-
|
|
79
|
+
const current = snapshot.get(owner.pid);
|
|
80
|
+
return current?.identity === owner.identity && !current.status.startsWith("Z");
|
|
105
81
|
}
|
|
106
82
|
function assertOutputGate(gate, abandoned = false) {
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
83
|
+
assertGateDirectory(gate.directory);
|
|
84
|
+
const manifest = OutputGateSchema.parse(
|
|
85
|
+
JSON.parse(assertPrivateFile(join(gate.directory, "gate.json")).toString("utf8"))
|
|
86
|
+
);
|
|
87
|
+
const snapshot = processSnapshot();
|
|
88
|
+
let actor = snapshot.get(process.pid);
|
|
89
|
+
const ancestors = /* @__PURE__ */ new Set();
|
|
90
|
+
while (actor && actor.pid !== gate.owner.pid && !ancestors.has(actor.pid)) {
|
|
91
|
+
ancestors.add(actor.pid);
|
|
92
|
+
actor = snapshot.get(actor.ppid);
|
|
93
|
+
}
|
|
94
|
+
if (digestValue(manifest) !== digestValue(gate) || (abandoned ? gateOwnerAlive(gate.owner, snapshot) : !gateOwnerAlive(gate.owner, snapshot) || actor?.identity !== gate.owner.identity))
|
|
95
|
+
throw new DeliveryError(
|
|
96
|
+
"Filesystem observation gate ownership changed, was abandoned or is not an inherited ancestor."
|
|
97
|
+
);
|
|
98
|
+
return snapshot;
|
|
122
99
|
}
|
|
123
100
|
function readGateClaim(gate, path) {
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
return claim;
|
|
101
|
+
const claim = GateClaimSchema.parse(JSON.parse(assertPrivateFile(path).toString("utf8")));
|
|
102
|
+
if (claim.gateId !== gate.id) throw new DeliveryError("Filesystem observation gate claim belongs to another run.");
|
|
103
|
+
return claim;
|
|
128
104
|
}
|
|
129
105
|
function gateScanRequests(gate, snapshot) {
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
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);
|
|
106
|
+
const directory = join(gate.directory, "requests");
|
|
107
|
+
assertGateDirectory(directory);
|
|
108
|
+
const requests = readdirSync(directory);
|
|
109
|
+
if (requests.length > 1024 || requests.some((name) => !/^[a-f0-9-]{36}\.json$/u.test(name)))
|
|
110
|
+
throw new DeliveryError("Filesystem observation gate scan requests are invalid.");
|
|
111
|
+
const live = [];
|
|
112
|
+
const currentSnapshot = snapshot ?? processSnapshot();
|
|
113
|
+
for (const name of requests) {
|
|
114
|
+
let claim;
|
|
115
|
+
try {
|
|
116
|
+
claim = readGateClaim(gate, join(directory, name));
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (error.code === "ENOENT") continue;
|
|
119
|
+
throw error;
|
|
150
120
|
}
|
|
151
|
-
|
|
121
|
+
if (claim.kind !== "scan" || name !== claim.id + ".json" || !gateOwnerAlive(claim.owner, currentSnapshot))
|
|
122
|
+
throw new DeliveryError("Filesystem observation gate scan request was abandoned.");
|
|
123
|
+
live.push(name);
|
|
124
|
+
}
|
|
125
|
+
return live;
|
|
152
126
|
}
|
|
153
127
|
function removeGateClaim(gate, path, claim) {
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
128
|
+
if (digestValue(readGateClaim(gate, path)) !== digestValue(claim))
|
|
129
|
+
throw new DeliveryError("Filesystem observation gate claim changed before release.");
|
|
130
|
+
unlinkSync(path);
|
|
157
131
|
}
|
|
158
132
|
async function withOutputGateLock(gate, kind, operation, signal) {
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
const
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
const
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
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 {
|
|
133
|
+
if (!gate) return operation();
|
|
134
|
+
const ownerSnapshot = assertOutputGate(gate);
|
|
135
|
+
const claim = { gateId: gate.id, id: randomUUID(), kind, owner: gateOwner(ownerSnapshot) };
|
|
136
|
+
const request = kind === "scan" ? join(gate.directory, "requests", claim.id + ".json") : void 0;
|
|
137
|
+
const lock = join(gate.directory, "held");
|
|
138
|
+
const holder = join(lock, "owner.json");
|
|
139
|
+
if (request) {
|
|
140
|
+
const staging = join(gate.directory, claim.id + ".pending");
|
|
141
|
+
writePrivateJsonFileAtomically(staging, claim);
|
|
142
|
+
renameSync(staging, request);
|
|
143
|
+
}
|
|
144
|
+
let acquired;
|
|
145
|
+
let incompleteSince;
|
|
146
|
+
let fixtureWait;
|
|
147
|
+
const release = () => {
|
|
148
|
+
if (!acquired) return;
|
|
149
|
+
const metadata = lstatSync(lock);
|
|
150
|
+
if (!metadata.isDirectory() || metadata.dev !== acquired.dev || metadata.ino !== acquired.ino)
|
|
151
|
+
throw new DeliveryError("Filesystem observation gate lock changed before release.");
|
|
152
|
+
if (readdirSync(lock).join(",") !== "owner.json")
|
|
153
|
+
throw new DeliveryError("Filesystem observation gate lock has unrelated metadata.");
|
|
154
|
+
removeGateClaim(gate, holder, claim);
|
|
155
|
+
rmdirSync(lock);
|
|
156
|
+
acquired = void 0;
|
|
157
|
+
};
|
|
158
|
+
try {
|
|
159
|
+
for (; ; ) {
|
|
160
|
+
if (signal?.aborted) throw new DeliveryError("Filesystem observation gate wait cancelled.");
|
|
161
|
+
const currentSnapshot = assertOutputGate(gate);
|
|
162
|
+
const requests = gateScanRequests(gate, currentSnapshot);
|
|
163
|
+
if (kind === "scan" || requests.length === 0) {
|
|
164
|
+
let created = false;
|
|
243
165
|
try {
|
|
244
|
-
|
|
166
|
+
mkdirSync(lock, { mode: 448 });
|
|
167
|
+
created = true;
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if (error.code !== "EEXIST") throw error;
|
|
245
170
|
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
171
|
+
if (created) {
|
|
172
|
+
const metadata = lstatSync(lock);
|
|
173
|
+
acquired = { dev: metadata.dev, ino: metadata.ino };
|
|
174
|
+
writePrivateJsonFileAtomically(holder, claim);
|
|
175
|
+
if (kind === "scan" || gateScanRequests(gate).length === 0) return await operation();
|
|
176
|
+
release();
|
|
249
177
|
}
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
throw new DeliveryError(
|
|
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
|
-
}
|
|
178
|
+
}
|
|
179
|
+
if (existsSync(lock)) {
|
|
180
|
+
try {
|
|
181
|
+
assertGateDirectory(lock);
|
|
182
|
+
const current = readGateClaim(gate, holder);
|
|
183
|
+
incompleteSince = void 0;
|
|
184
|
+
if (!gateOwnerAlive(current.owner))
|
|
185
|
+
throw new DeliveryError("Filesystem observation gate fixture or scanner was abandoned.");
|
|
186
|
+
if (kind === "scan" && current.kind === "fixture") {
|
|
187
|
+
if (fixtureWait?.claimId !== current.id) fixtureWait = { claimId: current.id, since: Date.now() };
|
|
188
|
+
if (Date.now() - fixtureWait.since > 5e3)
|
|
189
|
+
throw new DeliveryError(
|
|
190
|
+
"Filesystem-negative fixture did not release a waiting output scan within 5 seconds; reader or teardown is stalled."
|
|
191
|
+
);
|
|
192
|
+
} else fixtureWait = void 0;
|
|
193
|
+
} catch (error) {
|
|
194
|
+
if (error.code !== "ENOENT") throw error;
|
|
195
|
+
incompleteSince ??= Date.now();
|
|
196
|
+
if (Date.now() - incompleteSince > 2e3)
|
|
197
|
+
throw new DeliveryError("Filesystem observation gate owner publication is incomplete.");
|
|
323
198
|
}
|
|
199
|
+
}
|
|
200
|
+
await new Promise((resolve2) => setTimeout(resolve2, 100));
|
|
324
201
|
}
|
|
325
|
-
|
|
326
|
-
}
|
|
327
|
-
function retireOutputGateAfterOperation(gate, operationCompleted, operationFailure) {
|
|
202
|
+
} finally {
|
|
328
203
|
try {
|
|
329
|
-
|
|
330
|
-
}
|
|
331
|
-
|
|
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;
|
|
204
|
+
release();
|
|
205
|
+
} finally {
|
|
206
|
+
if (request) removeGateClaim(gate, request, claim);
|
|
349
207
|
}
|
|
208
|
+
}
|
|
350
209
|
}
|
|
351
|
-
async function
|
|
352
|
-
|
|
353
|
-
|
|
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
|
-
}
|
|
210
|
+
async function withVerificationFilesystemFixture(operation) {
|
|
211
|
+
const capability = process.env[OUTPUT_GATE_ENV];
|
|
212
|
+
return withOutputGateLock(capability === void 0 ? void 0 : readOutputGate(capability), "fixture", operation);
|
|
388
213
|
}
|
|
389
214
|
class OutputObservationError extends DeliveryError {
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
215
|
+
cause;
|
|
216
|
+
code;
|
|
217
|
+
constructor(message, path, cause) {
|
|
218
|
+
const code = cause.code;
|
|
219
|
+
super(
|
|
220
|
+
`${message} Path ${JSON.stringify(path)} (${code ?? "unknown errno"}): ${cause instanceof Error ? cause.message : String(cause)}`
|
|
221
|
+
);
|
|
222
|
+
this.code = code;
|
|
223
|
+
this.cause = cause;
|
|
224
|
+
}
|
|
398
225
|
}
|
|
399
226
|
function scanOutputRoots(roots, links, commandRunning = false, onMissingTarget) {
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
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;
|
|
227
|
+
const files = /* @__PURE__ */ new Map();
|
|
228
|
+
const observedLinks = /* @__PURE__ */ new Map();
|
|
229
|
+
const visit = (path) => {
|
|
230
|
+
let metadata;
|
|
231
|
+
try {
|
|
232
|
+
metadata = lstatSync(path);
|
|
233
|
+
} catch (error) {
|
|
234
|
+
if (error.code === "ENOENT") return;
|
|
235
|
+
throw new OutputObservationError("Filesystem output lstat failed.", path, error);
|
|
236
|
+
}
|
|
237
|
+
if (metadata.isSymbolicLink()) {
|
|
238
|
+
let link;
|
|
239
|
+
try {
|
|
240
|
+
link = readlinkSync(path);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
throw new OutputObservationError("Filesystem output readlink failed.", path, error);
|
|
243
|
+
}
|
|
244
|
+
const identity = digestValue({
|
|
245
|
+
device: metadata.dev,
|
|
246
|
+
inode: metadata.ino,
|
|
247
|
+
changed: metadata.ctimeMs,
|
|
248
|
+
modified: metadata.mtimeMs,
|
|
249
|
+
link
|
|
250
|
+
});
|
|
251
|
+
let target;
|
|
252
|
+
let missing = false;
|
|
253
|
+
try {
|
|
254
|
+
target = realpathSync(path);
|
|
255
|
+
} catch (error) {
|
|
256
|
+
const failure = new OutputObservationError(
|
|
257
|
+
"Filesystem output observation encountered a broken or cyclic symbolic link.",
|
|
258
|
+
path,
|
|
259
|
+
error
|
|
260
|
+
);
|
|
261
|
+
const previous2 = links.get(path);
|
|
262
|
+
if (previous2 !== void 0 && previous2.identity !== identity)
|
|
263
|
+
throw new DeliveryError(`Filesystem output alias identity changed. Path ${JSON.stringify(path)}.`);
|
|
264
|
+
if (!commandRunning || failure.code !== "ENOENT" || previous2?.identity !== identity) throw failure;
|
|
265
|
+
let lexical = resolve(dirname(path), link);
|
|
266
|
+
let ancestor = lexical;
|
|
267
|
+
const expanded = /* @__PURE__ */ new Set([path]);
|
|
268
|
+
for (; ; ) {
|
|
269
|
+
try {
|
|
270
|
+
target = join(realpathSync(ancestor), lexical.slice(ancestor.length));
|
|
271
|
+
break;
|
|
272
|
+
} catch (ancestorError) {
|
|
273
|
+
if (ancestorError.code !== "ENOENT" || dirname(ancestor) === ancestor)
|
|
274
|
+
throw new OutputObservationError(
|
|
275
|
+
"Filesystem output ancestor resolution failed.",
|
|
276
|
+
ancestor,
|
|
277
|
+
ancestorError
|
|
278
|
+
);
|
|
279
|
+
let ancestorMetadata;
|
|
529
280
|
try {
|
|
530
|
-
|
|
281
|
+
ancestorMetadata = lstatSync(ancestor);
|
|
282
|
+
} catch (metadataError) {
|
|
283
|
+
if (metadataError.code !== "ENOENT")
|
|
284
|
+
throw new OutputObservationError("Filesystem output ancestor lstat failed.", ancestor, metadataError);
|
|
531
285
|
}
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
286
|
+
if (ancestorMetadata?.isSymbolicLink()) {
|
|
287
|
+
let ancestorLink, currentAncestor;
|
|
288
|
+
try {
|
|
289
|
+
ancestorLink = readlinkSync(ancestor);
|
|
290
|
+
currentAncestor = lstatSync(ancestor);
|
|
291
|
+
} catch (aliasError) {
|
|
292
|
+
throw new OutputObservationError("Filesystem output ancestor alias read failed.", ancestor, aliasError);
|
|
293
|
+
}
|
|
294
|
+
const ancestorIdentity = digestValue({
|
|
295
|
+
device: ancestorMetadata.dev,
|
|
296
|
+
inode: ancestorMetadata.ino,
|
|
297
|
+
changed: ancestorMetadata.ctimeMs,
|
|
298
|
+
modified: ancestorMetadata.mtimeMs,
|
|
299
|
+
link: ancestorLink
|
|
300
|
+
});
|
|
301
|
+
const previousAncestor = links.get(ancestor);
|
|
302
|
+
if (previousAncestor === void 0) throw failure;
|
|
303
|
+
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)
|
|
304
|
+
throw new DeliveryError(
|
|
305
|
+
`Filesystem output ancestor alias identity changed. Path ${JSON.stringify(ancestor)}.`
|
|
306
|
+
);
|
|
307
|
+
expanded.add(ancestor);
|
|
308
|
+
lexical = join(resolve(dirname(ancestor), ancestorLink), lexical.slice(ancestor.length));
|
|
309
|
+
ancestor = lexical;
|
|
310
|
+
continue;
|
|
536
311
|
}
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
return;
|
|
540
|
-
}
|
|
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)}.`);
|
|
312
|
+
ancestor = dirname(ancestor);
|
|
313
|
+
}
|
|
543
314
|
}
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
315
|
+
if (target !== previous2.target)
|
|
316
|
+
throw new DeliveryError(`Filesystem output alias target identity changed. Path ${JSON.stringify(path)}.`);
|
|
317
|
+
missing = true;
|
|
318
|
+
onMissingTarget?.(failure.message);
|
|
319
|
+
}
|
|
320
|
+
const previous = links.get(path);
|
|
321
|
+
if (previous?.missing && (previous.identity !== identity || previous.target !== target))
|
|
322
|
+
throw new DeliveryError(
|
|
323
|
+
`Filesystem output alias identity changed after target absence. Path ${JSON.stringify(path)}.`
|
|
324
|
+
);
|
|
325
|
+
if (!roots.some((root) => target === root || target.startsWith(`${root}${sep}`))) {
|
|
326
|
+
throw new DeliveryError(
|
|
327
|
+
`Filesystem output observation encountered an escaping symbolic link. Path ${JSON.stringify(path)} resolves to ${JSON.stringify(target)}.`
|
|
328
|
+
);
|
|
329
|
+
}
|
|
330
|
+
let current;
|
|
331
|
+
try {
|
|
332
|
+
current = lstatSync(path);
|
|
333
|
+
} catch (error) {
|
|
334
|
+
if (commandRunning && error.code === "ENOENT" && previous?.identity === identity)
|
|
335
|
+
return;
|
|
336
|
+
throw new OutputObservationError("Filesystem output alias identity readback failed.", path, error);
|
|
337
|
+
}
|
|
338
|
+
if (!current.isSymbolicLink() || current.dev !== metadata.dev || current.ino !== metadata.ino || current.ctimeMs !== metadata.ctimeMs || current.mtimeMs !== metadata.mtimeMs)
|
|
339
|
+
throw new DeliveryError(
|
|
340
|
+
`Filesystem output alias identity changed during observation. Path ${JSON.stringify(path)}.`
|
|
341
|
+
);
|
|
342
|
+
observedLinks.set(path, { identity, target, missing });
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
345
|
+
if (metadata.isDirectory()) {
|
|
346
|
+
let names;
|
|
347
|
+
try {
|
|
348
|
+
names = readdirSync(path);
|
|
349
|
+
} catch (error) {
|
|
350
|
+
if (error.code === "ENOENT") return;
|
|
351
|
+
throw new OutputObservationError("Filesystem output readdir failed.", path, error);
|
|
352
|
+
}
|
|
353
|
+
for (const name of names) visit(join(path, name));
|
|
354
|
+
return;
|
|
553
355
|
}
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
356
|
+
if (!metadata.isFile() && !metadata.isSocket() || !Number.isSafeInteger(metadata.size)) {
|
|
357
|
+
throw new DeliveryError(
|
|
358
|
+
`Filesystem output observation encountered an unsupported file. Path ${JSON.stringify(path)}.`
|
|
359
|
+
);
|
|
360
|
+
}
|
|
361
|
+
files.set(path, metadata.isSocket() ? 0 : metadata.size);
|
|
362
|
+
if (files.size > 1e6) throw new DeliveryError("Filesystem output observation exceeded its file limit.");
|
|
363
|
+
};
|
|
364
|
+
for (const root of roots) {
|
|
365
|
+
if (existsSync(root) && realpathSync(root) !== root)
|
|
366
|
+
throw new DeliveryError("Filesystem output roots must not be symbolic links.");
|
|
367
|
+
visit(root);
|
|
368
|
+
}
|
|
369
|
+
links.clear();
|
|
370
|
+
for (const [path, link] of observedLinks) links.set(path, link);
|
|
371
|
+
return files;
|
|
559
372
|
}
|
|
560
373
|
async function positiveNewOutputBytes(baseline, signal, commandRunning = false, onUnavailable) {
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
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
|
-
}
|
|
374
|
+
let files;
|
|
375
|
+
let firstFailure;
|
|
376
|
+
let lastFailure;
|
|
377
|
+
let firstFailureAt;
|
|
378
|
+
const assertObservationWindow = () => {
|
|
379
|
+
if (firstFailureAt !== void 0 && Date.now() - firstFailureAt >= 1e3) {
|
|
380
|
+
throw new DeliveryError(
|
|
381
|
+
`Filesystem output observation remained unavailable for 1 second. First observation: ${firstFailure.message} Last observation: ${lastFailure.message}`
|
|
382
|
+
);
|
|
593
383
|
}
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
384
|
+
};
|
|
385
|
+
for (; ; ) {
|
|
386
|
+
if (signal?.aborted) throw new DeliveryError("Filesystem output observation cancelled.");
|
|
387
|
+
assertObservationWindow();
|
|
388
|
+
try {
|
|
389
|
+
files = await withOutputGateLock(
|
|
390
|
+
baseline.gate,
|
|
391
|
+
"scan",
|
|
392
|
+
() => scanOutputRoots(baseline.roots, baseline.links, commandRunning, onUnavailable),
|
|
393
|
+
signal
|
|
394
|
+
);
|
|
395
|
+
assertObservationWindow();
|
|
396
|
+
break;
|
|
397
|
+
} catch (error) {
|
|
398
|
+
if (!commandRunning || !(error instanceof OutputObservationError) || error.code !== "ENOENT") throw error;
|
|
399
|
+
lastFailure = error;
|
|
400
|
+
if (firstFailure === void 0) {
|
|
401
|
+
firstFailureAt = Date.now();
|
|
402
|
+
firstFailure = error;
|
|
403
|
+
onUnavailable?.(error.message);
|
|
404
|
+
}
|
|
405
|
+
assertObservationWindow();
|
|
406
|
+
await new Promise((resolve2) => setTimeout(resolve2, 25));
|
|
599
407
|
}
|
|
600
|
-
|
|
408
|
+
}
|
|
409
|
+
let bytes = 0;
|
|
410
|
+
for (const [path, size] of files) {
|
|
411
|
+
bytes += Math.max(0, size - (baseline.files.get(path) ?? 0));
|
|
412
|
+
if (!Number.isSafeInteger(bytes)) throw new DeliveryError("Filesystem output observation overflowed.");
|
|
413
|
+
}
|
|
414
|
+
return bytes;
|
|
601
415
|
}
|
|
602
416
|
function availableDiskBytes(path) {
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
throw error;
|
|
612
|
-
existing = dirname(existing);
|
|
613
|
-
}
|
|
417
|
+
let existing = path;
|
|
418
|
+
for (; ; ) {
|
|
419
|
+
try {
|
|
420
|
+
const disk = statfsSync(existing, { bigint: true });
|
|
421
|
+
return disk.bavail * disk.bsize;
|
|
422
|
+
} catch (error) {
|
|
423
|
+
if (error.code !== "ENOENT" || dirname(existing) === existing) throw error;
|
|
424
|
+
existing = dirname(existing);
|
|
614
425
|
}
|
|
426
|
+
}
|
|
615
427
|
}
|
|
616
428
|
function freeDiskBytes(repoRoot, baseline) {
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
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
|
-
}
|
|
429
|
+
const roots = baseline === void 0 ? [repoRoot] : [repoRoot, ...baseline.roots];
|
|
430
|
+
const minimum = roots.reduce((value, path) => {
|
|
431
|
+
const available = availableDiskBytes(path);
|
|
432
|
+
return available < value ? available : value;
|
|
433
|
+
}, BigInt(Number.MAX_SAFE_INTEGER));
|
|
434
|
+
if (minimum > BigInt(Number.MAX_SAFE_INTEGER)) throw new DeliveryError("Free disk observation overflowed.");
|
|
435
|
+
return Number(minimum);
|
|
630
436
|
}
|
|
631
437
|
class ProcessSnapshotError extends DeliveryError {
|
|
632
438
|
}
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
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;
|
|
439
|
+
function processSnapshot() {
|
|
440
|
+
const psPath = existsSync("/usr/bin/ps") ? "/usr/bin/ps" : "/bin/ps";
|
|
441
|
+
const started = performance.now();
|
|
442
|
+
const result = spawnSync(psPath, ["-A", "-o", "pid=,ppid=,pgid=,rss=,stat=,lstart="], {
|
|
443
|
+
encoding: "utf8",
|
|
444
|
+
// The absolute observer needs no author tokens, App keys or preload selectors.
|
|
445
|
+
env: { LC_ALL: "C" },
|
|
446
|
+
maxBuffer: 4 * 1024 * 1024,
|
|
447
|
+
timeout: 1e3
|
|
448
|
+
});
|
|
449
|
+
if (result.status !== 0 || result.error || result.signal || !result.stdout.endsWith("\n")) {
|
|
450
|
+
const elapsedMs = Math.round(performance.now() - started);
|
|
451
|
+
const stdout = typeof result.stdout === "string" ? result.stdout : "";
|
|
452
|
+
let completeLines = 0;
|
|
453
|
+
for (let index = 0; index < stdout.length; index++) if (stdout.charCodeAt(index) === 10) completeLines++;
|
|
454
|
+
const code = result.error?.code;
|
|
455
|
+
const signal = result.signal;
|
|
456
|
+
const metadata = {
|
|
457
|
+
status: Number.isSafeInteger(result.status) ? result.status : null,
|
|
458
|
+
errorCode: code === void 0 ? null : ["EACCES", "EPERM", "ETIMEDOUT", "ENOENT", "ENOBUFS", "EAGAIN", "ENOMEM", "EIO", "EINVAL"].includes(code) ? code : "other",
|
|
459
|
+
signal: signal === null ? null : ["SIGTERM", "SIGKILL", "SIGINT", "SIGABRT", "SIGSEGV", "SIGBUS", "SIGHUP", "SIGQUIT", "SIGPIPE"].includes(
|
|
460
|
+
signal
|
|
461
|
+
) ? signal : "other",
|
|
462
|
+
stdoutPresent: typeof result.stdout === "string",
|
|
463
|
+
stdoutTerminated: typeof result.stdout === "string" && result.stdout.endsWith("\n"),
|
|
464
|
+
elapsedMs,
|
|
465
|
+
stdoutBytes: Buffer.byteLength(stdout),
|
|
466
|
+
completeLines
|
|
467
|
+
};
|
|
468
|
+
throw new ProcessSnapshotError(`Owned process resource observation failed. ${JSON.stringify(metadata)}`);
|
|
469
|
+
}
|
|
470
|
+
const snapshot = /* @__PURE__ */ new Map();
|
|
471
|
+
for (const line of result.stdout.trim().split("\n")) {
|
|
472
|
+
const match = /^(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(.+)$/u.exec(line.trim());
|
|
473
|
+
if (!match) throw new DeliveryError("Owned process resource observation is ambiguous.");
|
|
474
|
+
const observed = {
|
|
475
|
+
pid: Number(match[1]),
|
|
476
|
+
ppid: Number(match[2]),
|
|
477
|
+
pgid: Number(match[3]),
|
|
478
|
+
rssBytes: Number(match[4]) * 1024,
|
|
479
|
+
status: match[5],
|
|
480
|
+
identity: match[6]
|
|
481
|
+
};
|
|
482
|
+
if (!Number.isSafeInteger(observed.pid) || observed.pid <= 0 || !Number.isSafeInteger(observed.ppid) || !Number.isSafeInteger(observed.pgid) || !Number.isSafeInteger(observed.rssBytes) || snapshot.has(observed.pid))
|
|
483
|
+
throw new DeliveryError("Owned process resource observation is ambiguous.");
|
|
484
|
+
snapshot.set(observed.pid, observed);
|
|
485
|
+
}
|
|
486
|
+
return snapshot;
|
|
695
487
|
}
|
|
696
488
|
function observeOwnedProcesses(state, snapshot) {
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
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.');
|
|
707
|
-
}
|
|
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);
|
|
718
|
-
}
|
|
719
|
-
for (const member of snapshot.values()) {
|
|
720
|
-
if (!member.status.startsWith('Z') && member.pgid === state.rootPid)
|
|
721
|
-
selected.set(member.pid, member);
|
|
489
|
+
const root = snapshot.get(state.rootPid);
|
|
490
|
+
if (state.rootIdentity === void 0) {
|
|
491
|
+
if (root === void 0 || root.status.startsWith("Z") || root.pgid !== state.rootPid) {
|
|
492
|
+
throw new DeliveryError("Owned process identity could not be established before the command exited.");
|
|
722
493
|
}
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
494
|
+
state.rootIdentity = root.identity;
|
|
495
|
+
state.tracked.set(root.pid, root);
|
|
496
|
+
} else if (root !== void 0 && root.identity !== state.rootIdentity) {
|
|
497
|
+
throw new DeliveryError("Owned process identity changed during verification.");
|
|
498
|
+
}
|
|
499
|
+
const selected = /* @__PURE__ */ new Map();
|
|
500
|
+
for (const [pid, previous] of state.tracked) {
|
|
501
|
+
const current = snapshot.get(pid);
|
|
502
|
+
if (current === void 0 || current.status.startsWith("Z")) state.tracked.delete(pid);
|
|
503
|
+
else if (current.identity !== previous.identity) {
|
|
504
|
+
throw new DeliveryError("Tracked process identity changed during verification.");
|
|
505
|
+
} else selected.set(pid, current);
|
|
506
|
+
}
|
|
507
|
+
for (const member of snapshot.values()) {
|
|
508
|
+
if (!member.status.startsWith("Z") && member.pgid === state.rootPid) selected.set(member.pid, member);
|
|
509
|
+
}
|
|
510
|
+
const children = /* @__PURE__ */ new Map();
|
|
511
|
+
for (const member of snapshot.values()) {
|
|
512
|
+
const siblings = children.get(member.ppid) ?? [];
|
|
513
|
+
siblings.push(member);
|
|
514
|
+
children.set(member.ppid, siblings);
|
|
515
|
+
}
|
|
516
|
+
const pending = [...selected.values()];
|
|
517
|
+
for (const parent of pending)
|
|
518
|
+
for (const child of children.get(parent.pid) ?? []) {
|
|
519
|
+
if (!child.status.startsWith("Z") && !selected.has(child.pid)) {
|
|
520
|
+
selected.set(child.pid, child);
|
|
521
|
+
pending.push(child);
|
|
522
|
+
}
|
|
728
523
|
}
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
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()];
|
|
524
|
+
for (const member of selected.values()) state.tracked.set(member.pid, member);
|
|
525
|
+
state.sampled = true;
|
|
526
|
+
return [...selected.values()];
|
|
741
527
|
}
|
|
742
528
|
function sampleOwnedTree(state, repoRoot, bounds, baseline, newOutputBytes, controllerRssBytes = 0, includeControllerTree = false) {
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
529
|
+
const snapshot = processSnapshot();
|
|
530
|
+
const owned = observeOwnedProcesses(state, snapshot);
|
|
531
|
+
const controller = includeControllerTree ? controllerTreeRssBytes(snapshot, new Set(owned.map((member) => member.pid))) : controllerRssBytes;
|
|
532
|
+
const rssBytes = owned.reduce((total, member) => total + member.rssBytes, controller);
|
|
533
|
+
if (!Number.isSafeInteger(rssBytes))
|
|
534
|
+
throw new DeliveryError("Owned aggregate RSS is outside the safe integer range.");
|
|
535
|
+
if (rssBytes > bounds.maxAggregateRssBytes) {
|
|
536
|
+
throw new DeliveryError(`Owned aggregate RSS ${rssBytes} exceeded limit ${bounds.maxAggregateRssBytes}.`);
|
|
537
|
+
}
|
|
538
|
+
const available = freeDiskBytes(repoRoot, baseline);
|
|
539
|
+
if (available < bounds.minFreeDiskBytes)
|
|
540
|
+
throw new DeliveryError(`Free disk fell below limit ${bounds.minFreeDiskBytes}.`);
|
|
541
|
+
if (newOutputBytes !== void 0 && !Number.isSafeInteger(newOutputBytes)) {
|
|
542
|
+
throw new DeliveryError("Filesystem output observation overflowed.");
|
|
543
|
+
}
|
|
544
|
+
if (baseline !== void 0 && bounds.maxNewOutputBytes !== void 0) {
|
|
545
|
+
if (newOutputBytes !== void 0 && newOutputBytes > bounds.maxNewOutputBytes) {
|
|
546
|
+
throw new DeliveryError(
|
|
547
|
+
`Positive new filesystem output ${newOutputBytes} exceeded limit ${bounds.maxNewOutputBytes}.`
|
|
548
|
+
);
|
|
759
549
|
}
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
}
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
freeDiskBytes: available,
|
|
768
|
-
...(newOutputBytes === undefined ? {} : { newOutputBytes }),
|
|
769
|
-
ownedProcessCount: owned.length,
|
|
770
|
-
};
|
|
771
|
-
}
|
|
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;
|
|
550
|
+
}
|
|
551
|
+
return {
|
|
552
|
+
aggregateRssBytes: rssBytes,
|
|
553
|
+
freeDiskBytes: available,
|
|
554
|
+
...newOutputBytes === void 0 ? {} : { newOutputBytes },
|
|
555
|
+
ownedProcessCount: owned.length
|
|
556
|
+
};
|
|
789
557
|
}
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
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
|
-
}
|
|
558
|
+
function controllerTreeRssBytes(snapshot = processSnapshot(), excluded = /* @__PURE__ */ new Set()) {
|
|
559
|
+
const controller = snapshot.get(process.pid);
|
|
560
|
+
if (controller === void 0 || controller.status.startsWith("Z"))
|
|
561
|
+
throw new DeliveryError("Runtime setup controller resource observation is unavailable.");
|
|
562
|
+
const selected = /* @__PURE__ */ new Set([process.pid]);
|
|
563
|
+
let bytes = process.memoryUsage().rss;
|
|
564
|
+
for (const pid of selected)
|
|
565
|
+
for (const member of snapshot.values())
|
|
566
|
+
if (member.ppid === pid && !member.status.startsWith("Z") && !selected.has(member.pid)) {
|
|
567
|
+
selected.add(member.pid);
|
|
568
|
+
if (!excluded.has(member.pid)) bytes += member.rssBytes;
|
|
569
|
+
}
|
|
570
|
+
if (!Number.isSafeInteger(bytes)) throw new DeliveryError("Controller aggregate RSS observation overflowed.");
|
|
571
|
+
return bytes;
|
|
816
572
|
}
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
573
|
+
async function confirmOwnedCleanup(state) {
|
|
574
|
+
if (!state.sampled || state.rootIdentity === void 0) {
|
|
575
|
+
throw new DeliveryError("Owned process cleanup cannot be verified without a root identity.");
|
|
576
|
+
}
|
|
577
|
+
const deadline = Date.now() + 2e3;
|
|
578
|
+
for (; ; ) {
|
|
821
579
|
const snapshot = processSnapshot();
|
|
822
580
|
const root = snapshot.get(state.rootPid);
|
|
823
|
-
if (root !==
|
|
824
|
-
|
|
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];
|
|
832
|
-
});
|
|
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) => {
|
|
837
|
-
try {
|
|
838
|
-
process.kill(pid, 'SIGKILL');
|
|
839
|
-
}
|
|
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
|
-
}
|
|
863
|
-
}
|
|
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.');
|
|
581
|
+
if (root !== void 0 && root.identity !== state.rootIdentity) {
|
|
582
|
+
throw new DeliveryError("Owned process group identity changed before cleanup readback.");
|
|
912
583
|
}
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
const
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
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
|
-
},
|
|
584
|
+
const groupAlive = [...snapshot.values()].some(
|
|
585
|
+
(member) => member.pgid === state.rootPid && !member.status.startsWith("Z")
|
|
586
|
+
);
|
|
587
|
+
const trackedAlive = [...state.tracked.values()].some((previous) => {
|
|
588
|
+
const current = snapshot.get(previous.pid);
|
|
589
|
+
if (current === void 0 || current.status.startsWith("Z")) return false;
|
|
590
|
+
if (current.identity !== previous.identity)
|
|
591
|
+
throw new DeliveryError("Tracked process identity changed before cleanup readback.");
|
|
592
|
+
return true;
|
|
1066
593
|
});
|
|
594
|
+
if (!groupAlive && !trackedAlive) return;
|
|
595
|
+
if (Date.now() >= deadline) throw new DeliveryError("Owned process cleanup did not release every sampled process.");
|
|
596
|
+
await new Promise((resolve2) => setTimeout(resolve2, 100));
|
|
597
|
+
}
|
|
1067
598
|
}
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
599
|
+
function terminateOwnedProcesses(state) {
|
|
600
|
+
if (!state.sampled || state.rootIdentity === void 0) throw new DeliveryError("Owned process identity is unknown.");
|
|
601
|
+
const snapshot = processSnapshot();
|
|
602
|
+
const root = snapshot.get(state.rootPid);
|
|
603
|
+
if (root !== void 0 && root.identity !== state.rootIdentity)
|
|
604
|
+
throw new DeliveryError("Owned process group identity changed before cleanup.");
|
|
605
|
+
const alive = [...state.tracked.values()].flatMap((previous) => {
|
|
606
|
+
const current = snapshot.get(previous.pid);
|
|
607
|
+
if (current === void 0 || current.status.startsWith("Z")) return [];
|
|
608
|
+
if (current.identity !== previous.identity)
|
|
609
|
+
throw new DeliveryError("Tracked process identity changed before cleanup.");
|
|
610
|
+
return [current];
|
|
611
|
+
});
|
|
612
|
+
const group = [...snapshot.values()].filter(
|
|
613
|
+
(member) => member.pgid === state.rootPid && !member.status.startsWith("Z")
|
|
614
|
+
);
|
|
615
|
+
if (group.length > 0 && !alive.some((member) => member.pgid === state.rootPid))
|
|
616
|
+
throw new DeliveryError("Owned process group has no surviving recorded identity; cleanup is ambiguous.");
|
|
617
|
+
const signal = (pid) => {
|
|
618
|
+
try {
|
|
619
|
+
process.kill(pid, "SIGKILL");
|
|
620
|
+
} catch (error) {
|
|
621
|
+
const code = error.code;
|
|
622
|
+
if (code === "ESRCH") return;
|
|
623
|
+
if (code !== "EPERM") throw error;
|
|
624
|
+
const readback = processSnapshot();
|
|
625
|
+
if (pid < 0) {
|
|
626
|
+
const currentRoot = readback.get(state.rootPid);
|
|
627
|
+
if (currentRoot !== void 0 && currentRoot.identity !== state.rootIdentity)
|
|
628
|
+
throw new DeliveryError("Owned process group identity changed during cleanup signal readback.");
|
|
629
|
+
if ([...readback.values()].some((member) => member.pgid === state.rootPid && !member.status.startsWith("Z")))
|
|
630
|
+
throw error;
|
|
631
|
+
} else {
|
|
632
|
+
const current = readback.get(pid);
|
|
633
|
+
if (current !== void 0 && current.identity !== state.tracked.get(pid)?.identity)
|
|
634
|
+
throw new DeliveryError("Tracked process identity changed during cleanup signal readback.");
|
|
635
|
+
if (current !== void 0 && !current.status.startsWith("Z")) throw error;
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
};
|
|
639
|
+
if (group.length > 0) signal(-state.rootPid);
|
|
640
|
+
for (const member of alive.reverse()) signal(member.pid);
|
|
1087
641
|
}
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
642
|
+
const ProcessIdentitySchema = z.strictObject({ pid: z.number().int().positive(), identity: z.string().min(1) });
|
|
643
|
+
const WriterStateSchema = z.strictObject({
|
|
644
|
+
schemaVersion: z.literal("ai-delivery.verification-writer@1"),
|
|
645
|
+
writerId: z.uuid(),
|
|
646
|
+
worktreeDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/u),
|
|
647
|
+
owner: ProcessIdentitySchema,
|
|
648
|
+
command: z.union([
|
|
649
|
+
z.strictObject({ phase: z.literal("idle") }),
|
|
650
|
+
z.strictObject({ phase: z.literal("starting") }),
|
|
651
|
+
z.strictObject({
|
|
652
|
+
phase: z.literal("running"),
|
|
653
|
+
root: ProcessIdentitySchema,
|
|
654
|
+
tracked: z.array(z.strictObject({ ...ProcessIdentitySchema.shape, pgid: z.number().int().positive() }))
|
|
655
|
+
})
|
|
656
|
+
]),
|
|
657
|
+
stateId: z.string().regex(/^sha256:[a-f0-9]{64}$/u)
|
|
658
|
+
}).superRefine((state, ctx) => {
|
|
659
|
+
const { stateId, ...content } = state;
|
|
660
|
+
if (stateId !== digestValue(content)) ctx.addIssue({ code: "custom", message: "Writer state is corrupt." });
|
|
661
|
+
});
|
|
662
|
+
function assertWorktreeTransitionWriterQuiescent(worktreePath, bytes) {
|
|
663
|
+
if (bytes === void 0) return;
|
|
664
|
+
const previous = WriterStateSchema.parse(JSON.parse(bytes.toString("utf8")));
|
|
665
|
+
if (previous.worktreeDigest !== worktreeDigest(worktreePath))
|
|
666
|
+
throw new DeliveryError("Verification writer belongs to another worktree.");
|
|
667
|
+
const snapshot = processSnapshot();
|
|
668
|
+
const owner = snapshot.get(previous.owner.pid);
|
|
669
|
+
if (owner?.identity === previous.owner.identity && !owner.status.startsWith("Z"))
|
|
670
|
+
throw new DeliveryError("A live verification writer still owns this worktree.");
|
|
671
|
+
if (previous.command.phase === "starting")
|
|
672
|
+
throw new DeliveryError("Interrupted writer has unknown command ownership; reconcile before retrying.");
|
|
673
|
+
if (previous.command.phase === "running") {
|
|
674
|
+
const identities = [previous.command.root, ...previous.command.tracked];
|
|
675
|
+
const groups = /* @__PURE__ */ new Set([previous.command.root.pid, ...previous.command.tracked.map((member) => member.pgid)]);
|
|
676
|
+
if (identities.some((member) => snapshot.has(member.pid)) || [...snapshot.values()].some((member) => groups.has(member.pgid)))
|
|
677
|
+
throw new DeliveryError("Transition requires identity-bound command and process-group absence.");
|
|
678
|
+
}
|
|
1099
679
|
}
|
|
1100
680
|
function worktreeDigest(root) {
|
|
1101
|
-
|
|
681
|
+
return digestValue(resolve(root));
|
|
1102
682
|
}
|
|
1103
683
|
function producerContent(root) {
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
684
|
+
const code = [];
|
|
685
|
+
const collect = (directory) => {
|
|
686
|
+
for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
|
|
687
|
+
const path = join(directory, entry.name);
|
|
688
|
+
if (entry.isDirectory()) collect(path);
|
|
689
|
+
else if (entry.isFile() && entry.name.endsWith(".js") && !entry.name.endsWith(".test.js"))
|
|
690
|
+
code.push({ path: path.slice(root.length + 1), digest: digestBytes(readFileSync(path)) });
|
|
691
|
+
}
|
|
692
|
+
};
|
|
693
|
+
collect(root);
|
|
694
|
+
const dependencies = /* @__PURE__ */ new Map();
|
|
695
|
+
const collectDependencies = (manifestPath) => {
|
|
696
|
+
if (dependencies.has(manifestPath)) return;
|
|
697
|
+
const bytes = readFileSync(manifestPath);
|
|
698
|
+
const manifest = z.object({ dependencies: z.record(z.string(), z.string()).optional() }).parse(JSON.parse(bytes.toString("utf8")));
|
|
699
|
+
dependencies.set(manifestPath, digestBytes(bytes));
|
|
700
|
+
const require2 = createRequire(manifestPath);
|
|
701
|
+
for (const name of Object.keys(manifest.dependencies ?? {}).sort()) {
|
|
702
|
+
let resolved;
|
|
703
|
+
try {
|
|
704
|
+
resolved = require2.resolve(`${name}/package.json`);
|
|
705
|
+
} catch {
|
|
706
|
+
try {
|
|
707
|
+
resolved = require2.resolve(name);
|
|
708
|
+
} catch (error) {
|
|
709
|
+
if (!types.isNativeError(error) || Reflect.get(error, "code") !== "ERR_PACKAGE_PATH_NOT_EXPORTED")
|
|
710
|
+
throw error;
|
|
711
|
+
const manifest2 = findPackageJSON(name, manifestPath);
|
|
712
|
+
if (!manifest2) throw error;
|
|
713
|
+
resolved = manifest2;
|
|
1112
714
|
}
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
if (
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
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
|
-
}
|
|
715
|
+
}
|
|
716
|
+
let directory = dirname(resolved);
|
|
717
|
+
for (; ; ) {
|
|
718
|
+
const path = join(directory, "package.json");
|
|
719
|
+
if (existsSync(path)) {
|
|
720
|
+
const candidate = z.object({ name: z.string().optional() }).parse(JSON.parse(readFileSync(path, "utf8")));
|
|
721
|
+
if (candidate.name === name) {
|
|
722
|
+
collectDependencies(path);
|
|
723
|
+
break;
|
|
724
|
+
}
|
|
1158
725
|
}
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
726
|
+
const parent = dirname(directory);
|
|
727
|
+
if (parent === directory) throw new DeliveryError(`Producer dependency identity is unavailable for ${name}.`);
|
|
728
|
+
directory = parent;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
};
|
|
732
|
+
collectDependencies(join(dirname(root), "package.json"));
|
|
733
|
+
return { code, dependencies: [...dependencies].sort(([a], [b]) => a.localeCompare(b)) };
|
|
1162
734
|
}
|
|
1163
735
|
function producerDigest(root = dirname(fileURLToPath(import.meta.url))) {
|
|
1164
|
-
|
|
736
|
+
return digestValue(producerContent(root));
|
|
1165
737
|
}
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
return producerDigest(realpathSync(distDirectory));
|
|
738
|
+
function retainedWorktreeTransitionProducerDigest(distDirectory) {
|
|
739
|
+
return producerDigest(realpathSync(distDirectory));
|
|
1169
740
|
}
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
return producerContent(realpathSync(distDirectory)).dependencies.map(([source, digest]) => ({ source, digest }));
|
|
741
|
+
function retainedWorktreeTransitionDependencyManifests(distDirectory) {
|
|
742
|
+
return producerContent(realpathSync(distDirectory)).dependencies.map(([source, digest]) => ({ source, digest }));
|
|
1173
743
|
}
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
?
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
744
|
+
function runStageCommand(repoRoot, argv, abortSignal, onRunning, resourceBounds, baseline, onResourceSample, writer, execution) {
|
|
745
|
+
const [executable, ...args] = argv;
|
|
746
|
+
if (!executable) throw new DeliveryError("Policy selected an empty stage command.");
|
|
747
|
+
if (abortSignal?.aborted) throw new DeliveryError("Selected policy stage command cancelled.");
|
|
748
|
+
writer?.starting();
|
|
749
|
+
return new Promise((resolve2, reject) => {
|
|
750
|
+
const child = spawn(
|
|
751
|
+
"/bin/sh",
|
|
752
|
+
[
|
|
753
|
+
"-c",
|
|
754
|
+
'IFS= read -r ready || exit 125; [ "$ready" = run ] || exit 125; exec "$@" </dev/null',
|
|
755
|
+
"ai-delivery-command",
|
|
756
|
+
executable,
|
|
757
|
+
...args
|
|
758
|
+
],
|
|
759
|
+
{
|
|
760
|
+
cwd: execution?.cwd ?? repoRoot,
|
|
761
|
+
detached: process.platform !== "win32",
|
|
762
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
763
|
+
...baseline?.gate === void 0 && execution === void 0 ? {} : {
|
|
764
|
+
env: {
|
|
765
|
+
...execution?.environment ?? process.env,
|
|
766
|
+
...baseline?.gate === void 0 ? {} : { [OUTPUT_GATE_ENV]: JSON.stringify(baseline.gate) }
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
);
|
|
771
|
+
const stdout = [];
|
|
772
|
+
const stderr = [];
|
|
773
|
+
const owned = process.platform === "win32" || child.pid === void 0 ? void 0 : { rootPid: child.pid, sampled: false, tracked: /* @__PURE__ */ new Map() };
|
|
774
|
+
let outputBytes = 0;
|
|
775
|
+
let retainedOutputBytes = 0;
|
|
776
|
+
const outputLimit = execution?.maxCapturedOutputBytes ?? 8 * 1024 * 1024;
|
|
777
|
+
let sampledOutputBytes = 0;
|
|
778
|
+
let failure;
|
|
779
|
+
let cleanupFailure;
|
|
780
|
+
let writerFailure;
|
|
781
|
+
let closed = false;
|
|
782
|
+
let settled = false;
|
|
783
|
+
let commandReleased = false;
|
|
784
|
+
let firstOutputObservationFailure;
|
|
785
|
+
let lastOutputObservationFailure;
|
|
786
|
+
let pendingOutput;
|
|
787
|
+
const scanCancellation = new AbortController();
|
|
788
|
+
const failedOutput = () => {
|
|
789
|
+
const observation = firstOutputObservationFailure === void 0 ? "" : ` First filesystem observation: ${firstOutputObservationFailure} Last filesystem observation: ${lastOutputObservationFailure}`;
|
|
790
|
+
try {
|
|
791
|
+
const bytes = Buffer.concat([...stdout, ...stderr]);
|
|
792
|
+
if (execution?.failedOutput) return execution.failedOutput(bytes);
|
|
793
|
+
return ` Command output ${writeRepositoryCommandOutput({ bytes, gitCommonDir: gitCommonDir(repoRoot) })}.${observation}`;
|
|
794
|
+
} catch (error) {
|
|
795
|
+
return ` Command output persistence failed (${error instanceof Error ? error.message : String(error)}).${observation}`;
|
|
796
|
+
}
|
|
1208
797
|
};
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
}
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
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));
|
|
798
|
+
let closeTimer;
|
|
799
|
+
let exitPipeTimer;
|
|
800
|
+
let resourceTimer;
|
|
801
|
+
const clearWatchers = () => {
|
|
802
|
+
clearInterval(progressTimer);
|
|
803
|
+
if (resourceTimer !== void 0) clearInterval(resourceTimer);
|
|
804
|
+
if (closeTimer !== void 0) clearTimeout(closeTimer);
|
|
805
|
+
if (exitPipeTimer !== void 0) clearTimeout(exitPipeTimer);
|
|
806
|
+
abortSignal?.removeEventListener("abort", onAbort);
|
|
807
|
+
process.removeListener("SIGINT", onSigint);
|
|
808
|
+
process.removeListener("SIGTERM", onSigterm);
|
|
809
|
+
};
|
|
810
|
+
const killOwned = () => {
|
|
811
|
+
if (child.pid === void 0) return;
|
|
812
|
+
if (owned?.sampled) {
|
|
813
|
+
try {
|
|
814
|
+
observeOwnedProcesses(owned, processSnapshot());
|
|
815
|
+
} catch (error) {
|
|
816
|
+
cleanupFailure ??= error instanceof Error ? error.message : String(error);
|
|
817
|
+
}
|
|
818
|
+
try {
|
|
819
|
+
writer?.observed(owned);
|
|
820
|
+
} catch (error) {
|
|
821
|
+
writerFailure ??= error instanceof Error ? error.message : String(error);
|
|
822
|
+
}
|
|
823
|
+
try {
|
|
824
|
+
terminateOwnedProcesses(owned);
|
|
825
|
+
} catch (error) {
|
|
826
|
+
cleanupFailure ??= error instanceof Error ? error.message : String(error);
|
|
827
|
+
}
|
|
828
|
+
} else {
|
|
829
|
+
try {
|
|
830
|
+
if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
|
|
831
|
+
if (commandReleased) cleanupFailure ??= "owned process identity was not observed before cleanup";
|
|
832
|
+
} catch (error) {
|
|
833
|
+
cleanupFailure ??= error instanceof Error ? error.message : String(error);
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
};
|
|
837
|
+
const stop = (reason) => {
|
|
838
|
+
if (failure !== void 0) return;
|
|
839
|
+
failure = reason;
|
|
840
|
+
scanCancellation.abort();
|
|
841
|
+
killOwned();
|
|
842
|
+
if (!closed) {
|
|
843
|
+
closeTimer = setTimeout(() => {
|
|
844
|
+
if (settled || closed) return;
|
|
845
|
+
settled = true;
|
|
846
|
+
clearWatchers();
|
|
847
|
+
child.stdout.destroy();
|
|
848
|
+
child.stderr.destroy();
|
|
849
|
+
child.unref();
|
|
850
|
+
execution?.onCleanupFailure?.("Owned command pipes did not close; descendant cleanup could not be verified.");
|
|
851
|
+
reject(
|
|
852
|
+
new DeliveryError(
|
|
853
|
+
`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).`
|
|
854
|
+
)
|
|
855
|
+
);
|
|
856
|
+
}, 2e3);
|
|
857
|
+
}
|
|
858
|
+
};
|
|
859
|
+
const capture = (chunks, chunk) => {
|
|
860
|
+
outputBytes += chunk.length;
|
|
861
|
+
execution?.onCaptured?.(outputBytes);
|
|
862
|
+
if (execution !== void 0 && resourceBounds?.maxNewOutputBytes !== void 0 && outputBytes + sampledOutputBytes > resourceBounds.maxNewOutputBytes) {
|
|
863
|
+
stop("source-phase captured output exceeded remaining cumulative allowance");
|
|
864
|
+
return;
|
|
865
|
+
}
|
|
866
|
+
if (outputBytes > outputLimit) {
|
|
867
|
+
const remaining = outputLimit - retainedOutputBytes;
|
|
868
|
+
if (remaining > 0) {
|
|
869
|
+
chunks.push(Buffer.from(chunk.subarray(0, remaining)));
|
|
870
|
+
retainedOutputBytes += Math.min(remaining, chunk.length);
|
|
871
|
+
}
|
|
872
|
+
stop(
|
|
873
|
+
execution?.maxCapturedOutputBytes === void 0 ? "captured output exceeded 8 MiB" : `captured output exceeded ${outputLimit} bytes`
|
|
874
|
+
);
|
|
875
|
+
return;
|
|
876
|
+
}
|
|
877
|
+
chunks.push(chunk);
|
|
878
|
+
retainedOutputBytes += chunk.length;
|
|
879
|
+
};
|
|
880
|
+
child.stdout.on("data", (chunk) => capture(stdout, chunk));
|
|
881
|
+
child.stderr.on("data", (chunk) => capture(stderr, chunk));
|
|
882
|
+
child.stdout.once("error", (error) => stop(error.message));
|
|
883
|
+
child.stderr.once("error", (error) => stop(error.message));
|
|
884
|
+
child.stdin.once("error", (error) => stop(error.message));
|
|
885
|
+
child.once("error", (error) => {
|
|
886
|
+
if (child.pid === void 0) writer?.idle();
|
|
887
|
+
stop(error.message);
|
|
888
|
+
});
|
|
889
|
+
child.once("exit", (code, signal) => {
|
|
890
|
+
if (code !== 0 || signal !== null) stop(`exit ${String(code)}${signal === null ? "" : ` signal ${signal}`}`);
|
|
891
|
+
else if (!closed) {
|
|
892
|
+
exitPipeTimer = setTimeout(() => {
|
|
893
|
+
if (!closed) stop("owned command pipes did not close after direct child exit");
|
|
894
|
+
}, 1e3);
|
|
895
|
+
}
|
|
896
|
+
});
|
|
897
|
+
child.once("spawn", () => {
|
|
898
|
+
const sample = () => {
|
|
899
|
+
if (failure !== void 0 || child.pid === void 0) return;
|
|
900
|
+
try {
|
|
901
|
+
if (owned === void 0) throw new DeliveryError("Owned process identity is unavailable on this platform.");
|
|
902
|
+
observeOwnedProcesses(owned, processSnapshot());
|
|
903
|
+
writer?.observed(owned);
|
|
904
|
+
if (resourceBounds !== void 0) {
|
|
905
|
+
const result = sampleOwnedTree(
|
|
906
|
+
owned,
|
|
907
|
+
repoRoot,
|
|
908
|
+
resourceBounds,
|
|
909
|
+
baseline,
|
|
910
|
+
void 0,
|
|
911
|
+
execution === void 0 ? 0 : process.memoryUsage().rss,
|
|
912
|
+
execution?.includeControllerTree
|
|
913
|
+
);
|
|
914
|
+
onResourceSample?.(result);
|
|
915
|
+
onRunning?.(outputBytes, result);
|
|
916
|
+
}
|
|
917
|
+
if (closed || pendingOutput !== void 0) return;
|
|
918
|
+
pendingOutput = (async () => {
|
|
919
|
+
if (resourceBounds !== void 0 && baseline !== void 0) {
|
|
920
|
+
const bytes = await positiveNewOutputBytes(
|
|
921
|
+
baseline,
|
|
922
|
+
scanCancellation.signal,
|
|
923
|
+
commandReleased,
|
|
924
|
+
(reason) => {
|
|
925
|
+
firstOutputObservationFailure ??= reason;
|
|
926
|
+
lastOutputObservationFailure = reason;
|
|
927
|
+
onRunning?.(outputBytes, void 0, reason);
|
|
1475
928
|
}
|
|
929
|
+
);
|
|
930
|
+
if (failure !== void 0) return;
|
|
931
|
+
sampledOutputBytes = bytes;
|
|
932
|
+
const result = sampleOwnedTree(
|
|
933
|
+
owned,
|
|
934
|
+
repoRoot,
|
|
935
|
+
resourceBounds,
|
|
936
|
+
baseline,
|
|
937
|
+
bytes + (execution === void 0 ? 0 : outputBytes),
|
|
938
|
+
execution === void 0 ? 0 : process.memoryUsage().rss,
|
|
939
|
+
execution?.includeControllerTree
|
|
940
|
+
);
|
|
941
|
+
onResourceSample?.(result);
|
|
942
|
+
onRunning?.(outputBytes, result);
|
|
1476
943
|
}
|
|
1477
|
-
if (failure
|
|
1478
|
-
|
|
1479
|
-
|
|
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;
|
|
944
|
+
if (failure === void 0 && !commandReleased) {
|
|
945
|
+
commandReleased = true;
|
|
946
|
+
child.stdin.end("run\n");
|
|
1502
947
|
}
|
|
948
|
+
})().catch((error) => stop(error instanceof Error ? error.message : String(error))).finally(() => {
|
|
949
|
+
pendingOutput = void 0;
|
|
950
|
+
});
|
|
951
|
+
} catch (error) {
|
|
952
|
+
stop(error instanceof Error ? error.message : String(error));
|
|
953
|
+
}
|
|
954
|
+
};
|
|
955
|
+
sample();
|
|
956
|
+
resourceTimer = setInterval(sample, 1e3);
|
|
957
|
+
resourceTimer.unref();
|
|
958
|
+
});
|
|
959
|
+
const progressTimer = setInterval(() => onRunning?.(outputBytes), 5e3);
|
|
960
|
+
progressTimer.unref();
|
|
961
|
+
const onAbort = () => stop("cancelled");
|
|
962
|
+
const onSigint = () => stop("cancelled by SIGINT");
|
|
963
|
+
const onSigterm = () => stop("cancelled by SIGTERM");
|
|
964
|
+
abortSignal?.addEventListener("abort", onAbort, { once: true });
|
|
965
|
+
process.once("SIGINT", onSigint);
|
|
966
|
+
process.once("SIGTERM", onSigterm);
|
|
967
|
+
if (abortSignal?.aborted) onAbort();
|
|
968
|
+
const handleClose = async (code, signal) => {
|
|
969
|
+
closed = true;
|
|
970
|
+
if (settled) return;
|
|
971
|
+
await pendingOutput;
|
|
972
|
+
if (failure === void 0 && owned !== void 0) {
|
|
973
|
+
try {
|
|
974
|
+
if (resourceBounds !== void 0) {
|
|
975
|
+
const sample = sampleOwnedTree(
|
|
976
|
+
owned,
|
|
977
|
+
repoRoot,
|
|
978
|
+
resourceBounds,
|
|
979
|
+
baseline,
|
|
980
|
+
baseline === void 0 ? void 0 : await positiveNewOutputBytes(baseline, scanCancellation.signal) + (execution === void 0 ? 0 : outputBytes),
|
|
981
|
+
execution === void 0 ? 0 : process.memoryUsage().rss,
|
|
982
|
+
execution?.includeControllerTree
|
|
983
|
+
);
|
|
984
|
+
onResourceSample?.(sample);
|
|
985
|
+
onRunning?.(outputBytes, sample);
|
|
986
|
+
}
|
|
987
|
+
if (!owned.sampled) throw new DeliveryError("Owned process resource observation was unavailable.");
|
|
988
|
+
const remaining = observeOwnedProcesses(owned, processSnapshot());
|
|
989
|
+
if (remaining.length > 0) throw new DeliveryError("A sampled owned descendant survived command exit.");
|
|
990
|
+
} catch (error) {
|
|
991
|
+
stop(error instanceof Error ? error.message : String(error));
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
if (failure !== void 0 || code !== 0 || signal !== null) {
|
|
995
|
+
const reason = failure ?? `exit ${String(code)}${signal === null ? "" : ` signal ${signal}`}`;
|
|
996
|
+
let cleanupConfirmed = child.pid === void 0 || !commandReleased;
|
|
997
|
+
if (owned !== void 0 && owned.sampled) {
|
|
998
|
+
try {
|
|
999
|
+
await confirmOwnedCleanup(owned);
|
|
1000
|
+
cleanupConfirmed = true;
|
|
1001
|
+
} catch (error) {
|
|
1002
|
+
cleanupFailure ??= error instanceof Error ? error.message : String(error);
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
if (cleanupConfirmed) {
|
|
1006
|
+
try {
|
|
1503
1007
|
writer?.idle();
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
})
|
|
1513
|
-
|
|
1514
|
-
|
|
1008
|
+
} catch (error) {
|
|
1009
|
+
writerFailure ??= error instanceof Error ? error.message : String(error);
|
|
1010
|
+
}
|
|
1011
|
+
}
|
|
1012
|
+
settled = true;
|
|
1013
|
+
if (cleanupFailure !== void 0) execution?.onCleanupFailure?.(cleanupFailure);
|
|
1014
|
+
reject(
|
|
1015
|
+
new DeliveryError(
|
|
1016
|
+
`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}).`}`
|
|
1017
|
+
)
|
|
1018
|
+
);
|
|
1019
|
+
return;
|
|
1020
|
+
}
|
|
1021
|
+
writer?.idle();
|
|
1022
|
+
settled = true;
|
|
1023
|
+
resolve2(execution?.stdoutOnly ? Buffer.concat(stdout) : Buffer.concat([...stdout, ...stderr], outputBytes));
|
|
1024
|
+
};
|
|
1025
|
+
child.once("close", (code, signal) => {
|
|
1026
|
+
void handleClose(code, signal).catch((error) => {
|
|
1027
|
+
settled = true;
|
|
1028
|
+
reject(error);
|
|
1029
|
+
}).finally(clearWatchers);
|
|
1515
1030
|
});
|
|
1031
|
+
});
|
|
1516
1032
|
}
|
|
1517
1033
|
const SourceDigest = z.string().regex(/^sha256:[a-f0-9]{64}$/u);
|
|
1518
1034
|
const SourceSha = z.string().regex(/^[a-f0-9]{40}$/u);
|
|
1519
1035
|
const SourceArtifactSchema = z.strictObject({ path: z.string().min(1), digest: SourceDigest });
|
|
1520
1036
|
const SourceFileSchema = SourceArtifactSchema.extend({
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1037
|
+
device: z.number().int().nonnegative().safe(),
|
|
1038
|
+
inode: z.number().int().nonnegative().safe(),
|
|
1039
|
+
uid: z.number().int().nonnegative().safe(),
|
|
1040
|
+
mode: z.number().int().nonnegative().safe()
|
|
1525
1041
|
});
|
|
1526
1042
|
const SourceCommandSchema = z.strictObject({
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1043
|
+
argv: z.array(z.string()).min(1),
|
|
1044
|
+
cwd: z.string().min(1),
|
|
1045
|
+
executable: SourceFileSchema
|
|
1530
1046
|
});
|
|
1531
1047
|
const SourceSnapshotSchema = z.strictObject({
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1048
|
+
head: SourceSha,
|
|
1049
|
+
indexTree: SourceSha,
|
|
1050
|
+
branch: z.string().min(1),
|
|
1051
|
+
configDigest: SourceDigest,
|
|
1052
|
+
dirty: z.array(z.strictObject({ path: z.string().min(1), digest: SourceDigest.nullable() }))
|
|
1537
1053
|
});
|
|
1538
1054
|
const SourceBoundsSchema = z.strictObject({
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1055
|
+
maxAggregateRssBytes: z.number().int().positive().safe(),
|
|
1056
|
+
maxNewOutputBytes: z.number().int().positive().safe(),
|
|
1057
|
+
minFreeDiskBytes: z.number().int().positive().safe(),
|
|
1058
|
+
outputRoots: z.array(z.string().min(1)).min(1)
|
|
1543
1059
|
});
|
|
1544
1060
|
const SourceReconciliationSchema = z.strictObject({
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1061
|
+
phaseId: SourceDigest,
|
|
1062
|
+
recordId: SourceDigest,
|
|
1063
|
+
baselineId: SourceDigest.optional(),
|
|
1064
|
+
authorizationDigest: SourceDigest
|
|
1549
1065
|
});
|
|
1550
1066
|
const IssueSourcePhaseInputSchema = z.strictObject({
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
1569
|
-
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
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,
|
|
1067
|
+
repoRoot: z.string().min(1),
|
|
1068
|
+
issueNumber: z.number().int().positive().safe(),
|
|
1069
|
+
identity: z.string().min(1),
|
|
1070
|
+
rowDigest: SourceDigest,
|
|
1071
|
+
controller: z.strictObject({
|
|
1072
|
+
head: SourceSha,
|
|
1073
|
+
configDigest: SourceDigest,
|
|
1074
|
+
admissionId: SourceDigest,
|
|
1075
|
+
runtimeEntryPath: z.string().min(1),
|
|
1076
|
+
packageVersion: z.string().min(1),
|
|
1077
|
+
archiveDigest: SourceDigest
|
|
1078
|
+
}),
|
|
1079
|
+
source: SourceSnapshotSchema.extend({
|
|
1080
|
+
path: z.string().min(1),
|
|
1081
|
+
effect: z.discriminatedUnion("kind", [
|
|
1082
|
+
z.strictObject({ kind: z.literal("preserve") }),
|
|
1083
|
+
z.strictObject({
|
|
1084
|
+
kind: z.literal("commitOnce"),
|
|
1085
|
+
parent: SourceSha,
|
|
1086
|
+
tree: SourceSha,
|
|
1087
|
+
configDigest: SourceDigest.optional()
|
|
1088
|
+
})
|
|
1089
|
+
])
|
|
1090
|
+
}),
|
|
1091
|
+
caller: SourceArtifactSchema,
|
|
1092
|
+
authorization: SourceArtifactSchema,
|
|
1093
|
+
inputs: z.array(SourceArtifactSchema),
|
|
1094
|
+
commands: z.array(SourceCommandSchema).min(1),
|
|
1095
|
+
commandGraphDigest: SourceDigest,
|
|
1096
|
+
environment: z.strictObject({ digest: SourceDigest, overrides: z.record(z.string(), z.string().nullable()) }),
|
|
1097
|
+
bounds: SourceBoundsSchema,
|
|
1098
|
+
completionArtifacts: z.array(z.string().min(1)),
|
|
1099
|
+
reconciliation: SourceReconciliationSchema.optional()
|
|
1593
1100
|
});
|
|
1594
1101
|
const SourcePhaseCommandResultSchema = z.strictObject({
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
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),
|
|
1102
|
+
index: z.number().int().nonnegative().safe(),
|
|
1103
|
+
outputDigest: SourceDigest.nullable(),
|
|
1104
|
+
outputBytes: z.number().int().nonnegative().safe(),
|
|
1105
|
+
status: z.enum(["complete", "failed"])
|
|
1606
1106
|
});
|
|
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
1107
|
const IssueSourcePhaseReceiptSchema = z.strictObject({
|
|
1709
|
-
|
|
1710
|
-
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
});
|
|
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
|
-
});
|
|
1108
|
+
status: z.literal("complete"),
|
|
1109
|
+
phaseId: SourceDigest,
|
|
1110
|
+
recordId: SourceDigest,
|
|
1111
|
+
source: SourceSnapshotSchema,
|
|
1112
|
+
commands: z.array(SourcePhaseCommandResultSchema)
|
|
1750
1113
|
});
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
1760
|
-
|
|
1761
|
-
|
|
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
|
|
1114
|
+
export {
|
|
1115
|
+
assertWorktreeTransitionWriterQuiescent,
|
|
1116
|
+
confirmOwnedCleanup,
|
|
1117
|
+
processSnapshot,
|
|
1118
|
+
retainedWorktreeTransitionDependencyManifests,
|
|
1119
|
+
retainedWorktreeTransitionProducerDigest,
|
|
1120
|
+
runStageCommand,
|
|
1121
|
+
terminateOwnedProcesses,
|
|
1122
|
+
withVerificationFilesystemFixture
|
|
1123
|
+
};
|
|
1124
|
+
//# sourceMappingURL=verification.js.map
|