@aiwg/cli 2026.10.16 → 2026.10.19

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 (155) hide show
  1. package/agentic/code/providers/capability-matrix.yaml +51 -0
  2. package/agentic/code/providers/flue/README.md +62 -0
  3. package/agentic/code/providers/flue/templates/aiwg/tools.ts +120 -0
  4. package/agentic/code/providers/model-capabilities.v1.json +23 -0
  5. package/agentic/code/providers/model-catalog.v1.json +9 -0
  6. package/dist/src/artifacts/corpus-tools/resolve.js +28 -6
  7. package/dist/src/artifacts/query-engine-corpus.js +217 -0
  8. package/dist/src/artifacts/query-engine-discover-output.js +229 -0
  9. package/dist/src/artifacts/query-engine-discover.js +285 -0
  10. package/dist/src/artifacts/query-engine-entries.js +188 -0
  11. package/dist/src/artifacts/query-engine-index.js +249 -0
  12. package/dist/src/artifacts/query-engine-matching.js +143 -0
  13. package/dist/src/artifacts/query-engine-options.js +2 -0
  14. package/dist/src/artifacts/query-engine-rules.js +202 -0
  15. package/dist/src/artifacts/query-engine-scoring.js +436 -0
  16. package/dist/src/artifacts/query-engine-show-card.js +194 -0
  17. package/dist/src/artifacts/query-engine-show-load.js +211 -0
  18. package/dist/src/artifacts/query-engine-show.js +300 -0
  19. package/dist/src/artifacts/query-engine.js +7 -2576
  20. package/dist/src/cli/handlers/help.js +1 -1
  21. package/dist/src/cli/handlers/init.js +1 -0
  22. package/dist/src/cli/handlers/mc-agents.js +111 -0
  23. package/dist/src/cli/handlers/mc-args.js +54 -0
  24. package/dist/src/cli/handlers/mc-control.js +227 -0
  25. package/dist/src/cli/handlers/mc-dispatch.js +203 -0
  26. package/dist/src/cli/handlers/mc-help.js +171 -0
  27. package/dist/src/cli/handlers/mc-run.js +343 -0
  28. package/dist/src/cli/handlers/mc-session.js +138 -0
  29. package/dist/src/cli/handlers/mc-status.js +258 -0
  30. package/dist/src/cli/handlers/mc-summary.js +43 -0
  31. package/dist/src/cli/handlers/mc-types.js +3 -0
  32. package/dist/src/cli/handlers/mc-worker.js +205 -0
  33. package/dist/src/cli/handlers/mc.js +12 -1665
  34. package/dist/src/cli/handlers/models-refusal.js +13 -0
  35. package/dist/src/cli/handlers/models.js +2 -1
  36. package/dist/src/cli/handlers/remove-bundled.js +133 -0
  37. package/dist/src/cli/handlers/remove-options.js +31 -0
  38. package/dist/src/cli/handlers/remove-user.js +174 -0
  39. package/dist/src/cli/handlers/remove.js +201 -0
  40. package/dist/src/cli/handlers/subcommands-bundles.js +257 -0
  41. package/dist/src/cli/handlers/subcommands-discovery.js +165 -0
  42. package/dist/src/cli/handlers/subcommands-list-format.js +129 -0
  43. package/dist/src/cli/handlers/subcommands-list.js +250 -0
  44. package/dist/src/cli/handlers/subcommands-plugins.js +213 -0
  45. package/dist/src/cli/handlers/subcommands-quickref.js +58 -0
  46. package/dist/src/cli/handlers/subcommands-rlm.js +113 -0
  47. package/dist/src/cli/handlers/subcommands-services.js +66 -0
  48. package/dist/src/cli/handlers/subcommands-storage.js +259 -0
  49. package/dist/src/cli/handlers/subcommands.js +18 -1984
  50. package/dist/src/cli/handlers/use.js +11 -5
  51. package/dist/src/cli/scope-resolver.js +1 -142
  52. package/dist/src/cli/services/deployment-verification.js +3 -0
  53. package/dist/src/cli/user-scope-mirror.js +173 -0
  54. package/dist/src/config/dispatch-host-thresholds.js +2 -0
  55. package/dist/src/config/dispatch-thresholds-runtime.mjs +4 -0
  56. package/dist/src/config/host-resource-report.d.mts +5 -0
  57. package/dist/src/config/host-resource-report.mjs +36 -6
  58. package/dist/src/config/host-resource-runtime.d.mts +3 -0
  59. package/dist/src/config/host-resource-runtime.mjs +9 -6
  60. package/dist/src/decision/ensemble-study/artifacts.js +7 -0
  61. package/dist/src/decision/ensemble-study/gate-policy.js +58 -0
  62. package/dist/src/decision/ensemble-study/gates.js +78 -0
  63. package/dist/src/decision/ensemble-study/protocol.js +18 -21
  64. package/dist/src/decision/ensemble-study/score.js +3 -2
  65. package/dist/src/decision/ensemble-study/statistics.js +7 -26
  66. package/dist/src/decision/sensitivity/comparative-gates.js +135 -0
  67. package/dist/src/decision/sensitivity/comparative.js +18 -41
  68. package/dist/src/extensions/claude-hooks-installer.js +18 -0
  69. package/dist/src/gates/evaluate.js +2 -358
  70. package/dist/src/gates/observations.js +363 -0
  71. package/dist/src/gates/pack-composition.js +270 -0
  72. package/dist/src/gates/pack-tightening.js +197 -0
  73. package/dist/src/gates/pack-validation.js +262 -0
  74. package/dist/src/gates/registry-error.js +5 -0
  75. package/dist/src/gates/registry.js +13 -685
  76. package/dist/src/mcp/json-document.mjs +29 -0
  77. package/dist/src/mcp/muse-native-config.mjs +1 -28
  78. package/dist/src/memory/provider-memory-adapter.js +1 -0
  79. package/dist/src/mission-protocol/worker-review-gate.js +7 -0
  80. package/dist/src/models/model-capabilities.v1.json +23 -0
  81. package/dist/src/models/model-catalog.v1.json +9 -0
  82. package/dist/src/models/policy-resources.js +1 -1
  83. package/dist/src/models/worker-plan.js +5 -5
  84. package/dist/src/plugin/command-ownership.js +34 -0
  85. package/dist/src/plugin/skill-command-frontmatter.js +197 -0
  86. package/dist/src/plugin/skill-command-translator.js +6 -232
  87. package/dist/src/providers/capability-matrix.yaml +51 -0
  88. package/dist/src/providers/context-output-ownership.js +26 -0
  89. package/dist/src/providers/deployment-ownership.d.mts +20 -0
  90. package/dist/src/providers/deployment-ownership.mjs +236 -0
  91. package/dist/src/providers/deployment-removal.js +222 -0
  92. package/dist/src/providers/provider-context-contracts.js +8 -0
  93. package/dist/src/providers/provider-definition-schema.js +1 -0
  94. package/dist/src/providers/provider-definitions.js +1 -0
  95. package/dist/src/providers/provider-seeds-3.js +18 -0
  96. package/dist/src/providers/removal-transaction.js +86 -0
  97. package/dist/src/providers/settings-document.d.mts +3 -0
  98. package/dist/src/providers/settings-document.mjs +47 -0
  99. package/dist/src/providers/settings-removal.js +190 -0
  100. package/dist/src/providers/skill-ownership.d.mts +20 -2
  101. package/dist/src/providers/skill-ownership.mjs +12 -4
  102. package/dist/src/providers/transformation-receipt-integration.js +15 -271
  103. package/dist/src/providers/transformation-receipt-outputs.js +99 -0
  104. package/dist/src/providers/transformation-receipt-source.js +194 -0
  105. package/dist/src/research/identity.js +8 -2
  106. package/dist/src/research/reference-match.js +66 -8
  107. package/dist/src/rules/activation.mjs +15 -6
  108. package/dist/src/rules/core-startup.mjs +2 -2
  109. package/dist/src/serve/mission-conductor.js +4 -0
  110. package/dist/src/serve/mission-summary.js +56 -0
  111. package/dist/src/skills/deployment-ownership.js +2 -2
  112. package/dist/src/skills/deployment-policy.js +9 -0
  113. package/dist/src/smiths/context-pipeline/aiwg-md.js +23 -0
  114. package/dist/src/smiths/context-pipeline/context-file-safety.js +3 -0
  115. package/dist/src/smiths/context-pipeline/flue-context.js +25 -0
  116. package/dist/src/smiths/context-pipeline/generator.js +7 -2
  117. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +9 -7
  118. package/dist/src/smiths/hook-bridge/index.js +9 -0
  119. package/package.json +5 -1
  120. package/schemas/decision/D17StudyProtocol.v1.schema.json +39 -67
  121. package/tools/agents/deploy-agents.mjs +21 -680
  122. package/tools/agents/deploy-command-mirrors.mjs +229 -0
  123. package/tools/agents/deploy-options.mjs +267 -0
  124. package/tools/agents/deploy-support.mjs +165 -0
  125. package/tools/agents/providers/base-addon-discovery.mjs +139 -0
  126. package/tools/agents/providers/base-behaviors.mjs +168 -0
  127. package/tools/agents/providers/base-context.mjs +205 -0
  128. package/tools/agents/providers/base-contract.mjs +116 -0
  129. package/tools/agents/providers/base-files.mjs +252 -0
  130. package/tools/agents/providers/base-flat-artifacts.mjs +233 -0
  131. package/tools/agents/providers/base-framework-discovery.mjs +309 -0
  132. package/tools/agents/providers/base-frontmatter.mjs +196 -0
  133. package/tools/agents/providers/base-inventory.mjs +269 -0
  134. package/tools/agents/providers/base-kernel-skills.mjs +354 -0
  135. package/tools/agents/providers/base-migrations.mjs +258 -0
  136. package/tools/agents/providers/base-models-platforms.mjs +273 -0
  137. package/tools/agents/providers/base-rule-index.mjs +450 -0
  138. package/tools/agents/providers/base-runtime.mjs +60 -0
  139. package/tools/agents/providers/base-skill-copy.mjs +273 -0
  140. package/tools/agents/providers/base.mjs +16 -3364
  141. package/tools/agents/providers/claude-post-deploy.mjs +10 -2
  142. package/tools/agents/providers/flue-project.mjs +79 -0
  143. package/tools/agents/providers/flue-specialists.mjs +64 -0
  144. package/tools/agents/providers/flue.mjs +50 -0
  145. package/tools/agents/providers/hermes-startup.mjs +0 -5
  146. package/tools/agents/providers/muse.mjs +7 -2
  147. package/tools/agents/providers/rule-delivery-surface.mjs +33 -5
  148. package/tools/agents/providers/rule-deployment-commit.mjs +19 -15
  149. package/tools/agents/providers/rule-deployment-prepare.mjs +13 -3
  150. package/tools/agents/providers/rule-projection.mjs +3 -0
  151. package/tools/agents/providers/rule-startup.mjs +3 -3
  152. package/tools/agents/use-rule-selection.mjs +17 -0
  153. package/tools/ralph-external/lib/worker-invocation-processes.mjs +4 -2
  154. package/tools/ralph-external/lib/worker-termination.mjs +15 -8
  155. 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);
