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
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
import { randomBytes } from 'node:crypto';
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'pathe';

import { afterEach, describe, expect, it } from 'vitest';

import { SyncDescriptor } from '#/_base/di/descriptors';
import { DisposableStore } from '#/_base/di/lifecycle';
import { TestInstantiationService } from '#/_base/di/test';
import {
  AppendLogStore,
  WIRE_PROTOCOL_VERSION,
  IFileSystemStorageService,
  IAppendLogStore,
  type WireRecord,
} from '#/index';
import { IWireService } from '#/wire/wire';
import { noopTelemetryService } from '#/app/telemetry/telemetry';
import { FileStorageService } from '#/persistence/backends/node-fs/fileStorageService';
import { InMemoryStorageService } from '#/persistence/backends/memory/inMemoryStorageService';

import { noopLogger, registerTestAgentWire } from './stubs';

const cleanups: string[] = [];
const disposables: DisposableStore[] = [];
const SCOPE = 'wire-test';
const KEY = 'wire.jsonl';

afterEach(async () => {
  for (const store of disposables.splice(0)) {
    store.dispose();
  }
  for (const dir of cleanups.splice(0)) {
    await rm(dir, { recursive: true, force: true }).catch(() => {});
  }
});

async function makeDir(prefix: string): Promise<string> {
  const dir = join(tmpdir(), `${prefix}-${randomBytes(6).toString('hex')}`);
  await mkdir(dir, { recursive: true });
  cleanups.push(dir);
  return dir;
}

async function readLines(path: string): Promise<string[]> {
  const raw = await readFile(path, 'utf8');
  return raw.split('\n').filter((line) => line.length > 0);
}

function createAppendLogHarness(storage: IFileSystemStorageService): IAppendLogStore {
  const disposable = new DisposableStore();
  disposables.push(disposable);

  const ix = disposable.add(new TestInstantiationService());
  ix.stub(IFileSystemStorageService, storage);
  ix.set(IAppendLogStore, new SyncDescriptor(AppendLogStore));
  return ix.get(IAppendLogStore);
}

function createAgentWireHarness(
  log: IAppendLogStore,
  storage?: IFileSystemStorageService,
): IWireService {
  const disposable = new DisposableStore();
  disposables.push(disposable);

  const ix = disposable.add(new TestInstantiationService());
  return registerTestAgentWire(ix, SCOPE, {
    log,
    storage,
    logger: noopLogger,
    telemetry: noopTelemetryService,
  });
}

async function createFileAppendLogHarness(): Promise<{
  readonly dir: string;
  readonly log: IAppendLogStore;
  readonly storage: IFileSystemStorageService;
}> {
  const dir = await makeDir('wire-jsonl-test');
  const storage = new FileStorageService(dir);
  return {
    dir,
    log: createAppendLogHarness(storage),
    storage,
  };
}

async function collect<R>(log: IAppendLogStore, scope = SCOPE, key = KEY): Promise<R[]> {
  const records: R[] = [];
  for await (const record of log.read<R>(scope, key)) {
    records.push(record);
  }
  return records;
}

async function drainJournal(svc: IWireService): Promise<WireRecord[]> {
  const records: WireRecord[] = [];
  for await (const record of svc.readJournal()) {
    records.push(record);
  }
  return records;
}

