@aiwg/cli 2026.11.1 → 2026.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (108) 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/model-capabilities.v1.json +27 -23
  4. package/agentic/code/providers/model-catalog.v1.json +3 -3
  5. package/dist/src/artifacts/cli.js +10 -11
  6. package/dist/src/artifacts/discover-cli-help.js +25 -0
  7. package/dist/src/artifacts/discover-session-facets.js +2 -1
  8. package/dist/src/artifacts/fortemi-core-prebuilt-freshness.js +28 -0
  9. package/dist/src/artifacts/fortemi-core-sync.js +3 -0
  10. package/dist/src/artifacts/framework-capabilities.js +4 -0
  11. package/dist/src/artifacts/framework-source-digest.js +1 -1
  12. package/dist/src/artifacts/index-builder.js +10 -10
  13. package/dist/src/artifacts/index-dependencies.js +72 -0
  14. package/dist/src/artifacts/query-engine-discover-output.js +13 -5
  15. package/dist/src/artifacts/query-engine-discover.js +49 -21
  16. package/dist/src/artifacts/query-engine-entries.js +56 -2
  17. package/dist/src/artifacts/query-engine-options.js +14 -1
  18. package/dist/src/artifacts/query-engine-scoring.js +8 -4
  19. package/dist/src/artifacts/query-engine-show-card.js +2 -0
  20. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  21. package/dist/src/artifacts/query-engine-show.js +3 -1
  22. package/dist/src/artifacts/query-engine-templates.js +33 -0
  23. package/dist/src/artifacts/query-engine-verbose.js +25 -0
  24. package/dist/src/artifacts/relations-builder.js +49 -4
  25. package/dist/src/artifacts/relations.js +9 -0
  26. package/dist/src/artifacts/template-references.js +42 -0
  27. package/dist/src/artifacts/types.js +1 -1
  28. package/dist/src/cli/handlers/bundle-reconciliation.js +7 -3
  29. package/dist/src/cli/handlers/checkpoint-handoff.js +48 -0
  30. package/dist/src/cli/handlers/checkpoint-record.js +20 -0
  31. package/dist/src/cli/handlers/checkpoint.js +50 -17
  32. package/dist/src/cli/handlers/decision.js +1 -1
  33. package/dist/src/cli/handlers/doctor-args.js +3 -1
  34. package/dist/src/cli/handlers/doctor-help.js +2 -1
  35. package/dist/src/cli/handlers/help.js +1 -1
  36. package/dist/src/cli/handlers/refresh-bundles.js +2 -1
  37. package/dist/src/cli/handlers/refresh-managed-deployment.js +196 -0
  38. package/dist/src/cli/handlers/refresh.js +10 -2
  39. package/dist/src/cli/handlers/subcommands-discovery.js +8 -1
  40. package/dist/src/cli/handlers/use.js +10 -3
  41. package/dist/src/cli/services/deployment-verification.js +11 -7
  42. package/dist/src/config/worker-write.js +4 -10
  43. package/dist/src/decision/ledger.js +15 -15
  44. package/dist/src/decision/offload.js +6 -7
  45. package/dist/src/delivery/pr.js +2 -0
  46. package/dist/src/delivery/template-sections.js +56 -0
  47. package/dist/src/extensions/claude-hooks-installer.js +61 -53
  48. package/dist/src/extensions/managed-hook-script-state.js +48 -0
  49. package/dist/src/extensions/muse-managed-hooks.js +49 -0
  50. package/dist/src/issues/cli.js +3 -0
  51. package/dist/src/issues/external-cli.js +4 -1
  52. package/dist/src/issues/live.js +9 -2
  53. package/dist/src/issues/local.js +5 -1
  54. package/dist/src/issues/tracker-policy.js +11 -1
  55. package/dist/src/mcp/json-document.d.mts +2 -0
  56. package/dist/src/models/model-capabilities.v1.json +27 -23
  57. package/dist/src/models/model-catalog.v1.json +3 -3
  58. package/dist/src/models/provider-policy.js +8 -0
  59. package/dist/src/models/worker-health-readiness.js +20 -4
  60. package/dist/src/models/worker-health-snapshot.js +29 -0
  61. package/dist/src/models/worker-installation.d.mts +5 -1
  62. package/dist/src/models/worker-installation.mjs +11 -5
  63. package/dist/src/models/worker-qualification-policy.js +54 -0
  64. package/dist/src/providers/skill-ownership.d.mts +1 -0
  65. package/dist/src/providers/transformation-receipt-integration.js +4 -2
  66. package/dist/src/providers/transformation-receipt.js +4 -2
  67. package/dist/src/serve/worker-invocation.js +4 -2
  68. package/dist/src/smiths/context-pipeline/workspace-audit.js +34 -17
  69. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +12 -6
  70. package/dist/src/smiths/context-pipeline/workspace-doctor.js +44 -4
  71. package/dist/src/smiths/context-pipeline/workspace-document.js +5 -2
  72. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -1
  73. package/dist/src/smiths/hook-bridge/codex-translator.js +150 -94
  74. package/dist/src/smiths/hook-bridge/codex-trust.js +50 -0
  75. package/dist/src/smiths/hook-bridge/factory-hook-config.js +132 -0
  76. package/dist/src/smiths/hook-bridge/factory-translator.js +88 -33
  77. package/dist/src/smiths/hook-bridge/index.js +3 -3
  78. package/dist/src/smiths/hook-bridge/loader.js +10 -2
  79. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +0 -1
  80. package/dist/src/storage/workspace-permissions-health.js +64 -0
  81. package/dist/src/storage/workspace-permissions.js +51 -0
  82. package/package.json +6 -1
  83. package/tools/agents/providers/base-files.mjs +2 -1
  84. package/tools/agents/providers/base-flat-artifacts.mjs +6 -3
  85. package/tools/agents/providers/base-models-platforms.mjs +3 -3
  86. package/tools/agents/providers/base-skill-copy.mjs +2 -0
  87. package/tools/agents/providers/bound-rules-pointer.mjs +21 -0
  88. package/tools/agents/providers/claude-post-deploy.mjs +9 -5
  89. package/tools/agents/providers/codex-post-deploy.mjs +10 -0
  90. package/tools/agents/providers/factory-hooks.mjs +43 -0
  91. package/tools/agents/providers/factory.mjs +4 -91
  92. package/tools/agents/providers/muse-hooks.mjs +4 -43
  93. package/tools/agents/providers/muse-prompt-discovery.mjs +3 -7
  94. package/tools/agents/providers/packaged-codex-agents.mjs +48 -0
  95. package/tools/agents/providers/rule-delivery-surface.mjs +4 -4
  96. package/tools/agents/providers/rule-presentation.mjs +6 -5
  97. package/tools/agents/providers/rule-projection.mjs +10 -2
  98. package/tools/agents/providers/rule-startup.mjs +8 -1
  99. package/tools/cli/decision-offload-report.mjs +7 -2
  100. package/tools/plugin/issue-template-copies.mjs +24 -0
  101. package/tools/plugin/package-plugins.mjs +11 -3
  102. package/tools/ralph-external/lib/factory-adapter.mjs +7 -8
  103. package/tools/ralph-external/lib/worker-artifacts.mjs +4 -2
  104. package/tools/ralph-external/lib/worker-final.mjs +43 -8
  105. package/tools/ralph-external/lib/worker-launch-cli.mjs +10 -1
  106. package/tools/ralph-external/lib/worker-prompt.mjs +35 -0
  107. package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +8 -0
  108. package/tools/ralph-external/session-launcher.mjs +10 -7
