dsh-message-rewind 1.2.2 → 1.2.4

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/index.test.js DELETED
@@ -1,227 +0,0 @@
1
- /**
2
- * Self-check for the Host half's disk and RPC surface.
3
- *
4
- * `sessionDirectory` is the only place that maps a session id onto disk, so it
5
- * must never return a path outside the sessions root — a bad id previously
6
- * resolved to `$DSH_HOME` or a parent directory before `purge` recursively
7
- * removed it. The route check drives the registered handler with a stub context
8
- * so admission, envelope validation, error codes, and the purge guard stay
9
- * covered without a running Harness.
10
- */
11
- import assert from 'node:assert/strict';
12
- import { promises as fsp } from 'node:fs';
13
- import { tmpdir } from 'node:os';
14
- import { join } from 'node:path';
15
- import { apply, sessionDirectory, validSessionId } from './index.js';
16
-
17
- let passed = 0;
18
- const check = async (label, fn) => {
19
- try {
20
- await fn();
21
- passed += 1;
22
- } catch (error) {
23
- throw new Error(`${label}: ${error.message}`);
24
- }
25
- };
26
-
27
- const root = await fsp.mkdtemp(join(tmpdir(), 'dmr-sessions-'));
28
- const realRoot = await fsp.realpath(root);
29
- const nested = 'session-11111111-2222-3333-4444-555555555555';
30
- const flat = 'session-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';
31
-
32
- await check('nested project directory is found', async () => {
33
- await fsp.mkdir(join(realRoot, '--workspace--', nested), { recursive: true });
34
- assert.equal(await sessionDirectory(realRoot, nested), join(realRoot, '--workspace--', nested));
35
- });
36
-
37
- await check('root-level session directory is found', async () => {
38
- await fsp.mkdir(join(realRoot, flat), { recursive: true });
39
- assert.equal(await sessionDirectory(realRoot, flat), join(realRoot, flat));
40
- });
41
-
42
- await check('path traversal ids are rejected', async () => {
43
- for (const id of ['..', '../..', '../../..', 'session-..', 'session-../..', 'a/b', 'C:\\Windows', '', 'session-']) {
44
- assert.equal(await sessionDirectory(realRoot, id), undefined, `accepted ${JSON.stringify(id)}`);
45
- }
46
- });
47
-
48
- await check('id validation matches the harness format', async () => {
49
- assert.equal(validSessionId(nested), true);
50
- assert.equal(validSessionId('session-123'), true);
51
- assert.equal(validSessionId('..'), false);
52
- assert.equal(validSessionId('session-..'), false);
53
- assert.equal(validSessionId('session-1/../..'), false);
54
- assert.equal(validSessionId(42), false);
55
- });
56
-
57
- await check('a junction cannot escape the sessions root', async () => {
58
- const outsideParent = await fsp.mkdtemp(join(tmpdir(), 'dmr-outside-'));
59
- const linked = 'session-99999999-8888-7777-6666-555555555555';
60
- const outside = join(outsideParent, linked);
61
- const linkedPath = join(realRoot, '--workspace--', linked);
62
- await fsp.mkdir(outside, { recursive: true });
63
- try {
64
- await fsp.symlink(outside, linkedPath, process.platform === 'win32' ? 'junction' : 'dir');
65
- } catch (error) {
66
- await fsp.rm(outsideParent, { recursive: true, force: true });
67
- if (error?.code === 'EPERM' || error?.code === 'EACCES') return;
68
- throw error;
69
- }
70
- try {
71
- assert.equal(await sessionDirectory(realRoot, linked), undefined);
72
- } finally {
73
- // A junction is removed like a file, but only when `recursive` is set on
74
- // Windows; a bare rm leaves the reparse point behind and the root cleanup
75
- // below then fails with ENOTEMPTY.
76
- await fsp.rm(linkedPath, { recursive: true, force: true }).catch(() => {});
77
- await fsp.rm(outsideParent, { recursive: true, force: true });
78
- }
79
- });
80
-
81
- await fsp.rm(realRoot, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 });
82
-
83
- // --- route surface ---------------------------------------------------------
84
- const routeCalls = [];
85
- const registrations = [];
86
- const makeContext = (overrides = {}) => ({
87
- effect: (factory) => factory(),
88
- get: (name) => (name === 'workspaceRegistry'
89
- ? { list: () => [{ id: 'ws-1', sessionIds: ['session-source'] }] }
90
- : name === 'sessions'
91
- ? { get: () => undefined }
92
- : undefined),
93
- webServer: {
94
- register: (route) => { registrations.push(route); return () => {}; },
95
- },
96
- connection: { admit: () => ({ peer: {} }) },
97
- workspaceController: {
98
- archiveSession: async ({ sessionId }) => { routeCalls.push(['archive', sessionId]); },
99
- },
100
- workspaceChanges: { summary: () => undefined, diff: async () => undefined },
101
- sessionQuery: {
102
- readSession: async () => ({
103
- session: { id: 'session-source', cwd: 'D:/tmp', agentPreset: 'preset-a' },
104
- events: [
105
- { seq: 0, type: 'turn/start', data: { turn: 1 } },
106
- { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'hi' }] } },
107
- { seq: 2, type: 'turn/end', data: { turn: 1, reason: { kind: 'completed' } } },
108
- ],
109
- }),
110
- },
111
- sessionController: {
112
- fork: async () => ({ sessionId: 'session-child' }),
113
- create: async (request) => { routeCalls.push(['create', request]); return { sessionId: 'session-child' }; },
114
- prompt: async () => ({ accepted: true }),
115
- },
116
- ...overrides,
117
- });
118
-
119
- const rpc = async (handler, endpoint, payload) => {
120
- const body = JSON.stringify({ type: 'client-request', rpcId: 'rpc-1', method: endpoint, payload });
121
- let status;
122
- let bodyText;
123
- const request = {
124
- method: 'POST',
125
- url: `/message-rewind/${endpoint}`,
126
- async *[Symbol.asyncIterator]() { yield Buffer.from(body); },
127
- };
128
- await handler(request, { writeHead: (code) => { status = code; }, end: (value) => { bodyText = value; } });
129
- return { status, envelope: bodyText === undefined ? undefined : JSON.parse(bodyText) };
130
- };
131
-
132
- await check('the route is registered as one prefix', async () => {
133
- apply(makeContext());
134
- assert.equal(registrations.length, 1);
135
- assert.equal(registrations[0].kind, 'prefix');
136
- assert.equal(registrations[0].path, '/message-rewind');
137
- });
138
-
139
- await check('an unauthenticated request is rejected before the body is read', async () => {
140
- apply(makeContext({ connection: { admit: () => ({ rejection: 401 }) } }));
141
- const handler = registrations.at(-1).handler;
142
- let status;
143
- await handler({ method: 'POST', url: '/message-rewind/inspect', headers: {} }, { writeHead: (code) => { status = code; }, end: () => {} });
144
- assert.equal(status, 401);
145
- });
146
-
147
- await check('a traversal id never reaches the filesystem', async () => {
148
- apply(makeContext());
149
- const handler = registrations.at(-1).handler;
150
- for (const bad of ['..', '../../..', 'session-..', 'session-1/../..']) {
151
- const { envelope } = await rpc(handler, 'purge', { sessionId: bad });
152
- assert.equal(envelope.result.ok, false, `purge accepted ${JSON.stringify(bad)}`);
153
- assert.equal(envelope.result.error.details.rewindCode, 'invalid-session');
154
- }
155
- assert.equal(routeCalls.some((call) => call[0] === 'archive'), false, 'purge archived before validating');
156
- });
157
-
158
- await check('a bad envelope is refused with a code', async () => {
159
- const handler = registrations.at(-1).handler;
160
- const body = JSON.stringify({ type: 'wrong', rpcId: 'rpc-2', method: 'inspect', payload: {} });
161
- let bodyText;
162
- await handler({
163
- method: 'POST',
164
- url: '/message-rewind/inspect',
165
- async *[Symbol.asyncIterator]() { yield Buffer.from(body); },
166
- }, { writeHead: () => {}, end: (value) => { bodyText = value; } });
167
- assert.equal(JSON.parse(bodyText).result.error.details.rewindCode, 'bad-request');
168
- });
169
-
170
- await check('execute binds the replacement to the source workspace', async () => {
171
- const handler = registrations.at(-1).handler;
172
- const { envelope } = await rpc(handler, 'execute', { sessionId: 'session-source', seq: 1, action: 'edit', text: 'edited', rewindFiles: false });
173
- assert.equal(envelope.result.ok, true);
174
- assert.deepEqual(envelope.result.value, { sessionId: 'session-child', restored: 0, sourceSessionId: 'session-source' });
175
- assert.deepEqual(routeCalls.filter((call) => call[0] === 'create').at(-1)[1], { workspaceId: 'ws-1', agentPreset: 'preset-a' });
176
- });
177
-
178
- await check('an open turn is refused with a localizable code', async () => {
179
- const context = makeContext({
180
- sessionQuery: {
181
- readSession: async () => ({
182
- session: { id: 'session-source', cwd: 'D:/tmp' },
183
- events: [
184
- { seq: 0, type: 'turn/start', data: { turn: 1 } },
185
- { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'hi' }] } },
186
- ],
187
- }),
188
- },
189
- });
190
- apply(context);
191
- const { envelope } = await rpc(registrations.at(-1).handler, 'execute', { sessionId: 'session-source', seq: 1, action: 'delete', rewindFiles: false });
192
- assert.equal(envelope.result.error.details.rewindCode, 'open-turn');
193
- });
194
-
195
- await check('a deleted session is reported with a localizable code', async () => {
196
- const context = makeContext({
197
- sessionQuery: {
198
- readSession: async () => {
199
- throw Object.assign(new Error('session "session-source" not found'), { code: 'SESSION_QUERY_SESSION_NOT_FOUND' });
200
- },
201
- },
202
- });
203
- apply(context);
204
- const { envelope } = await rpc(registrations.at(-1).handler, 'inspect', { sessionId: 'session-source', seq: 1 });
205
- assert.equal(envelope.result.ok, false);
206
- assert.equal(envelope.result.error.details.rewindCode, 'missing-session');
207
- });
208
-
209
- await check('purge reports a failed archive instead of deleting', async () => {
210
- const context = makeContext({
211
- workspaceController: { archiveSession: async () => { throw new Error('workspace/session-active'); } },
212
- });
213
- apply(context);
214
- const { envelope } = await rpc(registrations.at(-1).handler, 'purge', { sessionId: 'session-11111111-2222-3333-4444-555555555555' });
215
- assert.equal(envelope.result.ok, true);
216
- assert.equal(envelope.result.value.removed, false);
217
- assert.match(envelope.result.value.message, /归档失败/);
218
- });
219
-
220
- await check('purge reports a missing log directory honestly', async () => {
221
- apply(makeContext());
222
- const { envelope } = await rpc(registrations.at(-1).handler, 'purge', { sessionId: 'session-11111111-2222-3333-4444-555555555555' });
223
- assert.equal(envelope.result.value.removed, false);
224
- assert.equal(envelope.result.value.archivedOnly, false);
225
- });
226
-
227
- console.log(`index self-check passed (${passed} scenarios)`);
package/manifest.test.js DELETED
@@ -1,25 +0,0 @@
1
- /**
2
- * Manifest self-check: DSH reads these fields before it imports the plugin, so
3
- * a mismatch fails the whole bundle instead of one feature. `engines.dsh` is a
4
- * hard gate in app boot (`evaluatePluginCompatibility`); the client bundle id
5
- * must equal the package name or that entry stays pending and web boot fails.
6
- */
7
- import assert from 'node:assert/strict';
8
- import { readFile } from 'node:fs/promises';
9
-
10
- const pkg = JSON.parse(await readFile(new URL('./package.json', import.meta.url), 'utf8'));
11
-
12
- assert.equal(pkg.name, 'dsh-message-rewind');
13
- assert.match(pkg.version, /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/);
14
- // Bounded to the tested DSH release line: 0.2.2-rc.1 through 0.2.x, never 0.3.
15
- assert.match(pkg.engines?.dsh ?? '', /^>=0\.2\.2-rc\.\d+ <0\.3\.0-0$/);
16
- assert.equal(pkg.engines?.node, '>=20');
17
- assert.equal(pkg.dsh?.manifestVersion, 1);
18
- assert.equal(pkg.dsh?.bundle?.patch, './cordis.patch.yml');
19
- assert.equal(pkg.dsh?.client?.platform, 'web');
20
- assert.equal(pkg.exports?.['./client'], './client.js');
21
-
22
- const client = await readFile(new URL('./client.js', import.meta.url), 'utf8');
23
- assert.match(client, new RegExp(`id: '${pkg.name}'`), 'the client bundle id must be the package name');
24
-
25
- console.log('manifest self-check passed');
package/rewind.test.js DELETED
@@ -1,89 +0,0 @@
1
- import assert from 'node:assert/strict';
2
- import { prepareCut, inversePatch, textSide, terminated } from './rewind.js';
3
-
4
- // Real session order: a turn opens, then the user message lands inside it.
5
- const base = [
6
- { seq: 0, type: 'turn/start' },
7
- { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'first' }] } },
8
- { seq: 2, type: 'turn/end' },
9
- { seq: 3, type: 'turn/start' },
10
- { seq: 4, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'second' }] } },
11
- ];
12
- const events = [...base, { seq: 5, type: 'workspace/changes' }];
13
- assert.deepEqual(prepareCut(events, 1), { content: [{ type: 'text', text: 'first' }], boundary: undefined, hasOpenTurn: true, records: [5] });
14
- assert.deepEqual(prepareCut(events, 4), { content: [{ type: 'text', text: 'second' }], boundary: 2, hasOpenTurn: true, records: [5] });
15
- const closed = [...base, { seq: 5, type: 'turn/end' }, { seq: 6, type: 'workspace/changes' }];
16
- assert.equal(prepareCut(closed, 4).hasOpenTurn, false);
17
- assert.deepEqual(prepareCut(closed, 4).records, [6]);
18
-
19
- // A prompt queued during the previous turn sits between that turn and this one;
20
- // the cut must not hand the branch a still-pending queue item.
21
- const queued = [
22
- { seq: 0, type: 'turn/start' },
23
- { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'first' }] } },
24
- { seq: 2, type: 'turn/end' },
25
- { seq: 3, type: 'agent/inbox/spliced', data: { target: 'next-turn', start: 0, inserted: [{ content: [{ type: 'text', text: 'queued' }] }] } },
26
- { seq: 4, type: 'turn/start' },
27
- { seq: 5, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'queued' }] } },
28
- { seq: 6, type: 'turn/end' },
29
- ];
30
- assert.equal(prepareCut(queued, 5).boundary, 2);
31
- const doubleQueued = [
32
- { seq: 0, type: 'turn/start' },
33
- { seq: 1, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'first' }] } },
34
- { seq: 2, type: 'turn/end' },
35
- { seq: 3, type: 'agent/inbox/spliced', data: { target: 'next-turn', start: 0, inserted: [{}] } },
36
- { seq: 4, type: 'agent/inbox/spliced', data: { target: 'next-turn', start: 0, inserted: [{}] } },
37
- { seq: 5, type: 'turn/start' },
38
- { seq: 6, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'x' }] } },
39
- ];
40
- assert.equal(prepareCut(doubleQueued, 6).boundary, 2);
41
- assert.throws(() => prepareCut(events, 2));
42
- assert.throws(() => prepareCut(events, 0));
43
- assert.throws(() => prepareCut(events, 99));
44
-
45
- // A compacted session starts above seq 0; the cut must follow `seq`, not the array index.
46
- const offset = [
47
- { seq: 40, type: 'turn/start' },
48
- { seq: 41, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'later' }] } },
49
- { seq: 42, type: 'turn/end' },
50
- { seq: 43, type: 'turn/start' },
51
- { seq: 44, type: 'user/message', data: { source: { kind: 'user' }, content: [{ type: 'text', text: 'last' }] } },
52
- { seq: 45, type: 'turn/end' },
53
- ];
54
- assert.deepEqual(prepareCut(offset, 44), { content: [{ type: 'text', text: 'last' }], boundary: 42, hasOpenTurn: false, records: [] });
55
- assert.deepEqual(prepareCut(offset, 41), { content: [{ type: 'text', text: 'later' }], boundary: undefined, hasOpenTurn: false, records: [] });
56
-
57
- const current = 'zero\none\ntwo\nthree\nfour\n';
58
- const diff = { before: true, after: true, hunks: [{ oldStart: 2, oldLines: 2, newStart: 2, newLines: 3, lines: [' one\n', '-two\n', '+TWO\n', '+two again\n', ' three\n'] }] };
59
- assert.equal(textSide(true, diff.hunks, true), 'one\nTWO\ntwo again\nthree\n');
60
- assert.equal(textSide(true, diff.hunks, false), 'one\ntwo\nthree\n');
61
- assert.equal(inversePatch('zero\none\nTWO\ntwo again\nthree\nfour\n', diff.hunks), current);
62
- const created = { before: false, after: true, hunks: [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: 1, lines: ['+new\n'] }] };
63
- assert.equal(textSide(created.before, created.hunks, false), null);
64
- assert.equal(inversePatch('new\n', created.hunks), '');
65
- assert.throws(() => inversePatch('zero\none\nTWO\nthree\nfour\n', diff.hunks));
66
-
67
- // The recorder diffs terminated text, so a file stored without a final newline
68
- // must still invert instead of reading as "the file version changed".
69
- assert.equal(terminated('a'), 'a\n');
70
- assert.equal(terminated('a\n'), 'a\n');
71
- assert.equal(terminated(''), '');
72
- assert.equal(inversePatch('abc', [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: 1, lines: ['+abc'] }]), '');
73
- const unterminated = [{ oldStart: 1, oldLines: 1, newStart: 1, newLines: 2, lines: [' x\n', '+y'] }];
74
- assert.equal(inversePatch('x\ny', unterminated), 'x\n');
75
- // The recorder's jsdiff output strips the newline from every hunk line, and an
76
- // empty body is one blank line rather than no line; both shapes must invert.
77
- const stripped = [{ oldStart: 1, oldLines: 4, newStart: 1, newLines: 4, lines: [' a', ' ', '-b', '+B', ' c'] }];
78
- assert.equal(textSide(true, stripped, true), 'a\n\nB\nc\n');
79
- assert.equal(textSide(true, stripped, false), 'a\n\nb\nc\n');
80
- assert.equal(inversePatch('a\n\nB\nc\n', stripped), 'a\n\nb\nc\n');
81
- const insertedBlank = [{ oldStart: 1, oldLines: 4, newStart: 1, newLines: 5, lines: [' a', ' ', ' b', '+', ' c'] }];
82
- assert.equal(textSide(true, insertedBlank, true), 'a\n\nb\n\nc\n');
83
- assert.equal(inversePatch('a\n\nb\n\nc\n', insertedBlank), 'a\n\nb\nc\n');
84
- const createdBlank = [{ oldStart: 0, oldLines: 0, newStart: 1, newLines: 3, lines: ['+a', '+', '+b'] }];
85
- assert.equal(textSide(true, createdBlank, true), 'a\n\nb\n');
86
- assert.equal(textSide(false, createdBlank, false), null);
87
-
88
- console.log('rewind self-check passed');
89
-