@aiwg/cli 2026.11.0 → 2026.11.2

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 (168) hide show
  1. package/agentic/code/addons/aiwg-hooks/canonical/aiwg-prompt-discovery.yaml +9 -0
  2. package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +136 -0
  3. package/agentic/code/providers/flue/README.md +2 -1
  4. package/agentic/code/providers/model-capabilities.v1.json +27 -23
  5. package/agentic/code/providers/model-catalog.v1.json +3 -3
  6. package/dist/src/artifacts/cli.js +13 -13
  7. package/dist/src/artifacts/discover-cli-help.js +25 -0
  8. package/dist/src/artifacts/discover-facets.js +2 -0
  9. package/dist/src/artifacts/discover-session-facets.js +15 -0
  10. package/dist/src/artifacts/fortemi-core-prebuilt-freshness.js +28 -0
  11. package/dist/src/artifacts/fortemi-core-query-adapter.js +4 -4
  12. package/dist/src/artifacts/fortemi-core-sync.js +3 -0
  13. package/dist/src/artifacts/framework-capabilities.js +11 -3
  14. package/dist/src/artifacts/framework-source-digest.js +1 -1
  15. package/dist/src/artifacts/index-builder.js +12 -13
  16. package/dist/src/artifacts/index-dependencies.js +72 -0
  17. package/dist/src/artifacts/query-engine-discover-output.js +13 -5
  18. package/dist/src/artifacts/query-engine-discover.js +103 -28
  19. package/dist/src/artifacts/query-engine-entries.js +107 -10
  20. package/dist/src/artifacts/query-engine-installation.js +27 -0
  21. package/dist/src/artifacts/query-engine-options.js +14 -1
  22. package/dist/src/artifacts/query-engine-rules.js +1 -2
  23. package/dist/src/artifacts/query-engine-scoring.js +38 -32
  24. package/dist/src/artifacts/query-engine-show-card.js +8 -2
  25. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  26. package/dist/src/artifacts/query-engine-show.js +5 -3
  27. package/dist/src/artifacts/query-engine-templates.js +33 -0
  28. package/dist/src/artifacts/query-engine-verbose.js +25 -0
  29. package/dist/src/artifacts/relations-builder.js +49 -4
  30. package/dist/src/artifacts/relations.js +26 -10
  31. package/dist/src/artifacts/template-references.js +42 -0
  32. package/dist/src/artifacts/types.js +1 -1
  33. package/dist/src/cli/handlers/bundle-reconciliation.js +7 -3
  34. package/dist/src/cli/handlers/checkpoint-handoff.js +48 -0
  35. package/dist/src/cli/handlers/checkpoint-record.js +20 -0
  36. package/dist/src/cli/handlers/checkpoint.js +176 -0
  37. package/dist/src/cli/handlers/decision.js +1 -1
  38. package/dist/src/cli/handlers/doctor-args.js +3 -1
  39. package/dist/src/cli/handlers/doctor-help.js +2 -1
  40. package/dist/src/cli/handlers/help.js +1 -0
  41. package/dist/src/cli/handlers/index.js +4 -2
  42. package/dist/src/cli/handlers/models-resource-sample.js +7 -3
  43. package/dist/src/cli/handlers/ralph-launcher.js +1 -1
  44. package/dist/src/cli/handlers/refresh-bundles.js +2 -1
  45. package/dist/src/cli/handlers/refresh-managed-deployment.js +196 -0
  46. package/dist/src/cli/handlers/refresh.js +10 -2
  47. package/dist/src/cli/handlers/script-runner.js +2 -1
  48. package/dist/src/cli/handlers/steward-signing.js +44 -0
  49. package/dist/src/cli/handlers/steward.js +5 -0
  50. package/dist/src/cli/handlers/subcommands-discovery.js +8 -1
  51. package/dist/src/cli/handlers/use-provider-results.js +17 -0
  52. package/dist/src/cli/handlers/use.js +19 -18
  53. package/dist/src/cli/router.js +12 -2
  54. package/dist/src/cli/services/deployment-verification.js +11 -7
  55. package/dist/src/cli/user-scope-mirror.js +3 -1
  56. package/dist/src/config/aiwg-config.js +5 -1
  57. package/dist/src/config/cli.js +1 -0
  58. package/dist/src/config/delivery-validation.js +21 -0
  59. package/dist/src/config/host-resource-report.d.mts +1 -1
  60. package/dist/src/config/host-resource-report.mjs +23 -4
  61. package/dist/src/config/host-resource-runtime.d.mts +8 -0
  62. package/dist/src/config/host-resource-runtime.mjs +67 -24
  63. package/dist/src/config/index-graph-overrides.js +4 -0
  64. package/dist/src/config/worker-attribution.d.mts +7 -0
  65. package/dist/src/config/worker-attribution.mjs +44 -0
  66. package/dist/src/config/worker-write.js +4 -10
  67. package/dist/src/decision/ledger.js +15 -15
  68. package/dist/src/decision/offload.js +6 -7
  69. package/dist/src/delivery/git.js +62 -0
  70. package/dist/src/delivery/pr.js +151 -0
  71. package/dist/src/delivery/template-sections.js +56 -0
  72. package/dist/src/delivery/tracker.js +33 -0
  73. package/dist/src/discovery/interview.js +1 -1
  74. package/dist/src/extensions/claude-hooks-installer.js +62 -53
  75. package/dist/src/extensions/loader.js +2 -1
  76. package/dist/src/extensions/managed-hook-script-state.js +48 -0
  77. package/dist/src/extensions/muse-managed-hooks.js +49 -0
  78. package/dist/src/issues/cli.js +15 -3
  79. package/dist/src/issues/external-cli.js +79 -0
  80. package/dist/src/issues/live.js +26 -2
  81. package/dist/src/issues/local.js +5 -1
  82. package/dist/src/issues/tracker-policy.js +27 -0
  83. package/dist/src/mcp/json-document.d.mts +2 -0
  84. package/dist/src/mcp/tools/worker-invoke.mjs +2 -1
  85. package/dist/src/mcp/tools/worker-stdin-runtime.mjs +12 -0
  86. package/dist/src/models/conductor-data-policy.d.mts +3 -2
  87. package/dist/src/models/conductor-data-policy.mjs +94 -5
  88. package/dist/src/models/model-capabilities.v1.json +27 -23
  89. package/dist/src/models/model-catalog.v1.json +3 -3
  90. package/dist/src/models/provider-policy.js +8 -0
  91. package/dist/src/models/worker-health-readiness.js +20 -4
  92. package/dist/src/models/worker-health-snapshot.js +29 -0
  93. package/dist/src/models/worker-installation.d.mts +5 -1
  94. package/dist/src/models/worker-installation.mjs +11 -5
  95. package/dist/src/models/worker-plan.js +3 -3
  96. package/dist/src/models/worker-qualification-policy.js +54 -0
  97. package/dist/src/models/worker-selection-policy.js +2 -1
  98. package/dist/src/providers/deployment-lock.js +77 -0
  99. package/dist/src/providers/deployment-ownership.d.mts +12 -2
  100. package/dist/src/providers/deployment-ownership.mjs +115 -21
  101. package/dist/src/providers/deployment-preservation.d.mts +2 -1
  102. package/dist/src/providers/deployment-preservation.mjs +3 -0
  103. package/dist/src/providers/provider-definitions.js +4 -0
  104. package/dist/src/providers/skill-ownership.d.mts +1 -0
  105. package/dist/src/providers/transformation-receipt-integration.js +4 -2
  106. package/dist/src/providers/transformation-receipt.js +4 -2
  107. package/dist/src/serve/worker-invocation-preparation.js +3 -1
  108. package/dist/src/serve/worker-invocation.js +6 -2
  109. package/dist/src/skills/run.js +5 -0
  110. package/dist/src/smiths/context-pipeline/workspace-audit.js +34 -17
  111. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +12 -6
  112. package/dist/src/smiths/context-pipeline/workspace-doctor.js +44 -4
  113. package/dist/src/smiths/context-pipeline/workspace-document.js +5 -2
  114. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -1
  115. package/dist/src/smiths/hook-bridge/codex-translator.js +150 -92
  116. package/dist/src/smiths/hook-bridge/codex-trust.js +50 -0
  117. package/dist/src/smiths/hook-bridge/factory-hook-config.js +132 -0
  118. package/dist/src/smiths/hook-bridge/factory-translator.js +88 -33
  119. package/dist/src/smiths/hook-bridge/hermes-translator.js +3 -1
  120. package/dist/src/smiths/hook-bridge/index.js +3 -3
  121. package/dist/src/smiths/hook-bridge/loader.js +10 -2
  122. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +5 -0
  123. package/dist/src/storage/workspace-permissions-health.js +64 -0
  124. package/dist/src/storage/workspace-permissions.js +51 -0
  125. package/package.json +9 -2
  126. package/schemas/models/model-config-compatibility.v1.schema.json +4 -0
  127. package/tools/agents/deploy-agents.mjs +15 -0
  128. package/tools/agents/providers/base-contract.mjs +7 -1
  129. package/tools/agents/providers/base-files.mjs +2 -1
  130. package/tools/agents/providers/base-flat-artifacts.mjs +6 -3
  131. package/tools/agents/providers/base-inventory.mjs +35 -13
  132. package/tools/agents/providers/base-models-platforms.mjs +3 -3
  133. package/tools/agents/providers/base-skill-copy.mjs +2 -0
  134. package/tools/agents/providers/base.mjs +1 -1
  135. package/tools/agents/providers/bound-rules-pointer.mjs +21 -0
  136. package/tools/agents/providers/claude-post-deploy.mjs +9 -5
  137. package/tools/agents/providers/codex-post-deploy.mjs +10 -0
  138. package/tools/agents/providers/conductor-data-guard.mjs +35 -11
  139. package/tools/agents/providers/factory-hooks.mjs +43 -0
  140. package/tools/agents/providers/factory.mjs +4 -91
  141. package/tools/agents/providers/muse-hooks.mjs +6 -41
  142. package/tools/agents/providers/muse-prompt-discovery.mjs +18 -0
  143. package/tools/agents/providers/packaged-codex-agents.mjs +48 -0
  144. package/tools/agents/providers/provider-prepare-coordinator.mjs +15 -10
  145. package/tools/agents/providers/rule-delivery-surface.mjs +10 -7
  146. package/tools/agents/providers/rule-deployment-commit.mjs +10 -0
  147. package/tools/agents/providers/rule-presentation.mjs +6 -5
  148. package/tools/agents/providers/rule-projection.mjs +10 -2
  149. package/tools/agents/providers/rule-startup.mjs +8 -1
  150. package/tools/agents/providers/stale-artifact-prune.mjs +9 -8
  151. package/tools/cli/decision-offload-report.mjs +7 -2
  152. package/tools/plugin/issue-template-copies.mjs +24 -0
  153. package/tools/plugin/package-plugins.mjs +11 -3
  154. package/tools/ralph-external/lib/factory-adapter.mjs +7 -8
  155. package/tools/ralph-external/lib/worker-artifacts.mjs +4 -2
  156. package/tools/ralph-external/lib/worker-capture.mjs +157 -0
  157. package/tools/ralph-external/lib/worker-final.mjs +43 -8
  158. package/tools/ralph-external/lib/worker-health.mjs +3 -0
  159. package/tools/ralph-external/lib/worker-invocation-processes.mjs +9 -6
  160. package/tools/ralph-external/lib/worker-launch-cli.mjs +20 -2
  161. package/tools/ralph-external/lib/worker-process-identity.mjs +30 -0
  162. package/tools/ralph-external/lib/worker-prompt.mjs +35 -0
  163. package/tools/ralph-external/lib/worker-retry-evidence.mjs +87 -6
  164. package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +8 -0
  165. package/tools/ralph-external/lib/worker-termination.mjs +56 -6
  166. package/tools/ralph-external/process-monitor.mjs +12 -18
  167. package/tools/ralph-external/session-launcher.mjs +53 -36
  168. package/vscode-extension/schemas/aiwg.config.v1.json +15 -0
