@aiwg/cli 2026.11.1 → 2026.11.3

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 (120) 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/capability-matrix.yaml +2 -2
  4. package/agentic/code/providers/model-capabilities.v1.json +44 -39
  5. package/agentic/code/providers/model-catalog.v1.json +3 -3
  6. package/dist/src/artifacts/cli.js +10 -11
  7. package/dist/src/artifacts/discover-cli-help.js +25 -0
  8. package/dist/src/artifacts/discover-session-facets.js +2 -1
  9. package/dist/src/artifacts/fortemi-core-prebuilt-freshness.js +28 -0
  10. package/dist/src/artifacts/fortemi-core-sync.js +3 -0
  11. package/dist/src/artifacts/framework-capabilities.js +4 -0
  12. package/dist/src/artifacts/framework-source-digest.js +1 -1
  13. package/dist/src/artifacts/index-builder.js +10 -10
  14. package/dist/src/artifacts/index-dependencies.js +72 -0
  15. package/dist/src/artifacts/query-engine-discover-output.js +13 -5
  16. package/dist/src/artifacts/query-engine-discover.js +49 -21
  17. package/dist/src/artifacts/query-engine-entries.js +56 -2
  18. package/dist/src/artifacts/query-engine-options.js +14 -1
  19. package/dist/src/artifacts/query-engine-scoring.js +8 -4
  20. package/dist/src/artifacts/query-engine-show-card.js +2 -0
  21. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  22. package/dist/src/artifacts/query-engine-show.js +3 -1
  23. package/dist/src/artifacts/query-engine-templates.js +33 -0
  24. package/dist/src/artifacts/query-engine-verbose.js +25 -0
  25. package/dist/src/artifacts/relations-builder.js +49 -4
  26. package/dist/src/artifacts/relations.js +9 -0
  27. package/dist/src/artifacts/template-references.js +42 -0
  28. package/dist/src/artifacts/types.js +1 -1
  29. package/dist/src/cli/handlers/bundle-reconciliation.js +7 -3
  30. package/dist/src/cli/handlers/checkpoint-handoff.js +48 -0
  31. package/dist/src/cli/handlers/checkpoint-record.js +20 -0
  32. package/dist/src/cli/handlers/checkpoint.js +50 -17
  33. package/dist/src/cli/handlers/dataset.js +17 -0
  34. package/dist/src/cli/handlers/decision.js +1 -1
  35. package/dist/src/cli/handlers/doctor-args.js +3 -1
  36. package/dist/src/cli/handlers/doctor-help.js +2 -1
  37. package/dist/src/cli/handlers/help.js +1 -1
  38. package/dist/src/cli/handlers/refresh-bundles.js +2 -1
  39. package/dist/src/cli/handlers/refresh-managed-deployment.js +196 -0
  40. package/dist/src/cli/handlers/refresh.js +10 -2
  41. package/dist/src/cli/handlers/subcommands-discovery.js +8 -1
  42. package/dist/src/cli/handlers/use.js +26 -5
  43. package/dist/src/cli/services/deployment-verification.js +11 -7
  44. package/dist/src/config/decision-config.js +2 -1
  45. package/dist/src/config/jev-credential-reference.js +56 -0
  46. package/dist/src/config/user-config.js +13 -19
  47. package/dist/src/config/worker-write.js +4 -10
  48. package/dist/src/decision/ask.js +3 -2
  49. package/dist/src/decision/jev-credentials.js +22 -0
  50. package/dist/src/decision/ledger.js +15 -15
  51. package/dist/src/decision/offload.js +7 -8
  52. package/dist/src/decision/openbao-kv-resolver.mjs +96 -0
  53. package/dist/src/decision/openbao-runtime.js +101 -0
  54. package/dist/src/delivery/pr.js +2 -0
  55. package/dist/src/delivery/template-sections.js +56 -0
  56. package/dist/src/extensions/claude-hooks-installer.js +61 -53
  57. package/dist/src/extensions/managed-hook-script-state.js +48 -0
  58. package/dist/src/extensions/muse-managed-hooks.js +49 -0
  59. package/dist/src/issues/cli.js +3 -0
  60. package/dist/src/issues/external-cli.js +4 -1
  61. package/dist/src/issues/live.js +9 -2
  62. package/dist/src/issues/local.js +5 -1
  63. package/dist/src/issues/tracker-policy.js +11 -1
  64. package/dist/src/mcp/json-document.d.mts +2 -0
  65. package/dist/src/models/model-capabilities.v1.json +44 -39
  66. package/dist/src/models/model-catalog.v1.json +3 -3
  67. package/dist/src/models/provider-policy.js +8 -0
  68. package/dist/src/models/worker-health-readiness.js +20 -4
  69. package/dist/src/models/worker-health-snapshot.js +29 -0
  70. package/dist/src/models/worker-installation.d.mts +5 -1
  71. package/dist/src/models/worker-installation.mjs +11 -5
  72. package/dist/src/models/worker-qualification-policy.js +54 -0
  73. package/dist/src/providers/capability-matrix.yaml +2 -2
  74. package/dist/src/providers/skill-ownership.d.mts +1 -0
  75. package/dist/src/providers/transformation-receipt-integration.js +4 -2
  76. package/dist/src/providers/transformation-receipt.js +4 -2
  77. package/dist/src/serve/worker-invocation.js +4 -2
  78. package/dist/src/smiths/context-pipeline/workspace-audit.js +34 -17
  79. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +12 -6
  80. package/dist/src/smiths/context-pipeline/workspace-doctor.js +48 -4
  81. package/dist/src/smiths/context-pipeline/workspace-document.js +5 -2
  82. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -1
  83. package/dist/src/smiths/hook-bridge/codex-translator.js +150 -94
  84. package/dist/src/smiths/hook-bridge/codex-trust.js +50 -0
  85. package/dist/src/smiths/hook-bridge/factory-hook-config.js +132 -0
  86. package/dist/src/smiths/hook-bridge/factory-translator.js +88 -33
  87. package/dist/src/smiths/hook-bridge/factory-trust.js +56 -0
  88. package/dist/src/smiths/hook-bridge/index.js +3 -3
  89. package/dist/src/smiths/hook-bridge/loader.js +10 -2
  90. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +0 -1
  91. package/dist/src/storage/workspace-permissions-health.js +64 -0
  92. package/dist/src/storage/workspace-permissions.js +51 -0
  93. package/package.json +6 -1
  94. package/tools/agents/providers/base-files.mjs +2 -1
  95. package/tools/agents/providers/base-flat-artifacts.mjs +6 -3
  96. package/tools/agents/providers/base-models-platforms.mjs +3 -3
  97. package/tools/agents/providers/base-skill-copy.mjs +2 -0
  98. package/tools/agents/providers/bound-rules-pointer.mjs +21 -0
  99. package/tools/agents/providers/claude-post-deploy.mjs +9 -5
  100. package/tools/agents/providers/codex-post-deploy.mjs +10 -0
  101. package/tools/agents/providers/factory-hooks.mjs +43 -0
  102. package/tools/agents/providers/factory.mjs +4 -91
  103. package/tools/agents/providers/muse-hooks.mjs +4 -43
  104. package/tools/agents/providers/muse-prompt-discovery.mjs +3 -7
  105. package/tools/agents/providers/packaged-codex-agents.mjs +48 -0
  106. package/tools/agents/providers/rule-delivery-surface.mjs +4 -4
  107. package/tools/agents/providers/rule-presentation.mjs +6 -5
  108. package/tools/agents/providers/rule-projection.mjs +10 -2
  109. package/tools/agents/providers/rule-startup.mjs +8 -1
  110. package/tools/cli/decision-offload-report.mjs +9 -2
  111. package/tools/plugin/issue-template-copies.mjs +24 -0
  112. package/tools/plugin/package-plugins.mjs +17 -4
  113. package/tools/ralph-external/lib/claude-adapter.mjs +2 -2
  114. package/tools/ralph-external/lib/factory-adapter.mjs +7 -8
  115. package/tools/ralph-external/lib/worker-artifacts.mjs +4 -2
  116. package/tools/ralph-external/lib/worker-final.mjs +43 -8
  117. package/tools/ralph-external/lib/worker-launch-cli.mjs +10 -1
  118. package/tools/ralph-external/lib/worker-prompt.mjs +35 -0
  119. package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +8 -0
  120. package/tools/ralph-external/session-launcher.mjs +10 -7
