@aragon-agent/cli 0.6.53 → 0.6.54

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 (80) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +4042 -3982
  3. package/dist/agent/controller.d.ts +26 -0
  4. package/dist/agent/controller.js +129 -1
  5. package/dist/agent/system-prompt.d.ts +14 -0
  6. package/dist/agent/system-prompt.js +3 -0
  7. package/dist/app/App.d.ts +7 -0
  8. package/dist/app/App.js +135 -6
  9. package/dist/cli.js +25 -1
  10. package/dist/commands/builtins.js +10 -0
  11. package/dist/commands/catalog.js +1 -0
  12. package/dist/commands/registry.d.ts +7 -0
  13. package/dist/compaction/compactor.d.ts +26 -0
  14. package/dist/compaction/compactor.js +81 -8
  15. package/dist/compaction/summarize-call.d.ts +22 -0
  16. package/dist/compaction/summarize-call.js +29 -0
  17. package/dist/compaction/wiring.js +22 -3
  18. package/dist/config/app-paths.d.ts +13 -0
  19. package/dist/config/app-paths.js +15 -0
  20. package/dist/config/cli-commands.d.ts +15 -0
  21. package/dist/config/cli-commands.js +32 -1
  22. package/dist/config/env.d.ts +1 -0
  23. package/dist/config/env.js +11 -0
  24. package/dist/config/load.d.ts +6 -0
  25. package/dist/config/load.js +10 -1
  26. package/dist/config/store.js +10 -1
  27. package/dist/exec/bridge/server.js +9 -2
  28. package/dist/exec/options.js +16 -2
  29. package/dist/governance/prompts/orchestrator-block.js +2 -2
  30. package/dist/host/controller-factory.d.ts +25 -0
  31. package/dist/host/controller-factory.js +7 -0
  32. package/dist/host/follow-up-seed.d.ts +109 -0
  33. package/dist/host/follow-up-seed.js +196 -0
  34. package/dist/host/follow-up.d.ts +73 -0
  35. package/dist/host/follow-up.js +123 -0
  36. package/dist/host/index.d.ts +3 -0
  37. package/dist/host/index.js +3 -0
  38. package/dist/host/memory.d.ts +21 -0
  39. package/dist/host/memory.js +17 -0
  40. package/dist/host/sessions.d.ts +32 -2
  41. package/dist/host/sessions.js +40 -2
  42. package/dist/logging/install.d.ts +1 -0
  43. package/dist/logging/install.js +4 -0
  44. package/dist/logging/logger.d.ts +1 -1
  45. package/dist/memory/block.d.ts +24 -0
  46. package/dist/memory/block.js +54 -0
  47. package/dist/memory/command.d.ts +31 -0
  48. package/dist/memory/command.js +350 -0
  49. package/dist/memory/format.d.ts +51 -0
  50. package/dist/memory/format.js +308 -0
  51. package/dist/memory/paths.d.ts +68 -0
  52. package/dist/memory/paths.js +172 -0
  53. package/dist/memory/plan.d.ts +37 -0
  54. package/dist/memory/plan.js +184 -0
  55. package/dist/memory/resolve.d.ts +45 -0
  56. package/dist/memory/resolve.js +54 -0
  57. package/dist/memory/secrets.d.ts +30 -0
  58. package/dist/memory/secrets.js +73 -0
  59. package/dist/memory/service.d.ts +175 -0
  60. package/dist/memory/service.js +576 -0
  61. package/dist/memory/store.d.ts +133 -0
  62. package/dist/memory/store.js +694 -0
  63. package/dist/memory/tools.d.ts +36 -0
  64. package/dist/memory/tools.js +527 -0
  65. package/dist/memory/transfer.d.ts +53 -0
  66. package/dist/memory/transfer.js +93 -0
  67. package/dist/session/checkpoint.d.ts +18 -0
  68. package/dist/session/checkpoint.js +34 -0
  69. package/dist/session/limits.d.ts +16 -0
  70. package/dist/session/limits.js +16 -0
  71. package/dist/session/persist.d.ts +47 -0
  72. package/dist/session/persist.js +1 -0
  73. package/dist/session/startup-session.d.ts +6 -0
  74. package/dist/session/startup-session.js +3 -0
  75. package/dist/session/store.d.ts +14 -0
  76. package/dist/session/store.js +18 -0
  77. package/dist/session/validate-session.js +98 -0
  78. package/dist/tools/index.d.ts +21 -2
  79. package/dist/tools/index.js +33 -0
  80. package/package.json +3 -3
