@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
@@ -30,6 +30,7 @@ import { promises as fs } from 'node:fs';
30
30
  import * as path from 'node:path';
31
31
  import { captureDeploymentOutputs, recordDeploymentOutputs } from '../providers/deployment-ownership.mjs';
32
32
  import { mergeClaudeAttribution, undoClaudeAttribution } from './claude-attribution.js';
33
+ import { managedHookScriptState } from './managed-hook-script-state.js';
33
34
  /**
34
35
  * Hook script → Claude Code hook event mapping.
35
36
  *
@@ -38,11 +39,21 @@ import { mergeClaudeAttribution, undoClaudeAttribution } from './claude-attribut
38
39
  const HOOK_SCRIPTS = [
39
40
  { file: 'aiwg-permissions.cjs', events: { PermissionRequest: undefined } },
40
41
  { file: 'aiwg-session.cjs', events: { SessionStart: undefined } },
42
+ { file: 'aiwg-prompt-discovery.cjs', events: { UserPromptSubmit: undefined } },
41
43
  {
42
44
  file: 'aiwg-trace.cjs',
43
45
  events: { SubagentStart: 'start', SubagentStop: 'stop' },
44
46
  },
45
47
  ];
48
+ /** Canonical registrations shared by installation and the read-only drift check. */
49
+ export function managedClaudeHooks(sourceFiles) {
50
+ return HOOK_SCRIPTS.filter(({ file }) => sourceFiles.includes(file)).flatMap(({ file, events }) => Object.entries(events).map(([event, argument]) => ({
51
+ event,
52
+ script: path.posix.join('.claude', 'hooks', file),
53
+ hookId: file.replace(/\.(cjs|js)$/, ''),
54
+ command: `node ${path.posix.join('.claude', 'hooks', file)}${argument ? ` ${argument}` : ''}`,
55
+ })));
56
+ }
46
57
  /**
47
58
  * Migrate a legacy array-shaped `hooks` field to the object form Claude
48
59
  * Code expects. Returns the normalized object.
@@ -142,6 +153,11 @@ export async function installAiwgHooks(opts) {
142
153
  }
143
154
  const src = path.join(sourceHooksDir, file);
144
155
  const dst = path.join(claudeHooksDir, file);
156
+ const state = await managedHookScriptState(opts.projectPath, path.relative(opts.projectPath, dst), await fs.readFile(src));
157
+ if (state === 'operator-edited' || state === 'unreadable') {
158
+ result.warnings.push(`${dst}: kept (${state})`);
159
+ continue;
160
+ }
145
161
  if (opts.dryRun) {
146
162
  result.installedScripts.push(`${dst} (dry-run)`);
147
163
  continue;
@@ -194,67 +210,60 @@ export async function installAiwgHooks(opts) {
194
210
  result.warnings.push('Migrated legacy array-shaped hooks field to object form (#107).');
195
211
  }
196
212
  settings.hooks = hooksObj;
197
- for (const { file, events } of HOOK_SCRIPTS) {
198
- if (!sourceFiles.includes(file))
199
- continue;
213
+ for (const { event, script, hookId, command } of managedClaudeHooks(sourceFiles)) {
200
214
  // Claude Code parses hook commands as shell command strings. Keep the
201
215
  // embedded script path POSIX-style on every host: native Windows
202
216
  // backslashes are interpreted as escapes and collapse into a nonexistent
203
217
  // path such as `.claudehooksaiwg-session.cjs` (#133).
204
- const script = path.posix.join('.claude', 'hooks', file);
205
- const hookId = file.replace(/\.(cjs|js)$/, '');
206
- for (const [event, argument] of Object.entries(events)) {
207
- const command = `node ${script}${argument ? ` ${argument}` : ''}`;
208
- if (!hooksObj[event])
209
- hooksObj[event] = [];
210
- const groups = hooksObj[event];
211
- // Find any existing AIWG-managed entry for this hookId and refresh
212
- // its `command` to the current script path/extension. Required for
213
- // users upgrading from pre-`.cjs` installs where the registered
214
- // command still references `aiwg-{session,trace,permissions}.js` —
215
- // those files no longer exist on disk after refresh, causing
216
- // `MODULE_NOT_FOUND` at `node:internal/modules/cjs/loader` on every
217
- // hook invocation. (Fixes regression report on Claude Code 2.1.157.)
218
- // Match by `_aiwg_id` first, then by the script path. An entry invoking an
219
- // AIWG-owned hook script without the managed tag is AIWG residue from an
220
- // earlier install; appending a managed entry beside it registers the hook
221
- // twice and runs it twice per event. Adopt it instead. (#2543)
222
- let updated = false;
223
- for (const group of groups) {
224
- if (!Array.isArray(group.hooks))
218
+ if (!hooksObj[event])
219
+ hooksObj[event] = [];
220
+ const groups = hooksObj[event];
221
+ // Find any existing AIWG-managed entry for this hookId and refresh
222
+ // its `command` to the current script path/extension. Required for
223
+ // users upgrading from pre-`.cjs` installs where the registered
224
+ // command still references `aiwg-{session,trace,permissions}.js` —
225
+ // those files no longer exist on disk after refresh, causing
226
+ // `MODULE_NOT_FOUND` at `node:internal/modules/cjs/loader` on every
227
+ // hook invocation. (Fixes regression report on Claude Code 2.1.157.)
228
+ // Match by `_aiwg_id` first, then by the script path. An entry invoking an
229
+ // AIWG-owned hook script without the managed tag is AIWG residue from an
230
+ // earlier install; appending a managed entry beside it registers the hook
231
+ // twice and runs it twice per event. Adopt it instead. (#2543)
232
+ let updated = false;
233
+ for (const group of groups) {
234
+ if (!Array.isArray(group.hooks))
235
+ continue;
236
+ for (const h of group.hooks) {
237
+ const sameId = h._aiwg_id === hookId;
238
+ const sameScript = typeof h.command === 'string' && h.command.includes(script);
239
+ if (!sameId && !sameScript)
225
240
  continue;
226
- for (const h of group.hooks) {
227
- const sameId = h._aiwg_id === hookId;
228
- const sameScript = typeof h.command === 'string' && h.command.includes(script);
229
- if (!sameId && !sameScript)
230
- continue;
231
- const adopting = !sameId && sameScript;
232
- if (h.command !== command || h.type !== 'command' || h._aiwg_managed !== true || h._aiwg_id !== hookId) {
233
- h.type = 'command';
234
- h.command = command;
235
- h._aiwg_managed = true;
236
- h._aiwg_id = hookId;
237
- result.warnings.push(adopting
238
- ? `Adopted pre-existing untagged ${event} → ${hookId} entry instead of registering a duplicate`
239
- : `Refreshed stale ${event} → ${hookId} command path`);
240
- }
241
- updated = true;
241
+ const adopting = !sameId && sameScript;
242
+ if (h.command !== command || h.type !== 'command' || h._aiwg_managed !== true || h._aiwg_id !== hookId) {
243
+ h.type = 'command';
244
+ h.command = command;
245
+ h._aiwg_managed = true;
246
+ h._aiwg_id = hookId;
247
+ result.warnings.push(adopting
248
+ ? `Adopted pre-existing untagged ${event} → ${hookId} entry instead of registering a duplicate`
249
+ : `Refreshed stale ${event} → ${hookId} command path`);
242
250
  }
251
+ updated = true;
243
252
  }
244
- if (updated)
245
- continue;
246
- groups.push({
247
- hooks: [
248
- {
249
- type: 'command',
250
- command,
251
- _aiwg_managed: true,
252
- _aiwg_id: hookId,
253
- },
254
- ],
255
- });
256
- result.registeredEvents.push(`${event} → ${hookId}`);
257
253
  }
254
+ if (updated)
255
+ continue;
256
+ groups.push({
257
+ hooks: [
258
+ {
259
+ type: 'command',
260
+ command,
261
+ _aiwg_managed: true,
262
+ _aiwg_id: hookId,
263
+ },
264
+ ],
265
+ });
266
+ result.registeredEvents.push(`${event} → ${hookId}`);
258
267
  }
259
268
  }
260
269
  // 5. Atomic write
@@ -11,7 +11,6 @@
11
11
  import { getRegistry, createRegistry } from './registry.js';
12
12
  import { CapabilityIndex } from './capability-index.js';
13
13
  import { commandDefinitions } from './commands/definitions.js';
14
- import { allHandlers } from '../cli/handlers/index.js';
15
14
  /**
16
15
  * Load and populate the registry
17
16
  *
@@ -41,6 +40,7 @@ import { allHandlers } from '../cli/handlers/index.js';
41
40
  */