@@ -0,0 +1,48 @@
1
+ // Render packaged Codex agents with the same final bindings and marker as deploy.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { importImpl } from '../../_resolve-impl.mjs';
5
+ import { addManagedMarker, injectBoundRules, listMdFiles } from './base.mjs';
6
+ import { transformAgent } from './codex.mjs';
7
+ import { projectCodexAgentBindings } from './bound-rules-pointer.mjs';
8
+ import { resolveDeliveryRuleBindings } from './rule-binding-targets.mjs';
9
+ const { parseRuleFrontmatter } = await importImpl(import.meta.url, 'rules/activation.mjs');
10
+ const { collectRuleBindingEntries } = await importImpl(import.meta.url, 'artifacts/index-builder.js');
11
+ const { resolveDeployVersion } = await importImpl(import.meta.url, 'providers/deploy-version.mjs');
12
+
13
+ export function packagedRuleSources(root) {
14
+ const code = path.join(root, 'agentic/code');
15
+ const roots = [code];
16
+ for (const kind of ['frameworks', 'addons', 'extensions', 'plugins']) {
17
+ const dir = path.join(code, kind);
18
+ if (fs.existsSync(dir)) roots.push(...fs.readdirSync(dir, { withFileTypes: true })
19
+ .filter(entry => entry.isDirectory()).map(entry => path.join(dir, entry.name)));
20
+ }
21
+ return roots.flatMap(dir => {
22
+ const behaviors = path.join(dir, 'behaviors');
23
+ return [...listMdFiles(path.join(dir, 'rules')).filter(file => !/^RULES-(INDEX|ONDEMAND)\.md$/.test(path.basename(file))), ...(fs.existsSync(behaviors)
24
+ ? fs.readdirSync(behaviors, { recursive: true, withFileTypes: true }).filter(entry => entry.isFile() && entry.name === 'BEHAVIOR.md')
25
+ .map(entry => path.join(entry.parentPath, entry.name)) : [])];
26
+ });
27
+ }
28
+
29
+ export async function createPackagedCodexRenderer(root, { target = root, ruleSources = packagedRuleSources(root) } = {}) {
30
+ const rules = ruleSources.flatMap(file => {
31
+ const content = fs.readFileSync(file, 'utf8');
32
+ const parsed = parseRuleFrontmatter(content);
33
+ if (!parsed.valid) throw new Error(`Invalid rule frontmatter: ${file}`);
34
+ if (!parsed.rule?.tagged || !parsed.rule.bound_to.agents.length) return [];
35
+ return [{ ...parsed.rule, file, content, body: parsed.body,
36
+ name: path.basename(file) === 'BEHAVIOR.md' ? `behavior/${path.basename(path.dirname(file))}` : parsed.data.name || path.basename(file, '.md'),
37
+ bound_to: { agents: parsed.rule.bound_to.agents, skills: [], flows: [] } }];
38
+ });
39
+ const bindingEntries = rules.length ? await collectRuleBindingEntries(root, 'agentic/code') : [];
40
+ const delivery = await resolveDeliveryRuleBindings({ srcRoot: root, target, bindingEntries }, rules,
41
+ { project: {}, user: {} }, root, null);
42
+ const deployVersion = resolveDeployVersion(root, undefined, () => {});
43
+ return (source, content = fs.readFileSync(source, 'utf8'), opts = {}) => {
44
+ const transformed = transformAgent(source, injectBoundRules(content, source, { ruleDelivery: delivery }), opts);
45
+ const targets = delivery.targets.filter(entry => entry.source === path.resolve(source));
46
+ return projectCodexAgentBindings(addManagedMarker(transformed, deployVersion, 'bundled', 'line-comment'), targets);
47
+ };
48
+ }
@@ -14,6 +14,7 @@ import {
14
14
  ruleEnforcementLevel,
15
15
  } from './base.mjs';
