@aiwg/cli 2026.10.16 → 2026.10.18

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 (128) hide show
  1. package/dist/src/artifacts/corpus-tools/resolve.js +21 -4
  2. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  3. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  4. package/dist/src/artifacts/query-engine-discover.js +285 -0
  5. package/dist/src/artifacts/query-engine-entries.js +188 -0
  6. package/dist/src/artifacts/query-engine-index.js +249 -0
  7. package/dist/src/artifacts/query-engine-matching.js +143 -0
  8. package/dist/src/artifacts/query-engine-options.js +2 -0
  9. package/dist/src/artifacts/query-engine-rules.js +202 -0
  10. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  11. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  12. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  13. package/dist/src/artifacts/query-engine-show.js +300 -0
  14. package/dist/src/artifacts/query-engine.js +7 -2576
  15. package/dist/src/cli/handlers/mc-agents.js +111 -0
  16. package/dist/src/cli/handlers/mc-args.js +54 -0
  17. package/dist/src/cli/handlers/mc-control.js +227 -0
  18. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  19. package/dist/src/cli/handlers/mc-help.js +171 -0
  20. package/dist/src/cli/handlers/mc-run.js +343 -0
  21. package/dist/src/cli/handlers/mc-session.js +138 -0
  22. package/dist/src/cli/handlers/mc-status.js +258 -0
  23. package/dist/src/cli/handlers/mc-summary.js +43 -0
  24. package/dist/src/cli/handlers/mc-types.js +3 -0
  25. package/dist/src/cli/handlers/mc-worker.js +205 -0
  26. package/dist/src/cli/handlers/mc.js +12 -1665
  27. package/dist/src/cli/handlers/models-refusal.js +13 -0
  28. package/dist/src/cli/handlers/models.js +2 -1
  29. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  30. package/dist/src/cli/handlers/remove-options.js +31 -0
  31. package/dist/src/cli/handlers/remove-user.js +174 -0
  32. package/dist/src/cli/handlers/remove.js +201 -0
  33. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  34. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  35. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  36. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  37. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  38. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  39. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  40. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  41. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  42. package/dist/src/cli/handlers/subcommands.js +18 -1984
  43. package/dist/src/cli/scope-resolver.js +1 -142
  44. package/dist/src/cli/user-scope-mirror.js +173 -0
  45. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  46. package/dist/src/config/dispatch-thresholds-runtime.mjs +4 -0
  47. package/dist/src/config/host-resource-report.d.mts +5 -0
  48. package/dist/src/config/host-resource-report.mjs +36 -6
  49. package/dist/src/config/host-resource-runtime.d.mts +3 -0
  50. package/dist/src/config/host-resource-runtime.mjs +9 -6
  51. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  52. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  53. package/dist/src/decision/ensemble-study/gates.js +78 -0
  54. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  55. package/dist/src/decision/ensemble-study/score.js +3 -2
  56. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  57. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  58. package/dist/src/decision/sensitivity/comparative.js +18 -41
  59. package/dist/src/extensions/claude-hooks-installer.js +18 -0
  60. package/dist/src/gates/evaluate.js +2 -358
  61. package/dist/src/gates/observations.js +363 -0
  62. package/dist/src/gates/pack-composition.js +270 -0
  63. package/dist/src/gates/pack-tightening.js +197 -0
  64. package/dist/src/gates/pack-validation.js +262 -0
  65. package/dist/src/gates/registry-error.js +5 -0
  66. package/dist/src/gates/registry.js +13 -685
  67. package/dist/src/mcp/json-document.mjs +29 -0
  68. package/dist/src/mcp/muse-native-config.mjs +1 -28
  69. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  70. package/dist/src/models/worker-plan.js +5 -5
  71. package/dist/src/plugin/command-ownership.js +34 -0
  72. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  73. package/dist/src/plugin/skill-command-translator.js +6 -232
  74. package/dist/src/providers/context-output-ownership.js +26 -0
  75. package/dist/src/providers/deployment-ownership.d.mts +19 -0
  76. package/dist/src/providers/deployment-ownership.mjs +226 -0
  77. package/dist/src/providers/deployment-removal.js +200 -0
  78. package/dist/src/providers/removal-transaction.js +86 -0
  79. package/dist/src/providers/settings-document.d.mts +3 -0
  80. package/dist/src/providers/settings-document.mjs +47 -0
  81. package/dist/src/providers/settings-removal.js +190 -0
  82. package/dist/src/providers/skill-ownership.d.mts +19 -2
  83. package/dist/src/providers/skill-ownership.mjs +12 -4
  84. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  85. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  86. package/dist/src/providers/transformation-receipt-source.js +194 -0
  87. package/dist/src/research/identity.js +8 -2
  88. package/dist/src/research/reference-match.js +42 -7
  89. package/dist/src/rules/activation.mjs +15 -6
  90. package/dist/src/rules/core-startup.mjs +2 -2
  91. package/dist/src/serve/mission-conductor.js +4 -0
  92. package/dist/src/serve/mission-summary.js +56 -0
  93. package/dist/src/smiths/context-pipeline/aiwg-md.js +23 -0
  94. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  95. package/dist/src/smiths/context-pipeline/generator.js +1 -1
  96. package/dist/src/smiths/hook-bridge/index.js +9 -0
  97. package/package.json +4 -1
  98. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  99. package/tools/agents/deploy-agents.mjs +16 -677
  100. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  101. package/tools/agents/deploy-options.mjs +258 -0
  102. package/tools/agents/deploy-support.mjs +165 -0
  103. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  104. package/tools/agents/providers/base-behaviors.mjs +168 -0
  105. package/tools/agents/providers/base-context.mjs +205 -0
  106. package/tools/agents/providers/base-contract.mjs +116 -0
  107. package/tools/agents/providers/base-files.mjs +252 -0
  108. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  109. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  110. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  111. package/tools/agents/providers/base-inventory.mjs +269 -0
  112. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  113. package/tools/agents/providers/base-migrations.mjs +258 -0
  114. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  115. package/tools/agents/providers/base-rule-index.mjs +450 -0
  116. package/tools/agents/providers/base-runtime.mjs +60 -0
  117. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  118. package/tools/agents/providers/base.mjs +16 -3364
  119. package/tools/agents/providers/claude-post-deploy.mjs +10 -2
  120. package/tools/agents/providers/hermes-startup.mjs +0 -5
  121. package/tools/agents/providers/muse.mjs +7 -2
  122. package/tools/agents/providers/rule-delivery-surface.mjs +31 -4
  123. package/tools/agents/providers/rule-deployment-commit.mjs +19 -15
  124. package/tools/agents/providers/rule-deployment-prepare.mjs +11 -2
  125. package/tools/agents/providers/rule-projection.mjs +3 -0
  126. package/tools/ralph-external/lib/worker-invocation-processes.mjs +4 -2
  127. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  128. package/vscode-extension/schemas/aiwg.config.v1.json +2 -4
