Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

30.7 KB
Raw Blame
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, rmSync, existsSync, readFileSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';
import { makePathsProxy } from '../../lib/mockPathsDataRoot.js';

let tempRoot;

vi.mock('../../lib/fileUtils.js', async () => {
  const actual = await vi.importActual('../../lib/fileUtils.js');
  return makePathsProxy(actual, { dataRoot: () => tempRoot });
});

const local = await import('./local.js');
const {
  countWords, contentHash, buildSegmentIndex,
  listFolders, createFolder, deleteFolder,
  listWorks, countWorks, createWork, getWork, getWorkWithBody, updateWork, deleteWork,
  saveDraftBody, snapshotDraft, setActiveDraft, getDraftBody,
  listExercises, createExercise, finishExercise, discardExercise, promoteExercise,
  resolveLiveMode, recordLiveModeUsage, recordLiveModeRenderUsage, DEFAULT_LIVE_MODE,
  renderWorkVoiceGuide,
  segmentEvidenceRefs, renderWorkCharacterEvolutions,
} = local;

beforeEach(() => {
  tempRoot = mkdtempSync(join(tmpdir(), 'wr-test-'));
});

afterEach(() => {
  if (tempRoot && existsSync(tempRoot)) rmSync(tempRoot, { recursive: true, force: true });
  // Always restore real timers — without this, a thrown assertion inside a
  // useFakeTimers() block could leave subsequent tests running under fake
  // timers and silently flake (timeouts/Date.now stuck at the system time).
  vi.useRealTimers();
});

describe('text utilities', () => {
  it('countWords ignores leading/trailing whitespace and collapses runs', () => {
    expect(countWords('')).toBe(0);
    expect(countWords('   ')).toBe(0);
    expect(countWords('one')).toBe(1);
    expect(countWords('one two\nthree\tfour')).toBe(4);
    expect(countWords('  hello   world  ')).toBe(2);
  });

  it('contentHash is deterministic and changes when content changes', () => {
    const a = contentHash('hello');
    const b = contentHash('hello');
    const c = contentHash('hello!');
    expect(a).toBe(b);
    expect(a).not.toBe(c);
    expect(a).toMatch(/^[0-9a-f]{64}$/);
  });

  it('buildSegmentIndex returns single segment for body with no headings', () => {
    const idx = buildSegmentIndex('Some prose with no headings.');
    expect(idx).toHaveLength(1);
    expect(idx[0]).toMatchObject({ kind: 'paragraph', wordCount: 5 });
  });

  it('buildSegmentIndex splits on # / ## / ### (### collapses to scene)', () => {
    const text = '# Chapter 1\nProse here.\n## Scene A\nMore prose.\n### Beat 1\nA beat.';
    const idx = buildSegmentIndex(text);
    expect(idx.map((s) => s.kind)).toEqual(['chapter', 'scene', 'scene']);
    expect(idx.map((s) => s.heading)).toEqual(['Chapter 1', 'Scene A', 'Beat 1']);
    expect(idx.map((s) => s.id)).toEqual(['seg-001', 'seg-002', 'seg-003']);
  });

  it('buildSegmentIndex emits a preamble segment for content before the first heading', () => {
    const text = 'Preamble text.\n# Chapter 1\nBody.';
    const idx = buildSegmentIndex(text);
    expect(idx[0].heading).toBe('(preamble)');
    expect(idx[1].heading).toBe('Chapter 1');
  });
});

describe('folder CRUD', () => {
  it('creates and lists folders', async () => {
    const folder = await createFolder({ name: 'Novels' });
    expect(folder.id).toMatch(/^wr-folder-/);
    expect(folder.name).toBe('Novels');

    const all = await listFolders();
    expect(all).toHaveLength(1);
    expect(all[0].name).toBe('Novels');
  });

  it('rejects creating a folder with a missing parent', async () => {
    await expect(createFolder({ name: 'Child', parentId: 'wr-folder-missing' }))
      .rejects.toThrow(/not found/i);
  });

  it('refuses to delete a folder containing works', async () => {
    const folder = await createFolder({ name: 'Drafts' });
    await createWork({ folderId: folder.id, title: 'Story 1' });
    await expect(deleteFolder(folder.id)).rejects.toThrow(/not empty/i);
  });

  it('deletes an empty folder', async () => {
    const folder = await createFolder({ name: 'Empty' });
    const result = await deleteFolder(folder.id);
    expect(result.ok).toBe(true);
    expect(await listFolders()).toHaveLength(0);
  });
});

