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,942 +1,4 @@
1
1
  #!/usr/bin/env node
2
2
  // SPDX-License-Identifier: AGPL-3.0-or-later
3
3
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
4
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
5
- // Conveying a modified copy, or running one as a network service, owes the
6
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
7
- /**
8
- * AEGISONE — the ONLY vendoring stager (plan D6).
9
- *
10
- * Before this file there were two stagers with two hand-maintained manifests:
11
- * `cli/scripts/predist.mjs` (about forty modules, staged under `cli/vendor/`
12
- * keeping the repo's relative shape) and `desktop/scripts/predist.mjs` (a
13
- * subset of the same modules, staged FLAT into `desktop/vendor/`, because
14
- * electron-builder cannot reach outside the app directory). Two lists of the
15
- * same repo-relative paths, drifting independently, each with its own copy of
16
- * the "why is this file here" reasoning.
17
- *
18
- * Now there is ONE manifest — `MANIFEST`, below — and it is the only place a
19
- * staged path is written down. Each row records which SHAPE(s) that module must
20
- * appear in:
21
- *
22
- * mirror → `<cli>/vendor/<repo-relative path>` (the CLI's self-similar tree)
23
- * flat → `<desktop>/vendor/<basename>` (electron-builder's app dir)
24
- * nested → `<desktop>/vendor/<repo-relative path>` (artifacts whose SHAPE is
25
- * load-bearing: the seal is
26
- * resolved at ../../vendor/
27
- * covenant/aegis.seal)
28
- *
29
- * …plus a fourth output that only AEGISONE needs: the PRODUCT BUNDLE
30
- * (`one/vendor/cli/**`, `one/vendor/desktop/**`), which is what makes
31
- * `npm i -g aegisone` a single install with both faces inside it. The bundle
32
- * is a copy of the already-staged trees, so it inherits both shapes verbatim
33
- * and `sharedpaths.js`'s two-layout rule resolves inside it with no change.
34
- *
35
- * Two things this file refuses to do:
36
- *
37
- * 1. **It never trusts a copy.** Every staged file is re-read and compared
38
- * against its source; a mismatch is a hard failure, because a stale vendor
39
- * tree is how a published package ships last month's behaviour.
40
- * 2. **It never trusts a comment.** Both existing proofs are carried over and
41
- * actually executed here: the CLI's staged registry must LOAD from inside
42
- * `cli/vendor/` (not from the repo), and the desktop's flattened tree must
43
- * be self-contained (no staged file may require a path that escapes
44
- * `vendor/`) — which is the property flattening silently depends on.
45
- *
46
- * THE SEAM RULE (Phase 30.1, and the standing rule for everything under `one/`):
47
- * no `process.*` read happens at module scope. Every read is inside a function,
48
- * `main(argv, io)` takes its streams and arguments as parameters, and this
49
- * module is therefore importable by a test without running the staging. There
50
- * is also no `process.platform` anywhere in this file: nothing here branches on
51
- * the OS. Where a host list is needed it comes from `client/platform.js`, and
52
- * the copies themselves are `fs` calls with no platform vocabulary in them.
53
- */
54
-
55
- import fs from 'node:fs';
56
- import path from 'node:path';
57
- import { spawnSync } from 'node:child_process';
58
- import { fileURLToPath, pathToFileURL } from 'node:url';
59
- import { createRequire } from 'node:module';
60
-
61
- const HERE = path.dirname(fileURLToPath(import.meta.url));
62
- const require = createRequire(import.meta.url);
63
-
64
- /** `one/` */
65
- export const ONE_DIR = path.join(HERE, '..');
66
- /** the repository root (`aegiscode-plugin/`) */
67
- export const REPO_DIR = path.join(ONE_DIR, '..');
68
- export const CLI_DIR = path.join(REPO_DIR, 'cli');
69
- export const DESKTOP_DIR = path.join(REPO_DIR, 'desktop');
70
- export const CLI_VENDOR = path.join(CLI_DIR, 'vendor');
71
- export const DESKTOP_VENDOR = path.join(DESKTOP_DIR, 'vendor');
72
- export const ONE_VENDOR = path.join(ONE_DIR, 'vendor');
73
-
74
- // ---------------------------------------------------------------------------
75
- // THE MANIFEST — one row per shared module, one place a path is written down.
76
- // ---------------------------------------------------------------------------
77
- //
78
- // `src` repo-relative path of the file that lives at the repo root.
79
- // `shapes` where it must appear: 'mirror' (cli/vendor, repo-shaped),
80
- // 'flat' (desktop/vendor, basename only), 'nested' (desktop/vendor,
81
- // repo-shaped — only for artifacts whose shape the requiring code
82
- // depends on).
83
- //
84
- // A row appears ONCE even when both hosts need it. That is the whole point of
85
- // D6: the desktop's flat set is a subset of the CLI's mirror set, and the old
86
- // pair of scripts restated those nineteen paths in two files.
87
- //
88
- // Comment discipline: the old per-file notes are preserved verbatim-ish, but
89
- // none of them is load-bearing any more. Nothing parses these comments (the
90
- // `src:`/`shapes:` fields are matched as an object by test/one-vendor.test.mjs),
91
- // so a stray apostrophe can no longer swallow the next manifest row — which is
92
- // exactly the trap the old single-quote-paired parsers fell into.
93
- export const MANIFEST = [
94
- // ── the shared client: transport, stores, identity, catalogues ───────────
95
- { src: 'client/aegis.js', shapes: ['mirror', 'flat'],
96
- note: 'the thin transport — the one implementation of the wire format' },
97
- { src: 'client/update.js', shapes: ['mirror', 'flat'],
98
- note: 'the npm update checker (the desktop own update path)' },
99
- { src: 'client/foreign-memory.js', shapes: ['mirror', 'flat'],
100
- note: 'required by mcp/tools.js as ../client/foreign-memory.js' },
101
- { src: 'client/credentials.js', shapes: ['mirror', 'flat'],
102
- note: 'the account credential store, shared by all three hosts' },
103
- { src: 'client/session-store.js', shapes: ['mirror', 'flat'],
104
- note: 'the unified session store — one list in every host' },
105
- { src: 'client/prefs.js', shapes: ['mirror', 'flat'],
106
- note: 'the shared non-secret preference store (D5) — the CLI and the desktop store both read/write it' },
107
- { src: 'client/env-file.js', shapes: ['mirror', 'flat'],
108
- note: 'the shared ~/.aegiscode/.env loader, resolved before any key is read' },
109
- { src: 'client/auto-provision.js', shapes: ['mirror', 'flat'],
110
- note: 'free device key on first launch; requires ./device-fingerprint.js' },
111
- { src: 'client/device-fingerprint.js', shapes: ['mirror', 'flat'],
112
- note: 'the machine identity auto-provision.js and presence.js require' },
113
- { src: 'client/presence.js', shapes: ['mirror', 'flat'],
114
- note: 'the heartbeat beacon; requires ./presence-constants.js and ./device-fingerprint.js' },
115
- { src: 'client/presence-constants.js', shapes: ['mirror', 'flat'],
116
- note: 'the beacon constants — a package without them loses the beacon silently' },
117
- { src: 'client/touch.js', shapes: ['mirror', 'flat'],
118
- note: 'phi(alpha): the digest module fingerprint.js requires as ./touch.js' },
119
- { src: 'client/fingerprint.js', shapes: ['mirror', 'flat'],
120
- note: 'phi(alpha): the sealed session record, resolved by src/fingerprint.js' },
121
- { src: 'client/authorship-key.js', shapes: ['mirror', 'flat'],
122
- note: 'phi(alpha): the authorship key, required by ./attest.js and ./record-vault.js' },
123
- { src: 'client/attest.js', shapes: ['mirror', 'flat'],
124
- note: 'phi(alpha): attestation, requires ./fingerprint.js and ./authorship-key.js' },
125
- { src: 'client/record-vault.js', shapes: ['mirror', 'flat'],
126
- note: 'the vault, and its refusal to copy the key with the record' },
127
- { src: 'client/brain-catalog.js', shapes: ['mirror', 'flat'],
128
- note: 'the pooled-brain rule, required at load time by the engine and src/models.js' },
129
- { src: 'client/byok-catalog.js', shapes: ['mirror', 'flat'],
130
- note: 'the BYOK model additions the server catalog does not name' },
131
- { src: 'client/user-models.js', shapes: ['mirror', 'flat'],
132
- note: 'the models the USER declares, in one file both hosts read (requires ./credentials.js)' },
133
- { src: 'client/model-discovery.js', shapes: ['mirror', 'flat'],
134
- note: 'asks the vendor what it serves, so adding a new model is not a memory test (requires ./user-models.js)' },
135
- { src: 'client/hooks.js', shapes: ['mirror', 'flat'],
136
- note: 'the shared hook layer behind /hooks and the repo guard installer' },
137
- { src: 'client/platform.js', shapes: ['mirror', 'flat'],
138
- note: 'the ONE place that decides which OS this is (Phase 30.1)' },
139
- { src: 'client/topup.js', shapes: ['mirror', 'flat'],
140
- note: 'the token-bank top-up: amount bounds, the balance reading, and the credit watch every host drives' },
141
- { src: 'client/google-signin.js', shapes: ['mirror', 'flat'],
142
- note: 'the localhost half of aegis1\'s desktop Google OAuth round-trip; `connect --google` drives it' },
143
- { src: 'client/drive-connect.js', shapes: ['mirror', 'flat'],
144
- note: 'the desktop half of aegis1\'s Drive OAuth (/connect/drive, /api/drive/token); requires ./aegis.js only via the caller' },
145
- { src: 'client/drive-upload.js', shapes: ['mirror', 'flat'],
146
- note: 'the Drive v3 REST wrapper that uploads the memory backup' },
147
-
148
- // ── the MCP host surface ────────────────────────────────────────────────
149
- { src: 'mcp/tools.js', shapes: ['mirror'],
150
- note: 'the shared tool registry; requires ../client/foreign-memory.js' },
151
- { src: 'mcp/server.js', shapes: ['mirror'],
152
- note: 'the stdio MCP server every installed editor config names (compiled, never required)' },
153
- { src: 'hosts/spec.js', shapes: ['mirror'],
154
- note: 'the canonical server spec, staged under its own directory so it finds vendor/mcp/server.js' },
155
- { src: 'hosts/targets.js', shapes: ['mirror'],
156
- note: 'the editor target registry' },
157
- { src: 'hosts/install.js', shapes: ['mirror'],
158
- note: 'the merge-only installer behind aegiscode mcp install' },
159
- { src: 'hosts/openai-shim.js', shapes: ['mirror'],
160
- note: 'the loopback OpenAI-compatible shim' },
161
-
162
- // ── the engine the CLI reuses from the desktop app ──────────────────────
163
- { src: 'desktop/renderer/usage.js', shapes: ['mirror'],
164
- note: 'the pure usage mapping shared by the window and the terminal' },
165
- { src: 'desktop/lib/local/engine.js', shapes: ['mirror'],
166
- note: 'the agent loop, reused as-is (one loop, not a second one drifting)' },
167
- // engine.js requires ./claude-pro.js at load (the Claude Code Pro class'
168
- // transport), exactly as local.js requires ./context.js — and with exactly
169
- // the same consequence when the row is absent: the staged engine throws
170
- // MODULE_NOT_FOUND from inside vendor/, and the packaged CLI does not load at
171
- // all. test/one-manifest-complete.test.mjs derives the dependency, so this is
172
- // a red line there rather than a mystery in cli-package.
173
- { src: 'desktop/lib/local/claude-pro.js', shapes: ['mirror'],
174
- note: 'the Claude Code Pro transport; requires ./../../one/src/child.js at call time' },
175
- // The Pro class' argv half. claude-pro.js resolves these at CALL time through
176
- // path.join (not a relative require), so the manifest-completeness scan cannot
177
- // see them — which is why they are written down here by hand and why they were
178
- // missed. `one/src/permissions.js` reaches the CLI's own rule evaluator at
179
- // cli/src/permissions.js, itself resolved through the staged `../vendor/cli/`
180
- // layout ('mirror' stages them at cli/vendor/cli/src/…, which is the second
181
- // candidate that module looks in).
182
- { src: 'one/src/child.js', shapes: ['mirror'],
183
- note: 'the ONE claude-child argv builder (rule 4); resolved by claude-pro.js at call time' },
184
- { src: 'one/src/permissions.js', shapes: ['mirror'],
185
- note: 'resolvePosture() — the permission half of the argv, resolved at call time' },
186
- { src: 'desktop/lib/local/local.js', shapes: ['mirror'],
187
- note: 'the local model transport and its fail-closed base-URL check' },
188
- // The row whose ABSENCE broke the packaged CLI: `local.js` requires
189
- // `./context.js` at load (for the token-budget trimmer), context.js is a
190
- // committed module — and it had no manifest row, so no staged tree ever
191
- // carried it. `require('./context.js')` then threw MODULE_NOT_FOUND from
192
- // inside vendor/, which is the failure test/cli-approval.test.mjs and
193
- // test/cli-package.test.mjs were reporting: the packaged CLI could not load
194
- // at all. A manifest that lists a module's DEPENDENCIES by hand is exactly
195
- // where this hides, so test/one-manifest-complete.test.mjs now derives the
196
- // rule instead of trusting the list.
197
- { src: 'desktop/lib/local/context.js', shapes: ['mirror'],
198
- note: 'the token-budget trimmer local.js requires at load' },
199
- { src: 'desktop/lib/local/session-rounds.js', shapes: ['mirror'],
200
- note: 'interrupted-turn bookkeeping; required at load by engine.js' },
201
- { src: 'desktop/lib/local/tools.js', shapes: ['mirror'],
202
- note: 'the tool implementations (persistent shell, editFile, grep, exec)' },
203
- { src: 'desktop/lib/local/shell.js', shapes: ['mirror'],
204
- note: 'the persistent shell, required by tools.js' },
205
- { src: 'desktop/lib/local/agents.js', shapes: ['mirror'],
206
- note: 'Task subagents' },
207
- { src: 'desktop/lib/local/prompt.js', shapes: ['mirror'],
208
- note: 'the system prompt builder' },
209
- { src: 'desktop/lib/settings.js', shapes: ['mirror'],
210
- note: 'the provider-config store (base URL + key per provider)' },
211
- { src: 'desktop/lib/local/turn-guard.js', shapes: ['mirror'],
212
- note: 'engine.js requires it at load; it requires ./git-scope.js' },
213
- { src: 'desktop/lib/local/worktree-lock.js', shapes: ['mirror'],
214
- note: 'engine.js requires it at load' },
215
- { src: 'desktop/lib/local/git-scope.js', shapes: ['mirror'],
216
- note: 'the write-scope rule turn-guard.js and the queues share' },
217
- { src: 'desktop/lib/local/queue.js', shapes: ['mirror'],
218
- note: 'the autonomous work queue' },
219
- { src: 'desktop/lib/local/autonomous.js', shapes: ['mirror'],
220
- note: 'the unattended worker; requires ./queue.js and ./git-scope.js' },
221
- { src: 'desktop/lib/local/entitlement.js', shapes: ['mirror'],
222
- note: 'the shared Pro gate (account probe injected by the caller)' },
223
- { src: 'desktop/lib/local/covenant.js', shapes: ['mirror'],
224
- note: 'the pre-action gate engine.js requires unconditionally at load' },
225
- { src: 'desktop/lib/local/aegis-seal.mjs', shapes: ['mirror'],
226
- note: 'the codec covenant.js requires the first time it decodes' },
227
-
228
- // ── the sealed covenant: the one row whose SHAPE is load-bearing ────────
229
- // covenant.js resolves the artifact at `../../vendor/covenant/aegis.seal`
230
- // relative to itself, so it must keep the repo's path under vendor/ — flat
231
- // staging would place it where nothing looks, and the host would then report
232
- // `available: false` and enforce only the hard-coded immutable trio while
233
- // every other clause is silently gone.
234
- { src: 'covenant/aegis.seal', shapes: ['mirror', 'nested'],
235
- note: 'the sealed covenant (AES/1 container) — path shape is load-bearing' },
236
- { src: 'covenant/README.md', shapes: ['mirror', 'nested'],
237
- note: 'the decode notice shipped beside the artifact' },
238
-
239
- // ── the agent-key gate ─────────────────────────────────────────────────
240
- { src: 'tools/agent-gate.mjs', shapes: ['mirror', 'flat'],
241
- note: 'the in-process half of the lock; without it a packaged app had NO gate' },
242
- ];
243
-
244
- /** Rows in a given shape: `{src, dest}` pairs, destination computed here only. */
245
- export function entriesFor(shape) {
246
- const out = [];
247
- for (const row of MANIFEST) {
248
- if (!row.shapes.includes(shape)) continue;
249
- let dest;
250
- if (shape === 'mirror') dest = path.join(CLI_VENDOR, row.src);
251
- else if (shape === 'flat') dest = path.join(DESKTOP_VENDOR, path.basename(row.src));
252
- else if (shape === 'nested') dest = path.join(DESKTOP_VENDOR, row.src);
253
- else throw new Error(`predist: unknown shape ${shape}`);
254
- out.push({ src: row.src, dest, from: path.join(REPO_DIR, row.src) });
255
- }
256
- return out;
257
- }
258
-
259
- /** Every distinct shape named by the manifest, in a stable order. */
260
- export const SHAPES = ['mirror', 'flat', 'nested'];
261
-
262
- // ---------------------------------------------------------------------------
263
- // The product bundle: `one/vendor/cli/**` and `one/vendor/desktop/**`
264
- // ---------------------------------------------------------------------------
265
- //
266
- // `npm pack one/` has to produce a package that BOOTS. The two faces keep their
267
- // self-similar shape inside it, which is why no resolver changed to make this
268
- // work: `cli/src/sharedpaths.js` tries `<cli>/../../client` (absent in the
269
- // bundle, so it falls through) and then `<cli>/vendor/client` — staged above,
270
- // inside the bundle. The bundle is copied from the already-verified trees, so
271
- // the byte-identity proof covers these bytes too.
272
- const BUNDLE_SOURCES = [
273
- ['cli', CLI_DIR, ['bin', 'src', 'vendor', 'scripts', 'package.json', 'README.md', 'LICENSE']],
274
- [
275
- 'desktop',
276
- DESKTOP_DIR,
277
- ['main.js', 'preload.js', 'lib', 'renderer', 'bin', 'vendor', 'package.json', 'README.md'],
278
- ],
279
- ];
280
-
281
- /** Directory names that must never be copied into a published bundle. */
282
- const BUNDLE_EXCLUDE = new Set(['node_modules', 'release', '.git', '.cache', 'out']);
283
-
284
- function copyTree(from, toDir) {
285
- const skip = (name) => BUNDLE_EXCLUDE.has(name) || name.endsWith('.log');
286
- const copyFile = (file, dest) => {
287
- fs.mkdirSync(path.dirname(dest), { recursive: true });
288
- fs.copyFileSync(file, dest);
289
- if (!fs.readFileSync(file).equals(fs.readFileSync(dest))) {
290
- throw new Error(`predist: bundle copy differs from source: ${path.relative(REPO_DIR, file)}`);
291
- }
292
- };
293
- const walk = (dir, rel) => {
294
- const stat = fs.lstatSync(dir);
295
- // Symlinks are skipped rather than followed: a bundle that resolved through
296
- // one would pack a path that only exists on the machine that built it.
297
- if (stat.isSymbolicLink()) return;
298
- if (stat.isFile()) {
299
- copyFile(dir, path.join(toDir, rel));
300
- return;
301
- }
302
- for (const name of fs.readdirSync(dir)) {
303
- if (skip(name)) continue;
304
- walk(path.join(dir, name), rel ? path.join(rel, name) : name);
305
- }
306
- };
307
- // When `from` is a file, `toDir` is the file's FINAL path — not a directory to
308
- // append the basename to. The bundle's `parts` mix directories and files
309
- // (`bin`, `src`, … alongside `package.json`, `main.js`, `LICENSE`), and
310
- // treating both as directories nested every file one level too deep:
311
- // `one/vendor/cli/package.json/package.json`, `one/vendor/desktop/main.js/main.js`.
312
- // The module-resolution proof did not notice, because `deps.js` resolves the
313
- // shared modules and never the face's own entry point — so the tarball packed
314
- // and installed cleanly with no `main.js` anywhere in it. Only
315
- // `test/one-pack-boot.test.mjs` (ON2's real gate: pack → temp prefix → run)
316
- // exposed it; `proveBundle` now asserts the shapes directly.
317
- if (fs.lstatSync(from).isFile()) copyFile(from, toDir);
318
- else walk(from, '');
319
- }
320
-
321
- // ---------------------------------------------------------------------------
322
- // Mutual exclusion — one stager at a time per checkout
323
- // ---------------------------------------------------------------------------
324
- //
325
- // Staging is destructive by construction: `stageFiles(entries, CLI_VENDOR)`
326
- // removes `cli/vendor/` outright and re-copies every module into it, and the
327
- // bundle step does the same to `one/vendor/<face>/`. Two stagers in the same
328
- // checkout therefore cannot merely interleave harmlessly — the second one's
329
- // `rmSync` unlinks the tree the first one is still reading, and the first one's
330
- // per-file byte comparison (`readFileSync(from).equals(readFileSync(dest))`)
331
- // then fails, or the second one's copy is read half-written.
332
- //
333
- // That is not hypothetical: `test/one-vendor.test.mjs` and
334
- // `test/one-pack-boot.test.mjs` each shell out to this file, so running the
335
- // suite with block-level concurrency puts two stagers in the same tree at once.
336
- // Both pass alone and each can fail when overlapped, which reads as a flaky
337
- // gate rather than as the data race it is. The lock below is what makes the
338
- // gate honest under concurrency instead of pretending the race is a test bug.
339
- //
340
- // The lock file lives in this checkout's OWN git directory, and that location
341
- // is load-bearing three ways over:
342
- //
343
- // * It cannot be the OS temp dir — resolving that is an OS answer, and `one/`'s
344
- // seam rule (asserted by test/one-vendor.test.mjs) forbids this file from
345
- // knowing the platform at all: that answer belongs to `client/platform.js`.
346
- // * It cannot be `one/`, `cli/` or the repo root: an untracked lock file there
347
- // is visible to `git status` and one `git add -A` from being committed.
348
- // * It cannot be under any vendor tree, because `stageFiles(entries, CLI_VENDOR)`
349
- // deletes those — the lock would be destroyed by the very thing it guards.
350
- //
351
- // `.git` is per-checkout (so the `aegiscode-plugin-verify-main` worktree locks
352
- // independently, correctly), is never packed by `npm pack`, and is reachable
353
- // from every stager for this tree. In a linked worktree `.git` is a FILE
354
- // (`gitdir: …`) rather than a directory, so it is followed to its gitdir.
355
- const LOCK_WAIT_MS = 120000; // how long to wait for a peer before giving up
356
- const LOCK_STALE_MS = 600000; // a lock older than this is abandoned, not held
357
- const LOCK_POLL_MS = 50;
358
- /** The token a holder hands to its own descendants through the environment. */
359
- const LOCK_ENV = 'AEGISONE_PREDIST_LOCK_TOKEN';
360
-
361
- /** The lock file this process is inside, or null. */
362
- let LOCK_HELD = null;
363
- /** Only the process that CREATED the lock unlinks it. */
364
- let LOCK_OWNS = false;
365
- /** In-process nesting: a reader may hold the lock while stage() is called. */
366
- let LOCK_DEPTH = 0;
367
-
368
- function lockFile() {
369
- const dotGit = path.join(REPO_DIR, '.git');
370
- let dir = dotGit;
371
- try {
372
- if (!fs.lstatSync(dotGit).isDirectory()) {
373
- const m = /^gitdir:\s*(.+)$/m.exec(fs.readFileSync(dotGit, 'utf8'));
374
- if (m) dir = path.resolve(REPO_DIR, m[1].trim());
375
- }
376
- } catch {
377
- dir = dotGit; // no `.git` at all (an exported tree): the open below reports it
378
- }
379
- return path.join(dir, 'aegisone-predist.lock');
380
- }
381
-
382
- /** Is `pid` a live process? Signal 0 tests existence without signalling. */
383
- function pidAlive(pid) {
384
- try {
385
- process.kill(pid, 0);
386
- return true;
387
- } catch (error) {
388
- // EPERM means it exists and belongs to someone else — still alive.
389
- return Boolean(error) && error.code === 'EPERM';
390
- }
391
- }
392
-
393
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
394
-
395
- /**
396
- * Take the staging lock, or adopt the one an ANCESTOR already holds.
397
- *
398
- * Waiting is the right failure mode against a peer, and failing fast would not
399
- * be: the peer is about to produce exactly the tree this run wants, so the two
400
- * are not so much competing for a resource as queueing for it. A stale lock is
401
- * broken (dead pid, or older than LOCK_STALE_MS) so a killed stager cannot wedge
402
- * every later run — the alternative, a lock no one can clear, trades a rare
403
- * flake for a permanent one.
404
- *
405
- * ADOPTION is what makes the lock usable by a *reader*. `test/one-vendor.test.mjs`
406
- * asserts on the staged trees, and it also spawns both wrapper scripts with
407
- * `spawnSync` — which BLOCKS its own process. If those children had to queue for
408
- * a lock their parent is holding, the parent would block waiting for a child
409
- * that is waiting for the parent: a guaranteed 120-second deadlock, in the gate
410
- * that is supposed to prove staging works. So the holder writes a random token
411
- * into the lock file and exports it; a descendant that sees its OWN token in the
412
- * file is the same logical stager, runs immediately, and leaves the unlinking to
413
- * the process that created it.
414
- */
415
- async function takeLock(log) {
416
- const file = lockFile();
417
- const deadline = Date.now() + LOCK_WAIT_MS;
418
- const inherited = process.env[LOCK_ENV] || null;
419
- let token = null;
420
- let announced = false;
421
- for (;;) {
422
- // Adopt before waiting: the lock is held by our own ancestor.
423
- if (inherited) {
424
- try {
425
- const tokenLine = String(fs.readFileSync(file, 'utf8')).split('\n')[1];
426
- // The token match IS the test: it is a random value that only ever
427
- // existed inside this process tree, so a foreign holder's file cannot
428
- // match it and we will queue for that one like anybody else.
429
- if (tokenLine && tokenLine.trim() === inherited) {
430
- LOCK_HELD = file;
431
- LOCK_OWNS = false;
432
- return;
433
- }
434
- } catch {
435
- /* no lock file: fall through and take it normally */
436
- }
437
- }
438
- try {
439
- token = `${Date.now().toString(36)}-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
440
- const fd = fs.openSync(file, 'wx'); // atomic create-or-fail
441
- fs.writeSync(fd, `${process.pid}\n${token}\n`);
442
- fs.closeSync(fd);
443
- LOCK_HELD = file;
444
- LOCK_OWNS = true;
445
- // Handed to every descendant for the duration, so a stager this process
446
- // spawns (the two wrappers the suite runs) does not deadlock against us.
447
- process.env[LOCK_ENV] = token;
448
- return;
449
- } catch (error) {
450
- if (!error || error.code !== 'EEXIST') throw error;
451
- }
452
- // Somebody holds it. Decide whether they are still alive.
453
- let stat = null;
454
- let holder = 0;
455
- try {
456
- stat = fs.statSync(file);
457
- holder = Number(String(fs.readFileSync(file, 'utf8')).split('\n')[0].trim());
458
- } catch {
459
- continue; // released between the open and the stat — retry immediately
460
- }
461
- const abandoned =
462
- Date.now() - stat.mtimeMs > LOCK_STALE_MS ||
463
- (Number.isFinite(holder) && holder > 0 && !pidAlive(holder));
464
- if (abandoned) {
465
- log(`predist: breaking an abandoned staging lock (pid ${holder || 'unknown'})`);
466
- try {
467
- fs.unlinkSync(file);
468
- } catch {
469
- /* the holder released it first — the next open will succeed */
470
- }
471
- continue;
472
- }
473
- if (Date.now() > deadline) {
474
- throw new Error(
475
- `predist: another stager (pid ${holder || 'unknown'}) has held ${file} for over ` +
476
- `${Math.round(LOCK_WAIT_MS / 1000)}s. Staging is destructive — it removes and ` +
477
- 'rewrites cli/vendor, desktop/vendor and one/vendor — so it will not run ' +
478
- 'concurrently with a peer. Wait for it, or delete the lock if that process is gone.'
479
- );
480
- }
481
- if (!announced) {
482
- announced = true;
483
- log(
484
- `predist: another stager (pid ${holder || 'unknown'}) is running — waiting for it ` +
485
- '(concurrent staging would read a vendor tree the peer is rewriting)'
486
- );
487
- }
488
- await sleep(LOCK_POLL_MS + Math.floor(Math.random() * LOCK_POLL_MS));
489
- }
490
- }
491
-
492
- function releaseLock() {
493
- if (LOCK_DEPTH > 0) {
494
- LOCK_DEPTH--;
495
- return;
496
- }
497
- const file = LOCK_HELD;
498
- const owns = LOCK_OWNS;
499
- const token = process.env[LOCK_ENV];
500
- LOCK_HELD = null;
501
- LOCK_OWNS = false;
502
- if (!file || !owns) return; // an adopted lock is released by its creator
503
- if (token) delete process.env[LOCK_ENV];
504
- try {
505
- fs.unlinkSync(file);
506
- } catch {
507
- /* already gone, or broken as stale by a peer — either way we no longer hold it */
508
- }
509
- }
510
-
511
- /**
512
- * Hold the staging lock across an arbitrary span — staging AND the reads that
513
- * check what was staged — releasing when the returned function is called.
514
- *
515
- * Exported because a reader is a legitimate participant: whoever asserts on
516
- * `cli/vendor/` while another process may be re-staging it has the same race as
517
- * two stagers do, and `stage()`'s own critical section ends too early to cover
518
- * the assertions that follow it. Re-entrant in-process (a holder may call
519
- * `stage()`), and adopted by descendants through LOCK_ENV — see `takeLock`.
520
- *
521
- * @param {{stdout?: object}} [io] where the "waiting for a peer" line is written
522
- * @returns {Promise<() => void>} the release function
523
- */
524
- export async function acquireStageLock(io) {
525
- if (LOCK_HELD) {
526
- LOCK_DEPTH++;
527
- return releaseLock;
528
- }
529
- const out = (io && io.stdout) || process.stdout;
530
- await takeLock((line) => out.write(`${line}\n`));
531
- return releaseLock;
532
- }
533
-
534
- // ---------------------------------------------------------------------------
535
- // Staging primitives
536
- // ---------------------------------------------------------------------------
537
-
538
- function stageFiles(entries, removeRoot) {
539
- if (removeRoot) fs.rmSync(removeRoot, { recursive: true, force: true });
540
- const staged = [];
541
- for (const entry of entries) {
542
- if (!fs.existsSync(entry.from)) {
543
- throw new Error(`predist: missing shared module: ${entry.src} (expected at ${entry.from})`);
544
- }
545
- fs.mkdirSync(path.dirname(entry.dest), { recursive: true });
546
- fs.copyFileSync(entry.from, entry.dest);
547
- if (!fs.readFileSync(entry.from).equals(fs.readFileSync(entry.dest))) {
548
- throw new Error(`predist: staged copy differs from source: ${entry.src}`);
549
- }
550
- staged.push(entry);
551
- }
552
- return staged;
553
- }
554
-
555
- // ---------------------------------------------------------------------------
556
- // Proofs
557
- // ---------------------------------------------------------------------------
558
-
559
- /**
560
- * The CLI's standalone-load proof, carried over unchanged in substance: the
561
- * staged registry must build from inside `cli/vendor/`, the editor layer must
562
- * resolve the STAGED server (not a checkout path), and the staged gate module
563
- * must load.
564
- */
565
- function proveMirror(staged) {
566
- const toolsPath = path.join(CLI_VENDOR, 'mcp', 'tools.js');
567
- delete require.cache[require.resolve(toolsPath)];
568
- const { createTools } = require(toolsPath);
569
- const tools = createTools({
570
- apiBase: 'http://127.0.0.1',
571
- apiKey: 'predist-probe',
572
- randomUUID: () => 'id',
573
- });
574
- const count = tools.toolList().length;
575
- if (count === 0) throw new Error('predist: staged registry exposes no tools');
576
-
577
- // mcp/server.js registers process.stdin handlers at LOAD time and exports
578
- // nothing, so requiring it would take over this process's stdin and it would
579
- // never exit. It is verified by COMPILING it instead.
580
- const vm = require('node:vm');
581
- const serverJs = path.join(CLI_VENDOR, 'mcp', 'server.js');
582
- new vm.Script(fs.readFileSync(serverJs, 'utf8'), { filename: serverJs });
583
-
584
- const hostsDir = path.join(CLI_VENDOR, 'hosts');
585
- const spec = require(path.join(hostsDir, 'spec.js'));
586
- const install = require(path.join(hostsDir, 'install.js'));
587
- const targets = require(path.join(hostsDir, 'targets.js'));
588
-
589
- // An empty AEGIS_MCP_SERVER so a developer's own override cannot mask a
590
- // broken staged tree: the candidate asserted on must be the staged one.
591
- const resolved = spec.resolveServer({ AEGIS_MCP_SERVER: '' });
592
- if (!resolved.exists || resolved.path !== serverJs) {
593
- throw new Error(
594
- `predist: staged hosts/spec.js resolves the server as ${resolved.path} ` +
595
- `(exists: ${resolved.exists}), expected ${serverJs}. An installed aegiscode ` +
596
- `would write editor configs pointing at a file the package never shipped. ` +
597
- `Candidates were:\n ${resolved.candidates.join('\n ')}`
598
- );
599
- }
600
-
601
- // Plan one real install against a throwaway home: the exact document
602
- // `aegiscode mcp install vscode` would write, so the cheapest possible proof
603
- // that the packaged command points at a file that exists.
604
- const vscode = targets.getTarget('vscode');
605
- const plan = install.planTarget(vscode, 'user', {
606
- ctx: install.hostCtx({ home: path.join(CLI_VENDOR, '.predist-home'), env: {}, cwd: REPO_DIR }),
607
- specOpts: { env: { AEGIS_MCP_SERVER: '' } },
608
- });
609
- const wrote = JSON.stringify(plan.after || '');
610
- if (
611
- plan.error ||
612
- !plan.changed ||
613
- !wrote.includes(JSON.stringify(serverJs).slice(1, -1))
614
- ) {
615
- throw new Error(
616
- `predist: a planned vscode install does not name the staged server ` +
617
- `(error: ${plan.error && plan.error.message}, changed: ${plan.changed})`
618
- );
619
- }
620
-
621
- const shim = require(path.join(hostsDir, 'openai-shim.js'));
622
- if (typeof shim.createShimServer !== 'function') {
623
- throw new Error('predist: staged hosts/openai-shim.js exposes no createShimServer');
624
- }
625
-
626
- return { count, targets: targets.targetIds().length, staged: staged.length };
627
- }
628
-
629
- /** The gate is an ES module, so its proof is a dynamic import. */
630
- async function proveGate() {
631
- const gateStagedPath = path.join(CLI_VENDOR, 'tools', 'agent-gate.mjs');
632
- const gateMod = await import(pathToFileURL(gateStagedPath).href);
633
- if (typeof gateMod.run !== 'function') {
634
- throw new Error('predist: staged tools/agent-gate.mjs exposes no run()');
635
- }
636
- return gateStagedPath;
637
- }
638
-
639
- /**
640
- * The desktop's standalone-load proof — the property flattening depends on and
641
- * which nothing asserted before: a flat-staged module must resolve its siblings
642
- * from the SAME vendor directory. A `require('../client/...')` that survived
643
- * flattening would resolve outside the packaged app (electron-builder cannot
644
- * ship those files at all), so it is a hard failure here rather than a
645
- * MODULE_NOT_FOUND in a user's window.
646
- */
647
- /**
648
- * Drop comments before scanning for requires. `client/aegis.js` documents its
649
- * own usage as `require('./client/aegis.js')` inside a JSDoc block, which a raw
650
- * scan reads as a self-referential dependency — the first run of this proof
651
- * failed on exactly that line, which is why the strip is here and not in a
652
- * comment promising it happens.
653
- */
654
- function stripComments(source) {
655
- return source.replace(/\/\*[\s\S]*?\*\//g, '').replace(/(^|[^:])\/\/.*$/gm, '$1');
656
- }
657
-
658
- function proveFlat(staged) {
659
- const flatNames = new Set(staged.map((e) => path.basename(e.dest)));
660
- for (const entry of staged) {
661
- const src = stripComments(fs.readFileSync(entry.dest, 'utf8'));
662
- for (const m of src.matchAll(/require\(\s*'((?:\.\.?\/)[^']+)'\s*\)/g)) {
663
- const spec = m[1];
664
- const target = path.basename(spec).replace(/\.[cm]?js$/, '');
665
- const sibling = spec.replace(/^\.\//, '');
666
- if (sibling.startsWith('../')) {
667
- throw new Error(
668
- `predist: flat-staged ${path.basename(entry.dest)} requires '${spec}', ` +
669
- 'which escapes vendor/ — flattening only works for same-directory requires ' +
670
- `(add the target to the manifest, or stop staging this file flat)${target ? '' : ''}`
671
- );
672
- }
673
- const asFile = spec.replace(/^\.\//, '');
674
- if (!flatNames.has(asFile)) {
675
- throw new Error(
676
- `predist: flat-staged ${path.basename(entry.dest)} requires '${spec}', ` +
677
- `which is not staged into desktop/vendor/ — the packaged app would throw ` +
678
- 'MODULE_NOT_FOUND before the window could open'
679
- );
680
- }
681
- }
682
- }
683
-
684
- // …and the transport itself must actually LOAD from the flattened tree.
685
- const transport = require(path.join(DESKTOP_VENDOR, 'aegis.js'));
686
- if (!transport || Object.keys(transport).length === 0) {
687
- throw new Error('predist: staged desktop/vendor/aegis.js loads but exports nothing');
688
- }
689
- return { files: staged.length, exports: Object.keys(transport).length };
690
- }
691
-
692
- /**
693
- * The bundle proof: `one/vendor/cli` must resolve EVERY shared module from
694
- * inside the PRODUCT BUNDLE (`one/vendor/`), never from the repo checkout.
695
- *
696
- * The boundary is the bundle root and not `one/vendor/cli`, and that is not a
697
- * softened assertion — it is the layout rule itself. The bundle keeps the repo's
698
- * shape with the two faces as SIBLINGS (`one/vendor/cli`, `one/vendor/desktop`),
699
- * so `cli/src/deps.js`'s repo-shaped candidate `../desktop/renderer/usage.js`
700
- * lands on the bundled desktop face exactly as it does in a checkout. The first
701
- * run of this proof failed on that path, which is how the rule got written down
702
- * here instead of being assumed: it is the sibling face copy, one directory
703
- * over, not the repo.
704
- *
705
- * It runs as a child process with its cwd inside the bundle, so a path that only
706
- * exists in the repo fails here rather than after `npm i -g aegisone`.
707
- */
708
- function proveBundle() {
709
- const bundleCli = path.join(ONE_VENDOR, 'cli');
710
- const depsPath = path.join(bundleCli, 'src', 'deps.js');
711
- const script =
712
- 'const d=require(process.argv[1]);' +
713
- 'console.log(JSON.stringify(d.paths))';
714
- const res = spawnSync(process.execPath, ['-e', script, depsPath], {
715
- cwd: bundleCli,
716
- encoding: 'utf8',
717
- });
718
- if (res.status !== 0) {
719
- throw new Error(`predist: the bundled CLI does not load: ${res.stderr || res.stdout}`);
720
- }
721
- const paths = JSON.parse(res.stdout);
722
- const outside = [];
723
- let inSiblingFace = 0;
724
- for (const [name, p] of Object.entries(paths)) {
725
- const rel = path.relative(ONE_VENDOR, p);
726
- if (rel.startsWith('..') || path.isAbsolute(rel)) {
727
- outside.push(`${name} -> ${p}`);
728
- continue;
729
- }
730
- if (rel.split(path.sep)[0] !== 'cli') inSiblingFace++;
731
- }
732
- if (outside.length) {
733
- throw new Error(
734
- 'predist: the bundled CLI resolves these shared modules OUTSIDE the bundle ' +
735
- `(${ONE_VENDOR}) — the product tarball would depend on a repo checkout:\n ` +
736
- outside.join('\n ')
737
- );
738
- }
739
- const binShipped = fs.existsSync(path.join(bundleCli, 'bin', 'aegiscode.js'));
740
- if (!binShipped) throw new Error('predist: the bundle has no cli/bin/aegiscode.js');
741
-
742
- // Every bundled part keeps the shape its SOURCE had. This is the assertion
743
- // that would have caught `main.js/main.js`: the module-resolution proof above
744
- // says nothing about a face's own entry point, so a bundle can pass every
745
- // check here and still pack without the file the desktop face is launched by.
746
- const wrongShape = [];
747
- for (const [name, dir, parts] of BUNDLE_SOURCES) {
748
- for (const part of parts) {
749
- const dest = path.join(ONE_VENDOR, name, part);
750
- let srcStat = null;
751
- let destStat = null;
752
- try {
753
- srcStat = fs.lstatSync(path.join(dir, part));
754
- } catch {
755
- continue; // reported by the staging loop
756
- }
757
- try {
758
- destStat = fs.lstatSync(dest);
759
- } catch {
760
- wrongShape.push(`${name}/${part} -> missing`);
761
- continue;
762
- }
763
- if (srcStat.isFile() && !destStat.isFile()) wrongShape.push(`${name}/${part} -> not a regular file`);
764
- if (srcStat.isDirectory() && !destStat.isDirectory()) wrongShape.push(`${name}/${part} -> not a directory`);
765
- }
766
- }
767
- if (wrongShape.length) {
768
- throw new Error(`predist: the bundle staged these in the wrong shape:\n ${wrongShape.join('\n ')}`);
769
- }
770
- return { modules: Object.keys(paths).length, inSiblingFace };
771
- }
772
-
773
- // ---------------------------------------------------------------------------
774
- // The one entry point
775
- // ---------------------------------------------------------------------------
776
-
777
- /**
778
- * Stage every requested shape, then prove what was staged.
779
- *
780
- * @param {object} [opts]
781
- * @param {string[]} [opts.shapes] subset of SHAPES plus 'bundle'
782
- * @param {object} [opts.io] { stdout, stderr } — injectable, so a test can
783
- * capture this without capturing the process
784
- * @returns {Promise<object>} a report of what was staged and proven
785
- */
786
- export async function stage(opts) {
787
- const o = opts || {};
788
- const io = o.io || {};
789
- const out = io.stdout || process.stdout;
790
- const errOut = io.stderr || process.stderr;
791
- const shapes = Array.isArray(o.shapes) ? o.shapes : [...SHAPES, 'bundle'];
792
- const want = (s) => shapes.includes(s);
793
- const log = (line) => out.write(`${line}\n`);
794
-
795
- // The whole body is one critical section: every shape below removes and
796
- // rewrites a shared tree, and the proofs read those trees back. Held from
797
- // here to the end, released even when a proof throws — a thrown proof that
798
- // kept the lock would wedge every later run in this checkout. A caller that
799
- // already holds it (a test asserting on the staged trees) keeps holding it:
800
- // `acquireStageLock` nests in-process.
801
- const release = await acquireStageLock(io);
802
- try {
803
- return await stageLocked({ want, log });
804
- } finally {
805
- release();
806
- }
807
- }
808
-
809
- async function stageLocked({ want, log }) {
810
- const report = { mirror: null, flat: null, nested: null, bundle: null };
811
-
812
- if (want('mirror')) {
813
- const staged = stageFiles(entriesFor('mirror'), CLI_VENDOR);
814
- log(`predist: staged ${staged.length} shared modules into cli/vendor/`);
815
- for (const e of staged) log(` ${e.src} -> vendor/${e.src}`);
816
- report.mirror = { staged: staged.length };
817
- }
818
-
819
- if (want('nested')) {
820
- report.nested = { staged: stageFiles(entriesFor('nested'), null).length };
821
- }
822
-
823
- if (want('flat')) {
824
- const staged = stageFiles(entriesFor('flat'), null);
825
- for (const e of staged) log(`staged ${e.dest}`);
826
- report.flat = { staged: staged.length };
827
- }
828
-
829
- // One manifest, two shapes: wherever a module appears twice, the two copies
830
- // must be byte-identical to EACH OTHER as well as to the source. Nothing
831
- // asserted this before, and it is the whole payoff of a single manifest.
832
- if (want('mirror') && want('flat')) {
833
- for (const row of MANIFEST) {
834
- if (!row.shapes.includes('mirror') || !row.shapes.includes('flat')) continue;
835
- const a = path.join(CLI_VENDOR, row.src);
836
- const b = path.join(DESKTOP_VENDOR, path.basename(row.src));
837
- if (!fs.readFileSync(a).equals(fs.readFileSync(b))) {
838
- throw new Error(`predist: the two shapes disagree for ${row.src}`);
839
- }
840
- }
841
- }
842
-
843
- if (want('mirror')) {
844
- const p = proveMirror(entriesFor('mirror'));
845
- log(`predist: staged registry loads standalone (${p.count} tools)`);
846
- log(
847
- `predist: editor layer verified (${p.targets} host targets, ` +
848
- `server resolves to vendor/mcp/server.js, shim loads)`
849
- );
850
- const gate = await proveGate();
851
- log(`predist: ${path.relative(REPO_DIR, gate)} loads standalone and exposes run()`);
852
- report.mirror.proof = p;
853
- }
854
-
855
- if (want('flat')) {
856
- const p = proveFlat(entriesFor('flat'));
857
- log(
858
- `predist: flattened tree is self-contained (${p.files} files, ` +
859
- `${p.exports} transport exports) — no staged module escapes vendor/`
860
- );
861
- report.flat.proof = p;
862
- }
863
-
864
- if (want('bundle')) {
865
- for (const [name, dir, parts] of BUNDLE_SOURCES) {
866
- const to = path.join(ONE_VENDOR, name);
867
- fs.rmSync(to, { recursive: true, force: true });
868
- for (const part of parts) {
869
- const from = path.join(dir, part);
870
- if (!fs.existsSync(from)) {
871
- if (part === 'LICENSE' || part === 'README.md') continue;
872
- throw new Error(`predist: bundle source missing: ${path.relative(REPO_DIR, from)}`);
873
- }
874
- copyTree(from, path.join(to, part));
875
- }
876
- log(`staged the ${name} face into one/vendor/${name}/`);
877
- }
878
- const p = proveBundle();
879
- log(
880
- `predist: the bundled CLI resolves ${p.modules} shared modules from inside ` +
881
- `one/vendor/ (${p.inSiblingFace} through the bundled desktop face) — ` +
882
- 'no repo checkout needed'
883
- );
884
- report.bundle = p;
885
- }
886
-
887
- return report;
888
- }
889
-
890
- /**
891
- * CLI entry. `argv` and the streams are parameters so the seam survives: a test
892
- * passes its own, and nothing in this file reads the process at module scope.
893
- */
894
- export async function main(argv, io) {
895
- const o = io || {};
896
- const args = Array.isArray(argv) ? argv : [];
897
- // `--quiet` is not cosmetic: `prepack` runs this stager, and `npm pack --json`
898
- // interleaves hook stdout with its own JSON report. A caller that parses that
899
- // report (`test/one-pack-boot.test.mjs`) gets the progress lines instead of
900
- // JSON and fails. So the progress stream is silenced here rather than by
901
- // every caller remembering to.
902
- const quiet = args.includes('--quiet');
903
- const sink = { write: () => true };
904
- const out = quiet ? sink : o.stdout || process.stdout;
905
- const errOut = o.stderr || process.stderr;
906
- let shapes;
907
- if (args.includes('--mirror-only')) shapes = ['mirror'];
908
- else if (args.includes('--flat-only')) shapes = ['flat', 'nested'];
909
- else if (args.includes('--bundle-only')) shapes = ['bundle'];
910
- try {
911
- await stage({ shapes, io: { stdout: out, stderr: errOut } });
912
- return 0;
913
- } catch (error) {
914
- errOut.write(`${error && error.message}\n`);
915
- return 1;
916
- }
917
- }
918
-
919
- /**
920
- * Run when — and only when — this file was started directly
921
- * (`node one/scripts/predist.mjs`). The process reads live inside a function on
922
- * purpose: the seam rule for `one/` is that no `process.*` is read at module
923
- * scope, and this is the file that would have broken it.
924
- */
925
- function runIfDirect() {
926
- const entry = process.argv[1];
927
- let direct = false;
928
- if (entry) {
929
- try {
930
- direct = path.resolve(entry) === fileURLToPath(import.meta.url);
931
- } catch {
932
- direct = false;
933
- }
934
- }
935
- if (!direct) return false;
936
- main(process.argv.slice(2)).then((code) => {
937
- process.exitCode = code;
938
- });
939
- return true;
940
- }
941
-
942
- runIfDirect();
4
+ import e from"node:fs";import r from"node:path";import{spawnSync as s}from"node:child_process";import{fileURLToPath as t,pathToFileURL as o}from"node:url";import{createRequire as n}from"node:module";const i=r.dirname(t(import.meta.url)),a=n(import.meta.url);export const ONE_DIR=r.join(i,"..");export const REPO_DIR=r.join(ONE_DIR,"..");export const CLI_DIR=r.join(REPO_DIR,"cli");export const DESKTOP_DIR=r.join(REPO_DIR,"desktop");export const CLI_VENDOR=r.join(CLI_DIR,"vendor");export const DESKTOP_VENDOR=r.join(DESKTOP_DIR,"vendor");export const ONE_VENDOR=r.join(ONE_DIR,"vendor");export const MANIFEST=[{src:"client/aegis.js",shapes:["mirror","flat"],note:"the thin transport — the one implementation of the wire format"},{src:"client/update.js",shapes:["mirror","flat"],note:"the npm update checker (the desktop own update path)"},{src:"client/foreign-memory.js",shapes:["mirror","flat"],note:"required by mcp/tools.js as ../client/foreign-memory.js"},{src:"client/credentials.js",shapes:["mirror","flat"],note:"the account credential store, shared by all three hosts"},{src:"client/session-store.js",shapes:["mirror","flat"],note:"the unified session store — one list in every host"},{src:"client/prefs.js",shapes:["mirror","flat"],note:"the shared non-secret preference store (D5) — the CLI and the desktop store both read/write it"},{src:"client/env-file.js",shapes:["mirror","flat"],note:"the shared ~/.aegiscode/.env loader, resolved before any key is read"},{src:"client/auto-provision.js",shapes:["mirror","flat"],note:"free device key on first launch; requires ./device-fingerprint.js"},{src:"client/device-fingerprint.js",shapes:["mirror","flat"],note:"the machine identity auto-provision.js and presence.js require"},{src:"client/presence.js",shapes:["mirror","flat"],note:"the heartbeat beacon; requires ./presence-constants.js and ./device-fingerprint.js"},{src:"client/presence-constants.js",shapes:["mirror","flat"],note:"the beacon constants — a package without them loses the beacon silently"},{src:"client/touch.js",shapes:["mirror","flat"],note:"phi(alpha): the digest module fingerprint.js requires as ./touch.js"},{src:"client/fingerprint.js",shapes:["mirror","flat"],note:"phi(alpha): the sealed session record, resolved by src/fingerprint.js"},{src:"client/authorship-key.js",shapes:["mirror","flat"],note:"phi(alpha): the authorship key, required by ./attest.js and ./record-vault.js"},{src:"client/attest.js",shapes:["mirror","flat"],note:"phi(alpha): attestation, requires ./fingerprint.js and ./authorship-key.js"},{src:"client/record-vault.js",shapes:["mirror","flat"],note:"the vault, and its refusal to copy the key with the record"},{src:"client/brain-catalog.js",shapes:["mirror","flat"],note:"the pooled-brain rule, required at load time by the engine and src/models.js"},{src:"client/byok-catalog.js",shapes:["mirror","flat"],note:"the BYOK model additions the server catalog does not name"},{src:"client/user-models.js",shapes:["mirror","flat"],note:"the models the USER declares, in one file both hosts read (requires ./credentials.js)"},{src:"client/model-discovery.js",shapes:["mirror","flat"],note:"asks the vendor what it serves, so adding a new model is not a memory test (requires ./user-models.js)"},{src:"client/hooks.js",shapes:["mirror","flat"],note:"the shared hook layer behind /hooks and the repo guard installer"},{src:"client/platform.js",shapes:["mirror","flat"],note:"the ONE place that decides which OS this is (Phase 30.1)"},{src:"client/topup.js",shapes:["mirror","flat"],note:"the token-bank top-up: amount bounds, the balance reading, and the credit watch every host drives"},{src:"client/google-signin.js",shapes:["mirror","flat"],note:"the localhost half of aegis1's desktop Google OAuth round-trip; `connect --google` drives it"},{src:"client/drive-connect.js",shapes:["mirror","flat"],note:"the desktop half of aegis1's Drive OAuth (/connect/drive, /api/drive/token); requires ./aegis.js only via the caller"},{src:"client/drive-upload.js",shapes:["mirror","flat"],note:"the Drive v3 REST wrapper that uploads the memory backup"},{src:"mcp/tools.js",shapes:["mirror"],note:"the shared tool registry; requires ../client/foreign-memory.js"},{src:"mcp/server.js",shapes:["mirror"],note:"the stdio MCP server every installed editor config names (compiled, never required)"},{src:"hosts/spec.js",shapes:["mirror"],note:"the canonical server spec, staged under its own directory so it finds vendor/mcp/server.js"},{src:"hosts/targets.js",shapes:["mirror"],note:"the editor target registry"},{src:"hosts/install.js",shapes:["mirror"],note:"the merge-only installer behind aegiscode mcp install"},{src:"hosts/openai-shim.js",shapes:["mirror"],note:"the loopback OpenAI-compatible shim"},{src:"desktop/renderer/usage.js",shapes:["mirror"],note:"the pure usage mapping shared by the window and the terminal"},{src:"desktop/lib/local/engine.js",shapes:["mirror"],note:"the agent loop, reused as-is (one loop, not a second one drifting)"},{src:"desktop/lib/local/claude-pro.js",shapes:["mirror"],note:"the Claude Code Pro transport; requires ./../../one/src/child.js at call time"},{src:"one/src/child.js",shapes:["mirror"],note:"the ONE claude-child argv builder (rule 4); resolved by claude-pro.js at call time"},{src:"one/src/permissions.js",shapes:["mirror"],note:"resolvePosture() — the permission half of the argv, resolved at call time"},{src:"desktop/lib/local/local.js",shapes:["mirror"],note:"the local model transport and its fail-closed base-URL check"},{src:"desktop/lib/local/context.js",shapes:["mirror"],note:"the token-budget trimmer local.js requires at load"},{src:"desktop/lib/local/session-rounds.js",shapes:["mirror"],note:"interrupted-turn bookkeeping; required at load by engine.js"},{src:"desktop/lib/local/tools.js",shapes:["mirror"],note:"the tool implementations (persistent shell, editFile, grep, exec)"},{src:"desktop/lib/local/shell.js",shapes:["mirror"],note:"the persistent shell, required by tools.js"},{src:"desktop/lib/local/agents.js",shapes:["mirror"],note:"Task subagents"},{src:"desktop/lib/local/prompt.js",shapes:["mirror"],note:"the system prompt builder"},{src:"desktop/lib/settings.js",shapes:["mirror"],note:"the provider-config store (base URL + key per provider)"},{src:"desktop/lib/local/turn-guard.js",shapes:["mirror"],note:"engine.js requires it at load; it requires ./git-scope.js"},{src:"desktop/lib/local/worktree-lock.js",shapes:["mirror"],note:"engine.js requires it at load"},{src:"desktop/lib/local/git-scope.js",shapes:["mirror"],note:"the write-scope rule turn-guard.js and the queues share"},{src:"desktop/lib/local/queue.js",shapes:["mirror"],note:"the autonomous work queue"},{src:"desktop/lib/local/autonomous.js",shapes:["mirror"],note:"the unattended worker; requires ./queue.js and ./git-scope.js"},{src:"desktop/lib/local/entitlement.js",shapes:["mirror"],note:"the shared Pro gate (account probe injected by the caller)"},{src:"desktop/lib/local/covenant.js",shapes:["mirror"],note:"the pre-action gate engine.js requires unconditionally at load"},{src:"desktop/lib/local/aegis-seal.mjs",shapes:["mirror"],note:"the codec covenant.js requires the first time it decodes"},{src:"covenant/aegis.seal",shapes:["mirror","nested"],note:"the sealed covenant (AES/1 container) — path shape is load-bearing"},{src:"covenant/README.md",shapes:["mirror","nested"],note:"the decode notice shipped beside the artifact"},{src:"tools/agent-gate.mjs",shapes:["mirror","flat"],note:"the in-process half of the lock; without it a packaged app had NO gate"}];export function entriesFor(e){const s=[];for(const t of MANIFEST){if(!t.shapes.includes(e))continue;let o;if("mirror"===e)o=r.join(CLI_VENDOR,t.src);else if("flat"===e)o=r.join(DESKTOP_VENDOR,r.basename(t.src));else{if("nested"!==e)throw new Error(`predist: unknown shape ${e}`);o=r.join(DESKTOP_VENDOR,t.src)}s.push({src:t.src,dest:o,from:r.join(REPO_DIR,t.src)})}return s}export const SHAPES=["mirror","flat","nested"];const c=[["cli",CLI_DIR,["bin","src","vendor","scripts","package.json","README.md","LICENSE"]],["desktop",DESKTOP_DIR,["main.js","preload.js","lib","renderer","bin","vendor","package.json","README.md"]]],l=new Set(["node_modules","release",".git",".cache","out"]);function d(s,t){const o=e=>l.has(e)||e.endsWith(".log"),n=(s,t)=>{if(e.mkdirSync(r.dirname(t),{recursive:!0}),e.copyFileSync(s,t),!e.readFileSync(s).equals(e.readFileSync(t)))throw new Error(`predist: bundle copy differs from source: ${r.relative(REPO_DIR,s)}`)},i=(s,a)=>{const c=e.lstatSync(s);if(!c.isSymbolicLink())if(c.isFile())n(s,r.join(t,a));else for(const t of e.readdirSync(s))o(t)||i(r.join(s,t),a?r.join(a,t):t)};e.lstatSync(s).isFile()?n(s,t):i(s,"")}const p=12e4,h=6e5,u=50,f="AEGISONE_PREDIST_LOCK_TOKEN";let m=null,g=!1,j=0;function y(e){try{return process.kill(e,0),!0}catch(e){return Boolean(e)&&"EPERM"===e.code}}const v=e=>new Promise((r=>setTimeout(r,e)));function w(){if(j>0)return void j--;const r=m,s=g,t=process.env[f];if(m=null,g=!1,r&&s){t&&delete process.env[f];try{e.unlinkSync(r)}catch{}}}export async function acquireStageLock(s){if(m)return j++,w;const t=s&&s.stdout||process.stdout;return await async function(s){const t=function(){const s=r.join(REPO_DIR,".git");let t=s;try{if(!e.lstatSync(s).isDirectory()){const o=/^gitdir:\s*(.+)$/m.exec(e.readFileSync(s,"utf8"));o&&(t=r.resolve(REPO_DIR,o[1].trim()))}}catch{t=s}return r.join(t,"aegisone-predist.lock")}(),o=Date.now()+p,n=process.env[f]||null;let i=null,a=!1;for(;;){if(n)try{const r=String(e.readFileSync(t,"utf8")).split("\n")[1];if(r&&r.trim()===n)return m=t,void(g=!1)}catch{}try{i=`${Date.now().toString(36)}-${process.pid}-${Math.random().toString(36).slice(2,10)}`;const r=e.openSync(t,"wx");return e.writeSync(r,`${process.pid}\n${i}\n`),e.closeSync(r),m=t,g=!0,void(process.env[f]=i)}catch(e){if(!e||"EEXIST"!==e.code)throw e}let r=null,c=0;try{r=e.statSync(t),c=Number(String(e.readFileSync(t,"utf8")).split("\n")[0].trim())}catch{continue}if(Date.now()-r.mtimeMs>h||Number.isFinite(c)&&c>0&&!y(c)){s(`predist: breaking an abandoned staging lock (pid ${c||"unknown"})`);try{e.unlinkSync(t)}catch{}}else{if(Date.now()>o)throw new Error(`predist: another stager (pid ${c||"unknown"}) has held ${t} for over ${Math.round(p/1e3)}s. Staging is destructive — it removes and rewrites cli/vendor, desktop/vendor and one/vendor — so it will not run concurrently with a peer. Wait for it, or delete the lock if that process is gone.`);a||(a=!0,s(`predist: another stager (pid ${c||"unknown"}) is running — waiting for it (concurrent staging would read a vendor tree the peer is rewriting)`)),await v(u+Math.floor(Math.random()*u))}}}((e=>t.write(`${e}\n`))),w}function E(s,t){t&&e.rmSync(t,{recursive:!0,force:!0});const o=[];for(const t of s){if(!e.existsSync(t.from))throw new Error(`predist: missing shared module: ${t.src} (expected at ${t.from})`);if(e.mkdirSync(r.dirname(t.dest),{recursive:!0}),e.copyFileSync(t.from,t.dest),!e.readFileSync(t.from).equals(e.readFileSync(t.dest)))throw new Error(`predist: staged copy differs from source: ${t.src}`);o.push(t)}return o}export async function stage(t){const n=t||{},i=n.io||{},l=i.stdout||process.stdout,p=(i.stderr||process.stderr,Array.isArray(n.shapes)?n.shapes:[...SHAPES,"bundle"]),h=e=>p.includes(e),u=e=>l.write(`${e}\n`),f=await acquireStageLock(i);try{return await async function({want:t,log:n}){const i={mirror:null,flat:null,nested:null,bundle:null};if(t("mirror")){const e=E(entriesFor("mirror"),CLI_VENDOR);n(`predist: staged ${e.length} shared modules into cli/vendor/`);for(const r of e)n(` ${r.src} -> vendor/${r.src}`);i.mirror={staged:e.length}}if(t("nested")&&(i.nested={staged:E(entriesFor("nested"),null).length}),t("flat")){const e=E(entriesFor("flat"),null);for(const r of e)n(`staged ${r.dest}`);i.flat={staged:e.length}}if(t("mirror")&&t("flat"))for(const s of MANIFEST){if(!s.shapes.includes("mirror")||!s.shapes.includes("flat"))continue;const t=r.join(CLI_VENDOR,s.src),o=r.join(DESKTOP_VENDOR,r.basename(s.src));if(!e.readFileSync(t).equals(e.readFileSync(o)))throw new Error(`predist: the two shapes disagree for ${s.src}`)}if(t("mirror")){const s=function(s){const t=r.join(CLI_VENDOR,"mcp","tools.js");delete a.cache[a.resolve(t)];const{createTools:o}=a(t),n=o({apiBase:"http://127.0.0.1",apiKey:"predist-probe",randomUUID:()=>"id"}).toolList().length;if(0===n)throw new Error("predist: staged registry exposes no tools");const i=a("node:vm"),c=r.join(CLI_VENDOR,"mcp","server.js");new i.Script(e.readFileSync(c,"utf8"),{filename:c});const l=r.join(CLI_VENDOR,"hosts"),d=a(r.join(l,"spec.js")),p=a(r.join(l,"install.js")),h=a(r.join(l,"targets.js")),u=d.resolveServer({AEGIS_MCP_SERVER:""});if(!u.exists||u.path!==c)throw new Error(`predist: staged hosts/spec.js resolves the server as ${u.path} (exists: ${u.exists}), expected ${c}. An installed aegiscode would write editor configs pointing at a file the package never shipped. Candidates were:\n ${u.candidates.join("\n ")}`);const f=h.getTarget("vscode"),m=p.planTarget(f,"user",{ctx:p.hostCtx({home:r.join(CLI_VENDOR,".predist-home"),env:{},cwd:REPO_DIR}),specOpts:{env:{AEGIS_MCP_SERVER:""}}}),g=JSON.stringify(m.after||"");if(m.error||!m.changed||!g.includes(JSON.stringify(c).slice(1,-1)))throw new Error(`predist: a planned vscode install does not name the staged server (error: ${m.error&&m.error.message}, changed: ${m.changed})`);if("function"!=typeof a(r.join(l,"openai-shim.js")).createShimServer)throw new Error("predist: staged hosts/openai-shim.js exposes no createShimServer");return{count:n,targets:h.targetIds().length,staged:s.length}}(entriesFor("mirror"));n(`predist: staged registry loads standalone (${s.count} tools)`),n(`predist: editor layer verified (${s.targets} host targets, server resolves to vendor/mcp/server.js, shim loads)`);const t=await async function(){const e=r.join(CLI_VENDOR,"tools","agent-gate.mjs");if("function"!=typeof(await import(o(e).href)).run)throw new Error("predist: staged tools/agent-gate.mjs exposes no run()");return e}();n(`predist: ${r.relative(REPO_DIR,t)} loads standalone and exposes run()`),i.mirror.proof=s}if(t("flat")){const s=function(s){const t=new Set(s.map((e=>r.basename(e.dest))));for(const o of s){const s=e.readFileSync(o.dest,"utf8").replace(/\/\*[\s\S]*?\*\//g,"").replace(/(^|[^:])\/\/.*$/gm,"$1");for(const e of s.matchAll(/require\(\s*'((?:\.\.?\/)[^']+)'\s*\)/g)){const s=e[1];if(r.basename(s).replace(/\.[cm]?js$/,""),s.replace(/^\.\//,"").startsWith("../"))throw new Error(`predist: flat-staged ${r.basename(o.dest)} requires '${s}', which escapes vendor/ — flattening only works for same-directory requires (add the target to the manifest, or stop staging this file flat)`);const n=s.replace(/^\.\//,"");if(!t.has(n))throw new Error(`predist: flat-staged ${r.basename(o.dest)} requires '${s}', which is not staged into desktop/vendor/ — the packaged app would throw MODULE_NOT_FOUND before the window could open`)}}const o=a(r.join(DESKTOP_VENDOR,"aegis.js"));if(!o||0===Object.keys(o).length)throw new Error("predist: staged desktop/vendor/aegis.js loads but exports nothing");return{files:s.length,exports:Object.keys(o).length}}(entriesFor("flat"));n(`predist: flattened tree is self-contained (${s.files} files, ${s.exports} transport exports) — no staged module escapes vendor/`),i.flat.proof=s}if(t("bundle")){for(const[s,t,o]of c){const i=r.join(ONE_VENDOR,s);e.rmSync(i,{recursive:!0,force:!0});for(const s of o){const o=r.join(t,s);if(!e.existsSync(o)){if("LICENSE"===s||"README.md"===s)continue;throw new Error(`predist: bundle source missing: ${r.relative(REPO_DIR,o)}`)}d(o,r.join(i,s))}n(`staged the ${s} face into one/vendor/${s}/`)}const t=function(){const t=r.join(ONE_VENDOR,"cli"),o=r.join(t,"src","deps.js"),n=s(process.execPath,["-e","const d=require(process.argv[1]);console.log(JSON.stringify(d.paths))",o],{cwd:t,encoding:"utf8"});if(0!==n.status)throw new Error(`predist: the bundled CLI does not load: ${n.stderr||n.stdout}`);const i=JSON.parse(n.stdout),a=[];let l=0;for(const[e,s]of Object.entries(i)){const t=r.relative(ONE_VENDOR,s);t.startsWith("..")||r.isAbsolute(t)?a.push(`${e} -> ${s}`):"cli"!==t.split(r.sep)[0]&&l++}if(a.length)throw new Error(`predist: the bundled CLI resolves these shared modules OUTSIDE the bundle (${ONE_VENDOR}) — the product tarball would depend on a repo checkout:\n `+a.join("\n "));if(!e.existsSync(r.join(t,"bin","aegiscode.js")))throw new Error("predist: the bundle has no cli/bin/aegiscode.js");const d=[];for(const[s,t,o]of c)for(const n of o){const o=r.join(ONE_VENDOR,s,n);let i=null,a=null;try{i=e.lstatSync(r.join(t,n))}catch{continue}try{a=e.lstatSync(o)}catch{d.push(`${s}/${n} -> missing`);continue}i.isFile()&&!a.isFile()&&d.push(`${s}/${n} -> not a regular file`),i.isDirectory()&&!a.isDirectory()&&d.push(`${s}/${n} -> not a directory`)}if(d.length)throw new Error(`predist: the bundle staged these in the wrong shape:\n ${d.join("\n ")}`);return{modules:Object.keys(i).length,inSiblingFace:l}}();n(`predist: the bundled CLI resolves ${t.modules} shared modules from inside one/vendor/ (${t.inSiblingFace} through the bundled desktop face) — no repo checkout needed`),i.bundle=t}return i}({want:h,log:u})}finally{f()}}export async function main(e,r){const s=r||{},t=Array.isArray(e)?e:[],o=t.includes("--quiet")?{write:()=>!0}:s.stdout||process.stdout,n=s.stderr||process.stderr;let i;t.includes("--mirror-only")?i=["mirror"]:t.includes("--flat-only")?i=["flat","nested"]:t.includes("--bundle-only")&&(i=["bundle"]);try{return await stage({shapes:i,io:{stdout:o,stderr:n}}),0}catch(e){return n.write(`${e&&e.message}\n`),1}}!function(){const e=process.argv[1];let s=!1;if(e)try{s=r.resolve(e)===t(import.meta.url)}catch{s=!1}s&&main(process.argv.slice(2)).then((e=>{process.exitCode=e}))}();