@aiwg/cli 2026.11.0 → 2026.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (168) hide show
  1. package/agentic/code/addons/aiwg-hooks/canonical/aiwg-prompt-discovery.yaml +9 -0
  2. package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +136 -0
  3. package/agentic/code/providers/flue/README.md +2 -1
  4. package/agentic/code/providers/model-capabilities.v1.json +27 -23
  5. package/agentic/code/providers/model-catalog.v1.json +3 -3
  6. package/dist/src/artifacts/cli.js +13 -13
  7. package/dist/src/artifacts/discover-cli-help.js +25 -0
  8. package/dist/src/artifacts/discover-facets.js +2 -0
  9. package/dist/src/artifacts/discover-session-facets.js +15 -0
  10. package/dist/src/artifacts/fortemi-core-prebuilt-freshness.js +28 -0
  11. package/dist/src/artifacts/fortemi-core-query-adapter.js +4 -4
  12. package/dist/src/artifacts/fortemi-core-sync.js +3 -0
  13. package/dist/src/artifacts/framework-capabilities.js +11 -3
  14. package/dist/src/artifacts/framework-source-digest.js +1 -1
  15. package/dist/src/artifacts/index-builder.js +12 -13
  16. package/dist/src/artifacts/index-dependencies.js +72 -0
  17. package/dist/src/artifacts/query-engine-discover-output.js +13 -5
  18. package/dist/src/artifacts/query-engine-discover.js +103 -28
  19. package/dist/src/artifacts/query-engine-entries.js +107 -10
  20. package/dist/src/artifacts/query-engine-installation.js +27 -0
  21. package/dist/src/artifacts/query-engine-options.js +14 -1
  22. package/dist/src/artifacts/query-engine-rules.js +1 -2
  23. package/dist/src/artifacts/query-engine-scoring.js +38 -32
  24. package/dist/src/artifacts/query-engine-show-card.js +8 -2
  25. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  26. package/dist/src/artifacts/query-engine-show.js +5 -3
  27. package/dist/src/artifacts/query-engine-templates.js +33 -0
  28. package/dist/src/artifacts/query-engine-verbose.js +25 -0
  29. package/dist/src/artifacts/relations-builder.js +49 -4
  30. package/dist/src/artifacts/relations.js +26 -10
  31. package/dist/src/artifacts/template-references.js +42 -0
  32. package/dist/src/artifacts/types.js +1 -1
  33. package/dist/src/cli/handlers/bundle-reconciliation.js +7 -3
  34. package/dist/src/cli/handlers/checkpoint-handoff.js +48 -0
  35. package/dist/src/cli/handlers/checkpoint-record.js +20 -0
  36. package/dist/src/cli/handlers/checkpoint.js +176 -0
  37. package/dist/src/cli/handlers/decision.js +1 -1
  38. package/dist/src/cli/handlers/doctor-args.js +3 -1
  39. package/dist/src/cli/handlers/doctor-help.js +2 -1
  40. package/dist/src/cli/handlers/help.js +1 -0
  41. package/dist/src/cli/handlers/index.js +4 -2
  42. package/dist/src/cli/handlers/models-resource-sample.js +7 -3
  43. package/dist/src/cli/handlers/ralph-launcher.js +1 -1
  44. package/dist/src/cli/handlers/refresh-bundles.js +2 -1
  45. package/dist/src/cli/handlers/refresh-managed-deployment.js +196 -0
  46. package/dist/src/cli/handlers/refresh.js +10 -2
  47. package/dist/src/cli/handlers/script-runner.js +2 -1
  48. package/dist/src/cli/handlers/steward-signing.js +44 -0
  49. package/dist/src/cli/handlers/steward.js +5 -0
  50. package/dist/src/cli/handlers/subcommands-discovery.js +8 -1
  51. package/dist/src/cli/handlers/use-provider-results.js +17 -0
  52. package/dist/src/cli/handlers/use.js +19 -18
  53. package/dist/src/cli/router.js +12 -2
  54. package/dist/src/cli/services/deployment-verification.js +11 -7
  55. package/dist/src/cli/user-scope-mirror.js +3 -1
  56. package/dist/src/config/aiwg-config.js +5 -1
  57. package/dist/src/config/cli.js +1 -0
  58. package/dist/src/config/delivery-validation.js +21 -0
  59. package/dist/src/config/host-resource-report.d.mts +1 -1
  60. package/dist/src/config/host-resource-report.mjs +23 -4
  61. package/dist/src/config/host-resource-runtime.d.mts +8 -0
  62. package/dist/src/config/host-resource-runtime.mjs +67 -24
  63. package/dist/src/config/index-graph-overrides.js +4 -0
  64. package/dist/src/config/worker-attribution.d.mts +7 -0
  65. package/dist/src/config/worker-attribution.mjs +44 -0
  66. package/dist/src/config/worker-write.js +4 -10
  67. package/dist/src/decision/ledger.js +15 -15
  68. package/dist/src/decision/offload.js +6 -7
  69. package/dist/src/delivery/git.js +62 -0
  70. package/dist/src/delivery/pr.js +151 -0
  71. package/dist/src/delivery/template-sections.js +56 -0
  72. package/dist/src/delivery/tracker.js +33 -0
  73. package/dist/src/discovery/interview.js +1 -1
  74. package/dist/src/extensions/claude-hooks-installer.js +62 -53
  75. package/dist/src/extensions/loader.js +2 -1
  76. package/dist/src/extensions/managed-hook-script-state.js +48 -0
  77. package/dist/src/extensions/muse-managed-hooks.js +49 -0
  78. package/dist/src/issues/cli.js +15 -3
  79. package/dist/src/issues/external-cli.js +79 -0
  80. package/dist/src/issues/live.js +26 -2
  81. package/dist/src/issues/local.js +5 -1
  82. package/dist/src/issues/tracker-policy.js +27 -0
  83. package/dist/src/mcp/json-document.d.mts +2 -0
  84. package/dist/src/mcp/tools/worker-invoke.mjs +2 -1
  85. package/dist/src/mcp/tools/worker-stdin-runtime.mjs +12 -0
  86. package/dist/src/models/conductor-data-policy.d.mts +3 -2
  87. package/dist/src/models/conductor-data-policy.mjs +94 -5
  88. package/dist/src/models/model-capabilities.v1.json +27 -23
  89. package/dist/src/models/model-catalog.v1.json +3 -3
  90. package/dist/src/models/provider-policy.js +8 -0
  91. package/dist/src/models/worker-health-readiness.js +20 -4
  92. package/dist/src/models/worker-health-snapshot.js +29 -0
  93. package/dist/src/models/worker-installation.d.mts +5 -1
  94. package/dist/src/models/worker-installation.mjs +11 -5
  95. package/dist/src/models/worker-plan.js +3 -3
  96. package/dist/src/models/worker-qualification-policy.js +54 -0
  97. package/dist/src/models/worker-selection-policy.js +2 -1
  98. package/dist/src/providers/deployment-lock.js +77 -0
  99. package/dist/src/providers/deployment-ownership.d.mts +12 -2
  100. package/dist/src/providers/deployment-ownership.mjs +115 -21
  101. package/dist/src/providers/deployment-preservation.d.mts +2 -1
  102. package/dist/src/providers/deployment-preservation.mjs +3 -0
  103. package/dist/src/providers/provider-definitions.js +4 -0
  104. package/dist/src/providers/skill-ownership.d.mts +1 -0
  105. package/dist/src/providers/transformation-receipt-integration.js +4 -2
  106. package/dist/src/providers/transformation-receipt.js +4 -2
  107. package/dist/src/serve/worker-invocation-preparation.js +3 -1
  108. package/dist/src/serve/worker-invocation.js +6 -2
  109. package/dist/src/skills/run.js +5 -0
  110. package/dist/src/smiths/context-pipeline/workspace-audit.js +34 -17
  111. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +12 -6
  112. package/dist/src/smiths/context-pipeline/workspace-doctor.js +44 -4
  113. package/dist/src/smiths/context-pipeline/workspace-document.js +5 -2
  114. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -1
  115. package/dist/src/smiths/hook-bridge/codex-translator.js +150 -92
  116. package/dist/src/smiths/hook-bridge/codex-trust.js +50 -0
  117. package/dist/src/smiths/hook-bridge/factory-hook-config.js +132 -0
  118. package/dist/src/smiths/hook-bridge/factory-translator.js +88 -33
  119. package/dist/src/smiths/hook-bridge/hermes-translator.js +3 -1
  120. package/dist/src/smiths/hook-bridge/index.js +3 -3
  121. package/dist/src/smiths/hook-bridge/loader.js +10 -2
  122. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +5 -0
  123. package/dist/src/storage/workspace-permissions-health.js +64 -0
  124. package/dist/src/storage/workspace-permissions.js +51 -0
  125. package/package.json +9 -2
  126. package/schemas/models/model-config-compatibility.v1.schema.json +4 -0
  127. package/tools/agents/deploy-agents.mjs +15 -0
  128. package/tools/agents/providers/base-contract.mjs +7 -1
  129. package/tools/agents/providers/base-files.mjs +2 -1
  130. package/tools/agents/providers/base-flat-artifacts.mjs +6 -3
  131. package/tools/agents/providers/base-inventory.mjs +35 -13
  132. package/tools/agents/providers/base-models-platforms.mjs +3 -3
  133. package/tools/agents/providers/base-skill-copy.mjs +2 -0
  134. package/tools/agents/providers/base.mjs +1 -1
  135. package/tools/agents/providers/bound-rules-pointer.mjs +21 -0
  136. package/tools/agents/providers/claude-post-deploy.mjs +9 -5
  137. package/tools/agents/providers/codex-post-deploy.mjs +10 -0
  138. package/tools/agents/providers/conductor-data-guard.mjs +35 -11
  139. package/tools/agents/providers/factory-hooks.mjs +43 -0
  140. package/tools/agents/providers/factory.mjs +4 -91
  141. package/tools/agents/providers/muse-hooks.mjs +6 -41
  142. package/tools/agents/providers/muse-prompt-discovery.mjs +18 -0
  143. package/tools/agents/providers/packaged-codex-agents.mjs +48 -0
  144. package/tools/agents/providers/provider-prepare-coordinator.mjs +15 -10
  145. package/tools/agents/providers/rule-delivery-surface.mjs +10 -7
  146. package/tools/agents/providers/rule-deployment-commit.mjs +10 -0
  147. package/tools/agents/providers/rule-presentation.mjs +6 -5
  148. package/tools/agents/providers/rule-projection.mjs +10 -2
  149. package/tools/agents/providers/rule-startup.mjs +8 -1
  150. package/tools/agents/providers/stale-artifact-prune.mjs +9 -8
  151. package/tools/cli/decision-offload-report.mjs +7 -2
  152. package/tools/plugin/issue-template-copies.mjs +24 -0
  153. package/tools/plugin/package-plugins.mjs +11 -3
  154. package/tools/ralph-external/lib/factory-adapter.mjs +7 -8
  155. package/tools/ralph-external/lib/worker-artifacts.mjs +4 -2
  156. package/tools/ralph-external/lib/worker-capture.mjs +157 -0
  157. package/tools/ralph-external/lib/worker-final.mjs +43 -8
  158. package/tools/ralph-external/lib/worker-health.mjs +3 -0
  159. package/tools/ralph-external/lib/worker-invocation-processes.mjs +9 -6
  160. package/tools/ralph-external/lib/worker-launch-cli.mjs +20 -2
  161. package/tools/ralph-external/lib/worker-process-identity.mjs +30 -0
  162. package/tools/ralph-external/lib/worker-prompt.mjs +35 -0
  163. package/tools/ralph-external/lib/worker-retry-evidence.mjs +87 -6
  164. package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +8 -0
  165. package/tools/ralph-external/lib/worker-termination.mjs +56 -6
  166. package/tools/ralph-external/process-monitor.mjs +12 -18
  167. package/tools/ralph-external/session-launcher.mjs +53 -36
  168. package/vscode-extension/schemas/aiwg.config.v1.json +15 -0