describe('work CRUD', () => {
  it('creates a work with an empty active draft', async () => {
    const work = await createWork({ title: 'My Novel', kind: 'novel' });
    expect(work.id).toMatch(/^wr-work-/);
    expect(work.activeDraftVersionId).toMatch(/^wr-draft-/);
    expect(work.drafts).toHaveLength(1);
    expect(work.drafts[0].wordCount).toBe(0);
    expect(work.kind).toBe('novel');
    expect(work.status).toBe('drafting');
  });

  it('rejects unknown kinds', async () => {
    await expect(createWork({ title: 'Bad', kind: 'manifesto' }))
      .rejects.toThrow(/Invalid kind/i);
  });

  it('lists works ordered by updatedAt descending', async () => {
    // Drive nowIso() deterministically — the previous version slept 5ms between
    // creates which can collapse to the same timestamp on slow/coarse-clock CI.
    // Vitest's setSystemTime advances `new Date()` (which nowIso uses).
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));

    const a = await createWork({ title: 'First' });
    vi.setSystemTime(new Date('2026-01-01T00:00:01.000Z'));
    const b = await createWork({ title: 'Second' });
    vi.setSystemTime(new Date('2026-01-01T00:00:02.000Z'));
    await updateWork(a.id, { title: 'First Updated' });

    const list = await listWorks();
    expect(list[0].id).toBe(a.id); // most recently touched
    expect(list[1].id).toBe(b.id);
    // Note: afterEach() also calls useRealTimers() as a safety net.
  });

  it('updateWork patches allowed fields and rejects invalid status', async () => {
    const work = await createWork({ title: 'Test' });
    const updated = await updateWork(work.id, { status: 'revision', title: 'Renamed' });
    expect(updated.status).toBe('revision');
    expect(updated.title).toBe('Renamed');
    await expect(updateWork(work.id, { status: 'invalid-status' }))
      .rejects.toThrow(/Invalid status/i);
  });

  it('updateWork rejects whitespace-only titles', async () => {
    const work = await createWork({ title: 'Keep' });
    await expect(updateWork(work.id, { title: '   ' })).rejects.toThrow(/title required/i);
    // Original title preserved on the persisted manifest
    const reloaded = await getWork(work.id);
    expect(reloaded.title).toBe('Keep');
  });

  it('updateWork sanitizes and stores voice exemplars, and renders the voice guide (#2179)', async () => {
    const work = await createWork({ title: 'Voiced' });
    // renderWorkVoiceGuide is empty until exemplars are set.
    expect(renderWorkVoiceGuide(await getWork(work.id))).toBe('');

    const updated = await updateWork(work.id, {
      voiceExemplars: [
        { passage: 'She counted the exits, then the lies.', note: 'terse interiority' },
        { passage: '   ' }, // dropped: no usable passage
      ],
      voiceAntiExemplars: [
        { passage: 'The gossamer light danced upon the ancient stones of yore.', note: 'too ornate' },
      ],
    });
    expect(updated.voiceExemplars).toHaveLength(1);
    expect(updated.voiceExemplars[0]).toEqual({ passage: 'She counted the exits, then the lies.', note: 'terse interiority' });
    expect(updated.voiceAntiExemplars).toHaveLength(1);

    const guide = renderWorkVoiceGuide(await getWork(work.id));
    expect(guide).toContain('MATCH this voice');
    expect(guide).toContain('She counted the exits, then the lies.');
    expect(guide).toContain('NEVER drift toward this');
    expect(guide).toContain('too ornate');

    // An explicit empty array clears the list; an absent key leaves it untouched.
    const cleared = await updateWork(work.id, { voiceExemplars: [] });
    expect(cleared.voiceExemplars).toEqual([]);
    expect(cleared.voiceAntiExemplars).toHaveLength(1); // untouched
  });

  it('updateWork rejects unknown folderId and accepts null', async () => {
    const work = await createWork({ title: 'Filed' });
    await expect(updateWork(work.id, { folderId: 'wr-folder-does-not-exist' }))
      .rejects.toThrow(/Folder not found/i);
    // null is valid — it unfiles the work from any folder
    const unfiled = await updateWork(work.id, { folderId: null });
    expect(unfiled.folderId).toBeNull();
  });

  it('deleteWork removes the work directory', async () => {
    const work = await createWork({ title: 'To Delete' });
    await deleteWork(work.id);
    await expect(getWork(work.id)).rejects.toThrow(/not found/i);
    expect(await listWorks()).toHaveLength(0);
  });

  it('countWorks excludes tombstones and agrees with listWorks().length', async () => {
    // countWorks is the cheap tally the character skill registry reads instead of
    // rebuilding every work's manifest + drafts[] for a `.length` (#2729). Pin it
    // against listWorks so the two can never disagree — deleteWork soft-deletes
    // (the tombstone stays on disk so the deletion federates), so a count that
    // read the work directories alone would keep counting a deleted work forever.
    expect(await countWorks()).toBe(0);

    await createWork({ title: 'Kept' });
    const doomed = await createWork({ title: 'Doomed' });
    expect(await countWorks()).toBe(2);
    expect(await countWorks()).toBe((await listWorks()).length);

    await deleteWork(doomed.id);
    expect(await countWorks()).toBe(1);
    expect(await countWorks()).toBe((await listWorks()).length);
  });
});

