@aiwg/cli 2026.11.1 → 2026.11.3

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 (120) 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/capability-matrix.yaml +2 -2
  4. package/agentic/code/providers/model-capabilities.v1.json +44 -39
  5. package/agentic/code/providers/model-catalog.v1.json +3 -3
  6. package/dist/src/artifacts/cli.js +10 -11
  7. package/dist/src/artifacts/discover-cli-help.js +25 -0
  8. package/dist/src/artifacts/discover-session-facets.js +2 -1
  9. package/dist/src/artifacts/fortemi-core-prebuilt-freshness.js +28 -0
  10. package/dist/src/artifacts/fortemi-core-sync.js +3 -0
  11. package/dist/src/artifacts/framework-capabilities.js +4 -0
  12. package/dist/src/artifacts/framework-source-digest.js +1 -1
  13. package/dist/src/artifacts/index-builder.js +10 -10
  14. package/dist/src/artifacts/index-dependencies.js +72 -0
  15. package/dist/src/artifacts/query-engine-discover-output.js +13 -5
  16. package/dist/src/artifacts/query-engine-discover.js +49 -21
  17. package/dist/src/artifacts/query-engine-entries.js +56 -2
  18. package/dist/src/artifacts/query-engine-options.js +14 -1
  19. package/dist/src/artifacts/query-engine-scoring.js +8 -4
  20. package/dist/src/artifacts/query-engine-show-card.js +2 -0
  21. package/dist/src/artifacts/query-engine-show-load.js +1 -1
  22. package/dist/src/artifacts/query-engine-show.js +3 -1
  23. package/dist/src/artifacts/query-engine-templates.js +33 -0
  24. package/dist/src/artifacts/query-engine-verbose.js +25 -0
  25. package/dist/src/artifacts/relations-builder.js +49 -4
  26. package/dist/src/artifacts/relations.js +9 -0
  27. package/dist/src/artifacts/template-references.js +42 -0
  28. package/dist/src/artifacts/types.js +1 -1
  29. package/dist/src/cli/handlers/bundle-reconciliation.js +7 -3
  30. package/dist/src/cli/handlers/checkpoint-handoff.js +48 -0
  31. package/dist/src/cli/handlers/checkpoint-record.js +20 -0
  32. package/dist/src/cli/handlers/checkpoint.js +50 -17
  33. package/dist/src/cli/handlers/dataset.js +17 -0
  34. package/dist/src/cli/handlers/decision.js +1 -1
  35. package/dist/src/cli/handlers/doctor-args.js +3 -1
  36. package/dist/src/cli/handlers/doctor-help.js +2 -1
  37. package/dist/src/cli/handlers/help.js +1 -1
  38. package/dist/src/cli/handlers/refresh-bundles.js +2 -1
  39. package/dist/src/cli/handlers/refresh-managed-deployment.js +196 -0
  40. package/dist/src/cli/handlers/refresh.js +10 -2
  41. package/dist/src/cli/handlers/subcommands-discovery.js +8 -1
  42. package/dist/src/cli/handlers/use.js +26 -5
  43. package/dist/src/cli/services/deployment-verification.js +11 -7
  44. package/dist/src/config/decision-config.js +2 -1
  45. package/dist/src/config/jev-credential-reference.js +56 -0
  46. package/dist/src/config/user-config.js +13 -19
  47. package/dist/src/config/worker-write.js +4 -10
  48. package/dist/src/decision/ask.js +3 -2
  49. package/dist/src/decision/jev-credentials.js +22 -0
  50. package/dist/src/decision/ledger.js +15 -15
  51. package/dist/src/decision/offload.js +7 -8
  52. package/dist/src/decision/openbao-kv-resolver.mjs +96 -0
  53. package/dist/src/decision/openbao-runtime.js +101 -0
  54. package/dist/src/delivery/pr.js +2 -0
  55. package/dist/src/delivery/template-sections.js +56 -0
  56. package/dist/src/extensions/claude-hooks-installer.js +61 -53
  57. package/dist/src/extensions/managed-hook-script-state.js +48 -0
  58. package/dist/src/extensions/muse-managed-hooks.js +49 -0
  59. package/dist/src/issues/cli.js +3 -0
  60. package/dist/src/issues/external-cli.js +4 -1
  61. package/dist/src/issues/live.js +9 -2
  62. package/dist/src/issues/local.js +5 -1
  63. package/dist/src/issues/tracker-policy.js +11 -1
  64. package/dist/src/mcp/json-document.d.mts +2 -0
  65. package/dist/src/models/model-capabilities.v1.json +44 -39
  66. package/dist/src/models/model-catalog.v1.json +3 -3
  67. package/dist/src/models/provider-policy.js +8 -0
  68. package/dist/src/models/worker-health-readiness.js +20 -4
  69. package/dist/src/models/worker-health-snapshot.js +29 -0
  70. package/dist/src/models/worker-installation.d.mts +5 -1
  71. package/dist/src/models/worker-installation.mjs +11 -5
  72. package/dist/src/models/worker-qualification-policy.js +54 -0
  73. package/dist/src/providers/capability-matrix.yaml +2 -2
  74. package/dist/src/providers/skill-ownership.d.mts +1 -0
  75. package/dist/src/providers/transformation-receipt-integration.js +4 -2
  76. package/dist/src/providers/transformation-receipt.js +4 -2
  77. package/dist/src/serve/worker-invocation.js +4 -2
  78. package/dist/src/smiths/context-pipeline/workspace-audit.js +34 -17
  79. package/dist/src/smiths/context-pipeline/workspace-context-shared.js +12 -6
  80. package/dist/src/smiths/context-pipeline/workspace-doctor.js +48 -4
  81. package/dist/src/smiths/context-pipeline/workspace-document.js +5 -2
  82. package/dist/src/smiths/context-pipeline/workspace-migration.js +2 -1
  83. package/dist/src/smiths/hook-bridge/codex-translator.js +150 -94
  84. package/dist/src/smiths/hook-bridge/codex-trust.js +50 -0
  85. package/dist/src/smiths/hook-bridge/factory-hook-config.js +132 -0
  86. package/dist/src/smiths/hook-bridge/factory-translator.js +88 -33
  87. package/dist/src/smiths/hook-bridge/factory-trust.js +56 -0
  88. package/dist/src/smiths/hook-bridge/index.js +3 -3
  89. package/dist/src/smiths/hook-bridge/loader.js +10 -2
  90. package/dist/src/smiths/hook-bridge/prompt-discovery-gaps.js +0 -1
  91. package/dist/src/storage/workspace-permissions-health.js +64 -0
  92. package/dist/src/storage/workspace-permissions.js +51 -0
  93. package/package.json +6 -1
  94. package/tools/agents/providers/base-files.mjs +2 -1
  95. package/tools/agents/providers/base-flat-artifacts.mjs +6 -3
  96. package/tools/agents/providers/base-models-platforms.mjs +3 -3
  97. package/tools/agents/providers/base-skill-copy.mjs +2 -0
  98. package/tools/agents/providers/bound-rules-pointer.mjs +21 -0
  99. package/tools/agents/providers/claude-post-deploy.mjs +9 -5
  100. package/tools/agents/providers/codex-post-deploy.mjs +10 -0
  101. package/tools/agents/providers/factory-hooks.mjs +43 -0
  102. package/tools/agents/providers/factory.mjs +4 -91
  103. package/tools/agents/providers/muse-hooks.mjs +4 -43
  104. package/tools/agents/providers/muse-prompt-discovery.mjs +3 -7
  105. package/tools/agents/providers/packaged-codex-agents.mjs +48 -0
  106. package/tools/agents/providers/rule-delivery-surface.mjs +4 -4
  107. package/tools/agents/providers/rule-presentation.mjs +6 -5
  108. package/tools/agents/providers/rule-projection.mjs +10 -2
  109. package/tools/agents/providers/rule-startup.mjs +8 -1
  110. package/tools/cli/decision-offload-report.mjs +9 -2
  111. package/tools/plugin/issue-template-copies.mjs +24 -0
  112. package/tools/plugin/package-plugins.mjs +17 -4
  113. package/tools/ralph-external/lib/claude-adapter.mjs +2 -2
  114. package/tools/ralph-external/lib/factory-adapter.mjs +7 -8
  115. package/tools/ralph-external/lib/worker-artifacts.mjs +4 -2
  116. package/tools/ralph-external/lib/worker-final.mjs +43 -8
  117. package/tools/ralph-external/lib/worker-launch-cli.mjs +10 -1
  118. package/tools/ralph-external/lib/worker-prompt.mjs +35 -0
  119. package/tools/ralph-external/lib/worker-run-directory-refusal.mjs +8 -0
  120. package/tools/ralph-external/session-launcher.mjs +10 -7
