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,403 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * Session persistence — one JSON line per exchange in ~/.aegiscode/history.jsonl
10
- * (or $AEGISCODE_HOME). Keeps the file bounded (oldest entries dropped past
11
- * HISTORY_LIMIT lines).
12
- *
13
- * history.jsonl is this host's *ledger*: one record per exchange, carrying the
14
- * token/cost numbers `/cost` aggregates. It stays the CLI's own format.
15
- *
16
- * What changed with the shared store (`client/session-store.js`) is that every
17
- * recorded exchange is ALSO mirrored into `<dir>/sessions.json`, the store the
18
- * desktop app and the MCP plugin read. That file is what makes a terminal turn
19
- * show up in the GUI's session list — and, in the other direction, what lets
20
- * `/resume` open a session that was typed in the desktop, without cloud sync
21
- * and without a key. `readResumeList` merges both sources by id, so no session
22
- * is listed twice.
23
- *
24
- * Ported from the upstream engine reference (ESM → CommonJS). The data dir now
25
- * comes from config.js's shared `aegisDir()` helper.
26
- */
27
-
28
- const fs = require('node:fs');
29
- const os = require('node:os');
30
- const path = require('node:path');
31
- const { aegisDir } = require('./config.js');
32
- const { ensurePrivateDir, writePrivateFile } = require('./securefs.js');
33
- const { sessionStore } = require('./shared.js');
34
- const { cwdName } = require('./format.js');
35
- const { estimateTokens } = require('./tokens.js');
36
-
37
- const HISTORY_LIMIT = 500;
38
- /** Which host wrote a mirrored record, so either side can tell them apart. */
39
- const SOURCE = 'aegiscode-cli';
40
-
41
- function historyPath() {
42
- return path.join(aegisDir(), 'history.jsonl');
43
- }
44
-
45
- function ensureHistoryDir() {
46
- ensurePrivateDir(path.dirname(historyPath()));
47
- }
48
-
49
- /**
50
- * Record one exchange. `reply` is stored in full so /resume can restore the
51
- * transcript exactly. Token accounting:
52
- * live — `usage` carries the real numbers from the provider stream-json
53
- * (input/output/cacheRead/cacheWrite + costUsd), stored verbatim;
54
- * demo — estimated from text length (~4 chars/token), labeled real:false.
55
- * /cost aggregates these records, so compacted-away exchanges still count.
56
- *
57
- * `title` is the conversation's own name (naming.js). It is written on every
58
- * record for the session so `/resume` shows what the session is ABOUT — it used
59
- * to show `prompt.slice(0, 60)`, the raw first message, which is a prompt and
60
- * not a name ("heey").
61
- */
62
- function appendHistory({ sessionId, prompt, reply, status, usage, title }) {
63
- try {
64
- const entry = {
65
- ts: new Date().toISOString(),
66
- sessionId,
67
- cwd: process.cwd(),
68
- prompt,
69
- reply,
70
- status, // 'done' | 'stopped' | 'error'
71
- tokens: usage
72
- ? {
73
- input: usage.input || 0,
74
- output: usage.output || 0,
75
- cacheRead: usage.cacheRead || 0,
76
- cacheWrite: usage.cacheWrite || 0,
77
- real: true,
78
- }
79
- : { input: estimateTokens(prompt), output: estimateTokens(reply || ''), real: false },
80
- };
81
- if (usage && typeof usage.costUsd === 'number') entry.costUsd = usage.costUsd;
82
- const clean = String(title || '').trim();
83
- if (clean) entry.title = clean;
84
- return appendHistoryEntries([entry]);
85
- } catch (e) {
86
- // Persistence is best-effort; never crash the session over it.
87
- if (process.env.AEGIS_HIST_DEBUG) console.error('[history] write failed:', e);
88
- return 0;
89
- }
90
- }
91
-
92
- /**
93
- * Append a batch of already-shaped entries in ONE read/trim/write pass.
94
- *
95
- * `appendHistory` re-reads and rewrites the whole file per exchange, which is
96
- * fine for one turn at a time but quadratic for a caller with a list of them —
97
- * importing 50 pulled sessions would rewrite the file 50 times, each pass
98
- * re-parsing everything the previous pass just wrote. The single writer (and
99
- * therefore the single place the file format is defined) stays here.
100
- *
101
- * @returns {number} entries written
102
- */
103
- function appendHistoryEntries(entries) {
104
- const list = (Array.isArray(entries) ? entries : []).filter(Boolean);
105
- if (!list.length) return 0;
106
- try {
107
- ensureHistoryDir();
108
- const p = historyPath();
109
- const prev = fs.existsSync(p) ? fs.readFileSync(p, 'utf8').split('\n').filter(Boolean) : [];
110
- const lines = [...prev, ...list.map((e) => JSON.stringify(e))];
111
- const trimmed = lines.slice(Math.max(0, lines.length - HISTORY_LIMIT));
112
- // 0600: this file is every prompt and reply the session has ever had.
113
- writePrivateFile(p, trimmed.join('\n') + '\n');
114
- mirrorToSharedStore(list);
115
- return list.length;
116
- } catch (e) {
117
- // Persistence is best-effort; never crash the session over it.
118
- if (process.env.AEGIS_HIST_DEBUG) console.error('[history] write failed:', e);
119
- return 0;
120
- }
121
- }
122
-
123
- /**
124
- * Mirror freshly-recorded exchanges into the shared session store, so the
125
- * desktop and the MCP plugin can see this host's sessions.
126
- *
127
- * Only *writes* mirror — a read of history.jsonl never re-imports itself, which
128
- * is what would otherwise duplicate every exchange on every launch. A mirror
129
- * failure must never cost the user the history line it accompanies, so this is
130
- * called after the ledger write and swallows its own errors.
131
- */
132
- function mirrorToSharedStore(entries) {
133
- for (const e of entries) {
134
- try {
135
- sessionStore.recordExchange(aegisDir(), {
136
- sessionId: e.sessionId,
137
- prompt: e.prompt,
138
- reply: e.reply,
139
- status: e.status,
140
- cwd: e.cwd,
141
- ts: e.ts,
142
- tokens: e.tokens,
143
- costUsd: e.costUsd,
144
- origin: SOURCE,
145
- });
146
- } catch (err) {
147
- if (process.env.AEGIS_HIST_DEBUG) console.error('[history] mirror failed:', err);
148
- }
149
- }
150
- }
151
-
152
- function readEntries() {
153
- try {
154
- const raw = fs.readFileSync(historyPath(), 'utf8');
155
- return raw
156
- .split('\n')
157
- .map((l) => l.trim())
158
- .filter(Boolean)
159
- .map((l) => { try { return JSON.parse(l); } catch { return null; } })
160
- .filter(Boolean);
161
- } catch {
162
- return [];
163
- }
164
- }
165
-
166
- /** Every history record, oldest first. Public name for other modules. */
167
- function readHistoryEntries() {
168
- return readEntries();
169
- }
170
-
171
- /** Newest-first list of own sessions, one per distinct sessionId. */
172
- function readOwnSessions(limit = 8) {
173
- const entries = readEntries();
174
- const byId = new Map();
175
- for (const e of entries) {
176
- const cur = byId.get(e.sessionId);
177
- if (!cur) {
178
- byId.set(e.sessionId, e);
179
- continue;
180
- }
181
- // Prefer a record that carries the conversation's name — naming lands one
182
- // model round after the first exchange is persisted, so the newest record
183
- // is not necessarily the titled one. Failing that, the newest wins.
184
- if (!cur.title && e.title) byId.set(e.sessionId, e);
185
- else if (!cur.title === !e.title && String(e.ts) > String(cur.ts)) byId.set(e.sessionId, e);
186
- }
187
- const items = [...byId.values()]
188
- .sort((a, b) => (a.ts < b.ts ? 1 : -1))
189
- .slice(0, limit)
190
- .map((e) => ({
191
- id: e.sessionId,
192
- cwd: cwdName(e.cwd),
193
- // The conversation's own name when it has one (naming.js), else the old
194
- // raw-prompt fallback so a session recorded before naming existed is
195
- // still identifiable.
196
- summary: (e.title || e.prompt || '').slice(0, 60),
197
- time: e.ts,
198
- own: true,
199
- }));
200
- return items;
201
- }
202
-
203
- /**
204
- * Rebuild the transcript (user/assistant pairs) of a session, oldest first.
205
- *
206
- * history.jsonl wins when it has records for the id (this host's own ledger,
207
- * complete with the exchanges the shared store may have trimmed). Otherwise the
208
- * session came from another host — a desktop thread — and the shared store is
209
- * the only place its messages exist, so /resume can open it too.
210
- */
211
- function readSessionTranscript(sessionId) {
212
- const own = readEntries()
213
- .filter((e) => e.sessionId === sessionId)
214
- .flatMap((e) => [
215
- { role: 'user', text: e.prompt },
216
- { role: 'assistant', text: e.reply || '(no response)' },
217
- ]);
218
- if (own.length) return own;
219
- try {
220
- return sessionStore.readTranscript(aegisDir(), sessionId);
221
- } catch {
222
- return [];
223
- }
224
- }
225
-
226
- /** Sessions in the shared store written by another host (the desktop app). */
227
- function readSharedStoreSessions(limit = 8) {
228
- try {
229
- return sessionStore.listSummaries(aegisDir(), limit);
230
- } catch {
231
- return [];
232
- }
233
- }
234
-
235
- /** All history records for one session, oldest first (power /cost). */
236
- function sessionHistoryEntries(sessionId) {
237
- return readEntries().filter((e) => e.sessionId === sessionId);
238
- }
239
-
240
- /**
241
- * Stamp a conversation's name onto every record this session already has.
242
- *
243
- * Naming is one model round, run off the critical path, so it usually lands
244
- * *after* the first exchange was written to history.jsonl. Without this the
245
- * resume list would show the raw first prompt for the rest of the session's
246
- * life, because readOwnSessions() would find no `title` anywhere.
247
- *
248
- * Best-effort, like every other writer here: a failed rewrite costs a name in a
249
- * picker, never a turn. Records are rewritten to the same 0600 file via
250
- * securefs, and only the session's own lines are touched.
251
- */
252
- function setSessionTitle(sessionId, title) {
253
- const clean = String(title || '').trim();
254
- if (!clean) return 0;
255
- // The shared store is the other surface a name is read from: the desktop app
256
- // and the MCP plugin list sessions from `sessions.json`, so a name that lived
257
- // only in history.jsonl would name the session in `/resume` and leave it
258
- // unnamed in the GUI. Stamped first and unconditionally — the store may hold
259
- // this session even when the ledger does not. Best-effort, like everything
260
- // else here.
261
- try {
262
- sessionStore.setTitle(aegisDir(), sessionId, clean);
263
- } catch {
264
- /* the store is optional; the ledger below is the CLI's own */
265
- }
266
- try {
267
- const p = historyPath();
268
- if (!fs.existsSync(p)) return 0;
269
- let touched = 0;
270
- const out = fs
271
- .readFileSync(p, 'utf8')
272
- .split('\n')
273
- .map((l) => l.trim())
274
- .filter(Boolean)
275
- .map((l) => {
276
- try {
277
- const j = JSON.parse(l);
278
- if (j.sessionId !== sessionId || j.title === clean) return l;
279
- j.title = clean;
280
- touched++;
281
- return JSON.stringify(j);
282
- } catch {
283
- return l;
284
- }
285
- });
286
- if (!touched) return 0;
287
- writePrivateFile(p, out.join('\n') + '\n');
288
- return touched;
289
- } catch (e) {
290
- if (process.env.AEGIS_HIST_DEBUG) console.error('[history] title write failed:', e);
291
- return 0;
292
- }
293
- }
294
-
295
- /** The conversation's name, if any record for it carries one. */
296
- function readSessionTitle(sessionId) {
297
- const hit = readEntries().find((e) => e.sessionId === sessionId && e.title);
298
- return hit ? String(hit.title) : '';
299
- }
300
-
301
- /**
302
- * Drop every history record for a session. /clear
303
- * calls this so /cost stops summing old rows — the sessionId stays stable, so
304
- * rewind checkpoints and the transcript lineage are unaffected.
305
- */
306
- function pruneSessionHistory(sessionId) {
307
- try {
308
- const p = historyPath();
309
- if (!fs.existsSync(p)) return;
310
- const kept = fs
311
- .readFileSync(p, 'utf8')
312
- .split('\n')
313
- .map((l) => l.trim())
314
- .filter(Boolean)
315
- .filter((l) => {
316
- try { return JSON.parse(l).sessionId !== sessionId; } catch { return true; }
317
- });
318
- writePrivateFile(p, kept.length ? kept.join('\n') + '\n' : '');
319
- } catch (e) {
320
- if (process.env.AEGIS_HIST_DEBUG) console.error('[history] prune failed:', e);
321
- }
322
- }
323
-
324
- /**
325
- * Sum a session's token records across history.jsonl. Compacted-away exchanges
326
- * still count because /compact writes a summary exchange, it never deletes the
327
- * file. `real` is true only when every record carries live CLI usage numbers.
328
- */
329
- function aggregateSessionUsage(sessionId) {
330
- const entries = sessionHistoryEntries(sessionId);
331
- const usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
332
- let real = entries.length > 0;
333
- let costUsd = 0;
334
- for (const e of entries) {
335
- const t = e.tokens || {};
336
- if (!t.real) real = false;
337
- usage.input += t.input || 0;
338
- usage.output += t.output || 0;
339
- usage.cacheRead += t.cacheRead || 0;
340
- usage.cacheWrite += t.cacheWrite || 0;
341
- if (typeof e.costUsd === 'number') costUsd += e.costUsd;
342
- }
343
- return { entries: entries.length, usage, real, costUsd };
344
- }
345
-
346
- /**
347
- * Sessions for the /resume overlay: own Aegiscode sessions, sessions written
348
- * into the shared store by another host (the desktop app), and real Claude Code
349
- * sessions from ~/.claude/history.jsonl — newest first, deduplicated by id.
350
- *
351
- * The dedup matters: an own session is mirrored into the shared store, so
352
- * without it every terminal session would be listed twice, once from each
353
- * source.
354
- */
355
- function readResumeList(limit = 8, ownLimit = 5, claudeLimit = 8) {
356
- const items = readOwnSessions(ownLimit);
357
- const seen = new Set(items.map((i) => i.id));
358
- const sharedItems = readSharedStoreSessions(ownLimit).filter((i) => {
359
- if (seen.has(i.id)) return false;
360
- seen.add(i.id);
361
- return true;
362
- });
363
- const claudeItems = [];
364
- const histPath = `${os.homedir()}/.claude/history.jsonl`;
365
- try {
366
- const raw = fs.readFileSync(histPath, 'utf8');
367
- const lines = raw.trim().split('\n').reverse().slice(0, claudeLimit);
368
- for (const l of lines) {
369
- try {
370
- const j = JSON.parse(l);
371
- const meta = j.extra && JSON.parse(j.extra);
372
- if (meta && meta.sessionId && !seen.has(meta.sessionId)) {
373
- seen.add(meta.sessionId);
374
- const c = cwdName(j.cwd);
375
- const t = (j.summary || '').slice(0, 60);
376
- claudeItems.push({ id: meta.sessionId, cwd: c, summary: t, time: j.timestamp, own: false });
377
- }
378
- } catch {}
379
- }
380
- } catch {}
381
- return [...items, ...sharedItems, ...claudeItems]
382
- .sort((a, b) => (String(a.time || '') < String(b.time || '') ? 1 : -1))
383
- .slice(0, limit);
384
- }
385
-
386
- module.exports = {
387
- HISTORY_LIMIT,
388
- SOURCE,
389
- historyPath,
390
- ensureHistoryDir,
391
- appendHistory,
392
- appendHistoryEntries,
393
- readHistoryEntries,
394
- readOwnSessions,
395
- readSessionTranscript,
396
- readSharedStoreSessions,
397
- sessionHistoryEntries,
398
- pruneSessionHistory,
399
- aggregateSessionUsage,
400
- readResumeList,
401
- setSessionTitle,
402
- readSessionTitle,
403
- };
3
+ "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),{aegisDir:aegisDir}=require("./config.js"),{ensurePrivateDir:ensurePrivateDir,writePrivateFile:writePrivateFile}=require("./securefs.js"),{sessionStore:sessionStore}=require("./shared.js"),{cwdName:cwdName}=require("./format.js"),{estimateTokens:estimateTokens}=require("./tokens.js"),HISTORY_LIMIT=500,SOURCE="aegiscode-cli";function historyPath(){return path.join(aegisDir(),"history.jsonl")}function ensureHistoryDir(){ensurePrivateDir(path.dirname(historyPath()))}function appendHistory({sessionId:e,prompt:t,reply:s,status:r,usage:i,title:n}){try{const o={ts:(new Date).toISOString(),sessionId:e,cwd:process.cwd(),prompt:t,reply:s,status:r,tokens:i?{input:i.input||0,output:i.output||0,cacheRead:i.cacheRead||0,cacheWrite:i.cacheWrite||0,real:!0}:{input:estimateTokens(t),output:estimateTokens(s||""),real:!1}};i&&"number"==typeof i.costUsd&&(o.costUsd=i.costUsd);const a=String(n||"").trim();return a&&(o.title=a),appendHistoryEntries([o])}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function appendHistoryEntries(e){const t=(Array.isArray(e)?e:[]).filter(Boolean);if(!t.length)return 0;try{ensureHistoryDir();const e=historyPath(),s=[...fs.existsSync(e)?fs.readFileSync(e,"utf8").split("\n").filter(Boolean):[],...t.map((e=>JSON.stringify(e)))],r=s.slice(Math.max(0,s.length-HISTORY_LIMIT));return writePrivateFile(e,r.join("\n")+"\n"),mirrorToSharedStore(t),t.length}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] write failed:",e),0}}function mirrorToSharedStore(e){for(const t of e)try{sessionStore.recordExchange(aegisDir(),{sessionId:t.sessionId,prompt:t.prompt,reply:t.reply,status:t.status,cwd:t.cwd,ts:t.ts,tokens:t.tokens,costUsd:t.costUsd,origin:SOURCE})}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] mirror failed:",e)}}function readEntries(){try{return fs.readFileSync(historyPath(),"utf8").split("\n").map((e=>e.trim())).filter(Boolean).map((e=>{try{return JSON.parse(e)}catch{return null}})).filter(Boolean)}catch{return[]}}function readHistoryEntries(){return readEntries()}function readOwnSessions(e=8){const t=readEntries(),s=new Map;for(const e of t){const t=s.get(e.sessionId);t?(!t.title&&e.title||!t.title==!e.title&&String(e.ts)>String(t.ts))&&s.set(e.sessionId,e):s.set(e.sessionId,e)}return[...s.values()].sort(((e,t)=>e.ts<t.ts?1:-1)).slice(0,e).map((e=>({id:e.sessionId,cwd:cwdName(e.cwd),summary:(e.title||e.prompt||"").slice(0,60),time:e.ts,own:!0})))}function readSessionTranscript(e){const t=readEntries().filter((t=>t.sessionId===e)).flatMap((e=>[{role:"user",text:e.prompt},{role:"assistant",text:e.reply||"(no response)"}]));if(t.length)return t;try{return sessionStore.readTranscript(aegisDir(),e)}catch{return[]}}function readSharedStoreSessions(e=8){try{return sessionStore.listSummaries(aegisDir(),e)}catch{return[]}}function sessionHistoryEntries(e){return readEntries().filter((t=>t.sessionId===e))}function setSessionTitle(e,t){const s=String(t||"").trim();if(!s)return 0;try{sessionStore.setTitle(aegisDir(),e,s)}catch{}try{const t=historyPath();if(!fs.existsSync(t))return 0;let r=0;const i=fs.readFileSync(t,"utf8").split("\n").map((e=>e.trim())).filter(Boolean).map((t=>{try{const i=JSON.parse(t);return i.sessionId!==e||i.title===s?t:(i.title=s,r++,JSON.stringify(i))}catch{return t}}));return r?(writePrivateFile(t,i.join("\n")+"\n"),r):0}catch(e){return process.env.AEGIS_HIST_DEBUG&&console.error("[history] title write failed:",e),0}}function readSessionTitle(e){const t=readEntries().find((t=>t.sessionId===e&&t.title));return t?String(t.title):""}function pruneSessionHistory(e){try{const t=historyPath();if(!fs.existsSync(t))return;const s=fs.readFileSync(t,"utf8").split("\n").map((e=>e.trim())).filter(Boolean).filter((t=>{try{return JSON.parse(t).sessionId!==e}catch{return!0}}));writePrivateFile(t,s.length?s.join("\n")+"\n":"")}catch(e){process.env.AEGIS_HIST_DEBUG&&console.error("[history] prune failed:",e)}}function aggregateSessionUsage(e){const t=sessionHistoryEntries(e),s={input:0,output:0,cacheRead:0,cacheWrite:0};let r=t.length>0,i=0;for(const e of t){const t=e.tokens||{};t.real||(r=!1),s.input+=t.input||0,s.output+=t.output||0,s.cacheRead+=t.cacheRead||0,s.cacheWrite+=t.cacheWrite||0,"number"==typeof e.costUsd&&(i+=e.costUsd)}return{entries:t.length,usage:s,real:r,costUsd:i}}function readResumeList(e=8,t=5,s=8){const r=readOwnSessions(t),i=new Set(r.map((e=>e.id))),n=readSharedStoreSessions(t).filter((e=>!i.has(e.id)&&(i.add(e.id),!0))),o=[],a=`${os.homedir()}/.claude/history.jsonl`;try{const e=fs.readFileSync(a,"utf8").trim().split("\n").reverse().slice(0,s);for(const t of e)try{const e=JSON.parse(t),s=e.extra&&JSON.parse(e.extra);if(s&&s.sessionId&&!i.has(s.sessionId)){i.add(s.sessionId);const t=cwdName(e.cwd),r=(e.summary||"").slice(0,60);o.push({id:s.sessionId,cwd:t,summary:r,time:e.timestamp,own:!1})}}catch{}}catch{}return[...r,...n,...o].sort(((e,t)=>String(e.time||"")<String(t.time||"")?1:-1)).slice(0,e)}module.exports={HISTORY_LIMIT:HISTORY_LIMIT,SOURCE:SOURCE,historyPath:historyPath,ensureHistoryDir:ensureHistoryDir,appendHistory:appendHistory,appendHistoryEntries:appendHistoryEntries,readHistoryEntries:readHistoryEntries,readOwnSessions:readOwnSessions,readSessionTranscript:readSessionTranscript,readSharedStoreSessions:readSharedStoreSessions,sessionHistoryEntries:sessionHistoryEntries,pruneSessionHistory:pruneSessionHistory,aggregateSessionUsage:aggregateSessionUsage,readResumeList:readResumeList,setSessionTitle:setSessionTitle,readSessionTitle:readSessionTitle};
@@ -1,177 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * /init support: sniff a project (language, build/test/lint commands, layout)
10
- * and generate an AEGIS.md with real project instructions. Never overwrites an
11
- * existing file — the handler reports and leaves the file alone.
12
- *
13
- * Ported from the upstream engine reference (ESM → CommonJS). The reference wrote
14
- * a CLAUDE.md; this build writes AEGIS.md and the generated document is headed
15
- * "# AEGIS.md" and references "AEGIS Code". The `buildClaudeMd` export is kept
16
- * as an alias of `buildAegisMd` so callers ported from the reference still
17
- * resolve.
18
- */
19
-
20
- const fs = require('node:fs');
21
- const path = require('node:path');
22
- const { execSync } = require('node:child_process');
23
- const { pathName } = require('./format.js');
24
-
25
- function readJson(p, cwd) {
26
- try { return JSON.parse(fs.readFileSync(path.join(cwd, p), 'utf8')); } catch { return null; }
27
- }
28
-
29
- function hasFile(cwd, ...names) {
30
- return names.some((n) => fs.existsSync(path.join(cwd, n)));
31
- }
32
-
33
- function gitName(cwd) {
34
- try {
35
- const remote = execSync('git config --get remote.origin.url', { encoding: 'utf8', cwd, stdio: ['ignore', 'pipe', 'ignore'] }).trim();
36
- // A remote is normally a posix URL, but a Windows checkout can record a
37
- // drive path (`C:\src\foo`), and pathName reads both — it strips the same
38
- // trailing `.git` either way.
39
- const base = pathName(remote).replace(/\.git$/, '');
40
- if (base) return base;
41
- } catch {}
42
- try {
43
- // The project's own name is the leaf of its path — through the shared rule,
44
- // so a Windows checkout (`C:\src\proj`) names "proj" like every other host
45
- // instead of the whole path (see format.js).
46
- const dir = pathName(cwd);
47
- return dir || 'this project';
48
- } catch { return 'this project'; }
49
- }
50
-
51
- /** Describe a project enough to write a useful AEGIS.md. */
52
- function sniffProject(cwd = process.cwd()) {
53
- const pkg = readJson('package.json', cwd);
54
- const out = {
55
- name: pkg && pkg.name ? pkg.name : gitName(cwd),
56
- lang: 'unknown',
57
- build: null,
58
- test: null,
59
- lint: null,
60
- dev: null,
61
- structure: [],
62
- toolchain: [],
63
- };
64
-
65
- if (pkg) {
66
- out.lang = 'JavaScript/TypeScript (Node.js)';
67
- out.toolchain.push('Node.js');
68
- const scripts = pkg.scripts || {};
69
- if (scripts.build) out.build = `npm run build`;
70
- if (scripts.test) out.test = `npm test`;
71
- if (scripts.lint) out.lint = `npm run lint`;
72
- if (scripts.dev || scripts.start || scripts.watch) out.dev = scripts.dev ? `npm run dev` : `npm start`;
73
- if (pkg.packageManager) out.toolchain.push(pkg.packageManager);
74
- } else if (hasFile(cwd, 'go.mod')) {
75
- out.lang = 'Go';
76
- out.toolchain.push('Go');
77
- out.build = 'go build ./...';
78
- out.test = 'go test ./...';
79
- out.lint = 'golangci-lint run' ;
80
- out.dev = 'go run .';
81
- } else if (hasFile(cwd, 'Cargo.toml')) {
82
- out.lang = 'Rust';
83
- out.toolchain.push('Cargo');
84
- out.build = 'cargo build';
85
- out.test = 'cargo test';
86
- out.lint = 'cargo clippy -- -D warnings';
87
- out.dev = 'cargo run';
88
- } else if (hasFile(cwd, 'pyproject.toml', 'setup.py', 'requirements.txt')) {
89
- out.lang = 'Python';
90
- out.toolchain.push('Python');
91
- out.test = hasFile(cwd, 'pytest.ini', 'tox.ini') ? 'pytest' : 'python -m pytest';
92
- out.lint = 'ruff check .';
93
- } else if (hasFile(cwd, 'Makefile')) {
94
- out.lang = 'C/C++ or make-driven';
95
- out.toolchain.push('make');
96
- out.build = 'make';
97
- out.test = 'make test';
98
- out.dev = 'make run';
99
- } else if (hasFile(cwd, 'pom.xml', 'build.gradle')) {
100
- out.lang = 'Java';
101
- out.toolchain.push('Maven/Gradle');
102
- out.build = hasFile(cwd, 'pom.xml') ? 'mvn package' : 'gradle build';
103
- out.test = hasFile(cwd, 'pom.xml') ? 'mvn test' : 'gradle test';
104
- } else if (hasFile(cwd, 'Gemfile')) {
105
- out.lang = 'Ruby';
106
- out.toolchain.push('Ruby');
107
- out.test = 'bundle exec rspec';
108
- out.build = 'bundle exec rake build';
109
- } else if (hasFile(cwd, 'composer.json')) {
110
- out.lang = 'PHP';
111
- out.toolchain.push('Composer');
112
- out.test = 'composer test';
113
- } else if (hasFile(cwd, '.csproj')) {
114
- out.lang = 'C#/.NET';
115
- out.toolchain.push('.NET');
116
- out.build = 'dotnet build';
117
- out.test = 'dotnet test';
118
- }
119
-
120
- // Layout conventions.
121
- for (const d of ['src', 'lib', 'app', 'tests', 'test', 'spec', 'docs', 'scripts']) {
122
- if (fs.existsSync(path.join(cwd, d))) out.structure.push(d);
123
- }
124
- for (const f of ['eslint.config.js', '.eslintrc', '.prettierrc', 'biome.json', 'tsconfig.json', '.github/workflows']) {
125
- // The FIRST segment of a repo-relative probe path. This one stays a literal
126
- // split: `f` is written two lines up in repo-relative form, so its `/` is
127
- // not a host separator. A path that arrived from the OS needs pathName().
128
- if (fs.existsSync(path.join(cwd, f))) out.toolchain.push(f.split('/')[0]);
129
- }
130
-
131
- return out;
132
- }
133
-
134
- /** Render an AEGIS.md from a sniff result. */
135
- function buildAegisMd(sniff) {
136
- const s = sniff;
137
- const lines = [];
138
- lines.push(`# AEGIS.md`);
139
- lines.push('');
140
- lines.push(`Generated by AEGIS Code /init — edit freely. This file teaches AI agents how to work in this repo.`);
141
- lines.push('');
142
- lines.push('## Project');
143
- lines.push('');
144
- lines.push(`- Project: ${s.name}`);
145
- lines.push(`- Language: ${s.lang}`);
146
- if (s.toolchain.length) lines.push(`- Toolchain: ${[...new Set(s.toolchain)].join(', ')}`);
147
- lines.push('');
148
- lines.push('## Commands');
149
- lines.push('');
150
- lines.push('Run these to build, test, and lint:');
151
- lines.push('```bash');
152
- if (s.build) lines.push(s.build + ' # build');
153
- if (s.test) lines.push(s.test + ' # test');
154
- if (s.lint) lines.push(s.lint + ' # lint');
155
- if (s.dev) lines.push(s.dev + ' # dev server');
156
- lines.push('```');
157
- lines.push('');
158
- if (s.structure.length) {
159
- lines.push('## Project structure');
160
- lines.push('');
161
- for (const d of s.structure) lines.push(`- \`${d}/\` — ${d === 'src' || d === 'lib' ? 'source code' : d === 'tests' || d === 'test' || d === 'spec' ? 'tests' : d}`);
162
- lines.push('');
163
- }
164
- lines.push('## Coding conventions');
165
- lines.push('');
166
- lines.push('- Keep changes minimal and focused; match the surrounding style.');
167
- lines.push('- Before editing a file, read it; verify with the test command above.');
168
- lines.push('- Prefer the project\'s own scripts over ad-hoc shell commands.');
169
- lines.push('');
170
- return lines.join('\n');
171
- }
172
-
173
- module.exports = {
174
- sniffProject,
175
- buildAegisMd,
176
- buildClaudeMd: buildAegisMd, // reference name kept for compatibility
177
- };
3
+ "use strict";const fs=require("node:fs"),path=require("node:path"),{execSync:execSync}=require("node:child_process"),{pathName:pathName}=require("./format.js");function readJson(e,t){try{return JSON.parse(fs.readFileSync(path.join(t,e),"utf8"))}catch{return null}}function hasFile(e,...t){return t.some((t=>fs.existsSync(path.join(e,t))))}function gitName(e){try{const t=execSync("git config --get remote.origin.url",{encoding:"utf8",cwd:e,stdio:["ignore","pipe","ignore"]}).trim(),s=pathName(t).replace(/\.git$/,"");if(s)return s}catch{}try{return pathName(e)||"this project"}catch{return"this project"}}function sniffProject(e=process.cwd()){const t=readJson("package.json",e),s={name:t&&t.name?t.name:gitName(e),lang:"unknown",build:null,test:null,lint:null,dev:null,structure:[],toolchain:[]};if(t){s.lang="JavaScript/TypeScript (Node.js)",s.toolchain.push("Node.js");const e=t.scripts||{};e.build&&(s.build="npm run build"),e.test&&(s.test="npm test"),e.lint&&(s.lint="npm run lint"),(e.dev||e.start||e.watch)&&(s.dev=e.dev?"npm run dev":"npm start"),t.packageManager&&s.toolchain.push(t.packageManager)}else hasFile(e,"go.mod")?(s.lang="Go",s.toolchain.push("Go"),s.build="go build ./...",s.test="go test ./...",s.lint="golangci-lint run",s.dev="go run ."):hasFile(e,"Cargo.toml")?(s.lang="Rust",s.toolchain.push("Cargo"),s.build="cargo build",s.test="cargo test",s.lint="cargo clippy -- -D warnings",s.dev="cargo run"):hasFile(e,"pyproject.toml","setup.py","requirements.txt")?(s.lang="Python",s.toolchain.push("Python"),s.test=hasFile(e,"pytest.ini","tox.ini")?"pytest":"python -m pytest",s.lint="ruff check ."):hasFile(e,"Makefile")?(s.lang="C/C++ or make-driven",s.toolchain.push("make"),s.build="make",s.test="make test",s.dev="make run"):hasFile(e,"pom.xml","build.gradle")?(s.lang="Java",s.toolchain.push("Maven/Gradle"),s.build=hasFile(e,"pom.xml")?"mvn package":"gradle build",s.test=hasFile(e,"pom.xml")?"mvn test":"gradle test"):hasFile(e,"Gemfile")?(s.lang="Ruby",s.toolchain.push("Ruby"),s.test="bundle exec rspec",s.build="bundle exec rake build"):hasFile(e,"composer.json")?(s.lang="PHP",s.toolchain.push("Composer"),s.test="composer test"):hasFile(e,".csproj")&&(s.lang="C#/.NET",s.toolchain.push(".NET"),s.build="dotnet build",s.test="dotnet test");for(const t of["src","lib","app","tests","test","spec","docs","scripts"])fs.existsSync(path.join(e,t))&&s.structure.push(t);for(const t of["eslint.config.js",".eslintrc",".prettierrc","biome.json","tsconfig.json",".github/workflows"])fs.existsSync(path.join(e,t))&&s.toolchain.push(t.split("/")[0]);return s}function buildAegisMd(e){const t=e,s=[];if(s.push("# AEGIS.md"),s.push(""),s.push("Generated by AEGIS Code /init — edit freely. This file teaches AI agents how to work in this repo."),s.push(""),s.push("## Project"),s.push(""),s.push(`- Project: ${t.name}`),s.push(`- Language: ${t.lang}`),t.toolchain.length&&s.push(`- Toolchain: ${[...new Set(t.toolchain)].join(", ")}`),s.push(""),s.push("## Commands"),s.push(""),s.push("Run these to build, test, and lint:"),s.push("```bash"),t.build&&s.push(t.build+" # build"),t.test&&s.push(t.test+" # test"),t.lint&&s.push(t.lint+" # lint"),t.dev&&s.push(t.dev+" # dev server"),s.push("```"),s.push(""),t.structure.length){s.push("## Project structure"),s.push("");for(const e of t.structure)s.push(`- \`${e}/\` — ${"src"===e||"lib"===e?"source code":"tests"===e||"test"===e||"spec"===e?"tests":e}`);s.push("")}return s.push("## Coding conventions"),s.push(""),s.push("- Keep changes minimal and focused; match the surrounding style."),s.push("- Before editing a file, read it; verify with the test command above."),s.push("- Prefer the project's own scripts over ad-hoc shell commands."),s.push(""),s.join("\n")}module.exports={sniffProject:sniffProject,buildAegisMd:buildAegisMd,buildClaudeMd:buildAegisMd};