@@ -1,112 +1,128 @@
1
- /**
2
- * Codex hook translator — emits TOML hook entries for ~/.codex/config.toml.
3
- *
4
- * Per ADR-3 §5 backup-and-rollback: the operator-managed config file
5
- * (~/.codex/config.toml) is read, AIWG-tagged entries are merged in
6
- * (via _aiwg_managed: true), and the file is written atomically with a
7
- * timestamped backup.
8
- *
9
- * Codex hook events map per the assessment matrix; this translator
10
- * supports a conservative subset known to exist in the loader.
11
- */
1
+ // Emit Codex 0.165 matcher groups in project hooks.json; retain safe TOML repair.
12
2
  import { promises as fs } from 'node:fs';
13
3
  import * as path from 'node:path';
14
- import { homedir } from 'node:os';
4
+ import { randomUUID } from 'node:crypto';
15
5
  import { substituteEnvVars } from './shim.js';
6
+ import { loadHookSources } from './loader.js';
16
7
  import { tomlString } from '../../mcp/toml-string.mjs';
17
- /** Codex-native event names (subset; extend when verified against codex-rs). */
18
- const CODEX_EVENT_MAP = {
19
- PreToolUse: 'before_tool',
20
- PostToolUse: 'after_tool',
21
- UserPromptSubmit: 'before_prompt',
22
- SessionStart: 'session_start',
23
- SessionEnd: 'session_end',
24
- Stop: 'session_end',
25
- };
26
- /**
27
- * Render a single TOML hook entry for a Codex config block.
28
- *
29
- * Codex's hook TOML shape (per the assessment):
30
- * [[hooks.<event>]]
31
- * command = "..."
32
- * args = ["..."]
33
- * _aiwg_managed = true
34
- *
35
- * Operators add their own hooks at the same shape; the _aiwg_managed flag
36
- * lets `aiwg remove --addon aiwg-hooks` distinguish AIWG entries from
37
- * operator-authored ones.
38
- */
8
+ // Verified with the installed 0.165.0 app-server hooks/list. Config keys use
9
+ // PascalCase; snake_case names (user_prompt_submit, pre_tool_use, etc.) are IDs
10
+ // in the runtime, not accepted config keys. See docs/hook-patterns.md.
11
+ const CODEX_EVENTS = new Set([
12
+ 'PreToolUse', 'PostToolUse', 'UserPromptSubmit', 'SessionStart', 'SessionEnd',
13
+ 'PermissionRequest', 'PreCompact', 'PostCompact', 'SubagentStart', 'SubagentStop', 'Stop',
14
+ ]);
15
+ // Codex runs hooks in the session cwd, which may be below the hooks.json root.
16
+ const PROMPT_DISCOVERY_LAUNCHER = [
17
+ 'const fs=require("node:fs"),path=require("node:path");',
18
+ 'for(let dir=process.cwd();;dir=path.dirname(dir)){',
19
+ 'const script=path.join(dir,".codex/hooks/aiwg-prompt-discovery.cjs");',
20
+ 'if(fs.existsSync(script)){require(script);break;}',
21
+ 'if(path.dirname(dir)===dir)break;',
22
+ '}',
23
+ ].join('');
24
+ function shellArgument(value, expandEnvironment = true) {
25
+ // Preserve environment references, but never evaluate argument substitutions.
26
+ const escaped = value.replace(/[\\"`$]/g, '\\$&');
27
+ const argument = expandEnvironment
28
+ ? escaped.replace(/\\\$(\{[A-Z_][A-Z0-9_]*\}|[A-Z_][A-Z0-9_]*)/g, '$$$1') : escaped;
29
+ return `"${argument}"`;
30
+ }
31
+ function commandHook(source, literalArgs = false) {
32
+ const command = substituteEnvVars(source.command, 'codex');
33
+ const args = (source.args || []).map(a => shellArgument(substituteEnvVars(a, 'codex'), !literalArgs));
34
+ return {
35
+ type: 'command', command: [command, ...args].join(' '),
36
+ ...(source.timeout === undefined ? {} : { timeout: source.timeout }),
37
+ _aiwg_managed: true, _aiwg_id: source.id,
38
+ };
39
+ }
40
+ /** TOML uses the same matcher groups and command string as hooks.json. */
39
41
  export function renderCodexHookToml(source) {
40
42
  const lines = [];
43
+ const hook = commandHook(source);
41
44
  for (const event of source.events) {
42
- const codexEvent = CODEX_EVENT_MAP[event];
43
- if (!codexEvent)
45
+ if (!CODEX_EVENTS.has(event))
44
46
  continue;
45
- const subCommand = substituteEnvVars(source.command, 'codex');
46
- const subArgs = (source.args || []).map((a) => substituteEnvVars(a, 'codex'));
47
- lines.push(`[[hooks.${codexEvent}]]`);
47
+ lines.push(`[[hooks.${event}]]`);
48
48
  lines.push(`# AIWG-managed hook: ${`${source.id} — ${source.description}`.replace(/[\x00-\x1f\x7f]/g, ' ')}`);
49
- lines.push(`command = ${tomlString(subCommand)}`);
50
- if (subArgs.length > 0) {
51
- lines.push(`args = [${subArgs.map(tomlString).join(', ')}]`);
52
- }
53
- if (source.safetyCritical) {
54
- lines.push(`# safety-critical: cannot be auto-removed without --allow-unsafe-shadow`);
55
- }
56
- lines.push(`_aiwg_managed = true`);
57
- lines.push(`_aiwg_id = ${tomlString(source.id)}`);
58
- lines.push('');
49
+ if (source.safetyCritical)
50
+ lines.push('# safety-critical: cannot be auto-removed without --allow-unsafe-shadow');
51
+ lines.push(`[[hooks.${event}.hooks]]`, 'type = "command"', `command = ${tomlString(hook.command)}`);
52
+ if (hook.timeout !== undefined)
53
+ lines.push(`timeout = ${hook.timeout}`);
54
+ lines.push('_aiwg_managed = true', `_aiwg_id = ${tomlString(source.id)}`, '');
59
55
  }
60
56
  return lines.join('\n');
61
57
  }
62
58
  const SPILLOVER_START = '# >>> AIWG-managed hooks (do not edit between markers)';
63
59
  const SPILLOVER_END = '# <<< AIWG-managed hooks';
64
- /**
65
- * Inject AIWG-managed hook block into existing TOML config, preserving
66
- * everything outside the markers. Idempotent — replaces an existing block
67
- * rather than appending.
68
- */
60
+ function markerIndex(text, marker, from = 0) {
61
+ for (let index = text.indexOf(marker, from); index !== -1; index = text.indexOf(marker, index + marker.length)) {
62
+ const end = index + marker.length;
63
+ if ((index === 0 || text[index - 1] === '\n')
64
+ && (end === text.length || /^\r?\n/.test(text.slice(end, end + 2))))
65
+ return index;
66
+ }
67
+ return -1;
68
+ }
69
+ /** Replace only managed content, rescuing user tables inside a misplaced end. */
69
70
  export function injectHookBlock(existingToml, hookBlock) {
70
- const startIdx = existingToml.indexOf(SPILLOVER_START);
71
- const endIdx = existingToml.indexOf(SPILLOVER_END);
72
- const aiwgSection = `${SPILLOVER_START}\n${hookBlock}\n${SPILLOVER_END}\n`;
73
- if (startIdx === -1 || endIdx === -1 || endIdx < startIdx) {
74
- const trimmed = existingToml.replace(/\n+$/, '');
75
- return (trimmed.length > 0 ? trimmed + '\n\n' : '') + aiwgSection;
71
+ const startIdx = markerIndex(existingToml, SPILLOVER_START);
72
+ const endIdx = markerIndex(existingToml, SPILLOVER_END, startIdx);
73
+ const section = `${SPILLOVER_START}\n${hookBlock.trimEnd()}\n${SPILLOVER_END}`;
74
+ if (startIdx === -1 || endIdx === -1) {
75
+ return existingToml + (existingToml ? (existingToml.endsWith('\n') ? '\n' : '\n\n') : '') + section + '\n';
76
76
  }
77
- const before = existingToml.slice(0, startIdx);
78
- const after = existingToml.slice(endIdx + SPILLOVER_END.length).replace(/^\n+/, '\n');
79
- return `${before}${aiwgSection}${after}`;
77
+ const bodyStart = startIdx + SPILLOVER_START.length;
78
+ const body = existingToml.slice(bodyStart, endIdx);
79
+ const tables = body.matchAll(/^[ \t]*\[{1,2}([^\]\r\n]+)\]{1,2}[^\r\n]*/gm);
80
+ let rescued = '';
81
+ for (const table of tables) {
82
+ const name = table[1].trim();
83
+ if (name === 'hooks' || name.startsWith('hooks.'))
84
+ continue;
85
+ // Comments immediately preceding the first user table belong to the user.
86
+ let boundary = table.index;
87
+ while (boundary > 0) {
88
+ const previous = body.lastIndexOf('\n', boundary - 2) + 1;
89
+ if (!/^[ \t]*(?:#[^\r\n]*)?\r?\n$/.test(body.slice(previous, boundary)))
90
+ break;
91
+ boundary = previous;
92
+ }
93
+ rescued = '\n' + body.slice(boundary);
94
+ break;
95
+ }
96
+ return existingToml.slice(0, startIdx) + section + rescued
97
+ + existingToml.slice(endIdx + SPILLOVER_END.length);
80
98
  }
81
- /**
82
- * Translate one HookSource to Codex TOML config.
83
- *
84
- * Writes to ~/.codex/config.toml (user-global), backing up the existing
85
- * file if no AIWG signature is found per ADR-3 §5.
86
- */
99
+ /** Translate one source, merging by ID without replacing other managed hooks. */
87
100
  export async function translateForCodex(source, options) {
88
- const result = {
89
- provider: 'codex',
90
- emittedPaths: [],
91
- warnings: [],
92
- skipped: false,
93
- };
101
+ const result = { provider: 'codex', emittedPaths: [], warnings: [], skipped: false };
94
102
  if (source.degradeOn?.includes('codex')) {
95
- result.skipped = true;
96
- result.skipReason = 'degrade-on declared codex';
97
- return result;
98
- }
99
- const configPath = path.join(process.env.CODEX_HOME || path.join(homedir(), '.codex'), 'config.toml');
100
- const block = renderCodexHookToml(source);
101
- if (block.trim().length === 0) {
102
- result.skipped = true;
103
- result.skipReason = 'no Codex-mapped events';
104
- return result;
103
+ return { ...result, skipped: true, skipReason: 'degrade-on declared codex' };
105
104
  }
105
+ const events = source.events.filter(event => CODEX_EVENTS.has(event));
106
+ if (!events.length)
107
+ return { ...result, skipped: true, skipReason: 'no Codex-mapped events' };
108
+ const directory = path.join(options.projectPath, '.codex');
109
+ const configPath = path.join(directory, 'hooks.json');
110
+ const promptHook = source.id === 'aiwg-prompt-discovery';
111
+ const scriptPath = path.join(directory, 'hooks', 'aiwg-prompt-discovery.cjs');
106
112
  if (options.dryRun) {
107
- result.emittedPaths.push(configPath + ' (dry-run)');
113
+ result.emittedPaths = [configPath, ...(promptHook ? [scriptPath] : [])].map(p => p + ' (dry-run)');
108
114
  return result;
109
115
  }
116
+ for (const target of [directory, configPath, ...(promptHook ? [path.dirname(scriptPath), scriptPath] : [])]) {
117
+ try {
118
+ if ((await fs.lstat(target)).isSymbolicLink())
119
+ throw new Error(`Refusing symlinked Codex hook target: ${target}`);
120
+ }
121
+ catch (err) {
122
+ if (err.code !== 'ENOENT')
123
+ throw err;
124
+ }
125
+ }
110
126
  let existing = '';
111
127
  try {
112
128
  existing = await fs.readFile(configPath, 'utf8');
@@ -115,16 +131,58 @@ export async function translateForCodex(source, options) {
115
131
  if (err.code !== 'ENOENT')
116
132
  throw err;
117
133
  }
118
- // Backup-and-rollback per ADR-3 §5.
119
- if (existing && !existing.includes(SPILLOVER_START)) {
134
+ const doc = existing ? JSON.parse(existing) : {};
135
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc)
136
+ || (doc.hooks !== undefined && (!doc.hooks || typeof doc.hooks !== 'object' || Array.isArray(doc.hooks)))) {
137
+ throw new Error(`Invalid Codex hooks object in ${configPath}`);
138
+ }
139
+ const hooks = doc.hooks ?? {};
140
+ let managed = false;
141
+ for (const [event, groups] of Object.entries(hooks)) {
142
+ if (!Array.isArray(groups) || groups.some(g => !g || !Array.isArray(g.hooks))) {
143
+ throw new Error(`Invalid Codex matcher groups for ${event}`);
144
+ }
145
+ hooks[event] = groups.flatMap(group => {
146
+ managed ||= group.hooks.some(h => h._aiwg_managed === true);
147
+ const kept = group.hooks.filter(h => !(h._aiwg_managed === true && h._aiwg_id === source.id));
148
+ return kept.length === group.hooks.length ? [group] : kept.length ? [{ ...group, hooks: kept }] : [];
149
+ });
150
+ }
151
+ if (promptHook) {
152
+ if (!source.args?.[0])
153
+ throw new Error('Prompt discovery source is missing its shared script');
154
+ await fs.mkdir(path.dirname(scriptPath), { recursive: true });
155
+ await fs.copyFile(source.args[0], scriptPath);
156
+ source = { ...source, args: ['-e', PROMPT_DISCOVERY_LAUNCHER] };
157
+ }
158
+ for (const event of events)
159
+ (hooks[event] ??= []).push({ hooks: [commandHook(source, promptHook)] });
160
+ doc.hooks = hooks;
161
+ await fs.mkdir(directory, { recursive: true });
162
+ if (existing && !managed) {
120
163
  const backupPath = `${configPath}.bak.${new Date().toISOString().replace(/[:.]/g, '-')}`;
121
164
  await fs.writeFile(backupPath, existing, 'utf8');
122
165
  result.warnings.push(`Backed up pre-existing config to ${backupPath}`);
123
166
  }
124
- const updated = injectHookBlock(existing, block);
125
- await fs.mkdir(path.dirname(configPath), { recursive: true });
126
- await fs.writeFile(configPath, updated, 'utf8');
127
- result.emittedPaths.push(configPath);
167
+ const temporary = `${configPath}.tmp.${randomUUID()}`;
168
+ try {
169
+ await fs.writeFile(temporary, JSON.stringify(doc, null, 2) + '\n', { encoding: 'utf8', flag: 'wx' });
170
+ await fs.rename(temporary, configPath);
171
+ }
172
+ finally {
173
+ await fs.rm(temporary, { force: true });
174
+ }
175
+ result.emittedPaths = [configPath, ...(promptHook ? [scriptPath] : [])];
128
176
  return result;
129
177
  }
178
+ /** Default Codex prompt hook deployment reuses the canonical bridge source. */
179
+ export async function installCodexPromptDiscovery(options) {
180
+ const { sources, errors } = await loadHookSources(options.frameworkRoot);
181
+ if (errors.length)
182
+ throw new Error(errors.join('\n'));
183
+ const source = sources.find(s => s.id === 'aiwg-prompt-discovery');
184
+ if (!source)
185
+ throw new Error('Missing canonical aiwg-prompt-discovery source');
186
+ return translateForCodex(source, options);
187
+ }
130
188
  //# sourceMappingURL=codex-translator.js.map
@@ -0,0 +1,50 @@
1
+ // Read Codex project trust without granting trust or inventing hook-review storage.
2
+ import { promises as fs } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import * as path from 'node:path';
5
+ import { getStaticTOMLValue, parseTOML } from 'toml-eslint-parser';
6
+ export const CODEX_HOOK_TRUST_NEXT_STEP = 'Trust this project in Codex, then approve the AIWG hook when Codex asks.';
7
+ export function codexHookTrustNextStep(trust) {
8
+ return trust && (trust.project !== 'trusted' || trust.hookReview !== 'approved')
9
+ ? CODEX_HOOK_TRUST_NEXT_STEP : '';
10
+ }
11
+ export async function readCodexHookTrust(projectPath) {
12
+ const root = path.resolve(projectPath);
13
+ try {
14
+ const doc = JSON.parse(await fs.readFile(path.join(root, '.codex/hooks.json'), 'utf8'));
15
+ const groups = doc?.hooks?.UserPromptSubmit;
16
+ if (!Array.isArray(groups) || !groups.some(group => Array.isArray(group?.hooks)
17
+ && group.hooks.some((hook) => hook?.type === 'command'
18
+ && hook._aiwg_managed === true && hook._aiwg_id === 'aiwg-prompt-discovery')))
19
+ return null;
20
+ await fs.access(path.join(root, '.codex/hooks/aiwg-prompt-discovery.cjs'));
21
+ }
22
+ catch {
23
+ // Missing/broken installations are handled by deployment drift checks.
24
+ return null;
25
+ }
26
+ // Codex 0.167 has no documented offline file signal for hook review.
27
+ const trust = { project: 'unknown', hookReview: 'unknown' };
28
+ const codexHome = process.env.CODEX_HOME || path.join(process.env.HOME || homedir(), '.codex');
29
+ try {
30
+ const bytes = await fs.readFile(path.resolve(codexHome, 'config.toml'), 'utf8');
31
+ const config = getStaticTOMLValue(parseTOML(bytes));
32
+ const level = config.projects?.[root]?.trust_level;
33
+ trust.project = level === 'trusted' ? 'trusted' : 'untrusted';
34
+ }
35
+ catch {
36
+ // Unreadable, missing, and invalid config cannot establish project trust.
37
+ }
38
+ return trust;
39
+ }
40
+ export async function diagnoseCodexHookTrust(projectPath) {
41
+ const trust = await readCodexHookTrust(projectPath);
42
+ const nextStep = codexHookTrustNextStep(trust);
43
+ return trust && nextStep ? {
44
+ // Review state is never observable offline, so a trusted project is only advisory.
45
+ severity: trust.project === 'trusted' ? 'info' : 'warning', code: 'codex-prompt-discovery-trust', path: '.codex/hooks.json',
46
+ message: 'Codex prompt-discovery hook installed but inactive or unverified (untrusted project or unreviewed hook). '
47
+ + `Project trust: ${trust.project}; hook review: ${trust.hookReview}. ${nextStep}`,
48
+ } : null;
49
+ }
50
+ //# sourceMappingURL=codex-trust.js.map
@@ -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
@@ -11,6 +11,7 @@ import { promises as fs } from 'node:fs';
11
11
  import * as path from 'node:path';
12
12
  import { homedir } from 'node:os';
13
13
  import { substituteEnvVars } from './shim.js';
14
+ import { PROMPT_DISCOVERY_GAPS } from './prompt-discovery-gaps.js';
14
15
  const HERMES_EVENT_MAP = {
15
16
  PreToolUse: 'pre_tool',
16
17
  PostToolUse: 'post_tool',
@@ -63,7 +64,8 @@ export async function translateForHermes(source, options) {
63
64
  };
64
65
  if (source.degradeOn?.includes('hermes')) {
65
66
  result.skipped = true;
66
- result.skipReason = 'degrade-on declared hermes';
67
+ result.skipReason = source.id === 'aiwg-prompt-discovery'
68
+ ? PROMPT_DISCOVERY_GAPS['hermes'] : 'degrade-on declared hermes';
67
69
  return result;
68
70
  }
69
71
  const events = source.events
@@ -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);