describe('AppendLogStore file persistence', () => {
  it('writes only the appended record', async () => {
    const { dir, log } = await createFileAppendLogHarness();

    log.append(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'hello' }],
      origin: { kind: 'user' },
    });
    await log.close();

    const lines = await readLines(join(dir, SCOPE, KEY));
    expect(lines).toHaveLength(1);
    expect(JSON.parse(lines[0]!)['type']).toBe('turn.prompt');
  });

  it('appends to an existing file without injecting records', async () => {
    const dir = await makeDir('wire-jsonl-test');
    const first = createAppendLogHarness(new FileStorageService(dir));
    first.append(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'one' }],
      origin: { kind: 'user' },
    });
    await first.close();

    const second = createAppendLogHarness(new FileStorageService(dir));
    second.append(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'two' }],
      origin: { kind: 'user' },
    });
    await second.close();

    const lines = await readLines(join(dir, SCOPE, KEY));
    expect(lines).toHaveLength(2);
    expect(lines.map((line) => JSON.parse(line)['type'])).toEqual([
      'turn.prompt',
      'turn.prompt',
    ]);
  });

  it('returns appended metadata records from read() output', async () => {
    const { log } = await createFileAppendLogHarness();
    log.append(SCOPE, KEY, {
      type: 'metadata',
      protocol_version: WIRE_PROTOCOL_VERSION,
      created_at: 1,
    });
    log.append(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'hi' }],
      origin: { kind: 'user' },
    });
    await log.close();

    const records = await collect<WireRecord>(log);
    expect(records).toHaveLength(2);
    expect(records[0]).toMatchObject({
      type: 'metadata',
      protocol_version: WIRE_PROTOCOL_VERSION,
    });
    expect(records[1]!.type).toBe('turn.prompt');
  });

  it('rewrites records from the beginning and then appends after them', async () => {
    const { dir, log } = await createFileAppendLogHarness();
    log.append(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'old' }],
      origin: { kind: 'user' },
    });
    await log.flush();
    await log.rewrite(SCOPE, KEY, [
      {
        type: 'metadata',
        protocol_version: WIRE_PROTOCOL_VERSION,
        created_at: 1,
      },
      {
        type: 'turn.prompt',
        input: [{ type: 'text', text: 'new' }],
        origin: { kind: 'user' },
      },
    ]);
    log.append(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'later' }],
      origin: { kind: 'user' },
    });
    await log.flush();

    const lines = await readLines(join(dir, SCOPE, KEY));
    expect(lines.map((line) => JSON.parse(line)['type'])).toEqual([
      'metadata',
      'turn.prompt',
      'turn.prompt',
    ]);
    expect(JSON.parse(lines[1]!)['input'][0]['text']).toBe('new');
    expect(JSON.parse(lines[2]!)['input'][0]['text']).toBe('later');
  });

  it('rewrites already flushed records from the beginning', async () => {
    const { dir, log } = await createFileAppendLogHarness();
    log.append(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'old' }],
      origin: { kind: 'user' },
    });
    await log.flush();

    await log.rewrite(SCOPE, KEY, [
      {
        type: 'metadata',
        protocol_version: WIRE_PROTOCOL_VERSION,
        created_at: 1,
      },
      {
        type: 'turn.prompt',
        input: [{ type: 'text', text: 'new' }],
        origin: { kind: 'user' },
      },
    ]);
    await log.flush();

    const lines = await readLines(join(dir, SCOPE, KEY));
    expect(lines.map((line) => JSON.parse(line)['type'])).toEqual([
      'metadata',
      'turn.prompt',
    ]);
    expect(JSON.parse(lines[1]!)['input'][0]['text']).toBe('new');
  });

  it('flushes pending records on close', async () => {
    const { dir, log } = await createFileAppendLogHarness();

    log.append(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'late' }],
      origin: { kind: 'user' },
    });
    await log.close();

    const lines = await readLines(join(dir, SCOPE, KEY));
    expect(lines).toHaveLength(1);
    expect(JSON.parse(lines[0]!)['type']).toBe('turn.prompt');
  });

  it('propagates write failures from flush', async () => {
    const dir = await makeDir('wire-jsonl-test');
    await mkdir(join(dir, SCOPE, KEY), { recursive: true });
    const log = createAppendLogHarness(new FileStorageService(dir));

    log.append(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'first' }],
      origin: { kind: 'user' },
    });

    await expect(log.flush()).rejects.toBeInstanceOf(Error);
  });
});

describe('wire record append-log persistence', () => {
  it('can be backed by the same IAppendLogStore contract as file persistence', async () => {
    const storage = new InMemoryStorageService();
    const log = createAppendLogHarness(storage);

    log.append<WireRecord>(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'one' }],
      origin: { kind: 'user' },
    });
    await log.flush();
    await log.rewrite<WireRecord>(SCOPE, KEY, [
      {
        type: 'metadata',
        protocol_version: WIRE_PROTOCOL_VERSION,
        created_at: 1,
      },
    ]);

    expect(await collect<WireRecord>(log)).toEqual([
      {
        type: 'metadata',
        protocol_version: WIRE_PROTOCOL_VERSION,
        created_at: 1,
      },
    ]);
  });
});

describe('WireService seal', () => {
  it('appends the metadata envelope to an empty log', async () => {
    const { dir, log } = await createFileAppendLogHarness();
    const svc = createAgentWireHarness(log);

    await svc.seal();
    await log.close();

    const lines = await readLines(join(dir, SCOPE, KEY));
    expect(lines).toHaveLength(1);
    expect(JSON.parse(lines[0]!)).toMatchObject({
      type: 'metadata',
      protocol_version: WIRE_PROTOCOL_VERSION,
    });
  });

  it('is a no-op on a non-empty log', async () => {
    const { dir, log } = await createFileAppendLogHarness();
    log.append(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'existing' }],
      origin: { kind: 'user' },
    });
    await log.flush();
    const svc = createAgentWireHarness(log);

    await svc.seal();
    await log.close();

    const lines = await readLines(join(dir, SCOPE, KEY));
    expect(lines).toHaveLength(1);
    expect(JSON.parse(lines[0]!)['type']).toBe('turn.prompt');
  });

  it('seals only once across repeated calls', async () => {
    const { dir, log } = await createFileAppendLogHarness();
    const svc = createAgentWireHarness(log);

    await svc.seal();
    await svc.seal();
    await log.close();

    const lines = await readLines(join(dir, SCOPE, KEY));
    expect(lines).toHaveLength(1);
  });

  it('journal read after seal keeps the sealed log untouched', async () => {
    const { dir, log } = await createFileAppendLogHarness();
    const svc = createAgentWireHarness(log);

    await svc.seal();
    await drainJournal(svc);
    await log.close();

    const lines = await readLines(join(dir, SCOPE, KEY));
    expect(lines).toHaveLength(1);
    expect(JSON.parse(lines[0]!)).toMatchObject({
      type: 'metadata',
      protocol_version: WIRE_PROTOCOL_VERSION,
    });
  });
});

