@chenhw7/dsh-memory 0.7.0 → 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.
- package/README.i18n.yaml +2 -0
- package/README.md +8 -7
- package/{README.zh-CN.md → README.zh.md} +7 -6
- package/cordis.patch.yml +5 -1
- package/lib/benchmark/index.d.ts +24 -7
- package/lib/benchmark/index.d.ts.map +1 -1
- package/lib/benchmark/index.js +55 -7
- package/lib/benchmark/index.js.map +1 -1
- package/lib/client/index.js +37 -9
- package/lib/context/conflict.d.ts +23 -10
- package/lib/context/conflict.d.ts.map +1 -1
- package/lib/context/conflict.js +59 -20
- package/lib/context/conflict.js.map +1 -1
- package/lib/context/index.d.ts.map +1 -1
- package/lib/context/index.js +12 -5
- package/lib/context/index.js.map +1 -1
- package/lib/context/policy.d.ts +12 -0
- package/lib/context/policy.d.ts.map +1 -1
- package/lib/context/policy.js +22 -4
- package/lib/context/policy.js.map +1 -1
- package/lib/index.d.ts +23 -1
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +20 -0
- package/lib/index.js.map +1 -1
- package/lib/notes/cleanup.d.ts +7 -1
- package/lib/notes/cleanup.d.ts.map +1 -1
- package/lib/notes/cleanup.js +17 -12
- package/lib/notes/cleanup.js.map +1 -1
- package/lib/notes/index.d.ts +3 -1
- package/lib/notes/index.d.ts.map +1 -1
- package/lib/notes/index.js +8 -3
- package/lib/notes/index.js.map +1 -1
- package/lib/notes/scope.d.ts +5 -5
- package/lib/notes/scope.js +5 -5
- package/lib/remote/index.d.ts +67 -6
- package/lib/remote/index.d.ts.map +1 -1
- package/lib/remote/index.js +94 -9
- package/lib/remote/index.js.map +1 -1
- package/lib/remote/typert.remote-client.d.ts +8 -1
- package/lib/remote/typert.remote-client.js +6 -0
- package/lib/remote/types.d.ts +1 -1
- package/lib/remote/types.d.ts.map +1 -1
- package/lib/review/accumulator.d.ts +1 -1
- package/lib/review/accumulator.js +1 -1
- package/lib/review/dedup.d.ts +23 -15
- package/lib/review/dedup.d.ts.map +1 -1
- package/lib/review/dedup.js +34 -83
- package/lib/review/dedup.js.map +1 -1
- package/lib/review/extract.d.ts.map +1 -1
- package/lib/review/extract.js +5 -2
- package/lib/review/extract.js.map +1 -1
- package/lib/review/index.d.ts.map +1 -1
- package/lib/review/index.js +14 -9
- package/lib/review/index.js.map +1 -1
- package/lib/scanner.d.ts +2 -0
- package/lib/scanner.d.ts.map +1 -1
- package/lib/scanner.js +22 -0
- package/lib/scanner.js.map +1 -1
- package/lib/store/bm25.d.ts +75 -1
- package/lib/store/bm25.d.ts.map +1 -1
- package/lib/store/bm25.js +162 -17
- package/lib/store/bm25.js.map +1 -1
- package/lib/store/cross-process.d.ts +155 -0
- package/lib/store/cross-process.d.ts.map +1 -0
- package/lib/store/cross-process.js +254 -0
- package/lib/store/cross-process.js.map +1 -0
- package/lib/store/index.d.ts +89 -7
- package/lib/store/index.d.ts.map +1 -1
- package/lib/store/index.js +466 -89
- package/lib/store/index.js.map +1 -1
- package/lib/tool/index.d.ts +17 -5
- package/lib/tool/index.d.ts.map +1 -1
- package/lib/tool/index.js +235 -21
- package/lib/tool/index.js.map +1 -1
- package/lib/types.d.ts +31 -2
- package/lib/types.d.ts.map +1 -1
- package/package.json +11 -2
package/lib/store/index.js
CHANGED
|
@@ -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
|
|
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 {
|
|
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 =
|
|
20
|
-
id:
|
|
21
|
-
scope:
|
|
22
|
-
category:
|
|
23
|
-
content:
|
|
24
|
-
summary:
|
|
25
|
-
projectName:
|
|
26
|
-
createdAt:
|
|
27
|
-
updatedAt:
|
|
28
|
-
pinned:
|
|
29
|
-
lastRecalledAt:
|
|
30
|
-
staleSince:
|
|
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 =
|
|
34
|
-
id:
|
|
35
|
-
op:
|
|
36
|
-
entryId:
|
|
37
|
-
scope:
|
|
38
|
-
category:
|
|
39
|
-
source:
|
|
40
|
-
sessionId:
|
|
41
|
-
ts:
|
|
42
|
-
seq:
|
|
43
|
-
contentPreview:
|
|
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 =
|
|
47
|
-
id:
|
|
48
|
-
scope:
|
|
49
|
-
category:
|
|
50
|
-
content:
|
|
51
|
-
summary:
|
|
52
|
-
projectName:
|
|
53
|
-
hits:
|
|
54
|
-
firstSeenAt:
|
|
55
|
-
lastSeenAt:
|
|
56
|
-
targetEntryId:
|
|
57
|
-
source:
|
|
58
|
-
sessionId:
|
|
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
|
-
*
|
|
64
|
-
*
|
|
65
|
-
*
|
|
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
|
-
/**
|
|
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
|
-
*
|
|
85
|
-
* suggestion (re-observation, not a new row).
|
|
86
|
-
* prefilter
|
|
87
|
-
*
|
|
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.
|
|
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
|
-
|
|
118
|
-
|
|
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
|
-
|
|
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
|
|
259
|
-
//
|
|
260
|
-
//
|
|
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
|
-
|
|
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).
|
|
276
|
-
*
|
|
277
|
-
*
|
|
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(
|
|
503
|
+
async stampRecalled(ids) {
|
|
280
504
|
const now = Date.now();
|
|
281
|
-
for (const
|
|
282
|
-
//
|
|
283
|
-
//
|
|
284
|
-
|
|
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
|
-
|
|
287
|
-
|
|
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.
|
|
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
|
|
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
|
-
|
|
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 [,
|
|
517
|
-
if (
|
|
814
|
+
for (const [, snapshot] of this.entries.entries()) {
|
|
815
|
+
if (snapshot.pinned === true)
|
|
518
816
|
continue;
|
|
519
|
-
//
|
|
520
|
-
|
|
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 (
|
|
524
|
-
// Hard decay:
|
|
525
|
-
|
|
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',
|
|
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
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
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
|