@@ -0,0 +1,132 @@
1
+ // Merge Factory hook documents without replacing operator registrations.
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import { randomUUID } from 'node:crypto';
5
+ import { parseJson } from '../../mcp/json-document.mjs';
6
+ // droid reads hooks.json as a top-level event map; only settings.json nests events under `hooks`.
7
+ // Earlier AIWG releases wrote the nested shape into hooks.json, which droid ignored, so read both.
8
+ function isHooksFile(file) {
9
+ return path.basename(file) === 'hooks.json';
10
+ }
11
+ function fromHooksFile(raw) {
12
+ const doc = {};
13
+ const events = {};
14
+ for (const [key, value] of Object.entries(raw)) {
15
+ if (Array.isArray(value))
16
+ events[key] = value;
17
+ else if (key !== 'hooks')
18
+ doc[key] = value;
19
+ }
20
+ const nested = raw.hooks;
21
+ if (nested !== undefined) {
22
+ if (!nested || typeof nested !== 'object' || Array.isArray(nested))
23
+ return { ...doc, hooks: nested };
24
+ for (const [event, groups] of Object.entries(nested)) {
25
+ events[event] = Array.isArray(events[event]) && Array.isArray(groups) ? [...events[event], ...groups] : groups;
26
+ }
27
+ }
28
+ if (Object.keys(events).length)
29
+ doc.hooks = events;
30
+ return doc;
31
+ }
32
+ export function readFactoryDocument(file) {
33
+ try {
34
+ const raw = parseJson(fs.readFileSync(file, 'utf8'));
35
+ const doc = raw && typeof raw === 'object' && !Array.isArray(raw) && isHooksFile(file) ? fromHooksFile(raw) : raw;
36
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)
37
+ || (doc.hooks !== undefined && (!doc.hooks || typeof doc.hooks !== 'object' || Array.isArray(doc.hooks)))) {
38
+ throw new Error(`Invalid Factory hooks object: ${file}`);
39
+ }
40
+ for (const groups of Object.values(doc.hooks ?? {})) {
41
+ if (!Array.isArray(groups) || groups.some(group => !group || !Array.isArray(group.hooks)
42
+ || group.hooks.some(hook => !hook || typeof hook !== 'object'))) {
43
+ throw new Error(`Invalid Factory matcher groups: ${file}`);
44
+ }
45
+ }
46
+ return doc;
47
+ }
48
+ catch (error) {
49
+ if (error.code === 'ENOENT')
50
+ return {};
51
+ throw error;
52
+ }
53
+ }
54
+ export function writeFactoryDocument(file, doc) {
55
+ const { hooks, ...rest } = doc;
56
+ const content = JSON.stringify(isHooksFile(file) ? { ...rest, ...(hooks ?? {}) } : doc, null, 2) + '\n';
57
+ if (fs.existsSync(file) && fs.readFileSync(file, 'utf8') === content)
58
+ return;
59
+ if (fs.existsSync(file)) {
60
+ const original = fs.readFileSync(file, 'utf8');
61
+ if (original !== JSON.stringify(parseJson(original), null, 2) + '\n') {
62
+ fs.copyFileSync(file, `${file}.aiwg-backup-${randomUUID()}`);
63
+ }
64
+ }
65
+ fs.mkdirSync(path.dirname(file), { recursive: true });
66
+ const temporary = `${file}.tmp.${randomUUID()}`;
67
+ try {
68
+ fs.writeFileSync(temporary, content, { flag: 'wx' });
69
+ fs.renameSync(temporary, file);
70
+ }
71
+ finally {
72
+ fs.rmSync(temporary, { force: true });
73
+ }
74
+ }
75
+ export function isFactoryManaged(hook) {
76
+ return hook._aiwg_managed === true || /^aiwg (?:sync|refresh) --dry-run --quiet$/.test(hook.command ?? '');
77
+ }
78
+ export function removeFactoryManaged(doc, id) {
79
+ let changed = false;
80
+ for (const [event, groups] of Object.entries(doc.hooks ?? {})) {
81
+ doc.hooks[event] = groups.flatMap(group => {
82
+ const hooks = group.hooks.filter(hook => !(isFactoryManaged(hook)
83
+ && (!id || hook._aiwg_id === id || (id === 'aiwg-session' && /^aiwg (?:sync|refresh) --dry-run --quiet$/.test(hook.command ?? '')))));
84
+ if (hooks.length === group.hooks.length)
85
+ return [group];
86
+ changed = true;
87
+ return hooks.length ? [{ ...group, hooks }] : [];
88
+ });
89
+ if (!doc.hooks[event].length)
90
+ delete doc.hooks[event];
91
+ }
92
+ if (doc.hooks && !Object.keys(doc.hooks).length)
93
+ delete doc.hooks;
94
+ return changed;
95
+ }
96
+ /** Read all migration inputs before writes; retain user fallback hooks once shadowed. */
97
+ export function factoryHookDocuments(directory) {
98
+ const file = path.join(directory, 'hooks.json');
99
+ const legacyFile = path.join(directory, 'hooks/hooks.json');
100
+ const settingsFile = path.join(directory, 'settings.json');
101
+ const doc = readFactoryDocument(file);
102
+ const legacy = readFactoryDocument(legacyFile);
103
+ const settings = readFactoryDocument(settingsFile);
104
+ for (const [key, value] of Object.entries(legacy))
105
+ if (key !== 'hooks' && !(key in doc))
106
+ doc[key] = value;
107
+ doc.hooks ??= {};
108
+ const managedSettings = { hooks: Object.fromEntries(Object.entries(settings.hooks ?? {})
109
+ .map(([event, groups]) => [event, groups.flatMap(group => {
110
+ const hooks = group.hooks.filter(isFactoryManaged);
111
+ return hooks.length ? [{ ...group, hooks }] : [];
112
+ })])) };
113
+ const fallback = !fs.existsSync(file) && !fs.existsSync(legacyFile);
114
+ for (const input of [legacy, fallback ? settings : managedSettings]) {
115
+ for (const [event, groups] of Object.entries(input.hooks ?? {})) {
116
+ const target = doc.hooks[event] ??= [];
117
+ for (const group of groups)
118
+ if (!target.some(entry => JSON.stringify(entry) === JSON.stringify(group)))
119
+ target.push(group);
120
+ }
121
+ }
122
+ const migratedSettings = removeFactoryManaged(settings);
123
+ return { file, doc, legacyFile, settingsFile, settings, migratedSettings };
124
+ }
125
+ export function saveFactoryHooks(state) {
126
+ // Commit the active hook document before removing legacy registrations.
127
+ writeFactoryDocument(state.file, state.doc);
128
+ if (state.migratedSettings)
129
+ writeFactoryDocument(state.settingsFile, state.settings);
130
+ fs.rmSync(state.legacyFile, { force: true });
131
+ }
132
+ //# sourceMappingURL=factory-hook-config.js.map
@@ -1,43 +1,98 @@
1
- /**
2
- * Factory hook translator — emits per-droid hook scripts that use
3
- * $FACTORY_PROJECT_DIR instead of $CLAUDE_PROJECT_DIR.
4
- *
5
- * Per ADR-3 §2: the canonical $AIWG_PROJECT_DIR is substituted with
6
- * $FACTORY_PROJECT_DIR at deploy time. The translator emits a wrapper
7
- * shell script under .factory/hooks/<id>.sh that calls the AIWG hook
8
- * command with the right env-var binding.
9
- */
1
+ // Register Factory hooks and deploy the shared discovery script with ownership receipts.
10
2
  import { promises as fs } from 'node:fs';
