@chenhw7/dsh-memory 0.5.1 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.i18n.yaml +2 -0
  2. package/README.md +24 -15
  3. package/{README.zh-CN.md → README.zh.md} +22 -14
  4. package/cordis.patch.yml +10 -4
  5. package/lib/benchmark/index.d.ts +24 -7
  6. package/lib/benchmark/index.d.ts.map +1 -1
  7. package/lib/benchmark/index.js +55 -7
  8. package/lib/benchmark/index.js.map +1 -1
  9. package/lib/client/index.js +47 -31
  10. package/lib/context/conflict.d.ts +23 -10
  11. package/lib/context/conflict.d.ts.map +1 -1
  12. package/lib/context/conflict.js +59 -20
  13. package/lib/context/conflict.js.map +1 -1
  14. package/lib/context/index.d.ts +2 -6
  15. package/lib/context/index.d.ts.map +1 -1
  16. package/lib/context/index.js +29 -25
  17. package/lib/context/index.js.map +1 -1
  18. package/lib/context/policy.d.ts +17 -5
  19. package/lib/context/policy.d.ts.map +1 -1
  20. package/lib/context/policy.js +27 -9
  21. package/lib/context/policy.js.map +1 -1
  22. package/lib/index.d.ts +23 -1
  23. package/lib/index.d.ts.map +1 -1
  24. package/lib/index.js +20 -0
  25. package/lib/index.js.map +1 -1
  26. package/lib/notes/cleanup.d.ts +48 -0
  27. package/lib/notes/cleanup.d.ts.map +1 -0
  28. package/lib/notes/cleanup.js +98 -0
  29. package/lib/notes/cleanup.js.map +1 -0
  30. package/lib/notes/index.d.ts +23 -23
  31. package/lib/notes/index.d.ts.map +1 -1
  32. package/lib/notes/index.js +38 -131
  33. package/lib/notes/index.js.map +1 -1
  34. package/lib/notes/render.d.ts +13 -13
  35. package/lib/notes/render.d.ts.map +1 -1
  36. package/lib/notes/render.js +13 -13
  37. package/lib/notes/render.js.map +1 -1
  38. package/lib/notes/scope.d.ts +11 -10
  39. package/lib/notes/scope.d.ts.map +1 -1
  40. package/lib/notes/scope.js +11 -10
  41. package/lib/notes/scope.js.map +1 -1
  42. package/lib/notes/settings.d.ts +9 -20
  43. package/lib/notes/settings.d.ts.map +1 -1
  44. package/lib/notes/settings.js +9 -27
  45. package/lib/notes/settings.js.map +1 -1
  46. package/lib/remote/index.d.ts +67 -6
  47. package/lib/remote/index.d.ts.map +1 -1
  48. package/lib/remote/index.js +94 -9
  49. package/lib/remote/index.js.map +1 -1
  50. package/lib/remote/typert.remote-client.d.ts +8 -1
  51. package/lib/remote/typert.remote-client.js +6 -0
  52. package/lib/remote/types.d.ts +1 -1
  53. package/lib/remote/types.d.ts.map +1 -1
  54. package/lib/review/accumulator.d.ts +5 -5
  55. package/lib/review/accumulator.d.ts.map +1 -1
  56. package/lib/review/accumulator.js +3 -3
  57. package/lib/review/accumulator.js.map +1 -1
  58. package/lib/review/dedup.d.ts +23 -15
  59. package/lib/review/dedup.d.ts.map +1 -1
  60. package/lib/review/dedup.js +34 -83
  61. package/lib/review/dedup.js.map +1 -1
  62. package/lib/review/extract.d.ts.map +1 -1
  63. package/lib/review/extract.js +5 -2
  64. package/lib/review/extract.js.map +1 -1
  65. package/lib/review/index.d.ts.map +1 -1
  66. package/lib/review/index.js +28 -21
  67. package/lib/review/index.js.map +1 -1
  68. package/lib/scanner.d.ts +2 -0
  69. package/lib/scanner.d.ts.map +1 -1
  70. package/lib/scanner.js +22 -0
  71. package/lib/scanner.js.map +1 -1
  72. package/lib/store/bm25.d.ts +75 -1
  73. package/lib/store/bm25.d.ts.map +1 -1
  74. package/lib/store/bm25.js +162 -17
  75. package/lib/store/bm25.js.map +1 -1
  76. package/lib/store/cross-process.d.ts +155 -0
  77. package/lib/store/cross-process.d.ts.map +1 -0
  78. package/lib/store/cross-process.js +254 -0
  79. package/lib/store/cross-process.js.map +1 -0
  80. package/lib/store/index.d.ts +89 -7
  81. package/lib/store/index.d.ts.map +1 -1
  82. package/lib/store/index.js +466 -89
  83. package/lib/store/index.js.map +1 -1
  84. package/lib/tool/index.d.ts +17 -5
  85. package/lib/tool/index.d.ts.map +1 -1
  86. package/lib/tool/index.js +237 -24
  87. package/lib/tool/index.js.map +1 -1
  88. package/lib/types.d.ts +31 -2
  89. package/lib/types.d.ts.map +1 -1
  90. package/package.json +40 -31
  91. package/lib/notes/writer.d.ts +0 -65
  92. package/lib/notes/writer.d.ts.map +0 -1
  93. package/lib/notes/writer.js +0 -131
  94. package/lib/notes/writer.js.map +0 -1
@@ -11,82 +11,121 @@
11
11
  * @module @chenhw7/dsh-memory/store
12
12
  */
13
13
  import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
14
- import { z } from 'zod';
14
+ import z from '@deepseek-ai/schemastery';
15
+ import { z as zod } from 'zod';
15
16
  import { MemoryStore, MemoryId, AuditId, SuggestionId, scanContent, validateProjectScope, validateContent } from '../index.js';
