aegiscode 6.6.1 → 6.7.1

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.
package/src/config.js CHANGED
@@ -75,6 +75,87 @@ const DEFAULT_CONFIG = {
75
75
  lastCwd: '',
76
76
  };
77
77
 
78
+ // ── persisting memory (the WRITE half of aegis_memory) ──────────────────────
79
+
80
+ /**
81
+ * Cross-session memory has two halves. The READ half (`aegis_recall`) is sent
82
+ * unconditionally by both hosts — it is cheap, it is what lets an interrupted
83
+ * turn be picked up in a later session, and it is free on every plan. The
84
+ * WRITE half is what actually stored anything, and it used to sit behind
85
+ * `cloudSync`, which is absent (i.e. off) on every fresh install. That is the
86
+ * defect this key replaces: the copy promises "cross-session memory free with
87
+ * any account", the read half shipped to everybody, and the write half — the
88
+ * half that makes the promise true — was opt-in and undiscoverable.
89
+ *
90
+ * So the gate is now `memoryPersist` and it defaults ON. It stays a real gate:
91
+ * `/cloud memory off` (or `/sync off`) writes it false, and this resolver
92
+ * honours it. The write half also has a price, so the ceiling is surfaced
93
+ * rather than guessed at — aegis1 meters WRITES only (FREE_SYNC_TOKENS = 1 MB,
94
+ * PRO_SYNC_TOKENS = 10 MB); reads keep working past it. `/cloud memory` and the
95
+ * first-run notice state that in those words.
96
+ *
97
+ * Migration, not a reset. `loadConfig()` merges DEFAULT_CONFIG under the parsed
98
+ * file, so the *absence* of a key cannot be told from a default once merged —
99
+ * that is why this resolver reads the raw values in the order below instead of
100
+ * checking a merged boolean:
101
+ *
102
+ * memoryPersist (explicit) → cloudSync (an explicit pre-flip choice)
103
+ * → MEMORY_PERSIST_DEFAULT (on)
104
+ *
105
+ * An explicit `cloudSync: false` on disk therefore stays off (nobody who turned
106
+ * sync off gets quietly opted back in), an explicit `cloudSync: true` stays on,
107
+ * and a config with neither key becomes on. `setMemoryPersist()` then removes
108
+ * the legacy key, so the choice exists in exactly one place from then on.
109
+ */
110
+ const MEMORY_PERSIST_KEY = 'memoryPersist';
111
+ const LEGACY_MEMORY_PERSIST_KEY = 'cloudSync';
112
+ const MEMORY_PERSIST_DEFAULT = true;
113
+
114
+ /**
115
+ * Resolve the write half, with where the answer came from.
116
+ *
117
+ * @param {object} [cfg] a loaded config (defaults to `loadConfig()`).
118
+ * @returns {{enabled:boolean, source:'config'|'legacy'|'default'}}
119
+ * `explicit` is true for the first two — that is the distinction the
120
+ * status panels need to say "you turned this off" vs "this is the
121
+ * default", which is the difference between a setting and a rumour.
122
+ */
123
+ function memoryPersistState(cfg) {
124
+ let c = cfg;
125
+ if (!c) {
126
+ try {
127
+ c = loadConfig();
128
+ } catch {
129
+ return { enabled: MEMORY_PERSIST_DEFAULT, source: 'default', explicit: false };
130
+ }
131
+ }
132
+ if (c && typeof c[MEMORY_PERSIST_KEY] === 'boolean') {
133
+ return { enabled: c[MEMORY_PERSIST_KEY], source: 'config', explicit: true };
134
+ }
135
+ if (c && typeof c[LEGACY_MEMORY_PERSIST_KEY] === 'boolean') {
136
+ return { enabled: c[LEGACY_MEMORY_PERSIST_KEY], source: 'legacy', explicit: true };
137
+ }
138
+ return { enabled: MEMORY_PERSIST_DEFAULT, source: 'default', explicit: false };
139
+ }
140
+
141
+ /** True when this host should persist memory (default on — see above). */
142
+ function memoryPersistEnabled(cfg) {
143
+ return memoryPersistState(cfg).enabled;
144
+ }
145
+
146
+ /**
147
+ * Persist the flip, and retire the legacy key in the same write so the two can
148
+ * never disagree. `undefined` (not `false`) is what removes a key through
149
+ * JSON.stringify — writing `false` would look like an explicit opt-out under
150
+ * the legacy name.
151
+ */
152
+ function setMemoryPersist(on) {
153
+ return updateConfig({
154
+ [MEMORY_PERSIST_KEY]: on === true,
155
+ [LEGACY_MEMORY_PERSIST_KEY]: undefined,
156
+ });
157
+ }
158
+
78
159
  /** Read the config, falling back to defaults (never throws). */
