aegiscode 7.0.14 → 7.0.15

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.
Files changed (109) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +3 -2
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2932
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3020
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -4003
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/fingerprint.js +1 -592
  28. package/src/format.js +1 -259
  29. package/src/fuzzy.js +1 -119
  30. package/src/history.js +1 -401
  31. package/src/init.js +1 -175
  32. package/src/input.js +1 -139
  33. package/src/keys.js +1 -183
  34. package/src/markdown.js +1 -306
  35. package/src/models.js +1 -487
  36. package/src/naming.js +1 -229
  37. package/src/overlays.js +1 -461
  38. package/src/panels.js +1 -1418
  39. package/src/ping.js +1 -226
  40. package/src/presence.js +1 -238
  41. package/src/render.js +1 -515
  42. package/src/screen.js +1 -518
  43. package/src/screens.js +1 -896
  44. package/src/secret.js +1 -59
  45. package/src/securefs.js +1 -359
  46. package/src/settings.js +1 -155
  47. package/src/shared.js +1 -52
  48. package/src/sharedpaths.js +1 -53
  49. package/src/signup.js +1 -156
  50. package/src/summarize.js +1 -95
  51. package/src/sysdiag.js +1 -585
  52. package/src/system.js +1 -40
  53. package/src/theme.js +1 -570
  54. package/src/title.js +1 -220
  55. package/src/todos.js +1 -115
  56. package/src/tokens.js +1 -263
  57. package/src/topup.js +1 -210
  58. package/src/update.js +1 -181
  59. package/vendor/client/aegis.js +1 -2179
  60. package/vendor/client/attest.js +1 -442
  61. package/vendor/client/authorship-key.js +1 -410
  62. package/vendor/client/auto-provision.js +1 -134
  63. package/vendor/client/brain-catalog.js +1 -268
  64. package/vendor/client/byok-catalog.js +1 -230
  65. package/vendor/client/credentials.js +1 -494
  66. package/vendor/client/device-fingerprint.js +1 -141
  67. package/vendor/client/drive-connect.js +1 -110
  68. package/vendor/client/drive-upload.js +1 -174
  69. package/vendor/client/env-file.js +1 -1273
  70. package/vendor/client/fingerprint.js +1 -1064
  71. package/vendor/client/foreign-memory.js +1 -669
  72. package/vendor/client/google-signin.js +1 -133
  73. package/vendor/client/hooks.js +1 -430
  74. package/vendor/client/model-discovery.js +1 -373
  75. package/vendor/client/platform.js +1 -937
  76. package/vendor/client/prefs.js +1 -351
  77. package/vendor/client/presence-constants.js +1 -107
  78. package/vendor/client/presence.js +1 -438
  79. package/vendor/client/record-vault.js +3 -1055
  80. package/vendor/client/session-store.js +1 -548
  81. package/vendor/client/topup.js +1 -297
  82. package/vendor/client/touch.js +1 -458
  83. package/vendor/client/update.js +1 -704
  84. package/vendor/client/user-models.js +1 -381
  85. package/vendor/desktop/lib/local/agents.js +1 -105
  86. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  87. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  88. package/vendor/desktop/lib/local/context.js +1 -95
  89. package/vendor/desktop/lib/local/engine.js +1 -3301
  90. package/vendor/desktop/lib/local/entitlement.js +1 -660
  91. package/vendor/desktop/lib/local/git-scope.js +1 -228
  92. package/vendor/desktop/lib/local/local.js +1 -2135
  93. package/vendor/desktop/lib/local/prompt.js +1 -275
  94. package/vendor/desktop/lib/local/queue.js +1 -560
  95. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  96. package/vendor/desktop/lib/local/shell.js +1 -680
  97. package/vendor/desktop/lib/local/tools.js +1 -1238
  98. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  99. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  100. package/vendor/desktop/lib/settings.js +1 -890
  101. package/vendor/desktop/renderer/usage.js +1 -1239
  102. package/vendor/hosts/install.js +1 -638
  103. package/vendor/hosts/openai-shim.js +1 -515
  104. package/vendor/hosts/spec.js +1 -164
  105. package/vendor/hosts/targets.js +1 -346
  106. package/vendor/mcp/server.js +1 -221
  107. package/vendor/mcp/tools.js +1 -408
  108. package/vendor/one/src/child.js +1 -285
  109. package/vendor/one/src/permissions.js +1 -369