describe('WireService migration rewrite', () => {
  async function seedLegacyLog(storage: InMemoryStorageService): Promise<IAppendLogStore> {
    const log = createAppendLogHarness(storage);
    log.append<WireRecord>(SCOPE, KEY, {
      type: 'metadata',
      protocol_version: '1.0',
      created_at: 1,
    });
    log.append<WireRecord>(SCOPE, KEY, {
      type: 'turn.prompt',
      input: [{ type: 'text', text: 'hi' }],
      origin: { kind: 'user' },
    });
    await log.flush();
    return log;
  }

  it('journal read resolves only after the migration rewrite is durable', async () => {
    const storage = new InMemoryStorageService();
    const log = await seedLegacyLog(storage);
    let markWriteStarted!: () => void;
    const writeStarted = new Promise<void>((resolve) => {
      markWriteStarted = resolve;
    });
    let releaseWrite!: () => void;
    const writeGate = new Promise<void>((resolve) => {
      releaseWrite = resolve;
    });
    const originalWrite = storage.write.bind(storage);
    storage.write = async (...args) => {
      markWriteStarted();
      await writeGate;
      return originalWrite(...args);
    };

    const svc = createAgentWireHarness(log);
    let drained = false;
    const journalPromise = drainJournal(svc).then(() => {
      drained = true;
    });
    await writeStarted;
    expect(drained).toBe(false);

    releaseWrite();
    await journalPromise;

    const records = await collect<WireRecord>(log);
    expect(records[0]).toMatchObject({
      type: 'metadata',
      protocol_version: WIRE_PROTOCOL_VERSION,
    });
  });

  it('journal read propagates a migration rewrite failure', async () => {
    const storage = new InMemoryStorageService();
    const log = await seedLegacyLog(storage);
    storage.write = async () => {
      throw new Error('disk full');
    };

    const svc = createAgentWireHarness(log);

    await expect(drainJournal(svc)).rejects.toThrow('disk full');
  });
});

describe('WireService corruption repair on disk', () => {
  async function seedCorruptJournal(dir: string, raw: string): Promise<void> {
    await mkdir(join(dir, SCOPE), { recursive: true });
    await writeFile(join(dir, SCOPE, KEY), raw);
  }

  it('restores from the valid prefix and heals the file with a byte-identical backup', async () => {
    const { dir, log, storage } = await createFileAppendLogHarness();
    const metadata = JSON.stringify({
      type: 'metadata',
      protocol_version: WIRE_PROTOCOL_VERSION,
      created_at: 1,
    });
    const kept = JSON.stringify({ type: 'wire.test.kept', time: 2 });
    const raw = `${metadata}\n${kept}\nGARBAGE\n${JSON.stringify({ type: 'wire.test.dropped', time: 3 })}\n`;
    await seedCorruptJournal(dir, raw);
    const svc = createAgentWireHarness(log, storage);

    const yielded = await drainJournal(svc);
    await log.close();

    expect(yielded).toEqual([
      { type: 'metadata', protocol_version: WIRE_PROTOCOL_VERSION, created_at: 1 },
      { type: 'wire.test.kept', time: 2 },
    ]);
    expect(await readFile(join(dir, SCOPE, KEY), 'utf8')).toBe(`${metadata}\n${kept}\n`);
    expect(await readFile(join(dir, SCOPE, `${KEY}.bak`), 'utf8')).toBe(raw);
  });

  it('heals a torn final line left by a disk-full crash', async () => {
    const { dir, log, storage } = await createFileAppendLogHarness();
    const metadata = JSON.stringify({
      type: 'metadata',
      protocol_version: WIRE_PROTOCOL_VERSION,
      created_at: 1,
    });
    const kept = JSON.stringify({ type: 'wire.test.kept', time: 2 });
    const torn = JSON.stringify({ type: 'wire.test.torn', time: 3 }).slice(0, 12);
    await seedCorruptJournal(dir, `${metadata}\n${kept}\n${torn}`);
    const svc = createAgentWireHarness(log, storage);

    const yielded = await drainJournal(svc);
    await log.close();

    expect(yielded).toEqual([
      { type: 'metadata', protocol_version: WIRE_PROTOCOL_VERSION, created_at: 1 },
      { type: 'wire.test.kept', time: 2 },
    ]);
    expect(await readFile(join(dir, SCOPE, KEY), 'utf8')).toBe(`${metadata}\n${kept}\n`);
    expect(await readFile(join(dir, SCOPE, `${KEY}.bak`), 'utf8')).toBe(
      `${metadata}\n${kept}\n${torn}`,
    );
  });
});