dsh-engramory 0.2.5 → 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,454 +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, join, resolve } 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
- ctx.tools.guard((exec) => refuseOversizedIndex(exec, settings))
83
-
84
- // The skill registry is optional AND may activate after this plugin — fiber order
85
- // between unrelated providers is not guaranteed, so a one-shot probe here would
86
- // silently skip registration on such boots. ctx.inject() is Cordis' reactive form:
87
- // the callback runs once `skills` is available (however late), re-runs if the
88
- // registry reloads, and never makes the cap wait. A bare `ctx.skills` read at THIS
89
- // level would throw (undeclared service — issue #8's second crash); inside the
90
- // callback the service is declared, so the read is legal.
91
- if (config.registerSkill !== false) {
92
- ctx.inject(['skills'], (inner) => {
93
- const skill = config.skill ?? builtinSkillBody()
94
- // effect() ties the registration to the child fiber: it is disposed when the
95
- // registry unloads, so a reload cannot accumulate duplicate registrations.
96
- inner.effect(() => inner.skills.register({
97
- name: 'engramory',
98
- description:
99
- 'Curated file-based long-term memory: recall through MEMORY.md at the start of ' +
100
- 'a task, save durable user/feedback/project/reference facts, run a curation ' +
101
- 'checkpoint when a task finishes, and sync before compacting or opening a ' +
102
- 'fresh thread. A turn that starts no work — a greeting, an acknowledgement — ' +
103
- 'is not a task and needs none of this, but never judge that by length: a ' +
104
- 'one-word reply continuing work underway inherits that task.',
105
- whenToUse:
106
- 'Starting or resuming work, learning something durable worth a future session, ' +
107
- 'finishing a task — including one that leaves nothing worth saving, since the ' +
108
- 'checkpoint is still a decision to make — or approaching a ' +
109
- 'compact/clear/new-thread boundary. Not for a bare greeting, ' +
110
- 'acknowledgement, or reaction, which starts no task — but a terse reply ' +
111
- 'that continues work underway does, and material already in hand (a ' +
112
- 'pasted diff to review) does not make work a non-task. Unsure? Treat it ' +
113
- 'as a task.',
114
- source: 'runtime',
115
- content: skill,
116
- }))
117
- })
118
- }
119
- }
120
-
121
- /**
122
- * The cap itself. Returning a string denies the call; `undefined` lets it through.
123
- *
124
- * Guards are synchronous by contract, so this stays cheap: one basename comparison
125
- * rejects the overwhelming majority of calls before anything is measured, and the
126
- * only I/O is a single read of the index on a gated write.
127
- */
128
- function refuseOversizedIndex(exec, settings) {
129
- const args = exec?.arguments
130
- if (!args || typeof args !== 'object') return undefined
131
-
132
- // dsh's file tools carry the target as `file_path`; `str_replace_editor` calls it
133
- // `path`. Compare basenames case-INsensitively: on the case-insensitive
134
- // filesystems most stores live on (Windows/macOS), `memory.md` IS the guarded
135
- // index, and an exact compare let that spelling through. (Same trade-off as the
136
- // Python guard: on a case-sensitive FS this can gate an unrelated lowercase twin —
137
- // rename it, or point `indexName` elsewhere.)
138
- const filePath = typeof args.file_path === 'string' ? args.file_path
139
- : typeof args.path === 'string' ? args.path
140
- : undefined
141
- if (filePath === undefined) return undefined
142
- if (basename(filePath).toLowerCase() !== settings.matchName) return undefined
143
-
144
- const tool = typeof exec.name === 'string' ? exec.name : ''
145
-
146
- // Nothing below can refuse a read, a view, or an unknown tool, so leave before the
147
- // pinned-path check: pathKey() touches the filesystem and a guard runs on EVERY tool
148
- // call. Ordering it here keeps the common case a pair of string compares.
149
- const gated = WHOLE_FILE_WRITES.has(tool)
150
- || PARTIAL_WRITES.has(tool)
151
- || (tool === 'str_replace_editor'
152
- && (args.command === 'create' || args.command === 'str_replace'
153
- || args.command === 'insert'))
154
- if (!gated) return undefined
155
- // If the guard is pinned to one file, this is where an unrelated same-named file in
156
- // another project drops out.
157
- if (settings.indexKey !== undefined && pathKey(filePath) !== settings.indexKey) {
158
- return undefined
159
- }
160
-
161
- if (WHOLE_FILE_WRITES.has(tool)) {
162
- if (typeof args.content !== 'string') return undefined
163
- return verdict(args.content, readIfPossible(filePath), filePath, settings)
164
- }
165
- if (tool === 'str_replace_editor' && args.command === 'create') {
166
- if (typeof args.file_text !== 'string') return undefined
167
- return verdict(args.file_text, readIfPossible(filePath), filePath, settings)
168
- }
169
-
170
- const partial = PARTIAL_WRITES.has(tool)
171
- || (tool === 'str_replace_editor'
172
- && (args.command === 'str_replace' || args.command === 'insert'))
173
- if (!partial) return undefined // read / view / list / unknown: never refused
174
-
175
- const currentBuf = readIfPossible(filePath)
176
- if (currentBuf === undefined) return undefined
177
- const current = currentBuf.toString('utf8')
178
- const simulated = simulateEdit(current, args)
179
- if (simulated !== undefined) {
180
- return verdict(simulated, currentBuf, filePath, settings)
181
- }
182
-
183
- // The edit's result genuinely cannot be reconstructed from its arguments. Honest,
184
- // cheap rule: if the index is ALREADY over, refuse to mutate it blind — and name
185
- // the open door, because "compact first" while refusing edits reads as a dead end.
186
- const breach = measure(current, settings)
187
- if (!breach) return undefined
188
- return (
189
- `${displayName(settings)} is already over the Engramory cap (${breach}) and this ` +
190
- `edit's result cannot be measured. Compact it with a whole-file write instead: ` +
191
- `a rewrite that SHRINKS the index always passes, even while still over the cap. ` +
192
- `Pointer-ify over-long lines, merge duplicates, archive cold notes — the index ` +
193
- `is a table of contents, and anything past the cap silently stops being recalled.` +
194
- notMyIndexHint(settings)
195
- )
196
- }
197
-
198
- /**
199
- * Mirrors the Python guard's deny rule: refuse only when a dimension ends OVER its
200
- * cap AND grew past the current file, so a shrinking/keeping write on an over-cap
201
- * index always passes and incremental compaction stays possible. A missing or
202
- * unreadable current file counts as empty — a first write past the cap is refused.
203
- */
204
- function verdict(text, currentBuf, filePath, settings) {
205
- const lines = countLines(text)
206
- const bytes = Buffer.byteLength(text, 'utf8')
207
- // Current byte size comes from the RAW buffer, mirroring how the Python guard
208
- // sizes the on-disk file: decoding first inflated a non-UTF-8 index ~3x (every
209
- // bad byte becomes a 3-byte U+FFFD), which made a genuinely growing write look
210
- // like a shrink and pass. Newlines survive a lossy decode, so the line count may
211
- // use the decoded text.
212
- const curLines = currentBuf === undefined ? 0 : countLines(currentBuf.toString('utf8'))
213
- const curBytes = currentBuf === undefined ? 0 : currentBuf.length
214
- const over = []
215
- if (lines > settings.maxLines && lines > curLines) {
216
- over.push(`${lines} lines > ${settings.maxLines}`)
217
- }
218
- if (bytes > settings.maxBytes && bytes > curBytes) {
219
- over.push(`${bytes} bytes > ${settings.maxBytes}`)
220
- }
221
- if (!over.length) return undefined
222
- return (
223
- `This write would put ${basename(filePath)} over the Engramory index cap ` +
224
- `(${over.join(', ')}). The index is loaded every session and the host only reads ` +
225
- `so far, so anything past the cap silently stops being recalled. Compact before ` +
226
- `writing: move detail into the linked note files, merge duplicates, archive cold ` +
227
- `notes, and keep every line to "one short hook + link". A write that SHRINKS the ` +
228
- `index always passes, so you can compact step by step.` + notMyIndexHint(settings)
229
- )
230
- }
231
-
232
-
233
- /**
234
- * The name to show in a refusal. `indexPath` wins over `indexName` when both are set,
235
- * so quoting the ignored one would send a user looking for the wrong file.
236
- */
237
- function displayName(settings) {
238
- return settings.indexPath === undefined
239
- ? settings.indexName
240
- : basename(settings.indexPath)
241
- }
242
-
243
-
244
- /**
245
- * Without `indexPath` the guard matches on basename alone, so it can land on a file
246
- * that is not a memory index at all. Say so in the refusal: a user who hits this
247
- * needs the way out, not just the cap.
248
- */
249
- function notMyIndexHint(settings) {
250
- if (settings.indexPath !== undefined) return ''
251
- return (
252
- ` (If this file is NOT your memory index, set this plugin's \`indexPath\` config ` +
253
- `to your real index's absolute path so only that file is gated.)`
254
- )
255
- }
256
-
257
- /**
258
- * Reconstruct a partial edit's post-write text when its arguments carry enough to
259
- * do it (`old_str`/`new_str`, or the Claude-style `old_string`/`new_string`).
260
- * Mirrors the Python guard's Edit simulation: replace the unique occurrence, or all
261
- * of them under a replace-all flag; an absent or ambiguous old-string means the
262
- * real tool errors and changes nothing, so the current text is the honest
263
- * prediction. Returns undefined when the shape isn't recognised.
264
- */
265
- function simulateEdit(current, args) {
266
- const oldStr = firstString(args.old_str, args.old_string)
267
- if (oldStr === undefined || oldStr === '') return undefined
268
- const newStr = firstString(args.new_str, args.new_string) ?? ''
269
- if (args.replace_all === true || args.replaceAll === true) {
270
- return current.split(oldStr).join(newStr)
271
- }
272
- const first = current.indexOf(oldStr)
273
- if (first === -1) return current // the real tool errors: nothing changes
274
- const second = current.indexOf(oldStr, first + oldStr.length)
275
- if (second !== -1) return current // ambiguous: the real tool errors, nothing changes
276
- return current.slice(0, first) + newStr + current.slice(first + oldStr.length)
277
- }
278
-
279
- function firstString(...values) {
280
- for (const v of values) {
281
- if (typeof v === 'string') return v
282
- }
283
- return undefined
284
- }
285
-
286
- /** Returns a human-readable breach description, or `null` when the text is within caps. */
287
- function measure(text, { maxLines, maxBytes }) {
288
- const lines = countLines(text)
289
- const bytes = Buffer.byteLength(text, 'utf8')
290
- const over = []
291
- if (lines > maxLines) over.push(`${lines} lines > ${maxLines}`)
292
- if (bytes > maxBytes) over.push(`${bytes} bytes > ${maxBytes}`)
293
- return over.length ? over.join(', ') : null
294
- }
295
-
296
- /** Trailing-newline-insensitive, matching how the Python guard counts. */
297
- function countLines(text) {
298
- if (!text) return 0
299
- return text.split('\n').length - (text.endsWith('\n') ? 1 : 0)
300
- }
301
-
302
- /**
303
- * A missing or unreadable index is not a breach: the guard's job is to stop an
304
- * oversized index, never to block work because a path could not be read. Returns the
305
- * RAW buffer — byte comparisons must use on-disk bytes (see verdict), decode at the
306
- * call sites that need text.
307
- */
308
- function readIfPossible(filePath) {
309
- try {
310
- return readFileSync(filePath)
311
- } catch {
312
- return undefined
313
- }
314
- }
315
-
316
- function positive(value, fallback) {
317
- if (!Number.isFinite(value)) return fallback
318
- const floored = Math.floor(value)
319
- return floored > 0 ? floored : fallback
320
- }
321
-
322
- /**
323
- * Normalise a path for identity comparison. `realpath` resolves symlinks and `..` so
324
- * two spellings of the same file compare equal, but it throws for a path with no file
325
- * behind it yet — and a plain `resolve` fallback is NOT interchangeable with it: an
326
- * index pinned before it exists, under a symlinked ancestor, would be keyed by its
327
- * alias at config time and by the link's target on every later call. The keys would
328
- * never match again and the guard would silently stop guarding its own index.
329
- *
330
- * So resolve the deepest ancestor that DOES exist and re-attach the missing tail:
331
- * the same file then keys identically whether or not it exists yet. Case is folded on
332
- * Windows only, mirroring `os.path.normcase` in the Python guard — folding it on Linux
333
- * would make an unrelated `memory.md` collide with the pinned index. (Known limit:
334
- * `toLowerCase` is not NTFS's exact case-folding table, same as the Python guard.)
335
- */
336
- function pathKey(p) {
337
- let head = resolve(p)
338
- const tail = []
339
- for (;;) {
340
- try {
341
- head = realpathSync(head)
342
- break
343
- } catch {
344
- const parent = dirname(head)
345
- if (parent === head) break // hit the root with nothing resolvable
346
- tail.unshift(basename(head))
347
- head = parent
348
- }
349
- }
350
- const out = tail.length ? join(head, ...tail) : head
351
- return process.platform === 'win32' ? out.toLowerCase() : out
352
- }
353
-
354
-
355
- /**
356
- * An empty or non-string indexName must fall back, not silently disable the cap:
357
- * the numeric caps already recover from nonsense values, and this field is the one
358
- * that decides whether the guard fires at all.
359
- */
360
- function indexNameOf(value) {
361
- return typeof value === 'string' && value.trim() ? value.trim() : DEFAULT_INDEX_NAME
362
- }
363
-
364
- /**
365
- * The always-on block states the discipline; this is the on-demand detail the model
366
- * pulls when it is actually about to recall, write, or sync. Kept deliberately short —
367
- * the full protocol is SKILL.md in the Engramory repo, and a skill body that has to be
368
- * read before it is useful is a skill that will not be read.
369
- */
370
- function builtinSkillBody() {
371
- return [
372
- '# Engramory — curated file-based memory',
373
- '',
374
- 'One canonical store: `MEMORY.md` is an index of pointers, one line per memory;',
375
- 'each fact lives in its own small markdown file beside it. Never put content in',
376
- 'the index, and never keep a second parallel store for handoffs. The ACTIVE',
377
- 'store is flat — the four type names are values of the `type:` field, not',
378
- 'subdirectories to create; `archive/` is the one reserved subdirectory, for',
379
- 'notes retired out of the index.',
380
- '',
381
- '## Recall',
382
- '',
383
- 'A turn, a message, or a session is NOT BY ITSELF a task: a greeting, an',
384
- 'acknowledgement, or a reaction starts none, so it gets no recall and no',
385
- 'checkpoint. A task is user-directed work whose CORRECT handling could depend',
386
- 'on what the store holds — read-only work (analysis, diagnosis, planning,',
387
- 'review)',
388
- 'counts, and changing a file is not required. HAVING THE MATERIAL IN HAND does',
389
- 'not make work a non-task: a diff pasted for review is still a task. NEVER INFER',
390
- 'THIS FROM LENGTH: a one-word reply that picks an option or carries on work',
391
- 'underway inherits that task. Still unclear? Treat it as a task.',
392
- '',
393
- 'At the start of a task, read the index and open only the notes whose hooks look',
394
- 'relevant. Treat what you recall as background that may be stale: re-verify any',
395
- 'file, flag, or version against the repo before acting on it.',
396
- '',
397
- '## Write',
398
- '',
399
- 'Before writing, confirm the fact is not already in the repo, git history, or the',
400
- 'instruction files, and that it is not a secret value. Search the index and update',
401
- 'an existing note rather than adding a near-duplicate. A new note is one atomic',
402
- 'fact with frontmatter:',
403
- '',
404
- '```markdown',
405
- '---',
406
- 'name: <kebab-case-slug>',
407
- 'description: <one sharp line — this is what future-you reads to decide to open it>',
408
- 'type: user | feedback | project | reference',
409
- 'scope: global | repo # optional: does this still hold in another repo?',
410
- 'created: YYYY-MM-DD',
411
- 'updated: YYYY-MM-DD',
412
- '---',
413
- '```',
414
- '',
415
- '`feedback` and `project` notes MUST carry a `**Why:**` line and a',
416
- '`**How to apply:**` line. Add exactly one pointer line to the index, and delete',
417
- 'memories that turn out to be wrong.',
418
- '',
419
- 'Store settled facts, never current state: "2.0 shipped on 2026-01-15" is durable;',
420
- '"the current version is X", the tip commit, or a passing test count will rot —',
421
- 'record where to read those instead.',
422
- '',
423
- 'An unfinished task may keep AT MOST ONE live `project` note holding its goal,',
424
- 'status, decisions, constraints, blockers, and next step together — the single',
425
- 'exception to one-file-one-fact, and a ceiling rather than a quota: a task that',
426
- 'needs no resumable state keeps no note. Update it IN PLACE. Never a dated',
427
- 'series (`state-2026-01-15.md`, `state-2026-01-16.md`, …), never a second',
428
- 'handoff log indexed beside it, and retire its transient state once it ends.',
429
- '',
430
- '## When a task finishes',
431
- '',
432
- 'Run one curation checkpoint. It is a judgement, not a write: promote what is',
433
- 'durable, retire the transient state the CURRENT task left on its own live',
434
- '`project` note if it has one, and when nothing is worth keeping, write',
435
- 'nothing and say so. Never append a per-turn log TO THE STORE, and never touch',
436
- 'a file just to mark it fresh — a timestamp is not a memory.',
437
- '',
438
- '## Sync',
439
- '',
440
- 'Before a deliberate compact, clear, or new thread: scan the task, dedup and update,',
441
- 'refresh project state, promote only reusable feedback, retire completed transient',
442
- 'state, then report what was added, updated, archived, and skipped.',
443
- '',
444
- '## The cap is enforced here',
445
- '',
446
- 'This host denies a write that would GROW the index past 200 lines / 25 KB. That is',
447
- 'a real refusal, not a warning — but a write that shrinks the index always passes,',
448
- 'so compact first, step by step if needed: the index is loaded every session, and',
449
- 'anything past the cap silently stops being recalled.',
450
- '',
451
- 'Never write credentials, keys, tokens, or cookies into memory — record only where',
452
- 'the secret lives.',
453
- ].join('\n')
454
- }
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
+ }