@@ -0,0 +1,576 @@
1
+ /**
2
+ * MemoryService - the stateful half of agent memory (agent-memory spec 8.3 / 8.4).
3
+ *
4
+ * ASCII ONLY - `src/memory/**` is inside `glyphs.test.ts::inScope`.
5
+ *
6
+ * The controller is far over the repo's size limit, so session state, change tracking and
7
+ * the prompt block live here and the controller only forwards. THE DECISIONS are not here
8
+ * either: `planMemoryContext` and `resolveMemoryBudgets` are pure and table-tested; the
9
+ * disk is `store.ts`'s. This class holds what neither can: the session's mount overrides,
10
+ * the snapshot of the directory taken at the last sync, whether a change is waiting for the
11
+ * turn to end, and the subscriber list.
12
+ *
13
+ * THE SYSTEM PROMPT CHANGES ONLY WHEN SOMETHING THE USER (OR AN APPROVED TOOL CALL) DID
14
+ * CHANGES IT. `promptKey` hashes exactly those inputs - note contents, overrides, the
15
+ * auto-load switch, the budgets, the project - and nothing else: no clock, no counter, no
16
+ * "last read". That is what lets the block sit in the provider's prefix cache (I-4).
17
+ *
18
+ * CHANGES LAND AT TURN BOUNDARIES (D-13 / I-6). While a turn runs the prompt it captured
19
+ * stays untouched; a mount flips `pending`, the surface says "applies after this turn", and
20
+ * `onTurnEnd` clears the flag. The prompt itself is rebuilt at the START of the next turn
21
+ * (`prepareUserTurn`), which is also where edits made by another process or by hand are
22
+ * picked up - there is no watcher to rely on.
23
+ */
24
+ import { createHash } from 'node:crypto';
25
+ import { CHARS_PER_TOKEN } from '@aragon-agent/core';
26
+ import { DEFAULT_MEMORY_CONFIG } from '@aragon-agent/tui/model/config/schema';
27
+ import { nextMountAction, policyWantsBody } from '@aragon-agent/tui/model/memory/mount';
28
+ import { compareMemoryRows, filterMemoryRows } from '@aragon-agent/tui/model/memory/search';
29
+ import { getLogger } from '../logging/logger.js';
30
+ import { buildMemoryBlock } from './block.js';
31
+ import { planMemoryContext, resolveMemoryBudgets } from './plan.js';
32
+ import { isValidNoteId, resolveProjectKey, } from './paths.js';
33
+ import { createNote, listTrash, moveNote, purgeExpiredTrash, readNote, restoreNote, scanScope, toCatalogRow, trashNote, updateNote, } from './store.js';
34
+ const MAX_RESTORED_OVERRIDES = 400;
35
+ export class MemoryService {
36
+ deps;
37
+ session = { autoload: null, overrides: {}, agentWrites: null };
38
+ notes = [];
39
+ project;
40
+ memoryConfig;
41
+ pending = false;
42
+ notice = null;
43
+ computed = null;
44
+ blockKey = null;
45
+ block = '';
46
+ lastEmitted = null;
47
+ listeners = new Set();
48
+ constructor(deps) {
49
+ this.deps = deps;
50
+ this.memoryConfig = deps.getConfig().memory ?? DEFAULT_MEMORY_CONFIG;
51
+ this.project = resolveProjectKey(deps.getCwd());
52
+ this.sync();
53
+ if (deps.purgeTrashOnStart !== false) {
54
+ const timer = setTimeout(() => {
55
+ try {
56
+ purgeExpiredTrash(this.now());
57
+ }
58
+ catch {
59
+ // Best effort; the sweep is housekeeping only.
60
+ }
61
+ }, 1500);
62
+ timer.unref?.();
63
+ }
64
+ }
65
+ // ---- identity ----------------------------------------------------------
66
+ getProject() {
67
+ return this.project;
68
+ }
69
+ /** Both scopes the current workspace can see, project first. */
70
+ targets() {
71
+ return [{ scope: 'project', projectKey: this.project.key }, { scope: 'global' }];
72
+ }
73
+ targetOf(scope) {
74
+ return scope === 'global'
75
+ ? { scope: 'global' }
76
+ : { scope: 'project', projectKey: this.project.key };
77
+ }
78
+ // ---- reading -----------------------------------------------------------
79
+ /** The notes as of the last sync (full text). */
80
+ getNotes() {
81
+ return this.notes;
82
+ }
83
+ /** `true` if any note exists at all, enabled or not. */
84
+ hasNotes() {
85
+ return this.notes.length > 0;
86
+ }
87
+ /** Fresh read of one note by id (CAS source), resolving which scope owns it. */
88
+ getNote(id) {
89
+ if (!isValidNoteId(id))
90
+ return { ok: false, code: 'invalid_id' };
91
+ const known = this.notes.find((note) => note.id === id);
92
+ const order = known ? [known.scope] : ['project', 'global'];
93
+ for (const scope of order) {
94
+ const found = readNote(this.targetOf(scope), id);
95
+ if (found.ok || found.code !== 'not_found')
96
+ return found;
97
+ }
98
+ return { ok: false, code: 'not_found' };
99
+ }
100
+ /** Rows for a list: catalog fields plus where each stands in the context. */
101
+ listRows(query) {
102
+ const computed = this.compute(this.deps.getConfig());
103
+ const plan = computed.plan;
104
+ const inCatalog = new Set(plan.catalog.map((row) => row.id));
105
+ const rows = this.notes.map((note) => {
106
+ const body = plan.bodies.find((entry) => entry.id === note.id);
107
+ const state = note.enabled ? plan.rowState.get(note.id) ?? 'index' : 'disabled';
108
+ return {
109
+ ...toCatalogRow(note),
110
+ rowState: state,
111
+ override: this.session.overrides[note.id] ?? null,
112
+ clipped: body?.clipped === true,
113
+ inCatalog: inCatalog.has(note.id),
114
+ ...(body !== undefined ? { units: { loaded: body.loadedUnits, total: body.totalUnits } } : {}),
115
+ };
116
+ });
117
+ const sorted = rows.sort(compareMemoryRows);
118
+ return query !== undefined && query.trim().length > 0 ? filterMemoryRows(sorted, query) : sorted;
119
+ }
120
+ // ---- session state -----------------------------------------------------
121
+ effectiveAutoload(cfg) {
122
+ return this.session.autoload ?? cfg.autoload;
123
+ }
124
+ /** What `agentWrites` is right now. `off` can only come from configuration. */
125
+ effectiveAgentWrites() {
126
+ const configured = (this.deps.getConfig().memory ?? this.memoryConfig).agentWrites;
127
+ if (configured === 'off')
128
+ return 'off';
129
+ return this.session.agentWrites ?? configured;
130
+ }
131
+ /** Apply a change to session state, deferring the prompt rewrite when a turn is running. */
132
+ afterChange(promptAffected) {
133
+ this.computed = null;
134
+ if (!promptAffected) {
135
+ this.emitIfChanged();
136
+ return 'applied';
137
+ }
138
+ if (this.deps.isBusy()) {
139
+ this.pending = true;
140
+ this.emitIfChanged();
141
+ return 'deferred';
142
+ }
143
+ this.deps.rebuildPrompt();
144
+ this.emitIfChanged();
145
+ return 'applied';
146
+ }
147
+ setOverride(id, state) {
148
+ if (!this.memoryConfig.enabled)
149
+ return { ok: false, code: 'disabled' };
150
+ const note = this.notes.find((entry) => entry.id === id);
151
+ if (note === undefined)
152
+ return { ok: false, code: 'not_found' };
153
+ if (state === 'mount') {
154
+ if (!note.enabled)
155
+ return { ok: false, code: 'mount_refused' };
156
+ const trial = { ...this.session.overrides, [id]: 'mount' };
157
+ const plan = this.planWith(trial);
158
+ if (plan.refusedMounts.includes(id))
159
+ return { ok: false, code: 'mount_refused' };
160
+ }
161
+ const next = { ...this.session.overrides };
162
+ if (state === 'reset')
163
+ delete next[id];
164
+ else
165
+ next[id] = state;
166
+ if (JSON.stringify(next) === JSON.stringify(this.session.overrides)) {
167
+ return { ok: true, effect: 'applied' };
168
+ }
169
+ this.session = { ...this.session, overrides: next };
170
+ return { ok: true, effect: this.afterChange(true) };
171
+ }
172
+ /** Flip a note's text in or out, choosing the spelling that makes a second press undo it. */
173
+ toggleMount(id) {
174
+ const note = this.notes.find((entry) => entry.id === id);
175
+ if (note === undefined)
176
+ return { ok: false, code: 'not_found' };
177
+ const cfg = this.deps.getConfig();
178
+ const computed = this.compute(cfg);
179
+ const state = computed.plan.rowState.get(id);
180
+ const action = nextMountAction({
181
+ hasBody: state !== undefined && state.startsWith('body-'),
182
+ policyBody: policyWantsBody(computed.autoload, note.load),
183
+ override: this.session.overrides[id] ?? null,
184
+ });
185
+ return this.setOverride(id, action);
186
+ }
187
+ setAutoload(value) {
188
+ if (!this.memoryConfig.enabled)
189
+ return { ok: false, code: 'disabled' };
190
+ if (this.session.autoload === value)
191
+ return { ok: true, effect: 'applied' };
192
+ this.session = { ...this.session, autoload: value };
193
+ return { ok: true, effect: this.afterChange(true) };
194
+ }
195
+ setAgentWrites(mode) {
196
+ if (!this.memoryConfig.enabled)
197
+ return { ok: false, code: 'disabled' };
198
+ if (this.session.agentWrites === mode)
199
+ return { ok: true, effect: 'applied' };
200
+ this.session = { ...this.session, agentWrites: mode };
201
+ return { ok: true, effect: this.afterChange(false) };
202
+ }
203
+ // ---- prompt integration ------------------------------------------------
204
+ /** Hash of everything the block depends on, and nothing else (I-4). */
205
+ promptKey(config) {
206
+ return this.compute(config).key;
207
+ }
208
+ /**
209
+ * The `<memory>` block for the prompt being built for `config`. `''` = no block.
210
+ *
211
+ * THE WINDOW COMES FROM THE ARGUMENT, never from `this` (I-5): a model switch pre-builds
212
+ * the incoming model's prompt, and budgets sized for the outgoing window would overrun a
213
+ * smaller one.
214
+ */
215
+ renderBlock(config) {
216
+ const cfg = config.memory ?? this.memoryConfig;
217
+ if (!cfg.enabled)
218
+ return '';
219
+ const computed = this.compute(config);
220
+ if (this.blockKey === computed.key)
221
+ return this.block;
222
+ this.block = buildMemoryBlock(computed.plan);
223
+ this.blockKey = computed.key;
224
+ this.logRebuilt(computed);
225
+ return this.block;
226
+ }
227
+ logRebuilt(computed) {
228
+ try {
229
+ getLogger().info('memory', 'block_rebuilt', {
230
+ bodies: computed.plan.bodies.length,
231
+ indexLines: computed.plan.catalog.length,
232
+ chars: computed.plan.chars.total,
233
+ tokens: computed.plan.tokensEstimate,
234
+ degraded: computed.plan.degraded.length,
235
+ });
236
+ }
237
+ catch {
238
+ // Logging must never break prompt assembly.
239
+ }
240
+ }
241
+ planWith(overrides) {
242
+ const config = this.deps.getConfig();
243
+ const cfg = config.memory ?? this.memoryConfig;
244
+ const budgets = resolveMemoryBudgets(cfg, this.deps.resolveWindowTokens(config));
245
+ return planMemoryContext({
246
+ notes: this.notes,
247
+ overrides,
248
+ autoload: this.effectiveAutoload(cfg) && budgets.autoloadActive,
249
+ budgets,
250
+ });
251
+ }
252
+ /** Plan + key for `config`, memoised on the key. */
253
+ compute(config) {
254
+ const cfg = config.memory ?? this.memoryConfig;
255
+ const budgets = resolveMemoryBudgets(cfg, this.deps.resolveWindowTokens(config));
256
+ const autoload = this.effectiveAutoload(cfg) && budgets.autoloadActive;
257
+ const key = this.keyOf(autoload, budgets);
258
+ if (this.computed !== null && this.computed.key === key)
259
+ return this.computed;
260
+ const plan = planMemoryContext({
261
+ notes: this.notes,
262
+ overrides: this.session.overrides,
263
+ autoload,
264
+ budgets,
265
+ });
266
+ this.computed = { key, plan, budgets, autoload };
267
+ return this.computed;
268
+ }
269
+ keyOf(autoload, budgets) {
270
+ const notes = this.notes
271
+ .map((note) => `${note.scope}:${note.id}:${note.rev}:${note.load}:${note.enabled ? 1 : 0}`)
272
+ .sort();
273
+ // NOT sorted: for explicit mounts the order they were added in decides who is refused when
274
+ // the ceiling is reached (see `planMemoryContext`), so it is part of what the block depends on.
275
+ const overrides = Object.keys(this.session.overrides).map((id) => `${id}=${this.session.overrides[id]}`);
276
+ const text = JSON.stringify([
277
+ notes,
278
+ overrides,
279
+ autoload,
280
+ [budgets.indexChars, budgets.bodyChars, budgets.perBodyChars, budgets.explicitCeiling, budgets.autoloadActive],
281
+ this.project.key,
282
+ ]);
283
+ return createHash('sha1').update(text).digest('hex');
284
+ }
285
+ /**
286
+ * Re-read the directory (cached by mtime + size), drop overrides for notes that vanished,
287
+ * and refresh the view. Called at the start of every user turn, and after any write.
288
+ *
289
+ * THE ONLY WAY AN OUTSIDE EDIT REACHES THE MODEL: another process, another window and a
290
+ * text editor all write to the same files, and none of them can tell this process.
291
+ */
292
+ sync() {
293
+ this.refreshNotes();
294
+ this.notice = null;
295
+ const missing = Object.keys(this.session.overrides).filter((id) => !this.notes.some((note) => note.id === id));
296
+ if (missing.length > 0) {
297
+ const next = { ...this.session.overrides };
298
+ let lostMount;
299
+ for (const id of missing) {
300
+ if (next[id] === 'mount')
301
+ lostMount = id;
302
+ delete next[id];
303
+ }
304
+ this.session = { ...this.session, overrides: next };
305
+ if (lostMount !== undefined)
306
+ this.notice = { code: 'mounted_note_missing', detail: lostMount };
307
+ }
308
+ this.computed = null;
309
+ this.emitIfChanged();
310
+ }
311
+ refreshNotes() {
312
+ this.notes = this.scanFresh();
313
+ }
314
+ /**
315
+ * The notes on disk RIGHT NOW (cached by mtime + size), both scopes, project first.
316
+ *
317
+ * What the tools read: they must see disk truth, not this service's last snapshot, but
318
+ * a read must not touch session state - so this returns the list and changes nothing.
319
+ */
320
+ scanFresh() {
321
+ const project = scanScope({ scope: 'project', projectKey: this.project.key }).notes;
322
+ const global = scanScope({ scope: 'global' }).notes;
323
+ const taken = new Set(project.map((note) => note.id));
324
+ // An id lives in ONE scope: overrides are keyed by id alone, so a global note that
325
+ // shares an id with a project note (possible only for hand-placed files) is ignored.
326
+ return [...project, ...global.filter((note) => !taken.has(note.id))];
327
+ }
328
+ /** Make the pending flag visible to surfaces and clear it. The next turn rebuilds. */
329
+ onTurnEnd() {
330
+ if (!this.pending)
331
+ return;
332
+ this.pending = false;
333
+ this.emitIfChanged();
334
+ }
335
+ /** `prompt()` entry safety net: `agent_end` may never have arrived (forced stop, /clear). */
336
+ applyPending() {
337
+ this.onTurnEnd();
338
+ }
339
+ /** The working directory changed: recompute which project's notes are visible. */
340
+ setCwd(cwd) {
341
+ this.project = resolveProjectKey(cwd);
342
+ this.sync();
343
+ }
344
+ updateConfig(next) {
345
+ this.memoryConfig = next;
346
+ this.computed = null;
347
+ this.emitIfChanged();
348
+ }
349
+ // ---- changes made through the service (UI saves, commands, tools) -------
350
+ /**
351
+ * A note file was created, changed or removed through the store. Re-sync, and treat it
352
+ * like any other change to what the prompt would contain.
353
+ */
354
+ noteChanged() {
355
+ const before = this.computed?.key ?? this.blockKey;
356
+ this.refreshNotes();
357
+ this.computed = null;
358
+ const missing = Object.keys(this.session.overrides).filter((id) => !this.notes.some((note) => note.id === id));
359
+ if (missing.length > 0) {
360
+ const next = { ...this.session.overrides };
361
+ for (const id of missing)
362
+ delete next[id];
363
+ this.session = { ...this.session, overrides: next };
364
+ }
365
+ const after = this.compute(this.deps.getConfig()).key;
366
+ if (after !== before) {
367
+ if (this.deps.isBusy())
368
+ this.pending = true;
369
+ else
370
+ this.deps.rebuildPrompt();
371
+ }
372
+ this.emitIfChanged();
373
+ }
374
+ /** Options shared by every write the service makes on a surface's behalf. */
375
+ writeOptions(source, confirmSecret) {
376
+ return {
377
+ source,
378
+ ...(confirmSecret !== undefined ? { confirmSecret } : {}),
379
+ knownSecrets: this.deps.knownSecrets?.() ?? [],
380
+ now: this.now(),
381
+ projectInfo: { root: this.project.root, label: this.project.label },
382
+ };
383
+ }
384
+ /**
385
+ * Save from a surface the USER is looking at (editor Save, `/memory save`). The only
386
+ * UI-side write path (I-1): there is no autosave and no draft on disk.
387
+ */
388
+ saveNote(draft, options = {}) {
389
+ const opts = this.writeOptions('user', options.confirmSecret);
390
+ let result;
391
+ if (options.id === undefined) {
392
+ result = createNote(this.targetOf(draft.scope), draft, opts);
393
+ }
394
+ else {
395
+ result = this.updateExisting(options.id, draft, options.expectedRev, opts);
396
+ }
397
+ if (result.ok)
398
+ this.noteChanged();
399
+ return result;
400
+ }
401
+ updateExisting(id, draft, expectedRev, opts) {
402
+ const current = this.getNote(id);
403
+ if (!current.ok)
404
+ return current;
405
+ const from = this.targetOf(current.value.scope);
406
+ if (expectedRev === undefined)
407
+ return { ok: false, code: 'conflict', current: current.value };
408
+ const updated = updateNote(from, id, { ...draft, scope: current.value.scope }, expectedRev, opts);
409
+ if (!updated.ok || draft.scope === current.value.scope)
410
+ return updated;
411
+ // Scope changed: copy to the new scope, then trash the original (never lose the note).
412
+ return moveNote(from, id, this.targetOf(draft.scope), updated.value.rev, opts);
413
+ }
414
+ /**
415
+ * File validated drafts from an import (P1). Every note is a CREATE under a freshly minted id with
416
+ * `source: 'imported'`, so an import never overwrites anything; a secret is refused rather than
417
+ * confirmed (the file may come from anyone), and a full scope stops the import for that scope.
418
+ * One `noteChanged()` at the end: the whole import is one change to the prompt, not N.
419
+ */
420
+ importNotes(drafts) {
421
+ let added = 0;
422
+ let skipped = 0;
423
+ for (const draft of drafts) {
424
+ const result = createNote(this.targetOf(draft.scope), draft, this.writeOptions('imported'));
425
+ if (result.ok)
426
+ added += 1;
427
+ else
428
+ skipped += 1;
429
+ }
430
+ if (added > 0)
431
+ this.noteChanged();
432
+ return { added, skipped };
433
+ }
434
+ deleteNote(id, expectedRev) {
435
+ const current = this.getNote(id);
436
+ if (!current.ok)
437
+ return current;
438
+ const result = trashNote(this.targetOf(current.value.scope), id, expectedRev, this.now());
439
+ if (result.ok)
440
+ this.noteChanged();
441
+ return result;
442
+ }
443
+ restoreTrashed(scope, trashId) {
444
+ const result = restoreNote(this.targetOf(scope), trashId);
445
+ if (result.ok)
446
+ this.noteChanged();
447
+ return result;
448
+ }
449
+ trash() {
450
+ return this.targets().flatMap((target) => listTrash(target));
451
+ }
452
+ // ---- checkpoint --------------------------------------------------------
453
+ /**
454
+ * Session state for the checkpoint. `undefined` when everything is at its default.
455
+ *
456
+ * Authority never travels in a file (agent-memory I-19): `agentWrites: 'auto'` is a switch the
457
+ * user flipped in THIS process, so it is written as `null`. `'ask'` is kept because it can
458
+ * only make the session stricter than its configuration.
459
+ */
460
+ exportState() {
461
+ const { autoload, overrides } = this.session;
462
+ const agentWrites = this.session.agentWrites === 'ask' ? 'ask' : null;
463
+ if (autoload === null && Object.keys(overrides).length === 0 && agentWrites === null) {
464
+ return undefined;
465
+ }
466
+ return { autoload, overrides: { ...overrides }, agentWrites };
467
+ }
468
+ /**
469
+ * Tolerant restore: anything malformed is dropped, ids that no longer exist go with it.
470
+ * `agentWrites` is restored only as `'ask'`: a session file is user-editable and `--resume`
471
+ * accepts any path, so it must not be able to switch write approval off (I-19).
472
+ */
473
+ restoreState(raw) {
474
+ const src = (raw && typeof raw === 'object' ? raw : {});
475
+ const overrides = {};
476
+ if (src.overrides && typeof src.overrides === 'object') {
477
+ for (const [id, value] of Object.entries(src.overrides)) {
478
+ if (Object.keys(overrides).length >= MAX_RESTORED_OVERRIDES)
479
+ break;
480
+ if (isValidNoteId(id) && (value === 'mount' || value === 'unmount'))
481
+ overrides[id] = value;
482
+ }
483
+ }
484
+ this.session = {
485
+ autoload: typeof src.autoload === 'boolean' ? src.autoload : null,
486
+ overrides,
487
+ agentWrites: src.agentWrites === 'ask' ? 'ask' : null,
488
+ };
489
+ this.refreshNotes();
490
+ const live = {};
491
+ for (const [id, value] of Object.entries(this.session.overrides)) {
492
+ if (this.notes.some((note) => note.id === id))
493
+ live[id] = value;
494
+ }
495
+ this.session = { ...this.session, overrides: live };
496
+ this.computed = null;
497
+ this.emitIfChanged();
498
+ }
499
+ // ---- view --------------------------------------------------------------
500
+ /** The whole session view. Always delivered whole: a missed update heals on the next. */
501
+ getView() {
502
+ const config = this.deps.getConfig();
503
+ const cfg = config.memory ?? this.memoryConfig;
504
+ if (!cfg.enabled)
505
+ return UNAVAILABLE_VIEW;
506
+ const computed = this.compute(config);
507
+ const { plan, budgets } = computed;
508
+ const limitUnits = budgets.autoloadActive ? budgets.total : budgets.explicitCeiling;
509
+ return {
510
+ available: true,
511
+ autoload: {
512
+ effective: computed.autoload,
513
+ overridden: this.session.autoload !== null,
514
+ ...(budgets.autoloadActive ? {} : { windowTooSmall: true }),
515
+ },
516
+ agentWrites: this.effectiveAgentWrites(),
517
+ agentWritesOverridden: this.session.agentWrites !== null,
518
+ project: { key: this.project.key, label: this.project.label },
519
+ loaded: plan.bodies.map((body) => ({
520
+ id: body.id,
521
+ reason: body.reason,
522
+ ...(body.clipped ? { clipped: true } : {}),
523
+ })),
524
+ indexed: plan.catalog.length,
525
+ overrides: { ...this.session.overrides },
526
+ budget: {
527
+ indexChars: budgets.indexChars,
528
+ bodyChars: budgets.bodyChars,
529
+ usedChars: plan.chars.total,
530
+ tokensEstimate: plan.tokensEstimate,
531
+ limitTokens: Math.ceil(Math.max(limitUnits, plan.chars.total) / CHARS_PER_TOKEN),
532
+ overBudget: plan.overBudget,
533
+ },
534
+ pending: this.pending,
535
+ noteCount: this.notes.length,
536
+ ...(this.notice !== null ? { notice: this.notice } : {}),
537
+ };
538
+ }
539
+ subscribe(listener) {
540
+ this.listeners.add(listener);
541
+ return () => {
542
+ this.listeners.delete(listener);
543
+ };
544
+ }
545
+ /** Tell subscribers if the view differs from the last one they were told. */
546
+ emitIfChanged() {
547
+ const key = JSON.stringify(this.getView());
548
+ if (key === this.lastEmitted)
549
+ return;
550
+ this.lastEmitted = key;
551
+ for (const listener of [...this.listeners]) {
552
+ try {
553
+ listener();
554
+ }
555
+ catch {
556
+ // One broken subscriber must not stop the others from repainting.
557
+ }
558
+ }
559
+ }
560
+ now() {
561
+ return this.deps.now?.() ?? Date.now();
562
+ }
563
+ }
564
+ /** What a surface sees when the controller has no memory service, or memory is off. */
565
+ export const UNAVAILABLE_VIEW = {
566
+ available: false,
567
+ autoload: { effective: false, overridden: false },
568
+ agentWrites: 'off',
569
+ project: null,
570
+ loaded: [],
571
+ indexed: 0,
572
+ overrides: {},
573
+ budget: { indexChars: 0, bodyChars: 0, usedChars: 0, tokensEstimate: 0, limitTokens: 0, overBudget: false },
574
+ pending: false,
575
+ noteCount: 0,
576
+ };