@chenhw7/dsh-memory 0.7.0 → 0.9.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 +9 -8
- package/{README.zh-CN.md → README.zh.md} +8 -7
- 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 +75 -11
- 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 +45 -1
- package/lib/context/index.d.ts.map +1 -1
- package/lib/context/index.js +153 -9
- 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 +50 -2
- package/lib/index.d.ts.map +1 -1
- package/lib/index.js +46 -1
- 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/consolidate.d.ts +230 -0
- package/lib/review/consolidate.d.ts.map +1 -0
- package/lib/review/consolidate.js +435 -0
- package/lib/review/consolidate.js.map +1 -0
- 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 +63 -12
- package/lib/review/extract.d.ts.map +1 -1
- package/lib/review/extract.js +168 -31
- package/lib/review/extract.js.map +1 -1
- package/lib/review/index.d.ts +20 -0
- package/lib/review/index.d.ts.map +1 -1
- package/lib/review/index.js +68 -16
- package/lib/review/index.js.map +1 -1
- package/lib/review/sweep.d.ts +171 -0
- package/lib/review/sweep.d.ts.map +1 -0
- package/lib/review/sweep.js +310 -0
- package/lib/review/sweep.js.map +1 -0
- 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 +199 -9
- package/lib/store/index.d.ts.map +1 -1
- package/lib/store/index.js +652 -92
- package/lib/store/index.js.map +1 -1
- package/lib/store/sqlite.d.ts +126 -0
- package/lib/store/sqlite.d.ts.map +1 -0
- package/lib/store/sqlite.js +653 -0
- package/lib/store/sqlite.js.map +1 -0
- package/lib/tool/index.d.ts +17 -5
- package/lib/tool/index.d.ts.map +1 -1
- package/lib/tool/index.js +253 -21
- package/lib/tool/index.js.map +1 -1
- package/lib/types.d.ts +81 -2
- package/lib/types.d.ts.map +1 -1
- package/package.json +18 -3
package/lib/store/index.js
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* storage-domain provider for the long-term memory store. Opens a `memory`
|
|
3
|
-
* domain with
|
|
4
|
-
*
|
|
3
|
+
* domain with four tables (`entries` keyed by `MemoryId`, `audit`, and
|
|
4
|
+
* `suggestions` for the review queue, `meta` for subsystem state rows) and
|
|
5
|
+
* implements the {@link MemoryStore} abstract service against them. Reads are
|
|
6
|
+
* synchronous from
|
|
5
7
|
* the domain's authoritative in-memory state; writes serialize on the domain's
|
|
6
8
|
* write chain and reach the backend before updating memory.
|
|
7
9
|
*
|
|
@@ -11,82 +13,142 @@
|
|
|
11
13
|
* @module @chenhw7/dsh-memory/store
|
|
12
14
|
*/
|
|
13
15
|
import { defineDomain, domainTable } from '@deepseek-ai/dsh-storage-domain';
|
|
14
|
-
import
|
|
16
|
+
import z from '@deepseek-ai/schemastery';
|
|
17
|
+
import { z as zod } from 'zod';
|
|
15
18
|
import { MemoryStore, MemoryId, AuditId, SuggestionId, scanContent, validateProjectScope, validateContent } from '../index.js';
|
|
16
|
-
import { Bm25Index, tokenizeForSearch } from './bm25.js';
|
|
17
|
-
import {
|
|
19
|
+
import { Bm25Index, tokenizeForSearch, buildCorpusStats, buildCorpusStatsFromTokens, uniqueTokens, weightedOverlapSimilarity } from './bm25.js';
|
|
20
|
+
import { SqliteMemoryStore, SQLITE_MIGRATION_MARKER } from './sqlite.js';
|
|
21
|
+
import { CrossProcessGuard, DEFAULT_CROSS_PROCESS_PROBE_MS, EMPTY_OWNER, currentBootOwner, mediumOwnerReader, mediumGoodbyeWriter, ownerStampSchema, } from './cross-process.js';
|
|
18
22
|
/** 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:
|
|
23
|
+
const memoryEntrySchema = zod.object({
|
|
24
|
+
id: zod.string().min(1),
|
|
25
|
+
scope: zod.enum(['global', 'project', 'user']),
|
|
26
|
+
category: zod.enum(['failure', 'correction', 'insight', 'preference', 'convention', 'tool-quirk', 'procedure']).optional(),
|
|
27
|
+
content: zod.string(),
|
|
28
|
+
summary: zod.string().optional(),
|
|
29
|
+
projectName: zod.string().optional(),
|
|
30
|
+
createdAt: zod.number(),
|
|
31
|
+
updatedAt: zod.number(),
|
|
32
|
+
pinned: zod.boolean().optional(),
|
|
33
|
+
lastRecalledAt: zod.number().optional(),
|
|
34
|
+
staleSince: zod.number().optional(),
|
|
35
|
+
accessCount: zod.number().optional(),
|
|
36
|
+
importance: zod.number().optional(),
|
|
37
|
+
anchors: zod.array(zod.string()).optional(),
|
|
38
|
+
status: zod.enum(['active', 'superseded']).optional(),
|
|
39
|
+
supersededBy: zod.string().optional(),
|
|
40
|
+
hitCount: zod.number().optional(),
|
|
41
|
+
lastHitAt: zod.number().optional(),
|
|
31
42
|
});
|
|
32
43
|
/** 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:
|
|
44
|
+
const auditEntrySchema = zod.object({
|
|
45
|
+
id: zod.string().min(1),
|
|
46
|
+
op: zod.enum(['add', 'update', 'remove', 'readRaw']),
|
|
47
|
+
entryId: zod.string().min(1),
|
|
48
|
+
scope: zod.enum(['global', 'project', 'user']),
|
|
49
|
+
category: zod.enum(['failure', 'correction', 'insight', 'preference', 'convention', 'tool-quirk', 'procedure']).optional(),
|
|
50
|
+
source: zod.enum(['tool', 'review', 'flush', 'ui', 'janitor']),
|
|
51
|
+
sessionId: zod.string().optional(),
|
|
52
|
+
ts: zod.number(),
|
|
53
|
+
seq: zod.number().optional(),
|
|
54
|
+
contentPreview: zod.string(),
|
|
44
55
|
});
|
|
45
56
|
/** 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:
|
|
57
|
+
const suggestionSchema = zod.object({
|
|
58
|
+
id: zod.string().min(1),
|
|
59
|
+
scope: zod.enum(['global', 'project', 'user']),
|
|
60
|
+
category: zod.enum(['failure', 'correction', 'insight', 'preference', 'convention', 'tool-quirk', 'procedure']).optional(),
|
|
61
|
+
content: zod.string(),
|
|
62
|
+
summary: zod.string().optional(),
|
|
63
|
+
projectName: zod.string().optional(),
|
|
64
|
+
hits: zod.number(),
|
|
65
|
+
firstSeenAt: zod.number(),
|
|
66
|
+
lastSeenAt: zod.number(),
|
|
67
|
+
targetEntryId: zod.string().optional(),
|
|
68
|
+
source: zod.enum(['tool', 'review', 'flush', 'ui', 'janitor']),
|
|
69
|
+
sessionId: zod.string().optional(),
|
|
70
|
+
});
|
|
71
|
+
/**
|
|
72
|
+
* Zod schema for one meta record on the durable medium. The record is a
|
|
73
|
+
* deliberately permissive carrier: the `key` discriminates which subsystem
|
|
74
|
+
* owns the row, and every payload field is optional so a future carrier
|
|
75
|
+
* extension reopens on today's readers (zero-migration, the same looseObject
|
|
76
|
+
* rationale as the owner stamp).
|
|
77
|
+
*/
|
|
78
|
+
const metaRecordSchema = zod.looseObject({
|
|
79
|
+
key: zod.enum(['consolidation', 'medium', 'schema']),
|
|
80
|
+
value: zod.string().optional(),
|
|
81
|
+
updatedAt: zod.number().optional(),
|
|
59
82
|
});
|
|
60
83
|
/**
|
|
61
84
|
* 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
|
-
*
|
|
85
|
+
* (mutation audit trail) plus `suggestions` (P1-1 pending-review queue) plus
|
|
86
|
+
* `meta` (subsystem state rows: consolidation progress, migration markers),
|
|
87
|
+
* plus a global singleton carrying the single-writer owner stamp (P3
|
|
88
|
+
* cross-process detection). Domain version stays at 0 — all four later
|
|
89
|
+
* additions are forward-compatible: storage-json reads only declared tables
|
|
90
|
+
* and initializes any absent table as an empty map, and a medium whose global
|
|
91
|
+
* slot was never written reads as `null`, which the domain replaces with the
|
|
92
|
+
* spec's `initial` without materializing it, so existing v0 media reopen
|
|
93
|
+
* without migration.
|
|
94
|
+
*
|
|
95
|
+
* The stamp and meta-record schemas accept extra keys on purpose
|
|
96
|
+
* (`looseObject`): the medium holds both as opaque JSON, and a future
|
|
97
|
+
* extension of their shapes must reopen cleanly on today's readers.
|
|
66
98
|
*/
|
|
67
|
-
|
|
99
|
+
/** The memory domain spec, exported for the SQLite backend's migration path. */
|
|
100
|
+
export const memoryDomainSpec = defineDomain({
|
|
68
101
|
name: 'memory',
|
|
69
102
|
version: 0,
|
|
103
|
+
global: {
|
|
104
|
+
schema: ownerStampSchema,
|
|
105
|
+
initial: EMPTY_OWNER,
|
|
106
|
+
},
|
|
70
107
|
tables: {
|
|
71
108
|
entries: domainTable(memoryEntrySchema),
|
|
72
109
|
audit: domainTable(auditEntrySchema),
|
|
73
110
|
suggestions: domainTable(suggestionSchema),
|
|
111
|
+
meta: domainTable(metaRecordSchema),
|
|
74
112
|
},
|
|
75
113
|
});
|
|
76
|
-
/**
|
|
114
|
+
/**
|
|
115
|
+
* Maximum audit records retained; oldest are trimmed on overflow. Protocol
|
|
116
|
+
* default like {@link DEFAULT_ENTRIES_CAP}: settable per deployment through
|
|
117
|
+
* the `config:` entry on the `memory-store` composition row.
|
|
118
|
+
*/
|
|
77
119
|
const DEFAULT_AUDIT_CAP = 200;
|
|
120
|
+
/**
|
|
121
|
+
* Maximum memory entries retained in the `entries` table. Write paths
|
|
122
|
+
* (`add`, and `adoptSuggestion`'s new-entry path which delegates to `add`)
|
|
123
|
+
* trim back to this cap after a successful write, evicting by use signal.
|
|
124
|
+
*
|
|
125
|
+
* Why 500: the durable medium is one JSON file — it tolerates thousands of
|
|
126
|
+
* entries before size/migration pressure becomes real — so the cap only has
|
|
127
|
+
* to bound runaway extraction, not normal growth. 200 (the audit/suggestion
|
|
128
|
+
* cap precedent) would evict healthy, actively-recalled stores; the
|
|
129
|
+
* recall-golden fixture (24 entries) and integration suites sit far below it.
|
|
130
|
+
*
|
|
131
|
+
* Soft cap: entries that survive eviction (pinned, or high `accessCount`)
|
|
132
|
+
* may push the table past the cap; eviction never runs when every remaining
|
|
133
|
+
* candidate is protected. Settable per deployment through the `config:`
|
|
134
|
+
* entry on the `memory-store` composition row.
|
|
135
|
+
*/
|
|
136
|
+
const DEFAULT_ENTRIES_CAP = 500;
|
|
78
137
|
/**
|
|
79
138
|
* Maximum pending suggestions retained (P1-1). Overflow evicts the
|
|
80
139
|
* lowest-signal rows first: fewest hits, then oldest `lastSeenAt`.
|
|
81
140
|
*/
|
|
82
141
|
const DEFAULT_SUGGESTION_CAP = 200;
|
|
83
142
|
/**
|
|
84
|
-
*
|
|
85
|
-
* suggestion (re-observation, not a new row).
|
|
86
|
-
* prefilter
|
|
87
|
-
*
|
|
143
|
+
* IDF-weighted overlap above which two same-scope proposals count as the
|
|
144
|
+
* same suggestion (re-observation, not a new row). Sits below the entry-dedup
|
|
145
|
+
* prefilter line (DEDUP_SIMILARITY_THRESHOLD, 0.15) so a proposal is never
|
|
146
|
+
* silently dropped on this signal alone, while "the model keeps proposing X"
|
|
147
|
+
* still accumulates `hits` on one row instead of flooding the queue. The
|
|
148
|
+
* metric is the shared {@link ../store/bm25.ts weightedOverlapSimilarity}
|
|
149
|
+
* measured over the live queue as corpus.
|
|
88
150
|
*/
|
|
89
|
-
const SUGGESTION_DUP_THRESHOLD = 0.
|
|
151
|
+
const SUGGESTION_DUP_THRESHOLD = 0.3;
|
|
90
152
|
/**
|
|
91
153
|
* Deterministic audit ordering: newest/oldest by `ts`, ties broken by the
|
|
92
154
|
* monotonic append `seq`, then by id for records written before `seq` existed.
|
|
@@ -102,20 +164,188 @@ function compareAuditAsc(a, b) {
|
|
|
102
164
|
}
|
|
103
165
|
/** Cordis plugin name. */
|
|
104
166
|
export const name = 'memory-store-domain';
|
|
167
|
+
/**
|
|
168
|
+
* Fraction of {@link StoreConfig.entriesCap} at or beyond which the startup
|
|
169
|
+
* selfcheck warns that the store is approaching the single-JSON-medium
|
|
170
|
+
* migration threshold (scale-trigger-selfcheck): it detects "close to the
|
|
171
|
+
* cap" where the cap's own eviction only acts at "past the cap". File-size
|
|
172
|
+
* and multi-process concerns are deliberately not re-checked here — the file
|
|
173
|
+
* size is derived from the same entry count, and cross-process detection
|
|
174
|
+
* (cross-process-detect) already owns the concurrent-writer warning.
|
|
175
|
+
*/
|
|
176
|
+
const SCALE_SELFCHECK_FRACTION = 0.8;
|
|
105
177
|
/** Services required before this provider can mount. */
|
|
106
178
|
export const inject = ['storageDomain'];
|
|
179
|
+
/** Schemastery configuration for the `memory-store` composition row. */
|
|
180
|
+
export const Config = z.object({
|
|
181
|
+
storage: z.union(['host-medium', 'sqlite']).default('host-medium'),
|
|
182
|
+
entriesCap: z.number().step(1).min(1).default(DEFAULT_ENTRIES_CAP),
|
|
183
|
+
crossProcessProbeMs: z.number().step(1).min(0).default(DEFAULT_CROSS_PROCESS_PROBE_MS),
|
|
184
|
+
});
|
|
107
185
|
/**
|
|
108
186
|
* Mount the storage-domain memory store provider. Opens the `memory` domain
|
|
109
|
-
* and registers a {@link MemoryStore} subclass on `ctx.memory`.
|
|
187
|
+
* and registers a {@link MemoryStore} subclass on `ctx.memory`. On open, a
|
|
188
|
+
* {@link CrossProcessGuard} claims the medium's owner stamp (the domain's
|
|
189
|
+
* global slot) and starts the configured read-back probe; the dispose path
|
|
190
|
+
* stamps `closedAt` so the next boot does not warn about this one.
|
|
110
191
|
* @param ctx - Cordis context with `storageDomain` injected.
|
|
192
|
+
* @param config - row config; `entriesCap` and `crossProcessProbeMs` are read here.
|
|
111
193
|
*/
|
|
112
|
-
export async function apply(ctx) {
|
|
194
|
+
export async function apply(ctx, config = { storage: 'host-medium', entriesCap: DEFAULT_ENTRIES_CAP, crossProcessProbeMs: DEFAULT_CROSS_PROCESS_PROBE_MS }) {
|
|
113
195
|
const domain = await ctx.storageDomain.open(memoryDomainSpec);
|
|
114
196
|
const entries = domain.table('entries');
|
|
115
197
|
const audit = domain.table('audit');
|
|
116
198
|
const suggestions = domain.table('suggestions');
|
|
117
|
-
|
|
118
|
-
|
|
199
|
+
const meta = domain.table('meta');
|
|
200
|
+
// Backend selection (write-path rework Step 3.2): `sqlite` mounts the
|
|
201
|
+
// plugin-owned memory.db instead of the domain store. The medium's
|
|
202
|
+
// migration marker guards both directions — a sqlite boot over a
|
|
203
|
+
// non-empty, never-migrated medium imports it once; a host-medium boot
|
|
204
|
+
// after a migration fails loud (two diverging sources of truth).
|
|
205
|
+
if (config.storage === 'sqlite') {
|
|
206
|
+
const dbPath = resolveSqlitePath(ctx);
|
|
207
|
+
if (dbPath === undefined) {
|
|
208
|
+
throw new Error('dsh-memory: storage: sqlite needs the dshHomePath service to resolve $DSH_HOME/storages/memory.db — the composition does not provide it; fix the row or keep storage: host-medium');
|
|
209
|
+
}
|
|
210
|
+
const sqlite = new SqliteMemoryStore({
|
|
211
|
+
dbPath,
|
|
212
|
+
failureLogger: ctx.logger,
|
|
213
|
+
entriesCap: config.entriesCap,
|
|
214
|
+
});
|
|
215
|
+
// The marker lives in the MEDIUM's meta table (the migrating boot wrote
|
|
216
|
+
// it there); the sqlite database's own meta table is the new store's
|
|
217
|
+
// progress, not the migration record.
|
|
218
|
+
const migrated = meta.get(SQLITE_MIGRATION_MARKER);
|
|
219
|
+
const mediumEntries = [...entries.entries()].map(([, entry]) => entry);
|
|
220
|
+
if (migrated === undefined && mediumEntries.length > 0) {
|
|
221
|
+
// One-time import: the medium holds data this database has never seen.
|
|
222
|
+
sqlite.importFromDomain(mediumEntries, [...audit.entries()].map(([, record]) => record), [...suggestions.entries()].map(([, row]) => row));
|
|
223
|
+
await meta.put(SQLITE_MIGRATION_MARKER, { key: 'medium', value: new Date().toISOString(), updatedAt: Date.now() });
|
|
224
|
+
ctx.logger.warn(`dsh-memory: imported ${String(mediumEntries.length)} entries from memory.json into ${dbPath}`);
|
|
225
|
+
}
|
|
226
|
+
else if (migrated !== undefined && mediumEntries.length > 0) {
|
|
227
|
+
// Both sides hold data: the medium was written after the migration —
|
|
228
|
+
// a second writer. Failing loud is the only safe answer.
|
|
229
|
+
throw new Error('dsh-memory: storage: sqlite — the host medium holds entries but carries a migratedToSqlite marker; a host-medium process wrote memory.json after the migration. Reconcile the two stores by hand and remove the stale writes before restarting.');
|
|
230
|
+
}
|
|
231
|
+
ctx.effect(() => async () => { sqlite.close(); });
|
|
232
|
+
ctx.provide('memory', sqlite);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
// Cross-process single-writer detection (host storage-json is
|
|
236
|
+
// last-writer-wins across processes, silently): claim the medium's owner
|
|
237
|
+
// stamp at open, re-read it on a lightweight interval, stamp `closedAt` on
|
|
238
|
+
// dispose. The medium path comes from the harness-home resolver the boot
|
|
239
|
+
// provides to composition `!!js` expressions; when absent (unit tests,
|
|
240
|
+
// exotic hosts) the medium read-back seam is undefined and only the
|
|
241
|
+
// in-memory startup judgment + goodbye stamps run.
|
|
242
|
+
// One boot identity per mount, shared by the claim and the goodbye: a
|
|
243
|
+
// second `currentBootOwner()` would mint a fresh random bootId that the
|
|
244
|
+
// goodbye writer would (correctly) refuse to stamp.
|
|
245
|
+
// Mixed-version guard (Step 3.2): a host-medium boot over a medium whose
|
|
246
|
+
// meta table carries the sqlite migration marker fails loud — the medium
|
|
247
|
+
// is no longer this backend's source of truth, and writing to it anyway
|
|
248
|
+
// would fork the data.
|
|
249
|
+
if (meta.get(SQLITE_MIGRATION_MARKER) !== undefined) {
|
|
250
|
+
throw new Error('dsh-memory: storage: host-medium — the medium carries the migratedToSqlite marker: its data moved into memory.db and a host-medium process must not write memory.json anymore. Start with storage: sqlite, or reconcile the stores by hand and remove the marker.');
|
|
251
|
+
}
|
|
252
|
+
const own = currentBootOwner();
|
|
253
|
+
const mediumReader = resolveMediumReader(ctx);
|
|
254
|
+
const mediumGoodbye = resolveMediumGoodbye(ctx, own.bootId);
|
|
255
|
+
const store = new DomainMemoryStore(entries, audit, suggestions, meta, DEFAULT_AUDIT_CAP, DEFAULT_SUGGESTION_CAP, ctx.logger, config.entriesCap);
|
|
256
|
+
const guard = new CrossProcessGuard(own, mediumReader, owner => domain.global.set(owner), (site, error) => store.reportFailure(site, error), undefined, mediumGoodbye);
|
|
257
|
+
try {
|
|
258
|
+
// Startup judgment + claim: judge the open-time global (loaded from the
|
|
259
|
+
// medium), then stamp this boot as owner so later starters see us. A
|
|
260
|
+
// failed claim cannot run detection, but the store itself may still be
|
|
261
|
+
// usable — fail loud in the log, keep mounting.
|
|
262
|
+
await guard.startup(domain.global.get());
|
|
263
|
+
}
|
|
264
|
+
catch (error) {
|
|
265
|
+
// Detection is a background safety net, not the write path: an unwritable
|
|
266
|
+
// global slot degrades to no cross-process visibility, so the mount
|
|
267
|
+
// continues and only this warn marks the gap.
|
|
268
|
+
ctx.logger.warn(`dsh-memory: cross-process owner claim failed: ${String(error)}`);
|
|
269
|
+
}
|
|
270
|
+
ctx.effect(() => {
|
|
271
|
+
// The cordis-plugin-timer mixin is not a dependency of this package, so
|
|
272
|
+
// the probe uses the platform interval directly — registered inside the
|
|
273
|
+
// effect so the disposer below clears it on stop/update/undefine.
|
|
274
|
+
const probeTimer = config.crossProcessProbeMs > 0
|
|
275
|
+
? setInterval(() => { void guard.probe(); }, config.crossProcessProbeMs)
|
|
276
|
+
: undefined;
|
|
277
|
+
return async () => {
|
|
278
|
+
if (probeTimer !== undefined)
|
|
279
|
+
clearInterval(probeTimer);
|
|
280
|
+
await guard.sayGoodbye();
|
|
281
|
+
await domain.close();
|
|
282
|
+
};
|
|
283
|
+
});
|
|
284
|
+
ctx.provide('memory', store);
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Resolve the unit-file read seam for cross-process detection from the
|
|
288
|
+
* harness-home path resolver the boot exposes to `!!js` config expressions.
|
|
289
|
+
* Compositions derive the storage root from the same service, so the
|
|
290
|
+
* resolution agrees with where storage-json actually writes. Returns
|
|
291
|
+
* `undefined` when the service is absent.
|
|
292
|
+
* @param ctx - Cordis context that may carry `dshHomePath`.
|
|
293
|
+
* @returns an async medium reader, or `undefined` when unresolvable.
|
|
294
|
+
*/
|
|
295
|
+
function resolveMediumReader(ctx) {
|
|
296
|
+
const homePath = ctx.get('dshHomePath');
|
|
297
|
+
if (typeof homePath !== 'function')
|
|
298
|
+
return undefined;
|
|
299
|
+
return mediumOwnerReader(homePath('storages', 'memory.json'));
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Resolve the direct medium-file goodbye writer (same derivation as
|
|
303
|
+
* {@link resolveMediumReader}). The goodbye must not go through the domain's
|
|
304
|
+
* global slot: the storage facility's own unmount closes the domain
|
|
305
|
+
* concurrently with our disposer, so the domain write rejects with `closed`
|
|
306
|
+
* most dispose runs — the medium file is the only teardown-valid seam.
|
|
307
|
+
* @param ctx - Cordis context that may carry `dshHomePath`.
|
|
308
|
+
* @param bootId - This mount's boot identity, matching the claim the guard writes.
|
|
309
|
+
* @returns an async goodbye writer, or `undefined` when unresolvable.
|
|
310
|
+
*/
|
|
311
|
+
function resolveMediumGoodbye(ctx, bootId) {
|
|
312
|
+
const homePath = ctx.get('dshHomePath');
|
|
313
|
+
if (typeof homePath !== 'function')
|
|
314
|
+
return undefined;
|
|
315
|
+
return mediumGoodbyeWriter(homePath('storages', 'memory.json'), bootId);
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Resolve the plugin-owned SQLite database path from the same harness-home
|
|
319
|
+
* resolver the medium reader uses (`$DSH_HOME/storages/memory.db`). Returns
|
|
320
|
+
* `undefined` when the service is absent — the sqlite backend cannot mount
|
|
321
|
+
* without it (the caller fails loud).
|
|
322
|
+
*/
|
|
323
|
+
function resolveSqlitePath(ctx) {
|
|
324
|
+
const homePath = ctx.get('dshHomePath');
|
|
325
|
+
if (typeof homePath !== 'function')
|
|
326
|
+
return undefined;
|
|
327
|
+
return homePath('storages', 'memory.db');
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Token bags per entry: content tokens plus — when the entry carries a
|
|
331
|
+
* summary — the summary's tokens. Merging both fields into ONE bag (summary
|
|
332
|
+
* tokens simply repeat into tf) is the deliberately simple stand-in for
|
|
333
|
+
* BM25F: summary is a human-written high-signal distillation, so its terms
|
|
334
|
+
* earning the same tf boost as content terms IS the desired emphasis, and a
|
|
335
|
+
* matched summary keyword pushes an entry above content-only competitors.
|
|
336
|
+
* Explicit BM25F (per-field lengths + b-field + weight w_f) was considered
|
|
337
|
+
* and rejected for now: it adds per-field length bookkeeping and a weight
|
|
338
|
+
* tunable (against the "no hardcoded tunables" rule, another Config field)
|
|
339
|
+
* for a gain this merged bag already captures at fixture scale; revisit if
|
|
340
|
+
* the floors slip with real-corpus summaries. Empty-string summaries count
|
|
341
|
+
* as absent (add() already refuses to store them, but direct table seeds
|
|
342
|
+
* can still carry `summary: ''`).
|
|
343
|
+
*/
|
|
344
|
+
function entryIndexTokens(entry) {
|
|
345
|
+
const contentTokens = tokenizeForSearch(entry.content);
|
|
346
|
+
return entry.summary === undefined || entry.summary === ''
|
|
347
|
+
? contentTokens
|
|
348
|
+
: [...contentTokens, ...tokenizeForSearch(entry.summary)];
|
|
119
349
|
}
|
|
120
350
|
/**
|
|
121
351
|
* MemoryStore implementation backed by a storage-domain KV table. Reads are
|
|
@@ -127,17 +357,79 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
127
357
|
entries;
|
|
128
358
|
audit;
|
|
129
359
|
suggestions;
|
|
360
|
+
meta;
|
|
130
361
|
auditCap;
|
|
131
362
|
suggestionCap;
|
|
363
|
+
entriesCap;
|
|
364
|
+
/** Warn channel for swallowed background-path failures; the host `ctx.logger`. */
|
|
365
|
+
failureLogger;
|
|
366
|
+
/** Per-site counts of swallowed failures, surfaced through `health()`. */
|
|
367
|
+
failureCounts = new Map();
|
|
132
368
|
/** Last audit `seq` handed out; lazily initialized from the medium on first append. */
|
|
133
369
|
auditSeq;
|
|
134
|
-
constructor(entries, audit, suggestions, auditCap = DEFAULT_AUDIT_CAP, suggestionCap = DEFAULT_SUGGESTION_CAP) {
|
|
370
|
+
constructor(entries, audit, suggestions, meta, auditCap = DEFAULT_AUDIT_CAP, suggestionCap = DEFAULT_SUGGESTION_CAP, failureLogger, entriesCap = DEFAULT_ENTRIES_CAP) {
|
|
135
371
|
super();
|
|
136
372
|
this.entries = entries;
|
|
137
373
|
this.audit = audit;
|
|
138
374
|
this.suggestions = suggestions;
|
|
375
|
+
this.meta = meta;
|
|
139
376
|
this.auditCap = auditCap;
|
|
140
377
|
this.suggestionCap = suggestionCap;
|
|
378
|
+
this.entriesCap = entriesCap;
|
|
379
|
+
this.failureLogger = failureLogger;
|
|
380
|
+
// Startup selfcheck (scale-trigger-selfcheck): judge the entry count the
|
|
381
|
+
// medium opened with, once per construction. Deployments that reopen an
|
|
382
|
+
// already-large medium see the warning at boot — the point where a
|
|
383
|
+
// migration decision (per-record/SQLite backing) is still cheap — instead
|
|
384
|
+
// of first learning about the size from an eviction storm.
|
|
385
|
+
this.selfcheckScale();
|
|
386
|
+
}
|
|
387
|
+
/**
|
|
388
|
+
* One-time startup scale judgment. Fires a warn when the entry count
|
|
389
|
+
* loaded from the medium already sits at or above
|
|
390
|
+
* {@link SCALE_SELFCHECK_FRACTION} of {@link entriesCap}. The warn carries
|
|
391
|
+
* the concrete numbers and the documented migration threshold, and goes
|
|
392
|
+
* through the same best-effort logger channel as every background-path
|
|
393
|
+
* failure — a missing logger (unit tests, headless constructions) stays
|
|
394
|
+
* silent rather than throwing out of the constructor.
|
|
395
|
+
*/
|
|
396
|
+
selfcheckScale() {
|
|
397
|
+
if (this.entries.size < this.entriesCap * SCALE_SELFCHECK_FRACTION)
|
|
398
|
+
return;
|
|
399
|
+
this.failureLogger?.warn(`dsh-memory: entries table holds ${this.entries.size} of ${this.entriesCap} `
|
|
400
|
+
+ `allowed entries (≥ ${SCALE_SELFCHECK_FRACTION}× cap) — approaching the `
|
|
401
|
+
+ 'single-JSON-medium scale ceiling; consider migrating to per-record or '
|
|
402
|
+
+ 'SQLite backing (see the improvement program\'s scale-trigger-selfcheck entry)');
|
|
403
|
+
}
|
|
404
|
+
reportFailure(site, error) {
|
|
405
|
+
this.failureCounts.set(site, (this.failureCounts.get(site) ?? 0) + 1);
|
|
406
|
+
this.failureLogger?.warn(`dsh-memory: ${site} failed${error === undefined ? '' : `: ${String(error)}`}`);
|
|
407
|
+
}
|
|
408
|
+
// ─── Meta table (subsystem state rows, § consolidation/migration) ──────────
|
|
409
|
+
/**
|
|
410
|
+
* Read one meta record, synchronously from the domain's in-memory state.
|
|
411
|
+
* @param key - the record's table key (the owning subsystem's `key` plus
|
|
412
|
+
* any caller suffix, e.g. `'consolidation:lastRun'`).
|
|
413
|
+
* @returns the record, or `undefined` when never written.
|
|
414
|
+
*/
|
|
415
|
+
getMeta(key) {
|
|
416
|
+
return this.meta.get(key);
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Write one meta record durably (insert or full replace — the table's `put`
|
|
420
|
+
* contract, no partial merge). Best-effort on failure: a meta write never
|
|
421
|
+
* breaks the caller's primary path, mirroring the audit-append discipline.
|
|
422
|
+
* @param key - the record's table key.
|
|
423
|
+
* @param record - the full new record; `updatedAt` is stamped here when the
|
|
424
|
+
* caller leaves it off.
|
|
425
|
+
*/
|
|
426
|
+
async setMeta(key, record) {
|
|
427
|
+
try {
|
|
428
|
+
await this.meta.put(key, record.updatedAt !== undefined ? record : { ...record, updatedAt: Date.now() });
|
|
429
|
+
}
|
|
430
|
+
catch (error) {
|
|
431
|
+
this.reportFailure('meta-write', error);
|
|
432
|
+
}
|
|
141
433
|
}
|
|
142
434
|
/** Next monotonic audit sequence number (survives reopen via the medium). */
|
|
143
435
|
nextAuditSeq() {
|
|
@@ -157,6 +449,10 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
157
449
|
if (!scan.allowed) {
|
|
158
450
|
throw new Error(`memory content rejected by scanner: ${scan.reasons.join('; ')}`);
|
|
159
451
|
}
|
|
452
|
+
const summaryScan = scanContent(input.summary ?? '');
|
|
453
|
+
if (!summaryScan.allowed) {
|
|
454
|
+
throw new Error(`memory summary rejected by scanner: ${summaryScan.reasons.join('; ')}`);
|
|
455
|
+
}
|
|
160
456
|
const now = Date.now();
|
|
161
457
|
const id = MemoryId();
|
|
162
458
|
const entry = {
|
|
@@ -168,9 +464,14 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
168
464
|
projectName: input.projectName,
|
|
169
465
|
createdAt: now,
|
|
170
466
|
updatedAt: now,
|
|
467
|
+
...clampImportance(input.importance),
|
|
468
|
+
...input.anchors !== undefined ? { anchors: input.anchors } : {},
|
|
171
469
|
};
|
|
172
470
|
await this.entries.put(id, entry);
|
|
173
471
|
await this.appendAudit('add', id, entry, input.source, input.sessionId);
|
|
472
|
+
// Both new-entry write paths land here (adoptSuggestion's new-entry branch
|
|
473
|
+
// delegates to add), so the cap is enforced at this one chokepoint.
|
|
474
|
+
await this.trimEntries();
|
|
174
475
|
return { entry };
|
|
175
476
|
}
|
|
176
477
|
get(id) {
|
|
@@ -197,6 +498,12 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
197
498
|
if (!scan.allowed) {
|
|
198
499
|
throw new Error(`memory content rejected by scanner: ${scan.reasons.join('; ')}`);
|
|
199
500
|
}
|
|
501
|
+
// Scans only what this call writes: an entry stored before summary scanning
|
|
502
|
+
// existed stays updatable, so its summary can still be repaired or cleared.
|
|
503
|
+
const summaryScan = scanContent(input.summary ?? '');
|
|
504
|
+
if (!summaryScan.allowed) {
|
|
505
|
+
throw new Error(`memory summary rejected by scanner: ${summaryScan.reasons.join('; ')}`);
|
|
506
|
+
}
|
|
200
507
|
// summary semantics: `undefined` = keep existing; `''` = explicitly clear;
|
|
201
508
|
// a non-empty string = replace. Build the updated entry accordingly.
|
|
202
509
|
const base = {
|
|
@@ -204,6 +511,11 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
204
511
|
content: newContent,
|
|
205
512
|
category: input.category ?? existing.category,
|
|
206
513
|
updatedAt: Date.now(),
|
|
514
|
+
// Only rewrite the field when the caller supplies one; `undefined`
|
|
515
|
+
// keeps the stored importance (add-time assessment stands).
|
|
516
|
+
...clampImportance(input.importance),
|
|
517
|
+
// Same absent-means-keep semantics for anchors.
|
|
518
|
+
...(input.anchors !== undefined ? { anchors: input.anchors } : {}),
|
|
207
519
|
};
|
|
208
520
|
const updated = input.summary === ''
|
|
209
521
|
? (() => { const { summary: _c, ...rest } = base; return rest; })()
|
|
@@ -227,8 +539,12 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
227
539
|
search(query) {
|
|
228
540
|
const limit = query.limit ?? 50;
|
|
229
541
|
// Structured filters first; scoring runs over the surviving candidates.
|
|
542
|
+
// Superseded entries are excluded (consolidation conflict verdicts leave
|
|
543
|
+
// them to the navigable-only surfaces: memory_get/memory_list/management UI).
|
|
230
544
|
const candidates = [];
|
|
231
545
|
for (const [, entry] of this.entries.entries()) {
|
|
546
|
+
if (entry.status === 'superseded')
|
|
547
|
+
continue;
|
|
232
548
|
if (query.scope !== undefined && entry.scope !== query.scope)
|
|
233
549
|
continue;
|
|
234
550
|
if (query.category !== undefined && entry.category !== query.category)
|
|
@@ -243,7 +559,16 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
243
559
|
// BM25 over the filtered set: relevance-weighted (IDF × saturation),
|
|
244
560
|
// CJK bigrams for word-level Chinese precision. OR semantics preserved —
|
|
245
561
|
// any shared term scores above zero and keeps the document in play.
|
|
246
|
-
|
|
562
|
+
// The df table is built over the FULL corpus (every entry), not the
|
|
563
|
+
// filtered set: with a 3-entry candidate pool a per-pool df lets a pure
|
|
564
|
+
// function word present in 2 of 3 candidates earn the same IDF as a
|
|
565
|
+
// genuinely distinctive term, and the resulting noise reorders results.
|
|
566
|
+
// Full-corpus stats cost one tokenize pass over all entries per search
|
|
567
|
+
// — the same order as the candidate-set tokenization itself. Both
|
|
568
|
+
// corpus and index see the SAME merged content+summary bag, so df and
|
|
569
|
+
// tf stay consistent.
|
|
570
|
+
const corpus = buildCorpusStatsFromTokens([...this.entries.entries()].map(([, entry]) => entryIndexTokens(entry)));
|
|
571
|
+
const index = new Bm25Index(candidates.map(entry => entryIndexTokens(entry)), corpus);
|
|
247
572
|
const scores = index.scores(queryTokens);
|
|
248
573
|
ranked = [];
|
|
249
574
|
candidates.forEach((entry, i) => {
|
|
@@ -255,11 +580,18 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
255
580
|
else {
|
|
256
581
|
ranked = candidates.map(entry => ({ entry, score: 0 }));
|
|
257
582
|
}
|
|
258
|
-
// Rank by BM25 relevance (desc), then pinned entries (desc), then
|
|
259
|
-
//
|
|
260
|
-
//
|
|
583
|
+
// Rank by BM25 relevance (desc), then pinned entries (desc), then the
|
|
584
|
+
// model-assessed importance (desc; absent reads as mid-range so unassessed
|
|
585
|
+
// entries are not penalized), then by recency (updatedAt desc). Pinned
|
|
586
|
+
// entries surface early even among equal-relevance matches — pin means
|
|
587
|
+
// "the user wants this remembered"; importance is the model's weaker,
|
|
588
|
+
// optional version of the same judgment.
|
|
261
589
|
const pinOf = (entry) => entry.pinned === true ? 1 : 0;
|
|
262
|
-
|
|
590
|
+
const importanceOf = (entry) => entry.importance ?? 0;
|
|
591
|
+
ranked.sort((a, b) => b.score - a.score
|
|
592
|
+
|| pinOf(b.entry) - pinOf(a.entry)
|
|
593
|
+
|| importanceOf(b.entry) - importanceOf(a.entry)
|
|
594
|
+
|| b.entry.updatedAt - a.entry.updatedAt);
|
|
263
595
|
let all = ranked.map(r => r.entry);
|
|
264
596
|
const total = all.length;
|
|
265
597
|
all = limit > 0 ? all.slice(0, limit) : all;
|
|
@@ -268,23 +600,50 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
268
600
|
// Read-only consumers (management UI) opt out via recordRecall: false —
|
|
269
601
|
// merely viewing entries must not rewrite their recall metadata.
|
|
270
602
|
if (query.recordRecall !== false)
|
|
271
|
-
void this.stampRecalled(all);
|
|
603
|
+
void this.stampRecalled(all.map(entry => entry.id));
|
|
272
604
|
return { entries: all, total };
|
|
273
605
|
}
|
|
274
606
|
/**
|
|
275
|
-
* Stamp entries with a recall timestamp (fire-and-forget).
|
|
276
|
-
*
|
|
277
|
-
*
|
|
607
|
+
* Stamp entries with a recall timestamp (fire-and-forget). Each entry is
|
|
608
|
+
* stamped through the table's atomic read-modify-write, so the transform
|
|
609
|
+
* reads the record current at its write-chain slot — a concurrent
|
|
610
|
+
* `memory_replace` that lands first is never rolled back by the stamp, and
|
|
611
|
+
* the stamp never rolls one back. One stamp pass enqueues one job per
|
|
612
|
+
* changed entry; entries already carrying this pass's timestamp and no
|
|
613
|
+
* decay stamp are skipped without touching the chain. `updatedAt` is
|
|
614
|
+
* intentionally left untouched: recalling is not mutating.
|
|
615
|
+
* @param ids - the ids of the entries the caller surfaced to the model.
|
|
278
616
|
*/
|
|
279
|
-
async stampRecalled(
|
|
617
|
+
async stampRecalled(ids) {
|
|
280
618
|
const now = Date.now();
|
|
281
|
-
for (const
|
|
282
|
-
//
|
|
283
|
-
//
|
|
284
|
-
|
|
619
|
+
for (const id of ids) {
|
|
620
|
+
// Cheap pre-check on the synchronous snapshot: a stamp pass that would
|
|
621
|
+
// change nothing skips the queue entirely (the common repeat-search case).
|
|
622
|
+
const snapshot = this.entries.get(id);
|
|
623
|
+
if (snapshot?.lastRecalledAt === now && snapshot.staleSince === undefined)
|
|
285
624
|
continue;
|
|
286
|
-
|
|
287
|
-
|
|
625
|
+
try {
|
|
626
|
+
// The atomic RMW re-reads at the chain slot, so a content edit that
|
|
627
|
+
// landed between search and stamp survives in the written record.
|
|
628
|
+
await this.entries.update(id, current => {
|
|
629
|
+
if (current.lastRecalledAt === now && current.staleSince === undefined)
|
|
630
|
+
return current;
|
|
631
|
+
const { staleSince: _cleared, ...rest } = current;
|
|
632
|
+
return {
|
|
633
|
+
...rest,
|
|
634
|
+
lastRecalledAt: now,
|
|
635
|
+
accessCount: (rest.accessCount ?? 0) + 1,
|
|
636
|
+
};
|
|
637
|
+
});
|
|
638
|
+
}
|
|
639
|
+
catch (error) {
|
|
640
|
+
// A missing id (entry removed between search and stamp) or a domain
|
|
641
|
+
// going away mid-pass is a normal end-of-life for a stamp, not a
|
|
642
|
+
// failure to report.
|
|
643
|
+
if (error instanceof Error && !error.message.includes('no record')) {
|
|
644
|
+
this.reportFailure('recall-stamp', error);
|
|
645
|
+
}
|
|
646
|
+
}
|
|
288
647
|
}
|
|
289
648
|
}
|
|
290
649
|
/**
|
|
@@ -296,7 +655,44 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
296
655
|
markRecalled(ids) {
|
|
297
656
|
if (ids.length === 0)
|
|
298
657
|
return;
|
|
299
|
-
void this.stampRecalled(ids.
|
|
658
|
+
void this.stampRecalled(ids.filter(id => this.entries.get(id) !== undefined));
|
|
659
|
+
}
|
|
660
|
+
/**
|
|
661
|
+
* Record usage hits on the given entries (write-path rework Step 2):
|
|
662
|
+
* bump `hitCount` and stamp `lastHitAt` through the table's atomic
|
|
663
|
+
* read-modify-write — the same discipline as {@link stampRecalled}, so a
|
|
664
|
+
* concurrent content edit is never rolled back by a hit and vice versa.
|
|
665
|
+
* `updatedAt` is intentionally left untouched: a hit is a reading signal,
|
|
666
|
+
* not a mutation. Idempotent per call batch (one call adds exactly one
|
|
667
|
+
* hit per entry, regardless of duplicates inside `ids`); unknown ids and
|
|
668
|
+
* entries removed mid-pass are skipped like a stale recall stamp.
|
|
669
|
+
* @param ids - the ids of the entries the assistant's answer echoed.
|
|
670
|
+
*/
|
|
671
|
+
async markHits(ids) {
|
|
672
|
+
const now = Date.now();
|
|
673
|
+
// One batch = one hit per entry, regardless of duplicates inside `ids`
|
|
674
|
+
// (the caller passes the echoed id set; a set has no multiplicity).
|
|
675
|
+
for (const id of [...new Set(ids)]) {
|
|
676
|
+
const snapshot = this.entries.get(id);
|
|
677
|
+
if (snapshot === undefined)
|
|
678
|
+
continue;
|
|
679
|
+
try {
|
|
680
|
+
await this.entries.update(id, current => ({
|
|
681
|
+
...current,
|
|
682
|
+
hitCount: (current.hitCount ?? 0) + 1,
|
|
683
|
+
lastHitAt: now,
|
|
684
|
+
}));
|
|
685
|
+
await this.appendAudit('update', id, this.entries.get(id) ?? snapshot, 'review', undefined);
|
|
686
|
+
}
|
|
687
|
+
catch (error) {
|
|
688
|
+
// A missing id (entry removed between the caller's answer and this
|
|
689
|
+
// write) or a domain going away mid-pass is a normal end-of-life for
|
|
690
|
+
// a hit, not a failure to report.
|
|
691
|
+
if (error instanceof Error && !error.message.includes('no record')) {
|
|
692
|
+
this.reportFailure('mark-hits', error);
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
}
|
|
300
696
|
}
|
|
301
697
|
// ─── Suggestion queue (P1-1 optional human-confirm mode) ──────────────────
|
|
302
698
|
/**
|
|
@@ -311,7 +707,7 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
311
707
|
* `hits: 1`.
|
|
312
708
|
* @param input - the proposal to record.
|
|
313
709
|
* @returns the stored suggestion (existing row updated, or newly created).
|
|
314
|
-
* @throws when the proposed content fails validation or the scanner.
|
|
710
|
+
* @throws when the proposed content or summary fails validation or the scanner.
|
|
315
711
|
*/
|
|
316
712
|
async observeSuggestion(input) {
|
|
317
713
|
validateProjectScope({ ...input, projectName: input.projectName ?? (input.targetEntryId !== undefined ? this.entries.get(input.targetEntryId)?.projectName : undefined) });
|
|
@@ -320,9 +716,13 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
320
716
|
if (!scan.allowed) {
|
|
321
717
|
throw new Error(`suggestion content rejected by scanner: ${scan.reasons.join('; ')}`);
|
|
322
718
|
}
|
|
719
|
+
const summaryScan = scanContent(input.summary ?? '');
|
|
720
|
+
if (!summaryScan.allowed) {
|
|
721
|
+
throw new Error(`suggestion summary rejected by scanner: ${summaryScan.reasons.join('; ')}`);
|
|
722
|
+
}
|
|
323
723
|
const now = Date.now();
|
|
324
724
|
// Match against existing proposals: same target entry wins outright;
|
|
325
|
-
// otherwise nearest-content in the same scope above the
|
|
725
|
+
// otherwise nearest-content in the same scope above the dup threshold.
|
|
326
726
|
let matched;
|
|
327
727
|
for (const [, suggestion] of this.suggestions.entries()) {
|
|
328
728
|
if (input.targetEntryId !== undefined) {
|
|
@@ -334,7 +734,11 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
334
734
|
}
|
|
335
735
|
if (suggestion.scope !== input.scope)
|
|
336
736
|
continue;
|
|
337
|
-
|
|
737
|
+
// The live queue is the corpus: at queue scale (≤ cap rows) rebuilding
|
|
738
|
+
// the df table per row would be wasteful, but the queue is tiny — and
|
|
739
|
+
// the table only needs building once per observe call, not per row.
|
|
740
|
+
const stats = buildCorpusStats([input.content, suggestion.content]);
|
|
741
|
+
const similarity = weightedOverlapSimilarity(stats, uniqueTokens(input.content), uniqueTokens(suggestion.content));
|
|
338
742
|
if (similarity > SUGGESTION_DUP_THRESHOLD) {
|
|
339
743
|
matched = suggestion;
|
|
340
744
|
break;
|
|
@@ -454,6 +858,47 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
454
858
|
await this.suggestions.delete(all[i].id);
|
|
455
859
|
}
|
|
456
860
|
}
|
|
861
|
+
/**
|
|
862
|
+
* Trim the entries table to {@link DEFAULT_ENTRIES_CAP} / the configured
|
|
863
|
+
* `entriesCap` after a successful write. Awaited inline like
|
|
864
|
+
* {@link trimSuggestions} (not failure-shielded like {@link trimAudit}):
|
|
865
|
+
* an eviction failure propagates to the add caller even though the added
|
|
866
|
+
* row landed. Eviction runs in one pass down TO the cap (not one per add),
|
|
867
|
+
* ordered by the use signal — pinned entries are exempt; the rest go by
|
|
868
|
+
* ascending `accessCount` (never-recalled reads as 0), then ascending
|
|
869
|
+
* `lastRecalledAt` ?? `createdAt` (longest-unrecalled first). When every
|
|
870
|
+
* remaining candidate is protected (e.g. all pinned), the table is allowed
|
|
871
|
+
* to exceed the cap — the cap is a soft target, eviction never deletes a
|
|
872
|
+
* protected entry to reach it.
|
|
873
|
+
*
|
|
874
|
+
* Audit trail: the eviction records `op: 'remove'`, `source: 'janitor'`.
|
|
875
|
+
* The janitor source names system-initiated lifecycle writes (decay,
|
|
876
|
+
* dormancy), and `AuditSource` is a fixed schema enum — extending it would
|
|
877
|
+
* change the durable record shape — so the store's own eviction reuses it.
|
|
878
|
+
*/
|
|
879
|
+
async trimEntries() {
|
|
880
|
+
if (this.entries.size <= this.entriesCap)
|
|
881
|
+
return;
|
|
882
|
+
const all = [];
|
|
883
|
+
for (const [, entry] of this.entries.entries())
|
|
884
|
+
all.push(entry);
|
|
885
|
+
// Eviction order (ascending = evicted first): pinned last/never, then
|
|
886
|
+
// fewest recalls, then longest since last recall (never-recalled entries
|
|
887
|
+
// date from creation).
|
|
888
|
+
all.sort((a, b) => (a.pinned === true ? 1 : 0) - (b.pinned === true ? 1 : 0)
|
|
889
|
+
|| (a.accessCount ?? 0) - (b.accessCount ?? 0)
|
|
890
|
+
|| (a.lastRecalledAt ?? a.createdAt) - (b.lastRecalledAt ?? b.createdAt));
|
|
891
|
+
const excess = all.length - this.entriesCap;
|
|
892
|
+
for (let i = 0; i < excess; i++) {
|
|
893
|
+
const victim = all[i];
|
|
894
|
+
if (victim.pinned === true)
|
|
895
|
+
break;
|
|
896
|
+
const removed = await this.entries.delete(victim.id);
|
|
897
|
+
if (removed) {
|
|
898
|
+
await this.appendAudit('remove', victim.id, victim, 'janitor', undefined);
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
}
|
|
457
902
|
async pin(id) {
|
|
458
903
|
const existing = this.entries.get(id);
|
|
459
904
|
if (existing === undefined)
|
|
@@ -497,6 +942,38 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
497
942
|
await this.appendAudit('update', id, updated, 'ui', undefined);
|
|
498
943
|
return updated;
|
|
499
944
|
}
|
|
945
|
+
/**
|
|
946
|
+
* Supersede one entry (batch-consolidation seam, Step 1.3): flip `status`
|
|
947
|
+
* to `'superseded'`, stamp `supersededBy`, and append the caller's visible
|
|
948
|
+
* annotation to the content in one atomic write. Idempotent on an already
|
|
949
|
+
* superseded entry (returned unchanged, no audit). The audit trail records
|
|
950
|
+
* source `'janitor'` — the `AuditSource` enum has no consolidation member,
|
|
951
|
+
* and extending the durable enum shape is not this seam's business (the
|
|
952
|
+
* same rationale as {@link trimEntries}'s eviction records).
|
|
953
|
+
* @param id - the entry being superseded.
|
|
954
|
+
* @param supersededBy - the id of the newer, contradicting entry.
|
|
955
|
+
* @param annotate - optional content annotation (receives the pre-stamp
|
|
956
|
+
* entry, returns the new content); called before the write so the
|
|
957
|
+
* annotation lands atomically with the status flip.
|
|
958
|
+
* @returns the superseded entry, or `undefined` when the id does not exist.
|
|
959
|
+
*/
|
|
960
|
+
async supersedeEntry(id, supersededBy, annotate) {
|
|
961
|
+
const existing = this.entries.get(id);
|
|
962
|
+
if (existing === undefined)
|
|
963
|
+
return undefined;
|
|
964
|
+
if (existing.status === 'superseded')
|
|
965
|
+
return existing;
|
|
966
|
+
const annotated = annotate === undefined ? existing.content : annotate(existing);
|
|
967
|
+
const updated = {
|
|
968
|
+
...existing,
|
|
969
|
+
content: annotated,
|
|
970
|
+
status: 'superseded',
|
|
971
|
+
supersededBy,
|
|
972
|
+
};
|
|
973
|
+
await this.entries.put(id, updated);
|
|
974
|
+
await this.appendAudit('update', id, updated, 'janitor', undefined);
|
|
975
|
+
return updated;
|
|
976
|
+
}
|
|
500
977
|
/**
|
|
501
978
|
* Run the janitor pass with the lifecycle's two-tier policy:
|
|
502
979
|
* - `project` entries overdue by `decayDays` (pinned exempt) are REMOVED
|
|
@@ -504,6 +981,10 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
504
981
|
* - `global`/`user` entries overdue (pinned exempt) are soft-decayed: the
|
|
505
982
|
* first overdue pass stamps `staleSince`, which hides them from injection
|
|
506
983
|
* surfaces while keeping them searchable; a later recall clears the stamp.
|
|
984
|
+
* The snapshot iteration is only a pre-filter: every delete and stamp
|
|
985
|
+
* re-decides on the record current at its write-chain slot (the same
|
|
986
|
+
* atomic RMW discipline as `stampRecalled`), so a pin landing between the
|
|
987
|
+
* snapshot and the write is honored.
|
|
507
988
|
* @param decayDays - days without recall before the policy applies.
|
|
508
989
|
* @param now - evaluation clock; defaults to wall time (tests inject fixed clocks).
|
|
509
990
|
* @returns the number of project entries removed.
|
|
@@ -513,28 +994,84 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
513
994
|
return 0;
|
|
514
995
|
const decayMs = decayDays * 24 * 60 * 60 * 1000;
|
|
515
996
|
let removed = 0;
|
|
516
|
-
for (const [,
|
|
517
|
-
if (
|
|
997
|
+
for (const [, snapshot] of this.entries.entries()) {
|
|
998
|
+
if (snapshot.pinned === true)
|
|
518
999
|
continue;
|
|
519
|
-
//
|
|
520
|
-
|
|
1000
|
+
// Snapshot pass is a cheap pre-filter only: every decision below is
|
|
1001
|
+
// re-made on the record current at its write-chain slot, so a pin that
|
|
1002
|
+
// lands between this iteration and the write is still honored.
|
|
1003
|
+
const lastActive = snapshot.lastRecalledAt ?? snapshot.createdAt;
|
|
521
1004
|
if (now - lastActive < decayMs)
|
|
522
1005
|
continue;
|
|
523
|
-
if (
|
|
524
|
-
// Hard decay:
|
|
525
|
-
|
|
1006
|
+
if (snapshot.scope === 'project') {
|
|
1007
|
+
// Hard decay: KvTable.update cannot express delete, so the pinned
|
|
1008
|
+
// re-check runs as a guard update (returning `current` unchanged —
|
|
1009
|
+
// one empty write) and only an unpinned result reaches the delete.
|
|
1010
|
+
// Residual TOCTOU window: a pin landing AFTER the guard's chain slot
|
|
1011
|
+
// but BEFORE the delete is not observed; the single-process write
|
|
1012
|
+
// chain serializes these two calls, but nothing narrower than
|
|
1013
|
+
// "guard → delete" exists on KvTable to close the gap. Covered by
|
|
1014
|
+
// the janitor-pin-toctou contract test.
|
|
1015
|
+
let pinnedAtSlot = false;
|
|
1016
|
+
try {
|
|
1017
|
+
await this.entries.update(snapshot.id, current => {
|
|
1018
|
+
pinnedAtSlot = current.pinned === true;
|
|
1019
|
+
return current;
|
|
1020
|
+
});
|
|
1021
|
+
}
|
|
1022
|
+
catch (error) {
|
|
1023
|
+
// A missing id means the entry was removed by another caller
|
|
1024
|
+
// between the snapshot and this guard — nothing left to decay.
|
|
1025
|
+
if (error instanceof Error && !error.message.includes('no record')) {
|
|
1026
|
+
this.reportFailure('janitor', error);
|
|
1027
|
+
}
|
|
1028
|
+
}
|
|
1029
|
+
if (pinnedAtSlot)
|
|
1030
|
+
continue;
|
|
1031
|
+
const didRemove = await this.entries.delete(snapshot.id);
|
|
526
1032
|
if (didRemove) {
|
|
527
1033
|
removed++;
|
|
528
|
-
await this.appendAudit('remove',
|
|
1034
|
+
await this.appendAudit('remove', snapshot.id, snapshot, 'janitor', undefined);
|
|
529
1035
|
}
|
|
530
1036
|
continue;
|
|
531
1037
|
}
|
|
532
|
-
// global/user: soft decay only — stamp once, never auto-delete.
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
1038
|
+
// global/user: soft decay only — stamp once, never auto-delete. The
|
|
1039
|
+
// whole decision re-runs on the record current at its chain slot, so
|
|
1040
|
+
// the stamp is atomic: a pin or a fresh recall that lands between the
|
|
1041
|
+
// snapshot and here skips it, and an already-stamped entry is left
|
|
1042
|
+
// untouched. A model-assessed importance of 4–5 extends the grace
|
|
1043
|
+
// window 1.5×: a "this matters" judgment should survive a longer quiet
|
|
1044
|
+
// period, while low or unassessed entries keep the plain clock. Recall
|
|
1045
|
+
// (accessCount) stays the stronger signal — it clears decay outright
|
|
1046
|
+
// via stampRecalled.
|
|
1047
|
+
let didStamp = false;
|
|
1048
|
+
let stamped;
|
|
1049
|
+
try {
|
|
1050
|
+
stamped = await this.entries.update(snapshot.id, current => {
|
|
1051
|
+
const lastActiveNow = current.lastRecalledAt ?? current.createdAt;
|
|
1052
|
+
if (now - lastActiveNow < decayMs)
|
|
1053
|
+
return current;
|
|
1054
|
+
const graceFactor = current.importance !== undefined && current.importance >= 4 ? 1.5 : 1;
|
|
1055
|
+
if (now - lastActiveNow < decayMs * graceFactor)
|
|
1056
|
+
return current;
|
|
1057
|
+
if (current.pinned === true)
|
|
1058
|
+
return current;
|
|
1059
|
+
if (current.staleSince !== undefined)
|
|
1060
|
+
return current;
|
|
1061
|
+
didStamp = true;
|
|
1062
|
+
return { ...current, staleSince: now };
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
catch (error) {
|
|
1066
|
+
// A missing id (entry removed between the snapshot and this slot) or
|
|
1067
|
+
// a domain going away mid-pass is a normal end of life for a stamp.
|
|
1068
|
+
if (error instanceof Error && !error.message.includes('no record')) {
|
|
1069
|
+
this.reportFailure('janitor', error);
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
if (didStamp && stamped !== undefined) {
|
|
1073
|
+
await this.appendAudit('update', snapshot.id, stamped, 'janitor', undefined);
|
|
1074
|
+
}
|
|
538
1075
|
}
|
|
539
1076
|
return removed;
|
|
540
1077
|
}
|
|
@@ -575,8 +1112,16 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
575
1112
|
stale,
|
|
576
1113
|
...lastActivityTs !== undefined ? { lastActivityTs } : {},
|
|
577
1114
|
...lastExtractionTs !== undefined ? { lastExtractionTs } : {},
|
|
1115
|
+
...this.failureCounts.size > 0 ? { backgroundFailures: Object.fromEntries(this.failureCounts) } : {},
|
|
578
1116
|
};
|
|
579
1117
|
}
|
|
1118
|
+
async getRaw(id) {
|
|
1119
|
+
const entry = this.entries.get(id);
|
|
1120
|
+
if (entry === undefined)
|
|
1121
|
+
return undefined;
|
|
1122
|
+
await this.appendAudit('readRaw', id, entry, 'ui', undefined);
|
|
1123
|
+
return entry;
|
|
1124
|
+
}
|
|
580
1125
|
exportAuditLog() {
|
|
581
1126
|
const all = [];
|
|
582
1127
|
for (const [, record] of this.audit.entries())
|
|
@@ -606,8 +1151,9 @@ export class DomainMemoryStore extends MemoryStore {
|
|
|
606
1151
|
await this.audit.put(record.id, record);
|
|
607
1152
|
await this.trimAudit();
|
|
608
1153
|
}
|
|
609
|
-
catch {
|
|
1154
|
+
catch (error) {
|
|
610
1155
|
// Best-effort: an audit failure must never propagate to the caller.
|
|
1156
|
+
this.reportFailure('audit-append', error);
|
|
611
1157
|
}
|
|
612
1158
|
}
|
|
613
1159
|
/** Trim the audit table to the cap, deleting the oldest records. */
|
|
@@ -629,4 +1175,18 @@ function preview(content) {
|
|
|
629
1175
|
const p = content.slice(0, 100);
|
|
630
1176
|
return scanContent(p).allowed ? p : '[content redacted]';
|
|
631
1177
|
}
|
|
1178
|
+
/** Importances land in 1–5 regardless of what the caller passed in. */
|
|
1179
|
+
const IMPORTANCE_MIN = 1;
|
|
1180
|
+
const IMPORTANCE_MAX = 5;
|
|
1181
|
+
/**
|
|
1182
|
+
* Project an optional caller-supplied importance onto the entry-field spread:
|
|
1183
|
+
* absent input spreads nothing (stored value stands); out-of-range input is
|
|
1184
|
+
* clamped rather than rejected — a wrong assessment is not a protocol error.
|
|
1185
|
+
*/
|
|
1186
|
+
function clampImportance(importance) {
|
|
1187
|
+
if (importance === undefined || Number.isNaN(importance))
|
|
1188
|
+
return {};
|
|
1189
|
+
const clamped = Math.min(IMPORTANCE_MAX, Math.max(IMPORTANCE_MIN, Math.round(importance)));
|
|
1190
|
+
return { importance: clamped };
|
|
1191
|
+
}
|
|
632
1192
|
//# sourceMappingURL=index.js.map
|