aegiscode 6.8.18 → 6.8.20

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.
@@ -262,9 +262,67 @@ function parseEnvText(text) {
262
262
  * `loaded` — names taken from the file. `kept` — names the environment
263
263
  * already had, left alone (a real export always wins).
264
264
  */
265
+ /**
266
+ * Provenance of every value this process took from `~/.aegiscode/.env`.
267
+ *
268
+ * Keyed off the env object itself (a WeakMap, so an injected `{ env }` in a
269
+ * test is tracked without leaking and `process.env` needs no extra property).
270
+ * See `isFromEnvFile`.
271
+ */
272
+ const ENV_SOURCED = new WeakMap();
273
+
274
+ function sourcedFrom(env) {
275
+ let map = ENV_SOURCED.get(env);
276
+ if (!map) {
277
+ map = new Map();
278
+ ENV_SOURCED.set(env, map);
279
+ }
280
+ return map;
281
+ }
282
+
283
+ /**
284
+ * Was `name`'s CURRENT value in `env` one this process took from the shared env
285
+ * file, rather than something the launching shell exported?
286
+ *
287
+ * This is the distinction the file's own rule 1 depends on and could not
288
+ * previously express. The file is documented as a *convenience for the common
289
+ * case, not a way for a stale file to shadow an explicit export* — but once a
290
+ * value is copied into `process.env` the two are the same thing, so every
291
+ * env-first reader (`client/credentials.js`) treated a line in the file exactly
292
+ * like a deliberate export and let it win forever. Concretely: a user runs
293
+ * `aegiscode login`, the key is written to `credentials.json` (0600) and
294
+ * reported as saved, and every request since then authenticates with whatever
295
+ * `AEGIS_API_KEY=` line the file still carries — the "it says saved but the key
296
+ * is wrong" report. A real export still wins; a file value is a fallback.
297
+ *
298
+ * `value` is checked as well as the name: a shell export that replaced the
299
+ * loaded value is no longer file-sourced, and neither is a later `setEnvValue`
300
+ * (which applies the value it just wrote and marks it accordingly).
301
+ *
302
+ * @param {string} name
303
+ * @param {string} [value] the current value, to confirm it is still the one the
304
+ * file provided. Omit to ask about the name alone.
305
+ * @param {object} [o] `env`, for tests and injected environments
306
+ */
307
+ function isFromEnvFile(name, value, o = {}) {
308
+ const env = o.env || process.env;
309
+ const map = ENV_SOURCED.get(env);
310
+ if (!map || !map.has(name)) return false;
311
+ if (value === undefined) return true;
312
+ return map.get(name) === String(value);
313
+ }
314
+
265
315
  function loadEnvFile(o = {}) {
266
316
  const env = o.env || process.env;
267
317
  const file = o.file || envFileFor(o.dir);
318
+ // Names this process took from the FILE, with the value it took. Kept so a
319
+ // consumer can tell the two sources apart: rule 1 above makes the file a
320
+ // fallback, but the moment its value lands in `process.env` it is otherwise
321
+ // indistinguishable from an explicit `AEGIS_API_KEY=… aegiscode` export, and
322
+ // `client/credentials.js`'s resolution order is env-first. Without this
323
+ // marker a leftover line in a file every host sources at start-up outranks
324
+ // the key the user explicitly saved — see `isFromEnvFile()` below.
325
+ const sourced = sourcedFrom(env);
268
326
  const result = {
269
327
  ok: false, file, loaded: [], kept: [], refused: [], reason: '', loose: false, mode: 0,
270
328
  };
@@ -296,8 +354,14 @@ function loadEnvFile(o = {}) {
296
354
  }
297
355
  if (env[name] === undefined || env[name] === '') {
298
356
  env[name] = value;
357
+ // Provenance: this value is the FILE's, not the launching shell's. An
358
+ // env-first reader must treat it as the fallback the file is documented
359
+ // to be, not as an explicit export that outranks a saved key.
360
+ sourced.set(name, value);
299
361
  result.loaded.push(name);
300
362
  } else {
363
+ // A real export wins (rule 1) and is deliberately NOT marked: it is the
364
+ // one source allowed to outrank `credentials.json`.
301
365
  result.kept.push(name);
302
366
  }
303
367
  }
@@ -615,7 +679,12 @@ function setEnvValue(name, value, o = {}) {
615
679
  out.changed = false;
616
680
  out.replaced = true;
617
681
  out.mode = previousMode || SECRET_FILE_MODE;
618
- if (o.apply !== false) env[name] = secret;
682
+ if (o.apply !== false) {
683
+ env[name] = secret;
684
+ // Applied, and the file carries it: file-sourced, so an env-first reader
685
+ // treats it as the fallback it is (see isFromEnvFile).
686
+ sourcedFrom(env).set(name, secret);
687
+ }
619
688
  return out;
620
689
  }
621
690
 
@@ -640,7 +709,11 @@ function setEnvValue(name, value, o = {}) {
640
709
  out.replaced = replaced;
641
710
  out.mode = SECRET_FILE_MODE;
642
711
  out.tightened = !out.created && previousMode !== 0 && (previousMode & 0o077) !== 0;
643
- if (o.apply !== false) env[name] = secret;
712
+ if (o.apply !== false) {
713
+ env[name] = secret;
714
+ // Just written to the file and applied here: file-sourced (see above).
715
+ sourcedFrom(env).set(name, secret);
716
+ }
644
717
  return out;
645
718
  }
646
719
 
@@ -810,16 +883,91 @@ function keyStatus(name, o = {}) {
810
883
  *
811
884
  * @param {string} modelId
812
885
  * @param {string} [cls] 'byok' | 'aegis' | anything else
813
- * @returns {{env:string, provider:string, pooled:boolean}}
886
+ * @returns {{env:string, provider:string, vendor:string, pooled:boolean}}
814
887
  */
815
888
  function keyForModelId(modelId, cls) {
816
889
  const id = String(modelId == null ? '' : modelId).trim();
817
890
  const byok = String(cls || '').toLowerCase() === 'byok' || id.includes(':');
818
891
  if (byok && id.includes(':')) {
819
892
  const provider = id.slice(0, id.indexOf(':')).trim();
820
- return { env: envVarFor(provider), provider, pooled: false };
893
+ return { env: envVarFor(provider), provider, vendor: provider, pooled: false };
894
+ }
895
+ // A pooled id is served by the pool, so the credential the ROUTE needs is the
896
+ // account key — but the id may still NAME the vendor underneath it
897
+ // (`deepseek`, `anthropic-haiku`, `openai-gpt4o-mini`). That vendor is what
898
+ // `vendor` reports, and it is not the same question as `env`: it is the
899
+ // provider key a user may also want on this machine, which the picker asks
900
+ // for after the account key. `provider` stays '' for pooled on purpose — the
901
+ // byok call path reads it as "which provider's settings row to address", and
902
+ // a pooled row has none.
903
+ return { env: ACCOUNT_ENV_VAR, provider: '', vendor: providerForModelId(id, cls), pooled: true };
904
+ }
905
+
906
+ /**
907
+ * Vendors whose slug is a namespace a model id may be spelled under.
908
+ *
909
+ * Deliberately a *table* and not a pattern: the derivation below is a claim that
910
+ * a key for this vendor exists, so an id whose first segment is not on this list
911
+ * derives NO vendor (and the picker asks only for the account key) rather than
912
+ * inventing a variable name like `NEXUS_API_KEY` for the pool's own namespace.
913
+ * The list is the platform's providers as its own BYOK catalog spells them
914
+ * (aegis1 services/nexus_provider/catalog.py MODEL_CATALOG) plus the ids this
915
+ * module already re-spells in ALIASES above — keep it in step with that catalog,
916
+ * not with whatever vendor a user might mention.
917
+ */
918
+ const VENDOR_SLUGS = Object.freeze([
919
+ 'openai',
920
+ 'anthropic',
921
+ 'deepseek',
922
+ 'google',
923
+ 'gemini',
924
+ 'groq',
925
+ 'mistral',
926
+ 'openrouter',
927
+ 'together',
928
+ 'together-ai',
929
+ 'xai',
930
+ 'x-ai',
931
+ 'grok',
932
+ 'huggingface',
933
+ 'fireworks',
934
+ 'voyage-ai',
935
+ 'azure-openai',
936
+ ]);
937
+
938
+ /** The multi-segment slugs, longest first, so `azure-openai-x` matches the full slug. */
939
+ const VENDOR_COMPOUNDS = Object.freeze(
940
+ VENDOR_SLUGS.filter((s) => s.includes('-')).sort((a, b) => b.length - a.length)
941
+ );
942
+
943
+ /**
944
+ * The vendor a model id names, or '' — `deepseek-flash` → `deepseek`,
945
+ * `nexus-brain` → '', `deepseek:deepseek-v4-flash` → `deepseek`.
946
+ *
947
+ * The one question the picker needs to answer "is there a SECOND key worth
948
+ * asking for on this row?" A pooled row is billed to the AEGIS account, so its
949
+ * route needs the account key and nothing else — but when the row is named
950
+ * after a vendor whose key this machine could hold (`deepseek`), asking for that
951
+ * key too is what lets the account actually call the model instead of the pool
952
+ * failing a turn with "no provider key". That is the gap this closes:
953
+ * aegis-key present, models listed, and every turn still failing because the
954
+ * vendor key the models route through was never collected.
955
+ *
956
+ * @param {string} modelId
957
+ * @param {string} [cls] unused by the derivation; accepted so a caller can pass
958
+ * the same (id, cls) pair it passes `keyForModelId` without branching.
959
+ * @returns {string} the vendor slug, or '' when the id names none this module
960
+ * knows a variable for.
961
+ */
962
+ function providerForModelId(modelId, cls) { // eslint-disable-line no-unused-vars
963
+ const id = String(modelId == null ? '' : modelId).trim().toLowerCase();
964
+ if (!id) return '';
965
+ if (id.includes(':')) return id.slice(0, id.indexOf(':')).trim();
966
+ for (const slug of VENDOR_COMPOUNDS) {
967
+ if (id === slug || id.startsWith(slug + '-')) return slug;
821
968
  }
822
- return { env: ACCOUNT_ENV_VAR, provider: '', pooled: true };
969
+ const first = id.split('-')[0];
970
+ return VENDOR_SLUGS.includes(first) ? first : '';
823
971
  }
824
972
 
825
973
  module.exports = {
@@ -831,7 +979,15 @@ module.exports = {
831
979
  envVarFor,
832
980
  parseEnvText,
833
981
  loadEnvFile,
982
+ // Provenance of what loadEnvFile put in the environment: a value taken from
983
+ // the FILE is a fallback, not an explicit export, and the env-first readers
984
+ // (client/credentials.js) must be able to tell the two apart.
985
+ isFromEnvFile,
834
986
  providerKeyFromEnv,
987
+ // The vendor half of "what key does this model id need": the account key is
988
+ // the route's credential, this is the provider key underneath it.
989
+ providerForModelId,
990
+ VENDOR_SLUGS,
835
991
  isWritableName,
836
992
  quoteEnvValue,
837
993
  upsertEnvText,
@@ -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
+ };