File size: 22,417 Bytes
f0634fb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import { SyncDescriptor } from '#/_base/di/descriptors';
import { DisposableStore } from '#/_base/di/lifecycle';
import { ServiceCollection } from '#/_base/di/serviceCollection';
import { TestInstantiationService } from '#/_base/di/test';
import { ILogService } from '#/_base/log/log';
import { ISessionIndexMirror } from '#/app/sessionIndex/sessionIndex';
import { ISessionContext, makeSessionContext } from '#/session/sessionContext/sessionContext';
import { ISessionMetadata } from '#/session/sessionMetadata/sessionMetadata';
import { SessionMetadata } from '#/session/sessionMetadata/sessionMetadataService';
import { ISessionStateService } from '#/session/state/sessionState';
import { SessionStateService } from '#/session/state/sessionStateService';
import { JsonAtomicDocumentStore } from '#/persistence/backends/node-fs/atomicDocumentStore';
import { IFileSystemStorageService } from '#/persistence/interface/storage';
import { IAtomicDocumentStore } from '#/persistence/interface/atomicDocumentStore';
import { InMemoryStorageService } from '#/persistence/backends/memory/inMemoryStorageService';

import { stubSessionIndexMirror } from '../../app/sessionIndex/stubs';
import { stubLog } from '../../_base/log/stubs';

const META_SCOPE = 'sessions/wd_test/s1/session-meta';

function createFreshMetadata(ix: TestInstantiationService): SessionMetadata {
  return ix
    .createChild(new ServiceCollection([ISessionStateService, new SessionStateService()]))
    .createInstance(SessionMetadata);
}

function makeContext(): ISessionContext {
  return makeSessionContext({
    sessionId: 's1',
    workspaceId: 'wd_test',
    sessionDir: '/tmp/sessions/wd_test/s1',
    sessionScope: 'sessions/wd_test/s1',
    metaScope: META_SCOPE,
    cwd: '/tmp/sessions/wd_test/s1',
  });
}

