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.
- package/LICENSE +21 -0
- package/README.md +247 -2
- package/cordis.patch.yml +27 -0
- package/docs/DETAIL.md +13 -0
- package/docs/DETAIL.zh.md +17 -0
- package/icon.svg +1 -0
- package/lib/backfill.js +273 -0
- package/lib/citations.js +305 -0
- package/lib/client.js +1550 -0
- package/lib/config.js +736 -0
- package/lib/consolidate.js +1119 -0
- package/lib/extract.js +570 -0
- package/lib/gate.js +137 -0
- package/lib/git-origin.js +224 -0
- package/lib/index.js +4475 -0
- package/lib/log.js +260 -0
- package/lib/loops.js +186 -0
- package/lib/notices.js +195 -0
- package/lib/notify.js +33 -0
- package/lib/persona.js +112 -0
- package/lib/query.js +93 -0
- package/lib/raw-recall.js +286 -0
- package/lib/reflection.js +291 -0
- package/lib/remote.js +455 -0
- package/lib/render.js +678 -0
- package/lib/retention.js +64 -0
- package/lib/schedule.js +245 -0
- package/lib/search.js +1068 -0
- package/lib/skills.js +220 -0
- package/lib/state.js +701 -0
- package/lib/storage.js +1424 -0
- package/lib/sync-runtime.js +268 -0
- package/lib/sync.js +620 -0
- package/lib/test/activity.test.js +74 -0
- package/lib/test/archive.test.js +182 -0
- package/lib/test/backfill.test.js +144 -0
- package/lib/test/citations.test.js +91 -0
- package/lib/test/client-wiring.test.js +134 -0
- package/lib/test/consolidate-job.test.js +95 -0
- package/lib/test/consolidate.test.js +430 -0
- package/lib/test/consolidation-selection.test.js +152 -0
- package/lib/test/dedupe-keys.test.js +230 -0
- package/lib/test/delta.test.js +93 -0
- package/lib/test/derived.test.js +110 -0
- package/lib/test/disputes-panel.test.js +314 -0
- package/lib/test/eval.test.js +171 -0
- package/lib/test/expand.test.js +164 -0
- package/lib/test/extract.test.js +1020 -0
- package/lib/test/git-origin.test.js +189 -0
- package/lib/test/injection.test.js +440 -0
- package/lib/test/kind-filter.test.js +49 -0
- package/lib/test/legacy-state.test.js +69 -0
- package/lib/test/log.test.js +156 -0
- package/lib/test/loops.test.js +86 -0
- package/lib/test/memory.test.js +855 -0
- package/lib/test/notices.test.js +140 -0
- package/lib/test/persona.test.js +73 -0
- package/lib/test/prefilter.test.js +73 -0
- package/lib/test/preset.test.js +77 -0
- package/lib/test/raw-recall.test.js +186 -0
- package/lib/test/recall.test.js +433 -0
- package/lib/test/reflection.test.js +64 -0
- package/lib/test/remote.test.js +227 -0
- package/lib/test/retention.test.js +117 -0
- package/lib/test/retrieval.test.js +142 -0
- package/lib/test/rotation.test.js +228 -0
- package/lib/test/schedule.test.js +112 -0
- package/lib/test/settings-card.test.js +58 -0
- package/lib/test/skills.test.js +129 -0
- package/lib/test/state.test.js +212 -0
- package/lib/test/subagent-contract.test.js +139 -0
- package/lib/test/sweep.test.js +159 -0
- package/lib/test/sync.test.js +314 -0
- package/lib/test/time.test.js +171 -0
- package/lib/time.js +303 -0
- package/lib/tool.js +330 -0
- package/lib/types/backfill.d.ts +96 -0
- package/lib/types/citations.d.ts +105 -0
- package/lib/types/config.d.ts +811 -0
- package/lib/types/consolidate.d.ts +742 -0
- package/lib/types/extract.d.ts +352 -0
- package/lib/types/gate.d.ts +83 -0
- package/lib/types/git-origin.d.ts +23 -0
- package/lib/types/index.d.ts +1316 -0
- package/lib/types/log.d.ts +144 -0
- package/lib/types/loops.d.ts +82 -0
- package/lib/types/notices.d.ts +117 -0
- package/lib/types/notify.d.ts +12 -0
- package/lib/types/persona.d.ts +43 -0
- package/lib/types/query.d.ts +45 -0
- package/lib/types/raw-recall.d.ts +84 -0
- package/lib/types/reflection.d.ts +122 -0
- package/lib/types/remote.d.ts +233 -0
- package/lib/types/render.d.ts +286 -0
- package/lib/types/retention.d.ts +66 -0
- package/lib/types/schedule.d.ts +116 -0
- package/lib/types/search.d.ts +583 -0
- package/lib/types/skills.d.ts +71 -0
- package/lib/types/state.d.ts +294 -0
- package/lib/types/storage.d.ts +458 -0
- package/lib/types/sync-runtime.d.ts +103 -0
- package/lib/types/sync.d.ts +222 -0
- package/lib/types/test/activity.test.d.ts +1 -0
- package/lib/types/test/archive.test.d.ts +1 -0
- package/lib/types/test/backfill.test.d.ts +1 -0
- package/lib/types/test/citations.test.d.ts +1 -0
- package/lib/types/test/client-wiring.test.d.ts +1 -0
- package/lib/types/test/consolidate-job.test.d.ts +1 -0
- package/lib/types/test/consolidate.test.d.ts +1 -0
- package/lib/types/test/consolidation-selection.test.d.ts +1 -0
- package/lib/types/test/dedupe-keys.test.d.ts +1 -0
- package/lib/types/test/delta.test.d.ts +1 -0
- package/lib/types/test/derived.test.d.ts +1 -0
- package/lib/types/test/disputes-panel.test.d.ts +1 -0
- package/lib/types/test/eval.test.d.ts +1 -0
- package/lib/types/test/expand.test.d.ts +1 -0
- package/lib/types/test/extract.test.d.ts +1 -0
- package/lib/types/test/git-origin.test.d.ts +1 -0
- package/lib/types/test/injection.test.d.ts +1 -0
- package/lib/types/test/kind-filter.test.d.ts +1 -0
- package/lib/types/test/legacy-state.test.d.ts +1 -0
- package/lib/types/test/log.test.d.ts +1 -0
- package/lib/types/test/loops.test.d.ts +1 -0
- package/lib/types/test/memory.test.d.ts +1 -0
- package/lib/types/test/notices.test.d.ts +1 -0
- package/lib/types/test/persona.test.d.ts +1 -0
- package/lib/types/test/prefilter.test.d.ts +1 -0
- package/lib/types/test/preset.test.d.ts +1 -0
- package/lib/types/test/raw-recall.test.d.ts +1 -0
- package/lib/types/test/recall.test.d.ts +1 -0
- package/lib/types/test/reflection.test.d.ts +1 -0
- package/lib/types/test/remote.test.d.ts +1 -0
- package/lib/types/test/retention.test.d.ts +1 -0
- package/lib/types/test/retrieval.test.d.ts +1 -0
- package/lib/types/test/rotation.test.d.ts +1 -0
- package/lib/types/test/schedule.test.d.ts +1 -0
- package/lib/types/test/settings-card.test.d.ts +1 -0
- package/lib/types/test/skills.test.d.ts +1 -0
- package/lib/types/test/state.test.d.ts +1 -0
- package/lib/types/test/subagent-contract.test.d.ts +1 -0
- package/lib/types/test/sweep.test.d.ts +1 -0
- package/lib/types/test/sync.test.d.ts +1 -0
- package/lib/types/test/time.test.d.ts +1 -0
- package/lib/types/time.d.ts +67 -0
- package/lib/types/tool.d.ts +9 -0
- package/lib/types/types.d.ts +374 -0
- package/lib/types/workspace.d.ts +20 -0
- package/lib/types.js +47 -0
- package/lib/workspace.js +65 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +126 -4
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the age gate's clock.
|
|
3
|
+
*
|
|
4
|
+
* `maxAgeDays` decides whether a finished session is still worth mining. It
|
|
5
|
+
* reads the session's last OBSERVED activity, which only exists because the
|
|
6
|
+
* plugin records it on every status transition. Without that recording the
|
|
7
|
+
* gate silently never fires — the bug these tests exist to prevent from
|
|
8
|
+
* coming back.
|
|
9
|
+
*
|
|
10
|
+
* @module dsh-cross-memory/test/activity.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
|
+
/** A context stand-in exposing only what the runtime touches. */
|
|
19
|
+
const stubContext = {
|
|
20
|
+
get: () => undefined,
|
|
21
|
+
logger: { info: () => undefined, warn: () => undefined, debug: () => undefined },
|
|
22
|
+
};
|
|
23
|
+
/** A session stand-in: the runtime only reads the id and the header. */
|
|
24
|
+
function stubSession(id, cwd = process.cwd()) {
|
|
25
|
+
return {
|
|
26
|
+
id,
|
|
27
|
+
header: { version: 0, id, createdAt: 0, cwd, isSeeded: false },
|
|
28
|
+
seq: 1,
|
|
29
|
+
requestHeader: () => undefined,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
test('recordActivity writes the clock the age gate reads', async (t) => {
|
|
33
|
+
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-activity-'));
|
|
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
|
+
const session = stubSession('session-a');
|
|
40
|
+
assert.equal(runtime.state.getSession('session-a'), undefined, 'nothing is recorded before any activity');
|
|
41
|
+
runtime.recordActivity(session, 1_000);
|
|
42
|
+
assert.equal(runtime.state.getSession('session-a')?.activityAt, 1_000);
|
|
43
|
+
runtime.recordActivity(session, 2_000);
|
|
44
|
+
assert.equal(runtime.state.getSession('session-a')?.activityAt, 2_000, 'later activity moves the clock');
|
|
45
|
+
// Recording activity must not fabricate a watermark: a session can be used
|
|
46
|
+
// for days without ever being mined.
|
|
47
|
+
assert.equal(runtime.state.getSession('session-a')?.lastSeq, 0);
|
|
48
|
+
});
|
|
49
|
+
test('recording activity keeps an existing watermark intact', async (t) => {
|
|
50
|
+
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-activity-keep-'));
|
|
51
|
+
const runtime = new MemoriesRuntime(stubContext, { memoriesDir: dir, autoExtract: false });
|
|
52
|
+
t.after(() => {
|
|
53
|
+
runtime.dispose();
|
|
54
|
+
return rm(dir, { recursive: true, force: true });
|
|
55
|
+
});
|
|
56
|
+
runtime.state.putSession('session-a', { lastSeq: 42, at: 500, contributed: true, activityAt: 600 });
|
|
57
|
+
runtime.recordActivity(stubSession('session-a'), 9_000);
|
|
58
|
+
const state = runtime.state.getSession('session-a');
|
|
59
|
+
assert.equal(state?.activityAt, 9_000);
|
|
60
|
+
assert.equal(state?.lastSeq, 42, 'the watermark is untouched');
|
|
61
|
+
assert.equal(state?.contributed, true);
|
|
62
|
+
});
|
|
63
|
+
test('activity is per session', async (t) => {
|
|
64
|
+
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-activity-scope-'));
|
|
65
|
+
const runtime = new MemoriesRuntime(stubContext, { memoriesDir: dir, autoExtract: false });
|
|
66
|
+
t.after(() => {
|
|
67
|
+
runtime.dispose();
|
|
68
|
+
return rm(dir, { recursive: true, force: true });
|
|
69
|
+
});
|
|
70
|
+
runtime.recordActivity(stubSession('a'), 1_000);
|
|
71
|
+
runtime.recordActivity(stubSession('b'), 2_000);
|
|
72
|
+
assert.equal(runtime.state.getSession('a')?.activityAt, 1_000);
|
|
73
|
+
assert.equal(runtime.state.getSession('b')?.activityAt, 2_000);
|
|
74
|
+
});
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for archival: retiring a memory without destroying it.
|
|
3
|
+
*
|
|
4
|
+
* Consolidation retires what it judges stale and the per-scope cap evicts what
|
|
5
|
+
* it judges least valuable. Both judgements can be wrong, so the store moves an
|
|
6
|
+
* entry to `archive/` and `restore` brings it back — these tests pin that the
|
|
7
|
+
* round trip loses nothing.
|
|
8
|
+
*
|
|
9
|
+
* @module dsh-cross-memory/test/archive.test
|
|
10
|
+
*/
|
|
11
|
+
import assert from 'node:assert/strict';
|
|
12
|
+
import { mkdtemp, readFile, 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 { MemoryStore } from '../storage.js';
|
|
17
|
+
/** A store and its temporary directory. */
|
|
18
|
+
async function tempStore() {
|
|
19
|
+
const dir = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-archive-'));
|
|
20
|
+
return { store: new MemoryStore(dir), dir };
|
|
21
|
+
}
|
|
22
|
+
test('archive moves an entry out of the live store and restore brings it back', async (t) => {
|
|
23
|
+
const { store, dir } = await tempStore();
|
|
24
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
25
|
+
await store.upsert({ scope: 'global', title: 'Retire me', body: 'An old fact.', tags: ['x'] }, undefined, 'auto', 1_000);
|
|
26
|
+
assert.equal(await store.archive('global', undefined, 'retire-me', 2_000), true);
|
|
27
|
+
assert.deepEqual(await store.list('global', undefined, { fresh: true }), [], 'the live store no longer lists it');
|
|
28
|
+
assert.deepEqual((await store.listArchived('global', undefined)).map((entry) => entry.id), ['retire-me']);
|
|
29
|
+
// The archived file records when it happened, so a reader can tell how long it
|
|
30
|
+
// has been out of circulation.
|
|
31
|
+
const archived = await readFile(join(dir, 'archive', 'retire-me.md'), 'utf8');
|
|
32
|
+
assert.match(archived, /^archived: 1970-01-01T00:00:02\.000Z$/mu);
|
|
33
|
+
assert.match(archived, /An old fact\./u);
|
|
34
|
+
assert.equal(await store.restore('global', undefined, 'retire-me'), true);
|
|
35
|
+
const restored = await store.list('global', undefined, { fresh: true });
|
|
36
|
+
assert.deepEqual(restored.map((entry) => entry.id), ['retire-me']);
|
|
37
|
+
assert.equal(restored[0]?.body, 'An old fact.');
|
|
38
|
+
assert.equal(restored[0]?.tags[0], 'x');
|
|
39
|
+
assert.deepEqual(await store.listArchived('global', undefined), [], 'the archive is empty again');
|
|
40
|
+
assert.doesNotMatch(await readFile(join(dir, 'entries', 'retire-me.md'), 'utf8'), /archived:/u);
|
|
41
|
+
});
|
|
42
|
+
test('archiving something absent, and restoring twice, report the truth', async (t) => {
|
|
43
|
+
const { store, dir } = await tempStore();
|
|
44
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
45
|
+
assert.equal(await store.archive('global', undefined, 'missing'), false);
|
|
46
|
+
assert.equal(await store.restore('global', undefined, 'missing'), false);
|
|
47
|
+
await store.upsert({ scope: 'global', title: 'Once', body: 'x', tags: [] }, undefined, 'tool', 1);
|
|
48
|
+
await store.archive('global', undefined, 'once');
|
|
49
|
+
assert.equal(await store.restore('global', undefined, 'once'), true);
|
|
50
|
+
assert.equal(await store.restore('global', undefined, 'once'), false, 'the archive copy is gone');
|
|
51
|
+
});
|
|
52
|
+
test('restore refuses to overwrite a live entry that came back another way', async (t) => {
|
|
53
|
+
const { store, dir } = await tempStore();
|
|
54
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
55
|
+
await store.upsert({ scope: 'global', title: 'Conflict', body: 'first', tags: [] }, undefined, 'tool', 1);
|
|
56
|
+
await store.archive('global', undefined, 'conflict');
|
|
57
|
+
await store.upsert({ scope: 'global', title: 'Conflict', body: 'rewritten while archived', tags: [] }, undefined, 'tool', 2);
|
|
58
|
+
assert.equal(await store.restore('global', undefined, 'conflict'), false);
|
|
59
|
+
assert.equal((await store.read('global', undefined, 'conflict'))?.body, 'rewritten while archived');
|
|
60
|
+
});
|
|
61
|
+
test('the per-scope cap archives the entries it evicts instead of deleting them', async (t) => {
|
|
62
|
+
const { store, dir } = await tempStore();
|
|
63
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
64
|
+
store.entryLimit = () => 2;
|
|
65
|
+
for (let index = 0; index < 4; index += 1) {
|
|
66
|
+
await store.upsert({ scope: 'global', title: `Entry ${index}`, body: 'x', tags: [] }, undefined, 'tool', index + 1);
|
|
67
|
+
}
|
|
68
|
+
const listed = await store.list('global', undefined, { fresh: true });
|
|
69
|
+
assert.deepEqual(listed.map((entry) => entry.title), ['Entry 3', 'Entry 2']);
|
|
70
|
+
assert.deepEqual((await store.listArchived('global', undefined)).map((entry) => entry.id), ['entry-0', 'entry-1']);
|
|
71
|
+
});
|
|
72
|
+
test('an archived project entry stays inside its own workspace', async (t) => {
|
|
73
|
+
const { store, dir } = await tempStore();
|
|
74
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
75
|
+
const root = 'C:\\Code\\alpha';
|
|
76
|
+
await store.upsert({ scope: 'project', title: 'Only here', body: 'x', tags: [] }, root, 'auto', 1);
|
|
77
|
+
assert.equal(await store.archive('project', root, 'only-here'), true);
|
|
78
|
+
assert.deepEqual(await store.listArchived('project', 'C:\\Code\\beta'), [], 'another workspace sees no archive');
|
|
79
|
+
assert.deepEqual((await store.listArchived('project', root)).map((entry) => entry.id), ['only-here']);
|
|
80
|
+
});
|
|
81
|
+
test('the cap never evicts a pinned entry, nor one a person wrote', async (t) => {
|
|
82
|
+
const { store, dir } = await tempStore();
|
|
83
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
84
|
+
// One slot, three entries: the naive cap would evict the two oldest, which are
|
|
85
|
+
// exactly the two retention has always promised to protect.
|
|
86
|
+
store.entryLimit = () => 1;
|
|
87
|
+
await store.upsert({ scope: 'global', title: 'Pinned rule', body: 'keep me', tags: [], pinned: true }, undefined, 'auto', 1);
|
|
88
|
+
await store.upsert({ scope: 'global', title: 'Typed by a person', body: 'keep me too', tags: [] }, undefined, 'user', 2);
|
|
89
|
+
await store.upsert({ scope: 'global', title: 'Extracted', body: 'guess', tags: [] }, undefined, 'auto', 3);
|
|
90
|
+
const live = await store.list('global', undefined, { fresh: true });
|
|
91
|
+
assert.deepEqual(live.map((entry) => entry.id).sort(), ['pinned-rule', 'typed-by-a-person']);
|
|
92
|
+
assert.deepEqual((await store.listArchived('global', undefined)).map((entry) => entry.id), ['extracted'], 'the cap spent its one eviction on the only entry it is allowed to take');
|
|
93
|
+
});
|
|
94
|
+
test('every retirement is reported with the reason it happened', async (t) => {
|
|
95
|
+
const { store, dir } = await tempStore();
|
|
96
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
97
|
+
const retired = [];
|
|
98
|
+
store.onRetire = (info) => retired.push(info.reason + ':' + info.id);
|
|
99
|
+
await store.upsert({ scope: 'global', title: 'Old fact', body: 'a', tags: [] }, undefined, 'auto', 1);
|
|
100
|
+
await store.upsert({ scope: 'global', title: 'New fact', body: 'b', tags: [], supersedes: 'old-fact' }, undefined, 'tool', 2);
|
|
101
|
+
await store.archive('global', undefined, 'new-fact', 3);
|
|
102
|
+
assert.deepEqual(retired, ['superseded:old-fact', 'retention:new-fact']);
|
|
103
|
+
});
|
|
104
|
+
test('a retirement is reported when the cap causes it, not only when asked', async (t) => {
|
|
105
|
+
const { store, dir } = await tempStore();
|
|
106
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
107
|
+
const retired = [];
|
|
108
|
+
store.onRetire = (info) => retired.push(info.reason + ':' + info.id);
|
|
109
|
+
store.entryLimit = () => 1;
|
|
110
|
+
await store.upsert({ scope: 'global', title: 'First', body: 'a', tags: [] }, undefined, 'auto', 1);
|
|
111
|
+
await store.upsert({ scope: 'global', title: 'Second', body: 'b', tags: [] }, undefined, 'auto', 2);
|
|
112
|
+
assert.deepEqual(retired, ['evict:first']);
|
|
113
|
+
});
|
|
114
|
+
test('a broken reporter cannot undo the retirement it was told about', async (t) => {
|
|
115
|
+
const { store, dir } = await tempStore();
|
|
116
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
117
|
+
store.onRetire = () => { throw new Error('the log is gone'); };
|
|
118
|
+
await store.upsert({ scope: 'global', title: 'Doomed', body: 'x', tags: [] }, undefined, 'auto', 1);
|
|
119
|
+
assert.equal(await store.archive('global', undefined, 'doomed', 2), true);
|
|
120
|
+
assert.deepEqual((await store.listArchived('global', undefined)).map((entry) => entry.id), ['doomed']);
|
|
121
|
+
});
|
|
122
|
+
test('the cap takes the oldest entry it is allowed to take, not the permanent one', async (t) => {
|
|
123
|
+
const { store, dir } = await tempStore();
|
|
124
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
125
|
+
store.entryLimit = () => 2;
|
|
126
|
+
// The permanent entry is the OLDEST, so a cap that ignores the flag takes it first.
|
|
127
|
+
await store.upsert({ scope: 'global', title: 'Standing rule', body: 'keep', tags: [], permanent: true }, undefined, 'tool', 1);
|
|
128
|
+
await store.upsert({ scope: 'global', title: 'Middle one', body: 'x', tags: [] }, undefined, 'auto', 2);
|
|
129
|
+
await store.upsert({ scope: 'global', title: 'Newest one', body: 'y', tags: [] }, undefined, 'auto', 3);
|
|
130
|
+
const live = await store.list('global', undefined, { fresh: true });
|
|
131
|
+
assert.deepEqual(live.map((entry) => entry.id).sort(), ['newest-one', 'standing-rule']);
|
|
132
|
+
assert.deepEqual((await store.listArchived('global', undefined)).map((entry) => entry.id), ['middle-one']);
|
|
133
|
+
});
|
|
134
|
+
test('permanence survives a rewrite that does not mention it, and is read back from disk', async (t) => {
|
|
135
|
+
const { store, dir } = await tempStore();
|
|
136
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
137
|
+
await store.upsert({ scope: 'global', title: 'Standing rule', body: 'keep', tags: [], permanent: true }, undefined, 'tool', 1);
|
|
138
|
+
await store.upsert({ scope: 'global', title: 'Standing rule', body: 'keep, reworded', tags: [] }, undefined, 'tool', 2);
|
|
139
|
+
const live = await store.list('global', undefined, { fresh: true });
|
|
140
|
+
assert.equal(live.length, 1);
|
|
141
|
+
assert.equal(live[0]?.body, 'keep, reworded');
|
|
142
|
+
assert.equal(live[0]?.permanent, true, 'omitting the field means unchanged, the same rule pinned uses');
|
|
143
|
+
});
|
|
144
|
+
test('a near-duplicate rewrite that drops material does not archive its predecessor', async (t) => {
|
|
145
|
+
const { store, dir } = await tempStore();
|
|
146
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
147
|
+
store.similarityLimit = () => 0.7;
|
|
148
|
+
const older = await store.upsert({
|
|
149
|
+
scope: 'global', title: 'Push rule public repositories private',
|
|
150
|
+
body: 'public repositories push directly; private repositories ask first.',
|
|
151
|
+
tags: ['git', 'push'],
|
|
152
|
+
}, undefined, 'tool', 1);
|
|
153
|
+
// Same lesson, shorter body, one tag gone: a lossy rewrite, not a supersede.
|
|
154
|
+
const newer = await store.upsert({
|
|
155
|
+
scope: 'global', title: 'Push rule public repositories',
|
|
156
|
+
body: 'public repositories push directly; private repositories ask first, and either way say so.',
|
|
157
|
+
tags: ['git'],
|
|
158
|
+
}, undefined, 'tool', 2);
|
|
159
|
+
const live = await store.list('global', undefined, { fresh: true });
|
|
160
|
+
assert.equal(newer.action, 'created');
|
|
161
|
+
assert.ok(live.some((entry) => entry.id === older.entry.id), 'the predecessor stays retrievable');
|
|
162
|
+
assert.deepEqual((await store.listArchived('global', undefined)).map((entry) => entry.id), []);
|
|
163
|
+
});
|
|
164
|
+
test('a near-duplicate rewrite that keeps everything still supersedes', async (t) => {
|
|
165
|
+
const { store, dir } = await tempStore();
|
|
166
|
+
t.after(() => rm(dir, { recursive: true, force: true }));
|
|
167
|
+
store.similarityLimit = () => 0.7;
|
|
168
|
+
const older = await store.upsert({
|
|
169
|
+
scope: 'global', title: 'Push rule public repositories private',
|
|
170
|
+
body: 'public repositories push directly; private repositories ask first.',
|
|
171
|
+
tags: ['git', 'push'],
|
|
172
|
+
}, undefined, 'tool', 1);
|
|
173
|
+
const newer = await store.upsert({
|
|
174
|
+
scope: 'global', title: 'Push rule public repositories',
|
|
175
|
+
body: 'public repositories push directly; private repositories ask first, and say so in the PR.',
|
|
176
|
+
tags: ['git', 'push'],
|
|
177
|
+
}, undefined, 'tool', 2);
|
|
178
|
+
assert.equal(newer.action, 'created');
|
|
179
|
+
const live = await store.list('global', undefined, { fresh: true });
|
|
180
|
+
assert.ok(!live.some((entry) => entry.id === older.entry.id), 'the predecessor is retired');
|
|
181
|
+
assert.deepEqual((await store.listArchived('global', undefined)).map((entry) => entry.id), [older.entry.id]);
|
|
182
|
+
});
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backfill tests.
|
|
3
|
+
*
|
|
4
|
+
* The pass must read a real session log without a host service, keep only the
|
|
5
|
+
* prose the extractor wants, cut bounded windows, and never spend a model call
|
|
6
|
+
* unless the caller explicitly asked for it.
|
|
7
|
+
*
|
|
8
|
+
* @module dsh-cross-memory/test/backfill.test
|
|
9
|
+
*/
|
|
10
|
+
import assert from 'node:assert/strict';
|
|
11
|
+
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises';
|
|
12
|
+
import { tmpdir } from 'node:os';
|
|
13
|
+
import { join } from 'node:path';
|
|
14
|
+
import test from 'node:test';
|
|
15
|
+
import { zstdCompressSync } from 'node:zlib';
|
|
16
|
+
import { MemoriesRuntime } from '../index.js';
|
|
17
|
+
import { decodeSessionLog, findSessionLogs, parseSessionLog, planWindows, zstdAvailable } from '../backfill.js';
|
|
18
|
+
/** A session stand-in for the runtime call. */
|
|
19
|
+
function stubSession(id) {
|
|
20
|
+
return {
|
|
21
|
+
id,
|
|
22
|
+
header: { version: 0, id, createdAt: 0, isSeeded: false },
|
|
23
|
+
requestHeader: () => undefined,
|
|
24
|
+
deriveMessages: () => [],
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** One JSONL log line. */
|
|
28
|
+
function line(event) {
|
|
29
|
+
return `${JSON.stringify(event)}\n`;
|
|
30
|
+
}
|
|
31
|
+
/** A small synthetic session log with both kinds of message and one injected block. */
|
|
32
|
+
function sampleLog(sessionId = 'session-abc') {
|
|
33
|
+
return [
|
|
34
|
+
line({ type: 'session', seq: 1, id: sessionId, cwd: join('C:', 'work', 'alpha'), delegationDepth: 0 }),
|
|
35
|
+
line({ type: 'request/header', seq: 2, data: { header: { config: { provider: 'p', model: 'm', reasoningEffort: 'high' } } } }),
|
|
36
|
+
line({ type: 'user/message', seq: 3, data: { role: 'user', source: { kind: 'user' }, content: [{ type: 'text', text: 'ship it with pnpm' }] } }),
|
|
37
|
+
// A plugin-injected block is a user message too and must never be mined.
|
|
38
|
+
line({ type: 'user/message', seq: 4, data: { role: 'user', source: { kind: 'plugin:memories' }, content: [{ type: 'text', text: '<memory-context>old summary</memory-context>' }] } }),
|
|
39
|
+
line({ type: 'assistant/message', seq: 5, data: { message: { role: 'assistant', content: [{ type: 'reasoning', text: 'thinking' }, { type: 'text', text: 'use pnpm run ship' }] } } }),
|
|
40
|
+
line({ type: 'tool/call', seq: 6, data: { name: 'pwsh', arguments: '{}' } }),
|
|
41
|
+
].join('');
|
|
42
|
+
}
|
|
43
|
+
test('decodeSessionLog joins concatenated zstd frames', () => {
|
|
44
|
+
if (!zstdAvailable())
|
|
45
|
+
return;
|
|
46
|
+
const first = Buffer.from(line({ type: 'session', seq: 1, id: 'session-x' }), 'utf8');
|
|
47
|
+
const second = Buffer.from(line({ type: 'user/message', seq: 2, data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'hello' }] } }), 'utf8');
|
|
48
|
+
const buffer = Buffer.concat([zstdCompressSync(first), zstdCompressSync(second)]);
|
|
49
|
+
const text = decodeSessionLog(buffer);
|
|
50
|
+
assert.match(text, /session-x/u);
|
|
51
|
+
assert.match(text, /hello/u);
|
|
52
|
+
});
|
|
53
|
+
test('parseSessionLog keeps user/assistant prose, skips injected context and tool calls', () => {
|
|
54
|
+
const parsed = parseSessionLog(sampleLog(), join('tmp', 'sessions', 'session-abc', 'session.jsonl.zstd'), 1000);
|
|
55
|
+
assert.ok(parsed !== undefined);
|
|
56
|
+
assert.equal(parsed.sessionId, 'session-abc');
|
|
57
|
+
assert.equal(parsed.cwd, join('C:', 'work', 'alpha'));
|
|
58
|
+
assert.deepEqual(parsed.route, { provider: 'p', model: 'm', reasoningEffort: 'high' });
|
|
59
|
+
assert.equal(parsed.maxSeq, 6);
|
|
60
|
+
assert.deepEqual(parsed.messages.map((message) => message.role), ['user', 'assistant']);
|
|
61
|
+
assert.equal(parsed.messages[0]?.text, 'ship it with pnpm');
|
|
62
|
+
assert.equal(parsed.messages[1]?.text, 'use pnpm run ship');
|
|
63
|
+
assert.equal(parsed.modifiedAt, 1000);
|
|
64
|
+
});
|
|
65
|
+
test('planWindows respects both the message and the character budget', () => {
|
|
66
|
+
const messages = [
|
|
67
|
+
{ seq: 1, role: 'user', text: 'a'.repeat(50) },
|
|
68
|
+
{ seq: 2, role: 'assistant', text: 'b'.repeat(50) },
|
|
69
|
+
{ seq: 3, role: 'user', text: 'c'.repeat(50) },
|
|
70
|
+
];
|
|
71
|
+
const byMessages = planWindows(messages, 2, 10_000);
|
|
72
|
+
assert.equal(byMessages.length, 2);
|
|
73
|
+
assert.equal(byMessages[0]?.messages, 2);
|
|
74
|
+
assert.equal(byMessages[1]?.lastSeq, 3);
|
|
75
|
+
const longMessages = [
|
|
76
|
+
{ seq: 1, role: 'user', text: 'a'.repeat(120) },
|
|
77
|
+
{ seq: 2, role: 'assistant', text: 'b'.repeat(120) },
|
|
78
|
+
{ seq: 3, role: 'user', text: 'c'.repeat(120) },
|
|
79
|
+
];
|
|
80
|
+
const byChars = planWindows(longMessages, 10, 200);
|
|
81
|
+
assert.equal(byChars.length, 3, 'a line that no longer fits starts a new window');
|
|
82
|
+
for (const window of byChars) {
|
|
83
|
+
assert.equal(window.messages, 1);
|
|
84
|
+
assert.ok(window.text.length > 0);
|
|
85
|
+
}
|
|
86
|
+
});
|
|
87
|
+
test('findSessionLogs finds nested logs and ignores other files', async (t) => {
|
|
88
|
+
const home = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-backfill-logs-'));
|
|
89
|
+
t.after(() => rm(home, { recursive: true, force: true }));
|
|
90
|
+
const logDir = join(home, 'sessions', '--C-work-alpha--', 'session-abc');
|
|
91
|
+
await mkdir(logDir, { recursive: true });
|
|
92
|
+
await writeFile(join(logDir, 'session.jsonl.zstd'), 'not zstd');
|
|
93
|
+
// DSH 0.2.x writes a versioned name; the finder must see both, or a whole
|
|
94
|
+
// generation of sessions silently drops out of backfill.
|
|
95
|
+
await writeFile(join(logDir, 'session.v4.jsonl.zstd'), 'not zstd either');
|
|
96
|
+
await writeFile(join(logDir, 'other.txt'), 'ignore me');
|
|
97
|
+
const found = await findSessionLogs(join(home, 'sessions'));
|
|
98
|
+
assert.equal(found.length, 2);
|
|
99
|
+
for (const log of found)
|
|
100
|
+
assert.match(log.file, /session(\.v\d+)?\.jsonl\.zstd$/u);
|
|
101
|
+
});
|
|
102
|
+
test('backfill is a dry run unless --apply is given, and skips mined sessions', async (t) => {
|
|
103
|
+
const home = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-backfill-home-'));
|
|
104
|
+
const memories = join(home, 'memories');
|
|
105
|
+
const logDir = join(home, 'sessions', '--C-work-alpha--', 'session-abc');
|
|
106
|
+
await mkdir(logDir, { recursive: true });
|
|
107
|
+
const plain = Buffer.from(sampleLog('session-abc'), 'utf8');
|
|
108
|
+
await writeFile(join(logDir, 'session.jsonl.zstd'), Buffer.concat([zstdCompressSync(plain)]));
|
|
109
|
+
const runtime = new MemoriesRuntime(stubContext(), { memoriesDir: memories, dshHome: home, autoExtract: false });
|
|
110
|
+
t.after(async () => {
|
|
111
|
+
runtime.dispose();
|
|
112
|
+
await rm(home, { recursive: true, force: true });
|
|
113
|
+
});
|
|
114
|
+
const report = await runtime.backfill(stubSession('session-live'), { apply: false, days: 3650, limit: 3 });
|
|
115
|
+
assert.match(report, /Backfill plan/u);
|
|
116
|
+
assert.match(report, /Dry run/u);
|
|
117
|
+
assert.match(report, /1 unmined/u);
|
|
118
|
+
// A watermark past the log's last seq means the session was already mined.
|
|
119
|
+
runtime.state.putSession('session-abc', { lastSeq: 99, at: Date.now(), activityAt: Date.now() });
|
|
120
|
+
const skipped = await runtime.backfill(stubSession('session-live'), { apply: false, days: 3650, limit: 3 });
|
|
121
|
+
assert.match(skipped, /0 unmined/u);
|
|
122
|
+
assert.match(skipped, /Skipped 1 already mined/u);
|
|
123
|
+
});
|
|
124
|
+
test('apply without an llm route reports that nothing was mined', async (t) => {
|
|
125
|
+
const home = await mkdtemp(join(tmpdir(), 'dsh-cross-memory-backfill-nollm-'));
|
|
126
|
+
const memories = join(home, 'memories');
|
|
127
|
+
const logDir = join(home, 'sessions', 'x', 'session-abc');
|
|
128
|
+
await mkdir(logDir, { recursive: true });
|
|
129
|
+
await writeFile(join(logDir, 'session.jsonl.zstd'), zstdCompressSync(Buffer.from(sampleLog('session-abc'), 'utf8')));
|
|
130
|
+
const runtime = new MemoriesRuntime(stubContext(), { memoriesDir: memories, dshHome: home, autoExtract: false });
|
|
131
|
+
t.after(async () => {
|
|
132
|
+
runtime.dispose();
|
|
133
|
+
await rm(home, { recursive: true, force: true });
|
|
134
|
+
});
|
|
135
|
+
const report = await runtime.backfill(stubSession('session-live'), { apply: true, days: 3650, limit: 1 });
|
|
136
|
+
assert.match(report, /No llm route/u);
|
|
137
|
+
});
|
|
138
|
+
/** A context stand-in exposing only what the runtime touches. */
|
|
139
|
+
function stubContext() {
|
|
140
|
+
return {
|
|
141
|
+
get: () => undefined,
|
|
142
|
+
logger: { info: () => undefined, warn: () => undefined, debug: () => undefined },
|
|
143
|
+
};
|
|
144
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tests for the citation check.
|
|
3
|
+
*
|
|
4
|
+
* The rule under test is what makes "this memory points at a file that no longer
|
|
5
|
+
* exists" visible without turning every cross-checkout reference into noise.
|
|
6
|
+
*
|
|
7
|
+
* @module dsh-cross-memory/test/citations.test
|
|
8
|
+
*/
|
|
9
|
+
import assert from 'node:assert/strict';
|
|
10
|
+
import test from 'node:test';
|
|
11
|
+
import { citationRoots, citationWarning, extractCitations, ignoredUnder, isIgnoredPath, missingCitations, parseGitignore } from '../citations.js';
|
|
12
|
+
/** A probe backed by a set of paths, so the rule is tested without a filesystem. */
|
|
13
|
+
function probe(paths) {
|
|
14
|
+
const normalized = new Set(paths.map((path) => path.replace(/\\/gu, '/').toLowerCase()));
|
|
15
|
+
return (path) => normalized.has(path.replace(/\\/gu, '/').toLowerCase());
|
|
16
|
+
}
|
|
17
|
+
test('extractCitations keeps real relative paths and drops prose', () => {
|
|
18
|
+
const body = 'Report lives at output/market_report.json, script at ./scripts/verify_all.py, and/or in tools/check.py.';
|
|
19
|
+
assert.deepEqual(extractCitations(body), ['output/market_report.json', 'scripts/verify_all.py', 'tools/check.py']);
|
|
20
|
+
assert.deepEqual(extractCitations('config.ts/index.ts/consolidate.ts'), [], 'a slash-joined list is not a path');
|
|
21
|
+
assert.deepEqual(extractCitations('see https://example.com/a/b.js'), []);
|
|
22
|
+
assert.deepEqual(extractCitations('a single index.js is not checkable'), []);
|
|
23
|
+
assert.deepEqual(extractCitations('fonts live in app/.tools and are installed'), [], 'a hidden directory is not a file');
|
|
24
|
+
});
|
|
25
|
+
test('a citation is reported only when its directory exists but the file does not', () => {
|
|
26
|
+
const roots = ['C:\\repo'];
|
|
27
|
+
const exists = probe(['C:/repo/output', 'C:/repo/output/other.json']);
|
|
28
|
+
// The directory is there, the cited file is not: that is evidence of deletion.
|
|
29
|
+
assert.deepEqual(missingCitations('the report is output/market_report.json', roots, exists), ['output/market_report.json']);
|
|
30
|
+
// The whole directory is unknown: this checkout may simply not be the one the
|
|
31
|
+
// memory was written in, so the check stays silent.
|
|
32
|
+
assert.deepEqual(missingCitations('the report is elsewhere/market_report.json', roots, exists), []);
|
|
33
|
+
});
|
|
34
|
+
test('a citation that resolves is never reported', () => {
|
|
35
|
+
const roots = ['C:\\repo'];
|
|
36
|
+
const exists = probe(['C:/repo/scripts/verify_all.py']);
|
|
37
|
+
assert.deepEqual(missingCitations('run scripts/verify_all.py', roots, exists), []);
|
|
38
|
+
});
|
|
39
|
+
test('nothing is checked without a root', () => {
|
|
40
|
+
assert.deepEqual(missingCitations('the report is output/x.json', [], probe([])), []);
|
|
41
|
+
});
|
|
42
|
+
test('citationRoots puts the project first and de-duplicates', () => {
|
|
43
|
+
assert.deepEqual(citationRoots('C:\\repo', ['C:\\repo', 'C:\\home']), ['C:\\repo', 'C:\\home']);
|
|
44
|
+
assert.deepEqual(citationRoots(undefined, ['C:\\home']), ['C:\\home']);
|
|
45
|
+
});
|
|
46
|
+
test('the warning names at most two paths and counts the rest', () => {
|
|
47
|
+
assert.equal(citationWarning([]), '');
|
|
48
|
+
assert.match(citationWarning(['a/b.py']), /a\/b\.py/u);
|
|
49
|
+
assert.match(citationWarning(['a/b.py', 'c/d.py', 'e/f.py']), /等 3 处/u);
|
|
50
|
+
});
|
|
51
|
+
test('a repository-ignored path is generated, not stale', () => {
|
|
52
|
+
const rules = parseGitignore([
|
|
53
|
+
'# comment',
|
|
54
|
+
'',
|
|
55
|
+
'state/',
|
|
56
|
+
'*.log',
|
|
57
|
+
'/build/',
|
|
58
|
+
'cache/**/*.db',
|
|
59
|
+
'!cache/keep.db',
|
|
60
|
+
].join('\n'));
|
|
61
|
+
// An unanchored directory rule matches that directory at any depth.
|
|
62
|
+
assert.equal(isIgnoredPath('state/run.json', rules), true);
|
|
63
|
+
assert.equal(isIgnoredPath('nested/state/run.json', rules), true);
|
|
64
|
+
// A file glob matches the basename at any depth.
|
|
65
|
+
assert.equal(isIgnoredPath('logs/sniper.log', rules), true);
|
|
66
|
+
assert.equal(isIgnoredPath('sniper.log', rules), true);
|
|
67
|
+
// An anchored rule only matches from the root.
|
|
68
|
+
assert.equal(isIgnoredPath('build/out.js', rules), true);
|
|
69
|
+
assert.equal(isIgnoredPath('packages/x/build/out.js', rules), false);
|
|
70
|
+
// `**` spans directories, and the last matching rule wins.
|
|
71
|
+
assert.equal(isIgnoredPath('cache/a/recognition.db', rules), true);
|
|
72
|
+
assert.equal(isIgnoredPath('cache/keep.db', rules), false, 'the negation re-includes exactly the path it names');
|
|
73
|
+
assert.equal(isIgnoredPath('cache/a/keep.db', rules), true, 'and nothing else');
|
|
74
|
+
// Anything the rules do not name is still checkable.
|
|
75
|
+
assert.equal(isIgnoredPath('tools/verify_all.py', rules), false);
|
|
76
|
+
assert.equal(isIgnoredPath('state/run.json', []), false, 'no rules mean no suppression');
|
|
77
|
+
});
|
|
78
|
+
test('an ignored citation is not reported as missing', () => {
|
|
79
|
+
const roots = ['C:\\repo'];
|
|
80
|
+
// The parent directory exists and the file does not — the case that used to
|
|
81
|
+
// flag every runtime artifact a repository generates.
|
|
82
|
+
const exists = probe(['C:/repo/state', 'C:/repo/scripts', 'C:/repo/scripts/verify_all.py']);
|
|
83
|
+
const body = 'state lives in state/run.json; run scripts/verify_all.py';
|
|
84
|
+
assert.deepEqual(missingCitations(body, roots, exists), ['state/run.json']);
|
|
85
|
+
assert.deepEqual(missingCitations(body, roots, exists, { isIgnored: (path) => path.startsWith('state/') }), []);
|
|
86
|
+
});
|
|
87
|
+
test('ignoredUnder reads a root’s own .gitignore', () => {
|
|
88
|
+
const isIgnored = ignoredUnder(process.cwd());
|
|
89
|
+
assert.equal(typeof isIgnored('src/index.ts'), 'boolean');
|
|
90
|
+
assert.equal(ignoredUnder('C:\\definitely-not-a-repo-xyz')('state/run.json'), false);
|
|
91
|
+
});
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wiring guard for the browser half's two surfaces.
|
|
3
|
+
*
|
|
4
|
+
* `client/index.js` is a plain CJS script that the bundle wrapper turns into a
|
|
5
|
+
* DSH client bundle, so there is no module to import: the parts are
|
|
6
|
+
* concatenated here exactly the way `scripts/build-client.mjs` concatenates
|
|
7
|
+
* them, and the factory is called for real. What this pins is the registration
|
|
8
|
+
* contract, because nothing else in the suite covers it:
|
|
9
|
+
*
|
|
10
|
+
* - the **Memories page** (`settings.section`, id `memories`, order 25) stays
|
|
11
|
+
* — it is a feature surface, not a configuration menu;
|
|
12
|
+
* - the **tunables card** is registered a second time on the Plugins page as
|
|
13
|
+
* `plugins.bundle.config`, keyed by the **package name** (`dsh-cross-memory`).
|
|
14
|
+
* That key is what the Plugins page looks up (`ledger.bundles`) when it
|
|
15
|
+
* decides whether to render a bundle's configuration section at all, so a
|
|
16
|
+
* wrong key silently means "no card in the GUI";
|
|
17
|
+
* - both registrations hand the same shared form (`scope` + `useSnapshot`) to
|
|
18
|
+
* their component, so the two editors cannot disagree;
|
|
19
|
+
* - `PACKAGE` is the package name, and `scripts/build-client.mjs` uses that
|
|
20
|
+
* same value as the bundle id.
|
|
21
|
+
*
|
|
22
|
+
* @module dsh-cross-memory/test/client-wiring.test
|
|
23
|
+
*/
|
|
24
|
+
import assert from 'node:assert/strict';
|
|
25
|
+
import { readFile, readdir } from 'node:fs/promises';
|
|
26
|
+
import test from 'node:test';
|
|
27
|
+
import { REMOTE_INVOCATION_DATA } from '../remote.js';
|
|
28
|
+
/** Where the hand-written half lives. */
|
|
29
|
+
const PARTS = new URL('../../client/parts/', import.meta.url);
|
|
30
|
+
const INDEX = new URL('../../client/index.js', import.meta.url);
|
|
31
|
+
const MANIFEST = new URL('../../package.json', import.meta.url);
|
|
32
|
+
/**
|
|
33
|
+
* Concatenate the browser half the way the bundle script does.
|
|
34
|
+
* @returns the factory, and the package name it was built with.
|
|
35
|
+
*/
|
|
36
|
+
async function loadFactory() {
|
|
37
|
+
const names = (await readdir(PARTS)).filter((name) => name.endsWith('.js')).sort();
|
|
38
|
+
const parts = await Promise.all(names.map(async (name) => {
|
|
39
|
+
const body = await readFile(new URL(name, PARTS), 'utf8');
|
|
40
|
+
return `// ---- client/${name} ----\n${body}`;
|
|
41
|
+
}));
|
|
42
|
+
const index = await readFile(INDEX, 'utf8');
|
|
43
|
+
const { name: packageName } = JSON.parse(await readFile(MANIFEST, 'utf8'));
|
|
44
|
+
const source = [
|
|
45
|
+
`const PACKAGE = ${JSON.stringify(packageName)};`,
|
|
46
|
+
`const REMOTE_INVOCATION_DATA = ${JSON.stringify(REMOTE_INVOCATION_DATA)};`,
|
|
47
|
+
...parts,
|
|
48
|
+
index,
|
|
49
|
+
'return createPlugin',
|
|
50
|
+
].join('\n');
|
|
51
|
+
const createPlugin = new Function(source)();
|
|
52
|
+
return { createPlugin, packageName };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Mount the browser half against a context that behaves like the shell's.
|
|
56
|
+
* @returns every registration, the slots injected into, and the shared form.
|
|
57
|
+
*/
|
|
58
|
+
async function mount() {
|
|
59
|
+
const { createPlugin, packageName } = await loadFactory();
|
|
60
|
+
const registrations = [];
|
|
61
|
+
const injected = [];
|
|
62
|
+
const writes = [];
|
|
63
|
+
const scope = {
|
|
64
|
+
getSnapshot: () => ({ status: 'ready', value: {}, user: {}, revision: 3, writable: true }),
|
|
65
|
+
subscribe: () => () => { },
|
|
66
|
+
set: (field, value) => {
|
|
67
|
+
writes.push({ op: 'set', path: [field], value });
|
|
68
|
+
return Promise.resolve();
|
|
69
|
+
},
|
|
70
|
+
unset: (field) => {
|
|
71
|
+
writes.push({ op: 'unset', path: [field] });
|
|
72
|
+
return Promise.resolve();
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
// Nothing renders here, so the hook runtime stays empty: the factories only
|
|
76
|
+
// close over React, and the card is exercised by `settings-card.test.ts`.
|
|
77
|
+
const React = { createElement: () => ({}), useState: () => [undefined, () => { }], useEffect: () => { } };
|
|
78
|
+
const plugin = createPlugin((spec) => {
|
|
79
|
+
if (spec === 'react')
|
|
80
|
+
return React;
|
|
81
|
+
throw new Error(`unexpected require(${spec})`);
|
|
82
|
+
});
|
|
83
|
+
const ctx = {
|
|
84
|
+
configForms: { get: () => scope },
|
|
85
|
+
// `mountMemoriesRemote` reads the gateway through `get`; there is none here,
|
|
86
|
+
// which is the documented degradation (the card still renders).
|
|
87
|
+
get: (key) => (key === 'locale' ? { getLocale: () => ({ active: 'zh' }) } : undefined),
|
|
88
|
+
logger: { warn: () => { } },
|
|
89
|
+
slots: {
|
|
90
|
+
inject(name, callback) {
|
|
91
|
+
injected.push(name);
|
|
92
|
+
callback();
|
|
93
|
+
return () => { };
|
|
94
|
+
},
|
|
95
|
+
register(options, component) {
|
|
96
|
+
registrations.push({ name: String(options.name), options, component });
|
|
97
|
+
return { dispose: () => { } };
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
await plugin.apply(ctx);
|
|
102
|
+
return { registrations, injected, inject: plugin.inject, scope, packageName };
|
|
103
|
+
}
|
|
104
|
+
test('the browser half registers the Memories page and the Plugins-page config card', async () => {
|
|
105
|
+
const { registrations, injected, inject, scope, packageName } = await mount();
|
|
106
|
+
// The card reads `ctx.configForms`, so the plugin has to declare it.
|
|
107
|
+
assert.deepEqual(inject, ['slots', 'configForms']);
|
|
108
|
+
const pages = registrations.filter((entry) => entry.name === 'settings.section');
|
|
109
|
+
assert.equal(pages.length, 1, 'the Memories page stays registered, exactly once');
|
|
110
|
+
const page = pages[0];
|
|
111
|
+
assert.ok(page !== undefined);
|
|
112
|
+
assert.equal(page.options.id, 'memories');
|
|
113
|
+
assert.equal(page.options.order, 25);
|
|
114
|
+
const pageFace = page.options.inject();
|
|
115
|
+
assert.deepEqual(Object.keys(pageFace).sort(), ['api', 'copy', 'scope', 'useSnapshot']);
|
|
116
|
+
assert.equal(pageFace.scope, scope);
|
|
117
|
+
assert.equal(typeof page.component, 'function');
|
|
118
|
+
const cards = registrations.filter((entry) => entry.name === 'plugins.bundle.config');
|
|
119
|
+
assert.equal(cards.length, 1, 'the tunables card is registered once on the Plugins page');
|
|
120
|
+
const card = cards[0];
|
|
121
|
+
assert.ok(card !== undefined);
|
|
122
|
+
assert.equal(card.options.key, packageName, 'the Plugins page keys this slot by the PACKAGE NAME');
|
|
123
|
+
assert.equal(packageName, 'dsh-cross-memory');
|
|
124
|
+
// The slot passes no `form`; the registration's inject face must supply the
|
|
125
|
+
// same shared form the page's own tab supplies.
|
|
126
|
+
const face = card.options.inject();
|
|
127
|
+
assert.equal(face.scope, scope, 'the card edits the entry form, not a private copy');
|
|
128
|
+
assert.equal(typeof face.useSnapshot, 'function');
|
|
129
|
+
assert.equal(face.lang, 'zh');
|
|
130
|
+
assert.equal(face.intro, false);
|
|
131
|
+
assert.equal(typeof face.title, 'string');
|
|
132
|
+
assert.deepEqual(injected, ['settings.section', 'plugins.bundle.config']);
|
|
133
|
+
assert.equal(typeof card.component, 'function');
|
|
134
|
+
});
|