describe('draft body and versioning', () => {
  it('saveDraftBody persists text and updates word count + segment index', async () => {
    const work = await createWork({ title: 'Story' });
    const text = '# Chapter 1\nOnce upon a time, a cat learned to fly.';
    const { manifest, body } = await saveDraftBody(work.id, text);
    expect(body).toBe(text);
    const active = manifest.drafts.find((d) => d.id === manifest.activeDraftVersionId);
    expect(active.wordCount).toBe(countWords(text));
    expect(active.segmentIndex).toHaveLength(1);
    expect(active.segmentIndex[0].heading).toBe('Chapter 1');
    expect(active.contentHash).toBe(contentHash(text));
  });

  it('saveDraftBody round-trips through getWorkWithBody', async () => {
    const work = await createWork({ title: 'Round Trip' });
    await saveDraftBody(work.id, 'Body text v1.');
    const { body } = await getWorkWithBody(work.id);
    expect(body).toBe('Body text v1.');
  });

  it('saveDraftBody stores referencedIngredientIds when provided; absence preserves the prior snapshot', async () => {
    const work = await createWork({ title: 'Refs' });
    // Present array → stored on the active draft meta.
    const { manifest: m1 } = await saveDraftBody(work.id, 'Mira appears.', {
      referencedIngredientIds: ['cat-chr-mira'],
    });
    const a1 = m1.drafts.find((d) => d.id === m1.activeDraftVersionId);
    expect(a1.referencedIngredientIds).toEqual(['cat-chr-mira']);

    // Field omitted → the prior reference snapshot must NOT be wiped.
    const { manifest: m2 } = await saveDraftBody(work.id, 'Mira appears again.');
    const a2 = m2.drafts.find((d) => d.id === m2.activeDraftVersionId);
    expect(a2.referencedIngredientIds).toEqual(['cat-chr-mira']);

    // Empty array → an intentional clear (prose no longer mentions anyone).
    const { manifest: m3 } = await saveDraftBody(work.id, 'Nobody here.', {
      referencedIngredientIds: [],
    });
    const a3 = m3.drafts.find((d) => d.id === m3.activeDraftVersionId);
    expect(a3.referencedIngredientIds).toEqual([]);
  });

  it('snapshotDraft creates a new version that mirrors the current body', async () => {
    const work = await createWork({ title: 'Versioned' });
    await saveDraftBody(work.id, 'First pass.');
    const after = await snapshotDraft(work.id);
    expect(after.drafts).toHaveLength(2);
    expect(after.activeDraftVersionId).toBe(after.drafts[1].id);
    expect(after.drafts[1].wordCount).toBe(2);
    expect(after.drafts[1].createdFromVersionId).toBe(after.drafts[0].id);
  });

  it('snapshotDraft carries the source draft referencedIngredientIds forward (same body, same refs)', async () => {
    const work = await createWork({ title: 'Versioned Refs' });
    await saveDraftBody(work.id, 'Mira appears.', { referencedIngredientIds: ['cat-chr-mira'] });
    const after = await snapshotDraft(work.id);
    // Source version keeps its refs; the new active draft inherits them since
    // it copies the body verbatim (so its chips aren't blank until re-saved).
    expect(after.drafts[0].referencedIngredientIds).toEqual(['cat-chr-mira']);
    expect(after.drafts[1].referencedIngredientIds).toEqual(['cat-chr-mira']);
  });

  it('setActiveDraft switches the pointer; subsequent saves write the new version', async () => {
    const work = await createWork({ title: 'Switch' });
    const firstId = work.activeDraftVersionId;
    await saveDraftBody(work.id, 'Version 1.');
    const snapped = await snapshotDraft(work.id);
    const secondId = snapped.activeDraftVersionId;
    await saveDraftBody(work.id, 'Version 2.');
    // Switching back should not erase v1
    const switched = await setActiveDraft(work.id, firstId);
    expect(switched.activeDraftVersionId).toBe(firstId);
    const v1 = await getDraftBody(work.id, firstId);
    const v2 = await getDraftBody(work.id, secondId);
    expect(v1).toBe('Version 1.');
    expect(v2).toBe('Version 2.');
  });

  it('writes the active draft body to disk on the expected path', async () => {
    const work = await createWork({ title: 'On Disk' });
    const draftFilePath = join(tempRoot, 'writers-room', 'works', work.id, 'drafts', `${work.activeDraftVersionId}.md`);
    expect(existsSync(draftFilePath)).toBe(true);
    expect(readFileSync(draftFilePath, 'utf-8')).toBe('');

    await saveDraftBody(work.id, 'persisted prose');
    expect(readFileSync(draftFilePath, 'utf-8')).toBe('persisted prose');
  });

  it('snapshotDraft uses the explicit label argument when provided', async () => {
    const work = await createWork({ title: 'Labeled' });
    await saveDraftBody(work.id, 'first.');
    const after = await snapshotDraft(work.id, { label: 'Pre-edit' });
    const newest = after.drafts[after.drafts.length - 1];
    expect(newest.label).toBe('Pre-edit');
  });

  it('snapshotDraft preserves prior versions on disk after multiple snapshots', async () => {
    const work = await createWork({ title: 'Round Trip' });
    await saveDraftBody(work.id, 'V1 text.');
    const afterV2 = await snapshotDraft(work.id);
    await saveDraftBody(work.id, 'V2 text.');
    const afterV3 = await snapshotDraft(work.id);
    await saveDraftBody(work.id, 'V3 text.');

    const v1Id = afterV2.drafts[0].id;
    const v2Id = afterV3.drafts[1].id;
    const v3Id = afterV3.activeDraftVersionId;
    expect(await getDraftBody(work.id, v1Id)).toBe('V1 text.');
    expect(await getDraftBody(work.id, v2Id)).toBe('V2 text.');
    expect(await getDraftBody(work.id, v3Id)).toBe('V3 text.');
  });
});

