@aiwg/cli 2026.11.0 → 2026.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/agentic/code/providers/flue/README.md +2 -1
  2. package/dist/src/artifacts/cli.js +3 -2
  3. package/dist/src/artifacts/discover-facets.js +2 -0
  4. package/dist/src/artifacts/discover-session-facets.js +14 -0
  5. package/dist/src/artifacts/fortemi-core-query-adapter.js +4 -4
  6. package/dist/src/artifacts/framework-capabilities.js +7 -3
  7. package/dist/src/artifacts/index-builder.js +2 -3
  8. package/dist/src/artifacts/query-engine-discover-output.js +3 -3
  9. package/dist/src/artifacts/query-engine-discover.js +61 -14
  10. package/dist/src/artifacts/query-engine-entries.js +52 -9
  11. package/dist/src/artifacts/query-engine-installation.js +27 -0
  12. package/dist/src/artifacts/query-engine-rules.js +1 -2
  13. package/dist/src/artifacts/query-engine-scoring.js +33 -31
  14. package/dist/src/artifacts/query-engine-show-card.js +6 -2
  15. package/dist/src/artifacts/query-engine-show.js +2 -2
  16. package/dist/src/artifacts/relations.js +17 -10
  17. package/dist/src/cli/handlers/checkpoint.js +143 -0
  18. package/dist/src/cli/handlers/help.js +1 -0
  19. package/dist/src/cli/handlers/index.js +4 -2
  20. package/dist/src/cli/handlers/models-resource-sample.js +7 -3
  21. package/dist/src/cli/handlers/ralph-launcher.js +1 -1
  22. package/dist/src/cli/handlers/script-runner.js +2 -1
  23. package/dist/src/cli/handlers/steward-signing.js +44 -0
  24. package/dist/src/cli/handlers/steward.js +5 -0
  25. package/dist/src/cli/handlers/use-provider-results.js +17 -0
  26. package/dist/src/cli/handlers/use.js +9 -15
  27. package/dist/src/cli/router.js +12 -2
  28. package/dist/src/cli/user-scope-mirror.js +3 -1
  29. package/dist/src/config/aiwg-config.js +5 -1
  30. package/dist/src/config/cli.js +1 -0
  31. package/dist/src/config/delivery-validation.js +21 -0
  32. package/dist/src/config/host-resource-report.d.mts +1 -1
  33. package/dist/src/config/host-resource-report.mjs +23 -4
  34. package/dist/src/config/host-resource-runtime.d.mts +8 -0
  35. package/dist/src/config/host-resource-runtime.mjs +67 -24
  36. package/dist/src/config/index-graph-overrides.js +4 -0
  37. package/dist/src/config/worker-attribution.d.mts +7 -0
  38. package/dist/src/config/worker-attribution.mjs +44 -0
  39. package/dist/src/delivery/git.js +62 -0
  40. package/dist/src/delivery/pr.js +149 -0
  41. package/dist/src/delivery/tracker.js +33 -0
  42. package/dist/src/discovery/interview.js +1 -1
  43. package/dist/src/extensions/claude-hooks-installer.js +1 -0
  44. package/dist/src/extensions/loader.js +2 -1
  45. package/dist/src/issues/cli.js +12 -3
  46. package/dist/src/issues/external-cli.js +76 -0
  47. package/dist/src/issues/live.js +18 -1
  48. package/dist/src/issues/tracker-policy.js +17 -0
  49. package/dist/src/mcp/tools/worker-invoke.mjs +2 -1
  50. package/dist/src/mcp/tools/worker-stdin-runtime.mjs +12 -0
  51. package/dist/src/models/conductor-data-policy.d.mts +3 -2
  52. package/dist/src/models/conductor-data-policy.mjs +94 -5
  53. package/dist/src/models/worker-plan.js +3 -3
  54. package/dist/src/models/worker-selection-policy.js +2 -1
  55. package/dist/src/providers/deployment-lock.js +77 -0
  56. package/dist/src/providers/deployment-ownership.d.mts +12 -2
  57. package/dist/src/providers/deployment-ownership.mjs +115 -21
  58. package/dist/src/providers/deployment-preservation.d.mts +2 -1
  59. package/dist/src/providers/deployment-preservation.mjs +3 -0
  60. package/dist/src/providers/provider-definitions.js +4 -0
  61. package/dist/src/serve/worker-invocation-preparation.js +3 -1
  62. package/dist/src/serve/worker-invocation.js +2 -0
  63. package/dist/src/skills/run.js +5 -0
  64. package/dist/src/smiths/hook-bridge/codex-translator.js +3 -1
  65. package/dist/src/smiths/hook-bridge/hermes-translator.js +3 -1
  66. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +6 -0
  67. package/package.json +4 -2
  68. package/schemas/models/model-config-compatibility.v1.schema.json +4 -0
  69. package/tools/agents/deploy-agents.mjs +15 -0
  70. package/tools/agents/providers/base-contract.mjs +7 -1
  71. package/tools/agents/providers/base-inventory.mjs +35 -13
  72. package/tools/agents/providers/base.mjs +1 -1
  73. package/tools/agents/providers/conductor-data-guard.mjs +35 -11
  74. package/tools/agents/providers/muse-hooks.mjs +4 -0
  75. package/tools/agents/providers/muse-prompt-discovery.mjs +22 -0
  76. package/tools/agents/providers/provider-prepare-coordinator.mjs +15 -10
  77. package/tools/agents/providers/rule-delivery-surface.mjs +6 -3
  78. package/tools/agents/providers/rule-deployment-commit.mjs +10 -0
  79. package/tools/agents/providers/stale-artifact-prune.mjs +9 -8
  80. package/tools/ralph-external/lib/worker-capture.mjs +157 -0
  81. package/tools/ralph-external/lib/worker-health.mjs +3 -0
  82. package/tools/ralph-external/lib/worker-invocation-processes.mjs +9 -6
  83. package/tools/ralph-external/lib/worker-launch-cli.mjs +10 -1
  84. package/tools/ralph-external/lib/worker-process-identity.mjs +30 -0
  85. package/tools/ralph-external/lib/worker-retry-evidence.mjs +87 -6
  86. package/tools/ralph-external/lib/worker-termination.mjs +56 -6
  87. package/tools/ralph-external/process-monitor.mjs +12 -18
  88. package/tools/ralph-external/session-launcher.mjs +43 -29
  89. package/vscode-extension/schemas/aiwg.config.v1.json +15 -0