@@ -19,6 +19,7 @@ import os from 'os';
19
19
  import { fileURLToPath, pathToFileURL } from 'url';
20
20
  import { importImpl } from '../_resolve-impl.mjs';
21
21
  import { rewritePublishedMarkdown, reportPluginLinks } from './plugin-links.mjs';
22
+ import { syncIssueTemplateCopies } from './issue-template-copies.mjs';
22
23
 
23
24
  const __filename = fileURLToPath(import.meta.url);
24
25
  const __dirname = path.dirname(__filename);
@@ -41,6 +42,7 @@ const PLUGIN_CONFIGS = {
41
42
  skills: 'agentic/code/frameworks/sdlc-complete/skills'
42
43
  },
43
44
  extraCopy: [
45
+ { from: 'agentic/code/frameworks/sdlc-complete/templates/issue-comments', to: 'templates/issue-comments' },
44
46
  ...['threat-assessment.mjs', 'threat-assessment'].map(name => ({ from: `tools/security/${name}`, to: `tools/security/${name}` })),
45
47
  { from: 'agentic/code/frameworks/sdlc-complete/flows/flow-architecture-evolution.playbook.yaml', to: 'flows/flow-architecture-evolution.playbook.yaml' },
46
48
  { from: 'agentic/code/frameworks/sdlc-complete/flows/flow-release.playbook.yaml', to: 'flows/flow-release.playbook.yaml' }
@@ -240,7 +242,11 @@ Writing quality validation and AI pattern detection.
240
242
  { from: 'agentic/code/addons/aiwg-utils/rules/skill-discovery.md', to: 'rules/skill-discovery.md' },
241
243
  { from: 'agentic/code/addons/aiwg-utils/rules/skill-discovery-guidance.md', to: 'rules/skill-discovery-guidance.md' },
242
244
  { from: 'agentic/code/addons/aiwg-utils/rules/cli-secondary.md', to: 'rules/cli-secondary.md' },
243
- { from: 'agentic/code/addons/aiwg-utils/templates/subagent-brief.md', to: 'templates/subagent-brief.md' }
245
+ ...['artifact-output-policy', 'artifact-output-policy-guidance'].map(name =>
246
+ ({ from: `agentic/code/addons/aiwg-utils/rules/${name}.md`, to: `rules/${name}.md` })),
247
+ { from: 'agentic/code/addons/aiwg-utils/templates/subagent-brief.md', to: 'templates/subagent-brief.md' },
248
+ { from: 'agentic/code/addons/aiwg-utils/templates/issues', to: 'templates/issues' },
249
+ { from: 'agentic/code/addons/aiwg-utils/templates/pull-requests', to: 'templates/pull-requests' }
244
250
  ],