describe('exercise sessions', () => {
  it('creates a running exercise tied to a work', async () => {
    const work = await createWork({ title: 'Exercise Target' });
    const ex = await createExercise({ workId: work.id, prompt: 'free-write', startingWords: 100 });
    expect(ex.id).toMatch(/^wr-ex-/);
    expect(ex.status).toBe('running');
    expect(ex.workId).toBe(work.id);
    expect(ex.durationSeconds).toBe(600);
  });

  it('clamps duration to [60, 3600] seconds', async () => {
    const tooShort = await createExercise({ durationSeconds: 10 });
    expect(tooShort.durationSeconds).toBe(60);
    const tooLong = await createExercise({ durationSeconds: 99999 });
    expect(tooLong.durationSeconds).toBe(3600);
  });

  it('rejects creating an exercise tied to a missing work', async () => {
    await expect(createExercise({ workId: 'wr-work-deadbeef-1234-5678-aaaa-bbbbccccdddd' }))
      .rejects.toThrow(/not found/i);
  });

  it('finishExercise computes wordsAdded delta and seals the session', async () => {
    const start = Date.now();
    const ex = await createExercise({ startingWords: 50 });
    const finished = await finishExercise(ex.id, { endingWords: 175 });
    expect(finished.status).toBe('finished');
    expect(finished.wordsAdded).toBe(125);
    const finishedAtMs = Date.parse(finished.finishedAt);
    expect(finishedAtMs).toBeGreaterThanOrEqual(start);
    expect(finishedAtMs).toBeLessThanOrEqual(Date.now() + 1);

    // Finishing or discarding a settled session should be rejected.
    await expect(finishExercise(ex.id, { endingWords: 200 }))
      .rejects.toThrow(/already settled/i);
    await expect(discardExercise(ex.id))
      .rejects.toThrow(/already settled/i);
  });

  it('finishExercise clamps wordsAdded at 0 and defaults missing endingWords', async () => {
    // User backspaced past the starting word count → delta should not go negative.
    const ex1 = await createExercise({ startingWords: 200 });
    const finished1 = await finishExercise(ex1.id, { endingWords: 150 });
    expect(finished1.wordsAdded).toBe(0);
    expect(finished1.endingWords).toBe(150);

    // Caller forgot to send endingWords → fall back to startingWords (delta 0),
    // not 0 (which would have produced a -200 delta on the previous version).
    const ex2 = await createExercise({ startingWords: 200 });
    const finished2 = await finishExercise(ex2.id, {});
    expect(finished2.wordsAdded).toBe(0);
    expect(finished2.endingWords).toBe(200);
  });

  it('promoteExercise appends trimmed sprint text and preserves the active draft references', async () => {
    const work = await createWork({ title: 'Promotion' });
    await saveDraftBody(work.id, 'Existing draft', { referencedIngredientIds: ['cat-char-1'] });
    const exercise = await createExercise({ workId: work.id });
    await finishExercise(exercise.id, { appendedText: '  Sprint ending  ' });

    const result = await promoteExercise(exercise.id);
    expect(result.work.activeDraftBody).toBe('Existing draft\n\nSprint ending\n');
    expect(result.work.drafts[0].wordCount).toBe(4);
    expect(result.work.drafts[0].referencedIngredientIds).toEqual(['cat-char-1']);
    expect(result.exercise.promotedAt).toBeTruthy();
    expect(result.exercise.promotedDraftVersionId).toBe(work.activeDraftVersionId);
    await expect(promoteExercise(exercise.id)).rejects.toThrow(/already promoted/i);
  });

  it('promoteExercise rejects unfinished, standalone, and empty exercises', async () => {
    const work = await createWork({ title: 'Promotion guards' });
    const running = await createExercise({ workId: work.id });
    await expect(promoteExercise(running.id)).rejects.toThrow(/finished/i);

    const standalone = await createExercise({});
    await finishExercise(standalone.id, { appendedText: 'Text' });
    await expect(promoteExercise(standalone.id)).rejects.toThrow(/linked/i);

    const empty = await createExercise({ workId: work.id });
    await finishExercise(empty.id, { appendedText: '   ' });
    await expect(promoteExercise(empty.id)).rejects.toThrow(/no text/i);
    await expect(promoteExercise('wr-ex-missing')).rejects.toThrow(/not found/i);
  });

  it('discardExercise marks the session as discarded', async () => {
    const ex = await createExercise({});
    const discarded = await discardExercise(ex.id);
    expect(discarded.status).toBe('discarded');
  });

  it('listExercises filters by workId', async () => {
    const w1 = await createWork({ title: 'W1' });
    const w2 = await createWork({ title: 'W2' });
    await createExercise({ workId: w1.id });
    await createExercise({ workId: w2.id });
    await createExercise({});

    expect(await listExercises({ workId: w1.id })).toHaveLength(1);
    expect(await listExercises({ workId: w2.id })).toHaveLength(1);
    expect(await listExercises()).toHaveLength(3);
  });
});