42
41
  export async function loadRegistry(options) {
43
42
  const { registry = createRegistry(), indexCapabilities = false } = options || {};
43
+ const allHandlers = options?.handlers ?? (await import('../cli/handlers/index.js')).allHandlers;
44
44
  // Register all command definitions
45
45
  for (const definition of commandDefinitions) {
46
46
  registry.register(definition);
@@ -100,6 +100,7 @@ export async function getLoadedRegistry() {
100
100
  return loadRegistry({ registry: globalRegistry });
101
101
  }
102
102
  // Already loaded - just build handler map
103
+ const { allHandlers } = await import('../cli/handlers/index.js');
103
104
  const handlerMap = linkHandlers(allHandlers);
104
105
  return {
105
106
  registry: globalRegistry,
@@ -0,0 +1,48 @@
1
+ // Compare hook bytes and deployment receipts without changing either file.
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ export async function managedHookScriptState(projectRoot, file, expected) {
6
+ const target = path.resolve(projectRoot, file);
7
+ let actual;
8
+ try {
9
+ actual = await fs.readFile(target);
10
+ }
11
+ catch (error) {
12
+ return error.code === 'ENOENT' ? 'missing' : 'unreadable';
13
+ }
14
+ const digest = `sha256:${createHash('sha256').update(actual).digest('hex')}`;
15
+ // Writers may record hooks beside the script, at the provider root, or in
16
+ // the project-scoped receipt. Match the same relative claims as preservation.
17
+ const projectReceipt = path.join(projectRoot, '.aiwg/.aiwg-manifest.json');
18
+ const receipts = [];
19
+ for (let dir = path.dirname(target); dir !== path.resolve(projectRoot); dir = path.dirname(dir)) {
20
+ if (!dir.startsWith(`${path.resolve(projectRoot)}${path.sep}`))
21
+ break;
22
+ receipts.push(path.join(dir, '.aiwg-manifest.json'));
23
+ }
24
+ receipts.push(projectReceipt);
25
+ for (const receipt of receipts) {
26
+ let doc;
27
+ try {
28
+ doc = JSON.parse(await fs.readFile(receipt, 'utf8'));
29
+ }
30
+ catch (error) {
31
+ if (error.code === 'ENOENT')
32
+ continue;
33
+ return 'unreadable';
34
+ }
35
+ if (!doc || typeof doc !== 'object' || Array.isArray(doc))
36
+ return 'unreadable';
37
+ const base = receipt === projectReceipt && doc.scope === 'project' ? projectRoot : path.dirname(receipt);
38
+ const name = path.relative(base, target).split(path.sep).join('/');
39
+ const record = doc.managed?.[name];
40
+ if (record?.hash && record.hash !== digest)
41
+ return 'operator-edited';
42
+ // A nearer receipt supersedes an older ancestor claim.
43
+ if (record)
44
+ break;
45
+ }
46
+ return actual.equals(expected) ? undefined : 'outdated';
47
+ }
48
+ //# sourceMappingURL=managed-hook-script-state.js.map
@@ -0,0 +1,49 @@
1
+ // Canonical Muse hook registrations shared by deployment and read-only drift checks.
2
+ export const promptDiscoveryHook = {
3
+ id: 'aiwg-prompt-discovery',
4
+ event: 'UserPromptSubmit',
5
+ group: { matcher: '*', hooks: [{ type: 'command', command: 'node .muse/hooks/aiwg-prompt-discovery.cjs', timeout: 2 }] },
6
+ reason: 'Inject strong AIWG candidates or require discover before answering or declining; skip system turns, bounded and fail open.',
7
+ removal: 'Set AIWG_PROMPT_DISCOVERY=0, or remove this group from .muse/hooks.json.',
8
+ };
9
+ /**
10
+ * The AIWG-managed hook set. Each entry carries a stated reason (why this
11
+ * hook runs on the operator's machine, outside the agent sandbox) and a
12
+ * removal path (how the operator takes it back out).
13
+ *
14
+ * SessionEnd is intentionally *not* installed yet: Muse documents SessionEnd
15
+ * as observational-only (its output cannot block termination or inject
16
+ * context), and AIWG has no session-catalog note command to invoke — wiring
17
+ * a hook to a command that does not exist would fail every session end.
18
+ * When a real catalog-note command lands, it slots in here with its own
19
+ * reason + removal path.
20
+ */
21
+ export const AIWG_MANAGED_HOOKS = [
22
+ {
23
+ id: 'aiwg-session-start',
24
+ event: 'SessionStart',
25
+ // Muse matcher groups take ONLY `hooks` + optional `matcher`; no
26
+ // in-band AIWG tags (they would break the group).
27
+ //
28
+ // Muse Code 1.4.0 parses hook stdout as hook output: empty output, plain
29
+ // text, and `{"hookSpecificOutput": ...}` are accepted, but any other
30
+ // JSON key fails the hook ("unsupported `deploymentFailures` in output of
31
+ // SessionStart hook output"). `aiwg refresh --quiet` prints its JSON
32
+ // report, so stdout is discarded; the exit status still records a failed
33
+ // drift check in Muse's hook log. `--provider muse` is required because
34
+ // provider detection is fail-closed for muse and would resolve `claude`.
35
+ // Hook commands run through a shell, so the redirect is honored.
36
+ group: {
37
+ matcher: '*',
38
+ hooks: [{ type: 'command', command: 'aiwg refresh --dry-run --quiet --provider muse > /dev/null', timeout: 60 }],
39
+ },
40
+ reason: 'Session-start drift check. Runs a read-only `aiwg refresh --dry-run --provider muse` ' +
41
+ 'and records its exit status in the Muse hook log. Dry-run by construction: it ' +
42
+ 'never mutates the repo, and its report is not injected into the session.',
43
+ removal: 'Delete this matcher group from `.muse/hooks.json` (the one whose command is ' +
44
+ '`aiwg refresh --dry-run --quiet --provider muse > /dev/null`), or run `aiwg use --provider muse --no-hooks` ' +
45
+ 'to stop AIWG managing hooks for this project.',
46
+ },
47
+ promptDiscoveryHook,
48
+ ];
49
+ //# sourceMappingURL=muse-managed-hooks.js.map
@@ -12,15 +12,20 @@ import path from 'node:path';
12
12
  import { pathToFileURL } from 'node:url';
13
13
  import { getFrameworkRoot } from '../channel/manager.mjs';
14
14
  import { readAiwgConfig } from '../config/aiwg-config.js';
15
+ import { externalIssues } from './external-cli.js';
16
+ import { trackerToken } from './tracker-policy.js';
15
17
  import { sensitiveInputOptions } from '../auth/sensitive-input.js';
16
- import { LocalIssueProviderCore, buildExternalIssueSnapshotFromLocal, buildLocalIssueConflictReport, createLiveIssueClient, resolveLiveIssueToken, localIssueRoot, parseCommentIdMappings, parseExternalIssueSnapshot, } from './index.js';
18
+ import { LocalIssueProviderCore, buildExternalIssueSnapshotFromLocal, buildLocalIssueConflictReport, createLiveIssueClient, localIssueRoot, parseCommentIdMappings, parseExternalIssueSnapshot, } from './index.js';
17
19
  export async function main(args, cwd = process.cwd()) {
18
20
  const parsed = parseArgs(args);
21
+ parsed.cwd = cwd;
19
22
  const subcommand = parsed.positional[0];
20
23
  const rest = parsed.positional.slice(1);
21
24
  if (parsed.flags.has('backend')) {
22
25
  throw new Error('aiwg issue commands use the local issue provider; --backend is not supported');
23
26
  }
27
+ if (await externalIssues(parsed, cwd, async () => ({ plan: await buildIssuePlan(parsed, cwd), composer: await loadIssueComposer() })))
28
+ return;
24
29
  const provider = stringFlag(parsed, 'provider');
25
30
  if (provider && provider !== 'local') {
26
31
  throw new Error(`aiwg issue is for local issue storage only; configured external trackers use their tracker tools (${provider})`);
@@ -112,6 +117,7 @@ async function handleNew(issues, args, cwd) {
112
117
  if (plan.authorizationRequired && authorizationDigest !== plan.digest) {
113
118
  throw new Error(`Issue draft requires explicit policy authorization. Review 'aiwg issue plan', then pass --authorize-policy ${plan.digest}. No issue was written.`);
114
119
  }
120
+ await issues.requireInitialized();
115
121
  const composer = await loadIssueComposer();
116
122
  const records = new Map();
117
123
  const adapter = {
@@ -186,6 +192,8 @@ async function handleList(issues, args) {
186
192
  console.log(JSON.stringify(result, null, 2));
187
193
  return;
188
194
  }
195
+ if (result.issues.length === 0)
196
+ console.log('No matching issues found.');
189
197
  for (const issue of result.issues) {
190
198
  console.log(`${issue.id}\t${issue.status}\t${issue.priority}\t${issue.title}`);
191
199
  }
@@ -317,8 +325,9 @@ async function handleIndex(issues, rest, args) {
317
325
  }
318
326
  async function liveClient(args, provider) {
319
327
  const repo = requiredStringFlag(args, 'repo');
320
- const token = await resolveLiveIssueToken(provider, sensitiveInputOptions(args.raw, 'token'));
321
- return createLiveIssueClient({ provider, repo, apiUrl: stringFlag(args, 'api-url'), token });
328
+ const actor = (await readAiwgConfig(args.cwd ?? process.cwd()))?.remotes?.tracker_actor;
329
+ const token = await trackerToken(provider, actor, sensitiveInputOptions(args.raw, 'token'));
330
+ return createLiveIssueClient({ provider, repo, apiUrl: stringFlag(args, 'api-url'), token, actor });
322
331
  }
323
332
  function requiredStringFlag(args, flag) {
324
333
  const value = stringFlag(args, flag);
@@ -401,6 +410,9 @@ function csvFlag(args, name) {
401
410
  }
402
411
  function printUsage() {
403
412
  console.log(`Usage:
413
+ aiwg issues create --title "..." --body-file path (configured external tracker)
414
+ aiwg issues comment|close <number> [--body-file path] (configured external tracker)
415
+ Use --provider local for local writes when an external tracker is configured.
404
416
  aiwg issue init [--prefix KEY] [--padding N]
405
417
  aiwg issue plan --title "..." [--body "..."] [--body-file path] [--json]
406
418
  aiwg issue new --title "..." [--body "..."] [--body-file path] [--authorize-policy DIGEST]
@@ -0,0 +1,79 @@
1
+ // Route explicit/configured external issue writes through actor verification and existing issue composition.
2
+ import { readFile } from 'node:fs/promises';
3
+ import { readAiwgConfig } from '../config/aiwg-config.js';
4
+ import { sensitiveInputOptions } from '../auth/sensitive-input.js';
5
+ import { deliveryTracker } from '../delivery/tracker.js';
6
+ export async function externalIssues(args, cwd, composition) {
7
+ const [operation, number] = args.positional;
8
+ if (!['create', 'new', 'comment', 'close', 'list', 'ls'].includes(operation) || args.flags.get('provider') === 'local')
9
+ return false;
10
+ const config = await readAiwgConfig(cwd);
11
+ if (!config || config.remotes?.issue_provider === 'local' || config.remotes?.issue_tracker === 'local')
12
+ return false;
13
+ if (!config.remotes?.issue_tracker && !['gitea', 'github'].includes(String(config.remotes?.issue_provider)))
14
+ return false;
15
+ if (operation === 'list' || operation === 'ls') {
16
+ throw new Error('Cannot query the configured external tracker with aiwg issues list. Use its tracker tools for duplicate searches. For local storage, run aiwg issues init, then aiwg issues list --provider local.');
17
+ }
18
+ const value = (key) => typeof args.flags.get(key) === 'string' ? args.flags.get(key) : undefined;
19
+ if (value('provider') && value('provider') !== config.remotes?.issue_provider)
20
+ throw new Error('--provider must match the configured tracker');
21
+ const client = await deliveryTracker(cwd, config, { repo: value('repo'), apiUrl: value('api-url'), source: sensitiveInputOptions(args.raw, 'token') });
22
+ let result;
23
+ if (operation === 'create' || operation === 'new') {
24
+ const { plan, composer } = await composition();
25
+ result = await composer.executeIssuePlan(plan, {
26
+ async findByMarker(marker) {
27
+ for (let page = 1;; page++) {
28
+ const entries = await client.repositoryRequest('GET', `/issues?state=all&per_page=100&limit=100&page=${page}`);
29
+ const entry = entries.find(issue => issue.body?.includes(marker));
30
+ if (entry)
31
+ return { id: String(entry.number), reference: `#${entry.number}`, body: entry.body };
32
+ if (entries.length < 100)
33
+ return null;
34
+ }
35
+ },
36
+ async create(draft) {
37
+ let labels = draft.labels;
38
+ if (client.provider === 'gitea' && labels?.length) {
39
+ const available = [];
40
+ for (let page = 1;; page++) {
41
+ const entries = await client.repositoryRequest('GET', `/labels?limit=100&page=${page}`);
42
+ available.push(...entries);
43
+ if (entries.length < 100)
44
+ break;
45
+ }
46
+ labels = labels.map(name => {
47
+ const id = available.find(label => label.name === name)?.id;
48
+ if (id === undefined)
49
+ throw new Error('Issue label is not defined on the configured tracker');
50
+ return id;
51
+ });
52
+ }
53
+ const issue = await client.repositoryRequest('POST', '/issues', {
54
+ title: draft.title, body: draft.body, labels, assignees: draft.assignees,
55
+ });
56
+ return { id: String(issue.number), reference: `#${issue.number}`, body: issue.body };
57
+ },
58
+ async update(issue, patch) {
59
+ await client.repositoryRequest('PATCH', `/issues/${issue.id}`, patch);
60
+ },
61
+ }, { authorizationDigest: value('authorize-policy') });
62
+ if (result.status !== 'created')
63
+ throw new Error(`Issue creation refused: ${JSON.stringify(result)}`);
64
+ }
65
+ else {
66
+ if (!/^[1-9][0-9]*$/.test(number ?? ''))
67
+ throw new Error(`${operation} requires a positive issue number`);
68
+ const body = value('body-file') ? await readFile(value('body-file'), 'utf8') : value('body') ?? value('reason');
69
+ if (operation === 'comment' && !body)
70
+ throw new Error('comment requires --body or --body-file');
71
+ if (body)
72
+ result = await client.repositoryRequest('POST', `/issues/${number}/comments`, { body });
73
+ if (operation === 'close')
74
+ result = await client.repositoryRequest('PATCH', `/issues/${number}`, { state: 'closed' });
75
+ }
76
+ console.log(JSON.stringify(result, null, 2));
77
+ return true;
78
+ }
79
+ //# sourceMappingURL=external-cli.js.map
@@ -1,4 +1,5 @@
1
1
  import { resolveSensitiveInput } from '../auth/sensitive-input.js';
2
+ import { checkTrackerActor, trackerAuthenticationHint } from './tracker-policy.js';
2
3
  import { isInteractive } from '../cli/env.js';
3
4
  export class LiveIssueClient {
4
5
  options;
@@ -48,6 +49,10 @@ export class LiveIssueClient {
48
49
  const comments = await this.request('GET', this.commentsPath(externalId));
49
50
  return comments.map((comment) => normalizeComment(comment));
50
51
  }
52
+ get provider() { return this.options.provider; }
53
+ repositoryRequest(method, suffix, body) {
54
+ return this.request(method, `${this.issuesPath().replace(/\/issues$/, '')}${suffix}`, body);
55
+ }
51
56
  issuesPath() {
52
57
  return `/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.name)}/issues`;
53
58
  }
@@ -57,7 +62,15 @@ export class LiveIssueClient {
57
62
  commentsPath(externalId) {
58
63
  return `${this.issuePath(externalId)}/comments`;
59
64
  }
65
+ async verifyActor() {
66
+ if (!this.options.actor)
67
+ return;
68
+ const user = await this.request('GET', '/user');
69
+ checkTrackerActor(this.options.actor, user.login);
70
+ }
60
71
  async request(method, path, body) {
72
+ if (method !== 'GET')
73
+ await this.verifyActor();
61
74
  const headers = {
62
75
  Accept: 'application/json',
63
76
  };
@@ -65,17 +78,23 @@ export class LiveIssueClient {
65
78
  headers['Content-Type'] = 'application/json';
66
79
  if (this.options.token)
67
80
  headers.Authorization = `Bearer ${this.options.token}`;
81
+ let authenticationFailed = false;
68
82
  try {
69
83
  const response = await this.fetchFn(`${this.baseUrl}${path}`, {
70
84
  method,
85
+ redirect: 'error',
71
86
  headers,
72
87
  body: body === undefined ? undefined : JSON.stringify(body),
73
88
  });
74
89
  if (!response.ok) {
75
90
  const text = await response.text().catch(() => '');
91
+ authenticationFailed = response.status === 401;
76
92
  throw new Error(`${this.options.provider} issue API ${method} ${path} failed: ${response.status}${text ? ` ${redactSecrets(text, this.options.token)}` : ''}`);
77
93
  }
78
- const result = await response.json();
94
+ // Native HTTP responses may be empty (for example Gitea merge success).
95
+ // Preserve the injected fetch contract used by existing in-process clients.
96
+ const payload = typeof response.text === 'function' ? await response.text() : undefined;
97
+ const result = (payload === undefined ? await response.json() : payload.trim() ? JSON.parse(payload) : {});
79
98
  // A server can reflect request credentials in issue fields or comments.
80
99
  // Scrub them before they reach local storage or CLI output.
81
100
  if (!this.options.token)
@@ -84,7 +103,12 @@ export class LiveIssueClient {
84
103
  return JSON.parse(JSON.stringify(result).split(encodedToken).join('[REDACTED]'));
85
104
  }
86
105
  catch (error) {
87
- throw new Error(redactSecrets(error instanceof Error ? error.message : 'Live issue request failed', this.options.token));
106
+ // Append trusted setup instructions after scrubbing server text: the
107
+ // generic redactor also treats the command words "secret set" as data.
108
+ const hint = authenticationFailed && this.options.actor?.login
109
+ ? ` ${trackerAuthenticationHint(this.options.provider, this.options.actor)}` : '';
110
+ const safeHint = this.options.token ? hint.split(this.options.token).join('[REDACTED]') : hint;
111
+ throw new Error(redactSecrets(error instanceof Error ? error.message : 'Live issue request failed', this.options.token) + safeHint);
88
112
  }
89
113
  }
90
114
  }
@@ -89,6 +89,9 @@ export class LocalIssueProviderCore {
89
89
  this.root = resolve(root);
90
90
  this.lockManager = new LocalIssueLockManager(this.root);
91
91
  }
92
+ async requireInitialized() {
93
+ await this.readConfig();
94
+ }
92
95
  async init(options = {}) {
93
96
  await this.ensureLayout();
94
97
  const existing = await this.readConfigIfExists();
@@ -233,6 +236,7 @@ export class LocalIssueProviderCore {
233
236
  };
234
237
  }
235
238
  async listIssues(options = {}) {
239
+ await this.requireInitialized();
236
240
  const index = await this.readIndexOrRebuild();
237
241
  const offset = options.cursor ? Number.parseInt(options.cursor, 10) : 0;
238
242
  const limit = options.limit ?? 50;
@@ -418,7 +422,7 @@ export class LocalIssueProviderCore {
418
422
  async readConfig() {
419
423
  const config = await this.readConfigIfExists();
420
424
  if (!config)
421
- throw new LocalIssueProviderError('local issues are not initialized');
425
+ throw new LocalIssueProviderError('Local issue system is not initialized. Run aiwg issues init --prefix <PROJECT> to initialize local storage; use the target tracker tools for external issues.');
422
426
  return config;
423
427
  }
424
428
  async readIndexOrRebuild() {
@@ -0,0 +1,27 @@
1
+ import { resolveLiveIssueToken } from './live.js';
2
+ export async function trackerToken(provider, actor, source = {}, dependencies = {}) {
3
+ if (actor?.credential && Object.keys(source).some(key => key !== 'prefix')) {
4
+ throw new Error('Configured tracker_actor.credential cannot be overridden by token flags');
5
+ }
6
+ try {
7
+ return await resolveLiveIssueToken(provider, actor?.credential ?? source, dependencies);
8
+ }
9
+ catch (error) {
10
+ if (!actor?.login)
11
+ throw error;
12
+ throw new Error(`Cannot load tracker token. ${trackerAuthenticationHint(provider, actor)}`);
13
+ }
14
+ }
15
+ export function trackerAuthenticationHint(provider, actor) {
16
+ return `Authentication required for configured tracker_actor.login ${JSON.stringify(actor.login)}. Set up a ${provider} token belonging to this actor with aiwg auth secret set <name> --value-stdin, then set remotes.tracker_actor.credential to {"store":"<name>"} (or {"env":"TOKEN_ENV"} with that variable supplied). If a credential reference is already configured, refresh that source.`;
17
+ }
18
+ export function checkTrackerActor(actor, login) {
19
+ if (typeof login !== 'string' || !login)
20
+ throw new Error('Tracker API did not identify an authenticated actor');
21
+ const normalized = login.toLowerCase();
22
+ if (actor.forbid_actors?.some(value => value.toLowerCase() === normalized))
23
+ throw new Error('Tracker actor is forbidden by remotes.tracker_actor.forbid_actors');
24
+ if (actor.login && actor.login.toLowerCase() !== normalized)
25
+ throw new Error('Tracker API user does not match remotes.tracker_actor.login');
26
+ }
27
+ //# sourceMappingURL=tracker-policy.js.map
@@ -0,0 +1,2 @@
1
+ // Types for the shared JSONC settings reader.
2
+ export function parseJson(raw: string): unknown;
@@ -177,7 +177,7 @@ import path from 'node:path';
177
177
  import { fileURLToPath, pathToFileURL } from 'node:url';
178
178
  import { mcpError, mcpJson } from '../helpers.mjs';
179
179
  import { buildShellStopControl, waitForUnitTermination } from './worker-shell-control.mjs';
180
- import { launchPreparedShellWorker, sweepWorkerStdin } from './worker-stdin-runtime.mjs';
180
+ import { launchPreparedShellWorker, sweepWorkerStdin, markWorkerServer } from './worker-stdin-runtime.mjs';
181
181
  // NOTE: no static import of ../../config/worker-context.js here. That
182
182
  // module is TypeScript: a literal relative import resolves under vitest
183
183
  // but throws ERR_MODULE_NOT_FOUND under raw node (e.g. `node
@@ -1032,6 +1032,7 @@ async function defaultLaunchMcpWorkerProcessBaseline(server, { allowDegraded, co
1032
1032
  }
1033
1033
 
1034
1034
  async function defaultLaunchMcpWorkerProcess(server, { allowDegraded, config, name, cwd, memoryMaxGb = DEFAULT_MCP_WORKER_MEMORY_MAX_GB, live, readers, thresholdOverlay, admission, invocation, invocationId, dispatchGuard }) {
1035
+ server = markWorkerServer(server, invocation, invocationId);
1035
1036
  // #2915 round 8 (D6): see `defaultLaunchShellWorker`'s identical guard —
1036
1037
  // `admission` is only ever present when this attempt is actually gated.
1037
1038
  if (admission === undefined) {
@@ -1,8 +1,16 @@
1
+ // Prepare worker stdin and internal attribution for shell and spawned MCP transports.
2
+ import { directWorkerEnvironment } from '../../config/worker-attribution.mjs';
1
3
  import { createHash } from 'node:crypto';
2
4
  import { mkdtemp, mkdir, writeFile, rm, readdir, lstat } from 'node:fs/promises';
3
5
  import { tmpdir } from 'node:os';
4
6
  import path from 'node:path';
5
7
 
8
+ export function markWorkerServer(server, invocation, invocationId) {
9
+ if (!invocation?.cwd || !invocation?.selected?.group) return server;
10
+ return { ...server, env: { ...server.env,
11
+ ...directWorkerEnvironment({ ...invocation, ...(invocationId ? { invocationId } : {}) }) } };
12
+ }
13
+
6
14
  /** Sweep old private directories only for dead conductors; PID reuse retains
7
15
  * them. Runtime files keep prompts out of git, but cannot isolate same-user workers. */
8
16
  export async function sweepWorkerStdin(root = tmpdir(), { staleMs = 86400000, now = Date.now(),
@@ -57,7 +65,11 @@ export async function launchPreparedShellWorker(invocation, { allowDegraded, con
57
65
  if (bytes !== null) {
58
66
  ({ stdinPath, cleanup } = await prepareWorkerStdin(bytes, stdinRuntimeRoot));
59
67
  }
68
+ const markers = directWorkerEnvironment({ ...invocation, ...(invocationId ? { invocationId } : {}) });
60
69
  const launch = await planDirectWorkerLaunch({ invocation, config, allowDegraded, name, live, readers,
70
+ env: { ...Object.fromEntries((invocation.envNames ?? []).filter(name => process.env[name] !== undefined)
71
+ .map(name => [name, process.env[name]])), ...markers },
72
+ envNames: [...new Set([...(invocation.envNames ?? []), ...Object.keys(markers)])],
61
73
  thresholdOverlay, memoryMaxGb, stdinPath, ownedGroup: true, isolation, admission, invocationId, dispatchGuard,
62
74
  spawn, spawnAsync, onSpawnAttempt: value => {
63
75
  attempt = value;
@@ -4,5 +4,6 @@ import type { ParallelismConfig } from '../config/aiwg-config.js';
4
4
  export const LOCAL_ONLY_PATH_PATTERN: string;
5
5
  export function validLocalOnlyPath(value: unknown): boolean;
6
6
  export function collectLocalOnlyPaths(policy?: WorkerSelectionPolicy, parallelism?: ParallelismConfig): string[];
7
- export function conductorToolDenial(event: { tool_name?: string; tool_input?: Record<string, unknown>; cwd?: string }, root: string, paths: string[]): string | null;
8
- export function runConductorDataHook(root: string, paths: string[]): void;
7
+ export function conductorWorkerTrees(root: string): string[];
8
+ export function conductorToolDenial(event: { tool_name?: string; tool_input?: Record<string, unknown>; cwd?: string }, root: string, paths: string[], workerTrees?: string[]): string | null;
9
+ export function runConductorDataHook(root: string, paths: string[], denyWorkerExecution?: boolean): void;