79
160
  function loadConfig() {
80
161
  try {
@@ -176,6 +257,12 @@ module.exports = {
176
257
  DEFAULT_CONFIG,
177
258
  loadConfig,
178
259
  updateConfig,
260
+ MEMORY_PERSIST_KEY,
261
+ LEGACY_MEMORY_PERSIST_KEY,
262
+ MEMORY_PERSIST_DEFAULT,
263
+ memoryPersistState,
264
+ memoryPersistEnabled,
265
+ setMemoryPersist,
179
266
  DEFAULT_PERMISSIONS,
180
267
  loadPermissions,
181
268
  savePermissions,
package/src/diff.js ADDED
@@ -0,0 +1,330 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Line-level diff for the transcript's edit blocks.
5
+ *
6
+ * An `editFile`/`writeFile` call used to render as a single gray row
7
+ * (" ⎿ $ {\"file_path\":\"src/hello.js\",...}"): you could see that a file
8
+ * changed and never *what* changed — the one thing a coding session is
9
+ * actually about. This module turns the tool call's arguments into a real
10
+ * unified-style diff, which diffview.js paints as a colored block.
11
+ *
12
+ * Where the two sides come from:
13
+ * editFile — args.old_string → args.new_string. No I/O at all.
14
+ * writeFile — the file as it was on disk *before* the call ran, against
15
+ * args.content. app.js builds the preview when the tool's
16
+ * `phase: 'run'` event arrives, which is strictly before the
17
+ * executor writes, so the read is the pre-edit state.
18
+ *
19
+ * Pure: strings in, plain row objects out — no spans, no colors, no globals,
20
+ * no `process.stdout` — so the whole thing is unit-testable with no TTY. The
21
+ * ANSI painting lives in diffview.js, exactly the split render.js already
22
+ * keeps between structure and paint.
23
+ *
24
+ * Ported from `aegiscodex-dev/src/diff.js`; the engine's tool names are
25
+ * `Edit`/`Write`/`MultiEdit`, this host's are `editFile`/`writeFile`, so
26
+ * `editPreview` accepts both spellings. `MultiEdit` has no counterpart here
27
+ * and is kept only so a newer engine frame cannot silently render nothing.
28
+ */
29
+
30
+ const fs = require('node:fs');
31
+ const path = require('node:path');
32
+
33
+ // Budgets. The preview is built synchronously inside the tool event, on the
34
+ // render path, so a 200 MB writeFile must not stall the CLI — the read is
35
+ // capped and the LCS table is bounded so a pathological pair of long files
36
+ // cannot allocate hundreds of megabytes. Past a budget the middle collapses to
37
+ // "remove everything, add everything", which is honest about being incomplete
38
+ // (`truncated: true` on the preview, `… N unchanged lines` in the block).
39
+ const DIFF_LIMITS = {
40
+ fileBytes: 256 * 1024, // bytes read from disk for writeFile
41
+ lcsCells: 250000, // n*m cap for the LCS table (~1 MB of Int32)
42
+ rows: 400, // diff rows kept per preview
43
+ context: 3, // unchanged lines kept around each change
44
+ };
45
+
46
+ /**
47
+ * Split text into display lines. A trailing newline is a terminator, not an
48
+ * empty last line — otherwise every normal file diff ends in a phantom
49
+ * "- " / "+ " pair. CRLF is normalized so a Windows checkout doesn't render as
50
+ * "every line changed".
51
+ */
52
+ function splitLines(text) {
53
+ const s = String(text == null ? '' : text).replace(/\r\n?/g, '\n');
54
+ if (s === '') return [];
55
+ const lines = s.split('\n');
56
+ if (lines.length && lines[lines.length - 1] === '') lines.pop();
57
+ return lines;
58
+ }
59
+
60
+ /**
61
+ * Unified-style diff of two strings.
62
+ *
63
+ * @returns {{rows: Array<{sign: string, text: string, no: number|null,
64
+ * marker?: boolean, note?: string}>, adds: number, dels: number,
65
+ * truncated: boolean}} `rows` carries context rows around each change run
66
+ * (DIFF_LIMITS.context lines), collapsed runs of unchanged lines as `marker`
67
+ * rows, and every changed line with a `no` for the gutter (old number on
68
+ * '-', new number otherwise).
69
+ */
70
+ function lineDiff(oldText, newText) {
71
+ const a = splitLines(oldText);
72
+ const b = splitLines(newText);
73
+ let pre = 0;
74
+ while (pre < a.length && pre < b.length && a[pre] === b[pre]) pre++;
75
+ let post = 0;
76
+ while (post < a.length - pre && post < b.length - pre && a[a.length - 1 - post] === b[b.length - 1 - post]) post++;
77
+
78
+ const midA = a.slice(pre, a.length - post);
79
+ const midB = b.slice(pre, b.length - post);
80
+ const ops = lcsOps(midA, midB);
81
+ const truncated = ops === null;
82
+ const body = ops || [
83
+ ...midA.map((text) => ({ sign: '-', text })),
84
+ ...midB.map((text) => ({ sign: '+', text })),
85
+ ];
86
+
87
+ // Nothing changed: say so with no rows at all. The prefix/suffix trim ate the
88
+ // whole file (pre === a.length, post === 0), so the context arithmetic below
89
+ // would otherwise paint "… 46 unchanged lines" plus three orphans over an
90
+ // identical pair — a marker claiming an omission that never happened.
91
+ if (!body.some((op) => op.sign !== ' ')) return { rows: [], adds: 0, dels: 0, truncated };
92
+
93
+ const ctx = DIFF_LIMITS.context;
94
+
95
+ const rows = [];
96
+ let oldNo = 1;
97
+ let newNo = 1;
98
+ // Leading context: keep *all* of it when it fits, otherwise the last `ctx`
99
+ // lines plus a marker for the ones actually dropped. The engine's original
100
+ // condition (`ctxBeforeStart < pre`) fires whenever the change is preceded by
101
+ // any line at all, so an ordinary three-line edit grew a bogus
102
+ // "… 1 unchanged line" marker and a change deep in a file reported `ctx` as
103
+ // the number hidden rather than the real count. A marker means "something was
104
+ // omitted", so it may only appear when something was.
105
+ const leadStart = pre > ctx ? pre - ctx : 0;
106
+ const hiddenLead = leadStart;
107
+ if (hiddenLead > 0) {
108
+ rows.push({ sign: ' ', text: '', marker: true, note: `… ${hiddenLead} unchanged line${hiddenLead === 1 ? '' : 's'}` });
109
+ }
110
+ for (let i = leadStart; i < pre; i++) {
111
+ rows.push({ sign: ' ', text: a[i], no: newNo });
112
+ newNo++;
113
+ oldNo++;
114
+ }
115
+ for (const op of body) {
116
+ if (op.sign === ' ') {
117
+ rows.push({ sign: ' ', text: op.text, no: newNo });
118
+ newNo++;
119
+ oldNo++;
120
+ } else if (op.sign === '-') {
121
+ rows.push({ sign: '-', text: op.text, no: oldNo });
122
+ oldNo++;
123
+ } else {
124
+ rows.push({ sign: '+', text: op.text, no: newNo });
125
+ newNo++;
126
+ }
127
+ }
128
+ // Suffix context: the first `ctx` lines of the untouched tail, then a marker
129
+ // for whatever unchanged tail is left over. Both the index into `b` and the
130
+ // gutter number come from `b`'s tail, not `a`'s: the engine read
131
+ // `b[a.length - post + i]`, which is the wrong line — and the wrong numbering
132
+ // — for every edit that changes the line count.
133
+ const tailStart = b.length - post;
134
+ const tailCount = Math.min(post, ctx);
135
+ newNo = tailStart + 1;
136
+ for (let i = 0; i < tailCount; i++) {
137
+ rows.push({ sign: ' ', text: b[tailStart + i], no: newNo });
138
+ newNo++;
139
+ oldNo++;
140
+ }
141
+ if (post > ctx) {
142
+ const n = post - ctx;
143
+ rows.push({ sign: ' ', text: '', marker: true, note: `… ${n} unchanged line${n === 1 ? '' : 's'}` });
144
+ }
145
+
146
+ const adds = rows.filter((r) => r.sign === '+').length;
147
+ const dels = rows.filter((r) => r.sign === '-').length;
148
+ let out = rows;
149
+ let cut = false;
150
+ if (out.length > DIFF_LIMITS.rows) {
151
+ out = out.slice(0, DIFF_LIMITS.rows);
152
+ out.push({ sign: ' ', text: '', marker: true, note: `… ${rows.length - DIFF_LIMITS.rows} more diff lines` });
153
+ cut = true;
154
+ }
155
+ return { rows: out, adds, dels, truncated: truncated || cut };
156
+ }
157
+
158
+ /**
159
+ * Longest-common-subsequence walk over two line arrays.
160
+ * @returns {Array<{sign: string, text: string}>|null} ops, or null when the
161
+ * table would exceed DIFF_LIMITS.lcsCells (the caller then treats the middle
162
+ * as a full replacement).
163
+ */
164
+ function lcsOps(a, b) {
165
+ const n = a.length;
166
+ const m = b.length;
167
+ if (!n || !m) {
168
+ return [
169
+ ...a.map((text) => ({ sign: '-', text })),
170
+ ...b.map((text) => ({ sign: '+', text })),
171
+ ];
172
+ }
173
+ if (n * m > DIFF_LIMITS.lcsCells) return null;
174
+ const w = m + 1;
175
+ const dp = new Int32Array((n + 1) * w); // dp[i*w+j] = |LCS(a[i:], b[j:])|
176
+ for (let i = n - 1; i >= 0; i--) {
177
+ for (let j = m - 1; j >= 0; j--) {
178
+ dp[i * w + j] = a[i] === b[j]
179
+ ? dp[(i + 1) * w + (j + 1)] + 1
180
+ : Math.max(dp[(i + 1) * w + j], dp[i * w + (j + 1)]);
181
+ }
182
+ }
183
+ const ops = [];
184
+ let i = 0;
185
+ let j = 0;
186
+ while (i < n && j < m) {
187
+ if (a[i] === b[j]) { ops.push({ sign: ' ', text: a[i] }); i++; j++; }
188
+ else if (dp[(i + 1) * w + j] >= dp[i * w + (j + 1)]) { ops.push({ sign: '-', text: a[i] }); i++; }
189
+ else { ops.push({ sign: '+', text: b[j] }); j++; }
190
+ }
191
+ while (i < n) ops.push({ sign: '-', text: a[i++] });
192
+ while (j < m) ops.push({ sign: '+', text: b[j++] });
193
+ return ops;
194
+ }
195
+
196
+ /** Capped read for the pre-edit state. Never throws; missing/unreadable → null. */
197
+ function readCapped(file, opts = {}) {
198
+ const bytes = opts.bytes == null ? DIFF_LIMITS.fileBytes : opts.bytes;
199
+ try {
200
+ const st = fs.statSync(file);
201
+ if (!st.isFile()) return { text: null, missing: true };
202
+ const text = fs.readFileSync(file, 'utf8');
203
+ if (st.size > bytes) return { text: text.slice(0, bytes), missing: false, truncated: true };
204
+ return { text, missing: false };
205
+ } catch {
206
+ return { text: null, missing: true };
207
+ }
208
+ }
209
+
210
+ /** Path as the user thinks of it: relative to the session cwd when it is inside it. */
211
+ function shortPath(file, cwd) {
212
+ const f = String(file || '');
213
+ if (!cwd) return f;
214
+ const rel = path.relative(cwd, f);
215
+ if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) return rel;
216
+ const parts = f.split(path.sep).filter(Boolean);
217
+ const base = f.startsWith(path.sep) ? path.sep : '';
218
+ return parts.length > 2 ? base + '…' + path.sep + parts.slice(-2).join(path.sep) : f;
219
+ }
220
+
221
+ /**
222
+ * Build the diff preview for a tool call, or null when the call isn't an edit
223
+ * or its arguments don't carry enough to diff (a partial stream, a malformed
224
+ * call). Never throws — a preview is decoration, not the tool result, so a bad
225
+ * argument object must not be able to break a turn.
226
+ *
227
+ * @param {string} name Tool name — this host's `editFile`/`writeFile`, or the
228
+ * engine's `Edit`/`Write`/`MultiEdit` (a vendored frame can carry either).
229
+ * @param {object|string} args Tool arguments as parsed from the stream.
230
+ * @param {{cwd?: string, readFile?: Function}} [opts] `readFile` is injectable
231
+ * so tests never touch disk.
232
+ */
233
+ function editPreview(name, args, opts = {}) {
234
+ try {
235
+ const cwd = opts.cwd == null ? process.cwd() : opts.cwd;
236
+ const readFile = opts.readFile || readCapped;
237
+ if (!args || typeof args !== 'object') return null;
238
+ const file = typeof args.file_path === 'string' ? args.file_path
239
+ : typeof args.path === 'string' ? args.path : null;
240
+ if (!file) return null;
241
+ const base = { file, short: shortPath(file, cwd) };
242
+
243
+ if (name === 'Edit' || name === 'editFile') {
244
+ if (typeof args.old_string !== 'string' || typeof args.new_string !== 'string') return null;
245
+ return Object.assign(
246
+ { kind: 'Update' },
247
+ base,
248
+ lineDiff(args.old_string, args.new_string),
249
+ { replaceAll: !!args.replace_all },
250
+ );
251
+ }
252
+
253
+ if (name === 'Write' || name === 'writeFile') {
254
+ if (typeof args.content !== 'string') return null;
255
+ const prev = readFile(file) || { text: null, missing: true };
256
+ const d = lineDiff(prev.text == null ? '' : prev.text, args.content);
257
+ return Object.assign(
258
+ { kind: prev.missing ? 'Create' : 'Write' },
259
+ base,
260
+ d,
261
+ { truncated: d.truncated || !!prev.truncated },
262
+ );
263
+ }
264
+
265
+ if (name === 'MultiEdit') {
266
+ const edits = (Array.isArray(args.edits) ? args.edits : []).filter(
267
+ (e) => e && typeof e.old_string === 'string' && typeof e.new_string === 'string',
268
+ );
269
+ if (!edits.length) return null;
270
+ const prev = readFile(file) || { text: null, missing: true };
271
+ if (typeof prev.text === 'string') {
272
+ let cur = prev.text;
273
+ let misses = 0;
274
+ for (const e of edits) {
275
+ if (cur.indexOf(e.old_string) === -1) { misses++; continue; }
276
+ cur = e.replace_all
277
+ ? cur.split(e.old_string).join(e.new_string)
278
+ : cur.replace(e.old_string, e.new_string);
279
+ }
280
+ const d = lineDiff(prev.text, cur);
281
+ return Object.assign(
282
+ { kind: 'Update' },
283
+ base,
284
+ d,
285
+ { misses, replaceAll: edits.some((e) => e.replace_all) },
286
+ );
287
+ }
288
+ // No base on disk: stack each edit's own diff rather than inventing one.
289
+ let rows = [];
290
+ let adds = 0;
291
+ let dels = 0;
292
+ let truncated = false;
293
+ edits.forEach((e, i) => {
294
+ const d = lineDiff(e.old_string, e.new_string);
295
+ if (i) rows.push({ sign: ' ', text: '', marker: true, note: `… edit ${i + 1} of ${edits.length}` });
296
+ rows = rows.concat(d.rows);
297
+ adds += d.adds;
298
+ dels += d.dels;
299
+ truncated = truncated || d.truncated;
300
+ });
301
+ return Object.assign(
302
+ { kind: 'Update' },
303
+ base,
304
+ { rows, adds, dels, truncated, stacked: edits.length },
305
+ );
306
+ }
307
+
308
+ return null;
309
+ } catch {
310
+ return null; // decoration must never break a turn
311
+ }
312
+ }
313
+
314
+ /** Human count line in the reference's wording: "Added 3 lines, removed 1 line". */
315
+ function changeSummary(preview) {
316
+ const parts = [];
317
+ if (preview.adds) parts.push(`Added ${preview.adds} line${preview.adds === 1 ? '' : 's'}`);
318
+ if (preview.dels) parts.push(`removed ${preview.dels} line${preview.dels === 1 ? '' : 's'}`);
319
+ return parts.length ? parts.join(', ') : 'no line changes';
320
+ }
321
+
322
+ module.exports = {
323
+ DIFF_LIMITS,
324
+ splitLines,
325
+ lineDiff,
326
+ readCapped,
327
+ shortPath,
328
+ changeSummary,
329
+ editPreview,
330
+ };