osuite 2.10.0 → 2.10.1

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.
package/projectHooks.js CHANGED
@@ -5,8 +5,9 @@ import fs from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import crypto from 'node:crypto';
7
7
  import { spawn } from 'node:child_process';
8
+ import { fileURLToPath } from 'node:url';
8
9
 
9
- const HOOK_SCRIPT_RE = /osuite_(?:pretool|posttool|stop)\.py/;
10
+ const HOOK_SCRIPT_RE = /osuite_(?:pretool|posttool|stop|session)\.(?:py|mjs)/;
10
11
 
11
12
  export const RUNTIME_HOOKS = {
12
13
  claude: {
@@ -20,6 +21,10 @@ export const RUNTIME_HOOKS = {
20
21
  settings: ['.codex/hooks.json'],
21
22
  config: '.codex/config.toml',
22
23
  },
24
+ cursor: {
25
+ label: 'Cursor', dir: '.cursor', settings: ['.cursor/hooks.json'],
26
+ preEvent: 'preToolUse', postEvent: 'postToolUse', flatHooks: true,
27
+ },
23
28
  };
24
29
 
25
30
  const MERGED_FILES = {
@@ -27,6 +32,9 @@ const MERGED_FILES = {
27
32
  '.claude/settings.local.json': 'json',
28
33
  '.codex/hooks.json': 'json',
29
34
  '.codex/config.toml': 'toml',
35
+ '.mcp.json': 'mcp',
36
+ '.cursor/hooks.json': 'cursor-hooks',
37
+ '.cursor/mcp.json': 'mcp',
30
38
  };
31
39
 
32
40
  export const DOCTOR_COMMAND = 'echo "OSuite doctor hook check"';
@@ -45,7 +53,7 @@ function hookScriptName(command) {
45
53
  function sameHook(existing, wanted) {
46
54
  const existingScript = hookScriptName(existing?.command);
47
55
  const wantedScript = hookScriptName(wanted?.command);
48
- if (existingScript && wantedScript) return existingScript === wantedScript;
56
+ if (existingScript && wantedScript) return existingScript.replace(/\.(py|mjs)$/, '') === wantedScript.replace(/\.(py|mjs)$/, '');
49
57
  return String(existing?.command || '').trim() === String(wanted?.command || '').trim();
50
58
  }
51
59
 
@@ -96,30 +104,163 @@ export function mergeHookSettings(existingText, templateText) {
96
104
  const wanted = isPlainObject(template.hooks) ? template.hooks : {};
97
105
  const merged = { ...hooks };
98
106
  const added = [];
107
+ const migrated = [];
108
+ const migrationConflicts = [];
99
109
  for (const [event, groups] of Object.entries(wanted)) {
100
110
  const current = merged[event] === undefined ? [] : merged[event];
101
111
  if (!Array.isArray(current)) return { status: 'error', error: `"hooks.${event}" must be a list` };
102
- const present = current.flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []));
103
- const next = [...current];
112
+ const requested = (Array.isArray(groups) ? groups : []).flatMap(group => group.hooks || []);
113
+ const next = current.map(group => ({ ...group, hooks: (group.hooks || []).map(existing => {
114
+ const replacement = requested.find(hook => sameHook(existing, hook));
115
+ if (!replacement || !hookScriptName(existing.command).endsWith('.py') || !hookScriptName(replacement.command).endsWith('.mjs')) return existing;
116
+ const script = hookScriptName(existing.command);
117
+ const stock = [`python3 .claude/hooks/${script}`, `python3 .codex/hooks/${script}`,
118
+ `python3 "$(git rev-parse --show-toplevel)/.codex/hooks/${script}"`];
119
+ if (!stock.includes(existing.command)) {
120
+ migrationConflicts.push(`custom legacy ${script} command was preserved; review its Node migration before relying on this installation`);
121
+ return existing;
122
+ }
123
+ migrated.push({ event, matcher: group.matcher, command: replacement.command });
124
+ return { ...existing, ...replacement };
125
+ }) }));
126
+ const present = next.flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []));
104
127
  for (const group of Array.isArray(groups) ? groups : []) {
105
128
  const missing = (group.hooks || []).filter((hook) => !present.some((existing) => sameHook(existing, hook)));
106
129
  if (!missing.length) continue;
107
130
  next.push({ ...group, hooks: missing });
108
131
  missing.forEach((hook) => added.push({ event, matcher: group.matcher, command: hook.command }));
109
132
  }
110
- if (next.length !== current.length) merged[event] = next;
133
+ if (next.length !== current.length || migrated.some(item => item.event === event)) merged[event] = next;
111
134
  }
112
135
 
113
136
  const result = {
114
- added,
137
+ added, migrated,
115
138
  keptHooks: countHooks(hooks),
116
139
  keptKeys: Object.keys(settings).filter((key) => key !== 'hooks'),
117
- conflicts: disabledHookSettings(settings),
140
+ conflicts: [...disabledHookSettings(settings), ...migrationConflicts],
118
141
  };
119
- if (!added.length) return { ...result, status: 'unchanged', body: existingText };
142
+ if (!added.length && !migrated.length) return { ...result, status: 'unchanged', body: existingText };
120
143
  return { ...result, status: 'merged', body: `${JSON.stringify({ ...settings, hooks: merged }, null, 2)}\n` };
121
144
  }
122
145
 