@@ -17,6 +17,8 @@ export async function postDeploy(targetDir, opts) {
17
17
 
18
18
  // If settings.json doesn't exist, create a minimal one
19
19
  if (!fs.existsSync(settingsPath) && !opts.dryRun) {
20
+ const { captureDeploymentOutputs, recordDeploymentOutputs } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
21
+ const before = captureDeploymentOutputs([claudeDir]);
20
22
  ensureDir(claudeDir);
21
23
  const settings = {
22
24
  version: '1.0',
@@ -27,14 +29,20 @@ export async function postDeploy(targetDir, opts) {
27
29
  }
28
30
  };
29
31
  fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2), 'utf8');
32
+ recordDeploymentOutputs(before, [claudeDir], { ...opts, writtenFiles: [settingsPath] });
33
+ opts.writtenFiles?.push(settingsPath);
30
34
  console.log('Created .claude/settings.json');
31
35
  }
32
36
 
37
+ const addonPass = /(?:agentic\/code|\.aiwg)\/(?:addons|extensions)\//.test((opts.logicalInputPath?.(opts.srcRoot) || opts.srcRoot)?.replaceAll('\\', '/') || '');
38
+
33
39
  // Reuse the settings owner's backup/atomic merge, independently of hooks.
34
40
  if (opts.attribution !== false) {
35
41
  const { installAiwgHooks } = await importImpl(import.meta.url, 'extensions/claude-hooks-installer.js');
36
- const result = await installAiwgHooks({ projectPath: targetDir, frameworkRoot: opts.srcRoot || targetDir,
37
- hooks: false, dryRun: opts.dryRun });
42
+ const { deploymentOwner } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
43
+ const result = await installAiwgHooks({ frameworkSlug: deploymentOwner(opts), claimUnchangedSettings: !addonPass, projectPath: targetDir, frameworkRoot: opts.srcRoot || targetDir,
44
+ attribution: opts.attribution !== false, hooks: false, dryRun: opts.dryRun });
45
+ if (!opts.dryRun && result) opts.writtenFiles?.push(result.settingsPath);
38
46
  for (const warning of result?.warnings || []) console.warn(`Claude settings: ${warning}`);
39
47
  }
