aegiscode 7.0.25 → 7.0.26

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 (113) hide show
  1. package/package.json +7 -3
  2. package/scripts/check.mjs +52 -1
  3. package/scripts/demo.mjs +94 -1
  4. package/scripts/predist.mjs +75 -1
  5. package/scripts/runtests.mjs +56 -1
  6. package/scripts/seal-gate.mjs +74 -1
  7. package/src/agents.js +139 -1
  8. package/src/app.js +2957 -1
  9. package/src/art.js +289 -1
  10. package/src/chatflow.js +3023 -1
  11. package/src/checkpoint.js +90 -1
  12. package/src/clipboard.js +424 -1
  13. package/src/cloudsync.js +528 -1
  14. package/src/commands.js +4089 -1
  15. package/src/config.js +581 -1
  16. package/src/connect.js +349 -1
  17. package/src/credentials.js +33 -1
  18. package/src/deps.js +232 -1
  19. package/src/devrun.js +187 -1
  20. package/src/diff.js +333 -1
  21. package/src/diffview.js +296 -1
  22. package/src/engine.js +297 -1
  23. package/src/entitlement.js +355 -1
  24. package/src/events.js +707 -1
  25. package/src/export.js +67 -1
  26. package/src/filepreview.js +153 -1
  27. package/src/fingerprint.js +592 -1
  28. package/src/format.js +259 -1
  29. package/src/fuzzy.js +119 -1
  30. package/src/history.js +423 -1
  31. package/src/init.js +175 -1
  32. package/src/input.js +139 -1
  33. package/src/keys.js +183 -1
  34. package/src/markdown.js +306 -1
  35. package/src/models.js +507 -1
  36. package/src/naming.js +57 -1
  37. package/src/overlays.js +462 -1
  38. package/src/panels.js +1418 -1
  39. package/src/ping.js +226 -1
  40. package/src/presence.js +238 -1
  41. package/src/render.js +516 -1
  42. package/src/screen.js +518 -1
  43. package/src/screens.js +896 -1
  44. package/src/secret.js +59 -1
  45. package/src/securefs.js +359 -1
  46. package/src/settings.js +155 -1
  47. package/src/shared.js +52 -1
  48. package/src/sharedpaths.js +53 -1
  49. package/src/signup.js +156 -1
  50. package/src/summarize.js +95 -1
  51. package/src/sysdiag.js +585 -1
  52. package/src/system.js +40 -1
  53. package/src/theme.js +570 -1
  54. package/src/title.js +220 -1
  55. package/src/todos.js +115 -1
  56. package/src/tokens.js +263 -1
  57. package/src/topup.js +210 -1
  58. package/src/update.js +191 -1
  59. package/vendor/client/aegis.js +2441 -1
  60. package/vendor/client/attest.js +518 -1
  61. package/vendor/client/authorship-key.js +410 -1
  62. package/vendor/client/auto-provision.js +134 -1
  63. package/vendor/client/brain-catalog.js +268 -1
  64. package/vendor/client/byok-catalog.js +199 -1
  65. package/vendor/client/catalog-client.js +487 -1
  66. package/vendor/client/conversation-export.js +177 -1
  67. package/vendor/client/credentials.js +494 -1
  68. package/vendor/client/device-fingerprint.js +141 -1
  69. package/vendor/client/drive-connect.js +110 -1
  70. package/vendor/client/drive-upload.js +234 -1
  71. package/vendor/client/env-file.js +1273 -1
  72. package/vendor/client/fingerprint.js +1064 -1
  73. package/vendor/client/foreign-memory.js +669 -1
  74. package/vendor/client/google-signin.js +133 -1
  75. package/vendor/client/hooks.js +430 -1
  76. package/vendor/client/model-discovery.js +373 -1
  77. package/vendor/client/naming.js +283 -1
  78. package/vendor/client/platform.js +937 -1
  79. package/vendor/client/prefs.js +351 -1
  80. package/vendor/client/presence-constants.js +107 -1
  81. package/vendor/client/presence.js +438 -1
  82. package/vendor/client/record-vault.js +1055 -3
  83. package/vendor/client/session-store.js +575 -1
  84. package/vendor/client/topup.js +297 -1
  85. package/vendor/client/touch.js +458 -1
  86. package/vendor/client/update.js +763 -1
  87. package/vendor/client/user-models.js +381 -1
  88. package/vendor/desktop/lib/local/agents.js +105 -1
  89. package/vendor/desktop/lib/local/attachments.js +276 -1
  90. package/vendor/desktop/lib/local/autonomous.js +1045 -1
  91. package/vendor/desktop/lib/local/claude-pro.js +1028 -1
  92. package/vendor/desktop/lib/local/context.js +125 -1
  93. package/vendor/desktop/lib/local/engine.js +3666 -1
  94. package/vendor/desktop/lib/local/entitlement.js +660 -1
  95. package/vendor/desktop/lib/local/git-scope.js +228 -1
  96. package/vendor/desktop/lib/local/local.js +2145 -1
  97. package/vendor/desktop/lib/local/prompt.js +280 -1
  98. package/vendor/desktop/lib/local/queue.js +560 -1
  99. package/vendor/desktop/lib/local/session-rounds.js +238 -1
  100. package/vendor/desktop/lib/local/spill.js +75 -1
  101. package/vendor/desktop/lib/local/turn-guard.js +300 -1
  102. package/vendor/desktop/lib/local/worktree-lock.js +235 -1
  103. package/vendor/desktop/lib/settings.js +890 -1
  104. package/vendor/desktop/renderer/usage.js +1239 -1
  105. package/vendor/hosts/install.js +638 -1
  106. package/vendor/hosts/openai-shim.js +515 -1
  107. package/vendor/hosts/spec.js +164 -1
  108. package/vendor/hosts/targets.js +346 -1
  109. package/vendor/mcp/server.js +221 -1
  110. package/vendor/mcp/tools.js +408 -1
  111. package/vendor/one/src/child.js +285 -1
  112. package/vendor/one/src/permissions.js +383 -1
  113. package/SOURCE-OFFER.txt +0 -9