146
+ function mergeMcpSettings(existingText, templateText) {
147
+ const template = JSON.parse(templateText);
148
+ const existing = existingText ? JSON.parse(existingText) : {};
149
+ if (!isPlainObject(existing) || (existing.mcpServers !== undefined && !isPlainObject(existing.mcpServers))) return { status: 'error', error: 'expected an MCP configuration object' };
150
+ const servers = { ...(existing.mcpServers || {}) };
151
+ const added = [], conflicts = [];
152
+ for (const [name, server] of Object.entries(template.mcpServers || {})) {
153
+ if (servers[name] && JSON.stringify(servers[name]) !== JSON.stringify(server)) {
154
+ conflicts.push(`${name} MCP registration differs; it was preserved for explicit operator review`);
155
+ } else if (!servers[name]) { servers[name] = server; added.push(name); }
156
+ }
157
+ return { status: existingText == null ? 'created' : added.length ? 'merged' : 'unchanged', added, conflicts,
158
+ body: added.length || existingText == null ? `${JSON.stringify({ ...existing, mcpServers: servers }, null, 2)}\n` : existingText };
159
+ }
160
+
161
+ export function mergeCursorHookSettings(existingText, templateText) {
162
+ const template = JSON.parse(templateText);
163
+ const existing = existingText == null ? { version: 1, hooks: {} } : JSON.parse(existingText);
164
+ if (!isPlainObject(existing) || existing.version !== 1 || !isPlainObject(existing.hooks ?? {})) {
165
+ return { status: 'error', error: 'Cursor hooks require version 1 and a hooks object; existing configuration was preserved' };
166
+ }
167
+ const hooks = { ...(existing.hooks || {}) }, added = [], conflicts = [...disabledHookSettings(existing)];
168
+ for (const [event, handlers] of Object.entries(hooks)) {
169
+ if (!Array.isArray(handlers)) return { status: 'error', error: `hooks.${event} must be a list; existing configuration was preserved` };
170
+ }
171
+ // Cursor does not document this flag. Do not rely on it to suppress newly
172
+ // added hooks when preserving an operator's explicit disablement intent.
173
+ if (existing.disableAllHooks === true) return { status: 'unchanged', body: existingText, added: [],
174
+ conflicts: ['Existing disableAllHooks intent was preserved; no Cursor hook registrations were added'],
175
+ keptHooks: Object.values(hooks).reduce((count, handlers) => count + handlers.length, 0),
176
+ keptKeys: Object.keys(existing).filter(key => key !== 'hooks') };
177
+ for (const [event, handlers] of Object.entries(template.hooks)) {
178
+ const next = [...(hooks[event] || [])];
179
+ for (const handler of handlers) {
180
+ const present = next.find(current => sameHook(current, handler));
181
+ if (!present) { next.push(handler); added.push({ event, ...handler }); }
182
+ else if (present.command !== handler.command || present.enabled === false || present.disabled === true || !['command', undefined].includes(present.type)
183
+ || (event === 'preToolUse' && (present.failClosed !== true || !['', '*', undefined].includes(present.matcher)))) {
184
+ conflicts.push(`custom Cursor ${event} command or safety flags were preserved; review before relying on this installation`);
185
+ }
186
+ }
187
+ hooks[event] = next;
188
+ }
189
+ return { status: existingText == null ? 'created' : added.length ? 'merged' : 'unchanged', added, conflicts,
190
+ keptHooks: Object.values(existing.hooks || {}).reduce((count, handlers) => count + handlers.length, 0),
191
+ keptKeys: Object.keys(existing).filter(key => key !== 'hooks'),
192
+ body: existingText == null || added.length ? `${JSON.stringify({ ...existing, hooks }, null, 2)}\n` : existingText };
193
+ }
194
+
195
+ function packagedRuntimeFiles(directory) {
196
+ const source = fileURLToPath(new URL('./runtime/', import.meta.url));
197
+ return Object.fromEntries(fs.readdirSync(source).sort().filter(name => /^[a-zA-Z0-9-]+\.mjs$/.test(name))
198
+ .map(name => [`${directory}/runtime/${name}`, fs.readFileSync(path.join(source, name), 'utf8')]));
199
+ }
200
+
201
+ function buildCursorBootstrap(bootstrap) {
202
+ const files = { ...bootstrap.files, ...packagedRuntimeFiles('.cursor') };
203
+ const events = { preToolUse: 'pretool', postToolUse: 'posttool', sessionStart: 'session', stop: 'stop' };
204
+ const hooks = {};
205
+ for (const [event, script] of Object.entries(events)) {
206
+ files[`.cursor/hooks/osuite_${script}.mjs`] = `#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { runCursorHookCli } from '../runtime/cursor.mjs';\nawait runCursorHookCli({ installDir: fileURLToPath(new URL('..', import.meta.url)), event: ${JSON.stringify(event)} });\n`;
207
+ hooks[event] = [{ command: `node .cursor/hooks/osuite_${script}.mjs`, timeout: 60, ...(event === 'preToolUse' ? { failClosed: true } : {}) }];
208
+ }
209
+ hooks.postToolUseFailure = hooks.postToolUse;
210
+ hooks.sessionEnd = hooks.sessionStart;
211
+ files['.cursor/hooks.json'] = `${JSON.stringify({ version: 1, hooks }, null, 2)}\n`;
212
+ files['.cursor/server/osuite_runtime_mcp.mjs'] = "#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { runMcpCli } from '../runtime/mcp.mjs';\nawait runMcpCli({ host: 'cursor', runtimeId: 'cursor_hooks', installDir: fileURLToPath(new URL('..', import.meta.url)) });\n";
213
+ files['.cursor/mcp.json'] = `${JSON.stringify({ mcpServers: { osuite_runtime_governance: {
214
+ type: 'stdio', command: 'node', args: ['${workspaceFolder}/.cursor/server/osuite_runtime_mcp.mjs'],
215
+ } } }, null, 2)}\n`;
216
+ files['.cursor/README.node-runtime.md'] = '# OSuite Cursor Node runtime\n\nNode.js 18+; no Python or runtime dependency installation.\nProject hooks run from the project root in a trusted workspace. Preserve explicit disabled settings.\nGeneric Agent hooks are installed, not Tab hooks. Session start does not block; every preflight refreshes verified posture.\nThe MCP bridge is advisory and does not execute upstream tools.\nDirect diagnostics and wire fixtures do not establish native host invocation or all-action coverage.\n';
217
+ return { ...bootstrap, files, runtime: { ...bootstrap.runtime, id: 'cursor_hooks', implementation: 'node', implementation_version: 1 },
218
+ node_runtime: { schema_version: 'osuite.node_runtime.v1', minimum_node_major: 18, settings_path: '.cursor/hooks.json', requires_host_trust_review: true } };
219
+ }
220
+
221
+ /** Locally packaged, dependency-free runtime code replaces downloaded legacy launchers. */
222
+ export function buildNodeRuntimeBootstrap(runtime, bootstrap = {}, { projectRoot = process.cwd() } = {}) {
223
+ if (['cursor', 'cursor_hooks'].includes(runtime)) return buildCursorBootstrap(bootstrap);
224
+ const host = ['claude', 'claude-code', 'claude_code_hooks'].includes(runtime) ? 'claude'
225
+ : ['codex', 'codex_hooks'].includes(runtime) ? 'codex' : null;
226
+ if (!host) throw new Error('Node bootstrap supports Claude Code, Codex and Cursor project hooks only');
227
+ const directory = host === 'claude' ? '.claude' : '.codex';
228
+ const runtimeId = host === 'claude' ? 'claude_code_hooks' : 'codex_hooks';
229
+ const files = Object.fromEntries(Object.entries(bootstrap.files || {}).filter(([name]) => !/osuite_(pretool|posttool|stop)\.py$/.test(name)
230
+ && !['.claude/settings.json', '.claude/settings.local.json', '.codex/hooks.json', '.codex/config.toml'].includes(name)));
231
+ Object.assign(files, packagedRuntimeFiles(directory));
232
+ const literal = value => JSON.stringify(value);
233
+ const shellQuote = value => `'${String(value).replace(/'/g, "'\\''")}'`;
234
+ const events = { PreToolUse: 'pretool', PostToolUse: 'posttool', SessionStart: 'session', Stop: 'stop' };
235
+ const settings = { hooks: {} };
236
+ for (const [event, script] of Object.entries(events)) {
237
+ files[`${directory}/hooks/osuite_${script}.mjs`] = `#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { runHookCli } from '../runtime/hook.mjs';\nawait runHookCli({ host: ${literal(host)}, runtimeId: ${literal(runtimeId)}, installDir: fileURLToPath(new URL('..', import.meta.url)), event: ${literal(event)} });\n`;
238
+ const absolute = path.join(path.resolve(projectRoot), directory, `hooks/osuite_${script}.mjs`);
239
+ const handler = { type: 'command', command: `node ${shellQuote(absolute)}`, timeout: 60 };
240
+ if (host === 'codex') handler.commandWindows = `node "${absolute.replace(/"/g, '""')}"`;
241
+ settings.hooks[event] = [{ hooks: [handler] }];
242
+ }
243
+ if (host === 'claude') settings.hooks.PostToolUseFailure = settings.hooks.PostToolUse;
244
+ let settingsPath = host === 'claude' ? '.claude/settings.json' : '.codex/hooks.json';
245
+ if (host === 'claude') {
246
+ // Do not duplicate an existing registration across project and local layers.
247
+ for (const candidate of ['.claude/settings.json', '.claude/settings.local.json']) {
248
+ try {
249
+ const current = JSON.parse(fs.readFileSync(path.join(projectRoot, candidate), 'utf8'));
250
+ if (Object.values(current.hooks || {}).some(groups => Array.isArray(groups) && groups.some(group => (group.hooks || []).some(hook => HOOK_SCRIPT_RE.test(hook.command || ''))))) { settingsPath = candidate; break; }
251
+ } catch { /* The installer reports malformed settings without overwriting them. */ }
252
+ }
253
+ }
254
+ files[settingsPath] = `${JSON.stringify(settings, null, 2)}\n`;
255
+ files[`${directory}/server/osuite_runtime_mcp.mjs`] = `#!/usr/bin/env node\nimport { fileURLToPath } from 'node:url';\nimport { runMcpCli } from '../runtime/mcp.mjs';\nawait runMcpCli({ host: ${literal(host)}, runtimeId: ${literal(runtimeId)}, installDir: fileURLToPath(new URL('..', import.meta.url)) });\n`;
256
+ const mcpScript = path.join(path.resolve(projectRoot), directory, 'server/osuite_runtime_mcp.mjs');
257
+ if (host === 'claude') files['.mcp.json'] = `${JSON.stringify({ mcpServers: { osuite_runtime_governance: { command: 'node', args: [mcpScript] } } }, null, 2)}\n`;
258
+ else files['.codex/config.toml'] = `[features]\nhooks = true\n\n[mcp_servers.osuite_runtime_governance]\ncommand = "node"\nargs = [${literal(mcpScript)}]\n`;
259
+ files[`${directory}/README.node-runtime.md`] = '# OSuite Node runtime\n\nNode.js 18+ is required. No Python or runtime package installation is used.\nHooks read only this installation\'s .env and the process environment.\nRemote posture is refreshed at session start and preflight; expired enforce configuration blocks.\nReview changed hook definitions in the host. Existing disabled settings are preserved.\nDoctor is a direct diagnostic, not proof that the host has trusted or invoked a hook.\nThe MCP bridge does not execute upstream tools or prevent direct resource access.\n';
260
+ return { ...bootstrap, files, runtime: { ...bootstrap.runtime, implementation: 'node', implementation_version: 1 },
261
+ node_runtime: { schema_version: 'osuite.node_runtime.v1', minimum_node_major: 18, settings_path: settingsPath, requires_host_trust_review: host === 'codex' } };
262
+ }
263
+
123
264
  // --- TOML ------------------------------------------------------------------
