@aiwg/cli 2026.11.7 → 2026.11.8

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 (44) hide show
  1. package/agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs +3 -2
  2. package/agentic/code/providers/model-capabilities.v1.json +22 -21
  3. package/agentic/code/providers/model-catalog.v1.json +11 -10
  4. package/dist/src/cli/handlers/refresh-managed-deployment.js +13 -3
  5. package/dist/src/cli/handlers/refresh-user-hooks.js +102 -0
  6. package/dist/src/cli/handlers/refresh.js +2 -0
  7. package/dist/src/config/worker-guidance-warning.js +8 -0
  8. package/dist/src/extensions/user-hook-diagnostics.js +16 -1
  9. package/dist/src/extensions/verified-hook-command.js +7 -0
  10. package/dist/src/models/cursor-models.js +92 -0
  11. package/dist/src/models/model-capabilities.v1.json +22 -21
  12. package/dist/src/models/model-catalog.v1.json +11 -10
  13. package/dist/src/models/model-discovery.js +4 -3
  14. package/dist/src/models/provider-policy.js +1 -1
  15. package/dist/src/models/worker-health-readiness.js +4 -0
  16. package/dist/src/models/worker-installation.d.mts +2 -0
  17. package/dist/src/models/worker-installation.mjs +8 -2
  18. package/dist/src/models/worker-invocation-policy.js +21 -1
  19. package/dist/src/models/worker-plan.js +3 -1
  20. package/dist/src/models/worker-wiring-diagnostics.js +25 -0
  21. package/dist/src/providers/provider-context-contracts.js +3 -0
  22. package/dist/src/providers/provider-seeds-1.js +1 -1
  23. package/dist/src/smiths/context-pipeline/muse-bridge.js +7 -4
  24. package/dist/src/smiths/context-pipeline/workspace-audit.js +37 -6
  25. package/dist/src/smiths/context-pipeline/workspace-bootstrap.js +3 -1
  26. package/dist/src/smiths/context-pipeline/workspace-doctor.js +16 -4
  27. package/dist/src/smiths/context-pipeline/workspace-document.js +4 -2
  28. package/dist/src/smiths/hook-bridge/codex-trust.js +56 -7
  29. package/dist/src/smiths/hook-bridge/cursor-translator.js +89 -0
  30. package/dist/src/smiths/hook-bridge/index.js +4 -1
  31. package/dist/src/writing/contextual-diagnostics.js +2 -1
  32. package/dist/src/writing/current-patterns.catalogue.json +4 -4
  33. package/dist/src/writing/current-patterns.js +2 -2
  34. package/dist/src/writing/structural-patterns.js +23 -6
  35. package/package.json +1 -1
  36. package/tools/agents/providers/cursor-prompt-discovery.mjs +13 -0
  37. package/tools/agents/providers/cursor.mjs +2 -0
  38. package/tools/agents/providers/openclaw-context.mjs +6 -0
  39. package/tools/agents/providers/openclaw.mjs +14 -12
  40. package/tools/agents/providers/rule-delivery-surface.mjs +1 -1
  41. package/tools/agents/providers/rule-deployment-prepare.mjs +1 -0
  42. package/tools/agents/providers/rule-presentation.mjs +1 -1
  43. package/tools/agents/providers/rule-startup.mjs +3 -1
  44. package/vscode-extension/schemas/aiwg.config.v1.json +13 -0
@@ -96,7 +96,8 @@ async function main() {
96
96
  }
97
97
  const event = JSON.parse(Buffer.concat(chunks).toString('utf8'));
98
98
  const hermes = event.hook_event_name === 'pre_llm_call';
99
- if (event.hook_event_name && event.hook_event_name !== 'UserPromptSubmit' && !hermes) return finish();
99
+ const cursor = event.hook_event_name === 'beforeSubmitPrompt';
100
+ if (event.hook_event_name && event.hook_event_name !== 'UserPromptSubmit' && !hermes && !cursor) return finish();
100
101
  if ([event.role, event.message?.role].some(role => role && role !== 'user')
101
102
  || /^(system|notification|tool[_-]result)$/.test(event.type || '')) return finish();
102
103
  const text = hermes ? event.extra?.user_message : event.prompt;
