osuite 2.9.9 → 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/LICENSE +21 -0
- package/README.md +98 -106
- package/activationMetrics.js +116 -0
- package/cli.js +369 -70
- package/credentials.js +234 -0
- package/osuite.js +41 -13
- package/package.json +9 -3
- package/projectHooks.js +916 -0
- package/reviewSurface.js +10 -2
- package/runtime/admission.mjs +150 -0
- package/runtime/config.mjs +56 -0
- package/runtime/context.mjs +122 -0
- package/runtime/cursor.mjs +83 -0
- package/runtime/git.mjs +46 -0
- package/runtime/hook.mjs +200 -0
- package/runtime/mcp.mjs +219 -0
- package/runtime/outcome.mjs +98 -0
- package/runtime/posture.mjs +103 -0
- package/runtime/protocol.mjs +96 -0
- package/runtime/shell.mjs +186 -0
- package/runtime/state.mjs +83 -0
- package/tryContract.js +47 -0
- package/tryFlow.js +90 -0
package/projectHooks.js
ADDED
|
@@ -0,0 +1,916 @@
|
|
|
1
|
+
// Project hook install and verification for `osuite connect`, `osuite init` and `osuite doctor`.
|
|
2
|
+
// Settings files are merged, never replaced: most projects already have them.
|
|
3
|
+
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import crypto from 'node:crypto';
|
|
7
|
+
import { spawn } from 'node:child_process';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
9
|
+
|
|
10
|
+
const HOOK_SCRIPT_RE = /osuite_(?:pretool|posttool|stop|session)\.(?:py|mjs)/;
|
|
11
|
+
|
|
12
|
+
export const RUNTIME_HOOKS = {
|
|
13
|
+
claude: {
|
|
14
|
+
label: 'Claude Code',
|
|
15
|
+
dir: '.claude',
|
|
16
|
+
settings: ['.claude/settings.json', '.claude/settings.local.json'],
|
|
17
|
+
},
|
|
18
|
+
codex: {
|
|
19
|
+
label: 'Codex',
|
|
20
|
+
dir: '.codex',
|
|
21
|
+
settings: ['.codex/hooks.json'],
|
|
22
|
+
config: '.codex/config.toml',
|
|
23
|
+
},
|
|
24
|
+
cursor: {
|
|
25
|
+
label: 'Cursor', dir: '.cursor', settings: ['.cursor/hooks.json'],
|
|
26
|
+
preEvent: 'preToolUse', postEvent: 'postToolUse', flatHooks: true,
|
|
27
|
+
},
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
const MERGED_FILES = {
|
|
31
|
+
'.claude/settings.json': 'json',
|
|
32
|
+
'.claude/settings.local.json': 'json',
|
|
33
|
+
'.codex/hooks.json': 'json',
|
|
34
|
+
'.codex/config.toml': 'toml',
|
|
35
|
+
'.mcp.json': 'mcp',
|
|
36
|
+
'.cursor/hooks.json': 'cursor-hooks',
|
|
37
|
+
'.cursor/mcp.json': 'mcp',
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
export const DOCTOR_COMMAND = 'echo "OSuite doctor hook check"';
|
|
41
|
+
|
|
42
|
+
function isPlainObject(value) {
|
|
43
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function hookScriptName(command) {
|
|
47
|
+
const match = String(command || '').match(HOOK_SCRIPT_RE);
|
|
48
|
+
return match ? match[0] : '';
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// An OSuite hook already in the file counts as present even when its path differs,
|
|
52
|
+
// so a re-run never registers a second copy that would govern each call twice.
|
|
53
|
+
function sameHook(existing, wanted) {
|
|
54
|
+
const existingScript = hookScriptName(existing?.command);
|
|
55
|
+
const wantedScript = hookScriptName(wanted?.command);
|
|
56
|
+
if (existingScript && wantedScript) return existingScript.replace(/\.(py|mjs)$/, '') === wantedScript.replace(/\.(py|mjs)$/, '');
|
|
57
|
+
return String(existing?.command || '').trim() === String(wanted?.command || '').trim();
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function countHooks(hooks) {
|
|
61
|
+
if (!isPlainObject(hooks)) return 0;
|
|
62
|
+
return Object.values(hooks).reduce((total, groups) => total + (Array.isArray(groups)
|
|
63
|
+
? groups.reduce((sum, group) => sum + (Array.isArray(group?.hooks) ? group.hooks.length : 0), 0)
|
|
64
|
+
: 0), 0);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function templateHooks(template) {
|
|
68
|
+
const hooks = isPlainObject(template?.hooks) ? template.hooks : {};
|
|
69
|
+
return Object.entries(hooks).flatMap(([event, groups]) => (Array.isArray(groups) ? groups : [])
|
|
70
|
+
.flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : [])
|
|
71
|
+
.map((hook) => ({ event, matcher: group.matcher, command: hook.command }))));
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function disabledHookSettings(settings) {
|
|
75
|
+
return settings?.disableAllHooks === true
|
|
76
|
+
? ['disableAllHooks = true keeps hooks disabled; intentional disablement was preserved']
|
|
77
|
+
: [];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Add the OSuite PreToolUse/PostToolUse entries to a JSON settings file.
|
|
82
|
+
* The user's own hooks and every other key stay as they are.
|
|
83
|
+
*/
|
|
84
|
+
export function mergeHookSettings(existingText, templateText) {
|
|
85
|
+
const template = JSON.parse(templateText);
|
|
86
|
+
if (existingText === null || existingText === undefined) {
|
|
87
|
+
return { status: 'created', body: templateText, added: templateHooks(template), keptHooks: 0, keptKeys: [], conflicts: disabledHookSettings(template) };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
let settings = {};
|
|
91
|
+
if (existingText.trim()) {
|
|
92
|
+
try {
|
|
93
|
+
settings = JSON.parse(existingText);
|
|
94
|
+
} catch (error) {
|
|
95
|
+
return { status: 'error', error: `not valid JSON (${error.message})` };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
if (!isPlainObject(settings)) return { status: 'error', error: 'expected a JSON object at the top level' };
|
|
99
|
+
|
|
100
|
+
let hooks = settings.hooks;
|
|
101
|
+
if (hooks === undefined || hooks === null || (Array.isArray(hooks) && hooks.length === 0)) hooks = {};
|
|
102
|
+
if (!isPlainObject(hooks)) return { status: 'error', error: '"hooks" must be an object keyed by event name' };
|
|
103
|
+
|
|
104
|
+
const wanted = isPlainObject(template.hooks) ? template.hooks : {};
|
|
105
|
+
const merged = { ...hooks };
|
|
106
|
+
const added = [];
|
|
107
|
+
const migrated = [];
|
|
108
|
+
const migrationConflicts = [];
|
|
109
|
+
for (const [event, groups] of Object.entries(wanted)) {
|
|
110
|
+
const current = merged[event] === undefined ? [] : merged[event];
|
|
111
|
+
if (!Array.isArray(current)) return { status: 'error', error: `"hooks.${event}" must be a list` };
|
|
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 : []));
|
|
127
|
+
for (const group of Array.isArray(groups) ? groups : []) {
|
|
128
|
+
const missing = (group.hooks || []).filter((hook) => !present.some((existing) => sameHook(existing, hook)));
|
|
129
|
+
if (!missing.length) continue;
|
|
130
|
+
next.push({ ...group, hooks: missing });
|
|
131
|
+
missing.forEach((hook) => added.push({ event, matcher: group.matcher, command: hook.command }));
|
|
132
|
+
}
|
|
133
|
+
if (next.length !== current.length || migrated.some(item => item.event === event)) merged[event] = next;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const result = {
|
|
137
|
+
added, migrated,
|
|
138
|
+
keptHooks: countHooks(hooks),
|
|
139
|
+
keptKeys: Object.keys(settings).filter((key) => key !== 'hooks'),
|
|
140
|
+
conflicts: [...disabledHookSettings(settings), ...migrationConflicts],
|
|
141
|
+
};
|
|
142
|
+
if (!added.length && !migrated.length) return { ...result, status: 'unchanged', body: existingText };
|
|
143
|
+
return { ...result, status: 'merged', body: `${JSON.stringify({ ...settings, hooks: merged }, null, 2)}\n` };
|
|
144
|
+
}
|
|
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
|
+
|
|
264
|
+
// --- TOML ------------------------------------------------------------------
|
|
265
|
+
// Line-based on purpose: the CLI has no dependencies, and the partial only sets
|
|
266
|
+
// plain keys. Lines inside multi-line strings and arrays are skipped.
|
|
267
|
+
|
|
268
|
+
function normalizeTomlKey(raw) {
|
|
269
|
+
return String(raw || '')
|
|
270
|
+
.split('.')
|
|
271
|
+
.map((part) => part.trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1'))
|
|
272
|
+
.join('.');
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function stripTomlValue(raw) {
|
|
276
|
+
const value = String(raw || '').trim();
|
|
277
|
+
const quote = value[0];
|
|
278
|
+
if (quote === '"' || quote === "'") {
|
|
279
|
+
const end = value.indexOf(quote, 1);
|
|
280
|
+
return end > 0 ? value.slice(0, end + 1) : value;
|
|
281
|
+
}
|
|
282
|
+
const hash = value.indexOf('#');
|
|
283
|
+
return (hash >= 0 ? value.slice(0, hash) : value).trim();
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function withoutStrings(text) {
|
|
287
|
+
return String(text || '').replace(/"(?:[^"\\]|\\.)*"|'[^']*'/g, '');
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
function bracketDelta(text) {
|
|
291
|
+
const bare = withoutStrings(text).replace(/#.*$/, '');
|
|
292
|
+
return (bare.match(/[[{]/g) || []).length - (bare.match(/[\]}]/g) || []).length;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function parseInlineTable(raw) {
|
|
296
|
+
const inner = withoutStrings(raw).includes('{') ? String(raw).trim().replace(/^\{|\}\s*(#.*)?$/g, '') : '';
|
|
297
|
+
return inner.split(',').map((part) => part.split('=')).filter((pair) => pair.length >= 2)
|
|
298
|
+
.map(([key, ...rest]) => [normalizeTomlKey(key), stripTomlValue(rest.join('='))]);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function scanToml(text) {
|
|
302
|
+
const lines = String(text || '').split(/\r?\n/);
|
|
303
|
+
const values = new Map();
|
|
304
|
+
const tables = new Map();
|
|
305
|
+
const inlineTables = new Set();
|
|
306
|
+
const root = { lastIndex: -1 };
|
|
307
|
+
let current = root;
|
|
308
|
+
let tableName = '';
|
|
309
|
+
let firstHeaderIndex = -1;
|
|
310
|
+
let multiline = null;
|
|
311
|
+
let depth = 0;
|
|
312
|
+
|
|
313
|
+
lines.forEach((line, index) => {
|
|
314
|
+
if (multiline) {
|
|
315
|
+
if (line.includes(multiline)) multiline = null;
|
|
316
|
+
current.lastIndex = index;
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
if (depth > 0) {
|
|
320
|
+
depth += bracketDelta(line);
|
|
321
|
+
current.lastIndex = index;
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
const trimmed = line.trim();
|
|
325
|
+
if (!trimmed || trimmed.startsWith('#')) return;
|
|
326
|
+
|
|
327
|
+
const header = trimmed.match(/^\[(\[)?\s*([^\]]+?)\s*\]\]?\s*(?:#.*)?$/);
|
|
328
|
+
if (header) {
|
|
329
|
+
if (firstHeaderIndex < 0) firstHeaderIndex = index;
|
|
330
|
+
tableName = normalizeTomlKey(header[2]);
|
|
331
|
+
const isArrayTable = Boolean(header[1]);
|
|
332
|
+
current = { headerIndex: index, lastIndex: index, arrayTable: isArrayTable };
|
|
333
|
+
if (!isArrayTable && !tables.has(tableName)) tables.set(tableName, current);
|
|
334
|
+
return;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const pair = trimmed.match(/^([^=]+?)\s*=\s*(.*)$/);
|
|
338
|
+
if (!pair) return;
|
|
339
|
+
current.lastIndex = index;
|
|
340
|
+
const value = pair[2];
|
|
341
|
+
if (!current.arrayTable) {
|
|
342
|
+
const key = tableName ? `${tableName}.${normalizeTomlKey(pair[1])}` : normalizeTomlKey(pair[1]);
|
|
343
|
+
values.set(key, stripTomlValue(value));
|
|
344
|
+
if (value.trim().startsWith('{')) {
|
|
345
|
+
inlineTables.add(key);
|
|
346
|
+
parseInlineTable(value).forEach(([innerKey, innerValue]) => values.set(`${key}.${innerKey}`, innerValue));
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const tripleDouble = (value.match(/"""/g) || []).length;
|
|
350
|
+
const tripleSingle = (value.match(/'''/g) || []).length;
|
|
351
|
+
if (tripleDouble % 2 === 1) multiline = '"""';
|
|
352
|
+
else if (tripleSingle % 2 === 1) multiline = "'''";
|
|
353
|
+
else depth = Math.max(0, bracketDelta(value));
|
|
354
|
+
});
|
|
355
|
+
|
|
356
|
+
return { lines, values, tables, inlineTables, root, firstHeaderIndex };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function tomlEntries(text) {
|
|
360
|
+
const entries = [];
|
|
361
|
+
let table = '';
|
|
362
|
+
String(text || '').split(/\r?\n/).forEach((line) => {
|
|
363
|
+
const trimmed = line.trim();
|
|
364
|
+
if (!trimmed || trimmed.startsWith('#')) return;
|
|
365
|
+
const header = trimmed.match(/^\[\s*([^\]]+?)\s*\]$/);
|
|
366
|
+
if (header) {
|
|
367
|
+
table = normalizeTomlKey(header[1]);
|
|
368
|
+
return;
|
|
369
|
+
}
|
|
370
|
+
const pair = trimmed.match(/^([^=]+?)\s*=\s*(.*)$/);
|
|
371
|
+
if (pair) entries.push({ table, key: normalizeTomlKey(pair[1]), value: stripTomlValue(pair[2]) });
|
|
372
|
+
});
|
|
373
|
+
return entries;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function describeTomlEntry(entry) {
|
|
377
|
+
return `${entry.table ? `[${entry.table}] ` : ''}${entry.key} = ${entry.value}`;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const HOOK_FLAGS = ['features.hooks', 'features.codex_hooks'];
|
|
381
|
+
|
|
382
|
+
/**
|
|
383
|
+
* Add the keys of the OSuite config.toml partial that the file does not set yet.
|
|
384
|
+
* Values the user already chose are kept and reported; running it again changes nothing.
|
|
385
|
+
*/
|
|
386
|
+
export function mergeTomlPartial(existingText, partialText) {
|
|
387
|
+
const entries = tomlEntries(partialText);
|
|
388
|
+
if (existingText === null || existingText === undefined) {
|
|
389
|
+
return { status: 'created', body: partialText, added: entries.map(describeTomlEntry), kept: [], conflicts: [] };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const scan = scanToml(existingText);
|
|
393
|
+
const added = [];
|
|
394
|
+
const kept = [];
|
|
395
|
+
const conflicts = [];
|
|
396
|
+
const rootLines = [];
|
|
397
|
+
const tableLines = new Map();
|
|
398
|
+
const newTables = new Map();
|
|
399
|
+
|
|
400
|
+
HOOK_FLAGS.forEach((flag) => {
|
|
401
|
+
if (scan.values.get(flag) === 'false') {
|
|
402
|
+
conflicts.push(`${flag.replace('features.', '[features] ')} = false turns Codex hooks off; set it to true`);
|
|
403
|
+
}
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
for (const entry of entries) {
|
|
407
|
+
const fullKey = entry.table ? `${entry.table}.${entry.key}` : entry.key;
|
|
408
|
+
if (HOOK_FLAGS.includes(fullKey) && conflicts.length && !scan.values.has(fullKey)) continue;
|
|
409
|
+
if (scan.values.has(fullKey)) {
|
|
410
|
+
const current = scan.values.get(fullKey);
|
|
411
|
+
if (current !== entry.value && !HOOK_FLAGS.includes(fullKey)) {
|
|
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
|
+
}
|
|
416
|
+
}
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
const line = `${entry.key} = ${entry.value}`;
|
|
420
|
+
if (!entry.table) {
|
|
421
|
+
rootLines.push(line);
|
|
422
|
+
} else if (scan.inlineTables.has(entry.table) || (scan.values.has(entry.table) && !scan.tables.has(entry.table))) {
|
|
423
|
+
kept.push({ key: `${entry.table} (inline)`, suggested: `add ${line}` });
|
|
424
|
+
continue;
|
|
425
|
+
} else if (scan.tables.has(entry.table)) {
|
|
426
|
+
if (!tableLines.has(entry.table)) tableLines.set(entry.table, []);
|
|
427
|
+
tableLines.get(entry.table).push(line);
|
|
428
|
+
} else if ([...scan.values.keys()].some((key) => key.startsWith(`${entry.table}.`))) {
|
|
429
|
+
// The table only exists through dotted keys; a [table] header would redefine it.
|
|
430
|
+
rootLines.push(`${entry.table}.${line}`);
|
|
431
|
+
} else {
|
|
432
|
+
if (!newTables.has(entry.table)) newTables.set(entry.table, []);
|
|
433
|
+
newTables.get(entry.table).push(line);
|
|
434
|
+
}
|
|
435
|
+
added.push(describeTomlEntry(entry));
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
if (!added.length) return { status: 'unchanged', body: existingText, added, kept, conflicts };
|
|
439
|
+
|
|
440
|
+
const eol = existingText.includes('\r\n') ? '\r\n' : '\n';
|
|
441
|
+
const lines = [...scan.lines];
|
|
442
|
+
const inserts = [];
|
|
443
|
+
tableLines.forEach((items, table) => {
|
|
444
|
+
inserts.push({ index: scan.tables.get(table).lastIndex + 1, lines: items });
|
|
445
|
+
});
|
|
446
|
+
if (rootLines.length) {
|
|
447
|
+
const index = scan.root.lastIndex >= 0 ? scan.root.lastIndex + 1 : (scan.firstHeaderIndex >= 0 ? 0 : lines.length);
|
|
448
|
+
const spacer = scan.firstHeaderIndex >= index && String(lines[index] || '').trim() ? [''] : [];
|
|
449
|
+
inserts.push({ index, lines: ['# Added by OSuite', ...rootLines, ...spacer] });
|
|
450
|
+
}
|
|
451
|
+
inserts.sort((a, b) => b.index - a.index).forEach(({ index, lines: items }) => lines.splice(index, 0, ...items));
|
|
452
|
+
|
|
453
|
+
let body = lines.join(eol);
|
|
454
|
+
if (newTables.size) {
|
|
455
|
+
body = body.replace(/\s*$/, '');
|
|
456
|
+
newTables.forEach((items, table) => {
|
|
457
|
+
body += `${eol}${eol}# Added by OSuite${eol}[${table}]${eol}${items.join(eol)}`;
|
|
458
|
+
});
|
|
459
|
+
}
|
|
460
|
+
if (!body.endsWith(eol)) body += eol;
|
|
461
|
+
return { status: 'merged', body, added, kept, conflicts };
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// --- Install ---------------------------------------------------------------
|
|
465
|
+
|
|
466
|
+
function isInside(root, target) {
|
|
467
|
+
const relative = path.relative(root, target);
|
|
468
|
+
return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
export function resolveProjectPath(projectRoot, relativePath) {
|
|
472
|
+
const root = path.resolve(projectRoot);
|
|
473
|
+
const absolute = path.resolve(root, String(relativePath || '').replace(/^\/+/, ''));
|
|
474
|
+
if (!isInside(root, absolute)) {
|
|
475
|
+
throw new Error(`Refusing to write outside the project root: ${relativePath}`);
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const realRoot = fs.realpathSync(root);
|
|
479
|
+
const parts = path.relative(root, absolute).split(path.sep).filter(Boolean);
|
|
480
|
+
let resolved = realRoot;
|
|
481
|
+
for (let index = 0; index < parts.length; index += 1) {
|
|
482
|
+
const next = path.join(resolved, parts[index]);
|
|
483
|
+
let stat;
|
|
484
|
+
try {
|
|
485
|
+
stat = fs.lstatSync(next);
|
|
486
|
+
} catch (error) {
|
|
487
|
+
if (error.code === 'ENOENT') return path.join(next, ...parts.slice(index + 1));
|
|
488
|
+
throw error;
|
|
489
|
+
}
|
|
490
|
+
// Check each existing parent, not just the leaf. lstat also catches dangling
|
|
491
|
+
// links, which existsSync would mistake for safe new files.
|
|
492
|
+
try {
|
|
493
|
+
resolved = fs.realpathSync(next);
|
|
494
|
+
} catch (error) {
|
|
495
|
+
if (stat.isSymbolicLink()) throw new Error(`Cannot resolve project symlink safely: ${relativePath}`);
|
|
496
|
+
throw error;
|
|
497
|
+
}
|
|
498
|
+
if (!isInside(realRoot, resolved)) {
|
|
499
|
+
throw new Error(`Refusing to write outside the project root through a symlink: ${relativePath}`);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
return resolved;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function readIfExists(absolute) {
|
|
506
|
+
return fs.existsSync(absolute) ? fs.readFileSync(absolute, 'utf8') : null;
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
function writeFile(absolute, body) {
|
|
510
|
+
fs.mkdirSync(path.dirname(absolute), { recursive: true });
|
|
511
|
+
fs.writeFileSync(absolute, String(body ?? ''));
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
/**
|
|
515
|
+
* Install one bootstrap file. Settings files are merged; OSuite's own files
|
|
516
|
+
* are created, left alone when identical, and replaced only with --force.
|
|
517
|
+
*/
|
|
518
|
+
export function installProjectFile(projectRoot, relativePath, body, { force = false } = {}) {
|
|
519
|
+
const absolute = resolveProjectPath(projectRoot, relativePath);
|
|
520
|
+
const existing = readIfExists(absolute);
|
|
521
|
+
const kind = MERGED_FILES[relativePath];
|
|
522
|
+
|
|
523
|
+
if (kind) {
|
|
524
|
+
let merge;
|
|
525
|
+
try {
|
|
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 ?? ''));
|
|
528
|
+
} catch (error) {
|
|
529
|
+
merge = { status: 'error', error: `OSuite template could not be read (${error.message})` };
|
|
530
|
+
}
|
|
531
|
+
if (merge.status === 'created' || merge.status === 'merged') writeFile(absolute, merge.body);
|
|
532
|
+
const { body: _body, ...report } = merge;
|
|
533
|
+
return { relativePath, kind, ...report };
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
if (existing === null) {
|
|
537
|
+
writeFile(absolute, body);
|
|
538
|
+
return { relativePath, status: 'created' };
|
|
539
|
+
}
|
|
540
|
+
if (existing === String(body ?? '')) return { relativePath, status: 'unchanged' };
|
|
541
|
+
if (force) {
|
|
542
|
+
writeFile(absolute, body);
|
|
543
|
+
return { relativePath, status: 'replaced' };
|
|
544
|
+
}
|
|
545
|
+
return { relativePath, status: 'kept' };
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
export function installBlockers(results = []) {
|
|
549
|
+
return results.flatMap((result) => [
|
|
550
|
+
...(result.status === 'error' ? [`${result.relativePath}: ${result.error}`] : []),
|
|
551
|
+
...(result.conflicts || []).map((conflict) => `${result.relativePath}: ${conflict}`),
|
|
552
|
+
]);
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** Lines that say exactly what an install changed, for the terminal. */
|
|
556
|
+
export function describeInstallResult(result) {
|
|
557
|
+
const lines = [];
|
|
558
|
+
const name = result.relativePath;
|
|
559
|
+
if (result.status === 'error') {
|
|
560
|
+
lines.push(`failed ${name}: ${result.error}. Nothing was changed; fix the file and run this again.`);
|
|
561
|
+
return lines;
|
|
562
|
+
}
|
|
563
|
+
if (result.kind === 'json' || result.kind === 'cursor-hooks') {
|
|
564
|
+
if (result.status === 'unchanged') lines.push(`unchanged ${name} (OSuite hooks already there)`);
|
|
565
|
+
else lines.push(`${result.status === 'created' ? 'created' : 'merged '} ${name}`);
|
|
566
|
+
if (result.status !== 'unchanged') {
|
|
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`));
|
|
569
|
+
}
|
|
570
|
+
if (result.status === 'merged') {
|
|
571
|
+
const others = result.keptKeys.length ? ` and your other settings (${result.keptKeys.join(', ')})` : '';
|
|
572
|
+
lines.push(` kept ${result.keptHooks} existing hook${result.keptHooks === 1 ? '' : 's'}${others}`);
|
|
573
|
+
}
|
|
574
|
+
(result.conflicts || []).forEach((conflict) => lines.push(` ! ${conflict}`));
|
|
575
|
+
return lines;
|
|
576
|
+
}
|
|
577
|
+
if (result.kind === 'toml') {
|
|
578
|
+
if (result.status === 'unchanged') lines.push(`unchanged ${name} (OSuite settings already there)`);
|
|
579
|
+
else lines.push(`${result.status === 'created' ? 'created' : 'merged '} ${name}`);
|
|
580
|
+
if (result.status !== 'unchanged') result.added.forEach((entry) => lines.push(` + ${entry}`));
|
|
581
|
+
result.kept.forEach((entry) => lines.push(` kept your ${entry.key} (OSuite suggests ${entry.suggested})`));
|
|
582
|
+
result.conflicts.forEach((conflict) => lines.push(` ! ${conflict}`));
|
|
583
|
+
return lines;
|
|
584
|
+
}
|
|
585
|
+
const labels = {
|
|
586
|
+
created: `created ${name}`,
|
|
587
|
+
unchanged: `unchanged ${name}`,
|
|
588
|
+
replaced: `replaced ${name}`,
|
|
589
|
+
kept: `kept ${name} (differs from this OSuite version; use --force to replace)`,
|
|
590
|
+
};
|
|
591
|
+
lines.push(labels[result.status] || `${result.status} ${name}`);
|
|
592
|
+
return lines;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// --- Verify ----------------------------------------------------------------
|
|
596
|
+
|
|
597
|
+
function readJson(absolute) {
|
|
598
|
+
return JSON.parse(fs.readFileSync(absolute, 'utf8'));
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
function eventHooks(settings, event, flat = false) {
|
|
602
|
+
const groups = Array.isArray(settings?.hooks?.[event]) ? settings.hooks[event] : [];
|
|
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;
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** OSuite hooks registered in this project, with anything that stops them from running. */
|
|
612
|
+
export function findHookInstallations(projectRoot, runtimes = Object.keys(RUNTIME_HOOKS)) {
|
|
613
|
+
return runtimes.flatMap((runtime) => {
|
|
614
|
+
const spec = RUNTIME_HOOKS[runtime];
|
|
615
|
+
if (!spec) return [];
|
|
616
|
+
const problems = [];
|
|
617
|
+
const disabledReasons = [];
|
|
618
|
+
let pretoolCount = 0;
|
|
619
|
+
let posttoolCount = 0;
|
|
620
|
+
let pretool = null;
|
|
621
|
+
let posttool = null;
|
|
622
|
+
spec.settings.forEach((settingsPath) => {
|
|
623
|
+
const absolute = path.join(projectRoot, settingsPath);
|
|
624
|
+
if (!fs.existsSync(absolute)) return;
|
|
625
|
+
let settings;
|
|
626
|
+
try {
|
|
627
|
+
settings = readJson(absolute);
|
|
628
|
+
} catch {
|
|
629
|
+
problems.push(`${settingsPath} is not valid JSON, so ${spec.label} cannot load its hooks`);
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
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
|
+
}
|
|
648
|
+
if (pre && !pretool) pretool = { settingsPath, command: pre.command };
|
|
649
|
+
if (post && !posttool) posttool = { settingsPath, command: post.command };
|
|
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');
|
|
652
|
+
|
|
653
|
+
const scriptPath = `${spec.dir}/hooks/osuite_pretool.py`;
|
|
654
|
+
const scriptPresent = fs.existsSync(path.join(projectRoot, scriptPath)) || fs.existsSync(path.join(projectRoot, scriptPath.replace(/\.py$/, '.mjs')));
|
|
655
|
+
if (!pretool && !scriptPresent && !problems.length) return [];
|
|
656
|
+
if (!pretool) {
|
|
657
|
+
problems.push(`no ${spec.preEvent || 'PreToolUse'} hook in ${spec.settings.join(' or ')} runs osuite_pretool.${runtime === 'cursor' ? 'mjs' : 'py'}`);
|
|
658
|
+
}
|
|
659
|
+
if (spec.config) {
|
|
660
|
+
const config = readIfExists(path.join(projectRoot, spec.config));
|
|
661
|
+
if (config !== null) {
|
|
662
|
+
const values = scanToml(config).values;
|
|
663
|
+
HOOK_FLAGS.forEach((flag) => {
|
|
664
|
+
if (values.get(flag) === 'false') disabledReasons.push(`${spec.config} turns hooks off (${flag} = false)`);
|
|
665
|
+
});
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
return [{ runtime, label: spec.label, installDir: spec.dir, pretool, posttool,
|
|
669
|
+
hostEnabled: disabledReasons.length === 0, disabledReasons, problems: [...problems, ...disabledReasons] }];
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
export function parseDotenv(body) {
|
|
674
|
+
const values = {};
|
|
675
|
+
String(body || '').split(/\r?\n/).forEach((line) => {
|
|
676
|
+
const trimmed = line.trim();
|
|
677
|
+
if (!trimmed || trimmed.startsWith('#') || !trimmed.includes('=')) return;
|
|
678
|
+
const [rawKey, ...rawValue] = trimmed.split('=');
|
|
679
|
+
const key = rawKey.trim();
|
|
680
|
+
let value = rawValue.join('=').trim().replace(/^['"]|['"]$/g, '');
|
|
681
|
+
if (value.includes(' #')) value = value.slice(0, value.indexOf(' #')).trim();
|
|
682
|
+
if (key) values[key] = value;
|
|
683
|
+
});
|
|
684
|
+
return values;
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/** The credentials the installed hook will use: shell values first, then its own .env. */
|
|
688
|
+
export function hookCredentials(projectRoot, installation, shellEnv = process.env) {
|
|
689
|
+
const dotenv = parseDotenv(readIfExists(path.join(projectRoot, installation.installDir, '.env')));
|
|
690
|
+
const env = { ...dotenv };
|
|
691
|
+
Object.entries(shellEnv || {}).forEach(([key, value]) => {
|
|
692
|
+
if (value !== undefined) env[key] = value;
|
|
693
|
+
});
|
|
694
|
+
return {
|
|
695
|
+
baseUrl: String(env.OSUITE_BASE_URL || env.DASHCLAW_BASE_URL || '').replace(/\/$/, ''),
|
|
696
|
+
apiKey: String(env.OSUITE_API_KEY || env.DASHCLAW_API_KEY || ''),
|
|
697
|
+
envFile: `${installation.installDir}/.env`,
|
|
698
|
+
hookMode: String(env.OSUITE_HOOK_MODE || env.DASHCLAW_HOOK_MODE || (installation.runtime === 'cursor' ? 'observe' : 'enforce')),
|
|
699
|
+
};
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
function runShell(command, { cwd, env, input, timeoutMs }) {
|
|
703
|
+
return new Promise((resolve) => {
|
|
704
|
+
let stdout = '';
|
|
705
|
+
let stderr = '';
|
|
706
|
+
let settled = false;
|
|
707
|
+
const child = spawn(command, { cwd, env, shell: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
708
|
+
const finish = (result) => {
|
|
709
|
+
if (settled) return;
|
|
710
|
+
settled = true;
|
|
711
|
+
clearTimeout(timer);
|
|
712
|
+
resolve({ stdout, stderr, ...result });
|
|
713
|
+
};
|
|
714
|
+
const timer = setTimeout(() => {
|
|
715
|
+
child.kill('SIGKILL');
|
|
716
|
+
finish({ code: null, timedOut: true });
|
|
717
|
+
}, timeoutMs);
|
|
718
|
+
child.stdout.on('data', (chunk) => { stdout += chunk; });
|
|
719
|
+
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
720
|
+
child.on('error', (error) => finish({ code: null, error }));
|
|
721
|
+
child.on('close', (code) => finish({ code }));
|
|
722
|
+
child.stdin.on('error', () => {});
|
|
723
|
+
child.stdin.end(input);
|
|
724
|
+
});
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
function hookMessages(stdout) {
|
|
728
|
+
return String(stdout || '').split(/\r?\n/).flatMap((line) => {
|
|
729
|
+
try {
|
|
730
|
+
const parsed = JSON.parse(line);
|
|
731
|
+
return [...new Set(['systemMessage', 'user_message', 'agent_message', 'additional_context']
|
|
732
|
+
.map(field => parsed?.[field]).filter(value => typeof value === 'string' && value))];
|
|
733
|
+
} catch {
|
|
734
|
+
return [];
|
|
735
|
+
}
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
|
|
739
|
+
function hookWarnings(stdout, stderr) {
|
|
740
|
+
return [...new Set([
|
|
741
|
+
...hookMessages(stdout),
|
|
742
|
+
...String(stderr || '').split(/\r?\n/).map((line) => line.trim())
|
|
743
|
+
.filter((line) => /\bWarning:|Not governed|\[observe\]|Guard unavailable/i.test(line)),
|
|
744
|
+
])];
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
function lastLine(text) {
|
|
748
|
+
return String(text || '').trim().split(/\r?\n/).filter(Boolean).pop() || '';
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
async function fetchSessionEvents(fetchImpl, { baseUrl, apiKey, sessionId }) {
|
|
752
|
+
try {
|
|
753
|
+
const response = await fetchImpl(`${baseUrl}/api/runtime-sessions/${encodeURIComponent(sessionId)}/events?limit=50`, {
|
|
754
|
+
headers: { 'x-api-key': apiKey },
|
|
755
|
+
});
|
|
756
|
+
const payload = await response.json().catch(() => ({}));
|
|
757
|
+
return { status: response.status, items: Array.isArray(payload?.items) ? payload.items : [] };
|
|
758
|
+
} catch (error) {
|
|
759
|
+
return { status: 0, items: [], error: error.message };
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/**
|
|
764
|
+
* Directly probe the registered hook with an inert shell call. Configuration,
|
|
765
|
+
* telemetry, and policy outcomes are separate checks; this is not a host launch.
|
|
766
|
+
*/
|
|
767
|
+
export async function runHookCheck({
|
|
768
|
+
projectRoot,
|
|
769
|
+
installation,
|
|
770
|
+
shellEnv = process.env,
|
|
771
|
+
fetchImpl = globalThis.fetch,
|
|
772
|
+
timeoutMs = 30000,
|
|
773
|
+
} = {}) {
|
|
774
|
+
const steps = [];
|
|
775
|
+
const warnings = [];
|
|
776
|
+
const state = { configured: false, hostEnabled: false, connected: false, telemetry: false, governed: false };
|
|
777
|
+
let sessionId;
|
|
778
|
+
const result = (ok) => ({ ok, ...state, steps, runtime: installation?.runtime, sessionId, warnings });
|
|
779
|
+
const fail = (label, detail) => {
|
|
780
|
+
steps.push({ label, ok: false, detail });
|
|
781
|
+
return result(false);
|
|
782
|
+
};
|
|
783
|
+
|
|
784
|
+
if (!installation?.pretool) return fail('Hook installed', installation?.problems?.join('; ') || 'no OSuite hook found');
|
|
785
|
+
const disabledReasons = installation.disabledReasons || [];
|
|
786
|
+
const problems = (installation.problems || []).filter((problem) => !disabledReasons.includes(problem));
|
|
787
|
+
if (problems.length) return fail('Hook installed', problems.join('; '));
|
|
788
|
+
state.configured = true;
|
|
789
|
+
steps.push({ label: 'Hook installed', ok: true, detail: `${installation.pretool.settingsPath} runs ${installation.pretool.command}` });
|
|
790
|
+
if (installation.hostEnabled === false || disabledReasons.length) {
|
|
791
|
+
return fail('Host hooks enabled', disabledReasons.join('; ') || 'hooks are disabled in project settings');
|
|
792
|
+
}
|
|
793
|
+
state.hostEnabled = true;
|
|
794
|
+
steps.push({ label: 'Host hooks enabled', ok: true, detail: 'project settings permit hooks; actual host invocation is not verified by this direct probe' });
|
|
795
|
+
|
|
796
|
+
const credentials = hookCredentials(projectRoot, installation, shellEnv);
|
|
797
|
+
if (!credentials.baseUrl || !credentials.apiKey) {
|
|
798
|
+
return fail('Hook credentials', `OSUITE_BASE_URL and OSUITE_API_KEY are not set in ${credentials.envFile} or the shell; governance cannot be verified`);
|
|
799
|
+
}
|
|
800
|
+
steps.push({ label: 'Hook credentials', ok: true, detail: `base URL and API key configured for ${credentials.baseUrl}` });
|
|
801
|
+
|
|
802
|
+
const id = crypto.randomBytes(4).toString('hex');
|
|
803
|
+
sessionId = `osuite-doctor-${id}`;
|
|
804
|
+
const toolUseId = `osuite_doctor_${id}`;
|
|
805
|
+
const cursor = installation.runtime === 'cursor';
|
|
806
|
+
const sample = {
|
|
807
|
+
...(cursor ? { conversation_id: sessionId, generation_id: `osuite-doctor-generation-${id}` } : { session_id: sessionId }),
|
|
808
|
+
cwd: projectRoot,
|
|
809
|
+
hook_event_name: cursor ? 'preToolUse' : 'PreToolUse',
|
|
810
|
+
tool_name: cursor ? 'Shell' : 'Bash',
|
|
811
|
+
tool_input: { command: DOCTOR_COMMAND, description: 'OSuite doctor hook check' },
|
|
812
|
+
tool_use_id: toolUseId,
|
|
813
|
+
};
|
|
814
|
+
// OSUITE_HOOK_CHECK tells the hook and OSuite this is a probe: a call that
|
|
815
|
+
// would need approval is reported, not sent to reviewers.
|
|
816
|
+
const env = { ...shellEnv, OSUITE_APPROVAL_WAIT_SECONDS: '3', OSUITE_HOOK_CHECK: '1' };
|
|
817
|
+
const run = await runShell(installation.pretool.command, {
|
|
818
|
+
cwd: projectRoot, env, input: JSON.stringify(sample), timeoutMs,
|
|
819
|
+
});
|
|
820
|
+
const messages = hookMessages(run.stdout);
|
|
821
|
+
warnings.push(...hookWarnings(run.stdout, run.stderr));
|
|
822
|
+
const said = messages[0] || lastLine(run.stderr);
|
|
823
|
+
|
|
824
|
+
if (run.timedOut) return fail('Hook test', `the hook did not finish within ${Math.round(timeoutMs / 1000)}s`);
|
|
825
|
+
if (run.code === 127 && /^python3?\b/.test(installation.pretool.command)) {
|
|
826
|
+
return fail('Hook test', 'python3 was not found. The hook runs with Python 3.8 or newer: install it (macOS: xcode-select --install), then run osuite doctor');
|
|
827
|
+
}
|
|
828
|
+
if (run.error || (run.code !== 0 && run.code !== 2)) {
|
|
829
|
+
return fail('Hook test', `the hook command failed (${run.error ? run.error.message : `exit ${run.code}`})${said ? `: ${said}` : ''}`);
|
|
830
|
+
}
|
|
831
|
+
steps.push({
|
|
832
|
+
ok: true,
|
|
833
|
+
label: 'Hook test',
|
|
834
|
+
detail: `sample ${sample.tool_name} call (${DOCTOR_COMMAND}) ${run.code === 0 ? 'allowed' : 'stopped'} by the hook${run.code === 2 && said ? `: ${said}` : ''}`,
|
|
835
|
+
});
|
|
836
|
+
|
|
837
|
+
let lookup = await fetchSessionEvents(fetchImpl, { ...credentials, sessionId });
|
|
838
|
+
if (!lookup.items.some((event) => event?.tool_use_id === toolUseId) && lookup.status !== 401 && lookup.status !== 403) {
|
|
839
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
840
|
+
lookup = await fetchSessionEvents(fetchImpl, { ...credentials, sessionId });
|
|
841
|
+
}
|
|
842
|
+
const seen = lookup.items.filter((event) => event?.tool_use_id === toolUseId && event?.runtime_session_id === sessionId);
|
|
843
|
+
|
|
844
|
+
if (installation.posttool && run.code === 0) {
|
|
845
|
+
// Closes the sample action in the ledger; not part of the verdict.
|
|
846
|
+
await runShell(installation.posttool.command, {
|
|
847
|
+
cwd: projectRoot,
|
|
848
|
+
env,
|
|
849
|
+
timeoutMs,
|
|
850
|
+
input: JSON.stringify({
|
|
851
|
+
...sample,
|
|
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 } }),
|
|
855
|
+
}),
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
state.connected = lookup.status >= 200 && lookup.status < 300;
|
|
860
|
+
if (state.connected) steps.push({ ok: true, label: 'Studio connection', detail: `runtime event endpoint answered HTTP ${lookup.status}` });
|
|
861
|
+
if (!state.connected || !seen.length) {
|
|
862
|
+
const reason = lookup.status === 401 || lookup.status === 403
|
|
863
|
+
? `OSuite rejected the API key in ${credentials.envFile} (HTTP ${lookup.status})`
|
|
864
|
+
: said || (lookup.error ? `could not reach ${credentials.baseUrl} (${lookup.error})` : `no runtime event for session ${sessionId}`);
|
|
865
|
+
return fail(state.connected ? 'Studio event' : 'Studio connection', `the sample call did not reach OSuite: ${reason}`);
|
|
866
|
+
}
|
|
867
|
+
state.telemetry = true;
|
|
868
|
+
steps.push({
|
|
869
|
+
ok: true,
|
|
870
|
+
label: 'Studio event',
|
|
871
|
+
detail: `${[...new Set(seen.map((event) => event.event_type))].join(', ')} reached OSuite (session ${sessionId})`,
|
|
872
|
+
});
|
|
873
|
+
|
|
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) => (
|
|
878
|
+
event.payload?.hook_mode === 'observe' || event.payload?.observe_only === true
|
|
879
|
+
|| String(event.payload?.decision || '').startsWith('observe_')
|
|
880
|
+
));
|
|
881
|
+
if (observing) return fail('Governance', 'Not governed: observation-only mode records telemetry but does not enforce policy; the mode was not changed');
|
|
882
|
+
const unavailable = seen.some((event) => ['guard_unavailable', 'guard_unavailable_blocked'].includes(event.payload?.decision));
|
|
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`);
|
|
884
|
+
const ungoverned = warnings.find((warning) => /Not governed/i.test(warning));
|
|
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
|
+
}
|
|
889
|
+
|
|
890
|
+
const outcome = seen.find((event) => {
|
|
891
|
+
const decision = event.payload?.decision;
|
|
892
|
+
if (run.code === 0) {
|
|
893
|
+
return event.event_type === 'tool_allowed' && typeof event.action_id === 'string' && event.action_id.trim()
|
|
894
|
+
&& ['allow', 'warn', 'approved_by_reviewer'].includes(decision);
|
|
895
|
+
}
|
|
896
|
+
if (event.event_type === 'install_check_policy_result') {
|
|
897
|
+
return run.code === 2 && event.payload?.install_check === true
|
|
898
|
+
&& event.payload?.approval_state === 'not_requested'
|
|
899
|
+
&& ['require_approval', 'require_dual_approval'].includes(decision);
|
|
900
|
+
}
|
|
901
|
+
if (event.event_type === 'tool_blocked' && decision === 'block') {
|
|
902
|
+
if (nodeHook) return event.payload?.reason === 'policy_block';
|
|
903
|
+
return event.payload?.reason !== 'action_creation_not_authorized'
|
|
904
|
+
&& !String(event.payload?.reason || '').startsWith('Unsupported guard decision:');
|
|
905
|
+
}
|
|
906
|
+
return event.event_type === 'tool_requires_approval' && typeof event.action_id === 'string' && event.action_id.trim()
|
|
907
|
+
&& ['require_approval', 'require_dual_approval'].includes(decision);
|
|
908
|
+
});
|
|
909
|
+
if (!outcome) return fail('Governance', 'Not verified: telemetry arrived, but no matching enforced policy outcome was recorded for the sample call');
|
|
910
|
+
state.governed = true;
|
|
911
|
+
const detail = outcome.event_type === 'install_check_policy_result'
|
|
912
|
+
? `verified policy would require ${outcome.payload.decision === 'require_dual_approval' ? 'two-person approval' : 'approval'}; the probe was not executed and no request was sent to reviewers`
|
|
913
|
+
: `verified ${outcome.payload.decision} policy outcome for the direct hook probe; the sample command was not executed`;
|
|
914
|
+
steps.push({ ok: true, label: 'Governance', detail });
|
|
915
|
+
return result(true);
|
|
916
|
+
}
|