dsh-engramory 0.2.6 → 0.2.7

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/index.js CHANGED
@@ -1,530 +1,655 @@
1
- /**
2
- * dsh-engramory — the Engramory memory discipline as a DeepSeek Harness plugin.
3
- *
4
- * Two things the always-on AGENTS.md block cannot do on its own:
5
- *
6
- * 1. A DETERMINISTIC index cap. dsh's `ctx.tools.guard()` is a synchronous,
7
- * monotonic refusal — once a guard returns a reason, no later waterfall
8
- * listener can turn it back into an allow. That makes it a stronger seam than
9
- * most hosts expose, and it is why the 200-line / 25 KB limit can be enforced
10
- * here rather than merely asked for. Without a shim like this one, everywhere
11
- * except Claude Code the cap degrades to "rules plus a checker the agent has to
12
- * remember to run".
13
- * 2. Skill delivery that does not depend on install paths. Registering at runtime
14
- * sidesteps the five-root scan entirely, so the protocol is present because the
15
- * plugin is loaded, not because a directory happened to be right.
16
- *
17
- * The decision table mirrors hooks/engramory_index_guard.py: deny only a write that
18
- * ENDS over a cap AND grew past the current file — a shrinking rewrite always passes,
19
- * so an over-cap index can be compacted incrementally (210 → 205 → 198). Only known
20
- * mutating tools are gated; `read` and unknown tools are never refused (the first cut
21
- * gated everything that named the index, which blocked recall of an over-cap index at
22
- * exactly the moment compaction was needed).
23
- *
24
- * Zero dependencies, no build step: plain ESM, node: builtins only.
25
- */
26
- import { readFileSync, realpathSync } from 'node:fs'
27
- import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path'
28
-
29
- export const name = 'engramory'
30
-
31
- // `tools` carries the cap and is the plugin's only declared dependency. Cordis reads
32
- // `inject` as an array of service names (or an object KEYED by them) and treats every
33
- // entry as a hard wait — the `{ required, optional }` shape is older-Cordis syntax that
34
- // the build dsh vendors resolves as services literally named "required"/"optional",
35
- // which never appear, so the plugin sat pending forever (issue #8). `skills` is
36
- // deliberately NOT declared: the cap must mount even on a profile with no skill
37
- // registry, so apply() probes it at runtime instead.
38
- export const inject = ['tools']
39
-
40
- /** Mirrors hooks/engramory_index_guard.py — the caps are the protocol's, not this port's. */
41
- const DEFAULT_INDEX_NAME = 'MEMORY.md'
42
- const DEFAULT_MAX_LINES = 200
43
- const DEFAULT_MAX_BYTES = 25600
44
-
45
- /** Tools that replace a file wholesale, so the post-write text is in the arguments. */
46
- const WHOLE_FILE_WRITES = new Set(['write'])
47
-
48
- /**
49
- * Tools that mutate a file in place. Only tools named here (plus
50
- * `str_replace_editor`'s write commands, handled explicitly) count as partial
51
- * writes. Unknown tools pass through: this guard is a discipline rail, not a
52
- * security boundary (SECURITY.md), and a false refusal of `read` costs more than a
53
- * miss — the next whole-file write is measured exactly regardless.
54
- */
55
- const PARTIAL_WRITES = new Set(['edit', 'str_replace', 'insert'])
56
-
57
- export function apply(ctx, config = {}) {
58
- // `indexPath` pins the guard to ONE file. Without it the only signal is the
59
- // basename, so an unrelated MEMORY.md in any other project is gated too — a real
60
- // refusal on a file that is not a memory index at all, with no way to opt out
61
- // (renaming `indexName` would just unguard the real index). The Claude Code hook
62
- // has had ENGRAMORY_INDEX_PATH for exactly this; this is its counterpart.
63
- //
64
- // The key and the basename are computed ONCE here: guards run on every tool call
65
- // and must stay cheap, so the per-call path stays a string compare and the single
66
- // realpath() only happens when the basename already matched.
67
- const indexPath = typeof config.indexPath === 'string' && config.indexPath.trim()
68
- ? config.indexPath.trim()
69
- : undefined
70
- const settings = {
71
- indexName: indexNameOf(config.indexName),
72
- indexPath,
73
- indexKey: indexPath === undefined ? undefined : pathKey(indexPath),
74
- // When pinned, the name to match is the pinned file's own basename.
75
- matchName: (indexPath === undefined
76
- ? indexNameOf(config.indexName)
77
- : basename(indexPath)).toLowerCase(),
78
- maxLines: positive(config.maxLines, DEFAULT_MAX_LINES),
79
- maxBytes: positive(config.maxBytes, DEFAULT_MAX_BYTES),
80
- }
81
-
82
- // dsh 0.2 resolves a relative file path against the calling SESSION's working
83
- // directory, which its `working_directory` tool moves away from the process's own
84
- // cwd. Measured against process.cwd(), a bare `MEMORY.md` after a cd is the wrong
85
- // file or none: an edit of the real index passed unmeasured, and a shrinking rewrite
86
- // of an over-cap index was judged against an empty file and refused. The service is
87
- // optional (0.1.x has none) and may mount late, so — like `skills` below — it is
88
- // picked up reactively and never makes the cap wait.
89
- let workingDirectory
90
- ctx.inject(['workingDirectory'], (inner) => {
91
- inner.effect(() => {
92
- const service = inner.workingDirectory
93
- workingDirectory = service
94
- return () => {
95
- if (workingDirectory === service) workingDirectory = undefined
96
- }
97
- })
98
- })
99
- const sessionCwd = (exec) => {
100
- try {
101
- const dir = workingDirectory?.get(exec.agent.session)
102
- return typeof dir === 'string' && isAbsolute(dir) ? dir : undefined
103
- } catch {
104
- return undefined // no agent, no session, or a service shape this port predates
105
- }
106
- }
107
-
108
- ctx.tools.guard((exec) => refuseOversizedIndex(exec, settings, sessionCwd))
109
-
110
- // The skill registry is optional AND may activate after this plugin — fiber order
111
- // between unrelated providers is not guaranteed, so a one-shot probe here would
112
- // silently skip registration on such boots. ctx.inject() is Cordis' reactive form:
113
- // the callback runs once `skills` is available (however late), re-runs if the
114
- // registry reloads, and never makes the cap wait. A bare `ctx.skills` read at THIS
115
- // level would throw (undeclared service — issue #8's second crash); inside the
116
- // callback the service is declared, so the read is legal.
117
- if (config.registerSkill !== false) {
118
- ctx.inject(['skills'], (inner) => {
119
- const skill = config.skill ?? builtinSkillBody()
120
- // effect() ties the registration to the child fiber: it is disposed when the
121
- // registry unloads, so a reload cannot accumulate duplicate registrations.
122
- inner.effect(() => inner.skills.register({
123
- name: 'engramory',
124
- description:
125
- 'Curated file-based long-term memory: recall through MEMORY.md at the start of ' +
126
- 'a task, save durable user/feedback/project/reference facts, run a curation ' +
127
- 'checkpoint when a task finishes, and sync before compacting or opening a ' +
128
- 'fresh thread. A turn that starts no work — a greeting, an acknowledgement — ' +
129
- 'is not a task and needs none of this, but never judge that by length: a ' +
130
- 'one-word reply continuing work underway inherits that task.',
131
- whenToUse:
132
- 'Starting or resuming work, learning something durable worth a future session, ' +
133
- 'finishing a task — including one that leaves nothing worth saving, since the ' +
134
- 'checkpoint is still a decision to make — or approaching a ' +
135
- 'compact/clear/new-thread boundary. Not for a bare greeting, ' +
136
- 'acknowledgement, or reaction, which starts no task — but a terse reply ' +
137
- 'that continues work underway does, and material already in hand (a ' +
138
- 'pasted diff to review) does not make work a non-task. Unsure? Treat it ' +
139
- 'as a task.',
140
- source: 'runtime',
141
- content: skill,
142
- }))
143
- })
144
- }
145
- }
146
-
147
- /**
148
- * The cap itself. Returning a string denies the call; `undefined` lets it through.
149
- *
150
- * Guards are synchronous by contract, so this stays cheap: one basename comparison
151
- * rejects the overwhelming majority of calls before anything is measured, and the
152
- * only I/O is a single read of the index on a gated write.
153
- */
154
- function refuseOversizedIndex(exec, settings, sessionCwd) {
155
- const args = exec?.arguments
156
- if (!args || typeof args !== 'object') return undefined
157
-
158
- // dsh's file tools carry the target as `file_path`; `str_replace_editor` calls it
159
- // `path`. Compare basenames case-INsensitively: on the case-insensitive
160
- // filesystems most stores live on (Windows/macOS), `memory.md` IS the guarded
161
- // index, and an exact compare let that spelling through. (Same trade-off as the
162
- // Python guard: on a case-sensitive FS this can gate an unrelated lowercase twin —
163
- // rename it, or point `indexName` elsewhere.)
164
- const filePath = typeof args.file_path === 'string' ? args.file_path
165
- : typeof args.path === 'string' ? args.path
166
- : undefined
167
- if (filePath === undefined) return undefined
168
- if (basename(filePath).toLowerCase() !== settings.matchName) return undefined
169
-
170
- const tool = typeof exec.name === 'string' ? exec.name : ''
171
-
172
- // Nothing below can refuse a read, a view, or an unknown tool, so leave before the
173
- // pinned-path check: pathKey() touches the filesystem and a guard runs on EVERY tool
174
- // call. Ordering it here keeps the common case a pair of string compares.
175
- const gated = WHOLE_FILE_WRITES.has(tool)
176
- || PARTIAL_WRITES.has(tool)
177
- || (tool === 'str_replace_editor'
178
- && (args.command === 'create' || args.command === 'str_replace'
179
- || args.command === 'insert'))
180
- if (!gated) return undefined
181
- // Every read and identity check below uses the file the host will actually touch.
182
- let target
183
- try {
184
- target = hostPath(sessionCwd(exec), filePath)
185
- } catch {
186
- return undefined // a relative path and no cwd left to resolve it (deleted under us)
187
- }
188
- // If the guard is pinned to one file, this is where an unrelated same-named file in
189
- // another project drops out.
190
- if (settings.indexKey !== undefined && pathKey(target) !== settings.indexKey) {
191
- return undefined
192
- }
193
-
194
- if (WHOLE_FILE_WRITES.has(tool)) {
195
- if (typeof args.content !== 'string') return undefined
196
- return verdict(args.content, readIfPossible(target), filePath, settings)
197
- }
198
- if (tool === 'str_replace_editor' && args.command === 'create') {
199
- if (typeof args.file_text !== 'string') return undefined
200
- return verdict(args.file_text, readIfPossible(target), filePath, settings)
201
- }
202
-
203
- const partial = PARTIAL_WRITES.has(tool)
204
- || (tool === 'str_replace_editor'
205
- && (args.command === 'str_replace' || args.command === 'insert'))
206
- if (!partial) return undefined // read / view / list / unknown: never refused
207
-
208
- const currentBuf = readIfPossible(target)
209
- if (currentBuf === undefined) return undefined
210
- const current = currentBuf.toString('utf8')
211
- const simulated = simulateEdit(current, args)
212
- if (simulated !== undefined) {
213
- return verdict(simulated, currentBuf, filePath, settings)
214
- }
215
-
216
- // The edit's result genuinely cannot be reconstructed from its arguments. Honest,
217
- // cheap rule: if the index is ALREADY over, refuse to mutate it blind — and name
218
- // the open door, because "compact first" while refusing edits reads as a dead end.
219
- const breach = measure(current, settings)
220
- if (!breach) return undefined
221
- return (
222
- `${displayName(settings)} is already over the Engramory cap (${breach}) and this ` +
223
- `edit's result cannot be measured. Compact it with a whole-file write instead: ` +
224
- `a rewrite that SHRINKS the index always passes, even while still over the cap. ` +
225
- `Pointer-ify over-long lines, merge duplicates, archive cold notes — the index ` +
226
- `is a table of contents, and anything past the cap silently stops being recalled.` +
227
- notMyIndexHint(settings)
228
- )
229
- }
230
-
231
- /**
232
- * Mirrors the Python guard's deny rule: refuse only when a dimension ends OVER its
233
- * cap AND grew past the current file, so a shrinking/keeping write on an over-cap
234
- * index always passes and incremental compaction stays possible. A missing or
235
- * unreadable current file counts as empty — a first write past the cap is refused.
236
- */
237
- function verdict(text, currentBuf, filePath, settings) {
238
- const lines = countLines(text)
239
- const bytes = Buffer.byteLength(text, 'utf8')
240
- // Current byte size comes from the RAW buffer, mirroring how the Python guard
241
- // sizes the on-disk file: decoding first inflated a non-UTF-8 index ~3x (every
242
- // bad byte becomes a 3-byte U+FFFD), which made a genuinely growing write look
243
- // like a shrink and pass. Newlines survive a lossy decode, so the line count may
244
- // use the decoded text.
245
- const curLines = currentBuf === undefined ? 0 : countLines(currentBuf.toString('utf8'))
246
- const curBytes = currentBuf === undefined ? 0 : currentBuf.length
247
- const over = []
248
- if (lines > settings.maxLines && lines > curLines) {
249
- over.push(`${lines} lines > ${settings.maxLines}`)
250
- }
251
- if (bytes > settings.maxBytes && bytes > curBytes) {
252
- over.push(`${bytes} bytes > ${settings.maxBytes}`)
253
- }
254
- if (!over.length) return undefined
255
- return (
256
- `This write would put ${basename(filePath)} over the Engramory index cap ` +
257
- `(${over.join(', ')}). The index is loaded every session and the host only reads ` +
258
- `so far, so anything past the cap silently stops being recalled. Compact before ` +
259
- `writing: move detail into the linked note files, merge duplicates, archive cold ` +
260
- `notes, and keep every line to "one short hook + link". A write that SHRINKS the ` +
261
- `index always passes, so you can compact step by step.` + notMyIndexHint(settings)
262
- )
263
- }
264
-
265
-
266
- /**
267
- * The name to show in a refusal. `indexPath` wins over `indexName` when both are set,
268
- * so quoting the ignored one would send a user looking for the wrong file.
269
- */
270
- function displayName(settings) {
271
- return settings.indexPath === undefined
272
- ? settings.indexName
273
- : basename(settings.indexPath)
274
- }
275
-
276
-
277
- /**
278
- * Without `indexPath` the guard matches on basename alone, so it can land on a file
279
- * that is not a memory index at all. Say so in the refusal: a user who hits this
280
- * needs the way out, not just the cap.
281
- */
282
- function notMyIndexHint(settings) {
283
- if (settings.indexPath !== undefined) return ''
284
- return (
285
- ` (If this file is NOT your memory index, set this plugin's \`indexPath\` config ` +
286
- `to your real index's absolute path so only that file is gated.)`
287
- )
288
- }
289
-
290
- /**
291
- * Reconstruct a partial edit's post-write text when its arguments carry enough to
292
- * do it (`old_str`/`new_str`, or the Claude-style `old_string`/`new_string`).
293
- * Mirrors the Python guard's Edit simulation: replace the unique occurrence, or all
294
- * of them under a replace-all flag; an absent or ambiguous old-string means the
295
- * real tool errors and changes nothing, so the current text is the honest
296
- * prediction. Returns undefined when the shape isn't recognised.
297
- *
298
- * Matching happens on LF-normalised text and the result goes back in the file's own
299
- * line endings, as dsh's local backend does it (`applyLiteralEdit` /
300
- * `restoreLineEndings` in @deepseek-ai/dsh-fs-local). Matching the raw text let a CRLF
301
- * index — common on Windows — read every LF `old_string` as "not found", predict no
302
- * change, and pass an edit dsh then applied.
303
- */
304
- function simulateEdit(current, args) {
305
- const oldRaw = firstString(args.old_str, args.old_string)
306
- if (oldRaw === undefined || oldRaw === '') return undefined
307
- const oldStr = lf(oldRaw)
308
- const newStr = lf(firstString(args.new_str, args.new_string) ?? '')
309
- // dsh decodes with TextDecoder, which drops a leading BOM — from the text it
310
- // matches, from the sample it detects line endings on, and from what it writes back.
311
- const decoded = current.startsWith('') ? current.slice(1) : current
312
- const text = lf(decoded)
313
- const first = text.indexOf(oldStr)
314
- if (first === -1) return current // the real tool errors: nothing changes
315
- let edited
316
- if (args.replace_all === true || args.replaceAll === true) {
317
- edited = text.split(oldStr).join(newStr)
318
- } else {
319
- const second = text.indexOf(oldStr, first + oldStr.length)
320
- if (second !== -1) return current // ambiguous: the real tool errors, nothing changes
321
- edited = text.slice(0, first) + newStr + text.slice(first + oldStr.length)
322
- }
323
- // Normalised once more before expanding, as dsh's restoreLineEndings does: a lone
324
- // `\r` meeting an inserted `\n` at the seam is one CRLF, not `\r\r\n`.
325
- return crlfDominates(decoded) ? lf(edited).split('\n').join('\r\n') : edited
326
- }
327
-
328
- function lf(text) {
329
- return text.replaceAll('\r\n', '\n')
330
- }
331
-
332
- /** dsh's own call (`detectLineEndings`): CRLF wins on a majority in the first 4096 chars. */
333
- function crlfDominates(raw) {
334
- const sample = raw.slice(0, 4096)
335
- const crlf = sample.split('\r\n').length - 1
336
- return crlf > sample.split('\n').length - 1 - crlf
337
- }
338
-
339
- function firstString(...values) {
340
- for (const v of values) {
341
- if (typeof v === 'string') return v
342
- }
343
- return undefined
344
- }
345
-
346
- /** Returns a human-readable breach description, or `null` when the text is within caps. */
347
- function measure(text, { maxLines, maxBytes }) {
348
- const lines = countLines(text)
349
- const bytes = Buffer.byteLength(text, 'utf8')
350
- const over = []
351
- if (lines > maxLines) over.push(`${lines} lines > ${maxLines}`)
352
- if (bytes > maxBytes) over.push(`${bytes} bytes > ${maxBytes}`)
353
- return over.length ? over.join(', ') : null
354
- }
355
-
356
- /** Trailing-newline-insensitive, matching how the Python guard counts. */
357
- function countLines(text) {
358
- if (!text) return 0
359
- return text.split('\n').length - (text.endsWith('\n') ? 1 : 0)
360
- }
361
-
362
- /**
363
- * A missing or unreadable index is not a breach: the guard's job is to stop an
364
- * oversized index, never to block work because a path could not be read. Returns the
365
- * RAW buffer — byte comparisons must use on-disk bytes (see verdict), decode at the
366
- * call sites that need text.
367
- */
368
- function readIfPossible(filePath) {
369
- try {
370
- return readFileSync(filePath)
371
- } catch {
372
- return undefined
373
- }
374
- }
375
-
376
- function positive(value, fallback) {
377
- if (!Number.isFinite(value)) return fallback
378
- const floored = Math.floor(value)
379
- return floored > 0 ? floored : fallback
380
- }
381
-
382
- /**
383
- * The path the host's own file tools would touch for `p`, mirroring dsh's local
384
- * backend (`localDisplayPath` in @deepseek-ai/dsh-fs-local): resolve against `cwd`,
385
- * except that on POSIX a spelling with a `..` segment is kept as written, so a `..`
386
- * after a symlinked segment stays physical — collapsing it could measure a different
387
- * file than the one the write lands on. Without a session directory (`cwd`
388
- * undefined), the process's is used, and only when `p` needs one: process.cwd()
389
- * throws once that directory is deleted, and an absolute path must not care.
390
- */
391
- function hostPath(cwd, p) {
392
- const resolved = () => (cwd === undefined ? resolve(p) : resolve(cwd, p))
393
- if (process.platform === 'win32') return resolved()
394
- const raw = isAbsolute(p) ? p : `${cwd ?? process.cwd()}${sep}${p}`
395
- return /(?:^|[\\/])\.\.(?:[\\/]|$)/u.test(raw) ? raw : resolved()
396
- }
397
-
398
- /**
399
- * Normalise a path for identity comparison. `realpath` resolves symlinks and `..` so
400
- * two spellings of the same file compare equal, but it throws for a path with no file
401
- * behind it yet — and a plain `resolve` fallback is NOT interchangeable with it: an
402
- * index pinned before it exists, under a symlinked ancestor, would be keyed by its
403
- * alias at config time and by the link's target on every later call. The keys would
404
- * never match again and the guard would silently stop guarding its own index.
405
- *
406
- * So resolve the deepest ancestor that DOES exist and re-attach the missing tail:
407
- * the same file then keys identically whether or not it exists yet. Case is folded on
408
- * Windows only, mirroring `os.path.normcase` in the Python guard — folding it on Linux
409
- * would make an unrelated `memory.md` collide with the pinned index. (Known limit:
410
- * `toLowerCase` is not NTFS's exact case-folding table, same as the Python guard.)
411
- */
412
- function pathKey(p) {
413
- let head = resolve(p)
414
- const tail = []
415
- for (;;) {
416
- try {
417
- head = realpathSync(head)
418
- break
419
- } catch {
420
- const parent = dirname(head)
421
- if (parent === head) break // hit the root with nothing resolvable
422
- tail.unshift(basename(head))
423
- head = parent
424
- }
425
- }
426
- const out = tail.length ? join(head, ...tail) : head
427
- return process.platform === 'win32' ? out.toLowerCase() : out
428
- }
429
-
430
-
431
- /**
432
- * An empty or non-string indexName must fall back, not silently disable the cap:
433
- * the numeric caps already recover from nonsense values, and this field is the one
434
- * that decides whether the guard fires at all.
435
- */
436
- function indexNameOf(value) {
437
- return typeof value === 'string' && value.trim() ? value.trim() : DEFAULT_INDEX_NAME
438
- }
439
-
440
- /**
441
- * The always-on block states the discipline; this is the on-demand detail the model
442
- * pulls when it is actually about to recall, write, or sync. Kept deliberately short —
443
- * the full protocol is SKILL.md in the Engramory repo, and a skill body that has to be
444
- * read before it is useful is a skill that will not be read.
445
- */
446
- function builtinSkillBody() {
447
- return [
448
- '# Engramory — curated file-based memory',
449
- '',
450
- 'One canonical store: `MEMORY.md` is an index of pointers, one line per memory;',
451
- 'each fact lives in its own small markdown file beside it. Never put content in',
452
- 'the index, and never keep a second parallel store for handoffs. The ACTIVE',
453
- 'store is flat — the four type names are values of the `type:` field, not',
454
- 'subdirectories to create; `archive/` is the one reserved subdirectory, for',
455
- 'notes retired out of the index.',
456
- '',
457
- '## Recall',
458
- '',
459
- 'A turn, a message, or a session is NOT BY ITSELF a task: a greeting, an',
460
- 'acknowledgement, or a reaction starts none, so it gets no recall and no',
461
- 'checkpoint. A task is user-directed work whose CORRECT handling could depend',
462
- 'on what the store holds — read-only work (analysis, diagnosis, planning,',
463
- 'review)',
464
- 'counts, and changing a file is not required. HAVING THE MATERIAL IN HAND does',
465
- 'not make work a non-task: a diff pasted for review is still a task. NEVER INFER',
466
- 'THIS FROM LENGTH: a one-word reply that picks an option or carries on work',
467
- 'underway inherits that task. Still unclear? Treat it as a task.',
468
- '',
469
- 'At the start of a task, read the index and open only the notes whose hooks look',
470
- 'relevant. Treat what you recall as background that may be stale: re-verify any',
471
- 'file, flag, or version against the repo before acting on it.',
472
- '',
473
- '## Write',
474
- '',
475
- 'Before writing, confirm the fact is not already in the repo, git history, or the',
476
- 'instruction files, and that it is not a secret value. Search the index and update',
477
- 'an existing note rather than adding a near-duplicate. A new note is one atomic',
478
- 'fact with frontmatter:',
479
- '',
480
- '```markdown',
481
- '---',
482
- 'name: <kebab-case-slug>',
483
- 'description: <one sharp line — this is what future-you reads to decide to open it>',
484
- 'type: user | feedback | project | reference',
485
- 'scope: global | repo # optional: does this still hold in another repo?',
486
- 'created: YYYY-MM-DD',
487
- 'updated: YYYY-MM-DD',
488
- '---',
489
- '```',
490
- '',
491
- '`feedback` and `project` notes MUST carry a `**Why:**` line and a',
492
- '`**How to apply:**` line. Add exactly one pointer line to the index, and delete',
493
- 'memories that turn out to be wrong.',
494
- '',
495
- 'Store settled facts, never current state: "2.0 shipped on 2026-01-15" is durable;',
496
- '"the current version is X", the tip commit, or a passing test count will rot —',
497
- 'record where to read those instead.',
498
- '',
499
- 'An unfinished task may keep AT MOST ONE live `project` note holding its goal,',
500
- 'status, decisions, constraints, blockers, and next step together — the single',
501
- 'exception to one-file-one-fact, and a ceiling rather than a quota: a task that',
502
- 'needs no resumable state keeps no note. Update it IN PLACE. Never a dated',
503
- 'series (`state-2026-01-15.md`, `state-2026-01-16.md`, …), never a second',
504
- 'handoff log indexed beside it, and retire its transient state once it ends.',
505
- '',
506
- '## When a task finishes',
507
- '',
508
- 'Run one curation checkpoint. It is a judgement, not a write: promote what is',
509
- 'durable, retire the transient state the CURRENT task left on its own live',
510
- '`project` note if it has one, and when nothing is worth keeping, write',
511
- 'nothing and say so. Never append a per-turn log TO THE STORE, and never touch',
512
- 'a file just to mark it fresh — a timestamp is not a memory.',
513
- '',
514
- '## Sync',
515
- '',
516
- 'Before a deliberate compact, clear, or new thread: scan the task, dedup and update,',
517
- 'refresh project state, promote only reusable feedback, retire completed transient',
518
- 'state, then report what was added, updated, archived, and skipped.',
519
- '',
520
- '## The cap is enforced here',
521
- '',
522
- 'This host denies a write that would GROW the index past 200 lines / 25 KB. That is',
523
- 'a real refusal, not a warning — but a write that shrinks the index always passes,',
524
- 'so compact first, step by step if needed: the index is loaded every session, and',
525
- 'anything past the cap silently stops being recalled.',
526
- '',
527
- 'Never write credentials, keys, tokens, or cookies into memory — record only where',
528
- 'the secret lives.',
529
- ].join('\n')
530
- }
1
+ /**
2
+ * dsh-engramory — the Engramory memory discipline as a DeepSeek Harness plugin.
3
+ *
4
+ * Two things the always-on AGENTS.md block cannot do on its own:
5
+ *
6
+ * 1. A DETERMINISTIC index cap. dsh's `ctx.tools.guard()` is a synchronous,
7
+ * monotonic refusal — once a guard returns a reason, no later waterfall
8
+ * listener can turn it back into an allow. That makes it a stronger seam than
9
+ * most hosts expose, and it is why the 200-line / 25 KB limit can be enforced
10
+ * here rather than merely asked for. Without a shim like this one, everywhere
11
+ * except Claude Code the cap degrades to "rules plus a checker the agent has to
12
+ * remember to run".
13
+ * 2. Skill delivery that does not depend on install paths. Registering at runtime
14
+ * sidesteps the five-root scan entirely, so the protocol is present because the
15
+ * plugin is loaded, not because a directory happened to be right.
16
+ *
17
+ * The decision table mirrors hooks/engramory_index_guard.py: deny only a write that
18
+ * ENDS over a cap AND grew past the current file — a shrinking rewrite always passes,
19
+ * so an over-cap index can be compacted incrementally (210 → 205 → 198). Only known
20
+ * mutating tools are gated; `read` and unknown tools are never refused (the first cut
21
+ * gated everything that named the index, which blocked recall of an over-cap index at
22
+ * exactly the moment compaction was needed).
23
+ *
24
+ * Zero dependencies, no build step: plain ESM, node: builtins only.
25
+ */
26
+ import { closeSync, constants, fstatSync, openSync, readSync, realpathSync, statSync } from 'node:fs'
27
+ import { basename, dirname, isAbsolute, join, resolve, sep } from 'node:path'
28
+
29
+ export const name = 'engramory'
30
+
31
+ // `tools` carries the cap and is the plugin's only declared dependency. Cordis reads
32
+ // `inject` as an array of service names (or an object KEYED by them) and treats every
33
+ // entry as a hard wait — the `{ required, optional }` shape is older-Cordis syntax that
34
+ // the build dsh vendors resolves as services literally named "required"/"optional",
35
+ // which never appear, so the plugin sat pending forever (issue #8). `skills` is
36
+ // deliberately NOT declared: the cap must mount even on a profile with no skill
37
+ // registry, so apply() probes it at runtime instead.
38
+ export const inject = ['tools']
39
+
40
+ /** Mirrors hooks/engramory_index_guard.py — the caps are the protocol's, not this port's. */
41
+ const DEFAULT_INDEX_NAME = 'MEMORY.md'
42
+ const DEFAULT_MAX_LINES = 200
43
+ const DEFAULT_MAX_BYTES = 25600
44
+
45
+ /**
46
+ * The most the guard reads to measure the current index (#21). Guards run on the host's
47
+ * main thread, so an unbounded read of whatever answers to the index's name — a symlink
48
+ * to /dev/zero, a multi-gigabyte file — stalls or exhausts the host. Past this the index
49
+ * is long since over the cap, and its byte size comes from the filesystem instead.
50
+ * The ceiling holds even against an absurd `maxBytes` (4 × 1e308 is Infinity).
51
+ */
52
+ const MIN_READ_LIMIT = 1024 * 1024
53
+ const MAX_READ_LIMIT = 16 * 1024 * 1024
54
+
55
+ /** Tools that replace a file wholesale, so the post-write text is in the arguments. */
56
+ const WHOLE_FILE_WRITES = new Set(['write'])
57
+
58
+ /**
59
+ * Tools that mutate a file in place. Only tools named here (plus
60
+ * `str_replace_editor`'s write commands, handled explicitly) count as partial
61
+ * writes. Unknown tools pass through: this guard is a discipline rail, not a
62
+ * security boundary (SECURITY.md), and a false refusal of `read` costs more than a
63
+ * miss — the next whole-file write is measured exactly regardless.
64
+ */
65
+ const PARTIAL_WRITES = new Set(['edit', 'str_replace', 'insert'])
66
+
67
+ export function apply(ctx, config = {}) {
68
+ // `indexPath` pins the guard to ONE file. Without it the only signal is the
69
+ // basename, so an unrelated MEMORY.md in any other project is gated too — a real
70
+ // refusal on a file that is not a memory index at all, with no way to opt out
71
+ // (renaming `indexName` would just unguard the real index). The Claude Code hook
72
+ // has had ENGRAMORY_INDEX_PATH for exactly this; this is its counterpart.
73
+ //
74
+ // The key and the basename are computed ONCE here: guards run on every tool call
75
+ // and must stay cheap, so the per-call path stays a string compare and the single
76
+ // realpath() only happens when the basename already matched.
77
+ const indexPath = typeof config.indexPath === 'string' && config.indexPath.trim()
78
+ ? config.indexPath.trim()
79
+ : undefined
80
+ const settings = {
81
+ indexName: indexNameOf(config.indexName),
82
+ indexPath,
83
+ indexKey: indexPath === undefined ? undefined : pathKey(indexPath),
84
+ // When pinned, the name to match is the pinned file's own basename.
85
+ matchName: (indexPath === undefined
86
+ ? indexNameOf(config.indexName)
87
+ : basename(indexPath)).toLowerCase(),
88
+ maxLines: positive(config.maxLines, DEFAULT_MAX_LINES),
89
+ maxBytes: positive(config.maxBytes, DEFAULT_MAX_BYTES),
90
+ }
91
+ settings.readLimit = Math.min(MAX_READ_LIMIT, Math.max(MIN_READ_LIMIT, 4 * settings.maxBytes))
92
+
93
+ // dsh 0.2 resolves a relative file path against the calling SESSION's working
94
+ // directory, which its `working_directory` tool moves away from the process's own
95
+ // cwd. Measured against process.cwd(), a bare `MEMORY.md` after a cd is the wrong
96
+ // file or none: an edit of the real index passed unmeasured, and a shrinking rewrite
97
+ // of an over-cap index was judged against an empty file and refused. The service is
98
+ // optional (0.1.x has none) and may mount late, so — like `skills` below — it is
99
+ // picked up reactively and never makes the cap wait.
100
+ let workingDirectory
101
+ ctx.inject(['workingDirectory'], (inner) => {
102
+ inner.effect(() => {
103
+ const service = inner.workingDirectory
104
+ workingDirectory = service
105
+ return () => {
106
+ if (workingDirectory === service) workingDirectory = undefined
107
+ }
108
+ })
109
+ })
110
+ const sessionCwd = (exec) => {
111
+ try {
112
+ const dir = workingDirectory?.get(exec.agent.session)
113
+ return typeof dir === 'string' && isAbsolute(dir) ? dir : undefined
114
+ } catch {
115
+ return undefined // no agent, no session, or a service shape this port predates
116
+ }
117
+ }
118
+
119
+ // A guard that throws breaks the host's tool call; only an UNEXPECTED exception can
120
+ // get here (an edit whose simulated result exceeds V8's string limit, say), and like
121
+ // the Python guard it fails open — the host could not perform such an edit either.
122
+ ctx.tools.guard((exec) => {
123
+ try {
124
+ return refuseOversizedIndex(exec, settings, sessionCwd)
125
+ } catch {
126
+ return undefined
127
+ }
128
+ })
129
+
130
+ // The skill registry is optional AND may activate after this plugin — fiber order
131
+ // between unrelated providers is not guaranteed, so a one-shot probe here would
132
+ // silently skip registration on such boots. ctx.inject() is Cordis' reactive form:
133
+ // the callback runs once `skills` is available (however late), re-runs if the
134
+ // registry reloads, and never makes the cap wait. A bare `ctx.skills` read at THIS
135
+ // level would throw (undeclared service — issue #8's second crash); inside the
136
+ // callback the service is declared, so the read is legal.
137
+ if (config.registerSkill !== false) {
138
+ ctx.inject(['skills'], (inner) => {
139
+ const skill = config.skill ?? builtinSkillBody()
140
+ // effect() ties the registration to the child fiber: it is disposed when the
141
+ // registry unloads, so a reload cannot accumulate duplicate registrations.
142
+ inner.effect(() => inner.skills.register({
143
+ name: 'engramory',
144
+ description:
145
+ 'Curated file-based long-term memory: recall through MEMORY.md at the start of ' +
146
+ 'a task, save durable user/feedback/project/reference facts, run a curation ' +
147
+ 'checkpoint when a task finishes, and sync before compacting or opening a ' +
148
+ 'fresh thread. A turn that starts no work — a greeting, an acknowledgement — ' +
149
+ 'is not a task and needs none of this, but never judge that by length: a ' +
150
+ 'one-word reply continuing work underway inherits that task.',
151
+ whenToUse:
152
+ 'Starting or resuming work, learning something durable worth a future session, ' +
153
+ 'finishing a task — including one that leaves nothing worth saving, since the ' +
154
+ 'checkpoint is still a decision to make — or approaching a ' +
155
+ 'compact/clear/new-thread boundary. Not for a bare greeting, ' +
156
+ 'acknowledgement, or reaction, which starts no task — but a terse reply ' +
157
+ 'that continues work underway does, and material already in hand (a ' +
158
+ 'pasted diff to review) does not make work a non-task. Unsure? Treat it ' +
159
+ 'as a task.',
160
+ source: 'runtime',
161
+ content: skill,
162
+ }))
163
+ })
164
+ }
165
+ }
166
+
167
+ /**
168
+ * The cap itself. Returning a string denies the call; `undefined` lets it through.
169
+ *
170
+ * Guards are synchronous by contract, so this stays cheap: every tool that cannot
171
+ * write leaves on string compares; a write pays a path resolution, and a write to the
172
+ * index one bounded read of it.
173
+ */
174
+ function refuseOversizedIndex(exec, settings, sessionCwd) {
175
+ const args = exec?.arguments
176
+ if (!args || typeof args !== 'object') return undefined
177
+
178
+ // dsh's file tools carry the target as `file_path`; `str_replace_editor` calls it
179
+ // `path`.
180
+ const filePath = typeof args.file_path === 'string' ? args.file_path
181
+ : typeof args.path === 'string' ? args.path
182
+ : undefined
183
+ if (filePath === undefined) return undefined
184
+
185
+ const tool = typeof exec.name === 'string' ? exec.name : ''
186
+
187
+ // Nothing below can refuse a read, a view, or an unknown tool, so leave before
188
+ // anything touches the filesystem: a guard runs on EVERY tool call, and this keeps
189
+ // the common case a few string compares.
190
+ const gated = WHOLE_FILE_WRITES.has(tool)
191
+ || PARTIAL_WRITES.has(tool)
192
+ || (tool === 'str_replace_editor'
193
+ && (args.command === 'create' || args.command === 'str_replace'
194
+ || args.command === 'insert'))
195
+ if (!gated) return undefined
196
+ // Every read and identity check below uses the file the host will actually touch.
197
+ let target
198
+ try {
199
+ target = hostPath(sessionCwd(exec), filePath)
200
+ } catch {
201
+ return undefined // a relative path and no cwd left to resolve it (deleted under us)
202
+ }
203
+ // Is this the index? Decided on the file the write lands on, not the name it was
204
+ // called by: dsh follows a symlink, so `idx.md -> MEMORY.md` writes the index (#20).
205
+ // Pinned, that is identity — which is also where an unrelated same-named file in
206
+ // another project drops out. Unpinned, the name of the path or of what it resolves
207
+ // to, compared case-INsensitively: on the case-insensitive filesystems most stores
208
+ // live on (Windows/macOS), `memory.md` IS the guarded index. (Same trade-off as the
209
+ // Python guard: on a case-sensitive FS this can gate an unrelated lowercase twin —
210
+ // rename it, or pin `indexPath`.)
211
+ const named = (p) => basename(p).toLowerCase() === settings.matchName
212
+ const isIndex = settings.indexKey !== undefined
213
+ ? pathKey(target) === settings.indexKey
214
+ : named(filePath) || named(pathKey(target))
215
+ if (!isIndex) return undefined
216
+
217
+ if (WHOLE_FILE_WRITES.has(tool)) {
218
+ if (typeof args.content !== 'string') return undefined
219
+ return verdict(args.content, readIndex(target, settings.readLimit), filePath, settings)
220
+ }
221
+ if (tool === 'str_replace_editor' && args.command === 'create') {
222
+ if (typeof args.file_text !== 'string') return undefined
223
+ return verdict(args.file_text, readIndex(target, settings.readLimit), filePath, settings)
224
+ }
225
+
226
+ const partial = PARTIAL_WRITES.has(tool)
227
+ || (tool === 'str_replace_editor'
228
+ && (args.command === 'str_replace' || args.command === 'insert'))
229
+ if (!partial) return undefined // read / view / list / unknown: never refused
230
+
231
+ // Unreadable, or past the read limit: an edit's result cannot be simulated without
232
+ // the whole text, and refusing it blind would refuse the compacting ones too. Let it
233
+ // through, as for any index the guard cannot read; whole-file writes stay measured.
234
+ const currentBuf = readIndex(target, settings.readLimit)
235
+ if (currentBuf === undefined || !Buffer.isBuffer(currentBuf)) return undefined
236
+ const current = currentBuf.toString('utf8')
237
+ const simulated = simulateEdit(current, args, settings.readLimit)
238
+ if (typeof simulated === 'string') {
239
+ return verdict(simulated, currentBuf, filePath, settings)
240
+ }
241
+ if (simulated !== undefined) {
242
+ // Too long to build: judged on lower bounds of its size, by the same grow-past-the-
243
+ // cap rule as verdict(). A bound that clears both tests refuses only what the full
244
+ // result would; one that does not lets the edit through unmeasured.
245
+ const over = []
246
+ if (simulated.newlines > settings.maxLines && simulated.newlines > countLines(current)) {
247
+ over.push(`at least ${simulated.newlines} lines > ${settings.maxLines}`)
248
+ }
249
+ if (simulated.bytes > settings.maxBytes && simulated.bytes > currentBuf.length) {
250
+ over.push(`at least ${simulated.bytes} bytes > ${settings.maxBytes}`)
251
+ }
252
+ return over.length ? capRefusal(over, filePath, settings) : undefined
253
+ }
254
+
255
+ // The edit's result genuinely cannot be reconstructed from its arguments. Honest,
256
+ // cheap rule: if the index is ALREADY over, refuse to mutate it blind — and name
257
+ // the open door, because "compact first" while refusing edits reads as a dead end.
258
+ const breach = measure(current, settings)
259
+ if (!breach) return undefined
260
+ return (
261
+ `${displayName(settings)} is already over the Engramory cap (${breach}) and this ` +
262
+ `edit's result cannot be measured. Compact it with a whole-file write instead: ` +
263
+ `a rewrite that SHRINKS the index always passes, even while still over the cap. ` +
264
+ `Pointer-ify over-long lines, merge duplicates, archive cold notes — the index ` +
265
+ `is a table of contents, and anything past the cap silently stops being recalled.` +
266
+ notMyIndexHint(settings)
267
+ )
268
+ }
269
+
270
+ /**
271
+ * Mirrors the Python guard's deny rule: refuse only when a dimension ends OVER its
272
+ * cap AND grew past the current file, so a shrinking/keeping write on an over-cap
273
+ * index always passes and incremental compaction stays possible. A missing or
274
+ * unreadable current file counts as empty — a first write past the cap is refused.
275
+ * One too large to read (see readIndex) is sized by the filesystem, with a line count
276
+ * no write can exceed: only its byte growth can be refused, and every shrink passes.
277
+ */
278
+ function verdict(text, currentBuf, filePath, settings) {
279
+ const lines = countLines(text)
280
+ const bytes = Buffer.byteLength(text, 'utf8')
281
+ // Current byte size comes from the RAW buffer, mirroring how the Python guard
282
+ // sizes the on-disk file: decoding first inflated a non-UTF-8 index ~3x (every
283
+ // bad byte becomes a 3-byte U+FFFD), which made a genuinely growing write look
284
+ // like a shrink and pass. Newlines survive a lossy decode, so the line count may
285
+ // use the decoded text.
286
+ const unread = currentBuf !== undefined && !Buffer.isBuffer(currentBuf)
287
+ const curLines = currentBuf === undefined ? 0
288
+ : unread ? Infinity : countLines(currentBuf.toString('utf8'))
289
+ const curBytes = currentBuf === undefined ? 0 : unread ? currentBuf.bytes : currentBuf.length
290
+ const over = []
291
+ if (lines > settings.maxLines && lines > curLines) {
292
+ over.push(`${lines} lines > ${settings.maxLines}`)
293
+ }
294
+ if (bytes > settings.maxBytes && bytes > curBytes) {
295
+ over.push(`${bytes} bytes > ${settings.maxBytes}`)
296
+ }
297
+ return over.length ? capRefusal(over, filePath, settings) : undefined
298
+ }
299
+
300
+ function capRefusal(over, filePath, settings) {
301
+ return (
302
+ `This write would put ${basename(filePath)} over the Engramory index cap ` +
303
+ `(${over.join(', ')}). The index is loaded every session and the host only reads ` +
304
+ `so far, so anything past the cap silently stops being recalled. Compact before ` +
305
+ `writing: move detail into the linked note files, merge duplicates, archive cold ` +
306
+ `notes, and keep every line to "one short hook + link". A write that SHRINKS the ` +
307
+ `index always passes, so you can compact step by step.` + notMyIndexHint(settings)
308
+ )
309
+ }
310
+
311
+
312
+ /**
313
+ * The name to show in a refusal. `indexPath` wins over `indexName` when both are set,
314
+ * so quoting the ignored one would send a user looking for the wrong file.
315
+ */
316
+ function displayName(settings) {
317
+ return settings.indexPath === undefined
318
+ ? settings.indexName
319
+ : basename(settings.indexPath)
320
+ }
321
+
322
+
323
+ /**
324
+ * Without `indexPath` the guard matches on basename alone, so it can land on a file
325
+ * that is not a memory index at all. Say so in the refusal: a user who hits this
326
+ * needs the way out, not just the cap.
327
+ */
328
+ function notMyIndexHint(settings) {
329
+ if (settings.indexPath !== undefined) return ''
330
+ return (
331
+ ` (If this file is NOT your memory index, set this plugin's \`indexPath\` config ` +
332
+ `to your real index's absolute path so only that file is gated.)`
333
+ )
334
+ }
335
+
336
+ /**
337
+ * Reconstruct a partial edit's post-write text when its arguments carry enough to
338
+ * do it (`old_str`/`new_str`, or the Claude-style `old_string`/`new_string`).
339
+ * Mirrors the Python guard's Edit simulation: replace the unique occurrence, or all
340
+ * of them under a replace-all flag; an absent or ambiguous old-string means the
341
+ * real tool errors and changes nothing, so the current text is the honest
342
+ * prediction. Returns undefined when the shape isn't recognised, and `{ bytes, newlines }`
343
+ * — lower bounds of the result's size — when it is too long to build.
344
+ *
345
+ * Matching happens on LF-normalised text and the result goes back in the file's own
346
+ * line endings, as dsh's local backend does it (`applyLiteralEdit` /
347
+ * `restoreLineEndings` in @deepseek-ai/dsh-fs-local). Matching the raw text let a CRLF
348
+ * index — common on Windows — read every LF `old_string` as "not found", predict no
349
+ * change, and pass an edit dsh then applied.
350
+ */
351
+ function simulateEdit(current, args, limit) {
352
+ const oldRaw = firstString(args.old_str, args.old_string)
353
+ if (oldRaw === undefined || oldRaw === '') return undefined
354
+ const newRaw = firstString(args.new_str, args.new_string) ?? ''
355
+ // dsh decodes with TextDecoder, which drops a leading BOM — from the text it
356
+ // matches, from the sample it detects line endings on, and from what it writes back.
357
+ const decoded = current.startsWith('\uFEFF') ? current.slice(1) : current
358
+ // Normalising CRLF at most halves a string, so an old_string over twice the text's
359
+ // length cannot be in it: the real tool errors, nothing changes. Checked before it
360
+ // is normalised, so an argument the size of the heap is never copied (#21).
361
+ if (oldRaw.length > 2 * decoded.length) return current
362
+ const text = lf(decoded)
363
+ const oldStr = lf(oldRaw)
364
+ const first = text.indexOf(oldStr)
365
+ if (first === -1) return current // the real tool errors: nothing changes
366
+ const all = args.replace_all === true || args.replaceAll === true
367
+ if (!all && text.indexOf(oldStr, first + oldStr.length) !== -1) {
368
+ return current // ambiguous: the real tool errors, nothing changes
369
+ }
370
+ const matches = all ? occurrences(text, oldStr) : 1
371
+ // Sized before it is built: replace_all multiplies new_string by every match, and
372
+ // building the result just to measure it could cost the host gigabytes — or abort it
373
+ // outright on heap exhaustion, which no catch survives. new_string is measured as it
374
+ // will be once normalised, without normalising it: each CRLF in it loses its CR.
375
+ const crlfs = occurrences(newRaw, '\r\n')
376
+ const length = text.length + matches * (newRaw.length - crlfs - oldStr.length)
377
+ if (length > limit) {
378
+ // Exact for the LF text, and so lower bounds for what dsh writes: restoring CRLF
379
+ // only adds bytes, and never changes the line count. UTF-8 sizes add up only for
380
+ // well-formed text: a lone surrogate counts three bytes, but two meeting at a
381
+ // replacement seam encode as one four-byte pair. With one anywhere, fall back to
382
+ // the length — every UTF-16 unit is at least one byte, paired or not.
383
+ const wellFormed = !LONE_SURROGATE.test(text) && !LONE_SURROGATE.test(newRaw)
384
+ && !LONE_SURROGATE.test(oldStr)
385
+ return {
386
+ bytes: wellFormed
387
+ ? Buffer.byteLength(text)
388
+ + matches * (Buffer.byteLength(newRaw) - crlfs - Buffer.byteLength(oldStr))
389
+ : length,
390
+ newlines: occurrences(text, '\n')
391
+ + matches * (occurrences(newRaw, '\n') - occurrences(oldStr, '\n')),
392
+ }
393
+ }
394
+ const newStr = lf(newRaw) // no longer than the result, so within the limit
395
+ // A function replacer, so a `$&` in new_string stays literal.
396
+ const edited = all
397
+ ? text.replaceAll(oldStr, () => newStr)
398
+ : text.slice(0, first) + newStr + text.slice(first + oldStr.length)
399
+ // Normalised once more before expanding, as dsh's restoreLineEndings does: a lone
400
+ // `\r` meeting an inserted `\n` at the seam is one CRLF, not `\r\r\n`.
401
+ return crlfDominates(decoded) ? lf(edited).replaceAll('\n', '\r\n') : edited
402
+ }
403
+
404
+ /** A high surrogate with no low after it, or a low with no high before it. */
405
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/
406
+
407
+ /** Non-overlapping occurrences of `needle`, counted rather than split out. */
408
+ function occurrences(text, needle) {
409
+ let n = 0
410
+ for (let i = text.indexOf(needle); i !== -1; i = text.indexOf(needle, i + needle.length)) n++
411
+ return n
412
+ }
413
+
414
+ function lf(text) {
415
+ return text.replaceAll('\r\n', '\n')
416
+ }
417
+
418
+ /** dsh's own call (`detectLineEndings`): CRLF wins on a majority in the first 4096 chars. */
419
+ function crlfDominates(raw) {
420
+ const sample = raw.slice(0, 4096)
421
+ const crlf = sample.split('\r\n').length - 1
422
+ return crlf > sample.split('\n').length - 1 - crlf
423
+ }
424
+
425
+ function firstString(...values) {
426
+ for (const v of values) {
427
+ if (typeof v === 'string') return v
428
+ }
429
+ return undefined
430
+ }
431
+
432
+ /** Returns a human-readable breach description, or `null` when the text is within caps. */
433
+ function measure(text, { maxLines, maxBytes }) {
434
+ const lines = countLines(text)
435
+ const bytes = Buffer.byteLength(text, 'utf8')
436
+ const over = []
437
+ if (lines > maxLines) over.push(`${lines} lines > ${maxLines}`)
438
+ if (bytes > maxBytes) over.push(`${bytes} bytes > ${maxBytes}`)
439
+ return over.length ? over.join(', ') : null
440
+ }
441
+
442
+ /**
443
+ * Trailing-newline-insensitive, matching how the Python guard counts. Counted, not
444
+ * split: the text is whatever a tool call carried, and an array of its lines would
445
+ * cost a second copy of it.
446
+ */
447
+ function countLines(text) {
448
+ if (!text) return 0
449
+ return occurrences(text, '\n') + 1 - (text.endsWith('\n') ? 1 : 0)
450
+ }
451
+
452
+ /**
453
+ * A missing or unreadable index is not a breach: the guard's job is to stop an
454
+ * oversized index, never to block work because a path could not be read. Returns the
455
+ * RAW buffer — byte comparisons must use on-disk bytes (see verdict), decode at the
456
+ * call sites that need text — or `{ bytes }` for a regular file past `limit`.
457
+ *
458
+ * Only a regular file is read, and never more than `limit + 1` bytes (#21). The read
459
+ * runs on the host's main thread, and a plain readFileSync would block forever on a
460
+ * FIFO (opening one waits for a writer, hence O_NONBLOCK — absent on Windows, which has
461
+ * no FIFOs on disk) or keep allocating on a symlink to /dev/zero. Anything that is not
462
+ * a regular file counts as unreadable. A stat comes first, so a device is never even
463
+ * opened (some drivers block in open itself); the descriptor is checked again, since
464
+ * the path can be swapped between the two.
465
+ */
466
+ function readIndex(filePath, limit) {
467
+ let fd
468
+ try {
469
+ if (!statSync(filePath).isFile()) return undefined
470
+ fd = openSync(filePath, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0))
471
+ const stat = fstatSync(fd)
472
+ if (!stat.isFile()) return undefined
473
+ const chunks = []
474
+ let total = 0
475
+ for (;;) {
476
+ const chunk = Buffer.allocUnsafe(Math.min(65536, limit + 1 - total))
477
+ const got = readSync(fd, chunk, 0, chunk.length, null)
478
+ if (got === 0) return Buffer.concat(chunks, total)
479
+ chunks.push(chunk.subarray(0, got))
480
+ total += got
481
+ if (total > limit) return { bytes: Math.max(stat.size, total) }
482
+ }
483
+ } catch {
484
+ return undefined
485
+ } finally {
486
+ if (fd !== undefined) {
487
+ try { closeSync(fd) } catch { /* nothing left to do */ }
488
+ }
489
+ }
490
+ }
491
+
492
+ function positive(value, fallback) {
493
+ if (!Number.isFinite(value)) return fallback
494
+ const floored = Math.floor(value)
495
+ return floored > 0 ? floored : fallback
496
+ }
497
+
498
+ /**
499
+ * The path the host's own file tools would touch for `p`, mirroring dsh's local
500
+ * backend (`localDisplayPath` in @deepseek-ai/dsh-fs-local): resolve against `cwd`,
501
+ * except that on POSIX a spelling with a `..` segment is kept as written, so a `..`
502
+ * after a symlinked segment stays physical — collapsing it could measure a different
503
+ * file than the one the write lands on. Without a session directory (`cwd`
504
+ * undefined), the process's is used, and only when `p` needs one: process.cwd()
505
+ * throws once that directory is deleted, and an absolute path must not care.
506
+ */
507
+ function hostPath(cwd, p) {
508
+ const resolved = () => (cwd === undefined ? resolve(p) : resolve(cwd, p))
509
+ if (process.platform === 'win32') return resolved()
510
+ const raw = isAbsolute(p) ? p : `${cwd ?? process.cwd()}${sep}${p}`
511
+ return /(?:^|[\\/])\.\.(?:[\\/]|$)/u.test(raw) ? raw : resolved()
512
+ }
513
+
514
+ /**
515
+ * Normalise a path for identity comparison. `realpath` resolves symlinks and `..` so
516
+ * two spellings of the same file compare equal, but it throws for a path with no file
517
+ * behind it yet — and a plain `resolve` fallback is NOT interchangeable with it: an
518
+ * index pinned before it exists, under a symlinked ancestor, would be keyed by its
519
+ * alias at config time and by the link's target on every later call. The keys would
520
+ * never match again and the guard would silently stop guarding its own index.
521
+ *
522
+ * So resolve the deepest ancestor that DOES exist and re-attach the missing tail:
523
+ * the same file then keys identically whether or not it exists yet. Case is folded on
524
+ * Windows only, mirroring `os.path.normcase` in the Python guard — folding it on Linux
525
+ * would make an unrelated `memory.md` collide with the pinned index. (Known limit:
526
+ * `toLowerCase` is not NTFS's exact case-folding table, same as the Python guard.)
527
+ *
528
+ * On POSIX an absolute spelling is kept as written and walked by the OS
529
+ * (`realpathSync.native` is realpath(3)): Node's JS realpathSync resolve()s first, which
530
+ * collapses a `..` after a symlinked segment lexically — to the parent of the LINK,
531
+ * where dsh, walking it physically, reaches the parent of its TARGET. `link/../idx.md`
532
+ * then named another file than the one written (#20). Windows resolves `..` lexically
533
+ * anyway, as dsh does there, so it keeps the JS form.
534
+ */
535
+ function pathKey(p) {
536
+ const posix = process.platform !== 'win32'
537
+ const real = posix ? realpathSync.native : realpathSync
538
+ let head = posix && isAbsolute(p) ? p : resolve(p)
539
+ const tail = []
540
+ for (;;) {
541
+ try {
542
+ head = real(head)
543
+ break
544
+ } catch {
545
+ const parent = dirname(head)
546
+ if (parent === head) break // hit the root with nothing resolvable
547
+ tail.unshift(basename(head))
548
+ head = parent
549
+ }
550
+ }
551
+ const out = tail.length ? join(head, ...tail) : head
552
+ return process.platform === 'win32' ? out.toLowerCase() : out
553
+ }
554
+
555
+
556
+ /**
557
+ * An empty or non-string indexName must fall back, not silently disable the cap:
558
+ * the numeric caps already recover from nonsense values, and this field is the one
559
+ * that decides whether the guard fires at all.
560
+ */
561
+ function indexNameOf(value) {
562
+ return typeof value === 'string' && value.trim() ? value.trim() : DEFAULT_INDEX_NAME
563
+ }
564
+
565
+ /**
566
+ * The always-on block states the discipline; this is the on-demand detail the model
567
+ * pulls when it is actually about to recall, write, or sync. Kept deliberately short —
568
+ * the full protocol is SKILL.md in the Engramory repo, and a skill body that has to be
569
+ * read before it is useful is a skill that will not be read.
570
+ */
571
+ function builtinSkillBody() {
572
+ return [
573
+ '# Engramory — curated file-based memory',
574
+ '',
575
+ 'One canonical store: `MEMORY.md` is an index of pointers, one line per memory;',
576
+ 'each fact lives in its own small markdown file beside it. Never put content in',
577
+ 'the index, and never keep a second parallel store for handoffs. The ACTIVE',
578
+ 'store is flat — the four type names are values of the `type:` field, not',
579
+ 'subdirectories to create; `archive/` is the one reserved subdirectory, for',
580
+ 'notes retired out of the index.',
581
+ '',
582
+ '## Recall',
583
+ '',
584
+ 'A turn, a message, or a session is NOT BY ITSELF a task: a greeting, an',
585
+ 'acknowledgement, or a reaction starts none, so it gets no recall and no',
586
+ 'checkpoint. A task is user-directed work whose CORRECT handling could depend',
587
+ 'on what the store holds — read-only work (analysis, diagnosis, planning,',
588
+ 'review)',
589
+ 'counts, and changing a file is not required. HAVING THE MATERIAL IN HAND does',
590
+ 'not make work a non-task: a diff pasted for review is still a task. NEVER INFER',
591
+ 'THIS FROM LENGTH: a one-word reply that picks an option or carries on work',
592
+ 'underway inherits that task. Still unclear? Treat it as a task.',
593
+ '',
594
+ 'At the start of a task, read the index and open only the notes whose hooks look',
595
+ 'relevant. Treat what you recall as background that may be stale: re-verify any',
596
+ 'file, flag, or version against the repo before acting on it.',
597
+ '',
598
+ '## Write',
599
+ '',
600
+ 'Before writing, confirm the fact is not already in the repo, git history, or the',
601
+ 'instruction files, and that it is not a secret value. Search the index and update',
602
+ 'an existing note rather than adding a near-duplicate. A new note is one atomic',
603
+ 'fact with frontmatter:',
604
+ '',
605
+ '```markdown',
606
+ '---',
607
+ 'name: <kebab-case-slug>',
608
+ 'description: <one sharp line — this is what future-you reads to decide to open it>',
609
+ 'type: user | feedback | project | reference',
610
+ 'scope: global | repo # optional: does this still hold in another repo?',
611
+ 'created: YYYY-MM-DD',
612
+ 'updated: YYYY-MM-DD',
613
+ '---',
614
+ '```',
615
+ '',
616
+ '`feedback` and `project` notes MUST carry a `**Why:**` line and a',
617
+ '`**How to apply:**` line. Add exactly one pointer line to the index, and delete',
618
+ 'memories that turn out to be wrong.',
619
+ '',
620
+ 'Store settled facts, never current state: "2.0 shipped on 2026-01-15" is durable;',
621
+ '"the current version is X", the tip commit, or a passing test count will rot —',
622
+ 'record where to read those instead.',
623
+ '',
624
+ 'An unfinished task may keep AT MOST ONE live `project` note holding its goal,',
625
+ 'status, decisions, constraints, blockers, and next step together — the single',
626
+ 'exception to one-file-one-fact, and a ceiling rather than a quota: a task that',
627
+ 'needs no resumable state keeps no note. Update it IN PLACE. Never a dated',
628
+ 'series (`state-2026-01-15.md`, `state-2026-01-16.md`, …), never a second',
629
+ 'handoff log indexed beside it, and retire its transient state once it ends.',
630
+ '',
631
+ '## When a task finishes',
632
+ '',
633
+ 'Run one curation checkpoint. It is a judgement, not a write: promote what is',
634
+ 'durable, retire the transient state the CURRENT task left on its own live',
635
+ '`project` note if it has one, and when nothing is worth keeping, write',
636
+ 'nothing and say so. Never append a per-turn log TO THE STORE, and never touch',
637
+ 'a file just to mark it fresh — a timestamp is not a memory.',
638
+ '',
639
+ '## Sync',
640
+ '',
641
+ 'Before a deliberate compact, clear, or new thread: scan the task, dedup and update,',
642
+ 'refresh project state, promote only reusable feedback, retire completed transient',
643
+ 'state, then report what was added, updated, archived, and skipped.',
644
+ '',
645
+ '## The cap is enforced here',
646
+ '',
647
+ 'This host denies a write that would GROW the index past 200 lines / 25 KB. That is',
648
+ 'a real refusal, not a warning — but a write that shrinks the index always passes,',
649
+ 'so compact first, step by step if needed: the index is loaded every session, and',
650
+ 'anything past the cap silently stops being recalled.',
651
+ '',
652
+ 'Never write credentials, keys, tokens, or cookies into memory — record only where',
653
+ 'the secret lives.',
654
+ ].join('\n')
655
+ }