This repository was archived by the owner on Jul 24, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.test.ts
More file actions
393 lines (348 loc) · 14.5 KB
/
Copy pathlib.test.ts
File metadata and controls
393 lines (348 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// tests/unit/lib.test.ts — exercise createSt's wiring.
//
// The deep edge cases are covered by tests/unit/<command>.test.ts. This
// file just verifies the factory routes calls correctly, threads
// `{ root, identity, configRoot }` everywhere, and surfaces typed
// errors as expected.
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { createSt, type St } from '../../src/lib.ts';
import { asFilename, asIdentity, type Filename, type Identity } from '../../src/types.ts';
import {
EmptyBodyError,
IdentityNotHostedError,
InvalidStateError,
MessageNotFoundError,
} from '../../src/errors.ts';
let scratch: string;
let stRoot: string;
let alice: Identity;
let bob: Identity;
let smalltalk: St;
beforeEach(() => {
scratch = mkdtempSync(join(tmpdir(), 'st-lib-test-'));
stRoot = join(scratch, 'smalltalk');
mkdirSync(stRoot, { recursive: true });
mkdirSync(join(stRoot, 'alice', 'inbox'), { recursive: true });
mkdirSync(join(stRoot, 'alice', 'archive'), { recursive: true });
mkdirSync(join(stRoot, 'bob', 'inbox'), { recursive: true });
mkdirSync(join(stRoot, 'bob', 'archive'), { recursive: true });
alice = asIdentity('alice');
bob = asIdentity('bob');
smalltalk = createSt({
root: stRoot,
identity: alice,
configRoot: join(scratch, 'config'),
});
mkdirSync(join(scratch, 'config'), { recursive: true });
});
afterEach(() => {
rmSync(scratch, { recursive: true, force: true });
});
// ─── construction ──────────────────────────────────────────────────────
describe('createSt — construction', () => {
it('exposes root, identity, configRoot', () => {
expect(smalltalk.root).toBe(stRoot);
expect(smalltalk.identity).toBe('alice');
expect(smalltalk.configRoot).toBe(join(scratch, 'config'));
});
it('defaults configRoot to ~/.config/smalltalk', () => {
const c = createSt({ root: stRoot, identity: alice });
expect(c.configRoot.endsWith('.config/smalltalk')).toBe(true);
});
it('throws if identity is invalid (asIdentity catches at construction)', () => {
expect(() =>
createSt({
root: stRoot,
identity: 'INVALID' as unknown as Identity,
})
).toThrowError(/invalid (agent name|identity)/);
});
});
// ─── send ──────────────────────────────────────────────────────────────
describe('smalltalk.send', () => {
it('writes a file and returns its branded Filename', async () => {
const filename = await smalltalk.send(bob, 'hello bob');
expect(filename).toMatch(/^[0-9]{13}-[0-9a-z]{6}\.md$/);
expect(existsSync(join(stRoot, 'bob', 'inbox', filename))).toBe(true);
});
it('uses the Smalltalk identity as `from` by default', async () => {
const filename = await smalltalk.send(bob, 'body');
const text = require('node:fs').readFileSync(
join(stRoot, 'bob', 'inbox', filename),
'utf8'
);
expect(text).toContain('from: alice');
});
it('opts.from overrides the default identity', async () => {
const filename = await smalltalk.send(bob, 'body', {
from: asIdentity('bob'), // bob sending to himself for the test
});
const text = require('node:fs').readFileSync(
join(stRoot, 'bob', 'inbox', filename),
'utf8'
);
expect(text).toContain('from: bob');
});
it('throws EmptyBodyError on empty body', async () => {
await expect(smalltalk.send(bob, '')).rejects.toBeInstanceOf(EmptyBodyError);
});
it('subject + tags + priority emit into frontmatter', async () => {
const filename = await smalltalk.send(bob, 'body', {
subject: 're: hello',
tags: ['a', 'b'],
priority: 'high',
});
const text = require('node:fs').readFileSync(
join(stRoot, 'bob', 'inbox', filename),
'utf8'
);
expect(text).toContain('subject: "re: hello"');
expect(text).toContain('tags: [a, b]');
expect(text).toContain('priority: high');
});
});
// ─── ls ────────────────────────────────────────────────────────────────
describe('smalltalk.ls', () => {
it('defaults to the Smalltalk identity\'s inbox', async () => {
await smalltalk.send(alice, 'msg', { from: bob }); // bob → alice
const matches = await smalltalk.ls();
expect(matches).toHaveLength(1);
});
it('explicit identity arg overrides default', async () => {
await smalltalk.send(bob, 'msg');
const matches = await smalltalk.ls(bob);
expect(matches).toHaveLength(1);
});
it('--archive lists archive folder', async () => {
const f = await smalltalk.send(bob, 'msg');
await smalltalk.archive(bob, f);
expect(await smalltalk.ls(bob)).toEqual([]);
const arch = await smalltalk.ls(bob, { archive: true });
expect(arch).toEqual([f]);
});
it('--since filters by filename ts', async () => {
const f = await smalltalk.send(bob, 'msg');
const ts = Number(f.slice(0, 13));
expect(await smalltalk.ls(bob, { since: ts })).toEqual([f]);
expect(await smalltalk.ls(bob, { since: ts + 1 })).toEqual([]);
});
it('--from filters by frontmatter from key', async () => {
await smalltalk.send(bob, 'msg from alice'); // from = alice
expect(await smalltalk.ls(bob, { fromFilter: alice })).toHaveLength(1);
expect(await smalltalk.ls(bob, { fromFilter: bob })).toEqual([]);
});
});
// ─── read ──────────────────────────────────────────────────────────────
describe('smalltalk.read', () => {
it('returns a typed MessageWithLocation', async () => {
const filename = await smalltalk.send(bob, 'hello bob', { subject: 'hi' });
const r = await smalltalk.read(bob, filename);
expect(r.filename).toBe(filename);
expect(r.identity).toBe('bob');
expect(r.folder).toBe('inbox');
expect(r.message.from).toBe('alice');
expect(r.message.subject).toBe('hi');
expect(r.message.body).toBe('hello bob\n');
});
it('throws MessageNotFoundError for missing file', async () => {
await expect(
smalltalk.read(bob, asFilename('1714826789010-zzzzzz.md'))
).rejects.toBeInstanceOf(MessageNotFoundError);
});
it('falls back to archive automatically', async () => {
const f = await smalltalk.send(bob, 'msg');
await smalltalk.archive(bob, f);
const r = await smalltalk.read(bob, f);
expect(r.folder).toBe('archive');
});
});
// ─── archive (+ trim) ──────────────────────────────────────────────────
describe('smalltalk.archive', () => {
it('moves inbox → archive', async () => {
const f = await smalltalk.send(bob, 'msg');
await smalltalk.archive(bob, f);
expect(existsSync(join(stRoot, 'bob', 'inbox', f))).toBe(false);
expect(existsSync(join(stRoot, 'bob', 'archive', f))).toBe(true);
});
});
describe('smalltalk.archiveTrim', () => {
it('removes files older than the cutoff and returns the victims', async () => {
// Plant 5 archived files at known timestamps.
const fakeNow = 1_800_000_000_000;
const archDir = join(stRoot, 'alice', 'archive');
for (let i = 0; i < 5; i++) {
const ts = fakeNow - (i + 1) * 24 * 60 * 60 * 1000;
writeFileSync(join(archDir, `${ts}-aaaaaa.md`), 'x');
}
const victims = await smalltalk.archiveTrim(alice, {
olderThan: '3d',
now: () => fakeNow,
});
expect(victims).toHaveLength(2); // 2 files older than 3 days
});
it('--dry-run returns victims without deleting', async () => {
const archDir = join(stRoot, 'alice', 'archive');
for (const ts of ['1714826789010', '1714826789020', '1714826789030']) {
writeFileSync(join(archDir, `${ts}-aaaaaa.md`), 'x');
}
const victims = await smalltalk.archiveTrim(alice, {
keepLast: 1,
dryRun: true,
});
expect(victims).toHaveLength(2);
// Files are still on disk.
expect(require('node:fs').readdirSync(archDir)).toHaveLength(3);
});
});
// ─── thread ────────────────────────────────────────────────────────────
describe('smalltalk.thread', () => {
it('returns MessageWithLocation[] in flat chronological order', async () => {
const f1 = await smalltalk.send(bob, 'root', { subject: 'A' });
// Force a strictly-later ms so chronological sort = send order
// (two sends in the same ms break this ordering deterministically).
await new Promise((r) => setTimeout(r, 2));
const f2 = await smalltalk.send(bob, 'reply', {
subject: 'B',
inReplyTo: f1,
});
const out = await smalltalk.thread(bob, f1);
expect(out.map((m) => m.filename)).toEqual([f1, f2]);
expect(out[0]!.message.subject).toBe('A');
expect(out[1]!.message.subject).toBe('B');
});
});
// ─── status ────────────────────────────────────────────────────────────
describe('smalltalk.getStatus / setStatus', () => {
it('default is offline', async () => {
expect(await smalltalk.getStatus(alice)).toBe('offline');
});
it('roundtrip', async () => {
await smalltalk.setStatus(alice, 'busy');
expect(await smalltalk.getStatus(alice)).toBe('busy');
});
it('setStatus with invalid state throws InvalidStateError', async () => {
await expect(
smalltalk.setStatus(alice, 'urgent' as unknown as 'busy')
).rejects.toBeInstanceOf(InvalidStateError);
});
});
// ─── sweep ─────────────────────────────────────────────────────────────
describe('smalltalk.sweep', () => {
it('removes byte-identical inbox+archive twins', async () => {
const f = '1714826789010-aaaaaa.md';
writeFileSync(join(stRoot, 'bob', 'inbox', f), 'same');
writeFileSync(join(stRoot, 'bob', 'archive', f), 'same');
const r = await smalltalk.sweep();
expect(r.removed).toBe(1);
});
});
// ─── identity validation ──────────────────────────────────────────────
describe('smalltalk — identity-not-hosted error path', () => {
it('throws IdentityNotHostedError when an identity has no folder', async () => {
const ghost = asIdentity('ghost');
await expect(smalltalk.archive(ghost, asFilename('1714826789010-aaaaaa.md')))
.rejects.toBeInstanceOf(IdentityNotHostedError);
});
});
// ─── watch (async iterable, AbortSignal) ──────────────────────────────
describe('smalltalk.watch', () => {
it('replay phase yields existing files at cutoff=0 (default)', async () => {
await smalltalk.send(alice, 'msg from bob', { from: bob });
const ac = new AbortController();
const seen: string[] = [];
const iterable = smalltalk.watch(alice, { intervalMs: 50, signal: ac.signal });
const consume = (async () => {
for await (const ev of iterable) {
seen.push(ev.filename);
ac.abort(); // stop after first event
}
})();
await consume;
expect(seen).toHaveLength(1);
});
it('AbortSignal stops the iterator', async () => {
const ac = new AbortController();
const seen: string[] = [];
const consume = (async () => {
for await (const ev of smalltalk.watch(bob, {
intervalMs: 50,
signal: ac.signal,
})) {
seen.push(ev.filename);
}
})();
// Abort immediately; the iterable should resolve.
ac.abort();
await consume;
expect(seen).toEqual([]);
});
it('--all watch suppresses the Smalltalk identity\'s own folder (cross-tree supervisor)', async () => {
// brief-017a bug 3: cross-tree mode is now opt-in via `{all: true}`.
// Send to alice (her own inbox) and to bob (peer). With --all,
// we should see ONLY the bob entry; the watcher's own folder
// is suppressed.
await smalltalk.send(alice, 'self-msg', { from: bob });
await smalltalk.send(bob, 'peer-msg', { from: alice });
const ac = new AbortController();
const seen: string[] = [];
const consume = (async () => {
for await (const ev of smalltalk.watch(undefined, {
all: true,
intervalMs: 50,
signal: ac.signal,
})) {
seen.push(`${ev.identity}:${ev.filename}`);
ac.abort();
}
})();
await consume;
expect(seen.every((s) => s.startsWith('bob:'))).toBe(true);
expect(seen.length).toBeGreaterThan(0);
});
it('default watch (no id, no --all) watches the Smalltalk identity\'s own inbox', async () => {
// brief-017a bug 3: default is now "watch own inbox" — same as
// CLI `st watch` with no args.
await smalltalk.send(alice, 'self-msg', { from: bob });
await smalltalk.send(bob, 'peer-msg', { from: alice });
const ac = new AbortController();
const seen: string[] = [];
const consume = (async () => {
for await (const ev of smalltalk.watch(undefined, {
intervalMs: 50,
signal: ac.signal,
})) {
seen.push(`${ev.identity}:${ev.filename}`);
ac.abort();
}
})();
await consume;
// The `smalltalk` instance here is built with identity=alice (see the
// beforeEach). So default watch yields alice:* entries, not bob's.
expect(seen.every((s) => s.startsWith('alice:'))).toBe(true);
expect(seen.length).toBeGreaterThan(0);
});
it('--with-subject yields the subject', async () => {
const f = await smalltalk.send(alice, 'msg', {
from: bob,
subject: 'hi there',
});
void f;
const ac = new AbortController();
let captured: string | undefined;
const consume = (async () => {
for await (const ev of smalltalk.watch(alice, {
withSubject: true,
intervalMs: 50,
signal: ac.signal,
})) {
captured = ev.subject;
ac.abort();
}
})();
await consume;
expect(captured).toBe('hi there');
});
});