@@ -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.3",
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
  }
@@ -0,0 +1,43 @@
1
+ // Install Factory user preflight and project discovery through the existing hook bridge.
2
+ import path from 'node:path';
3
+ import fs from 'node:fs';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { importImpl } from '../../_resolve-impl.mjs';
6
+
7
+ export async function deployFactoryHooks(dryRun, projectPath) {
8
+ const config = await importImpl(import.meta.url, 'smiths/hook-bridge/factory-hook-config.js');
9
+ const { managedFactoryHooks, installFactoryPromptDiscovery } = await importImpl(import.meta.url, 'smiths/hook-bridge/factory-translator.js');
10
+ const { captureDeploymentOutputs, recordDeploymentOutputs } = await importImpl(import.meta.url, 'providers/deployment-ownership.mjs');
11
+ const home = process.env.HOME || process.env.USERPROFILE;
12
+ if (home) {
13
+ const directory = path.join(home, '.factory');
14
+ for (const file of [directory, path.join(directory, 'hooks'), ...['hooks.json', 'settings.json', 'hooks/hooks.json'].map(name => path.join(directory, name))]) {
15
+ if (fs.existsSync(file) && fs.lstatSync(file).isSymbolicLink()) throw new Error(`Refusing symlinked Factory hook target: ${file}`);
16
+ }
17
+ const state = config.factoryHookDocuments(directory);
18
+ const roots = [state.file, state.settingsFile, state.legacyFile, path.join(directory, '.aiwg-manifest.json')];
19
+ const before = dryRun ? undefined : captureDeploymentOutputs(roots);
20
+ const removed = config.removeFactoryManaged(state.doc, 'aiwg-session');
21
+ // A project deploy carries the preflight in the project hooks.json; user scope only
22
+ // migrates AIWG's old copy away, so the session hook never runs twice.
23
+ if (!projectPath) {
24
+ const hook = managedFactoryHooks()[0];
25
+ ((state.doc.hooks ??= {})[hook.event] ??= []).push({ matcher: '*', hooks: [{
26
+ type: 'command', command: hook.command, _aiwg_managed: true, _aiwg_id: hook.id,
27
+ }] });
28
+ }
29
+ // Only touch user files when there is something to migrate or install: creating
30
+ // ~/.factory/hooks.json would shadow the user's settings.json hooks fallback.
31
+ const changed = removed || state.migratedSettings || fs.existsSync(state.legacyFile) || !projectPath;
32
+ if (dryRun) { if (changed) console.log(`[dry-run] Would update Factory user hooks in ${state.file}`); }
33
+ else if (changed) {
34
+ config.saveFactoryHooks(state);
35
+ recordDeploymentOutputs(before, roots, { frameworkSlug: 'aiwg-hooks', claimUnchangedSettings: false, writtenFiles: [state.file] });
36
+ }
37
+ }
38
+ if (projectPath) {
39
+ const frameworkRoot = fileURLToPath(new URL('../../../', import.meta.url));
40
+ const result = await installFactoryPromptDiscovery({ projectPath, frameworkRoot, dryRun });
41
+ for (const warning of result.warnings) console.warn(warning);
42
+ }
43
+ }
@@ -710,95 +710,8 @@ export function enableFactoryCustomDroids(dryRun) {
710
710
  // Factory Hooks
711
711
  // ============================================================================
712
712
 
713
- /**
714
- * Deploy SessionStart hook for AIWG pre-flight checks.
715
- *
716
- * Writes a SessionStart hook to ~/.factory/settings.json that runs
717
- * `aiwg sync --dry-run --quiet` on every new session. Preserves
718
- * existing hooks and settings.
719
- */
720
- export function deployFactoryHooks(dryRun) {
721
- const homeDir = process.env.HOME || process.env.USERPROFILE;
722
- if (!homeDir) {
723
- console.warn('Could not determine home directory, skipping Factory hooks configuration');
724
- return;
725
- }
726
-
727
- const settingsDir = path.join(homeDir, '.factory');
728
- const settingsPath = path.join(settingsDir, 'settings.json');
729
-
730
- let settings = {};
731
- let originalContent = '';
732
- let hasExistingFile = false;
733
-
734
- // Read existing settings if present
735
- if (fs.existsSync(settingsPath)) {
736
- hasExistingFile = true;
737
- try {
738
- originalContent = fs.readFileSync(settingsPath, 'utf8');
739
- const jsonContent = stripJsonComments(originalContent);
740
- settings = JSON.parse(jsonContent);
741
- } catch (err) {
742
- console.warn(`Warning: Could not parse Factory settings.json for hooks: ${err.message}`);
743
- console.warn('Skipping hook deployment to avoid corrupting settings file.');
744
- return;
745
- }
746
- }
747
-
748
- // Define the AIWG pre-flight hook
749
- const aiwgHook = {
750
- type: 'command',
751
- command: 'aiwg sync --dry-run --quiet'
752
- };
753
-
754
- const aiwgMatcher = {
755
- matcher: '*',
756
- hooks: [aiwgHook]
757
- };
758
-
759
- // Initialize hooks structure if missing
760
- if (!settings.hooks) {
761
- settings.hooks = {};
762
- }
763
- if (!settings.hooks.SessionStart) {
764
- settings.hooks.SessionStart = [];
765
- }
766
-
767
- // Check if AIWG hook already exists (by command string)
768
- const alreadyInstalled = settings.hooks.SessionStart.some(entry =>
769
- entry.hooks?.some(h => h.command && h.command.includes('aiwg sync'))
770
- );
771
-
772
- if (alreadyInstalled) {
773
- console.log('Factory SessionStart hook already installed for AIWG pre-flight');
774
- return;
775
- }
776
-
777
- // Add the hook
778
- settings.hooks.SessionStart.push(aiwgMatcher);
779
-
780
- if (dryRun) {
781
- console.log(`[dry-run] Would add SessionStart hook to ${settingsPath}`);
782
- console.log(`[dry-run] Hook: aiwg sync --dry-run --quiet`);
783
- } else {
784
- if (!fs.existsSync(settingsDir)) {
785
- fs.mkdirSync(settingsDir, { recursive: true });
786
- }
787
-
788
- // Parsed successfully, so the merge is safe to write back. It is written
789
- // as canonical JSON, which drops operator comments and formatting, so
790
- // keep a timestamped copy of a hand-edited user-global file first.
791
- const updatedContent = JSON.stringify(settings, null, 2) + '\n';
792
- if (hasExistingFile && originalContent !== JSON.stringify(JSON.parse(stripJsonComments(originalContent)), null, 2) + '\n') {
793
- const backupPath = `${settingsPath}.aiwg-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`;
794
- fs.copyFileSync(settingsPath, backupPath);
795
- console.log(`Backed up ${settingsPath} to ${backupPath} (comments and formatting are not preserved)`);
796
- }
797
- fs.writeFileSync(settingsPath, updatedContent, 'utf8');
798
- console.log(`Deployed SessionStart hook to ${settingsPath}`);
799
- console.log('Hook: aiwg sync --dry-run --quiet (runs on every new Factory session)');
800
- }
801
- }
713
+ export { deployFactoryHooks } from './factory-hooks.mjs';
714
+ import { deployFactoryHooks } from './factory-hooks.mjs';
802
715
 
803
716
  // ============================================================================
804
717
  // Post-Deployment
@@ -812,7 +725,7 @@ export async function postDeploy(targetDir, opts) {
812
725
  enableFactoryCustomDroids(opts.dryRun);
813
726
 
814
727
  // Deploy SessionStart hook for AIWG pre-flight checks
815
- deployFactoryHooks(opts.dryRun);
728
+ if (opts.hooks !== false) await deployFactoryHooks(opts.dryRun, opts.scope === 'user' ? undefined : targetDir);
816
729
 
817
730
  // Create/update AGENTS.md if requested
818
731
  if (opts.createAgentsMd) {
@@ -901,7 +814,7 @@ export function generatePluginBundle(targetDir, opts) {
901
814
  hooks: [
902
815
  {
903
816
  type: 'command',
904
- command: 'aiwg sync --dry-run --quiet'
817
+ command: 'aiwg refresh --dry-run --quiet'
905
818
  }
906
819
  ]
907
820
  }
@@ -54,9 +54,11 @@ import path from 'node:path';
54
54
  import { randomUUID } from 'node:crypto';
55
55
  import { importImpl } from '../../_resolve-impl.mjs';
56
56
  import { stripJsonComments } from './base.mjs';
57
- import { promptDiscoveryHook, deployPromptDiscovery } from './muse-prompt-discovery.mjs';
57
+ import { deployPromptDiscovery } from './muse-prompt-discovery.mjs';
58
58
  import { resolveMuseXdgSkillsDir, museXdgSkillsDirRemediation } from './muse-paths.mjs';
59
59
 
60
+ const { AIWG_MANAGED_HOOKS } = await importImpl(import.meta.url, 'extensions/muse-managed-hooks.js');
61
+
60
62
  const { assertConfigDestination, writeConfigAtomic, writeConfigTransaction } = await importImpl(import.meta.url, 'mcp/config-file.mjs');
61
63
 
62
64
  // ---------------------------------------------------------------------------
@@ -180,48 +182,7 @@ export const MUSE_HOOK_EVENTS = [
180
182
  'SessionEnd',
181
183
  ];
182
184
 
183
- /**
184
- * The AIWG-managed hook set. Each entry carries a stated reason (why this
185
- * hook runs on the operator's machine, outside the agent sandbox) and a
186
- * removal path (how the operator takes it back out).
187
- *
188
- * SessionEnd is intentionally *not* installed yet: Muse documents SessionEnd
189
- * as observational-only (its output cannot block termination or inject
190
- * context), and AIWG has no session-catalog note command to invoke — wiring
191
- * a hook to a command that does not exist would fail every session end.
192
- * When a real catalog-note command lands, it slots in here with its own
193
- * reason + removal path.
194
- */
195
- export const AIWG_MANAGED_HOOKS = [
196
- {
197
- id: 'aiwg-session-start',
198
- event: 'SessionStart',
199
- // Muse matcher groups take ONLY `hooks` + optional `matcher`; no
200
- // in-band AIWG tags (they would break the group).
201
- //
202
- // Muse Code 1.4.0 parses hook stdout as hook output: empty output, plain
203
- // text, and `{"hookSpecificOutput": ...}` are accepted, but any other
204
- // JSON key fails the hook ("unsupported `deploymentFailures` in output of
205
- // SessionStart hook output"). `aiwg refresh --quiet` prints its JSON
206
- // report, so stdout is discarded; the exit status still records a failed
207
- // drift check in Muse's hook log. `--provider muse` is required because
208
- // provider detection is fail-closed for muse and would resolve `claude`.
209
- // Hook commands run through a shell, so the redirect is honored.
210
- group: {
211
- matcher: '*',
212
- hooks: [{ type: 'command', command: 'aiwg refresh --dry-run --quiet --provider muse > /dev/null', timeout: 60 }],
213
- },
214
- reason:
215
- 'Session-start drift check. Runs a read-only `aiwg refresh --dry-run --provider muse` ' +
216
- 'and records its exit status in the Muse hook log. Dry-run by construction: it ' +
217
- 'never mutates the repo, and its report is not injected into the session.',
218
- removal:
219
- 'Delete this matcher group from `.muse/hooks.json` (the one whose command is ' +
220
- '`aiwg refresh --dry-run --quiet --provider muse > /dev/null`), or run `aiwg use --provider muse --no-hooks` ' +
221
- 'to stop AIWG managing hooks for this project.',
222
- },
223
- promptDiscoveryHook,
224
- ];
185
+ export { AIWG_MANAGED_HOOKS };
225
186
 
226
187
  /** Canonical group payloads keyed by hook id, for merge/prune identity. */
227
188
  function managedGroupsById() {
@@ -3,13 +3,9 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
 
6
- export const promptDiscoveryHook = {
7
- id: 'aiwg-prompt-discovery',
8
- event: 'UserPromptSubmit',
9
- group: { matcher: '*', hooks: [{ type: 'command', command: 'node .muse/hooks/aiwg-prompt-discovery.cjs', timeout: 2 }] },
10
- reason: 'Discover the top three AIWG capabilities and inject next steps on each substantive prompt; bounded and fail open.',
11
- removal: 'Set AIWG_PROMPT_DISCOVERY=0, or remove this group from .muse/hooks.json.',
12
- };
6
+ import { importImpl } from '../../_resolve-impl.mjs';
7
+
8
+ export const { promptDiscoveryHook } = await importImpl(import.meta.url, 'extensions/muse-managed-hooks.js');
13
9
 
14
10
  export function deployPromptDiscovery(targetDir) {
15
11
  const directory = path.join(targetDir, '.muse', 'hooks');