describe('live mode (Phase 5)', () => {
  it('resolveLiveMode falls back to defaults for a work that never opted in', async () => {
    const work = await createWork({ title: 'Fresh' });
    const live = resolveLiveMode(work);
    expect(live.enabled).toBe(false);
    expect(live.debounceMs).toBe(DEFAULT_LIVE_MODE.debounceMs);
    expect(live.dailyCallBudget).toBe(DEFAULT_LIVE_MODE.dailyCallBudget);
    expect(live.dailyRenderBudget).toBe(DEFAULT_LIVE_MODE.dailyRenderBudget);
    expect(live.usage).toEqual({ date: null, count: 0 });
    expect(live.renderUsage).toEqual({ date: null, count: 0 });
  });

  it('updateWork partial-merges liveMode knobs without clobbering siblings', async () => {
    const work = await createWork({ title: 'Live' });
    const a = await updateWork(work.id, { liveMode: { enabled: true } });
    expect(a.liveMode.enabled).toBe(true);
    expect(a.liveMode.debounceMs).toBe(DEFAULT_LIVE_MODE.debounceMs);

    const b = await updateWork(work.id, { liveMode: { debounceMs: 5000 } });
    expect(b.liveMode.enabled).toBe(true); // preserved
    expect(b.liveMode.debounceMs).toBe(5000);

    // The distinct render budget merges independently of the suggest budget.
    const c = await updateWork(work.id, { liveMode: { dailyRenderBudget: 7 } });
    expect(c.liveMode.dailyRenderBudget).toBe(7);
    expect(c.liveMode.dailyCallBudget).toBe(DEFAULT_LIVE_MODE.dailyCallBudget); // preserved
    expect(c.liveMode.enabled).toBe(true); // preserved
  });

  it('updateWork strips client-supplied usage counters (both server-owned)', async () => {
    const work = await createWork({ title: 'Guard' });
    await recordLiveModeUsage(work.id); // suggest count -> 1 today
    await recordLiveModeRenderUsage(work.id); // render count -> 1 today
    const tampered = await updateWork(work.id, {
      liveMode: {
        enabled: true,
        usage: { date: '1999-01-01', count: 9999 },
        renderUsage: { date: '1999-01-01', count: 9999 },
      },
    });
    // Both crafted counters are dropped — the real counters are preserved.
    expect(tampered.liveMode.usage.count).toBe(1);
    expect(tampered.liveMode.usage.date).not.toBe('1999-01-01');
    expect(tampered.liveMode.renderUsage.count).toBe(1);
    expect(tampered.liveMode.renderUsage.date).not.toBe('1999-01-01');
  });

  it('recordLiveModeUsage increments within a day and rolls over on a new UTC day', async () => {
    const work = await createWork({ title: 'Budget' });
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2026-06-03T10:00:00Z'));
    const u1 = await recordLiveModeUsage(work.id);
    expect(u1.usage).toEqual({ date: '2026-06-03', count: 1 });
    const u2 = await recordLiveModeUsage(work.id);
    expect(u2.usage).toEqual({ date: '2026-06-03', count: 2 });

    // New UTC day resets the counter to 1.
    vi.setSystemTime(new Date('2026-06-04T00:05:00Z'));
    const u3 = await recordLiveModeUsage(work.id);
    expect(u3.usage).toEqual({ date: '2026-06-04', count: 1 });
  });

  it('recordLiveModeRenderUsage bumps a counter independent of the suggest counter', async () => {
    const work = await createWork({ title: 'RenderBudget' });
    vi.useFakeTimers();
    vi.setSystemTime(new Date('2026-06-03T10:00:00Z'));
    await recordLiveModeUsage(work.id); // suggest -> 1

    const r1 = await recordLiveModeRenderUsage(work.id);
    expect(r1.renderUsage).toEqual({ date: '2026-06-03', count: 1 });
    expect(r1.usage).toEqual({ date: '2026-06-03', count: 1 }); // suggest untouched
    const r2 = await recordLiveModeRenderUsage(work.id);
    expect(r2.renderUsage).toEqual({ date: '2026-06-03', count: 2 });

    // New UTC day resets the render counter to 1.
    vi.setSystemTime(new Date('2026-06-04T00:05:00Z'));
    const r3 = await recordLiveModeRenderUsage(work.id);
    expect(r3.renderUsage).toEqual({ date: '2026-06-04', count: 1 });
  });
});

