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,212 @@
1
+ /**
2
+ * Tests for the SQLite-backed operational state.
3
+ *
4
+ * These pin the behaviour the JSON files got wrong: two concurrent writers must
5
+ * not lose each other's update, a job lease must be exclusive, and a store that
6
+ * cannot open the driver must still work in memory.
7
+ *
8
+ * @module dsh-cross-memory/test/state.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 { StateStore, statePath } from '../state.js';
16
+ /** A fresh state store in a temp directory. */
17
+ async function tempStore(t) {
18
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-state-'));
19
+ const store = new StateStore(statePath(dir));
20
+ t.after(() => {
21
+ store.close();
22
+ return rm(dir, { recursive: true, force: true });
23
+ });
24
+ return { store, dir };
25
+ }
26
+ test('the state store uses the built-in SQLite driver', async (t) => {
27
+ const { store } = await tempStore(t);
28
+ assert.equal(store.durable, true, 'node:sqlite should be available on this runtime');
29
+ assert.equal(store.degradedReason, undefined);
30
+ });
31
+ test('the write-ahead log checkpoints far more often than the 1000-page default', async (t) => {
32
+ const { store } = await tempStore(t);
33
+ // The default lets a 143 KB database sit beside a 4 MB WAL. This store is a
34
+ // few writes per pass, so it has no reason to carry a log that large.
35
+ assert.equal(store.walAutocheckpoint, 64);
36
+ });
37
+ test('watermarks survive a reopen', async (t) => {
38
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-state-reopen-'));
39
+ const first = new StateStore(statePath(dir));
40
+ first.putSession('session-a', { lastSeq: 42, at: 1_000, root: 'C:\\work', contributed: true, activityAt: 2_000 });
41
+ first.close();
42
+ const second = new StateStore(statePath(dir));
43
+ // Close both handles before the directory goes away, or Windows refuses the unlink.
44
+ t.after(() => {
45
+ second.close();
46
+ first.close();
47
+ return rm(dir, { recursive: true, force: true });
48
+ });
49
+ const state = second.getSession('session-a');
50
+ assert.equal(state?.lastSeq, 42);
51
+ assert.equal(state?.root, 'C:\\work');
52
+ assert.equal(state?.contributed, true);
53
+ assert.equal(second.sessionCount(), 1);
54
+ });
55
+ test('concurrent writers do not lose each other\'s update', async (t) => {
56
+ const { store } = await tempStore(t);
57
+ // The old JSON read-modify-write lost one of these; SQLite serializes them.
58
+ store.putSession('a', { lastSeq: 1, at: 0 });
59
+ store.putSession('b', { lastSeq: 1, at: 0 });
60
+ store.putSession('a', { lastSeq: 2, at: 0 });
61
+ assert.equal(store.getSession('a')?.lastSeq, 2);
62
+ assert.equal(store.getSession('b')?.lastSeq, 1);
63
+ assert.equal(store.sessionCount(), 2);
64
+ });
65
+ test('touchSession records activity without disturbing the watermark', async (t) => {
66
+ const { store } = await tempStore(t);
67
+ store.putSession('a', { lastSeq: 9, at: 5, contributed: true });
68
+ store.touchSession('a', 77);
69
+ const state = store.getSession('a');
70
+ assert.equal(state?.lastSeq, 9);
71
+ assert.equal(state?.contributed, true);
72
+ assert.equal(state?.activityAt, 77);
73
+ store.touchSession('fresh', 88);
74
+ assert.equal(store.getSession('fresh')?.lastSeq, 0);
75
+ });
76
+ test('a job lease is exclusive until it expires, and backoff is honoured', async (t) => {
77
+ const { store } = await tempStore(t);
78
+ store.putJob({ key: 'global', enqueuedAt: 0, notBefore: 0, retries: 0 });
79
+ const first = store.claimJob('global', 'worker-1', 1_000, 100);
80
+ assert.equal(first?.lease, 'worker-1');
81
+ // A second worker cannot take a live lease.
82
+ assert.equal(store.claimJob('global', 'worker-2', 1_000, 200), undefined);
83
+ // The same holder may renew it.
84
+ assert.equal(store.claimJob('global', 'worker-1', 1_000, 300)?.lease, 'worker-1');
85
+ // After expiry anyone may take over.
86
+ assert.equal(store.claimJob('global', 'worker-2', 1_000, 2_000)?.lease, 'worker-2');
87
+ // Backoff blocks even an expired lease.
88
+ store.putJob({ key: 'global', enqueuedAt: 0, notBefore: 5_000, retries: 1, leaseUntil: 0 });
89
+ assert.equal(store.claimJob('global', 'worker-3', 1_000, 4_000), undefined);
90
+ assert.equal(store.claimJob('global', 'worker-3', 1_000, 5_000)?.lease, 'worker-3');
91
+ });
92
+ test('a job can be deleted', async (t) => {
93
+ const { store } = await tempStore(t);
94
+ store.putJob({ key: 'global', enqueuedAt: 0, notBefore: 0, retries: 0 });
95
+ assert.ok(store.getJob('global') !== undefined);
96
+ store.deleteJob('global');
97
+ assert.equal(store.getJob('global'), undefined);
98
+ });
99
+ test('usage counters accumulate per scope and id', async (t) => {
100
+ const { store } = await tempStore(t);
101
+ assert.deepEqual(store.bumpUsage('global', 'x', 10), { uses: 1, lastUsedAt: 10 });
102
+ assert.deepEqual(store.bumpUsage('global', 'x', 20), { uses: 2, lastUsedAt: 20 });
103
+ assert.deepEqual(store.bumpUsage('project', 'x', 30), { uses: 1, lastUsedAt: 30 });
104
+ assert.deepEqual(store.getUsage('global', 'x'), { uses: 2, lastUsedAt: 20 });
105
+ assert.deepEqual(store.getUsage('project', 'x'), { uses: 1, lastUsedAt: 30 });
106
+ assert.equal(store.listUsage().length, 2);
107
+ });
108
+ test('a store created before the root column migrates on open', async (t) => {
109
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-state-migrate-'));
110
+ // A jobs table in the v1 shape: no `root` column.
111
+ const legacy = new StateStore(statePath(dir));
112
+ legacy.close();
113
+ const { DatabaseSync } = await import('node:sqlite');
114
+ const raw = new DatabaseSync(statePath(dir));
115
+ raw.exec('DROP TABLE jobs');
116
+ raw.exec('CREATE TABLE jobs (key TEXT PRIMARY KEY, enqueued_at INTEGER NOT NULL, not_before INTEGER NOT NULL DEFAULT 0, lease TEXT, lease_until INTEGER NOT NULL DEFAULT 0, retries INTEGER NOT NULL DEFAULT 0, last_error TEXT)');
117
+ raw.prepare('INSERT INTO jobs (key, enqueued_at, not_before, retries) VALUES (?, ?, ?, ?)').run('global', 1, 2, 0);
118
+ raw.close();
119
+ const reopened = new StateStore(statePath(dir));
120
+ t.after(() => {
121
+ reopened.close();
122
+ return rm(dir, { recursive: true, force: true });
123
+ });
124
+ // Reading and writing a job must work: without the migration this throws
125
+ // "no such column: root".
126
+ const job = reopened.getJob('global');
127
+ assert.equal(job?.enqueuedAt, 1);
128
+ assert.equal(job?.root, undefined);
129
+ reopened.putJob({ key: 'global', enqueuedAt: 1, notBefore: 2, retries: 0, root: 'C:\\work' });
130
+ assert.equal(reopened.getJob('global')?.root, 'C:\\work');
131
+ });
132
+ test('closing twice is safe and a closed store degrades instead of throwing', async (t) => {
133
+ const { store } = await tempStore(t);
134
+ store.close();
135
+ store.close();
136
+ // The fallback map keeps the API usable after close.
137
+ store.putSession('after-close', { lastSeq: 1, at: 1 });
138
+ assert.equal(store.getSession('after-close')?.lastSeq, 1);
139
+ });
140
+ test('surfaced marks are recorded without touching the read counters', async (t) => {
141
+ const { store } = await tempStore(t);
142
+ store.bumpUsage('global', 'x', 10);
143
+ store.bumpSurfaced('global', 'x', 20);
144
+ store.bumpSurfaced('global', 'x', 30);
145
+ // Surfacing is a weaker signal than a read: it must not inflate `uses`.
146
+ assert.deepEqual(store.getUsage('global', 'x'), { uses: 1, lastUsedAt: 10 });
147
+ const row = store.retentionRows().find((candidate) => candidate.id === 'x');
148
+ assert.equal(row?.surfacedAt, 30);
149
+ assert.equal(row?.consolidatedAt, 0);
150
+ });
151
+ test('a review mark is per entry and survives alongside usage', async (t) => {
152
+ const { store } = await tempStore(t);
153
+ store.bumpUsage('global', 'a', 5);
154
+ store.bumpSurfaced('global', 'a', 7);
155
+ store.markConsolidated([{ scope: 'global', id: 'a' }, { scope: 'project', id: 'b' }], 99);
156
+ const rows = store.retentionRows();
157
+ const global = rows.find((candidate) => candidate.scope === 'global' && candidate.id === 'a');
158
+ const project = rows.find((candidate) => candidate.scope === 'project' && candidate.id === 'b');
159
+ assert.deepEqual({ uses: global?.uses, lastUsedAt: global?.lastUsedAt, surfacedAt: global?.surfacedAt, consolidatedAt: global?.consolidatedAt }, { uses: 1, lastUsedAt: 5, surfacedAt: 7, consolidatedAt: 99 });
160
+ assert.equal(project?.consolidatedAt, 99);
161
+ });
162
+ test('bookkeeping values and per-session switches survive a reopen', async (t) => {
163
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-state-meta-'));
164
+ const first = new StateStore(statePath(dir));
165
+ first.putMeta('sweep-at', '1234');
166
+ first.setSessionMode('session-a', 'off');
167
+ first.close();
168
+ const second = new StateStore(statePath(dir));
169
+ t.after(() => {
170
+ second.close();
171
+ first.close();
172
+ return rm(dir, { recursive: true, force: true });
173
+ });
174
+ assert.equal(second.getMeta('sweep-at'), '1234');
175
+ assert.equal(second.getMeta('never-written'), undefined);
176
+ assert.equal(second.getSessionMode('session-a'), 'off');
177
+ assert.equal(second.getSessionMode('session-b'), 'on', 'memory is on unless it was turned off');
178
+ second.setSessionMode('session-a', 'on');
179
+ assert.equal(second.getSessionMode('session-a'), 'on');
180
+ // The switch is a column on the watermark row, so it must not disturb it.
181
+ assert.equal(second.getSession('session-a')?.lastSeq, 0);
182
+ });
183
+ test('a store created before the retention columns migrates on open', async (t) => {
184
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-state-usage-migrate-'));
185
+ const legacy = new StateStore(statePath(dir));
186
+ legacy.close();
187
+ const { DatabaseSync } = await import('node:sqlite');
188
+ const raw = new DatabaseSync(statePath(dir));
189
+ raw.exec('DROP TABLE usage');
190
+ raw.exec('DROP TABLE sessions');
191
+ raw.exec('CREATE TABLE usage (scope TEXT NOT NULL, id TEXT NOT NULL, uses INTEGER NOT NULL DEFAULT 0, last_used_at INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (scope, id))');
192
+ raw.exec('CREATE TABLE sessions (id TEXT PRIMARY KEY, last_seq INTEGER NOT NULL DEFAULT 0, at INTEGER NOT NULL DEFAULT 0, root TEXT, contributed INTEGER NOT NULL DEFAULT 0, activity_at INTEGER NOT NULL DEFAULT 0)');
193
+ raw.close();
194
+ const reopened = new StateStore(statePath(dir));
195
+ t.after(() => {
196
+ reopened.close();
197
+ return rm(dir, { recursive: true, force: true });
198
+ });
199
+ // Each of these names a column the old table did not have.
200
+ reopened.bumpSurfaced('global', 'x', 1);
201
+ reopened.markConsolidated([{ scope: 'global', id: 'x' }], 2);
202
+ assert.equal(reopened.retentionRows()[0]?.consolidatedAt, 2);
203
+ assert.equal(reopened.getSessionMode('nobody'), 'on');
204
+ });
205
+ test('minedCount separates mined sessions from merely tracked ones', async (t) => {
206
+ const { store } = await tempStore(t);
207
+ store.touchSession('touched', 5);
208
+ store.setSessionMode('switched', 'off');
209
+ store.putSession('mined', { lastSeq: 7, at: 6, contributed: true });
210
+ assert.equal(store.sessionCount(), 3, 'every row counts as tracked');
211
+ assert.equal(store.minedCount(), 1, 'only the session with a watermark was mined');
212
+ });
@@ -0,0 +1,139 @@
1
+ /**
2
+ * The kernel contract the consolidation child is started under.
3
+ *
4
+ * Since 0.2.1-rc.2 a child is started through `subagents.startActivation`, which
5
+ * folds the caller's fields into a continuable descriptor and validates that
6
+ * descriptor with the kernel's lossless-JSON snapshot. The descriptor is built
7
+ * with `label: input.label` written UNCONDITIONALLY, so a caller that omits the
8
+ * label does not get "no label" — it gets a descriptor the snapshot rejects, and
9
+ * the error surfaces as
10
+ * `subagent descriptor is not losslessly JSON-serializable`.
11
+ *
12
+ * That is exactly how consolidation died on 2026-10-20: the pass kept retrying,
13
+ * the job kept backing off, and every attempt failed before the child started.
14
+ * The unit tests did not catch it because the fake seam in `consolidate.test.ts`
15
+ * returns a canned reply and never builds a descriptor — the plugin's own
16
+ * interface was tested instead of the kernel's contract.
17
+ *
18
+ * This file pins the contract without starting a kernel: it reproduces the two
19
+ * steps that actually failed (fold the fields, then validate) and asserts the
20
+ * spec this plugin builds survives both, including a mutation test proving the
21
+ * assertion is not vacuous.
22
+ *
23
+ * @module dsh-cross-memory/test/subagent-contract.test
24
+ */
25
+ import assert from 'node:assert/strict';
26
+ import test from 'node:test';
27
+ import { buildActivationSpec, CONSOLIDATE_LABEL } from '../consolidate.js';
28
+ /**
29
+ * Reject a value the kernel's descriptor snapshot would refuse.
30
+ *
31
+ * `dsh-util-values` detaches a value with `walkJsonValue`, which yields
32
+ * `undefined` for any leaf JSON cannot express — `undefined`, functions,
33
+ * symbols, bigints — and `snapshotSubagentDescriptor` turns that into a thrown
34
+ * error. Note this is STRICTER than `JSON.stringify`, which silently drops an
35
+ * `undefined`-valued property instead of failing: that difference is the whole
36
+ * bug this file exists for.
37
+ *
38
+ * @param value - candidate value.
39
+ * @param path - location used in the failure message.
40
+ */
41
+ function assertLossless(value, path = '$') {
42
+ if (value === null)
43
+ return;
44
+ const type = typeof value;
45
+ if (type === 'string' || type === 'number' || type === 'boolean')
46
+ return;
47
+ if (type === 'object') {
48
+ if (Array.isArray(value)) {
49
+ value.forEach((item, index) => assertLossless(item, `${path}[${index}]`));
50
+ return;
51
+ }
52
+ const proto = Object.getPrototypeOf(value);
53
+ if (proto !== Object.prototype && proto !== null)
54
+ throw new Error(`${path} is not a plain object`);
55
+ const record = value;
56
+ for (const [key, item] of Object.entries(record))
57
+ assertLossless(item, `${path}.${key}`);
58
+ return;
59
+ }
60
+ throw new Error(`${path} is not losslessly JSON-serializable (${type})`);
61
+ }
62
+ /**
63
+ * The subset of the spec that the kernel snapshots into a descriptor.
64
+ *
65
+ * The request (prompt blocks, a live Agent, an AbortSignal) is passed through,
66
+ * never serialized, so it is deliberately absent here — a check over the whole
67
+ * spec would fail for the wrong reason.
68
+ *
69
+ * @param spec - the seam spec this plugin builds.
70
+ * @returns the candidate descriptor, shaped as the kernel shapes it.
71
+ */
72
+ function descriptorOf(spec) {
73
+ return { version: 1, mode: 'continuable', provider: spec.provider, label: spec.label };
74
+ }
75
+ /** A request naming a route and a preset, i.e. the common production case. */
76
+ function routedRequest() {
77
+ return {
78
+ parent: {},
79
+ provider: 'test-provider',
80
+ model: 'test-model',
81
+ agentPreset: 'memories-consolidator',
82
+ subagentProvider: 'spawn',
83
+ entries: [],
84
+ projectLabel: 'demo',
85
+ maxUpserts: 3,
86
+ denyTools: [],
87
+ timeoutMs: 1000,
88
+ signal: AbortSignal.timeout(1000),
89
+ };
90
+ }
91
+ /** A request with no route and no preset: both optionals must be absent, not undefined. */
92
+ function bareRequest() {
93
+ return {
94
+ parent: {},
95
+ entries: [],
96
+ projectLabel: 'demo',
97
+ maxUpserts: 3,
98
+ denyTools: [],
99
+ timeoutMs: 1000,
100
+ signal: AbortSignal.timeout(1000),
101
+ };
102
+ }
103
+ const PROMPT = [{ type: 'text', text: 'consolidate these memories' }];
104
+ test('the descriptor the kernel builds from our spec survives its lossless snapshot', () => {
105
+ const spec = buildActivationSpec(routedRequest(), PROMPT, AbortSignal.timeout(1000));
106
+ assert.doesNotThrow(() => assertLossless(descriptorOf(spec)));
107
+ });
108
+ test('the label is a non-empty string, so the kernel never sees undefined', () => {
109
+ const spec = buildActivationSpec(routedRequest(), PROMPT, AbortSignal.timeout(1000));
110
+ assert.equal(typeof spec.label, 'string');
111
+ assert.ok(spec.label.length > 0);
112
+ assert.equal(spec.label, CONSOLIDATE_LABEL);
113
+ });
114
+ test('a bare request omits optional fields instead of setting them to undefined', () => {
115
+ const spec = buildActivationSpec(bareRequest(), PROMPT, AbortSignal.timeout(1000));
116
+ assert.ok(!('agentOptions' in spec.request));
117
+ assert.ok(!('agentPreset' in spec.request));
118
+ for (const [key, value] of Object.entries(spec.request)) {
119
+ assert.ok(value !== undefined, `request.${key} is present but undefined`);
120
+ }
121
+ assert.doesNotThrow(() => assertLossless(descriptorOf(spec)));
122
+ });
123
+ test('the check is not vacuous: a descriptor with an undefined label is rejected', () => {
124
+ // This is the exact regression. If the plugin drops the label again, the first
125
+ // test fails; if this checker stops catching undefined, this one does.
126
+ assert.throws(() => assertLossless({ version: 1, mode: 'continuable', provider: 'spawn', label: undefined }), /not losslessly JSON-serializable/u);
127
+ });
128
+ test('the spec carries the signal at the top level, where the kernel reads it', () => {
129
+ // The kernel's continuable path calls `spec.signal.throwIfAborted()` and passes
130
+ // `spec.signal` into prepareContinuable; it never looks at `spec.request.signal`.
131
+ // A spec with the signal only inside the request reserved the child and then
132
+ // crashed with "Cannot read properties of undefined (reading 'throwIfAborted')".
133
+ const timeout = AbortSignal.timeout(1_000);
134
+ const spec = buildActivationSpec(routedRequest(), PROMPT, timeout);
135
+ assert.equal(spec.signal, timeout, 'the top-level signal is the one the caller passed');
136
+ assert.equal(spec.request.signal, timeout, 'and the request kept its own copy');
137
+ assert.equal(typeof spec.signal.throwIfAborted, 'function');
138
+ assert.doesNotThrow(() => spec.signal.throwIfAborted());
139
+ });
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Tests for the periodic maintenance sweep.
3
+ *
4
+ * Extraction used to be the only thing that ever triggered cleaning, so a store
5
+ * that stopped producing new memories was never cleaned at all. The sweep is
6
+ * driven by its own clock, covers every workspace on disk, and survives a
7
+ * restart through the state database.
8
+ *
9
+ * @module dsh-cross-memory/test/sweep.test
10
+ */
11
+ import assert from 'node:assert/strict';
12
+ import { existsSync } from 'node:fs';
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 { projectSlug } from '../storage.js';
19
+ /** One day in milliseconds. */
20
+ const DAY = 86_400_000;
21
+ /** A clock far enough from the epoch that ages read naturally. */
22
+ const NOW = 10_000 * DAY;
23
+ /** An hour in milliseconds. */
24
+ const HOUR = 3_600_000;
25
+ /** A context stand-in exposing only what the runtime touches. */
26
+ const stubContext = {
27
+ get: () => undefined,
28
+ logger: { info: () => undefined, warn: () => undefined, debug: () => undefined },
29
+ };
30
+ /** A session stand-in. */
31
+ function stubSession(cwd) {
32
+ return {
33
+ id: 'test-session',
34
+ header: { version: 0, id: 'test-session', createdAt: 0, cwd, isSeeded: false },
35
+ seq: 1,
36
+ requestHeader: () => undefined,
37
+ deriveMessages: () => [],
38
+ };
39
+ }
40
+ /** A runtime over a temp store. */
41
+ async function fixture(t, settings = {}) {
42
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-sweep-'));
43
+ const runtime = new MemoriesRuntime(stubContext, { memoriesDir: dir, autoExtract: false, ...settings });
44
+ t.after(() => {
45
+ runtime.dispose();
46
+ return rm(dir, { recursive: true, force: true });
47
+ });
48
+ return { dir, runtime };
49
+ }
50
+ test('the sweep archives unused memories once, then waits for its interval', async (t) => {
51
+ const { runtime } = await fixture(t);
52
+ await runtime.store.upsert({ scope: 'global', title: 'Ancient fact', body: 'x', tags: [] }, undefined, 'auto', NOW - 400 * DAY);
53
+ assert.equal(await runtime.sweepIfDue(NOW), 1);
54
+ assert.deepEqual(await runtime.store.list('global', undefined, { fresh: true }), []);
55
+ assert.deepEqual((await runtime.store.listArchived('global', undefined)).map((entry) => entry.id), ['ancient-fact']);
56
+ assert.equal(runtime.state.getMeta('sweep-at'), String(NOW), 'the interval is recorded');
57
+ // Inside the interval nothing runs, even with more stale material waiting.
58
+ await runtime.store.upsert({ scope: 'global', title: 'Another fact', body: 'x', tags: [] }, undefined, 'auto', NOW - 400 * DAY);
59
+ assert.equal(await runtime.sweepIfDue(NOW + HOUR), 0);
60
+ assert.equal((await runtime.store.list('global', undefined, { fresh: true })).length, 1);
61
+ // Past it, the next sweep collects what the last one skipped.
62
+ assert.equal(await runtime.sweepIfDue(NOW + 13 * HOUR), 1);
63
+ });
64
+ test('a manual sweep ignores the interval, which is what `/memories sweep` means', async (t) => {
65
+ const { runtime } = await fixture(t);
66
+ await runtime.store.upsert({ scope: 'global', title: 'Ancient fact', body: 'x', tags: [] }, undefined, 'auto', NOW - 400 * DAY);
67
+ assert.equal(await runtime.sweepNow(NOW), 1);
68
+ await runtime.store.upsert({ scope: 'global', title: 'Second fact', body: 'x', tags: [] }, undefined, 'auto', NOW - 400 * DAY);
69
+ assert.equal(await runtime.sweepNow(NOW), 1, 'the interval does not gate a manual sweep');
70
+ });
71
+ test('the sweep covers every workspace on disk, not only the active one', async (t) => {
72
+ const { runtime } = await fixture(t);
73
+ const root = 'C:\\Code\\alpha';
74
+ await runtime.store.upsert({ scope: 'project', title: 'Stale project fact', body: 'x', tags: [] }, root, 'auto', NOW - 400 * DAY);
75
+ assert.equal(await runtime.sweepIfDue(NOW), 1);
76
+ assert.deepEqual(await runtime.store.list('project', root, { fresh: true }), []);
77
+ assert.deepEqual((await runtime.store.listArchived('project', root)).map((entry) => entry.id), ['stale-project-fact']);
78
+ });
79
+ test('the sweep removes project directories that hold nothing recoverable', async (t) => {
80
+ const { runtime, dir } = await fixture(t);
81
+ const archivedRoot = 'C:\\Code\\abandoned';
82
+ const emptyRoot = 'C:\\Code\\never-used';
83
+ // One workspace produced a memory that retention then archived; another left a
84
+ // slug behind without ever producing one. A real store had 12 of its 19 project
85
+ // directories like this, six of them without even a descriptor.
86
+ await runtime.store.upsert({ scope: 'project', title: 'Stale project fact', body: 'x', tags: [] }, archivedRoot, 'auto', NOW - 400 * DAY);
87
+ await runtime.store.writeProjectDescriptor(emptyRoot, NOW);
88
+ assert.equal((await runtime.store.listProjects()).length, 2);
89
+ await runtime.sweepNow(NOW);
90
+ assert.deepEqual(await runtime.store.listProjects(), [projectSlug(archivedRoot)], 'only the empty directory is gone');
91
+ assert.deepEqual((await runtime.store.listArchived('project', archivedRoot)).map((entry) => entry.id), ['stale-project-fact'], 'the archived workspace keeps its directory: an archive is restorable data');
92
+ assert.equal(existsSync(join(dir, 'projects', projectSlug(emptyRoot))), false);
93
+ });
94
+ test('retention is off when maxUnusedDays is 0', async (t) => {
95
+ const { runtime } = await fixture(t, { maxUnusedDays: 0 });
96
+ await runtime.store.upsert({ scope: 'global', title: 'Ancient fact', body: 'x', tags: [] }, undefined, 'auto', 1);
97
+ assert.equal(await runtime.sweepIfDue(NOW), 0);
98
+ assert.equal((await runtime.store.list('global', undefined, { fresh: true })).length, 1);
99
+ });
100
+ test('an archived memory can be listed and restored through the runtime', async (t) => {
101
+ const { runtime } = await fixture(t);
102
+ const session = stubSession(process.cwd());
103
+ await runtime.store.upsert({ scope: 'global', title: 'Ancient fact', body: 'Body text', tags: [] }, undefined, 'auto', NOW - 400 * DAY);
104
+ await runtime.sweepNow(NOW);
105
+ assert.match(await runtime.archived(session, 'global'), /ancient-fact|Ancient fact/u);
106
+ assert.match(await runtime.restore(session, 'ancient-fact'), /Restored ancient-fact into global/u);
107
+ assert.equal((await runtime.store.list('global', undefined, { fresh: true })).length, 1);
108
+ assert.match(await runtime.restore(session, 'ancient-fact'), /No archived memory/u);
109
+ });
110
+ test('the sweep and the background pass each report themselves in one line', async (t) => {
111
+ const lines = [];
112
+ const capturing = {
113
+ get: () => undefined,
114
+ logger: {
115
+ info: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
116
+ warn: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
117
+ debug: (format, ...args) => lines.push(`${format} ${args.join(' ')}`),
118
+ },
119
+ };
120
+ const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-report-'));
121
+ const runtime = new MemoriesRuntime(capturing, { memoriesDir: dir, autoExtract: true });
122
+ t.after(() => {
123
+ runtime.dispose();
124
+ return rm(dir, { recursive: true, force: true });
125
+ });
126
+ // One memory nothing has ever surfaced: at twelve days old nothing is old
127
+ // enough for retention, so only this line can say the store has dead weight.
128
+ await runtime.store.upsert({ scope: 'global', title: 'Never surfaced', body: 'x', tags: [] }, undefined, 'auto', NOW);
129
+ await runtime.sweepNow(NOW);
130
+ // The host formats `%d`/`%s` downstream, so the stub sees the template plus its
131
+ // arguments; what matters here is that the line exists at all.
132
+ const sweep = lines.find((line) => line.startsWith('dsh-cross-memory: sweep:'));
133
+ assert.ok(sweep !== undefined, 'a sweep says what it did even when that is nothing');
134
+ assert.match(sweep, /archived %d memories across %d project scopes, pruned %d empty project/u);
135
+ // An unseen tail is invisible to an age-based retention rule, so the sweep is
136
+ // where "nobody has ever seen these" has to be said.
137
+ const unseen = lines.find((line) => line.includes('never been injected or read'));
138
+ assert.ok(unseen !== undefined, 'a memory nothing has surfaced is reported');
139
+ assert.match(unseen, /%d of %d memories/u);
140
+ lines.length = 0;
141
+ // No tracked session: the pass has nothing to do, and the point is that the
142
+ // file still answers "did the extractor run, and why did it do nothing".
143
+ await runtime.runPeriodicPass();
144
+ const pass = lines.find((line) => line.startsWith('dsh-cross-memory: extract pass:'));
145
+ assert.ok(pass !== undefined, 'a pass with no work still leaves a line');
146
+ assert.match(pass, /%d live, %d considered, %d mined/u, 'the line separates what was live from what was considered');
147
+ });
148
+ test('stats reports the recall and retention configuration', async (t) => {
149
+ const { runtime } = await fixture(t, { recallMode: 'once', maxUnusedDays: 30, sweepIntervalHours: 24, autoExtract: true, minIdleHours: 6 });
150
+ const text = await runtime.stats(stubSession(process.cwd()));
151
+ assert.match(text, /recall: once/u);
152
+ assert.match(text, /archive after 30d unused/u);
153
+ assert.match(text, /sweep every 24h/u);
154
+ assert.match(text, /session mode: on/u);
155
+ assert.match(text, /logging: info → /u, 'stats names the log level and file');
156
+ assert.match(text, /sessions: 0 mined \/ 0 tracked/u);
157
+ assert.match(text, /auto-extract: on \(every 30m \+ 6h quiet to settle/u, 'stats shows both the periodic check and the settle wait');
158
+ assert.match(text, /peak-hours: off/u, 'no peak rule is reported as off');
159
+ });