11
- import * as path from 'node:path';
3
+ import path from 'node:path';
12
4
  import { generateShimBash } from './shim.js';
5
+ import { loadHookSources } from './loader.js';
6
+ import { captureDeploymentOutputs, recordDeploymentOutputs } from '../../providers/deployment-ownership.mjs';
7
+ import { managedHookScriptState } from '../../extensions/managed-hook-script-state.js';
8
+ import { factoryHookDocuments, removeFactoryManaged, saveFactoryHooks } from './factory-hook-config.js';
9
+ // Droid accepts plain stdout context. Decode either shared-script JSON shape
10
+ // without changing the shared script's fail-open, read-only, bounded contract.
11
+ const launcher = [
12
+ 'const write=process.stdout.write.bind(process.stdout);',
13
+ 'process.stdout.write=(s,...a)=>{try{const o=JSON.parse(String(s));',
14
+ 's=o.hookSpecificOutput?.additionalContext??o.additionalContext??"";}catch{}return write(s,...a);};',
15
+ 'const fs=require("node:fs"),p=require("node:path");',
16
+ 'for(let d=process.env.FACTORY_PROJECT_DIR||process.cwd();;d=p.dirname(d)){',
17
+ 'const s=p.join(d,".factory/hooks/aiwg-prompt-discovery.cjs");',
18
+ 'if(fs.existsSync(s)){require(s);break;}if(p.dirname(d)===d)break;}',
19
+ ].join('');
20
+ const quote = (value) => `'${value.replaceAll("'", "'\"'\"'")}'`;
21
+ export function managedFactoryHooks() {
22
+ return [
23
+ { event: 'SessionStart', id: 'aiwg-session', command: 'aiwg refresh --dry-run --quiet' },
24
+ { event: 'UserPromptSubmit', id: 'aiwg-prompt-discovery', command: `node -e ${quote(launcher)}` },
25
+ ];
26
+ }
13
27
  export async function translateForFactory(source, options) {
14
- const result = {
15
- provider: 'factory',
16
- emittedPaths: [],
17
- warnings: [],
18
- skipped: false,
19
- };
20
- if (source.degradeOn?.includes('factory')) {
21
- result.skipped = true;
22
- result.skipReason = 'degrade-on declared factory';
23
- return result;
28
+ const result = { provider: 'factory', emittedPaths: [], warnings: [], skipped: false };
29
+ if (source.degradeOn?.includes('factory'))
30
+ return { ...result, skipped: true, skipReason: 'degrade-on declared factory' };
31
+ const directory = path.join(options.projectPath, '.factory');
32
+ const prompt = source.id === 'aiwg-prompt-discovery';
33
+ const script = path.join(directory, 'hooks', `${source.id}.${prompt ? 'cjs' : 'sh'}`);
34
+ const config = path.join(directory, 'hooks.json');
35
+ if (options.dryRun)
36
+ return { ...result, emittedPaths: [script, config].map(file => file + ' (dry-run)') };
37
+ for (const file of [directory, config, path.dirname(script), script,
38
+ path.join(directory, 'settings.json'), path.join(directory, 'hooks/hooks.json')]) {
39
+ try {
40
+ if ((await fs.lstat(file)).isSymbolicLink())
41
+ throw new Error(`Refusing symlinked Factory hook target: ${file}`);
42
+ }
43
+ catch (error) {
44
+ if (error.code !== 'ENOENT')
45
+ throw error;
46
+ }
47
+ }
48
+ const state = factoryHookDocuments(directory);
49
+ const roots = [directory];
50
+ const before = captureDeploymentOutputs(roots);
51
+ const bytes = prompt
52
+ ? await fs.readFile(source.args?.[0] ?? (() => { throw new Error('Missing shared prompt discovery script'); })())
53
+ : Buffer.from(generateShimBash('factory', source.command, source.args ?? []));
54
+ const status = await managedHookScriptState(options.projectPath, path.relative(options.projectPath, script), bytes);
55
+ if (status === 'operator-edited' || status === 'unreadable') {
56
+ result.warnings.push(`${script}: kept (${status})`);
24
57
  }
25
- const hooksDir = path.join(options.projectPath, '.factory', 'hooks');
26
- const scriptPath = path.join(hooksDir, `${source.id}.sh`);
27
- const shim = generateShimBash('factory', source.command, source.args || []);
28
- if (options.dryRun) {
29
- result.emittedPaths.push(scriptPath + ' (dry-run)');
30
- return result;
58
+ else {
59
+ await fs.mkdir(path.dirname(script), { recursive: true });
60
+ await fs.writeFile(script, bytes, { mode: 0o755 });
61
+ result.emittedPaths.push(script);
31
62
  }
32
- await fs.mkdir(hooksDir, { recursive: true });
33
- await fs.writeFile(scriptPath, shim, 'utf8');
34
- try {
35
- await fs.chmod(scriptPath, 0o755);
63
+ removeFactoryManaged(state.doc, source.id);
64
+ const hooks = state.doc.hooks ??= {};
65
+ for (const event of source.events) {
66
+ (hooks[event] ??= []).push({ hooks: [{ type: 'command',
67
+ command: prompt ? managedFactoryHooks()[1].command : `bash ${quote(script)}`,
68
+ ...(source.timeout === undefined ? {} : { timeout: source.timeout }),
69
+ _aiwg_managed: true, _aiwg_id: source.id }] });
36
70
  }
37
- catch {
38
- // Non-POSIX
71
+ saveFactoryHooks(state);
72
+ result.emittedPaths.push(config);
73
+ recordDeploymentOutputs(before, roots, { frameworkSlug: 'aiwg-hooks', claimUnchangedSettings: false, writtenFiles: result.emittedPaths });
74
+ return result;
75
+ }
76
+ export async function installFactoryPromptDiscovery(options) {
77
+ const { sources, errors } = await loadHookSources(options.frameworkRoot);
78
+ if (errors.length)
79
+ throw new Error(errors.join('\n'));
80
+ const source = sources.find(entry => entry.id === 'aiwg-prompt-discovery');
81
+ if (!source)
82
+ throw new Error('Missing canonical aiwg-prompt-discovery source');
83
+ const result = await translateForFactory(source, options);
84
+ if (!options.dryRun && !result.skipped) {
85
+ const directory = path.join(options.projectPath, '.factory');
86
+ const before = captureDeploymentOutputs([directory]);
87
+ const state = factoryHookDocuments(directory);
88
+ removeFactoryManaged(state.doc, 'aiwg-session');
89
+ const hook = managedFactoryHooks()[0];
90
+ ((state.doc.hooks ??= {})[hook.event] ??= []).push({ matcher: '*', hooks: [{
91
+ type: 'command', command: hook.command, _aiwg_managed: true, _aiwg_id: hook.id,
92
+ }] });
93
+ saveFactoryHooks(state);
94
+ recordDeploymentOutputs(before, [directory], { frameworkSlug: 'aiwg-hooks', claimUnchangedSettings: false, writtenFiles: [state.file] });
39
95
  }
40
- result.emittedPaths.push(scriptPath);
41
96
  return result;
42
97
  }
43
98
  //# sourceMappingURL=factory-translator.js.map
@@ -22,7 +22,7 @@ export { AIWG_ENV_VARS, NATIVE_ENV_VAR_MAP } from './types.js';
22
22
  export { substituteEnvVars, generateShimBash, EXIT_CODE_MAP } from './shim.js';
23
23
  export { translateForCodex, renderCodexHookToml, injectHookBlock as injectCodexHookBlock } from './codex-translator.js';
24
24
  export { translateForCopilot } from './copilot-translator.js';
25
- export { translateForFactory } from './factory-translator.js';
25
+ export { translateForFactory, installFactoryPromptDiscovery } from './factory-translator.js';
26
26
  export { translateForHermes } from './hermes-translator.js';
27
27
  export { translateForGrokBuild, GROK_EVENT_MAP } from './grok-build-translator.js';
28
28
  export { loadHookSources } from './loader.js';
@@ -66,8 +66,8 @@ export async function bridgeAll(sources, providers, options) {
66
66
  continue;
67
67
  }
68
68
  try {
69
- const roots = [path.join(options.projectPath, '.factory/hooks'), path.join(options.projectPath, '.github/hooks'),
70
- path.join(options.projectPath, '.grok/hooks'), path.join(process.env.CODEX_HOME || path.join(homedir(), '.codex'), 'config.toml'),
69
+ const roots = [path.join(options.projectPath, '.factory/hooks'), path.join(options.projectPath, '.factory/hooks.json'), path.join(options.projectPath, '.github/hooks'),
70
+ path.join(options.projectPath, '.grok/hooks'), path.join(options.projectPath, '.codex/hooks.json'), path.join(options.projectPath, '.codex/hooks'),
71
71
  path.join(homedir(), '.hermes/plugins')];
72
72
  const before = options.dryRun ? undefined : captureDeploymentOutputs(roots);
73
73
  const r = await translator(source, options);
@@ -24,6 +24,11 @@ const VALID_EVENTS = new Set([
24
24
  'SessionStart',
25
25
  'SessionEnd',
26
26
  'Stop',
27
+ 'PermissionRequest',
28
+ 'PreCompact',
29
+ 'PostCompact',
30
+ 'SubagentStart',
31
+ 'SubagentStop',
27
32
  ]);
28
33
  /**
29
34
  * Validate and normalize a parsed HookSource. Returns null if the input
@@ -50,6 +55,7 @@ function normalize(input, filePath) {
50
55
  events,
51
56
  command: o.command,
52
57
  args: Array.isArray(o.args) ? o.args.filter((a) => typeof a === 'string') : undefined,
58
+ timeout: typeof o.timeout === 'number' && Number.isFinite(o.timeout) && o.timeout > 0 ? o.timeout : undefined,
53
59
  safetyCritical: o['safety-critical'] === true || o.safetyCritical === true,
54
60
  degradeOn: Array.isArray(o['degrade-on'])
55
61
  ? o['degrade-on'].filter((p) => typeof p === 'string')
@@ -108,8 +114,10 @@ export async function loadHookSources(frameworkRoot) {
108
114
  errors.push(error);
109
115
  continue;
110
116
  }
111
- if (source)
112
- sources.push(source);
117
+ if (source) {
118
+ const resolveRoot = (value) => value.replace(/\$AIWG_ROOT\b|\$\{AIWG_ROOT\}/g, () => frameworkRoot);
119
+ sources.push({ ...source, command: resolveRoot(source.command), args: source.args?.map(resolveRoot) });
120
+ }
113
121
  }
114
122
  return { sources, errors };
115
123
  }
@@ -1,6 +1,5 @@
1
1
  // Explain prompt discovery gaps where an event mapping has no context contract.
2
2
  export const PROMPT_DISCOVERY_GAPS = {
3
- codex: 'Prompt discovery unavailable: the Codex bridge maps before_prompt but has no verified additionalContext injection contract.',
4
3
  hermes: 'Prompt discovery unavailable: the Hermes bridge returns an exit code without forwarding prompt JSON or injecting additionalContext.',
5
4
  };
6
5
  //# sourceMappingURL=prompt-discovery-gaps.js.map
@@ -0,0 +1,64 @@
1
+ // Diagnose and explicitly repair permissions on known non-secret workspace outputs.
2
+ import { constants } from 'node:fs';
3
+ import { lstat, open, readdir } from 'node:fs/promises';
4
+ import { dirname, join, relative } from 'node:path';
5
+ import { projectAiwgPath } from '../config/project-artifacts.js';
6
+ import { sharedWorkspace, workspacePermissionsAllowed } from './workspace-permissions.js';
7
+ /** Only outputs with a non-secret contract are eligible; token/key stores are never traversed. */
8
+ export async function inspectWorkspacePermissions(projectRoot, fix = false) {
9
+ const root = projectAiwgPath(projectRoot);
10
+ const report = { findings: [], journals: [] };
11
+ const visit = async (file, descend = true) => {
12
+ let info;
13
+ try {
14
+ info = await lstat(file);
15
+ }
16
+ catch (error) {
17
+ if (error.code === 'ENOENT')
18
+ return;
19
+ throw error;
20
+ }
21
+ if (info.isSymbolicLink() || (!info.isDirectory() && !info.isFile()))
22
+ return;
23
+ const name = relative(root, file);
24
+ const journal = /^decision\/(ledger|opportunities)\.jsonl$/.test(name);
25
+ const allowed = workspacePermissionsAllowed(file, info);
26
+ const shared = sharedWorkspace(dirname(file));
27
+ if (journal)
28
+ report.journals.push({ path: file, state: !allowed ? 'unsafe' : (info.mode & 0o070) ? 'shared' : 'private' });
29
+ const collapsed = shared !== null && info.gid === shared.gid && (info.mode & 0o070) === 0;
30
+ if (collapsed || (journal && !allowed)) {
31
+ const finding = { path: file, reason: collapsed ? 'collapsed-group-mask' : 'ledger-permissions',
32
+ repaired: false, repair: 'aiwg doctor --decision-offload --fix' };
33
+ report.findings.push(finding);
34
+ if (fix && (!process.getuid || info.uid === process.getuid()) && (info.isDirectory() || info.nlink === 1)) {
35
+ const handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
36
+ try {
37
+ const opened = await handle.stat();
38
+ if (opened.ino === info.ino && opened.dev === info.dev && opened.uid === info.uid && opened.nlink === info.nlink) {
39
+ await handle.chmod(collapsed ? (info.mode & 0o7777) | (info.isDirectory() ? 0o070 : 0o060) : 0o600);
40
+ finding.repaired = true;
41
+ }
42
+ }
43
+ finally {
44
+ await handle.close();
45
+ }
46
+ }
47
+ }
48
+ if (info.isDirectory() && descend) {
49
+ for (const entry of await readdir(file))
50
+ await visit(join(file, entry));
51
+ }
52
+ };
53
+ // The local config and firewall baseline are control-plane outputs even with an external artifact root.
54
+ for (const file of [join(projectRoot, '.aiwg', 'aiwg.config'), join(projectRoot, '.aiwg', 'context-memory-firewall-baseline.json'),
55
+ join(root, 'receipts'), join(root, 'traces', 'transcripts'), join(root, 'archive', 'decision')])
56
+ await visit(file);
57
+ for (const directory of new Set([join(projectRoot, '.aiwg'), root, join(root, 'decision')]))
58
+ await visit(directory, false);
59
+ // Do not descend into decision's credential/private stores or transient lock files.
60
+ for (const name of ['ledger.jsonl', 'opportunities.jsonl'])
61
+ await visit(join(root, 'decision', name));
62
+ return report;
63
+ }
64
+ //# sourceMappingURL=workspace-permissions-health.js.map
@@ -0,0 +1,51 @@
1
+ // Stat-only permission policy for non-secret files in setgid, closed-to-others workspaces.
2
+ import { lstatSync } from 'node:fs';
3
+ import { chmod, lstat } from 'node:fs/promises';
4
+ import { dirname, resolve } from 'node:path';
5
+ /** Walk existing directories only; no ACL commands, subprocesses, or cached policy. */
6
+ export function sharedWorkspace(directory) {
7
+ if (process.platform === 'win32')
8
+ return null;
9
+ let current = resolve(directory);
10
+ for (;;) {
11
+ try {
12
+ const info = lstatSync(current);
13
+ if (info.isSymbolicLink())
14
+ return null;
15
+ if (info.isDirectory() && (info.mode & 0o2000) !== 0) {
16
+ return (info.mode & 0o007) === 0 ? { gid: info.gid } : null;
17
+ }
18
+ }
19
+ catch (error) {
20
+ if (error.code !== 'ENOENT')
21
+ throw error;
22
+ }
23
+ const parent = dirname(current);
24
+ if (parent === current)
25
+ return null;
26
+ current = parent;
27
+ }
28
+ }
29
+ // Group bits leave the inherited ACL mask usable; umask/default ACL still apply.
30
+ export const workspaceFileMode = (file) => sharedWorkspace(dirname(file)) ? 0o660 : 0o600;
31
+ export const workspaceDirectoryMode = (directory) => sharedWorkspace(directory) ? 0o770 : 0o700;
32
+ /** Private files remain valid; shared files must match the workspace gid and exclude others. */
33
+ export function workspacePermissionsAllowed(file, info) {
34
+ if ((info.mode & 0o077) === 0)
35
+ return true;
36
+ const shared = sharedWorkspace(info.isDirectory?.() ? file : dirname(file));
37
+ return (info.mode & 0o007) === 0 && shared !== null && info.gid === shared.gid;
38
+ }
39
+ /** chmod after creation preserves the target mode even when umask filters temporary-file creation. */
40
+ export async function preserveReplacementMode(temporary, destination) {
41
+ try {
42
+ const info = await lstat(destination);
43
+ if (info.isFile())
44
+ await chmod(temporary, info.mode & 0o777);
45
+ }
46
+ catch (error) {
47
+ if (error.code !== 'ENOENT')
48
+ throw error;
49
+ }
50
+ }
51
+ //# sourceMappingURL=workspace-permissions.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiwg/cli",
3
- "version": "2026.11.1",
3
+ "version": "2026.11.2",
4
4
  "description": "Lightweight AIWG CLI for signed, versioned web-backed resources.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -27,6 +27,8 @@
27
27
  "THIRD_PARTY_NOTICES.md",
28
28
  "bin/",
29
29
  "agentic/code/providers/",
30
+ "agentic/code/addons/aiwg-hooks/canonical/aiwg-prompt-discovery.yaml",
31
+ "agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs",
30
32
  "agentic/code/addons/aiwg-utils/rules/anti-laziness.md",
31
33
  "agentic/code/addons/aiwg-utils/rules/anti-laziness.core.md",
32
34
  "agentic/code/addons/composition-engine/lib/runtime.mjs",
@@ -61,8 +63,10 @@
61
63
  "tools/ralph-external/lib/session-environment.mjs",
62
64
  "tools/ralph-external/lib/worker-inputs.mjs",
63
65
  "tools/ralph-external/lib/worker-final.mjs",
66
+ "tools/ralph-external/lib/worker-prompt.mjs",
64
67
  "tools/ralph-external/lib/worker-capture.mjs",
65
68
  "tools/ralph-external/lib/worker-launch-cli.mjs",
69
+ "tools/ralph-external/lib/worker-run-directory-refusal.mjs",
66
70
  "tools/ralph-external/lib/worker-isolation.mjs",
67
71
  "tools/ralph-external/lib/worker-isolation-args.mjs",
68
72
  "tools/ralph-external/lib/worker-unit-cleanup.mjs",
@@ -106,6 +110,7 @@
106
110
  "tools/providers/antigravity-transport.mjs",
107
111
  "tools/commands/deploy-prompts-codex.mjs",
108
112
  "tools/plugin/package-plugins.mjs",
113
+ "tools/plugin/issue-template-copies.mjs",
109
114
  "tools/plugin/plugin-links.mjs",
110
115
  "tools/skills/deploy-skills-codex.mjs",
111
116
  "tools/skills/codex-skill-transform.mjs",
@@ -236,11 +236,12 @@ export function updateSidecarManifest(dir, deployedEntries, opts) {
236
236
  const existing = readSidecarManifest(dir) || { managed: {} };
237
237
 
238
238
  for (const entry of deployedEntries) {
239
- const { filename, hash, frameworkSlug, kind, sourcePath } = entry;
239
+ const { filename, hash, frameworkSlug, kind, sourcePath, sourceHash } = entry;
240
240
  const prior = existing.managed[filename];
241
241
  const digest = `sha256:${hash}`;
242
242
  const sidecarEntry = { ...(prior?.hash === digest ? prior : {}), hash: digest, source, version };
243
243
  if (sourcePath) sidecarEntry.sourcePath = sourcePath;
244
+ if (sourceHash) sidecarEntry.sourceHash = sourceHash;
244
245
  if (frameworkSlug) sidecarEntry.frameworkSlug = frameworkSlug;
245
246
  // `kind` marks artifacts whose lifecycle is governed elsewhere — currently
246
247
  // only `skill-command` wrappers, which follow their source skill (#2507).
@@ -23,6 +23,7 @@ export function deployFiles(files, destDir, opts, transformFn) {
23
23
  // (#1169). Each value: { src, frameworkSlug }
24
24
  const seen = new Map();
25
25
  const actions = [];
26
+ const sourceHashes = new Map();
26
27
  // Collision report — one entry per detected cross-framework collision
27
28
  // (within-batch or against sidecar). Surfaced after the loop.
28
29
  const collisions = [];
@@ -45,7 +46,9 @@ export function deployFiles(files, destDir, opts, transformFn) {
45
46
 
46
47
  // Read and transform source content (needed for content-equality check
47
48
  // and the collision-vs-duplicate distinction)
48
- const srcContent = injectBoundRules(fs.readFileSync(f, 'utf8'), f, opts);
49
+ const rawContent = fs.readFileSync(f, 'utf8');
50
+ sourceHashes.set(f, `sha256:${contentHash(rawContent)}`);
51
+ const srcContent = injectBoundRules(rawContent, f, opts);
49
52
  let transformedContent = transformFn ? transformFn(f, srcContent, opts) : srcContent;
50
53
 
51
54
  // Rule triggers are index metadata, not something the reading agent needs.
@@ -185,11 +188,11 @@ export function deployFiles(files, destDir, opts, transformFn) {
185
188
  if (dryRun) console.log(`[dry-run] deploy ${a.src} -> ${a.dest} (${a.reason})`);
186
189
  else writeFile(a.dest, a.content, false);
187
190
  if (verbose) console.log(`deployed ${path.basename(a.src)} -> ${path.relative(process.cwd(), opts.logicalOutputPath?.(a.dest) || a.dest)} (${a.reason})`);
188
- deployedEntries.push({ filename: path.basename(a.dest), hash: a.hash, frameworkSlug: a.frameworkSlug, sourcePath: path.resolve(a.src) });
191
+ deployedEntries.push({ filename: path.basename(a.dest), hash: a.hash, sourceHash: sourceHashes.get(a.src), frameworkSlug: a.frameworkSlug, sourcePath: path.resolve(a.src) });
189
192
  } else if (a.type === 'skip') {
190
193
  if (verbose) console.log(`skip (${a.reason}): ${path.basename(a.dest)}`);
191
194
  // Preserve existing sidecar entries for skipped files
192
- if (a.hash) deployedEntries.push({ filename: path.basename(a.dest), hash: a.hash, frameworkSlug: a.frameworkSlug, sourcePath: path.resolve(a.src) });
195
+ if (a.hash) deployedEntries.push({ filename: path.basename(a.dest), hash: a.hash, sourceHash: sourceHashes.get(a.src), frameworkSlug: a.frameworkSlug, sourcePath: path.resolve(a.src) });
193
196
  }
194
197
  }
195
198
 
@@ -42,9 +42,9 @@ export function loadModelConfig(srcRoot) {
42
42
  efficiency: { model: 'claude-haiku-4-5' }
43
43
  },
44
44
  factory: {
45
- reasoning: { model: 'heavy' },
46
- coding: { model: 'medium' },
47
- efficiency: { model: 'light' }
45
+ reasoning: { model: 'claude-opus-5' },
46
+ coding: { model: 'claude-sonnet-5' },
47
+ efficiency: { model: 'claude-haiku-4-5-20251001' }
48
48
  },
49
49
  shorthand: {
50
50
  'opus': 'claude-opus-5',
@@ -74,6 +74,7 @@ export function deploySkillDir(skillDir, destDir, opts) {
74
74
  copyRecursive(srcPath, destPath);
75
75
  } else {
76
76
  let srcContent = fs.readFileSync(srcPath, 'utf8');
77
+ const sourceHash = `sha256:${contentHash(srcContent)}`;
77
78
 
78
79
  // Inject target platform into SKILL.md — replaces [all] token with [provider-name]
79
80
  if (entry.name === 'SKILL.md' && provider) {
@@ -93,6 +94,7 @@ export function deploySkillDir(skillDir, destDir, opts) {
93
94
  const relative = path.relative(destSkillDir, destPath);
94
95
  managed[relative] = {
95
96
  hash: `sha256:${contentHash(srcContent)}`,
97
+ sourceHash,
96
98
  source: opts.deploySource || 'bundled',
97
99
  version: opts.deployVersion || 'unknown',
98
100
  ...(frameworkSlug ? { frameworkSlug } : {}),
@@ -0,0 +1,21 @@
1
+ // Render the final bound-rule pointer shared by deployment and size checks.
2
+ import { replaceBoundRulesBlock } from './base-contract.mjs';
3
+
4
+ export const boundRuleAnchor = target => `${target.type}-${target.name}`.toLowerCase().replace(/[^a-z0-9_-]/g, '-');
5
+
6
+ export function renderBoundRulesPointer(body, targets, indexRel, { fetch = '', compact = false } = {}) {
7
+ const clean = replaceBoundRulesBlock(body, []);
8
+ const pointers = [...new Set(targets.map(target => `${indexRel}#${boundRuleAnchor(target)}`))];
9
+ if (!pointers.length) return clean;
10
+ // Authored pointers already reach the same complete rule set; keep one copy.
11
+ const missing = pointers.filter(pointer => !clean.includes(`\`${pointer}\``));
12
+ const instruction = missing.length
13
+ ? `${compact ? 'Read and follow' : 'Read and follow before governed work'}: ${missing.map(pointer => `\`${pointer}\``).join('; ')}.`
14
+ : 'Read and follow the bound rules listed above before governed work.';
15
+ return `${clean}${clean.endsWith('\n') ? '' : '\n'}\n<!-- AIWG:bound-rules:start -->\n${instruction}\n${fetch ? fetch + '\n' : ''}<!-- AIWG:bound-rules:end -->\n`;
16
+ }
17
+
18
+ export function projectCodexAgentBindings(rendered, targets) {
19
+ return rendered.replace(/^developer_instructions = (".*")$/m, (_, value) =>
20
+ `developer_instructions = ${JSON.stringify(renderBoundRulesPointer(JSON.parse(value), targets, '.codex/RULES-BOUND.md', { compact: true }))}`);
21
+ }
@@ -1,6 +1,7 @@
1
1
  // Apply project settings and context after provider file deployment.
2
2
  import fs from 'node:fs';
3
3
  import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
4
5
  import { importImpl } from '../../_resolve-impl.mjs';
5
6
  import { initializeFrameworkWorkspace, ensureDir } from './base.mjs';
6
7
  import { deployHookFile } from './claude.mjs';
@@ -36,13 +37,16 @@ export async function postDeploy(targetDir, opts) {
36
37
 
37
38
  const addonPass = /(?:agentic\/code|\.aiwg)\/(?:addons|extensions)\//.test((opts.logicalInputPath?.(opts.srcRoot) || opts.srcRoot)?.replaceAll('\\', '/') || '');
38
39
 
39
- // Reuse the settings owner's backup/atomic merge, independently of hooks.
40
- if (opts.attribution !== false) {
40
+ // Full addon passes also refresh runtime scripts, using this package's source.
41
+ const fullDeploy = !opts.commandsOnly && !opts.rulesOnly && (!opts.skillsOnly || opts.kernelOnly === true);
42
+ const hooks = fullDeploy && opts.hooks === true && opts.scope !== 'user';
43
+ if (opts.attribution !== false || hooks) {
41
44
  const { installAiwgHooks } = await importImpl(import.meta.url, 'extensions/claude-hooks-installer.js');
42
45
  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);
46
+ const result = await installAiwgHooks({ frameworkSlug: deploymentOwner(opts), claimUnchangedSettings: !addonPass, projectPath: targetDir,
47
+ frameworkRoot: fileURLToPath(new URL('../../../', import.meta.url)),
48
+ attribution: opts.attribution !== false, hooks, dryRun: opts.dryRun });
49
+ if (!opts.dryRun && result) opts.writtenFiles?.push(result.settingsPath, ...result.installedScripts);
46
50
  for (const warning of result?.warnings || []) console.warn(`Claude settings: ${warning}`);
47
51
  }
48
52
  await deployConductorDataGuard(targetDir, 'claude', opts);
@@ -1,4 +1,6 @@
1
1
  // Apply project settings and context after provider file deployment.
2
+ import { importImpl } from '../../_resolve-impl.mjs';
3
+ import { fileURLToPath } from 'node:url';
2
4
  import { initializeFrameworkWorkspace } from './base.mjs';
3
5
  import { createAgentsMd } from './codex.mjs';
4
6
  import { deployConductorDataGuard } from './conductor-data-guard.mjs';
@@ -7,6 +9,14 @@ export async function postDeploy(targetDir, opts) {
7
9
  initializeFrameworkWorkspace(targetDir, opts.mode, opts.dryRun, opts.srcRoot);
8
10
  await deployConductorDataGuard(targetDir, 'codex', opts);
9
11
 
12
+ const fullDeploy = !opts.commandsOnly && !opts.rulesOnly && (!opts.skillsOnly || opts.kernelOnly === true);
13
+ if (fullDeploy && opts.hooks !== false && opts.scope !== 'user') {
14
+ const { installCodexPromptDiscovery } = await importImpl(import.meta.url, 'smiths/hook-bridge/codex-translator.js');
15
+ const packageRoot = fileURLToPath(new URL('../../../', import.meta.url));
16
+ // Runtime hooks belong to this package, even when deploying an external bundle.
17
+ await installCodexPromptDiscovery({ projectPath: targetDir, frameworkRoot: packageRoot, dryRun: opts.dryRun });
18
+ }
19
+
10
20
  if (opts.createAgentsMd) {
11
21
  if (opts.contextFiles !== false) createAgentsMd(targetDir, opts.srcRoot, opts.dryRun);
12
22
  }