@@ -1,3 +1,240 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const TTL_MS=18e5,MAX_ENTRIES=64,entries=new Map,historyKeys=new WeakMap;let historyKeySeq=0;function prune(e=Date.now()){for(const[t,n]of entries)e-n.at>TTL_MS&&entries.delete(t);for(;entries.size>MAX_ENTRIES;){const e=entries.keys().next();if(e.done)break;entries.delete(e.value)}return entries.size}function keyFor(e,t){const n=e&&"object"==typeof e?e:{},r=n.sessionKey||n.sessionId||n.chatId||n.threadId||n.conversationId;if("string"==typeof r&&r.trim())return`s:${r.trim()}`;if("string"==typeof n.cwd&&n.cwd.trim())return`cwd:${n.cwd.trim()}`;if(t&&"object"==typeof t){let e=historyKeys.get(t);return e||(historyKeySeq+=1,e=`hist-${historyKeySeq}`,historyKeys.set(t,e)),e}return"default"}function isStatedKey(e){const t=e&&"object"==typeof e?e:{},n=t.sessionKey||t.sessionId||t.chatId||t.threadId||t.conversationId;return!("string"!=typeof n||!n.trim())||"string"==typeof t.cwd&&t.cwd.trim().length>0}function bonus(e){const t=Number.isFinite(e)&&e>0?e:0;return Math.max(4,Math.ceil(t/4))}function peek(e,t=Date.now()){return prune(t),entries.get(e)||null}function take(e,t=Date.now()){prune(t);const n=entries.get(e);return n?(entries.delete(e),n):null}function adopt({now:e=Date.now(),maxAgeMs:t=6e5}={}){prune(e);let n=null,r=null;for(const[s,i]of entries)e-i.at>t||(!r||i.at>r.at)&&(r=i,n=s);return r?(entries.delete(n),{key:n,entry:r}):null}function record(e,{rounds:t,tokens:n,note:r,chain:s,messages:i,added:o}={},a=Date.now()){prune(a);const u=entries.get(e),d={rounds:Number.isFinite(t)?t:0,tokens:Number.isFinite(n)?n:0,note:"string"==typeof r?r:"",at:a,interruptions:(Number.isFinite(s)?s:u&&u.interruptions)||0,messages:Array.isArray(i)?i.slice():[],added:Array.isArray(o)?o.slice():[]};return d.interruptions+=1,entries.delete(e),entries.set(e,d),prune(a),d}function resumePreamble(e){return`[session resume] The previous turn in this conversation was cut off at ${e&&e.rounds?e.rounds:"the previous turn's"} tool rounds${e&&e.tokens?` (${e.tokens.toLocaleString()} tokens)`:""} because it reached the round horizon, so the work it started is unfinished. Continue that work now: do not restart, do not re-do steps that already completed, and do not treat the interruption as a failure to report. Pick up the next unfinished step and finish with a written answer.`}function state(e=Date.now()){return prune(e),{size:entries.size,ttlMs:TTL_MS,maxEntries:MAX_ENTRIES,entries:[...entries].map((([e,t])=>({key:e,...t})))}}function reset(){return entries.clear(),entries.size}module.exports={TTL_MS:TTL_MS,MAX_ENTRIES:MAX_ENTRIES,keyFor:keyFor,isStatedKey:isStatedKey,bonus:bonus,peek:peek,take:take,adopt:adopt,record:record,resumePreamble:resumePreamble,state:state,reset:reset};
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-scoped tool-round ledger.
10
+ *
11
+ * The engine's tool-round cap used to be a wall. A turn that reached it ended
12
+ * mid-investigation with `[stopped at 24 tool rounds…]`, and because the
13
+ * accounting lived only for the duration of that call, the next turn in the
14
+ * same conversation started from zero: it knew nothing about the horizon that
15
+ * had just cut it off, so a long job could be truncated by the cap forever
16
+ * without ever being finished.
17
+ *
18
+ * This makes the cap *session* state instead of turn state:
19
+ *
20
+ * - a turn that reaches its horizon records the unfinished work against the
21
+ * session key (rounds spent, tokens, the note the user saw, and the
22
+ * tool-call transcript itself — see `record`'s `messages`);
23
+ * - the next turn in that session takes the record — consuming it, so one
24
+ * resume per interruption and a chain of interruptions is a chain of
25
+ * deliberate asks, never an automatic loop — and gets a continuation
26
+ * preamble plus a small round bonus, so re-orientation does not eat the
27
+ * new horizon before any work happens;
28
+ * - an entry nobody comes back for expires after TTL_MS.
29
+ *
30
+ * State is module-level, so it outlives a turn, a `send()` and whichever
31
+ * engine instance the desktop happens to be using. It never leaves the
32
+ * process and is never written to disk.
33
+ */
34
+
35
+ /** How long an unclaimed interruption stays resumable (30 min). */
36
+ const TTL_MS = 30 * 60 * 1000;
37
+ /** Bound on live entries: a long-lived app must not grow without limit. */
38
+ const MAX_ENTRIES = 64;
39
+
40
+ const entries = new Map(); // key -> { rounds, tokens, note, at, interruptions }
41
+ const historyKeys = new WeakMap(); // history[] -> key
42
+ let historyKeySeq = 0;
43
+
44
+ /** Drop expired entries, then the oldest ones past the bound. */
45
+ function prune(now = Date.now()) {
46
+ for (const [key, entry] of entries) {
47
+ if (now - entry.at > TTL_MS) entries.delete(key);
48
+ }
49
+ while (entries.size > MAX_ENTRIES) {
50
+ // Map iteration is insertion-ordered and `record` re-inserts on write, so
51
+ // the first key is the oldest.
52
+ const oldest = entries.keys().next();
53
+ if (oldest.done) break;
54
+ entries.delete(oldest.value);
55
+ }
56
+ return entries.size;
57
+ }
58
+
59
+ /**
60
+ * The key an interruption is filed under. A caller that states its session
61
+ * (desktop payloads carry an id) gets an exact match; otherwise the working
62
+ * directory, then the identity of the history array, then a single shared
63
+ * bucket. `adopt` covers the remaining case — a caller that mints a fresh key
64
+ * every turn.
65
+ */
66
+ function keyFor(payload, history) {
67
+ const p = payload && typeof payload === 'object' ? payload : {};
68
+ const stated = p.sessionKey || p.sessionId || p.chatId || p.threadId || p.conversationId;
69
+ if (typeof stated === 'string' && stated.trim()) return `s:${stated.trim()}`;
70
+ if (typeof p.cwd === 'string' && p.cwd.trim()) return `cwd:${p.cwd.trim()}`;
71
+ if (history && typeof history === 'object') {
72
+ let key = historyKeys.get(history);
73
+ if (!key) {
74
+ historyKeySeq += 1;
75
+ key = `hist-${historyKeySeq}`;
76
+ historyKeys.set(history, key);
77
+ }
78
+ return key;
79
+ }
80
+ return 'default';
81
+ }
82
+
83
+ /**
84
+ * Whether `keyFor` would resolve to an identity the CALLER actually chose
85
+ * (a stated session id/key, or an explicit cwd) rather than one this module
86
+ * had to synthesise (the history-array identity, or the bare `'default'`
87
+ * bucket).
88
+ *
89
+ * This is what `adopt()` must be gated on. Every real caller today — the
90
+ * desktop renderer, the CLI (`sessionKey`), the queue worker (`queue-<id>`)
91
+ * — states an id, so a miss on THEIR key means exactly what it says: this
92
+ * conversation has no held work, full stop. Before this gate, engine.js
93
+ * called `adopt()` on every such miss regardless, which is the "bridge for a
94
+ * caller whose key does not survive between turns" firing for callers whose
95
+ * key demonstrably DOES survive — stealing whatever OTHER session's
96
+ * interruption happened to be the most recent one in the process-wide ledger
97
+ * and splicing its tool-call transcript into a conversation that never ran
98
+ * it. Live symptom: an unrelated chat opens with "[session resume] The
99
+ * previous turn in this conversation was cut off…" quoting a job it never
100
+ * started, because some other stated session — a benchmark run, a different
101
+ * open thread, anything that hit the horizon in the last `adopt()` window —
102
+ * had an entry sitting in the shared, module-level `entries` map when this
103
+ * one's `take()` came up empty.
104
+ */
105
+ function isStatedKey(payload) {
106
+ const p = payload && typeof payload === 'object' ? payload : {};
107
+ const stated = p.sessionKey || p.sessionId || p.chatId || p.threadId || p.conversationId;
108
+ if (typeof stated === 'string' && stated.trim()) return true;
109
+ return typeof p.cwd === 'string' && p.cwd.trim().length > 0;
110
+ }
111
+
112
+ /**
113
+ * Extra rounds granted to a resuming turn. Deliberately small and bounded: the
114
+ * point of resuming is to *continue* work that already exists, not to hand out
115
+ * a second full horizon (every round re-sends the whole conversation, so this
116
+ * is the cheapest way to make the cap non-fatal).
117
+ */
118
+ function bonus(base) {
119
+ const n = Number.isFinite(base) && base > 0 ? base : 0;
120
+ return Math.max(4, Math.ceil(n / 4));
121
+ }
122
+
123
+ /** Peek without consuming — the entry stays resumable. */
124
+ function peek(key, now = Date.now()) {
125
+ prune(now);
126
+ return entries.get(key) || null;
127
+ }
128
+
129
+ /** Claim the interruption for `key`, if any. Consuming: a second call gets null. */
130
+ function take(key, now = Date.now()) {
131
+ prune(now);
132
+ const entry = entries.get(key);
133
+ if (!entry) return null;
134
+ entries.delete(key);
135
+ return entry;
136
+ }
137
+
138
+ /**
139
+ * Claim the most recent interruption filed under ANY key. This is the bridge
140
+ * for a caller whose key does not survive between turns: the next turn on this
141
+ * process adopts the held work rather than losing it. Bounded by `maxAgeMs` so
142
+ * an unrelated new conversation is not handed yesterday's job.
143
+ */
144
+ function adopt({ now = Date.now(), maxAgeMs = 10 * 60 * 1000 } = {}) {
145
+ prune(now);
146
+ let bestKey = null;
147
+ let best = null;
148
+ for (const [key, entry] of entries) {
149
+ if (now - entry.at > maxAgeMs) continue;
150
+ if (!best || entry.at > best.at) {
151
+ best = entry;
152
+ bestKey = key;
153
+ }
154
+ }
155
+ if (!best) return null;
156
+ entries.delete(bestKey);
157
+ return { key: bestKey, entry: best };
158
+ }
159
+
160
+ /**
161
+ * File an interruption. `chain` carries the count forward from the entry this
162
+ * turn resumed, so `interruptions` reports how many times one job has been cut
163
+ * off — visible in the note and useful when deciding to raise the horizon.
164
+ *
165
+ * `messages` is the interrupted turn's own tool-call transcript (its live
166
+ * `history` array at the moment it hit the horizon) — real memory of what was
167
+ * already done, not just a rounds/tokens count of it. Without it a caller
168
+ * that supplies no conversation of its own (a queue task's fresh dispatch)
169
+ * resumes with an empty history: the model is told "continue, don't restart"
170
+ * with nothing to continue FROM, which is a cold start wearing a note.
171
+ * Stored as a defensive copy — the caller's `history` array keeps being
172
+ * mutated by the turn that is returning it.
173
+ */
174
+ function record(key, { rounds, tokens, note, chain, messages, added } = {}, now = Date.now()) {
175
+ prune(now);
176
+ const prior = entries.get(key);
177
+ const entry = {
178
+ rounds: Number.isFinite(rounds) ? rounds : 0,
179
+ tokens: Number.isFinite(tokens) ? tokens : 0,
180
+ note: typeof note === 'string' ? note : '',
181
+ at: now,
182
+ interruptions: (Number.isFinite(chain) ? chain : prior && prior.interruptions) || 0,
183
+ messages: Array.isArray(messages) ? messages.slice() : [],
184
+ // And what the interrupted turn added on TOP of what its caller already
185
+ // had. A resuming caller who brings its own conversation (an interactive
186
+ // chat) must get this half, not `messages` — pushing the full transcript
187
+ // into a history that already holds its first half duplicates the user's
188
+ // own turns back to the model.
189
+ added: Array.isArray(added) ? added.slice() : [],
190
+ };
191
+ entry.interruptions += 1;
192
+ entries.delete(key);
193
+ entries.set(key, entry); // re-insert so Map order stays age order
194
+ prune(now);
195
+ return entry;
196
+ }
197
+
198
+ /** The instruction that turns a cold start into a continuation. */
199
+ function resumePreamble(entry) {
200
+ const rounds = entry && entry.rounds ? entry.rounds : 'the previous turn\'s';
201
+ const tokens = entry && entry.tokens ? ` (${entry.tokens.toLocaleString()} tokens)` : '';
202
+ return (
203
+ `[session resume] The previous turn in this conversation was cut off at ${rounds} tool rounds${tokens} ` +
204
+ 'because it reached the round horizon, so the work it started is unfinished. Continue that work now: ' +
205
+ 'do not restart, do not re-do steps that already completed, and do not treat the interruption as a ' +
206
+ 'failure to report. Pick up the next unfinished step and finish with a written answer.'
207
+ );
208
+ }
209
+
210
+ /** Read-only snapshot for the UI (and for tests). */
211
+ function state(now = Date.now()) {
212
+ prune(now);
213
+ return {
214
+ size: entries.size,
215
+ ttlMs: TTL_MS,
216
+ maxEntries: MAX_ENTRIES,
217
+ entries: [...entries].map(([key, entry]) => ({ key, ...entry })),
218
+ };
219
+ }
220
+
221
+ /** Test hook: forget everything. */
222
+ function reset() {
223
+ entries.clear();
224
+ return entries.size;
225
+ }
226
+
227
+ module.exports = {
228
+ TTL_MS,
229
+ MAX_ENTRIES,
230
+ keyFor,
231
+ isStatedKey,
232
+ bonus,
233
+ peek,
234
+ take,
235
+ adopt,
236
+ record,
237
+ resumePreamble,
238
+ state,
239
+ reset,
240
+ };
@@ -1,3 +1,77 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const fs=require("node:fs"),os=require("node:os"),path=require("node:path"),SPILL_MAX_FILES=40;let spillDir=null,spillCount=0;function spill(t){try{if(spillCount>=SPILL_MAX_FILES)return null;spillDir||(spillDir=fs.mkdtempSync(path.join(os.tmpdir(),"aegiscode-tool-"))),spillCount+=1;const l=path.join(spillDir,`output-${spillCount}.txt`);return fs.writeFileSync(l,String(t),"utf8"),l}catch{return null}}function cap(t,l){const n=String(null==t?"":t);if(n.length<=l)return n;const i=n.slice(0,l),r=spill(n);return r?`${i}\n… (truncated after ${l} of ${n.length} chars — full output: ${r} — grep or readFile that path)`:`${i}\n… (truncated)`}module.exports={spill:spill,cap:cap,SPILL_MAX_FILES:SPILL_MAX_FILES};
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
+ * spill.js — what an oversized tool result becomes instead of nothing.
10
+ *
11
+ * `tools.js` (readFile/grep/glob/exec-one-shot) and `shell.js` (the persistent
12
+ * session `exec`) each cut their output at OUTPUT_CAP. That was lossless for the
13
+ * model only as long as the answer was in the first 30 000 chars — and for the
14
+ * commands that overflow it usually is not: a wide grep, a full test log, a
15
+ * `find` over a big tree. The model's only recovery was to re-run a narrower
16
+ * command, which re-sends the whole prefix and bills a fresh round for
17
+ * information it had already paid to produce. Pi spilled the overflow to a file
18
+ * and told the model where it was; this is the same behaviour, in one place,
19
+ * because two copies would drift.
20
+ *
21
+ * Why it lives in its own module rather than in either caller: `shell.js` may
22
+ * not require `tools.js` (tools.js requires shell.js), so a shared helper is the
23
+ * only arrangement where both sides spill identically.
24
+ *
25
+ * Bounded on purpose — this is reachable from a tool call:
26
+ * · one temp dir per process (`mkdtemp`, 0700), lazily created;
27
+ * · at most SPILL_MAX_FILES files, after which `spill` returns null and the
28
+ * caller degrades to its old "… (truncated)" behaviour;
29
+ * · every failure path returns null rather than throwing, because this runs
30
+ * inside executors whose contract is "never throw".
31
+ *
32
+ * Cleanup is left to the OS temp reaper on purpose: a file the model may still
33
+ * read on the next round must not disappear when the turn ends (the queue and
34
+ * resume paths make "the turn" a fuzzy boundary), and a bounded set of 40 files
35
+ * per process in the temp dir is not a leak worth that risk.
36
+ */
37
+
38
+ const fs = require('node:fs');
39
+ const os = require('node:os');
40
+ const path = require('node:path');
41
+
42
+ const SPILL_MAX_FILES = 40;
43
+
44
+ let spillDir = null;
45
+ let spillCount = 0;
46
+
47
+ /** Write `text` to a fresh temp file and return its path, or null when
48
+ * spilling is unavailable (no cap left, no temp dir, read-only fs). */
49
+ function spill(text) {
50
+ try {
51
+ if (spillCount >= SPILL_MAX_FILES) return null;
52
+ if (!spillDir) spillDir = fs.mkdtempSync(path.join(os.tmpdir(), 'aegiscode-tool-'));
53
+ spillCount += 1;
54
+ const file = path.join(spillDir, `output-${spillCount}.txt`);
55
+ fs.writeFileSync(file, String(text), 'utf8');
56
+ return file;
57
+ } catch {
58
+ return null;
59
+ }
60
+ }
61
+
62
+ /** Cut `text` at `cap` chars, keeping the full text reachable on disk. The
63
+ * returned string stays within cap + ~200 chars so callers (and the tests in
64
+ * test/shell-buffer-bound.test.mjs) that budget on the cap keep their bound. */
65
+ function cap(text, limit) {
66
+ const s = String(text == null ? '' : text);
67
+ if (s.length <= limit) return s;
68
+ const head = s.slice(0, limit);
69
+ const file = spill(s);
70
+ if (!file) return `${head}\n… (truncated)`;
71
+ return (
72
+ `${head}\n… (truncated after ${limit} of ${s.length} chars — full output: ${file} ` +
73
+ `— grep or readFile that path)`
74
+ );
75
+ }
76
+
77
+ module.exports = { spill, cap, SPILL_MAX_FILES };
@@ -1,3 +1,302 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{gitRoot:gitRoot,gitStatusSnapshot:gitStatusSnapshot}=require("./git-scope.js"),GIT_FLAGS_WITH_ARG=new Set(["-C","-c","--git-dir","--work-tree","--namespace","--exec-path"]);function tokenize(t){const e=[];for(const n of String(t||"").split(/[|;&\n]+/)){const t=[],r=/"([^"]*)"|'([^']*)'|(\S+)/g;let s;for(;s=r.exec(n);)t.push(s[1]??s[2]??s[3]);t.length&&e.push(t)}return e}function gitInvocation(t){const e=t.findIndex((t=>"git"===t||t.endsWith("/git")));if(-1===e)return null;let n=e+1;for(;n<t.length&&t[n].startsWith("-");)n+=GIT_FLAGS_WITH_ARG.has(t[n])?2:1;return n>=t.length?null:{sub:t[n],args:t.slice(n+1)}}function namedPaths(t){const e=t.indexOf("--");return-1!==e?t.slice(e+1).filter((t=>!t.startsWith("-"))):t.filter((t=>!t.startsWith("-")))}const isTreeMark=t=>"."===t||"./"===t||"*"===t||"./*"===t,hasForce=t=>t.some((t=>"-f"===t||"--force"===t||/^-[a-zA-Z]*f/.test(t)));function judge(t,e){const n=namedPaths(e),r=0===n.length||n.some(isTreeMark);switch(t){case"checkout":return e.includes("--")||hasForce(e)?{what:"checkout of uncommitted changes",scope:r?"tree":"paths",paths:n}:r&&n.length?{what:"checkout . (tree-wide restore)",scope:"tree",paths:n}:null;case"restore":return{what:"restore (discards uncommitted changes)",scope:r?"tree":"paths",paths:n};case"reset":return e.includes("--hard")?{what:"reset --hard",scope:"tree",paths:[]}:null;case"clean":return hasForce(e)?{what:"clean -f (deletes untracked files)",scope:"tree",paths:[]}:null;case"stash":{const t=e.find((t=>!t.startsWith("-")));return"list"===t||"show"===t?null:{what:`stash ${t||"push"} (uncommitted changes across the tree)`,scope:"tree",paths:[]}}case"worktree":{const t=e.find((t=>!t.startsWith("-")));return"remove"===t||"prune"===t?{what:`worktree ${t}`,scope:"tree",paths:[]}:null}default:return null}}function classifyDestructive(t){for(const e of tokenize(t)){const t=gitInvocation(e);if(!t)continue;const n=judge(t.sub,t.args);if(n)return{destructive:!0,...n}}return{destructive:!1}}function beginTurnGuard(t){const e=gitRoot(t),n=e?gitStatusSnapshot(t):null;return{root:e,cwd:t,before:n,startedAt:Date.now(),written:new Set,active:Boolean(e&&n)}}function toRel(t,e){let n=String(e||"");return n?(t.root&&n.startsWith(t.root)&&(n=n.slice(t.root.length).replace(/^[/\\]/,"")),n.split("\\").join("/")):null}function recordWrite(t,e){if(!t||!t.active)return;const n=toRel(t,e);n&&t.written.add(n)}function foreignSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r,s]of e)t.written.has(r)||t.before.has(r)&&t.before.get(r)===s&&n.push(r);return n.sort()}function concurrentSince(t){if(!t||!t.active)return[];const e=gitStatusSnapshot(t.cwd);if(!e)return[];const n=[];for(const[r]of e)t.written.has(r)||t.before.has(r)||n.push(r);return n.sort()}function blocksDestructive(t,e){const n=classifyDestructive(e);if(!n.destructive)return{ok:!0};if(!t||!t.active)return{ok:!0};let r=foreignSince(t),s=concurrentSince(t).filter((t=>!r.includes(t))),o=[];if("tree"===n.scope)o=[...r,...s];else{const t=new Set(n.paths.map((t=>t.replace(/^\.\//,"")))),e=e=>e.filter((e=>t.has(e)||t.has("./"+e)));r=e(r),s=e(s),o=[...r,...s]}if(!o.length)return{ok:!0,what:n.what};const i=[];return r.length&&i.push(`${r.length} hold another agent's uncommitted work: `+r.slice(0,8).join(", ")+(r.length>8?` (+${r.length-8} more)`:"")),s.length&&i.push(`${s.length} changed since this turn began and were not written by this session: ${s.slice(0,8).join(", ")}`+(s.length>8?` (+${s.length-8} more)`:"")),{ok:!1,what:n.what,scope:n.scope,foreign:r,unattributed:s,reason:`refusing \`${n.what}\` in ${t.root}: `+("tree"===n.scope?"it is tree-scoped and would discard work it did not create — ":"it targets a path that is not yours to discard — ")+i.join("; ")+". Name only the paths you mean, or take the worktree lock first."}}module.exports={classifyDestructive:classifyDestructive,beginTurnGuard:beginTurnGuard,recordWrite:recordWrite,foreignSince:foreignSince,concurrentSince:concurrentSince,blocksDestructive:blocksDestructive};
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
+ * Turn-start foreign-write detection.
10
+ *
11
+ * Ported from the upstream engine reference (ESM → CommonJS).
12
+ *
13
+ * Bug this exists for: the commit-time scope check already knew how to tell
14
+ * "my changes" from "somebody else's in-flight work" — but only *after* a
15
+ * task had finished. The dangerous window is the opposite end: a session
16
+ * reads a file, time passes, a second agent edits that file, and the first
17
+ * session then acts on a stale mental model. That is how a live session
18
+ * destroyed a peer's work — the content it reverted was real and correct,
19
+ * just not the content it had read.
20
+ *
21
+ * `git checkout HEAD -- <file>`, `git reset --hard`, `git stash` and
22
+ * `git clean` are the destructive operations, and their default scope is the
23
+ * whole tree. Running any of them while a peer has uncommitted work is the
24
+ * entire incident.
25
+ *
26
+ * Fix: snapshot the dirty set at turn start, record the paths this session
27
+ * actually writes, then answer two questions on demand —
28
+ * `foreignSince()` / `concurrentSince()` whose work is in the tree
29
+ * `blocksDestructive()` would a given command clobber it
30
+ * The second is load-bearing: it turns "revert someone else's file" into a
31
+ * refusal, which is the cheapest place to stop it.
32
+ *
33
+ * This is detection, not prevention — it cannot stop a writer outside the
34
+ * host. Paired with worktree-lock.js it covers our own sessions.
35
+ */
36
+
37
+ const { gitRoot, gitStatusSnapshot } = require('./git-scope.js');
38
+
39
+ /** Git's own flags that consume the *next* argv entry, so that token is not
40
+ * the subcommand. Without this, `git -C /repo reset --hard` parses `reset`
41
+ * as a flag argument and the whole command reads as harmless. */
42
+ const GIT_FLAGS_WITH_ARG = new Set([
43
+ '-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path',
44
+ ]);
45
+
46
+ /** Split a command line into shell segments and then argv, stripping quotes.
47
+ * Segmenting on `&&`/`;`/`|` means `ls && git checkout -- a` is still caught,
48
+ * while `git stash list` is judged on its own segment. */
49
+ function tokenize(command) {
50
+ const out = [];
51
+ for (const segment of String(command || '').split(/[|;&\n]+/)) {
52
+ const argv = [];
53
+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g;
54
+ let m;
55
+ while ((m = re.exec(segment))) argv.push(m[1] ?? m[2] ?? m[3]);
56
+ if (argv.length) out.push(argv);
57
+ }
58
+ return out;
59
+ }
60
+
61
+ /** The git subcommand and its arguments in one argv, or null if this argv
62
+ * isn't a git invocation that has a subcommand. */
63
+ function gitInvocation(argv) {
64
+ const i = argv.findIndex((t) => t === 'git' || t.endsWith('/git'));
65
+ if (i === -1) return null;
66
+ let j = i + 1;
67
+ while (j < argv.length && argv[j].startsWith('-')) {
68
+ j += GIT_FLAGS_WITH_ARG.has(argv[j]) ? 2 : 1;
69
+ }
70
+ if (j >= argv.length) return null;
71
+ return { sub: argv[j], args: argv.slice(j + 1) };
72
+ }
73
+
74
+ /** Positional arguments (the paths a command names), dropping flags. Values
75
+ * after `--` are always paths; before it, anything not starting with `-` is
76
+ * taken as one, which is right for checkout/restore and harmlessly unused
77
+ * elsewhere. */
78
+ function namedPaths(args) {
79
+ const sep = args.indexOf('--');
80
+ if (sep !== -1) return args.slice(sep + 1).filter((a) => !a.startsWith('-'));
81
+ return args.filter((a) => !a.startsWith('-'));
82
+ }
83
+
84
+ const isTreeMark = (p) => p === '.' || p === './' || p === '*' || p === './*';
85
+ const hasForce = (args) => args.some((a) => a === '-f' || a === '--force' || /^-[a-zA-Z]*f/.test(a));
86
+
87
+ /** subcommand -> { what, scope } where scope is 'tree' (discards broadly) or
88
+ * 'paths' (discards only the paths it names). Returns null when harmless. */
89
+ function judge(sub, args) {
90
+ const paths = namedPaths(args);
91
+ const treeWide = paths.length === 0 || paths.some(isTreeMark);
92
+ switch (sub) {
93
+ case 'checkout':
94
+ if (args.includes('--') || hasForce(args)) {
95
+ return { what: 'checkout of uncommitted changes', scope: treeWide ? 'tree' : 'paths', paths };
96
+ }
97
+ // `git checkout .` restores the whole tree; a bare branch switch is safe.
98
+ if (treeWide && paths.length) return { what: 'checkout . (tree-wide restore)', scope: 'tree', paths };
99
+ return null;
100
+ case 'restore':
101
+ return { what: 'restore (discards uncommitted changes)', scope: treeWide ? 'tree' : 'paths', paths };
102
+ case 'reset':
103
+ return args.includes('--hard') ? { what: 'reset --hard', scope: 'tree', paths: [] } : null;
104
+ case 'clean':
105
+ return hasForce(args) ? { what: 'clean -f (deletes untracked files)', scope: 'tree', paths: [] } : null;
106
+ case 'stash': {
107
+ const first = args.find((a) => !a.startsWith('-'));
108
+ if (first === 'list' || first === 'show') return null;
109
+ // pop/apply can conflict with, and push parks, every path in the tree.
110
+ return { what: `stash ${first || 'push'} (uncommitted changes across the tree)`, scope: 'tree', paths: [] };
111
+ }
112
+ case 'worktree': {
113
+ const first = args.find((a) => !a.startsWith('-'));
114
+ return first === 'remove' || first === 'prune'
115
+ ? { what: `worktree ${first}`, scope: 'tree', paths: [] }
116
+ : null;
117
+ }
118
+ default:
119
+ return null;
120
+ }
121
+ }
122
+
123
+ /**
124
+ * Classify a shell command line. Returns
125
+ * `{destructive:false}` or `{destructive:true, what, scope:'tree'|'paths', paths}`.
126
+ *
127
+ * Parsed as argv rather than matched as text, because a message *about* a
128
+ * destructive command is not one: `git commit -m "fix stash handling"` must
129
+ * not read as a stash. Quoting is handled, so the two are actually different.
130
+ */
131
+ function classifyDestructive(command) {
132
+ for (const argv of tokenize(command)) {
133
+ const inv = gitInvocation(argv);
134
+ if (!inv) continue;
135
+ const verdict = judge(inv.sub, inv.args);
136
+ if (verdict) return { destructive: true, ...verdict };
137
+ }
138
+ return { destructive: false };
139
+ }
140
+
141
+ /**
142
+ * Begin guarding a turn in `cwd`. Costs one `git status`; a non-repo (or a
143
+ * git failure) yields a guard that reports nothing, so callers never have to
144
+ * branch on whether the guard is armed.
145
+ */
146
+ function beginTurnGuard(cwd) {
147
+ const root = gitRoot(cwd);
148
+ const before = root ? gitStatusSnapshot(cwd) : null;
149
+ return {
150
+ root,
151
+ cwd,
152
+ before,
153
+ startedAt: Date.now(),
154
+ written: new Set(),
155
+ active: Boolean(root && before),
156
+ };
157
+ }
158
+
159
+ /** Normalise a written path to root-relative, so it can be compared against
160
+ * porcelain output. Accepts absolute or relative paths. */
161
+ function toRel(guard, p) {
162
+ let s = String(p || '');
163
+ if (!s) return null;
164
+ if (guard.root && s.startsWith(guard.root)) {
165
+ s = s.slice(guard.root.length).replace(/^[/\\]/, '');
166
+ }
167
+ return s.split('\\').join('/');
168
+ }
169
+
170
+ /**
171
+ * Record a path this session itself wrote. A recorded path is never reported
172
+ * as foreign — this is what keeps the guard from crying wolf about the
173
+ * caller's own edits, and it is why the host's file tools must call it.
174
+ */
175
+ function recordWrite(guard, p) {
176
+ if (!guard || !guard.active) return;
177
+ const rel = toRel(guard, p);
178
+ if (rel) guard.written.add(rel);
179
+ }
180
+
181
+ /**
182
+ * Paths that are *unambiguously* a peer's in-flight work: dirty when the turn
183
+ * started, byte-identical now, and never written by this session.
184
+ *
185
+ * "Dirty before and still identical" is what makes this confident — a path
186
+ * nobody touched is dirty *because* it belongs to someone else. It is
187
+ * git-scope's own definition, which is why the two modules agree.
188
+ */
189
+ function foreignSince(guard) {
190
+ if (!guard || !guard.active) return [];
191
+ const now = gitStatusSnapshot(guard.cwd);
192
+ if (!now) return [];
193
+ const out = [];
194
+ for (const [p, hash] of now) {
195
+ if (guard.written.has(p)) continue;
196
+ if (guard.before.has(p) && guard.before.get(p) === hash) out.push(p);
197
+ }
198
+ return out.sort();
199
+ }
200
+
201
+ /**
202
+ * Paths clean at turn start and dirty now, excluding any this session
203
+ * recorded writing.
204
+ *
205
+ * Weaker than `foreignSince` because attribution is incomplete: the host's
206
+ * file tools call `recordWrite`, but a path a shell command creates
207
+ * (`> out.txt`, `npm install`) is invisible here and can be mistaken for a
208
+ * peer's. Still reported, and still consulted by `blocksDestructive` — see
209
+ * the asymmetry note there.
210
+ */
211
+ function concurrentSince(guard) {
212
+ if (!guard || !guard.active) return [];
213
+ const now = gitStatusSnapshot(guard.cwd);
214
+ if (!now) return [];
215
+ const out = [];
216
+ for (const [p] of now) {
217
+ if (guard.written.has(p)) continue;
218
+ if (!guard.before.has(p)) out.push(p);
219
+ }
220
+ return out.sort();
221
+ }
222
+
223
+ /**
224
+ * Would running `command` be unsafe right now? Returns `{ok:true}` or
225
+ * `{ok:false, what, scope, reason, foreign, unattributed}`.
226
+ *
227
+ * Scope decides what has to be at risk:
228
+ * - a *tree-wide* op (`git reset --hard`, `git stash`, `git checkout .`) is
229
+ * refused whenever any peer work is present, because it cannot help but
230
+ * touch it;
231
+ * - a *path-scoped* op is refused only when one of the paths it names is
232
+ * actually foreign, so reverting your own file still works while a peer
233
+ * happens to be editing a different one.
234
+ *
235
+ * Both signals count, because the risk is asymmetric: a refusal costs the
236
+ * caller one step (name the paths, or take the lock), while a miss destroys
237
+ * work that may exist nowhere else. In the incident this module exists for,
238
+ * the peer's files appeared *during* the turn, so the confident signal was
239
+ * empty — blocking on it alone would have missed the exact case that
240
+ * motivated the guard.
241
+ *
242
+ * A tree with nothing foreign is never blocked, so a solo session is never
243
+ * wedged: the module is inert unless somebody else's work is present.
244
+ */
245
+ function blocksDestructive(guard, command) {
246
+ const verdict = classifyDestructive(command);
247
+ if (!verdict.destructive) return { ok: true };
248
+ if (!guard || !guard.active) return { ok: true };
249
+
250
+ let foreign = foreignSince(guard);
251
+ let unattributed = concurrentSince(guard).filter((p) => !foreign.includes(p));
252
+
253
+ let atRisk = [];
254
+ if (verdict.scope === 'tree') {
255
+ atRisk = [...foreign, ...unattributed];
256
+ } else {
257
+ const named = new Set(verdict.paths.map((p) => p.replace(/^\.\//, '')));
258
+ const hits = (list) => list.filter((p) => named.has(p) || named.has('./' + p));
259
+ foreign = hits(foreign);
260
+ unattributed = hits(unattributed);
261
+ atRisk = [...foreign, ...unattributed];
262
+ }
263
+ if (!atRisk.length) return { ok: true, what: verdict.what };
264
+
265
+ const parts = [];
266
+ if (foreign.length) {
267
+ parts.push(
268
+ `${foreign.length} hold another agent's uncommitted work: `
269
+ + foreign.slice(0, 8).join(', ') + (foreign.length > 8 ? ` (+${foreign.length - 8} more)` : ''),
270
+ );
271
+ }
272
+ if (unattributed.length) {
273
+ parts.push(
274
+ `${unattributed.length} changed since this turn began and were not written by `
275
+ + `this session: ${unattributed.slice(0, 8).join(', ')}`
276
+ + (unattributed.length > 8 ? ` (+${unattributed.length - 8} more)` : ''),
277
+ );
278
+ }
279
+ return {
280
+ ok: false,
281
+ what: verdict.what,
282
+ scope: verdict.scope,
283
+ foreign,
284
+ unattributed,
285
+ reason:
286
+ `refusing \`${verdict.what}\` in ${guard.root}: `
287
+ + (verdict.scope === 'tree'
288
+ ? 'it is tree-scoped and would discard work it did not create — '
289
+ : 'it targets a path that is not yours to discard — ')
290
+ + parts.join('; ')
291
+ + '. Name only the paths you mean, or take the worktree lock first.',
292
+ };
293
+ }
294
+
295
+ module.exports = {
296
+ classifyDestructive,
297
+ beginTurnGuard,
298
+ recordWrite,
299
+ foreignSince,
300
+ concurrentSince,
301
+ blocksDestructive,
302
+ };