@xiangyixie/dsh-superagent 0.9.3 → 0.10.0

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/lib/lock.js ADDED
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Best-effort cross-process lock for the small shared files that have no run id
3
+ * of their own (memory lines, notification counters).
4
+ *
5
+ * The lock is advisory: every writer in this package takes it, but a process
6
+ * that ignores it can still append. That is acceptable because the protected
7
+ * operations either append one short line (atomic enough on a local filesystem)
8
+ * or replace a whole file from a temp file. The lock exists to keep compaction
9
+ * and the notification counter from racing, not to protect a critical section
10
+ * that a hostile process honours.
11
+ *
12
+ * A lock whose holder is provably dead on this machine, or whose file is older
13
+ * than `staleMs`, is removed once. Operations under the lock are expected to be
14
+ * short; `staleMs` exists for a process killed mid-write, not for long work.
15
+ *
16
+ * @module dsh-superagent/lock
17
+ */
18
+ import fsp from 'node:fs/promises'
19
+ import os from 'node:os'
20
+
21
+ export const DEFAULT_STALE_MS = 30 * 1000
22
+
23
+ /**
24
+ * @param {unknown} pid - pid recorded by the lock holder.
25
+ * @returns {boolean | null} true when alive, false when gone, null when unknown.
26
+ */
27
+ export function pidAlive(pid) {
28
+ const number = Number(pid)
29
+ if (!Number.isInteger(number) || number <= 0) return null
30
+ try {
31
+ process.kill(number, 0)
32
+ return true
33
+ } catch (error) {
34
+ // EPERM means the process exists but belongs to another user.
35
+ return error?.code === 'EPERM'
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Try to create `file` exclusively.
41
+ *
42
+ * @param {string} file - absolute path of the lock file.
43
+ * @param {object} [options] - lock options.
44
+ * @param {number} [options.staleMs] - age after which the lock is considered abandoned.
45
+ * @param {() => number} [options.now] - clock, injectable for tests.
46
+ * @param {number} [options.retries] - extra attempts after a held lock is seen.
47
+ * @param {number} [options.retryDelayMs] - wait between attempts.
48
+ * @param {(ms: number) => Promise<void>} [options.sleep] - wait function, injectable for tests.
49
+ * @returns {Promise<(() => Promise<void>) | null>} release function, or null when the lock is held.
50
+ */
51
+ export async function acquireFileLock(
52
+ file,
53
+ {
54
+ staleMs = DEFAULT_STALE_MS,
55
+ now = () => Date.now(),
56
+ retries = 0,
57
+ retryDelayMs = 50,
58
+ sleep = ms => new Promise(resolve => setTimeout(resolve, ms)),
59
+ } = {},
60
+ ) {
61
+ for (let round = 0; round <= retries; round++) {
62
+ if (round > 0) await sleep(retryDelayMs)
63
+ let contended = false
64
+ const payload = {
65
+ pid: process.pid,
66
+ hostname: os.hostname(),
67
+ at: new Date(now()).toISOString(),
68
+ }
69
+ for (let attempt = 0; attempt < 2; attempt++) {
70
+ try {
71
+ await fsp.writeFile(file, `${JSON.stringify(payload)}\n`, { encoding: 'utf8', flag: 'wx' })
72
+ return async () => {
73
+ try {
74
+ await fsp.unlink(file)
75
+ } catch {
76
+ // Already gone; releasing twice is not an error.
77
+ }
78
+ }
79
+ } catch (error) {
80
+ if (error?.code !== 'EEXIST') return null
81
+ let existing = null
82
+ try {
83
+ existing = JSON.parse(await fsp.readFile(file, 'utf8'))
84
+ } catch {
85
+ // Unreadable lock content is treated as stale below.
86
+ }
87
+ const age = now() - Date.parse(existing?.at ?? '')
88
+ const deadHere = existing?.hostname === os.hostname() && pidAlive(existing.pid) === false
89
+ const expired = !Number.isFinite(age) || age > staleMs
90
+ // A live holder on this machine wins regardless of age: an operation may
91
+ // legitimately take longer than staleMs on a slow disk.
92
+ const aliveHere = existing?.hostname === os.hostname() && pidAlive(existing.pid) === true
93
+ if (!deadHere && (aliveHere || !expired)) {
94
+ contended = true
95
+ break
96
+ }
97
+ try {
98
+ await fsp.unlink(file)
99
+ } catch {
100
+ // Someone else removed it; the next attempt can try to claim it.
101
+ }
102
+ }
103
+ }
104
+ if (!contended) return null
105
+ }
106
+ return null
107
+ }
package/lib/memory.js ADDED
@@ -0,0 +1,503 @@
1
+ /**
2
+ * Cross-run memory for dsh-superagent.
3
+ *
4
+ * A run is stateless by design: planner and workers start empty, and a finished
5
+ * run leaves only its state file behind. That is good for isolation and bad for
6
+ * continuity — the next run cannot know which approach was already rejected or
7
+ * which step left a trap. This module keeps a small, curated notebook between
8
+ * runs without turning the state directory into a growing pile of logs:
9
+ *
10
+ * - Exact activity history is *derived* from the run store at planning time
11
+ * (which runs existed, how they ended). Nothing is copied into memory for it.
12
+ * - Durable knowledge (decisions, pitfalls, next steps) is written only when a
13
+ * run's aggregator emits a fenced `memory` block. One short entry per topic.
14
+ * - Reads are bounded: at most `maxEntries` notes, each shortened, inside a
15
+ * fixed character budget. The notebook is a digest, never the full file.
16
+ * - A note is refuted, not deleted silently: a newer entry with the same `key`
17
+ * supersedes it, a `retracted` entry drops it, and the `superagent_memory`
18
+ * tool can list, set, or forget a key by hand.
19
+ * - Entries older than `maxAgeDays` are ignored and then compacted away, so a
20
+ * stale conclusion cannot become a permanent bias.
21
+ *
22
+ * Storage is `<stateDir>/memory/<scope>.jsonl`, one JSON object per line. The
23
+ * directory is created with a `.gitignore` containing `*`, so even a state
24
+ * directory that points inside a repository cannot be committed by accident.
25
+ * The package `files` whitelist never ships this directory.
26
+ *
27
+ * Writes append one short line with a single `write` call (atomic for a small
28
+ * buffer on a local filesystem) while holding a lock file, so a concurrent
29
+ * append and a compaction cannot drop each other's lines. Compaction replaces
30
+ * the file from a temp file under the same lock. Two runs finishing at the same
31
+ * time therefore serialise instead of overwriting; the per-key resolution is by
32
+ * timestamp, so order alone never changes a conclusion.
33
+ *
34
+ * @module dsh-superagent/memory
35
+ */
36
+ import { randomBytes } from 'node:crypto'
37
+ import fsp from 'node:fs/promises'
38
+ import path from 'node:path'
39
+ import { acquireFileLock } from './lock.js'
40
+
41
+ /** Kinds a note may declare. Anything else is stored as `note`. */
42
+ export const MEMORY_KINDS = new Set(['dispatch', 'decision', 'pitfall', 'next', 'note'])
43
+
44
+ /** Longest note kept; longer text is cut, not rejected. */
45
+ export const MAX_ENTRY_CHARS = 400
46
+
47
+ /** Longest key; keys are lowercase slugs so a later note can match an older one. */
48
+ export const MAX_KEY_CHARS = 48
49
+
50
+ /** File-level limits; crossing either one, or `maxEntries`, triggers compaction. */
51
+ const MAX_FILE_BYTES = 128 * 1024
52
+ const MAX_FILE_LINES = 400
53
+
54
+ /** How long a writer waits for another process's lock before failing open. */
55
+ const LOCK_RETRIES = 10
56
+ const LOCK_RETRY_DELAY_MS = 50
57
+
58
+ const DEFAULT_MAX_AGE_DAYS = 30
59
+ const DEFAULT_MAX_ENTRIES = 60
60
+ const DEFAULT_DIGEST_ENTRIES = 12
61
+ const DEFAULT_DIGEST_CHARS = 1600
62
+
63
+ const SCOPE_PATTERN = /^[a-z0-9][a-z0-9_-]{0,31}$/
64
+ const MEMORY_FENCE = /```memory[^\n]*\n([\s\S]*?)```/i
65
+
66
+ /**
67
+ * Coerce a configured scope into a safe file name. Anything unrecognised falls
68
+ * back to `default` instead of producing a path from user input.
69
+ * @param {unknown} value - configured scope.
70
+ * @returns {string} a scope that matches `SCOPE_PATTERN`.
71
+ */
72
+ export function normalizeScope(value) {
73
+ const text = typeof value === 'string' ? value.trim().toLowerCase() : ''
74
+ return SCOPE_PATTERN.test(text) ? text : 'default'
75
+ }
76
+
77
+ /**
78
+ * Remove the shapes of secret that a model is most likely to paste into a note:
79
+ * API keys, bearer headers, known token prefixes, long hex/base64 blobs, email
80
+ * addresses, and absolute home paths. Redaction happens before storage, so a
81
+ * file that is copied or backed up later cannot leak the original.
82
+ *
83
+ * @param {unknown} value - text to clean.
84
+ * @returns {string} text with secrets replaced by markers.
85
+ */
86
+ export function redact(value) {
87
+ if (typeof value !== 'string') return ''
88
+ return value
89
+ .replace(/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{8,}/g, '[redacted-key]')
90
+ .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]{8,}/gi, 'Bearer [redacted]')
91
+ .replace(/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{16,}\b/g, '[redacted-token]')
92
+ .replace(/\bAKIA[0-9A-Z]{16}\b/g, '[redacted-key]')
93
+ .replace(/\b[A-Za-z0-9+/]{40,}={0,2}\b/g, '[redacted-blob]')
94
+ .replace(/\b[A-Fa-f0-9]{32,}\b/g, '[redacted-hex]')
95
+ .replace(/\b[\w.+-]+@[\w-]+\.[\w.-]+\b/g, '[redacted-email]')
96
+ .replace(/\b[A-Za-z]:\\Users\\[^\\\s]+/gi, '%USERPROFILE%')
97
+ .replace(/\/(?:home|Users)\/[^/\s]+/g, '~')
98
+ }
99
+
100
+ /**
101
+ * Turn arbitrary text into one bounded line: redacted, no newlines, trimmed.
102
+ * @param {unknown} value - source text.
103
+ * @param {number} [limit] - maximum characters.
104
+ * @returns {string} a single line.
105
+ */
106
+ export function cleanText(value, limit = MAX_ENTRY_CHARS) {
107
+ const text = redact(String(value ?? ''))
108
+ .replace(/\s+/g, ' ')
109
+ .trim()
110
+ if (!text) return ''
111
+ // Slice by code point so a cut never leaves a lone surrogate behind.
112
+ return [...text].slice(0, limit).join('')
113
+ }
114
+
115
+ /**
116
+ * @param {unknown} value - proposed key.
117
+ * @returns {string} lowercase slug, possibly empty.
118
+ */
119
+ export function slugKey(value) {
120
+ return redact(String(value ?? ''))
121
+ .toLowerCase()
122
+ .replace(/[^a-z0-9._-]+/g, '-')
123
+ .replace(/^[-.]+|[-.]+$/g, '')
124
+ .slice(0, MAX_KEY_CHARS)
125
+ }
126
+
127
+ /**
128
+ * True when `child` is `parent` or inside it. Used to refuse a memory directory
129
+ * that would end up inside the installed package.
130
+ * @param {string} child - absolute path to test.
131
+ * @param {string} parent - absolute path to compare against.
132
+ */
133
+ export function isInside(child, parent) {
134
+ const from = path.resolve(parent)
135
+ const to = path.resolve(child)
136
+ const relative = path.relative(from, to)
137
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
138
+ }
139
+
140
+ function normalizeEntry(item) {
141
+ if (!item || typeof item !== 'object') return null
142
+ const status = item.status === 'retracted' ? 'retracted' : 'active'
143
+ const kind = MEMORY_KINDS.has(item.kind) ? item.kind : 'note'
144
+ const text = status === 'retracted' ? '' : cleanText(item.text)
145
+ const key = slugKey(item.key) || slugKey(text.slice(0, 48)) || `${kind}-${randomBytes(3).toString('hex')}`
146
+ if (status === 'active' && !text) return null
147
+ return { key, kind, status, text }
148
+ }
149
+
150
+ function tsOf(record) {
151
+ const value = Date.parse(record?.ts ?? '')
152
+ return Number.isFinite(value) ? value : 0
153
+ }
154
+
155
+ /**
156
+ * Resolve raw lines into the notes a reader should see.
157
+ *
158
+ * Records are applied oldest-first, so a newer entry wins on the same key and a
159
+ * `retracted` entry removes it. Timestamps are used rather than file order
160
+ * because a shared state directory can be written by two clocks. TTL is applied
161
+ * after resolution: because a tombstone is newer than its target, an expired
162
+ * tombstone cannot resurrect an older active entry.
163
+ *
164
+ * @param {object[]} records - parsed lines.
165
+ * @param {{ now?: number, maxAgeDays?: number }} [options] - clock and TTL.
166
+ * @returns {object[]} active entries, newest first.
167
+ */
168
+ export function effectiveEntries(records, { now = Date.now(), maxAgeDays = DEFAULT_MAX_AGE_DAYS } = {}) {
169
+ const active = new Map()
170
+ const ordered = records
171
+ .map((record, index) => ({ record, index }))
172
+ .filter(({ record }) => record && typeof record === 'object' && typeof record.key === 'string')
173
+ .sort((a, b) => (tsOf(a.record) - tsOf(b.record)) || (a.index - b.index))
174
+ for (const { record, index } of ordered) {
175
+ if (record.status === 'retracted') active.delete(record.key)
176
+ else active.set(record.key, { record, index })
177
+ }
178
+ const cutoff = maxAgeDays > 0 ? now - maxAgeDays * 86400000 : -Infinity
179
+ return [...active.values()]
180
+ .filter(({ record }) => tsOf(record) >= cutoff)
181
+ // Newest first. Notes written in the same millisecond keep reverse line
182
+ // order, so a later line is treated as newer rather than older.
183
+ .sort((a, b) => (tsOf(b.record) - tsOf(a.record)) || (b.index - a.index))
184
+ .map(({ record }) => record)
185
+ }
186
+
187
+ function ageText(ts, now) {
188
+ const days = Math.max(0, Math.floor((now - ts) / 86400000))
189
+ if (days === 0) return 'today'
190
+ return `${days}d`
191
+ }
192
+
193
+ function capLine(text, limit) {
194
+ const points = [...text]
195
+ return points.length <= limit ? text : `${points.slice(0, Math.max(0, limit - 1)).join('')}…`
196
+ }
197
+
198
+ /**
199
+ * Pull the fenced `memory` block out of an aggregator report.
200
+ *
201
+ * The block is removed from the report whether or not it parses: the user asked
202
+ * for a report, not for the plugin's notebook syntax. A malformed block is
203
+ * reported through `error` so the run record shows why no note was written.
204
+ *
205
+ * @param {unknown} text - final report.
206
+ * @returns {{ report: string, entries: object[], found: boolean, error?: string }}
207
+ */
208
+ export function extractMemoryBlock(text) {
209
+ if (typeof text !== 'string' || !text) return { report: typeof text === 'string' ? text : '', entries: [], found: false }
210
+ const match = MEMORY_FENCE.exec(text)
211
+ if (!match) return { report: text, entries: [], found: false }
212
+ const report = `${text.slice(0, match.index)}${text.slice(match.index + match[0].length)}`
213
+ .replace(/\n{3,}/g, '\n\n')
214
+ .trim()
215
+ let parsed
216
+ try {
217
+ parsed = JSON.parse(match[1].trim())
218
+ } catch {
219
+ return { report, entries: [], found: true, error: 'the memory block was not valid JSON' }
220
+ }
221
+ const raw = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.entries) ? parsed.entries : []
222
+ const entries = []
223
+ for (const item of raw) {
224
+ const entry = normalizeEntry(item)
225
+ if (entry) entries.push(entry)
226
+ }
227
+ if (raw.length > 0 && entries.length === 0) {
228
+ return { report, entries, found: true, error: 'the memory block had no usable entry' }
229
+ }
230
+ return { report, entries, found: true }
231
+ }
232
+
233
+ /**
234
+ * Build the memory notebook bound to one state root.
235
+ *
236
+ * @param {string} root - absolute state directory (`<root>/memory` is used).
237
+ * @param {object} [options] - collaborators.
238
+ * @param {(message: string) => void} [options.warn] - diagnostic sink.
239
+ * @param {() => number} [options.now] - clock, injectable for tests.
240
+ */
241
+ export function createMemory(root, { warn = () => {}, now = () => Date.now() } = {}) {
242
+ const dir = path.join(root, 'memory')
243
+ const fileOf = scope => path.join(dir, `${normalizeScope(scope)}.jsonl`)
244
+ const lockOf = scope => path.join(dir, `${normalizeScope(scope)}.lock`)
245
+ /** Per-scope write chain, so two settles in this process cannot interleave. */
246
+ const chains = new Map()
247
+
248
+ /**
249
+ * Create the directory and make it git-invisible even inside a repository.
250
+ * A `*` in a nested .gitignore ignores every file here, including the
251
+ * notebook, without editing the repository's own .gitignore.
252
+ */
253
+ async function initDir() {
254
+ await fsp.mkdir(dir, { recursive: true })
255
+ const ignore = path.join(dir, '.gitignore')
256
+ try {
257
+ await fsp.access(ignore)
258
+ } catch {
259
+ await fsp.writeFile(ignore, '*\n', 'utf8')
260
+ }
261
+ }
262
+
263
+ function serialize(scope, task) {
264
+ const previous = chains.get(scope) ?? Promise.resolve()
265
+ const next = previous.catch(() => {}).then(task)
266
+ chains.set(scope, next.catch(() => {}))
267
+ return next
268
+ }
269
+
270
+ async function readRecords(file) {
271
+ let text
272
+ try {
273
+ text = await fsp.readFile(file, 'utf8')
274
+ } catch (error) {
275
+ if (error?.code === 'ENOENT') return { records: [], bad: 0, bytes: 0 }
276
+ throw error
277
+ }
278
+ const records = []
279
+ let bad = 0
280
+ for (const line of text.split('\n')) {
281
+ const trimmed = line.trim()
282
+ if (!trimmed) continue
283
+ try {
284
+ const parsed = JSON.parse(trimmed)
285
+ if (parsed && typeof parsed === 'object') records.push(parsed)
286
+ else bad++
287
+ } catch {
288
+ // A process killed mid-append leaves one truncated line; skipping it is
289
+ // the whole reason for the JSONL format.
290
+ bad++
291
+ }
292
+ }
293
+ return { records, bad, bytes: Buffer.byteLength(text, 'utf8') }
294
+ }
295
+
296
+ /**
297
+ * Rewrite the file with the newest notes. The caller already holds the scope
298
+ * lock; acquiring it here as well would deadlock against that same writer.
299
+ */
300
+ async function compactLocked(scope, { maxEntries, maxAgeDays }) {
301
+ try {
302
+ const file = fileOf(scope)
303
+ const { records } = await readRecords(file)
304
+ // Keep the newest notes but write them oldest-first, so the file stays in
305
+ // append order and a same-millisecond tie is still resolved by line order.
306
+ const keep = effectiveEntries(records, { now: now(), maxAgeDays })
307
+ .slice(0, maxEntries)
308
+ .reverse()
309
+ const body = keep.map(record => `${JSON.stringify(record)}\n`).join('')
310
+ const tmp = path.join(dir, `.${normalizeScope(scope)}.${process.pid}.${Date.now()}.tmp`)
311
+ await fsp.writeFile(tmp, body, 'utf8')
312
+ await fsp.rename(tmp, file)
313
+ return true
314
+ } catch (error) {
315
+ warn(`cannot compact memory scope "${scope}": ${error?.message ?? error}`)
316
+ return false
317
+ }
318
+ }
319
+
320
+ async function append(scope, records) {
321
+ if (records.length === 0) return 0
322
+ const file = fileOf(scope)
323
+ const body = records.map(record => `${JSON.stringify(record)}\n`).join('')
324
+ // One write for the whole batch: a concurrent append either lands before or
325
+ // after this buffer, never inside it on a local filesystem.
326
+ const handle = await fsp.open(file, 'a')
327
+ try {
328
+ await handle.write(body)
329
+ } finally {
330
+ await handle.close()
331
+ }
332
+ return records.length
333
+ }
334
+
335
+ return {
336
+ root,
337
+ dir,
338
+ fileOf,
339
+
340
+ /** Create the directory and make it git-invisible even inside a repository. */
341
+ async init() {
342
+ await initDir()
343
+ },
344
+
345
+ /**
346
+ * Read the notebook's current notes.
347
+ * @param {{ scope?: string, maxAgeDays?: number }} [options] - read options.
348
+ */
349
+ async read({ scope = 'default', maxAgeDays = DEFAULT_MAX_AGE_DAYS } = {}) {
350
+ const file = fileOf(scope)
351
+ const { records, bad, bytes } = await readRecords(file)
352
+ return {
353
+ entries: effectiveEntries(records, { now: now(), maxAgeDays }),
354
+ bad,
355
+ bytes,
356
+ path: file,
357
+ }
358
+ },
359
+
360
+ /**
361
+ * Append the notes a finished run produced. Idempotent per run id: a resume
362
+ * settles the same run again and must not duplicate its notes.
363
+ *
364
+ * @param {{ scope?: string, runId: string, entries: object[], maxEntries?: number, maxAgeDays?: number }} options - note batch.
365
+ * @returns {Promise<{ written: number, skipped: number, reason: string | null }>}
366
+ */
367
+ async write({ scope = 'default', runId, entries, maxEntries = DEFAULT_MAX_ENTRIES, maxAgeDays = DEFAULT_MAX_AGE_DAYS } = {}) {
368
+ const normalized = (Array.isArray(entries) ? entries : []).map(normalizeEntry).filter(Boolean)
369
+ if (normalized.length === 0) return { written: 0, skipped: 0, reason: 'no usable entry' }
370
+ const key = normalizeScope(scope)
371
+ return serialize(key, async () => {
372
+ await initDir()
373
+ // One lock for the whole read/dedupe/append/compaction sequence. Without
374
+ // it a compaction in another process could rename the file between this
375
+ // writer's read and append and silently drop the new line.
376
+ const release = await acquireFileLock(lockOf(key), {
377
+ now,
378
+ retries: LOCK_RETRIES,
379
+ retryDelayMs: LOCK_RETRY_DELAY_MS,
380
+ })
381
+ if (!release) {
382
+ warn(`memory scope "${key}" is locked by another process; appended without compaction`)
383
+ }
384
+ try {
385
+ const file = fileOf(key)
386
+ const { records } = await readRecords(file)
387
+ if (runId && records.some(record => record?.runId === runId)) {
388
+ return { written: 0, skipped: normalized.length, reason: 'this run already wrote its notes' }
389
+ }
390
+ const ts = new Date(now()).toISOString()
391
+ const batch = normalized.map(entry => ({
392
+ v: 1,
393
+ id: randomBytes(4).toString('hex'),
394
+ ts,
395
+ runId: runId ?? null,
396
+ ...entry,
397
+ }))
398
+ const written = await append(key, batch)
399
+ let bytes = 0
400
+ try {
401
+ bytes = (await fsp.stat(file)).size
402
+ } catch {
403
+ // A missing stat only means compaction cannot be sized this round.
404
+ }
405
+ // `maxEntries` is a trigger, not just the size kept by an existing
406
+ // compaction: lowering it must bound the notebook on the next write.
407
+ const total = records.length + batch.length
408
+ if (release && (bytes > MAX_FILE_BYTES || total > MAX_FILE_LINES || total > maxEntries)) {
409
+ await compactLocked(key, { maxEntries, maxAgeDays })
410
+ }
411
+ return { written, skipped: normalized.length - written, reason: null }
412
+ } finally {
413
+ await release?.()
414
+ }
415
+ })
416
+ },
417
+
418
+ /**
419
+ * Record one note by hand (the `superagent_memory` tool's `set`).
420
+ * @param {{ scope?: string, key: string, kind?: string, text: string, runId?: string }} options - note.
421
+ */
422
+ async set({ scope = 'default', key, kind = 'note', text, runId = null } = {}) {
423
+ const entry = normalizeEntry({ key, kind, text })
424
+ if (!entry) return { written: 0, reason: 'a note needs non-empty text' }
425
+ const result = await this.write({ scope, runId: runId ?? `manual-${randomBytes(3).toString('hex')}`, entries: [entry] })
426
+ return { written: result.written, reason: result.reason }
427
+ },
428
+
429
+ /**
430
+ * Retract a note by key. The tombstone is itself a line, so a later
431
+ * compaction that drops the old note also drops the tombstone.
432
+ * @param {{ scope?: string, key: string }} options - key to forget.
433
+ */
434
+ async forget({ scope = 'default', key } = {}) {
435
+ const slug = slugKey(key)
436
+ if (!slug) return { forgotten: false, reason: 'a key is required' }
437
+ const result = await this.write({
438
+ scope,
439
+ runId: `forget-${randomBytes(3).toString('hex')}`,
440
+ entries: [{ key: slug, kind: 'note', status: 'retracted' }],
441
+ })
442
+ return { forgotten: result.written > 0, reason: result.reason }
443
+ },
444
+
445
+ /**
446
+ * Bounded digest injected into prompts. Never the whole file.
447
+ * @param {{ scope?: string, maxEntries?: number, maxChars?: number, maxAgeDays?: number }} [options] - digest limits.
448
+ * @returns {Promise<string>} note lines, or an empty string.
449
+ */
450
+ async digest({
451
+ scope = 'default',
452
+ maxEntries = DEFAULT_DIGEST_ENTRIES,
453
+ maxChars = DEFAULT_DIGEST_CHARS,
454
+ maxAgeDays = DEFAULT_MAX_AGE_DAYS,
455
+ } = {}) {
456
+ const { entries } = await this.read({ scope, maxAgeDays })
457
+ if (entries.length === 0) return ''
458
+ const picked = entries.slice(0, maxEntries)
459
+ const perEntry = Math.max(100, Math.floor(maxChars / Math.max(1, picked.length)) - 28)
460
+ const lines = []
461
+ let used = 0
462
+ let omitted = 0
463
+ for (const entry of picked) {
464
+ const line = `- [${ageText(tsOf(entry), now())}] ${entry.kind} ${entry.key}: ${capLine(entry.text, perEntry)}`
465
+ if (used + line.length + 1 > maxChars) {
466
+ omitted++
467
+ continue
468
+ }
469
+ lines.push(line)
470
+ used += line.length + 1
471
+ }
472
+ if (lines.length === 0) return ''
473
+ if (omitted > 0) lines.push(`- (+${omitted} more; call superagent_memory action="list" to read them)`)
474
+ return lines.join('\n')
475
+ },
476
+
477
+ /**
478
+ * Rows for the `superagent_memory` tool.
479
+ * @param {{ scope?: string, limit?: number, maxAgeDays?: number }} [options] - list options.
480
+ */
481
+ async list({ scope = 'default', limit = 20, maxAgeDays = DEFAULT_MAX_AGE_DAYS } = {}) {
482
+ const { entries, bad, bytes, path: file } = await this.read({ scope, maxAgeDays })
483
+ return { entries: entries.slice(0, limit), total: entries.length, bad, bytes, path: file }
484
+ },
485
+
486
+ /**
487
+ * Size and count for `superagent_list`.
488
+ * @param {{ scope?: string, maxAgeDays?: number }} [options] - stats options.
489
+ */
490
+ async stats({ scope = 'default', maxAgeDays = DEFAULT_MAX_AGE_DAYS } = {}) {
491
+ const { entries, bytes, path: file } = await this.read({ scope, maxAgeDays })
492
+ return { entries: entries.length, bytes, path: file }
493
+ },
494
+
495
+ /** Defaults exposed so the orchestrator and tests agree on one set of limits. */
496
+ defaults: {
497
+ maxEntries: DEFAULT_MAX_ENTRIES,
498
+ maxAgeDays: DEFAULT_MAX_AGE_DAYS,
499
+ digestEntries: DEFAULT_DIGEST_ENTRIES,
500
+ digestChars: DEFAULT_DIGEST_CHARS,
501
+ },
502
+ }
503
+ }