16
16
  import { resolveDeliveryRuleBindings } from './rule-binding-targets.mjs';
17
+ import { boundRuleAnchor, renderBoundRulesPointer } from './bound-rules-pointer.mjs';
17
18
  import { inlineStartup, nativePathLoader, ruleDirectory } from './rule-projection.mjs';
18
19
 
19
20
  export const { parseRuleFrontmatter, inferRuleActivation, readCoreBody, validateCoreSet, formatRuleFrontmatterError } = await importImpl(import.meta.url, 'rules/activation.mjs');
@@ -202,7 +203,7 @@ export function finishBindings(opts, provider) {
202
203
  const files = [...new Set(roots.flatMap(walk))];
203
204
  const indexRel = provider.name === 'copilot' ? '.github/RULES-BOUND.md' : provider.name === 'flue' ? '.agents/.aiwg/RULES-BOUND.md' : `.${provider.name}/RULES-BOUND.md`;
204
205
  const indexFile = path.join(opts.target, indexRel);
205
- const anchor = target => `${target.type}-${target.name}`.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
206
+ const anchor = boundRuleAnchor;
206
207
  const sections = new Map();
207
208
  const targetsBySource = new Map();
208
209
  for (const target of opts.ruleDelivery.targets) {
@@ -256,15 +257,14 @@ export function finishBindings(opts, provider) {
256
257
  const bound = opts.ruleDelivery.bindings.get(target.source) || [];
257
258
  const unique = [...new Map(bound.map(rule => [rule.name, rule])).values()].sort((a, b) => a.name.localeCompare(b.name));
258
259
  if (unique.length) sections.set(anchor(target), `## ${anchor(target)}\n\n` + unique.map(rule =>
259
- `- ${rule.name} — ${rule.summary} Fetch and follow: \`aiwg show rule ${rule.name} --body\`.`).join('\n'));
260
+ `- ${rule.name} — ${rule.summary} Fetch when a task or discovered component needs it: \`aiwg show rule ${rule.name} --body\`.`).join('\n'));
260
261
  }
261
262
  // Skills must carry exact fetch commands themselves: a section pointer
262
263
  // alone loses the invocation contract in clean installs (#3473).
263
264
  const fetch = skill ? [...new Map(rules.map(rule => [rule.name, rule])).values()]
264
265
  .sort((a, b) => a.name.localeCompare(b.name))
265
266
  .map(rule => `${rule.summary}\nFetch and follow before governed work: \`aiwg show rule ${rule.name} --body\`.`).join('\n') : '';