16
- import { Bm25Index, tokenizeForSearch } from './bm25.js';
17
- import { jaccardSimilarity, tokenize } from '../review/dedup.js';
17
+ import { Bm25Index, tokenizeForSearch, buildCorpusStats, buildCorpusStatsFromTokens, uniqueTokens, weightedOverlapSimilarity } from './bm25.js';
18
+ import { CrossProcessGuard, DEFAULT_CROSS_PROCESS_PROBE_MS, EMPTY_OWNER, currentBootOwner, mediumOwnerReader, mediumGoodbyeWriter, ownerStampSchema, } from './cross-process.js';
18
19
  /** Zod schema for one memory entry record on the durable medium. */
19
- const memoryEntrySchema = z.object({
20
- id: z.string().min(1),
21
- scope: z.enum(['global', 'project', 'user']),
22
- category: z.enum(['failure', 'correction', 'insight', 'preference', 'convention', 'tool-quirk', 'procedure']).optional(),
23
- content: z.string(),
24
- summary: z.string().optional(),
25
- projectName: z.string().optional(),
26
- createdAt: z.number(),
27
- updatedAt: z.number(),
28
- pinned: z.boolean().optional(),
29
- lastRecalledAt: z.number().optional(),
30
- staleSince: z.number().optional(),
20
+ const memoryEntrySchema = zod.object({
21
+ id: zod.string().min(1),
22
+ scope: zod.enum(['global', 'project', 'user']),
23
+ category: zod.enum(['failure', 'correction', 'insight', 'preference', 'convention', 'tool-quirk', 'procedure']).optional(),
24
+ content: zod.string(),
25
+ summary: zod.string().optional(),
26
+ projectName: zod.string().optional(),
27
+ createdAt: zod.number(),
28
+ updatedAt: zod.number(),
29
+ pinned: zod.boolean().optional(),
30
+ lastRecalledAt: zod.number().optional(),
31
+ staleSince: zod.number().optional(),
32
+ accessCount: zod.number().optional(),
33
+ importance: zod.number().optional(),
31
34
  });
32
35
  /** Zod schema for one audit-record entry on the durable medium. */
33
- const auditEntrySchema = z.object({
34
- id: z.string().min(1),
35
- op: z.enum(['add', 'update', 'remove']),
36
- entryId: z.string().min(1),
37
- scope: z.enum(['global', 'project', 'user']),
38
- category: z.enum(['failure', 'correction', 'insight', 'preference', 'convention', 'tool-quirk', 'procedure']).optional(),
39
- source: z.enum(['tool', 'review', 'flush', 'ui', 'janitor']),
40
- sessionId: z.string().optional(),
41
- ts: z.number(),
42
- seq: z.number().optional(),
43
- contentPreview: z.string(),
36
+ const auditEntrySchema = zod.object({
37
+ id: zod.string().min(1),
38
+ op: zod.enum(['add', 'update', 'remove', 'readRaw']),
39
+ entryId: zod.string().min(1),
40
+ scope: zod.enum(['global', 'project', 'user']),
41
+ category: zod.enum(['failure', 'correction', 'insight', 'preference', 'convention', 'tool-quirk', 'procedure']).optional(),
42
+ source: zod.enum(['tool', 'review', 'flush', 'ui', 'janitor']),
43
+ sessionId: zod.string().optional(),
44
+ ts: zod.number(),
45
+ seq: zod.number().optional(),
46
+ contentPreview: zod.string(),
44
47
  });
45
48
  /** Zod schema for one pending suggestion in the human-review queue (P1-1). */
46
- const suggestionSchema = z.object({
47
- id: z.string().min(1),
48
- scope: z.enum(['global', 'project', 'user']),
49
- category: z.enum(['failure', 'correction', 'insight', 'preference', 'convention', 'tool-quirk', 'procedure']).optional(),
50
- content: z.string(),
51
- summary: z.string().optional(),
52
- projectName: z.string().optional(),
53
- hits: z.number(),
54
- firstSeenAt: z.number(),
55
- lastSeenAt: z.number(),
56
- targetEntryId: z.string().optional(),
57
- source: z.enum(['tool', 'review', 'flush', 'ui', 'janitor']),
58
- sessionId: z.string().optional(),
49
+ const suggestionSchema = zod.object({
50
+ id: zod.string().min(1),
51
+ scope: zod.enum(['global', 'project', 'user']),
52
+ category: zod.enum(['failure', 'correction', 'insight', 'preference', 'convention', 'tool-quirk', 'procedure']).optional(),
53
+ content: zod.string(),
54
+ summary: zod.string().optional(),
55
+ projectName: zod.string().optional(),
56
+ hits: zod.number(),
57
+ firstSeenAt: zod.number(),
58
+ lastSeenAt: zod.number(),
59
+ targetEntryId: zod.string().optional(),
60
+ source: zod.enum(['tool', 'review', 'flush', 'ui', 'janitor']),
61
+ sessionId: zod.string().optional(),
59
62
  });
60
63
  /**
61
64
  * The memory domain spec: `entries` (memory records keyed by id) plus `audit`
62
- * (mutation audit trail) plus `suggestions` (P1-1 pending-review queue).
63
- * Domain version stays at 0 — both later tables are forward-compatible
64
- * additions: storage-json reads only declared tables and initializes any
65
- * absent table as an empty map, so existing v0 media reopen without migration.
65
+ * (mutation audit trail) plus `suggestions` (P1-1 pending-review queue), plus
66
+ * a global singleton carrying the single-writer owner stamp (P3
67
+ * cross-process detection). Domain version stays at 0 — all three later
68
+ * additions are forward-compatible: storage-json reads only declared tables
69
+ * and initializes any absent table as an empty map, and a medium whose global
70
+ * slot was never written reads as `null`, which the domain replaces with the
71
+ * spec's `initial` without materializing it, so existing v0 media reopen
72
+ * without migration.
73
+ *
74
+ * The stamp schema accepts extra keys on purpose (`looseObject`): the medium
75
+ * holds the global as opaque JSON, and a future extension of the stamp shape
76
+ * must reopen cleanly on today's readers.
66
77
  */
67
78
  const memoryDomainSpec = defineDomain({
68
79
  name: 'memory',
69
80
  version: 0,
81
+ global: {
82
+ schema: ownerStampSchema,
83
+ initial: EMPTY_OWNER,
84
+ },
70
85
  tables: {
71
86
  entries: domainTable(memoryEntrySchema),
72
87
  audit: domainTable(auditEntrySchema),
73
88
  suggestions: domainTable(suggestionSchema),
74
89
  },
75
90
  });
76
- /** Maximum audit records retained; oldest are trimmed on overflow. */
91
+ /**
92
+ * Maximum audit records retained; oldest are trimmed on overflow. Protocol
93
+ * default like {@link DEFAULT_ENTRIES_CAP}: settable per deployment through
94
+ * the `config:` entry on the `memory-store` composition row.
95
+ */
77
96
  const DEFAULT_AUDIT_CAP = 200;
97
+ /**
98
+ * Maximum memory entries retained in the `entries` table. Write paths
99
+ * (`add`, and `adoptSuggestion`'s new-entry path which delegates to `add`)
100
+ * trim back to this cap after a successful write, evicting by use signal.
101
+ *
102
+ * Why 500: the durable medium is one JSON file — it tolerates thousands of
103
+ * entries before size/migration pressure becomes real — so the cap only has
104
+ * to bound runaway extraction, not normal growth. 200 (the audit/suggestion
105
+ * cap precedent) would evict healthy, actively-recalled stores; the
106
+ * recall-golden fixture (24 entries) and integration suites sit far below it.
107
+ *
108
+ * Soft cap: entries that survive eviction (pinned, or high `accessCount`)
109
+ * may push the table past the cap; eviction never runs when every remaining
110
+ * candidate is protected. Settable per deployment through the `config:`
111
+ * entry on the `memory-store` composition row.
112
+ */
113
+ const DEFAULT_ENTRIES_CAP = 500;
78
114
  /**
79
115
  * Maximum pending suggestions retained (P1-1). Overflow evicts the
80
116
  * lowest-signal rows first: fewest hits, then oldest `lastSeenAt`.
81
117
  */
82
118
  const DEFAULT_SUGGESTION_CAP = 200;
83
119
  /**
84
- * Jaccard similarity above which two same-scope proposals count as the same
85
- * suggestion (re-observation, not a new row). Matches the entry-dedup
86
- * prefilter threshold so "the model keeps proposing X" and "X is already
87
- * stored" draw the same near-duplicate line.
120
+ * IDF-weighted overlap above which two same-scope proposals count as the
121
+ * same suggestion (re-observation, not a new row). Sits below the entry-dedup
122
+ * prefilter line (DEDUP_SIMILARITY_THRESHOLD, 0.15) so a proposal is never
123
+ * silently dropped on this signal alone, while "the model keeps proposing X"
124
+ * still accumulates `hits` on one row instead of flooding the queue. The
125
+ * metric is the shared {@link ../store/bm25.ts weightedOverlapSimilarity}
126
+ * measured over the live queue as corpus.
88
127
  */
89
- const SUGGESTION_DUP_THRESHOLD = 0.15;
128
+ const SUGGESTION_DUP_THRESHOLD = 0.3;
90
129
  /**
91
130
  * Deterministic audit ordering: newest/oldest by `ts`, ties broken by the
92
131
  * monotonic append `seq`, then by id for records written before `seq` existed.
@@ -102,20 +141,132 @@ function compareAuditAsc(a, b) {
102
141
  }
103
142
  /** Cordis plugin name. */
104
143
  export const name = 'memory-store-domain';
144
+ /**
145
+ * Fraction of {@link StoreConfig.entriesCap} at or beyond which the startup
146
+ * selfcheck warns that the store is approaching the single-JSON-medium
147
+ * migration threshold (scale-trigger-selfcheck): it detects "close to the
148
+ * cap" where the cap's own eviction only acts at "past the cap". File-size
149
+ * and multi-process concerns are deliberately not re-checked here — the file
150
+ * size is derived from the same entry count, and cross-process detection
151
+ * (cross-process-detect) already owns the concurrent-writer warning.
152
+ */
153
+ const SCALE_SELFCHECK_FRACTION = 0.8;
105
154
  /** Services required before this provider can mount. */
106
155
  export const inject = ['storageDomain'];
156
+ /** Schemastery configuration for the `memory-store` composition row. */
157
+ export const Config = z.object({
158
+ entriesCap: z.number().step(1).min(1).default(DEFAULT_ENTRIES_CAP),
159
+ crossProcessProbeMs: z.number().step(1).min(0).default(DEFAULT_CROSS_PROCESS_PROBE_MS),
160
+ });
107
161
  /**
108
162
  * Mount the storage-domain memory store provider. Opens the `memory` domain
109
- * and registers a {@link MemoryStore} subclass on `ctx.memory`.
163
+ * and registers a {@link MemoryStore} subclass on `ctx.memory`. On open, a
164
+ * {@link CrossProcessGuard} claims the medium's owner stamp (the domain's
165
+ * global slot) and starts the configured read-back probe; the dispose path
166
+ * stamps `closedAt` so the next boot does not warn about this one.
110
167
  * @param ctx - Cordis context with `storageDomain` injected.
168
+ * @param config - row config; `entriesCap` and `crossProcessProbeMs` are read here.
111
169
  */
112
- export async function apply(ctx) {
170
+ export async function apply(ctx, config = { entriesCap: DEFAULT_ENTRIES_CAP, crossProcessProbeMs: DEFAULT_CROSS_PROCESS_PROBE_MS }) {
113
171
  const domain = await ctx.storageDomain.open(memoryDomainSpec);
114
172
  const entries = domain.table('entries');
115
173
  const audit = domain.table('audit');
116
174
  const suggestions = domain.table('suggestions');
117
- ctx.effect(() => async () => { await domain.close(); });
118
- ctx.provide('memory', new DomainMemoryStore(entries, audit, suggestions));
175
+ // Cross-process single-writer detection (host storage-json is
176
+ // last-writer-wins across processes, silently): claim the medium's owner
177
+ // stamp at open, re-read it on a lightweight interval, stamp `closedAt` on
178
+ // dispose. The medium path comes from the harness-home resolver the boot
179
+ // provides to composition `!!js` expressions; when absent (unit tests,
180
+ // exotic hosts) the medium read-back seam is undefined and only the
181
+ // in-memory startup judgment + goodbye stamps run.
182
+ // One boot identity per mount, shared by the claim and the goodbye: a
183
+ // second `currentBootOwner()` would mint a fresh random bootId that the
184
+ // goodbye writer would (correctly) refuse to stamp.
185
+ const own = currentBootOwner();
186
+ const mediumReader = resolveMediumReader(ctx);
187
+ const mediumGoodbye = resolveMediumGoodbye(ctx, own.bootId);
188
+ const store = new DomainMemoryStore(entries, audit, suggestions, DEFAULT_AUDIT_CAP, DEFAULT_SUGGESTION_CAP, ctx.logger, config.entriesCap);
189
+ const guard = new CrossProcessGuard(own, mediumReader, owner => domain.global.set(owner), (site, error) => store.reportFailure(site, error), undefined, mediumGoodbye);
190
+ try {
191
+ // Startup judgment + claim: judge the open-time global (loaded from the
192
+ // medium), then stamp this boot as owner so later starters see us. A
193
+ // failed claim cannot run detection, but the store itself may still be
194
+ // usable — fail loud in the log, keep mounting.
195
+ await guard.startup(domain.global.get());
196
+ }
197
+ catch (error) {
198
+ // Detection is a background safety net, not the write path: an unwritable
199
+ // global slot degrades to no cross-process visibility, so the mount
200
+ // continues and only this warn marks the gap.
201
+ ctx.logger.warn(`dsh-memory: cross-process owner claim failed: ${String(error)}`);
202
+ }
203
+ ctx.effect(() => {
204
+ // The cordis-plugin-timer mixin is not a dependency of this package, so
205
+ // the probe uses the platform interval directly — registered inside the
206
+ // effect so the disposer below clears it on stop/update/undefine.
207
+ const probeTimer = config.crossProcessProbeMs > 0
208
+ ? setInterval(() => { void guard.probe(); }, config.crossProcessProbeMs)
209
+ : undefined;
210
+ return async () => {
211
+ if (probeTimer !== undefined)
212
+ clearInterval(probeTimer);
213
+ await guard.sayGoodbye();
214
+ await domain.close();
215
+ };
216
+ });
217
+ ctx.provide('memory', store);
218
+ }
219
+ /**
220
+ * Resolve the unit-file read seam for cross-process detection from the
221
+ * harness-home path resolver the boot exposes to `!!js` config expressions.
222
+ * Compositions derive the storage root from the same service, so the
223
+ * resolution agrees with where storage-json actually writes. Returns
224
+ * `undefined` when the service is absent.
225
+ * @param ctx - Cordis context that may carry `dshHomePath`.
226
+ * @returns an async medium reader, or `undefined` when unresolvable.
227
+ */
228
+ function resolveMediumReader(ctx) {
229
+ const homePath = ctx.get('dshHomePath');
230
+ if (typeof homePath !== 'function')
231
+ return undefined;
232
+ return mediumOwnerReader(homePath('storages', 'memory.json'));
233
+ }
234
+ /**
235
+ * Resolve the direct medium-file goodbye writer (same derivation as
236
+ * {@link resolveMediumReader}). The goodbye must not go through the domain's
237
+ * global slot: the storage facility's own unmount closes the domain
238
+ * concurrently with our disposer, so the domain write rejects with `closed`
239
+ * most dispose runs — the medium file is the only teardown-valid seam.
240
+ * @param ctx - Cordis context that may carry `dshHomePath`.
241
+ * @param bootId - This mount's boot identity, matching the claim the guard writes.
242
+ * @returns an async goodbye writer, or `undefined` when unresolvable.
243
+ */
244
+ function resolveMediumGoodbye(ctx, bootId) {
245
+ const homePath = ctx.get('dshHomePath');
246
+ if (typeof homePath !== 'function')
247
+ return undefined;
248
+ return mediumGoodbyeWriter(homePath('storages', 'memory.json'), bootId);
249
+ }
250
+ /**
251
+ * Token bags per entry: content tokens plus — when the entry carries a
252
+ * summary — the summary's tokens. Merging both fields into ONE bag (summary
253
+ * tokens simply repeat into tf) is the deliberately simple stand-in for
254
+ * BM25F: summary is a human-written high-signal distillation, so its terms
255
+ * earning the same tf boost as content terms IS the desired emphasis, and a
256
+ * matched summary keyword pushes an entry above content-only competitors.
257
+ * Explicit BM25F (per-field lengths + b-field + weight w_f) was considered
258
+ * and rejected for now: it adds per-field length bookkeeping and a weight
259
+ * tunable (against the "no hardcoded tunables" rule, another Config field)
260
+ * for a gain this merged bag already captures at fixture scale; revisit if
261
+ * the floors slip with real-corpus summaries. Empty-string summaries count
262
+ * as absent (add() already refuses to store them, but direct table seeds
263
+ * can still carry `summary: ''`).
264
+ */
265
+ function entryIndexTokens(entry) {
266
+ const contentTokens = tokenizeForSearch(entry.content);
267
+ return entry.summary === undefined || entry.summary === ''
268
+ ? contentTokens
269
+ : [...contentTokens, ...tokenizeForSearch(entry.summary)];
119
270
  }
120
271
  /**
121
272
  * MemoryStore implementation backed by a storage-domain KV table. Reads are
@@ -129,15 +280,49 @@ export class DomainMemoryStore extends MemoryStore {
129
280
  suggestions;
130
281
  auditCap;
131
282
  suggestionCap;
283
+ entriesCap;
284
+ /** Warn channel for swallowed background-path failures; the host `ctx.logger`. */
285
+ failureLogger;
286
+ /** Per-site counts of swallowed failures, surfaced through `health()`. */
287
+ failureCounts = new Map();
132
288
  /** Last audit `seq` handed out; lazily initialized from the medium on first append. */
133
289
  auditSeq;
134
- constructor(entries, audit, suggestions, auditCap = DEFAULT_AUDIT_CAP, suggestionCap = DEFAULT_SUGGESTION_CAP) {
290
+ constructor(entries, audit, suggestions, auditCap = DEFAULT_AUDIT_CAP, suggestionCap = DEFAULT_SUGGESTION_CAP, failureLogger, entriesCap = DEFAULT_ENTRIES_CAP) {
135
291
  super();
136
292
  this.entries = entries;
137
293
  this.audit = audit;
138
294
  this.suggestions = suggestions;
139
295
  this.auditCap = auditCap;
140
296
  this.suggestionCap = suggestionCap;
297
+ this.entriesCap = entriesCap;
298
+ this.failureLogger = failureLogger;
299
+ // Startup selfcheck (scale-trigger-selfcheck): judge the entry count the
300
+ // medium opened with, once per construction. Deployments that reopen an
301
+ // already-large medium see the warning at boot — the point where a
302
+ // migration decision (per-record/SQLite backing) is still cheap — instead
303
+ // of first learning about the size from an eviction storm.
304
+ this.selfcheckScale();
305
+ }
306
+ /**
307
+ * One-time startup scale judgment. Fires a warn when the entry count
308
+ * loaded from the medium already sits at or above
309
+ * {@link SCALE_SELFCHECK_FRACTION} of {@link entriesCap}. The warn carries
310
+ * the concrete numbers and the documented migration threshold, and goes
311
+ * through the same best-effort logger channel as every background-path
312
+ * failure — a missing logger (unit tests, headless constructions) stays
313
+ * silent rather than throwing out of the constructor.
314
+ */
315
+ selfcheckScale() {
316
+ if (this.entries.size < this.entriesCap * SCALE_SELFCHECK_FRACTION)
317
+ return;
318
+ this.failureLogger?.warn(`dsh-memory: entries table holds ${this.entries.size} of ${this.entriesCap} `
319
+ + `allowed entries (≥ ${SCALE_SELFCHECK_FRACTION}× cap) — approaching the `
320
+ + 'single-JSON-medium scale ceiling; consider migrating to per-record or '
321
+ + 'SQLite backing (see the improvement program\'s scale-trigger-selfcheck entry)');
322
+ }
323
+ reportFailure(site, error) {
324
+ this.failureCounts.set(site, (this.failureCounts.get(site) ?? 0) + 1);
325
+ this.failureLogger?.warn(`dsh-memory: ${site} failed${error === undefined ? '' : `: ${String(error)}`}`);
141
326
  }
142
327
  /** Next monotonic audit sequence number (survives reopen via the medium). */
143
328
  nextAuditSeq() {
@@ -157,6 +342,10 @@ export class DomainMemoryStore extends MemoryStore {
157
342
  if (!scan.allowed) {
158
343
  throw new Error(`memory content rejected by scanner: ${scan.reasons.join('; ')}`);
159
344
  }
345
+ const summaryScan = scanContent(input.summary ?? '');
346
+ if (!summaryScan.allowed) {
347
+ throw new Error(`memory summary rejected by scanner: ${summaryScan.reasons.join('; ')}`);
348
+ }
160
349
  const now = Date.now();
161
350
  const id = MemoryId();
162
351
  const entry = {
@@ -168,9 +357,13 @@ export class DomainMemoryStore extends MemoryStore {
168
357
  projectName: input.projectName,
169
358
  createdAt: now,
170
359
  updatedAt: now,
360
+ ...clampImportance(input.importance),
171
361
  };
172
362
  await this.entries.put(id, entry);
173
363
  await this.appendAudit('add', id, entry, input.source, input.sessionId);
364
+ // Both new-entry write paths land here (adoptSuggestion's new-entry branch
365
+ // delegates to add), so the cap is enforced at this one chokepoint.
366
+ await this.trimEntries();
174
367
  return { entry };
175
368
  }
176
369
  get(id) {
@@ -197,6 +390,12 @@ export class DomainMemoryStore extends MemoryStore {
197
390
  if (!scan.allowed) {
198
391
  throw new Error(`memory content rejected by scanner: ${scan.reasons.join('; ')}`);
199
392
  }
393
+ // Scans only what this call writes: an entry stored before summary scanning
394
+ // existed stays updatable, so its summary can still be repaired or cleared.
395
+ const summaryScan = scanContent(input.summary ?? '');
396
+ if (!summaryScan.allowed) {
397
+ throw new Error(`memory summary rejected by scanner: ${summaryScan.reasons.join('; ')}`);
398
+ }
200
399
  // summary semantics: `undefined` = keep existing; `''` = explicitly clear;
201
400
  // a non-empty string = replace. Build the updated entry accordingly.
202
401
  const base = {
@@ -204,6 +403,9 @@ export class DomainMemoryStore extends MemoryStore {
204
403
  content: newContent,
205
404
  category: input.category ?? existing.category,
206
405
  updatedAt: Date.now(),
406
+ // Only rewrite the field when the caller supplies one; `undefined`
407
+ // keeps the stored importance (add-time assessment stands).
408
+ ...clampImportance(input.importance),
207
409
  };
208
410
  const updated = input.summary === ''
209
411
  ? (() => { const { summary: _c, ...rest } = base; return rest; })()
@@ -243,7 +445,16 @@ export class DomainMemoryStore extends MemoryStore {
243
445
  // BM25 over the filtered set: relevance-weighted (IDF × saturation),
244
446
  // CJK bigrams for word-level Chinese precision. OR semantics preserved —
245
447
  // any shared term scores above zero and keeps the document in play.
246
- const index = new Bm25Index(candidates.map(entry => tokenizeForSearch(entry.content)));
448
+ // The df table is built over the FULL corpus (every entry), not the
449
+ // filtered set: with a 3-entry candidate pool a per-pool df lets a pure
450
+ // function word present in 2 of 3 candidates earn the same IDF as a
451
+ // genuinely distinctive term, and the resulting noise reorders results.
452
+ // Full-corpus stats cost one tokenize pass over all entries per search
453
+ // — the same order as the candidate-set tokenization itself. Both
454
+ // corpus and index see the SAME merged content+summary bag, so df and
455
+ // tf stay consistent.
456
+ const corpus = buildCorpusStatsFromTokens([...this.entries.entries()].map(([, entry]) => entryIndexTokens(entry)));
457
+ const index = new Bm25Index(candidates.map(entry => entryIndexTokens(entry)), corpus);
247
458
  const scores = index.scores(queryTokens);
248
459
  ranked = [];
249
460
  candidates.forEach((entry, i) => {
@@ -255,11 +466,18 @@ export class DomainMemoryStore extends MemoryStore {
255
466
  else {
256
467
  ranked = candidates.map(entry => ({ entry, score: 0 }));
257
468
  }
258
- // Rank by BM25 relevance (desc), then pinned entries (desc), then by
259
- // recency (updatedAt desc). Pinned entries surface early even among
260
- // equal-relevance matches — pin means "the user wants this remembered".
469
+ // Rank by BM25 relevance (desc), then pinned entries (desc), then the
470
+ // model-assessed importance (desc; absent reads as mid-range so unassessed
471
+ // entries are not penalized), then by recency (updatedAt desc). Pinned
472
+ // entries surface early even among equal-relevance matches — pin means
473
+ // "the user wants this remembered"; importance is the model's weaker,
474
+ // optional version of the same judgment.
261
475
  const pinOf = (entry) => entry.pinned === true ? 1 : 0;
262
- ranked.sort((a, b) => b.score - a.score || pinOf(b.entry) - pinOf(a.entry) || b.entry.updatedAt - a.entry.updatedAt);
476
+ const importanceOf = (entry) => entry.importance ?? 0;
477
+ ranked.sort((a, b) => b.score - a.score
478
+ || pinOf(b.entry) - pinOf(a.entry)
479
+ || importanceOf(b.entry) - importanceOf(a.entry)
480
+ || b.entry.updatedAt - a.entry.updatedAt);
263
481
  let all = ranked.map(r => r.entry);
264
482
  const total = all.length;
265
483
  all = limit > 0 ? all.slice(0, limit) : all;
@@ -268,23 +486,50 @@ export class DomainMemoryStore extends MemoryStore {
268
486
  // Read-only consumers (management UI) opt out via recordRecall: false —
269
487
  // merely viewing entries must not rewrite their recall metadata.
270
488
  if (query.recordRecall !== false)
271
- void this.stampRecalled(all);
489
+ void this.stampRecalled(all.map(entry => entry.id));
272
490
  return { entries: all, total };
273
491
  }
274
492
  /**
275
- * Stamp entries with a recall timestamp (fire-and-forget). Updates
276
- * `lastRecalledAt` on each entry so the janitor can track staleness.
277
- * `updatedAt` is intentionally left untouched: recalling is not mutating.
493
+ * Stamp entries with a recall timestamp (fire-and-forget). Each entry is
494
+ * stamped through the table's atomic read-modify-write, so the transform
495
+ * reads the record current at its write-chain slot — a concurrent
496
+ * `memory_replace` that lands first is never rolled back by the stamp, and
497
+ * the stamp never rolls one back. One stamp pass enqueues one job per
498
+ * changed entry; entries already carrying this pass's timestamp and no
499
+ * decay stamp are skipped without touching the chain. `updatedAt` is
500
+ * intentionally left untouched: recalling is not mutating.
501
+ * @param ids - the ids of the entries the caller surfaced to the model.
278
502
  */
279
- async stampRecalled(entries) {
503
+ async stampRecalled(ids) {
280
504
  const now = Date.now();
281
- for (const entry of entries) {
282
- // Recall proves usefulness: it refreshes lastRecalledAt AND clears a
283
- // soft-decay stamp, bringing the entry back into injection surfaces.
284
- if (entry.lastRecalledAt === now && entry.staleSince === undefined)
505
+ for (const id of ids) {
506
+ // Cheap pre-check on the synchronous snapshot: a stamp pass that would
507
+ // change nothing skips the queue entirely (the common repeat-search case).
508
+ const snapshot = this.entries.get(id);
509
+ if (snapshot?.lastRecalledAt === now && snapshot.staleSince === undefined)
285
510
  continue;
286
- const { staleSince: _cleared, ...rest } = entry;
287
- await this.entries.put(entry.id, { ...rest, lastRecalledAt: now });
511
+ try {
512
+ // The atomic RMW re-reads at the chain slot, so a content edit that
513
+ // landed between search and stamp survives in the written record.
514
+ await this.entries.update(id, current => {
515
+ if (current.lastRecalledAt === now && current.staleSince === undefined)
516
+ return current;
517
+ const { staleSince: _cleared, ...rest } = current;
518
+ return {
519
+ ...rest,
520
+ lastRecalledAt: now,
521
+ accessCount: (rest.accessCount ?? 0) + 1,
522
+ };
523
+ });
524
+ }
525
+ catch (error) {
526
+ // A missing id (entry removed between search and stamp) or a domain
527
+ // going away mid-pass is a normal end-of-life for a stamp, not a
528
+ // failure to report.
529
+ if (error instanceof Error && !error.message.includes('no record')) {
530
+ this.reportFailure('recall-stamp', error);
531
+ }
532
+ }
288
533
  }
289
534
  }
290
535
  /**
@@ -296,7 +541,7 @@ export class DomainMemoryStore extends MemoryStore {
296
541
  markRecalled(ids) {
297
542
  if (ids.length === 0)
298
543
  return;
299
- void this.stampRecalled(ids.map(id => this.entries.get(id)).filter((e) => e !== undefined));
544
+ void this.stampRecalled(ids.filter(id => this.entries.get(id) !== undefined));
300
545
  }
301
546
  // ─── Suggestion queue (P1-1 optional human-confirm mode) ──────────────────
302
547
  /**
@@ -311,7 +556,7 @@ export class DomainMemoryStore extends MemoryStore {
311
556
  * `hits: 1`.
312
557
  * @param input - the proposal to record.
313
558
  * @returns the stored suggestion (existing row updated, or newly created).
314
- * @throws when the proposed content fails validation or the scanner.
559
+ * @throws when the proposed content or summary fails validation or the scanner.
315
560
  */
316
561
  async observeSuggestion(input) {
317
562
  validateProjectScope({ ...input, projectName: input.projectName ?? (input.targetEntryId !== undefined ? this.entries.get(input.targetEntryId)?.projectName : undefined) });
@@ -320,9 +565,13 @@ export class DomainMemoryStore extends MemoryStore {
320
565
  if (!scan.allowed) {
321
566
  throw new Error(`suggestion content rejected by scanner: ${scan.reasons.join('; ')}`);
322
567
  }
568
+ const summaryScan = scanContent(input.summary ?? '');
569
+ if (!summaryScan.allowed) {
570
+ throw new Error(`suggestion summary rejected by scanner: ${summaryScan.reasons.join('; ')}`);
571
+ }
323
572
  const now = Date.now();
324
573
  // Match against existing proposals: same target entry wins outright;
325
- // otherwise nearest-content in the same scope above the dedup threshold.
574
+ // otherwise nearest-content in the same scope above the dup threshold.
326
575
  let matched;
327
576
  for (const [, suggestion] of this.suggestions.entries()) {
328
577
  if (input.targetEntryId !== undefined) {
@@ -334,7 +583,11 @@ export class DomainMemoryStore extends MemoryStore {
334
583
  }
335
584
  if (suggestion.scope !== input.scope)
336
585
  continue;
337
- const similarity = jaccardSimilarity(tokenize(input.content), tokenize(suggestion.content));
586
+ // The live queue is the corpus: at queue scale (≤ cap rows) rebuilding
587
+ // the df table per row would be wasteful, but the queue is tiny — and
588
+ // the table only needs building once per observe call, not per row.
589
+ const stats = buildCorpusStats([input.content, suggestion.content]);
590
+ const similarity = weightedOverlapSimilarity(stats, uniqueTokens(input.content), uniqueTokens(suggestion.content));
338
591
  if (similarity > SUGGESTION_DUP_THRESHOLD) {
339
592
  matched = suggestion;
340
593
  break;
@@ -454,6 +707,47 @@ export class DomainMemoryStore extends MemoryStore {
454
707
  await this.suggestions.delete(all[i].id);
455
708
  }
456
709
  }
710
+ /**
711
+ * Trim the entries table to {@link DEFAULT_ENTRIES_CAP} / the configured
712
+ * `entriesCap` after a successful write. Awaited inline like
713
+ * {@link trimSuggestions} (not failure-shielded like {@link trimAudit}):
714
+ * an eviction failure propagates to the add caller even though the added
715
+ * row landed. Eviction runs in one pass down TO the cap (not one per add),
716
+ * ordered by the use signal — pinned entries are exempt; the rest go by
717
+ * ascending `accessCount` (never-recalled reads as 0), then ascending
718
+ * `lastRecalledAt` ?? `createdAt` (longest-unrecalled first). When every
719
+ * remaining candidate is protected (e.g. all pinned), the table is allowed
720
+ * to exceed the cap — the cap is a soft target, eviction never deletes a
721
+ * protected entry to reach it.
722
+ *
723
+ * Audit trail: the eviction records `op: 'remove'`, `source: 'janitor'`.
724
+ * The janitor source names system-initiated lifecycle writes (decay,
725
+ * dormancy), and `AuditSource` is a fixed schema enum — extending it would
726
+ * change the durable record shape — so the store's own eviction reuses it.
727
+ */
728
+ async trimEntries() {
729
+ if (this.entries.size <= this.entriesCap)
730
+ return;
731
+ const all = [];
732
+ for (const [, entry] of this.entries.entries())
733
+ all.push(entry);
734
+ // Eviction order (ascending = evicted first): pinned last/never, then
735
+ // fewest recalls, then longest since last recall (never-recalled entries
736
+ // date from creation).
737
+ all.sort((a, b) => (a.pinned === true ? 1 : 0) - (b.pinned === true ? 1 : 0)
738
+ || (a.accessCount ?? 0) - (b.accessCount ?? 0)
739
+ || (a.lastRecalledAt ?? a.createdAt) - (b.lastRecalledAt ?? b.createdAt));
740
+ const excess = all.length - this.entriesCap;
741
+ for (let i = 0; i < excess; i++) {
742
+ const victim = all[i];
743
+ if (victim.pinned === true)
744
+ break;
745
+ const removed = await this.entries.delete(victim.id);
746
+ if (removed) {
747
+ await this.appendAudit('remove', victim.id, victim, 'janitor', undefined);
748
+ }
749
+ }
750
+ }
457
751
  async pin(id) {
458
752
  const existing = this.entries.get(id);
459
753
  if (existing === undefined)
@@ -504,6 +798,10 @@ export class DomainMemoryStore extends MemoryStore {
504
798
  * - `global`/`user` entries overdue (pinned exempt) are soft-decayed: the
505
799
  * first overdue pass stamps `staleSince`, which hides them from injection
506
800
  * surfaces while keeping them searchable; a later recall clears the stamp.
801
+ * The snapshot iteration is only a pre-filter: every delete and stamp
802
+ * re-decides on the record current at its write-chain slot (the same
803
+ * atomic RMW discipline as `stampRecalled`), so a pin landing between the
804
+ * snapshot and the write is honored.
507
805
  * @param decayDays - days without recall before the policy applies.
508
806
  * @param now - evaluation clock; defaults to wall time (tests inject fixed clocks).
509
807
  * @returns the number of project entries removed.
@@ -513,28 +811,84 @@ export class DomainMemoryStore extends MemoryStore {
513
811
  return 0;
514
812
  const decayMs = decayDays * 24 * 60 * 60 * 1000;
515
813
  let removed = 0;
516
- for (const [, entry] of this.entries.entries()) {
517
- if (entry.pinned === true)
814
+ for (const [, snapshot] of this.entries.entries()) {
815
+ if (snapshot.pinned === true)
518
816
  continue;
519
- // Use lastRecalledAt if available, otherwise fall back to createdAt.
520
- const lastActive = entry.lastRecalledAt ?? entry.createdAt;
817
+ // Snapshot pass is a cheap pre-filter only: every decision below is
818
+ // re-made on the record current at its write-chain slot, so a pin that
819
+ // lands between this iteration and the write is still honored.
820
+ const lastActive = snapshot.lastRecalledAt ?? snapshot.createdAt;
521
821
  if (now - lastActive < decayMs)
522
822
  continue;
523
- if (entry.scope === 'project') {
524
- // Hard decay: remove and log to the audit store.
525
- const didRemove = await this.entries.delete(entry.id);
823
+ if (snapshot.scope === 'project') {
824
+ // Hard decay: KvTable.update cannot express delete, so the pinned
825
+ // re-check runs as a guard update (returning `current` unchanged —
826
+ // one empty write) and only an unpinned result reaches the delete.
827
+ // Residual TOCTOU window: a pin landing AFTER the guard's chain slot
828
+ // but BEFORE the delete is not observed; the single-process write
829
+ // chain serializes these two calls, but nothing narrower than
830
+ // "guard → delete" exists on KvTable to close the gap. Covered by
831
+ // the janitor-pin-toctou contract test.
832
+ let pinnedAtSlot = false;
833
+ try {
834
+ await this.entries.update(snapshot.id, current => {
835
+ pinnedAtSlot = current.pinned === true;
836
+ return current;
837
+ });
838
+ }
839
+ catch (error) {
840
+ // A missing id means the entry was removed by another caller
841
+ // between the snapshot and this guard — nothing left to decay.
842
+ if (error instanceof Error && !error.message.includes('no record')) {
843
+ this.reportFailure('janitor', error);
844
+ }
845
+ }
846
+ if (pinnedAtSlot)
847
+ continue;
848
+ const didRemove = await this.entries.delete(snapshot.id);
526
849
  if (didRemove) {
527
850
  removed++;
528
- await this.appendAudit('remove', entry.id, entry, 'janitor', undefined);
851
+ await this.appendAudit('remove', snapshot.id, snapshot, 'janitor', undefined);
529
852
  }
530
853
  continue;
531
854
  }
532
- // global/user: soft decay only — stamp once, never auto-delete.
533
- if (entry.staleSince !== undefined)
534
- continue;
535
- const stamped = { ...entry, staleSince: now };
536
- await this.entries.put(entry.id, stamped);
537
- await this.appendAudit('update', entry.id, stamped, 'janitor', undefined);
855
+ // global/user: soft decay only — stamp once, never auto-delete. The
856
+ // whole decision re-runs on the record current at its chain slot, so
857
+ // the stamp is atomic: a pin or a fresh recall that lands between the
858
+ // snapshot and here skips it, and an already-stamped entry is left
859
+ // untouched. A model-assessed importance of 4–5 extends the grace
860
+ // window 1.5×: a "this matters" judgment should survive a longer quiet
861
+ // period, while low or unassessed entries keep the plain clock. Recall
862
+ // (accessCount) stays the stronger signal — it clears decay outright
863
+ // via stampRecalled.
864
+ let didStamp = false;
865
+ let stamped;
866
+ try {
867
+ stamped = await this.entries.update(snapshot.id, current => {
868
+ const lastActiveNow = current.lastRecalledAt ?? current.createdAt;
869
+ if (now - lastActiveNow < decayMs)
870
+ return current;
871
+ const graceFactor = current.importance !== undefined && current.importance >= 4 ? 1.5 : 1;
872
+ if (now - lastActiveNow < decayMs * graceFactor)
873
+ return current;
874
+ if (current.pinned === true)
875
+ return current;
876
+ if (current.staleSince !== undefined)
877
+ return current;
878
+ didStamp = true;
879
+ return { ...current, staleSince: now };
880
+ });
881
+ }
882
+ catch (error) {
883
+ // A missing id (entry removed between the snapshot and this slot) or
884
+ // a domain going away mid-pass is a normal end of life for a stamp.
885
+ if (error instanceof Error && !error.message.includes('no record')) {
886
+ this.reportFailure('janitor', error);
887
+ }
888
+ }
889
+ if (didStamp && stamped !== undefined) {
890
+ await this.appendAudit('update', snapshot.id, stamped, 'janitor', undefined);
891
+ }
538
892
  }
539
893
  return removed;
540
894
  }
@@ -575,8 +929,16 @@ export class DomainMemoryStore extends MemoryStore {
575
929
  stale,
576
930
  ...lastActivityTs !== undefined ? { lastActivityTs } : {},
577
931
  ...lastExtractionTs !== undefined ? { lastExtractionTs } : {},
932
+ ...this.failureCounts.size > 0 ? { backgroundFailures: Object.fromEntries(this.failureCounts) } : {},
578
933
  };
579
934
  }
935
+ async getRaw(id) {
936
+ const entry = this.entries.get(id);
937
+ if (entry === undefined)
938
+ return undefined;
939
+ await this.appendAudit('readRaw', id, entry, 'ui', undefined);
940
+ return entry;
941
+ }
580
942
  exportAuditLog() {
581
943
  const all = [];
582
944
  for (const [, record] of this.audit.entries())
@@ -606,8 +968,9 @@ export class DomainMemoryStore extends MemoryStore {
606
968
  await this.audit.put(record.id, record);
607
969
  await this.trimAudit();
608
970
  }
609
- catch {
971
+ catch (error) {
610
972
  // Best-effort: an audit failure must never propagate to the caller.
973
+ this.reportFailure('audit-append', error);
611
974
  }
612
975
  }
613
976
  /** Trim the audit table to the cap, deleting the oldest records. */
@@ -629,4 +992,18 @@ function preview(content) {
629
992
  const p = content.slice(0, 100);
630
993
  return scanContent(p).allowed ? p : '[content redacted]';
631
994
  }
995
+ /** Importances land in 1–5 regardless of what the caller passed in. */
996
+ const IMPORTANCE_MIN = 1;
997
+ const IMPORTANCE_MAX = 5;
998
+ /**
999
+ * Project an optional caller-supplied importance onto the entry-field spread:
1000
+ * absent input spreads nothing (stored value stands); out-of-range input is
1001
+ * clamped rather than rejected — a wrong assessment is not a protocol error.
1002
+ */
1003
+ function clampImportance(importance) {
1004
+ if (importance === undefined || Number.isNaN(importance))
1005
+ return {};
1006
+ const clamped = Math.min(IMPORTANCE_MAX, Math.max(IMPORTANCE_MIN, Math.round(importance)));
1007
+ return { importance: clamped };
1008
+ }
632
1009
  //# sourceMappingURL=index.js.map