dsh-cross-memory 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +247 -2
  3. package/cordis.patch.yml +27 -0
  4. package/docs/DETAIL.md +13 -0
  5. package/docs/DETAIL.zh.md +17 -0
  6. package/icon.svg +1 -0
  7. package/lib/backfill.js +273 -0
  8. package/lib/citations.js +305 -0
  9. package/lib/client.js +1550 -0
  10. package/lib/config.js +736 -0
  11. package/lib/consolidate.js +1119 -0
  12. package/lib/extract.js +570 -0
  13. package/lib/gate.js +137 -0
  14. package/lib/git-origin.js +224 -0
  15. package/lib/index.js +4475 -0
  16. package/lib/log.js +260 -0
  17. package/lib/loops.js +186 -0
  18. package/lib/notices.js +195 -0
  19. package/lib/notify.js +33 -0
  20. package/lib/persona.js +112 -0
  21. package/lib/query.js +93 -0
  22. package/lib/raw-recall.js +286 -0
  23. package/lib/reflection.js +291 -0
  24. package/lib/remote.js +455 -0
  25. package/lib/render.js +678 -0
  26. package/lib/retention.js +64 -0
  27. package/lib/schedule.js +245 -0
  28. package/lib/search.js +1068 -0
  29. package/lib/skills.js +220 -0
  30. package/lib/state.js +701 -0
  31. package/lib/storage.js +1424 -0
  32. package/lib/sync-runtime.js +268 -0
  33. package/lib/sync.js +620 -0
  34. package/lib/test/activity.test.js +74 -0
  35. package/lib/test/archive.test.js +182 -0
  36. package/lib/test/backfill.test.js +144 -0
  37. package/lib/test/citations.test.js +91 -0
  38. package/lib/test/client-wiring.test.js +134 -0
  39. package/lib/test/consolidate-job.test.js +95 -0
  40. package/lib/test/consolidate.test.js +430 -0
  41. package/lib/test/consolidation-selection.test.js +152 -0
  42. package/lib/test/dedupe-keys.test.js +230 -0
  43. package/lib/test/delta.test.js +93 -0
  44. package/lib/test/derived.test.js +110 -0
  45. package/lib/test/disputes-panel.test.js +314 -0
  46. package/lib/test/eval.test.js +171 -0
  47. package/lib/test/expand.test.js +164 -0
  48. package/lib/test/extract.test.js +1020 -0
  49. package/lib/test/git-origin.test.js +189 -0
  50. package/lib/test/injection.test.js +440 -0
  51. package/lib/test/kind-filter.test.js +49 -0
  52. package/lib/test/legacy-state.test.js +69 -0
  53. package/lib/test/log.test.js +156 -0
  54. package/lib/test/loops.test.js +86 -0
  55. package/lib/test/memory.test.js +855 -0
  56. package/lib/test/notices.test.js +140 -0
  57. package/lib/test/persona.test.js +73 -0
  58. package/lib/test/prefilter.test.js +73 -0
  59. package/lib/test/preset.test.js +77 -0
  60. package/lib/test/raw-recall.test.js +186 -0
  61. package/lib/test/recall.test.js +433 -0
  62. package/lib/test/reflection.test.js +64 -0
  63. package/lib/test/remote.test.js +227 -0
  64. package/lib/test/retention.test.js +117 -0
  65. package/lib/test/retrieval.test.js +142 -0
  66. package/lib/test/rotation.test.js +228 -0
  67. package/lib/test/schedule.test.js +112 -0
  68. package/lib/test/settings-card.test.js +58 -0
  69. package/lib/test/skills.test.js +129 -0
  70. package/lib/test/state.test.js +212 -0
  71. package/lib/test/subagent-contract.test.js +139 -0
  72. package/lib/test/sweep.test.js +159 -0
  73. package/lib/test/sync.test.js +314 -0
  74. package/lib/test/time.test.js +171 -0
  75. package/lib/time.js +303 -0
  76. package/lib/tool.js +330 -0
  77. package/lib/types/backfill.d.ts +96 -0
  78. package/lib/types/citations.d.ts +105 -0
  79. package/lib/types/config.d.ts +811 -0
  80. package/lib/types/consolidate.d.ts +742 -0
  81. package/lib/types/extract.d.ts +352 -0
  82. package/lib/types/gate.d.ts +83 -0
  83. package/lib/types/git-origin.d.ts +23 -0
  84. package/lib/types/index.d.ts +1316 -0
  85. package/lib/types/log.d.ts +144 -0
  86. package/lib/types/loops.d.ts +82 -0
  87. package/lib/types/notices.d.ts +117 -0
  88. package/lib/types/notify.d.ts +12 -0
  89. package/lib/types/persona.d.ts +43 -0
  90. package/lib/types/query.d.ts +45 -0
  91. package/lib/types/raw-recall.d.ts +84 -0
  92. package/lib/types/reflection.d.ts +122 -0
  93. package/lib/types/remote.d.ts +233 -0
  94. package/lib/types/render.d.ts +286 -0
  95. package/lib/types/retention.d.ts +66 -0
  96. package/lib/types/schedule.d.ts +116 -0
  97. package/lib/types/search.d.ts +583 -0
  98. package/lib/types/skills.d.ts +71 -0
  99. package/lib/types/state.d.ts +294 -0
  100. package/lib/types/storage.d.ts +458 -0
  101. package/lib/types/sync-runtime.d.ts +103 -0
  102. package/lib/types/sync.d.ts +222 -0
  103. package/lib/types/test/activity.test.d.ts +1 -0
  104. package/lib/types/test/archive.test.d.ts +1 -0
  105. package/lib/types/test/backfill.test.d.ts +1 -0
  106. package/lib/types/test/citations.test.d.ts +1 -0
  107. package/lib/types/test/client-wiring.test.d.ts +1 -0
  108. package/lib/types/test/consolidate-job.test.d.ts +1 -0
  109. package/lib/types/test/consolidate.test.d.ts +1 -0
  110. package/lib/types/test/consolidation-selection.test.d.ts +1 -0
  111. package/lib/types/test/dedupe-keys.test.d.ts +1 -0
  112. package/lib/types/test/delta.test.d.ts +1 -0
  113. package/lib/types/test/derived.test.d.ts +1 -0
  114. package/lib/types/test/disputes-panel.test.d.ts +1 -0
  115. package/lib/types/test/eval.test.d.ts +1 -0
  116. package/lib/types/test/expand.test.d.ts +1 -0
  117. package/lib/types/test/extract.test.d.ts +1 -0
  118. package/lib/types/test/git-origin.test.d.ts +1 -0
  119. package/lib/types/test/injection.test.d.ts +1 -0
  120. package/lib/types/test/kind-filter.test.d.ts +1 -0
  121. package/lib/types/test/legacy-state.test.d.ts +1 -0
  122. package/lib/types/test/log.test.d.ts +1 -0
  123. package/lib/types/test/loops.test.d.ts +1 -0
  124. package/lib/types/test/memory.test.d.ts +1 -0
  125. package/lib/types/test/notices.test.d.ts +1 -0
  126. package/lib/types/test/persona.test.d.ts +1 -0
  127. package/lib/types/test/prefilter.test.d.ts +1 -0
  128. package/lib/types/test/preset.test.d.ts +1 -0
  129. package/lib/types/test/raw-recall.test.d.ts +1 -0
  130. package/lib/types/test/recall.test.d.ts +1 -0
  131. package/lib/types/test/reflection.test.d.ts +1 -0
  132. package/lib/types/test/remote.test.d.ts +1 -0
  133. package/lib/types/test/retention.test.d.ts +1 -0
  134. package/lib/types/test/retrieval.test.d.ts +1 -0
  135. package/lib/types/test/rotation.test.d.ts +1 -0
  136. package/lib/types/test/schedule.test.d.ts +1 -0
  137. package/lib/types/test/settings-card.test.d.ts +1 -0
  138. package/lib/types/test/skills.test.d.ts +1 -0
  139. package/lib/types/test/state.test.d.ts +1 -0
  140. package/lib/types/test/subagent-contract.test.d.ts +1 -0
  141. package/lib/types/test/sweep.test.d.ts +1 -0
  142. package/lib/types/test/sync.test.d.ts +1 -0
  143. package/lib/types/test/time.test.d.ts +1 -0
  144. package/lib/types/time.d.ts +67 -0
  145. package/lib/types/tool.d.ts +9 -0
  146. package/lib/types/types.d.ts +374 -0
  147. package/lib/types/workspace.d.ts +20 -0
  148. package/lib/types.js +47 -0
  149. package/lib/workspace.js +65 -0
  150. package/locale/en.json +7 -0
  151. package/locale/zh.json +7 -0
  152. package/package.json +126 -4