// ---------------------------------------------------------------------------
// Retrospective five-stage evolution lens anchored to manuscript segments
// (#6445, epic #6418). Synthetic manuscripts only — never a real instance
// record.
// ---------------------------------------------------------------------------

// A short two-chapter manuscript. `# Ledger` is seg-001, `# Harbor` is seg-002.
const MANUSCRIPT = [
  '# Ledger',
  '',
  'She balanced the books before she balanced anything else.',
  '',
  '# Harbor',
  '',
  'She let the boat go without counting what it cost her.',
  '',
].join('\n');

const lensCharacter = (name, outcome, evidence, extra = {}) => ({
  name,
  evolution: {
    outcome,
    stages: [{
      stageId: 'final-proof',
      characterChoice: 'She lets the boat go.',
      evidence,
      ...extra,
    }],
  },
});

describe('retrospective evolution-lens anchors (#6445)', () => {
  const segments = () => buildSegmentIndex(MANUSCRIPT);

  it('maps every segment id to the prose it currently covers', () => {
    const { segmentIds } = segmentEvidenceRefs(segments(), MANUSCRIPT);
    expect([...segmentIds.keys()]).toEqual(['seg-001', 'seg-002']);
    expect(segmentIds.get('seg-002')).toContain('let the boat go');
    expect(segmentIds.get('seg-001')).not.toContain('let the boat go');
  });

  it('renders nothing at all when no character carries a lens', () => {
    const cast = [{ name: 'Wren Calloway', lie: 'I only matter while I am useful.' }];
    expect(renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT })).toBeNull();
    expect(renderWorkCharacterEvolutions([], { segmentIndex: segments(), text: MANUSCRIPT })).toBeNull();
  });

  it('annotates a resolving, quote-matched anchor as anchored', () => {
    const cast = [lensCharacter('Wren Calloway', 'full-change', {
      segmentId: 'seg-002', anchorQuote: 'let the boat go',
    })];
    const block = renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT });
    expect(block).toContain('declared outcome: full-change');
    expect(block).toContain('segment seg-002');
    expect(block).toContain('[anchored]');
  });

  it('marks an anchor stale — keeping the authored prose — once its segment is gone', () => {
    const shortened = '# Ledger\n\nShe balanced the books before she balanced anything else.\n';
    const cast = [lensCharacter('Wren Calloway', 'full-change', {
      segmentId: 'seg-002', anchorQuote: 'let the boat go',
    })];
    const block = renderWorkCharacterEvolutions(cast, {
      segmentIndex: buildSegmentIndex(shortened), text: shortened,
    });
    expect(block).toContain('[stale]');
    expect(block).not.toContain('[anchored]');
    // Preserved, never silently dropped: the prose and the re-anchoring quote
    // both survive so the writer can re-point the stage.
    expect(block).toContain('choice: She lets the boat go.');
    expect(block).toContain('let the boat go');
  });

  it('marks an anchor stale when renumbering leaves the id on a different passage', () => {
    // A new opening chapter renumbers everything below it: the old `seg-002`
    // still EXISTS, and now covers prose the stage was never written for. The
    // quote is what catches it — an existence check alone would read "anchored".
    const expanded = `# Prologue\n\nThe harbor master kept his own ledger.\n\n${MANUSCRIPT}`;
    const cast = [lensCharacter('Wren Calloway', 'full-change', {
      segmentId: 'seg-002', anchorQuote: 'let the boat go',
    })];
    const block = renderWorkCharacterEvolutions(cast, {
      segmentIndex: buildSegmentIndex(expanded), text: expanded,
    });
    expect(block).toContain('[stale]');
    expect(block).not.toContain('[anchored]');
  });

  it('reports an unquoted anchor as resolved but never invents a quote check', () => {
    const cast = [lensCharacter('Wren Calloway', 'partial-open', { segmentId: 'seg-001' })];
    const block = renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT });
    expect(block).toContain('[anchored]');
    expect(block).not.toContain('quote');
  });

  it('reports a quote with no segment as unverified rather than proven', () => {
    const cast = [lensCharacter('Wren Calloway', 'full-change', { anchorQuote: 'let the boat go' })];
    const block = renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT });
    expect(block).toContain('[unverified]');
    expect(block).not.toContain('[anchored]');
  });

  it('carries all four declared outcomes verbatim, including the two that are endings', () => {
    const cast = [
      lensCharacter('Wren Calloway', 'full-change', { segmentId: 'seg-002', anchorQuote: 'let the boat go' }),
      lensCharacter('Dov Marchetti', 'tragic-refusal', { segmentId: 'seg-001', anchorQuote: 'balanced the books' }),
      lensCharacter('Ilsa Renn', 'flat-testing', { segmentId: 'seg-001', anchorQuote: 'balanced the books' }),
      lensCharacter('Peto Vane', 'partial-open', { segmentId: 'seg-002', anchorQuote: 'let the boat go' }),
    ];
    const block = renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT });
    for (const outcome of ['full-change', 'tragic-refusal', 'flat-testing', 'partial-open']) {
      expect(block).toContain(`declared outcome: ${outcome}`);
    }
    // One block per character, each nested under its own name.
    for (const name of ['Wren Calloway', 'Dov Marchetti', 'Ilsa Renn', 'Peto Vane']) {
      expect(block).toContain(`- ${name}`);
    }
  });

  it('renders an undeclared lens as undeclared rather than assuming an outcome', () => {
    const cast = [lensCharacter('Wren Calloway', null, { segmentId: 'seg-002', anchorQuote: 'let the boat go' })];
    const block = renderWorkCharacterEvolutions(cast, { segmentIndex: segments(), text: MANUSCRIPT });
    expect(block).toContain('declared outcome: undeclared');
  });

  it('tolerates a work with no draft body at all', () => {
    const cast = [lensCharacter('Wren Calloway', 'full-change', { segmentId: 'seg-001' })];
    const block = renderWorkCharacterEvolutions(cast, {});
    // Nothing to resolve against — unverified, never anchored.
    expect(block).toContain('[unverified]');
  });
});