266
- return `${clean}${clean.endsWith('\n') ? '' : '\n'}\n<!-- AIWG:bound-rules:start -->\nRead and follow before governed work: ${identities.map(target =>
267
- `\`${indexRel}#${anchor(target)}\``).join('; ')}.\n${fetch ? fetch + '\n' : ''}<!-- AIWG:bound-rules:end -->\n`;
267
+ return renderBoundRulesPointer(body, identities, indexRel, { fetch, compact: provider.name === 'codex' && !skill });
268
268
  };
269
269
  if (file.endsWith('.toml')) content = content.replace(/^developer_instructions = (".*")$/m, (_, value) => `developer_instructions = ${JSON.stringify(pointer(JSON.parse(value)))}`);
270
270
  else content = pointer(content);
@@ -27,15 +27,16 @@ export function renderRuleKernelIndex(rules, nativePaths = false, perRuleFetch =
27
27
  if (!summary.length && !paths.length && !kernels.length) return '';
28
28
  const lines = ['# Rule kernel index', ''];
29
29
  // RULES-INDEX receipts are parsed by deployment accounting; retain their command format.
30
- if (!perRuleFetch) lines.push("Fetch and follow each rule's full body before governed work: `aiwg show rule <name> --body`.", '');
31
- if (kernelFile && kernels.length) lines.push('Read and follow every kernel file below before every task and subagent task.', '');
30
+ // #3900: "fetch before governed work" made Muse read every rule before discovery; fetch on need.
31
+ if (!perRuleFetch) lines.push("Fetch a rule's full body when a task or discovered component needs it: `aiwg show rule <name> --body`.", '');
32
+ if (kernelFile && kernels.length) lines.push("Kernel rules bind every task and subagent task. On a new task, first run discovery for the request (`aiwg discover --stdin <<'AIWG_REQUEST'`, the request, then `AIWG_REQUEST`) before reading any file below; then read a kernel file before work its subject covers.", '');
32
33
  for (const rule of kernels) lines.push(kernelFile
33
- ? `- ${rule.name} — ${rule.summary || 'Read and follow the complete kernel rule.'} Read and follow: [${kernelFile(rule)}](./${kernelFile(rule)}).`
34
+ ? `- ${rule.name} — ${rule.summary || 'Binding kernel rule.'} Full rule: [${kernelFile(rule)}](./${kernelFile(rule)}).`
34
35
  : perRuleFetch
35
- ? `- ${rule.name} — ${rule.summary || 'Fetch and follow the full rule before governed work.'} Fetch and follow: \`aiwg show rule ${rule.name} --body\`.`
36
+ ? `- ${rule.name} — ${rule.summary || 'Binding kernel rule.'} Full rule: \`aiwg show rule ${rule.name} --body\`.`
36
37
  : `- ${rule.name}${rule.summary ? ` — ${rule.summary}` : ''}`, '');
37
38
  for (const rule of summary) lines.push(perRuleFetch
38
- ? `- ${rule.name} — ${rule.summary} Fetch and follow: \`aiwg show rule ${rule.name} --body\`.`
39
+ ? `- ${rule.name} — ${rule.summary} Fetch when a task or discovered component needs it: \`aiwg show rule ${rule.name} --body\`.`
39
40
  : `- ${rule.name}${rule.summary ? ` — ${rule.summary}` : ''}`, '');