@@ -1,4 +1,5 @@
1
1
  // Confirm owned containment is empty independently of semantic observer coverage.
2
+ import { readdirSync, readFileSync } from 'node:fs';
2
3
  import { sampleWorkerIdentity, isSafeWorkerGroupTarget } from '../process-monitor.mjs';
3
4
  import { getWorkerIsolationStatus } from './worker-isolation-status.mjs';
4
5
  import { scanWorkerInvocationProcesses } from './worker-invocation-processes.mjs';
@@ -9,7 +10,7 @@ const TERMINATION_MAX_ATTEMPTS = 21;
9
10
 
10
11
  export function observeWorkerTermination({ mode, native, workerExited, identity,
11
12
  supervisor = sampleWorkerIdentity(process.pid), kill = process.kill, invocationId,
12
- scan = scanWorkerInvocationProcesses, deadline, now = () => performance.now() } = {}) {
13
+ scan = scanWorkerInvocationProcesses, groupStates = sampleGroupStates, deadline, now = () => performance.now() } = {}) {
13
14
  if (mode === 'systemd-unit') {
14
15
  const exited = workerExited === true || [1, 2, 3].includes(native?.execMainCode);
15
16
  return { confirmed: exited && native?.active === false && native?.cgroupEmpty === true,
@@ -22,22 +23,71 @@ export function observeWorkerTermination({ mode, native, workerExited, identity,
22
23
  || !isSafeWorkerGroupTarget(identity.pgid, supervisor)) {
23
24
  return { confirmed: false, missing: 'launcher-owned process group identity on this host and boot' };
24
25
  }
25
- try { kill(-identity.pgid, 0); }
26
+ let groupEmpty = false;
27
+ try {
28
+ kill(-identity.pgid, 0);
29
+ // Signal 0 also reaches zombies. A reaper that never waits (a container's
30
+ // PID 1) can leave killed members as zombies indefinitely; a group whose
31
+ // remaining members are all zombies has no live process (#3853).
32
+ // Absence from /proc is never proof; only observed zombies explaining
33
+ // signal 0, with no live or unreadable member, count as an empty group.
34
+ const states = groupStates(identity.pgid);
35
+ groupEmpty = !!states && states.zombies > 0 && states.live === 0 && states.unreadable === 0;
36
+ }
26
37
  catch (error) {
27
38
  // Pass the recorded leader so the marker scan can tell a parallel
28
39
  // hardened (non-dumpable) worker's tree apart from a genuine escapee via
29
40
  // readable stat/cgroup links instead of failing closed on every
30
41
  // unreadable post-start process.
31
42
  if (error.code === 'ESRCH') {
32
- // Exit-time callers get one scan, at most 2 s. An explicit deadline
33
- // leaves the scan budget and retries to the recheck caller.
43
+ // A standalone observation gets one scan, at most 2 s. An explicit
44
+ // deadline leaves the shared budget and retries to its caller.
34
45
  return scan({ invocationId, startTicks: identity.startTicks, uid: identity.uid, now,
35
46
  deadline: deadline ?? now() + TERMINATION_BUDGET_MS,
36
47
  workerPid: identity.pid, workerPgid: identity.pgid, workerSession: identity.sessionId });
37
48
  }
38
49
  return { confirmed: false, missing: `empty owned process group (signal-0 returned ${error.code ?? 'unknown'})` };
39
50
  }
40
- return { confirmed: false, missing: 'empty owned process group (signal-0 still finds members)' };
51
+ if (groupEmpty) {
52
+ return scan({ invocationId, startTicks: identity.startTicks, uid: identity.uid, now,
53
+ deadline: deadline ?? now() + TERMINATION_BUDGET_MS,
54
+ workerPid: identity.pid, workerPgid: identity.pgid, workerSession: identity.sessionId });
55
+ }
56
+ return { confirmed: false, missing: 'empty owned process group (signal-0 still finds members)', retryable: true };
57
+ }
58
+
59
+ /** Count a process group's members by /proc state: zombies, live and unreadable. */
60
+ export function sampleGroupStates(pgid) {
61
+ if (!Number.isSafeInteger(pgid) || pgid <= 0 || process.platform !== 'linux') return null;
62
+ const states = { zombies: 0, live: 0, unreadable: 0 };
63
+ let entries;
64
+ try { entries = readdirSync('/proc'); } catch { return null; }
65
+ for (const entry of entries) {
66
+ if (!/^\d+$/.test(entry)) continue;
67
+ let stat;
68
+ try { stat = readFileSync(`/proc/${entry}/stat`, 'utf8'); }
69
+ catch (error) { if (error.code !== 'ENOENT' && error.code !== 'ESRCH') states.unreadable += 1; continue; }
70
+ const fields = stat.slice(stat.lastIndexOf(')') + 2).split(/\s+/);
71
+ if (Number(fields[2]) !== pgid) continue;
72
+ if (fields[0] === 'Z') states.zombies += 1; else states.live += 1;
73
+ }
74
+ return states;
75
+ }
76
+
77
+ // Share the exit-time budget across transient kernel observations; each scan
78
+ // gets all remaining time so a large inventory is never restarted at 100 ms.
79
+ export async function settleWorkerTermination({ now = () => performance.now(),
80
+ wait = ms => new Promise(resolve => setTimeout(resolve, ms)), ...options } = {}) {
81
+ const deadline = now() + TERMINATION_BUDGET_MS;
82
+ let evidence;
83
+ for (let attempt = 0; attempt < TERMINATION_MAX_ATTEMPTS; attempt++) {
84
+ if (evidence && now() >= deadline) return evidence;
85
+ evidence = observeWorkerTermination({ ...options, now, deadline });
86
+ if (evidence.confirmed || evidence.markerPresent || !evidence.retryable
87
+ || now() >= deadline || attempt === TERMINATION_MAX_ATTEMPTS - 1) return evidence;
88
+ await wait(Math.min(TERMINATION_ATTEMPT_MS, Math.max(0, deadline - now())));
89
+ }
90
+ return evidence;
41
91
  }
42
92
 
43
93
  export function terminationRemedy(result, runDir) {
@@ -79,7 +129,7 @@ export async function recheckWorkerTermination({ processRecord, exitRecord,
79
129
  catch { /* Unavailable is never empty. */ }
80
130
  }
81
131
  evidence = observe({ mode: processRecord.isolation, native, identity, invocationId: processRecord.invocationId,
82
- deadline: Math.min(deadline, now() + TERMINATION_ATTEMPT_MS), now,
132
+ deadline, now,
83
133
  workerExited: Number.isInteger(exitRecord.exitCode) && exitRecord.exitCode >= 0 && exitRecord.exitCode <= 255
84
134
  || exitRecord.captureCoverage === 'complete' && exitRecord.workerTermination === 'confirmed' && /^SIG[A-Z0-9]+$/.test(exitRecord.signal ?? '') });
85
135
  if (evidence.confirmed || evidence.markerPresent || now() >= deadline || attempt === TERMINATION_MAX_ATTEMPTS - 1) return evidence;
@@ -10,14 +10,14 @@
10
10
  import { fileURLToPath } from 'node:url';
11
11
  import { EventEmitter } from 'events';
12
12
  import { execFileSync } from 'child_process';
13
- import { existsSync, readFileSync, writeFileSync, mkdirSync, readlinkSync, readdirSync } from 'fs';
14
- import { hostname } from 'node:os';
13
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'fs';
15
14
  import { join, dirname } from 'path';
16
15
  import { constants } from 'node:fs';
17
16
  import { open, opendir, rename, unlink } from 'node:fs/promises';
18
17
  import { createHash, randomUUID } from 'node:crypto';
19
18
  import path from 'node:path';
20
19
  import { createWorkerHealthObserver } from './lib/worker-health.mjs';
20
+ import { sampleWorkerProcIdentity } from './lib/worker-process-identity.mjs';
21
21
 
22
22
  // This module is loaded standalone in some contexts (e.g. staged/partial
23
23
  // installs, or copied in isolation for a test) without its sibling
@@ -68,22 +68,16 @@ if (importImpl) {
68
68
  }
69
69
  }
70
70
 
71
- /** Side-effect-free Linux sample. Unknown identity never grants signal authority. */
72
- export function sampleWorkerIdentity(pid) {
73
- if (process.platform !== 'linux' || !Number.isSafeInteger(pid) || pid <= 0) return null;
74
- try {
75
- const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');
76
- const fields = stat.slice(stat.lastIndexOf(')') + 2).trim().split(/\s+/);
77
- const uid = Number(/^Uid:\s+(\d+)/m.exec(readFileSync(`/proc/${pid}/status`, 'utf8'))?.[1]);
78
- const bootId = readFileSync('/proc/sys/kernel/random/boot_id', 'utf8').trim();
79
- const executable = readlinkSync(`/proc/${pid}/exe`);
80
- if (!Number.isSafeInteger(uid) || !bootId || !fields[19]) return null;
81
- return { pid, pgid: Number(fields[2]), uid, parentPid: Number(fields[1]), sessionId: Number(fields[3]),
82
- host: hostname(), bootId, startTicks: fields[19], executable, state: fields[0],
83
- // /proc stat fields 14/15 are utime/stime; 16/17 are cutime/cstime
84
- // accumulated for waited-for children, including child-heavy CLIs.
85
- cpuTicks: Number(fields[11]) + Number(fields[12]) + Number(fields[13]) + Number(fields[14]) };
86
- } catch { return null; }
71
+ /**
72
+ * Side-effect-free Linux sample. Unknown identity never grants signal authority.
73
+ * An exited, unreaped child (zombie without /proc/<pid>/exe) counts as gone, so
74
+ * liveness, group-member and ancestry checks never treat it as running. Only
75
+ * spawn-time identity capture passes `includeExited` to keep a fast-exiting
76
+ * worker's birth identity (#3835).
77
+ */
78
+ export function sampleWorkerIdentity(pid, { includeExited = false } = {}) {
79
+ const identity = sampleWorkerProcIdentity(pid);
80
+ return identity && (includeExited || identity.executable !== null) ? identity : null;
87
81
  }
88
82
 
89
83
  export function sameWorkerIdentity(expected, actual) {
@@ -51,10 +51,10 @@ export { assertManagedWorkerLaunch } from './lib/managed-worker-attempt.mjs';
51
51
  import { buildSessionEnvironment } from './lib/session-environment.mjs';
52
52
  import { withWorkerPath, boundedPrivateRead } from './lib/worker-inputs.mjs';
53
53
  import { collectWorkerFinal } from './lib/worker-final.mjs';
54
- import { verifyRetryPredecessor } from './lib/worker-retry-evidence.mjs';
55
- import { observeWorkerTermination, terminationRemedy } from './lib/worker-termination.mjs';
56
- import { buildWorkerInvocationEnvironment, WORKER_INVOCATION_MARKER } from './lib/worker-invocation-processes.mjs';
57
- import { resolveRetryReference } from './lib/worker-launch-cli.mjs';
54
+ import { prepareWorkerRetry, workerRetryRecordFields } from './lib/worker-retry-evidence.mjs';
55
+ import { settleWorkerTermination, terminationRemedy } from './lib/worker-termination.mjs';
56
+ import { WorkerCaptureOwner, assertWorkerCapturePathsAvailable } from './lib/worker-capture.mjs';
57
+ import { buildWorkerInvocationEnvironment } from './lib/worker-invocation-processes.mjs';
58
58
  import { launcherRecoveryEvidence, observeLauncherRecoveryOutcome, recordLauncherRecoveryHint } from './lib/launcher-recovery-evidence.mjs';
59
59
  export { observeLauncherRecoveryOutcome } from './lib/launcher-recovery-evidence.mjs';
60
60
  import { publishWorkerUnitExit, readRecordedWorkerUnitStop } from './lib/worker-unit-cleanup.mjs';
@@ -426,12 +426,8 @@ async function launchOneWorker(owner, options) {
426
426
  // `writableRoots` is already computed above for the run-directory check)
427
427
  // is what it takes to pass the SAME production-resolved roots into this
428
428
  // check too.
429
- let verifiedPreviousAttemptId = null;
430
- if (options?.retryOf !== undefined) {
431
- const exitRecord = await verifyRetryPredecessor(await resolveRetryReference(options.retryOf, { inspect }),
432
- { newInvocationPath: options?.invocationPath, inspect, workerWritableRoots: writableRoots, checkDescendants: options.checkDescendants });
433
- verifiedPreviousAttemptId = exitRecord.invocationId;
434
- }
429
+ options = { ...options, retryEvidence: await prepareWorkerRetry(options, { saved, inspect, workerWritableRoots: writableRoots }) };
430
+ const verifiedPreviousAttemptId = options.retryEvidence?.previousAttemptId ?? null;
435
431
  const paths = (await importImpl(import.meta.url, 'serve/worker-invocation-paths.js')).workerOutputPaths(invocation);
436
432
  if (new Set(Object.values(paths)).size !== Object.keys(paths).length || Object.values(paths).some(filename =>
437
433
  filename === options.invocationPath || filename === invocation.briefPath
@@ -440,6 +436,7 @@ async function launchOneWorker(owner, options) {
440
436
  'stdout.log', 'stdout.events.jsonl', 'stderr.log', '.launch-owner'].some(name => filename === join(runDir, name)))) {
441
437
  throw new Error('Worker output paths must be distinct from trusted metadata, capture files and artifact- paths');
442
438
  }
439
+ await assertWorkerCapturePathsAvailable(paths, inspect, { runDir, writableRoots: [invocation.cwd, ...writableRoots] });
443
440
  for (const filename of Object.values(paths)) {
444
441
  if (await inspect(filename, 'output')) throw new Error('Fresh worker output paths are required');
445
442
  if (!await inspect(dirname(filename), 'directory')) throw new Error('Worker output parent is missing');
@@ -517,7 +514,7 @@ async function launchOneWorker(owner, options) {
517
514
  // unconditionally here is exactly as safe as computing it conditionally
518
515
  // was unsafe — this file no longer has two places that both decide
519
516
  // "is this gated" and can disagree.
520
- const taskDigest = await stableTaskChainDigest(saved.request, invocation.briefDigest);
517
+ const taskDigest = options.retryEvidence?.taskDigest ?? await stableTaskChainDigest(saved.request, invocation.briefDigest);
521
518
  const dispatchClockNow = () => options.scopedBreaker?.nowMs?.() ?? Number(process.hrtime.bigint()) / 1e6;
522
519
  const dispatchGuard = options.dispatchGuard ?? {
523
520
  nowMs: dispatchClockNow,
@@ -639,7 +636,8 @@ async function launchOneWorker(owner, options) {
639
636
  const profile = inputs.drivers[invocation.selected.cli].qualification.adapter.invocationProfiles[invocation.selected.profileRef];
640
637
  const captures = { stdout: join(runDir, profile.health?.outputFraming === 'jsonl' ? 'stdout.events.jsonl' : 'stdout.log'),
641
638
  stderr: join(runDir, 'stderr.log') };
642
- const writeRecord = options.publishRecord ?? publishWorkerRecord;
639
+ const captureOwner = new WorkerCaptureOwner({ runDir, paths, captures, inspect, invocationId });
640
+ const writeRecord = captureOwner.writer(options.publishRecord ?? publishWorkerRecord, publishWorkerRecord);
643
641
  const publishFailures = [];
644
642
  let publishing = Promise.resolve();
645
643
  // Each write must stay independent: one rejected publish must never block
@@ -685,6 +683,7 @@ async function launchOneWorker(owner, options) {
685
683
  // owned, launcher-written, confirmed-terminal evidence for this exact
686
684
  // task — never from an unverified caller claim.
687
685
  previousAttemptId: verifiedPreviousAttemptId,
686
+ ...workerRetryRecordFields(options.retryEvidence),
688
687
  requestId: invocationId, taskDigest, role: saved.request.role,
689
688
  ...(options.managedAdmission ? { attempt: options.attempt } : {}),
690
689
  selected: invocation.selected, planDigest: qualificationDigest(saved), invocationDigest: qualificationDigest(invocation),
@@ -695,7 +694,7 @@ async function launchOneWorker(owner, options) {
695
694
  executedArgvDigest: qualificationDigest(artifacts.argv),
696
695
  artifacts: (invocation.artifacts ?? []).map(artifact => ({ name: artifact.name,
697
696
  byteLength: Buffer.byteLength(artifact.content), sha256: bytesDigest(artifact.content) })),
698
- envNames: [...new Set([...invocation.envNames, WORKER_INVOCATION_MARKER])], stdin: invocation.stdin,
697
+ envNames: buildWorkerInvocationEnvironment(invocation.envNames, invocationId, {}, invocation).envNames, stdin: invocation.stdin,
699
698
  prompt: { path: invocation.briefPath, digest: invocation.briefDigest }, cwd: invocation.cwd,
700
699
  worktree: { path: invocation.cwd, baseRevision: null }, paths, captures, outputFraming: profile.health?.outputFraming ?? 'opaque',
701
700
  health: invocation.health ?? null, transport: invocation.transport,
@@ -706,7 +705,7 @@ async function launchOneWorker(owner, options) {
706
705
  // All captures (including the reserved final) open successfully BEFORE spawn.
707
706
  for (const filename of [...Object.values(paths), ...Object.values(captures)]) {
708
707
  const handle = await withWorkerPath(filename, target => (options.openCapture ?? open)(target, constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600));
709
- handles.push(handle);
708
+ handles.push(handle); await captureOwner.reserveOutput(filename);
710
709
  }
711
710
  // Recheck policy, prompt, installation and exact bindings after file preparation.
712
711
  inputs = await loadInputs();
@@ -715,7 +714,7 @@ async function launchOneWorker(owner, options) {
715
714
  paths: await Promise.all([invocation.cwd, runDir].map(workerDispatchPath)) });
716
715
  if (!gate.ok) throw workerDispatchRefusal(gate);
717
716
  if (bytesDigest(await boundedPrivateRead(invocation.briefPath, 262144, inspect)) !== invocation.briefDigest) throw new Error('Worker prompt changed before spawn');
718
- const environment = buildWorkerInvocationEnvironment(invocation.envNames, invocationId);
717
+ const environment = buildWorkerInvocationEnvironment(invocation.envNames, invocationId, process.env, invocation);
719
718
  const baselineContent = await sampleOwnedWorktreeContent(invocation.cwd, { files: options.healthArtifacts });
720
719
  // #2915 round 8 (D2, replaces the former "debit immediately before this
721
720
  // call" comment): the ledger debit now happens INSIDE the dispatch-
@@ -909,6 +908,7 @@ async function launchOneWorker(owner, options) {
909
908
  await inspect(runDir, 'directory');
910
909
  await withWorkerPath(runDir, async target => { const handle = await open(target, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
911
910
  try { await handle.chmod(0o700); } finally { await handle.close(); } });
911
+ await captureOwner.finish();
912
912
  }
913
913
  }
914
914
  }
@@ -949,7 +949,8 @@ async function captureOneWorker(owner, ctx) {
949
949
  const { child, outcome, invocation, invocationId, supervisor, launchTime, monotonicStart, publish, paths, handles, options,
950
950
  canaryDeadlineMs = null, canaryNowMs = () => Date.now(), recoveryGated = false } = ctx;
951
951
  const hasTransport = outcome.mode === 'systemd-unit' || outcome.transportSupervisor;
952
- const sampleIdentity = options.sampleIdentity ?? sampleWorkerIdentity;
952
+ // Spawn-time capture keeps a fast-exiting worker's identity (#3835).
953
+ const sampleIdentity = options.sampleIdentity ?? (pid => sampleWorkerIdentity(pid, { includeExited: true }));
953
954
  // Separate hook from `sampleIdentity` (the worker-side sampler): this one
954
955
  // samples the launcher's own trusted transport child, never a worker PID,
955
956
  // and tests need to control the two independently (e.g. the transport
@@ -1138,8 +1139,10 @@ async function captureOneWorker(owner, ctx) {
1138
1139
  const native = outcome.unit ? readNative() ?? readRecordedWorkerUnitStop(outcome, { native: true }) : null;
1139
1140
  const members = identity ? sampleWorkerGroup(identity.pgid) : null;
1140
1141
  // Require positive kernel evidence of owned containment being empty.
1141
- const confirmed = (outcome.mode !== 'systemd-unit' && child.pid === undefined) || observeWorkerTermination({ mode: outcome.mode, native,
1142
- workerExited: sawExit, identity, supervisor, invocationId }).confirmed;
1142
+ const terminationEvidence = outcome.mode !== 'systemd-unit' && child.pid === undefined
1143
+ ? { confirmed: true, missing: null } : await settleWorkerTermination({ mode: outcome.mode, native,
1144
+ workerExited: sawExit, identity, supervisor, invocationId });
1145
+ const confirmed = terminationEvidence.confirmed;
1143
1146
  // `worker-exit.json`/`worker-identity.json` are written into a directory
1144
1147
  // the worker itself can reach (same UID, no filesystem confinement), so a
1145
1148
  // worker can plant either file before the trusted transport ever writes
@@ -1175,7 +1178,7 @@ async function captureOneWorker(owner, ctx) {
1175
1178
  : outcome.mode === 'systemd-unit' && native?.execMainCode === 1 ? native.execMainStatus : waitCode;
1176
1179
  const result = { invocationId, exitCode, signal: resultSignal,
1177
1180
  endedAt: new Date().toISOString(), termination: confirmed ? 'confirmed' : 'uncertain',
1178
- descendants: confirmed ? 'none' : 'unknown', timedOut: resultTimedOut,
1181
+ terminationMissing: terminationEvidence.missing, descendants: confirmed ? 'none' : 'unknown', timedOut: resultTimedOut,
1179
1182
  cancelled: stopReason === 'CANCELLED', stopReason, errorCode: errorCode ?? null, capturedBytes: Math.min(total, output.length),
1180
1183
  // Unauthenticated: reported by the worker-writable transport record, not
1181
1184
  // kernel-observed. Never used above for exitCode/signal/termination.
@@ -1547,7 +1550,8 @@ async function launchOneWorkerBaseline(owner, options, ctx) {
1547
1550
  const profile = inputs.drivers[invocation.selected.cli].qualification.adapter.invocationProfiles[invocation.selected.profileRef];
1548
1551
  const captures = { stdout: join(runDir, profile.health?.outputFraming === 'jsonl' ? 'stdout.events.jsonl' : 'stdout.log'),
1549
1552
  stderr: join(runDir, 'stderr.log') };
1550
- const writeRecord = options.publishRecord ?? publishWorkerRecord;
1553
+ const captureOwner = new WorkerCaptureOwner({ runDir, paths, captures, inspect, invocationId });
1554
+ const writeRecord = captureOwner.writer(options.publishRecord ?? publishWorkerRecord, publishWorkerRecord);
1551
1555
  const publishFailures = [];
1552
1556
  let publishing = Promise.resolve();
1553
1557
  const artifactLifecycle = new WorkerArtifactLifecycle(invocation, invocationId);
@@ -1565,7 +1569,8 @@ async function launchOneWorkerBaseline(owner, options, ctx) {
1565
1569
  artifacts = await materializeWorkerArtifacts(invocation, runDir);
1566
1570
  const displayArgv = artifacts.argv.map((token, i) => i === 0 ? token : `<argument:${bytesDigest(token)}>`);
1567
1571
  await publish('invocation.json', { version: 1, origin: 'launcher', invocationId, attemptId: invocationId,
1568
- previousAttemptId: verifiedPreviousAttemptId ?? null, requestId: options.managedAdmission?.requestId ?? invocationId, taskDigest: qualificationDigest(saved.request), role: saved.request.role,
1572
+ previousAttemptId: verifiedPreviousAttemptId ?? null, requestId: options.managedAdmission?.requestId ?? invocationId, taskDigest: options.retryEvidence?.taskDigest ?? qualificationDigest(saved.request), role: saved.request.role,
1573
+ ...workerRetryRecordFields(options.retryEvidence),
1569
1574
  ...(options.managedAdmission ? { attempt: options.attempt } : {}),
1570
1575
  selected: invocation.selected, planDigest: qualificationDigest(saved), invocationDigest: qualificationDigest(invocation),
1571
1576
  policyDigest: invocation.policyDigest, catalogDigest: invocation.catalogDigest, profileDigest: invocation.profileDigest,
@@ -1575,7 +1580,7 @@ async function launchOneWorkerBaseline(owner, options, ctx) {
1575
1580
  executedArgvDigest: qualificationDigest(artifacts.argv),
1576
1581
  artifacts: (invocation.artifacts ?? []).map(artifact => ({ name: artifact.name,
1577
1582
  byteLength: Buffer.byteLength(artifact.content), sha256: bytesDigest(artifact.content) })),
1578
- envNames: [...new Set([...invocation.envNames, WORKER_INVOCATION_MARKER])], stdin: invocation.stdin,
1583
+ envNames: buildWorkerInvocationEnvironment(invocation.envNames, invocationId, {}, invocation).envNames, stdin: invocation.stdin,
1579
1584
  prompt: { path: invocation.briefPath, digest: invocation.briefDigest }, cwd: invocation.cwd,
1580
1585
  worktree: { path: invocation.cwd, baseRevision: null }, paths, captures, outputFraming: profile.health?.outputFraming ?? 'opaque',
1581
1586
  health: invocation.health ?? null, transport: invocation.transport,
@@ -1586,7 +1591,7 @@ async function launchOneWorkerBaseline(owner, options, ctx) {
1586
1591
  // All captures (including the reserved final) open successfully BEFORE spawn.
1587
1592
  for (const filename of [...Object.values(paths), ...Object.values(captures)]) {
1588
1593
  const handle = await withWorkerPath(filename, target => (options.openCapture ?? open)(target, constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600));
1589
- handles.push(handle);
1594
+ handles.push(handle); await captureOwner.reserveOutput(filename);
1590
1595
  }
1591
1596
  // Recheck policy, prompt, installation and exact bindings after file preparation.
1592
1597
  inputs = await loadInputs();
@@ -1595,7 +1600,7 @@ async function launchOneWorkerBaseline(owner, options, ctx) {
1595
1600
  paths: await Promise.all([invocation.cwd, runDir].map(workerDispatchPath)) });
1596
1601
  if (!localGate.ok) throw workerDispatchRefusal(localGate);
1597
1602
  if (bytesDigest(await boundedPrivateRead(invocation.briefPath, 262144, inspect)) !== invocation.briefDigest) throw new Error('Worker prompt changed before spawn');
1598
- const environment = buildWorkerInvocationEnvironment(invocation.envNames, invocationId);
1603
+ const environment = buildWorkerInvocationEnvironment(invocation.envNames, invocationId, process.env, invocation);
1599
1604
  const baselineContent = await sampleOwnedWorktreeContent(invocation.cwd, { files: options.healthArtifacts });
1600
1605
  // The real `launchIsolatedWorker`, called with no `onDispatchCommit`
1601
1606
  // (never passed anywhere in this frozen function), is synchronous —
@@ -1637,6 +1642,7 @@ async function launchOneWorkerBaseline(owner, options, ctx) {
1637
1642
  await inspect(runDir, 'directory');
1638
1643
  await withWorkerPath(runDir, async target => { const handle = await open(target, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
1639
1644
  try { await handle.chmod(0o700); } finally { await handle.close(); } });
1645
+ await captureOwner.finish();
1640
1646
  }
1641
1647
  }
1642
1648
  }
@@ -1644,7 +1650,8 @@ async function launchOneWorkerBaseline(owner, options, ctx) {
1644
1650
  async function captureOneWorkerBaseline(owner, ctx) {
1645
1651
  const { child, outcome, invocation, invocationId, supervisor, launchTime, monotonicStart, publish, paths, handles, options } = ctx;
1646
1652
  const hasTransport = outcome.mode === 'systemd-unit' || outcome.transportSupervisor;
1647
- const sampleIdentity = options.sampleIdentity ?? sampleWorkerIdentity;
1653
+ // Spawn-time capture keeps a fast-exiting worker's identity (#3835).
1654
+ const sampleIdentity = options.sampleIdentity ?? (pid => sampleWorkerIdentity(pid, { includeExited: true }));
1648
1655
  const sampleNativeSupervisor = options.sampleNativeSupervisor ?? sampleWorkerIdentity;
1649
1656
  // For our own detached child, spawn waits through setsid/exec; one owned leader sample suffices.
1650
1657
  const immediate = !hasTransport ? sampleIdentity(child.pid) : null;
@@ -1807,8 +1814,10 @@ async function captureOneWorkerBaseline(owner, ctx) {
1807
1814
  // evidence is used wherever it is available.
1808
1815
  const native = outcome.unit ? readNative() ?? readRecordedWorkerUnitStop(outcome, { native: true }) : null;
1809
1816
  const members = identity ? sampleWorkerGroup(identity.pgid) : null;
1810
- const confirmed = (outcome.mode !== 'systemd-unit' && child.pid === undefined) || observeWorkerTermination({ mode: outcome.mode, native,
1811
- workerExited: sawExit, identity, supervisor, invocationId }).confirmed;
1817
+ const terminationEvidence = outcome.mode !== 'systemd-unit' && child.pid === undefined
1818
+ ? { confirmed: true, missing: null } : await settleWorkerTermination({ mode: outcome.mode, native,
1819
+ workerExited: sawExit, identity, supervisor, invocationId });
1820
+ const confirmed = terminationEvidence.confirmed;
1812
1821
  const workerExit = hasTransport ? await transportRecord('worker-exit.json') : null;
1813
1822
  if (!identity && hasTransport && nativeSupervisor) {
1814
1823
  const workerStart = await transportRecord('worker-identity.json');
@@ -1827,7 +1836,7 @@ async function captureOneWorkerBaseline(owner, ctx) {
1827
1836
  const result = { invocationId, exitCode, signal: resultSignal,
1828
1837
  ...(options.managedAdmission ? { managedAdmission: options.managedAdmission } : {}),
1829
1838
  endedAt: new Date().toISOString(), termination: confirmed ? 'confirmed' : 'uncertain',
1830
- descendants: confirmed ? 'none' : 'unknown', timedOut: resultTimedOut,
1839
+ terminationMissing: terminationEvidence.missing, descendants: confirmed ? 'none' : 'unknown', timedOut: resultTimedOut,
1831
1840
  cancelled: stopReason === 'CANCELLED', stopReason, errorCode: errorCode ?? null, capturedBytes: Math.min(total, output.length),
1832
1841
  workerTermination: hasTransport ? workerExit && !workerExit.errorCode ? 'confirmed' : 'uncertain' : sawExit ? 'confirmed' : 'uncertain',
1833
1842
  workerReportedExit: workerExit ? { exitCode: workerExit.exitCode, signal: workerExit.signal, errorCode: workerExit.errorCode ?? null } : null,
@@ -2037,7 +2046,7 @@ export const UNBOUND_RETRY_EVIDENCE_CODE = 'UNBOUND_RETRY_EVIDENCE';
2037
2046
  * retry and is surfaced with a code the conductor can act on — it must never
2038
2047
  * silently spawn a duplicate writer.
2039
2048
  */
2040
- export function stopBeforeRetryGate(previousResult, { expectedInvocationId = null, runDir, missing } = {}) {
2049
+ export function stopBeforeRetryGate(previousResult, { expectedInvocationId = null, runDir, missing = previousResult?.terminationMissing } = {}) {
2041
2050
  if (previousResult?.termination !== 'confirmed') {
2042
2051
  return {
2043
2052
  ok: false,
@@ -4969,6 +4978,11 @@ export function planDirectWorkerLaunch({
4969
4978
  // for the not-gated/disabled-CLI paths below, which must stay
4970
4979
  // synchronous and byte-for-byte legacy — passing `undefined` through to
4971
4980
  // `launchIsolatedWorker` is the dual-mode contract that keeps it so.
4981
+ if (invocation?.cwd && invocation?.selected?.group) {
4982
+ invocationId ??= invocation.invocationId ?? randomUUID();
4983
+ const marked = buildWorkerInvocationEnvironment(envNames ?? [], invocationId, env ?? process.env, invocation);
4984
+ envNames = marked.envNames; env = marked.env;
4985
+ }
4972
4986
  let dispatchAttempt;
4973
4987
  const launch = (onDispatchCommit) => launchIsolatedWorker({ name, memoryMaxGb, command, args, cwd, logFile, stdinPath, stdoutPath, stderrPath,
4974
4988
  gate, config, allowDegraded, attached, ownedGroup,
@@ -516,6 +516,11 @@
516
516
  ],
517
517
  "description": "How agents deliver code. direct = commit/push to default_branch; feature-branch = push branch, no PR; pr-required = branch + PR (default)"
518
518
  },
519
+ "merge": {
520
+ "type": "string",
521
+ "enum": ["local-signed", "local", "tracker"],
522
+ "description": "Merge execution route. Defaults to tracker; local-signed is optional and requires signing configuration."
523
+ },
519
524
  "default_branch": {
520
525
  "type": "string",
521
526
  "description": "Default branch name. Defaults to 'main'."
@@ -2486,6 +2491,16 @@
2486
2491
  "type": "object",
2487
2492
  "additionalProperties": false,
2488
2493
  "properties": {
2494
+ "credential": {
2495
+ "type": "object",
2496
+ "additionalProperties": false,
2497
+ "properties": {
2498
+ "store": { "type": "string", "minLength": 1, "pattern": "^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$" },
2499
+ "env": { "type": "string", "pattern": "^[A-Za-z_][A-Za-z0-9_]*$" }
2500
+ },
2501
+ "oneOf": [{ "required": ["store"], "properties": { "store": {} } }, { "required": ["env"], "properties": { "env": {} } }],
2502
+ "description": "Sensitive-input reference only; never a literal token."
2503
+ },
2489
2504
  "login": {
2490
2505
  "type": "string",
2491
2506
  "description": "Forge login that should author delivery writes."