@aviaratech/ai-delivery 0.3.37 → 0.3.39
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -18
- package/dist/agent.d.ts +0 -4
- package/dist/agent.js +1 -8
- package/dist/agent.js.map +2 -2
- package/dist/cli.js +2 -72
- package/dist/cli.js.map +2 -2
- package/dist/cliResult.js +2 -14
- package/dist/cliResult.js.map +2 -2
- package/dist/cliResult.test.js +0 -74
- package/dist/cliResult.test.js.map +2 -2
- package/dist/config/deliveryConfig.d.ts +0 -6
- package/dist/config/deliveryConfig.js +2 -35
- package/dist/config/deliveryConfig.js.map +2 -2
- package/dist/config/deliveryConfig.test.js +1 -25
- package/dist/config/deliveryConfig.test.js.map +2 -2
- package/dist/contributorChecks.test.js +5 -3
- package/dist/contributorChecks.test.js.map +2 -2
- package/dist/delivery/common.d.ts +0 -14
- package/dist/delivery/common.js +1 -44
- package/dist/delivery/common.js.map +2 -2
- package/dist/directoryIndependent.test.js +2 -24
- package/dist/directoryIndependent.test.js.map +2 -2
- package/dist/dispatch.js +0 -46
- package/dist/dispatch.js.map +3 -3
- package/dist/fixtures/inertTarget.js +3 -5
- package/dist/fixtures/inertTarget.js.map +2 -2
- package/dist/fixtures/recordedGitHubFlows.d.ts +0 -72
- package/dist/fixtures/recordedGitHubFlows.js +1 -57
- package/dist/fixtures/recordedGitHubFlows.js.map +2 -2
- package/dist/git.d.ts +0 -6
- package/dist/git.js +0 -15
- package/dist/git.js.map +2 -2
- package/dist/github/client.js +0 -3
- package/dist/github/client.js.map +2 -2
- package/dist/github/commandIdentityPolicy.js +0 -1
- package/dist/github/commandIdentityPolicy.js.map +2 -2
- package/dist/github/issueHistory.d.ts +0 -6
- package/dist/github/issueHistory.js +0 -39
- package/dist/github/issueHistory.js.map +2 -2
- package/dist/github/nativeIssueMetadata.d.ts +0 -10
- package/dist/github/nativeIssueMetadata.js +1 -33
- package/dist/github/nativeIssueMetadata.js.map +3 -3
- package/dist/github/projectDelivery.d.ts +0 -34
- package/dist/github/projectDelivery.js +0 -211
- package/dist/github/projectDelivery.js.map +2 -2
- package/dist/github/repo.d.ts +0 -8
- package/dist/github/repo.js +0 -72
- package/dist/github/repo.js.map +2 -2
- package/dist/issue.js +22 -17
- package/dist/issue.js.map +2 -2
- package/dist/issue63Routes.test.js +1 -72
- package/dist/issue63Routes.test.js.map +2 -2
- package/dist/issueInfoReadback.test.js +59 -1
- package/dist/issueInfoReadback.test.js.map +2 -2
- package/dist/issueIntake.test.js +12 -0
- package/dist/issueIntake.test.js.map +2 -2
- package/dist/issueJournal.d.ts +0 -9
- package/dist/issueJournal.js +10 -76
- package/dist/issueJournal.js.map +2 -2
- package/dist/issueJournal.test.js +1 -108
- package/dist/issueJournal.test.js.map +2 -2
- package/dist/issueTracking.test.js +0 -48
- package/dist/issueTracking.test.js.map +2 -2
- package/dist/lifecycle.test.js +12 -48
- package/dist/lifecycle.test.js.map +2 -2
- package/dist/logger.d.ts +0 -4
- package/dist/logger.js +0 -31
- package/dist/logger.js.map +2 -2
- package/dist/mcp/tools.d.ts +2 -618
- package/dist/mcp/tools.js +8 -34
- package/dist/mcp/tools.js.map +2 -2
- package/dist/pluginAuthProbe.js +0 -3
- package/dist/pluginAuthProbe.js.map +2 -2
- package/dist/pluginDoctor.test.js +1 -1
- package/dist/pluginDoctor.test.js.map +2 -2
- package/dist/pluginInstaller.js +0 -3
- package/dist/pluginInstaller.js.map +2 -2
- package/dist/pluginInstaller.test.js +3 -19
- package/dist/pluginInstaller.test.js.map +2 -2
- package/dist/pluginPackaging.test.js +1 -118
- package/dist/pluginPackaging.test.js.map +2 -2
- package/dist/pr.d.ts +2 -73
- package/dist/pr.js +27 -220
- package/dist/pr.js.map +3 -3
- package/dist/pr.test.js +11 -304
- package/dist/pr.test.js.map +2 -2
- package/dist/prAssociation.test.js +112 -22
- package/dist/prAssociation.test.js.map +2 -2
- package/dist/prDispatch.test.js +4 -11
- package/dist/prDispatch.test.js.map +2 -2
- package/dist/releaseWorkflow.test.js +0 -1
- package/dist/releaseWorkflow.test.js.map +2 -2
- package/dist/review.d.ts +0 -82
- package/dist/review.js +3 -94
- package/dist/review.js.map +2 -2
- package/dist/review.test.js +2 -4
- package/dist/review.test.js.map +2 -2
- package/dist/services/agentReadinessService.d.ts +0 -1
- package/dist/services/agentReadinessService.js.map +2 -2
- package/dist/stdoutRegression.test.js +3 -22
- package/dist/stdoutRegression.test.js.map +2 -2
- package/dist/targetPolicyDiscovery.test.js +0 -86
- package/dist/targetPolicyDiscovery.test.js.map +2 -2
- package/dist/targetPolicyEntrypoints.test.js +1 -54
- package/dist/targetPolicyEntrypoints.test.js.map +2 -2
- package/dist/targetRepositoryExecution.test.js +1 -49
- package/dist/targetRepositoryExecution.test.js.map +2 -2
- package/dist/terminalMessages.d.ts +0 -10
- package/dist/terminalMessages.js +1 -31
- package/dist/terminalMessages.js.map +2 -2
- package/dist/toolOutput.js +0 -2
- package/dist/toolOutput.js.map +2 -2
- package/dist/toolOutput.test.js +15 -1
- package/dist/toolOutput.test.js.map +2 -2
- package/dist/verification.d.ts +1 -186
- package/dist/verification.js +29 -587
- package/dist/verification.js.map +3 -3
- package/dist/verificationGate.test.js +4 -90
- package/dist/verificationGate.test.js.map +2 -2
- package/dist/version.d.ts +0 -6
- package/dist/version.js +2 -39
- package/dist/version.js.map +2 -2
- package/package.json +1 -1
- package/plugins/ai-delivery/.claude-plugin/plugin.json +2 -2
- package/plugins/ai-delivery/plugin.json +1 -1
- package/plugins/ai-delivery/runtime/dist/cli.js +118 -162
- package/plugins/ai-delivery/runtime/package.json +1 -1
- package/dist/boardReconcile.test.d.ts +0 -1
- package/dist/boardReconcile.test.js +0 -1746
- package/dist/boardReconcile.test.js.map +0 -7
- package/dist/delivery/delivery.test.d.ts +0 -1
- package/dist/delivery/delivery.test.js +0 -560
- package/dist/delivery/delivery.test.js.map +0 -7
- package/dist/delivery/evidence.d.ts +0 -92
- package/dist/delivery/evidence.js +0 -139
- package/dist/delivery/evidence.js.map +0 -7
- package/dist/delivery/legacy.d.ts +0 -8
- package/dist/delivery/legacy.js +0 -65
- package/dist/delivery/legacy.js.map +0 -7
- package/dist/delivery/policy.d.ts +0 -252
- package/dist/delivery/policy.js +0 -221
- package/dist/delivery/policy.js.map +0 -7
- package/dist/delivery/stage.d.ts +0 -179
- package/dist/delivery/stage.js +0 -242
- package/dist/delivery/stage.js.map +0 -7
- package/dist/deliveryBoard.d.ts +0 -74
- package/dist/deliveryBoard.js +0 -644
- package/dist/deliveryBoard.js.map +0 -7
- package/dist/deliveryBoard.test.d.ts +0 -1
- package/dist/deliveryBoard.test.js +0 -649
- package/dist/deliveryBoard.test.js.map +0 -7
- package/dist/deliveryHealth.test.d.ts +0 -1
- package/dist/deliveryHealth.test.js +0 -191
- package/dist/deliveryHealth.test.js.map +0 -7
- package/dist/fixtures/deliveryBoardReplay.d.ts +0 -56
- package/dist/fixtures/deliveryBoardReplay.js +0 -617
- package/dist/fixtures/deliveryBoardReplay.js.map +0 -7
- package/dist/genericCompatibility.test.d.ts +0 -1
- package/dist/genericCompatibility.test.js +0 -66
- package/dist/genericCompatibility.test.js.map +0 -7
- package/dist/services/boardReconcileService.d.ts +0 -1204
- package/dist/services/boardReconcileService.js +0 -1445
- package/dist/services/boardReconcileService.js.map +0 -7
- package/dist/services/deliveryHealthService.d.ts +0 -84
- package/dist/services/deliveryHealthService.js +0 -204
- package/dist/services/deliveryHealthService.js.map +0 -7
- package/dist/services/legacyIssueMigration.d.ts +0 -46
- package/dist/services/legacyIssueMigration.js +0 -299
- package/dist/services/legacyIssueMigration.js.map +0 -7
- package/dist/utils/filesystem.d.ts +0 -1
- package/dist/utils/filesystem.js +0 -5
- package/dist/utils/filesystem.js.map +0 -7
package/dist/verification.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/verification.ts"],
|
|
4
|
-
"sourcesContent": ["import { spawn, spawnSync } from 'node:child_process';\nimport { randomUUID } from 'node:crypto';\nimport { createRequire, findPackageJSON } from 'node:module';\nimport { types } from 'node:util';\nimport {\n existsSync,\n unlinkSync,\n lstatSync,\n mkdirSync,\n rmdirSync,\n renameSync,\n readFileSync,\n readlinkSync,\n readdirSync,\n realpathSync,\n statfsSync,\n} from 'node:fs';\nimport { dirname, join, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { z } from 'zod';\n\nimport { assertPrivateFile } from './delivery/common.js';\nimport { digestBytes, digestValue, writeRepositoryCommandOutput } from './delivery/legacy.js';\nimport { DeliveryError } from './errors.js';\nimport { gitCommonDir } from './git.js';\nimport { writePrivateJsonFileAtomically } from './utils/atomicJson.js';\n\nexport interface VerificationResourceBounds {\n maxAggregateRssBytes: number;\n maxNewOutputBytes?: number;\n minFreeDiskBytes: number;\n outputRoots?: readonly string[];\n}\n\nconst ResourceSummarySchema = z\n .strictObject({\n bounds: z.strictObject({\n maxAggregateRssBytes: z.number().int().positive().safe(),\n maxNewOutputBytes: z.number().int().positive().safe().optional(),\n minFreeDiskBytes: z.number().int().positive().safe(),\n outputRoots: z.array(z.string().min(1)).min(1).optional(),\n }),\n maxSampledAggregateRssBytes: z.number().int().nonnegative().safe().nullable(),\n maxSampledNewOutputBytes: z.number().int().nonnegative().safe().nullable(),\n minSampledFreeDiskBytes: z.number().int().nonnegative().safe().nullable(),\n observation: z.literal('sampled'),\n outputBaselineId: z\n .string()\n .regex(/^sha256:[a-f0-9]{64}$/u)\n .optional(),\n processCoverage: z.literal('observed-processes-only'),\n sampleCount: z.number().int().nonnegative().safe(),\n })\n .superRefine((value, ctx) => {\n if (\n (value.maxSampledAggregateRssBytes !== null &&\n value.maxSampledAggregateRssBytes > value.bounds.maxAggregateRssBytes) ||\n (value.maxSampledNewOutputBytes !== null &&\n value.bounds.maxNewOutputBytes !== undefined &&\n value.maxSampledNewOutputBytes > value.bounds.maxNewOutputBytes) ||\n (value.minSampledFreeDiskBytes !== null && value.minSampledFreeDiskBytes < value.bounds.minFreeDiskBytes) ||\n (value.sampleCount > 0 &&\n (value.maxSampledAggregateRssBytes === null || value.minSampledFreeDiskBytes === null)) ||\n (value.bounds.maxNewOutputBytes !== undefined &&\n value.sampleCount > 0 &&\n value.maxSampledNewOutputBytes === null) ||\n (value.bounds.maxNewOutputBytes !== undefined) !== (value.outputBaselineId !== undefined)\n )\n ctx.addIssue({ code: 'custom', message: 'Resource samples do not satisfy their declared bounds.' });\n });\nexport type VerificationResourceSummary = z.infer<typeof ResourceSummarySchema>;\n\ninterface ResourceSample {\n aggregateRssBytes: number;\n freeDiskBytes: number;\n newOutputBytes?: number;\n ownedProcessCount: number;\n}\n\nconst OUTPUT_GATE_ENV = 'AI_DELIVERY_OUTPUT_OBSERVATION_GATE';\nconst GateOwnerSchema = z.strictObject({ pid: z.number().int().positive(), identity: z.string().min(1) });\nconst OutputGateSchema = z.strictObject({ directory: z.string().min(1), id: z.uuid(), owner: GateOwnerSchema });\nconst GateClaimSchema = z.strictObject({\n gateId: z.uuid(),\n id: z.uuid(),\n kind: z.enum(['scan', 'fixture']),\n owner: GateOwnerSchema,\n});\ntype OutputGate = z.infer<typeof OutputGateSchema>;\ntype GateClaim = z.infer<typeof GateClaimSchema>;\n\nfunction gateOwner(snapshot = processSnapshot()): z.infer<typeof GateOwnerSchema> {\n const owner = snapshot.get(process.pid);\n if (!owner) throw new DeliveryError('Filesystem observation gate owner is unavailable.');\n return { pid: owner.pid, identity: owner.identity };\n}\n\nfunction assertGateDirectory(path: string): void {\n const metadata = lstatSync(path);\n if (!metadata.isDirectory() || (metadata.mode & 0o077) !== 0 || realpathSync(path) !== path)\n throw new DeliveryError('Filesystem observation gate directory is invalid.');\n}\n\nfunction readOutputGate(value: string): OutputGate {\n try {\n const gate = OutputGateSchema.parse(JSON.parse(value) as unknown);\n assertOutputGate(gate);\n return gate;\n } catch (error) {\n throw new DeliveryError(\n 'Filesystem observation gate capability is invalid or stale: ' +\n (error instanceof Error ? error.message : String(error)),\n );\n }\n}\n\nfunction gateOwnerAlive(owner: z.infer<typeof GateOwnerSchema>, snapshot = processSnapshot()): boolean {\n const current = snapshot.get(owner.pid);\n return current?.identity === owner.identity && !current.status.startsWith('Z');\n}\n\nfunction assertOutputGate(gate: OutputGate, abandoned = false): Map<number, ObservedProcess> {\n assertGateDirectory(gate.directory);\n const manifest = OutputGateSchema.parse(\n JSON.parse(assertPrivateFile(join(gate.directory, 'gate.json')).toString('utf8')) as unknown,\n );\n const snapshot = processSnapshot();\n let actor = snapshot.get(process.pid);\n const ancestors = new Set<number>();\n while (actor && actor.pid !== gate.owner.pid && !ancestors.has(actor.pid)) {\n ancestors.add(actor.pid);\n actor = snapshot.get(actor.ppid);\n }\n if (\n digestValue(manifest) !== digestValue(gate) ||\n (abandoned\n ? gateOwnerAlive(gate.owner, snapshot)\n : !gateOwnerAlive(gate.owner, snapshot) || actor?.identity !== gate.owner.identity)\n )\n throw new DeliveryError(\n 'Filesystem observation gate ownership changed, was abandoned or is not an inherited ancestor.',\n );\n return snapshot;\n}\n\nfunction readGateClaim(gate: OutputGate, path: string): GateClaim {\n const claim = GateClaimSchema.parse(JSON.parse(assertPrivateFile(path).toString('utf8')) as unknown);\n if (claim.gateId !== gate.id) throw new DeliveryError('Filesystem observation gate claim belongs to another run.');\n return claim;\n}\n\nfunction gateScanRequests(gate: OutputGate, snapshot?: Map<number, ObservedProcess>): string[] {\n const directory = join(gate.directory, 'requests');\n assertGateDirectory(directory);\n const requests = readdirSync(directory);\n if (requests.length > 1024 || requests.some((name) => !/^[a-f0-9-]{36}\\.json$/u.test(name)))\n throw new DeliveryError('Filesystem observation gate scan requests are invalid.');\n const live: string[] = [];\n const currentSnapshot = snapshot ?? processSnapshot();\n for (const name of requests) {\n let claim: GateClaim;\n try {\n claim = readGateClaim(gate, join(directory, name));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue;\n throw error;\n }\n if (claim.kind !== 'scan' || name !== claim.id + '.json' || !gateOwnerAlive(claim.owner, currentSnapshot))\n throw new DeliveryError('Filesystem observation gate scan request was abandoned.');\n live.push(name);\n }\n return live;\n}\n\nfunction removeGateClaim(gate: OutputGate, path: string, claim: GateClaim): void {\n if (digestValue(readGateClaim(gate, path)) !== digestValue(claim))\n throw new DeliveryError('Filesystem observation gate claim changed before release.');\n unlinkSync(path);\n}\n\nasync function withOutputGateLock<T>(\n gate: OutputGate | undefined,\n kind: 'scan' | 'fixture',\n operation: () => T | Promise<T>,\n signal?: AbortSignal,\n): Promise<T> {\n if (!gate) return operation();\n // Self identity belongs to this same synchronous ownership check, before any claim publication.\n const ownerSnapshot = assertOutputGate(gate);\n const claim: GateClaim = { gateId: gate.id, id: randomUUID(), kind, owner: gateOwner(ownerSnapshot) };\n const request = kind === 'scan' ? join(gate.directory, 'requests', claim.id + '.json') : undefined;\n const lock = join(gate.directory, 'held');\n const holder = join(lock, 'owner.json');\n if (request) {\n const staging = join(gate.directory, claim.id + '.pending');\n writePrivateJsonFileAtomically(staging, claim);\n renameSync(staging, request);\n }\n let acquired: { dev: number; ino: number } | undefined;\n let incompleteSince: number | undefined;\n let fixtureWait: { claimId: string; since: number } | undefined;\n const release = (): void => {\n if (!acquired) return;\n const metadata = lstatSync(lock);\n if (!metadata.isDirectory() || metadata.dev !== acquired.dev || metadata.ino !== acquired.ino)\n throw new DeliveryError('Filesystem observation gate lock changed before release.');\n if (readdirSync(lock).join(',') !== 'owner.json')\n throw new DeliveryError('Filesystem observation gate lock has unrelated metadata.');\n removeGateClaim(gate, holder, claim);\n rmdirSync(lock);\n acquired = undefined;\n };\n try {\n for (;;) {\n if (signal?.aborted) throw new DeliveryError('Filesystem observation gate wait cancelled.');\n const currentSnapshot = assertOutputGate(gate);\n const requests = gateScanRequests(gate, currentSnapshot);\n if (kind === 'scan' || requests.length === 0) {\n let created = false;\n try {\n mkdirSync(lock, { mode: 0o700 });\n created = true;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;\n }\n if (created) {\n const metadata = lstatSync(lock);\n acquired = { dev: metadata.dev, ino: metadata.ino };\n writePrivateJsonFileAtomically(holder, claim);\n // A scan may queue between the fixture's request check and atomic lock acquisition.\n if (kind === 'scan' || gateScanRequests(gate).length === 0) return await operation();\n release();\n }\n }\n if (existsSync(lock)) {\n try {\n assertGateDirectory(lock);\n const current = readGateClaim(gate, holder);\n incompleteSince = undefined;\n if (!gateOwnerAlive(current.owner))\n throw new DeliveryError('Filesystem observation gate fixture or scanner was abandoned.');\n if (kind === 'scan' && current.kind === 'fixture') {\n if (fixtureWait?.claimId !== current.id) fixtureWait = { claimId: current.id, since: Date.now() };\n // A negative reader that blocks prevents strict output observation; terminate this command, never steal its live lease.\n if (Date.now() - fixtureWait.since > 5000)\n throw new DeliveryError(\n 'Filesystem-negative fixture did not release a waiting output scan within 5 seconds; reader or teardown is stalled.',\n );\n } else fixtureWait = undefined;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n incompleteSince ??= Date.now();\n // A concrete publication failure, never an elapsed fixture-work allowance or stale-lock takeover.\n if (Date.now() - incompleteSince > 2000)\n throw new DeliveryError('Filesystem observation gate owner publication is incomplete.');\n }\n }\n await new Promise<void>((resolve) => setTimeout(resolve, 100));\n }\n } finally {\n try {\n release();\n } finally {\n if (request) removeGateClaim(gate, request, claim);\n }\n }\n}\n\n/** Run a real filesystem-negative fixture between strict scans; the callback must clean it up before returning. */\nexport async function withVerificationFilesystemFixture<T>(operation: () => T | Promise<T>): Promise<T> {\n const capability = process.env[OUTPUT_GATE_ENV];\n return withOutputGateLock(capability === undefined ? undefined : readOutputGate(capability), 'fixture', operation);\n}\n\ninterface OutputBaseline {\n gate?: OutputGate;\n baselineId: string;\n files: Map<string, number>;\n links: Map<string, { identity: string; target: string; missing: boolean }>;\n roots: string[];\n}\n\nclass OutputObservationError extends DeliveryError {\n override readonly cause: unknown;\n readonly code: string | undefined;\n\n constructor(message: string, path: string, cause: unknown) {\n const code = (cause as NodeJS.ErrnoException).code;\n super(\n `${message} Path ${JSON.stringify(path)} (${code ?? 'unknown errno'}): ${cause instanceof Error ? cause.message : String(cause)}`,\n );\n this.code = code;\n this.cause = cause;\n }\n}\n\nfunction scanOutputRoots(\n roots: readonly string[],\n links: OutputBaseline['links'],\n commandRunning = false,\n onMissingTarget?: (reason: string) => void,\n): Map<string, number> {\n const files = new Map<string, number>();\n const observedLinks: OutputBaseline['links'] = new Map();\n const visit = (path: string): void => {\n let metadata;\n try {\n metadata = lstatSync(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;\n throw new OutputObservationError('Filesystem output lstat failed.', path, error);\n }\n if (metadata.isSymbolicLink()) {\n let link: string;\n try {\n link = readlinkSync(path);\n } catch (error) {\n throw new OutputObservationError('Filesystem output readlink failed.', path, error);\n }\n const identity = digestValue({\n device: metadata.dev,\n inode: metadata.ino,\n changed: metadata.ctimeMs,\n modified: metadata.mtimeMs,\n link,\n });\n let target: string;\n let missing = false;\n try {\n target = realpathSync(path);\n } catch (error) {\n const failure = new OutputObservationError(\n 'Filesystem output observation encountered a broken or cyclic symbolic link.',\n path,\n error,\n );\n const previous = links.get(path);\n if (previous !== undefined && previous.identity !== identity)\n throw new DeliveryError(`Filesystem output alias identity changed. Path ${JSON.stringify(path)}.`);\n if (!commandRunning || failure.code !== 'ENOENT' || previous?.identity !== identity) throw failure;\n // A validated alias contributes no physical file bytes. Resolve the missing suffix through\n // its current existing ancestor, so an ancestor retarget cannot hide an escaping output.\n let lexical = resolve(dirname(path), link);\n let ancestor = lexical;\n const expanded = new Set([path]);\n for (;;) {\n try {\n target = join(realpathSync(ancestor), lexical.slice(ancestor.length));\n break;\n } catch (ancestorError) {\n if ((ancestorError as NodeJS.ErrnoException).code !== 'ENOENT' || dirname(ancestor) === ancestor)\n throw new OutputObservationError(\n 'Filesystem output ancestor resolution failed.',\n ancestor,\n ancestorError,\n );\n let ancestorMetadata;\n try {\n ancestorMetadata = lstatSync(ancestor);\n } catch (metadataError) {\n if ((metadataError as NodeJS.ErrnoException).code !== 'ENOENT')\n throw new OutputObservationError('Filesystem output ancestor lstat failed.', ancestor, metadataError);\n }\n if (ancestorMetadata?.isSymbolicLink()) {\n let ancestorLink, currentAncestor;\n try {\n ancestorLink = readlinkSync(ancestor);\n currentAncestor = lstatSync(ancestor);\n } catch (aliasError) {\n throw new OutputObservationError('Filesystem output ancestor alias read failed.', ancestor, aliasError);\n }\n const ancestorIdentity = digestValue({\n device: ancestorMetadata.dev,\n inode: ancestorMetadata.ino,\n changed: ancestorMetadata.ctimeMs,\n modified: ancestorMetadata.mtimeMs,\n link: ancestorLink,\n });\n const previousAncestor = links.get(ancestor);\n if (previousAncestor === undefined) throw failure;\n if (\n expanded.has(ancestor) ||\n previousAncestor.identity !== ancestorIdentity ||\n !currentAncestor.isSymbolicLink() ||\n currentAncestor.dev !== ancestorMetadata.dev ||\n currentAncestor.ino !== ancestorMetadata.ino ||\n currentAncestor.ctimeMs !== ancestorMetadata.ctimeMs ||\n currentAncestor.mtimeMs !== ancestorMetadata.mtimeMs\n )\n throw new DeliveryError(\n `Filesystem output ancestor alias identity changed. Path ${JSON.stringify(ancestor)}.`,\n );\n expanded.add(ancestor);\n lexical = join(resolve(dirname(ancestor), ancestorLink), lexical.slice(ancestor.length));\n ancestor = lexical;\n continue;\n }\n ancestor = dirname(ancestor);\n }\n }\n if (target !== previous.target)\n throw new DeliveryError(`Filesystem output alias target identity changed. Path ${JSON.stringify(path)}.`);\n missing = true;\n onMissingTarget?.(failure.message);\n }\n const previous = links.get(path);\n if (previous?.missing && (previous.identity !== identity || previous.target !== target))\n throw new DeliveryError(\n `Filesystem output alias identity changed after target absence. Path ${JSON.stringify(path)}.`,\n );\n if (!roots.some((root) => target === root || target.startsWith(`${root}${sep}`))) {\n throw new DeliveryError(\n `Filesystem output observation encountered an escaping symbolic link. Path ${JSON.stringify(path)} resolves to ${JSON.stringify(target)}.`,\n );\n }\n let current;\n try {\n current = lstatSync(path);\n } catch (error) {\n // A previously validated alias removed during this visit has no physical payload.\n // Continue the complete current scan, publishing no identity for the vanished alias.\n if (commandRunning && (error as NodeJS.ErrnoException).code === 'ENOENT' && previous?.identity === identity)\n return;\n throw new OutputObservationError('Filesystem output alias identity readback failed.', path, error);\n }\n if (\n !current.isSymbolicLink() ||\n current.dev !== metadata.dev ||\n current.ino !== metadata.ino ||\n current.ctimeMs !== metadata.ctimeMs ||\n current.mtimeMs !== metadata.mtimeMs\n )\n throw new DeliveryError(\n `Filesystem output alias identity changed during observation. Path ${JSON.stringify(path)}.`,\n );\n observedLinks.set(path, { identity, target, missing });\n // Observe physical targets through their declared root only, never traverse aliases.\n return;\n }\n if (metadata.isDirectory()) {\n let names: string[];\n try {\n names = readdirSync(path);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return;\n throw new OutputObservationError('Filesystem output readdir failed.', path, error);\n }\n for (const name of names) visit(join(path, name));\n return;\n }\n if ((!metadata.isFile() && !metadata.isSocket()) || !Number.isSafeInteger(metadata.size)) {\n throw new DeliveryError(\n `Filesystem output observation encountered an unsupported file. Path ${JSON.stringify(path)}.`,\n );\n }\n // Unix IPC endpoints store no regular-file payload, but still count toward the scan's entry limit.\n files.set(path, metadata.isSocket() ? 0 : metadata.size);\n if (files.size > 1_000_000) throw new DeliveryError('Filesystem output observation exceeded its file limit.');\n };\n for (const root of roots) {\n if (existsSync(root) && realpathSync(root) !== root)\n throw new DeliveryError('Filesystem output roots must not be symbolic links.');\n visit(root);\n }\n // Publish alias identities only with the complete physical-file scan that validated them.\n links.clear();\n for (const [path, link] of observedLinks) links.set(path, link);\n return files;\n}\n\nasync function positiveNewOutputBytes(\n baseline: OutputBaseline,\n signal?: AbortSignal,\n commandRunning = false,\n onUnavailable?: (reason: string) => void,\n): Promise<number> {\n let files: Map<string, number>;\n let firstFailure: OutputObservationError | undefined;\n let lastFailure: OutputObservationError | undefined;\n let firstFailureAt: number | undefined;\n const assertObservationWindow = (): void => {\n if (firstFailureAt !== undefined && Date.now() - firstFailureAt >= 1_000) {\n throw new DeliveryError(\n `Filesystem output observation remained unavailable for 1 second. First observation: ${firstFailure!.message} Last observation: ${lastFailure!.message}`,\n );\n }\n };\n for (;;) {\n if (signal?.aborted) throw new DeliveryError('Filesystem output observation cancelled.');\n assertObservationWindow();\n try {\n files = await withOutputGateLock(\n baseline.gate,\n 'scan',\n () => scanOutputRoots(baseline.roots, baseline.links, commandRunning, onUnavailable),\n signal,\n );\n assertObservationWindow();\n break;\n } catch (error) {\n // Unvalidated aliases still prevent a complete scan. Retry only during a command,\n // with the stall window starting at the first failed scan, not before that scan.\n if (!commandRunning || !(error instanceof OutputObservationError) || error.code !== 'ENOENT') throw error;\n lastFailure = error;\n if (firstFailure === undefined) {\n firstFailureAt = Date.now();\n firstFailure = error;\n onUnavailable?.(error.message);\n }\n assertObservationWindow();\n await new Promise<void>((resolve) => setTimeout(resolve, 25));\n }\n }\n let bytes = 0;\n for (const [path, size] of files) {\n bytes += Math.max(0, size - (baseline.files.get(path) ?? 0));\n if (!Number.isSafeInteger(bytes)) throw new DeliveryError('Filesystem output observation overflowed.');\n }\n return bytes;\n}\n\nfunction availableDiskBytes(path: string): bigint {\n let existing = path;\n for (;;) {\n try {\n const disk = statfsSync(existing, { bigint: true });\n return disk.bavail * disk.bsize;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || dirname(existing) === existing) throw error;\n existing = dirname(existing);\n }\n }\n}\n\nfunction freeDiskBytes(repoRoot: string, baseline?: OutputBaseline): number {\n const roots = baseline === undefined ? [repoRoot] : [repoRoot, ...baseline.roots];\n const minimum = roots.reduce((value, path) => {\n const available = availableDiskBytes(path);\n return available < value ? available : value;\n }, BigInt(Number.MAX_SAFE_INTEGER));\n if (minimum > BigInt(Number.MAX_SAFE_INTEGER)) throw new DeliveryError('Free disk observation overflowed.');\n return Number(minimum);\n}\n\ninterface ObservedProcess {\n identity: string;\n pgid: number;\n pid: number;\n ppid: number;\n rssBytes: number;\n status: string;\n}\n\nexport interface OwnedProcessState {\n rootIdentity?: string;\n rootPid: number;\n sampled: boolean;\n tracked: Map<number, ObservedProcess>;\n}\n\nclass ProcessSnapshotError extends DeliveryError {}\n\nexport function processSnapshot(): Map<number, ObservedProcess> {\n const psPath = existsSync('/usr/bin/ps') ? '/usr/bin/ps' : '/bin/ps';\n const started = performance.now();\n const result = spawnSync(psPath, ['-A', '-o', 'pid=,ppid=,pgid=,rss=,stat=,lstart='], {\n encoding: 'utf8',\n // The absolute observer needs no author tokens, App keys or preload selectors.\n env: { LC_ALL: 'C' },\n maxBuffer: 4 * 1024 * 1024,\n timeout: 1_000,\n });\n if (result.status !== 0 || result.error || result.signal || !result.stdout.endsWith('\\n')) {\n const elapsedMs = Math.round(performance.now() - started);\n const stdout = typeof result.stdout === 'string' ? result.stdout : '';\n let completeLines = 0;\n for (let index = 0; index < stdout.length; index++) if (stdout.charCodeAt(index) === 10) completeLines++;\n const code = (result.error as NodeJS.ErrnoException | undefined)?.code;\n const signal = result.signal;\n // Only fixed labels, bounded numbers and completeness flags leave this observation.\n const metadata = {\n status: Number.isSafeInteger(result.status) ? result.status : null,\n errorCode:\n code === undefined\n ? null\n : ['EACCES', 'EPERM', 'ETIMEDOUT', 'ENOENT', 'ENOBUFS', 'EAGAIN', 'ENOMEM', 'EIO', 'EINVAL'].includes(code)\n ? code\n : 'other',\n signal:\n signal === null\n ? null\n : ['SIGTERM', 'SIGKILL', 'SIGINT', 'SIGABRT', 'SIGSEGV', 'SIGBUS', 'SIGHUP', 'SIGQUIT', 'SIGPIPE'].includes(\n signal,\n )\n ? signal\n : 'other',\n stdoutPresent: typeof result.stdout === 'string',\n stdoutTerminated: typeof result.stdout === 'string' && result.stdout.endsWith('\\n'),\n elapsedMs,\n stdoutBytes: Buffer.byteLength(stdout),\n completeLines,\n };\n throw new ProcessSnapshotError(`Owned process resource observation failed. ${JSON.stringify(metadata)}`);\n }\n const snapshot = new Map<number, ObservedProcess>();\n for (const line of result.stdout.trim().split('\\n')) {\n const match = /^(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(.+)$/u.exec(line.trim());\n if (!match) throw new DeliveryError('Owned process resource observation is ambiguous.');\n const observed = {\n pid: Number(match[1]),\n ppid: Number(match[2]),\n pgid: Number(match[3]),\n rssBytes: Number(match[4]) * 1_024,\n status: match[5]!,\n identity: match[6]!,\n };\n if (\n !Number.isSafeInteger(observed.pid) ||\n observed.pid <= 0 ||\n !Number.isSafeInteger(observed.ppid) ||\n !Number.isSafeInteger(observed.pgid) ||\n !Number.isSafeInteger(observed.rssBytes) ||\n snapshot.has(observed.pid)\n )\n throw new DeliveryError('Owned process resource observation is ambiguous.');\n snapshot.set(observed.pid, observed);\n }\n return snapshot;\n}\n\nfunction observeOwnedProcesses(state: OwnedProcessState, snapshot: Map<number, ObservedProcess>): ObservedProcess[] {\n const root = snapshot.get(state.rootPid);\n if (state.rootIdentity === undefined) {\n if (root === undefined || root.status.startsWith('Z') || root.pgid !== state.rootPid) {\n throw new DeliveryError('Owned process identity could not be established before the command exited.');\n }\n state.rootIdentity = root.identity;\n state.tracked.set(root.pid, root);\n } else if (root !== undefined && root.identity !== state.rootIdentity) {\n throw new DeliveryError('Owned process identity changed during verification.');\n }\n const selected = new Map<number, ObservedProcess>();\n for (const [pid, previous] of state.tracked) {\n const current = snapshot.get(pid);\n if (current === undefined || current.status.startsWith('Z')) state.tracked.delete(pid);\n else if (current.identity !== previous.identity) {\n throw new DeliveryError('Tracked process identity changed during verification.');\n } else selected.set(pid, current);\n }\n for (const member of snapshot.values()) {\n if (!member.status.startsWith('Z') && member.pgid === state.rootPid) selected.set(member.pid, member);\n }\n const children = new Map<number, ObservedProcess[]>();\n for (const member of snapshot.values()) {\n const siblings = children.get(member.ppid) ?? [];\n siblings.push(member);\n children.set(member.ppid, siblings);\n }\n const pending = [...selected.values()];\n for (const parent of pending)\n for (const child of children.get(parent.pid) ?? []) {\n if (!child.status.startsWith('Z') && !selected.has(child.pid)) {\n selected.set(child.pid, child);\n pending.push(child);\n }\n }\n for (const member of selected.values()) state.tracked.set(member.pid, member);\n state.sampled = true;\n return [...selected.values()];\n}\n\nfunction sampleOwnedTree(\n state: OwnedProcessState,\n repoRoot: string,\n bounds: VerificationResourceBounds,\n baseline?: OutputBaseline,\n newOutputBytes?: number,\n controllerRssBytes = 0,\n includeControllerTree = false,\n): ResourceSample {\n const snapshot = processSnapshot();\n const owned = observeOwnedProcesses(state, snapshot);\n const controller = includeControllerTree\n ? controllerTreeRssBytes(snapshot, new Set(owned.map((member) => member.pid)))\n : controllerRssBytes;\n const rssBytes = owned.reduce((total, member) => total + member.rssBytes, controller);\n if (!Number.isSafeInteger(rssBytes))\n throw new DeliveryError('Owned aggregate RSS is outside the safe integer range.');\n if (rssBytes > bounds.maxAggregateRssBytes) {\n throw new DeliveryError(`Owned aggregate RSS ${rssBytes} exceeded limit ${bounds.maxAggregateRssBytes}.`);\n }\n const available = freeDiskBytes(repoRoot, baseline);\n if (available < bounds.minFreeDiskBytes)\n throw new DeliveryError(`Free disk fell below limit ${bounds.minFreeDiskBytes}.`);\n if (newOutputBytes !== undefined && !Number.isSafeInteger(newOutputBytes)) {\n throw new DeliveryError('Filesystem output observation overflowed.');\n }\n if (baseline !== undefined && bounds.maxNewOutputBytes !== undefined) {\n if (newOutputBytes !== undefined && newOutputBytes > bounds.maxNewOutputBytes) {\n throw new DeliveryError(\n `Positive new filesystem output ${newOutputBytes} exceeded limit ${bounds.maxNewOutputBytes}.`,\n );\n }\n }\n return {\n aggregateRssBytes: rssBytes,\n freeDiskBytes: available,\n ...(newOutputBytes === undefined ? {} : { newOutputBytes }),\n ownedProcessCount: owned.length,\n };\n}\n\n/** Accounting includes the caller's tree; containment remains restricted to the recorded command. */\nfunction controllerTreeRssBytes(snapshot = processSnapshot(), excluded = new Set<number>()): number {\n const controller = snapshot.get(process.pid);\n if (controller === undefined || controller.status.startsWith('Z'))\n throw new DeliveryError('Runtime setup controller resource observation is unavailable.');\n const selected = new Set([process.pid]);\n let bytes = process.memoryUsage().rss;\n for (const pid of selected)\n for (const member of snapshot.values())\n if (member.ppid === pid && !member.status.startsWith('Z') && !selected.has(member.pid)) {\n selected.add(member.pid);\n if (!excluded.has(member.pid)) bytes += member.rssBytes;\n }\n if (!Number.isSafeInteger(bytes)) throw new DeliveryError('Controller aggregate RSS observation overflowed.');\n return bytes;\n}\n\nexport async function confirmOwnedCleanup(state: OwnedProcessState): Promise<void> {\n if (!state.sampled || state.rootIdentity === undefined) {\n throw new DeliveryError('Owned process cleanup cannot be verified without a root identity.');\n }\n const deadline = Date.now() + 2_000;\n for (;;) {\n const snapshot = processSnapshot();\n const root = snapshot.get(state.rootPid);\n if (root !== undefined && root.identity !== state.rootIdentity) {\n throw new DeliveryError('Owned process group identity changed before cleanup readback.');\n }\n const groupAlive = [...snapshot.values()].some(\n (member) => member.pgid === state.rootPid && !member.status.startsWith('Z'),\n );\n const trackedAlive = [...state.tracked.values()].some((previous) => {\n const current = snapshot.get(previous.pid);\n if (current === undefined || current.status.startsWith('Z')) return false;\n if (current.identity !== previous.identity)\n throw new DeliveryError('Tracked process identity changed before cleanup readback.');\n return true;\n });\n if (!groupAlive && !trackedAlive) return;\n if (Date.now() >= deadline) throw new DeliveryError('Owned process cleanup did not release every sampled process.');\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n}\n\n/** Signal only birth identities established by this command, including observed detached children. */\nexport function terminateOwnedProcesses(state: OwnedProcessState): void {\n if (!state.sampled || state.rootIdentity === undefined) throw new DeliveryError('Owned process identity is unknown.');\n const snapshot = processSnapshot();\n const root = snapshot.get(state.rootPid);\n if (root !== undefined && root.identity !== state.rootIdentity)\n throw new DeliveryError('Owned process group identity changed before cleanup.');\n const alive = [...state.tracked.values()].flatMap((previous) => {\n const current = snapshot.get(previous.pid);\n if (current === undefined || current.status.startsWith('Z')) return [];\n if (current.identity !== previous.identity)\n throw new DeliveryError('Tracked process identity changed before cleanup.');\n return [current];\n });\n const group = [...snapshot.values()].filter(\n (member) => member.pgid === state.rootPid && !member.status.startsWith('Z'),\n );\n if (group.length > 0 && !alive.some((member) => member.pgid === state.rootPid))\n throw new DeliveryError('Owned process group has no surviving recorded identity; cleanup is ambiguous.');\n const signal = (pid: number): void => {\n try {\n process.kill(pid, 'SIGKILL');\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ESRCH') return;\n if (code !== 'EPERM') throw error;\n // macOS can return EPERM when the last group member exits after our snapshot.\n // Accept only fresh absence/zombie proof; a live target remains a cleanup failure.\n const readback = processSnapshot();\n if (pid < 0) {\n const currentRoot = readback.get(state.rootPid);\n if (currentRoot !== undefined && currentRoot.identity !== state.rootIdentity)\n throw new DeliveryError('Owned process group identity changed during cleanup signal readback.');\n if ([...readback.values()].some((member) => member.pgid === state.rootPid && !member.status.startsWith('Z')))\n throw error;\n } else {\n const current = readback.get(pid);\n if (current !== undefined && current.identity !== state.tracked.get(pid)?.identity)\n throw new DeliveryError('Tracked process identity changed during cleanup signal readback.');\n if (current !== undefined && !current.status.startsWith('Z')) throw error;\n }\n }\n };\n if (group.length > 0) signal(-state.rootPid);\n for (const member of alive.reverse()) signal(member.pid);\n}\n\ninterface VerificationWriter {\n starting(): void;\n observed(state: OwnedProcessState): void;\n idle(): void;\n assertQuiescent(): void;\n}\n\nfunction producerContent(root: string) {\n const code: { path: string; digest: string }[] = [];\n const collect = (directory: string): void => {\n for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const path = join(directory, entry.name);\n if (entry.isDirectory()) collect(path);\n else if (entry.isFile() && entry.name.endsWith('.js') && !entry.name.endsWith('.test.js'))\n code.push({ path: path.slice(root.length + 1), digest: digestBytes(readFileSync(path)) });\n }\n };\n collect(root);\n const dependencies = new Map<string, string>();\n const collectDependencies = (manifestPath: string): void => {\n if (dependencies.has(manifestPath)) return;\n const bytes = readFileSync(manifestPath);\n const manifest = z\n .object({ dependencies: z.record(z.string(), z.string()).optional() })\n .parse(JSON.parse(bytes.toString('utf8')));\n dependencies.set(manifestPath, digestBytes(bytes));\n const require = createRequire(manifestPath);\n for (const name of Object.keys(manifest.dependencies ?? {}).sort()) {\n let resolved: string;\n try {\n resolved = require.resolve(`${name}/package.json`);\n } catch {\n try {\n resolved = require.resolve(name);\n } catch (error) {\n if (!types.isNativeError(error) || Reflect.get(error, 'code') !== 'ERR_PACKAGE_PATH_NOT_EXPORTED')\n throw error;\n const manifest = findPackageJSON(name, manifestPath);\n if (!manifest) throw error;\n resolved = manifest;\n }\n }\n let directory = dirname(resolved);\n for (;;) {\n const path = join(directory, 'package.json');\n if (existsSync(path)) {\n const candidate = z.object({ name: z.string().optional() }).parse(JSON.parse(readFileSync(path, 'utf8')));\n if (candidate.name === name) {\n collectDependencies(path);\n break;\n }\n }\n const parent = dirname(directory);\n if (parent === directory) throw new DeliveryError(`Producer dependency identity is unavailable for ${name}.`);\n directory = parent;\n }\n }\n };\n collectDependencies(join(dirname(root), 'package.json'));\n return { code, dependencies: [...dependencies].sort(([a], [b]) => a.localeCompare(b)) };\n}\n\nfunction producerDigest(root = dirname(fileURLToPath(import.meta.url))): string {\n return digestValue(producerContent(root));\n}\n\n/** @internal Retained public code is hashed as data; it is never imported or executed. */\nexport function retainedWorktreeTransitionProducerDigest(distDirectory: string): string {\n return producerDigest(realpathSync(distDirectory));\n}\n\n/** @internal Preserve the same dependency manifests that participate in the existing producer digest. */\nexport function retainedWorktreeTransitionDependencyManifests(\n distDirectory: string,\n): { source: string; digest: string }[] {\n return producerContent(realpathSync(distDirectory)).dependencies.map(([source, digest]) => ({ source, digest }));\n}\n\nexport function runStageCommand(\n repoRoot: string,\n argv: readonly string[],\n abortSignal?: AbortSignal,\n onRunning?: (capturedOutputBytes: number, resource?: ResourceSample, reason?: string) => void,\n resourceBounds?: VerificationResourceBounds,\n baseline?: OutputBaseline,\n onResourceSample?: (sample: ResourceSample) => void,\n writer?: VerificationWriter,\n execution?: {\n environment: NodeJS.ProcessEnv;\n cwd?: string;\n maxCapturedOutputBytes?: number;\n includeControllerTree?: boolean;\n onCaptured?(bytes: number): void;\n onCleanupFailure?(reason: string): void;\n failedOutput?(bytes: Buffer): string;\n stdoutOnly?: boolean;\n },\n): Promise<Buffer> {\n const [executable, ...args] = argv;\n if (!executable) throw new DeliveryError('Policy selected an empty stage command.');\n if (abortSignal?.aborted) throw new DeliveryError('Selected policy stage command cancelled.');\n writer?.starting();\n return new Promise((resolve, reject) => {\n // The shell waits for our ownership receipt, then exec preserves its PID, birth identity and process group.\n const child = spawn(\n '/bin/sh',\n [\n '-c',\n 'IFS= read -r ready || exit 125; [ \"$ready\" = run ] || exit 125; exec \"$@\" </dev/null',\n 'ai-delivery-command',\n executable,\n ...args,\n ],\n {\n cwd: execution?.cwd ?? repoRoot,\n detached: process.platform !== 'win32',\n stdio: ['pipe', 'pipe', 'pipe'],\n ...(baseline?.gate === undefined && execution === undefined\n ? {}\n : {\n env: {\n ...(execution?.environment ?? process.env),\n ...(baseline?.gate === undefined ? {} : { [OUTPUT_GATE_ENV]: JSON.stringify(baseline.gate) }),\n },\n }),\n },\n );\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n const owned: OwnedProcessState | undefined =\n process.platform === 'win32' || child.pid === undefined\n ? undefined\n : { rootPid: child.pid, sampled: false, tracked: new Map() };\n let outputBytes = 0;\n let retainedOutputBytes = 0;\n const outputLimit = execution?.maxCapturedOutputBytes ?? 8 * 1024 * 1024;\n let sampledOutputBytes = 0;\n let failure: string | undefined;\n let cleanupFailure: string | undefined;\n let writerFailure: string | undefined;\n let closed = false;\n let settled = false;\n let commandReleased = false;\n let firstOutputObservationFailure: string | undefined;\n let lastOutputObservationFailure: string | undefined;\n let pendingOutput: Promise<void> | undefined;\n const scanCancellation = new AbortController();\n const failedOutput = (): string => {\n const observation =\n firstOutputObservationFailure === undefined\n ? ''\n : ` First filesystem observation: ${firstOutputObservationFailure} Last filesystem observation: ${lastOutputObservationFailure}`;\n try {\n const bytes = Buffer.concat([...stdout, ...stderr]);\n if (execution?.failedOutput) return execution.failedOutput(bytes);\n return ` Command output ${writeRepositoryCommandOutput({ bytes, gitCommonDir: gitCommonDir(repoRoot) })}.${observation}`;\n } catch (error) {\n return ` Command output persistence failed (${error instanceof Error ? error.message : String(error)}).${observation}`;\n }\n };\n let closeTimer: NodeJS.Timeout | undefined;\n let exitPipeTimer: NodeJS.Timeout | undefined;\n let resourceTimer: NodeJS.Timeout | undefined;\n const clearWatchers = (): void => {\n clearInterval(progressTimer);\n if (resourceTimer !== undefined) clearInterval(resourceTimer);\n if (closeTimer !== undefined) clearTimeout(closeTimer);\n if (exitPipeTimer !== undefined) clearTimeout(exitPipeTimer);\n abortSignal?.removeEventListener('abort', onAbort);\n process.removeListener('SIGINT', onSigint);\n process.removeListener('SIGTERM', onSigterm);\n };\n const killOwned = (): void => {\n if (child.pid === undefined) return;\n if (owned?.sampled) {\n try {\n observeOwnedProcesses(owned, processSnapshot());\n } catch (error) {\n cleanupFailure ??= error instanceof Error ? error.message : String(error);\n }\n try {\n writer?.observed(owned);\n } catch (error) {\n writerFailure ??= error instanceof Error ? error.message : String(error);\n }\n // Durable state failure cannot prevent identity-checked termination of known-owned processes.\n try {\n terminateOwnedProcesses(owned);\n } catch (error) {\n cleanupFailure ??= error instanceof Error ? error.message : String(error);\n }\n } else {\n try {\n // The still-owned direct child is the only safe signal target before identity observation.\n if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');\n if (commandReleased) cleanupFailure ??= 'owned process identity was not observed before cleanup';\n } catch (error) {\n cleanupFailure ??= error instanceof Error ? error.message : String(error);\n }\n }\n };\n const stop = (reason: string): void => {\n if (failure !== undefined) return;\n failure = reason;\n scanCancellation.abort();\n killOwned();\n if (!closed) {\n closeTimer = setTimeout(() => {\n if (settled || closed) return;\n settled = true;\n clearWatchers();\n child.stdout.destroy();\n child.stderr.destroy();\n child.unref();\n execution?.onCleanupFailure?.('Owned command pipes did not close; descendant cleanup could not be verified.');\n reject(\n new DeliveryError(\n `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).`,\n ),\n );\n }, 2_000);\n }\n };\n const capture = (chunks: Buffer[], chunk: Buffer): void => {\n outputBytes += chunk.length;\n execution?.onCaptured?.(outputBytes);\n if (\n execution !== undefined &&\n resourceBounds?.maxNewOutputBytes !== undefined &&\n outputBytes + sampledOutputBytes > resourceBounds.maxNewOutputBytes\n ) {\n stop('source-phase captured output exceeded remaining cumulative allowance');\n return;\n }\n if (outputBytes > outputLimit) {\n const remaining = outputLimit - retainedOutputBytes;\n if (remaining > 0) {\n chunks.push(Buffer.from(chunk.subarray(0, remaining)));\n retainedOutputBytes += Math.min(remaining, chunk.length);\n }\n stop(\n execution?.maxCapturedOutputBytes === undefined\n ? 'captured output exceeded 8 MiB'\n : `captured output exceeded ${outputLimit} bytes`,\n );\n return;\n }\n chunks.push(chunk);\n retainedOutputBytes += chunk.length;\n };\n child.stdout.on('data', (chunk: Buffer) => capture(stdout, chunk));\n child.stderr.on('data', (chunk: Buffer) => capture(stderr, chunk));\n child.stdout.once('error', (error) => stop(error.message));\n child.stderr.once('error', (error) => stop(error.message));\n child.stdin.once('error', (error) => stop(error.message));\n child.once('error', (error) => {\n if (child.pid === undefined) writer?.idle();\n stop(error.message);\n });\n child.once('exit', (code, signal) => {\n if (code !== 0 || signal !== null) stop(`exit ${String(code)}${signal === null ? '' : ` signal ${signal}`}`);\n else if (!closed) {\n exitPipeTimer = setTimeout(() => {\n if (!closed) stop('owned command pipes did not close after direct child exit');\n }, 1_000);\n }\n });\n child.once('spawn', () => {\n const sample = (): void => {\n if (failure !== undefined || child.pid === undefined) return;\n try {\n if (owned === undefined) throw new DeliveryError('Owned process identity is unavailable on this platform.');\n observeOwnedProcesses(owned, processSnapshot());\n writer?.observed(owned);\n if (resourceBounds !== undefined) {\n const result = sampleOwnedTree(\n owned,\n repoRoot,\n resourceBounds,\n baseline,\n undefined,\n execution === undefined ? 0 : process.memoryUsage().rss,\n execution?.includeControllerTree,\n );\n onResourceSample?.(result);\n onRunning?.(outputBytes, result);\n }\n if (closed || pendingOutput !== undefined) return;\n pendingOutput = (async () => {\n if (resourceBounds !== undefined && baseline !== undefined) {\n const bytes = await positiveNewOutputBytes(\n baseline,\n scanCancellation.signal,\n commandReleased,\n (reason) => {\n firstOutputObservationFailure ??= reason;\n lastOutputObservationFailure = reason;\n onRunning?.(outputBytes, undefined, reason);\n },\n );\n if (failure !== undefined) return;\n sampledOutputBytes = bytes;\n const result = sampleOwnedTree(\n owned,\n repoRoot,\n resourceBounds,\n baseline,\n bytes + (execution === undefined ? 0 : outputBytes),\n execution === undefined ? 0 : process.memoryUsage().rss,\n execution?.includeControllerTree,\n );\n onResourceSample?.(result);\n onRunning?.(outputBytes, result);\n }\n if (failure === undefined && !commandReleased) {\n commandReleased = true;\n child.stdin.end('run\\n');\n }\n })()\n .catch((error: unknown) => stop(error instanceof Error ? error.message : String(error)))\n .finally(() => {\n pendingOutput = undefined;\n });\n } catch (error) {\n stop(error instanceof Error ? error.message : String(error));\n }\n };\n sample();\n resourceTimer = setInterval(sample, 1_000);\n resourceTimer.unref();\n });\n const progressTimer = setInterval(() => onRunning?.(outputBytes), 5_000);\n progressTimer.unref();\n const onAbort = (): void => stop('cancelled');\n const onSigint = (): void => stop('cancelled by SIGINT');\n const onSigterm = (): void => stop('cancelled by SIGTERM');\n abortSignal?.addEventListener('abort', onAbort, { once: true });\n process.once('SIGINT', onSigint);\n process.once('SIGTERM', onSigterm);\n if (abortSignal?.aborted) onAbort();\n const handleClose = async (code: number | null, signal: NodeJS.Signals | null): Promise<void> => {\n closed = true;\n if (settled) return;\n await pendingOutput;\n if (failure === undefined && owned !== undefined) {\n try {\n if (resourceBounds !== undefined) {\n const sample = sampleOwnedTree(\n owned,\n repoRoot,\n resourceBounds,\n baseline,\n baseline === undefined\n ? undefined\n : (await positiveNewOutputBytes(baseline, scanCancellation.signal)) +\n (execution === undefined ? 0 : outputBytes),\n execution === undefined ? 0 : process.memoryUsage().rss,\n execution?.includeControllerTree,\n );\n onResourceSample?.(sample);\n onRunning?.(outputBytes, sample);\n }\n if (!owned.sampled) throw new DeliveryError('Owned process resource observation was unavailable.');\n const remaining = observeOwnedProcesses(owned, processSnapshot());\n if (remaining.length > 0) throw new DeliveryError('A sampled owned descendant survived command exit.');\n } catch (error) {\n stop(error instanceof Error ? error.message : String(error));\n }\n }\n if (failure !== undefined || code !== 0 || signal !== null) {\n const reason = failure ?? `exit ${String(code)}${signal === null ? '' : ` signal ${signal}`}`;\n let cleanupConfirmed = child.pid === undefined || !commandReleased;\n if (owned !== undefined && owned.sampled) {\n try {\n await confirmOwnedCleanup(owned);\n cleanupConfirmed = true;\n } catch (error) {\n cleanupFailure ??= error instanceof Error ? error.message : String(error);\n }\n }\n if (cleanupConfirmed) {\n try {\n writer?.idle();\n } catch (error) {\n writerFailure ??= error instanceof Error ? error.message : String(error);\n }\n }\n settled = true;\n if (cleanupFailure !== undefined) execution?.onCleanupFailure?.(cleanupFailure);\n reject(\n new DeliveryError(\n `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}).`}`,\n ),\n );\n return;\n }\n writer?.idle();\n settled = true;\n resolve(execution?.stdoutOnly ? Buffer.concat(stdout) : Buffer.concat([...stdout, ...stderr], outputBytes));\n };\n child.once('close', (code, signal) => {\n void handleClose(code, signal)\n .catch((error: unknown) => {\n settled = true;\n reject(error);\n })\n .finally(clearWatchers);\n });\n });\n}\n\nconst SourceDigest = z.string().regex(/^sha256:[a-f0-9]{64}$/u);\nconst SourceSha = z.string().regex(/^[a-f0-9]{40}$/u);\nconst SourceArtifactSchema = z.strictObject({ path: z.string().min(1), digest: SourceDigest });\nconst SourceFileSchema = SourceArtifactSchema.extend({\n device: z.number().int().nonnegative().safe(),\n inode: z.number().int().nonnegative().safe(),\n uid: z.number().int().nonnegative().safe(),\n mode: z.number().int().nonnegative().safe(),\n});\nconst SourceCommandSchema = z.strictObject({\n argv: z.array(z.string()).min(1),\n cwd: z.string().min(1),\n executable: SourceFileSchema,\n});\nconst SourceSnapshotSchema = z.strictObject({\n head: SourceSha,\n indexTree: SourceSha,\n branch: z.string().min(1),\n configDigest: SourceDigest,\n dirty: z.array(z.strictObject({ path: z.string().min(1), digest: SourceDigest.nullable() })),\n});\nconst SourceBoundsSchema = z.strictObject({\n maxAggregateRssBytes: z.number().int().positive().safe(),\n maxNewOutputBytes: z.number().int().positive().safe(),\n minFreeDiskBytes: z.number().int().positive().safe(),\n outputRoots: z.array(z.string().min(1)).min(1),\n});\nconst SourceReconciliationSchema = z.strictObject({\n phaseId: SourceDigest,\n recordId: SourceDigest,\n baselineId: SourceDigest.optional(),\n authorizationDigest: SourceDigest,\n});\nconst IssueSourcePhaseInputSchema = z.strictObject({\n repoRoot: z.string().min(1),\n issueNumber: z.number().int().positive().safe(),\n identity: z.string().min(1),\n rowDigest: SourceDigest,\n controller: z.strictObject({\n head: SourceSha,\n configDigest: SourceDigest,\n admissionId: SourceDigest,\n runtimeEntryPath: z.string().min(1),\n packageVersion: z.string().min(1),\n archiveDigest: SourceDigest,\n }),\n source: SourceSnapshotSchema.extend({\n path: z.string().min(1),\n effect: z.discriminatedUnion('kind', [\n z.strictObject({ kind: z.literal('preserve') }),\n z.strictObject({\n kind: z.literal('commitOnce'),\n parent: SourceSha,\n tree: SourceSha,\n configDigest: SourceDigest.optional(),\n }),\n ]),\n }),\n caller: SourceArtifactSchema,\n authorization: SourceArtifactSchema,\n inputs: z.array(SourceArtifactSchema),\n commands: z.array(SourceCommandSchema).min(1),\n commandGraphDigest: SourceDigest,\n environment: z.strictObject({ digest: SourceDigest, overrides: z.record(z.string(), z.string().nullable()) }),\n bounds: SourceBoundsSchema,\n completionArtifacts: z.array(z.string().min(1)),\n reconciliation: SourceReconciliationSchema.optional(),\n});\nconst SourcePhaseCommandResultSchema = z.strictObject({\n index: z.number().int().nonnegative().safe(),\n outputDigest: SourceDigest.nullable(),\n outputBytes: z.number().int().nonnegative().safe(),\n status: z.enum(['complete', 'failed']),\n});\n\nexport type IssueSourcePhaseInput = z.input<typeof IssueSourcePhaseInputSchema> & { signal?: AbortSignal };\nexport interface IssueSourcePhaseContext {\n readonly phaseId: string;\n readonly signal: AbortSignal;\n readonly source: Readonly<Omit<z.infer<typeof SourceSnapshotSchema>, 'dirty'>> & {\n readonly dirty: readonly Readonly<{ path: string; digest: string | null }>[];\n };\n readonly controller: Readonly<z.infer<typeof IssueSourcePhaseInputSchema>['controller']>;\n readonly actor: Readonly<{ identity: string; actorLogin: string; credentialIdentity: string }>;\n readonly inputs: readonly Readonly<z.infer<typeof SourceArtifactSchema>>[];\n readonly run: (index: number) => Promise<Buffer>;\n}\nconst IssueSourcePhaseReceiptSchema = z.strictObject({\n status: z.literal('complete'),\n phaseId: SourceDigest,\n recordId: SourceDigest,\n source: SourceSnapshotSchema,\n commands: z.array(SourcePhaseCommandResultSchema),\n});\nexport type IssueSourcePhaseReceipt = z.infer<typeof IssueSourcePhaseReceiptSchema>;\n"],
|
|
5
|
-
"mappings": "AAAA,SAAS,OAAO,iBAAiB;AACjC,SAAS,kBAAkB;AAC3B,SAAS,eAAe,uBAAuB;AAC/C,SAAS,aAAa;AACtB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,SAAS,MAAM,SAAS,WAAW;AAC5C,SAAS,qBAAqB;AAC9B,SAAS,SAAS;AAElB,SAAS,yBAAyB;AAClC,SAAS,aAAa,aAAa,oCA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 'node:child_process';\nimport { createRequire, findPackageJSON } from 'node:module';\nimport { types } from 'node:util';\nimport { existsSync, readFileSync, readdirSync, realpathSync, statfsSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { z } from 'zod';\n\nimport { digestBytes, digestValue, writeCreateOnly } from './delivery/common.js';\nimport { DeliveryError } from './errors.js';\nimport { gitCommonDir } from './git.js';\n\nexport interface VerificationResourceBounds {\n maxAggregateRssBytes: number;\n maxNewOutputBytes?: number;\n minFreeDiskBytes: number;\n outputRoots?: readonly string[];\n}\n\nfunction availableDiskBytes(path: string): bigint {\n let existing = path;\n for (;;) {\n try {\n const disk = statfsSync(existing, { bigint: true });\n return disk.bavail * disk.bsize;\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT' || dirname(existing) === existing) throw error;\n existing = dirname(existing);\n }\n }\n}\n\nfunction freeDiskBytes(repoRoot: string): number {\n const available = availableDiskBytes(repoRoot);\n // Some filesystems (AWS EFS) report more free bytes than a safe integer; the bound only needs a floor.\n return Number(available < BigInt(Number.MAX_SAFE_INTEGER) ? available : BigInt(Number.MAX_SAFE_INTEGER));\n}\n\ninterface ObservedProcess {\n identity: string;\n pgid: number;\n pid: number;\n ppid: number;\n rssBytes: number;\n status: string;\n}\n\nexport interface OwnedProcessState {\n rootIdentity?: string;\n rootPid: number;\n sampled: boolean;\n tracked: Map<number, ObservedProcess>;\n}\n\nclass ProcessSnapshotError extends DeliveryError {}\n\nexport function processSnapshot(): Map<number, ObservedProcess> {\n const psPath = existsSync('/usr/bin/ps') ? '/usr/bin/ps' : '/bin/ps';\n const started = performance.now();\n const result = spawnSync(psPath, ['-A', '-o', 'pid=,ppid=,pgid=,rss=,stat=,lstart='], {\n encoding: 'utf8',\n // The absolute observer needs no author tokens, App keys or preload selectors.\n env: { LC_ALL: 'C' },\n maxBuffer: 4 * 1024 * 1024,\n timeout: 1_000,\n });\n if (result.status !== 0 || result.error || result.signal || !result.stdout.endsWith('\\n')) {\n const elapsedMs = Math.round(performance.now() - started);\n const stdout = typeof result.stdout === 'string' ? result.stdout : '';\n let completeLines = 0;\n for (let index = 0; index < stdout.length; index++) if (stdout.charCodeAt(index) === 10) completeLines++;\n const code = (result.error as NodeJS.ErrnoException | undefined)?.code;\n const signal = result.signal;\n // Only fixed labels, bounded numbers and completeness flags leave this observation.\n const metadata = {\n status: Number.isSafeInteger(result.status) ? result.status : null,\n errorCode:\n code === undefined\n ? null\n : ['EACCES', 'EPERM', 'ETIMEDOUT', 'ENOENT', 'ENOBUFS', 'EAGAIN', 'ENOMEM', 'EIO', 'EINVAL'].includes(code)\n ? code\n : 'other',\n signal:\n signal === null\n ? null\n : ['SIGTERM', 'SIGKILL', 'SIGINT', 'SIGABRT', 'SIGSEGV', 'SIGBUS', 'SIGHUP', 'SIGQUIT', 'SIGPIPE'].includes(\n signal,\n )\n ? signal\n : 'other',\n stdoutPresent: typeof result.stdout === 'string',\n stdoutTerminated: typeof result.stdout === 'string' && result.stdout.endsWith('\\n'),\n elapsedMs,\n stdoutBytes: Buffer.byteLength(stdout),\n completeLines,\n };\n throw new ProcessSnapshotError(`Owned process resource observation failed. ${JSON.stringify(metadata)}`);\n }\n const snapshot = new Map<number, ObservedProcess>();\n for (const line of result.stdout.trim().split('\\n')) {\n const match = /^(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\S+)\\s+(.+)$/u.exec(line.trim());\n if (!match) throw new DeliveryError('Owned process resource observation is ambiguous.');\n const observed = {\n pid: Number(match[1]),\n ppid: Number(match[2]),\n pgid: Number(match[3]),\n rssBytes: Number(match[4]) * 1_024,\n status: match[5]!,\n identity: match[6]!,\n };\n if (\n !Number.isSafeInteger(observed.pid) ||\n observed.pid <= 0 ||\n !Number.isSafeInteger(observed.ppid) ||\n !Number.isSafeInteger(observed.pgid) ||\n !Number.isSafeInteger(observed.rssBytes) ||\n snapshot.has(observed.pid)\n )\n throw new DeliveryError('Owned process resource observation is ambiguous.');\n snapshot.set(observed.pid, observed);\n }\n return snapshot;\n}\n\nfunction observeOwnedProcesses(state: OwnedProcessState, snapshot: Map<number, ObservedProcess>): ObservedProcess[] {\n const root = snapshot.get(state.rootPid);\n if (state.rootIdentity === undefined) {\n if (root === undefined || root.status.startsWith('Z') || root.pgid !== state.rootPid) {\n throw new DeliveryError('Owned process identity could not be established before the command exited.');\n }\n state.rootIdentity = root.identity;\n state.tracked.set(root.pid, root);\n } else if (root !== undefined && root.identity !== state.rootIdentity) {\n throw new DeliveryError('Owned process identity changed during verification.');\n }\n const selected = new Map<number, ObservedProcess>();\n for (const [pid, previous] of state.tracked) {\n const current = snapshot.get(pid);\n if (current === undefined || current.status.startsWith('Z')) state.tracked.delete(pid);\n else if (current.identity !== previous.identity) {\n throw new DeliveryError('Tracked process identity changed during verification.');\n } else selected.set(pid, current);\n }\n for (const member of snapshot.values()) {\n if (!member.status.startsWith('Z') && member.pgid === state.rootPid) selected.set(member.pid, member);\n }\n const children = new Map<number, ObservedProcess[]>();\n for (const member of snapshot.values()) {\n const siblings = children.get(member.ppid) ?? [];\n siblings.push(member);\n children.set(member.ppid, siblings);\n }\n const pending = [...selected.values()];\n for (const parent of pending)\n for (const child of children.get(parent.pid) ?? []) {\n if (!child.status.startsWith('Z') && !selected.has(child.pid)) {\n selected.set(child.pid, child);\n pending.push(child);\n }\n }\n for (const member of selected.values()) state.tracked.set(member.pid, member);\n state.sampled = true;\n return [...selected.values()];\n}\n\nfunction sampleOwnedTree(\n state: OwnedProcessState,\n repoRoot: string,\n bounds: VerificationResourceBounds,\n controllerRssBytes = 0,\n includeControllerTree = false,\n): void {\n const snapshot = processSnapshot();\n const owned = observeOwnedProcesses(state, snapshot);\n const controller = includeControllerTree\n ? controllerTreeRssBytes(snapshot, new Set(owned.map((member) => member.pid)))\n : controllerRssBytes;\n const rssBytes = owned.reduce((total, member) => total + member.rssBytes, controller);\n if (!Number.isSafeInteger(rssBytes))\n throw new DeliveryError('Owned aggregate RSS is outside the safe integer range.');\n if (rssBytes > bounds.maxAggregateRssBytes) {\n throw new DeliveryError(`Owned aggregate RSS ${rssBytes} exceeded limit ${bounds.maxAggregateRssBytes}.`);\n }\n const available = freeDiskBytes(repoRoot);\n if (available < bounds.minFreeDiskBytes)\n throw new DeliveryError(`Free disk fell below limit ${bounds.minFreeDiskBytes}.`);\n}\n\n/** Accounting includes the caller's tree; containment remains restricted to the recorded command. */\nfunction controllerTreeRssBytes(snapshot = processSnapshot(), excluded = new Set<number>()): number {\n const controller = snapshot.get(process.pid);\n if (controller === undefined || controller.status.startsWith('Z'))\n throw new DeliveryError('Runtime setup controller resource observation is unavailable.');\n const selected = new Set([process.pid]);\n let bytes = process.memoryUsage().rss;\n for (const pid of selected)\n for (const member of snapshot.values())\n if (member.ppid === pid && !member.status.startsWith('Z') && !selected.has(member.pid)) {\n selected.add(member.pid);\n if (!excluded.has(member.pid)) bytes += member.rssBytes;\n }\n if (!Number.isSafeInteger(bytes)) throw new DeliveryError('Controller aggregate RSS observation overflowed.');\n return bytes;\n}\n\nexport async function confirmOwnedCleanup(state: OwnedProcessState): Promise<void> {\n if (!state.sampled || state.rootIdentity === undefined) {\n throw new DeliveryError('Owned process cleanup cannot be verified without a root identity.');\n }\n const deadline = Date.now() + 2_000;\n for (;;) {\n const snapshot = processSnapshot();\n const root = snapshot.get(state.rootPid);\n if (root !== undefined && root.identity !== state.rootIdentity) {\n throw new DeliveryError('Owned process group identity changed before cleanup readback.');\n }\n const groupAlive = [...snapshot.values()].some(\n (member) => member.pgid === state.rootPid && !member.status.startsWith('Z'),\n );\n const trackedAlive = [...state.tracked.values()].some((previous) => {\n const current = snapshot.get(previous.pid);\n if (current === undefined || current.status.startsWith('Z')) return false;\n if (current.identity !== previous.identity)\n throw new DeliveryError('Tracked process identity changed before cleanup readback.');\n return true;\n });\n if (!groupAlive && !trackedAlive) return;\n if (Date.now() >= deadline) throw new DeliveryError('Owned process cleanup did not release every sampled process.');\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n}\n\n/** Signal only birth identities established by this command, including observed detached children. */\nexport function terminateOwnedProcesses(state: OwnedProcessState): void {\n if (!state.sampled || state.rootIdentity === undefined) throw new DeliveryError('Owned process identity is unknown.');\n const snapshot = processSnapshot();\n const root = snapshot.get(state.rootPid);\n if (root !== undefined && root.identity !== state.rootIdentity)\n throw new DeliveryError('Owned process group identity changed before cleanup.');\n const alive = [...state.tracked.values()].flatMap((previous) => {\n const current = snapshot.get(previous.pid);\n if (current === undefined || current.status.startsWith('Z')) return [];\n if (current.identity !== previous.identity)\n throw new DeliveryError('Tracked process identity changed before cleanup.');\n return [current];\n });\n const group = [...snapshot.values()].filter(\n (member) => member.pgid === state.rootPid && !member.status.startsWith('Z'),\n );\n if (group.length > 0 && !alive.some((member) => member.pgid === state.rootPid))\n throw new DeliveryError('Owned process group has no surviving recorded identity; cleanup is ambiguous.');\n const signal = (pid: number): void => {\n try {\n process.kill(pid, 'SIGKILL');\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === 'ESRCH') return;\n if (code !== 'EPERM') throw error;\n // macOS can return EPERM when the last group member exits after our snapshot.\n // Accept only fresh absence/zombie proof; a live target remains a cleanup failure.\n const readback = processSnapshot();\n if (pid < 0) {\n const currentRoot = readback.get(state.rootPid);\n if (currentRoot !== undefined && currentRoot.identity !== state.rootIdentity)\n throw new DeliveryError('Owned process group identity changed during cleanup signal readback.');\n if ([...readback.values()].some((member) => member.pgid === state.rootPid && !member.status.startsWith('Z')))\n throw error;\n } else {\n const current = readback.get(pid);\n if (current !== undefined && current.identity !== state.tracked.get(pid)?.identity)\n throw new DeliveryError('Tracked process identity changed during cleanup signal readback.');\n if (current !== undefined && !current.status.startsWith('Z')) throw error;\n }\n }\n };\n if (group.length > 0) signal(-state.rootPid);\n for (const member of alive.reverse()) signal(member.pid);\n}\n\ninterface VerificationWriter {\n starting(): void;\n observed(state: OwnedProcessState): void;\n idle(): void;\n assertQuiescent(): void;\n}\n\nfunction producerContent(root: string) {\n const code: { path: string; digest: string }[] = [];\n const collect = (directory: string): void => {\n for (const entry of readdirSync(directory, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {\n const path = join(directory, entry.name);\n if (entry.isDirectory()) collect(path);\n else if (entry.isFile() && entry.name.endsWith('.js') && !entry.name.endsWith('.test.js'))\n code.push({ path: path.slice(root.length + 1), digest: digestBytes(readFileSync(path)) });\n }\n };\n collect(root);\n const dependencies = new Map<string, string>();\n const collectDependencies = (manifestPath: string): void => {\n if (dependencies.has(manifestPath)) return;\n const bytes = readFileSync(manifestPath);\n const manifest = z\n .object({ dependencies: z.record(z.string(), z.string()).optional() })\n .parse(JSON.parse(bytes.toString('utf8')));\n dependencies.set(manifestPath, digestBytes(bytes));\n const require = createRequire(manifestPath);\n for (const name of Object.keys(manifest.dependencies ?? {}).sort()) {\n let resolved: string;\n try {\n resolved = require.resolve(`${name}/package.json`);\n } catch {\n try {\n resolved = require.resolve(name);\n } catch (error) {\n if (!types.isNativeError(error) || Reflect.get(error, 'code') !== 'ERR_PACKAGE_PATH_NOT_EXPORTED')\n throw error;\n const manifest = findPackageJSON(name, manifestPath);\n if (!manifest) throw error;\n resolved = manifest;\n }\n }\n let directory = dirname(resolved);\n for (;;) {\n const path = join(directory, 'package.json');\n if (existsSync(path)) {\n const candidate = z.object({ name: z.string().optional() }).parse(JSON.parse(readFileSync(path, 'utf8')));\n if (candidate.name === name) {\n collectDependencies(path);\n break;\n }\n }\n const parent = dirname(directory);\n if (parent === directory) throw new DeliveryError(`Producer dependency identity is unavailable for ${name}.`);\n directory = parent;\n }\n }\n };\n collectDependencies(join(dirname(root), 'package.json'));\n return { code, dependencies: [...dependencies].sort(([a], [b]) => a.localeCompare(b)) };\n}\n\nfunction producerDigest(root = dirname(fileURLToPath(import.meta.url))): string {\n return digestValue(producerContent(root));\n}\n\n/** @internal Retained public code is hashed as data; it is never imported or executed. */\nexport function retainedWorktreeTransitionProducerDigest(distDirectory: string): string {\n return producerDigest(realpathSync(distDirectory));\n}\n\nfunction writeCommandOutput(bytes: Buffer, commonDir: string): string {\n const digest = digestBytes(bytes);\n const path = join(commonDir, 'ai-delivery', 'verification@1', 'command-output', `${digest.slice(7)}.bin`);\n writeCreateOnly(path, bytes, digest);\n return digest;\n}\n\nexport function runStageCommand(\n repoRoot: string,\n argv: readonly string[],\n abortSignal?: AbortSignal,\n resourceBounds?: VerificationResourceBounds,\n writer?: VerificationWriter,\n execution?: {\n environment: NodeJS.ProcessEnv;\n cwd?: string;\n maxCapturedOutputBytes?: number;\n includeControllerTree?: boolean;\n onCaptured?(bytes: number): void;\n onCleanupFailure?(reason: string): void;\n failedOutput?(bytes: Buffer): string;\n stdoutOnly?: boolean;\n },\n): Promise<Buffer> {\n const [executable, ...args] = argv;\n if (!executable) throw new DeliveryError('Policy selected an empty stage command.');\n if (abortSignal?.aborted) throw new DeliveryError('Selected policy stage command cancelled.');\n writer?.starting();\n return new Promise((resolve, reject) => {\n // The shell waits for our ownership receipt, then exec preserves its PID, birth identity and process group.\n const child = spawn(\n '/bin/sh',\n [\n '-c',\n 'IFS= read -r ready || exit 125; [ \"$ready\" = run ] || exit 125; exec \"$@\" </dev/null',\n 'ai-delivery-command',\n executable,\n ...args,\n ],\n {\n cwd: execution?.cwd ?? repoRoot,\n detached: process.platform !== 'win32',\n stdio: ['pipe', 'pipe', 'pipe'],\n ...(execution === undefined ? {} : { env: execution.environment }),\n },\n );\n const stdout: Buffer[] = [];\n const stderr: Buffer[] = [];\n const owned: OwnedProcessState | undefined =\n process.platform === 'win32' || child.pid === undefined\n ? undefined\n : { rootPid: child.pid, sampled: false, tracked: new Map() };\n let outputBytes = 0;\n let retainedOutputBytes = 0;\n const outputLimit = execution?.maxCapturedOutputBytes ?? 8 * 1024 * 1024;\n let failure: string | undefined;\n let cleanupFailure: string | undefined;\n let writerFailure: string | undefined;\n let closed = false;\n let settled = false;\n let commandReleased = false;\n const failedOutput = (): string => {\n try {\n const bytes = Buffer.concat([...stdout, ...stderr]);\n if (execution?.failedOutput) return execution.failedOutput(bytes);\n return ` Command output ${writeCommandOutput(bytes, gitCommonDir(repoRoot))}.`;\n } catch (error) {\n return ` Command output persistence failed (${error instanceof Error ? error.message : String(error)}).`;\n }\n };\n let closeTimer: NodeJS.Timeout | undefined;\n let exitPipeTimer: NodeJS.Timeout | undefined;\n let resourceTimer: NodeJS.Timeout | undefined;\n const clearWatchers = (): void => {\n if (resourceTimer !== undefined) clearInterval(resourceTimer);\n if (closeTimer !== undefined) clearTimeout(closeTimer);\n if (exitPipeTimer !== undefined) clearTimeout(exitPipeTimer);\n abortSignal?.removeEventListener('abort', onAbort);\n process.removeListener('SIGINT', onSigint);\n process.removeListener('SIGTERM', onSigterm);\n };\n const killOwned = (): void => {\n if (child.pid === undefined) return;\n if (owned?.sampled) {\n try {\n observeOwnedProcesses(owned, processSnapshot());\n } catch (error) {\n cleanupFailure ??= error instanceof Error ? error.message : String(error);\n }\n try {\n writer?.observed(owned);\n } catch (error) {\n writerFailure ??= error instanceof Error ? error.message : String(error);\n }\n // Durable state failure cannot prevent identity-checked termination of known-owned processes.\n try {\n terminateOwnedProcesses(owned);\n } catch (error) {\n cleanupFailure ??= error instanceof Error ? error.message : String(error);\n }\n } else {\n try {\n // The still-owned direct child is the only safe signal target before identity observation.\n if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');\n if (commandReleased) cleanupFailure ??= 'owned process identity was not observed before cleanup';\n } catch (error) {\n cleanupFailure ??= error instanceof Error ? error.message : String(error);\n }\n }\n };\n const stop = (reason: string): void => {\n if (failure !== undefined) return;\n failure = reason;\n killOwned();\n if (!closed) {\n closeTimer = setTimeout(() => {\n if (settled || closed) return;\n settled = true;\n clearWatchers();\n child.stdout.destroy();\n child.stderr.destroy();\n child.unref();\n execution?.onCleanupFailure?.('Owned command pipes did not close; descendant cleanup could not be verified.');\n reject(\n new DeliveryError(\n `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).`,\n ),\n );\n }, 2_000);\n }\n };\n const capture = (chunks: Buffer[], chunk: Buffer): void => {\n outputBytes += chunk.length;\n execution?.onCaptured?.(outputBytes);\n if (\n execution !== undefined &&\n resourceBounds?.maxNewOutputBytes !== undefined &&\n outputBytes > resourceBounds.maxNewOutputBytes\n ) {\n stop('source-phase captured output exceeded remaining cumulative allowance');\n return;\n }\n if (outputBytes > outputLimit) {\n const remaining = outputLimit - retainedOutputBytes;\n if (remaining > 0) {\n chunks.push(Buffer.from(chunk.subarray(0, remaining)));\n retainedOutputBytes += Math.min(remaining, chunk.length);\n }\n stop(\n execution?.maxCapturedOutputBytes === undefined\n ? 'captured output exceeded 8 MiB'\n : `captured output exceeded ${outputLimit} bytes`,\n );\n return;\n }\n chunks.push(chunk);\n retainedOutputBytes += chunk.length;\n };\n child.stdout.on('data', (chunk: Buffer) => capture(stdout, chunk));\n child.stderr.on('data', (chunk: Buffer) => capture(stderr, chunk));\n child.stdout.once('error', (error) => stop(error.message));\n child.stderr.once('error', (error) => stop(error.message));\n child.stdin.once('error', (error) => stop(error.message));\n child.once('error', (error) => {\n if (child.pid === undefined) writer?.idle();\n stop(error.message);\n });\n child.once('exit', (code, signal) => {\n if (code !== 0 || signal !== null) stop(`exit ${String(code)}${signal === null ? '' : ` signal ${signal}`}`);\n else if (!closed) {\n exitPipeTimer = setTimeout(() => {\n if (!closed) stop('owned command pipes did not close after direct child exit');\n }, 1_000);\n }\n });\n child.once('spawn', () => {\n const sample = (): void => {\n if (failure !== undefined || child.pid === undefined) return;\n try {\n if (owned === undefined) throw new DeliveryError('Owned process identity is unavailable on this platform.');\n observeOwnedProcesses(owned, processSnapshot());\n writer?.observed(owned);\n if (resourceBounds !== undefined)\n sampleOwnedTree(\n owned,\n repoRoot,\n resourceBounds,\n execution === undefined ? 0 : process.memoryUsage().rss,\n execution?.includeControllerTree,\n );\n if (!closed && failure === undefined && !commandReleased) {\n commandReleased = true;\n child.stdin.end('run\\n');\n }\n } catch (error) {\n stop(error instanceof Error ? error.message : String(error));\n }\n };\n sample();\n resourceTimer = setInterval(sample, 1_000);\n resourceTimer.unref();\n });\n const onAbort = (): void => stop('cancelled');\n const onSigint = (): void => stop('cancelled by SIGINT');\n const onSigterm = (): void => stop('cancelled by SIGTERM');\n abortSignal?.addEventListener('abort', onAbort, { once: true });\n process.once('SIGINT', onSigint);\n process.once('SIGTERM', onSigterm);\n if (abortSignal?.aborted) onAbort();\n const handleClose = async (code: number | null, signal: NodeJS.Signals | null): Promise<void> => {\n closed = true;\n if (settled) return;\n if (failure === undefined && owned !== undefined) {\n try {\n if (resourceBounds !== undefined)\n sampleOwnedTree(\n owned,\n repoRoot,\n resourceBounds,\n execution === undefined ? 0 : process.memoryUsage().rss,\n execution?.includeControllerTree,\n );\n if (!owned.sampled) throw new DeliveryError('Owned process resource observation was unavailable.');\n const remaining = observeOwnedProcesses(owned, processSnapshot());\n if (remaining.length > 0) throw new DeliveryError('A sampled owned descendant survived command exit.');\n } catch (error) {\n stop(error instanceof Error ? error.message : String(error));\n }\n }\n if (failure !== undefined || code !== 0 || signal !== null) {\n const reason = failure ?? `exit ${String(code)}${signal === null ? '' : ` signal ${signal}`}`;\n let cleanupConfirmed = child.pid === undefined || !commandReleased;\n if (owned !== undefined && owned.sampled) {\n try {\n await confirmOwnedCleanup(owned);\n cleanupConfirmed = true;\n } catch (error) {\n cleanupFailure ??= error instanceof Error ? error.message : String(error);\n }\n }\n if (cleanupConfirmed) {\n try {\n writer?.idle();\n } catch (error) {\n writerFailure ??= error instanceof Error ? error.message : String(error);\n }\n }\n settled = true;\n if (cleanupFailure !== undefined) execution?.onCleanupFailure?.(cleanupFailure);\n reject(\n new DeliveryError(\n `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}).`}`,\n ),\n );\n return;\n }\n writer?.idle();\n settled = true;\n resolve(execution?.stdoutOnly ? Buffer.concat(stdout) : Buffer.concat([...stdout, ...stderr], outputBytes));\n };\n child.once('close', (code, signal) => {\n void handleClose(code, signal)\n .catch((error: unknown) => {\n settled = true;\n reject(error);\n })\n .finally(clearWatchers);\n });\n });\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,OAAO,iBAAiB;AACjC,SAAS,eAAe,uBAAuB;AAC/C,SAAS,aAAa;AACtB,SAAS,YAAY,cAAc,aAAa,cAAc,kBAAkB;AAChF,SAAS,SAAS,YAAY;AAC9B,SAAS,qBAAqB;AAC9B,SAAS,SAAS;AAElB,SAAS,aAAa,aAAa,uBAAuB;AAC1D,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAS7B,SAAS,mBAAmB,MAAsB;AAChD,MAAI,WAAW;AACf,aAAS;AACP,QAAI;AACF,YAAM,OAAO,WAAW,UAAU,EAAE,QAAQ,KAAK,CAAC;AAClD,aAAO,KAAK,SAAS,KAAK;AAAA,IAC5B,SAAS,OAAO;AACd,UAAK,MAAgC,SAAS,YAAY,QAAQ,QAAQ,MAAM,SAAU,OAAM;AAChG,iBAAW,QAAQ,QAAQ;AAAA,IAC7B;AAAA,EACF;AACF;AAEA,SAAS,cAAc,UAA0B;AAC/C,QAAM,YAAY,mBAAmB,QAAQ;AAE7C,SAAO,OAAO,YAAY,OAAO,OAAO,gBAAgB,IAAI,YAAY,OAAO,OAAO,gBAAgB,CAAC;AACzG;AAkBA,MAAM,6BAA6B,cAAc;AAAC;AAE3C,SAAS,kBAAgD;AAC9D,QAAM,SAAS,WAAW,aAAa,IAAI,gBAAgB;AAC3D,QAAM,UAAU,YAAY,IAAI;AAChC,QAAM,SAAS,UAAU,QAAQ,CAAC,MAAM,MAAM,qCAAqC,GAAG;AAAA,IACpF,UAAU;AAAA;AAAA,IAEV,KAAK,EAAE,QAAQ,IAAI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,UAAmB;AACzB,kBAAU;AACV,eAAO,KAAK;AAAA,MACd,CAAC,EACA,QAAQ,aAAa;AAAA,IAC1B,CAAC;AAAA,EACH,CAAC;AACH;",
|
|
6
|
+
"names": ["require", "manifest"]
|
|
7
7
|
}
|
|
@@ -1,10 +1,6 @@
|
|
|
1
1
|
import assert from "node:assert/strict";
|
|
2
|
-
import {
|
|
3
|
-
|
|
4
|
-
import { tmpdir } from "node:os";
|
|
5
|
-
import { join } from "node:path";
|
|
6
|
-
import { afterEach, test, vi } from "vitest";
|
|
7
|
-
const observation = vi.hoisted(() => ({ mode: "healthy", directory: "", calls: 0 }));
|
|
2
|
+
import { test, vi } from "vitest";
|
|
3
|
+
const observation = vi.hoisted(() => ({ mode: "healthy", calls: 0 }));
|
|
8
4
|
vi.mock("node:child_process", async (original) => {
|
|
9
5
|
const actual = await original();
|
|
10
6
|
return {
|
|
@@ -12,7 +8,7 @@ vi.mock("node:child_process", async (original) => {
|
|
|
12
8
|
spawnSync: (...args) => {
|
|
13
9
|
if (args[0] !== "/usr/bin/ps" && args[0] !== "/bin/ps") return actual.spawnSync(...args);
|
|
14
10
|
observation.calls++;
|
|
15
|
-
if (observation.mode === "unavailable" || observation.mode === "partial-unavailable"
|
|
11
|
+
if (observation.mode === "unavailable" || observation.mode === "partial-unavailable")
|
|
16
12
|
return {
|
|
17
13
|
status: null,
|
|
18
14
|
error: Object.assign(new Error("synthetic observation timeout"), { code: "ETIMEDOUT" }),
|
|
@@ -31,28 +27,7 @@ vi.mock("node:child_process", async (original) => {
|
|
|
31
27
|
}
|
|
32
28
|
};
|
|
33
29
|
});
|
|
34
|
-
const { processSnapshot
|
|
35
|
-
const directories = [];
|
|
36
|
-
afterEach(() => {
|
|
37
|
-
vi.unstubAllEnvs();
|
|
38
|
-
for (const directory of directories.splice(0)) rmSync(directory, { recursive: true, force: true });
|
|
39
|
-
});
|
|
40
|
-
function gate(unrelated = false) {
|
|
41
|
-
const directory = mkdtempSync(join(tmpdir(), "ai-delivery-gate-refusal-"));
|
|
42
|
-
directories.push(directory);
|
|
43
|
-
mkdirSync(join(directory, "requests"), { mode: 448 });
|
|
44
|
-
const capability = {
|
|
45
|
-
directory,
|
|
46
|
-
id: randomUUID(),
|
|
47
|
-
owner: unrelated ? { pid: 999999, identity: "unrelated birth" } : { pid: process.pid, identity: "current birth" }
|
|
48
|
-
};
|
|
49
|
-
writeFileSync(join(directory, "gate.json"), JSON.stringify(capability), { mode: 384 });
|
|
50
|
-
vi.stubEnv("AI_DELIVERY_OUTPUT_OBSERVATION_GATE", JSON.stringify(capability));
|
|
51
|
-
observation.directory = directory;
|
|
52
|
-
observation.mode = "healthy";
|
|
53
|
-
observation.calls = 0;
|
|
54
|
-
return capability;
|
|
55
|
-
}
|
|
30
|
+
const { processSnapshot } = await import("./verification.js");
|
|
56
31
|
for (const mode of ["unavailable", "partial-unavailable"]) {
|
|
57
32
|
test(`observer failure preserves bounded numeric provenance for ${mode}`, () => {
|
|
58
33
|
observation.mode = mode;
|
|
@@ -75,65 +50,4 @@ for (const mode of ["unavailable", "partial-unavailable"]) {
|
|
|
75
50
|
});
|
|
76
51
|
});
|
|
77
52
|
}
|
|
78
|
-
test("filesystem gate refuses unavailable full observation before invoking its fixture", async () => {
|
|
79
|
-
const current = gate();
|
|
80
|
-
observation.mode = "unavailable";
|
|
81
|
-
let invoked = false;
|
|
82
|
-
await assert.rejects(
|
|
83
|
-
withVerificationFilesystemFixture(() => {
|
|
84
|
-
invoked = true;
|
|
85
|
-
}),
|
|
86
|
-
/observation failed/u
|
|
87
|
-
);
|
|
88
|
-
assert.equal(invoked, false);
|
|
89
|
-
assert.equal(existsSync(join(current.directory, "held")), false);
|
|
90
|
-
});
|
|
91
|
-
test("filesystem gate still observes after lock publication and releases its own lock on refusal", async () => {
|
|
92
|
-
const current = gate();
|
|
93
|
-
observation.mode = "after-lock";
|
|
94
|
-
let invoked = false;
|
|
95
|
-
await assert.rejects(
|
|
96
|
-
withVerificationFilesystemFixture(() => {
|
|
97
|
-
invoked = true;
|
|
98
|
-
}),
|
|
99
|
-
/observation failed/u
|
|
100
|
-
);
|
|
101
|
-
assert.equal(invoked, false);
|
|
102
|
-
assert.equal(existsSync(join(current.directory, "held")), false);
|
|
103
|
-
assert.equal(existsSync(join(current.directory, "gate.json")), true);
|
|
104
|
-
});
|
|
105
|
-
test("filesystem gate preserves an abandoned scan request and never invokes the fixture", async () => {
|
|
106
|
-
const current = gate();
|
|
107
|
-
const requestId = randomUUID();
|
|
108
|
-
const path = join(current.directory, "requests", requestId + ".json");
|
|
109
|
-
const bytes = JSON.stringify({
|
|
110
|
-
gateId: current.id,
|
|
111
|
-
id: requestId,
|
|
112
|
-
kind: "scan",
|
|
113
|
-
owner: { pid: 999998, identity: "absent birth" }
|
|
114
|
-
});
|
|
115
|
-
writeFileSync(path, bytes, { mode: 384 });
|
|
116
|
-
let invoked = false;
|
|
117
|
-
await assert.rejects(
|
|
118
|
-
withVerificationFilesystemFixture(() => {
|
|
119
|
-
invoked = true;
|
|
120
|
-
}),
|
|
121
|
-
/scan request was abandoned/u
|
|
122
|
-
);
|
|
123
|
-
assert.equal(invoked, false);
|
|
124
|
-
assert.equal(readFileSync(path, "utf8"), bytes);
|
|
125
|
-
assert.equal(existsSync(join(current.directory, "held")), false);
|
|
126
|
-
});
|
|
127
|
-
test("filesystem gate refuses a live unrelated owner that is not an inherited ancestor", async () => {
|
|
128
|
-
const current = gate(true);
|
|
129
|
-
let invoked = false;
|
|
130
|
-
await assert.rejects(
|
|
131
|
-
withVerificationFilesystemFixture(() => {
|
|
132
|
-
invoked = true;
|
|
133
|
-
}),
|
|
134
|
-
/not an inherited ancestor/u
|
|
135
|
-
);
|
|
136
|
-
assert.equal(invoked, false);
|
|
137
|
-
assert.equal(existsSync(join(current.directory, "held")), false);
|
|
138
|
-
});
|
|
139
53
|
//# sourceMappingURL=verificationGate.test.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/verificationGate.test.ts"],
|
|
4
|
-
"sourcesContent": ["import assert from 'node:assert/strict';\nimport {
|
|
5
|
-
"mappings": "AAAA,OAAO,YAAY;AACnB,SAAS,
|
|
4
|
+
"sourcesContent": ["import assert from 'node:assert/strict';\nimport { test, vi } from 'vitest';\n\nconst observation = vi.hoisted(() => ({ mode: 'healthy', calls: 0 }));\nvi.mock('node:child_process', async (original) => {\n const actual = await original<typeof import('node:child_process')>();\n return {\n ...actual,\n spawnSync: (...args: Parameters<typeof actual.spawnSync>) => {\n if (args[0] !== '/usr/bin/ps' && args[0] !== '/bin/ps') return actual.spawnSync(...args);\n observation.calls++;\n if (observation.mode === 'unavailable' || observation.mode === 'partial-unavailable')\n return {\n status: null,\n error: Object.assign(new Error('synthetic observation timeout'), { code: 'ETIMEDOUT' }),\n signal: 'SIGTERM',\n stdout: observation.mode === 'partial-unavailable' ? '1 0 1 1 S birth\\n2 0' : '',\n stderr: '',\n };\n return {\n status: 0,\n signal: null,\n stdout: `${process.pid} ${process.ppid} ${process.pid} 32 S current birth\\n999999 0 999999 32 S unrelated birth\\n`,\n stderr: '',\n };\n },\n };\n});\nconst { processSnapshot } = await import('./verification.js');\n\nfor (const mode of ['unavailable', 'partial-unavailable'] as const) {\n test(`observer failure preserves bounded numeric provenance for ${mode}`, () => {\n observation.mode = mode;\n assert.throws(processSnapshot, (error: unknown) => {\n assert.ok(error instanceof Error);\n const prefix = 'Owned process resource observation failed. ';\n assert.ok(error.message.startsWith(prefix));\n const metadata = JSON.parse(error.message.slice(prefix.length)) as Record<string, unknown>;\n assert.equal(metadata.status, null);\n assert.equal(metadata.errorCode, 'ETIMEDOUT');\n assert.equal(metadata.signal, 'SIGTERM');\n assert.equal(metadata.stdoutPresent, true);\n assert.equal(metadata.stdoutTerminated, false);\n assert.ok(typeof metadata.elapsedMs === 'number' && Number.isSafeInteger(metadata.elapsedMs));\n assert.ok(metadata.elapsedMs >= 0);\n assert.equal(metadata.stdoutBytes, mode === 'unavailable' ? 0 : 19);\n assert.equal(metadata.completeLines, mode === 'unavailable' ? 0 : 1);\n assert.equal(error.message.includes('birth'), false);\n return true;\n });\n });\n}\n"],
|
|
5
|
+
"mappings": "AAAA,OAAO,YAAY;AACnB,SAAS,MAAM,UAAU;AAEzB,MAAM,cAAc,GAAG,QAAQ,OAAO,EAAE,MAAM,WAAW,OAAO,EAAE,EAAE;AACpE,GAAG,KAAK,sBAAsB,OAAO,aAAa;AAChD,QAAM,SAAS,MAAM,SAA8C;AACnE,SAAO;AAAA,IACL,GAAG;AAAA,IACH,WAAW,IAAI,SAA8C;AAC3D,UAAI,KAAK,CAAC,MAAM,iBAAiB,KAAK,CAAC,MAAM,UAAW,QAAO,OAAO,UAAU,GAAG,IAAI;AACvF,kBAAY;AACZ,UAAI,YAAY,SAAS,iBAAiB,YAAY,SAAS;AAC7D,eAAO;AAAA,UACL,QAAQ;AAAA,UACR,OAAO,OAAO,OAAO,IAAI,MAAM,+BAA+B,GAAG,EAAE,MAAM,YAAY,CAAC;AAAA,UACtF,QAAQ;AAAA,UACR,QAAQ,YAAY,SAAS,wBAAwB,yBAAyB;AAAA,UAC9E,QAAQ;AAAA,QACV;AACF,aAAO;AAAA,QACL,QAAQ;AAAA,QACR,QAAQ;AAAA,QACR,QAAQ,GAAG,QAAQ,GAAG,IAAI,QAAQ,IAAI,IAAI,QAAQ,GAAG;AAAA;AAAA;AAAA,QACrD,QAAQ;AAAA,MACV;AAAA,IACF;AAAA,EACF;AACF,CAAC;AACD,MAAM,EAAE,gBAAgB,IAAI,MAAM,OAAO,mBAAmB;AAE5D,WAAW,QAAQ,CAAC,eAAe,qBAAqB,GAAY;AAClE,OAAK,6DAA6D,IAAI,IAAI,MAAM;AAC9E,gBAAY,OAAO;AACnB,WAAO,OAAO,iBAAiB,CAAC,UAAmB;AACjD,aAAO,GAAG,iBAAiB,KAAK;AAChC,YAAM,SAAS;AACf,aAAO,GAAG,MAAM,QAAQ,WAAW,MAAM,CAAC;AAC1C,YAAM,WAAW,KAAK,MAAM,MAAM,QAAQ,MAAM,OAAO,MAAM,CAAC;AAC9D,aAAO,MAAM,SAAS,QAAQ,IAAI;AAClC,aAAO,MAAM,SAAS,WAAW,WAAW;AAC5C,aAAO,MAAM,SAAS,QAAQ,SAAS;AACvC,aAAO,MAAM,SAAS,eAAe,IAAI;AACzC,aAAO,MAAM,SAAS,kBAAkB,KAAK;AAC7C,aAAO,GAAG,OAAO,SAAS,cAAc,YAAY,OAAO,cAAc,SAAS,SAAS,CAAC;AAC5F,aAAO,GAAG,SAAS,aAAa,CAAC;AACjC,aAAO,MAAM,SAAS,aAAa,SAAS,gBAAgB,IAAI,EAAE;AAClE,aAAO,MAAM,SAAS,eAAe,SAAS,gBAAgB,IAAI,CAAC;AACnE,aAAO,MAAM,MAAM,QAAQ,SAAS,OAAO,GAAG,KAAK;AACnD,aAAO;AAAA,IACT,CAAC;AAAA,EACH,CAAC;AACH;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/dist/version.d.ts
CHANGED
|
@@ -1,7 +1 @@
|
|
|
1
1
|
export declare const PACKAGE_VERSION: string;
|
|
2
|
-
/** Module-relative identity of the executing distribution, including the single bundled CLI layout. */
|
|
3
|
-
export declare function readPackageArtifactIdentity(): {
|
|
4
|
-
packageVersion: string;
|
|
5
|
-
packageManifestDigest: string;
|
|
6
|
-
packageDistDigest: string;
|
|
7
|
-
};
|
package/dist/version.js
CHANGED
|
@@ -1,46 +1,9 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { lstatSync, readFileSync, readdirSync } from "node:fs";
|
|
3
|
-
import { join } from "node:path";
|
|
4
|
-
import { fileURLToPath } from "node:url";
|
|
5
|
-
import { digestValue } from "./delivery/common.js";
|
|
6
|
-
import { DeliveryError } from "./errors.js";
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
7
2
|
const packageMetadata = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
8
3
|
if (typeof packageMetadata !== "object" || packageMetadata === null || !("version" in packageMetadata) || typeof packageMetadata.version !== "string" || !/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/u.test(packageMetadata.version))
|
|
9
4
|
throw new Error("The adjacent ai-delivery package identity must contain a stable version.");
|
|
10
5
|
const PACKAGE_VERSION = packageMetadata.version;
|
|
11
|
-
function readPackageArtifactIdentity() {
|
|
12
|
-
const manifest = fileURLToPath(new URL("../package.json", import.meta.url));
|
|
13
|
-
const distribution = fileURLToPath(new URL(".", import.meta.url));
|
|
14
|
-
if (!lstatSync(manifest).isFile() || !lstatSync(distribution).isDirectory())
|
|
15
|
-
throw new DeliveryError("Executing package identity contains an unsupported link or file type.");
|
|
16
|
-
return {
|
|
17
|
-
packageVersion: PACKAGE_VERSION,
|
|
18
|
-
packageManifestDigest: fileDigest(manifest),
|
|
19
|
-
packageDistDigest: directoryDigest(distribution)
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
function fileDigest(path) {
|
|
23
|
-
return `sha256:${createHash("sha256").update(readFileSync(path)).digest("hex")}`;
|
|
24
|
-
}
|
|
25
|
-
function directoryDigest(path) {
|
|
26
|
-
const entries = [];
|
|
27
|
-
const visit = (directory, relative) => {
|
|
28
|
-
for (const entry of readdirSync(directory, { withFileTypes: true }).sort(
|
|
29
|
-
(left, right) => left.name < right.name ? -1 : left.name > right.name ? 1 : 0
|
|
30
|
-
)) {
|
|
31
|
-
const child = join(directory, entry.name);
|
|
32
|
-
const childRelative = relative ? `${relative}/${entry.name}` : entry.name;
|
|
33
|
-
if (entry.isDirectory()) visit(child, childRelative);
|
|
34
|
-
else if (entry.isFile()) entries.push({ path: childRelative, sha256: fileDigest(child) });
|
|
35
|
-
else throw new DeliveryError("Runtime distribution contains an unsupported link or file type.");
|
|
36
|
-
}
|
|
37
|
-
};
|
|
38
|
-
visit(path, "");
|
|
39
|
-
if (entries.length === 0) throw new DeliveryError("Runtime distribution is empty.");
|
|
40
|
-
return digestValue(entries);
|
|
41
|
-
}
|
|
42
6
|
export {
|
|
43
|
-
PACKAGE_VERSION
|
|
44
|
-
readPackageArtifactIdentity
|
|
7
|
+
PACKAGE_VERSION
|
|
45
8
|
};
|
|
46
9
|
//# sourceMappingURL=version.js.map
|
package/dist/version.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/version.ts"],
|
|
4
|
-
"sourcesContent": ["import {
|
|
5
|
-
"mappings": "AAAA,SAAS,
|
|
4
|
+
"sourcesContent": ["import { readFileSync } from 'node:fs';\n\nconst packageMetadata: unknown = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));\nif (\n typeof packageMetadata !== 'object' ||\n packageMetadata === null ||\n !('version' in packageMetadata) ||\n typeof packageMetadata.version !== 'string' ||\n !/^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)$/u.test(packageMetadata.version)\n)\n throw new Error('The adjacent ai-delivery package identity must contain a stable version.');\n\nexport const PACKAGE_VERSION = packageMetadata.version;\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,oBAAoB;AAE7B,MAAM,kBAA2B,KAAK,MAAM,aAAa,IAAI,IAAI,mBAAmB,YAAY,GAAG,GAAG,MAAM,CAAC;AAC7G,IACE,OAAO,oBAAoB,YAC3B,oBAAoB,QACpB,EAAE,aAAa,oBACf,OAAO,gBAAgB,YAAY,YACnC,CAAC,8CAA8C,KAAK,gBAAgB,OAAO;AAE3E,QAAM,IAAI,MAAM,0EAA0E;AAErF,MAAM,kBAAkB,gBAAgB;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ai-delivery",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.39",
|
|
4
4
|
"description": "GitHub issue and pull request delivery tools for prepared worktrees and evidence-based handoff.",
|
|
5
5
|
"author": { "name": "AviaraTech", "url": "https://github.com/aviaratech" },
|
|
6
6
|
"homepage": "https://github.com/aviaratech/ai-delivery#readme",
|
|
7
7
|
"repository": "https://github.com/aviaratech/ai-delivery",
|
|
8
8
|
"license": "MIT",
|
|
9
9
|
"deliveryCapabilityVersion": 2,
|
|
10
|
-
"packageVersion": "0.3.
|
|
10
|
+
"packageVersion": "0.3.39"
|
|
11
11
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
|
|
3
3
|
"name": "ai-delivery",
|
|
4
|
-
"version": "0.3.
|
|
4
|
+
"version": "0.3.39",
|
|
5
5
|
"description": "GitHub issue and pull request delivery tools for prepared worktrees and evidence-based handoff.",
|
|
6
6
|
"author": { "name": "AviaraTech", "url": "https://github.com/aviaratech" },
|
|
7
7
|
"homepage": "https://github.com/aviaratech/ai-delivery#readme",
|