@aragon-agent/cli 0.6.53 → 0.6.55

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 (101) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +135 -6
  3. package/dist/agent/controller.d.ts +98 -0
  4. package/dist/agent/controller.js +341 -1
  5. package/dist/agent/redteam-prompt.d.ts +47 -0
  6. package/dist/agent/redteam-prompt.js +161 -0
  7. package/dist/agent/redteam-wiring.d.ts +159 -0
  8. package/dist/agent/redteam-wiring.js +349 -0
  9. package/dist/agent/system-prompt.d.ts +27 -0
  10. package/dist/agent/system-prompt.js +10 -0
  11. package/dist/app/App.d.ts +17 -1
  12. package/dist/app/App.js +266 -26
  13. package/dist/app/use-redteam-mode.d.ts +56 -0
  14. package/dist/app/use-redteam-mode.js +121 -0
  15. package/dist/cli.js +78 -4
  16. package/dist/commands/builtins.js +49 -1
  17. package/dist/commands/catalog.js +5 -0
  18. package/dist/commands/index-build.js +2 -1
  19. package/dist/commands/redteam-command.d.ts +22 -0
  20. package/dist/commands/redteam-command.js +141 -0
  21. package/dist/commands/registry.d.ts +7 -0
  22. package/dist/compaction/compactor.d.ts +26 -0
  23. package/dist/compaction/compactor.js +81 -8
  24. package/dist/compaction/summarize-call.d.ts +22 -0
  25. package/dist/compaction/summarize-call.js +29 -0
  26. package/dist/compaction/wiring.js +22 -3
  27. package/dist/config/app-paths.d.ts +13 -0
  28. package/dist/config/app-paths.js +15 -0
  29. package/dist/config/cli-commands.d.ts +15 -0
  30. package/dist/config/cli-commands.js +32 -1
  31. package/dist/config/env.d.ts +3 -1
  32. package/dist/config/env.js +23 -1
  33. package/dist/config/load.d.ts +18 -0
  34. package/dist/config/load.js +19 -1
  35. package/dist/config/redteam-launch.d.ts +77 -0
  36. package/dist/config/redteam-launch.js +58 -0
  37. package/dist/config/store.js +20 -1
  38. package/dist/config/ui-state.d.ts +44 -0
  39. package/dist/config/ui-state.js +38 -0
  40. package/dist/exec/bridge/server.js +9 -2
  41. package/dist/exec/options.js +16 -2
  42. package/dist/governance/prompts/orchestrator-block.js +2 -2
  43. package/dist/host/controller-factory.d.ts +33 -0
  44. package/dist/host/controller-factory.js +14 -0
  45. package/dist/host/follow-up-seed.d.ts +109 -0
  46. package/dist/host/follow-up-seed.js +196 -0
  47. package/dist/host/follow-up.d.ts +73 -0
  48. package/dist/host/follow-up.js +123 -0
  49. package/dist/host/index.d.ts +3 -0
  50. package/dist/host/index.js +3 -0
  51. package/dist/host/memory.d.ts +21 -0
  52. package/dist/host/memory.js +17 -0
  53. package/dist/host/sessions.d.ts +32 -2
  54. package/dist/host/sessions.js +40 -2
  55. package/dist/logging/install.d.ts +1 -0
  56. package/dist/logging/install.js +4 -0
  57. package/dist/logging/logger.d.ts +1 -1
  58. package/dist/memory/block.d.ts +24 -0
  59. package/dist/memory/block.js +54 -0
  60. package/dist/memory/command.d.ts +31 -0
  61. package/dist/memory/command.js +350 -0
  62. package/dist/memory/format.d.ts +51 -0
  63. package/dist/memory/format.js +308 -0
  64. package/dist/memory/paths.d.ts +68 -0
  65. package/dist/memory/paths.js +172 -0
  66. package/dist/memory/plan.d.ts +37 -0
  67. package/dist/memory/plan.js +184 -0
  68. package/dist/memory/resolve.d.ts +45 -0
  69. package/dist/memory/resolve.js +54 -0
  70. package/dist/memory/secrets.d.ts +30 -0
  71. package/dist/memory/secrets.js +73 -0
  72. package/dist/memory/service.d.ts +175 -0
  73. package/dist/memory/service.js +576 -0
  74. package/dist/memory/store.d.ts +133 -0
  75. package/dist/memory/store.js +694 -0
  76. package/dist/memory/tools.d.ts +36 -0
  77. package/dist/memory/tools.js +527 -0
  78. package/dist/memory/transfer.d.ts +53 -0
  79. package/dist/memory/transfer.js +93 -0
  80. package/dist/session/checkpoint.d.ts +33 -0
  81. package/dist/session/checkpoint.js +52 -0
  82. package/dist/session/limits.d.ts +16 -0
  83. package/dist/session/limits.js +16 -0
  84. package/dist/session/persist.d.ts +68 -0
  85. package/dist/session/persist.js +11 -0
  86. package/dist/session/startup-session.d.ts +17 -2
  87. package/dist/session/startup-session.js +15 -2
  88. package/dist/session/store.d.ts +14 -0
  89. package/dist/session/store.js +18 -0
  90. package/dist/session/validate-session.js +129 -0
  91. package/dist/team/runtime.d.ts +11 -0
  92. package/dist/team/runtime.js +6 -0
  93. package/dist/team/subagent.d.ts +21 -0
  94. package/dist/team/subagent.js +7 -0
  95. package/dist/tools/index.d.ts +45 -2
  96. package/dist/tools/index.js +53 -3
  97. package/package.json +3 -3
  98. package/skills/project-indexer/SKILL.md +275 -147
  99. package/skills/project-indexer/templates/artifact-hygiene-template.md +14 -0
  100. package/skills/project-indexer/templates/config-template.md +12 -0
  101. package/skills/project-indexer/templates/index-template.md +4 -0