124
265
  // Line-based on purpose: the CLI has no dependencies, and the partial only sets
125
266
  // plain keys. Lines inside multi-line strings and arrays are skipped.
@@ -269,6 +410,9 @@ export function mergeTomlPartial(existingText, partialText) {
269
410
  const current = scan.values.get(fullKey);
270
411
  if (current !== entry.value && !HOOK_FLAGS.includes(fullKey)) {
271
412
  kept.push({ key: describeTomlEntry({ ...entry, value: current }), suggested: entry.value });
413
+ if (entry.table === 'mcp_servers.osuite_runtime_governance') {
414
+ conflicts.push(`OSuite MCP ${entry.key} differs; the existing registration was preserved for explicit operator review`);
415
+ }
272
416
  }
273
417
  continue;
274
418
  }
@@ -379,7 +523,8 @@ export function installProjectFile(projectRoot, relativePath, body, { force = fa
379
523
  if (kind) {
380
524
  let merge;
381
525
  try {
382
- merge = kind === 'json' ? mergeHookSettings(existing, String(body ?? '')) : mergeTomlPartial(existing, String(body ?? ''));
526
+ merge = kind === 'json' ? mergeHookSettings(existing, String(body ?? '')) : kind === 'cursor-hooks' ? mergeCursorHookSettings(existing, String(body ?? ''))
527
+ : kind === 'mcp' ? mergeMcpSettings(existing, String(body ?? '')) : mergeTomlPartial(existing, String(body ?? ''));
383
528
  } catch (error) {
384
529
  merge = { status: 'error', error: `OSuite template could not be read (${error.message})` };
385
530
  }
@@ -415,11 +560,12 @@ export function describeInstallResult(result) {
415
560
  lines.push(`failed ${name}: ${result.error}. Nothing was changed; fix the file and run this again.`);
416
561
  return lines;
417
562
  }
418
- if (result.kind === 'json') {
563
+ if (result.kind === 'json' || result.kind === 'cursor-hooks') {
419
564
  if (result.status === 'unchanged') lines.push(`unchanged ${name} (OSuite hooks already there)`);
420
565
  else lines.push(`${result.status === 'created' ? 'created' : 'merged '} ${name}`);
421
566
  if (result.status !== 'unchanged') {
422
567
  result.added.forEach((hook) => lines.push(` + ${hook.event} ${hook.matcher || '*'} → ${hook.command}`));
568
+ (result.migrated || []).forEach((hook) => lines.push(` migrated ${hook.event} to Node; review the changed hook in the host`));
423
569
  }
424
570
  if (result.status === 'merged') {
425
571
  const others = result.keptKeys.length ? ` and your other settings (${result.keptKeys.join(', ')})` : '';
@@ -452,11 +598,14 @@ function readJson(absolute) {
452
598
  return JSON.parse(fs.readFileSync(absolute, 'utf8'));
453
599
  }
454
600
 
455
- function findCommand(settings, event, script) {
601
+ function eventHooks(settings, event, flat = false) {
456
602
  const groups = Array.isArray(settings?.hooks?.[event]) ? settings.hooks[event] : [];
457
- return groups
458
- .flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : []))
459
- .find((hook) => typeof hook?.command === 'string' && hookScriptName(hook.command) === script) || null;
603
+ return flat ? groups : groups.flatMap(group => Array.isArray(group?.hooks) ? group.hooks : []);
604
+ }
605
+
606
+ function findCommand(settings, event, script, flat = false) {
607
+ return eventHooks(settings, event, flat)
608
+ .find((hook) => typeof hook?.command === 'string' && hookScriptName(hook.command).replace(/\.(py|mjs)$/, '') === script.replace(/\.(py|mjs)$/, '')) || null;
460
609
  }
461
610
 
462
611
  /** OSuite hooks registered in this project, with anything that stops them from running. */
@@ -466,6 +615,8 @@ export function findHookInstallations(projectRoot, runtimes = Object.keys(RUNTIM
466
615
  if (!spec) return [];
467
616
  const problems = [];
468
617
  const disabledReasons = [];
618
+ let pretoolCount = 0;
619
+ let posttoolCount = 0;
469
620
  let pretool = null;
470
621
  let posttool = null;
471
622
  spec.settings.forEach((settingsPath) => {
@@ -478,18 +629,32 @@ export function findHookInstallations(projectRoot, runtimes = Object.keys(RUNTIM
478
629
  problems.push(`${settingsPath} is not valid JSON, so ${spec.label} cannot load its hooks`);
479
630
  return;
480
631
  }
481
- disabledHookSettings(settings).forEach((reason) => disabledReasons.push(`${settingsPath}: ${reason}`));
482
- const pre = findCommand(settings, 'PreToolUse', 'osuite_pretool.py');
483
- const post = findCommand(settings, 'PostToolUse', 'osuite_posttool.py');
632
+ disabledHookSettings(settings).forEach((reason) => disabledReasons.push(`${settingsPath}: ${runtime === 'cursor'
633
+ ? 'explicit disableAllHooks intent was preserved; this is not a documented Cursor host control' : reason}`));
634
+ const preEvent = spec.preEvent || 'PreToolUse', postEvent = spec.postEvent || 'PostToolUse';
635
+ const pre = findCommand(settings, preEvent, 'osuite_pretool.py', spec.flatHooks);
636
+ const post = findCommand(settings, postEvent, 'osuite_posttool.py', spec.flatHooks);
637
+ pretoolCount += eventHooks(settings, preEvent, spec.flatHooks)
638
+ .filter(hook => /osuite_pretool\.(?:py|mjs)/.test(hook?.command || '')).length;
639
+ posttoolCount += eventHooks(settings, postEvent, spec.flatHooks)
640
+ .filter(hook => /osuite_posttool\.(?:py|mjs)/.test(hook?.command || '')).length;
641
+ if (runtime === 'cursor') {
642
+ if (settings.version !== 1) problems.push(`${settingsPath} is not Cursor hooks schema version 1`);
643
+ if ([pre, post].some(handler => handler && !['command', undefined].includes(handler.type))) problems.push('Cursor OSuite hooks must use command execution type, not a prompt');
644
+ if (pre && pre.failClosed !== true) problems.push('Cursor preToolUse must have failClosed: true to block hook process failures');
645
+ if (pre && !['', '*', undefined].includes(pre.matcher)) problems.push('Cursor preToolUse matcher restricts coverage; the custom matcher was preserved');
646
+ if (pre?.disabled === true || pre?.enabled === false) disabledReasons.push('Cursor preToolUse contains explicit disabled intent; it was preserved');
647
+ }
484
648
  if (pre && !pretool) pretool = { settingsPath, command: pre.command };
485
649
  if (post && !posttool) posttool = { settingsPath, command: post.command };
486
650
  });
651
+ if (!disabledReasons.length && (pretoolCount > 1 || posttoolCount > 1)) problems.push('Multiple OSuite hook registrations were preserved; resolve duplicate hooks before relying on a single governed invocation');
487
652
 
488
653
  const scriptPath = `${spec.dir}/hooks/osuite_pretool.py`;
489
- const scriptPresent = fs.existsSync(path.join(projectRoot, scriptPath));
654
+ const scriptPresent = fs.existsSync(path.join(projectRoot, scriptPath)) || fs.existsSync(path.join(projectRoot, scriptPath.replace(/\.py$/, '.mjs')));
490
655
  if (!pretool && !scriptPresent && !problems.length) return [];
491
656
  if (!pretool) {
492
- problems.push(`no PreToolUse hook in ${spec.settings.join(' or ')} runs osuite_pretool.py`);
657
+ problems.push(`no ${spec.preEvent || 'PreToolUse'} hook in ${spec.settings.join(' or ')} runs osuite_pretool.${runtime === 'cursor' ? 'mjs' : 'py'}`);
493
658
  }
494
659
  if (spec.config) {
495
660
  const config = readIfExists(path.join(projectRoot, spec.config));
@@ -530,7 +695,7 @@ export function hookCredentials(projectRoot, installation, shellEnv = process.en
530
695
  baseUrl: String(env.OSUITE_BASE_URL || env.DASHCLAW_BASE_URL || '').replace(/\/$/, ''),
531
696
  apiKey: String(env.OSUITE_API_KEY || env.DASHCLAW_API_KEY || ''),
532
697
  envFile: `${installation.installDir}/.env`,
533
- hookMode: String(env.OSUITE_HOOK_MODE || env.DASHCLAW_HOOK_MODE || 'enforce'),
698
+ hookMode: String(env.OSUITE_HOOK_MODE || env.DASHCLAW_HOOK_MODE || (installation.runtime === 'cursor' ? 'observe' : 'enforce')),
534
699
  };
535
700
  }
536
701
 
@@ -563,7 +728,8 @@ function hookMessages(stdout) {
563
728
  return String(stdout || '').split(/\r?\n/).flatMap((line) => {
564
729
  try {
565
730
  const parsed = JSON.parse(line);
566
- return typeof parsed?.systemMessage === 'string' ? [parsed.systemMessage] : [];
731
+ return [...new Set(['systemMessage', 'user_message', 'agent_message', 'additional_context']
732
+ .map(field => parsed?.[field]).filter(value => typeof value === 'string' && value))];
567
733
  } catch {
568
734
  return [];
569
735
  }
@@ -595,7 +761,7 @@ async function fetchSessionEvents(fetchImpl, { baseUrl, apiKey, sessionId }) {
595
761
  }
596
762
 
597
763
  /**
598
- * Directly probe the registered hook with an inert Bash call. Configuration,
764
+ * Directly probe the registered hook with an inert shell call. Configuration,
599
765
  * telemetry, and policy outcomes are separate checks; this is not a host launch.
600
766
  */
601
767
  export async function runHookCheck({
@@ -636,11 +802,12 @@ export async function runHookCheck({
636
802
  const id = crypto.randomBytes(4).toString('hex');
637
803
  sessionId = `osuite-doctor-${id}`;
638
804
  const toolUseId = `osuite_doctor_${id}`;
805
+ const cursor = installation.runtime === 'cursor';
639
806
  const sample = {
640
- session_id: sessionId,
807
+ ...(cursor ? { conversation_id: sessionId, generation_id: `osuite-doctor-generation-${id}` } : { session_id: sessionId }),
641
808
  cwd: projectRoot,
642
- hook_event_name: 'PreToolUse',
643
- tool_name: 'Bash',
809
+ hook_event_name: cursor ? 'preToolUse' : 'PreToolUse',
810
+ tool_name: cursor ? 'Shell' : 'Bash',
644
811
  tool_input: { command: DOCTOR_COMMAND, description: 'OSuite doctor hook check' },
645
812
  tool_use_id: toolUseId,
646
813
  };
@@ -664,7 +831,7 @@ export async function runHookCheck({
664
831
  steps.push({
665
832
  ok: true,
666
833
  label: 'Hook test',
667
- detail: `sample Bash call (${DOCTOR_COMMAND}) ${run.code === 0 ? 'allowed' : 'stopped'} by the hook${run.code === 2 && said ? `: ${said}` : ''}`,
834
+ detail: `sample ${sample.tool_name} call (${DOCTOR_COMMAND}) ${run.code === 0 ? 'allowed' : 'stopped'} by the hook${run.code === 2 && said ? `: ${said}` : ''}`,
668
835
  });
669
836
 
670
837
  let lookup = await fetchSessionEvents(fetchImpl, { ...credentials, sessionId });
@@ -682,8 +849,9 @@ export async function runHookCheck({
682
849
  timeoutMs,
683
850
  input: JSON.stringify({
684
851
  ...sample,
685
- hook_event_name: 'PostToolUse',
686
- tool_response: { stdout: 'OSuite doctor hook check', stderr: '', interrupted: false, exit_code: 0 },
852
+ hook_event_name: cursor ? 'postToolUse' : 'PostToolUse',
853
+ ...(cursor ? { tool_output: JSON.stringify({ exitCode: 0 }) }
854
+ : { tool_response: { stdout: 'OSuite doctor hook check', stderr: '', interrupted: false, exit_code: 0 } }),
687
855
  }),
688
856
  });
689
857
  }
@@ -703,7 +871,10 @@ export async function runHookCheck({
703
871
  detail: `${[...new Set(seen.map((event) => event.event_type))].join(', ')} reached OSuite (session ${sessionId})`,
704
872
  });
705
873
 
706
- const observing = credentials.hookMode === 'observe' || seen.some((event) => (
874
+ const nodeHook = /\bosuite_pretool\.mjs\b/.test(installation.pretool.command);
875
+ const preflightModes = seen.filter((event) => event.event_type === 'tool_preflight')
876
+ .map((event) => event.payload?.hook_mode).filter((mode) => ['observe', 'enforce', 'strict'].includes(mode));
877
+ const observing = (!preflightModes.length && credentials.hookMode === 'observe') || seen.some((event) => (
707
878
  event.payload?.hook_mode === 'observe' || event.payload?.observe_only === true
708
879
  || String(event.payload?.decision || '').startsWith('observe_')
709
880
  ));
@@ -712,6 +883,9 @@ export async function runHookCheck({
712
883
  if (unavailable) return fail('Governance', `Not governed: guard unavailable; the hook ${run.code === 0 ? 'failed open' : 'failed closed'}, and telemetry alone does not verify governance`);
713
884
  const ungoverned = warnings.find((warning) => /Not governed/i.test(warning));
714
885
  if (ungoverned) return fail('Governance', ungoverned);
886
+ if (nodeHook && !preflightModes.some((mode) => mode === 'enforce' || mode === 'strict')) {
887
+ return fail('Governance', 'Not verified: no matching event-time enforcing posture was recorded for the sample call');
888
+ }
715
889
 
716
890
  const outcome = seen.find((event) => {
717
891
  const decision = event.payload?.decision;
@@ -725,6 +899,7 @@ export async function runHookCheck({
725
899
  && ['require_approval', 'require_dual_approval'].includes(decision);
726
900
  }
727
901
  if (event.event_type === 'tool_blocked' && decision === 'block') {
902
+ if (nodeHook) return event.payload?.reason === 'policy_block';
728
903
  return event.payload?.reason !== 'action_creation_not_authorized'
729
904
  && !String(event.payload?.reason || '').startsWith('Unsupported guard decision:');
730
905
  }
@@ -0,0 +1,150 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+ import { isObject, safeId } from './protocol.mjs';
3
+
4
+ export const REVIEW_DECISIONS = new Set(['require_approval', 'require_dual_approval']);
5
+ const DECISIONS = new Set(['allow', 'warn', 'block', ...REVIEW_DECISIONS]);
6
+ const closed = (reason, extra = {}) => ({ authorized: false, decision: 'block', reason, retryAutomatically: false, ...extra });
7
+
8
+ function approvalReceipts(payload) {
9
+ const action = payload?.action || payload || {};
10
+ return [action.approval_receipts, action.proof_bundle?.approval_receipts,
11
+ payload?.approval_receipts, payload?.contracts?.proof_bundle?.approval_receipts]
12
+ .flatMap(value => Array.isArray(value) ? value.filter(isObject) : []);
13
+ }
14
+
15
+ export function cavaFingerprint(payload) {
16
+ return [payload?.contracts?.action_envelope?.cava?.fingerprint,
17
+ payload?.contracts?.proof_bundle?.action_envelope?.cava?.fingerprint,
18
+ payload?.action?.action_envelope?.cava?.fingerprint,
19
+ payload?.action?.proof_bundle?.action_envelope?.cava?.fingerprint,
20
+ payload?.action_envelope?.cava?.fingerprint, payload?.proof_bundle?.action_envelope?.cava?.fingerprint]
21
+ .find(value => typeof value === 'string' && value.trim()) || null;
22
+ }
23
+
24
+ export function matchesAction(payload, context, { actionId = null, fingerprint = null } = {}) {
25
+ const action = payload?.action || payload;
26
+ if (!isObject(action) || !safeId(action.action_id)) return false;
27
+ if (actionId && action.action_id !== actionId) return false;
28
+ if (payload.action_id && payload.action_id !== action.action_id) return false;
29
+ if (action.tool_input_digest && action.tool_input_digest !== context.tool_input_digest) return false;
30
+ if (action.agent_id && action.agent_id !== context.agent_id) return false;
31
+ if (action.runtime_session_id && action.runtime_session_id !== context.runtime_session_id) return false;
32
+ for (const envelope of [action.action_envelope, payload.contracts?.action_envelope]) {
33
+ if (envelope?.runtime_session_id !== undefined && envelope.runtime_session_id !== context.runtime_session_id) return false;
34
+ }
35
+ if (fingerprint) {
36
+ const receipts = approvalReceipts(payload).filter(receipt => ['allow', 'approved', 'approve'].includes(receipt.decision || receipt.status));
37
+ const fingerprints = receipts.flatMap(receipt => {
38
+ const scope = receipt.approval_scope || {};
39
+ if (scope.reusable === true || (receipt.action_id || scope.action_id) !== action.action_id) return [];
40
+ return [receipt.canonical_fingerprint || scope.canonical_fingerprint].filter(Boolean);
41
+ });
42
+ if (fingerprints.length ? !fingerprints.includes(fingerprint) : cavaFingerprint(payload) !== fingerprint) return false;
43
+ }
44
+ return true;
45
+ }
46
+
47
+ function approvalTime(value) {
48
+ return typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.test(value)
49
+ ? Date.parse(value) : NaN;
50
+ }
51
+
52
+ function confirmedRedemption({ action, approval }) {
53
+ if (approval?.state !== 'approved' || approval.reused !== true || action.approval_decision !== 'allow'
54
+ || typeof action.approved_by !== 'string' || !action.approved_by.trim()) return false;
55
+ const approvedAt = approvalTime(action.approved_at);
56
+ const redeemedAt = approvalTime(action.approval_redeemed_at);
57
+ const expiresAt = approvalTime(action.approval_expires_at);
58
+ const now = Date.now();
59
+ // A GET-shaped approval is not a redeemed grant. These are consistency checks,
60
+ // not independent proof of the server's atomic update or exactly-once effects.
61
+ if (![approvedAt, redeemedAt, expiresAt].every(Number.isFinite)
62
+ || approvedAt > redeemedAt || redeemedAt > now || expiresAt <= now) return false;
63
+ if (approval.decided_by !== undefined && approval.decided_by !== action.approved_by) return false;
64
+ if (approval.decided_at !== undefined && approvalTime(approval.decided_at) !== approvedAt) return false;
65
+ if (approval.expires_at !== undefined && approvalTime(approval.expires_at) !== expiresAt) return false;
66
+ return true;
67
+ }
68
+
69
+ export function actionAdmission(payload, requestedDecision, context, expected = {}) {
70
+ if (!isObject(payload) || payload.error || !isObject(payload.action) || !safeId(payload.action_id)
71
+ || payload.action.action_id !== payload.action_id || !matchesAction(payload, context)) return closed('action_creation_not_authorized');
72
+ const actionId = payload.action_id;
73
+ const action = payload.action;
74
+ const decision = payload.decision?.decision;
75
+ const base = { actionId, response: payload };
76
+ if (!DECISIONS.has(decision) || !['running', 'pending_approval'].includes(action.status)
77
+ || (payload.status !== undefined && payload.status !== action.status)
78
+ || action.timestamp_end != null || ['denied', 'expired'].includes(payload.approval?.state)
79
+ || requestedDecision === 'block' || decision === 'block') return closed('action_creation_not_authorized', base);
80
+ if (action.status === 'pending_approval') return { ...base, authorized: false, decision: 'require_approval', reason: 'awaiting_approval' };
81
+ if (REVIEW_DECISIONS.has(decision) || REVIEW_DECISIONS.has(requestedDecision)) {
82
+ if (!confirmedRedemption(payload)
83
+ || !matchesAction(payload, context, expected)) return closed('approval_not_confirmed', base);
84
+ return { ...base, authorized: true, decision: 'approved_by_reviewer' };
85
+ }
86
+ return { ...base, authorized: true, decision: decision === 'warn' || requestedDecision === 'warn' ? 'warn' : 'allow' };
87
+ }
88
+
89
+ function installCheck(payload, context) {
90
+ if (!context.health_check || payload?.approval?.state !== 'not_requested') return null;
91
+ if (payload.error || !safeId(payload.action_id) || payload.action?.action_id !== payload.action_id
92
+ || payload.action?.status !== 'cancelled' || (payload.status !== undefined && payload.status !== 'cancelled')
93
+ || !REVIEW_DECISIONS.has(payload.decision?.decision)) return closed('invalid_install_check');
94
+ return { authorized: false, decision: payload.decision.decision, installCheck: true, reason: 'approval_not_requested', response: payload };
95
+ }
96
+
97
+ export async function admitAction(context, { api, config, sleep = delay, now = () => performance.now(), beforeRelease = async () => true } = {}) {
98
+ const guard = await api.request('POST', '/api/guard', context);
99
+ if (!guard.ok) {
100
+ const failOpen = config.guardFailureMode === 'allow' && ![401, 403].includes(guard.status)
101
+ && !['signing_unavailable', 'invalid_response', 'invalid_request'].includes(guard.error);
102
+ return { ...closed('guard_unavailable'), decision: failOpen ? 'allow' : 'block', degraded: true };
103
+ }
104
+ const requestedDecision = guard.body?.decision;
105
+ if (!DECISIONS.has(requestedDecision)) return closed('unsupported_guard_decision');
106
+ if (requestedDecision === 'block') {
107
+ // Observation still persists the would-block result, but never calls it authority.
108
+ if (config.mode === 'observe') await api.request('POST', '/api/actions', { ...context, status: 'blocked' });
109
+ return { ...closed('policy_block'), observeOnly: config.mode === 'observe', response: guard.body };
110
+ }
111
+ const created = await api.request('POST', '/api/actions', {
112
+ ...context, status: REVIEW_DECISIONS.has(requestedDecision) ? 'pending_approval' : 'running',
113
+ });
114
+ if (!created.ok) return closed('admission_unconfirmed');
115
+ const diagnostic = installCheck(created.body, context);
116
+ if (diagnostic) return diagnostic;
117
+ let result = actionAdmission(created.body, requestedDecision, context);
118
+ if (result.authorized) return await beforeRelease(result.response) ? result : closed('action_evidence_changed');
119
+ if (result.decision !== 'require_approval') return result;
120
+ if (config.mode === 'observe') return { ...result, observeOnly: true };
121
+
122
+ const expected = { actionId: result.actionId, fingerprint: cavaFingerprint(created.body) };
123
+ const waitMs = Math.max(0, Math.min(config.approvalWaitMs ?? 30000, 600000));
124
+ const deadline = now() + waitMs;
125
+ while (now() < deadline) {
126
+ await sleep(Math.min(3000, Math.max(0, deadline - now())));
127
+ const polled = await api.request('GET', `/api/actions/${encodeURIComponent(expected.actionId)}`, undefined, {
128
+ timeoutMs: Math.max(1, Math.min(2500, deadline - now())),
129
+ });
130
+ if (!polled.ok) {
131
+ if ([401, 403].includes(polled.status)) return closed('approval_access_rejected', { actionId: expected.actionId });
132
+ continue;
133
+ }
134
+ const action = polled.body?.action || polled.body;
135
+ if (!matchesAction(polled.body, context, expected)) return closed('approval_binding_mismatch', { actionId: expected.actionId });
136
+ if (action.status === 'pending_approval') continue;
137
+ if (action.status !== 'running') return closed('approval_closed', { actionId: expected.actionId });
138
+ if (action.approval_redeemed_at != null || action.timestamp_end != null) return closed('execution_outcome_unknown', { actionId: expected.actionId });
139
+ if (!(action.approved_by || action.approved_at) || polled.body.approval?.state === 'denied') {
140
+ return closed('approval_not_confirmed', { actionId: expected.actionId });
141
+ }
142
+ // GET observes a grant. Only this fresh POST may redeem it. Never retry a lost reply.
143
+ const current = await api.request('POST', '/api/actions', { ...context, status: 'running' });
144
+ if (!current.ok) return closed('admission_unconfirmed', { actionId: expected.actionId });
145
+ result = actionAdmission(current.body, 'allow', context, expected);
146
+ if (result.authorized && !await beforeRelease(result.response)) return closed('action_evidence_changed', { actionId: result.actionId });
147
+ return result;
148
+ }
149
+ return result;
150
+ }
@@ -0,0 +1,56 @@
1
+ import { constants, closeSync, fstatSync, openSync, readFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ function readDotenv(installDir, filename = '.env') {
5
+ let fd;
6
+ try {
7
+ fd = openSync(path.join(installDir, filename), constants.O_RDONLY | (constants.O_NOFOLLOW || 0) | constants.O_NONBLOCK);
8
+ const stat = fstatSync(fd);
9
+ if (!stat.isFile() || stat.size > 65536) return {};
10
+ const values = {};
11
+ for (const line of readFileSync(fd, 'utf8').split(/\r?\n/)) {
12
+ const match = line.match(/^\s*(?:export\s+)?((?:OSUITE|DASHCLAW)_[A-Z0-9_]+)\s*=\s*(.*?)\s*$/);
13
+ if (!match) continue;
14
+ let value = match[2];
15
+ if (/^(['"]).*\1$/.test(value)) value = value.slice(1, -1);
16
+ else value = value.replace(/\s+#.*$/, '');
17
+ values[match[1]] = value;
18
+ }
19
+ return values;
20
+ } catch { return {}; }
21
+ finally { if (fd !== undefined) closeSync(fd); }
22
+ }
23
+
24
+ export function loadRuntimeConfig({ installDir, env = process.env, host = 'claude', runtimeId } = {}) {
25
+ const plugin = runtimeId === 'codex_plugin';
26
+ const hardened = plugin || host === 'cursor';
27
+ const source = { ...(installDir ? readDotenv(installDir) : {}), ...(plugin && installDir ? readDotenv(installDir, '.env.osuite') : {}), ...env };
28
+ const get = (name, fallback = '') => source[`OSUITE_${name}`] ?? source[`DASHCLAW_${name}`] ?? fallback;
29
+ const number = (name, fallback, min, max) => {
30
+ const value = Number(get(name, fallback));
31
+ return Number.isFinite(value) ? Math.min(max, Math.max(min, value)) : fallback;
32
+ };
33
+ const requestedMode = get('HOOK_MODE', host === 'cursor' ? 'observe' : 'enforce');
34
+ const mode = ['observe', 'enforce', 'strict'].includes(requestedMode) ? requestedMode : 'strict';
35
+ return {
36
+ host,
37
+ runtimeId: get('RUNTIME_ADAPTER_ID', runtimeId || (host === 'cursor' ? 'cursor_hooks' : host === 'codex' ? 'codex_hooks' : 'claude_code_hooks')),
38
+ agentId: get('AGENT_ID', plugin ? 'codex-plugin-runtime' : host === 'cursor' ? 'cursor' : host === 'codex' ? 'codex' : 'claude-code'),
39
+ orgId: get('ORG_ID'), provider: get('RUNTIME_PROVIDER') || null,
40
+ baseUrl: get('BASE_URL').replace(/\/+$/, ''), apiKey: get('API_KEY'),
41
+ privateKeyBase64: get('PRIVATE_KEY_BASE64').trim(),
42
+ signatureMode: get('SIGNATURE_MODE', hardened ? 'required' : 'workspace_key_optional'),
43
+ mode, guardFailureMode: mode === 'strict' ? 'block' : (get('GUARD_FAILURE_MODE', hardened ? 'block' : 'allow') === 'allow' ? 'allow' : 'block'),
44
+ requireAssumptionCapture: get('REQUIRE_ASSUMPTION_CAPTURE') === 'true',
45
+ approvalTimeoutSeconds: number('APPROVAL_TIMEOUT_SECONDS', 300, 1, 3600),
46
+ approvalWaitMs: number('APPROVAL_WAIT_SECONDS', 30, 0, 40) * 1000,
47
+ stopWaitMs: number('STOP_WAIT_SECONDS', 0, 0, 40) * 1000,
48
+ installCheck: get('HOOK_CHECK') === '1',
49
+ installChannel: get('INSTALL_CHANNEL', plugin ? 'plugin' : 'project_settings'), settingsScope: get('SETTINGS_SCOPE', plugin ? 'managed' : 'project'),
50
+ trustedProjectRequired: get('TRUSTED_PROJECT_REQUIRED', hardened ? 'true' : 'false') === 'true',
51
+ runtimeSessionId: get('RUNTIME_SESSION_ID'), runtimePermissionMode: get('RUNTIME_PERMISSION_MODE'),
52
+ stateDir: get('STATE_DIR') || undefined,
53
+ captureToolInput: get('CAPTURE_TOOL_INPUT', 'summary'),
54
+ allowInsecureHttp: get('ALLOW_INSECURE_HTTP') === '1',
55
+ };
56
+ }