@@ -1,135 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * Sign this machine in with the user's actual Google identity, instead of the
10
- * anonymous per-machine key `auto-provision.js`/`connect.js` mint by default.
11
- *
12
- * aegis1 already runs the full web side of this (`app.py`: `/auth/google`,
13
- * `/auth/callback/google`) including a desktop round-trip it was built for:
14
- * pass `?callback=http://127.0.0.1:{port}` and, once the browser finishes the
15
- * Google consent screen, aegis1 redirects the browser back to that local
16
- * address with `token`, `username` and (when available) `memory_token` as
17
- * query params. Nothing here talks to Google or to aegis1 directly — this
18
- * module only runs the localhost half of that round-trip: open a one-shot
19
- * HTTP server, hand the caller the URL to open, and resolve once the browser
20
- * comes back to it.
21
- *
22
- * `token` IS the ordinary AEGIS API key for the account aegis1 resolved
23
- * (looked up or created by `google_id`/email) — there is no second credential
24
- * format to support. The caller saves it exactly as `register-device`'s key,
25
- * through `credentials.saveApiKey`.
26
- */
27
-
28
- const http = require('node:http');
29
- const { URL } = require('node:url');
30
-
31
- /** Escapes text placed into the one-shot HTML page — the values riding in the
32
- * query string came back through the user's browser, so treat them as
33
- * untrusted even though this server only ever talks to localhost. */
34
- function escapeHtml(s) {
35
- return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({
36
- '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
37
- }[c]));
38
- }
39
-
40
- function page({ ok, error, username, surface }) {
41
- const title = ok ? 'Signed in' : 'Sign-in failed';
42
- // This page is shared by the CLI and the desktop, and only one of them is
43
- // a terminal. The desktop passes `surface: 'app'`; the default keeps the
44
- // CLI's existing wording.
45
- const where = surface === 'app' ? 'the app' : 'the terminal';
46
- const body = ok
47
- ? `Signed in${username ? ` as <b>${escapeHtml(username)}</b>` : ''}. You can close this tab and return to ${where}.`
48
- : `Sign-in failed: ${escapeHtml(error || 'no token was returned')}. You can close this tab and try again.`;
49
- return `<!doctype html><html><head><meta charset="utf-8"><title>${title} — AEGIS</title></head>` +
50
- `<body style="font:16px sans-serif;max-width:32rem;margin:4rem auto;text-align:center;">` +
51
- `<h2>${title}</h2><p>${body}</p></body></html>`;
52
- }
53
-
54
- /** `${apiBase}/auth/google?callback=${callbackUrl}` — the one URL this flow opens. */
55
- function buildAuthUrl(apiBase, callbackUrl) {
56
- const url = new URL('/auth/google', apiBase);
57
- url.searchParams.set('callback', callbackUrl);
58
- return url.toString();
59
- }
60
-
61
- /**
62
- * Starts the local callback server and returns the URL to open, plus a
63
- * `wait()` that resolves once the browser lands on it.
64
- *
65
- * Only a request that carries `token` or `error` ends the wait — anything
66
- * else (a browser pre-connect, `/favicon.ico`) gets a plain 404 and the
67
- * server keeps listening for the real one.
68
- *
69
- * `surface` only changes the wording of the page the browser lands on after
70
- * signing in ('terminal' for the CLI, 'app' for the desktop) — it changes
71
- * nothing about the flow itself.
72
- *
73
- * @returns {Promise<{url: string, wait: () => Promise<{apiKey:string, username:?string, memoryToken:?string}>}>}
74
- */
75
- async function startGoogleSignIn({ apiBase, host = '127.0.0.1', timeoutMs = 5 * 60 * 1000, surface = 'terminal' } = {}) {
76
- if (!apiBase) throw new Error('startGoogleSignIn requires apiBase');
77
-
78
- let settled = false;
79
- let resolveResult;
80
- let rejectResult;
81
- const result = new Promise((resolve, reject) => {
82
- resolveResult = resolve;
83
- rejectResult = reject;
84
- });
85
-
86
- const server = http.createServer((req, res) => {
87
- let parsed;
88
- try {
89
- parsed = new URL(req.url, `http://${host}`);
90
- } catch {
91
- res.writeHead(400).end();
92
- return;
93
- }
94
- const token = parsed.searchParams.get('token');
95
- const username = parsed.searchParams.get('username');
96
- const memoryToken = parsed.searchParams.get('memory_token');
97
- const error = parsed.searchParams.get('error');
98
-
99
- if (!token && !error) {
100
- res.writeHead(404).end();
101
- return;
102
- }
103
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
104
- res.end(page({ ok: Boolean(token), error, username, surface }));
105
-
106
- if (settled) return;
107
- settled = true;
108
- clearTimeout(timer);
109
- server.close();
110
- if (token) resolveResult({ apiKey: token, username: username || null, memoryToken: memoryToken || null });
111
- else rejectResult(new Error(error || 'no token was returned'));
112
- });
113
-
114
- await new Promise((resolve, reject) => {
115
- server.once('error', reject);
116
- server.listen(0, host, resolve);
117
- });
118
-
119
- const { port } = server.address();
120
- const callbackUrl = `http://${host}:${port}`;
121
- const url = buildAuthUrl(apiBase, callbackUrl);
122
-
123
- const timer = setTimeout(() => {
124
- if (settled) return;
125
- settled = true;
126
- server.close();
127
- rejectResult(new Error(`timed out after ${Math.round(timeoutMs / 1000)}s waiting for the browser sign-in`));
128
- }, timeoutMs);
129
- // A pending timer must not keep the process alive just for this wait.
130
- if (typeof timer.unref === 'function') timer.unref();
131
-
132
- return { url, wait: () => result };
133
- }
134
-
135
- module.exports = { startGoogleSignIn, buildAuthUrl };
3
+ "use strict";const http=require("node:http"),{URL:URL}=require("node:url");function escapeHtml(e){return String(null==e?"":e).replace(/[&<>"']/g,(e=>({"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"}[e])))}function page({ok:e,error:t,username:r,surface:n}){const a=e?"Signed in":"Sign-in failed",o="app"===n?"the app":"the terminal";return`<!doctype html><html><head><meta charset="utf-8"><title>${a} — AEGIS</title></head><body style="font:16px sans-serif;max-width:32rem;margin:4rem auto;text-align:center;"><h2>${a}</h2><p>${e?`Signed in${r?` as <b>${escapeHtml(r)}</b>`:""}. You can close this tab and return to ${o}.`:`Sign-in failed: ${escapeHtml(t||"no token was returned")}. You can close this tab and try again.`}</p></body></html>`}function buildAuthUrl(e,t){const r=new URL("/auth/google",e);return r.searchParams.set("callback",t),r.toString()}async function startGoogleSignIn({apiBase:e,host:t="127.0.0.1",timeoutMs:r=3e5,surface:n="terminal"}={}){if(!e)throw new Error("startGoogleSignIn requires apiBase");let a,o,s=!1;const i=new Promise(((e,t)=>{a=e,o=t})),u=http.createServer(((e,r)=>{let i;try{i=new URL(e.url,`http://${t}`)}catch{return void r.writeHead(400).end()}const l=i.searchParams.get("token"),c=i.searchParams.get("username"),m=i.searchParams.get("memory_token"),d=i.searchParams.get("error");l||d?(r.writeHead(200,{"Content-Type":"text/html; charset=utf-8"}),r.end(page({ok:Boolean(l),error:d,username:c,surface:n})),s||(s=!0,clearTimeout(h),u.close(),l?a({apiKey:l,username:c||null,memoryToken:m||null}):o(new Error(d||"no token was returned")))):r.writeHead(404).end()}));await new Promise(((e,r)=>{u.once("error",r),u.listen(0,t,e)}));const{port:l}=u.address(),c=buildAuthUrl(e,`http://${t}:${l}`),h=setTimeout((()=>{s||(s=!0,u.close(),o(new Error(`timed out after ${Math.round(r/1e3)}s waiting for the browser sign-in`)))}),r);return"function"==typeof h.unref&&h.unref(),{url:c,wait:()=>i}}module.exports={startGoogleSignIn:startGoogleSignIn,buildAuthUrl:buildAuthUrl};
@@ -1,432 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * hooks.js — the hook layer every host shares (CLI `/hooks`, the desktop's
10
- * `hooks` tool, and `aegiscode gate install-hooks`).
11
- *
12
- * Two halves live here, and they are deliberately in ONE file because they are
13
- * the same question asked twice:
14
- *
15
- * 1. **Config hooks** — what `settings.json` says should run at
16
- * PreToolUse/PostToolUse/…. Both hosts must read the same five files in
17
- * the same order and count the same things, or the two hosts report
18
- * different worlds for one machine. Before this file, the CLI had a
19
- * private `readHooks()` in `src/commands.js` and the desktop had nothing
20
- * at all.
21
- *
22
- * 2. **Repo guard hooks** — this repository's own `.githooks/` (the agent-key
23
- * gate, the secret scan, the invariant lock). Installing them was a
24
- * *printed suggestion*, never an action: `agent-gate.mjs install-hooks`
25
- * chmod'ed two files and told the user to run `git config` themselves, and
26
- * `init --hooks` ended with the same "finish: git config …" line. On every
27
- * platform that means a fresh clone has NO hooks — the documented failure
28
- * in `.githooks/lib-gate.sh`'s own header. `installRepoHooks()` below does
29
- * the install.
30
- *
31
- * ## Cross-platform, and provably so
32
- *
33
- * This is the part the previous implementations got wrong, so it is stated
34
- * plainly:
35
- *
36
- * · **Paths** are joined with `path.win32` when `platform === 'win32'` and
37
- * `path.posix` otherwise. `path.join` would use the HOST's separator, which
38
- * means the Windows branch could only ever be exercised on Windows — and a
39
- * branch no test can reach is a claim, not a feature. The injected
40
- * `platform` is what makes `C:\Users\me\.aegis\settings.json` testable from
41
- * Linux.
42
- * · **`chmod(0o755)` is POSIX-only.** On Windows the mode bits are not
43
- * enforced, so a `chmodSync` there is a silent no-op that reads as
44
- * protection. We do it only where it means something and say so where it
45
- * does not. (Git for Windows runs hooks with its own bundled `sh`, so the
46
- * `#!/bin/sh` hooks DO run there — the exec bit is simply not the mechanism.)
47
- * · **Nothing shells out to `sh`.** `git` is invoked as an argv array through
48
- * `execFile`, never through a shell string, so a path or a repo with a space
49
- * cannot become a different command.
50
- * · **`$HOME` is not trusted.** `home` resolves from an explicit override,
51
- * then `USERPROFILE` (Windows), then `HOME` (POSIX), then `os.homedir()`.
52
- *
53
- * Every entry point takes an options object — `{ platform, env, home, cwd,
54
- * readFile, exists, runGit, chmod }` — defaulting to the real environment, so
55
- * each branch is exercisable on this host instead of only on the OS it targets.
56
- *
57
- * Zero dependencies beyond `node:` builtins, because this file is staged into
58
- * both vendor trees (see `cli/scripts/predist.mjs`, `desktop/scripts/predist.mjs`)
59
- * and must load inside a packaged ASAR and a globally installed npm package.
60
- */
61
-
62
- const fs = require('node:fs');
63
- const os = require('node:os');
64
- const path = require('node:path');
65
- const { execFileSync } = require('node:child_process');
66
-
67
- /** The settings directories both hosts read, most-authoritative last. */
68
- const SETTINGS_DIRS = ['.aegis', '.aegiscode'];
69
-
70
- /**
71
- * The settings files, in merge order (later wins for a given event).
72
- * `.claude` is last and is reported as FOREIGN rather than treated as ours —
73
- * see `hookSourceKind`.
74
- */
75
- function hookSettingPaths(opts = {}) {
76
- const p = platformPath(opts.platform);
77
- const home = homeDir(opts);
78
- const cwd = opts.cwd || process.cwd();
79
- const out = [];
80
- for (const dir of SETTINGS_DIRS) {
81
- out.push(p.join(home, dir, 'settings.json'));
82
- out.push(p.join(cwd, dir, 'settings.json'));
83
- }
84
- out.push(p.join(home, '.claude', 'settings.json'));
85
- return dedupe(out);
86
- }
87
-
88
- /** `path.win32` for a win32 host, `path.posix` otherwise — see the header. */
89
- function platformPath(platform) {
90
- return (platform || process.platform) === 'win32' ? path.win32 : path.posix;
91
- }
92
-
93
- /** Explicit home → USERPROFILE (win32) → HOME (posix) → os.homedir(). */
94
- function homeDir(opts = {}) {
95
- if (opts.home) return String(opts.home);
96
- const env = opts.env || process.env;
97
- const platform = opts.platform || process.platform;
98
- const keys = platform === 'win32' ? ['USERPROFILE', 'HOME'] : ['HOME', 'USERPROFILE'];
99
- for (const k of keys) if (env && env[k]) return String(env[k]);
100
- return os.homedir();
101
- }
102
-
103
- /** 'aegis' (our own trees), 'foreign' (`.claude`, another vendor's), 'other'. */
104
- function hookSourceKind(p) {
105
- const dir = path.posix.basename(String(p).replace(/\\/g, '/'));
106
- const parent = path.posix.basename(path.posix.dirname(String(p).replace(/\\/g, '/')));
107
- if (dir !== 'settings.json') return 'other';
108
- if (parent === '.claude') return 'foreign';
109
- if (SETTINGS_DIRS.includes(parent)) return 'aegis';
110
- return 'other';
111
- }
112
-
113
- function dedupe(list) {
114
- const seen = new Set();
115
- const out = [];
116
- for (const item of list) {
117
- const key = String(item).replace(/\\/g, '/');
118
- if (seen.has(key)) continue;
119
- seen.add(key);
120
- out.push(item);
121
- }
122
- return out;
123
- }
124
-
125
- /** `~`-shorten for display, on either separator. */
126
- function shorten(p, opts = {}) {
127
- const home = homeDir(opts);
128
- const s = String(p);
129
- if (!home) return s;
130
- const posix = s.replace(/\\/g, '/');
131
- const h = String(home).replace(/\\/g, '/').replace(/\/+$/, '');
132
- if (posix === h) return '~';
133
- if (posix.startsWith(`${h}/`)) return `~${posix.slice(h.length)}`;
134
- return s;
135
- }
136
-
137
- /**
138
- * Read and merge hook config from the standard settings files.
139
- *
140
- * Merge rule, preserved from this CLI's shipped behaviour: matching hooks from
141
- * every settings file are CONCATENATED per event, in file order. That is what
142
- * actually happens — a hook host runs every matching hook it was configured
143
- * with, it does not let a project file delete the user's hook — so `hooks` is
144
- * the number of hooks that will run, not the number of files that mention one.
145
- * `from` lists every contributing file, `foreign` every `.claude` file seen, so
146
- * a machine where another vendor's hooks are among what runs is visible instead
147
- * of invisible.
148
- *
149
- * @returns {{hooks: object, from: string[], foreign: string[], files: Array}}
150
- */
151
- function readHookConfig(opts = {}) {
152
- const readFile = opts.readFile || defaultReadFile;
153
- const paths = opts.paths || hookSettingPaths(opts);
154
- const hooks = {};
155
- const from = [];
156
- const foreign = [];
157
- const files = [];
158
- for (const file of paths) {
159
- let text = null;
160
- try { text = readFile(file); } catch { text = null; }
161
- if (text === null || text === undefined) { files.push({ path: file, exists: false, kind: hookSourceKind(file) }); continue; }
162
- let json;
163
- try { json = JSON.parse(String(text)); } catch { files.push({ path: file, exists: true, parsed: false, kind: hookSourceKind(file) }); continue; }
164
- const kind = hookSourceKind(file);
165
- const events = eventsOf(json);
166
- const names = Object.keys(events);
167
- files.push({ path: file, exists: true, parsed: true, kind, events: names });
168
- // A foreign file is reported, not merged — so it must not appear in `from`,
169
- // which means "the files ÆGIS reads as its own policy". Listing it there
170
- // (with no marker) is how the status panel came to imply that another
171
- // vendor's hooks were ours. `files[]` carries the full picture; `foreign`
172
- // names them explicitly.
173
- if (kind === 'foreign') {
174
- foreign.push(shorten(file, opts));
175
- continue;
176
- }
177
- if (!names.length) continue;
178
- from.push(shorten(file, opts));
179
- for (const [event, arr] of Object.entries(events)) {
180
- if (!Array.isArray(arr) || !arr.length) continue;
181
- hooks[event] = [...(hooks[event] || []), ...arr];
182
- }
183
- }
184
- return { hooks, from, foreign, files };
185
- }
186
-
187
- /** The `hooks` object of a settings document (either layout), never throws. */
188
- function eventsOf(json) {
189
- if (!json || typeof json !== 'object') return {};
190
- if (json.hooks && typeof json.hooks === 'object' && !Array.isArray(json.hooks)) {
191
- const out = {};
192
- for (const [k, v] of Object.entries(json.hooks)) if (Array.isArray(v)) out[k] = v;
193
- return out;
194
- }
195
- const out = {};
196
- for (const event of HOOK_EVENTS) if (Array.isArray(json[event])) out[event] = json[event];
197
- return out;
198
- }
199
-
200
- /** The events the Claude Code host tracks. */
201
- const HOOK_EVENTS = [
202
- 'PreToolUse', 'PostToolUse', 'PostToolUseFailure', 'PermissionRequest',
203
- 'UserPromptSubmit', 'SessionStart', 'SessionEnd', 'Stop', 'SubagentStop',
204
- 'Notification', 'Compaction',
205
- ];
206
-
207
- /**
208
- * `{enabled, hooks, events, byEvent}` from a merged hooks map.
209
- *
210
- * `hooks` counts MATCHER entries (one `{name, matcher, hooks}` object = one),
211
- * which is the number the CLI's `/hooks status` has always shown. Counting the
212
- * nested `hooks[]` array instead — a different, also-defensible number — is how
213
- * two hosts end up disagreeing about one machine; there is one number here.
214
- */
215
- function hookStats(hooks) {
216
- const map = hooks && typeof hooks === 'object' ? hooks : {};
217
- const events = Object.keys(map);
218
- let count = 0;
219
- const byEvent = {};
220
- for (const ev of events) {
221
- const arr = Array.isArray(map[ev]) ? map[ev] : [];
222
- byEvent[ev] = arr.length;
223
- count += arr.length;
224
- }
225
- return { enabled: count > 0, hooks: count, events, byEvent };
226
- }
227
-
228
- // ── the repo's own guard hooks (.githooks/) ─────────────────────────────────
229
-
230
- /** Files `.githooks/` is expected to carry; the first two are required. */
231
- const REQUIRED_HOOKS = ['pre-commit', 'pre-push'];
232
- const OPTIONAL_HOOKS = ['post-merge', 'lib-gate.sh', 'push-policy'];
233
-
234
- /**
235
- * The default git runner: argv array, no shell, cwd pinned.
236
- * @returns {{ok: boolean, out: string, err: string}}
237
- */
238
- function defaultRunGit(args, { cwd, env } = {}) {
239
- try {
240
- const out = execFileSync('git', args, {
241
- cwd, env: env || process.env, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'],
242
- windowsHide: true,
243
- });
244
- return { ok: true, out: String(out).trim(), err: '' };
245
- } catch (e) {
246
- return { ok: false, out: String(e && e.stdout ? e.stdout : '').trim(), err: String(e && e.stderr ? e.stderr : (e && e.message) || e).trim() };
247
- }
248
- }
249
-
250
- function defaultReadFile(file) { return fs.readFileSync(file, 'utf8'); }
251
- function defaultExists(file) { try { return fs.statSync(file).isFile(); } catch { return false; } }
252
- function defaultChmod(file) { fs.chmodSync(file, 0o755); }
253
-
254
- /**
255
- * What state the repo's guard hooks are in — read-only, never throws.
256
- *
257
- * @returns {{repo, hooksDir, inGitRepo, configured, wanted, installed,
258
- * present: string[], missing: string[], gitVersion, platform,
259
- * execBit, execNote}}
260
- */
261
- function repoHookStatus(opts = {}) {
262
- const platform = opts.platform || process.platform;
263
- const p = platformPath(platform);
264
- const cwd = opts.cwd || process.cwd();
265
- const exists = opts.exists || defaultExists;
266
- const runGit = opts.runGit || defaultRunGit;
267
-
268
- const hooksDir = p.join(cwd, '.githooks');
269
- const present = [];
270
- const missing = [];
271
- for (const name of [...REQUIRED_HOOKS, ...OPTIONAL_HOOKS]) {
272
- if (exists(p.join(hooksDir, name))) present.push(name);
273
- else missing.push(name);
274
- }
275
-
276
- const inside = runGit(['rev-parse', '--is-inside-work-tree'], { cwd, env: opts.env });
277
- const inGitRepo = inside.ok && inside.out === 'true';
278
- let configured = null;
279
- if (inGitRepo) {
280
- const got = runGit(['config', '--get', 'core.hooksPath'], { cwd, env: opts.env });
281
- // Exit 1 with no output means "not set" — that is a value, not a failure.
282
- configured = got.ok && got.out ? got.out : null;
283
- }
284
-
285
- // git resolves core.hooksPath relative to the repo root; compare normalized.
286
- const wanted = '.githooks';
287
- const norm = (v) => (v === null || v === undefined ? null : String(v).replace(/\\/g, '/').replace(/\/+$/, ''));
288
- const installed = inGitRepo && norm(configured) === wanted;
289
-
290
- return {
291
- repo: cwd,
292
- hooksDir,
293
- platform,
294
- inGitRepo,
295
- configured,
296
- wanted,
297
- installed,
298
- present,
299
- missing,
300
- execBit: platform !== 'win32',
301
- execNote: platform === 'win32'
302
- ? 'Windows: the exec bit is not enforced and not needed — git for Windows runs hooks with its bundled sh.'
303
- : 'POSIX: the hooks are chmod 0755 so git can execute them.',
304
- };
305
- }
306
-
307
- /**
308
- * INSTALL the repo's guard hooks: point `core.hooksPath` at `.githooks/` and
309
- * make them executable.
310
- *
311
- * This is the action `agent-gate.mjs install-hooks` only ever described. It is
312
- * idempotent (a second call reports `changed: false`), it verifies the write by
313
- * reading the config back, and `dryRun` returns the exact commands without
314
- * touching anything — the shape `--dry-run` must have before a user lets an
315
- * agent near their git config.
316
- *
317
- * @returns {{ok, changed, code, actions: string[], status, error?}}
318
- */
319
- function installRepoHooks(opts = {}) {
320
- const platform = opts.platform || process.platform;
321
- const p = platformPath(platform);
322
- const cwd = opts.cwd || process.cwd();
323
- const runGit = opts.runGit || defaultRunGit;
324
- const exists = opts.exists || defaultExists;
325
- const chmod = opts.chmod || defaultChmod;
326
- const dryRun = Boolean(opts.dryRun);
327
-
328
- const status = repoHookStatus({ ...opts, platform, cwd, runGit, exists });
329
- const actions = [];
330
- const done = (extra) => ({ ok: true, changed: actions.length > 0, code: 'installed', actions, status, ...extra });
331
-
332
- if (!exists(p.join(status.hooksDir, 'pre-commit'))) {
333
- return {
334
- ok: false, changed: false, code: 'no-hooks', actions, status,
335
- error: `no ${status.wanted}/pre-commit under ${cwd} — nothing to install. ` +
336
- 'A tree that never had the hooks needs them restored (`git checkout -- .githooks/`) ' +
337
- 'or created (`agent-gate.mjs init --hooks`).',
338
- };
339
- }
340
- if (!status.inGitRepo) {
341
- return {
342
- ok: false, changed: false, code: 'no-git', actions, status,
343
- error: `${cwd} is not inside a git work tree (core.hooksPath is a per-repo setting), ` +
344
- 'or git is not on PATH.',
345
- };
346
- }
347
-
348
- if (!status.installed) {
349
- actions.push(`git -C ${cwd} config core.hooksPath ${status.wanted}`);
350
- if (!dryRun) {
351
- const res = runGit(['config', 'core.hooksPath', status.wanted], { cwd, env: opts.env });
352
- if (!res.ok) {
353
- return { ok: false, changed: false, code: 'git-failed', actions, status, error: `git config refused: ${res.err || 'unknown error'}` };
354
- }
355
- const readback = runGit(['config', '--get', 'core.hooksPath'], { cwd, env: opts.env });
356
- const got = readback.ok ? String(readback.out).replace(/\\/g, '/').replace(/\/+$/, '') : null;
357
- if (got !== status.wanted) {
358
- // Report it rather than assume it — a config write that did not take
359
- // is exactly the failure the old print-only version could not see.
360
- return { ok: false, changed: true, code: 'verify-failed', actions, status, error: `core.hooksPath reads back as "${got || '(unset)'}", not "${status.wanted}"` };
361
- }
362
- }
363
- }
364
-
365
- // The exec bit: meaningful only where git actually reads it. On Windows we
366
- // say so instead of pretending a no-op chmod did something.
367
- //
368
- // The mode is READ first and only written when it differs. Chmod-ing every
369
- // hook on every run made `changed` come back true for a tree that was already
370
- // installed — an idempotency claim that was simply false, and the reason
371
- // `install` could never report "already installed" honestly.
372
- const modes = [];
373
- if (platform !== 'win32') {
374
- const modeOf = opts.modeOf || ((file) => { try { return fs.statSync(file).mode & 0o777; } catch { return null; } });
375
- for (const name of status.present.filter((n) => n !== 'push-policy')) {
376
- const file = p.join(status.hooksDir, name);
377
- if (modeOf(file) === 0o755) continue; // already executable — nothing to change
378
- if (dryRun) { modes.push(`chmod 0755 ${file}`); continue; }
379
- try { chmod(file, 0o755); modes.push(`chmod 0755 ${name}`); } catch (e) {
380
- modes.push(`chmod 0755 ${name} FAILED: ${(e && e.message) || e}`);
381
- }
382
- }
383
- actions.push(...modes);
384
- }
385
- return done({ modes, note: status.execNote });
386
- }
387
-
388
- /**
389
- * One plain-text report of both halves, for the desktop's `hooks` tool (the CLI
390
- * renders its own themed panel from the same numbers). Same facts in both
391
- * places, so the GUI and the terminal cannot describe one machine differently.
392
- */
393
- function hooksSummary(opts = {}) {
394
- const platform = opts.platform || process.platform;
395
- const config = opts.config || readHookConfig({ ...opts, platform });
396
- const stats = opts.stats || hookStats(config.hooks);
397
- const repo = opts.repo || repoHookStatus({ ...opts, platform });
398
- const lines = [];
399
- lines.push(`hooks: ${stats.enabled ? 'enabled' : 'disabled'} · ${stats.hooks} matcher(s) in ${stats.events.length} event(s)`);
400
- if (stats.events.length) {
401
- for (const ev of stats.events) lines.push(` ${ev}: ${stats.byEvent[ev]}`);
402
- } else {
403
- lines.push(' (no settings.json declares hooks — checked ' + hookSettingPaths({ ...opts, platform }).map((f) => shorten(f, opts)).join(', ') + ')');
404
- }
405
- if (config.from.length) lines.push(` from: ${config.from.join(', ')}`);
406
- if (config.foreign && config.foreign.length) {
407
- lines.push(` foreign host files (read, listed—${stats.hooks && config.foreign.length ? 'may outrank ours' : 'no hooks'}): ${config.foreign.join(', ')}`);
408
- }
409
- lines.push('');
410
- lines.push(`repo guard hooks (${repo.wanted}/): ${repo.present.length ? repo.present.join(', ') : 'none found'}`);
411
- if (repo.missing.length) lines.push(` missing: ${repo.missing.join(', ')}`);
412
- lines.push(` core.hooksPath: ${repo.installed ? `${repo.wanted} (installed)` : `${repo.configured || '(unset)'} — NOT installed, so a commit runs NO guard hooks`}`);
413
- lines.push(` ${repo.execNote}`);
414
- return lines.join('\n');
415
- }
416
-
417
- module.exports = {
418
- HOOK_EVENTS,
419
- SETTINGS_DIRS,
420
- hooksSummary,
421
- REQUIRED_HOOKS,
422
- OPTIONAL_HOOKS,
423
- hookSettingPaths,
424
- hookSourceKind,
425
- homeDir,
426
- platformPath,
427
- shorten,
428
- readHookConfig,
429
- hookStats,
430
- repoHookStatus,
431
- installRepoHooks,
432
- };
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{execFileSync:execFileSync}=require("node:child_process"),SETTINGS_DIRS=[".aegis",".aegiscode"];function hookSettingPaths(o={}){const e=platformPath(o.platform),t=homeDir(o),n=o.cwd||process.cwd(),s=[];for(const o of SETTINGS_DIRS)s.push(e.join(t,o,"settings.json")),s.push(e.join(n,o,"settings.json"));return s.push(e.join(t,".claude","settings.json")),dedupe(s)}function platformPath(o){return"win32"===(o||process.platform)?path.win32:path.posix}function homeDir(o={}){if(o.home)return String(o.home);const e=o.env||process.env,t="win32"===(o.platform||process.platform)?["USERPROFILE","HOME"]:["HOME","USERPROFILE"];for(const o of t)if(e&&e[o])return String(e[o]);return os.homedir()}function hookSourceKind(o){const e=path.posix.basename(String(o).replace(/\\/g,"/")),t=path.posix.basename(path.posix.dirname(String(o).replace(/\\/g,"/")));return"settings.json"!==e?"other":".claude"===t?"foreign":SETTINGS_DIRS.includes(t)?"aegis":"other"}function dedupe(o){const e=new Set,t=[];for(const n of o){const o=String(n).replace(/\\/g,"/");e.has(o)||(e.add(o),t.push(n))}return t}function shorten(o,e={}){const t=homeDir(e),n=String(o);if(!t)return n;const s=n.replace(/\\/g,"/"),r=String(t).replace(/\\/g,"/").replace(/\/+$/,"");return s===r?"~":s.startsWith(`${r}/`)?`~${s.slice(r.length)}`:n}function readHookConfig(o={}){const e=o.readFile||defaultReadFile,t=o.paths||hookSettingPaths(o),n={},s=[],r=[],i=[];for(const a of t){let t,c=null;try{c=e(a)}catch{c=null}if(null==c){i.push({path:a,exists:!1,kind:hookSourceKind(a)});continue}try{t=JSON.parse(String(c))}catch{i.push({path:a,exists:!0,parsed:!1,kind:hookSourceKind(a)});continue}const h=hookSourceKind(a),u=eventsOf(t),d=Object.keys(u);if(i.push({path:a,exists:!0,parsed:!0,kind:h,events:d}),"foreign"!==h){if(d.length){s.push(shorten(a,o));for(const[o,e]of Object.entries(u))Array.isArray(e)&&e.length&&(n[o]=[...n[o]||[],...e])}}else r.push(shorten(a,o))}return{hooks:n,from:s,foreign:r,files:i}}function eventsOf(o){if(!o||"object"!=typeof o)return{};if(o.hooks&&"object"==typeof o.hooks&&!Array.isArray(o.hooks)){const e={};for(const[t,n]of Object.entries(o.hooks))Array.isArray(n)&&(e[t]=n);return e}const e={};for(const t of HOOK_EVENTS)Array.isArray(o[t])&&(e[t]=o[t]);return e}const HOOK_EVENTS=["PreToolUse","PostToolUse","PostToolUseFailure","PermissionRequest","UserPromptSubmit","SessionStart","SessionEnd","Stop","SubagentStop","Notification","Compaction"];function hookStats(o){const e=o&&"object"==typeof o?o:{},t=Object.keys(e);let n=0;const s={};for(const o of t){const t=Array.isArray(e[o])?e[o]:[];s[o]=t.length,n+=t.length}return{enabled:n>0,hooks:n,events:t,byEvent:s}}const REQUIRED_HOOKS=["pre-commit","pre-push"],OPTIONAL_HOOKS=["post-merge","lib-gate.sh","push-policy"];function defaultRunGit(o,{cwd:e,env:t}={}){try{const n=execFileSync("git",o,{cwd:e,env:t||process.env,encoding:"utf8",stdio:["ignore","pipe","pipe"],windowsHide:!0});return{ok:!0,out:String(n).trim(),err:""}}catch(o){return{ok:!1,out:String(o&&o.stdout?o.stdout:"").trim(),err:String(o&&o.stderr?o.stderr:o&&o.message||o).trim()}}}function defaultReadFile(o){return fs.readFileSync(o,"utf8")}function defaultExists(o){try{return fs.statSync(o).isFile()}catch{return!1}}function defaultChmod(o){fs.chmodSync(o,493)}function repoHookStatus(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.exists||defaultExists,r=o.runGit||defaultRunGit,i=t.join(n,".githooks"),a=[],c=[];for(const o of[...REQUIRED_HOOKS,...OPTIONAL_HOOKS])s(t.join(i,o))?a.push(o):c.push(o);const h=r(["rev-parse","--is-inside-work-tree"],{cwd:n,env:o.env}),u=h.ok&&"true"===h.out;let d=null;if(u){const e=r(["config","--get","core.hooksPath"],{cwd:n,env:o.env});d=e.ok&&e.out?e.out:null}const f=".githooks";var l;return{repo:n,hooksDir:i,platform:e,inGitRepo:u,configured:d,wanted:f,installed:u&&(null==(l=d)?null:String(l).replace(/\\/g,"/").replace(/\/+$/,""))===f,present:a,missing:c,execBit:"win32"!==e,execNote:"win32"===e?"Windows: the exec bit is not enforced and not needed — git for Windows runs hooks with its bundled sh.":"POSIX: the hooks are chmod 0755 so git can execute them."}}function installRepoHooks(o={}){const e=o.platform||process.platform,t=platformPath(e),n=o.cwd||process.cwd(),s=o.runGit||defaultRunGit,r=o.exists||defaultExists,i=o.chmod||defaultChmod,a=Boolean(o.dryRun),c=repoHookStatus({...o,platform:e,cwd:n,runGit:s,exists:r}),h=[];if(!r(t.join(c.hooksDir,"pre-commit")))return{ok:!1,changed:!1,code:"no-hooks",actions:h,status:c,error:`no ${c.wanted}/pre-commit under ${n} — nothing to install. A tree that never had the hooks needs them restored (\`git checkout -- .githooks/\`) or created (\`agent-gate.mjs init --hooks\`).`};if(!c.inGitRepo)return{ok:!1,changed:!1,code:"no-git",actions:h,status:c,error:`${n} is not inside a git work tree (core.hooksPath is a per-repo setting), or git is not on PATH.`};if(!c.installed&&(h.push(`git -C ${n} config core.hooksPath ${c.wanted}`),!a)){const e=s(["config","core.hooksPath",c.wanted],{cwd:n,env:o.env});if(!e.ok)return{ok:!1,changed:!1,code:"git-failed",actions:h,status:c,error:`git config refused: ${e.err||"unknown error"}`};const t=s(["config","--get","core.hooksPath"],{cwd:n,env:o.env}),r=t.ok?String(t.out).replace(/\\/g,"/").replace(/\/+$/,""):null;if(r!==c.wanted)return{ok:!1,changed:!0,code:"verify-failed",actions:h,status:c,error:`core.hooksPath reads back as "${r||"(unset)"}", not "${c.wanted}"`}}const u=[];if("win32"!==e){const e=o.modeOf||(o=>{try{return 511&fs.statSync(o).mode}catch{return null}});for(const o of c.present.filter((o=>"push-policy"!==o))){const n=t.join(c.hooksDir,o);if(493!==e(n))if(a)u.push(`chmod 0755 ${n}`);else try{i(n,493),u.push(`chmod 0755 ${o}`)}catch(e){u.push(`chmod 0755 ${o} FAILED: ${e&&e.message||e}`)}}h.push(...u)}return d={modes:u,note:c.execNote},{ok:!0,changed:h.length>0,code:"installed",actions:h,status:c,...d};var d}function hooksSummary(o={}){const e=o.platform||process.platform,t=o.config||readHookConfig({...o,platform:e}),n=o.stats||hookStats(t.hooks),s=o.repo||repoHookStatus({...o,platform:e}),r=[];if(r.push(`hooks: ${n.enabled?"enabled":"disabled"} · ${n.hooks} matcher(s) in ${n.events.length} event(s)`),n.events.length)for(const o of n.events)r.push(` ${o}: ${n.byEvent[o]}`);else r.push(" (no settings.json declares hooks — checked "+hookSettingPaths({...o,platform:e}).map((e=>shorten(e,o))).join(", ")+")");return t.from.length&&r.push(` from: ${t.from.join(", ")}`),t.foreign&&t.foreign.length&&r.push(` foreign host files (read, listed—${n.hooks&&t.foreign.length?"may outrank ours":"no hooks"}): ${t.foreign.join(", ")}`),r.push(""),r.push(`repo guard hooks (${s.wanted}/): ${s.present.length?s.present.join(", "):"none found"}`),s.missing.length&&r.push(` missing: ${s.missing.join(", ")}`),r.push(" core.hooksPath: "+(s.installed?`${s.wanted} (installed)`:`${s.configured||"(unset)"} — NOT installed, so a commit runs NO guard hooks`)),r.push(` ${s.execNote}`),r.join("\n")}module.exports={HOOK_EVENTS:HOOK_EVENTS,SETTINGS_DIRS:SETTINGS_DIRS,hooksSummary:hooksSummary,REQUIRED_HOOKS:REQUIRED_HOOKS,OPTIONAL_HOOKS:OPTIONAL_HOOKS,hookSettingPaths:hookSettingPaths,hookSourceKind:hookSourceKind,homeDir:homeDir,platformPath:platformPath,shorten:shorten,readHookConfig:readHookConfig,hookStats:hookStats,repoHookStatus:repoHookStatus,installRepoHooks:installRepoHooks};