describe('SessionMetadata', () => {
  let disposables: DisposableStore;
  let ix: TestInstantiationService;
  let mirror: ReturnType<typeof stubSessionIndexMirror>;

  beforeEach(() => {
    disposables = new DisposableStore();
    ix = disposables.add(new TestInstantiationService());
    mirror = stubSessionIndexMirror();
    ix.stub(ILogService, stubLog());
    ix.stub(ISessionContext, makeContext());
    ix.stub(ISessionIndexMirror, mirror);
    ix.set(ISessionStateService, new SyncDescriptor(SessionStateService));
    ix.set(IFileSystemStorageService, new SyncDescriptor(InMemoryStorageService));
    ix.set(IAtomicDocumentStore, new SyncDescriptor(JsonAtomicDocumentStore));
    ix.set(ISessionMetadata, new SyncDescriptor(SessionMetadata));
  });

  afterEach(() => {
    disposables.dispose();
    vi.restoreAllMocks();
  });

  it('creates an initial document on first read', async () => {
    const meta = ix.get(ISessionMetadata);
    expect(await meta.read()).toMatchObject({
      id: 's1',
      archived: false,
      agents: {},
      custom: {},
    });
    expect((await meta.read()).createdAt).toBeGreaterThan(0);
  });

  it('update merges fields and bumps updatedAt', async () => {
    const meta = ix.get(ISessionMetadata);
    const before = (await meta.read()).updatedAt;
    await new Promise((r) => setTimeout(r, 2));
    await meta.update({ title: 'hello' });

    const next = await meta.read();
    expect(next.title).toBe('hello');
    expect(next.updatedAt).toBeGreaterThanOrEqual(before);
  });

  it('update with touchUpdatedAt:false keeps the previous updatedAt', async () => {
    const meta = ix.get(ISessionMetadata);
    const before = (await meta.read()).updatedAt;
    await meta.update({ title: 'quiet' }, { touchUpdatedAt: false });

    const next = await meta.read();
    expect(next.title).toBe('quiet');
    expect(next.updatedAt).toBe(before);
  });

  it('setTitle / setArchived write through', async () => {
    const meta = ix.get(ISessionMetadata);
    await meta.setTitle('t');
    await meta.setArchived(true);
    expect(await meta.read()).toMatchObject({ title: 't', titleKind: 'custom', archived: true });
  });

  it('sets a generated title while the metadata remains uncustomized', async () => {
    const meta = ix.get(ISessionMetadata);

    await expect(meta.setGeneratedTitleIfUncustomized('generated title')).resolves.toBe(true);
    await expect(meta.read()).resolves.toMatchObject({
      title: 'generated title',
      titleKind: 'generated',
    });
  });

  it('setTitle keeps updatedAt (rename must not reorder listings)', async () => {
    const meta = ix.get(ISessionMetadata);
    const before = (await meta.read()).updatedAt;
    await new Promise((r) => setTimeout(r, 2));
    await meta.setTitle('renamed');

    const next = await meta.read();
    expect(next.title).toBe('renamed');
    expect(next.updatedAt).toBe(before);
  });

  it('setArchived records archivedAt without touching updatedAt; restore clears it', async () => {
    const meta = ix.get(ISessionMetadata);
    const before = (await meta.read()).updatedAt;
    await new Promise((r) => setTimeout(r, 2));

    await meta.setArchived(true);
    const archived = await meta.read();
    expect(archived.archived).toBe(true);
    expect(archived.archivedAt).toBeGreaterThan(before);
    expect(archived.updatedAt).toBe(before);

    await meta.setArchived(false);
    const restored = await meta.read();
    expect(restored.archived).toBe(false);
    expect(restored.archivedAt).toBeUndefined();
    expect(restored.updatedAt).toBe(before);
  });

  it('registerAgent never bumps updatedAt — the agents map is structural', async () => {
    const meta = ix.get(ISessionMetadata);
    const before = (await meta.read()).updatedAt;
    await new Promise((r) => setTimeout(r, 2));
    await meta.registerAgent('main', { homedir: '/tmp/h', type: 'main' });

    const next = await meta.read();
    expect(next.agents?.['main']?.homedir).toBe('/tmp/h');
    expect(next.updatedAt).toBe(before);
  });

  it('an explicit patch.updatedAt always wins (fork inherits the source recency)', async () => {
    const meta = ix.get(ISessionMetadata);
    await meta.update({ title: 'fork', updatedAt: 1234 });

    const next = await meta.read();
    expect(next.title).toBe('fork');
    expect(next.updatedAt).toBe(1234);
  });

  it('reads a loaded document without the archived field as not-archived', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      agents: {},
      custom: {},
    });

    const meta = ix.get(ISessionMetadata);
    expect(await meta.read()).toMatchObject({ id: 's1', archived: false });
  });

  it('mirrors a boolean archived to the read model even when the loaded document lacks the field', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      agents: {},
      custom: {},
    });

    const meta = ix.get(ISessionMetadata);
    await meta.ready;
    expect(mirror.recorded).toEqual([]);

    await meta.update({ title: 'x' });

    expect(mirror.recorded).toHaveLength(1);
    expect(mirror.recorded[0]).toMatchObject({ id: 's1', archived: false });
  });

  it('persists the authoritative document before recording to the mirror', async () => {
    const store = ix.get(IAtomicDocumentStore);
    const persistedAtRecord: Promise<Record<string, unknown> | undefined>[] = [];
    const baseRecord = mirror.record;
    mirror.record = (summary) => {
      persistedAtRecord.push(store.get<Record<string, unknown>>(META_SCOPE, 'state.json'));
      baseRecord(summary);
    };

    const meta = ix.get(ISessionMetadata);
    await meta.ready;
    await meta.update({ title: 'durable-first' });

    expect(persistedAtRecord).toHaveLength(2);
    const [atCreate, atUpdate] = await Promise.all(persistedAtRecord);
    expect(atCreate).toMatchObject({ id: 's1', archived: false });
    expect(atUpdate).toMatchObject({ title: 'durable-first' });
  });

  it('a mirror failure degrades the read model but never fails the metadata mutation', async () => {
    mirror.record = () => {
      throw new Error('mirror down');
    };

    const meta = ix.get(ISessionMetadata);
    await meta.ready;
    await meta.update({ title: 'still fine' });
    expect(await meta.read()).toMatchObject({ title: 'still fine' });

    const fresh = createFreshMetadata(ix);
    expect(await fresh.read()).toMatchObject({ title: 'still fine' });
  });

  it('persists across instances', async () => {
    const meta = ix.get(ISessionMetadata);
    await meta.update({ title: 'persisted' });

    const fresh = createFreshMetadata(ix);
    expect(await fresh.read()).toMatchObject({ id: 's1', title: 'persisted' });
  });

  it('backfills and persists missing agents/custom maps on a pre-fix document', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      archived: false,
    });

    const meta = ix.get(ISessionMetadata);
    expect(await meta.read()).toMatchObject({ agents: {}, custom: {} });

    const fresh = createFreshMetadata(ix);
    const healed = await fresh.read();
    expect(healed.agents).toEqual({});
    expect(healed.custom).toEqual({});
    expect(healed.updatedAt).toBe(1700000000000);
  });

  it('normalizes the legacy customTitle field before callers read metadata', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      archived: false,
      customTitle: 'legacy title',
    });

    const meta = ix.get(ISessionMetadata);
    await expect(meta.read()).resolves.toMatchObject({
      title: 'legacy title',
      titleKind: 'custom',
    });

    const fresh = createFreshMetadata(ix);
    await expect(fresh.read()).resolves.toMatchObject({
      title: 'legacy title',
      titleKind: 'custom',
    });
  });

  it('trusts modern custom title state over a stale legacy customTitle', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      archived: false,
      title: 'renamed title',
      isCustomTitle: true,
      customTitle: 'legacy custom title',
    });

    const meta = ix.get(ISessionMetadata);
    await expect(meta.read()).resolves.toMatchObject({
      title: 'renamed title',
      titleKind: 'custom',
    });

    await meta.update({ archived: true });
    const fresh = createFreshMetadata(ix);
    await expect(fresh.read()).resolves.toMatchObject({
      title: 'renamed title',
      titleKind: 'custom',
      archived: true,
    });
    const persisted = await store.get<Record<string, unknown>>(META_SCOPE, 'state.json');
    expect(persisted).toMatchObject({ isCustomTitle: true });
    expect(persisted).not.toHaveProperty('customTitle');
  });

  it('migrates a legacy non-custom title to replaceable title state', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      archived: false,
      title: 'prompt title',
      isCustomTitle: false,
      agents: {},
      custom: {},
    });

    const meta = ix.get(ISessionMetadata);

    await expect(meta.read()).resolves.toMatchObject({
      title: 'prompt title',
      titleKind: 'replaceable',
    });
    const persisted = await store.get<Record<string, unknown>>(META_SCOPE, 'state.json');
    expect(persisted).toMatchObject({
      title: 'prompt title',
      titleKind: 'replaceable',
      isCustomTitle: false,
    });
  });

  it('honors a legacy writer custom marker over the stale titleKind it left behind', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      archived: false,
      title: '用户手工标题',
      titleKind: 'replaceable',
      isCustomTitle: true,
      agents: {},
      custom: {},
    });

    const meta = ix.get(ISessionMetadata);
    await expect(meta.read()).resolves.toMatchObject({
      title: '用户手工标题',
      titleKind: 'custom',
    });

    const persisted = await store.get<Record<string, unknown>>(META_SCOPE, 'state.json');
    expect(persisted).toMatchObject({ titleKind: 'custom', isCustomTitle: true });

    const fresh = createFreshMetadata(ix);
    await expect(fresh.read()).resolves.toMatchObject({
      title: '用户手工标题',
      titleKind: 'custom',
    });
    await expect(fresh.setGeneratedTitleIfUncustomized('generated title')).resolves.toBe(false);
  });

  it('double-writes the derived isCustomTitle marker for v1 readers', async () => {
    const store = ix.get(IAtomicDocumentStore);
    const meta = ix.get(ISessionMetadata);

    await meta.setGeneratedTitleIfUncustomized('generated title');
    await expect(store.get<Record<string, unknown>>(META_SCOPE, 'state.json')).resolves.toMatchObject(
      { titleKind: 'generated', isCustomTitle: false },
    );

    await meta.setTitle('user title');
    await expect(store.get<Record<string, unknown>>(META_SCOPE, 'state.json')).resolves.toMatchObject(
      { titleKind: 'custom', isCustomTitle: true },
    );
  });

  it('does not downgrade a modern titleKind on a legacy false marker', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      archived: false,
      title: 'generated title',
      titleKind: 'generated',
      isCustomTitle: false,
      agents: {},
      custom: {},
    });

    const meta = ix.get(ISessionMetadata);
    await expect(meta.read()).resolves.toMatchObject({
      title: 'generated title',
      titleKind: 'generated',
    });
  });

  it.each([
    [{ isCustomTitle: true, titleKind: 'generated' as const }, 'custom'],
    [{ isCustomTitle: true, titleKind: 'replaceable' as const }, 'custom'],
    [{ isCustomTitle: true }, 'custom'],
    [{ isCustomTitle: false, titleKind: 'custom' as const }, 'custom'],
    [{ isCustomTitle: false, titleKind: 'generated' as const }, 'generated'],
    [{ isCustomTitle: false }, 'replaceable'],
    [{ titleKind: 'generated' as const }, 'generated'],
    [{ customTitle: 'legacy title' }, 'custom'],
    [{}, 'replaceable'],
  ])('normalizes title state %j to titleKind %s', async (fields, expectedKind) => {
    const store = ix.get(IAtomicDocumentStore);
    const title = 'customTitle' in fields ? undefined : 'some title';
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      archived: false,
      ...(title === undefined ? {} : { title }),
      ...fields,
      agents: {},
      custom: {},
    });

    const meta = ix.get(ISessionMetadata);
    expect((await meta.read()).titleKind).toBe(expectedKind);
  });

  it('migrates the title state once, not on every load', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      archived: false,
      title: '用户手工标题',
      titleKind: 'replaceable',
      isCustomTitle: true,
      agents: {},
      custom: {},
    });

    const first = ix.get(ISessionMetadata);
    await first.ready;
    const setSpy = vi.spyOn(store, 'set');
    const fresh = createFreshMetadata(ix);
    await fresh.ready;

    expect(setSpy).not.toHaveBeenCalled();
    expect((await fresh.read()).titleKind).toBe('custom');
  });

  it('keeps a queued custom title when a generated title is enqueued afterward', async () => {
    const meta = ix.get(ISessionMetadata);
    await meta.ready;
    const store = ix.get(IAtomicDocumentStore);
    const set = store.set.bind(store);
    let releaseWrite: (() => void) | undefined;
    let markWriteStarted: (() => void) | undefined;
    const writeStarted = new Promise<void>((resolve) => {
      markWriteStarted = resolve;
    });
    const writeReleased = new Promise<void>((resolve) => {
      releaseWrite = resolve;
    });
    let shouldBlock = true;
    vi.spyOn(store, 'set').mockImplementation(async (scope, key, value) => {
      if (shouldBlock) {
        shouldBlock = false;
        markWriteStarted?.();
        await writeReleased;
      }
      await set(scope, key, value);
    });

    const priorWrite = meta.update({ lastPrompt: 'hello' });
    await writeStarted;
    const rename = meta.setTitle('user title');
    const generated = meta.setGeneratedTitleIfUncustomized('generated title');
    releaseWrite?.();

    await priorWrite;
    await rename;
    await expect(generated).resolves.toBe(false);
    await expect(meta.read()).resolves.toMatchObject({
      title: 'user title',
      titleKind: 'custom',
    });
  });

  it('leaves existing agents/custom maps untouched', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      archived: false,
      agents: { main: { homedir: '/tmp/sessions/wd_test/s1/agents/main', type: 'main' } },
      custom: { cwd: '/tmp/work' },
    });

    const meta = ix.get(ISessionMetadata);
    expect(await meta.read()).toMatchObject({
      agents: { main: { homedir: '/tmp/sessions/wd_test/s1/agents/main', type: 'main' } },
      custom: { cwd: '/tmp/work' },
    });
  });

  it('fires onDidChangeMetadata with the changed keys after update', async () => {
    const meta = ix.get(ISessionMetadata);
    await meta.ready;
    let fired = 0;
    let captured: { readonly changed: readonly string[] } | undefined;
    const sub = meta.onDidChangeMetadata((e) => {
      fired++;
      captured = e;
    });
    await meta.update({ title: 'x' });
    expect(fired).toBe(1);
    expect(captured).toEqual({ changed: ['title'] });
    sub.dispose();
  });

  it('preserves every concurrently registered agent', async () => {
    const meta = ix.get(ISessionMetadata);

    await Promise.all([
      meta.registerAgent('agent-0', {
        labels: { swarmItem: 'src/a.ts' },
      }),
      meta.registerAgent('agent-1', {
        labels: { swarmItem: 'src/b.ts' },
      }),
    ]);

    expect(Object.keys((await meta.read()).agents ?? {}).sort()).toEqual([
      'agent-0',
      'agent-1',
    ]);
  });

  it('treats re-registering an unchanged agent as a no-op', async () => {
    const meta = ix.get(ISessionMetadata);
    await meta.registerAgent('main', {
      homedir: '/tmp/sessions/wd_test/s1/agents/main',
      type: 'main',
      parentAgentId: undefined,
      forkedFrom: undefined,
      labels: undefined,
    });

    const before = (await meta.read()).updatedAt;
    await new Promise((r) => setTimeout(r, 2));

    let fired = 0;
    const sub = meta.onDidChangeMetadata(() => {
      fired++;
    });
    await meta.registerAgent('main', {
      homedir: '/tmp/sessions/wd_test/s1/agents/main',
      type: 'main',
      parentAgentId: undefined,
      forkedFrom: undefined,
      labels: undefined,
    });

    expect(fired).toBe(0);
    expect((await meta.read()).updatedAt).toBe(before);
    sub.dispose();
  });

  it('stays a no-op when re-registering against a persisted document', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      archived: false,
      agents: {
        main: {
          homedir: '/tmp/sessions/wd_test/s1/agents/main',
          type: 'main',
          parentAgentId: null,
        },
      },
    });

    const meta = ix.get(ISessionMetadata);
    await meta.registerAgent('main', {
      homedir: '/tmp/sessions/wd_test/s1/agents/main',
      type: 'main',
      parentAgentId: undefined,
      forkedFrom: undefined,
      labels: undefined,
    });

    expect((await meta.read()).updatedAt).toBe(1700000000000);
  });

  it('updates changed fields on re-registration without bumping updatedAt', async () => {
    const meta = ix.get(ISessionMetadata);
    await meta.registerAgent('main', {
      homedir: '/tmp/sessions/wd_test/s1/agents/main',
      type: 'main',
    });
    const before = (await meta.read()).updatedAt;
    await new Promise((r) => setTimeout(r, 2));

    await meta.registerAgent('main', {
      homedir: '/tmp/sessions/wd_test/s1/agents/main',
      type: 'main',
      labels: { swarmItem: 'src/a.ts' },
    });

    const next = await meta.read();
    expect(next.agents?.['main']?.labels).toEqual({ swarmItem: 'src/a.ts' });
    expect(next.updatedAt).toBe(before);
  });

  it('records the fresh summary into the session index mirror on update', async () => {
    const meta = ix.get(ISessionMetadata);
    await meta.ready;
    expect(mirror.recorded).toHaveLength(1);

    await meta.update({ title: 'mirrored' });

    expect(mirror.recorded).toHaveLength(2);
    expect(mirror.recorded[1]).toMatchObject({
      id: 's1',
      workspaceId: 'wd_test',
      title: 'mirrored',
      archived: false,
    });
    expect(mirror.recorded[1]?.updatedAt).toBe((await meta.read()).updatedAt);
  });

  it('does not re-record when loading an existing document', async () => {
    const store = ix.get(IAtomicDocumentStore);
    await store.set(META_SCOPE, 'state.json', {
      id: 's1',
      version: 2,
      createdAt: 1700000000000,
      updatedAt: 1700000000000,
      archived: false,
      agents: {},
      custom: {},
    });

    const meta = ix.get(ISessionMetadata);
    await meta.ready;
    expect(mirror.recorded).toEqual([]);

    await meta.setArchived(true);
    expect(mirror.recorded).toHaveLength(1);
    expect(mirror.recorded[0]?.archived).toBe(true);
  });
});