osuite 2.9.8 → 2.10.0
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 +69 -37
- package/cli.js +405 -41
- package/osuite.js +9 -2
- package/package.json +2 -1
- package/projectHooks.js +741 -0
- package/reviewSurface.js +10 -2
package/projectHooks.js
ADDED
|
@@ -0,0 +1,741 @@
|
|
|
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
|
+
|
|
9
|
+
const HOOK_SCRIPT_RE = /osuite_(?:pretool|posttool|stop)\.py/;
|
|
10
|
+
|
|
11
|
+
export const RUNTIME_HOOKS = {
|
|
12
|
+
claude: {
|
|
13
|
+
label: 'Claude Code',
|
|
14
|
+
dir: '.claude',
|
|
15
|
+
settings: ['.claude/settings.json', '.claude/settings.local.json'],
|
|
16
|
+
},
|
|
17
|
+
codex: {
|
|
18
|
+
label: 'Codex',
|
|
19
|
+
dir: '.codex',
|
|
20
|
+
settings: ['.codex/hooks.json'],
|
|
21
|
+
config: '.codex/config.toml',
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
const MERGED_FILES = {
|
|
26
|
+
'.claude/settings.json': 'json',
|
|
27
|
+
'.claude/settings.local.json': 'json',
|
|
28
|
+
'.codex/hooks.json': 'json',
|
|
29
|
+
'.codex/config.toml': 'toml',
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export const DOCTOR_COMMAND = 'echo "OSuite doctor hook check"';
|
|
33
|
+
|
|
34
|
+
function isPlainObject(value) {
|
|
35
|
+
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function hookScriptName(command) {
|
|
39
|
+
const match = String(command || '').match(HOOK_SCRIPT_RE);
|
|
40
|
+
return match ? match[0] : '';
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// An OSuite hook already in the file counts as present even when its path differs,
|
|
44
|
+
// so a re-run never registers a second copy that would govern each call twice.
|
|
45
|
+
function sameHook(existing, wanted) {
|
|
46
|
+
const existingScript = hookScriptName(existing?.command);
|
|
47
|
+
const wantedScript = hookScriptName(wanted?.command);
|
|
48
|
+
if (existingScript && wantedScript) return existingScript === wantedScript;
|
|
49
|
+
return String(existing?.command || '').trim() === String(wanted?.command || '').trim();
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function countHooks(hooks) {
|
|
53
|
+
if (!isPlainObject(hooks)) return 0;
|
|
54
|
+
return Object.values(hooks).reduce((total, groups) => total + (Array.isArray(groups)
|
|
55
|
+
? groups.reduce((sum, group) => sum + (Array.isArray(group?.hooks) ? group.hooks.length : 0), 0)
|
|
56
|
+
: 0), 0);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function templateHooks(template) {
|
|
60
|
+
const hooks = isPlainObject(template?.hooks) ? template.hooks : {};
|
|
61
|
+
return Object.entries(hooks).flatMap(([event, groups]) => (Array.isArray(groups) ? groups : [])
|
|
62
|
+
.flatMap((group) => (Array.isArray(group?.hooks) ? group.hooks : [])
|
|
63
|
+
.map((hook) => ({ event, matcher: group.matcher, command: hook.command }))));
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function disabledHookSettings(settings) {
|
|
67
|
+
return settings?.disableAllHooks === true
|
|
68
|
+
? ['disableAllHooks = true keeps hooks disabled; intentional disablement was preserved']
|
|
69
|
+
: [];
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Add the OSuite PreToolUse/PostToolUse entries to a JSON settings file.
|
|
74
|
+
* The user's own hooks and every other key stay as they are.
|
|
75
|
+
*/
|
|
76
|
+
export function mergeHookSettings(existingText, templateText) {
|
|
77
|
+
const template = JSON.parse(templateText);
|
|
78
|
+
if (existingText === null || existingText === undefined) {
|
|
79
|
+
return { status: 'created', body: templateText, added: templateHooks(template), keptHooks: 0, keptKeys: [], conflicts: disabledHookSettings(template) };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
let settings = {};
|
|
83
|
+
if (existingText.trim()) {
|
|
84
|
+
try {
|
|
85
|
+
settings = JSON.parse(existingText);
|
|
86
|
+
} catch (error) {
|
|
87
|
+
return { status: 'error', error: `not valid JSON (${error.message})` };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (!isPlainObject(settings)) return { status: 'error', error: 'expected a JSON object at the top level' };
|
|
91
|
+
|
|
92
|
+
let hooks = settings.hooks;
|
|
93
|
+
if (hooks === undefined || hooks === null || (Array.isArray(hooks) && hooks.length === 0)) hooks = {};
|
|
94
|
+
if (!isPlainObject(hooks)) return { status: 'error', error: '"hooks" must be an object keyed by event name' };
|
|
95
|
+
|
|
96
|
+
const wanted = isPlainObject(template.hooks) ? template.hooks : {};
|
|
97
|
+
const merged = { ...hooks };
|
|
98
|
+
const added = [];
|
|
99
|
+
for (const [event, groups] of Object.entries(wanted)) {
|
|
100
|
+
const current = merged[event] === undefined ? [] : merged[event];
|
|
101
|
+
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];
|
|
104
|
+
for (const group of Array.isArray(groups) ? groups : []) {
|
|
105
|
+
const missing = (group.hooks || []).filter((hook) => !present.some((existing) => sameHook(existing, hook)));
|
|
106
|
+
if (!missing.length) continue;
|
|
107
|
+
next.push({ ...group, hooks: missing });
|
|
108
|
+
missing.forEach((hook) => added.push({ event, matcher: group.matcher, command: hook.command }));
|
|
109
|
+
}
|
|
110
|
+
if (next.length !== current.length) merged[event] = next;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const result = {
|
|
114
|
+
added,
|
|
115
|
+
keptHooks: countHooks(hooks),
|
|
116
|
+
keptKeys: Object.keys(settings).filter((key) => key !== 'hooks'),
|
|
117
|
+
conflicts: disabledHookSettings(settings),
|
|
118
|
+
};
|
|
119
|
+
if (!added.length) return { ...result, status: 'unchanged', body: existingText };
|
|
120
|
+
return { ...result, status: 'merged', body: `${JSON.stringify({ ...settings, hooks: merged }, null, 2)}\n` };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// --- TOML ------------------------------------------------------------------
|
|
124
|
+
// Line-based on purpose: the CLI has no dependencies, and the partial only sets
|
|
125
|
+
// plain keys. Lines inside multi-line strings and arrays are skipped.
|
|
126
|
+
|
|
127
|
+
function normalizeTomlKey(raw) {
|
|
128
|
+
return String(raw || '')
|
|
129
|
+
.split('.')
|
|
130
|
+
.map((part) => part.trim().replace(/^"(.*)"$/, '$1').replace(/^'(.*)'$/, '$1'))
|
|
131
|
+
.join('.');
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function stripTomlValue(raw) {
|
|
135
|
+
const value = String(raw || '').trim();
|
|
136
|
+
const quote = value[0];
|
|
137
|
+
if (quote === '"' || quote === "'") {
|
|
138
|
+
const end = value.indexOf(quote, 1);
|
|
139
|
+
return end > 0 ? value.slice(0, end + 1) : value;
|
|
140
|
+
}
|
|
141
|
+
const hash = value.indexOf('#');
|
|
142
|
+
return (hash >= 0 ? value.slice(0, hash) : value).trim();
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function withoutStrings(text) {
|
|
146
|
+
return String(text || '').replace(/"(?:[^"\\]|\\.)*"|'[^']*'/g, '');
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function bracketDelta(text) {
|
|
150
|
+
const bare = withoutStrings(text).replace(/#.*$/, '');
|
|
151
|
+
return (bare.match(/[[{]/g) || []).length - (bare.match(/[\]}]/g) || []).length;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function parseInlineTable(raw) {
|
|
155
|
+
const inner = withoutStrings(raw).includes('{') ? String(raw).trim().replace(/^\{|\}\s*(#.*)?$/g, '') : '';
|
|
156
|
+
return inner.split(',').map((part) => part.split('=')).filter((pair) => pair.length >= 2)
|
|
157
|
+
.map(([key, ...rest]) => [normalizeTomlKey(key), stripTomlValue(rest.join('='))]);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function scanToml(text) {
|
|
161
|
+
const lines = String(text || '').split(/\r?\n/);
|
|
162
|
+
const values = new Map();
|
|
163
|
+
const tables = new Map();
|
|
164
|
+
const inlineTables = new Set();
|
|
165
|
+
const root = { lastIndex: -1 };
|
|
166
|
+
let current = root;
|
|
167
|
+
let tableName = '';
|
|
168
|
+
let firstHeaderIndex = -1;
|
|
169
|
+
let multiline = null;
|
|
170
|
+
let depth = 0;
|
|
171
|
+
|
|
172
|
+
lines.forEach((line, index) => {
|
|
173
|
+
if (multiline) {
|
|
174
|
+
if (line.includes(multiline)) multiline = null;
|
|
175
|
+
current.lastIndex = index;
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
if (depth > 0) {
|
|
179
|
+
depth += bracketDelta(line);
|
|
180
|
+
current.lastIndex = index;
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
const trimmed = line.trim();
|
|
184
|
+
if (!trimmed || trimmed.startsWith('#')) return;
|
|
185
|
+
|
|
186
|
+
const header = trimmed.match(/^\[(\[)?\s*([^\]]+?)\s*\]\]?\s*(?:#.*)?$/);
|
|
187
|
+
if (header) {
|
|
188
|
+
if (firstHeaderIndex < 0) firstHeaderIndex = index;
|
|
189
|
+
tableName = normalizeTomlKey(header[2]);
|
|
190
|
+
const isArrayTable = Boolean(header[1]);
|
|
191
|
+
current = { headerIndex: index, lastIndex: index, arrayTable: isArrayTable };
|
|
192
|
+
if (!isArrayTable && !tables.has(tableName)) tables.set(tableName, current);
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const pair = trimmed.match(/^([^=]+?)\s*=\s*(.*)$/);
|
|
197
|
+
if (!pair) return;
|
|
198
|
+
current.lastIndex = index;
|
|
199
|
+
const value = pair[2];
|
|
200
|
+
if (!current.arrayTable) {
|
|
201
|
+
const key = tableName ? `${tableName}.${normalizeTomlKey(pair[1])}` : normalizeTomlKey(pair[1]);
|
|
202
|
+
values.set(key, stripTomlValue(value));
|
|
203
|
+
if (value.trim().startsWith('{')) {
|
|
204
|
+
inlineTables.add(key);
|
|
205
|
+
parseInlineTable(value).forEach(([innerKey, innerValue]) => values.set(`${key}.${innerKey}`, innerValue));
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
const tripleDouble = (value.match(/"""/g) || []).length;
|
|
209
|
+
const tripleSingle = (value.match(/'''/g) || []).length;
|
|
210
|
+
if (tripleDouble % 2 === 1) multiline = '"""';
|
|
211
|
+
else if (tripleSingle % 2 === 1) multiline = "'''";
|
|
212
|
+
else depth = Math.max(0, bracketDelta(value));
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
return { lines, values, tables, inlineTables, root, firstHeaderIndex };
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function tomlEntries(text) {
|
|
219
|
+
const entries = [];
|
|
220
|
+
let table = '';
|
|
221
|
+
String(text || '').split(/\r?\n/).forEach((line) => {
|
|
222
|
+
const trimmed = line.trim();
|
|
223
|
+
if (!trimmed || trimmed.startsWith('#')) return;
|
|
224
|
+
const header = trimmed.match(/^\[\s*([^\]]+?)\s*\]$/);
|
|
225
|
+
if (header) {
|
|
226
|
+
table = normalizeTomlKey(header[1]);
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const pair = trimmed.match(/^([^=]+?)\s*=\s*(.*)$/);
|
|
230
|
+
if (pair) entries.push({ table, key: normalizeTomlKey(pair[1]), value: stripTomlValue(pair[2]) });
|
|
231
|
+
});
|
|
232
|
+
return entries;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function describeTomlEntry(entry) {
|
|
236
|
+
return `${entry.table ? `[${entry.table}] ` : ''}${entry.key} = ${entry.value}`;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const HOOK_FLAGS = ['features.hooks', 'features.codex_hooks'];
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Add the keys of the OSuite config.toml partial that the file does not set yet.
|
|
243
|
+
* Values the user already chose are kept and reported; running it again changes nothing.
|
|
244
|
+
*/
|
|
245
|
+
export function mergeTomlPartial(existingText, partialText) {
|
|
246
|
+
const entries = tomlEntries(partialText);
|
|
247
|
+
if (existingText === null || existingText === undefined) {
|
|
248
|
+
return { status: 'created', body: partialText, added: entries.map(describeTomlEntry), kept: [], conflicts: [] };
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const scan = scanToml(existingText);
|
|
252
|
+
const added = [];
|
|
253
|
+
const kept = [];
|
|
254
|
+
const conflicts = [];
|
|
255
|
+
const rootLines = [];
|
|
256
|
+
const tableLines = new Map();
|
|
257
|
+
const newTables = new Map();
|
|
258
|
+
|
|
259
|
+
HOOK_FLAGS.forEach((flag) => {
|
|
260
|
+
if (scan.values.get(flag) === 'false') {
|
|
261
|
+
conflicts.push(`${flag.replace('features.', '[features] ')} = false turns Codex hooks off; set it to true`);
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
for (const entry of entries) {
|
|
266
|
+
const fullKey = entry.table ? `${entry.table}.${entry.key}` : entry.key;
|
|
267
|
+
if (HOOK_FLAGS.includes(fullKey) && conflicts.length && !scan.values.has(fullKey)) continue;
|
|
268
|
+
if (scan.values.has(fullKey)) {
|
|
269
|
+
const current = scan.values.get(fullKey);
|
|
270
|
+
if (current !== entry.value && !HOOK_FLAGS.includes(fullKey)) {
|
|
271
|
+
kept.push({ key: describeTomlEntry({ ...entry, value: current }), suggested: entry.value });
|
|
272
|
+
}
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
const line = `${entry.key} = ${entry.value}`;
|
|
276
|
+
if (!entry.table) {
|
|
277
|
+
rootLines.push(line);
|
|
278
|
+
} else if (scan.inlineTables.has(entry.table) || (scan.values.has(entry.table) && !scan.tables.has(entry.table))) {
|
|
279
|
+
kept.push({ key: `${entry.table} (inline)`, suggested: `add ${line}` });
|
|
280
|
+
continue;
|
|
281
|
+
} else if (scan.tables.has(entry.table)) {
|
|
282
|
+
if (!tableLines.has(entry.table)) tableLines.set(entry.table, []);
|
|
283
|
+
tableLines.get(entry.table).push(line);
|
|
284
|
+
} else if ([...scan.values.keys()].some((key) => key.startsWith(`${entry.table}.`))) {
|
|
285
|
+
// The table only exists through dotted keys; a [table] header would redefine it.
|
|
286
|
+
rootLines.push(`${entry.table}.${line}`);
|
|
287
|
+
} else {
|
|
288
|
+
if (!newTables.has(entry.table)) newTables.set(entry.table, []);
|
|
289
|
+
newTables.get(entry.table).push(line);
|
|
290
|
+
}
|
|
291
|
+
added.push(describeTomlEntry(entry));
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
if (!added.length) return { status: 'unchanged', body: existingText, added, kept, conflicts };
|
|
295
|
+
|
|
296
|
+
const eol = existingText.includes('\r\n') ? '\r\n' : '\n';
|
|
297
|
+
const lines = [...scan.lines];
|
|
298
|
+
const inserts = [];
|
|
299
|
+
tableLines.forEach((items, table) => {
|
|
300
|
+
inserts.push({ index: scan.tables.get(table).lastIndex + 1, lines: items });
|
|
301
|
+
});
|
|
302
|
+
if (rootLines.length) {
|
|
303
|
+
const index = scan.root.lastIndex >= 0 ? scan.root.lastIndex + 1 : (scan.firstHeaderIndex >= 0 ? 0 : lines.length);
|
|
304
|
+
const spacer = scan.firstHeaderIndex >= index && String(lines[index] || '').trim() ? [''] : [];
|
|
305
|
+
inserts.push({ index, lines: ['# Added by OSuite', ...rootLines, ...spacer] });
|
|
306
|
+
}
|
|
307
|
+
inserts.sort((a, b) => b.index - a.index).forEach(({ index, lines: items }) => lines.splice(index, 0, ...items));
|
|
308
|
+
|
|
309
|
+
let body = lines.join(eol);
|
|
310
|
+
if (newTables.size) {
|
|
311
|
+
body = body.replace(/\s*$/, '');
|
|
312
|
+
newTables.forEach((items, table) => {
|
|
313
|
+
body += `${eol}${eol}# Added by OSuite${eol}[${table}]${eol}${items.join(eol)}`;
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
if (!body.endsWith(eol)) body += eol;
|
|
317
|
+
return { status: 'merged', body, added, kept, conflicts };
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// --- Install ---------------------------------------------------------------
|
|
321
|
+
|
|
322
|
+
function isInside(root, target) {
|
|
323
|
+
const relative = path.relative(root, target);
|
|
324
|
+
return relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
export function resolveProjectPath(projectRoot, relativePath) {
|
|
328
|
+
const root = path.resolve(projectRoot);
|
|
329
|
+
const absolute = path.resolve(root, String(relativePath || '').replace(/^\/+/, ''));
|
|
330
|
+
if (!isInside(root, absolute)) {
|
|
331
|
+
throw new Error(`Refusing to write outside the project root: ${relativePath}`);
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
const realRoot = fs.realpathSync(root);
|
|
335
|
+
const parts = path.relative(root, absolute).split(path.sep).filter(Boolean);
|
|
336
|
+
let resolved = realRoot;
|
|
337
|
+
for (let index = 0; index < parts.length; index += 1) {
|
|
338
|
+
const next = path.join(resolved, parts[index]);
|
|
339
|
+
let stat;
|
|
340
|
+
try {
|
|
341
|
+
stat = fs.lstatSync(next);
|
|
342
|
+
} catch (error) {
|
|
343
|
+
if (error.code === 'ENOENT') return path.join(next, ...parts.slice(index + 1));
|
|
344
|
+
throw error;
|
|
345
|
+
}
|
|
346
|
+
// Check each existing parent, not just the leaf. lstat also catches dangling
|
|
347
|
+
// links, which existsSync would mistake for safe new files.
|
|
348
|
+
try {
|
|
349
|
+
resolved = fs.realpathSync(next);
|
|
350
|
+
} catch (error) {
|
|
351
|
+
if (stat.isSymbolicLink()) throw new Error(`Cannot resolve project symlink safely: ${relativePath}`);
|
|
352
|
+
throw error;
|
|
353
|
+
}
|
|
354
|
+
if (!isInside(realRoot, resolved)) {
|
|
355
|
+
throw new Error(`Refusing to write outside the project root through a symlink: ${relativePath}`);
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return resolved;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function readIfExists(absolute) {
|
|
362
|
+
return fs.existsSync(absolute) ? fs.readFileSync(absolute, 'utf8') : null;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
function writeFile(absolute, body) {
|
|
366
|
+
fs.mkdirSync(path.dirname(absolute), { recursive: true });
|
|
367
|
+
fs.writeFileSync(absolute, String(body ?? ''));
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/**
|
|
371
|
+
* Install one bootstrap file. Settings files are merged; OSuite's own files
|
|
372
|
+
* are created, left alone when identical, and replaced only with --force.
|
|
373
|
+
*/
|
|
374
|
+
export function installProjectFile(projectRoot, relativePath, body, { force = false } = {}) {
|
|
375
|
+
const absolute = resolveProjectPath(projectRoot, relativePath);
|
|
376
|
+
const existing = readIfExists(absolute);
|
|
377
|
+
const kind = MERGED_FILES[relativePath];
|
|
378
|
+
|
|
379
|
+
if (kind) {
|
|
380
|
+
let merge;
|
|
381
|
+
try {
|
|
382
|
+
merge = kind === 'json' ? mergeHookSettings(existing, String(body ?? '')) : mergeTomlPartial(existing, String(body ?? ''));
|
|
383
|
+
} catch (error) {
|
|
384
|
+
merge = { status: 'error', error: `OSuite template could not be read (${error.message})` };
|
|
385
|
+
}
|
|
386
|
+
if (merge.status === 'created' || merge.status === 'merged') writeFile(absolute, merge.body);
|
|
387
|
+
const { body: _body, ...report } = merge;
|
|
388
|
+
return { relativePath, kind, ...report };
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
if (existing === null) {
|
|
392
|
+
writeFile(absolute, body);
|
|
393
|
+
return { relativePath, status: 'created' };
|
|
394
|
+
}
|
|
395
|
+
if (existing === String(body ?? '')) return { relativePath, status: 'unchanged' };
|
|
396
|
+
if (force) {
|
|
397
|
+
writeFile(absolute, body);
|
|
398
|
+
return { relativePath, status: 'replaced' };
|
|
399
|
+
}
|
|
400
|
+
return { relativePath, status: 'kept' };
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
export function installBlockers(results = []) {
|
|
404
|
+
return results.flatMap((result) => [
|
|
405
|
+
...(result.status === 'error' ? [`${result.relativePath}: ${result.error}`] : []),
|
|
406
|
+
...(result.conflicts || []).map((conflict) => `${result.relativePath}: ${conflict}`),
|
|
407
|
+
]);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** Lines that say exactly what an install changed, for the terminal. */
|
|
411
|
+
export function describeInstallResult(result) {
|
|
412
|
+
const lines = [];
|
|
413
|
+
const name = result.relativePath;
|
|
414
|
+
if (result.status === 'error') {
|
|
415
|
+
lines.push(`failed ${name}: ${result.error}. Nothing was changed; fix the file and run this again.`);
|
|
416
|
+
return lines;
|
|
417
|
+
}
|
|
418
|
+
if (result.kind === 'json') {
|
|
419
|
+
if (result.status === 'unchanged') lines.push(`unchanged ${name} (OSuite hooks already there)`);
|
|
420
|
+
else lines.push(`${result.status === 'created' ? 'created' : 'merged '} ${name}`);
|
|
421
|
+
if (result.status !== 'unchanged') {
|
|
422
|
+
result.added.forEach((hook) => lines.push(` + ${hook.event} ${hook.matcher || '*'} → ${hook.command}`));
|
|
423
|
+
}
|
|
424
|
+
if (result.status === 'merged') {
|
|
425
|
+
const others = result.keptKeys.length ? ` and your other settings (${result.keptKeys.join(', ')})` : '';
|
|
426
|
+
lines.push(` kept ${result.keptHooks} existing hook${result.keptHooks === 1 ? '' : 's'}${others}`);
|
|
427
|
+
}
|
|
428
|
+
(result.conflicts || []).forEach((conflict) => lines.push(` ! ${conflict}`));
|
|
429
|
+
return lines;
|
|
430
|
+
}
|
|
431
|
+
if (result.kind === 'toml') {
|
|
432
|
+
if (result.status === 'unchanged') lines.push(`unchanged ${name} (OSuite settings already there)`);
|
|
433
|
+
else lines.push(`${result.status === 'created' ? 'created' : 'merged '} ${name}`);
|
|
434
|
+
if (result.status !== 'unchanged') result.added.forEach((entry) => lines.push(` + ${entry}`));
|
|
435
|
+
result.kept.forEach((entry) => lines.push(` kept your ${entry.key} (OSuite suggests ${entry.suggested})`));
|
|
436
|
+
result.conflicts.forEach((conflict) => lines.push(` ! ${conflict}`));
|
|
437
|
+
return lines;
|
|
438
|
+
}
|
|
439
|
+
const labels = {
|
|
440
|
+
created: `created ${name}`,
|
|
441
|
+
unchanged: `unchanged ${name}`,
|
|
442
|
+
replaced: `replaced ${name}`,
|
|
443
|
+
kept: `kept ${name} (differs from this OSuite version; use --force to replace)`,
|
|
444
|
+
};
|
|
445
|
+
lines.push(labels[result.status] || `${result.status} ${name}`);
|
|
446
|
+
return lines;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// --- Verify ----------------------------------------------------------------
|
|
450
|
+
|
|
451
|
+
function readJson(absolute) {
|
|
452
|
+
return JSON.parse(fs.readFileSync(absolute, 'utf8'));
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function findCommand(settings, event, script) {
|
|
456
|
+
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;
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** OSuite hooks registered in this project, with anything that stops them from running. */
|
|
463
|
+
export function findHookInstallations(projectRoot, runtimes = Object.keys(RUNTIME_HOOKS)) {
|
|
464
|
+
return runtimes.flatMap((runtime) => {
|
|
465
|
+
const spec = RUNTIME_HOOKS[runtime];
|
|
466
|
+
if (!spec) return [];
|
|
467
|
+
const problems = [];
|
|
468
|
+
const disabledReasons = [];
|
|
469
|
+
let pretool = null;
|
|
470
|
+
let posttool = null;
|
|
471
|
+
spec.settings.forEach((settingsPath) => {
|
|
472
|
+
const absolute = path.join(projectRoot, settingsPath);
|
|
473
|
+
if (!fs.existsSync(absolute)) return;
|
|
474
|
+
let settings;
|
|
475
|
+
try {
|
|
476
|
+
settings = readJson(absolute);
|
|
477
|
+
} catch {
|
|
478
|
+
problems.push(`${settingsPath} is not valid JSON, so ${spec.label} cannot load its hooks`);
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
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');
|
|
484
|
+
if (pre && !pretool) pretool = { settingsPath, command: pre.command };
|
|
485
|
+
if (post && !posttool) posttool = { settingsPath, command: post.command };
|
|
486
|
+
});
|
|
487
|
+
|
|
488
|
+
const scriptPath = `${spec.dir}/hooks/osuite_pretool.py`;
|
|
489
|
+
const scriptPresent = fs.existsSync(path.join(projectRoot, scriptPath));
|
|
490
|
+
if (!pretool && !scriptPresent && !problems.length) return [];
|
|
491
|
+
if (!pretool) {
|
|
492
|
+
problems.push(`no PreToolUse hook in ${spec.settings.join(' or ')} runs osuite_pretool.py`);
|
|
493
|
+
}
|
|
494
|
+
if (spec.config) {
|
|
495
|
+
const config = readIfExists(path.join(projectRoot, spec.config));
|
|
496
|
+
if (config !== null) {
|
|
497
|
+
const values = scanToml(config).values;
|
|
498
|
+
HOOK_FLAGS.forEach((flag) => {
|
|
499
|
+
if (values.get(flag) === 'false') disabledReasons.push(`${spec.config} turns hooks off (${flag} = false)`);
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
return [{ runtime, label: spec.label, installDir: spec.dir, pretool, posttool,
|
|
504
|
+
hostEnabled: disabledReasons.length === 0, disabledReasons, problems: [...problems, ...disabledReasons] }];
|
|
505
|
+
});
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
export function parseDotenv(body) {
|
|
509
|
+
const values = {};
|
|
510
|
+
String(body || '').split(/\r?\n/).forEach((line) => {
|
|
511
|
+
const trimmed = line.trim();
|
|
512
|
+
if (!trimmed || trimmed.startsWith('#') || !trimmed.includes('=')) return;
|
|
513
|
+
const [rawKey, ...rawValue] = trimmed.split('=');
|
|
514
|
+
const key = rawKey.trim();
|
|
515
|
+
let value = rawValue.join('=').trim().replace(/^['"]|['"]$/g, '');
|
|
516
|
+
if (value.includes(' #')) value = value.slice(0, value.indexOf(' #')).trim();
|
|
517
|
+
if (key) values[key] = value;
|
|
518
|
+
});
|
|
519
|
+
return values;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** The credentials the installed hook will use: shell values first, then its own .env. */
|
|
523
|
+
export function hookCredentials(projectRoot, installation, shellEnv = process.env) {
|
|
524
|
+
const dotenv = parseDotenv(readIfExists(path.join(projectRoot, installation.installDir, '.env')));
|
|
525
|
+
const env = { ...dotenv };
|
|
526
|
+
Object.entries(shellEnv || {}).forEach(([key, value]) => {
|
|
527
|
+
if (value !== undefined) env[key] = value;
|
|
528
|
+
});
|
|
529
|
+
return {
|
|
530
|
+
baseUrl: String(env.OSUITE_BASE_URL || env.DASHCLAW_BASE_URL || '').replace(/\/$/, ''),
|
|
531
|
+
apiKey: String(env.OSUITE_API_KEY || env.DASHCLAW_API_KEY || ''),
|
|
532
|
+
envFile: `${installation.installDir}/.env`,
|
|
533
|
+
hookMode: String(env.OSUITE_HOOK_MODE || env.DASHCLAW_HOOK_MODE || 'enforce'),
|
|
534
|
+
};
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function runShell(command, { cwd, env, input, timeoutMs }) {
|
|
538
|
+
return new Promise((resolve) => {
|
|
539
|
+
let stdout = '';
|
|
540
|
+
let stderr = '';
|
|
541
|
+
let settled = false;
|
|
542
|
+
const child = spawn(command, { cwd, env, shell: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
543
|
+
const finish = (result) => {
|
|
544
|
+
if (settled) return;
|
|
545
|
+
settled = true;
|
|
546
|
+
clearTimeout(timer);
|
|
547
|
+
resolve({ stdout, stderr, ...result });
|
|
548
|
+
};
|
|
549
|
+
const timer = setTimeout(() => {
|
|
550
|
+
child.kill('SIGKILL');
|
|
551
|
+
finish({ code: null, timedOut: true });
|
|
552
|
+
}, timeoutMs);
|
|
553
|
+
child.stdout.on('data', (chunk) => { stdout += chunk; });
|
|
554
|
+
child.stderr.on('data', (chunk) => { stderr += chunk; });
|
|
555
|
+
child.on('error', (error) => finish({ code: null, error }));
|
|
556
|
+
child.on('close', (code) => finish({ code }));
|
|
557
|
+
child.stdin.on('error', () => {});
|
|
558
|
+
child.stdin.end(input);
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
function hookMessages(stdout) {
|
|
563
|
+
return String(stdout || '').split(/\r?\n/).flatMap((line) => {
|
|
564
|
+
try {
|
|
565
|
+
const parsed = JSON.parse(line);
|
|
566
|
+
return typeof parsed?.systemMessage === 'string' ? [parsed.systemMessage] : [];
|
|
567
|
+
} catch {
|
|
568
|
+
return [];
|
|
569
|
+
}
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
function hookWarnings(stdout, stderr) {
|
|
574
|
+
return [...new Set([
|
|
575
|
+
...hookMessages(stdout),
|
|
576
|
+
...String(stderr || '').split(/\r?\n/).map((line) => line.trim())
|
|
577
|
+
.filter((line) => /\bWarning:|Not governed|\[observe\]|Guard unavailable/i.test(line)),
|
|
578
|
+
])];
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
function lastLine(text) {
|
|
582
|
+
return String(text || '').trim().split(/\r?\n/).filter(Boolean).pop() || '';
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
async function fetchSessionEvents(fetchImpl, { baseUrl, apiKey, sessionId }) {
|
|
586
|
+
try {
|
|
587
|
+
const response = await fetchImpl(`${baseUrl}/api/runtime-sessions/${encodeURIComponent(sessionId)}/events?limit=50`, {
|
|
588
|
+
headers: { 'x-api-key': apiKey },
|
|
589
|
+
});
|
|
590
|
+
const payload = await response.json().catch(() => ({}));
|
|
591
|
+
return { status: response.status, items: Array.isArray(payload?.items) ? payload.items : [] };
|
|
592
|
+
} catch (error) {
|
|
593
|
+
return { status: 0, items: [], error: error.message };
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
/**
|
|
598
|
+
* Directly probe the registered hook with an inert Bash call. Configuration,
|
|
599
|
+
* telemetry, and policy outcomes are separate checks; this is not a host launch.
|
|
600
|
+
*/
|
|
601
|
+
export async function runHookCheck({
|
|
602
|
+
projectRoot,
|
|
603
|
+
installation,
|
|
604
|
+
shellEnv = process.env,
|
|
605
|
+
fetchImpl = globalThis.fetch,
|
|
606
|
+
timeoutMs = 30000,
|
|
607
|
+
} = {}) {
|
|
608
|
+
const steps = [];
|
|
609
|
+
const warnings = [];
|
|
610
|
+
const state = { configured: false, hostEnabled: false, connected: false, telemetry: false, governed: false };
|
|
611
|
+
let sessionId;
|
|
612
|
+
const result = (ok) => ({ ok, ...state, steps, runtime: installation?.runtime, sessionId, warnings });
|
|
613
|
+
const fail = (label, detail) => {
|
|
614
|
+
steps.push({ label, ok: false, detail });
|
|
615
|
+
return result(false);
|
|
616
|
+
};
|
|
617
|
+
|
|
618
|
+
if (!installation?.pretool) return fail('Hook installed', installation?.problems?.join('; ') || 'no OSuite hook found');
|
|
619
|
+
const disabledReasons = installation.disabledReasons || [];
|
|
620
|
+
const problems = (installation.problems || []).filter((problem) => !disabledReasons.includes(problem));
|
|
621
|
+
if (problems.length) return fail('Hook installed', problems.join('; '));
|
|
622
|
+
state.configured = true;
|
|
623
|
+
steps.push({ label: 'Hook installed', ok: true, detail: `${installation.pretool.settingsPath} runs ${installation.pretool.command}` });
|
|
624
|
+
if (installation.hostEnabled === false || disabledReasons.length) {
|
|
625
|
+
return fail('Host hooks enabled', disabledReasons.join('; ') || 'hooks are disabled in project settings');
|
|
626
|
+
}
|
|
627
|
+
state.hostEnabled = true;
|
|
628
|
+
steps.push({ label: 'Host hooks enabled', ok: true, detail: 'project settings permit hooks; actual host invocation is not verified by this direct probe' });
|
|
629
|
+
|
|
630
|
+
const credentials = hookCredentials(projectRoot, installation, shellEnv);
|
|
631
|
+
if (!credentials.baseUrl || !credentials.apiKey) {
|
|
632
|
+
return fail('Hook credentials', `OSUITE_BASE_URL and OSUITE_API_KEY are not set in ${credentials.envFile} or the shell; governance cannot be verified`);
|
|
633
|
+
}
|
|
634
|
+
steps.push({ label: 'Hook credentials', ok: true, detail: `base URL and API key configured for ${credentials.baseUrl}` });
|
|
635
|
+
|
|
636
|
+
const id = crypto.randomBytes(4).toString('hex');
|
|
637
|
+
sessionId = `osuite-doctor-${id}`;
|
|
638
|
+
const toolUseId = `osuite_doctor_${id}`;
|
|
639
|
+
const sample = {
|
|
640
|
+
session_id: sessionId,
|
|
641
|
+
cwd: projectRoot,
|
|
642
|
+
hook_event_name: 'PreToolUse',
|
|
643
|
+
tool_name: 'Bash',
|
|
644
|
+
tool_input: { command: DOCTOR_COMMAND, description: 'OSuite doctor hook check' },
|
|
645
|
+
tool_use_id: toolUseId,
|
|
646
|
+
};
|
|
647
|
+
// OSUITE_HOOK_CHECK tells the hook and OSuite this is a probe: a call that
|
|
648
|
+
// would need approval is reported, not sent to reviewers.
|
|
649
|
+
const env = { ...shellEnv, OSUITE_APPROVAL_WAIT_SECONDS: '3', OSUITE_HOOK_CHECK: '1' };
|
|
650
|
+
const run = await runShell(installation.pretool.command, {
|
|
651
|
+
cwd: projectRoot, env, input: JSON.stringify(sample), timeoutMs,
|
|
652
|
+
});
|
|
653
|
+
const messages = hookMessages(run.stdout);
|
|
654
|
+
warnings.push(...hookWarnings(run.stdout, run.stderr));
|
|
655
|
+
const said = messages[0] || lastLine(run.stderr);
|
|
656
|
+
|
|
657
|
+
if (run.timedOut) return fail('Hook test', `the hook did not finish within ${Math.round(timeoutMs / 1000)}s`);
|
|
658
|
+
if (run.code === 127 && /^python3?\b/.test(installation.pretool.command)) {
|
|
659
|
+
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');
|
|
660
|
+
}
|
|
661
|
+
if (run.error || (run.code !== 0 && run.code !== 2)) {
|
|
662
|
+
return fail('Hook test', `the hook command failed (${run.error ? run.error.message : `exit ${run.code}`})${said ? `: ${said}` : ''}`);
|
|
663
|
+
}
|
|
664
|
+
steps.push({
|
|
665
|
+
ok: true,
|
|
666
|
+
label: 'Hook test',
|
|
667
|
+
detail: `sample Bash call (${DOCTOR_COMMAND}) ${run.code === 0 ? 'allowed' : 'stopped'} by the hook${run.code === 2 && said ? `: ${said}` : ''}`,
|
|
668
|
+
});
|
|
669
|
+
|
|
670
|
+
let lookup = await fetchSessionEvents(fetchImpl, { ...credentials, sessionId });
|
|
671
|
+
if (!lookup.items.some((event) => event?.tool_use_id === toolUseId) && lookup.status !== 401 && lookup.status !== 403) {
|
|
672
|
+
await new Promise((resolve) => setTimeout(resolve, 500));
|
|
673
|
+
lookup = await fetchSessionEvents(fetchImpl, { ...credentials, sessionId });
|
|
674
|
+
}
|
|
675
|
+
const seen = lookup.items.filter((event) => event?.tool_use_id === toolUseId && event?.runtime_session_id === sessionId);
|
|
676
|
+
|
|
677
|
+
if (installation.posttool && run.code === 0) {
|
|
678
|
+
// Closes the sample action in the ledger; not part of the verdict.
|
|
679
|
+
await runShell(installation.posttool.command, {
|
|
680
|
+
cwd: projectRoot,
|
|
681
|
+
env,
|
|
682
|
+
timeoutMs,
|
|
683
|
+
input: JSON.stringify({
|
|
684
|
+
...sample,
|
|
685
|
+
hook_event_name: 'PostToolUse',
|
|
686
|
+
tool_response: { stdout: 'OSuite doctor hook check', stderr: '', interrupted: false, exit_code: 0 },
|
|
687
|
+
}),
|
|
688
|
+
});
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
state.connected = lookup.status >= 200 && lookup.status < 300;
|
|
692
|
+
if (state.connected) steps.push({ ok: true, label: 'Studio connection', detail: `runtime event endpoint answered HTTP ${lookup.status}` });
|
|
693
|
+
if (!state.connected || !seen.length) {
|
|
694
|
+
const reason = lookup.status === 401 || lookup.status === 403
|
|
695
|
+
? `OSuite rejected the API key in ${credentials.envFile} (HTTP ${lookup.status})`
|
|
696
|
+
: said || (lookup.error ? `could not reach ${credentials.baseUrl} (${lookup.error})` : `no runtime event for session ${sessionId}`);
|
|
697
|
+
return fail(state.connected ? 'Studio event' : 'Studio connection', `the sample call did not reach OSuite: ${reason}`);
|
|
698
|
+
}
|
|
699
|
+
state.telemetry = true;
|
|
700
|
+
steps.push({
|
|
701
|
+
ok: true,
|
|
702
|
+
label: 'Studio event',
|
|
703
|
+
detail: `${[...new Set(seen.map((event) => event.event_type))].join(', ')} reached OSuite (session ${sessionId})`,
|
|
704
|
+
});
|
|
705
|
+
|
|
706
|
+
const observing = credentials.hookMode === 'observe' || seen.some((event) => (
|
|
707
|
+
event.payload?.hook_mode === 'observe' || event.payload?.observe_only === true
|
|
708
|
+
|| String(event.payload?.decision || '').startsWith('observe_')
|
|
709
|
+
));
|
|
710
|
+
if (observing) return fail('Governance', 'Not governed: observation-only mode records telemetry but does not enforce policy; the mode was not changed');
|
|
711
|
+
const unavailable = seen.some((event) => ['guard_unavailable', 'guard_unavailable_blocked'].includes(event.payload?.decision));
|
|
712
|
+
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
|
+
const ungoverned = warnings.find((warning) => /Not governed/i.test(warning));
|
|
714
|
+
if (ungoverned) return fail('Governance', ungoverned);
|
|
715
|
+
|
|
716
|
+
const outcome = seen.find((event) => {
|
|
717
|
+
const decision = event.payload?.decision;
|
|
718
|
+
if (run.code === 0) {
|
|
719
|
+
return event.event_type === 'tool_allowed' && typeof event.action_id === 'string' && event.action_id.trim()
|
|
720
|
+
&& ['allow', 'warn', 'approved_by_reviewer'].includes(decision);
|
|
721
|
+
}
|
|
722
|
+
if (event.event_type === 'install_check_policy_result') {
|
|
723
|
+
return run.code === 2 && event.payload?.install_check === true
|
|
724
|
+
&& event.payload?.approval_state === 'not_requested'
|
|
725
|
+
&& ['require_approval', 'require_dual_approval'].includes(decision);
|
|
726
|
+
}
|
|
727
|
+
if (event.event_type === 'tool_blocked' && decision === 'block') {
|
|
728
|
+
return event.payload?.reason !== 'action_creation_not_authorized'
|
|
729
|
+
&& !String(event.payload?.reason || '').startsWith('Unsupported guard decision:');
|
|
730
|
+
}
|
|
731
|
+
return event.event_type === 'tool_requires_approval' && typeof event.action_id === 'string' && event.action_id.trim()
|
|
732
|
+
&& ['require_approval', 'require_dual_approval'].includes(decision);
|
|
733
|
+
});
|
|
734
|
+
if (!outcome) return fail('Governance', 'Not verified: telemetry arrived, but no matching enforced policy outcome was recorded for the sample call');
|
|
735
|
+
state.governed = true;
|
|
736
|
+
const detail = outcome.event_type === 'install_check_policy_result'
|
|
737
|
+
? `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`
|
|
738
|
+
: `verified ${outcome.payload.decision} policy outcome for the direct hook probe; the sample command was not executed`;
|
|
739
|
+
steps.push({ ok: true, label: 'Governance', detail });
|
|
740
|
+
return result(true);
|
|
741
|
+
}
|