@@ -127,7 +128,7 @@ async function main() {
127
128
  worker.on('message', envelope => {
128
129
  if (Date.now() >= deadline) return finish();
129
130
  const context = contextFor(envelope, prompt);
130
- if (context) process.stdout.write(JSON.stringify(hermes ? { context } : {
131
+ if (context) process.stdout.write(JSON.stringify(cursor ? { continue: true, additional_context: context } : hermes ? { context } : {
131
132
  hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: context },
132
133
  }) + '\n', finish);
133
134
  else finish();
@@ -891,7 +891,7 @@
891
891
  "id": "cursor-direct",
892
892
  "provider": "cursor",
893
893
  "adapterVersion": "1",
894
- "supportedVersions": "2026.10.1-e373342",
894
+ "supportedVersions": "2026.11.13-eacade1",
895
895
  "runtimeDriver": "installed:cursor",
896
896
  "catalogAdapter": {
897
897
  "kind": "file",
@@ -946,67 +946,67 @@
946
946
  "invocationProfiles": {
947
947
  "direct-shell": {
948
948
  "transport": "shell",
949
- "supportedVersions": "2026.10.1-e373342",
949
+ "supportedVersions": "2026.11.13-eacade1",
950
950
  "controls": {
951
951
  "model": {
952
952
  "support": "unqualified",
953
- "mapping": "[--model MODEL[effort=E]]; exact catalog model ID with the embedded bracket effort override, never a generic alias, never the CLI's own auto-selection ('auto'/'default'); the captured --help documents only --model, no -m short alias",
954
- "evidence": "H: cursor-agent 2026.10.01-e373342 --help documents --model <model> (no -m alias) and its bracket-override syntax; unqualified until live model-pin evidence"
953
+ "mapping": "[--model MODEL]; exact catalog model ID including its effort variant, never a generic alias, never the CLI's own auto-selection ('auto'/'default'); the captured --help documents only --model, no -m short alias",
954
+ "evidence": "H: cursor-agent 2026.11.13-eacade1 --help and live --list-models observed 2026-11-17; composer-2.5 stdin smoke exited 0 with one success result; dispatch remains unqualified pending human review of a live run"
955
955
  },
956
956
  "effort": {
957
957
  "support": "unqualified",
958
- "mapping": "embedded in --model as MODEL[effort=E]; valid levels are account/backend-scoped (parameterizedModels is fetched from the Cursor backend), never a CLI default",
959
- "evidence": "H: cursor-agent 2026.10.01-e373342 --help documents the bracket-override example 'claude-opus-4-8[context=1m,effort=high,fast=false]'; D: installed-module bundle read on noodle (~/.local/share/cursor-agent/versions/2026.10.01-e373342/7000.index.js), never executed shows parameterizedModels is fetched remotely; unqualified until live evidence"
958
+ "mapping": "select the exact catalog model ID encoding effort, e.g. gpt-5.3-codex-high; never append bracket overrides; composer-2.5 has no separate effort selector",
959
+ "evidence": "H: 2026.11.13-eacade1 help still advertises parameterized bracket overrides, but the live list encodes effort in IDs; observed 2026-11-17: claude-sonnet-5-thinking-high[effort=low] rejected with plain-text Cannot use this model, exit 1 and no JSON"
960
960
  },
961
961
  "sandbox": {
962
962
  "support": "unqualified",
963
963
  "mapping": "both contracts emit [--sandbox enabled] (never --sandbox disabled); read-only additionally emits [--mode ask] (the CLI's own documented read-only mode) on top of --sandbox enabled; -f/--force, --yolo, --auto-review and --approve-mcps are out of this contract's scope and are never emitted (--approve-mcps is a bypass, not a non-approval convenience; see pitfalls)",
964
- "evidence": "H: cursor-agent 2026.10.01-e373342 --help documents --sandbox <enabled|disabled>, --mode <plan|ask> ('ask: ... (read-only)') and -f/--force/--yolo/--auto-review/--approve-mcps; D: installed-module bundle read on noodle (~/.local/share/cursor-agent/versions/2026.10.01-e373342/7000.index.js and 8192.index.js), never executed, shows sandboxMode:\"enabled\" pairs with approvalMode:\"allowlist\" and --approve-mcps sets ignoreApprovals:true on the MCP approval source; unqualified until live evidence"
964
+ "evidence": "H: cursor-agent 2026.11.13-eacade1 --help documents --sandbox <enabled|disabled>, --mode <plan|ask> ('ask: ... (read-only)') and -f/--force/--yolo/--auto-review/--approve-mcps; D: installed-module bundle read on noodle (~/.local/share/cursor-agent/versions/2026.10.01-e373342/7000.index.js and 8192.index.js), never executed, shows sandboxMode:\"enabled\" pairs with approvalMode:\"allowlist\" and --approve-mcps sets ignoreApprovals:true on the MCP approval source; Observed 2026-11-17: composer-2.5 smoke with --sandbox enabled exited 0 on titan after host AppArmor setup; read-only mode is help-evidenced only; dispatch unqualified pending human review"
965
965
  },
966
966
  "approval": {
967
967
  "support": "unqualified",
968
968
  "mapping": "unavailable as a separate flag: --sandbox/--mode are the only non-bypass permission gates; the direct profile never emits -f/--force, --yolo, --auto-review or --approve-mcps",
969
- "evidence": "H: cursor-agent 2026.10.01-e373342 --help documents no non-bypass approval-policy flag; unqualified until live evidence"
969
+ "evidence": "H: cursor-agent 2026.11.13-eacade1 --help documents no non-bypass approval-policy flag; Observed 2026-11-17: unapproved project MCP server never ran; smoke exited 0 without error or interaction_query events; dispatch unqualified pending human review"
970
970
  },
971
971
  "workdir": {
972
972
  "support": "unqualified",
973
973
  "mapping": "[--workspace W] conductor working root, plus the conductor process cwd",
974
- "evidence": "H: cursor-agent 2026.10.01-e373342 --help documents --workspace <path-or-name>; unqualified until live evidence"
974
+ "evidence": "H: cursor-agent 2026.11.13-eacade1 --help documents --workspace <path-or-name>; Observed 2026-11-17: smoke system/init cwd matched the supplied temporary workspace; dispatch unqualified pending human review"
975
975
  },
976
976
  "finalOutput": {
977
977
  "support": "unqualified",
978
978
  "mapping": "unavailable as a file target: no output-file flag is documented; the final is the last type:\"result\" line of the captured --output-format stream-json stdout stream",
979
- "evidence": "H: cursor-agent 2026.10.01-e373342 --help documents --output-format <text|json|stream-json> with no file-path argument; D: installed-module bundle read on noodle (~/.local/share/cursor-agent/versions/2026.10.01-e373342/7000.index.js), never executed shows the single terminal result object shape; unqualified until live evidence"
979
+ "evidence": "H: cursor-agent 2026.11.13-eacade1 --help documents --output-format <text|json|stream-json> with no file-path argument; D: installed-module bundle read on noodle (~/.local/share/cursor-agent/versions/2026.10.01-e373342/7000.index.js), never executed shows the single terminal result object shape; Observed 2026-11-17: plain-model smoke emitted exactly one result with subtype success, is_error false and result cursor-smoke-ok, exit 0; dispatch unqualified pending human review"
980
980
  },
981
981
  "stdin": {
982
982
  "support": "unqualified",
983
983
  "mapping": "brief-text: omitting the prompt argument makes the CLI read the prompt from stdin to EOF; brief text never enters argv, rendered commands or serialized plans",
984
- "evidence": "D: installed-module bundle read on noodle (~/.local/share/cursor-agent/versions/2026.10.01-e373342/7000.index.js), never executed shows the prompt-building function reads stdin to EOF only when no positional prompt argument is supplied; unqualified until live evidence"
984
+ "evidence": "D: installed-module bundle read on noodle (~/.local/share/cursor-agent/versions/2026.10.01-e373342/7000.index.js), never executed shows the prompt-building function reads stdin to EOF only when no positional prompt argument is supplied; Observed 2026-11-17: brief piped on stdin with no positional prompt produced cursor-smoke-ok, exit 0; dispatch unqualified pending human review"
985
985
  },
986
986
  "structuredOutput": {
987
987
  "support": "unqualified",
988
988
  "mapping": "unavailable: no output-schema flag is documented",
989
- "evidence": "H: cursor-agent 2026.10.01-e373342 --help advertises no output-schema flag; unqualified until live evidence"
989
+ "evidence": "H: cursor-agent 2026.11.13-eacade1 --help advertises no output-schema flag; unqualified until live evidence"
990
990
  },
991
991
  "stepCap": {
992
992
  "support": "unqualified",
993
993
  "mapping": "unavailable: no step or turn cap flag is evidenced; deadline and output-byte bounds come from the invoking shell",
994
- "evidence": "H: cursor-agent 2026.10.01-e373342 --help advertises no step-cap flag; unknown controls block tasks requiring them"
994
+ "evidence": "H: cursor-agent 2026.11.13-eacade1 --help advertises no step-cap flag; unknown controls block tasks requiring them"
995
995
  },
996
996
  "trust": {
997
997
  "support": "unqualified",
998
998
  "mapping": "always emitted: [--trust] removes the only documented workspace-trust prompt so the non-interactive run cannot block on it",
999
- "evidence": "H: cursor-agent 2026.10.01-e373342 --help documents --trust ('Trust the current workspace without prompting'); unqualified until live evidence"
999
+ "evidence": "H: cursor-agent 2026.11.13-eacade1 --help documents --trust ('Trust the current workspace without prompting'); Observed 2026-11-17: --trust smoke completed with no interaction_query or error events; dispatch unqualified pending human review"
1000
1000
  },
1001
1001
  "children": {
1002
1002
  "support": "unqualified",
1003
1003
  "mapping": "unknown: no subagent/child-process fan-out flag is documented for -p",
1004
- "evidence": "H: cursor-agent 2026.10.01-e373342 --help documents no child-process flag for -p; unqualified until live evidence"
1004
+ "evidence": "H: cursor-agent 2026.11.13-eacade1 --help documents no child-process flag for -p; unqualified until live evidence"
1005
1005
  },
1006
1006
  "fallback": {
1007
1007
  "support": "unqualified",
1008
1008
  "mapping": "unavailable: no fallback-model flag is documented",
1009
- "evidence": "H: cursor-agent 2026.10.01-e373342 --help advertises no fallback-model flag; unknown controls block tasks requiring them"
1009
+ "evidence": "H: cursor-agent 2026.11.13-eacade1 --help advertises no fallback-model flag; unknown controls block tasks requiring them"
1010
1010
  }
1011
1011
  },
1012
1012
  "envAllowlist": [
@@ -1015,16 +1015,17 @@
1015
1015
  "PATH"
1016
1016
  ],
1017
1017
  "pitfalls": [
1018
- "Documentation/help and synthetic observations are not authenticated live qualification.",
1018
+ "Help, live model list and smoke observations from 2026-11-17 are recorded in docs/providers/cursor-direct.md; dispatch remains unqualified pending human review of a live run.",
1019
1019
  "Unknown model, effort, permission or required step mappings block dispatch.",
1020
+ "On hosts with kernel.apparmor_restrict_unprivileged_userns=1, cursorsandbox needs a host AppArmor profile; without it the CLI reports Sandbox mode is enabled but not available in plain text and exits non-zero.",
1020
1021
  "Native MCP/client, MSP/ACP, gateway and conversation capabilities do not establish worker authority.",
1021
1022
  "-f/--force, --yolo and --auto-review are never part of the direct profile; none was ever shipped as a new argv-prompt path.",
1022
1023
  "--approve-mcps is a BYPASS, not a harmless convenience: it sets ignoreApprovals:true on the MCP approval source (installed-module bundle read, 8192.index.js), which is folded with --force/--yolo into one upstream bypass flag. Without it, an MCP server not already recorded as approved fails its load() call and is skipped; the run continues without that server's tools. It is never emitted by this profile.",
1023
1024
  "This version's non-interactive path has no type:\"error\" terminal event: a thrown error writes plain text and exits non-zero with no JSON result line at all; a missing terminal plus a non-zero exit is the failure signal here. Defensively, ANY type:\"error\" event or non-null top-level error field fails the stream regardless of position, including after an earlier success.",
1024
1025
  "A type:\"interaction_query\" line means the CLI is waiting for an approval answer this profile cannot supply; treated as fatal regardless of position (before or after a success line), never as a pending success.",
1025
1026
  "The template placeholder ${mode} documents the conditional --mode ask that read-only additionally emits on top of --sandbox enabled; it is omitted entirely for workspace-write, never rendered as an empty token.",
1026
- "CURSOR_API_KEY must be present for auth (there is no login on the evidenced host); HOME locates ~/.cursor for persistent settings.",
1027
- "SE4: the raw `cursor-agent --version` banner is `2026.10.01-e373342` (leading-zero day-of-month), which is not valid semver; supportedVersions here is the semver-normalized `2026.10.1-e373342` and a caller must apply the same normalization to the live version string before qualification, or a correct installation is unconditionally refused."
1027
+ "Auth may use CURSOR_API_KEY or an existing login (live smoke used login); HOME locates ~/.cursor for persistent settings.",
1028
+ "SE4: historical raw banner 2026.10.01-e373342 needs semver normalization to 2026.10.1-e373342; current supported version 2026.11.13-eacade1 needs no normalization."
1028
1029
  ],
1029
1030
  "health": {
1030
1031
  "version": 1,
@@ -1050,8 +1051,8 @@
1050
1051
  {
1051
1052
  "kind": "help",
1052
1053
  "ref": "tools/ralph-external/lib/cursor-adapter.mjs",
1053
- "observedAt": "2026-10-10T00:00:00Z",
1054
- "cliVersion": "2026.10.1-e373342"
1054
+ "observedAt": "2026-11-17T00:00:00Z",
1055
+ "cliVersion": "2026.11.13-eacade1"
1055
1056
  },
1056
1057
  {
1057
1058
  "kind": "repository",
@@ -141,23 +141,24 @@
141
141
  "cursor": {
142
142
  "roles": {
143
143
  "reasoning": {
144
- "id": "claude-4.6-opus-high-thinking",
145
- "status": "unverified",
146
- "observed": false
144
+ "id": "claude-opus-5-thinking-high",
145
+ "status": "active",
146
+ "observed": true
147
147
  },
148
148
  "coding": {
149
- "id": "claude-4.6-sonnet",
150
- "status": "unverified",
151
- "observed": false
149
+ "id": "gpt-5.3-codex-high",
150
+ "status": "active",
151
+ "observed": true
152
152
  },
153
153
  "efficiency": {
154
- "id": "auto",
155
- "status": "unverified",
156
- "observed": false
154
+ "id": "composer-2.5",
155
+ "status": "active",
156
+ "observed": true
157
157
  }
158
158
  },
159
159
  "sourceUrl": "https://cursor.com/docs/models",
160
- "verifiedAt": "2026-07-20"
160
+ "verifiedAt": "2026-11-17",
161
+ "evidence": "Source: live cursor-agent 2026.11.13-eacade1 --list-models on 2026-11-17 (models.txt); account-offered IDs observed, not dispatch qualification. See docs/providers/cursor-direct.md#live-observations-2026-11-17."
161
162
  },
162
163
  "factory": {
163
164
  "roles": {
@@ -7,6 +7,7 @@ import { managedClaudeHooks } from '../../extensions/claude-hooks-installer.js';
7
7
  import { verifiedHookCommand } from '../../extensions/verified-hook-command.js';
8
8
  import { managedMuseHooks } from '../../extensions/muse-managed-hooks.js';
9
9
  import { managedHookScriptState } from '../../extensions/managed-hook-script-state.js';
10
+ import { managedCursorPromptHook } from '../../smiths/hook-bridge/cursor-translator.js';
10
11
  import { managedFactoryHooks } from '../../smiths/hook-bridge/factory-translator.js';
11
12
  import { readFactoryDocument } from '../../smiths/hook-bridge/factory-hook-config.js';
12
13
  import { loadHookSources } from '../../smiths/hook-bridge/loader.js';
@@ -42,7 +43,7 @@ function groups(doc, event) {
42
43
  return Array.isArray(hooks?.[event]) ? hooks[event] : [];
43
44
  }
44
45
  async function staleHooks(projectRoot, frameworkRoot, provider) {
45
- if (!['claude', 'muse', 'factory', 'codex'].includes(provider))
46
+ if (!['claude', 'muse', 'factory', 'codex', 'cursor'].includes(provider))
46
47
  return [];
47
48
  const file = provider === 'claude' ? '.claude/settings.json' : `.${provider}/hooks.json`;
48
49
  let doc;
@@ -54,7 +55,16 @@ async function staleHooks(projectRoot, frameworkRoot, provider) {
54
55
  return [{ name: `${provider} managed hooks`, file, reason: 'unreadable' }];
55
56
  }
56
57
  const stale = [];
57
- if (provider === 'codex') {
58
+ if (provider === 'cursor') {
59
+ const expected = managedCursorPromptHook(projectRoot, await fs.readFile(path.join(frameworkRoot, 'agentic/code/addons/aiwg-hooks/hooks/aiwg-prompt-discovery.cjs')));
60
+ const hooks = doc.hooks?.beforeSubmitPrompt;
61
+ const candidates = Array.isArray(hooks) ? hooks.filter(hook => hook?._aiwg_id === expected._aiwg_id) : [];
62
+ if (!candidates.some(hook => hook.type === expected.type && hook.command === expected.command
63
+ && hook.timeout === expected.timeout && hook._aiwg_managed === true)) {
64
+ stale.push({ name: `beforeSubmitPrompt → ${expected._aiwg_id}`, file, reason: candidates.length ? 'outdated' : 'missing' });
65
+ }
66
+ }
67
+ else if (provider === 'codex') {
58
68
  const { sources } = await loadHookSources(frameworkRoot);
59
69
  const source = sources.find(hook => hook.id === 'aiwg-prompt-discovery');
60
70
  if (!source?.args?.[0])
@@ -169,7 +179,7 @@ async function staleHookScripts(projectRoot, frameworkRoot, provider) {
169
179
  else if (provider === 'muse') {
170
180
  scripts.set('.muse/hooks/aiwg-prompt-discovery.cjs', path.join(source, 'aiwg-prompt-discovery.cjs'));
171
181
  }
172
- else if (provider === 'codex' || provider === 'factory') {
182
+ else if (provider === 'codex' || provider === 'factory' || provider === 'cursor') {
173
183
  // Match installCodexPromptDiscovery: resolve packaged canonical arguments,
174
184
  // not the portable launcher command emitted into hooks.json.
175
185
  const { sources, errors } = await loadHookSources(frameworkRoot);
@@ -0,0 +1,102 @@
1
+ // Migrate only existing legacy user hook registrations, preserving operator settings.
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import os from 'node:os';
5
+ import { managedClaudeHooks } from '../../extensions/claude-hooks-installer.js';
6
+ import { managedMuseHooks } from '../../extensions/muse-managed-hooks.js';
7
+ import { managedHookScriptState } from '../../extensions/managed-hook-script-state.js';
8
+ import { diagnoseUserHookCommands } from '../../extensions/user-hook-diagnostics.js';
9
+ import { captureDeploymentOutputs, recordDeploymentOutputs } from '../../providers/deployment-ownership.mjs';
10
+ import * as ui from '../ui.js';
11
+ function relativeCommand(command) {
12
+ if (typeof command !== 'string')
13
+ return;
14
+ const match = /^node\s+(?:"([^"]+)"|'([^']+)'|(\S+))(?:\s+(start|stop))?\s*$/.exec(command);
15
+ if (!match)
16
+ return;
17
+ const script = (match[1] || match[2] || match[3]).replace(/\\/g, '/').replace(/\.js$/, '.cjs');
18
+ return `node ${script}${match[4] ? ` ${match[4]}` : ''}`;
19
+ }
20
+ export async function refreshUserHooks(options) {
21
+ const { frameworkRoot, provider, dryRun, quiet } = options;
22
+ if (!['claude', 'muse'].includes(provider))
23
+ return;
24
+ const home = os.homedir();
25
+ const directory = path.join(home, `.${provider}`);
26
+ const file = path.join(directory, provider === 'claude' ? 'settings.json' : 'hooks.json');
27
+ const diagnostics = await diagnoseUserHookCommands();
28
+ if (!diagnostics.some(diagnostic => diagnostic.path === file))
29
+ return;
30
+ const doc = JSON.parse(await fs.readFile(file, 'utf8'));
31
+ const source = path.join(frameworkRoot, 'agentic/code/addons/aiwg-hooks/hooks');
32
+ const files = await fs.readdir(source);
33
+ const canonical = provider === 'claude'
34
+ ? managedClaudeHooks(files, home, source, 'user').map((hook, i) => ({ ...hook,
35
+ relativeCommand: managedClaudeHooks(files)[i].command }))
36
+ : managedMuseHooks(home, await fs.readFile(path.join(source, 'aiwg-prompt-discovery.cjs')), 'user')
37
+ .filter(hook => hook.id === 'aiwg-prompt-discovery').map(hook => ({ event: hook.event,
38
+ script: '.muse/hooks/aiwg-prompt-discovery.cjs', command: hook.group.hooks[0].command,
39
+ relativeCommand: 'node .muse/hooks/aiwg-prompt-discovery.cjs' }));
40
+ const scripts = new Map();
41
+ let count = 0;
42
+ for (const hook of canonical) {
43
+ const groups = doc.hooks?.[hook.event];
44
+ if (!Array.isArray(groups))
45
+ continue;
46
+ for (const group of groups) {
47
+ for (const entry of Array.isArray(group?.hooks) ? group.hooks : []) {
48
+ if (entry?.type !== 'command' || relativeCommand(entry.command) !== hook.relativeCommand)
49
+ continue;
50
+ entry.command = hook.command;
51
+ scripts.set(hook.script, await fs.readFile(path.join(source, path.basename(hook.script))));
52
+ count++;
53
+ }
54
+ }
55
+ }
56
+ if (!count)
57
+ return;
58
+ // Validate every script before making any writes or blessing a new digest.
59
+ for (const [script, bytes] of scripts) {
60
+ const state = await managedHookScriptState(home, script, bytes);
61
+ if (state === 'operator-edited' || state === 'unreadable')
62
+ throw new Error(`${script}: kept (${state}); user hook migration needs review`);
63
+ }
64
+ if (dryRun) {
65
+ if (!quiet)
66
+ ui.info(`Would anchor ${count} ${provider} user hook(s) — ${file} (with backup)`);
67
+ return;
68
+ }
69
+ const before = captureDeploymentOutputs([directory]);
70
+ const backup = `${file}.bak.${new Date().toISOString().replace(/[:.]/g, '-')}`;
71
+ await fs.copyFile(file, backup, fs.constants.COPYFILE_EXCL);
72
+ for (const [script, bytes] of scripts) {
73
+ const target = path.join(home, script);
74
+ await fs.mkdir(path.dirname(target), { recursive: true });
75
+ await fs.writeFile(target, bytes);
76
+ }
77
+ const temporary = `${file}.tmp.${process.pid}`;
78
+ try {
79
+ await fs.writeFile(temporary, JSON.stringify(doc, null, 2) + '\n');
80
+ await fs.rename(temporary, file);
81
+ }
82
+ finally {
83
+ await fs.rm(temporary, { force: true });
84
+ }
85
+ recordDeploymentOutputs(before, [directory], { frameworkSlug: 'aiwg-hooks',
86
+ writtenFiles: [file, ...[...scripts.keys()].map(script => path.join(home, script))] });
87
+ if (!quiet)
88
+ ui.info(`Anchored ${count} ${provider} user hook(s) — backup: ${backup}`);
89
+ }
90
+ /** Run the user-hook migration without letting a review-needed hook abort `aiwg refresh`. */
91
+ export async function refreshUserHooksOrWarn(options, migrate = refreshUserHooks) {
92
+ try {
93
+ await migrate(options);
94
+ return undefined;
95
+ }
96
+ catch (error) {
97
+ const message = `User hook migration skipped: ${error instanceof Error ? error.message : String(error)}`;
98
+ ui.warn(message);
99
+ return message;
100
+ }
101
+ }
102
+ //# sourceMappingURL=refresh-user-hooks.js.map
@@ -23,6 +23,7 @@ import { automaticRemovalAllowed } from '../../providers/deployment-preservation
23
23
  import { refreshDeclaredBundles } from './refresh-bundles.js';
24
24
  import { bundledRuleOutputNames } from './refresh-rule-inventory.js';
25
25
  import { checkManagedDeployment, sourcePrebuiltIndexRepairHint } from './refresh-managed-deployment.js';
26
+ import { refreshUserHooksOrWarn } from './refresh-user-hooks.js';
26
27
  import { getFrameworkRoot } from '../../channel/manager.mjs';
27
28
  import { refreshAllPackages } from '../../packages/registry.js';
28
29
  import { resolveActiveProvider } from '../provider-resolution.js';
@@ -545,6 +546,7 @@ export const refreshHandler = {
545
546
  if (!quiet)
546
547
  ui.dim(' Skipping package update (--skip-update)');
547
548
  }
549
+ await refreshUserHooksOrWarn({ frameworkRoot, provider: detectedProvider, dryRun, quiet });
548
550
  // Step 4: Re-deploy frameworks. Both the default form and --all mean
549
551
  // "all installed", never the `aiwg use all` expansion meta-target. This
550
552
  // preserves the operator's selected footprint and removal symmetry.
@@ -20,9 +20,17 @@ export function warnStaleParallelism(cfg, projectDir, key, before) {
20
20
  ` aiwg regenerate --workspace --provider ${provider}`,
21
21
  ]),
22
22
  ' aiwg workspace-context doctor',
23
+ ...(qualificationInputsChanged(cfg, key, before)
24
+ ? ['Worker routing or qualification inputs changed; recheck approval after fixing wiring:', ' aiwg doctor --probe-workers --qualify'] : []),
23
25
  `Shared parallelism defaults and labels use primary provider '${cfg.providers?.[0] ?? 'unknown'}' (providers[0]); --provider selects the adapter/context target.`,
24
26
  ];
25
27
  console.error(lines.join('\n'));
26
28
  }
27
29
  function getDottedPath(value, key) { return key.split('.').reduce((node, part) => node?.[part], value); }
30
+ function qualificationInputsChanged(cfg, key, before) {
31
+ const fields = ['clis', 'groups', 'groupTemplates', 'worker_dispatch', 'worker_mode'];
32
+ if (key === 'parallelism')
33
+ return fields.some(field => !isDeepStrictEqual(before?.[field], cfg.parallelism?.[field]));
34
+ return fields.some(field => key === `parallelism.${field}` || key.startsWith(`parallelism.${field}.`));
35
+ }
28
36
  //# sourceMappingURL=worker-guidance-warning.js.map
@@ -2,7 +2,12 @@
2
2
  import fs from 'node:fs/promises';
3
3
  import path from 'node:path';
4
4
  import os from 'node:os';
5
- export async function diagnoseUserHookCommands() {
5
+ function hasPromptHook(doc) {
6
+ const groups = doc?.hooks?.UserPromptSubmit;
7
+ return Array.isArray(groups) && groups.some(group => Array.isArray(group?.hooks) && group.hooks.some((hook) => hook?.type === 'command' && hook._aiwg_managed === true && hook._aiwg_id === 'aiwg-prompt-discovery'
8
+ && typeof hook.command === 'string' && hook.command.trim()));
9
+ }
10
+ export async function diagnoseUserHookCommands(projectRoot) {
6
11
  const diagnostics = [];
7
12
  for (const provider of ['claude', 'muse']) {
8
13
  const file = path.join(os.homedir(), `.${provider}`, provider === 'claude' ? 'settings.json' : 'hooks.json');
@@ -13,6 +18,16 @@ export async function diagnoseUserHookCommands() {
13
18
  catch {
14
19
  continue;
15
20
  } // Existing config diagnostics own unreadable documents.
21
+ if (provider === 'claude' && projectRoot && path.resolve(projectRoot) !== path.resolve(os.homedir()) && hasPromptHook(doc)) {
22
+ try {
23
+ const projectFile = path.join(projectRoot, '.claude/settings.json');
24
+ if (hasPromptHook(JSON.parse(await fs.readFile(projectFile, 'utf8')))) {
25
+ diagnostics.push({ severity: 'warning', code: 'duplicate-prompt-hook', path: projectFile,
26
+ message: 'Claude user and project settings both register AIWG prompt discovery. The current user loader defers to the project hook; refresh older global hooks with aiwg use all --global --providers claude.' });
27
+ }
28
+ }
29
+ catch { /* Existing config diagnostics own unreadable project settings. */ }
30
+ }
16
31
  for (const [event, groups] of Object.entries(doc.hooks || {})) {
17
32
  if (!Array.isArray(groups))
18
33
  continue;
@@ -18,6 +18,13 @@ export function verifiedHookCommand(root, relative, bytes, args = [], scope) {
18
18
  const loader = [
19
19
  "const fs=require('node:fs'),p=require('node:path'),M=require('node:module');",
20
20
  `const c=JSON.parse(Buffer.from('${data}','base64').toString());`,
21
+ // Claude merges project and user hooks. The project registration wins;
22
+ // keep the global fallback active when this is the home settings itself.
23
+ ...(user && relative === '.claude/hooks/aiwg-prompt-discovery.cjs' ? [
24
+ "try{const project=p.resolve(process.env.CLAUDE_PROJECT_DIR||process.cwd());",
25
+ "if(project!==c.anchor){const groups=JSON.parse(fs.readFileSync(p.join(project,'.claude/settings.json'),'utf8')).hooks?.UserPromptSubmit;",
26
+ "if(Array.isArray(groups)&&groups.some(g=>Array.isArray(g?.hooks)&&g.hooks.some(h=>h?.type==='command'&&h._aiwg_managed===true&&h._aiwg_id==='aiwg-prompt-discovery'&&typeof h.command==='string'&&h.command.trim())))process.exit(0);}}catch{}",
27
+ ] : []),
21
28
  'const root=c.projectEnv?process.env[c.projectEnv]||c.anchor:c.anchor;',
22
29
  `const script=p.resolve(root,'${relative}');`,
23
30
  "if(p.relative(fs.realpathSync(script),script)!==''||!fs.lstatSync(script).isFile())throw Error('Unsafe AIWG hook path');",
@@ -0,0 +1,92 @@
1
+ import { tmpdir } from 'node:os';
2
+ import { stripVTControlCharacters } from 'node:util';
3
+ import { buildWorkerObservation, classifyDiscoveryError, discoveryDigest, redactModelDiscoveryText, runModelDiscoveryCommand } from './model-discovery.js';
4
+ function diagnostic(value) {
5
+ // Redact bearer values before assignment redaction consumes the scheme.
6
+ return redactModelDiscoveryText(value.replace(/\bbearer\s+[A-Za-z0-9._~+/=-]+/gi, 'Bearer [REDACTED]'));
7
+ }
8
+ export async function discoverCursorListModels(command = 'cursor-agent', runner = runModelDiscoveryCommand, options = {}) {
9
+ const observedAt = (options.now?.() ?? new Date()).toISOString();
10
+ const base = { provider: 'cursor', source: 'native', observedAt,
11
+ accountScope: 'local-account', ...(options.accountBinding ? { accountBinding: options.accountBinding } : {}), models: [] };
12
+ try {
13
+ let version = options.runtimeVersion;
14
+ if (!version) {
15
+ const probe = await runner(command, ['--version'], { cwd: tmpdir(), timeoutMs: 5000 });
16
+ // Cursor emits a plain date-version banner. Retain only that known shape.
17
+ if (probe.exitCode === 0)
18
+ version = /^(\d+\.\d+\.\d+-[\w.-]+)$/.exec(probe.stdout.trim())?.[1]
19
+ .replace(/^(\d+)\.(\d+)\.(\d+)/, (_, major, minor, patch) => [major, minor, patch].map(Number).join('.'));
20
+ }
21
+ if (version)
22
+ base.runtimeVersion = version;
23
+ const result = await runner(command, ['--list-models'], { cwd: tmpdir(), timeoutMs: 15_000 });
24
+ if (result.exitCode !== 0) {
25
+ const error = diagnostic(result.stderr.trim() || result.stdout.trim())
26
+ || `Cursor --list-models exited ${result.exitCode}`;
27
+ return { ...base, errorKind: /not logged in|log in|sign in/i.test(error) ? 'authentication' : classifyDiscoveryError(error), error };
28
+ }
29
+ const diagnostics = [];
30
+ const seen = new Set();
31
+ for (const [index, raw] of result.stdout.split(/\r?\n/).entries()) {
32
+ const line = stripVTControlCharacters(raw).replace(/[\u200B-\u200D\u2060\uFEFF]/g, '').trim();
33
+ if (!line || /^Available models$/i.test(line) || /^Tip: use --model <id>/.test(line))
34
+ continue;
35
+ const match = /^([a-z0-9][a-z0-9._-]*) - (\S.*)$/i.exec(line);
36
+ if (!match || /[\x00-\x1f\x7f]/.test(line)) {
37
+ diagnostics.push(`Cursor --list-models line ${index + 1}: malformed model row`);
38
+ continue;
39
+ }
40
+ const [, id, label] = match;
41
+ if (seen.has(id)) {
42
+ diagnostics.push(`Cursor --list-models line ${index + 1}: duplicate model selector`);
43
+ continue;
44
+ }
45
+ seen.add(id);
46
+ const displayName = label.replace(/(?:\s+\([^()]*\))+$/, '').trim();
47
+ const automatic = /^(?:auto|default)$/i.test(id);
48
+ // Effort belongs to the exact selector; never invent bracket overrides or
49
+ // a default effort for a name that does not report a variant.
50
+ const effort = /-extra-high(?:-fast)?$/.test(id) ? 'xhigh'
51
+ : /-(minimal|none|low|medium|high|xhigh|max)(?:-fast)?$/.exec(id)?.[1];
52
+ const declared = Object.hasOwn(options.modelLimits ?? {}, id) ? options.modelLimits[id] : undefined;
53
+ const displayContext = /(?:^|\s)1M(?:\s|$)/.test(displayName) ? 1_000_000 : undefined;
54
+ const worker = buildWorkerObservation({ cliId: options.cliId ?? 'cursor', source: `${command} --list-models`,
55
+ pointer: `/lines/${index + 1}`, runtimeVersion: version ?? 'unknown', accountScope: 'local-account',
56
+ accountBinding: options.accountBinding, observedAt, contentDigest: discoveryDigest(line) }, {
57
+ modelId: id, family: 'unknown', visibility: 'listed', lifecycle: 'active',
58
+ availability: automatic ? 'unavailable' : 'accessible',
59
+ contextTokens: declared?.contextTokens ?? displayContext, maxOutputTokens: declared?.maxOutputTokens,
60
+ efforts: !automatic && effort ? [{ id: effort, selfDelegates: null }] : [],
61
+ provenanceFields: ['/apiModelId:listed-selector', '/llmProvider:cursor-gateway', '/displayName', '/efforts:selector-suffix',
62
+ ...(!declared && displayContext ? ['/contextTokens:display-name-1M'] : [])],
63
+ });
64
+ if (declared) {
65
+ // The native list does not attest operator limits.
66
+ worker.provenance[0].fields = worker.provenance[0].fields.filter(field => field !== '/contextTokens' && (declared.maxOutputTokens === undefined || field !== '/maxOutputTokens'));
67
+ const source = `/parallelism/clis/${options.cliId ?? 'cursor'}/modelLimits`;
68
+ worker.provenance.push({ fields: ['/contextTokens', ...(declared.maxOutputTokens === undefined ? [] : ['/maxOutputTokens'])],
69
+ source, kind: 'operator', observedAt, digest: discoveryDigest(JSON.stringify({ id, ...declared })), confidence: 'reported' });
70
+ worker.evidenceDigest = discoveryDigest(JSON.stringify({ native: worker.evidenceDigest, source, id, ...declared }));
71
+ }
72
+ // The list identifies the Cursor gateway selector, not an attested
73
+ // upstream API model, vendor, family or data policy.
74
+ base.models.push({ id, apiModelId: id, llmProvider: 'cursor', displayName,
75
+ isDefault: /\([^()]*\bdefault\b[^()]*\)/i.test(label), hidden: false,
76
+ reasoningEfforts: worker.efforts.map(entry => entry.id), worker });
77
+ }
78
+ return { ...base, ...(diagnostics.length || !base.models.length ? { errorKind: 'invalid-output',
79
+ error: diagnostics.join('; ') || 'Cursor returned no parseable model rows.' } : {}) };
80
+ }
81
+ catch (cause) {
82
+ const error = diagnostic(cause instanceof Error ? cause.message : 'Cursor discovery command failed');
83
+ return { ...base, models: [], errorKind: classifyDiscoveryError(error), error };
84
+ }
85
+ }
86
+ /** Bind refresh to the configured Cursor executable and account label when unambiguous. */
87
+ export async function discoverProjectCursorModels(options) {
88
+ const clis = Object.entries(options.parallelism?.clis ?? {}).filter(([id, cli]) => cli.enabled !== false && !cli.localModels && (cli.adapter ?? `providers:${id}`) === 'providers:cursor');
89
+ const [cliId, cli] = clis.length === 1 ? clis[0] : [];
90
+ return discoverCursorListModels(cli?.executable, options.runner, { cliId, accountBinding: cli?.accountScope, modelLimits: cli?.modelLimits, now: options.now });
91
+ }
92
+ //# sourceMappingURL=cursor-models.js.map