@@ -0,0 +1,79 @@
1
+ // Select only Flue's conventional database module and preserve operator modules.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+
6
+ const exists = file => { try { fs.lstatSync(file); return true; } catch (error) { if (error.code === 'ENOENT') return false; throw error; } };
7
+ const directory = file => exists(file) && fs.lstatSync(file).isDirectory();
8
+ const databaseFiles = () => ['.flue', 'src', ''].flatMap(dir => ['ts', 'mts', 'js', 'mjs'].map(ext => path.join(dir, `db.${ext}`)));
9
+ // Flue 2.3.0: @flue/runtime/dist/config.mjs:91-98,113-116 (first existing wins).
10
+ const configFiles = ['ts', 'mts', 'mjs', 'js', 'cjs', 'cts'].map(ext => `flue.config.${ext}`);
11
+ export function flueDeploymentFiles(target) {
12
+ const source = ['.flue', 'src'].find(dir => directory(path.join(target, dir))) || 'src';
13
+ // Snapshot config and conventional entries too: deployment reads a staged project.
14
+ return [...new Set([path.join(source, 'db.ts'), '.gitignore', 'src/aiwg/tools.ts', 'src/aiwg/specialists.ts',
15
+ ...configFiles, ...databaseFiles()])];
16
+ }
17
+ function explicitDatabase(target) {
18
+ const config = configFiles.find(file => exists(path.join(target, file)));
19
+ if (!config) return;
20
+ // Static tokens only; comments and string/template contents cannot become keys.
21
+ const tokens = fs.readFileSync(path.join(target, config), 'utf8').match(/\/\*[\s\S]*?\*\/|\/\/[^\r\n]*|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|`(?:\\.|[^`\\])*`|[A-Za-z_$][\w$]*|[^\s]/g) || [];
22
+ const code = tokens.filter(token => !token.startsWith('//') && !token.startsWith('/*'));
23
+ let start = code.findIndex((token, index) => token === 'export' && code[index + 1] === 'default');
24
+ if (start >= 0) start += 2;
25
+ else {
26
+ start = code.findIndex((token, index) => token === 'module' && code.slice(index + 1, index + 4).join('') === '.exports=');
27
+ if (start < 0) return;
28
+ start += 4;
29
+ }
30
+ // Accept a literal default export, optionally parenthesized or wrapped in defineConfig.
31
+ if (code[start] === 'defineConfig' && code[start + 1] === '(') start += 2;
32
+ while (code[start] === '(') start++;
33
+ if (code[start] !== '{') return;
34
+ const nesting = [];
35
+ for (let index = start; index < code.length; index++) {
36
+ const token = code[index];
37
+ if (nesting.length === 1 && ['db', '"db"', "'db'"].includes(token)
38
+ && ['{', ','].includes(code[index - 1]) && code[index + 1] === ':') return config;
39
+ if (['{', '[', '('].includes(token)) nesting.push(token);
40
+ else if (['}', ']', ')'].includes(token)) {
41
+ nesting.pop();
42
+ if (!nesting.length) break;
43
+ }
44
+ }
45
+ }
46
+ export function claimRecordedFile(target, file, opts) {
47
+ if (!exists(file)) return false;
48
+ let record;
49
+ try { record = JSON.parse(fs.readFileSync(path.join(target, '.aiwg/.aiwg-manifest.json'), 'utf8')).managed?.[path.relative(target, file).split(path.sep).join('/')]; }
50
+ catch { return false; }
51
+ const hash = `sha256:${createHash('sha256').update(fs.readFileSync(file)).digest('hex')}`;
52
+ if (!record?.filePreimage || record.hash !== hash) return false;
53
+ opts.writtenFiles?.push(file);
54
+ return true;
55
+ }
56
+ export function deployFlueDatabase(target, opts) {
57
+ const config = explicitDatabase(target);
58
+ if (config) {
59
+ console.warn(`Flue (experimental): keeping explicit db entry in ${config}; verify the operator module selects durable SQLite at .flue-state/state.db.`);
60
+ return;
61
+ }
62
+ const relative = opts.flueDatabaseFile || flueDeploymentFiles(target)[0];
63
+ const file = path.join(target, relative);
64
+ // All conventional operator database formats take precedence over generation.
65
+ const operator = databaseFiles().map(name => path.join(target, name))
66
+ .find(exists);
67
+ if (operator && !claimRecordedFile(target, operator, opts)) console.warn(`Flue (experimental): keeping existing database module ${opts.logicalOutputPath?.(operator) || operator}; verify it selects durable SQLite at .flue-state/state.db.`);
68
+ else if (!operator && !opts.dryRun) {
69
+ fs.mkdirSync(path.dirname(file), { recursive: true });
70
+ const state = path.relative(path.dirname(file), path.join(target, '.flue-state/state.db')).split(path.sep).join('/');
71
+ fs.writeFileSync(file, `import { sqlite } from '@flue/runtime/node';\nimport { fileURLToPath } from 'node:url';\n\nexport default sqlite(fileURLToPath(new URL(${JSON.stringify(state)}, import.meta.url)));\n`);
72
+ }
73
+ const ignore = path.join(target, '.gitignore');
74
+ claimRecordedFile(target, ignore, opts);
75
+ const before = exists(ignore) ? fs.readFileSync(ignore, 'utf8') : '';
76
+ if (!before.split(/\r?\n/).some(line => line.trim().replace(/^\//, '').replace(/\/\*{0,2}$/, '') === '.flue-state') && !opts.dryRun) {
77
+ fs.writeFileSync(ignore, `${before}${before && !before.endsWith('\n') ? '\n' : ''}.flue-state/\n`);
78
+ }
79
+ }
@@ -0,0 +1,64 @@
1
+ // Generate the fixed Flue delegates from canonical agents and shared rule transforms.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { resolveAiwgRoot } from './base-inventory.mjs';
6
+ import { parseFrontmatter } from './base-frontmatter.mjs';
7
+ import { injectBoundRules } from './base-contract.mjs';
8
+ import { claimRecordedFile } from './flue-project.mjs';
9
+
10
+ export const FLUE_SPECIALISTS = Object.freeze([
11
+ Object.freeze({ name: 'code-reviewer', exportName: 'codeReviewer', file: 'code-reviewer.md' }),
12
+ Object.freeze({ name: 'test-engineer', exportName: 'testEngineer', file: 'test-engineer.md' }),
13
+ ]);
14
+
15
+ export function generateFlueSpecialists(opts) {
16
+ const root = resolveAiwgRoot(opts.srcRoot);
17
+ const framework = root ? path.join(root, 'agentic/code/frameworks/sdlc-complete') : opts.srcRoot;
18
+ const definitions = FLUE_SPECIALISTS.map(specialist => {
19
+ const logical = path.join(framework, 'agents', specialist.file);
20
+ const file = opts.mapInputPath?.(logical) || logical;
21
+ const { body, metadata } = parseFrontmatter(injectBoundRules(fs.readFileSync(file, 'utf8'), file, opts));
22
+ return `export const ${specialist.exportName} = defineSubagent({
23
+ name: ${JSON.stringify(specialist.name)},
24
+ description: ${JSON.stringify(metadata.description || metadata.name)},
25
+ agent() {
26
+ useTool(aiwg_discover);
27
+ useTool(aiwg_show);
28
+ useTool(aiwg_artifact_write);
29
+ return ${JSON.stringify(body.trim())};
30
+ },
31
+ });`;
32
+ });
33
+ return `// Curated AIWG delegates; regenerate from canonical sdlc-complete agents.
34
+ import { defineSubagent, useSubagent, useTool } from '@flue/runtime';
35
+ import { aiwg_discover, aiwg_show, aiwg_artifact_write } from './tools.ts';
36
+
37
+ ${definitions.join('\n\n')}
38
+
39
+ /** Trusted app options: omit pins to inherit the app model and effort. */
40
+ export function useAiwgSpecialists(pins: { codeReviewer?: string; testEngineer?: string } = {}) {
41
+ ${FLUE_SPECIALISTS.map(({ exportName }) => ` useSubagent(pins.${exportName} === undefined ? ${exportName} : { ...${exportName}, model: pins.${exportName} });`).join('\n')}
42
+ }
43
+ `;
44
+ }
45
+
46
+ export function deployFlueSpecialists(target, opts) {
47
+ // Preserve operator files even on --force. Unchanged managed outputs can refresh.
48
+ const write = (relative, content) => {
49
+ const file = path.join(target, relative);
50
+ if (fs.lstatSync(file, { throwIfNoEntry: false })) {
51
+ if (!claimRecordedFile(target, file, opts)) {
52
+ console.warn(`Flue (experimental): keeping existing module ${opts.logicalOutputPath?.(file) || file}`);
53
+ return;
54
+ }
55
+ }
56
+ if (!opts.dryRun) {
57
+ fs.mkdirSync(path.dirname(file), { recursive: true });
58
+ fs.writeFileSync(file, content());
59
+ }
60
+ };
61
+ const template = fileURLToPath(new URL('../../../agentic/code/providers/flue/templates/aiwg/tools.ts', import.meta.url));
62
+ write('src/aiwg/tools.ts', () => fs.readFileSync(opts.mapInputPath?.(template) || template, 'utf8'));
63
+ write('src/aiwg/specialists.ts', () => generateFlueSpecialists(opts));
64
+ }
@@ -0,0 +1,50 @@
1
+ // Deploy the experimental Flue app target through shared skills and context owners.
2
+ import path from 'node:path';
3
+ import { importImpl } from '../../_resolve-impl.mjs';
4
+ import { collectFrameworkArtifacts, deploySkillsWithKernelRouting, getAddonSkillDirs,
5
+ isKernelSkill, normalizeDeploymentMode, withRuleDeployment } from './base.mjs';
6
+ import { flueDeploymentFiles, deployFlueDatabase } from './flue-project.mjs';
7
+ import { deployFlueSpecialists } from './flue-specialists.mjs';
8
+ export { FLUE_SPECIALISTS } from './flue-specialists.mjs';
9
+ const { generate } = await importImpl(import.meta.url, 'smiths/context-pipeline/generator.js');
10
+
11
+ export const name = 'flue';
12
+ export const aliases = [];
13
+ export const paths = { agents: '', commands: '', skills: '.agents/skills', rules: '.agents/.aiwg/rules' };
14
+ export const kernelSkillsPath = '.agents/skills';
15
+ export const capabilities = { skills: true, rules: false, aggregatedOutput: false, homeDirectoryDeploy: false };
16
+ export const support = { agents: 'indexed', commands: 'indexed', skills: 'native', rules: 'context' };
17
+ export const deploymentFiles = flueDeploymentFiles;
18
+ export const mapModel = value => value;
19
+ export const getFileExtension = () => '.md';
20
+ export const deployAgents = () => 0;
21
+ export const deployCommands = () => 0;
22
+ export const deployRules = () => 0;
23
+
24
+ export function deploySkills(skillDirs, target, opts) {
25
+ // Flue has no legacy bulk mirror. Limit cleanup to its selected kernel set
26
+ // so another provider's mirrors and operator standard skills stay untouched.
27
+ return deploySkillsWithKernelRouting(skillDirs.filter(isKernelSkill), null,
28
+ path.join(target, kernelSkillsPath), { ...opts, copyStandardSkills: false });
29
+ }
30
+
31
+ export async function postDeploy(target, opts) {
32
+ deployFlueDatabase(target, opts);
33
+ deployFlueSpecialists(target, opts);
34
+ if (opts.contextFiles !== false) await generate({ provider: name, projectPath: target, sections: [], detectExistingFiles: true });
35
+ }
36
+
37
+ export async function deploy(opts) {
38
+ if (opts.userScope) throw new Error('Flue (experimental) supports project scope only.');
39
+ return withRuleDeployment({ ...opts, provider: name }, provider, async staged => {
40
+ const mode = normalizeDeploymentMode(staged.mode);
41
+ const skills = [...getAddonSkillDirs(staged.srcRoot),
42
+ ...collectFrameworkArtifacts(staged.srcRoot, mode, { includeAgents: false, includeCommands: false, includeSkills: true, includeRules: false }).skills];
43
+ const count = deploySkills(skills, staged.target, staged);
44
+ await postDeploy(staged.target, staged);
45
+ return count.kernel;
46
+ });
47
+ }
48
+ const provider = { name, aliases, paths, kernelSkillsPath, capabilities, support, deploymentFiles,
49
+ mapModel, getFileExtension, deployAgents, deployCommands, deployRules, deploySkills, postDeploy, deploy };
50
+ export default provider;
@@ -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,10 +178,28 @@ 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))];
183
- const indexRel = provider.name === 'copilot' ? '.github/RULES-BOUND.md' : `.${provider.name}/RULES-BOUND.md`;
202
+ const indexRel = provider.name === 'copilot' ? '.github/RULES-BOUND.md' : provider.name === 'flue' ? '.agents/.aiwg/RULES-BOUND.md' : `.${provider.name}/RULES-BOUND.md`;
184
203
  const indexFile = path.join(opts.target, indexRel);
185
204
  const anchor = target => `${target.type}-${target.name}`.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
186
205
  const sections = new Map();
@@ -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
 
@@ -241,6 +268,7 @@ export function finishBindings(opts, provider) {
241
268
  /** Bindings annotate the selected deployment; they do not select standard skills
242
269
  * (ADR lines 102–108). Flow projections follow the same opt-in and tier routing. */
243
270
  export function projectBoundFlowSkills(opts, provider, selected) {
271
+ if (provider.name === 'flue') return; // This app target deploys kernel skills only (#3121).
244
272
  opts.flowSkillSources = new Map();
245
273
  if (opts.rulesOnly || opts.commandsOnly || !(opts.deploySkills || opts.skillsOnly)) return;
246
274
  const kernel = path.isAbsolute(provider.kernelSkillsPath || '') ? opts.kernelSkillsPath
@@ -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
@@ -220,6 +222,7 @@ export async function prepareRuleDeployment(original, provider, deploy) {
220
222
  fs.mkdirSync(path.join(stage, '.aiwg'), { recursive: true });
221
223
  if (fs.existsSync(projectSnapshot)) materializeInput(projectSnapshot, path.join(stage, '.aiwg', 'aiwg.config'));
222
224
  const rootNames = ['opencode.json', ...GENERATED_CONTEXT_NAMES, ...OPERATOR_CONTEXT_NAMES, '.aiwg/frameworks/registry.json'];
225
+ if (provider.deploymentFiles) rootNames.push(...provider.deploymentFiles(target));
223
226
  if (provider.name === 'windsurf') rootNames.push('.windsurfrules');
224
227
  for (const framework of getFrameworksForMode(original.srcRoot, original.mode)) {
225
228
  for (const entry of framework.manifest?.memory?.creates || []) {
@@ -229,6 +232,10 @@ export async function prepareRuleDeployment(original, provider, deploy) {
229
232
  if (!rootNames.includes(safe)) rootNames.push(safe);
230
233
  }
231
234
  }
235
+ for (const name of [...rootNames]) {
236
+ const sidecar = path.join(path.dirname(name) === '.' ? '.aiwg' : path.dirname(name), '.aiwg-manifest.json');
237
+ if (!rootNames.includes(sidecar)) rootNames.push(sidecar);
238
+ }
232
239
  preimages.push(...snapshotPreimages(rootNames.map(name => path.join(target, name))));
233
240
  for (const name of rootNames) {
234
241
  const from = path.join(target, name), to = path.join(stage, name);
@@ -328,8 +335,10 @@ export async function prepareRuleDeployment(original, provider, deploy) {
328
335
  }
329
336
  delivery.bindings = remappedBindings;
330
337
  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),
332
- kernelSkillsPath: kernel, deploymentHome: home, activeWorkspace, hermesLegacySkills, legacyCodexSkills, staging: true };
338
+ const opts = { ...original, writeReceipt: writeContextFileSync, writtenFiles: [], target: stage, dryRun: false, ruleDelivery: delivery, logicalOutputPath: file => logicalProviderOutputPath(file, stage, target, mappings),
339
+ flueDatabaseFile: provider.name === 'flue' ? provider.deploymentFiles(target)[0] : undefined, kernelSkillsPath: kernel, deploymentHome: home, activeWorkspace, hermesLegacySkills, legacyCodexSkills, staging: true };
340
+ const ownershipRoots = [stage, ...mappings.map(mapping => mapping.to)];
341
+ const ownershipBefore = captureDeploymentOutputs(ownershipRoots);
333
342
  if (!opts.deferRuleProjection && (opts.kernelOnly || opts.deployRules || opts.rulesOnly ||
334
343
  (!opts.skillsOnly && !opts.commandsOnly && (inlineStartup[provider.name] || ['hermes', 'warp'].includes(provider.name))))) retireInlineStartup(opts, provider);
335
344
  await deploySelectedSurface(opts, provider, deploy);
@@ -422,6 +431,7 @@ export async function prepareRuleDeployment(original, provider, deploy) {
422
431
  console.log(`[dry-run] Planned ${provider.name} deployment: ${guarded.report.selected_bytes} startup bytes; no output promoted.`);
423
432
  return { report: guarded.report, noop: true };
424
433
  }
434
+ recordDeploymentOutputs(ownershipBefore, ownershipRoots, opts);
425
435
  const workspaceDirs = [];
426
436
  const collectDirs = (dir, rel = '') => {
427
437
  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);
@@ -14,7 +14,7 @@ const bootstrap = [
14
14
  ].join('\n');
15
15
  const read = file => fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
16
16
  export const inlineStartup = {
17
- codex: 'AGENTS.md', pi: 'AGENTS.md', hermes: 'AGENTS.md', warp: 'WARP.md',
17
+ codex: 'AGENTS.md', flue: 'AGENTS.md', pi: 'AGENTS.md', hermes: 'AGENTS.md', warp: 'WARP.md',
18
18
  copilot: '.github/copilot-instructions.md', factory: 'AGENTS.md', opencode: 'AGENTS.md',
19
19
  windsurf: 'AGENTS.md', antigravity: 'AGENTS.md', muse: 'AGENTS.md',
20
20
  omp: '.omp/AGENTS.md', 'grok-build': 'AGENTS.md',
@@ -57,8 +57,8 @@ export function projectStartup(opts, provider, coreSection, indexFile) {
57
57
  retireInlineStartup(opts, provider, file);
58
58
  const files = provider.name === 'hermes' ? [file, path.join(opts.target, '.hermes.md')] : [file];
59
59
  for (const startup of files) {
60
- let content = normalizeRuleStartup(read(startup), bootstrap, path.basename(startup) === 'AGENTS.md');
61
- content = section(content, 'rule-core', coreSection.replace(/<!-- AIWG:(?:core-rules|rule-core):(?:start|end) -->\n?/g, '').trimEnd());
60
+ let content = provider.name === 'flue' ? read(startup) : normalizeRuleStartup(read(startup), bootstrap, path.basename(startup) === 'AGENTS.md');
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
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.`;
@@ -0,0 +1,17 @@
1
+ // Carry use's requested frameworks through additive passes without recording an installation.
2
+ import { getFrameworksForMode, resolveAiwgRoot } from './providers/base.mjs';
3
+ import { importImpl } from '../_resolve-impl.mjs';
4
+
5
+ const { loadRulePinConfigs } = await importImpl(import.meta.url, 'rules/pins.mjs');
6
+
7
+ export function useRuleSelectionConfig(cfg, srcRoot) {
8
+ if (!cfg.ruleSelectionMode || cfg.kernelOnly) return undefined;
9
+ const root = resolveAiwgRoot(srcRoot) || srcRoot;
10
+ const frameworks = getFrameworksForMode(root, cfg.ruleSelectionMode);
11
+ if (!frameworks.length) return undefined;
12
+ const { project } = loadRulePinConfigs(cfg.target);
13
+ // Existing install metadata and operator pins win; provisional entries exist
14
+ // only in this projector's config snapshot and are never written to disk.
15
+ const installed = Object.fromEntries(frameworks.map(framework => [framework.id, { source: 'bundled' }]));
16
+ return { ...project, installed: { ...installed, ...project.installed } };
17
+ }
@@ -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
  }