@@ -0,0 +1,1020 @@
1
+ /**
2
+ * Background-extraction tests for {@link MemoriesRuntime}.
3
+ *
4
+ * The extractor is the one path that normally needs a live model, so these
5
+ * tests drive it through a fake LLM runtime and a synthetic session surface.
6
+ * They pin the parts that matter: only human/assistant prose is read, the
7
+ * watermark advances so a session is never mined twice, secrets are redacted
8
+ * before anything is written, and a failing call leaves the store untouched.
9
+ *
10
+ * @module dsh-cross-memory/test/extract.test
11
+ */
12
+ import assert from 'node:assert/strict';
13
+ import { mkdtemp, rm } from 'node:fs/promises';
14
+ import { tmpdir } from 'node:os';
15
+ import { join } from 'node:path';
16
+ import test from 'node:test';
17
+ import { MemoriesRuntime } from '../index.js';
18
+ import { EXTRACT_JSON_SCHEMA, bindEvidence, collectWindow, parseExtraction, redactSecrets, runExtraction } from '../extract.js';
19
+ import { normalizeSettings } from '../config.js';
20
+ import { peakDelayMs } from '../schedule.js';
21
+ /**
22
+ * Project entries this session actually maps to.
23
+ *
24
+ * The scope root is resolved from the session cwd by walking up for project
25
+ * markers (see resolveProjectRoot); inside the monorepo that walks past this
26
+ * package to the workspace root, so a test that hard-coded process.cwd() asserted
27
+ * against a directory the plugin never writes to.
28
+ */
29
+ async function projectEntries(runtime, session) {
30
+ return runtime.store.list('project', await runtime.projectRoot(session), { fresh: true });
31
+ }
32
+ /** A streaming text delta in the shape the assembler consumes. */
33
+ function textChunk(text, index = 0) {
34
+ return { type: 'text-delta', index, text };
35
+ }
36
+ /** The terminal chunk of a successful stream. */
37
+ function stopChunk() {
38
+ return { type: 'finish', reason: { kind: 'stop' } };
39
+ }
40
+ /** A fake LLM runtime that replays one canned reply. */
41
+ function fakeLlm(reply, seen = {}) {
42
+ return {
43
+ stream: (options) => {
44
+ seen.system = options.system;
45
+ seen.user = options.messages.map((message) => message.content.filter((block) => block.type === 'text').map((block) => block.text ?? '').join('')).join('\n');
46
+ return (async function* chunks() {
47
+ yield textChunk(withQuote(reply, transcriptQuote(options)));
48
+ yield stopChunk();
49
+ })();
50
+ },
51
+ };
52
+ }
53
+ /**
54
+ * The first user line of the framed prompt, quoted the way a model would.
55
+ *
56
+ * The extractor is asked to copy a verbatim passage from the transcript, and
57
+ * this fake copies the first user message so tests of other behaviour keep
58
+ * their hand-written replies short. Evidence checks themselves get dedicated
59
+ * tests with explicit quotes below.
60
+ */
61
+ function transcriptQuote(options) {
62
+ const prompt = options.messages
63
+ .map((message) => message.content.filter((block) => block.type === 'text').map((block) => block.text ?? '').join(''))
64
+ .join('\n');
65
+ const line = /(?:^|\n)(?:USER|ASSISTANT): ([^\n]+)/u.exec(prompt)?.[1];
66
+ return line === undefined ? undefined : line.trim().slice(0, 160);
67
+ }
68
+ /** Add `quote` to every memory of a canned reply that does not already carry one. */
69
+ function withQuote(reply, quote) {
70
+ if (quote === undefined || quote.length === 0)
71
+ return reply;
72
+ const start = reply.indexOf('{');
73
+ const end = reply.lastIndexOf('}');
74
+ if (start < 0 || end <= start)
75
+ return reply;
76
+ try {
77
+ const value = JSON.parse(reply.slice(start, end + 1));
78
+ if (!Array.isArray(value.memories))
79
+ return reply;
80
+ for (const item of value.memories) {
81
+ if (typeof item !== 'object' || item === null)
82
+ continue;
83
+ const record = item;
84
+ if (record['quote'] === undefined)
85
+ record['quote'] = quote;
86
+ }
87
+ return JSON.stringify(value);
88
+ }
89
+ catch {
90
+ return reply;
91
+ }
92
+ }
93
+ /** A session stand-in with a controllable surface. */
94
+ function stubSession(cwd, events, id = 'extract-session') {
95
+ const nodes = events.map((event) => event.seq);
96
+ const bySeq = new Map(events.map((event) => [event.seq, event]));
97
+ return {
98
+ id,
99
+ header: { version: 0, id, createdAt: 0, cwd, isSeeded: false },
100
+ surface: { nodes },
101
+ eventAt: (seq) => {
102
+ const event = bySeq.get(seq);
103
+ if (event === undefined)
104
+ return undefined;
105
+ if (event.role === 'user') {
106
+ return {
107
+ type: 'user/message',
108
+ data: {
109
+ content: [{ type: 'text', text: event.text }],
110
+ source: event.source === 'plugin' ? { kind: 'plugin:other' } : { kind: 'user' },
111
+ },
112
+ };
113
+ }
114
+ return {
115
+ type: 'assistant/message',
116
+ data: {
117
+ message: { role: 'assistant', content: [{ type: 'text', text: event.text }], source: { kind: 'model' } },
118
+ },
119
+ };
120
+ },
121
+ requestHeader: () => ({ config: { provider: 'fake-provider', model: 'fake-model' } }),
122
+ /** Grow the surface mid-test, the way a conversation does. */
123
+ append: (event) => {
124
+ bySeq.set(event.seq, event);
125
+ nodes.push(event.seq);
126
+ },
127
+ };
128
+ }
129
+ /**
130
+ * Grow a stub session mid-test, the way a conversation does.
131
+ *
132
+ * The real `Session.append` demands surface placement metadata that a synthetic
133
+ * event has no source for, so this reaches the stub's own appender — the one
134
+ * boundary the test itself built.
135
+ *
136
+ * @param session - the stub to grow.
137
+ * @param event - the message to add at the tail.
138
+ */
139
+ function grow(session, event) {
140
+ const stub = session;
141
+ stub.append(event);
142
+ }
143
+ /** A context whose only service is the fake LLM. */
144
+ function stubContext(llm) {
145
+ return {
146
+ get: (name) => (name === 'llm' ? llm : undefined),
147
+ logger: { info: () => undefined, warn: () => undefined, debug: () => undefined },
148
+ };
149
+ }
150
+ test('redactSecrets removes credential-shaped text and keeps prose', () => {
151
+ assert.equal(redactSecrets('use key sk-abcdefghijklmnopqrstuvwx now'), 'use key [redacted] now');
152
+ assert.equal(redactSecrets('token: ghp_abcdefghijklmnopqrstuvwxyz01'), '[redacted]');
153
+ assert.equal(redactSecrets('AWS AKIAABCDEFGHIJKLMNOP here'), 'AWS [redacted] here');
154
+ assert.equal(redactSecrets('Authorization: Bearer abcdefghijklmnopqrstuvwxyz'), 'Authorization: [redacted]');
155
+ assert.equal(redactSecrets('api_key = "supersecretvalue"'), '[redacted]');
156
+ assert.equal(redactSecrets('plain prose about pnpm'), 'plain prose about pnpm');
157
+ });
158
+ test('parseExtraction keeps the string keys and drops the rest', () => {
159
+ const parsed = parseExtraction('{"memories":[{"scope":"global","title":"Prefer pnpm","body":"Use pnpm.","keys":["monorepo",7]}]}', 5, 'session-1');
160
+ assert.deepEqual([...parsed.drafts[0]?.keys ?? []], ['monorepo']);
161
+ // A reply that omits keys is normal: they are an optimization, not a contract.
162
+ assert.deepEqual([...parseExtraction('{"memories":[{"scope":"global","title":"x","body":"y"}]}', 5, 's').drafts[0]?.keys ?? []], []);
163
+ });
164
+ test('parseExtraction accepts a bare object, a fenced object, and rejects junk', () => {
165
+ const payload = '{"summary":"The user set up a pnpm workflow.","memories":[{"scope":"global","title":"Prefer pnpm","body":"Use pnpm.","tags":["tooling"]}]}';
166
+ const parsed = parseExtraction(payload, 5, 'session-1');
167
+ assert.equal(parsed.drafts.length, 1);
168
+ assert.equal(parsed.summary, 'The user set up a pnpm workflow.');
169
+ assert.equal(parsed.drafts[0]?.sourceSession, 'session-1');
170
+ assert.equal(parseExtraction(`\`\`\`json\n${payload}\n\`\`\``, 5, 'session-1').drafts.length, 1);
171
+ assert.equal(parseExtraction('{"memories":[]}', 5, 'session-1').drafts.length, 0);
172
+ // A reply without a summary still parses; the evidence note then says so.
173
+ assert.equal(parseExtraction('{"memories":[]}', 5, 'session-1').summary, '');
174
+ assert.equal(parseExtraction('not json at all', 5, 'session-1').drafts.length, 0);
175
+ assert.equal(parseExtraction('{"memories":[{"scope":"elsewhere","title":"x","body":"y"}]}', 5, 'session-1').drafts.length, 0);
176
+ assert.equal(parseExtraction('{"memories":[{"scope":"global","title":"","body":"y"}]}', 5, 'session-1').drafts.length, 0);
177
+ const capped = parseExtraction(JSON.stringify({
178
+ memories: [1, 2, 3, 4].map((index) => ({ scope: 'global', title: `t${index}`, body: `b${index}` })),
179
+ }), 2, 'session-1');
180
+ assert.equal(capped.drafts.length, 2);
181
+ // What the cap threw away is reported, not silently lost: a pass that always
182
+ // lands exactly on the cap is otherwise indistinguishable from one that found
183
+ // exactly that many memories, which hides the knob that limits the store.
184
+ assert.equal(capped.dropped, 2);
185
+ assert.equal(parseExtraction('{"memories":[{"scope":"global","title":"only","body":"one"}]}', 5, 's').dropped, 0);
186
+ });
187
+ test('parseExtraction redacts secrets inside extracted memories and the summary', () => {
188
+ const parsed = parseExtraction('{"summary":"they pasted sk-abcdefghijklmnopqrstuvwx","memories":[{"scope":"global","title":"API key","body":"the key is sk-abcdefghijklmnopqrstuvwx"}]}', 5, 'session-1');
189
+ assert.equal(parsed.drafts[0]?.body, 'the key is [redacted]');
190
+ assert.equal(parsed.summary, 'they pasted [redacted]');
191
+ // A quote that is entirely a credential is dropped, not stored as "[redacted]":
192
+ // an evidence field reading "[redacted]" proves nothing.
193
+ const secretQuote = parseExtraction('{"memories":[{"scope":"global","title":"t","body":"b","appliesTo":"a","quote":"sk-abcdefghijklmnopqrstuvwx"}]}', 5, 'session-1');
194
+ assert.equal(secretQuote.drafts[0]?.quote, undefined);
195
+ });
196
+ test('bindEvidence accepts only a quote that appears verbatim in one message', () => {
197
+ const sources = [
198
+ { seq: 3, text: 'I always deploy with pnpm run ship.' },
199
+ { seq: 4, text: 'Also run tsc before publishing.' },
200
+ ];
201
+ const base = { scope: 'global', title: 't', body: 'b', tags: [] };
202
+ const bound = bindEvidence([
203
+ { ...base, title: 'exact', quote: 'I always deploy with pnpm run ship.' },
204
+ // Line wrapping changes whitespace, not the words; that still counts.
205
+ { ...base, title: 'wrapped', quote: 'Also run tsc\nbefore publishing.' },
206
+ { ...base, title: 'paraphrased', quote: 'I usually deploy with pnpm.' },
207
+ { ...base, title: 'too short', quote: 'pnpm' },
208
+ { ...base, title: 'missing' },
209
+ ], sources);
210
+ assert.deepEqual(bound.drafts.map((draft) => draft.title), ['exact', 'wrapped']);
211
+ assert.equal(bound.drafts[0]?.evidenceSeq, 3);
212
+ assert.equal(bound.drafts[1]?.evidenceSeq, 4);
213
+ assert.equal(bound.unsupported, 3);
214
+ });
215
+ test('collectWindow reads only human/assistant prose after the watermark', () => {
216
+ const session = stubSession('C:\\work', [
217
+ { seq: 1, role: 'user', text: 'old question' },
218
+ { seq: 2, role: 'assistant', text: 'old answer' },
219
+ { seq: 3, role: 'user', text: 'new question' },
220
+ { seq: 4, role: 'user', text: 'injected plugin context', source: 'plugin' },
221
+ { seq: 5, role: 'assistant', text: 'new answer' },
222
+ ]);
223
+ const window = collectWindow(session, 2, 10, 10_000);
224
+ assert.equal(window.lastSeq, 5);
225
+ assert.equal(window.messages, 2);
226
+ assert.match(window.text, /new question/u);
227
+ assert.match(window.text, /new answer/u);
228
+ assert.doesNotMatch(window.text, /old question/u);
229
+ assert.doesNotMatch(window.text, /injected plugin context/u);
230
+ });
231
+ test('collectWindow honours the message and character caps from the newest end', () => {
232
+ const events = Array.from({ length: 12 }, (_, index) => ({ seq: index + 1, role: 'user', text: `line ${index}` }));
233
+ const session = stubSession('C:\\work', events);
234
+ const byMessages = collectWindow(session, 0, 3, 100_000);
235
+ assert.equal(byMessages.messages, 3);
236
+ assert.match(byMessages.text, /line 11/u);
237
+ const byChars = collectWindow(session, 0, 100, 30);
238
+ assert.ok(byChars.text.length <= 30);
239
+ assert.match(byChars.text, /line 11/u);
240
+ });
241
+ test('the extraction JSON schema is closed and requires the documented fields', () => {
242
+ assert.equal(EXTRACT_JSON_SCHEMA.additionalProperties, false);
243
+ // The summary is required too: it becomes the evidence note behind the drafts.
244
+ // `memories` is declared first because a capped reply is only salvageable if
245
+ // the array was written before the prose (see EXTRACT_SYSTEM).
246
+ assert.deepEqual([...EXTRACT_JSON_SCHEMA.required], ['memories', 'summary']);
247
+ // `appliesTo` is required because it is the field that lets a paraphrased turn
248
+ // find the memory again; half the store was unsearchable without it.
249
+ // `quote` is required because it is the only evidence the code can check.
250
+ assert.deepEqual([...EXTRACT_JSON_SCHEMA.properties.memories.items.required], ['scope', 'title', 'body', 'appliesTo', 'quote']);
251
+ });
252
+ test('runExtraction sends the transcript and returns parsed drafts', async () => {
253
+ const seen = {};
254
+ const session = stubSession('C:\\work', [{ seq: 1, role: 'user', text: 'I always use pnpm here.' }]);
255
+ const outcome = await runExtraction(fakeLlm('{"memories":[{"scope":"project","title":"Use pnpm","body":"This repo uses pnpm.","tags":["tooling"]}]}', seen), {
256
+ session,
257
+ window: collectWindow(session, 0, 10, 10_000),
258
+ projectLabel: 'project:work',
259
+ maxOutputTokens: 512,
260
+ maxMemories: 5,
261
+ timeoutMs: 5_000,
262
+ signal: new AbortController().signal,
263
+ });
264
+ assert.equal(outcome.kind, 'memories');
265
+ assert.equal(outcome.kind === 'memories' ? outcome.drafts.length : 0, 1);
266
+ // The fake copied the user's line, so the draft carries the message it came from.
267
+ assert.equal(outcome.kind === 'memories' ? outcome.drafts[0]?.evidenceSeq : undefined, 1);
268
+ assert.match(seen.system ?? '', /durable, reusable facts/u);
269
+ assert.match(seen.system ?? '', /"quote"/u);
270
+ assert.match(seen.user ?? '', /I always use pnpm here/u);
271
+ assert.match(seen.user ?? '', /project:work/u);
272
+ });
273
+ test('a candidate whose quote is not in the transcript is dropped, not stored', async () => {
274
+ const session = stubSession('C:\\work', [
275
+ { seq: 1, role: 'user', text: 'I always use pnpm here.' },
276
+ { seq: 2, role: 'assistant', text: 'Then add a workspace file.' },
277
+ ]);
278
+ const reply = (quote) => ({
279
+ stream: () => (async function* chunks() {
280
+ yield textChunk(JSON.stringify({ memories: [{ scope: 'project', title: 'Use pnpm', body: 'This repo uses pnpm.', appliesTo: 'installing', quote }] }));
281
+ yield stopChunk();
282
+ })(),
283
+ });
284
+ const request = {
285
+ session,
286
+ window: collectWindow(session, 0, 10, 10_000),
287
+ projectLabel: 'project:work',
288
+ maxOutputTokens: 512,
289
+ maxMemories: 5,
290
+ timeoutMs: 5_000,
291
+ signal: new AbortController().signal,
292
+ };
293
+ // Paraphrasing the source is exactly the failure the check exists to catch.
294
+ const paraphrased = await runExtraction(reply('I usually use pnpm.'), request);
295
+ assert.deepEqual(paraphrased.kind === 'none' ? paraphrased.reason : paraphrased.kind, 'unsupported-evidence');
296
+ // An assistant line is a valid source too; the seq tells the reader which turn.
297
+ const fromAssistant = await runExtraction(reply('Then add a workspace file.'), request);
298
+ assert.equal(fromAssistant.kind === 'memories' ? fromAssistant.drafts[0]?.evidenceSeq : undefined, 2);
299
+ });
300
+ test('runExtraction reports an empty window and a missing route without calling the model', async () => {
301
+ const session = stubSession('C:\\work', [{ seq: 1, role: 'user', text: 'hi' }]);
302
+ const empty = await runExtraction(fakeLlm('{}'), {
303
+ session,
304
+ window: { text: '', lastSeq: undefined, messages: 0, sources: [] },
305
+ projectLabel: 'project:work',
306
+ maxOutputTokens: 128,
307
+ maxMemories: 1,
308
+ timeoutMs: 1_000,
309
+ signal: new AbortController().signal,
310
+ });
311
+ assert.deepEqual(empty, { kind: 'none', reason: 'empty-window' });
312
+ const routeless = stubSession('C:\\work', [{ seq: 1, role: 'user', text: 'hi' }]);
313
+ routeless.requestHeader = () => undefined;
314
+ const noRoute = await runExtraction(fakeLlm('{}'), {
315
+ session: routeless,
316
+ window: collectWindow(routeless, 0, 10, 1_000),
317
+ projectLabel: 'project:work',
318
+ maxOutputTokens: 128,
319
+ maxMemories: 1,
320
+ timeoutMs: 1_000,
321
+ signal: new AbortController().signal,
322
+ });
323
+ assert.deepEqual(noRoute, { kind: 'none', reason: 'no-route' });
324
+ });
325
+ test('a reply the output cap cut short is salvaged, never thrown', async () => {
326
+ const session = stubSession('C:\\work', [{ seq: 1, role: 'user', text: 'Hi, remember this workflow.' }]);
327
+ const truncated = {
328
+ stream: () => (async function* chunks() {
329
+ // Two complete memories, then the cut lands inside the third object.
330
+ yield textChunk('{"summary":"The user set up a workflow.","memories":['
331
+ + '{"scope":"project","title":"First fact","body":"Body one.","tags":["a"],"quote":"remember this workflow"},'
332
+ + '{"scope":"global","title":"Second fact","body":"Body two.","tags":["b"],"quote":"remember this workflow"},'
333
+ + '{"scope":"project","title":"Third fac');
334
+ yield { type: 'finish', reason: { kind: 'max-tokens' } };
335
+ })(),
336
+ };
337
+ const salvaged = await runExtraction(truncated, {
338
+ session,
339
+ window: collectWindow(session, 0, 10, 1_000),
340
+ projectLabel: 'project:work',
341
+ maxOutputTokens: 8,
342
+ maxMemories: 5,
343
+ timeoutMs: 1_000,
344
+ signal: new AbortController().signal,
345
+ });
346
+ assert.equal(salvaged.kind, 'memories');
347
+ if (salvaged.kind !== 'memories')
348
+ throw new Error('unreachable');
349
+ assert.deepEqual(salvaged.drafts.map((draft) => draft.title), ['First fact', 'Second fact']);
350
+ assert.equal(salvaged.summary, 'The user set up a workflow.');
351
+ assert.equal(salvaged.truncated, true, 'the caller can tell the cap was the binding limit');
352
+ });
353
+ test('a capped reply with nothing usable reports the cap instead of throwing', async () => {
354
+ const session = stubSession('C:\\work', [{ seq: 1, role: 'user', text: 'hi' }]);
355
+ const cutEarly = {
356
+ stream: () => (async function* chunks() {
357
+ yield textChunk('{"summary":"The user was just getting start');
358
+ yield { type: 'finish', reason: { kind: 'max-tokens' } };
359
+ })(),
360
+ };
361
+ const outcome = await runExtraction(cutEarly, {
362
+ session,
363
+ window: collectWindow(session, 0, 10, 1_000),
364
+ projectLabel: 'project:work',
365
+ maxOutputTokens: 8,
366
+ maxMemories: 1,
367
+ timeoutMs: 1_000,
368
+ signal: new AbortController().signal,
369
+ });
370
+ assert.deepEqual(outcome, { kind: 'none', reason: 'max-tokens', route: { provider: 'fake-provider', model: 'fake-model' } });
371
+ // Any other non-stop finish is reported the same way: a background pass must
372
+ // not turn a provider-side stop into an exception the user sees.
373
+ const aborted = {
374
+ stream: () => (async function* chunks() {
375
+ yield textChunk('{"memories":[');
376
+ yield { type: 'finish', reason: { kind: 'aborted' } };
377
+ })(),
378
+ };
379
+ assert.deepEqual(await runExtraction(aborted, {
380
+ session,
381
+ window: collectWindow(session, 0, 10, 1_000),
382
+ projectLabel: 'project:work',
383
+ maxOutputTokens: 8,
384
+ maxMemories: 1,
385
+ timeoutMs: 1_000,
386
+ signal: new AbortController().signal,
387
+ }), { kind: 'none', reason: 'incomplete', route: { provider: 'fake-provider', model: 'fake-model' } });
388
+ });
389
+ test('runExtraction stores drafts, advances the watermark, and never mines twice', async (t) => {
390
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-extract-'));
391
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'I always deploy with pnpm run ship.' }]);
392
+ const reply = '{"memories":[{"scope":"project","title":"Deploy with pnpm run ship","body":"Ship this project with `pnpm run ship`.","tags":["deploy"]}]}';
393
+ const runtime = new MemoriesRuntime(stubContext(fakeLlm(reply)), { memoriesDir: dir, autoExtract: true, extractTimeoutMs: 5_000 });
394
+ t.after(() => runtime.dispose());
395
+ const agent = { id: 'extract-session', session, status: 'idle' };
396
+ assert.equal((await runtime.runExtraction(agent)).stored, 1);
397
+ const stored = await projectEntries(runtime, session);
398
+ assert.equal(stored.length, 1);
399
+ assert.equal(stored[0]?.source, 'auto');
400
+ assert.match(stored[0]?.body ?? '', /pnpm run ship/u);
401
+ const state = runtime.state.getSession('extract-session');
402
+ assert.equal(state?.lastSeq, 1);
403
+ assert.equal(state?.contributed, true);
404
+ // Nothing new on the surface, so a second pass is a no-op.
405
+ assert.equal((await runtime.runExtraction(agent)).stored, 0);
406
+ assert.equal((await projectEntries(runtime, session)).length, 1);
407
+ t.after(() => rm(dir, { recursive: true, force: true }));
408
+ });
409
+ test('an llm service that arrives after activation is still used', async (t) => {
410
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-late-llm-'));
411
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'I always deploy with pnpm run ship.' }]);
412
+ const reply = '{"memories":[{"scope":"project","title":"Deploy with pnpm run ship","body":"Ship with `pnpm run ship`.","tags":["deploy"]}]}';
413
+ let live;
414
+ const ctx = {
415
+ get: (name) => (name === 'llm' ? live : undefined),
416
+ logger: { info: () => undefined, warn: () => undefined, debug: () => undefined },
417
+ };
418
+ const runtime = new MemoriesRuntime(ctx, { memoriesDir: dir, autoExtract: true, extractTimeoutMs: 5_000 });
419
+ t.after(() => runtime.dispose());
420
+ const agent = { id: 'extract-session', session, status: 'idle' };
421
+ // In 0.1.7 the service can be provided by a row that runs after this plugin's,
422
+ // so the activation snapshot is legitimately empty. Capturing it once — which
423
+ // is what the plugin used to do — turned every later pass into a silent no-op
424
+ // and left the watermark frozen for days.
425
+ const before = await runtime.runExtraction(agent);
426
+ assert.equal(before.stored, 0);
427
+ assert.equal(before.reason, 'no-llm', 'the refusal names the missing service');
428
+ live = fakeLlm(reply);
429
+ assert.equal((await runtime.runExtraction(agent)).stored, 1, 'the pass picks the service up when it appears');
430
+ assert.equal((await projectEntries(runtime, session)).length, 1);
431
+ t.after(() => rm(dir, { recursive: true, force: true }));
432
+ });
433
+ test('a session the registry knows but this process never settled is still mined', async (t) => {
434
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-registry-'));
435
+ const lines = [];
436
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'Always run the tests with npm test here.' }]);
437
+ const reply = '{"memories":[{"scope":"project","title":"Run npm test","body":"Use `npm test`.","tags":["test"]}]}';
438
+ const agent = {
439
+ id: 'extract-session',
440
+ session,
441
+ status: 'idle',
442
+ runMaintenance: (job) => job(new AbortController().signal),
443
+ };
444
+ const ctx = {
445
+ get: (name) => {
446
+ if (name === 'llm')
447
+ return fakeLlm(reply);
448
+ if (name === 'agents')
449
+ return { roots: () => [agent] };
450
+ return undefined;
451
+ },
452
+ logger: {
453
+ info: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
454
+ warn: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
455
+ debug: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
456
+ },
457
+ };
458
+ const runtime = new MemoriesRuntime(ctx, { memoriesDir: dir, autoExtract: true, extractTimeoutMs: 5_000 });
459
+ t.after(() => runtime.dispose());
460
+ // `tracked` only holds agents that settled in THIS process, so a restored
461
+ // window is invisible to it. The live registry is the second source.
462
+ await runtime.runPeriodicPass();
463
+ assert.equal((await projectEntries(runtime, session)).length, 1, 'a registry session is mined without ever settling here');
464
+ const pass = lines.find((line) => line.startsWith('dsh-cross-memory: extract pass:'));
465
+ assert.ok(pass !== undefined, 'the pass reports itself');
466
+ assert.match(pass, /%d live, %d considered/u, 'the line separates what was live from what was considered');
467
+ t.after(() => rm(dir, { recursive: true, force: true }));
468
+ });
469
+ test('one pass mines at most maxSessionsPerPass sessions, newest first', async (t) => {
470
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-cap-'));
471
+ const lines = [];
472
+ /** A session stub under its own id, so the pass has two candidates to choose from. */
473
+ const sessionWithId = (id, text) => stubSession(process.cwd(), [{ seq: 1, role: 'user', text }], id);
474
+ const older = sessionWithId('older-session', 'The older session said something worth remembering.');
475
+ const newer = sessionWithId('newer-session', 'The newer session said something worth remembering.');
476
+ const agents = [older, newer].map((session) => ({
477
+ id: session.id,
478
+ session,
479
+ status: 'idle',
480
+ runMaintenance: (job) => job(new AbortController().signal),
481
+ }));
482
+ const reply = '{"memories":[{"scope":"project","title":"A fact","body":"A fact.","tags":["x"]}]}';
483
+ const ctx = {
484
+ get: (name) => {
485
+ if (name === 'llm')
486
+ return fakeLlm(reply);
487
+ if (name === 'agents')
488
+ return { roots: () => agents };
489
+ return undefined;
490
+ },
491
+ logger: {
492
+ info: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
493
+ warn: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
494
+ debug: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
495
+ },
496
+ };
497
+ const runtime = new MemoriesRuntime(ctx, {
498
+ memoriesDir: dir,
499
+ autoExtract: true,
500
+ extractTimeoutMs: 5_000,
501
+ maxSessionsPerPass: 1,
502
+ });
503
+ t.after(() => runtime.dispose());
504
+ runtime.recordActivity(older, Date.now() - 60_000);
505
+ runtime.recordActivity(newer, Date.now());
506
+ await runtime.runPeriodicPass();
507
+ assert.ok((runtime.state.getSession('newer-session')?.at ?? 0) > 0, 'the newest session is mined first');
508
+ assert.equal(runtime.state.getSession('older-session')?.at, 0, 'the cap stops the pass after one model call');
509
+ const pass = lines.find((line) => line.startsWith('dsh-cross-memory: extract pass:'));
510
+ assert.match(pass ?? '', /pass-cap 1/u, 'a session held back by the cap is named as such, not as nothing-new');
511
+ t.after(() => rm(dir, { recursive: true, force: true }));
512
+ });
513
+ test('a capped extraction is a reported outcome, not an error the command layer sees', async (t) => {
514
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-cap-outcome-'));
515
+ const lines = [];
516
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'Something worth remembering.' }]);
517
+ let calls = 0;
518
+ const capped = {
519
+ stream: () => (async function* chunks() {
520
+ calls += 1;
521
+ yield textChunk('{"summary":"Cut off before the first memory.');
522
+ yield { type: 'finish', reason: { kind: 'max-tokens' } };
523
+ })(),
524
+ };
525
+ const ctx = {
526
+ get: (name) => (name === 'llm' ? capped : undefined),
527
+ logger: {
528
+ info: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
529
+ warn: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
530
+ debug: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
531
+ },
532
+ };
533
+ const runtime = new MemoriesRuntime(ctx, {
534
+ memoriesDir: dir,
535
+ autoExtract: true,
536
+ extractTimeoutMs: 5_000,
537
+ extractMaxOutputTokens: 128,
538
+ });
539
+ t.after(() => runtime.dispose());
540
+ const agent = {
541
+ id: 'extract-session',
542
+ session,
543
+ status: 'idle',
544
+ runMaintenance: (job) => job(new AbortController().signal),
545
+ };
546
+ // This is the exact path `/memories mine` drives. It used to throw, and the
547
+ // command layer reports a handler error verbatim to the user.
548
+ assert.deepEqual(await runtime.runExtraction(agent), { stored: 0, reason: 'max-tokens' });
549
+ // A capped reply is retryable. Consuming its window here would make every
550
+ // later periodic pass say `nothing-new` and permanently lose the transcript.
551
+ assert.equal(runtime.state.getSession('extract-session')?.lastSeq, undefined, 'the watermark stays put after a capped reply');
552
+ assert.ok(lines.some((line) => line.includes('raise extractMaxOutputTokens')), 'the cap is reported at info, with the knob to raise');
553
+ // The line also names the route: the ceiling alone does not explain a reply
554
+ // that produced nothing, and the inherited reasoning level is the usual cause.
555
+ assert.ok(lines.some((line) => line.includes('fake-provider/fake-model')), 'the capped line names the route it ran on');
556
+ assert.equal(await runtime.mineNow(agent), 0, 'the forced path returns a count instead of throwing');
557
+ assert.equal(calls, 2, 'a capped window is retried instead of being hidden behind the watermark');
558
+ t.after(() => rm(dir, { recursive: true, force: true }));
559
+ });
560
+ test('a capped window cools down, and retries the moment the cap it blamed changes', async (t) => {
561
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-cap-cooldown-'));
562
+ const lines = [];
563
+ const cooling = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'A cooling marker worth remembering.' }], 'cooling-session');
564
+ const fresh = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'A fresh marker worth remembering.' }], 'fresh-session');
565
+ const agentFor = (session) => ({
566
+ id: session.id,
567
+ session,
568
+ status: 'idle',
569
+ runMaintenance: (job) => job(new AbortController().signal),
570
+ });
571
+ const coolingAgent = agentFor(cooling);
572
+ const freshAgent = agentFor(fresh);
573
+ /** Which session each call was spent on, in order. The transcripts name it. */
574
+ const asked = [];
575
+ let capTheCoolingOne = true;
576
+ const llm = {
577
+ stream: (options) => {
578
+ const transcript = options.messages
579
+ .map((message) => message.content.filter((block) => block.type === 'text').map((block) => block.text ?? '').join(''))
580
+ .join('\n');
581
+ // The cooling session is mined more than once, and a later window no longer
582
+ // holds the first message — so the fresh session is the one identified by
583
+ // its text, and everything else is the session under test.
584
+ const fromFresh = transcript.includes('A fresh marker');
585
+ asked.push(fromFresh ? 'fresh' : 'cooling');
586
+ const capped = capTheCoolingOne && !fromFresh;
587
+ return (async function* chunks() {
588
+ if (capped) {
589
+ yield textChunk('{"summary":"Cut off before the first memory.');
590
+ yield { type: 'finish', reason: { kind: 'max-tokens' } };
591
+ return;
592
+ }
593
+ yield textChunk('{"memories":[{"scope":"project","title":"A fact","body":"A fact.","tags":["x"],"quote":"worth remembering"}]}');
594
+ yield stopChunk();
595
+ })();
596
+ },
597
+ };
598
+ const ctx = {
599
+ get: (name) => {
600
+ if (name === 'llm')
601
+ return llm;
602
+ if (name === 'agents')
603
+ return { roots: () => [coolingAgent, freshAgent] };
604
+ return undefined;
605
+ },
606
+ logger: {
607
+ info: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
608
+ warn: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
609
+ debug: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
610
+ },
611
+ };
612
+ // The tunables are read live, so this test can change the ceiling the way the
613
+ // settings page does — no restart, which is the point of the cause field.
614
+ const settings = normalizeSettings({
615
+ autoExtract: true,
616
+ extractMaxOutputTokens: 128,
617
+ extractTimeoutMs: 5_000,
618
+ maxSessionsPerPass: 1,
619
+ });
620
+ const runtime = new MemoriesRuntime(ctx, { memoriesDir: dir, autoExtract: true }, () => settings);
621
+ t.after(() => runtime.dispose());
622
+ // The cooling session is the newer one, so it is the pass's first candidate.
623
+ runtime.recordActivity(fresh, Date.now() - 60_000);
624
+ runtime.recordActivity(cooling, Date.now());
625
+ await runtime.runPeriodicPass();
626
+ assert.deepEqual(asked, ['cooling'], 'the first pass spends the call on the newest session');
627
+ assert.equal(runtime.state.getSession('cooling-session')?.at ?? 0, 0, 'a capped reply writes no watermark');
628
+ assert.ok(lines.some((line) => line.includes('the window stays unmined and the next attempt is in')), 'the cooldown is announced, with the wait');
629
+ // The per-pass budget is one call, and the capped session is still the first
630
+ // candidate: if its cooldown did not resolve before the budget, this pass
631
+ // would spend its only call on the request that just failed and stop.
632
+ await runtime.runPeriodicPass();
633
+ assert.deepEqual(asked, ['cooling', 'fresh'], 'the cooled-down session steps aside instead of eating the pass');
634
+ const cooled = lines.filter((line) => line.startsWith('dsh-cross-memory: extract pass:')).at(-1) ?? '';
635
+ assert.match(cooled, /capped 1/u, 'the skip is named in the pass line, not silent');
636
+ assert.doesNotMatch(cooled, /pass-cap/u, 'a skip that costs no model call leaves the budget alone');
637
+ assert.equal(runtime.state.getSession('cooling-session')?.at ?? 0, 0, 'and the capped window is still unmined');
638
+ // `/memories mine` is a person asking for the call, so the wait does not apply.
639
+ assert.equal(await runtime.mineNow(coolingAgent), 0, 'the forced path still runs while the window cools down');
640
+ assert.deepEqual(asked, ['cooling', 'fresh', 'cooling'], 'the caller decided to spend it, so it was spent');
641
+ // Raising the ceiling is the fix the log line asks for; it must end the
642
+ // cooldown immediately rather than leave the user waiting out 4 hours.
643
+ capTheCoolingOne = false;
644
+ settings.extractMaxOutputTokens = 8_192;
645
+ await runtime.runPeriodicPass();
646
+ assert.deepEqual(asked.at(-1), 'cooling', 'a changed cap retires the cooldown');
647
+ assert.equal(runtime.state.getSession('cooling-session')?.lastSeq, 1, 'and the retried window is mined for real');
648
+ // A completed extraction clears it for good: the next window is mined at the
649
+ // normal cadence, not held behind the cooldown this session had earned.
650
+ grow(cooling, { seq: 2, role: 'user', text: 'More worth remembering.' });
651
+ await runtime.runPeriodicPass();
652
+ assert.deepEqual(asked.at(-1), 'cooling', 'the state does not outlive the extraction that resolved it');
653
+ assert.equal(runtime.state.getSession('cooling-session')?.lastSeq, 2, 'and it mines the new window, not a stale one');
654
+ t.after(() => rm(dir, { recursive: true, force: true }));
655
+ });
656
+ test('a reply capped mid-array keeps the memories that were already complete', async () => {
657
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'Something worth remembering.' }]);
658
+ // The reply order the contract asks for: `memories` first, `summary` last. A
659
+ // cap that bites mid-array therefore leaves complete objects behind, which is
660
+ // the shape `repairTruncatedJson` closes. With the summary written first, the
661
+ // same truncation kept nothing — that is the case the test above pins.
662
+ const capped = {
663
+ stream: () => (async function* chunks() {
664
+ yield textChunk('{"memories":[{"scope":"project","kind":"fact","title":"First fact","body":"Finished before the cap.","appliesTo":"任何时候","quote":"Something worth remembering."},{"scope":"project","kind":"fact","title":"Second fact","body":"cut off he');
665
+ yield { type: 'finish', reason: { kind: 'max-tokens' } };
666
+ })(),
667
+ };
668
+ const outcome = await runExtraction(capped, {
669
+ session,
670
+ window: collectWindow(session, 0, 10, 10_000),
671
+ projectLabel: 'project:work',
672
+ maxOutputTokens: 128,
673
+ maxMemories: 5,
674
+ timeoutMs: 5_000,
675
+ signal: new AbortController().signal,
676
+ });
677
+ assert.equal(outcome.kind, 'memories');
678
+ assert.equal(outcome.kind === 'memories' ? outcome.truncated : undefined, true, 'the caller can tell it was salvaged');
679
+ assert.deepEqual(outcome.kind === 'memories' ? outcome.drafts.map((draft) => draft.title) : [], ['First fact']);
680
+ });
681
+ test('the resolved route carries the reasoning level that spends the cap', async () => {
682
+ const session = stubSession('C:\\work', [{ seq: 1, role: 'user', text: 'Remember this.' }]);
683
+ session.requestHeader = () => ({
684
+ config: { provider: 'deepseek-official', model: 'deepseek-flash', reasoningEffort: 'high' },
685
+ });
686
+ const lined = {
687
+ stream: () => (async function* chunks() {
688
+ yield textChunk('{"memories":[{"scope":"project","kind":"fact","title":"T","body":"B","appliesTo":"A","quote":"Remember this."}],"summary":"s');
689
+ yield { type: 'finish', reason: { kind: 'max-tokens' } };
690
+ })(),
691
+ };
692
+ const outcome = await runExtraction(lined, {
693
+ session,
694
+ window: collectWindow(session, 0, 10, 10_000),
695
+ projectLabel: 'project:work',
696
+ maxOutputTokens: 128,
697
+ maxMemories: 5,
698
+ timeoutMs: 5_000,
699
+ signal: new AbortController().signal,
700
+ });
701
+ assert.equal(outcome.kind, 'memories');
702
+ assert.equal(outcome.kind === 'memories' ? outcome.route.model : '', 'deepseek-flash');
703
+ assert.equal(outcome.kind === 'memories' ? outcome.route.reasoningEffort : undefined, 'high', 'the level travels with the route');
704
+ });
705
+ test('a peak window refuses every session without spending the per-pass budget', async (t) => {
706
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-peak-cap-'));
707
+ const lines = [];
708
+ const sessionWithId = (id) => stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'Something worth remembering.' }], id);
709
+ const sessions = [sessionWithId('peak-a'), sessionWithId('peak-b')];
710
+ const agents = sessions.map((session) => ({
711
+ id: session.id,
712
+ session,
713
+ status: 'idle',
714
+ runMaintenance: (job) => job(new AbortController().signal),
715
+ }));
716
+ const ctx = {
717
+ get: (name) => {
718
+ if (name === 'llm')
719
+ return fakeLlm('{"memories":[]}');
720
+ if (name === 'agents')
721
+ return { roots: () => agents };
722
+ return undefined;
723
+ },
724
+ logger: {
725
+ info: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
726
+ warn: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
727
+ debug: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
728
+ },
729
+ };
730
+ // A window that always contains "now": every day, midnight to midnight.
731
+ const runtime = new MemoriesRuntime(ctx, {
732
+ memoriesDir: dir,
733
+ autoExtract: true,
734
+ extractTimeoutMs: 5_000,
735
+ maxSessionsPerPass: 1,
736
+ peakHours: '* 00:00-24:00',
737
+ });
738
+ t.after(() => runtime.dispose());
739
+ assert.ok(peakDelayMs('* 00:00-24:00', new Date()) > 0, 'the test window really covers now');
740
+ await runtime.runPeriodicPass();
741
+ // Nothing was mined, and the reason is the peak window — not the pass cap,
742
+ // even though the cap is 1 and there were two candidates.
743
+ assert.equal(runtime.state.getSession('peak-a')?.at ?? 0, 0);
744
+ const pass = lines.find((line) => line.startsWith('dsh-cross-memory: extract pass:'));
745
+ assert.match(pass ?? '', /peak 2/u);
746
+ assert.doesNotMatch(pass ?? '', /pass-cap/u, 'a refusal that costs no model call leaves the budget alone');
747
+ t.after(() => rm(dir, { recursive: true, force: true }));
748
+ });
749
+ test('a failing extraction call leaves the store and watermark untouched', async (t) => {
750
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-extract-fail-'));
751
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'something memorable' }]);
752
+ const failing = { stream: () => { throw new Error('provider exploded'); } };
753
+ const runtime = new MemoriesRuntime(stubContext(failing), { memoriesDir: dir, autoExtract: true });
754
+ t.after(() => runtime.dispose());
755
+ const agent = { id: 'extract-session', session, status: 'idle' };
756
+ await assert.rejects(() => runtime.runExtraction(agent), /provider exploded/u);
757
+ assert.equal((await projectEntries(runtime, session)).length, 0);
758
+ assert.equal(runtime.state.getSession('extract-session'), undefined);
759
+ // The watermark is only written on success.
760
+ assert.equal(runtime.state.sessionCount(), 0);
761
+ t.after(() => rm(dir, { recursive: true, force: true }));
762
+ });
763
+ test('extraction is skipped for subagent sessions and when disabled', async (t) => {
764
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-extract-skip-'));
765
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'x' }]);
766
+ session.header.delegationDepth = 1;
767
+ const runtime = new MemoriesRuntime(stubContext(fakeLlm('{"memories":[]}')), { memoriesDir: dir, autoExtract: true });
768
+ t.after(() => runtime.dispose());
769
+ const agent = { id: 'extract-session', session, status: 'idle' };
770
+ runtime.scheduleExtraction(agent);
771
+ assert.equal((await runtime.runExtraction(agent)).stored, 0);
772
+ t.after(() => rm(dir, { recursive: true, force: true }));
773
+ });
774
+ test('a provider refusal pauses background passes and the pause survives a reopen', async (t) => {
775
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-quota-'));
776
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'I always deploy with pnpm run ship.' }]);
777
+ let calls = 0;
778
+ const refusing = {
779
+ stream: () => {
780
+ calls += 1;
781
+ const error = new Error('rate limit exceeded');
782
+ error.code = 'RATE_LIMIT';
783
+ throw error;
784
+ },
785
+ };
786
+ const runtime = new MemoriesRuntime(stubContext(refusing), {
787
+ memoriesDir: dir,
788
+ autoExtract: true,
789
+ quotaCooldownMinutes: 30,
790
+ quotaCooldownMaxMinutes: 120,
791
+ });
792
+ t.after(() => runtime.dispose());
793
+ const agent = { id: 'extract-session', session, status: 'idle' };
794
+ await assert.rejects(() => runtime.runExtraction(agent), /rate limit/u);
795
+ assert.equal(calls, 1);
796
+ const first = runtime.state.getLimit();
797
+ assert.ok(first !== undefined, 'a refusal is recorded');
798
+ assert.equal(first.failures, 1);
799
+ assert.equal(first.until - first.at, 30 * 60_000);
800
+ // The next pass never reaches the provider, so the refusal costs one call per
801
+ // cooldown instead of one per idle timer.
802
+ assert.equal((await runtime.runExtraction(agent)).stored, 0);
803
+ assert.equal(calls, 1);
804
+ // A second refusal doubles the wait; consecutive refusals keep doubling to a cap.
805
+ runtime.state.clearLimit();
806
+ await assert.rejects(() => runtime.runExtraction(agent), /rate limit/u);
807
+ const second = runtime.state.noteLimitFailure('again', 30 * 60_000, 120 * 60_000);
808
+ assert.equal(second.failures, 2);
809
+ assert.equal(second.until - second.at, 60 * 60_000);
810
+ // The pause is durable state: a restarted process must not immediately retry.
811
+ const reopened = new MemoriesRuntime(stubContext(refusing), { memoriesDir: dir, autoExtract: true });
812
+ t.after(() => reopened.dispose());
813
+ assert.equal(reopened.state.isLimited(), true);
814
+ assert.equal((await reopened.runExtraction(agent)).stored, 0);
815
+ assert.equal(calls, 2, 'a paused pass never calls the provider');
816
+ // A successful pass forgets the pause.
817
+ reopened.state.clearLimit();
818
+ assert.equal(reopened.state.isLimited(), false);
819
+ t.after(() => rm(dir, { recursive: true, force: true }));
820
+ });
821
+ test('consolidation quotes the rate limit as its own refusal', async (t) => {
822
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-quota-consolidate-'));
823
+ const runtime = new MemoriesRuntime(stubContext({ stream: async function* () { } }), { memoriesDir: dir, autoExtract: false });
824
+ t.after(() => runtime.dispose());
825
+ runtime.state.noteLimitFailure('quota exhausted', 1_000, 1_000);
826
+ assert.equal(runtime.state.isLimited(), true);
827
+ assert.match(await runtime.stats(stubSession(process.cwd(), [])), /background: paused until/u);
828
+ t.after(() => rm(dir, { recursive: true, force: true }));
829
+ });
830
+ test('a successful pass writes the evidence note behind the drafts', async (t) => {
831
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-evidence-'));
832
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'We always ship with pnpm run ship.' }]);
833
+ const reply = '{"summary":"The user explained how this project ships.","memories":[{"scope":"project","title":"Deploy with pnpm run ship","body":"Ship this project with `pnpm run ship`.","tags":["deploy"]}]}';
834
+ const runtime = new MemoriesRuntime(stubContext(fakeLlm(reply)), { memoriesDir: dir, autoExtract: true, extractTimeoutMs: 5_000 });
835
+ t.after(() => runtime.dispose());
836
+ const agent = { id: 'extract-session', session, status: 'idle' };
837
+ assert.equal((await runtime.runExtraction(agent)).stored, 1);
838
+ const note = await runtime.store.readSessionNote('extract-session');
839
+ assert.equal(note?.summary, 'The user explained how this project ships.');
840
+ assert.deepEqual(note?.memories, ['deploy-with-pnpm-run-ship']);
841
+ const stored = (await projectEntries(runtime, session))[0];
842
+ assert.equal(stored?.sourceSession, 'extract-session');
843
+ t.after(() => rm(dir, { recursive: true, force: true }));
844
+ });
845
+ test('the settle timer actually runs a pass once its wait elapses', async (t) => {
846
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-settle-'));
847
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'We always ship with pnpm run ship.' }]);
848
+ const reply = '{"memories":[{"scope":"project","title":"Deploy with pnpm run ship","body":"Ship this project with `pnpm run ship`.","tags":["deploy"]}]}';
849
+ // Short waits on both knobs: this is the whole settle path — timer, quiet-window
850
+ // gate, pass, watermark — and it is what the shipped defaults could never reach
851
+ // (a 5 minute timer guarded by a 6 hour window, with no re-arm). The idle delay
852
+ // is clamped to a 1000 ms floor, so this is as short as the timer can be.
853
+ const runtime = new MemoriesRuntime(stubContext(fakeLlm(reply)), {
854
+ memoriesDir: dir,
855
+ autoExtract: true,
856
+ minIdleHours: 0,
857
+ autoExtractIdleMs: 1_000,
858
+ extractTimeoutMs: 5_000,
859
+ });
860
+ t.after(() => runtime.dispose());
861
+ const agent = {
862
+ id: 'settle-session',
863
+ session,
864
+ status: 'idle',
865
+ runMaintenance: async (task) => await task(new AbortController().signal),
866
+ };
867
+ runtime.scheduleExtraction(agent);
868
+ await new Promise((settle) => setTimeout(settle, 1_400));
869
+ assert.equal(runtime.state.getSession('extract-session')?.lastSeq, 1, 'the settle timer mined the session');
870
+ assert.equal((await projectEntries(runtime, session)).length, 1);
871
+ t.after(() => rm(dir, { recursive: true, force: true }));
872
+ });
873
+ test('the exit flush mines a session that never had its quiet window', async (t) => {
874
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-flush-'));
875
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'We always ship with pnpm run ship.' }]);
876
+ const reply = '{"memories":[{"scope":"project","title":"Deploy with pnpm run ship","body":"Ship this project with `pnpm run ship`.","tags":["deploy"]}]}';
877
+ // A six-hour quiet window against an immediate exit: the timer cannot be what
878
+ // saves this session, only the forced flush can.
879
+ const runtime = new MemoriesRuntime(stubContext(fakeLlm(reply)), { memoriesDir: dir, autoExtract: true, minIdleHours: 6, extractTimeoutMs: 5_000 });
880
+ t.after(() => runtime.dispose());
881
+ // `mine` claims the idle phase through `runMaintenance`, so the stub has to
882
+ // provide it the way a real agent does.
883
+ const agent = {
884
+ id: 'flush-session',
885
+ session,
886
+ status: 'idle',
887
+ runMaintenance: async (task) => await task(new AbortController().signal),
888
+ };
889
+ runtime.scheduleExtraction(agent);
890
+ assert.equal(await runtime.flushExit(5_000), 1, 'the exit boundary ignores the quiet window');
891
+ // The watermark is keyed by the session, not by the agent id.
892
+ assert.equal(runtime.state.getSession('extract-session')?.lastSeq, 1);
893
+ t.after(() => rm(dir, { recursive: true, force: true }));
894
+ });
895
+ test('peak hours hold back the automatic passes but not an explicit one', async (t) => {
896
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-peak-'));
897
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'We always ship with pnpm run ship.' }]);
898
+ const reply = '{"memories":[{"scope":"project","title":"Deploy with pnpm run ship","body":"Ship this project with `pnpm run ship`.","tags":["deploy"]}]}';
899
+ // `* 00:00-24:00` is peak forever, which makes the gate deterministic to test;
900
+ // a real timetable would only be in or out depending on when the suite runs.
901
+ const runtime = new MemoriesRuntime(stubContext(fakeLlm(reply)), {
902
+ memoriesDir: dir,
903
+ autoExtract: true,
904
+ minIdleHours: 0,
905
+ peakHours: '* 00:00-24:00',
906
+ extractTimeoutMs: 5_000,
907
+ });
908
+ t.after(() => runtime.dispose());
909
+ const agent = {
910
+ id: 'peak-session',
911
+ session,
912
+ status: 'idle',
913
+ runMaintenance: async (task) => await task(new AbortController().signal),
914
+ };
915
+ runtime.scheduleExtraction(agent);
916
+ await new Promise((settle) => setTimeout(settle, 1_300));
917
+ assert.equal(runtime.state.getSession('extract-session'), undefined, 'the settle timer waits the window out');
918
+ assert.equal(await runtime.flushExit(5_000), 0, 'the exit flush is an automatic spend, so it defers too');
919
+ assert.equal(await runtime.mineNow(agent), 1, 'an explicit /memories mine ignores the window');
920
+ t.after(() => rm(dir, { recursive: true, force: true }));
921
+ });
922
+ /** The agent stub every periodic test needs: idle, and able to claim the idle phase. */
923
+ function idleAgent(session, id = 'periodic-session') {
924
+ return {
925
+ id,
926
+ session,
927
+ status: 'idle',
928
+ runMaintenance: async (task) => await task(new AbortController().signal),
929
+ };
930
+ }
931
+ test('a periodic pass mines new material and costs nothing when there is none', async (t) => {
932
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-periodic-'));
933
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'We always ship with pnpm run ship.' }]);
934
+ const reply = '{"memories":[{"scope":"project","title":"Deploy with pnpm run ship","body":"Ship this project with `pnpm run ship`.","tags":[]}]}';
935
+ const seen = {};
936
+ // The quiet window is six hours, so the settle path could not fire for hours:
937
+ // the periodic check is what mines this session, and it must not consult that
938
+ // window — the whole point is to capture while the session is still running.
939
+ const runtime = new MemoriesRuntime(stubContext(fakeLlm(reply, seen)), {
940
+ memoriesDir: dir,
941
+ autoExtract: true,
942
+ minIdleHours: 6,
943
+ extractIntervalMinutes: 30,
944
+ extractTimeoutMs: 5_000,
945
+ });
946
+ t.after(() => runtime.dispose());
947
+ const agent = idleAgent(session);
948
+ runtime.scheduleExtraction(agent);
949
+ await runtime.runPeriodicPass();
950
+ assert.equal(runtime.state.getSession('extract-session')?.lastSeq, 1, 'the slice was mined');
951
+ assert.ok(seen.user !== undefined, 'the first pass called the model');
952
+ // Nothing new since the watermark: the next pass must not spend a call.
953
+ seen.user = undefined;
954
+ await runtime.runPeriodicPass();
955
+ assert.equal(seen.user, undefined, 'a session with nothing new costs no model call');
956
+ t.after(() => rm(dir, { recursive: true, force: true }));
957
+ });
958
+ test('a periodic pass respects the peak window', async (t) => {
959
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-periodic-peak-'));
960
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'We always ship with pnpm run ship.' }]);
961
+ const reply = '{"memories":[{"scope":"project","title":"Deploy with pnpm run ship","body":"Ship it.","tags":[]}]}';
962
+ const runtime = new MemoriesRuntime(stubContext(fakeLlm(reply)), {
963
+ memoriesDir: dir,
964
+ autoExtract: true,
965
+ extractIntervalMinutes: 30,
966
+ peakHours: '* 00:00-24:00',
967
+ extractTimeoutMs: 5_000,
968
+ });
969
+ t.after(() => runtime.dispose());
970
+ runtime.scheduleExtraction(idleAgent(session));
971
+ await runtime.runPeriodicPass();
972
+ assert.equal(runtime.state.getSession('extract-session'), undefined, 'spending waits for off-peak');
973
+ t.after(() => rm(dir, { recursive: true, force: true }));
974
+ });
975
+ test('the periodic timer actually runs a pass', async (t) => {
976
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-periodic-timer-'));
977
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'We always ship with pnpm run ship.' }]);
978
+ const reply = '{"memories":[{"scope":"project","title":"Deploy with pnpm run ship","body":"Ship it.","tags":[]}]}';
979
+ // 0.01 minutes = 600ms: fractional intervals are kept, which is what makes this
980
+ // testable without waiting half an hour. 2026-09-29 实测:原来的 0.02min(1200ms) 配
981
+ // 1600ms 等待,在整套 259 个测试并发跑时会偶发不触发(单独跑 3/3 稳定通过)——
982
+ // 属于负载敏感的 flake,不是功能回归。改成 600ms 周期 + 2400ms 等待(4 个周期),
983
+ // 判定逻辑不变,只把余量从 400ms 拉到约 1.8s。
984
+ const runtime = new MemoriesRuntime(stubContext(fakeLlm(reply)), {
985
+ memoriesDir: dir,
986
+ autoExtract: true,
987
+ extractIntervalMinutes: 0.01,
988
+ extractTimeoutMs: 5_000,
989
+ });
990
+ t.after(() => runtime.dispose());
991
+ runtime.scheduleExtraction(idleAgent(session));
992
+ runtime.startPeriodicExtraction();
993
+ await new Promise((settle) => setTimeout(settle, 2_400));
994
+ assert.equal(runtime.state.getSession('extract-session')?.lastSeq, 1, 'the interval fired');
995
+ runtime.stopPeriodicExtraction();
996
+ t.after(() => rm(dir, { recursive: true, force: true }));
997
+ });
998
+ test('the exit flush still mines what arrived after a periodic pass', async (t) => {
999
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-periodic-flush-'));
1000
+ const session = stubSession(process.cwd(), [{ seq: 1, role: 'user', text: 'We always ship with pnpm run ship.' }]);
1001
+ const reply = '{"memories":[{"scope":"project","title":"Deploy with pnpm run ship","body":"Ship it.","tags":[]}]}';
1002
+ const runtime = new MemoriesRuntime(stubContext(fakeLlm(reply)), {
1003
+ memoriesDir: dir,
1004
+ autoExtract: true,
1005
+ minIdleHours: 6,
1006
+ extractIntervalMinutes: 30,
1007
+ extractTimeoutMs: 5_000,
1008
+ });
1009
+ t.after(() => runtime.dispose());
1010
+ const agent = idleAgent(session);
1011
+ runtime.scheduleExtraction(agent);
1012
+ await runtime.runPeriodicPass();
1013
+ assert.equal(runtime.state.getSession('extract-session')?.lastSeq, 1);
1014
+ // The turn continues after the periodic pass, and then the process exits: the
1015
+ // flush must look at the content, not at "have we mined this session already".
1016
+ grow(session, { seq: 2, role: 'user', text: 'Also run tsc before publishing.' });
1017
+ assert.equal(await runtime.flushExit(5_000), 1, 'new material is not skipped by a per-process flag');
1018
+ assert.equal(runtime.state.getSession('extract-session')?.lastSeq, 2);
1019
+ t.after(() => rm(dir, { recursive: true, force: true }));
1020
+ });