aegiscode 6.8.19 → 6.8.21

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.
@@ -0,0 +1,427 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * hooks.js — the hook layer every host shares (CLI `/hooks`, the desktop's
5
+ * `hooks` tool, and `aegiscode gate install-hooks`).
6
+ *
7
+ * Two halves live here, and they are deliberately in ONE file because they are
8
+ * the same question asked twice:
9
+ *
10
+ * 1. **Config hooks** — what `settings.json` says should run at
11
+ * PreToolUse/PostToolUse/…. Both hosts must read the same five files in
12
+ * the same order and count the same things, or the two hosts report
13
+ * different worlds for one machine. Before this file, the CLI had a
14
+ * private `readHooks()` in `src/commands.js` and the desktop had nothing
15
+ * at all.
16
+ *
17
+ * 2. **Repo guard hooks** — this repository's own `.githooks/` (the agent-key
18
+ * gate, the secret scan, the invariant lock). Installing them was a
19
+ * *printed suggestion*, never an action: `agent-gate.mjs install-hooks`
20
+ * chmod'ed two files and told the user to run `git config` themselves, and
21
+ * `init --hooks` ended with the same "finish: git config …" line. On every
22
+ * platform that means a fresh clone has NO hooks — the documented failure
23
+ * in `.githooks/lib-gate.sh`'s own header. `installRepoHooks()` below does
24
+ * the install.
25
+ *
26
+ * ## Cross-platform, and provably so
27
+ *
28
+ * This is the part the previous implementations got wrong, so it is stated
29
+ * plainly:
30
+ *
31
+ * · **Paths** are joined with `path.win32` when `platform === 'win32'` and
32
+ * `path.posix` otherwise. `path.join` would use the HOST's separator, which
33
+ * means the Windows branch could only ever be exercised on Windows — and a
34
+ * branch no test can reach is a claim, not a feature. The injected
35
+ * `platform` is what makes `C:\Users\me\.aegis\settings.json` testable from
36
+ * Linux.
37
+ * · **`chmod(0o755)` is POSIX-only.** On Windows the mode bits are not
38
+ * enforced, so a `chmodSync` there is a silent no-op that reads as
39
+ * protection. We do it only where it means something and say so where it
40
+ * does not. (Git for Windows runs hooks with its own bundled `sh`, so the
41
+ * `#!/bin/sh` hooks DO run there — the exec bit is simply not the mechanism.)
42
+ * · **Nothing shells out to `sh`.** `git` is invoked as an argv array through
43
+ * `execFile`, never through a shell string, so a path or a repo with a space
44
+ * cannot become a different command.
45
+ * · **`$HOME` is not trusted.** `home` resolves from an explicit override,
46
+ * then `USERPROFILE` (Windows), then `HOME` (POSIX), then `os.homedir()`.
47
+ *
48
+ * Every entry point takes an options object — `{ platform, env, home, cwd,
49
+ * readFile, exists, runGit, chmod }` — defaulting to the real environment, so
50
+ * each branch is exercisable on this host instead of only on the OS it targets.
51
+ *
52
+ * Zero dependencies beyond `node:` builtins, because this file is staged into
53
+ * both vendor trees (see `cli/scripts/predist.mjs`, `desktop/scripts/predist.mjs`)
54
+ * and must load inside a packaged ASAR and a globally installed npm package.
55
+ */
56
+
57
+ const fs = require('node:fs');
58
+ const os = require('node:os');
59
+ const path = require('node:path');
60
+ const { execFileSync } = require('node:child_process');
61
+
62
+ /** The settings directories both hosts read, most-authoritative last. */
63
+ const SETTINGS_DIRS = ['.aegis', '.aegiscode'];
64
+
65
+ /**
66
+ * The settings files, in merge order (later wins for a given event).
67
+ * `.claude` is last and is reported as FOREIGN rather than treated as ours —
68
+ * see `hookSourceKind`.
69
+ */
70
+ function hookSettingPaths(opts = {}) {
71
+ const p = platformPath(opts.platform);
72
+ const home = homeDir(opts);
73
+ const cwd = opts.cwd || process.cwd();
74
+ const out = [];
75
+ for (const dir of SETTINGS_DIRS) {
76
+ out.push(p.join(home, dir, 'settings.json'));
77
+ out.push(p.join(cwd, dir, 'settings.json'));
78
+ }
79
+ out.push(p.join(home, '.claude', 'settings.json'));
80
+ return dedupe(out);
81
+ }
82
+
83
+ /** `path.win32` for a win32 host, `path.posix` otherwise — see the header. */
84
+ function platformPath(platform) {
85
+ return (platform || process.platform) === 'win32' ? path.win32 : path.posix;
86
+ }
87
+
88
+ /** Explicit home → USERPROFILE (win32) → HOME (posix) → os.homedir(). */
89
+ function homeDir(opts = {}) {
90
+ if (opts.home) return String(opts.home);
91
+ const env = opts.env || process.env;
92
+ const platform = opts.platform || process.platform;
93
+ const keys = platform === 'win32' ? ['USERPROFILE', 'HOME'] : ['HOME', 'USERPROFILE'];
94
+ for (const k of keys) if (env && env[k]) return String(env[k]);
95
+ return os.homedir();
96
+ }
97
+
98
+ /** 'aegis' (our own trees), 'foreign' (`.claude`, another vendor's), 'other'. */
99
+ function hookSourceKind(p) {
100
+ const dir = path.posix.basename(String(p).replace(/\\/g, '/'));
101
+ const parent = path.posix.basename(path.posix.dirname(String(p).replace(/\\/g, '/')));
102
+ if (dir !== 'settings.json') return 'other';
103
+ if (parent === '.claude') return 'foreign';
104
+ if (SETTINGS_DIRS.includes(parent)) return 'aegis';
105
+ return 'other';
106
+ }
107
+
108
+ function dedupe(list) {
109
+ const seen = new Set();
110
+ const out = [];
111
+ for (const item of list) {
112
+ const key = String(item).replace(/\\/g, '/');
113
+ if (seen.has(key)) continue;
114
+ seen.add(key);
115
+ out.push(item);
116
+ }
117
+ return out;
118
+ }
119
+
120
+ /** `~`-shorten for display, on either separator. */
121
+ function shorten(p, opts = {}) {
122
+ const home = homeDir(opts);
123
+ const s = String(p);
124
+ if (!home) return s;
125
+ const posix = s.replace(/\\/g, '/');
126
+ const h = String(home).replace(/\\/g, '/').replace(/\/+$/, '');
127
+ if (posix === h) return '~';
128
+ if (posix.startsWith(`${h}/`)) return `~${posix.slice(h.length)}`;
129
+ return s;
130
+ }
131
+
132
+ /**
133
+ * Read and merge hook config from the standard settings files.
134
+ *
135
+ * Merge rule, preserved from this CLI's shipped behaviour: matching hooks from
136
+ * every settings file are CONCATENATED per event, in file order. That is what
137
+ * actually happens — a hook host runs every matching hook it was configured
138
+ * with, it does not let a project file delete the user's hook — so `hooks` is
139
+ * the number of hooks that will run, not the number of files that mention one.
140
+ * `from` lists every contributing file, `foreign` every `.claude` file seen, so
141
+ * a machine where another vendor's hooks are among what runs is visible instead
142
+ * of invisible.
143
+ *
144
+ * @returns {{hooks: object, from: string[], foreign: string[], files: Array}}
145
+ */
146
+ function readHookConfig(opts = {}) {
147
+ const readFile = opts.readFile || defaultReadFile;
148
+ const paths = opts.paths || hookSettingPaths(opts);
149
+ const hooks = {};
150
+ const from = [];
151
+ const foreign = [];
152
+ const files = [];
153
+ for (const file of paths) {
154
+ let text = null;
155
+ try { text = readFile(file); } catch { text = null; }
156
+ if (text === null || text === undefined) { files.push({ path: file, exists: false, kind: hookSourceKind(file) }); continue; }
157
+ let json;
158
+ try { json = JSON.parse(String(text)); } catch { files.push({ path: file, exists: true, parsed: false, kind: hookSourceKind(file) }); continue; }
159
+ const kind = hookSourceKind(file);
160
+ const events = eventsOf(json);
161
+ const names = Object.keys(events);
162
+ files.push({ path: file, exists: true, parsed: true, kind, events: names });
163
+ // A foreign file is reported, not merged — so it must not appear in `from`,
164
+ // which means "the files ÆGIS reads as its own policy". Listing it there
165
+ // (with no marker) is how the status panel came to imply that another
166
+ // vendor's hooks were ours. `files[]` carries the full picture; `foreign`
167
+ // names them explicitly.
168
+ if (kind === 'foreign') {
169
+ foreign.push(shorten(file, opts));
170
+ continue;
171
+ }
172
+ if (!names.length) continue;
173
+ from.push(shorten(file, opts));
174
+ for (const [event, arr] of Object.entries(events)) {
175
+ if (!Array.isArray(arr) || !arr.length) continue;
176
+ hooks[event] = [...(hooks[event] || []), ...arr];
177
+ }
178
+ }
179
+ return { hooks, from, foreign, files };
180
+ }
181
+
182
+ /** The `hooks` object of a settings document (either layout), never throws. */
183
+ function eventsOf(json) {
184
+ if (!json || typeof json !== 'object') return {};
185
+ if (json.hooks && typeof json.hooks === 'object' && !Array.isArray(json.hooks)) {
186
+ const out = {};
187
+ for (const [k, v] of Object.entries(json.hooks)) if (Array.isArray(v)) out[k] = v;
188
+ return out;
189
+ }
190
+ const out = {};
191
+ for (const event of HOOK_EVENTS) if (Array.isArray(json[event])) out[event] = json[event];
192
+ return out;
193
+ }
194
+
195
+ /** The events the Claude Code host tracks. */
196
+ const HOOK_EVENTS = [
197
+ 'PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'PermissionRequest',
198
+ 'UserPromptSubmit', 'SessionStart', 'SessionEnd', 'Stop', 'SubagentStop',
199
+ 'Notification', 'Compaction',
200
+ ];
201
+
202
+ /**
203
+ * `{enabled, hooks, events, byEvent}` from a merged hooks map.
204
+ *
205
+ * `hooks` counts MATCHER entries (one `{name, matcher, hooks}` object = one),
206
+ * which is the number the CLI's `/hooks status` has always shown. Counting the
207
+ * nested `hooks[]` array instead — a different, also-defensible number — is how
208
+ * two hosts end up disagreeing about one machine; there is one number here.
209
+ */
210
+ function hookStats(hooks) {
211
+ const map = hooks && typeof hooks === 'object' ? hooks : {};
212
+ const events = Object.keys(map);
213
+ let count = 0;
214
+ const byEvent = {};
215
+ for (const ev of events) {
216
+ const arr = Array.isArray(map[ev]) ? map[ev] : [];
217
+ byEvent[ev] = arr.length;
218
+ count += arr.length;
219
+ }
220
+ return { enabled: count > 0, hooks: count, events, byEvent };
221
+ }
222
+
223
+ // ── the repo's own guard hooks (.githooks/) ─────────────────────────────────
224
+
225
+ /** Files `.githooks/` is expected to carry; the first two are required. */
226
+ const REQUIRED_HOOKS = ['pre-commit', 'pre-push'];
227
+ const OPTIONAL_HOOKS = ['post-merge', 'lib-gate.sh', 'push-policy'];
228
+
229
+ /**
230
+ * The default git runner: argv array, no shell, cwd pinned.
231
+ * @returns {{ok: boolean, out: string, err: string}}
232
+ */
233
+ function defaultRunGit(args, { cwd, env } = {}) {
234
+ try {
235
+ const out = execFileSync('git', args, {
236
+ cwd, env: env || process.env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'],
237
+ windowsHide: true,
238
+ });
239
+ return { ok: true, out: String(out).trim(), err: '' };
240
+ } catch (e) {
241
+ return { ok: false, out: String(e && e.stdout ? e.stdout : '').trim(), err: String(e && e.stderr ? e.stderr : (e && e.message) || e).trim() };
242
+ }
243
+ }
244
+
245
+ function defaultReadFile(file) { return fs.readFileSync(file, 'utf8'); }
246
+ function defaultExists(file) { try { return fs.statSync(file).isFile(); } catch { return false; } }
247
+ function defaultChmod(file) { fs.chmodSync(file, 0o755); }
248
+
249
+ /**
250
+ * What state the repo's guard hooks are in — read-only, never throws.
251
+ *
252
+ * @returns {{repo, hooksDir, inGitRepo, configured, wanted, installed,
253
+ * present: string[], missing: string[], gitVersion, platform,
254
+ * execBit, execNote}}
255
+ */
256
+ function repoHookStatus(opts = {}) {
257
+ const platform = opts.platform || process.platform;
258
+ const p = platformPath(platform);
259
+ const cwd = opts.cwd || process.cwd();
260
+ const exists = opts.exists || defaultExists;
261
+ const runGit = opts.runGit || defaultRunGit;
262
+
263
+ const hooksDir = p.join(cwd, '.githooks');
264
+ const present = [];
265
+ const missing = [];
266
+ for (const name of [...REQUIRED_HOOKS, ...OPTIONAL_HOOKS]) {
267
+ if (exists(p.join(hooksDir, name))) present.push(name);
268
+ else missing.push(name);
269
+ }
270
+
271
+ const inside = runGit(['rev-parse', '--is-inside-work-tree'], { cwd, env: opts.env });
272
+ const inGitRepo = inside.ok && inside.out === 'true';
273
+ let configured = null;
274
+ if (inGitRepo) {
275
+ const got = runGit(['config', '--get', 'core.hooksPath'], { cwd, env: opts.env });
276
+ // Exit 1 with no output means "not set" — that is a value, not a failure.
277
+ configured = got.ok && got.out ? got.out : null;
278
+ }
279
+
280
+ // git resolves core.hooksPath relative to the repo root; compare normalized.
281
+ const wanted = '.githooks';
282
+ const norm = (v) => (v === null || v === undefined ? null : String(v).replace(/\\/g, '/').replace(/\/+$/, ''));
283
+ const installed = inGitRepo && norm(configured) === wanted;
284
+
285
+ return {
286
+ repo: cwd,
287
+ hooksDir,
288
+ platform,
289
+ inGitRepo,
290
+ configured,
291
+ wanted,
292
+ installed,
293
+ present,
294
+ missing,
295
+ execBit: platform !== 'win32',
296
+ execNote: platform === 'win32'
297
+ ? 'Windows: the exec bit is not enforced and not needed — git for Windows runs hooks with its bundled sh.'
298
+ : 'POSIX: the hooks are chmod 0755 so git can execute them.',
299
+ };
300
+ }
301
+
302
+ /**
303
+ * INSTALL the repo's guard hooks: point `core.hooksPath` at `.githooks/` and
304
+ * make them executable.
305
+ *
306
+ * This is the action `agent-gate.mjs install-hooks` only ever described. It is
307
+ * idempotent (a second call reports `changed: false`), it verifies the write by
308
+ * reading the config back, and `dryRun` returns the exact commands without
309
+ * touching anything — the shape `--dry-run` must have before a user lets an
310
+ * agent near their git config.
311
+ *
312
+ * @returns {{ok, changed, code, actions: string[], status, error?}}
313
+ */
314
+ function installRepoHooks(opts = {}) {
315
+ const platform = opts.platform || process.platform;
316
+ const p = platformPath(platform);
317
+ const cwd = opts.cwd || process.cwd();
318
+ const runGit = opts.runGit || defaultRunGit;
319
+ const exists = opts.exists || defaultExists;
320
+ const chmod = opts.chmod || defaultChmod;
321
+ const dryRun = Boolean(opts.dryRun);
322
+
323
+ const status = repoHookStatus({ ...opts, platform, cwd, runGit, exists });
324
+ const actions = [];
325
+ const done = (extra) => ({ ok: true, changed: actions.length > 0, code: 'installed', actions, status, ...extra });
326
+
327
+ if (!exists(p.join(status.hooksDir, 'pre-commit'))) {
328
+ return {
329
+ ok: false, changed: false, code: 'no-hooks', actions, status,
330
+ error: `no ${status.wanted}/pre-commit under ${cwd} — nothing to install. ` +
331
+ 'A tree that never had the hooks needs them restored (`git checkout -- .githooks/`) ' +
332
+ 'or created (`agent-gate.mjs init --hooks`).',
333
+ };
334
+ }
335
+ if (!status.inGitRepo) {
336
+ return {
337
+ ok: false, changed: false, code: 'no-git', actions, status,
338
+ error: `${cwd} is not inside a git work tree (core.hooksPath is a per-repo setting), ` +
339
+ 'or git is not on PATH.',
340
+ };
341
+ }
342
+
343
+ if (!status.installed) {
344
+ actions.push(`git -C ${cwd} config core.hooksPath ${status.wanted}`);
345
+ if (!dryRun) {
346
+ const res = runGit(['config', 'core.hooksPath', status.wanted], { cwd, env: opts.env });
347
+ if (!res.ok) {
348
+ return { ok: false, changed: false, code: 'git-failed', actions, status, error: `git config refused: ${res.err || 'unknown error'}` };
349
+ }
350
+ const readback = runGit(['config', '--get', 'core.hooksPath'], { cwd, env: opts.env });
351
+ const got = readback.ok ? String(readback.out).replace(/\\/g, '/').replace(/\/+$/, '') : null;
352
+ if (got !== status.wanted) {
353
+ // Report it rather than assume it — a config write that did not take
354
+ // is exactly the failure the old print-only version could not see.
355
+ return { ok: false, changed: true, code: 'verify-failed', actions, status, error: `core.hooksPath reads back as "${got || '(unset)'}", not "${status.wanted}"` };
356
+ }
357
+ }
358
+ }
359
+
360
+ // The exec bit: meaningful only where git actually reads it. On Windows we
361
+ // say so instead of pretending a no-op chmod did something.
362
+ //
363
+ // The mode is READ first and only written when it differs. Chmod-ing every
364
+ // hook on every run made `changed` come back true for a tree that was already
365
+ // installed — an idempotency claim that was simply false, and the reason
366
+ // `install` could never report "already installed" honestly.
367
+ const modes = [];
368
+ if (platform !== 'win32') {
369
+ const modeOf = opts.modeOf || ((file) => { try { return fs.statSync(file).mode & 0o777; } catch { return null; } });
370
+ for (const name of status.present.filter((n) => n !== 'push-policy')) {
371
+ const file = p.join(status.hooksDir, name);
372
+ if (modeOf(file) === 0o755) continue; // already executable — nothing to change
373
+ if (dryRun) { modes.push(`chmod 0755 ${file}`); continue; }
374
+ try { chmod(file, 0o755); modes.push(`chmod 0755 ${name}`); } catch (e) {
375
+ modes.push(`chmod 0755 ${name} FAILED: ${(e && e.message) || e}`);
376
+ }
377
+ }
378
+ actions.push(...modes);
379
+ }
380
+ return done({ modes, note: status.execNote });
381
+ }
382
+
383
+ /**
384
+ * One plain-text report of both halves, for the desktop's `hooks` tool (the CLI
385
+ * renders its own themed panel from the same numbers). Same facts in both
386
+ * places, so the GUI and the terminal cannot describe one machine differently.
387
+ */
388
+ function hooksSummary(opts = {}) {
389
+ const platform = opts.platform || process.platform;
390
+ const config = opts.config || readHookConfig({ ...opts, platform });
391
+ const stats = opts.stats || hookStats(config.hooks);
392
+ const repo = opts.repo || repoHookStatus({ ...opts, platform });
393
+ const lines = [];
394
+ lines.push(`hooks: ${stats.enabled ? 'enabled' : 'disabled'} · ${stats.hooks} matcher(s) in ${stats.events.length} event(s)`);
395
+ if (stats.events.length) {
396
+ for (const ev of stats.events) lines.push(` ${ev}: ${stats.byEvent[ev]}`);
397
+ } else {
398
+ lines.push(' (no settings.json declares hooks — checked ' + hookSettingPaths({ ...opts, platform }).map((f) => shorten(f, opts)).join(', ') + ')');
399
+ }
400
+ if (config.from.length) lines.push(` from: ${config.from.join(', ')}`);
401
+ if (config.foreign && config.foreign.length) {
402
+ lines.push(` foreign host files (read, listed—${stats.hooks && config.foreign.length ? 'may outrank ours' : 'no hooks'}): ${config.foreign.join(', ')}`);
403
+ }
404
+ lines.push('');
405
+ lines.push(`repo guard hooks (${repo.wanted}/): ${repo.present.length ? repo.present.join(', ') : 'none found'}`);
406
+ if (repo.missing.length) lines.push(` missing: ${repo.missing.join(', ')}`);
407
+ lines.push(` core.hooksPath: ${repo.installed ? `${repo.wanted} (installed)` : `${repo.configured || '(unset)'} — NOT installed, so a commit runs NO guard hooks`}`);
408
+ lines.push(` ${repo.execNote}`);
409
+ return lines.join('\n');
410
+ }
411
+
412
+ module.exports = {
413
+ HOOK_EVENTS,
414
+ SETTINGS_DIRS,
415
+ hooksSummary,
416
+ REQUIRED_HOOKS,
417
+ OPTIONAL_HOOKS,
418
+ hookSettingPaths,
419
+ hookSourceKind,
420
+ homeDir,
421
+ platformPath,
422
+ shorten,
423
+ readHookConfig,
424
+ hookStats,
425
+ repoHookStatus,
426
+ installRepoHooks,
427
+ };