@@ -0,0 +1,694 @@
1
+ /**
2
+ * The memory directory's ONLY read/write authority (agent-memory spec 8.2 / 8.5,
3
+ * D-1, D-15, D-16, I-3, I-11, I-12, I-14).
4
+ *
5
+ * ASCII ONLY - `src/memory/**` is inside `glyphs.test.ts::inScope`.
6
+ *
7
+ * EVERY WRITE IS: read the file as it is NOW, compare its content hash with the `rev` the
8
+ * caller saw, back the old bytes up, write a temp file in the same directory, rename it
9
+ * over the target. No lock (D-16): a stale lock file is a worse failure than one lost race,
10
+ * and the backup turns the one lost race into "your earlier text is in `.trash/versions`".
11
+ *
12
+ * NOTHING HERE THROWS (I-3). A bad file becomes a skipped entry plus a one-time notice; an
13
+ * unwritable directory becomes `write_failed`. The caller always gets a value it can show.
14
+ *
15
+ * READS ARE FREE OF SIDE EFFECTS (I-14): no directory is created, no file is touched, no
16
+ * mtime changes. Opening the manager on a hand-written file must not rewrite it.
17
+ *
18
+ * THIS MODULE IS THE ONLY CODE THAT WRITES UNDER `getMemoryDir()` (I-12). The tool, the
19
+ * `/memory` command, the overlay and the desktop IPC handlers all come through here, which
20
+ * is what lets one test prove "nothing writes without a user action" for the whole feature.
21
+ */
22
+ import { chmodSync, copyFileSync, existsSync, linkSync, lstatSync, mkdirSync, readdirSync, readFileSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
23
+ import { join } from 'node:path';
24
+ import process from 'node:process';
25
+ import { MEMORY_LIMITS } from '@aragon-agent/tui/model/memory/limits';
26
+ import { deriveMemorySummary, validateMemoryDraft, } from '@aragon-agent/tui/model/memory/validate';
27
+ import { getLogger } from '../logging/logger.js';
28
+ import { getMemoryDir } from '../config/app-paths.js';
29
+ import { computeRev, parseNoteBytes, serializeNote, MEMORY_FILE_SCHEMA, } from './format.js';
30
+ import { isInside, isValidNoteId, isValidProjectKey, mintNoteId, noteFile, projectMetaFile, scopeDir, stemOfNoteFile, trashDir, versionsDir, } from './paths.js';
31
+ import { looksLikeSecret } from './secrets.js';
32
+ function realSleep(ms) {
33
+ try {
34
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
35
+ }
36
+ catch {
37
+ // Some hosts forbid Atomics.wait on the main thread; a busy-wait of <=100 ms is fine.
38
+ const until = Date.now() + ms;
39
+ while (Date.now() < until) {
40
+ /* spin */
41
+ }
42
+ }
43
+ }
44
+ const REAL_FS = {
45
+ writeFileSync,
46
+ renameSync,
47
+ linkSync,
48
+ copyFileSync,
49
+ unlinkSync,
50
+ sleep: realSleep,
51
+ };
52
+ let io = REAL_FS;
53
+ /** Tests only: override pieces of the filesystem; call with no argument to restore. */
54
+ export function setMemoryFsOpsForTest(overrides) {
55
+ io = overrides === undefined ? REAL_FS : { ...REAL_FS, ...overrides };
56
+ }
57
+ // ---------------------------------------------------------------------------
58
+ // Process-wide state
59
+ // ---------------------------------------------------------------------------
60
+ let revision = 0;
61
+ let tmpSeq = 0;
62
+ let pendingSkipped = 0;
63
+ const reportedSkips = new Set();
64
+ const cache = new Map();
65
+ /** Number of successful writes to note files since start-up. Tests assert "one action, one write". */
66
+ export function getMemoryRevision() {
67
+ return revision;
68
+ }
69
+ /** Drop every cached parse (tests, and after the home root changes). */
70
+ export function resetMemoryCacheForTest() {
71
+ cache.clear();
72
+ reportedSkips.clear();
73
+ pendingSkipped = 0;
74
+ revision = 0;
75
+ }
76
+ /**
77
+ * What the last scans had to skip, once. `skipped` counts files that could not be used
78
+ * (bad name, not UTF-8, too large, a link out of the directory). Reading never backs
79
+ * anything up, so unlike the prompt library there is no "file was backed up" variant.
80
+ */
81
+ export function takeMemoryRepairNotice() {
82
+ if (pendingSkipped === 0)
83
+ return null;
84
+ const notice = { skipped: pendingSkipped };
85
+ pendingSkipped = 0;
86
+ return notice;
87
+ }
88
+ function noteSkip(key) {
89
+ if (reportedSkips.has(key))
90
+ return;
91
+ reportedSkips.add(key);
92
+ pendingSkipped += 1;
93
+ }
94
+ function log(event, fields) {
95
+ try {
96
+ getLogger().info('memory', event, fields);
97
+ }
98
+ catch {
99
+ // Logging must never break a write.
100
+ }
101
+ }
102
+ function isIgnoredName(name) {
103
+ return name.startsWith('.') || name === '_project.json' || name.includes('.tmp-');
104
+ }
105
+ /** `lstat` a directory entry; resolve links, but only ones that stay inside `dir`. */
106
+ function usableFileStat(full, dir) {
107
+ try {
108
+ const info = lstatSync(full);
109
+ if (info.isFile())
110
+ return { mtimeMs: info.mtimeMs, size: info.size };
111
+ if (!info.isSymbolicLink())
112
+ return null;
113
+ const real = realpathSync(full);
114
+ if (!isInside(realpathSync(dir), real))
115
+ return null;
116
+ const target = statSync(real);
117
+ return target.isFile() ? { mtimeMs: target.mtimeMs, size: target.size } : null;
118
+ }
119
+ catch {
120
+ return null;
121
+ }
122
+ }
123
+ function readEntries(dir) {
124
+ try {
125
+ return readdirSync(dir, { withFileTypes: true });
126
+ }
127
+ catch {
128
+ return [];
129
+ }
130
+ }
131
+ /**
132
+ * Every usable note in one scope, parsed (cached by path + mtime + size). Never throws,
133
+ * never writes. Skipped files are counted and reported once via `takeMemoryRepairNotice`.
134
+ */
135
+ export function scanScope(target) {
136
+ const dir = scopeDir(target);
137
+ if (dir === null)
138
+ return { notes: [], skipped: 0 };
139
+ const entries = readEntries(dir);
140
+ const notes = [];
141
+ let skipped = 0;
142
+ let seen = 0;
143
+ for (const entry of entries) {
144
+ const name = entry.name;
145
+ if (isIgnoredName(name) || !name.endsWith('.md'))
146
+ continue;
147
+ if (seen >= MEMORY_LIMITS.maxScanFiles) {
148
+ skipped += 1;
149
+ noteSkip(`${dir}|overflow`);
150
+ continue;
151
+ }
152
+ seen += 1;
153
+ const full = join(dir, name);
154
+ const stem = stemOfNoteFile(name);
155
+ const stat = stem === null ? null : usableFileStat(full, dir);
156
+ if (stem === null || stat === null || stat.size > MEMORY_LIMITS.maxFileBytes) {
157
+ skipped += 1;
158
+ noteSkip(`${full}|${stat?.mtimeMs ?? 0}`);
159
+ continue;
160
+ }
161
+ const cached = cache.get(full);
162
+ if (cached !== undefined && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
163
+ if (cached.note === null)
164
+ skipped += 1;
165
+ else
166
+ notes.push(cached.note);
167
+ continue;
168
+ }
169
+ const note = readNoteFile(full, stem, target.scope, stat.mtimeMs);
170
+ cache.set(full, { mtimeMs: stat.mtimeMs, size: stat.size, note });
171
+ if (note === null) {
172
+ skipped += 1;
173
+ noteSkip(`${full}|${stat.mtimeMs}`);
174
+ }
175
+ else
176
+ notes.push(note);
177
+ }
178
+ return { notes, skipped };
179
+ }
180
+ function readNoteFile(full, id, scope, mtimeMs) {
181
+ try {
182
+ return parseNoteBytes(readFileSync(full), { id, scope, mtimeMs });
183
+ }
184
+ catch {
185
+ return null;
186
+ }
187
+ }
188
+ /** Catalog rows (no bodies) for one scope. */
189
+ export function listCatalog(target) {
190
+ const scan = scanScope(target);
191
+ return { rows: scan.notes.map(toCatalogRow), skipped: scan.skipped };
192
+ }
193
+ /** Strip a note down to its catalog row. */
194
+ export function toCatalogRow(note) {
195
+ const { body, extra: _extra, ...rest } = note;
196
+ return {
197
+ ...rest,
198
+ bodyPreview: [...body].slice(0, MEMORY_LIMITS.bodyPreviewChars).join(''),
199
+ };
200
+ }
201
+ /** One note, read fresh from its file (never from the cache - this is what CAS compares). */
202
+ export function readNote(target, id) {
203
+ const file = noteFile(target, id);
204
+ if (file === null)
205
+ return { ok: false, code: 'invalid_id' };
206
+ const dir = scopeDir(target);
207
+ const stat = usableFileStat(file, dir);
208
+ if (stat === null)
209
+ return { ok: false, code: 'not_found' };
210
+ if (stat.size > MEMORY_LIMITS.maxFileBytes)
211
+ return { ok: false, code: 'not_found' };
212
+ const note = readNoteFile(file, id, target.scope, stat.mtimeMs);
213
+ return note === null ? { ok: false, code: 'not_found' } : { ok: true, value: note };
214
+ }
215
+ function fail(code, extra) {
216
+ return { ok: false, code, ...extra };
217
+ }
218
+ function normaliseTitle(title) {
219
+ return title.replace(/\s+/g, ' ').trim().toLowerCase();
220
+ }
221
+ function secretVerdict(input, opts) {
222
+ const text = [input.title, input.summary, input.body, input.tags.join(' ')].join('\n');
223
+ const verdict = looksLikeSecret(text, opts.knownSecrets ?? []);
224
+ if (!verdict.hit)
225
+ return null;
226
+ if (opts.source !== 'agent' && opts.confirmSecret === true)
227
+ return null;
228
+ return verdict.kind ?? 'secret';
229
+ }
230
+ /** Re-validate at the write boundary; the editor already did, the tool maybe did not. */
231
+ function revalidate(input) {
232
+ const verdict = validateMemoryDraft({
233
+ title: input.title,
234
+ summary: input.summary,
235
+ body: input.body,
236
+ tags: input.tags.join(','),
237
+ load: input.load,
238
+ enabled: input.enabled,
239
+ scope: input.scope,
240
+ });
241
+ return verdict.ok ? null : verdict.code;
242
+ }
243
+ const RETRY_CODES = new Set(['EPERM', 'EBUSY', 'EACCES']);
244
+ function mkdirPrivate(dir) {
245
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
246
+ if (process.platform !== 'win32') {
247
+ try {
248
+ chmodSync(getMemoryDir(), 0o700);
249
+ chmodSync(dir, 0o700);
250
+ }
251
+ catch {
252
+ // Best effort: the directory exists and works either way.
253
+ }
254
+ }
255
+ }
256
+ function errorCode(error) {
257
+ return error?.code ?? '';
258
+ }
259
+ /**
260
+ * Write `text` to `file` through a temp file in the same directory.
261
+ *
262
+ * `exclusive` creates only if absent (`link` is atomic where `rename` would overwrite), so
263
+ * two writers minting the same id cannot clobber each other. Otherwise the temp file is
264
+ * renamed over the target, retrying on the transient errors Windows raises when another
265
+ * process holds the target open.
266
+ */
267
+ function writeFileAtomic(file, text, exclusive) {
268
+ const tmp = `${file}.tmp-${process.pid}-${tmpSeq++}`;
269
+ try {
270
+ mkdirPrivate(join(file, '..'));
271
+ io.writeFileSync(tmp, text, { encoding: 'utf-8', mode: 0o600 });
272
+ if (exclusive) {
273
+ const outcome = linkExclusive(tmp, file);
274
+ if (outcome !== 'fallback')
275
+ return outcome;
276
+ if (existsSync(file))
277
+ return 'exists';
278
+ }
279
+ renameWithRetry(tmp, file);
280
+ if (process.platform !== 'win32')
281
+ chmodSync(file, 0o600);
282
+ return 'ok';
283
+ }
284
+ catch {
285
+ return 'failed';
286
+ }
287
+ finally {
288
+ try {
289
+ if (existsSync(tmp))
290
+ rmSync(tmp, { force: true });
291
+ }
292
+ catch {
293
+ // Nothing further to try.
294
+ }
295
+ }
296
+ }
297
+ function linkExclusive(tmp, file) {
298
+ try {
299
+ io.linkSync(tmp, file);
300
+ return 'ok';
301
+ }
302
+ catch (error) {
303
+ if (errorCode(error) === 'EEXIST')
304
+ return 'exists';
305
+ // A filesystem without hard links: fall back to exists-check + rename.
306
+ return 'fallback';
307
+ }
308
+ }
309
+ function renameWithRetry(from, to) {
310
+ let lastError;
311
+ for (let attempt = 0; attempt < 5; attempt += 1) {
312
+ try {
313
+ io.renameSync(from, to);
314
+ return;
315
+ }
316
+ catch (error) {
317
+ lastError = error;
318
+ if (!RETRY_CODES.has(errorCode(error)))
319
+ throw error;
320
+ io.sleep(20 * (attempt + 1));
321
+ }
322
+ }
323
+ throw lastError;
324
+ }
325
+ /** Keep the three newest backups of `id`. */
326
+ function backupVersion(target, id, file, now) {
327
+ const dir = versionsDir(target, id);
328
+ if (dir === null)
329
+ return 'failed';
330
+ try {
331
+ mkdirPrivate(dir);
332
+ io.copyFileSync(file, join(dir, `${now}.md`));
333
+ const names = readEntries(dir)
334
+ .map((entry) => entry.name)
335
+ .filter((name) => /^\d+\.md$/.test(name))
336
+ .sort((a, b) => Number.parseInt(b, 10) - Number.parseInt(a, 10));
337
+ for (const stale of names.slice(MEMORY_LIMITS.versionsKept)) {
338
+ try {
339
+ io.unlinkSync(join(dir, stale));
340
+ }
341
+ catch {
342
+ // A leftover backup is harmless; purgeExpiredTrash collects it later.
343
+ }
344
+ }
345
+ return 'ok';
346
+ }
347
+ catch {
348
+ return 'failed';
349
+ }
350
+ }
351
+ /** Best-effort sidecar so a "projects with memory" list can show a name instead of a hash. */
352
+ function touchProjectMeta(target, info, now) {
353
+ if (target.scope !== 'project' || info === undefined)
354
+ return;
355
+ const file = projectMetaFile(target.projectKey);
356
+ if (file === null)
357
+ return;
358
+ const body = JSON.stringify({ schema: 1, root: info.root, label: info.label, lastSeenAt: now });
359
+ writeFileAtomic(file, `${body}\n`, false);
360
+ }
361
+ function buildNoteBytes(input, base) {
362
+ return serializeNote({
363
+ title: input.title,
364
+ summary: input.summary.length > 0 ? input.summary : deriveMemorySummary(input.body),
365
+ body: input.body,
366
+ tags: input.tags,
367
+ load: input.load,
368
+ enabled: input.enabled,
369
+ createdAt: base.createdAt,
370
+ updatedAt: base.updatedAt,
371
+ source: base.source,
372
+ schema: base.schema,
373
+ ...(base.extra !== undefined ? { extra: base.extra } : {}),
374
+ });
375
+ }
376
+ function reparse(file, id, scope, text, mtimeMs) {
377
+ const parsed = parseNoteBytes(Buffer.from(text, 'utf-8'), { id, scope, mtimeMs });
378
+ if (parsed === null)
379
+ throw new Error('memory: a note we just serialised did not parse');
380
+ cache.delete(file);
381
+ return parsed;
382
+ }
383
+ /** Create a note. Mints the id; never overwrites an existing file. */
384
+ export function createNote(target, input, opts) {
385
+ const dir = scopeDir(target);
386
+ if (dir === null)
387
+ return fail('invalid_id');
388
+ const invalid = revalidate(input);
389
+ if (invalid !== null)
390
+ return fail(invalid);
391
+ const kind = secretVerdict(input, opts);
392
+ if (kind !== null)
393
+ return fail('secret_detected', { kind });
394
+ const scan = scanScope(target);
395
+ if (scan.notes.length >= MEMORY_LIMITS.maxNotesPerScope)
396
+ return fail('limit_reached');
397
+ if (opts.rejectDuplicateTitle === true) {
398
+ const wanted = normaliseTitle(input.title);
399
+ const clash = scan.notes.find((note) => note.enabled && normaliseTitle(note.title) === wanted);
400
+ if (clash !== undefined)
401
+ return fail('duplicate_title', { current: clash });
402
+ }
403
+ const now = opts.now ?? Date.now();
404
+ for (let attempt = 0; attempt < 5; attempt += 1) {
405
+ const id = mintNoteId();
406
+ const file = noteFile(target, id);
407
+ if (file === null || existsSync(file))
408
+ continue;
409
+ const text = buildNoteBytes(input, {
410
+ createdAt: now,
411
+ updatedAt: now,
412
+ schema: MEMORY_FILE_SCHEMA,
413
+ source: opts.source,
414
+ });
415
+ const outcome = writeFileAtomic(file, text, true);
416
+ if (outcome === 'exists')
417
+ continue;
418
+ if (outcome === 'failed') {
419
+ log('write_refused', { op: 'create', scope: target.scope, code: 'write_failed' });
420
+ return fail('write_failed');
421
+ }
422
+ revision += 1;
423
+ touchProjectMeta(target, opts.projectInfo, now);
424
+ const note = reparse(file, id, target.scope, text, now);
425
+ log('note_created', { id, scope: target.scope, op: 'create', rev: note.rev, chars: note.bodyChars });
426
+ return { ok: true, value: note };
427
+ }
428
+ return fail('write_failed');
429
+ }
430
+ function sameContent(note, input) {
431
+ const summary = input.summary.length > 0 ? input.summary : deriveMemorySummary(input.body);
432
+ return (note.title === input.title &&
433
+ note.summary === summary &&
434
+ note.body.replace(/\s+$/, '') === input.body.replace(/\s+$/, '') &&
435
+ note.load === input.load &&
436
+ note.enabled === input.enabled &&
437
+ note.tags.length === input.tags.length &&
438
+ note.tags.every((tag, index) => tag === input.tags[index]));
439
+ }
440
+ /**
441
+ * Replace a note's content, but only if it is still the version the caller saw (I-11).
442
+ *
443
+ * A mismatch returns `conflict` WITH the current note, so the editor can offer "reload" or
444
+ * "overwrite" - and "overwrite" is the same call again with the fresh `rev`, never a blind
445
+ * write. Saving content identical to what is on disk (and not in need of repair) writes
446
+ * nothing.
447
+ */
448
+ export function updateNote(target, id, input, expectedRev, opts) {
449
+ const file = noteFile(target, id);
450
+ if (file === null)
451
+ return fail('invalid_id');
452
+ const invalid = revalidate(input);
453
+ if (invalid !== null)
454
+ return fail(invalid);
455
+ const current = readNote(target, id);
456
+ if (!current.ok)
457
+ return fail(current.code);
458
+ if (current.value.rev !== expectedRev)
459
+ return fail('conflict', { current: current.value });
460
+ const kind = secretVerdict(input, opts);
461
+ if (kind !== null)
462
+ return fail('secret_detected', { kind });
463
+ if (sameContent(current.value, input) && !current.value.repaired)
464
+ return current;
465
+ if (opts.rejectDuplicateTitle === true) {
466
+ const wanted = normaliseTitle(input.title);
467
+ const clash = scanScope(target).notes.find((note) => note.id !== id && note.enabled && normaliseTitle(note.title) === wanted);
468
+ if (clash !== undefined)
469
+ return fail('duplicate_title', { current: clash });
470
+ }
471
+ const now = opts.now ?? Date.now();
472
+ const backup = backupVersion(target, id, file, now);
473
+ const text = buildNoteBytes(input, {
474
+ createdAt: current.value.createdAt,
475
+ updatedAt: Math.max(now, current.value.updatedAt),
476
+ schema: current.value.schema,
477
+ source: opts.source,
478
+ ...(current.value.extra !== undefined ? { extra: current.value.extra } : {}),
479
+ });
480
+ if (writeFileAtomic(file, text, false) !== 'ok') {
481
+ log('write_refused', { op: 'update', id, scope: target.scope, code: 'write_failed' });
482
+ return fail('write_failed');
483
+ }
484
+ revision += 1;
485
+ touchProjectMeta(target, opts.projectInfo, now);
486
+ const note = reparse(file, id, target.scope, text, now);
487
+ log('note_updated', { id, scope: target.scope, op: 'update', rev: note.rev, chars: note.bodyChars });
488
+ return backup === 'failed' ? { ok: true, value: note, backup: 'failed' } : { ok: true, value: note };
489
+ }
490
+ /** Move a note to the trash (30 days), if it is still the version the caller saw. */
491
+ export function trashNote(target, id, expectedRev, now = Date.now()) {
492
+ const file = noteFile(target, id);
493
+ const dir = trashDir(target);
494
+ if (file === null || dir === null)
495
+ return fail('invalid_id');
496
+ const current = readNote(target, id);
497
+ if (!current.ok)
498
+ return fail(current.code);
499
+ if (current.value.rev !== expectedRev)
500
+ return fail('conflict', { current: current.value });
501
+ try {
502
+ mkdirPrivate(dir);
503
+ renameWithRetry(file, join(dir, `${id}.${now}.md`));
504
+ }
505
+ catch {
506
+ log('write_refused', { op: 'delete', id, scope: target.scope, code: 'write_failed' });
507
+ return fail('write_failed');
508
+ }
509
+ cache.delete(file);
510
+ revision += 1;
511
+ log('note_trashed', { id, scope: target.scope, op: 'delete', rev: current.value.rev });
512
+ return { ok: true, value: { trashId: `${id}.${now}` } };
513
+ }
514
+ const TRASH_ID = /^([a-z0-9][a-z0-9_-]*)\.(\d{10,16})$/;
515
+ function parseTrashId(trashId) {
516
+ const match = TRASH_ID.exec(trashId);
517
+ if (match === null || !isValidNoteId(match[1]))
518
+ return null;
519
+ return { id: match[1], ts: Number.parseInt(match[2], 10) };
520
+ }
521
+ /**
522
+ * Bring a trashed note back. If its id has been taken meanwhile, it returns under a NEW id
523
+ * (never over the live note) and the caller is told which.
524
+ */
525
+ export function restoreNote(target, trashId) {
526
+ const parsed = parseTrashId(trashId);
527
+ const dir = trashDir(target);
528
+ const live = scopeDir(target);
529
+ if (parsed === null || dir === null || live === null)
530
+ return fail('invalid_id');
531
+ const from = join(dir, `${trashId}.md`);
532
+ if (!existsSync(from))
533
+ return fail('not_found');
534
+ if (scanScope(target).notes.length >= MEMORY_LIMITS.maxNotesPerScope)
535
+ return fail('limit_reached');
536
+ let id = parsed.id;
537
+ if (existsSync(join(live, `${id}.md`))) {
538
+ id = mintNoteId();
539
+ for (let attempt = 0; attempt < 5 && existsSync(join(live, `${id}.md`)); attempt += 1)
540
+ id = mintNoteId();
541
+ }
542
+ const to = noteFile(target, id);
543
+ if (to === null)
544
+ return fail('invalid_id');
545
+ try {
546
+ mkdirPrivate(live);
547
+ renameWithRetry(from, to);
548
+ }
549
+ catch {
550
+ return fail('write_failed');
551
+ }
552
+ cache.delete(to);
553
+ revision += 1;
554
+ log('note_restored', { id, scope: target.scope, op: 'restore' });
555
+ return { ok: true, value: { id } };
556
+ }
557
+ /** The trash for one scope, newest first. */
558
+ export function listTrash(target) {
559
+ const dir = trashDir(target);
560
+ if (dir === null)
561
+ return [];
562
+ const items = [];
563
+ for (const entry of readEntries(dir)) {
564
+ if (!entry.isFile() || !entry.name.endsWith('.md'))
565
+ continue;
566
+ const trashId = entry.name.slice(0, -3);
567
+ const parsed = parseTrashId(trashId);
568
+ if (parsed === null)
569
+ continue;
570
+ const note = readNoteFile(join(dir, entry.name), parsed.id, target.scope, parsed.ts);
571
+ if (note === null)
572
+ continue;
573
+ items.push({
574
+ trashId,
575
+ id: parsed.id,
576
+ scope: target.scope,
577
+ title: note.title,
578
+ summary: note.summary,
579
+ deletedAt: parsed.ts,
580
+ });
581
+ }
582
+ return items.sort((a, b) => b.deletedAt - a.deletedAt);
583
+ }
584
+ /** Delete one trashed note for good. */
585
+ export function purgeTrash(target, trashId) {
586
+ const parsed = parseTrashId(trashId);
587
+ const dir = trashDir(target);
588
+ if (parsed === null || dir === null)
589
+ return fail('invalid_id');
590
+ const file = join(dir, `${trashId}.md`);
591
+ if (!existsSync(file))
592
+ return fail('not_found');
593
+ try {
594
+ unlinkSync(file);
595
+ }
596
+ catch {
597
+ return fail('write_failed');
598
+ }
599
+ return { ok: true, value: { ok: true } };
600
+ }
601
+ /**
602
+ * Delete trash and old backups older than the retention window. Best effort, bounded, and
603
+ * only ever inside `.trash/` - live notes are never touched (I-1). Called once at service
604
+ * start-up, off the hot path.
605
+ */
606
+ export function purgeExpiredTrash(now = Date.now()) {
607
+ const root = join(getMemoryDir(), '.trash');
608
+ const cutoff = now - MEMORY_LIMITS.trashDays * 24 * 60 * 60 * 1000;
609
+ let removed = 0;
610
+ let visited = 0;
611
+ const walk = (dir, depth) => {
612
+ if (depth > 5)
613
+ return;
614
+ for (const entry of readEntries(dir)) {
615
+ if (visited++ > 5000)
616
+ return;
617
+ const full = join(dir, entry.name);
618
+ if (entry.isDirectory()) {
619
+ walk(full, depth + 1);
620
+ continue;
621
+ }
622
+ try {
623
+ if (lstatSync(full).mtimeMs < cutoff) {
624
+ unlinkSync(full);
625
+ removed += 1;
626
+ }
627
+ }
628
+ catch {
629
+ // A file that vanished or is locked is not worth stopping for.
630
+ }
631
+ }
632
+ };
633
+ walk(root, 0);
634
+ return removed;
635
+ }
636
+ /**
637
+ * Move a note to the other scope: create the copy first, trash the original second. If the
638
+ * second step fails both exist (and the caller is told) - duplicate, never lost.
639
+ */
640
+ export function moveNote(from, id, to, expectedRev, opts) {
641
+ const current = readNote(from, id);
642
+ if (!current.ok)
643
+ return fail(current.code);
644
+ if (current.value.rev !== expectedRev)
645
+ return fail('conflict', { current: current.value });
646
+ const note = current.value;
647
+ const created = createNote(to, {
648
+ title: note.title,
649
+ summary: note.summaryDerived ? '' : note.summary,
650
+ body: note.body,
651
+ tags: note.tags,
652
+ load: note.load,
653
+ enabled: note.enabled,
654
+ scope: to.scope,
655
+ }, { ...opts, confirmSecret: true });
656
+ if (!created.ok)
657
+ return created;
658
+ const trashed = trashNote(from, id, expectedRev, opts.now);
659
+ if (!trashed.ok)
660
+ return fail('write_failed', { current: created.value });
661
+ return created;
662
+ }
663
+ /** Projects that have a directory under `memory/projects/`. */
664
+ export function listProjectScopes() {
665
+ const root = join(getMemoryDir(), 'projects');
666
+ const entries = [];
667
+ for (const entry of readEntries(root)) {
668
+ if (!entry.isDirectory() || !isValidProjectKey(entry.name))
669
+ continue;
670
+ const target = { scope: 'project', projectKey: entry.name };
671
+ const count = scanScope(target).notes.length;
672
+ let label = entry.name;
673
+ let projectRoot = '';
674
+ const meta = projectMetaFile(entry.name);
675
+ if (meta !== null && existsSync(meta)) {
676
+ try {
677
+ const parsed = JSON.parse(readFileSync(meta, 'utf-8'));
678
+ if (typeof parsed.label === 'string')
679
+ label = parsed.label.slice(0, 80);
680
+ if (typeof parsed.root === 'string')
681
+ projectRoot = parsed.root.slice(0, 400);
682
+ }
683
+ catch {
684
+ // A damaged sidecar only costs the friendly name.
685
+ }
686
+ }
687
+ entries.push({ key: entry.name, label, root: projectRoot, count });
688
+ }
689
+ return entries.sort((a, b) => a.label.localeCompare(b.label));
690
+ }
691
+ /** Convenience used by tests and the service: the current rev of a file's bytes. */
692
+ export function revOfBytes(bytes) {
693
+ return computeRev(bytes);
694
+ }