aegisone 1.0.34 → 1.0.37

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 (372) 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 -976
  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/iface/paths.js +3 -0
  14. package/src/iface/pty.js +3 -0
  15. package/src/iface/update.js +3 -0
  16. package/src/iface/window.js +3 -0
  17. package/src/permissions.js +1 -383
  18. package/src/probes.js +1 -159
  19. package/src/protocol.js +3 -0
  20. package/src/release.js +1 -409
  21. package/src/selfhost.js +3 -0
  22. package/vendor/cli/package.json +3 -7
  23. package/vendor/cli/scripts/check.mjs +1 -52
  24. package/vendor/cli/scripts/demo.mjs +1 -94
  25. package/vendor/cli/scripts/predist.mjs +1 -75
  26. package/vendor/cli/scripts/runtests.mjs +1 -56
  27. package/vendor/cli/scripts/seal-gate.mjs +1 -74
  28. package/vendor/cli/src/agents.js +1 -139
  29. package/vendor/cli/src/app.js +1 -2957
  30. package/vendor/cli/src/art.js +1 -289
  31. package/vendor/cli/src/chatflow.js +1 -3023
  32. package/vendor/cli/src/checkpoint.js +1 -90
  33. package/vendor/cli/src/clipboard.js +1 -424
  34. package/vendor/cli/src/cloudsync.js +1 -528
  35. package/vendor/cli/src/commands.js +1 -4089
  36. package/vendor/cli/src/config.js +1 -581
  37. package/vendor/cli/src/connect.js +1 -349
  38. package/vendor/cli/src/credentials.js +1 -33
  39. package/vendor/cli/src/deps.js +1 -232
  40. package/vendor/cli/src/devrun.js +1 -187
  41. package/vendor/cli/src/diff.js +1 -333
  42. package/vendor/cli/src/diffview.js +1 -296
  43. package/vendor/cli/src/engine.js +1 -297
  44. package/vendor/cli/src/entitlement.js +1 -355
  45. package/vendor/cli/src/events.js +1 -707
  46. package/vendor/cli/src/export.js +1 -67
  47. package/vendor/cli/src/filepreview.js +1 -153
  48. package/vendor/cli/src/fingerprint.js +1 -592
  49. package/vendor/cli/src/format.js +1 -259
  50. package/vendor/cli/src/fuzzy.js +1 -119
  51. package/vendor/cli/src/history.js +1 -423
  52. package/vendor/cli/src/init.js +1 -175
  53. package/vendor/cli/src/input.js +1 -139
  54. package/vendor/cli/src/keys.js +1 -183
  55. package/vendor/cli/src/markdown.js +1 -306
  56. package/vendor/cli/src/models.js +1 -507
  57. package/vendor/cli/src/naming.js +1 -57
  58. package/vendor/cli/src/overlays.js +1 -462
  59. package/vendor/cli/src/panels.js +1 -1418
  60. package/vendor/cli/src/ping.js +1 -226
  61. package/vendor/cli/src/presence.js +1 -238
  62. package/vendor/cli/src/render.js +1 -516
  63. package/vendor/cli/src/screen.js +1 -518
  64. package/vendor/cli/src/screens.js +1 -896
  65. package/vendor/cli/src/secret.js +1 -59
  66. package/vendor/cli/src/securefs.js +1 -359
  67. package/vendor/cli/src/settings.js +1 -155
  68. package/vendor/cli/src/shared.js +1 -52
  69. package/vendor/cli/src/sharedpaths.js +1 -53
  70. package/vendor/cli/src/signup.js +1 -156
  71. package/vendor/cli/src/summarize.js +1 -95
  72. package/vendor/cli/src/sysdiag.js +1 -585
  73. package/vendor/cli/src/system.js +1 -40
  74. package/vendor/cli/src/theme.js +1 -570
  75. package/vendor/cli/src/title.js +1 -220
  76. package/vendor/cli/src/todos.js +1 -115
  77. package/vendor/cli/src/tokens.js +1 -263
  78. package/vendor/cli/src/topup.js +1 -210
  79. package/vendor/cli/src/update.js +1 -191
  80. package/vendor/cli/vendor/client/aegis.js +1 -2441
  81. package/vendor/cli/vendor/client/attest.js +1 -518
  82. package/vendor/cli/vendor/client/authorship-key.js +1 -410
  83. package/vendor/cli/vendor/client/auto-provision.js +1 -134
  84. package/vendor/cli/vendor/client/brain-catalog.js +1 -268
  85. package/vendor/cli/vendor/client/byok-catalog.js +1 -199
  86. package/vendor/cli/vendor/client/catalog-client.js +1 -487
  87. package/vendor/cli/vendor/client/conversation-export.js +1 -177
  88. package/vendor/cli/vendor/client/credentials.js +1 -494
  89. package/vendor/cli/vendor/client/device-fingerprint.js +1 -141
  90. package/vendor/cli/vendor/client/drive-connect.js +1 -110
  91. package/vendor/cli/vendor/client/drive-upload.js +1 -234
  92. package/vendor/cli/vendor/client/env-file.js +1 -1273
  93. package/vendor/cli/vendor/client/fingerprint.js +1 -1064
  94. package/vendor/cli/vendor/client/foreign-memory.js +1 -669
  95. package/vendor/cli/vendor/client/google-signin.js +1 -133
  96. package/vendor/cli/vendor/client/hooks.js +1 -430
  97. package/vendor/cli/vendor/client/model-discovery.js +1 -373
  98. package/vendor/cli/vendor/client/naming.js +1 -283
  99. package/vendor/cli/vendor/client/platform.js +1 -937
  100. package/vendor/cli/vendor/client/prefs.js +1 -351
  101. package/vendor/cli/vendor/client/presence-constants.js +1 -107
  102. package/vendor/cli/vendor/client/presence.js +1 -438
  103. package/vendor/cli/vendor/client/record-vault.js +3 -1055
  104. package/vendor/cli/vendor/client/session-store.js +1 -575
  105. package/vendor/cli/vendor/client/topup.js +1 -297
  106. package/vendor/cli/vendor/client/touch.js +1 -458
  107. package/vendor/cli/vendor/client/update.js +1 -763
  108. package/vendor/cli/vendor/client/user-models.js +1 -381
  109. package/vendor/cli/vendor/desktop/lib/local/agents.js +1 -105
  110. package/vendor/cli/vendor/desktop/lib/local/attachments.js +1 -276
  111. package/vendor/cli/vendor/desktop/lib/local/autonomous.js +1 -1045
  112. package/vendor/cli/vendor/desktop/lib/local/claude-pro.js +1 -1028
  113. package/vendor/cli/vendor/desktop/lib/local/context.js +1 -125
  114. package/vendor/cli/vendor/desktop/lib/local/engine.js +1 -3666
  115. package/vendor/cli/vendor/desktop/lib/local/entitlement.js +1 -660
  116. package/vendor/cli/vendor/desktop/lib/local/git-scope.js +1 -228
  117. package/vendor/cli/vendor/desktop/lib/local/integrity.js +1 -1
  118. package/vendor/cli/vendor/desktop/lib/local/local.js +1 -2145
  119. package/vendor/cli/vendor/desktop/lib/local/prompt.js +1 -280
  120. package/vendor/cli/vendor/desktop/lib/local/queue.js +1 -560
  121. package/vendor/cli/vendor/desktop/lib/local/session-rounds.js +1 -238
  122. package/vendor/cli/vendor/desktop/lib/local/spill.js +1 -75
  123. package/vendor/cli/vendor/desktop/lib/local/turn-guard.js +1 -300
  124. package/vendor/cli/vendor/desktop/lib/local/worktree-lock.js +1 -235
  125. package/vendor/cli/vendor/desktop/lib/settings.js +1 -890
  126. package/vendor/cli/vendor/desktop/main.js +67 -1
  127. package/vendor/cli/vendor/desktop/renderer/usage.js +1 -1239
  128. package/vendor/cli/vendor/hosts/install.js +1 -638
  129. package/vendor/cli/vendor/hosts/openai-shim.js +1 -515
  130. package/vendor/cli/vendor/hosts/spec.js +1 -164
  131. package/vendor/cli/vendor/hosts/targets.js +1 -346
  132. package/vendor/cli/vendor/mcp/server.js +1 -221
  133. package/vendor/cli/vendor/mcp/tools.js +1 -408
  134. package/vendor/cli/vendor/one/src/child.js +1 -285
  135. package/vendor/cli/vendor/one/src/permissions.js +1 -383
  136. package/vendor/cli/vendor/one/src/selfhost.js +3 -0
  137. package/vendor/desktop/bin/aegis.js +1 -32
  138. package/vendor/desktop/lib/account-key.js +1 -56
  139. package/vendor/desktop/lib/auto.js +1 -461
  140. package/vendor/desktop/lib/avatar/companion.js +1 -698
  141. package/vendor/desktop/lib/avatar/cosmetics.js +1 -532
  142. package/vendor/desktop/lib/avatar/events.js +1 -344
  143. package/vendor/desktop/lib/avatar/holder-turn.js +1 -350
  144. package/vendor/desktop/lib/avatar/holders.js +1 -612
  145. package/vendor/desktop/lib/avatar/identity.js +1 -641
  146. package/vendor/desktop/lib/avatar/level.js +1 -368
  147. package/vendor/desktop/lib/avatar/mirror.js +1 -524
  148. package/vendor/desktop/lib/avatar/persona.js +1 -388
  149. package/vendor/desktop/lib/avatar/profile.js +1 -977
  150. package/vendor/desktop/lib/avatar/register.js +1 -307
  151. package/vendor/desktop/lib/avatar/store.js +1 -472
  152. package/vendor/desktop/lib/avatar/tiers.js +1 -38
  153. package/vendor/desktop/lib/avatar/transfer.js +1 -415
  154. package/vendor/desktop/lib/avatar/turn.js +1 -216
  155. package/vendor/desktop/lib/avatar/voice.js +1 -328
  156. package/vendor/desktop/lib/avatar/xp.js +1 -404
  157. package/vendor/desktop/lib/deep-link.js +1 -120
  158. package/vendor/desktop/lib/fingerprint.js +2 -347
  159. package/vendor/desktop/lib/google-connect.js +1 -323
  160. package/vendor/desktop/lib/local/agents.js +1 -105
  161. package/vendor/desktop/lib/local/attachments.js +1 -276
  162. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  163. package/vendor/desktop/lib/local/claude-pro.js +1 -1028
  164. package/vendor/desktop/lib/local/context.js +1 -125
  165. package/vendor/desktop/lib/local/engine.js +1 -3666
  166. package/vendor/desktop/lib/local/entitlement.js +1 -660
  167. package/vendor/desktop/lib/local/git-scope.js +1 -228
  168. package/vendor/desktop/lib/local/integrity.js +1 -1
  169. package/vendor/desktop/lib/local/local.js +1 -2145
  170. package/vendor/desktop/lib/local/prompt.js +1 -280
  171. package/vendor/desktop/lib/local/queue.js +1 -560
  172. package/vendor/desktop/lib/local/session-rounds.js +1 -238
  173. package/vendor/desktop/lib/local/spill.js +1 -75
  174. package/vendor/desktop/lib/local/telemetry.js +1 -470
  175. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  176. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  177. package/vendor/desktop/lib/provider-key-mirror.js +1 -252
  178. package/vendor/desktop/lib/quick-launcher.js +1 -84
  179. package/vendor/desktop/lib/settings.js +1 -890
  180. package/vendor/desktop/lib/sync/memory-queue.js +1 -60
  181. package/vendor/desktop/lib/sync/persist-gate.js +1 -148
  182. package/vendor/desktop/lib/sync/sessions.js +1 -106
  183. package/vendor/desktop/lib/window-state.js +1 -66
  184. package/vendor/desktop/main.js +67 -1
  185. package/vendor/desktop/package.json +3 -5
  186. package/vendor/desktop/preload.js +1 -679
  187. package/vendor/desktop/renderer/app.js +1 -7250
  188. package/vendor/desktop/renderer/avatar/assemble.js +1 -335
  189. package/vendor/desktop/renderer/avatar/avatar.js +1 -380
  190. package/vendor/desktop/renderer/avatar/cards.js +1 -141
  191. package/vendor/desktop/renderer/avatar/hud.js +1 -206
  192. package/vendor/desktop/renderer/avatar/machine.js +1 -213
  193. package/vendor/desktop/renderer/avatar/pane.js +1 -439
  194. package/vendor/desktop/renderer/avatar/parts.js +1 -437
  195. package/vendor/desktop/renderer/budget.js +1 -172
  196. package/vendor/desktop/renderer/companion.js +1 -223
  197. package/vendor/desktop/renderer/diff.js +1 -359
  198. package/vendor/desktop/renderer/diffview.js +1 -336
  199. package/vendor/desktop/renderer/filepreview.js +1 -211
  200. package/vendor/desktop/renderer/fingerprint.js +3 -789
  201. package/vendor/desktop/renderer/markdown.js +1 -168
  202. package/vendor/desktop/renderer/provider-mark.js +1 -311
  203. package/vendor/desktop/renderer/provider-toolbar.js +1 -134
  204. package/vendor/desktop/renderer/providers.js +1 -259
  205. package/vendor/desktop/renderer/quick.js +1 -285
  206. package/vendor/desktop/renderer/stream-policy.js +1 -387
  207. package/vendor/desktop/renderer/transcript-view.js +1 -323
  208. package/vendor/desktop/renderer/usage.js +1 -1239
  209. package/vendor/desktop/vendor/aegis.js +1 -2441
  210. package/vendor/desktop/vendor/attest.js +1 -518
  211. package/vendor/desktop/vendor/authorship-key.js +1 -410
  212. package/vendor/desktop/vendor/auto-provision.js +1 -134
  213. package/vendor/desktop/vendor/brain-catalog.js +1 -268
  214. package/vendor/desktop/vendor/byok-catalog.js +1 -199
  215. package/vendor/desktop/vendor/catalog-client.js +1 -487
  216. package/vendor/desktop/vendor/conversation-export.js +1 -177
  217. package/vendor/desktop/vendor/credentials.js +1 -494
  218. package/vendor/desktop/vendor/device-fingerprint.js +1 -141
  219. package/vendor/desktop/vendor/drive-connect.js +1 -110
  220. package/vendor/desktop/vendor/drive-upload.js +1 -234
  221. package/vendor/desktop/vendor/env-file.js +1 -1273
  222. package/vendor/desktop/vendor/faces/cli/LICENSE +661 -0
  223. package/vendor/desktop/vendor/faces/cli/README.md +784 -0
  224. package/vendor/desktop/vendor/faces/cli/bin/aegiscode.js +20 -0
  225. package/vendor/desktop/vendor/faces/cli/package.json +44 -0
  226. package/vendor/desktop/vendor/faces/cli/scripts/check.mjs +4 -0
  227. package/vendor/desktop/vendor/faces/cli/scripts/demo.mjs +4 -0
  228. package/vendor/desktop/vendor/faces/cli/scripts/predist.mjs +4 -0
  229. package/vendor/desktop/vendor/faces/cli/scripts/runtests.mjs +4 -0
  230. package/vendor/desktop/vendor/faces/cli/scripts/seal-gate.mjs +3 -0
  231. package/vendor/desktop/vendor/faces/cli/src/agents.js +3 -0
  232. package/vendor/desktop/vendor/faces/cli/src/app.js +3 -0
  233. package/vendor/desktop/vendor/faces/cli/src/art.js +3 -0
  234. package/vendor/desktop/vendor/faces/cli/src/autonomous.js +3 -0
  235. package/vendor/desktop/vendor/faces/cli/src/caps.js +3 -0
  236. package/vendor/desktop/vendor/faces/cli/src/chatflow.js +3 -0
  237. package/vendor/desktop/vendor/faces/cli/src/checkpoint.js +3 -0
  238. package/vendor/desktop/vendor/faces/cli/src/clipboard.js +3 -0
  239. package/vendor/desktop/vendor/faces/cli/src/cloudsync.js +3 -0
  240. package/vendor/desktop/vendor/faces/cli/src/commands.js +3 -0
  241. package/vendor/desktop/vendor/faces/cli/src/config.js +3 -0
  242. package/vendor/desktop/vendor/faces/cli/src/connect.js +3 -0
  243. package/vendor/desktop/vendor/faces/cli/src/credentials.js +3 -0
  244. package/vendor/desktop/vendor/faces/cli/src/deps.js +3 -0
  245. package/vendor/desktop/vendor/faces/cli/src/devrun.js +3 -0
  246. package/vendor/desktop/vendor/faces/cli/src/diff.js +3 -0
  247. package/vendor/desktop/vendor/faces/cli/src/diffview.js +3 -0
  248. package/vendor/desktop/vendor/faces/cli/src/engine.js +3 -0
  249. package/vendor/desktop/vendor/faces/cli/src/entitlement.js +3 -0
  250. package/vendor/desktop/vendor/faces/cli/src/events.js +3 -0
  251. package/vendor/desktop/vendor/faces/cli/src/export.js +3 -0
  252. package/vendor/desktop/vendor/faces/cli/src/filepreview.js +3 -0
  253. package/vendor/desktop/vendor/faces/cli/src/fingerprint.js +3 -0
  254. package/vendor/desktop/vendor/faces/cli/src/format.js +3 -0
  255. package/vendor/desktop/vendor/faces/cli/src/fuzzy.js +3 -0
  256. package/vendor/desktop/vendor/faces/cli/src/gate.js +3 -0
  257. package/vendor/desktop/vendor/faces/cli/src/history.js +3 -0
  258. package/vendor/desktop/vendor/faces/cli/src/init.js +3 -0
  259. package/vendor/desktop/vendor/faces/cli/src/input.js +3 -0
  260. package/vendor/desktop/vendor/faces/cli/src/keys.js +3 -0
  261. package/vendor/desktop/vendor/faces/cli/src/limits.js +3 -0
  262. package/vendor/desktop/vendor/faces/cli/src/markdown.js +3 -0
  263. package/vendor/desktop/vendor/faces/cli/src/mcp.js +3 -0
  264. package/vendor/desktop/vendor/faces/cli/src/models.js +3 -0
  265. package/vendor/desktop/vendor/faces/cli/src/naming.js +3 -0
  266. package/vendor/desktop/vendor/faces/cli/src/overlays.js +3 -0
  267. package/vendor/desktop/vendor/faces/cli/src/panels.js +3 -0
  268. package/vendor/desktop/vendor/faces/cli/src/permissions.js +3 -0
  269. package/vendor/desktop/vendor/faces/cli/src/ping.js +3 -0
  270. package/vendor/desktop/vendor/faces/cli/src/presence.js +3 -0
  271. package/vendor/desktop/vendor/faces/cli/src/provenance.js +58 -0
  272. package/vendor/desktop/vendor/faces/cli/src/provenance.lock.json +36 -0
  273. package/vendor/desktop/vendor/faces/cli/src/render.js +3 -0
  274. package/vendor/desktop/vendor/faces/cli/src/screen.js +3 -0
  275. package/vendor/desktop/vendor/faces/cli/src/screens.js +3 -0
  276. package/vendor/desktop/vendor/faces/cli/src/secret.js +3 -0
  277. package/vendor/desktop/vendor/faces/cli/src/securefs.js +3 -0
  278. package/vendor/desktop/vendor/faces/cli/src/settings.js +3 -0
  279. package/vendor/desktop/vendor/faces/cli/src/shared.js +3 -0
  280. package/vendor/desktop/vendor/faces/cli/src/sharedpaths.js +3 -0
  281. package/vendor/desktop/vendor/faces/cli/src/signup.js +3 -0
  282. package/vendor/desktop/vendor/faces/cli/src/summarize.js +3 -0
  283. package/vendor/desktop/vendor/faces/cli/src/sysdiag.js +3 -0
  284. package/vendor/desktop/vendor/faces/cli/src/system.js +3 -0
  285. package/vendor/desktop/vendor/faces/cli/src/theme.js +3 -0
  286. package/vendor/desktop/vendor/faces/cli/src/title.js +3 -0
  287. package/vendor/desktop/vendor/faces/cli/src/todos.js +3 -0
  288. package/vendor/desktop/vendor/faces/cli/src/tokens.js +3 -0
  289. package/vendor/desktop/vendor/faces/cli/src/topup.js +3 -0
  290. package/vendor/desktop/vendor/faces/cli/src/update.js +3 -0
  291. package/vendor/desktop/vendor/faces/cli/vendor/client/aegis.js +4 -0
  292. package/vendor/desktop/vendor/faces/cli/vendor/client/attest.js +3 -0
  293. package/vendor/desktop/vendor/faces/cli/vendor/client/authorship-key.js +3 -0
  294. package/vendor/desktop/vendor/faces/cli/vendor/client/auto-provision.js +3 -0
  295. package/vendor/desktop/vendor/faces/cli/vendor/client/brain-catalog.js +3 -0
  296. package/vendor/desktop/vendor/faces/cli/vendor/client/byok-catalog.js +3 -0
  297. package/vendor/desktop/vendor/faces/cli/vendor/client/catalog-client.js +3 -0
  298. package/vendor/desktop/vendor/faces/cli/vendor/client/conversation-export.js +3 -0
  299. package/vendor/desktop/vendor/faces/cli/vendor/client/credentials.js +3 -0
  300. package/vendor/desktop/vendor/faces/cli/vendor/client/device-fingerprint.js +3 -0
  301. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-connect.js +3 -0
  302. package/vendor/desktop/vendor/faces/cli/vendor/client/drive-upload.js +3 -0
  303. package/vendor/desktop/vendor/faces/cli/vendor/client/env-file.js +3 -0
  304. package/vendor/desktop/vendor/faces/cli/vendor/client/fingerprint.js +3 -0
  305. package/vendor/desktop/vendor/faces/cli/vendor/client/foreign-memory.js +3 -0
  306. package/vendor/desktop/vendor/faces/cli/vendor/client/google-signin.js +3 -0
  307. package/vendor/desktop/vendor/faces/cli/vendor/client/hooks.js +3 -0
  308. package/vendor/desktop/vendor/faces/cli/vendor/client/model-discovery.js +3 -0
  309. package/vendor/desktop/vendor/faces/cli/vendor/client/naming.js +3 -0
  310. package/vendor/desktop/vendor/faces/cli/vendor/client/platform.js +3 -0
  311. package/vendor/desktop/vendor/faces/cli/vendor/client/prefs.js +3 -0
  312. package/vendor/desktop/vendor/faces/cli/vendor/client/presence-constants.js +3 -0
  313. package/vendor/desktop/vendor/faces/cli/vendor/client/presence.js +3 -0
  314. package/vendor/desktop/vendor/faces/cli/vendor/client/record-vault.js +105 -0
  315. package/vendor/desktop/vendor/faces/cli/vendor/client/session-store.js +3 -0
  316. package/vendor/desktop/vendor/faces/cli/vendor/client/topup.js +3 -0
  317. package/vendor/desktop/vendor/faces/cli/vendor/client/touch.js +3 -0
  318. package/vendor/desktop/vendor/faces/cli/vendor/client/update.js +3 -0
  319. package/vendor/desktop/vendor/faces/cli/vendor/client/user-models.js +3 -0
  320. package/vendor/desktop/vendor/faces/cli/vendor/covenant/README.md +21 -0
  321. package/vendor/desktop/vendor/faces/cli/vendor/covenant/aegis.seal +177 -0
  322. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/aegis-seal.mjs +241 -0
  323. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/agents.js +3 -0
  324. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/attachments.js +3 -0
  325. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/autonomous.js +3 -0
  326. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/claude-pro.js +3 -0
  327. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/context.js +3 -0
  328. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/covenant.js +567 -0
  329. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/engine.js +3 -0
  330. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/entitlement.js +3 -0
  331. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/exec-plan.js +3 -0
  332. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/git-scope.js +3 -0
  333. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/integrity.js +3 -0
  334. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/local.js +3 -0
  335. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/prompt.js +3 -0
  336. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/queue.js +3 -0
  337. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/session-rounds.js +3 -0
  338. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/shell.js +3 -0
  339. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/spill.js +3 -0
  340. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/tools.js +3 -0
  341. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/turn-guard.js +3 -0
  342. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/local/worktree-lock.js +3 -0
  343. package/vendor/desktop/vendor/faces/cli/vendor/desktop/lib/settings.js +3 -0
  344. package/vendor/desktop/vendor/faces/cli/vendor/desktop/main.js +4 -0
  345. package/vendor/desktop/vendor/faces/cli/vendor/desktop/renderer/usage.js +3 -0
  346. package/vendor/desktop/vendor/faces/cli/vendor/hosts/install.js +1 -0
  347. package/vendor/desktop/vendor/faces/cli/vendor/hosts/openai-shim.js +2 -0
  348. package/vendor/desktop/vendor/faces/cli/vendor/hosts/spec.js +1 -0
  349. package/vendor/desktop/vendor/faces/cli/vendor/hosts/targets.js +1 -0
  350. package/vendor/desktop/vendor/faces/cli/vendor/mcp/server.js +4 -0
  351. package/vendor/desktop/vendor/faces/cli/vendor/mcp/tools.js +3 -0
  352. package/vendor/desktop/vendor/faces/cli/vendor/one/src/child.js +3 -0
  353. package/vendor/desktop/vendor/faces/cli/vendor/one/src/permissions.js +3 -0
  354. package/vendor/desktop/vendor/faces/cli/vendor/one/src/selfhost.js +3 -0
  355. package/vendor/desktop/vendor/faces/cli/vendor/tools/agent-gate.mjs +1203 -0
  356. package/vendor/desktop/vendor/fingerprint.js +1 -1064
  357. package/vendor/desktop/vendor/foreign-memory.js +1 -669
  358. package/vendor/desktop/vendor/google-signin.js +1 -133
  359. package/vendor/desktop/vendor/hooks.js +1 -430
  360. package/vendor/desktop/vendor/model-discovery.js +1 -373
  361. package/vendor/desktop/vendor/naming.js +1 -283
  362. package/vendor/desktop/vendor/platform.js +1 -937
  363. package/vendor/desktop/vendor/prefs.js +1 -351
  364. package/vendor/desktop/vendor/presence-constants.js +1 -107
  365. package/vendor/desktop/vendor/presence.js +1 -438
  366. package/vendor/desktop/vendor/record-vault.js +3 -1055
  367. package/vendor/desktop/vendor/selfhost.js +3 -0
  368. package/vendor/desktop/vendor/session-store.js +1 -575
  369. package/vendor/desktop/vendor/topup.js +1 -297
  370. package/vendor/desktop/vendor/touch.js +1 -458
  371. package/vendor/desktop/vendor/update.js +1 -763
  372. package/vendor/desktop/vendor/user-models.js +1 -381