245
251
  readme: `# AIWG Utilities
246
252
 
@@ -294,6 +300,7 @@ Core AIWG utilities for context regeneration and workspace management.
294
300
  skills: 'agentic/code/frameworks/sdlc-complete/skills'
295
301
  },
296
302
  extraCopy: [
303
+ { from: 'agentic/code/frameworks/sdlc-complete/templates/issue-comments', to: 'templates/issue-comments' },
297
304
  { from: 'agentic/code/frameworks/sdlc-complete/flows/flow-architecture-evolution.playbook.yaml', to: 'flows/flow-architecture-evolution.playbook.yaml' },
298
305
  { from: 'agentic/code/frameworks/sdlc-complete/flows/flow-release.playbook.yaml', to: 'flows/flow-release.playbook.yaml' }
299
306
  ],
@@ -1192,9 +1199,9 @@ function writeCodexMarketplaceManifest(options) {
1192
1199
  // rewrites and skill pruning. Only default Claude-owned paths are checked:
1193
1200
  // provider-native metadata and separately maintained templates are preserved.
1194
1201
  export function checkPackagedPlugins({ pluginsDir = PLUGINS_DIR,
1195
- marketplacePath = path.join(ROOT_DIR, '.claude-plugin/marketplace.json') } = {}) {
1202
+ marketplacePath = path.join(ROOT_DIR, '.claude-plugin/marketplace.json'), trackerRoot = ROOT_DIR } = {}) {
1196
1203
  const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'aiwg-plugin-check-'));
1197
- const differences = [];
1204
+ const differences = syncIssueTemplateCopies(trackerRoot, { check: true });
1198
1205
  function files(root) {
1199
1206
  if (!fs.existsSync(root)) return [];
1200
1207
  if (!fs.statSync(root).isDirectory()) return [''];
@@ -1338,6 +1345,7 @@ async function main() {
1338
1345
  }
1339
1346
 
1340
1347
  // Package for each (provider, plugin) combination
1348
+ if (options.all) syncIssueTemplateCopies(ROOT_DIR, options);
1341
1349
  for (const provider of providersToRun) {
1342
1350
  for (const [name, config] of pluginsToPackage) {
1343
1351
  // Provider-specific bundles are not part of another provider's catalog.
@@ -35,16 +35,15 @@ const MODEL_MAP = {
35
35
  /**
36
36
  * Version-bound direct-worker surface (roctinam/aiwg#2902, B-OG-37).
37
37
  *
38
- * Qualified against droid-cli 0.238.0 `droid exec --help` (help/version
39
- * syntax only, captured on host 'noodle' 2026-10-10,
40
- * .aiwg/working/s1-scratch/cli-help/droid-0.238.0.txt; never live
41
- * qualification):
38
+ * Help-verified on titan with droid-cli 1.0.0 (2026-11-06 eval).
39
+ * Stdin brief echoed in the first stream-json message; live result pending
40
+ * (402 No active subscription). This is not live qualification:
42
41
  *
43
42
  * droid exec [--auto low] -m M -r E --cwd W --output-format stream-json < briefPath
44
43
  *
45
44
  * `exec` is Droid's non-interactive mode ("Run non-interactively (for
46
45
  * scripts/automation)"); `-m/--model`, `-r/--reasoning-effort`, `--auto`,
47
- * `--cwd` and `-o/--output-format` are all `exec`-level flags on 0.238.0
46
+ * `--cwd` and `-o/--output-format` are all `exec`-level flags on 1.0.0
48
47
  * `exec --help`. There is no file-output flag (`-o` selects the *format*,
49
48
  * not a destination path): the final is read from the captured stdout
50
49
  * stream instead, never a separate file. There is no positional `prompt`
@@ -71,8 +70,8 @@ const MODEL_MAP = {
71
70
  * required and the CLI's per-model default is never inherited.
72
71
  *
73
72
  * `--output-format stream-json` and the terminal `json` object shape are
74
- * doc-sourced, not help-verified (the installed CLI was never run with a
75
- * prompt): https://docs.factory.com/droid-exec/overview documents
73
+ * doc-sourced; stdin ingestion alone does not verify a successful
74
+ * result: https://docs.factory.com/droid-exec/overview documents
76
75
  * `--output-format json` producing exactly one terminal object,
77
76
  * `{"type":"result","subtype":"success","is_error":false,"duration_ms":N,
78
77
  * "num_turns":N,"result":"...","session_id":"..."}`, and
@@ -97,7 +96,7 @@ const MODEL_MAP = {
97
96
  * Ralph-loop registry only; the direct worker profile loads through the
98
97
  * installed loader.
99
98
  */
100
- export const FACTORY_SUPPORTED_VERSIONS = Object.freeze(['0.238.0']);
99
+ export const FACTORY_SUPPORTED_VERSIONS = Object.freeze(['1.0.0']);
101
100
  /** Union of every reasoning-effort label observed across models in
102
101
  * `exec --help`'s "Model details" section (including `none`, the sole
103
102
  * level for "Auto Model" and one of the levels for GPT-6 Sol/Luna and
@@ -3,12 +3,14 @@ import { constants } from 'node:fs';
3
3
  import { open, mkdir, mkdtemp, lstat, readdir, unlink, rmdir, rename } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import { importImpl } from '../../_resolve-impl.mjs';
6
+ import { workerPromptArtifacts } from './worker-prompt.mjs';
6
7
 
7
8
  const { validateWorkerArtifacts } = await importImpl(import.meta.url, 'serve/worker-artifacts.mjs');
8
9
  const directoryFlags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
9
10
  const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
10
11
 
11
- export async function materializeWorkerArtifacts(invocation, runDir) {
12
+ export async function materializeWorkerArtifacts(invocation, runDir, prompt) {
13
+ invocation = workerPromptArtifacts(invocation, prompt);
12
14
  const artifacts = validateWorkerArtifacts(invocation);
13
15
  const targets = new Map(artifacts.map(artifact => [artifact.name, artifact.location === 'workspace-relative'
14
16
  ? path.join(invocation.cwd, artifact.relativePath) : path.join(runDir, `artifact-${artifact.name}`)]));
@@ -172,7 +174,7 @@ export async function materializeWorkerArtifacts(invocation, runDir) {
172
174
  await handle.writeFile(artifact.content); await handle.sync();
173
175
  if (chain) await verifyPath(invocation.cwd, chain, leaf, identity);
174
176
  }
175
- return { argv, cleanup };
177
+ return { argv, cleanup, declarations: artifacts };
176
178
  } catch (error) {
177
179
  try { await cleanup(); } catch (cleanupError) { throw new AggregateError([error, cleanupError], `${error.message}; worker artifact creation and cleanup failed`); }
178
180
  throw error;
@@ -0,0 +1,157 @@
1
+ // Preserve one-shot attempt captures as read-only snapshots bound to the terminal run record.
2
+ import { constants } from 'node:fs';
3
+ import { mkdir, open, readdir, lstat } from 'node:fs/promises';
4
+ import { createHash } from 'node:crypto';
5
+ import { join, dirname, basename } from 'node:path';
6
+ import { withWorkerPath } from './worker-inputs.mjs';
7
+ import { importImpl } from '../../_resolve-impl.mjs';
8
+
9
+ const hash = bytes => `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
10
+ const reservationPath = filename => `${filename}.launch-owner`;
11
+ const directoryPath = runDir => join(dirname(runDir), `.captures-${basename(runDir)}`);
12
+ const fileFlags = constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK;
13
+ const directoryFlags = constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW;
14
+ const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
15
+
16
+ export async function assertWorkerCapturePathsAvailable(paths, inspect, { runDir, writableRoots }) {
17
+ const { realBeneath } = await importImpl(import.meta.url, 'serve/worker-invocation-paths.js');
18
+ for (const root of writableRoots) {
19
+ if (await realBeneath(root, directoryPath(runDir))) throw new Error('Sealed captures must be outside worker-writable roots');
20
+ }
21
+ const filenames = Object.values(paths);
22
+ if (filenames.some(filename => filenames.includes(reservationPath(filename)))) {
23
+ throw new Error('Worker output paths collide with capture reservations');
24
+ }
25
+ for (const filename of filenames) {
26
+ // A removed live capture still belongs to the attempt whose snapshot survives beside its run directory.
27
+ if (await inspect(directoryPath(dirname(filename)), 'directory')) throw new Error('Worker output path belongs to an earlier attempt capture directory');
28
+ if (await inspect(reservationPath(filename), 'output')) throw new Error('Worker output path belongs to an earlier attempt');
29
+ }
30
+ }
31
+
32
+ async function ownedFile(filename, operation) {
33
+ return withWorkerPath(filename, async target => {
34
+ const handle = await open(target, fileFlags);
35
+ try {
36
+ const stat = await handle.stat({ bigint: true });
37
+ if (!stat.isFile() || stat.nlink !== 1n || stat.uid !== BigInt(process.getuid())) throw new Error('Capture must be an owned unaliased regular file');
38
+ const result = await operation(handle, stat);
39
+ const after = await handle.stat({ bigint: true });
40
+ if (stat.size !== after.size || stat.mtimeNs !== after.mtimeNs || stat.ctimeNs !== after.ctimeNs
41
+ || !sameFile(after, await lstat(target, { bigint: true }))) {
42
+ throw new Error('Capture changed while sealing or verifying');
43
+ }
44
+ return result;
45
+ } finally { await handle.close(); }
46
+ });
47
+ }
48
+
49
+ async function digestFile(filename, expectedMode) {
50
+ return ownedFile(filename, async (handle, stat) => {
51
+ if (expectedMode !== undefined && Number(stat.mode & 0o777n) !== expectedMode) throw new Error('Sealed capture is not read-only');
52
+ const digest = createHash('sha256');
53
+ for await (const chunk of handle.createReadStream({ autoClose: false, start: 0 })) digest.update(chunk);
54
+ return { digest: `sha256:${digest.digest('hex')}`, byteLength: Number(stat.size) };
55
+ });
56
+ }
57
+
58
+ export class WorkerCaptureOwner {
59
+ constructor({ runDir, paths, captures, inspect, invocationId }) {
60
+ Object.assign(this, { runDir, paths, captures, inspect, invocationId });
61
+ this.directory = directoryPath(runDir);
62
+ this.sources = { ...Object.fromEntries(Object.entries(paths).map(([key, value]) => [`output-${key}`, value])),
63
+ ...Object.fromEntries(Object.entries(captures).map(([key, value]) => [`capture-${key}`, value])) };
64
+ }
65
+
66
+ writer(writeRecord, publishSeal = writeRecord) {
67
+ this.publishSeal = publishSeal;
68
+ return async (runDir, name, value, inspect) => {
69
+ if (name === 'invocation.json') {
70
+ // Exclusive even if a conductor has deleted the old mutable run directory.
71
+ await withWorkerPath(this.directory, target => mkdir(target, { mode: 0o700 }));
72
+ this.started = true;
73
+ value.captureDirectory = this.directory;
74
+ this.invocationRecord = value;
75
+ }
76
+ if (name === 'exit.json') this.result = value;
77
+ return writeRecord(runDir, name, value, inspect);
78
+ };
79
+ }
80
+
81
+ async reserveOutput(filename) {
82
+ if (Object.values(this.paths).includes(filename)) {
83
+ const marker = reservationPath(filename);
84
+ await this.inspect(marker, 'output');
85
+ const handle = await withWorkerPath(marker, target => open(target,
86
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600));
87
+ try { await handle.writeFile(JSON.stringify({ invocationId: this.invocationId, runDir: this.runDir })); await handle.sync(); }
88
+ finally { await handle.close(); }
89
+ }
90
+ }
91
+
92
+ async finish() {
93
+ if (!this.started) return;
94
+ const files = [];
95
+ for (const [name, source] of Object.entries(this.sources)) {
96
+ const path = join(this.directory, name);
97
+ if (!await this.inspect(source, 'file')) { files.push({ source, path, missing: true }); continue; }
98
+ const recorded = await ownedFile(source, async (input, stat) => {
99
+ const output = await withWorkerPath(path, target => open(target,
100
+ constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600));
101
+ const digest = createHash('sha256');
102
+ try {
103
+ for await (const chunk of input.createReadStream({ autoClose: false, start: 0 })) {
104
+ digest.update(chunk); await output.writeFile(chunk);
105
+ }
106
+ await output.chmod(0o400); await output.sync();
107
+ return { digest: `sha256:${digest.digest('hex')}`, byteLength: Number(stat.size) };
108
+ } finally { await output.close(); }
109
+ });
110
+ files.push({ source, path, ...recorded });
111
+ }
112
+ await withWorkerPath(this.directory, async target => {
113
+ const directory = await open(target, directoryFlags);
114
+ try { await directory.chmod(0o500); await directory.sync(); } finally { await directory.close(); }
115
+ });
116
+ // A capture-setup exception can precede exit.json; retain its seal in the invocation record.
117
+ const record = this.result ?? this.invocationRecord;
118
+ record.captureSeal = { directory: this.directory, sealedAt: new Date().toISOString(), files,
119
+ digest: hash(JSON.stringify(files)) };
120
+ await this.publishSeal(this.runDir, this.result ? 'exit.json' : 'invocation.json', record, this.inspect);
121
+ }
122
+ }
123
+
124
+ export async function verifyWorkerCaptureSeal(runDir, invocation, exit, inspect) {
125
+ // Pre-sealing launcher records remain readable; every new invocation declares its capture directory.
126
+ if (invocation.captureDirectory === undefined && exit.captureSeal === undefined) return;
127
+ const seal = exit.captureSeal;
128
+ if (invocation.captureDirectory !== directoryPath(runDir) || seal?.directory !== invocation.captureDirectory
129
+ || !Array.isArray(seal.files) || seal.digest !== hash(JSON.stringify(seal.files))) throw new Error('Capture seal is missing or invalid');
130
+ const expected = { ...Object.fromEntries(Object.entries(invocation.paths).map(([key, value]) => [`output-${key}`, value])),
131
+ ...Object.fromEntries(Object.entries(invocation.captures).map(([key, value]) => [`capture-${key}`, value])) };
132
+ if (seal.files.length !== Object.keys(expected).length) throw new Error('Capture seal omits attempt paths');
133
+ await withWorkerPath(seal.directory, async target => {
134
+ const directory = await open(target, directoryFlags);
135
+ try {
136
+ const stat = await directory.stat();
137
+ if (stat.uid !== process.getuid() || (stat.mode & 0o777) !== 0o500) throw new Error('Capture directory is not sealed read-only');
138
+ const names = (await readdir(target)).sort();
139
+ const present = seal.files.filter(file => !file.missing).map(file => Object.keys(expected).find(name => file.path === join(seal.directory, name))).sort();
140
+ if (JSON.stringify(names) !== JSON.stringify(present)) throw new Error('Sealed capture directory entries changed');
141
+ } finally { await directory.close(); }
142
+ });
143
+ const seen = new Set();
144
+ for (const file of seal.files) {
145
+ const name = Object.keys(expected).find(key => file.path === join(seal.directory, key));
146
+ if (!name || seen.has(name) || file.source !== expected[name]) throw new Error('Capture seal path binding mismatch');
147
+ seen.add(name);
148
+ if (file.missing) {
149
+ if (await inspect(file.source, 'file')) throw new Error('Previously missing capture has changed');
150
+ continue;
151
+ }
152
+ for (const [filename, mode] of [[file.path, 0o400], [file.source, undefined]]) {
153
+ const actual = await digestFile(filename, mode);
154
+ if (actual.digest !== file.digest || actual.byteLength !== file.byteLength) throw new Error(`Capture digest mismatch: ${filename}`);
155
+ }
156
+ }
157
+ }
@@ -1,8 +1,8 @@
1
1
  // Collect workerClaims candidates only after schema and on-disk artifact validation.