40
48
  await deployConductorDataGuard(targetDir, 'claude', opts);
@@ -58,11 +58,6 @@ whenever the user mentions AIWG, a framework name (sdlc, research, forensics,
58
58
  ops, marketing, security-engineering, media-curator, knowledge-base), or
59
59
  capability keywords (skill, agent, command, rule, workflow).
60
60
 
61
- ### Rule: no-attribution
62
- Never add AI-tool attribution to commits, PRs, code, or docs. No \`Co-Authored-By:\`,
63
- no "Generated with", no "Written by [AI tool]". The AI is a tool; tools don't sign
64
- their output. Applies to ALL platforms (Claude, Codex, Copilot, Cursor, etc.).
65
-
66
61
  ### Rule: citation-policy
67
62
  Never fabricate citations, DOIs, URLs, or page numbers. Only cite sources that
68
63
  exist in the research corpus (.aiwg/research/sources/). Match claim strength
@@ -49,7 +49,9 @@ import {
49
49
  resolveMuseXdgSkillsDir,
50
50
  museXdgSkillsDirRemediation,
51
51
  } from './muse-paths.mjs';
52
- import { deployMuseHooks, deployMuseMcp } from './muse-hooks.mjs';
52
+ import { importImpl } from '../../_resolve-impl.mjs';
53
+ const { captureDeploymentOutputs, recordDeploymentOutputs } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
54
+ import { assertMuseUserSettingsPath, deployMuseHooks, deployMuseMcp } from './muse-hooks.mjs';
53
55
 
54
56
  export const name = 'muse';
55
57
  export const aliases = []; // ADR: no aliases (no muse-spark, muse-code, spark, meta)
@@ -241,7 +243,10 @@ export async function postDeploy(targetDir, opts = {}) {
241
243
  // #228 — optional MCP settings profile. Explicit opt-in only (--mcp);
242
244
  // default `aiwg use --provider muse` never touches user settings.
243
245
  if (fullDeploy && opts.mcp === true) {
244
- await deployMuseMcp(opts);
246
+ const settingsPath = assertMuseUserSettingsPath(opts.env || process.env, opts.userHome || os.homedir());
247
+ const before = opts.dryRun ? null : captureDeploymentOutputs([settingsPath]);
248
+ const result = await deployMuseMcp(opts);
249
+ if (before && result.wrote) recordDeploymentOutputs(before, [settingsPath], { ...opts, writtenFiles: [settingsPath] });
245
250
  }
246
251
 
247
252
  if (!opts.quiet) {
@@ -6,6 +6,7 @@ import { importImpl } from '../../_resolve-impl.mjs';
6
6
  import {
7
7
  addManagedMarker,
8
8
  contentHash,
9
+ extractFrameworkSlug,
9
10
  getFrameworksForMode,
10
11
  listMdFiles,
11
12
  replaceBoundRulesBlock,
@@ -177,6 +178,24 @@ export function put(file, content) { fs.mkdirSync(path.dirname(file), { recursiv
177
178
 
178
179
  /** External helpers also project skills/flows. Inject into their body, never descriptions. */
179
180
  export function finishBindings(opts, provider) {
181
+ const putOwned = (file, content) => { put(file, content); opts.writtenFiles?.push(file); };
182
+ const corpus = opts.srcRoot && (resolveAiwgRoot(opts.srcRoot) || opts.srcRoot);
183
+ const frameworks = corpus ? getFrameworksForMode(corpus, 'all') : [];
184
+ const knownFrameworks = new Set(frameworks.map(framework => framework.id));
185
+ const installed = Object.keys(opts.config?.installed || opts.pinConfigs?.project?.installed || {});
186
+ const invoked = opts.srcRoot ? getFrameworksForMode(opts.srcRoot,
187
+ opts.mode === 'all' && installed.length ? 'general' : opts.mode) : [];
188
+ const selectedFrameworks = new Set([
189
+ ...invoked,
190
+ ...installed.filter(name => name !== 'all').flatMap(name => corpus ? getFrameworksForMode(corpus, name) : []),
191
+ ...frameworks.filter(framework => [opts.srcRoot, ...(opts.additionalSources || [])].filter(Boolean)
192
+ .some(source => path.resolve(framework.path) === path.resolve(source)) || (framework.manifest.core && framework.manifest.autoInstall)),
193
+ ].map(framework => framework.id));
194
+ // Selected dependency rules also identify frameworks reached through addons.
195
+ for (const rule of opts.ruleDelivery.rules || []) {
196
+ const owner = rule.file && extractFrameworkSlug(rule.file);
197
+ if (knownFrameworks.has(owner)) selectedFrameworks.add(owner);
198
+ }
180
199
  const roots = [opts.target, opts.deploymentHome,
181
200
  ...[opts.kernelSkillsPath, opts.activeWorkspace, ...Object.values(provider.paths)].filter(p => p && path.isAbsolute(p))];
182
201
  const files = [...new Set(roots.flatMap(walk))];
@@ -197,7 +216,15 @@ export function finishBindings(opts, provider) {
197
216
  const name = skill ? path.basename(path.dirname(file)) : path.basename(file).replace(/\.(md|toml)$/, '');
198
217
  const sidecarPath = path.join(skill ? path.dirname(file) : path.dirname(file), '.aiwg-manifest.json');
199
218
  const sidecar = fs.existsSync(sidecarPath) ? JSON.parse(read(sidecarPath)) : null;
200
- const source = sidecar?.skillSource ? path.join(sidecar.skillSource, 'SKILL.md') : sidecar?.managed?.[path.basename(file)]?.sourcePath;
219
+ // Wrapper source identity is ownership metadata. Preserve the legacy
220
+ // flow-only name lookup instead of selecting new skill binding targets.
221
+ const wrapper = !skill && sidecar?.managed?.[path.basename(file)]?.kind === 'skill-command';
222
+ const wrapperOwner = sidecar?.managed?.[path.basename(file)]?.frameworkSlug
223
+ || extractFrameworkSlug(sidecar?.managed?.[path.basename(file)]?.sourcePath || '');
224
+ // Shared command surfaces can contain a framework's late wrappers before
225
+ // that framework is selected. Do not activate its bindings on redeploy.
226
+ if (wrapper && knownFrameworks.has(wrapperOwner) && !selectedFrameworks.has(wrapperOwner)) continue;
227
+ const source = wrapper ? undefined : sidecar?.skillSource ? path.join(sidecar.skillSource, 'SKILL.md') : sidecar?.managed?.[path.basename(file)]?.sourcePath;
201
228
  const flowSource = opts.flowSkillSources?.get(file);
202
229
  const targets = [...(flowSource ? targetsBySource.get(flowSource) || [] : []),
203
230
  ...(source ? targetsBySource.get(path.resolve(source)) || [] : opts.ruleDelivery.targets.filter(target =>
@@ -225,14 +252,14 @@ export function finishBindings(opts, provider) {
225
252
  };
226
253
  if (file.endsWith('.toml')) content = content.replace(/^developer_instructions = (".*")$/m, (_, value) => `developer_instructions = ${JSON.stringify(pointer(JSON.parse(value)))}`);
227
254
  else content = pointer(content);
228
- put(file, content);
255
+ putOwned(file, content);
229
256
  // Keep deployment hashes honest after projection by external helpers.
230
257
  if (sidecar?.managed?.[path.basename(file)]) {
231
258
  sidecar.managed[path.basename(file)].hash = `sha256:${contentHash(content)}`;
232
- put(sidecarPath, `${JSON.stringify(sidecar, null, 2)}\n`);
259
+ putOwned(sidecarPath, `${JSON.stringify(sidecar, null, 2)}\n`);
233
260
  }
234
261
  }
235
- if (sections.size) put(indexFile, managed('# Bound rules\n\nFetch and follow every full rule in the invoked artifact’s section before governed work.\n\n' +
262
+ if (sections.size) putOwned(indexFile, managed('# Bound rules\n\nFetch and follow every full rule in the invoked artifact’s section before governed work.\n\n' +
236
263
  [...sections.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([, section]) => section).join('\n\n') + '\n', opts));
237
264
  else if (/aiwg:managed/.test(read(indexFile))) fs.rmSync(indexFile);
238
265
 
@@ -1,6 +1,8 @@
1
1
  // Validate and promote staged deployment plans through safe writers.
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
+ import { importImpl } from '../../_resolve-impl.mjs';
5
+ const { refreshSettingsDigests } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
4
6
  import {
5
7
  contentHash,
6
8
  deploySkillsWithKernelRouting,
@@ -53,6 +55,21 @@ export function commitRuleDeploymentPlan(plan) {
53
55
  for (const mapping of [...plan.sourceMappings].sort((a, b) => b.to.length - a.to.length)) content = content.split(mapping.to).join(mapping.from);
54
56
  return content.split(plan.snapshotRoot).join(plan.corpusRoot).split(stage).join(target);
55
57
  };
58
+ const normalizeReceipt = (file, output) => {
59
+ if (path.basename(file) !== '.aiwg-manifest.json') return output;
60
+ const receipt = JSON.parse(output.toString('utf8'));
61
+ for (const [name, record] of Object.entries(receipt.managed || {})) {
62
+ const base = file === path.join(stage, '.aiwg/.aiwg-manifest.json') && receipt.scope === 'project' ? stage : path.dirname(file);
63
+ const recordedFile = path.resolve(base, name);
64
+ if (!within(base, recordedFile) || !fs.existsSync(recordedFile)) continue;
65
+ const recorded = fs.readFileSync(recordedFile);
66
+ if (record.hash !== `sha256:${contentHash(recorded)}`) continue;
67
+ const promoted = recorded.includes(0) ? recorded : Buffer.from(normalize(recorded.toString('utf8')));
68
+ record.hash = `sha256:${contentHash(promoted)}`;
69
+ refreshSettingsDigests(record);
70
+ }
71
+ return Buffer.from(`${JSON.stringify(receipt, null, 2)}\n`);
72
+ };
56
73
  const delegated = (from, rel) => mappings.some(mapping => mapping.from !== from
57
74
  && mapping.from.startsWith(`${from}${path.sep}`)
58
75
  && (path.join(from, rel) === mapping.from || path.join(from, rel).startsWith(`${mapping.from}${path.sep}`)));
@@ -79,27 +96,14 @@ export function commitRuleDeploymentPlan(plan) {
79
96
  const buffer = fs.readFileSync(file);
80
97
  // Provider output includes binary skill resources; normalize text only.
81
98
  let output = buffer.includes(0) ? buffer : Buffer.from(normalize(buffer.toString('utf8')));
82
- if (path.basename(file) === '.aiwg-manifest.json') {
83
- const receipt = JSON.parse(output.toString('utf8'));
84
- for (const [name, record] of Object.entries(receipt.managed || {})) {
85
- const recordedFile = path.resolve(path.dirname(file), name);
86
- if (!within(path.dirname(file), recordedFile) || !fs.existsSync(recordedFile)) continue;
87
- const recorded = fs.readFileSync(recordedFile);
88
- // Do not bless operator edits whose bytes already differ from the
89
- // ownership receipt. Only normalize hashes of pristine staged files.
90
- if (record.hash !== `sha256:${contentHash(recorded)}`) continue;
91
- const promoted = recorded.includes(0) ? recorded : Buffer.from(normalize(recorded.toString('utf8')));
92
- record.hash = `sha256:${contentHash(promoted)}`;
93
- }
94
- output = Buffer.from(`${JSON.stringify(receipt, null, 2)}\n`);
95
- }
99
+ output = normalizeReceipt(file, output);
96
100
  fs.mkdirSync(path.dirname(path.join(from, rel)), { recursive: true });
97
101
  if (plan.contextWrites.includes(file)) writeContextFileSync(path.join(from, rel), output);
98
102
  else fs.writeFileSync(path.join(from, rel), output);
99
103
  }
100
104
  }
101
105
  for (const name of rootNames) if (fs.existsSync(path.join(stage, name))) {
102
- const output = normalize(read(path.join(stage, name)));
106
+ const output = normalizeReceipt(path.join(stage, name), Buffer.from(normalize(read(path.join(stage, name))))).toString('utf8');
103
107
  if (output === read(path.join(target, name))) continue;
104
108
  const write = plan.contextWrites.includes(path.join(stage, name)) ? writeContextFileSync : put;
105
109
  write(path.join(target, name), output);
@@ -3,6 +3,7 @@ import { createHash, randomUUID } from 'node:crypto';
3
3
  import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
+ import { importImpl } from '../../_resolve-impl.mjs';
6
7
  import {
7
8
  deployEmulatedBehaviors,
8
9
  discoverAddons,
@@ -11,7 +12,7 @@ import {
11
12
  replaceBoundRulesBlock,
12
13
  resolveAiwgRoot,
13
14
  } from './base.mjs';
14
- import { CONTEXT_STAGE_ENV, GENERATED_CONTEXT_NAMES, OPERATOR_CONTEXT_NAMES } from './context-write.mjs';
15
+ import { writeContextFileSync, CONTEXT_STAGE_ENV, GENERATED_CONTEXT_NAMES, OPERATOR_CONTEXT_NAMES } from './context-write.mjs';
15
16
  import { captureProviderPathDescriptors, logicalProviderOutputPath, restoreProviderPaths, setStagedProviderPath } from './provider-paths-staging.mjs';
16
17
  import {
17
18
  collectDeploymentRuleSources,
@@ -44,6 +45,7 @@ import {
44
45
  verifyInputPool,
45
46
  } from './rule-deployment-state.mjs';
46
47
  import { inlineStartup, projectRules } from './rule-projection.mjs';
48
+ const { captureDeploymentOutputs, recordDeploymentOutputs } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
47
49
  import { retireInlineStartup } from './rule-startup.mjs';
48
50
 
49
51
  /** Stage only provider/context output, never the user's source tree. On failure
@@ -229,6 +231,10 @@ export async function prepareRuleDeployment(original, provider, deploy) {
229
231
  if (!rootNames.includes(safe)) rootNames.push(safe);
230
232
  }
231
233
  }
234
+ for (const name of [...rootNames]) {
235
+ const sidecar = path.join(path.dirname(name) === '.' ? '.aiwg' : path.dirname(name), '.aiwg-manifest.json');
236
+ if (!rootNames.includes(sidecar)) rootNames.push(sidecar);
237
+ }
232
238
  preimages.push(...snapshotPreimages(rootNames.map(name => path.join(target, name))));
233
239
  for (const name of rootNames) {
234
240
  const from = path.join(target, name), to = path.join(stage, name);
@@ -328,8 +334,10 @@ export async function prepareRuleDeployment(original, provider, deploy) {
328
334
  }
329
335
  delivery.bindings = remappedBindings;
330
336
  preimages.push(...snapshotPreimages([...delivery.rules.map(rule => rule.file), ...delivery.targets.map(entry => entry.source), path.join(target, '.aiwg', 'aiwg.config')]));
331
- const opts = { ...original, target: stage, dryRun: false, ruleDelivery: delivery, logicalOutputPath: file => logicalProviderOutputPath(file, stage, target, mappings),
337
+ const opts = { ...original, writeReceipt: writeContextFileSync, writtenFiles: [], target: stage, dryRun: false, ruleDelivery: delivery, logicalOutputPath: file => logicalProviderOutputPath(file, stage, target, mappings),
332
338
  kernelSkillsPath: kernel, deploymentHome: home, activeWorkspace, hermesLegacySkills, legacyCodexSkills, staging: true };
339
+ const ownershipRoots = [stage, ...mappings.map(mapping => mapping.to)];
340
+ const ownershipBefore = captureDeploymentOutputs(ownershipRoots);
333
341
  if (!opts.deferRuleProjection && (opts.kernelOnly || opts.deployRules || opts.rulesOnly ||
334
342
  (!opts.skillsOnly && !opts.commandsOnly && (inlineStartup[provider.name] || ['hermes', 'warp'].includes(provider.name))))) retireInlineStartup(opts, provider);
335
343
  await deploySelectedSurface(opts, provider, deploy);
@@ -422,6 +430,7 @@ export async function prepareRuleDeployment(original, provider, deploy) {
422
430
  console.log(`[dry-run] Planned ${provider.name} deployment: ${guarded.report.selected_bytes} startup bytes; no output promoted.`);
423
431
  return { report: guarded.report, noop: true };
424
432
  }
433
+ recordDeploymentOutputs(ownershipBefore, ownershipRoots, opts);
425
434
  const workspaceDirs = [];
426
435
  const collectDirs = (dir, rel = '') => {
427
436
  if (!fs.existsSync(dir)) return;
@@ -47,6 +47,9 @@ function registerOpenCode(opts, provider, rulesDir) {
47
47
  writeContextFileSync(file, `${JSON.stringify(config, null, 2)}\n`);
48
48
  }
49
49
  export function projectRules(opts, provider) {
50
+ const put = (file, content) => {
51
+ fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, content); opts.writtenFiles?.push(file);
52
+ };
50
53
  const nativePaths = nativePathLoader(provider.name);
51
54
  const rules = projectOnDemandReferences(opts.ruleDelivery.rules, nativePaths);
52
55
  const rulesDir = ruleDirectory(opts, provider);
@@ -59,13 +59,15 @@ export function scanWorkerInvocationProcesses({ invocationId, startTicks, uid =
59
59
  const present = () => ({ ...unknown('same-uid process still carries invocation marker (possible escaped descendant)'), markerPresent: true });
60
60
  const gone = error => ['ENOENT', 'ESRCH'].includes(error.code);
61
61
  let directory, uncertain = null;
62
+ // A time bound must never hide earlier unreadable-process or byte-bound evidence.
63
+ const timedOut = () => uncertain ?? { ...unknown('same-uid invocation-marker scan time bound reached'), timeBoundReached: true };
62
64
  try {
63
65
  directory = fs.opendirSync(procRoot);
64
66
  // Stream entries and cap per-process reads; neither a huge PID set nor
65
67
  // a large environment can turn this proof into an unbounded allocation.
66
68
  const buffer = Buffer.alloc(Math.min(65536, maxEnvironmentBytes + 1));
67
69
  for (let count = 0; ; count++) {
68
- if (now() >= deadline) return unknown('same-uid invocation-marker scan time bound reached');
70
+ if (now() >= deadline) return timedOut();
69
71
  const entry = directory.readSync();
70
72
  if (!entry) return uncertain ?? { confirmed: true, missing: null };
71
73
  if (count >= maxEntries) return unknown('same-uid invocation-marker scan count bound reached');
@@ -79,7 +81,7 @@ export function scanWorkerInvocationProcesses({ invocationId, startTicks, uid =
79
81
  let bytes = 0, tail = '';
80
82
  const decoder = new StringDecoder('utf8');
81
83
  for (;;) {
82
- if (now() >= deadline) return unknown('same-uid invocation-marker scan time bound reached');
84
+ if (now() >= deadline) return timedOut();
83
85
  const size = fs.readSync(fd, buffer, 0, Math.min(buffer.length, maxEnvironmentBytes + 1 - bytes), null);
84
86
  if (!size) break;
85
87
  bytes += size;
@@ -3,9 +3,13 @@ import { sampleWorkerIdentity, isSafeWorkerGroupTarget } from '../process-monito
3
3
  import { getWorkerIsolationStatus } from './worker-isolation-status.mjs';
4
4
  import { scanWorkerInvocationProcesses } from './worker-invocation-processes.mjs';
5
5
 
6
+ const TERMINATION_BUDGET_MS = 2000;
7
+ const TERMINATION_ATTEMPT_MS = 100;
8
+ const TERMINATION_MAX_ATTEMPTS = 21;
9
+
6
10
  export function observeWorkerTermination({ mode, native, workerExited, identity,
7
11
  supervisor = sampleWorkerIdentity(process.pid), kill = process.kill, invocationId,
8
- scan = scanWorkerInvocationProcesses, deadline } = {}) {
12
+ scan = scanWorkerInvocationProcesses, deadline, now = () => performance.now() } = {}) {
9
13
  if (mode === 'systemd-unit') {
10
14
  const exited = workerExited === true || [1, 2, 3].includes(native?.execMainCode);
11
15
  return { confirmed: exited && native?.active === false && native?.cgroupEmpty === true,
@@ -25,7 +29,10 @@ export function observeWorkerTermination({ mode, native, workerExited, identity,
25
29
  // readable stat/cgroup links instead of failing closed on every
26
30
  // unreadable post-start process.
27
31
  if (error.code === 'ESRCH') {
28
- return scan({ invocationId, startTicks: identity.startTicks, uid: identity.uid, deadline,
32
+ // Exit-time callers get one scan, at most 2 s. An explicit deadline
33
+ // leaves the scan budget and retries to the recheck caller.
34
+ return scan({ invocationId, startTicks: identity.startTicks, uid: identity.uid, now,
35
+ deadline: deadline ?? now() + TERMINATION_BUDGET_MS,
29
36
  workerPid: identity.pid, workerPgid: identity.pgid, workerSession: identity.sessionId });
30
37
  }
31
38
  return { confirmed: false, missing: `empty owned process group (signal-0 returned ${error.code ?? 'unknown'})` };
@@ -57,10 +64,10 @@ export async function recheckWorkerTermination({ processRecord, exitRecord,
57
64
  if (processRecord.isolation !== 'systemd-unit' && processRecord.invocationMarker !== processRecord.invocationId) {
58
65
  return { confirmed: false, missing: 'escaped-descendant evidence: launcher-bound invocation marker in process.json' };
59
66
  }
60
- const deadline = now() + 2000;
67
+ const deadline = now() + TERMINATION_BUDGET_MS;
61
68
  // Both elapsed time and sample count bound the check, including injected clocks.
62
69
  let evidence;
63
- for (let attempt = 0; attempt < 21; attempt++) {
70
+ for (let attempt = 0; attempt < TERMINATION_MAX_ATTEMPTS; attempt++) {
64
71
  if (evidence && now() >= deadline) return evidence;
65
72
  let native = null;
66
73
  // Use the unit's retained exit state whenever a unit name is recorded,
@@ -68,15 +75,15 @@ export async function recheckWorkerTermination({ processRecord, exitRecord,
68
75
  // selection is unchanged, but unit (cgroup) evidence is preferred
69
76
  // wherever it is available. Non-unit modes still ignore it below.
70
77
  if (typeof processRecord.unit === 'string' && processRecord.unit !== '') {
71
- try { native = status(processRecord.unit, { timeoutMs: Math.max(1, Math.min(100, deadline - now())) }); }
78
+ try { native = status(processRecord.unit, { timeoutMs: Math.max(1, Math.min(TERMINATION_ATTEMPT_MS, deadline - now())) }); }
72
79
  catch { /* Unavailable is never empty. */ }
73
80
  }
74
81
  evidence = observe({ mode: processRecord.isolation, native, identity, invocationId: processRecord.invocationId,
75
- deadline: Math.min(deadline, now() + 100),
82
+ deadline: Math.min(deadline, now() + TERMINATION_ATTEMPT_MS), now,
76
83
  workerExited: Number.isInteger(exitRecord.exitCode) && exitRecord.exitCode >= 0 && exitRecord.exitCode <= 255
77
84
  || exitRecord.captureCoverage === 'complete' && exitRecord.workerTermination === 'confirmed' && /^SIG[A-Z0-9]+$/.test(exitRecord.signal ?? '') });
78
- if (evidence.confirmed || evidence.markerPresent || now() >= deadline || attempt === 20) return evidence;
79
- await wait(Math.min(100, Math.max(0, deadline - now())));
85
+ if (evidence.confirmed || evidence.markerPresent || now() >= deadline || attempt === TERMINATION_MAX_ATTEMPTS - 1) return evidence;
86
+ await wait(Math.min(TERMINATION_ATTEMPT_MS, Math.max(0, deadline - now())));
80
87
  }
81
88
  return evidence;
82
89
  }
@@ -738,10 +738,8 @@
738
738
  "minimum": 0,
739
739
  "default": 2
740
740
  },
741
- "max_workers": {
742
- "type": "integer",
743
- "minimum": 1
744
- }
741
+ "max_workers": { "type": "integer", "minimum": 1 },
742
+ "max_snapshot_age_seconds": { "type": "number", "exclusiveMinimum": 0, "default": 300 }
745
743
  }
746
744
  }
747
745
  }