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,95 @@
1
+ /**
2
+ * Unit test for consolidation's workspace bookkeeping.
3
+ *
4
+ * Consolidation is process-level but project scope is per-workspace. The job
5
+ * must remember which workspace enqueued it, otherwise whichever session runs
6
+ * the pass decides whose project memories get consolidated — the bug that let a
7
+ * pass run against the wrong workspace and report success.
8
+ *
9
+ * @module dsh-cross-memory/test/consolidate-job.test
10
+ */
11
+ import assert from 'node:assert/strict';
12
+ import { mkdtemp, rm } from 'node:fs/promises';
13
+ import { tmpdir } from 'node:os';
14
+ import { join } from 'node:path';
15
+ import test from 'node:test';
16
+ import { MemoriesRuntime } from '../index.js';
17
+ /** A context stand-in. */
18
+ const stubContext = {
19
+ get: () => undefined,
20
+ logger: { info: () => undefined, warn: () => undefined, debug: () => undefined },
21
+ };
22
+ /** A session stand-in. */
23
+ function stubSession(id, cwd) {
24
+ return {
25
+ id,
26
+ header: { version: 0, id, createdAt: 0, cwd, isSeeded: false },
27
+ seq: 1,
28
+ requestHeader: () => undefined,
29
+ };
30
+ }
31
+ /** A runtime over a temp store. */
32
+ async function fixture(t) {
33
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-job-'));
34
+ const runtime = new MemoriesRuntime(stubContext, { memoriesDir: dir, autoExtract: false });
35
+ t.after(() => {
36
+ runtime.dispose();
37
+ return rm(dir, { recursive: true, force: true });
38
+ });
39
+ return { dir, runtime };
40
+ }
41
+ test('enqueue records the workspace the pass should cover', async (t) => {
42
+ const { runtime } = await fixture(t);
43
+ runtime.enqueueConsolidation(1_000, false, 'C:\\work\\alpha');
44
+ const job = runtime.state.getJob('global');
45
+ assert.equal(job?.root, 'C:\\work\\alpha');
46
+ assert.equal(job?.enqueuedAt, 1_000);
47
+ // The cooldown applies to a background enqueue.
48
+ assert.ok((job?.notBefore ?? 0) > 1_000);
49
+ });
50
+ test('a manual enqueue skips the cooldown but still records the root', async (t) => {
51
+ const { runtime } = await fixture(t);
52
+ runtime.enqueueConsolidation(2_000, true, 'C:\\work\\beta');
53
+ const job = runtime.state.getJob('global');
54
+ assert.equal(job?.notBefore, 2_000, 'ready now');
55
+ assert.equal(job?.root, 'C:\\work\\beta');
56
+ });
57
+ test('a later enqueue updates the root so the newest workspace wins', async (t) => {
58
+ const { runtime } = await fixture(t);
59
+ runtime.enqueueConsolidation(1_000, false, 'C:\\work\\alpha');
60
+ runtime.enqueueConsolidation(2_000, false, 'C:\\work\\beta');
61
+ assert.equal(runtime.state.getJob('global')?.root, 'C:\\work\\beta');
62
+ });
63
+ test('an enqueue without a root keeps the recorded one', async (t) => {
64
+ const { runtime } = await fixture(t);
65
+ runtime.enqueueConsolidation(1_000, false, 'C:\\work\\alpha');
66
+ runtime.enqueueConsolidation(2_000, false);
67
+ assert.equal(runtime.state.getJob('global')?.root, 'C:\\work\\alpha');
68
+ });
69
+ test('consolidation is a no-op without a subagent seam', async (t) => {
70
+ const { runtime } = await fixture(t);
71
+ // No `subagents` service in the stub context, so the pass cannot run and
72
+ // must report that rather than creating a job it can never complete.
73
+ assert.equal(await runtime.consolidateNow({ session: stubSession('s', process.cwd()) }), undefined);
74
+ assert.equal(runtime.state.getJob('global'), undefined);
75
+ });
76
+ test('a stale backoff cannot refuse a pass a person asked for', async (t) => {
77
+ const { runtime } = await fixture(t);
78
+ // The row left behind by a pass that kept failing: queued, backed off for
79
+ // hours, and still carrying the old error.
80
+ runtime.state.putJob({
81
+ key: 'global',
82
+ enqueuedAt: 1_000,
83
+ notBefore: 10_000_000,
84
+ retries: 6,
85
+ lastError: 'subagent descriptor is not losslessly JSON-serializable',
86
+ });
87
+ assert.equal(runtime.state.claimJob('global', 'token-a', 1_000, 2_000), undefined, 'the backoff still gates the background pass');
88
+ runtime.state.clearJobBackoff('global');
89
+ const job = runtime.state.getJob('global');
90
+ assert.equal(job?.notBefore, 0, 'the backoff is gone');
91
+ assert.equal(job?.retries, 0, 'and the retry count with it');
92
+ assert.equal(job?.lastError, undefined, 'and the failure message');
93
+ assert.equal(job?.root, undefined, 'while the rest of the row survives');
94
+ assert.ok(runtime.state.claimJob('global', 'token-b', 1_000, 2_000) !== undefined, 'a forced pass can now claim it');
95
+ });
@@ -0,0 +1,430 @@
1
+ /**
2
+ * Tests for stage-2 consolidation.
3
+ *
4
+ * The child agent is a stub here; what matters is the boundary the plugin owns:
5
+ * a plan is validated against the ids that actually exist, application is
6
+ * all-or-nothing, and a failure puts the store back the way it was.
7
+ *
8
+ * @module dsh-cross-memory/test/consolidate.test
9
+ */
10
+ import assert from 'node:assert/strict';
11
+ import { mkdtemp, rm } from 'node:fs/promises';
12
+ import { tmpdir } from 'node:os';
13
+ import { join } from 'node:path';
14
+ import test from 'node:test';
15
+ import { assertObjectJsonSchema } from '@deepseek-ai/dsh-tools';
16
+ import { CONSOLIDATE_DENY_TOOLS, CONSOLIDATE_JSON_SCHEMA, clearPendingPlan, classifyPlan, denyToolsFor, applyPlan, hasApplicableFragment, parsePlan, pinExistingScopes, proposalIsFresh, readPendingPlan, renderConsolidationInput, runConsolidation, runConsolidationDirect, writePendingPlan, } from '../consolidate.js';
17
+ /** Build one entry. */
18
+ function entry(partial) {
19
+ return { scope: 'global', kind: 'fact', tags: [], keys: [], createdAt: 1, updatedAt: 1, uses: 0, lastUsedAt: 0, lastSurfacedAt: 0, source: 'auto', ...partial };
20
+ }
21
+ /** A stub subagent seam recording the request and replaying one reply. */
22
+ function seam(reply, seen = {}) {
23
+ return {
24
+ start: async (_name, request) => {
25
+ seen.request = request;
26
+ return { result: Promise.resolve({ output: [{ type: 'text', text: reply }], structured: undefined, stopReason: { kind: 'completed' } }) };
27
+ },
28
+ };
29
+ }
30
+ /** A stub LLM runtime replaying one text answer. */
31
+ function llm(reply, seen = {}) {
32
+ return {
33
+ stream: (options) => {
34
+ seen.options = options;
35
+ return (async function* () {
36
+ yield { type: 'text-delta', index: 0, text: reply };
37
+ yield { type: 'finish', reason: 'stop' };
38
+ })();
39
+ },
40
+ };
41
+ }
42
+ /** An in-memory store target that can be made to fail on demand. */
43
+ function target(initial, failOn) {
44
+ const entries = new Map(initial.map((item) => [`${item.scope}\u0000${item.id}`, item]));
45
+ const writes = [];
46
+ const api = {
47
+ upsert: async (draft, _root, source, keepId) => {
48
+ const id = keepId ?? draft.title.toLowerCase().replace(/[^a-z0-9]+/gu, '-');
49
+ if (failOn === id)
50
+ throw new Error('write exploded');
51
+ writes.push(`upsert:${id}`);
52
+ const existing = entries.get(`${draft.scope}\u0000${id}`);
53
+ const next = {
54
+ id,
55
+ scope: draft.scope,
56
+ kind: draft.kind ?? 'fact',
57
+ title: draft.title,
58
+ body: draft.body,
59
+ tags: draft.tags,
60
+ keys: draft.keys ?? existing?.keys ?? [],
61
+ createdAt: existing?.createdAt ?? 1,
62
+ updatedAt: 2,
63
+ uses: existing?.uses ?? 0,
64
+ lastUsedAt: existing?.lastUsedAt ?? 0,
65
+ lastSurfacedAt: existing?.lastSurfacedAt ?? 0,
66
+ source,
67
+ };
68
+ entries.set(`${draft.scope}\u0000${id}`, next);
69
+ return { entry: next, action: existing === undefined ? 'created' : 'updated' };
70
+ },
71
+ archive: async (scope, _root, id) => {
72
+ writes.push(`archive:${id}`);
73
+ return entries.delete(`${scope}\u0000${id}`);
74
+ },
75
+ restore: async (scope, _root, id) => {
76
+ writes.push(`restore:${id}`);
77
+ return entries.has(`${scope}\u0000${id}`);
78
+ },
79
+ };
80
+ return { api, writes, get: (scope, id) => entries.get(`${scope}\u0000${id}`), all: () => [...entries.values()] };
81
+ }
82
+ test('the consolidation schema is accepted by the harness schema subset', () => {
83
+ // The child run fails at start if the harness rejects the schema, and the
84
+ // failure is opaque ("unsupported JSON schema: ..."), so validate it here
85
+ // with the same function the subagent seam uses. `type: ["string","null"]`
86
+ // for a nullable field is exactly what this catches.
87
+ assert.doesNotThrow(() => { assertObjectJsonSchema(CONSOLIDATE_JSON_SCHEMA); });
88
+ });
89
+ test('denyToolsFor keeps only names the registry actually has', () => {
90
+ // The deny list is cross-platform; `tools.restrict()` rejects an unknown
91
+ // name, so passing the raw list would sink every consolidation pass.
92
+ const available = new Set(['write', 'edit', 'pwsh', 'read', 'memory', 'subagent_fork']);
93
+ const denied = denyToolsFor(available);
94
+ assert.ok(denied.includes('write'));
95
+ assert.ok(denied.includes('pwsh'));
96
+ assert.ok(denied.includes('subagent_fork'));
97
+ assert.ok(!denied.includes('bash'), 'bash is not registered on this deployment');
98
+ assert.ok(!denied.includes('str_replace_editor'), 'that name does not exist here');
99
+ assert.ok(!denied.includes('read'), 'read stays available to the child');
100
+ assert.equal(denyToolsFor(new Set()).length, 0);
101
+ });
102
+ test('the consolidation child is denied every write and network tool', async () => {
103
+ const seen = {};
104
+ const reply = '{"memories":[{"id":null,"scope":"global","title":"t","body":"b"}],"retire":[],"notes":"n"}';
105
+ await runConsolidation(seam(reply, seen), {
106
+ parent: {},
107
+ entries: [entry({ id: 'a', title: 'A', body: 'a' })],
108
+ projectLabel: 'project:x',
109
+ maxUpserts: 10,
110
+ denyTools: [...CONSOLIDATE_DENY_TOOLS],
111
+ timeoutMs: 5_000,
112
+ signal: new AbortController().signal,
113
+ });
114
+ const request = seen.request;
115
+ for (const tool of ['write', 'edit', 'pwsh', 'web_search', 'subagent', 'memory']) {
116
+ assert.ok(request.toolFilter.deny.includes(tool), `${tool} must be denied to the consolidation child`);
117
+ }
118
+ // DSH counts depth from 1 (a top-level agent is 0, its child is 1): the cap
119
+ // must admit THIS child while refusing a grandchild. `0` rejects the child
120
+ // itself, which is the bug this pins.
121
+ assert.equal(request.maxDepth, 1, 'the child runs, but cannot delegate further');
122
+ assert.ok(request.outputSchema !== undefined, 'the child must answer through the JSON schema');
123
+ assert.deepEqual([...CONSOLIDATE_DENY_TOOLS].length, request.toolFilter.deny.length);
124
+ });
125
+ test('the 0.2.1-rc.2 seam runs the child under a tool-free preset', async () => {
126
+ // The kernel of 0.2.1-rc.2 takes the child's tool set from the preset it
127
+ // names; `toolFilter` and `persona` are gone from the start request, and the
128
+ // model-facing subagent tool rejects both outright.
129
+ const seen = {};
130
+ const reply = '{"memories":[{"id":null,"scope":"global","title":"t","body":"b"}],"retire":[],"notes":"n"}';
131
+ const modern = {
132
+ startActivation: async (spec) => {
133
+ seen.spec = spec;
134
+ return { result: Promise.resolve({ output: [{ type: 'text', text: reply }], structured: undefined, stopReason: { kind: 'completed' } }) };
135
+ },
136
+ };
137
+ const plan = await runConsolidation(modern, {
138
+ parent: {},
139
+ entries: [entry({ id: 'a', title: 'A', body: 'a' })],
140
+ projectLabel: 'project:x',
141
+ maxUpserts: 10,
142
+ denyTools: [...CONSOLIDATE_DENY_TOOLS],
143
+ agentPreset: 'memories-consolidator',
144
+ timeoutMs: 5_000,
145
+ signal: new AbortController().signal,
146
+ });
147
+ assert.ok(plan !== undefined);
148
+ const spec = seen.spec;
149
+ assert.equal(spec.provider, 'spawn');
150
+ assert.equal(spec.request.agentPreset, 'memories-consolidator');
151
+ assert.equal(spec.request.maxDepth, 1, 'the child runs, but cannot delegate further');
152
+ assert.ok(spec.request.outputSchema !== undefined, 'the child must answer through the JSON schema');
153
+ assert.equal(spec.request.toolFilter, undefined, 'the new request carries no tool filter');
154
+ });
155
+ test('the modern seam is refused without a preset, because the child would inherit the parent tools', async () => {
156
+ // A child that names no preset inherits the parent's composition, so the
157
+ // "restricted" child would quietly get the parent's tools back. The pass
158
+ // must not start one.
159
+ let called = false;
160
+ const modern = {
161
+ startActivation: async () => {
162
+ called = true;
163
+ return { result: Promise.resolve({ output: [], structured: undefined }) };
164
+ },
165
+ };
166
+ const plan = await runConsolidation(modern, {
167
+ parent: {},
168
+ entries: [entry({ id: 'a', title: 'A', body: 'a' })],
169
+ projectLabel: 'project:x',
170
+ maxUpserts: 10,
171
+ denyTools: [...CONSOLIDATE_DENY_TOOLS],
172
+ timeoutMs: 5_000,
173
+ signal: new AbortController().signal,
174
+ });
175
+ assert.equal(plan, undefined);
176
+ assert.equal(called, false, 'the child must not be started without a tool-free preset');
177
+ });
178
+ test('the direct path reads a plain text answer and hands the model no tools', async () => {
179
+ const seen = {};
180
+ const reply = '{"memories":[{"id":null,"scope":"global","title":"t","body":"b"}],"retire":[],"notes":"n"}';
181
+ const plan = await runConsolidationDirect(llm(reply, seen), {
182
+ parent: { session: { id: 'session-1' } },
183
+ entries: [entry({ id: 'a', title: 'A', body: 'a' })],
184
+ projectLabel: 'project:x',
185
+ maxUpserts: 10,
186
+ denyTools: [...CONSOLIDATE_DENY_TOOLS],
187
+ timeoutMs: 5_000,
188
+ maxOutputTokens: 4096,
189
+ route: { provider: 'deepseek', model: 'deepseek-chat' },
190
+ signal: new AbortController().signal,
191
+ });
192
+ assert.ok(plan !== undefined);
193
+ assert.equal(plan.upserts.length, 1);
194
+ const options = seen.options;
195
+ assert.equal(options.provider, 'deepseek');
196
+ assert.equal(options.model, 'deepseek-chat');
197
+ assert.equal(options.maxTokens, 4096);
198
+ assert.equal(options.tools, undefined, 'the direct path hands the model no tools at all');
199
+ });
200
+ test('renderConsolidationInput groups by scope and lists ids', () => {
201
+ const text = renderConsolidationInput([
202
+ entry({ id: 'g1', title: 'Global one', body: 'g', scope: 'global', tags: ['x'] }),
203
+ entry({ id: 'p1', title: 'Project one', body: 'p', scope: 'project' }),
204
+ ], 'project:demo');
205
+ assert.match(text, /Workspace scope label: project:demo/u);
206
+ assert.match(text, /## global/u);
207
+ assert.match(text, /## project/u);
208
+ assert.match(text, /id: g1/u);
209
+ assert.match(text, /id: p1/u);
210
+ });
211
+ test('parsePlan keeps only ids that exist and drops self-contradictory retirements', () => {
212
+ const known = new Set(['keep-me', 'retire-me']);
213
+ const plan = parsePlan(JSON.stringify({
214
+ memories: [
215
+ { id: 'keep-me', scope: 'global', title: 'Merged', body: 'merged body', tags: ['a'] },
216
+ { id: 'invented', scope: 'project', title: 'New', body: 'new body' },
217
+ { id: null, scope: 'global', title: 'Brand new', body: 'body' },
218
+ { id: 'keep-me', scope: 'global', title: 'Duplicate id', body: 'ignored' },
219
+ { scope: 'nonsense', title: 'Bad scope', body: 'x' },
220
+ ],
221
+ retire: ['retire-me', 'keep-me', 'not-known'],
222
+ notes: 'merged two',
223
+ }), known, 10);
224
+ assert.ok(plan !== undefined);
225
+ // The invented id becomes a new memory rather than a dangling reference.
226
+ assert.deepEqual(plan.upserts.map((item) => item.id), ['keep-me', null, null]);
227
+ // `keep-me` is rewritten, so it cannot also be retired.
228
+ assert.deepEqual(plan.retire, ['retire-me']);
229
+ assert.equal(plan.notes, 'merged two');
230
+ });
231
+ test('parsePlan rejects a plan with nothing to do and tolerates a code fence', () => {
232
+ assert.equal(parsePlan('{"memories":[],"retire":[]}', new Set(), 10), undefined);
233
+ assert.equal(parsePlan('not json', new Set(['a']), 10), undefined);
234
+ const fenced = parsePlan('```json\n{"memories":[{"id":null,"scope":"global","title":"t","body":"b"}]}\n```', new Set(), 10);
235
+ assert.equal(fenced?.upserts.length, 1);
236
+ });
237
+ test('parsePlan caps the returned memories', () => {
238
+ const reply = JSON.stringify({
239
+ memories: Array.from({ length: 9 }, (_, index) => ({ id: null, scope: 'global', title: `t${index}`, body: 'b' })),
240
+ });
241
+ assert.equal(parsePlan(reply, new Set(), 3)?.upserts.length, 3);
242
+ });
243
+ test('runConsolidation reads the structured result when the provider returns one', async () => {
244
+ const structured = { memories: [{ id: null, scope: 'global', title: 'From schema', body: 'body' }], retire: [], notes: 'ok' };
245
+ const withSchema = {
246
+ start: async () => ({ result: Promise.resolve({ output: [], structured, stopReason: { kind: 'completed' } }) }),
247
+ };
248
+ const plan = await runConsolidation(withSchema, {
249
+ parent: {},
250
+ entries: [entry({ id: 'a', title: 'A', body: 'a' })],
251
+ projectLabel: 'project:x',
252
+ maxUpserts: 5,
253
+ denyTools: [...CONSOLIDATE_DENY_TOOLS],
254
+ timeoutMs: 5_000,
255
+ signal: new AbortController().signal,
256
+ });
257
+ assert.equal(plan?.upserts[0]?.title, 'From schema');
258
+ });
259
+ test('a proposal is left alone while fresh, and replaced once it is stale', () => {
260
+ const hour = 3_600_000;
261
+ const pending = { plan: { upserts: [], retire: [], skills: [], notes: '' }, disputes: [], projectRoot: '', at: 0, label: 'global' };
262
+ // Inside the window a decision nobody made is left alone; past it the store has
263
+ // moved on, so the conservative outcome is to drop the question, not apply it.
264
+ assert.equal(proposalIsFresh(pending, 72, 24 * hour), true);
265
+ assert.equal(proposalIsFresh(pending, 72, 100 * hour), false, 'the store moved on, so the question is stale');
266
+ assert.equal(proposalIsFresh(pending, 0, 10_000 * hour), true, '0 means wait for an answer');
267
+ });
268
+ test('a proposal round-trips through disk and can be dropped', async (t) => {
269
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-pending-'));
270
+ t.after(() => rm(dir, { recursive: true, force: true }));
271
+ const plan = {
272
+ upserts: [{ id: 'a', scope: 'global', kind: 'fact', title: 'A', body: 'a', tags: [] }],
273
+ retire: ['b'],
274
+ skills: [],
275
+ notes: 'merged two',
276
+ };
277
+ const disputes = [{ id: 'a', scope: 'global', action: 'rewrite', title: 'A', reason: 'r', before: 'a', after: 'a2' }];
278
+ await writePendingPlan(dir, { plan, disputes, projectRoot: '', at: 1_700_000_000_000, label: 'global' });
279
+ const read = await readPendingPlan(dir);
280
+ assert.equal(read?.plan.retire[0], 'b');
281
+ assert.equal(read?.disputes[0]?.id, 'a');
282
+ assert.equal(read?.label, 'global');
283
+ assert.equal(await clearPendingPlan(dir), true);
284
+ assert.equal(await readPendingPlan(dir), undefined);
285
+ });
286
+ test('an absent or unreadable proposal reads as none', async (t) => {
287
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-pending2-'));
288
+ t.after(() => rm(dir, { recursive: true, force: true }));
289
+ assert.equal(await readPendingPlan(dir), undefined);
290
+ });
291
+ test('classification applies what is reversible and asks about what is not', () => {
292
+ const quoted = 'See scripts/verify_all.py and app/api/routes.py for the two entry points.';
293
+ const base = entry({ id: 'a', title: 'A', body: quoted, uses: 0 });
294
+ const plan = (upserts, retire = []) => ({ upserts, retire, skills: [], notes: '' });
295
+ const rewrite = (body, over = {}) => ({
296
+ id: 'a', scope: 'global', kind: 'fact', title: 'A', body, tags: [], ...over,
297
+ });
298
+ // Sharpening wording while keeping the anchors is what a pass is FOR.
299
+ const sharpened = classifyPlan(plan([rewrite(`${quoted} Both are exercised by the smoke test.`)]), { entries: [base] });
300
+ assert.equal(sharpened.disputes.length, 0);
301
+ assert.equal(sharpened.safe.upserts.length, 1);
302
+ // Dropping a cited path is a silent loss: nothing downstream can notice it.
303
+ const dropped = classifyPlan(plan([rewrite('See the two entry points.')]), { entries: [base] });
304
+ assert.equal(dropped.disputes.length, 1);
305
+ assert.match(dropped.disputes[0]?.reason ?? '', /文件路径引用/u);
306
+ // Halving a body is a summary, and what it drops is what the pass judged noise.
307
+ const halved = classifyPlan(plan([rewrite(`${quoted}\n\nMore detail that makes this body long enough to matter.`)]), { entries: [entry({ id: 'a', title: 'A', body: `${quoted} ${'x'.repeat(400)}` })] });
308
+ assert.equal(halved.disputes.length, 1);
309
+ assert.match(halved.disputes[0]?.reason ?? '', /不到原来的一半/u);
310
+ // A person's own words and a pin are not the pass's call.
311
+ for (const [previous, expected] of [
312
+ [entry({ id: 'a', title: 'A', body: quoted, source: 'user' }), /人手写/u],
313
+ [entry({ id: 'a', title: 'A', body: quoted, pinned: true }), /置顶/u],
314
+ ]) {
315
+ const result = classifyPlan(plan([rewrite(`${quoted} sharpened`)]), { entries: [previous] });
316
+ assert.equal(result.disputes.length, 1);
317
+ assert.match(result.disputes[0]?.reason ?? '', expected);
318
+ }
319
+ // A scope is pinned, not asked about: the rewrite still applies, in the scope
320
+ // the memory already lives in, and the move creates no row for a person.
321
+ const moved = classifyPlan(plan([rewrite(`${quoted} sharpened`, { scope: 'project' })]), { entries: [base] });
322
+ assert.equal(moved.disputes.length, 0);
323
+ assert.equal(moved.safe.upserts[0]?.scope, 'global', 'an existing memory keeps its scope');
324
+ // Retirement: nothing ever read it is safe; something a session used is not.
325
+ assert.equal(classifyPlan(plan([], ['a']), { entries: [base] }).safe.retire.length, 1);
326
+ const used = classifyPlan(plan([], ['a']), { entries: [entry({ id: 'a', title: 'A', body: 'x', uses: 7 })] });
327
+ assert.equal(used.safe.retire.length, 0);
328
+ assert.match(used.disputes[0]?.reason ?? '', /被读到过 7 次/u);
329
+ // A brand-new memory destroys nothing.
330
+ const created = classifyPlan(plan([{ id: null, scope: 'global', kind: 'fact', title: 'New', body: 'x', tags: [] }]), { entries: [] });
331
+ assert.equal(created.disputes.length, 0);
332
+ assert.equal(created.safe.upserts.length, 1);
333
+ });
334
+ test('a row without its plan fragment has nothing to apply', () => {
335
+ const row = { id: 'a', scope: 'global', action: 'rewrite', title: 'A', reason: 'r', before: 'a', after: 'a2' };
336
+ const empty = { upserts: [], retire: [], skills: [], notes: '' };
337
+ const withUpsert = {
338
+ upserts: [{ id: 'a', scope: 'global', kind: 'fact', title: 'A', body: 'a2', tags: [] }],
339
+ retire: [],
340
+ skills: [],
341
+ notes: '',
342
+ };
343
+ // A rewrite is applied by its upsert; without one, accepting it can only be a no-op.
344
+ assert.equal(hasApplicableFragment(empty, row), false);
345
+ assert.equal(hasApplicableFragment(withUpsert, row), true);
346
+ // A retirement reads the other half of the same plan, so the two cannot stand in for each other.
347
+ const retireRow = { ...row, action: 'retire', after: '' };
348
+ assert.equal(hasApplicableFragment(withUpsert, retireRow), false);
349
+ assert.equal(hasApplicableFragment({ ...empty, retire: ['a'] }, retireRow), true);
350
+ });
351
+ test('applyPlan merges and retires through the target', async () => {
352
+ const first = entry({ id: 'a', title: 'A', body: 'a' });
353
+ const second = entry({ id: 'b', title: 'B', body: 'b' });
354
+ const store = target([first, second]);
355
+ const result = await applyPlan({
356
+ upserts: [{ id: 'a', scope: 'global', kind: 'preference', title: 'A merged', body: 'merged', tags: [], keys: ['alias'] }, { id: null, scope: 'project', kind: 'fact', title: 'New', body: 'new', tags: [] }],
357
+ retire: ['b'],
358
+ skills: [],
359
+ notes: 'merged',
360
+ }, store.api, undefined, { entries: [first, second] });
361
+ assert.deepEqual(result, { written: 2, retired: 1, notes: 'merged' });
362
+ assert.deepEqual([...(store.get('global', 'a')?.keys ?? [])], ['alias'], 'a merged memory keeps the keys it was given');
363
+ assert.equal(store.get('global', 'a')?.title, 'A merged');
364
+ assert.equal(store.get('project', 'new')?.body, 'new');
365
+ assert.equal(store.get('global', 'b'), undefined);
366
+ });
367
+ test('applyPlan keeps the provenance of the memory it rewrites', async () => {
368
+ const written = entry({ id: 'rule', title: 'Never break the prompt cache', body: 'only append', source: 'user' });
369
+ const store = target([written]);
370
+ await applyPlan({
371
+ upserts: [{ id: 'rule', scope: 'global', kind: 'preference', title: 'Never break the prompt cache', body: 'only append, never touch the prefix', tags: [] }],
372
+ retire: [],
373
+ skills: [],
374
+ notes: 'sharpened',
375
+ }, store.api, undefined, { entries: [written] });
376
+ // `auto` means "an extractor's guess": stamping it on a rewrite of somebody's
377
+ // own rule loses both the ranking bonus and the retention exemption, and one
378
+ // real consolidation run demoted the user's prompt-cache rule that way.
379
+ assert.equal(store.get('global', 'rule')?.source, 'user', 'a rewrite does not demote an explicit memory');
380
+ });
381
+ test('applyPlan restores what it changed when a write fails', async () => {
382
+ const first = entry({ id: 'a', title: 'A', body: 'original a' });
383
+ const store = target([first], 'b');
384
+ await assert.rejects(() => applyPlan({
385
+ upserts: [
386
+ { id: 'a', scope: 'global', kind: 'fact', title: 'A changed', body: 'changed', tags: [] },
387
+ { id: 'b', scope: 'global', kind: 'fact', title: 'B', body: 'b', tags: [] },
388
+ ],
389
+ retire: [],
390
+ skills: [],
391
+ notes: '',
392
+ }, store.api, undefined, { entries: [first] }), /write exploded/u);
393
+ // The first write is rolled back to the snapshot's content.
394
+ assert.equal(store.get('global', 'a')?.body, 'original a');
395
+ });
396
+ test('an existing memory is pinned to its own scope; only new memories choose one', () => {
397
+ const existing = entry({ id: 'keep', title: 'Keep', body: 'machine fact about C:/Code and the PC' });
398
+ const plan = {
399
+ upserts: [
400
+ // The model read a path in the body and proposed project scope; the body
401
+ // rewrite itself is still wanted, so it is kept and re-scoped to global.
402
+ { id: 'keep', scope: 'project', kind: 'fact', title: 'Keep', body: 'machine fact about C:/Code and the PC, reworded', tags: [] },
403
+ // A brand-new memory has no scope to keep, so the pass may place it.
404
+ { id: null, scope: 'project', kind: 'fact', title: 'New', body: 'this workspace only', tags: [] },
405
+ ],
406
+ retire: [],
407
+ skills: [],
408
+ notes: '',
409
+ };
410
+ const { plan: pinned, pinned: moves } = pinExistingScopes(plan, [existing]);
411
+ assert.deepEqual(moves, [{ id: 'keep', proposed: 'project', kept: 'global' }]);
412
+ assert.equal(pinned.upserts[0]?.scope, 'global', 'the existing memory stays where it lives');
413
+ assert.match(pinned.upserts[0]?.body ?? '', /reworded/u, 'the rewrite itself is untouched');
414
+ assert.equal(pinned.upserts[1]?.scope, 'project', 'a new memory keeps the proposed scope');
415
+ // Already-honest plans come back as the same object, so the common path costs nothing.
416
+ const honest = { upserts: [{ id: 'keep', scope: 'global', kind: 'fact', title: 'Keep', body: 'x', tags: [] }], retire: [], skills: [], notes: '' };
417
+ const kept = pinExistingScopes(honest, [existing]);
418
+ assert.equal(kept.plan, honest);
419
+ assert.deepEqual(kept.pinned, []);
420
+ // One id can live in both scopes; the proposal names the copy to pin, so a
421
+ // project copy stays project even when a global copy shares the id.
422
+ const twins = [entry({ id: 'twin', title: 'Twin', body: 'global copy' }), entry({ id: 'twin', scope: 'project', title: 'Twin', body: 'project copy' })];
423
+ const twinPlan = {
424
+ upserts: [{ id: 'twin', scope: 'project', kind: 'fact', title: 'Twin', body: 'project copy, reviewed', tags: [] }],
425
+ retire: [], skills: [], notes: '',
426
+ };
427
+ const twinsResult = pinExistingScopes(twinPlan, twins);
428
+ assert.equal(twinsResult.pinned.length, 0, 'naming the copy it lives in is not a move');
429
+ assert.equal(twinsResult.plan.upserts[0]?.scope, 'project');
430
+ });