2
2
  import { createHash } from 'node:crypto';
3
3
  import { constants } from 'node:fs';
4
- import { lstat, open } from 'node:fs/promises';
5
- import { isAbsolute, relative, resolve } from 'node:path';
4
+ import { lstat, open, opendir } from 'node:fs/promises';
5
+ import { basename, isAbsolute, join, relative, resolve } from 'node:path';
6
6
  import { importImpl } from '../../_resolve-impl.mjs';
7
7
  import { boundedPrivateRead, withWorkerPath } from './worker-inputs.mjs';
8
8
  import { parseStrictWorkerJson } from './strict-worker-json.mjs';
@@ -17,6 +17,29 @@ function schemaDiagnostic(error) {
17
17
  return match ? `${match[1] === '/' ? '' : match[1]}/${escapePointer(match[3])} ${match[2]}` : error;
18
18
  }
19
19
 
20
+ // Names only: bounded, nonrecursive discovery never reads or accepts worker candidates.
21
+ async function rootCandidates(workdir, finalPath) {
22
+ const candidates = [];
23
+ let truncated = false, scanError = null;
24
+ try {
25
+ await withWorkerPath(workdir, async target => {
26
+ const root = await open(target, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
27
+ try {
28
+ const entries = await opendir(`/proc/self/fd/${root.fd}`);
29
+ let scanned = 0;
30
+ for await (const entry of entries) {
31
+ if (++scanned > 256 || candidates.length === 32) { truncated = true; break; }
32
+ const path = join(workdir, entry.name);
33
+ if (entry.isFile() && path !== finalPath && /\.(json|jsonl|txt|md|ya?ml|csv)$/i.test(entry.name)) {
34
+ candidates.push({ path, location: 'worker-tree-root', candidate: true, verified: false });
35
+ }
36
+ }
37
+ } finally { await root.close(); }
38
+ });
39
+ } catch (error) { scanError = error.message; }
40
+ return { candidates: candidates.sort((a, b) => a.path.localeCompare(b.path)), truncated, scanError };
41
+ }
42
+
20
43
  async function artifactErrors(claims, workdir) {
21
44
  const errors = [];
22
45
  for (const [index, artifact] of claims.artifacts.entries()) {
@@ -56,7 +79,7 @@ export async function collectWorkerFinal({ path, workdir, driver, output, invoca
56
79
  await importImpl(import.meta.url, 'mission-protocol/index.js');
57
80
  const scan = bytes => parseStrictWorkerJson(
58
81
  new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes), WORKER_MAX_NESTING_DEPTH);
59
- let finalBytes, extracted = false, parsedClaims, parseError;
82
+ let finalBytes, extracted = false, parsedClaims, parseError, failureKind = 'invalid-file';
60
83
  const evidence = () => ({ invocationId, path, digest: finalBytes ? digest(finalBytes) : null,
61
84
  source: extracted ? 'adapter-extraction' : 'worker-output', candidate: true, verified: false });
62
85
  try {
@@ -65,6 +88,7 @@ export async function collectWorkerFinal({ path, workdir, driver, output, invoca
65
88
  await inspect(path, 'file');
66
89
  let claims;
67
90
  if (stat.size === 0 && driver.extractFinal) {
91
+ failureKind = output.length ? 'wrong-shape' : 'missing-file';
68
92
  claims = driver.extractFinal(output.toString('utf8'));
69
93
  if (claims === null || claims === undefined || claims.success === false) throw new Error('Missing or unsuccessful final extraction');
70
94
  const bytes = JSON.stringify({ invocationId, source: 'adapter-extraction', candidate: true, verified: false, result: claims });
@@ -72,7 +96,8 @@ export async function collectWorkerFinal({ path, workdir, driver, output, invoca
72
96
  await handle.writeFile(bytes); extracted = true;
73
97
  }
74
98
  finalBytes = await boundedPrivateRead(path, WORKER_MAX_JSON_BYTES, inspect, true);
75
- if (!finalBytes.length) throw new Error('Missing final output');
99
+ if (!finalBytes.length) { failureKind = 'missing-file'; throw new Error('Missing final output'); }
100
+ failureKind = 'wrong-shape';
76
101
  if (extracted) {
77
102
  if (driver.parseWorkerFinal) {
78
103
  try {
@@ -110,7 +135,10 @@ export async function collectWorkerFinal({ path, workdir, driver, output, invoca
110
135
  if (!parseError) {
111
136
  const validation = validateWorkerPayload('workerClaims', claims);
112
137
  const errors = validation.errors.map(schemaDiagnostic);
113
- if (validation.valid) errors.push(...await artifactErrors(claims, workdir));
138
+ if (validation.valid) {
139
+ failureKind = 'invalid-artifact';
140
+ errors.push(...await artifactErrors(claims, workdir));
141
+ }
114
142
  if (errors.length) {
115
143
  result.finalOutputErrors = errors;
116
144
  throw new Error('Invalid workerClaims');
@@ -118,13 +146,20 @@ export async function collectWorkerFinal({ path, workdir, driver, output, invoca
118
146
  }
119
147
  } catch (error) {
120
148
  result.errorCode ??= 'FINAL_OUTPUT_INVALID';
121
- // Preserve the existing missing/empty-final failure: there is no
122
- // candidate document (and therefore no schema pointer) to record.
123
- if (!finalBytes?.length) throw error;
149
+ const found = await rootCandidates(workdir, path);
150
+ if (error.code === 'ENOENT') failureKind = 'missing-file';
151
+ if (failureKind === 'missing-file' && found.candidates.some(candidate => basename(candidate.path) === basename(path))) {
152
+ failureKind = 'wrong-location';
153
+ }
154
+ result.finalOutputFailure = { kind: failureKind, expectedPath: path,
155
+ message: `${failureKind}: final output at ${JSON.stringify(path)}: ${error.message}`,
156
+ ...found };
124
157
  // Adapter decoding uses assertValidWorkerPayload's existing rendered
125
158
  // diagnostics; retain its pointers when validation fails inside it.
126
159
  const schemaErrors = /^Invalid workerClaims: (.*)\.$/.exec(error.message)?.[1];
127
160
  result.finalOutputErrors ??= schemaErrors ? schemaErrors.split('; ').map(schemaDiagnostic) : [`/ ${error.message}`];
161
+ // No candidate document exists for a missing/empty final; retain diagnostics in exit.json.
162
+ if (!finalBytes?.length) throw error;
128
163
  await publish('final-evidence.json', { ...evidence(), terminalSuccess: false,
129
164
  errorCode: 'FINAL_OUTPUT_INVALID', errors: result.finalOutputErrors });
130
165
  throw error;
@@ -126,6 +126,7 @@ export function createWorkerHealthObserver(options = {}) {
126
126
  let sequence = 0, generation = options.observerGeneration ?? 0, steps = null, total = 0, lastCheck = started, maxGap = 0;
127
127
  let observed = null, activity = null, progress = null, heartbeat = null, handshakeAt = null, stalledAt = null;
128
128
  let state = 'launching', handshake = 'unobserved', confidence = 'unobserved', reasonCode = 'AWAITING_HANDSHAKE';
129
+ let terminationMissing = null;
129
130
  let termination = 'running', transitionCount = 0, live = null, disconnected = false, finalized = false;
130
131
  let terminal = null, fatalFailure = false, cpuTimeMs = null, contentDigest = options.contentDigest ?? null;
131
132
  const unavailable = new Set(profile.handshake === 'semantic' ? [] : ['semantic-start']);
@@ -350,6 +351,7 @@ export function createWorkerHealthObserver(options = {}) {
350
351
  if (finalized) return snapshot();
351
352
  for (const [id, cursor] of buffers) if (cursor.bytes.length || cursor.discarding) gap('MALFORMED_FRAME', { id });
352
353
  finalized = true; observed = now(); termination = result.termination ?? 'uncertain';
354
+ terminationMissing = result.terminationMissing ?? null;
353
355
  if (termination !== 'confirmed' || disconnected) {
354
356
  termination = 'uncertain';
355
357
  if (result.signal || result.exitCode != null && result.exitCode !== 0) transition(handshakeAt === null ? 'failed-to-start' : 'crashed', 'CRASH');
@@ -375,6 +377,7 @@ export function createWorkerHealthObserver(options = {}) {
375
377
  return Math.max(1, Math.min(...pending) - time);
376
378
  },
377
379
  evidence() { return { invocationId: binding.invocationId, sequence, observerGeneration: generation,
380
+ ...(terminationMissing ? { terminationMissing } : {}),
378
381
  lastWorkerHeartbeatAt: utc(heartbeat), cpuTimeMs, steps: windows.stepEnforcement === 'unavailable' ? null : steps,
379
382
  gaps: gaps.map(item => ({ ...item })), events: events.map(item => ({ ...item })) }; },
380
383
  };
@@ -5,6 +5,7 @@ import { classifyUnreadableWorkerProcess, readProcCgroup } from './worker-invoca
5
5
  import { importImpl } from '../../_resolve-impl.mjs';
6
6
  const { WORKER_INVOCATION_MARKER } = await importImpl(import.meta.url, 'config/worker-invocation-marker.mjs');
7
7
  export { WORKER_INVOCATION_MARKER };
8
+ const { workerAttributionEnvironment } = await importImpl(import.meta.url, 'config/worker-attribution.mjs');
8
9
 
9
10
  function startedBeforeWorker(fs, path, startTicks) {
10
11
  if (typeof startTicks !== 'string' || !/^\d+$/.test(startTicks)) return false;
@@ -23,14 +24,16 @@ function startedBeforeWorker(fs, path, startTicks) {
23
24
  finally { if (fd !== undefined) fs.closeSync(fd); }
24
25
  }
25
26
 
26
- export function buildWorkerInvocationEnvironment(envNames, invocationId, inherited = process.env) {
27
+ export function buildWorkerInvocationEnvironment(envNames, invocationId, inherited = process.env, attribution) {
27
28
  if (typeof invocationId !== 'string' || !invocationId || invocationId.includes('\0')) {
28
29
  throw new Error('Worker environment requires a non-empty NUL-free invocation ID');
29
30
  }
30
- const names = [...new Set([...envNames, WORKER_INVOCATION_MARKER])];
31
+ const markers = attribution ? workerAttributionEnvironment(invocationId, attribution.cwd, attribution.selected.group)
32
+ : { [WORKER_INVOCATION_MARKER]: invocationId };
33
+ const names = [...new Set([...envNames, ...Object.keys(markers)])];
31
34
  const env = Object.fromEntries(envNames.filter(name => inherited[name] !== undefined)
32
35
  .map(name => [name, inherited[name]]));
33
- return { env: { ...env, [WORKER_INVOCATION_MARKER]: invocationId }, envNames: names };
36
+ return { env: { ...env, ...markers }, envNames: names };
34
37
  }
35
38
 
36
39
  export function scanWorkerInvocationProcesses({ invocationId, startTicks, uid = process.getuid?.(),
@@ -98,12 +101,12 @@ export function scanWorkerInvocationProcesses({ invocationId, startTicks, uid =
98
101
  // failures and unreadable/missing start times still cannot prove absence.
99
102
  if (gone(error)) continue;
100
103
  if (!sameUid) {
101
- uncertain = unknown('unreadable same-uid process environment or ownership');
104
+ uncertain = { ...unknown('unreadable same-uid process environment or ownership'), retryable: true };
102
105
  continue;
103
106
  }
104
107
  if (!workerKnown) {
105
108
  if (!startedBeforeWorker(fs, path, startTicks)) {
106
- uncertain = unknown('unreadable same-uid process environment or ownership');
109
+ uncertain = { ...unknown('unreadable same-uid process environment or ownership'), retryable: true };
107
110
  }
108
111
  continue;
109
112
  }
@@ -117,7 +120,7 @@ export function scanWorkerInvocationProcesses({ invocationId, startTicks, uid =
117
120
  workerCgroup: resolvedWorkerCgroup, selfCgroup: resolvedSelfCgroup,
118
121
  now, deadline, ...(maxAncestryDepth === undefined ? {} : { maxDepth: maxAncestryDepth }) });
119
122
  if (verdict === 'possible-descendant') {
120
- uncertain = unknown('unreadable same-uid process links to the worker (ancestry, session, group or cgroup)');
123
+ uncertain = { ...unknown('unreadable same-uid process links to the worker (ancestry, session, group or cgroup)'), retryable: true };
121
124
  }
122
125
  } finally { if (fd !== undefined) fs.closeSync(fd); }
123
126
  }
@@ -2,6 +2,15 @@
2
2
  import { join, isAbsolute } from 'node:path';
3
3
  import { boundedPrivateRead } from './worker-inputs.mjs';
4
4
 
5
+ export function workerFinalFailureMessage(result) {
6
+ const failure = result.finalOutputFailure;
7
+ if (!failure) return null;
8
+ const candidates = failure.candidates.map(candidate => JSON.stringify(candidate.path)).join(', ') || '(none)';
9
+ return `FINAL_OUTPUT_INVALID: ${failure.message}. Unverified candidate artifacts: ${candidates}`
10
+ + (failure.truncated ? ' (scan truncated)' : '')
11
+ + (failure.scanError ? ` (scan failed: ${failure.scanError})` : '');
12
+ }
13
+
5
14
  export function parseWorkerLaunchArgs(args) {
6
15
  const result = {};
7
16
  const seen = new Set();
@@ -13,11 +22,12 @@ export function parseWorkerLaunchArgs(args) {
13
22
  seen.add(flag);
14
23
  if (flag === '--launch-worker') continue;
15
24
  if (flag === '--check-descendants') { result.checkDescendants = true; continue; }
25
+ if (flag === '--retry-correction') continue;
16
26
  if (flag === '--allow-degraded-worker') { result.allowDegraded = true; continue; }
17
27
  // A run directory declares a retry; its launcher ID is derived before validation.
18
28
  const key = { '--invocation': 'invocationPath', '--run-dir': 'runDir',
19
29
  '--retry-of': '__retryOfInvocationId', '--retry-of-run-dir': '__retryOfRunDir' }[flag];
20
- if (!key) throw new Error(`Unsupported worker launch option: ${flag}`);
30
+ if (!key) throw new Error(`Unsupported worker launch option: ${flag}. Worker launch already emits JSON; for JSON status use aiwg ralph-external --status --workers --run-dir DIR --json separately. Run the resolved command unchanged.`);
21
31
  const value = args[++i];
22
32
  if (!value || value.startsWith('--')) throw new Error(`${flag} requires a value`);
23
33
  if (key === '__retryOfInvocationId') retryOfInvocationId = value;
@@ -25,13 +35,21 @@ export function parseWorkerLaunchArgs(args) {
25
35
  else result[key] = value;
26
36
  }
27
37
  if (!seen.has('--launch-worker') || !result.invocationPath || !result.runDir) {
28
- throw new Error('Usage: ralph-external --launch-worker --invocation FILE --run-dir DIR [--allow-degraded-worker] [--check-descendants] [--retry-of-run-dir DIR [--retry-of ID]]');
38
+ throw new Error('Usage: ralph-external --launch-worker --invocation FILE --run-dir DIR [--allow-degraded-worker] [--check-descendants] [--retry-of-run-dir DIR [--retry-of ID] [--retry-correction]]');
39
+ }
40
+ // #3857: reject relative paths here, naming the flag, before any launch work.
41
+ for (const [flag, value] of [['--invocation', result.invocationPath], ['--run-dir', result.runDir], ['--retry-of-run-dir', retryOfRunDir]]) {
42
+ if (value !== undefined && !isAbsolute(value)) {
43
+ throw new Error(`${flag} must be an absolute path; relative paths are not resolved against cwd.`);
44
+ }
29
45
  }
30
46
  if (retryOfInvocationId !== undefined && retryOfRunDir === undefined) {
31
47
  throw new Error('--retry-of and --retry-of-run-dir must be supplied together when an explicit ID is used');
32
48
  }
33
49
  if (result.checkDescendants && retryOfRunDir === undefined) throw new Error('--check-descendants requires --retry-of-run-dir');
50
+ if (seen.has('--retry-correction') && retryOfRunDir === undefined) throw new Error('--retry-correction requires --retry-of-run-dir');
34
51
  if (retryOfRunDir !== undefined) result.retryOf = { runDir: retryOfRunDir, ...(retryOfInvocationId === undefined ? {} : { invocationId: retryOfInvocationId }) };
52
+ if (seen.has('--retry-correction')) result.retryOf.correction = true;
35
53
  return result;
36
54
  }
37
55
 
@@ -0,0 +1,30 @@
1
+ // Retain kernel birth identity when an exited child has already lost its executable link.
2
+ import { readFileSync, readlinkSync } from 'node:fs';
3
+ import { hostname } from 'node:os';
4
+
5
+ export function sampleWorkerProcIdentity(pid, { procRoot = '/proc', platform = process.platform,
6
+ host = hostname(), fs = { readFileSync, readlinkSync } } = {}) {
7
+ if (platform !== 'linux' || !Number.isSafeInteger(pid) || pid <= 0) return null;
8
+ try {
9
+ const parse = text => text.slice(text.lastIndexOf(')') + 2).trim().split(/\s+/);
10
+ const fields = parse(fs.readFileSync(`${procRoot}/${pid}/stat`, 'utf8'));
11
+ const uid = Number(/^Uid:\s+(\d+)/m.exec(fs.readFileSync(`${procRoot}/${pid}/status`, 'utf8'))?.[1]);
12
+ const bootId = fs.readFileSync(`${procRoot}/sys/kernel/random/boot_id`, 'utf8').trim();
13
+ if (!Number.isSafeInteger(uid) || !bootId || !/^\d+$/.test(fields[19] ?? '')) return null;
14
+ let executable;
15
+ try { executable = fs.readlinkSync(`${procRoot}/${pid}/exe`); }
16
+ catch (error) {
17
+ if (!['ENOENT', 'ESRCH'].includes(error.code)) return null;
18
+ // exit_mm removes /exe before wait() reaps the child. Its readable
19
+ // stat/status still prove birth, ownership and group, but grant no
20
+ // executable claim. Re-read stat to reject disappearance/PID reuse
21
+ // and any live process (including a transient exec failure).
22
+ const exited = parse(fs.readFileSync(`${procRoot}/${pid}/stat`, 'utf8'));
23
+ if (exited[0] !== 'Z' || [1, 2, 3, 19].some(index => exited[index] !== fields[index])) return null;
24
+ executable = null;
25
+ }
26
+ return { pid, pgid: Number(fields[2]), uid, parentPid: Number(fields[1]), sessionId: Number(fields[3]),
27
+ host, bootId, startTicks: fields[19], executable, state: executable === null ? 'Z' : fields[0],
28
+ cpuTicks: Number(fields[11]) + Number(fields[12]) + Number(fields[13]) + Number(fields[14]) };
29
+ } catch { return null; }
30
+ }
@@ -0,0 +1,35 @@
1
+ // Add the final-output contract to launch-time briefs without changing the bound source brief.
2
+ export function workerPromptBrief(brief, finalPath) {
3
+ const text = Buffer.isBuffer(brief) ? new TextDecoder('utf-8', { fatal: true }).decode(brief) : brief;
4
+ return Buffer.from(`[Worker final-output contract]
5
+ Write one strict workerClaims JSON object to this exact absolute path: ${JSON.stringify(finalPath)}
6
+ The task's answer alone (for example {"facts":[],"warning":""}) is not the final-output wrapper.
7
+ Required minimal wrapper example (replace the summary and report your actual status):
8
+ {"version":1,"status":"completed","summary":"Task result","claims":[],"artifacts":[],"checks":[],"limitations":[]}
9
+ Allowed status: completed, partial, blocked, failed. Keep all seven fields; add no other top-level fields.
10
+ Put the answer in summary or a separate task artifact. For each listed artifact use
11
+ {"path":"answer.json","digest":"sha256:<64 lowercase hex characters>","change":"created"}
12
+ with a real digest and a file beneath the worker tree. Empty collections are allowed.
13
+ Keep this JSON separate from stdout, stderr and last-message captures. A file at the worker-tree root
14
+ does not satisfy a different declared final-output path. Worker claims remain unverified.
15
+
16
+ [Task]
17
+ ${text}`);
18
+ }
19
+
20
+ // File-based profiles receive a private derived brief through the existing artifact lifecycle.
21
+ export function workerPromptArtifacts(invocation, { brief, invocationId } = {}) {
22
+ if (brief === undefined || invocation.stdin !== 'closed') return invocation;
23
+ const text = Buffer.isBuffer(brief) ? brief.toString('utf8') : brief;
24
+ const prompt = workerPromptBrief(brief, invocation.finalPath).toString('utf8');
25
+ if (invocation.argv.includes(invocation.briefPath)) {
26
+ const name = 'launcher-worker-brief', prefix = '.handoff/worker-brief-';
27
+ return { ...invocation, invocationId,
28
+ argv: invocation.argv.map(token => token === invocation.briefPath ? `\${artifact:${name}}` : token),
29
+ artifacts: [...(invocation.artifacts ?? []), { name, content: prompt, location: 'workspace-relative',
30
+ prefix, relativePath: `${prefix}${invocationId}/brief.md` }] };
31
+ }
32
+ // Skill-file profiles embed the brief after frontmatter. Preserve their framing.
33
+ return { ...invocation, artifacts: invocation.artifacts?.map(artifact => ({ ...artifact,
34
+ content: text && artifact.content.includes(text) ? artifact.content.replace(text, () => prompt) : artifact.content })) };
35
+ }