@@ -0,0 +1,1203 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ /**
5
+ * agent-gate.mjs — "only the holder of the agent key may manipulate this code".
6
+ *
7
+ * ## What this actually enforces, and what it does not
8
+ *
9
+ * This is one half of a two-half lock. Be clear about which half is which,
10
+ * because the honest answer is not "the repo is secure now".
11
+ *
12
+ * ENFORCED HERE (real, on-machine):
13
+ * • `.githooks/pre-commit` and `.githooks/pre-push` refuse to commit or
14
+ * push a change to a protected path unless a valid agent key is present
15
+ * AND this machine is bound in the manifest. The hook runs inside the
16
+ * real `git` process, so it also catches edits made by a host that
17
+ * bypasses the ÆGIS tool layer entirely (a bare editor, the `claude`
18
+ * CLI, a stray script).
19
+ * • The engine's own tool layer reads the SAME manifest before running
20
+ * Write/Edit/mutating Bash (see aegiscodex-dev `src/repoguard.js`), so
21
+ * an agent turn cannot edit this tree without the key either.
22
+ *
23
+ * NOT ENFORCED HERE, and cannot be by anything inside this repo:
24
+ * • Anyone with the bytes can delete this file, the manifest, or the
25
+ * hooks, and edit whatever they like. `git commit --no-verify` skips
26
+ * the hooks outright. A clean clone has no hooks at all (git does not
27
+ * clone `.githooks/` into `core.hooksPath`) until `install-hooks` runs.
28
+ * • A gate that lives inside the thing it protects is a *speed bump with
29
+ * a receipt*, not a cryptographic boundary. It stops the casual case
30
+ * (a copied tree, a borrowed laptop, a new collaborator) and it makes
31
+ * the deliberate case leave a trail.
32
+ *
33
+ * THE ACTUAL LOCK is server-side and lives at the remote: a GitHub ruleset
34
+ * / branch protection on `main` with required reviewers and no force-push.
35
+ * Nothing on this machine can be stronger than the remote's own policy.
36
+ * See SECURITY.md, and `agent-gate.mjs lock-status` for what to check.
37
+ *
38
+ * ## What is in the repo, and what is not
39
+ *
40
+ * `.aegis/guard.json` (committed) holds **only SHA-256 hashes**, never a key.
41
+ * The key itself lives outside the tree, at `$AEGIS_HOME/keys/agent.key`
42
+ * (mode 0600, `$AEGIS_HOME` defaults to `~/.aegiscode`), or in the
43
+ * `AEGIS_AGENT_KEY` environment variable. That placement is deliberate: a
44
+ * secret inside the repo is committed on the next `git add -A`, and this
45
+ * repo's own pre-commit guard scans for exactly that mistake. The module
46
+ * refuses outright to read a key file that is inside the repository it is
47
+ * guarding, or one that is group/other-readable.
48
+ *
49
+ * ## The derivation (the contract; both implementations must match)
50
+ *
51
+ * keyHash = sha256("aegiscode-agent-gate-v1\n" + key) → hex
52
+ * fingerprint = keyHash[0:12]
53
+ * machineFp = sha256("aegiscode-machine-v1\n" + salt + "\n" +
54
+ * hostname + "\n" + machineId + "\n" + username
55
+ * + "\n" + platform + "\n" + arch)[0:16]
56
+ *
57
+ * The domain-separation prefixes are not decoration: without them, a raw
58
+ * `sha256(key)` would be the same value as the φ(α) authorship derivation
59
+ * (`sha256('aegiscode-agent-v1\n' + secret)`) and the two key spaces could be
60
+ * confused for each other. The engine's `src/repoguard.js` re-implements this
61
+ * formula and `test/agent-gate.test.mjs` pins both against the same vector.
62
+ *
63
+ * The machine salt is a random per-install value at `$AEGIS_HOME/keys/machine.salt`
64
+ * (0600). Without it the fingerprint would be a hash of public facts
65
+ * (hostname, /etc/machine-id, username) and therefore forgeable by anyone who
66
+ * can guess them; with it, an allow-list entry is only reproducible on the
67
+ * install that minted it.
68
+ *
69
+ * ## Verbs
70
+ *
71
+ * status what this machine can currently do, and why
72
+ * check [--paths a b …] exit 0 allowed / 3 denied — for hooks and CI
73
+ * init [--cwd DIR] [--mode enforce|warn] [--protect GLOB,…] [--hooks]
74
+ * TURN THE GATE ON for a repository that has none:
75
+ * write .aegis/guard.json with the CURRENT key's
76
+ * hash and this machine bound, and with --hooks
77
+ * vendor lib-gate.sh + wire the pre-commit section.
78
+ * Refuses to run with no key, because enforcing an
79
+ * empty key list denies everyone including you.
80
+ * lock-status the server-side half: what to verify remotely
81
+ * hash --stdin hash a key (never pass a key as an argument)
82
+ * add-key --label <name> append a hash; key read from stdin or the key file
83
+ * rotate mint a NEW key, burn the old ones, print only
84
+ * the new fingerprint
85
+ * bind-machine add THIS machine's fingerprint to the allow-list
86
+ * install-hooks point git at .githooks (a fresh clone has none)
87
+ *
88
+ * Exit codes: 0 = allowed, 3 = denied, 4 = misconfiguration (unreadable or
89
+ * unparseable manifest/key). 3 and 4 are distinct so a hook can tell "the key
90
+ * is wrong" from "the gate is broken" — a broken gate must never silently
91
+ * allow, and it must be diagnosable without reading this file.
92
+ */
93
+
94
+ import crypto from 'node:crypto';
95
+ import fs from 'node:fs';
96
+ import os from 'node:os';
97
+ import path from 'node:path';
98
+ import { createRequire } from 'node:module';
99
+ import { fileURLToPath } from 'node:url';
100
+
101
+ /**
102
+ * Load a CommonJS sibling (client/hooks.js) from this ES module. `createRequire`
103
+ * rather than a plain `import` so the caller can try/catch it synchronously and
104
+ * keep its own behaviour when the file is absent — a bare tools/ copy is a
105
+ * supported layout, and it must fail loudly rather than silently do nothing.
106
+ */
107
+ const require_ = createRequire(import.meta.url);
108
+ function requireClient(spec) { return require_(spec); }
109
+
110
+ export const GATE_VERSION = 1;
111
+ export const KEY_DOMAIN = 'aegiscode-agent-gate-v1';
112
+ export const MACHINE_DOMAIN = 'aegiscode-machine-v1';
113
+ export const MANIFEST_REL = path.join('.aegis', 'guard.json');
114
+ export const KEY_FILE_REL = path.join('keys', 'agent.key');
115
+ export const SALT_FILE_REL = path.join('keys', 'machine.salt');
116
+
117
+ export const EXIT = { ALLOW: 0, DENY: 3, CONFIG: 4 };
118
+
119
+ /** 0600 / 0700, enforced after the write and re-checked — see authorship-key.js. */
120
+ const KEY_FILE_MODE = 0o600;
121
+ const DIR_MODE = 0o700;
122
+ const GROUP_OTHER_BITS = 0o077;
123
+
124
+ /**
125
+ * Do `fs.stat().mode` permission bits mean anything on this host?
126
+ *
127
+ * Windows: no. libuv has no NTFS ACL to report, so it synthesises the mode from
128
+ * the single read-only attribute and returns `0o666` for every writable file —
129
+ * the agent key included. `(mode & GROUP_OTHER_BITS) !== 0` is therefore ALWAYS
130
+ * true there, so the check below refused the agent key unconditionally: on
131
+ * Windows a correctly locked-down key at 0600 was reported as "readable by other
132
+ * users, refusing to treat it as a secret", and no chmod could ever clear it.
133
+ * `writeAgentKey` then threw on its own post-write assert for the same reason,
134
+ * so the gate could not even be initialised there.
135
+ *
136
+ * Where this returns false the boundary is the DIRECTORY's ACL — a per-user
137
+ * profile directory is already inaccessible to other non-admin accounts — which
138
+ * is what client/authorship-key.js has always done for the key file. The right
139
+ * behaviour is to skip the judgement, never to assume the worst.
140
+ *
141
+ * Duplicated from client/platform.js `hasPosixModes()` rather than imported: this
142
+ * file is deliberately standalone so it still runs from a copied hook, a staged
143
+ * tarball, or a vendored tools/ directory that has no sibling `client/`. Same
144
+ * reason cli/src/securefs.js carries its own copy.
145
+ */
146
+ function hasPosixModes(platform) {
147
+ return (platform || process.platform) !== 'win32';
148
+ }
149
+
150
+ // ── derivations ─────────────────────────────────────────────────────────────
151
+
152
+ /** @param {string} key @returns {string} hex sha256 under the gate domain */
153
+ export function hashKey(key) {
154
+ return crypto.createHash('sha256').update(`${KEY_DOMAIN}\n${String(key)}`, 'utf8').digest('hex');
155
+ }
156
+
157
+ /** The 12 hex a human quotes to confirm two machines hold the same key. */
158
+ export function keyFingerprint(key) {
159
+ return hashKey(key).slice(0, 12);
160
+ }
161
+
162
+ /** Constant-time compare of two hex digests (length differs ⇒ false, no early exit on content). */
163
+ export function safeEqualHex(a, b) {
164
+ const ba = Buffer.from(String(a ?? ''), 'utf8');
165
+ const bb = Buffer.from(String(b ?? ''), 'utf8');
166
+ if (ba.length !== bb.length || ba.length === 0) return false;
167
+ return crypto.timingSafeEqual(ba, bb);
168
+ }
169
+
170
+ export function aegisHome(env = process.env) {
171
+ return env.AEGIS_HOME || path.join(os.homedir(), '.aegiscode');
172
+ }
173
+
174
+ function readFirstLine(file) {
175
+ try {
176
+ return fs.readFileSync(file, 'utf8').split('\n')[0].trim();
177
+ } catch {
178
+ return '';
179
+ }
180
+ }
181
+
182
+ /**
183
+ * The per-install random salt, created on first use at 0600. Returns '' only
184
+ * when it cannot be written (a read-only $AEGIS_HOME), in which case the
185
+ * fingerprint silently degrades to unsalted — the caller's `status` output
186
+ * reports that, so a degraded fingerprint is visible rather than assumed.
187
+ */
188
+ export function machineSalt(env = process.env) {
189
+ const file = path.join(aegisHome(env), SALT_FILE_REL);
190
+ const existing = readFirstLine(file);
191
+ if (existing) return existing;
192
+ try {
193
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: DIR_MODE });
194
+ const salt = crypto.randomBytes(16).toString('base64url');
195
+ fs.writeFileSync(file, `${salt}\n`, { mode: KEY_FILE_MODE });
196
+ fs.chmodSync(file, KEY_FILE_MODE);
197
+ return salt;
198
+ } catch {
199
+ return '';
200
+ }
201
+ }
202
+
203
+ /** Stable 16-hex identifier for THIS machine's install. See the header for the formula. */
204
+ export function machineFingerprint(env = process.env, overrides = {}) {
205
+ const hostname = overrides.hostname ?? os.hostname();
206
+ const username = overrides.username ?? (() => { try { return os.userInfo().username; } catch { return '?'; } })();
207
+ // `??` may not be mixed with `||` unparenthesised — the middle rung is
208
+ // spelled out rather than chained, because the file fallback has to be
209
+ // parenthesised anyway.
210
+ const machineId = overrides.machineId
211
+ ?? (readFirstLine('/etc/machine-id') || readFirstLine('/var/lib/dbus/machine-id'));
212
+ const platform = overrides.platform ?? process.platform;
213
+ const arch = overrides.arch ?? process.arch;
214
+ const salt = overrides.salt ?? machineSalt(env);
215
+ const body = [salt, hostname, machineId, username, platform, arch].join('\n');
216
+ return crypto.createHash('sha256').update(`${MACHINE_DOMAIN}\n${body}`, 'utf8').digest('hex').slice(0, 16);
217
+ }
218
+
219
+ // ── manifest ────────────────────────────────────────────────────────────────
220
+
221
+ /** Nearest `.aegis/guard.json` at or above `startPath`. */
222
+ export function findManifest(startPath) {
223
+ let dir = path.resolve(startPath || process.cwd());
224
+ try { if (fs.statSync(dir).isFile()) dir = path.dirname(dir); } catch { /* keep as-is */ }
225
+ for (;;) {
226
+ const candidate = path.join(dir, MANIFEST_REL);
227
+ if (fs.existsSync(candidate)) return candidate;
228
+ const parent = path.dirname(dir);
229
+ if (parent === dir) return null;
230
+ dir = parent;
231
+ }
232
+ }
233
+
234
+ /** Parse a manifest, or throw with the reason (never return a half-read policy). */
235
+ export function loadManifest(file) {
236
+ if (!file) throw new Error(`no ${MANIFEST_REL} found at or above this path`);
237
+ let raw;
238
+ try {
239
+ raw = fs.readFileSync(file, 'utf8');
240
+ } catch (e) {
241
+ throw new Error(`cannot read manifest ${file}: ${e.message}`);
242
+ }
243
+ let data;
244
+ try {
245
+ data = JSON.parse(raw);
246
+ } catch (e) {
247
+ throw new Error(`manifest ${file} is not valid JSON: ${e.message}`);
248
+ }
249
+ if (Number(data.version) !== GATE_VERSION) {
250
+ throw new Error(`manifest ${file} declares version ${data.version}; this gate speaks version ${GATE_VERSION}`);
251
+ }
252
+ data.keys = Array.isArray(data.keys) ? data.keys : [];
253
+ data.machines = Array.isArray(data.machines) ? data.machines : [];
254
+ data.protect = Array.isArray(data.protect) ? data.protect : ['**'];
255
+ data.__file = file;
256
+ data.__root = path.dirname(path.dirname(file));
257
+ return data;
258
+ }
259
+
260
+ /** Active key entries only — a burned entry is kept for the record, never honoured. */
261
+ export function activeKeys(manifest) {
262
+ return (manifest.keys || []).filter((k) => k && (k.status || 'active') === 'active' && k.sha256);
263
+ }
264
+
265
+ // ── the tool half (the desktop app's own tool layer) ────────────────────────
266
+
267
+ /**
268
+ * The app names its tools differently from the engine (`writeFile`/`editFile`/
269
+ * `exec` vs `Write`/`Edit`/`Bash`), and both are wired to THIS function so
270
+ * there is one decision and one manifest format across the hooks, the CLI, the
271
+ * app and the engine. Every alias of a mutating tool must be listed here or
272
+ * that tool silently escapes the gate — which is why the app's own names are
273
+ * spelled out rather than derived.
274
+ */
275
+ export const MUTATING_TOOL_NAMES = new Set([
276
+ 'Write', 'Edit', 'MultiEdit', 'NotebookEdit', // engine + provider names
277
+ 'writeFile', 'editFile', // desktop/lib/local/tools.js
278
+ ]);
279
+
280
+ /** Bash/`exec` commands whose whole purpose is to write. Tested, not guessed. */
281
+ export const BASH_TOOL_NAMES = new Set(['Bash', 'exec']);
282
+ export const SKIP_ENV = 'AEGIS_GATE_SKIP';
283
+
284
+ const WRITEISH_BASH = [
285
+ /(^|[^<])>>?\s*\S/, // > file, >> file
286
+ /\btee\b/, /\bsed\s+-i/, /\btruncate\b/, /\bdd\b/,
287
+ /\b(rm|mv|cp|install|touch|mkdir|rmdir|chmod|chown|ln)\b/,
288
+ /\b(patch|applypatch)\b/, /\bperl\s+-i\b/,
289
+ /\bgit\s+(checkout|restore|reset|clean|stash|apply|revert|cherry-pick|merge|rebase)\b/,
290
+ /\bnpm\s+(install|ci|uninstall|update)\b/, /\byarn\s+(add|remove)\b/, /\bpip[0-9.]*\s+install\b/,
291
+ /\bAEGIS_GATE_SKIP\b/,
292
+
293
+ // `find` is a writer the moment it mutates: -delete, -exec/-execdir, and the
294
+ // -fprint/-fls family all write without ever containing `rm` or a redirect.
295
+ // Found by probing this gate keylessly on 2026-10-02 (`find <gated-tree>
296
+ // -name guard.json -delete` was reported as a read). Kept in step with
297
+ // aegiscodex-dev/src/repoguard.js, which carries the same list.
298
+ /\bfind\b[^|;]*\s-(delete|exec|execdir|fprint|fprint0|fls)\b/,
299
+ /\bxargs\b/,
300
+
301
+ // An inline-eval interpreter is an opaque program: `node -e`, `python -c`,
302
+ // `perl -e`, `sh -c` can write anywhere without naming a path in the command
303
+ // text. The old python rule looked for a literal `open(` and so missed
304
+ // `open(String.fromCharCode(...))`; the interpreter itself is the honest
305
+ // marker, and path-less write-ish commands fall back to cwd (fail-closed).
306
+ // `node --test` is deliberately NOT a hit.
307
+ /\b(python[0-9.]*|perl)\s+-c\b/, /\b(python[0-9.]*|perl)\s+-e\b/,
308
+ /\bnode\b[^|;]*\s(?:-e|--eval)\b/, /\b(sh|bash|zsh|dash)\s+-c\b/,
309
+
310
+ // Archive extraction overwrites arbitrary paths in bulk with none of the
311
+ // markers above: `tar -x`, `unzip`, `7z x/e` never mention `cp`/`mv`/a `>`.
312
+ // Found probing this list by hand on 2026-10-12 — none of these tripped it.
313
+ // Kept in step with aegiscodex-dev/src/repoguard.js, which carries the same list.
314
+ /\btar\b[^|;]*(?:-[A-Za-z]*x[A-Za-z]*\b|--extract\b)/,
315
+ /\bunzip\b/, /\b7z[ar]?\s+[xe]\b/,
316
+
317
+ // Download-straight-to-file: the write is the whole point, but the marker
318
+ // is a flag shared with nothing else (`-o`/`-O`/`--output`), not a bare tool
319
+ // name, so it is scoped to the specific tool that owns that flag.
320
+ /\bcurl\b[^|;]*\s-{1,2}(?:o|O|output|remote-name)\b/,
321
+ /\bwget\b[^|;]*\s-{1,2}(?:O|output-document)\b/,
322
+
323
+ // Bulk copy/sync — functionally `cp -r` under a different name.
324
+ /\brsync\b/,
325
+
326
+ // `-out`/`-o`/`--output` on the specific tools that use it to write a file,
327
+ // each scoped to its own tool name so an unrelated `-o` (e.g. `ls -o`) on
328
+ // some other command is not a false hit.
329
+ /\bopenssl\b[^|;]*\s-out\b/,
330
+ /\bgpg2?\b[^|;]*\s-{1,2}(?:o|output)\b/,
331
+ /\bbase64\b[^|;]*\s-{1,2}(?:o|output)\b/,
332
+ ];
333
+
334
+ /** Path-shaped tokens in a command line. Deliberately over-eager: see bashTargets. */
335
+ function pathTokens(command) {
336
+ const out = [];
337
+ const re = /(?:^|[\s'"=<>|&;(])((?:~|\.{1,2})?\/[^\s'"|&;)>]+|[A-Za-z0-9_.-]+\/[^\s'"|&;)>]+)/g;
338
+ let m;
339
+ while ((m = re.exec(String(command))) !== null) out.push(m[1]);
340
+ return out;
341
+ }
342
+
343
+ /**
344
+ * Does this command write, and where?
345
+ *
346
+ * A heuristic, and named one: a script that CALLS `cp`, or an interpreter that
347
+ * reads a write out of a file, is not seen. A bare relative target (`cp a b`)
348
+ * has no `/`, so the whole command is judged against `cwd` instead — the
349
+ * fail-closed direction, because the alternative is "unparseable, so allow".
350
+ *
351
+ * @returns {{ writeish: boolean, paths: string[] }}
352
+ */
353
+ export function bashTargets(command, cwd = process.cwd()) {
354
+ const cmd = String(command || '');
355
+ const writeish = WRITEISH_BASH.some((re) => re.test(cmd));
356
+ if (!writeish) return { writeish: false, paths: [] };
357
+ const paths = pathTokens(cmd);
358
+ return { writeish: true, paths: paths.length ? paths : [cwd] };
359
+ }
360
+
361
+ /**
362
+ * Paths (manifest-relative) that this call would touch. Unlike a git path
363
+ * list, a tool target may be a directory or the repo root itself (`rm -rf .`):
364
+ * a directory is treated as protected whenever the manifest protects anything,
365
+ * which over-blocks a non-holder writing to an unprotected subdirectory — the
366
+ * safe direction, and free for the holder, who is allowed through anyway.
367
+ */
368
+ function protectedUnder(manifest, absPaths) {
369
+ const root = manifest.__root;
370
+ const hasIncludes = manifest.protect.some((p) => {
371
+ const pat = String(p).trim();
372
+ return pat && !pat.startsWith('!');
373
+ });
374
+ const out = [];
375
+ for (const abs of absPaths) {
376
+ const rel = path.relative(root, abs);
377
+ if (path.isAbsolute(rel) || rel.startsWith('..')) continue;
378
+ if (rel === '') { if (hasIncludes) out.push('.'); continue; }
379
+ let isDir = false;
380
+ try { isDir = fs.statSync(abs).isDirectory(); } catch { isDir = false; }
381
+ if (isDir) { if (hasIncludes) out.push(rel); continue; }
382
+ if (isProtected(manifest, rel)) out.push(rel);
383
+ }
384
+ return out;
385
+ }
386
+
387
+
388
+ // ── the key ─────────────────────────────────────────────────────────────────
389
+
390
+ /**
391
+ * The key-resolution ladder, most explicit first:
392
+ * 1. an explicit `key` argument (tests, and the engine passing a key through)
393
+ * 2. `AEGIS_AGENT_KEY` in the environment
394
+ * 3. `$AEGIS_HOME/keys/agent.key` — where `rotate` writes
395
+ *
396
+ * A file is refused when it is group/other-readable (any bit of 0o077) or
397
+ * when it lives inside the repo being guarded. Both refusals exist because
398
+ * the alternative is a gate that passes for the wrong reason.
399
+ *
400
+ * @returns {{ key: string, source: string, error: string|null }}
401
+ */
402
+ export function resolveAgentKey({ env = process.env, manifestRoot = null, key = null, platform = null } = {}) {
403
+ if (key) return { key: String(key).trim(), source: 'argument', error: null };
404
+
405
+ const fromEnv = env.AEGIS_AGENT_KEY;
406
+ if (fromEnv && String(fromEnv).trim()) {
407
+ return { key: String(fromEnv).trim(), source: 'env:AEGIS_AGENT_KEY', error: null };
408
+ }
409
+
410
+ const file = path.join(aegisHome(env), KEY_FILE_REL);
411
+ let st;
412
+ try {
413
+ st = fs.statSync(file);
414
+ } catch {
415
+ return { key: '', source: 'none', error: `no agent key at ${file} (and AEGIS_AGENT_KEY is unset)` };
416
+ }
417
+ let mode = null;
418
+ try { mode = st.mode & 0o777; } catch { /* non-POSIX */ }
419
+ // Skipped where the mode is synthesised (see hasPosixModes): the test is true
420
+ // for every file on Windows, so it refused the key on every read there.
421
+ if (hasPosixModes(platform) && mode !== null && (mode & GROUP_OTHER_BITS)) {
422
+ return {
423
+ key: '',
424
+ source: file,
425
+ error: `${file} is mode 0${mode.toString(8)} — readable by other users, refusing to treat it as a secret (chmod 600)`,
426
+ };
427
+ }
428
+ if (manifestRoot) {
429
+ const rel = path.relative(path.resolve(manifestRoot), path.resolve(file));
430
+ if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
431
+ return { key: '', source: file, error: `${file} lives INSIDE the guarded repo — move it outside or it will be committed` };
432
+ }
433
+ }
434
+ const value = readFirstLine(file);
435
+ if (!value) return { key: '', source: file, error: `${file} is empty` };
436
+ return { key: value, source: file, error: null };
437
+ }
438
+
439
+ export function writeAgentKey(key, env = process.env, platform = null) {
440
+ const file = path.join(aegisHome(env), KEY_FILE_REL);
441
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: DIR_MODE });
442
+ fs.writeFileSync(file, `${key}\n`, { mode: KEY_FILE_MODE });
443
+ fs.chmodSync(file, KEY_FILE_MODE); // writeFileSync's mode is masked by umask
444
+ // The re-read assert only means something where stat reports what chmod wrote;
445
+ // on Windows it reports 0666 for this 0600 file, so this threw on every init.
446
+ if (hasPosixModes(platform)) {
447
+ const after = fs.statSync(file).mode & 0o777;
448
+ if (after !== KEY_FILE_MODE) throw new Error(`key file landed at mode 0${after.toString(8)}, expected 0600`);
449
+ }
450
+ return file;
451
+ }
452
+
453
+ // ── path scoping ────────────────────────────────────────────────────────────
454
+
455
+ /**
456
+ * Globs in `protect`. `**` matches everything; `*` does not cross `/` — same
457
+ * rule as .gitignore, because the people writing these entries think in
458
+ * .gitignore. `!`-prefixed entries are exceptions, evaluated after includes.
459
+ */
460
+ function globToRegex(pattern) {
461
+ let re = '^';
462
+ const src = String(pattern);
463
+ for (let i = 0; i < src.length; i++) {
464
+ const c = src[i];
465
+ if (c === '*') {
466
+ if (src[i + 1] === '*') {
467
+ // `**/` should also match zero directories
468
+ if (src[i + 2] === '/') { re += '(?:.*/)?'; i += 2; } else { re += '.*'; i += 1; }
469
+ } else {
470
+ re += '[^/]*';
471
+ }
472
+ } else if (c === '?') re += '[^/]';
473
+ else if (/[.+^${}()|[\]\\]/.test(c)) re += `\\${c}`;
474
+ else re += c;
475
+ }
476
+ return new RegExp(re + '$');
477
+ }
478
+
479
+ /** Is `relPath` (repo-relative, POSIX separators) covered by the manifest? */
480
+ export function isProtected(manifest, relPath) {
481
+ const rel = String(relPath).split(path.sep).join('/').replace(/^\.\//, '');
482
+ const negations = [];
483
+ let hit = false;
484
+ for (const entry of manifest.protect) {
485
+ const pat = String(entry).trim();
486
+ if (!pat) continue;
487
+ if (pat.startsWith('!')) {
488
+ const inner = pat.slice(1);
489
+ if (inner) negations.push(globToRegex(inner));
490
+ continue;
491
+ }
492
+ if (globToRegex(pat).test(rel)) hit = true;
493
+ }
494
+ // Negations are evaluated after all includes, so an exception line further
495
+ // up the list still wins — the order the entry was written does not have to
496
+ // be the order it takes effect, which is what .gitignore readers expect.
497
+ if (hit && negations.some((re) => re.test(rel))) return false;
498
+ return hit;
499
+ }
500
+
501
+ /** Split paths into protected / not, relative to the manifest root. */
502
+ export function partitionPaths(manifest, cwd, paths) {
503
+ const root = manifest.__root;
504
+ const protectedPaths = [];
505
+ const outside = [];
506
+ for (const p of paths || []) {
507
+ const abs = path.resolve(cwd || process.cwd(), p);
508
+ const rel = path.relative(root, abs);
509
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel)) { outside.push(p); continue; }
510
+ if (isProtected(manifest, rel)) protectedPaths.push(rel);
511
+ else outside.push(p);
512
+ }
513
+ return { protectedPaths, outside };
514
+ }
515
+
516
+ // ── the verdict ─────────────────────────────────────────────────────────────
517
+
518
+ /**
519
+ * The single decision function. Everything above exists to feed it; every
520
+ * caller (the hooks, the CLI, the engine's repoguard) must go through it, so
521
+ * there is exactly one place where "allowed" is decided.
522
+ *
523
+ * @returns {{ ok: boolean, code: 'allow'|'deny', keyId: string|null,
524
+ * fingerprint: string|null, machine: string, reason: string,
525
+ * configError: string|null }}
526
+ */
527
+ export function verifyAgent({ cwd = process.cwd(), key = null, env = process.env, manifest = null, manifestFile = null, machine = null } = {}) {
528
+ let man = manifest;
529
+ let configError = null;
530
+ try {
531
+ if (!man) man = loadManifest(manifestFile || findManifest(cwd));
532
+ } catch (e) {
533
+ configError = e.message;
534
+ return {
535
+ ok: false, code: 'deny', keyId: null, fingerprint: null,
536
+ machine: machine || machineFingerprint(env), reason: configError, configError,
537
+ };
538
+ }
539
+
540
+ const machineFp = machine || machineFingerprint(env);
541
+ const { key: resolved, source, error } = resolveAgentKey({ env, manifestRoot: man.__root, key });
542
+
543
+ if (error) {
544
+ return {
545
+ ok: false, code: 'deny', keyId: null, fingerprint: null,
546
+ machine: machineFp, reason: error, configError: /inside the guarded repo|readable by other users/.test(error) ? error : null,
547
+ };
548
+ }
549
+
550
+ const presented = hashKey(resolved);
551
+ const match = activeKeys(man).find((k) => safeEqualHex(k.sha256, presented));
552
+
553
+ if (!match) {
554
+ return {
555
+ ok: false, code: 'deny', keyId: null, fingerprint: keyFingerprint(resolved),
556
+ machine: machineFp,
557
+ reason: `agent key rejected (presented fingerprint ${keyFingerprint(resolved)} from ${source}) — not in ${man.__file}`,
558
+ configError: null,
559
+ };
560
+ }
561
+
562
+ // Machine binding is checked only AFTER the key, so a wrong key and a wrong
563
+ // machine report differently (and neither reports the other's state).
564
+ if (man.machines.length > 0 && !man.machines.some((m) => safeEqualHex(String(m).toLowerCase(), machineFp.toLowerCase()))) {
565
+ return {
566
+ ok: false, code: 'deny', keyId: match.id || null, fingerprint: keyFingerprint(resolved),
567
+ machine: machineFp,
568
+ reason: `agent key "${match.id}" is valid but this machine (${machineFp}) is not bound in ${man.__file}`,
569
+ configError: null,
570
+ };
571
+ }
572
+
573
+ return {
574
+ ok: true, code: 'allow', keyId: match.id || null, fingerprint: keyFingerprint(resolved),
575
+ machine: machineFp, reason: `agent key "${match.id}" accepted${man.machines.length ? ' on a bound machine' : ' (no machine binding configured)'}`,
576
+ configError: null,
577
+ };
578
+ }
579
+
580
+ // ── the tool gate (the third caller, after the hooks and the CLI) ───────────
581
+
582
+ /**
583
+ * Decide whether a TOOL CALL may run against a gated tree. This is the
584
+ * in-process half of the same lock the hooks enforce at commit time, and the
585
+ * one the desktop app (`desktop/lib/local/tools.js`) and the engine
586
+ * (`aegiscodex-dev/src/repoguard.js`) both route through.
587
+ *
588
+ * Fail-closed, like the hooks: a gated path with no resolvable key, an
589
+ * unreadable manifest, or a key file that is world-readable is a refusal
590
+ * rather than a passthrough. Reads are never gated (`read: "open"`).
591
+ *
592
+ * `AEGIS_GATE_SKIP=1` is the single documented bypass — the same variable
593
+ * `.githooks/lib-gate.sh` honours — and it is REFUSED when `unattended` is
594
+ * true: an autonomous run has no one to answer for a bypass, so it cannot
595
+ * grant itself one.
596
+ *
597
+ * @returns {{ allowed: boolean, gated: boolean,
598
+ * code: 'allow'|'deny'|'not-gated'|'skipped',
599
+ * reason: string, tool: string, manifest: string|null, verdicts: object[] }}
600
+ */
601
+ export function guardTool({ tool, args = {}, cwd = process.cwd(), env = process.env, unattended = false } = {}) {
602
+ const base = { allowed: true, gated: false, code: 'not-gated', reason: 'no agent-gated tree in this call', tool, manifest: null, verdicts: [] };
603
+
604
+ if (env[SKIP_ENV] === '1') {
605
+ if (unattended) {
606
+ return { ...base, allowed: false, code: 'deny', reason: `refused: ${SKIP_ENV}=1 is not honoured in an unattended run — the gate is not skippable by an agent's own judgment` };
607
+ }
608
+ return { ...base, code: 'skipped', reason: `agent gate SKIPPED (${SKIP_ENV}=1) — this edit is unverified` };
609
+ }
610
+
611
+ let targets = [];
612
+ if (MUTATING_TOOL_NAMES.has(tool)) {
613
+ const target = args.file_path || args.notebook_path || args.path;
614
+ if (!target) return { ...base, reason: `no file path in this ${tool} call` };
615
+ targets = [path.resolve(cwd, String(target))];
616
+ } else if (BASH_TOOL_NAMES.has(tool)) {
617
+ const { writeish, paths } = bashTargets(args.command, cwd);
618
+ if (!writeish) return base;
619
+ targets = paths.map((p) => path.resolve(cwd, p));
620
+ } else {
621
+ return base;
622
+ }
623
+
624
+ const byManifest = new Map();
625
+ for (const abs of targets) {
626
+ const file = findManifest(abs);
627
+ if (!file) continue;
628
+ if (!byManifest.has(file)) byManifest.set(file, []);
629
+ byManifest.get(file).push(abs);
630
+ }
631
+ if (byManifest.size === 0) return base;
632
+
633
+ const verdicts = [];
634
+ let allowed = true;
635
+ let reason = '';
636
+ let manifestFile = null;
637
+ for (const [file, absPaths] of byManifest) {
638
+ let man;
639
+ try {
640
+ man = loadManifest(file);
641
+ } catch (e) {
642
+ return { ...base, allowed: false, gated: true, code: 'deny', configError: e.message, manifest: file, reason: `agent gate misconfigured: ${e.message}` };
643
+ }
644
+ const protectedPaths = protectedUnder(man, absPaths);
645
+ if (protectedPaths.length === 0) continue;
646
+ const verdict = verifyAgent({ manifest: man, cwd, env });
647
+ verdicts.push({ ...verdict, paths: protectedPaths });
648
+ manifestFile = man.__file;
649
+ if (verdict.ok) {
650
+ if (!reason) reason = `${verdict.reason} — ${protectedPaths.join(', ')}`;
651
+ continue;
652
+ }
653
+ if (man.mode === 'warn' && !verdict.configError) {
654
+ if (!reason) reason = `manifest mode is "warn" — reporting, not blocking: ${verdict.reason}`;
655
+ continue;
656
+ }
657
+ allowed = false;
658
+ reason = verdict.reason;
659
+ }
660
+
661
+ if (verdicts.length === 0) return base;
662
+ return { ...base, allowed, gated: true, code: allowed ? 'allow' : 'deny', reason: reason || 'agent-gated tree', manifest: manifestFile, verdicts };
663
+ }
664
+
665
+ /** Exit-code mapping for a `guardTool` result. 3 = denied, 4 = broken gate. */
666
+ export function exitCodeFor(verdict) {
667
+ if (verdict.allowed) return EXIT.ALLOW;
668
+ return (verdict.configError || verdict.verdicts?.some((v) => v.configError)) ? EXIT.CONFIG : EXIT.DENY;
669
+ }
670
+
671
+ /** The human-facing refusal, without the CLI's "how to fix" prose. */
672
+ export function refusalText(verdict) {
673
+ return `refused by the agent-key gate: ${verdict.reason}. This tree is agent-gated — a change to a protected path needs the agent key at $AEGIS_HOME/keys/agent.key (mode 600) or AEGIS_AGENT_KEY, on a machine bound in ${verdict.manifest || '.aegis/guard.json'}. Run \`node tools/agent-gate.mjs status\` to see what this machine can do.`;
674
+ }
675
+
676
+ // ── CLI ─────────────────────────────────────────────────────────────────────
677
+
678
+ const VERBS = ['status', 'check', 'init', 'lock-status', 'hash', 'add-key', 'rotate', 'bind-machine', 'import-key', 'install-hooks', 'help'];
679
+
680
+ // Flags that take a value. Anything else long-form is a boolean, so `--hooks`
681
+ // and `--force` work without a special case each.
682
+ const VALUE_FLAGS = new Set(['--cwd', '--manifest', '--label', '--mode', '--protect']);
683
+
684
+ function parseArgs(argv) {
685
+ const out = { verb: 'status', flags: {}, rest: [] };
686
+ const list = [...argv];
687
+ if (list.length && !list[0].startsWith('-')) out.verb = list.shift();
688
+ while (list.length) {
689
+ const a = list.shift();
690
+ if (a === '--paths') {
691
+ // Consumes the whole run of following non-flag arguments: `--paths a b c`
692
+ // is how both hooks call this, and a parser that ate only the first one
693
+ // would silently check one file and pass the rest through as prose.
694
+ const group = [];
695
+ while (list.length && !list[0].startsWith('--')) group.push(list.shift());
696
+ out.flags.paths = group.join(' ').split(/[\s,]+/).filter(Boolean);
697
+ } else if (VALUE_FLAGS.has(a)) {
698
+ out.flags[a.slice(2)] = list.shift();
699
+ } else if (a.startsWith('--')) out.flags[a.slice(2)] = true;
700
+ else out.rest.push(a);
701
+ }
702
+ return out;
703
+ }
704
+
705
+ function readStdin() {
706
+ try {
707
+ return fs.readFileSync(0, 'utf8').trim();
708
+ } catch {
709
+ return '';
710
+ }
711
+ }
712
+
713
+ function editManifest(file, mutate) {
714
+ const man = loadManifest(file);
715
+ const clean = { ...man };
716
+ delete clean.__file; delete clean.__root;
717
+ mutate(clean);
718
+ fs.writeFileSync(file, `${JSON.stringify(clean, null, 2)}\n`, 'utf8');
719
+ return clean;
720
+ }
721
+
722
+ // ── init: turn the gate ON for a repository that has none ───────────────────
723
+ //
724
+ // Every other verb edits a manifest that already exists. This is the one that
725
+ // creates one, and it exists because the alternative was hand-writing JSON from
726
+ // a template — which is how a repo ends up with a manifest whose key hash or
727
+ // machine entry is subtly wrong, i.e. a gate that denies its own owner. It
728
+ // therefore REFUSES to run without a resolvable key: `mode: "enforce"` with an
729
+ // empty key list denies every write, and the operator finds that out at the
730
+ // first commit rather than here.
731
+
732
+ const MANIFEST_COMMENT = [
733
+ 'The agent-key gate for this repository. Read tools/agent-gate.mjs\'s header before',
734
+ 'trusting anything here: this file is the RECEIPT, not the lock. It stops a copied',
735
+ 'tree, a borrowed laptop and a casual collaborator, and it makes a deliberate edit',
736
+ 'leave a trail. It cannot stop someone who has the bytes — they delete this file.',
737
+ 'The real lock is a GitHub ruleset on main: run `agent-gate.mjs lock-status`.',
738
+ '',
739
+ 'HASHES ONLY. Never put a key in this file: it is committed, and the repo\'s own',
740
+ 'pre-commit guard scans staged content for exactly that mistake. The key lives at',
741
+ '$AEGIS_HOME/keys/agent.key (mode 0600), outside the tree.',
742
+ '',
743
+ 'sha256 = sha256(\'aegiscode-agent-gate-v1\\n\' + key) — see KEY_DOMAIN in tools/agent-gate.mjs',
744
+ 'The engine re-implements this in aegiscodex-dev/src/repoguard.js; a shared test',
745
+ 'vector in aegiscode-plugin/test/agent-gate.test.mjs holds the two in step.',
746
+ ];
747
+
748
+ const HOOK_MARKER = '# ── agent-key gate';
749
+
750
+ function hookSection() {
751
+ // Self-contained on purpose: it defines nothing and calls nothing from the
752
+ // host hook except lib-gate.sh, so it drops into a pre-commit of any shape
753
+ // (this repo's uses `fail()`, aegis1's differs, a bare one has neither).
754
+ return [
755
+ '# ── agent-key gate (tools/agent-gate.mjs + .aegis/guard.json) ───────────────',
756
+ '# "Only the holder of the agent key may manipulate this code." Policy lives in',
757
+ '# .aegis/guard.json; the decision function lives in tools/agent-gate.mjs; this is',
758
+ '# the shell edge of it.',
759
+ '#',
760
+ '# LAST, deliberately: the path blocklist and the secret scan above are',
761
+ '# unconditional and must not become conditional on a key being present.',
762
+ '#',
763
+ '# Fail-closed: a missing gate CLI, missing node or unreadable manifest refuses.',
764
+ '# The one bypass is AEGIS_GATE_SKIP=1 — an env var, so it is greppable.',
765
+ '# shellcheck source=.githooks/lib-gate.sh',
766
+ '. "$(dirname "$0")/lib-gate.sh"',
767
+ 'if ! agent_gate_check_staged; then',
768
+ ' echo "✗ pre-commit blocked: the agent-key gate refused this commit (reason above)." >&2',
769
+ ' exit 1',
770
+ 'fi',
771
+ ].join('\n');
772
+ }
773
+
774
+ /** Vendor lib-gate.sh next to the hook and wire the section in, idempotently. */
775
+ function wireHook(root) {
776
+ const src = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', '.githooks', 'lib-gate.sh');
777
+ if (!fs.existsSync(src)) throw new Error(`cannot vendor the hook library — ${src} does not exist`);
778
+ const hooksDir = path.join(root, '.githooks');
779
+ fs.mkdirSync(hooksDir, { recursive: true });
780
+ const lib = path.join(hooksDir, 'lib-gate.sh');
781
+ fs.copyFileSync(src, lib);
782
+ // The exec bit means something only where git reads it. On win32 chmod is not
783
+ // enforced, so a chmodSync there is a silent no-op that READS as protection;
784
+ // git for Windows runs hooks with its bundled sh, so the bit is not needed.
785
+ const execBit = process.platform !== 'win32';
786
+ if (execBit) fs.chmodSync(lib, 0o755);
787
+
788
+ const hook = path.join(hooksDir, 'pre-commit');
789
+ let text = fs.existsSync(hook)
790
+ ? fs.readFileSync(hook, 'utf8')
791
+ : '#!/bin/sh\n# pre-commit guard — created by `agent-gate.mjs init --hooks`.\n\nset -u\n\nexit 0\n';
792
+ const already = text.includes(HOOK_MARKER);
793
+ if (!already) {
794
+ const lines = text.split('\n');
795
+ let at = -1;
796
+ for (let i = lines.length - 1; i >= 0; i -= 1) if (lines[i].trim() === 'exit 0') { at = i; break; }
797
+ const section = hookSection().split('\n');
798
+ if (at >= 0) lines.splice(at, 0, ...section, ''); else lines.push(...section, '');
799
+ text = lines.join('\n');
800
+ }
801
+ fs.writeFileSync(hook, text, 'utf8');
802
+ if (execBit) fs.chmodSync(hook, 0o755);
803
+ return { lib, hook, already, execBit };
804
+ }
805
+
806
+ function cmdInit({ flags }) {
807
+ const root = path.resolve(flags.cwd || process.cwd());
808
+ let stat = null;
809
+ try { stat = fs.statSync(root); } catch { /* reported below */ }
810
+ if (!stat || !stat.isDirectory()) { console.error(`✗ agent-gate: ${root} is not a directory`); return EXIT.CONFIG; }
811
+ const file = flags.manifest || path.join(root, MANIFEST_REL);
812
+ if (fs.existsSync(file) && !flags.force) {
813
+ console.error(`✗ agent-gate: ${file} already exists — refusing to overwrite it.`);
814
+ console.error(' Edit it with add-key / bind-machine / rotate, or pass --force to replace it outright.');
815
+ return EXIT.CONFIG;
816
+ }
817
+ const mode = flags.mode === undefined ? 'enforce' : String(flags.mode);
818
+ if (mode !== 'enforce' && mode !== 'warn') { console.error(`✗ agent-gate: --mode must be enforce or warn, got "${mode}"`); return EXIT.CONFIG; }
819
+ const protect = flags.protect ? String(flags.protect).split(/[\s,]+/).filter(Boolean) : ['**'];
820
+ if (protect.length === 0) protect.push('**');
821
+
822
+ const fromStdin = flags['key-stdin'] ? readStdin() : '';
823
+ const { key, source, error } = fromStdin
824
+ ? { key: fromStdin, source: 'stdin', error: null }
825
+ : resolveAgentKey({ env: process.env, manifestRoot: root });
826
+ if (!key) {
827
+ console.error(`✗ agent-gate: refusing to init without a key — ${error || 'no agent key found'}`);
828
+ console.error(' "enforce" with no active key denies EVERY write in the tree, mine and yours:');
829
+ console.error(' that is fail-closed, not something you should discover at the first commit.');
830
+ console.error(' Put a key in place first: agent-gate.mjs rotate (mints one, 0600, never printed)');
831
+ console.error(' or: agent-gate.mjs init --key-stdin < ~/.aegiscode/keys/agent.key');
832
+ return EXIT.CONFIG;
833
+ }
834
+
835
+ const id = flags.label || 'agent-key-1';
836
+ const machines = flags['no-bind'] ? [] : [machineFingerprint()];
837
+ const manifest = {
838
+ version: GATE_VERSION,
839
+ comment: MANIFEST_COMMENT,
840
+ mode,
841
+ read: 'open',
842
+ protect,
843
+ keys: [{
844
+ id,
845
+ label: flags.label || 'primary agent key',
846
+ sha256: hashKey(key),
847
+ status: 'active',
848
+ addedAt: new Date().toISOString(),
849
+ keySource: source,
850
+ }],
851
+ machines,
852
+ machinesNote: 'Machine binding is a speed bump, not identity: the fingerprint is a hash of public facts plus a per-install salt (keys/machine.salt), so it is reproducible on this install and not by guessing. Adding a machine is explicit (bind-machine); moving the key file does not carry the binding. `init` binds the machine that runs it, because the alternative is an operator locked out by their own manifest.',
853
+ };
854
+ fs.mkdirSync(path.dirname(file), { recursive: true });
855
+ fs.writeFileSync(file, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8');
856
+
857
+ let hooks = null;
858
+ if (flags.hooks) {
859
+ try { hooks = wireHook(root); } catch (e) { console.error(`✗ agent-gate: ${e.message}`); return EXIT.CONFIG; }
860
+ }
861
+
862
+ console.error(`✓ agent-gate: wrote ${file}`);
863
+ console.error(` mode ${mode} · protects ${protect.join(' ')} · key "${id}" fingerprint ${keyFingerprint(key)} (${source})`);
864
+ console.error(machines.length
865
+ ? ` bound machine ${machines[0]}`
866
+ : ' NO machine bound (--no-bind): any machine holding the key file opens this gate');
867
+ if (hooks) console.error(`✓ vendored ${hooks.lib}${hooks.already ? ' (gate section already present)' : ` and inserted the gate section into ${hooks.hook}`}`);
868
+ else console.error(' hooks NOT wired — pass --hooks to vendor lib-gate.sh and wire pre-commit');
869
+ // `--hooks` was the user asking for hooks. Ending on "now run this yourself"
870
+ // left a fresh tree with the files present and the hooks still not installed —
871
+ // the documented state in which NO guard runs. So the install happens here,
872
+ // where the request was made, and it is verified rather than assumed.
873
+ if (hooks) {
874
+ let hooksLib = null;
875
+ try { hooksLib = requireClient('../client/hooks.js'); } catch { hooksLib = null; }
876
+ if (hooksLib) {
877
+ const res = hooksLib.installRepoHooks({ cwd: root });
878
+ if (!res.ok) console.error(`✗ agent-gate: the hooks were vendored but NOT installed — ${res.error}`);
879
+ else if (!res.changed) console.error(`✓ guard hooks already installed (core.hooksPath = .githooks)`);
880
+ else console.error(`✓ installed: core.hooksPath = .githooks (read back to verify)\n ${res.actions.join('\n ')}`);
881
+ } else {
882
+ console.error(` finish: git -C ${root} config core.hooksPath .githooks`);
883
+ console.error(' (client/hooks.js is missing from this copy, so the install could not be done or verified here)');
884
+ }
885
+ }
886
+ console.error(` verify: agent-gate.mjs status --cwd ${root} (expect ALLOW)`);
887
+ console.error(' prove: AEGIS_AGENT_KEY=wrong agent-gate.mjs check --cwd … (expect exit 3, not 0)');
888
+ return EXIT.ALLOW;
889
+ }
890
+
891
+ function cmdStatus({ flags }) {
892
+ const cwd = flags.cwd || process.cwd();
893
+ const verdict = verifyAgent({ cwd });
894
+ const file = verdict.configError ? (flags.manifest || findManifest(cwd)) : null;
895
+ let man = null;
896
+ try { man = loadManifest(file || findManifest(cwd)); } catch { /* reported below */ }
897
+
898
+ console.log(`agent-gate v${GATE_VERSION}`);
899
+ if (man) {
900
+ console.log(` manifest ${man.__file}`);
901
+ console.log(` root ${man.__root}`);
902
+ console.log(` protects ${man.protect.join(' ')}`);
903
+ console.log(` active keys ${activeKeys(man).map((k) => k.id || '(unnamed)').join(', ') || '(none)'}`);
904
+ const burned = man.keys.filter((k) => (k.status || 'active') !== 'active');
905
+ if (burned.length) console.log(` burned keys ${burned.map((k) => k.id || '(unnamed)').join(', ')}`);
906
+ console.log(` bound machines ${man.machines.length || '(none — any machine with the key)'}`);
907
+ } else {
908
+ console.log(` manifest none found at or above ${cwd}`);
909
+ }
910
+ console.log(` this machine ${verdict.machine}${machineSalt() ? '' : ' (UNSALTED — $AEGIS_HOME not writable)'}`);
911
+ console.log(` verdict ${verdict.ok ? 'ALLOW' : 'DENY'} — ${verdict.reason}`);
912
+ return verdict.ok ? EXIT.ALLOW : (verdict.configError ? EXIT.CONFIG : EXIT.DENY);
913
+ }
914
+
915
+ function cmdCheck({ flags }) {
916
+ const cwd = flags.cwd || process.cwd();
917
+ const file = flags.manifest || findManifest(cwd);
918
+ let man;
919
+ try {
920
+ man = loadManifest(file);
921
+ } catch (e) {
922
+ if (!flags.quiet) console.error(`✗ agent-gate: ${e.message}`);
923
+ return EXIT.CONFIG;
924
+ }
925
+
926
+ // Only protected paths gate the operation; a commit touching nothing
927
+ // protected (docs, a vendored file outside the globs) is not held hostage.
928
+ const paths = flags.paths && flags.paths.length ? flags.paths : null;
929
+ if (paths) {
930
+ const { protectedPaths } = partitionPaths(man, cwd, paths);
931
+ if (protectedPaths.length === 0) {
932
+ if (!flags.quiet) console.error('✓ agent-gate: no protected path in this change');
933
+ return EXIT.ALLOW;
934
+ }
935
+ }
936
+
937
+ const verdict = verifyAgent({ manifest: man, cwd });
938
+ if (verdict.ok) {
939
+ if (!flags.quiet) console.error(`✓ agent-gate: ${verdict.reason}`);
940
+ return EXIT.ALLOW;
941
+ }
942
+
943
+ // `mode: "warn"` is the rollout state: the gate reports and does not block,
944
+ // so a repo can adopt this without locking out a collaborator whose key has
945
+ // not been added yet. Policy lives HERE, not in the hooks, so the engine's
946
+ // repoguard inherits the identical rule instead of re-deriving it.
947
+ if (man.mode === 'warn' && !flags.strict && !verdict.configError) {
948
+ if (!flags.quiet) console.error(' (manifest mode is "warn" — reporting, not blocking; --strict to block anyway)');
949
+ return EXIT.ALLOW;
950
+ }
951
+
952
+ if (!flags.quiet) console.error(`✗ agent-gate: ${verdict.reason}`);
953
+ return verdict.configError ? EXIT.CONFIG : EXIT.DENY;
954
+ }
955
+
956
+ function cmdLockStatus() {
957
+ console.log(`agent-gate: the server-side half of the lock, which no local file can substitute.
958
+
959
+ Nothing in this repository can stop someone who has the bytes from editing
960
+ them. The only real lock is at the remote. Verify these, in this order:
961
+
962
+ 1. GitHub → Settings → Rules → Rulesets, target "main":
963
+ ☑ Restrict force pushes
964
+ ☑ Require a pull request before merging (≥1 approval)
965
+ ☑ Require signed commits (ties a push to a real key holder)
966
+ ☑ Block force pushes / deletions
967
+ 2. GitHub → Settings → Collaborators: who can push at all. Everyone in this
968
+ list can write the code regardless of the local gate.
969
+ 3. Deploy keys: read-only unless a push from CI is genuinely needed.
970
+ 4. Branch protection on any release branch, plus tag protection for v*.
971
+
972
+ A local clone that has never run \`agent-gate.mjs install-hooks\` has no
973
+ hooks and this gate does not run there at all. That is expected, and it is
974
+ exactly why (1) is the lock and this file is the receipt.`);
975
+ return EXIT.ALLOW;
976
+ }
977
+
978
+ function cmdHash({ flags }) {
979
+ const key = flags.stdin ? readStdin() : '';
980
+ if (!key) {
981
+ console.error('agent-gate: refusing to take a key from argv (it would land in `ps` and your shell history).\n echo -n "<key>" | agent-gate.mjs hash --stdin');
982
+ return EXIT.CONFIG;
983
+ }
984
+ console.log(JSON.stringify({ sha256: hashKey(key), fingerprint: keyFingerprint(key) }, null, 2));
985
+ return EXIT.ALLOW;
986
+ }
987
+
988
+ function cmdAddKey({ flags }) {
989
+ const file = flags.manifest || findManifest(flags.cwd || process.cwd());
990
+ let man;
991
+ try { man = loadManifest(file); } catch (e) { console.error(`✗ ${e.message}`); return EXIT.CONFIG; }
992
+
993
+ const fromStdin = readStdin();
994
+ const { key, source, error } = fromStdin
995
+ ? { key: fromStdin, source: 'stdin', error: null }
996
+ : resolveAgentKey({ env: process.env, manifestRoot: man.__root });
997
+ if (error) { console.error(`✗ ${error}`); return EXIT.CONFIG; }
998
+
999
+ const sha = hashKey(key);
1000
+ if (activeKeys(man).some((k) => safeEqualHex(k.sha256, sha))) {
1001
+ console.error(`= agent-gate: that key is already active (${keyFingerprint(key)})`);
1002
+ return EXIT.ALLOW;
1003
+ }
1004
+ const id = flags.label || `key-${activeKeys(man).length + 1}`;
1005
+ editManifest(file, (m) => {
1006
+ m.keys.push({ id, sha256: sha, label: flags.label || id, status: 'active', addedAt: new Date().toISOString(), keySource: source });
1007
+ });
1008
+ console.error(`✓ agent-gate: added "${id}" (fingerprint ${keyFingerprint(key)}) to ${file}`);
1009
+ return EXIT.ALLOW;
1010
+ }
1011
+
1012
+ function cmdRotate({ flags }) {
1013
+ const file = flags.manifest || findManifest(flags.cwd || process.cwd());
1014
+ let man;
1015
+ try { man = loadManifest(file); } catch (e) { console.error(`✗ ${e.message}`); return EXIT.CONFIG; }
1016
+
1017
+ const fresh = crypto.randomBytes(32).toString('base64url');
1018
+ const written = writeAgentKey(fresh);
1019
+ const sha = hashKey(fresh);
1020
+
1021
+ editManifest(file, (m) => {
1022
+ for (const k of m.keys) if ((k.status || 'active') === 'active') { k.status = 'burned'; k.burnedAt = new Date().toISOString(); k.burnedReason = 'rotated'; }
1023
+ m.keys.push({ id: flags.label || `key-${m.keys.length + 1}`, sha256: sha, label: 'rotated', status: 'active', addedAt: new Date().toISOString(), keySource: written });
1024
+ if (m.machines.length === 0) m.machines.push(machineFingerprint());
1025
+ });
1026
+
1027
+ // The new key is written to disk and never printed. Printing it would put a
1028
+ // live credential into scrollback, shell history, CI logs and — the case
1029
+ // that actually happened in this repo — a chat transcript.
1030
+ console.error(`✓ agent-gate: rotated. New key at ${written} (mode 0600), fingerprint ${keyFingerprint(fresh)}.`);
1031
+ console.error(` Previous active keys are marked burned in ${file}: the old value no longer opens the gate,`);
1032
+ console.error(` including anywhere it was pasted or logged. To move the key to another machine, copy the FILE.`);
1033
+ return EXIT.ALLOW;
1034
+ }
1035
+
1036
+ function cmdBindMachine({ flags }) {
1037
+ const file = flags.manifest || findManifest(flags.cwd || process.cwd());
1038
+ try { loadManifest(file); } catch (e) { console.error(`✗ ${e.message}`); return EXIT.CONFIG; }
1039
+ const fp = machineFingerprint();
1040
+ editManifest(file, (m) => { if (!m.machines.some((x) => String(x).toLowerCase() === fp.toLowerCase())) m.machines.push(fp); });
1041
+ console.error(`✓ agent-gate: bound machine ${fp} in ${file}`);
1042
+ console.error(' A machine fingerprint is a hash of public facts plus a per-install salt: it identifies this');
1043
+ console.error(' install, not a person. Moving the key FILE to another machine does not carry the binding —');
1044
+ console.error(' that is the point, and it is why rotating on a new machine needs one explicit bind-machine.');
1045
+ return EXIT.ALLOW;
1046
+ }
1047
+
1048
+ /**
1049
+ * Adopt a key from an arbitrary file — the point is a Downloads-folder drop
1050
+ * ("I just moved this key to a new machine") without hand-running `cat | env`.
1051
+ * Downloads is a STAGING spot, not where the live secret should sit: it's
1052
+ * commonly cloud-synced, browser-permissioned, and indexed. So this installs
1053
+ * the key at the real location ($AEGIS_HOME/keys/agent.key, mode 0600) and
1054
+ * then deletes the source file — the opposite of making Downloads a place the
1055
+ * gate trusts on an ongoing basis. `--keep` skips the delete for anyone who
1056
+ * wants to move it manually instead.
1057
+ */
1058
+ function cmdImportKey({ flags, rest }) {
1059
+ const src = (rest && rest[0]) ? path.resolve(rest[0]) : path.join(os.homedir(), 'Downloads', 'agent.key');
1060
+ let raw;
1061
+ try {
1062
+ raw = fs.readFileSync(src, 'utf8');
1063
+ } catch (e) {
1064
+ console.error(`✗ agent-gate: cannot read ${src}: ${e.message}`);
1065
+ console.error(' Pass a path explicitly: agent-gate.mjs import-key /path/to/agent.key');
1066
+ return EXIT.CONFIG;
1067
+ }
1068
+ const key = raw.split('\n')[0].trim();
1069
+ if (!key) { console.error(`✗ agent-gate: ${src} is empty`); return EXIT.CONFIG; }
1070
+
1071
+ let srcMode = null;
1072
+ try { srcMode = fs.statSync(src).mode & 0o777; } catch { /* unreadable already reported above */ }
1073
+ if (srcMode !== null && (srcMode & 0o077)) {
1074
+ console.error(`⚠ agent-gate: ${src} was mode 0${srcMode.toString(8)} (group/other-readable) — importing anyway,`);
1075
+ console.error(' but treat that key as potentially exposed to anything else with access to that folder.');
1076
+ }
1077
+
1078
+ const dest = writeAgentKey(key);
1079
+ console.error(`✓ agent-gate: installed key (fingerprint ${keyFingerprint(key)}) at ${dest} (mode 0600)`);
1080
+
1081
+ if (!flags.keep) {
1082
+ try {
1083
+ fs.unlinkSync(src);
1084
+ console.error(`✓ agent-gate: removed ${src} — the live copy now lives only at ${dest}`);
1085
+ } catch (e) {
1086
+ console.error(`⚠ agent-gate: could not remove ${src} (${e.message}) — delete it yourself, it should not sit there long-term`);
1087
+ }
1088
+ } else {
1089
+ console.error(` --keep set: left ${src} in place. Downloads is not a safe long-term home for this file.`);
1090
+ }
1091
+
1092
+ const cwd = flags.cwd || process.cwd();
1093
+ const verdict = verifyAgent({ cwd });
1094
+ console.error(` this machine ${verdict.machine}`);
1095
+ console.error(` verdict ${verdict.ok ? 'ALLOW' : 'DENY'} — ${verdict.reason}`);
1096
+ if (!verdict.ok && !verdict.configError) {
1097
+ console.error(` the key imported fine; this machine likely still needs: agent-gate.mjs bind-machine --cwd ${cwd}`);
1098
+ }
1099
+ return verdict.ok ? EXIT.ALLOW : (verdict.configError ? EXIT.CONFIG : EXIT.DENY);
1100
+ }
1101
+
1102
+ function cmdInstallHooks({ flags }) {
1103
+ const root = path.resolve(flags.cwd || process.cwd());
1104
+ const dryRun = Boolean(flags['dry-run'] || flags.dryRun);
1105
+ // The install itself lives in the SHARED module (client/hooks.js), the same
1106
+ // one the CLI /hooks and the desktop hooks tool call, so "installed" means
1107
+ // one thing on every host. Loaded through createRequire because this file is
1108
+ // ESM and that module is CJS. A build without the client tree (a bare
1109
+ // tools/ copy) falls back to the old describe-only behaviour below rather
1110
+ // than pretending the install happened.
1111
+ let hooksLib = null;
1112
+ try { hooksLib = requireClient('../client/hooks.js'); } catch { hooksLib = null; }
1113
+
1114
+ if (!hooksLib) {
1115
+ const hooksDir = path.join(root, '.githooks');
1116
+ if (!fs.existsSync(path.join(hooksDir, 'pre-commit'))) {
1117
+ console.error(`✗ agent-gate: no .githooks/pre-commit under ${root}`);
1118
+ return EXIT.CONFIG;
1119
+ }
1120
+ if (process.platform !== 'win32') {
1121
+ for (const name of ['pre-commit', 'pre-push']) {
1122
+ const p = path.join(hooksDir, name);
1123
+ if (fs.existsSync(p)) fs.chmodSync(p, 0o755);
1124
+ }
1125
+ }
1126
+ console.error('✗ agent-gate: client/hooks.js is missing, so this copy cannot install the hooks itself.');
1127
+ console.error(` run: git -C ${root} config core.hooksPath .githooks`);
1128
+ console.error(' (the shared installer is what verifies the write; restore client/hooks.js to get it)');
1129
+ return EXIT.CONFIG;
1130
+ }
1131
+
1132
+ const res = hooksLib.installRepoHooks({ cwd: root, dryRun });
1133
+ if (!res.ok) {
1134
+ console.error(`✗ agent-gate: ${res.error}`);
1135
+ if (res.actions.length) console.error(` ${dryRun ? 'would run' : 'ran'}:\n ${res.actions.join('\n ')}`);
1136
+ return EXIT.CONFIG;
1137
+ }
1138
+ if (dryRun) {
1139
+ console.error(` would install the guard hooks in ${res.status.repo}:`);
1140
+ for (const a of res.actions) console.error(` ${a}`);
1141
+ if (res.status.installed) console.error(' (core.hooksPath is already .githooks — nothing to change)');
1142
+ return EXIT.ALLOW;
1143
+ }
1144
+ if (!res.changed) {
1145
+ console.error(`= agent-gate: guard hooks already installed in ${res.status.repo} (core.hooksPath = .githooks)`);
1146
+ } else {
1147
+ console.error(`✓ agent-gate: installed the guard hooks in ${res.status.repo} — core.hooksPath = .githooks (read back to verify)`);
1148
+ for (const a of res.actions) console.error(` ${a}`);
1149
+ }
1150
+ console.error(` present: ${res.status.present.join(', ') || '(none)'}${res.status.missing.length ? ` · missing: ${res.status.missing.join(', ')}` : ''}`);
1151
+ console.error(` ${res.status.execNote}`);
1152
+ console.error(` verify: node tools/invariant-lock.mjs status (the hooks run it)`);
1153
+ return EXIT.ALLOW;
1154
+ }
1155
+
1156
+ function cmdHelp() {
1157
+ console.log(`agent-gate — the agent-key gate for this repository.
1158
+
1159
+ agent-gate.mjs status [--cwd DIR] [--manifest FILE]
1160
+ agent-gate.mjs check [--cwd DIR] [--manifest FILE] [--paths a b c] [--quiet]
1161
+ agent-gate.mjs init [--cwd DIR] [--mode enforce|warn] [--protect GLOB,…]
1162
+ [--label NAME] [--key-stdin] [--no-bind] [--hooks] [--force]
1163
+ agent-gate.mjs lock-status
1164
+ agent-gate.mjs hash --stdin
1165
+ agent-gate.mjs add-key [--label NAME] (key from stdin, else the key file)
1166
+ agent-gate.mjs rotate
1167
+ agent-gate.mjs bind-machine
1168
+ agent-gate.mjs import-key [PATH] [--keep] [--cwd DIR]
1169
+ (default PATH: ~/Downloads/agent.key; installs it at
1170
+ $AEGIS_HOME/keys/agent.key mode 0600, then deletes PATH
1171
+ unless --keep, then prints this machine's verdict)
1172
+ agent-gate.mjs install-hooks [--cwd DIR]
1173
+
1174
+ Exit codes: 0 allowed, 3 denied, 4 misconfiguration.`);
1175
+ return EXIT.ALLOW;
1176
+ }
1177
+
1178
+ const COMMANDS = {
1179
+ status: cmdStatus, check: cmdCheck, init: cmdInit, 'lock-status': cmdLockStatus, hash: cmdHash,
1180
+ 'add-key': cmdAddKey, rotate: cmdRotate, 'bind-machine': cmdBindMachine,
1181
+ 'import-key': cmdImportKey, 'install-hooks': cmdInstallHooks, help: cmdHelp,
1182
+ };
1183
+
1184
+ /**
1185
+ * Run the CLI. Returns the exit code instead of calling process.exit, so the
1186
+ * test file can drive every verb in-process and assert the code.
1187
+ */
1188
+ export function run(argv = process.argv.slice(2)) {
1189
+ const parsed = parseArgs(argv);
1190
+ if (!VERBS.includes(parsed.verb)) {
1191
+ console.error(`✗ agent-gate: unknown verb "${parsed.verb}" — try "help"`);
1192
+ return EXIT.CONFIG;
1193
+ }
1194
+ try {
1195
+ return COMMANDS[parsed.verb](parsed);
1196
+ } catch (e) {
1197
+ console.error(`✗ agent-gate: ${e.message}`);
1198
+ return EXIT.CONFIG;
1199
+ }
1200
+ }
1201
+
1202
+ const invokedDirectly = process.argv[1] && path.resolve(process.argv[1]) === path.resolve(fileURLToPath(import.meta.url));
1203
+ if (invokedDirectly) process.exit(run());