@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
@@ -27,17 +27,43 @@ export function directivePolarity(directive) {
27
27
  return /^(?:never|do not|don't|avoid)\b/i.test(directive) ? 'negative' : 'positive';
28
28
  }
29
29
  export function sensitiveEvidence(content) {
30
+ return sensitiveLineEvidence(content).map((finding) => finding.evidence);
31
+ }
32
+ function sensitiveLineEvidence(content) {
30
33
  const findings = [];
31
- for (const line of content.split('\n')) {
34
+ for (const [index, line] of content.split('\n').entries()) {
32
35
  if (/-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/.test(line)) {
33
- findings.push(`private-key material (${sha256(line).slice(0, 12)})`);
36
+ findings.push({ line: index + 1, evidence: `private-key material (${sha256(line).slice(0, 12)})` });
34
37
  }
35
- if (/\b(?:api[_-]?key|token|secret|password)\s*[:=]\s*(?!<|\$\{|\*{3}|example|placeholder)["']?[A-Za-z0-9_\-/.+=]{12,}/i.test(line)) {
36
- findings.push(`credential-like assignment (${sha256(line).slice(0, 12)})`);
38
+ // Inspect whole values before applying the length threshold: ellipses and
39
+ // redaction characters are documentation, including inside quoted agent bodies.
40
+ const assignments = line.matchAll(/\b(?:api[_-]?key|token|secret|password)\s*[:=]\s*["']?([A-Za-z0-9_\-/.+=…*]+)/gi);
41
+ for (const [, value] of assignments) {
42
+ if (value.length < 12 || /(?:\.{3}|…)$/.test(value)
43
+ || /^(?:example|placeholder|\*{3})/i.test(value) || /^x+$/i.test(value)
44
+ || (value.match(/\./g)?.length ?? 0) > value.length / 2)
45
+ continue;
46
+ findings.push({ line: index + 1, evidence: `credential-like assignment (${sha256(line).slice(0, 12)})` });
47
+ break;
37
48
  }
38
49
  }
39
50
  return findings;
40
51
  }
52
+ function operatorContext(relativePath, content, preserveLines = false) {
53
+ if (relativePath === 'WORKSPACE.md') {
54
+ const start = content.indexOf(WORKSPACE_OPERATOR_START);
55
+ const end = content.indexOf(WORKSPACE_OPERATOR_END);
56
+ if (start >= 0 && end > start) {
57
+ const offset = start + WORKSPACE_OPERATOR_START.length;
58
+ const body = content.slice(offset, end);
59
+ return preserveLines
60
+ ? '\n'.repeat(content.slice(0, offset).split('\n').length - 1) + stripGeneratedBlocks(body, true)
61
+ : body.trim();
62
+ }
63
+ return stripGeneratedBlocks(content, preserveLines);
64
+ }
65
+ return isGeneratedRootContext(relativePath, content) ? '' : stripGeneratedBlocks(content, preserveLines);
66
+ }
41
67
  // Directory names the context-graph walk always skips, regardless of where
42
68
  // the walk root is: VCS/build output that is never hand-authored project
43
69
  // content (#277, pre-existing) plus two reserved, self-identifying names
@@ -194,19 +220,10 @@ export async function auditWorkspaceContext(projectPath) {
194
220
  const content = await readOptional(path.join(projectPath, relativePath));
195
221
  if (content === null)
196
222
  continue;
197
- const operatorContent = relativePath === 'WORKSPACE.md'
198
- ? (() => {
199
- const start = content.indexOf(WORKSPACE_OPERATOR_START);
200
- const end = content.indexOf(WORKSPACE_OPERATOR_END);
201
- return start >= 0 && end > start
202
- ? content.slice(start + WORKSPACE_OPERATOR_START.length, end).trim()
203
- : stripGeneratedBlocks(content);
204
- })()
205
- : isGeneratedRootContext(relativePath, content)
206
- ? ''
207
- : stripGeneratedBlocks(content);
208
- for (const evidence of sensitiveEvidence(operatorContent))
209
- sensitiveFindings.push({ path: relativePath, evidence });
223
+ const operatorContent = operatorContext(relativePath, content);
224
+ for (const finding of sensitiveLineEvidence(operatorContext(relativePath, content, true))) {
225
+ sensitiveFindings.push({ path: relativePath, ...finding });
226
+ }
210
227
  sources.push({
211
228
  path: relativePath,
212
229
  provider: providerForPath(relativePath),
@@ -85,20 +85,26 @@ export function replaceBlock(content, start, end, block) {
85
85
  const renderedBlock = withLineEnding(block, dominantLineEnding(content));
86
86
  return content.slice(0, startIndex) + renderedBlock + content.slice(endIndex + end.length);
87
87
  }
88
- export function stripGeneratedBlocks(content) {
88
+ export function stripGeneratedBlocks(content, preserveLines = false) {
89
89
  let stripped = content;
90
90
  for (const [start, end] of GENERATED_BLOCKS) {
91
91
  while (stripped.includes(start) || stripped.includes(end)) {
92
- const replaced = replaceBlock(stripped, start, end, '');
92
+ const startIndex = stripped.indexOf(start);
93
+ const endIndex = stripped.indexOf(end);
94
+ const replacement = preserveLines && startIndex >= 0 && endIndex > startIndex
95
+ ? '\n'.repeat(stripped.slice(startIndex, endIndex + end.length).split('\n').length - 1)
96
+ : '';
97
+ const replaced = replaceBlock(stripped, start, end, replacement);
93
98
  if (replaced === null)
94
99
  break;
95
100
  stripped = replaced;
96
101
  }
97
102
  }
98
- return stripped
99
- .replace(/^(?:\uFEFF)?<!-- aiwg-managed -->[ \t]*(?:\r?\n|$)/, '')
100
- .replace(/^<!-- Generated by AIWG[^\r\n]*-->[ \t]*(?:\r?\n|$)/, '')
101
- .trim();
103
+ const removeMetadata = (text) => preserveLines ? text.replace(/[^\n]/g, '') : '';
104
+ stripped = stripped
105
+ .replace(/^(?:\uFEFF)?<!-- aiwg-managed -->[ \t]*(?:\r?\n|$)/, removeMetadata)
106
+ .replace(/^<!-- Generated by AIWG[^\r\n]*-->[ \t]*(?:\r?\n|$)/, removeMetadata);
107
+ return preserveLines ? stripped : stripped.trim();
102
108
  }
103
109
  export function isGeneratedRootContext(relativePath, content) {
104
110
  const head = maskCodeRegions(content.replace(/^\uFEFF/, '')).split('\n').slice(0, 12).join('\n');
@@ -7,6 +7,7 @@ import { auditWorkspaceContext } from './workspace-audit.js';
7
7
  import { PROVIDER_BOOTSTRAP_START, readOptional, resolveProjectRelative, WORKSPACE_MANAGED_START, WORKSPACE_OPERATOR_START, WORKSPACE_SIGNATURE, } from './workspace-context-shared.js';
8
8
  import { BOOTSTRAP_AUTHORITY_SIGNATURE, WORKSPACE_PRECEDENCE_SIGNATURE, WORKSPACE_PRECEDENCE_SUPERSEDED } from './workspace-document.js';
9
9
  import { configuredProviders } from './workspace-migration.js';
10
+ import { diagnoseCodexHookTrust } from '../hook-bridge/codex-trust.js';
10
11
  import { maskCodeRegions } from './code-regions.js';
11
12
  export { maskCodeRegions } from './code-regions.js';
12
13
  export function markdownLinks(content) {
@@ -36,6 +37,44 @@ export async function workspaceLinkedFiles(projectPath) {
36
37
  }
37
38
  export async function diagnoseWorkspaceContext(projectPath) {
38
39
  const diagnostics = [];
40
+ const codexTrust = await diagnoseCodexHookTrust(projectPath);
41
+ if (codexTrust)
42
+ diagnostics.push(codexTrust);
43
+ const root = path.resolve(projectPath);
44
+ const scopes = new Map();
45
+ // Ordinary subdirectories share root policy; repository/project markers start a separate scope.
46
+ function directoryScope(directory) {
47
+ if (directory === root || !directory.startsWith(`${root}${path.sep}`))
48
+ return Promise.resolve(null);
49
+ let scope = scopes.get(directory);
50
+ if (!scope) {
51
+ scope = (async () => {
52
+ const markers = await Promise.all(['.git', '.aiwg/aiwg.config'].map(async (marker) => {
53
+ try {
54
+ await fs.stat(path.join(directory, marker));
55
+ return true;
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }));
61
+ return markers.some(Boolean)
62
+ ? path.relative(root, directory).replace(/\\/g, '/')
63
+ : directoryScope(path.dirname(directory));
64
+ })();
65
+ scopes.set(directory, scope);
66
+ }
67
+ return scope;
68
+ }
69
+ async function reportSourceDiagnostic(diagnostic, sources) {
70
+ const sourceScopes = await Promise.all(sources.map((source) => directoryScope(path.dirname(path.resolve(root, source)))));
71
+ const nestedOnly = sourceScopes.length > 0 && sourceScopes.every((scope) => scope !== null);
72
+ diagnostics.push(nestedOnly ? {
73
+ ...diagnostic,
74
+ severity: diagnostic.severity === 'error' ? 'warning' : diagnostic.severity,
75
+ message: `Advisory for nested project(s) ${[...new Set(sourceScopes)].join(', ')}: ${diagnostic.message}`,
76
+ } : diagnostic);
77
+ }
39
78
  const { existing, notes } = await readAiwgOperatorNotes(projectPath);
40
79
  if (existing !== null && existing !== notes)
41
80
  diagnostics.push({
@@ -87,7 +126,7 @@ export async function diagnoseWorkspaceContext(projectPath) {
87
126
  }
88
127
  }
89
128
  for (const conflict of audit.conflicts) {
90
- diagnostics.push({ severity: 'error', code: 'directive-conflict', message: `Conflicting duplicate directive group '${conflict.key}' appears in ${conflict.sources.map((source) => source.path).join(', ')}.` });
129
+ await reportSourceDiagnostic({ severity: 'error', code: 'directive-conflict', message: `Conflicting duplicate directive group '${conflict.key}' appears in ${conflict.sources.map((source) => source.path).join(', ')}.` }, conflict.sources.map((source) => source.path));
91
130
  }
92
131
  // One diagnostic per source pair, not one per duplicated line: a shared
93
132
  // pointer stub otherwise reports every line as a separate policy conflict
@@ -102,13 +141,13 @@ export async function diagnoseWorkspaceContext(projectPath) {
102
141
  const paths = pair.split(', ');
103
142
  const bodies = paths.map((item) => operatorBodies.get(item) ?? '');
104
143
  const wholeFileDuplicate = bodies.every((body) => body.length > 0 && body === bodies[0]);
105
- diagnostics.push({
144
+ await reportSourceDiagnostic({
106
145
  severity: wholeFileDuplicate ? 'info' : 'warning',
107
146
  code: 'duplicate-directive',
108
147
  message: wholeFileDuplicate
109
148
  ? `${pair} carry identical operator content (${count} directive(s)); keep one copy or accept the shared stub.`
110
149
  : `${count} identical directive(s) duplicated across ${pair}.`,
111
- });
150
+ }, paths);
112
151
  }
113
152
  for (const source of audit.sources) {
114
153
  if (!source.path.replace(/\\/g, '/').includes('/context/providers/') || !source.operatorContent.trim())
@@ -121,7 +160,8 @@ export async function diagnoseWorkspaceContext(projectPath) {
121
160
  });
122
161
  }
123
162
  for (const finding of audit.sensitiveFindings) {
124
- diagnostics.push({ severity: 'error', code: 'possible-secret', message: 'Possible credential value found in context; remove it.', path: finding.path });
163
+ const location = finding.line ? `${finding.path}:${finding.line}` : finding.path;
164
+ await reportSourceDiagnostic({ severity: 'error', code: 'possible-secret', message: `Possible credential value found in ${location}; remove it.`, path: finding.path }, [finding.path]);
125
165
  }
126
166
  // #2512 — "points at WORKSPACE.md" is not the same as "carries current policy".
127
167
  // Without this, a workspace generated before the precedence correction reads
@@ -1,7 +1,7 @@
1
1
  // Render and preserve the canonical WORKSPACE document and resident memory.
2
2
  import * as path from 'node:path';
3
3
  import { readAiwgConfigCandidate } from '../../config/aiwg-config.js';
4
- import { projectControlPath } from '../../config/project-artifacts.js';
4
+ import { isProjectArtifactRootExternal, projectControlPath } from '../../config/project-artifacts.js';
5
5
  import { listProviderDefinitions } from '../../providers/provider-definitions.js';
6
6
  import { resolveRulesInlineBudget } from '../../rules/inline-budget.mjs';
7
7
  import { writeContextFileSync } from './context-file-safety.js';
@@ -131,7 +131,10 @@ export function buildWorkspaceManagedBlock(projectPath, providerFiles = [], resi
131
131
  '',
132
132
  '- Before any agent or provider writes AIWG payload, run `aiwg artifacts path --json --check-write` and write beneath its `artifact_root`.',
133
133
  '- Treat `.aiwg/...` in skills and templates as a logical artifact path, not necessarily a repository-local filesystem path.',
134
- '- Only `aiwg.config`, `frameworks/registry.json`, and optional operator-only `AIWG.md` notes belong in the repository-local `.aiwg` control plane; generated framework context lives in root `AIWG.md`.',
134
+ '- Configure an external artifact root with a path in `.aiwg-location`; `AIWG_ARTIFACTS_PATH` overrides that pointer.',
135
+ isProjectArtifactRootExternal(projectPath)
136
+ ? '- Only `aiwg.config`, `frameworks/registry.json`, and optional operator-only `AIWG.md` notes belong in the repository-local `.aiwg` control plane; generated framework context lives in root `AIWG.md`.'
137
+ : '- With no external artifact root configured, repository-local `.aiwg` stores AIWG payload alongside control-plane files; generated framework context lives in root `AIWG.md`.',
135
138
  '- If the configured external artifact root is unavailable, stop with an actionable error; never fall back to repository-local payload.',
136
139
  '',
137
140
  '### Linked Context',
@@ -156,7 +156,8 @@ export async function migrateWorkspaceContext(projectPath, options = {}) {
156
156
  const audit = await auditWorkspaceContext(projectPath);
157
157
  const sensitiveFindingCount = audit.sensitiveFindings.length;
158
158
  if (sensitiveFindingCount > 0) {
159
- throw new Error(`Migration refused: ${sensitiveFindingCount} possible secret/credential value(s) found. Remove them before migration.`);
159
+ const locations = audit.sensitiveFindings.map((finding) => finding.line ? `${finding.path}:${finding.line}` : finding.path);
160
+ throw new Error(`Migration refused: ${sensitiveFindingCount} possible secret/credential value(s) found in ${locations.join(', ')}. Remove them before migration.`);
160
161
  }
161
162
  if (audit.conflicts.length > 0 && !options.allowConflicts) {
162
163
  throw new Error(`Migration refused: ${audit.conflicts.length} ambiguous directive conflict(s). Review the deterministic audit or pass --allow-conflicts to preserve each source separately.`);
@@ -1,114 +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';
16
- import { PROMPT_DISCOVERY_GAPS } from './prompt-discovery-gaps.js';
6
+ import { loadHookSources } from './loader.js';
17
7
  import { tomlString } from '../../mcp/toml-string.mjs';
18
- /** Codex-native event names (subset; extend when verified against codex-rs). */
19
- const CODEX_EVENT_MAP = {
20
- PreToolUse: 'before_tool',
21
- PostToolUse: 'after_tool',
22
- UserPromptSubmit: 'before_prompt',
23
- SessionStart: 'session_start',
24
- SessionEnd: 'session_end',
25
- Stop: 'session_end',
26
- };
27
- /**
28
- * Render a single TOML hook entry for a Codex config block.
29
- *
30
- * Codex's hook TOML shape (per the assessment):
31
- * [[hooks.<event>]]
32
- * command = "..."
33
- * args = ["..."]
34
- * _aiwg_managed = true
35
- *
36
- * Operators add their own hooks at the same shape; the _aiwg_managed flag
37
- * lets `aiwg remove --addon aiwg-hooks` distinguish AIWG entries from
38
- * operator-authored ones.
39
- */
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. */
40
41
  export function renderCodexHookToml(source) {
41
42
  const lines = [];
43
+ const hook = commandHook(source);
42
44
  for (const event of source.events) {
43
- const codexEvent = CODEX_EVENT_MAP[event];
44
- if (!codexEvent)
45
+ if (!CODEX_EVENTS.has(event))
45
46
  continue;
46
- const subCommand = substituteEnvVars(source.command, 'codex');
47
- const subArgs = (source.args || []).map((a) => substituteEnvVars(a, 'codex'));
48
- lines.push(`[[hooks.${codexEvent}]]`);
47
+ lines.push(`[[hooks.${event}]]`);
49
48
  lines.push(`# AIWG-managed hook: ${`${source.id} — ${source.description}`.replace(/[\x00-\x1f\x7f]/g, ' ')}`);
50
- lines.push(`command = ${tomlString(subCommand)}`);
51
- if (subArgs.length > 0) {
52
- lines.push(`args = [${subArgs.map(tomlString).join(', ')}]`);
53
- }
54
- if (source.safetyCritical) {
55
- lines.push(`# safety-critical: cannot be auto-removed without --allow-unsafe-shadow`);
56
- }
57
- lines.push(`_aiwg_managed = true`);
58
- lines.push(`_aiwg_id = ${tomlString(source.id)}`);
59
- 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)}`, '');
60
55
  }
61
56
  return lines.join('\n');
62
57
  }
63
58
  const SPILLOVER_START = '# >>> AIWG-managed hooks (do not edit between markers)';
64
59
  const SPILLOVER_END = '# <<< AIWG-managed hooks';
65
- /**
66
- * Inject AIWG-managed hook block into existing TOML config, preserving
67
- * everything outside the markers. Idempotent — replaces an existing block
68
- * rather than appending.
69
- */
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. */
70
70
  export function injectHookBlock(existingToml, hookBlock) {
71
- const startIdx = existingToml.indexOf(SPILLOVER_START);
72
- const endIdx = existingToml.indexOf(SPILLOVER_END);
73
- const aiwgSection = `${SPILLOVER_START}\n${hookBlock}\n${SPILLOVER_END}\n`;
74
- if (startIdx === -1 || endIdx === -1 || endIdx < startIdx) {
75
- const trimmed = existingToml.replace(/\n+$/, '');
76
- 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';
77
76
  }
78
- const before = existingToml.slice(0, startIdx);
79
- const after = existingToml.slice(endIdx + SPILLOVER_END.length).replace(/^\n+/, '\n');
80
- 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);
81
98
  }
82
- /**
83
- * Translate one HookSource to Codex TOML config.
84
- *
85
- * Writes to ~/.codex/config.toml (user-global), backing up the existing
86
- * file if no AIWG signature is found per ADR-3 §5.
87
- */
99
+ /** Translate one source, merging by ID without replacing other managed hooks. */
88
100
  export async function translateForCodex(source, options) {
89
- const result = {
90
- provider: 'codex',
91
- emittedPaths: [],
92
- warnings: [],
93
- skipped: false,
94
- };
101
+ const result = { provider: 'codex', emittedPaths: [], warnings: [], skipped: false };
95
102
  if (source.degradeOn?.includes('codex')) {
96
- result.skipped = true;
97
- result.skipReason = source.id === 'aiwg-prompt-discovery'
98
- ? PROMPT_DISCOVERY_GAPS['codex'] : 'degrade-on declared codex';
99
- return result;
100
- }
101
- const configPath = path.join(process.env.CODEX_HOME || path.join(homedir(), '.codex'), 'config.toml');
102
- const block = renderCodexHookToml(source);
103
- if (block.trim().length === 0) {
104
- result.skipped = true;
105
- result.skipReason = 'no Codex-mapped events';
106
- return result;
103
+ return { ...result, skipped: true, skipReason: 'degrade-on declared codex' };
107
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');
108
112
  if (options.dryRun) {
109
- result.emittedPaths.push(configPath + ' (dry-run)');
113
+ result.emittedPaths = [configPath, ...(promptHook ? [scriptPath] : [])].map(p => p + ' (dry-run)');
110
114
  return result;
111
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
+ }
112
126
  let existing = '';
113
127
  try {
114
128
  existing = await fs.readFile(configPath, 'utf8');
@@ -117,16 +131,58 @@ export async function translateForCodex(source, options) {
117
131
  if (err.code !== 'ENOENT')
118
132
  throw err;
119
133
  }
120
- // Backup-and-rollback per ADR-3 §5.
121
- 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) {
122
163
  const backupPath = `${configPath}.bak.${new Date().toISOString().replace(/[:.]/g, '-')}`;
123
164
  await fs.writeFile(backupPath, existing, 'utf8');
124
165
  result.warnings.push(`Backed up pre-existing config to ${backupPath}`);
125
166
  }
126
- const updated = injectHookBlock(existing, block);
127
- await fs.mkdir(path.dirname(configPath), { recursive: true });
128
- await fs.writeFile(configPath, updated, 'utf8');
129
- 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] : [])];
130
176
  return result;
131
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
+ }
132
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