aegisone 1.0.22 → 1.0.24

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 (226) hide show
  1. package/LICENSE +661 -0
  2. package/README.md +1 -1
  3. package/SOURCE-OFFER.txt +9 -0
  4. package/bin/aegis.js +1 -322
  5. package/package.json +4 -5
  6. package/scripts/bump.mjs +1 -211
  7. package/scripts/bundle.js +1 -129
  8. package/scripts/predist.mjs +1 -939
  9. package/src/child.js +1 -285
  10. package/src/dispatch.js +1 -269
  11. package/src/doctor.js +1 -639
  12. package/src/host.js +1 -111
  13. package/src/permissions.js +1 -369
  14. package/src/probes.js +1 -159
  15. package/src/release.js +1 -409
  16. package/vendor/cli/bin/aegiscode.js +2 -914
  17. package/vendor/cli/package.json +3 -7
  18. package/vendor/cli/scripts/check.mjs +1 -52
  19. package/vendor/cli/scripts/demo.mjs +1 -94
  20. package/vendor/cli/scripts/predist.mjs +1 -75
  21. package/vendor/cli/scripts/runtests.mjs +1 -56
  22. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  23. package/vendor/cli/src/agents.js +1 -139
  24. package/vendor/cli/src/app.js +1 -2932
  25. package/vendor/cli/src/art.js +1 -289
  26. package/vendor/cli/src/autonomous.js +1 -515
  27. package/vendor/cli/src/caps.js +1 -879
  28. package/vendor/cli/src/chatflow.js +1 -3020
  29. package/vendor/cli/src/checkpoint.js +1 -90
  30. package/vendor/cli/src/clipboard.js +1 -424
  31. package/vendor/cli/src/cloudsync.js +1 -528
  32. package/vendor/cli/src/commands.js +1 -4003
  33. package/vendor/cli/src/config.js +1 -581
  34. package/vendor/cli/src/connect.js +1 -349
  35. package/vendor/cli/src/credentials.js +1 -33
  36. package/vendor/cli/src/deps.js +1 -232
  37. package/vendor/cli/src/devrun.js +1 -187
  38. package/vendor/cli/src/diff.js +1 -333
  39. package/vendor/cli/src/diffview.js +1 -296
  40. package/vendor/cli/src/engine.js +1 -297
  41. package/vendor/cli/src/entitlement.js +1 -355
  42. package/vendor/cli/src/events.js +1 -707
  43. package/vendor/cli/src/export.js +1 -67
  44. package/vendor/cli/src/fingerprint.js +1 -592
  45. package/vendor/cli/src/format.js +1 -259
  46. package/vendor/cli/src/fuzzy.js +1 -119
  47. package/vendor/cli/src/gate.js +1 -55
  48. package/vendor/cli/src/history.js +1 -401
  49. package/vendor/cli/src/init.js +1 -175
  50. package/vendor/cli/src/input.js +1 -139
  51. package/vendor/cli/src/keys.js +1 -183
  52. package/vendor/cli/src/limits.js +1 -190
  53. package/vendor/cli/src/markdown.js +1 -306
  54. package/vendor/cli/src/mcp.js +1 -694
  55. package/vendor/cli/src/models.js +1 -487
  56. package/vendor/cli/src/naming.js +1 -229
  57. package/vendor/cli/src/overlays.js +1 -461
  58. package/vendor/cli/src/panels.js +1 -1418
  59. package/vendor/cli/src/permissions.js +1 -290
  60. package/vendor/cli/src/ping.js +1 -226
  61. package/vendor/cli/src/presence.js +1 -238
  62. package/vendor/cli/src/provenance.js +2 -182
  63. package/vendor/cli/src/render.js +1 -515
  64. package/vendor/cli/src/screen.js +1 -518
  65. package/vendor/cli/src/screens.js +1 -896
  66. package/vendor/cli/src/secret.js +1 -59
  67. package/vendor/cli/src/securefs.js +1 -359
  68. package/vendor/cli/src/settings.js +1 -155
  69. package/vendor/cli/src/shared.js +1 -52
  70. package/vendor/cli/src/sharedpaths.js +1 -53
  71. package/vendor/cli/src/signup.js +1 -156
  72. package/vendor/cli/src/summarize.js +1 -95
  73. package/vendor/cli/src/sysdiag.js +1 -585
  74. package/vendor/cli/src/system.js +1 -40
  75. package/vendor/cli/src/theme.js +1 -570
  76. package/vendor/cli/src/title.js +1 -220
  77. package/vendor/cli/src/todos.js +1 -115
  78. package/vendor/cli/src/tokens.js +1 -263
  79. package/vendor/cli/src/topup.js +1 -210
  80. package/vendor/cli/src/update.js +1 -181
  81. package/vendor/cli/vendor/client/aegis.js +1 -2179
  82. package/vendor/cli/vendor/client/attest.js +1 -442
  83. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  84. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  85. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  86. package/vendor/cli/vendor/client/byok-catalog.js +1 -230
  87. package/vendor/cli/vendor/client/credentials.js +1 -494
  88. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  89. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  90. package/vendor/cli/vendor/client/drive-upload.js +1 -174
  91. package/vendor/cli/vendor/client/env-file.js +1 -1273
  92. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  93. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  94. package/vendor/cli/vendor/client/google-signin.js +1 -133
  95. package/vendor/cli/vendor/client/hooks.js +1 -430
  96. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  97. package/vendor/cli/vendor/client/platform.js +1 -937
  98. package/vendor/cli/vendor/client/prefs.js +1 -351
  99. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  100. package/vendor/cli/vendor/client/presence.js +1 -438
  101. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  102. package/vendor/cli/vendor/client/session-store.js +1 -548
  103. package/vendor/cli/vendor/client/topup.js +1 -297
  104. package/vendor/cli/vendor/client/touch.js +1 -458
  105. package/vendor/cli/vendor/client/update.js +1 -704
  106. package/vendor/cli/vendor/client/user-models.js +1 -381
  107. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  108. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  109. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -993
  110. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -95
  111. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3301
  112. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  113. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  114. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2135
  115. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -275
  116. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  117. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -208
  118. package/vendor/cli/vendor/desktop/lib/local/shell.js +1 -680
  119. package/vendor/cli/vendor/desktop/lib/local/tools.js +1 -1238
  120. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  121. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  122. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  123. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  124. package/vendor/cli/vendor/hosts/install.js +1 -638
  125. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  126. package/vendor/cli/vendor/hosts/spec.js +1 -164
  127. package/vendor/cli/vendor/hosts/targets.js +1 -346
  128. package/vendor/cli/vendor/mcp/server.js +1 -221
  129. package/vendor/cli/vendor/mcp/tools.js +1 -408
  130. package/vendor/cli/vendor/one/src/child.js +1 -285
  131. package/vendor/cli/vendor/one/src/permissions.js +1 -369
  132. package/vendor/desktop/bin/aegis.js +1 -32
  133. package/vendor/desktop/lib/account-key.js +1 -56
  134. package/vendor/desktop/lib/auto.js +1 -430
  135. package/vendor/desktop/lib/avatar/companion.js +1 -698
  136. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  137. package/vendor/desktop/lib/avatar/events.js +1 -344
  138. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  139. package/vendor/desktop/lib/avatar/holders.js +1 -612
  140. package/vendor/desktop/lib/avatar/identity.js +1 -641
  141. package/vendor/desktop/lib/avatar/level.js +1 -368
  142. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  143. package/vendor/desktop/lib/avatar/persona.js +1 -388
  144. package/vendor/desktop/lib/avatar/profile.js +1 -977
  145. package/vendor/desktop/lib/avatar/register.js +1 -307
  146. package/vendor/desktop/lib/avatar/store.js +1 -472
  147. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  148. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  149. package/vendor/desktop/lib/avatar/turn.js +1 -216
  150. package/vendor/desktop/lib/avatar/voice.js +1 -328
  151. package/vendor/desktop/lib/avatar/xp.js +1 -404
  152. package/vendor/desktop/lib/deep-link.js +1 -120
  153. package/vendor/desktop/lib/fingerprint.js +2 -347
  154. package/vendor/desktop/lib/google-connect.js +1 -227
  155. package/vendor/desktop/lib/local/agents.js +1 -105
  156. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  157. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  158. package/vendor/desktop/lib/local/context.js +1 -95
  159. package/vendor/desktop/lib/local/engine.js +1 -3301
  160. package/vendor/desktop/lib/local/entitlement.js +1 -660
  161. package/vendor/desktop/lib/local/git-scope.js +1 -228
  162. package/vendor/desktop/lib/local/local.js +1 -2135
  163. package/vendor/desktop/lib/local/prompt.js +1 -275
  164. package/vendor/desktop/lib/local/queue.js +1 -560
  165. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  166. package/vendor/desktop/lib/local/shell.js +1 -680
  167. package/vendor/desktop/lib/local/telemetry.js +1 -470
  168. package/vendor/desktop/lib/local/tools.js +1 -1238
  169. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  170. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  171. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  172. package/vendor/desktop/lib/quick-launcher.js +1 -84
  173. package/vendor/desktop/lib/settings.js +1 -890
  174. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  175. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  176. package/vendor/desktop/lib/sync/sessions.js +1 -106
  177. package/vendor/desktop/lib/window-state.js +1 -66
  178. package/vendor/desktop/main.js +1 -4529
  179. package/vendor/desktop/package.json +3 -5
  180. package/vendor/desktop/preload.js +1 -636
  181. package/vendor/desktop/renderer/app.js +1 -6660
  182. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  183. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  184. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  185. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  186. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  187. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  188. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  189. package/vendor/desktop/renderer/budget.js +1 -168
  190. package/vendor/desktop/renderer/companion.js +1 -223
  191. package/vendor/desktop/renderer/diff.js +1 -359
  192. package/vendor/desktop/renderer/diffview.js +1 -336
  193. package/vendor/desktop/renderer/fingerprint.js +3 -736
  194. package/vendor/desktop/renderer/markdown.js +1 -168
  195. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  196. package/vendor/desktop/renderer/providers.js +1 -259
  197. package/vendor/desktop/renderer/quick.js +1 -191
  198. package/vendor/desktop/renderer/stream-policy.js +1 -306
  199. package/vendor/desktop/renderer/transcript-view.js +1 -323
  200. package/vendor/desktop/renderer/usage.js +1 -1239
  201. package/vendor/desktop/vendor/aegis.js +1 -2179
  202. package/vendor/desktop/vendor/attest.js +1 -442
  203. package/vendor/desktop/vendor/authorship-key.js +1 -410
  204. package/vendor/desktop/vendor/auto-provision.js +1 -134
  205. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  206. package/vendor/desktop/vendor/byok-catalog.js +1 -230
  207. package/vendor/desktop/vendor/credentials.js +1 -494
  208. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  209. package/vendor/desktop/vendor/drive-connect.js +1 -110
  210. package/vendor/desktop/vendor/drive-upload.js +1 -174
  211. package/vendor/desktop/vendor/env-file.js +1 -1273
  212. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  213. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  214. package/vendor/desktop/vendor/google-signin.js +1 -133
  215. package/vendor/desktop/vendor/hooks.js +1 -430
  216. package/vendor/desktop/vendor/model-discovery.js +1 -373
  217. package/vendor/desktop/vendor/platform.js +1 -937
  218. package/vendor/desktop/vendor/prefs.js +1 -351
  219. package/vendor/desktop/vendor/presence-constants.js +1 -107
  220. package/vendor/desktop/vendor/presence.js +1 -438
  221. package/vendor/desktop/vendor/record-vault.js +3 -1055
  222. package/vendor/desktop/vendor/session-store.js +1 -548
  223. package/vendor/desktop/vendor/topup.js +1 -297
  224. package/vendor/desktop/vendor/touch.js +1 -458
  225. package/vendor/desktop/vendor/update.js +1 -704
  226. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -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 n=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 s=t.join(c.hooksDir,o);if(493!==n(s))if(a)u.push(`chmod 0755 ${s}`);else try{i(s,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};