40
41
  if (paths.length) {
41
42
  lines.push(nativePaths ? '## Path rules (native)' : '## Path rules (prompt emulation)', '',
@@ -56,7 +56,13 @@ export function projectRules(opts, provider) {
56
56
  const tagged = rules.filter(rule => rule.tagged);
57
57
  const extension = provider.name === 'cursor' ? '.mdc' : '.md';
58
58
  const managed = content => addManagedMarker(content, opts.deployVersion, opts.deploySource || 'bundled');
59
- const writeRule = (rule, content) => put(path.join(rulesDir, `${ruleName(rule, provider)}${extension}`), managed(content));
59
+ const deployedSources = new Map();
60
+ const writeRule = (rule, content) => {
61
+ const name = `${ruleName(rule, provider)}${extension}`;
62
+ put(path.join(rulesDir, name), managed(content));
63
+ // Keep the source before reference rewriting, pinning, and native transforms.
64
+ deployedSources.set(name, opts.ruleDelivery.rules.find(original => original.file === rule.file));
65
+ };
60
66
  for (const file of walk(rulesDir)) {
61
67
  if (/\.(md|mdc)$/.test(file) && /aiwg:managed/.test(read(file))) fs.rmSync(file);
62
68
  }
@@ -115,7 +121,9 @@ export function projectRules(opts, provider) {
115
121
  manifest.managed ||= {};
116
122
  for (const file of walk(rulesDir).filter(file => /\.(md|mdc)$/.test(file) && /aiwg:managed/.test(read(file)))) {
117
123
  const name = path.relative(rulesDir, file);
118
- manifest.managed[name] = { ...manifest.managed[name], hash: `sha256:${contentHash(read(file))}` };
124
+ const source = deployedSources.get(name);
125
+ manifest.managed[name] = { ...manifest.managed[name], hash: `sha256:${contentHash(read(file))}`,
126
+ ...(source ? { sourceHash: `sha256:${contentHash(source.content)}` } : {}) };
119
127
  }
120
128
  for (const name of Object.keys(manifest.managed)) if (!fs.existsSync(path.join(rulesDir, name))) delete manifest.managed[name];
121
129
  put(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
@@ -61,7 +61,14 @@ export function projectStartup(opts, provider, coreSection, indexFile) {
61
61
  if (provider.name !== 'flue' || coreSection) content = section(content, 'rule-core', coreSection.replace(/<!-- AIWG:(?:core-rules|rule-core):(?:start|end) -->\n?/g, '').trimEnd());
62
62
  const logical = opts.logicalOutputPath || (file => file);
63
63
  const location = path.relative(logical(opts.target), logical(indexFile)).replaceAll('\\', '/');
64
- const hook = `${provider.name}: Before every task and subagent task, read and follow \`${location}\`; read every listed kernel file and fetch matching full rules before governed work.`;
64
+ let hook = `${provider.name}: Before every task and subagent task, read and follow \`${location}\`; read every listed kernel file and fetch matching full rules before governed work.`;
65
+ // droid exec runs no prompt hooks, so the Factory line carries discovery itself (#3942).
66
+ // The request goes through a quoted heredoc so the shell never expands it (#3946).
67
+ if (provider.name === 'factory') hook += " On every new request, your first tool call must be the shell command \`aiwg discover --stdin <<'AIWG_REQUEST'\` "
68
+ + "with the request text on the next lines and \`AIWG_REQUEST\` on the last line; never put request text in quotes on a command line. Answer from its result. "
69
+ + "Answering or declining without running it violates the skill-discovery rule. Use the \`aiwg\` CLI, not droid's built-in Skill tool. "
70
+ + "Before writing an issue, comment, PR, report or SDLC artifact, run the same heredoc command with \`--type template\` and \`<output> template\` as the text, "
71
+ + "read the chosen template with \`aiwg show template <name> --body\`, and fill every required section.";
65
72
  content = section(content, `rule-hook-${provider.name}`, hook);
66
73
  fs.mkdirSync(path.dirname(startup), { recursive: true });
67
74
  writeContextFileSync(startup, content);
@@ -2,10 +2,13 @@ import { fileURLToPath } from 'node:url';
2
2
  import { importImpl } from '../_resolve-impl.mjs';
3
3
 
4
4
  /** Offline inspection only: never probes a service or records an opportunity. */
5
- export async function collectDecisionOffloadReport(projectRoot) {
5
+ export async function collectDecisionOffloadReport(projectRoot, { fix = false } = {}) {
6
6
  try {
7
7
  const { buildDecisionOffloadSnapshot } = await importImpl(import.meta.url, 'decision/offload.js');
8
- return await buildDecisionOffloadSnapshot({ projectRoot, frameworkRoot: fileURLToPath(new URL('../../', import.meta.url)) });
8
+ const { inspectWorkspacePermissions } = await importImpl(import.meta.url, 'storage/workspace-permissions-health.js');
9
+ const permissions = await inspectWorkspacePermissions(projectRoot, fix);
10
+ const snapshot = await buildDecisionOffloadSnapshot({ projectRoot, frameworkRoot: fileURLToPath(new URL('../../', import.meta.url)) });
11
+ return { ...snapshot, permissions };
9
12
  } catch {
10
13
  // An unavailable reader must not be interpreted as healthy adoption, nor
11
14
  // leak exception details that can include private paths or stored values.
@@ -19,10 +22,14 @@ export function formatDecisionOffloadReport(snapshot) {
19
22
  lines.push(' Observation: unknown (report unavailable).');
20
23
  return lines;
21
24
  }
25
+ for (const journal of snapshot.permissions?.journals ?? []) lines.push(` Journal permissions: ${journal.state} (${journal.path})`);
26
+ for (const finding of snapshot.permissions?.findings ?? []) lines.push(` Permissions: ${finding.reason} (${finding.path}); ${finding.repaired ? 'repaired' : finding.repair}`);
22
27
  const calls = snapshot.calls?.organic;
23
28
  const opportunities = snapshot.opportunities?.organic;
24
29
  lines.push(` Scope: ${snapshot.scope?.mode ?? 'unknown'}${snapshot.scope?.sessionId ? ` (${snapshot.scope.sessionId})` : ''}`);
25
30
  lines.push(` Ask: ${snapshot.readiness?.ask?.state ?? 'unknown'}; evaluate: ${snapshot.readiness?.evaluate?.state ?? 'unknown'} (no probe)`);
31
+ const credential = snapshot.readiness?.ask;
32
+ if (credential?.source) lines.push(` Credential source: ${credential.source}${credential.path ? `; path: ${credential.path}` : ''}`);
26
33
  lines.push(` Completed calls: ${calls?.completed ?? 'unknown'}; answered: ${calls?.answered ?? 'unknown'}; fallback: ${calls?.fallback ?? 'unknown'}`);
27
34
  if (calls) {
28
35
  lines.push(` Estimated LLM tokens avoided: ${calls.llmTokensAvoided}; Jev tokens: ${calls.jevTokens}`);
@@ -0,0 +1,24 @@
1
+ // Synchronize tracker issue forms from the owning aiwg-utils bundle.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ const templates = ['bug-report', 'feature-request', 'tester-report', 'imported-report'];
6
+
7
+ export function syncIssueTemplateCopies(root, { check = false, dryRun = false } = {}) {
8
+ const differences = [];
9
+ for (const name of templates) {
10
+ const source = path.join(root, 'agentic/code/addons/aiwg-utils/templates/issues', `${name}.md`);
11
+ const canonical = fs.readFileSync(source);
12
+ for (const tracker of ['.gitea', '.github']) {
13
+ const relative = `${tracker}/ISSUE_TEMPLATE/${name}.md`;
14
+ const target = path.join(root, relative);
15
+ if (!fs.existsSync(target)) differences.push(`Missing: ${relative}`);
16
+ else if (!fs.readFileSync(target).equals(canonical)) differences.push(`Changed: ${relative}`);
17
+ if (!check && !dryRun) {
18
+ fs.mkdirSync(path.dirname(target), { recursive: true });
19
+ fs.writeFileSync(target, canonical);
20
+ }
21
+ }
22
+ }
23
+ return differences;
24
+ }
@@ -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,8 @@ 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' },
46
+ ...['milestone-worker-brief.md', 'verification-oracle-checklist.md'].map(name => ({ from: `agentic/code/frameworks/sdlc-complete/templates/management/${name}`, to: `templates/management/${name}` })),
44
47
  ...['threat-assessment.mjs', 'threat-assessment'].map(name => ({ from: `tools/security/${name}`, to: `tools/security/${name}` })),
45
48
  { from: 'agentic/code/frameworks/sdlc-complete/flows/flow-architecture-evolution.playbook.yaml', to: 'flows/flow-architecture-evolution.playbook.yaml' },
46
49
  { from: 'agentic/code/frameworks/sdlc-complete/flows/flow-release.playbook.yaml', to: 'flows/flow-release.playbook.yaml' }
@@ -240,7 +243,11 @@ Writing quality validation and AI pattern detection.
240
243
  { from: 'agentic/code/addons/aiwg-utils/rules/skill-discovery.md', to: 'rules/skill-discovery.md' },
241
244
  { from: 'agentic/code/addons/aiwg-utils/rules/skill-discovery-guidance.md', to: 'rules/skill-discovery-guidance.md' },
242
245
  { 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' }
246
+ ...['artifact-output-policy', 'artifact-output-policy-guidance'].map(name =>
247
+ ({ from: `agentic/code/addons/aiwg-utils/rules/${name}.md`, to: `rules/${name}.md` })),
248
+ { from: 'agentic/code/addons/aiwg-utils/templates/subagent-brief.md', to: 'templates/subagent-brief.md' },
249
+ { from: 'agentic/code/addons/aiwg-utils/templates/issues', to: 'templates/issues' },
250
+ { from: 'agentic/code/addons/aiwg-utils/templates/pull-requests', to: 'templates/pull-requests' }
244
251
  ],
245
252
  readme: `# AIWG Utilities
246
253
 
@@ -294,6 +301,8 @@ Core AIWG utilities for context regeneration and workspace management.
294
301
  skills: 'agentic/code/frameworks/sdlc-complete/skills'
295
302
  },
296
303
  extraCopy: [
304
+ { from: 'agentic/code/frameworks/sdlc-complete/templates/issue-comments', to: 'templates/issue-comments' },
305
+ ...['milestone-worker-brief.md', 'verification-oracle-checklist.md'].map(name => ({ from: `agentic/code/frameworks/sdlc-complete/templates/management/${name}`, to: `templates/management/${name}` })),
297
306
  { from: 'agentic/code/frameworks/sdlc-complete/flows/flow-architecture-evolution.playbook.yaml', to: 'flows/flow-architecture-evolution.playbook.yaml' },
298
307
  { from: 'agentic/code/frameworks/sdlc-complete/flows/flow-release.playbook.yaml', to: 'flows/flow-release.playbook.yaml' }
299
308
  ],
@@ -329,6 +338,8 @@ Then install in Codex via the \`/plugins\` command or the repo marketplace.
329
338
  agents: 'agentic/code/frameworks/forensics-complete/agents',
330
339
  skills: 'agentic/code/frameworks/forensics-complete/skills'
331
340
  },
341
+ extraCopy: ['evidence-integrity', 'non-destructive'].map(name =>
342
+ ({ from: `agentic/code/frameworks/forensics-complete/rules/${name}.md`, to: `rules/${name}.md` })),
332
343
  readme: `# AIWG Forensics Complete
333
344
 
334
345
  Digital forensics and incident response framework with 14 specialized agents.
@@ -373,7 +384,8 @@ Digital forensics and incident response framework with 14 specialized agents.
373
384
  skills: 'agentic/code/frameworks/security-engineering/skills'
374
385
  },
375
386
  extraCopy: [
376
- { from: 'agentic/code/frameworks/security-engineering/rules/ci-action-pinning.md', to: 'rules/ci-action-pinning.md' }
387
+ { from: 'agentic/code/frameworks/security-engineering/rules/ci-action-pinning.md', to: 'rules/ci-action-pinning.md' },
388
+ { from: 'agentic/code/frameworks/security-engineering/rules/published-port-binding.md', to: 'rules/published-port-binding.md' }
377
389
  ],
378
390
  readme: `# AIWG Security Engineering
379
391
 
@@ -1192,9 +1204,9 @@ function writeCodexMarketplaceManifest(options) {
1192
1204
  // rewrites and skill pruning. Only default Claude-owned paths are checked:
1193
1205
  // provider-native metadata and separately maintained templates are preserved.
1194
1206
  export function checkPackagedPlugins({ pluginsDir = PLUGINS_DIR,
1195
- marketplacePath = path.join(ROOT_DIR, '.claude-plugin/marketplace.json') } = {}) {
1207
+ marketplacePath = path.join(ROOT_DIR, '.claude-plugin/marketplace.json'), trackerRoot = ROOT_DIR } = {}) {
1196
1208
  const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'aiwg-plugin-check-'));
1197
- const differences = [];
1209
+ const differences = syncIssueTemplateCopies(trackerRoot, { check: true });
1198
1210
  function files(root) {
1199
1211
  if (!fs.existsSync(root)) return [];
1200
1212
  if (!fs.statSync(root).isDirectory()) return [''];
@@ -1338,6 +1350,7 @@ async function main() {
1338
1350
  }
1339
1351
 
1340
1352
  // Package for each (provider, plugin) combination
1353
+ if (options.all) syncIssueTemplateCopies(ROOT_DIR, options);
1341
1354
  for (const provider of providersToRun) {
1342
1355
  for (const [name, config] of pluginsToPackage) {
1343
1356
  // Provider-specific bundles are not part of another provider's catalog.
@@ -13,12 +13,12 @@ import { homedir } from 'os';
13
13
  import { ProviderAdapter, registerProvider } from './provider-adapter.mjs';
14
14
  import { classifyWorkerHealthFailure, healthEventMatchesBinding } from './worker-health.mjs';
15
15
 
16
- /** Help-only evidence: /home/roctinam/.local/bin/claude 2.1.295, 2026-10-09.
16
+ /** Help-only evidence: /home/roctinam/.local/bin/claude 2.1.319, 2026-11-07.
17
17
  * Exact help excerpts and unavailable controls: docs/providers/claude-direct.md.
18
18
  * No inference or credential inspection was performed to establish this syntax.
19
19
  */
20
20
  export const interfaceVersion = 1;
21
- export const CLAUDE_SUPPORTED_VERSIONS = Object.freeze(['2.1.295']);
21
+ export const CLAUDE_SUPPORTED_VERSIONS = Object.freeze(['>=2.1.295 <2.2.0']);
22
22
  export const CLAUDE_DIRECT_EFFORT_VALUES = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
23
23
  // Named aliases --help documents (opus/sonnet/fable) plus other known moving
24
24
  // pointers: 'default', 'haiku', and the Max-plan 'opusplan' alias. None of
@@ -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;
@@ -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;
@@ -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();
@@ -18,7 +27,7 @@ export function parseWorkerLaunchArgs(args) {
18
27
  // A run directory declares a retry; its launcher ID is derived before validation.
19
28
  const key = { '--invocation': 'invocationPath', '--run-dir': 'runDir',
20
29
  '--retry-of': '__retryOfInvocationId', '--retry-of-run-dir': '__retryOfRunDir' }[flag];
21
- 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.`);
22
31
  const value = args[++i];
23
32
  if (!value || value.startsWith('--')) throw new Error(`${flag} requires a value`);
24
33
  if (key === '__retryOfInvocationId') retryOfInvocationId = value;
@@ -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
+ }
@@ -0,0 +1,8 @@
1
+ // Format bounded, actionable diagnostics for a refused worker run directory.
2
+ export function workerRunDirectoryRefusal(entries) {
3
+ const reason = 'Worker run directory must be fresh, empty, private and owned';
4
+ if (!entries.length) return reason;
5
+ const names = entries.toSorted().slice(0, 5).map(name => JSON.stringify(name)).join(', ');
6
+ const remaining = entries.length > 5 ? ` (+${entries.length - 5} more)` : '';
7
+ return `${reason}. Unexpected entries: ${names}${remaining}. Keep the plan and other files outside the run dir, or pass a new run dir.`;
8
+ }
@@ -51,6 +51,8 @@ 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 { workerRunDirectoryRefusal } from './lib/worker-run-directory-refusal.mjs';
55
+ import { workerPromptBrief } from './lib/worker-prompt.mjs';
54
56
  import { prepareWorkerRetry, workerRetryRecordFields } from './lib/worker-retry-evidence.mjs';
55
57
  import { settleWorkerTermination, terminationRemedy } from './lib/worker-termination.mjs';
56
58
  import { WorkerCaptureOwner, assertWorkerCapturePathsAvailable } from './lib/worker-capture.mjs';
@@ -406,8 +408,9 @@ async function launchOneWorker(owner, options) {
406
408
  const runExists = await inspect(runDir, 'directory');
407
409
  if (runExists) {
408
410
  const stat = await lstat(runDir);
409
- if (stat.uid !== process.getuid() || (stat.mode & 0o077) || (await readdir(runDir)).length) {
410
- throw new Error('Worker run directory must be fresh, empty, private and owned');
411
+ const entries = stat.uid === process.getuid() && !(stat.mode & 0o077) ? await readdir(runDir) : [];
412
+ if (stat.uid !== process.getuid() || (stat.mode & 0o077) || entries.length) {
413
+ throw new Error(workerRunDirectoryRefusal(entries));
411
414
  }
412
415
  }
413
416
  const writableRoots = inputs.drivers[invocation.selected.cli].qualification.installation?.workerWritableRoots ?? [invocation.cwd];
@@ -446,7 +449,7 @@ async function launchOneWorker(owner, options) {
446
449
  // Frame stdin before any spawn: brief-json delivers a conductor-built params
447
450
  // document on the stdin pipe, never brief text in argv (#2911).
448
451
  const { workerStdinBytes } = await importImpl(import.meta.url, 'serve/worker-stdin-frame.mjs');
449
- const stdinBytes = workerStdinBytes(invocation, brief, inputs.drivers[invocation.selected.cli]);
452
+ const stdinBytes = workerStdinBytes(invocation, workerPromptBrief(brief, paths.final), inputs.drivers[invocation.selected.cli]);
450
453
  let gate = (options.checkDispatch ?? checkWorkerDispatch)({ config: inputs.snapshot.config,
451
454
  paths: await Promise.all([invocation.cwd, runDir].map(workerDispatchPath)) });
452
455
  if (!gate.ok) throw workerDispatchRefusal(gate);
@@ -666,7 +669,7 @@ async function launchOneWorker(owner, options) {
666
669
  let outcome;
667
670
  let artifacts;
668
671
  try {
669
- artifacts = await materializeWorkerArtifacts(invocation, runDir);
672
+ artifacts = await materializeWorkerArtifacts(invocation, runDir, { brief, invocationId });
670
673
  const displayArgv = artifacts.argv.map((token, i) => i === 0 ? token : `<argument:${bytesDigest(token)}>`);
671
674
  // #2915 review 4 (finding 4): a STABLE task-chain identity, never the
672
675
  // raw request object — `qualificationDigest(saved.request)` included
@@ -692,7 +695,7 @@ async function launchOneWorker(owner, options) {
692
695
  // Retain the legacy digest binding while naming both argv stages explicitly.
693
696
  argvDigest: qualificationDigest(invocation.argv), placeholderArgvDigest: qualificationDigest(invocation.argv),
694
697
  executedArgvDigest: qualificationDigest(artifacts.argv),
695
- artifacts: (invocation.artifacts ?? []).map(artifact => ({ name: artifact.name,
698
+ artifacts: artifacts.declarations.map(artifact => ({ name: artifact.name,
696
699
  byteLength: Buffer.byteLength(artifact.content), sha256: bytesDigest(artifact.content) })),
697
700
  envNames: buildWorkerInvocationEnvironment(invocation.envNames, invocationId, {}, invocation).envNames, stdin: invocation.stdin,
698
701
  prompt: { path: invocation.briefPath, digest: invocation.briefDigest }, cwd: invocation.cwd,
@@ -1566,7 +1569,7 @@ async function launchOneWorkerBaseline(owner, options, ctx) {
1566
1569
  let artifacts;
1567
1570
  let managedSpawnAttempted = false;
1568
1571
  try {
1569
- artifacts = await materializeWorkerArtifacts(invocation, runDir);
1572
+ artifacts = await materializeWorkerArtifacts(invocation, runDir, { brief: ctx.brief, invocationId });
1570
1573
  const displayArgv = artifacts.argv.map((token, i) => i === 0 ? token : `<argument:${bytesDigest(token)}>`);
1571
1574
  await publish('invocation.json', { version: 1, origin: 'launcher', invocationId, attemptId: invocationId,
1572
1575
  previousAttemptId: verifiedPreviousAttemptId ?? null, requestId: options.managedAdmission?.requestId ?? invocationId, taskDigest: options.retryEvidence?.taskDigest ?? qualificationDigest(saved.request), role: saved.request.role,
@@ -1578,7 +1581,7 @@ async function launchOneWorkerBaseline(owner, options, ctx) {
1578
1581
  // Retain the legacy digest binding while naming both argv stages explicitly.
1579
1582
  argvDigest: qualificationDigest(invocation.argv), placeholderArgvDigest: qualificationDigest(invocation.argv),
1580
1583
  executedArgvDigest: qualificationDigest(artifacts.argv),
1581
- artifacts: (invocation.artifacts ?? []).map(artifact => ({ name: artifact.name,
1584
+ artifacts: artifacts.declarations.map(artifact => ({ name: artifact.name,
1582
1585
  byteLength: Buffer.byteLength(artifact.content), sha256: bytesDigest(artifact.content) })),
1583
1586
  envNames: buildWorkerInvocationEnvironment(invocation.envNames, invocationId, {}, invocation).envNames, stdin: invocation.stdin,
1584
1587
  prompt: { path: invocation.briefPath, digest: invocation.briefDigest }, cwd: invocation.cwd,