describe('library snapshot pages', () => {
  it('holds membership across equal timestamps, edits, inserts and deletions; expires with restart guidance', async () => {
    vi.useFakeTimers({ toFake: ['Date'] });
    vi.setSystemTime(new Date('2026-01-01T00:00:00Z'));
    const created = await Promise.all(['A', 'B', 'C', 'D'].map(title => createWork({ title, kind: 'short-story' })));
    const ordered = created.map(work => work.id).sort();
    const first = await local.listWorksPage({ limit: 2 });
    expect(first.items.map(work => work.id)).toEqual(ordered.slice(0, 2));
    vi.setSystemTime(new Date('2026-01-01T00:01:00Z'));
    await updateWork(ordered[3], { title: 'Edited' });
    await deleteWork(ordered[2]);
    await createWork({ title: 'New arrival', kind: 'short-story' });
    const second = await local.listWorksPage({ limit: 2, cursor: first.nextCursor });
    expect(second.items.map(work => work.id)).toEqual([ordered[3]]);
    expect(second.items[0].title).toBe('Edited');
    expect(second.total).toBe(4);
    expect(second.nextCursor).toBeNull();
    vi.setSystemTime(new Date('2026-01-01T00:06:00Z'));
    await expect(local.listWorksPage({ cursor: first.nextCursor })).rejects.toMatchObject({ code: 'CURSOR_EXPIRED' });
    expect((await local.listWorksPage({ limit: 100 })).items).toHaveLength(4);
  });
});