Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript
39.6 KB
Raw Blame
// v0.41 T5+T6 — extract_atoms + synthesize_concepts minimal-viable bodies.
//
// Tests the LLM-driven extraction + synthesis paths with a stubbed
// chat function so no real Haiku/Sonnet calls fire in CI. Pins:
//   - extract_atoms parses Haiku JSON output, writes atom-typed pages
//   - parseAtomsResponse tolerates markdown fences + trailing prose
//   - extract_atoms skips invalid atom_type values
//   - extract_atoms budget cap halts mid-run
//   - synthesize_concepts groups atoms by concept frontmatter ref
//   - tier assignment by count (T1 ≥10, T2 ≥5, T3 ≥2)
//   - T1/T2 use LLM narrative; T3 falls back deterministic
//   - dry-run mode counts but doesn't write

import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
import { PGLiteEngine } from '../../src/core/pglite-engine.ts';
import { runPhaseExtractAtoms, parseAtomsResponse } from '../../src/core/cycle/extract-atoms.ts';
import { runPhaseSynthesizeConcepts } from '../../src/core/cycle/synthesize-concepts.ts';
import { resetPgliteState } from '../helpers/reset-pglite.ts';
import type { ChatResult, ChatOpts } from '../../src/core/ai/gateway.ts';
import { canonicalLookup } from '../../src/core/model-pricing.ts';

let engine: PGLiteEngine;

beforeAll(async () => {
  engine = new PGLiteEngine();
  await engine.connect({});
  await engine.initSchema();
}, 60000);

afterAll(async () => {
  await engine.disconnect();
});

beforeEach(async () => {
  await resetPgliteState(engine);
});

function stubChat(text: string, opts: { input_tokens?: number; output_tokens?: number } = {}): (o: ChatOpts) => Promise<ChatResult> {
  return async (_o: ChatOpts) => ({
    text,
    blocks: [{ type: 'text', text }],
    stopReason: 'end',
    usage: {
      input_tokens: opts.input_tokens ?? 500,
      output_tokens: opts.output_tokens ?? 200,
      cache_read_tokens: 0,
      cache_creation_tokens: 0,
    },
    model: 'anthropic:claude-haiku-4-5',
    providerId: 'anthropic',
  });
}

describe('v0.41 T5: parseAtomsResponse', () => {
  test('parses well-formed JSON array', () => {
    const raw = `[{"title":"Test","atom_type":"insight","body":"body text"}]`;
    const atoms = parseAtomsResponse(raw);
    expect(atoms.length).toBe(1);
    expect(atoms[0].title).toBe('Test');
    expect(atoms[0].atom_type).toBe('insight');
  });

  test('strips markdown code fences', () => {
    const raw = '```json\n[{"title":"T","atom_type":"quote","body":"b"}]\n```';
    expect(parseAtomsResponse(raw).length).toBe(1);
  });

  test('tolerates trailing prose after JSON', () => {
    const raw = `[{"title":"T","atom_type":"framework","body":"b"}]\n\nThanks!`;
    expect(parseAtomsResponse(raw).length).toBe(1);
  });

  test('rejects atoms with invalid atom_type', () => {
    const raw = `[{"title":"T","atom_type":"made_up_type","body":"b"}]`;
    expect(parseAtomsResponse(raw).length).toBe(0);
  });

  test('rejects atoms missing required fields', () => {
    const raw = `[{"title":"T","atom_type":"insight"}]`; // no body
    expect(parseAtomsResponse(raw).length).toBe(0);
  });

  test('returns [] on garbage input', () => {
    expect(parseAtomsResponse('not json')).toEqual([]);
    expect(parseAtomsResponse('')).toEqual([]);
  });

  test('accepts all 11 declared atom_type values', () => {
    const types = ['insight', 'anecdote', 'quote', 'framework', 'statistic',
                   'story_angle', 'strategy_angle', 'strategy', 'endorsement',
                   'critique', 'collection'];
    for (const t of types) {
      const raw = `[{"title":"x","atom_type":"${t}","body":"b"}]`;
      const atoms = parseAtomsResponse(raw);
      expect(atoms.length).toBe(1);
      expect(atoms[0].atom_type as string).toBe(t);
    }
  });

  test('clamps virality_score to [0, 100]', () => {
    expect(parseAtomsResponse(`[{"title":"a","atom_type":"insight","body":"b","virality_score":150}]`)[0].virality_score).toBeUndefined();
    expect(parseAtomsResponse(`[{"title":"a","atom_type":"insight","body":"b","virality_score":-5}]`)[0].virality_score).toBeUndefined();
    expect(parseAtomsResponse(`[{"title":"a","atom_type":"insight","body":"b","virality_score":75}]`)[0].virality_score).toBe(75);
  });
});

describe('v0.41 T5: runPhaseExtractAtoms via stubbed chat', () => {
  test('no-op when no transcripts AND no pages provided', async () => {
    // v0.41.2.1: _pages:[] suppresses page-discovery so this matches the
    // pre-v0.41.2.1 "transcript-only no-op" path. Reason changed from
    // 'no_transcripts' to 'no_work' to reflect the dual-source design.
    const result = await runPhaseExtractAtoms(engine, { _transcripts: [], _pages: [] });
    expect(result.status).toBe('skipped');
    expect(result.details?.reason).toBe('no_work');
  });

  test('extracts atoms from transcript via stub chat', async () => {
    const chat = stubChat(`[
      {"title":"Renders vs physical proof","atom_type":"insight","body":"Enterprise buyers want tangible prototypes."},
      {"title":"Founder lesson","atom_type":"anecdote","body":"Story about a founder."}
    ]`);
    const result = await runPhaseExtractAtoms(engine, {
      _transcripts: [{ filePath: '/fake/meeting.txt', content: 'content', contentHash: 'abc123def' }],
      _pages: [], // suppress page discovery — transcript-only test
      _chat: chat,
    });
    expect(result.status).toBe('ok');
    expect(result.details?.atoms_extracted).toBe(2);
    expect(result.details?.transcripts_processed).toBe(1);

    // Verify pages were written
    const rows = await engine.executeRaw<{ slug: string; type: string }>(
      `SELECT slug, type FROM pages WHERE type = 'atom'`,
    );
    expect(rows.length).toBe(2);
  });

  test('dry-run counts but does NOT write', async () => {
    const chat = stubChat(`[{"title":"x","atom_type":"insight","body":"b"}]`);
    const result = await runPhaseExtractAtoms(engine, {
      _transcripts: [{ filePath: '/x.txt', content: 'c', contentHash: 'h' }],
      _pages: [],
      _chat: chat,
      dryRun: true,
    });
    expect(result.details?.atoms_extracted).toBe(1);
    expect(result.details?.dry_run).toBe(true);
    const rows = await engine.executeRaw<{ count: number }>(
      `SELECT COUNT(*)::int AS count FROM pages WHERE type = 'atom'`,
    );
    expect(rows[0].count).toBe(0);
  });

  test('failures tracked per-transcript without halting', async () => {
    let callCount = 0;
    const chat = async (_o: ChatOpts) => {
      callCount++;
      if (callCount === 1) throw new Error('rate limit');
      return {
        text: `[{"title":"t","atom_type":"insight","body":"b"}]`,
        blocks: [],
        stopReason: 'end' as const,
        usage: { input_tokens: 100, output_tokens: 50, cache_read_tokens: 0, cache_creation_tokens: 0 },
        model: 'anthropic:claude-haiku-4-5',
        providerId: 'anthropic',
      };
    };
    const result = await runPhaseExtractAtoms(engine, {
      _transcripts: [
        { filePath: '/a.txt', content: 'a', contentHash: 'ha' },
        { filePath: '/b.txt', content: 'b', contentHash: 'hb' },
      ],
      _pages: [],
      _chat: chat as typeof import('../../src/core/ai/gateway.ts').chat,
    });
    expect(result.status).toBe('warn');
    expect(result.details?.atoms_extracted).toBe(1);
    expect((result.details?.failures as unknown[]).length).toBe(1);
  });

  // issue #3218 — when EVERY item's chat() call throws (all-provider-failed),
  // `transcripts_processed`/`pages_processed` must stay 0 while `failures`
  // records one entry per item. This is the exact shape the
  // extract-atoms-drain wiring (`runExtractAtomsDrainForSource`) uses to
  // derive `providerFailure` (failures.length > 0 && itemsSucceeded === 0),
  // distinguishing a total outage from the partial-success case above.
  test('all items fail: transcripts_processed/pages_processed stay 0, every item recorded in failures', async () => {
    const chat = async (_o: ChatOpts): Promise<never> => {
      throw new Error('provider unavailable');
    };
    const result = await runPhaseExtractAtoms(engine, {
      _transcripts: [
        { filePath: '/a.txt', content: 'a', contentHash: 'ha' },
        { filePath: '/b.txt', content: 'b', contentHash: 'hb' },
      ],
      _pages: [],
      _chat: chat as typeof import('../../src/core/ai/gateway.ts').chat,
    });
    expect(result.status).toBe('warn');
    expect(result.details?.atoms_extracted).toBe(0);
    expect(result.details?.transcripts_processed).toBe(0);
    expect(result.details?.pages_processed).toBe(0);
    expect((result.details?.failures as unknown[]).length).toBe(2);
  });

  // v0.41.2.1 regression case (D9 #14 wording): with _pages:[] and same
  // _transcripts, all PRE-EXISTING PhaseResult.details fields match
  // pre-fix values byte-for-byte. The new fields (pages_processed,
  // pages_total, pages_skipped_budget, duplicates_skipped) exist but
  // are zeros. Closes the "transcript path silently regresses" risk.
  test('legacy transcript-only fields unchanged when _pages:[] (regression guard)', async () => {
    const chat = stubChat(`[{"title":"r","atom_type":"insight","body":"b"}]`);
    const result = await runPhaseExtractAtoms(engine, {
      _transcripts: [{ filePath: '/regression.txt', content: 'c', contentHash: 'rH' }],
      _pages: [],
      _chat: chat,
    });
    expect(result.status).toBe('ok');
    // Pre-existing fields — must keep their pre-fix values verbatim
    expect(result.details?.atoms_extracted).toBe(1);
    expect(result.details?.transcripts_processed).toBe(1);
    expect(result.details?.transcripts_total).toBe(1);
    expect(result.details?.transcripts_skipped_budget).toBe(0);
    expect(result.details?.failures).toEqual([]);
    expect(result.details?.budget_usd).toBe(0.3);
    expect(result.details?.source_id).toBe('default');
    expect(result.details?.dry_run).toBe(false);
    // New additive fields — zero when no page work
    expect(result.details?.pages_processed).toBe(0);
    expect(result.details?.pages_total).toBe(0);
    expect(result.details?.pages_skipped_budget).toBe(0);
    expect(result.details?.duplicates_skipped).toBe(0);
  });
});

describe('v0.41 T6: runPhaseSynthesizeConcepts via stubbed chat', () => {
  /** Persist injected atoms as pages: provenance edges need both endpoints
   *  (the batch JOIN drops absent slugs, and an all-dropped batch is a warn). */
  async function persistAtoms(atoms: Array<{ slug: string; title: string; body: string }>): Promise<void> {
    for (const a of atoms) {
      await engine.putPage(a.slug, { type: 'atom', title: a.title, compiled_truth: a.body, timeline: '' });
    }
  }

  test('no-op when no atoms have concept refs', async () => {
    const result = await runPhaseSynthesizeConcepts(engine, { _atoms: [] });
    expect(result.status).toBe('skipped');
    expect(result.details?.reason).toBe('no_atoms');
  });

  test('groups atoms by concept and assigns tier by count', async () => {
    const atoms: Array<{ slug: string; title: string; body: string; concept_refs: string[] }> = [];
    for (let i = 0; i < 12; i++) {
      atoms.push({
        slug: `atoms/2026-05-24/atom-${i}`,
        title: `Atom ${i}`,
        body: `Body of atom ${i}.`,
        concept_refs: ['ai-agents'],
      });
    }
    for (let i = 0; i < 6; i++) {
      atoms.push({
        slug: `atoms/2026-05-24/founder-${i}`,
        title: `Founder ${i}`,
        body: `Founder body ${i}.`,
        concept_refs: ['founder-psychology'],
      });
    }
    for (let i = 0; i < 3; i++) {
      atoms.push({
        slug: `atoms/2026-05-24/hw-${i}`,
        title: `HW ${i}`,
        body: `HW body ${i}.`,
        concept_refs: ['hardware-renaissance'],
      });
    }

    await persistAtoms(atoms);
    const chat = stubChat('AI agents are software factories.');
    const result = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, _chat: chat });
    expect(result.status).toBe('ok');
    expect(result.details?.concepts_written).toBe(3);
    const tiers = result.details?.tier_counts as Record<string, number>;
    expect(tiers.T1).toBe(1); // ai-agents (12)
    expect(tiers.T2).toBe(1); // founder-psychology (6)
    expect(tiers.T3).toBe(1); // hardware-renaissance (3)
  });

  test('atoms with no concept refs are filtered out', async () => {
    const atoms = [
      { slug: 's1', title: 't1', body: 'b1', concept_refs: [] },
      { slug: 's2', title: 't2', body: 'b2', concept_refs: [] },
    ];
    const result = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms });
    expect(result.status).toBe('skipped');
  });

  test('concept count below T3 threshold (2) is filtered out', async () => {
    const atoms = [{ slug: 's', title: 't', body: 'b', concept_refs: ['only-one-mention'] }];
    const result = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms });
    expect(result.status).toBe('skipped');
    expect(result.details?.reason).toBe('no_groups_above_threshold');
  });

  test('T3 concepts use deterministic narrative (no LLM call)', async () => {
    const atoms = [
      { slug: 'a1', title: 'A1', body: 'b1', concept_refs: ['theme'] },
      { slug: 'a2', title: 'A2', body: 'b2', concept_refs: ['theme'] },
    ];
    let chatCalled = false;
    const chat = async (_o: ChatOpts) => {
      chatCalled = true;
      return stubChat('should not be called')(_o);
    };
    const result = await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, _chat: chat as typeof import('../../src/core/ai/gateway.ts').chat });
    expect(chatCalled).toBe(false);
    expect((await engine.getPage('concepts/theme'))?.frontmatter.synthesis_mode).toBe('deterministic_tier');
    expect(result.details?.synthesis_mode_counts).toEqual({
      llm: 0,
      deterministic_tier: 1,
      budget_fallback: 0,
      error_fallback: 0,
    });
  });

  test('dry-run counts but does NOT write', async () => {
    const atoms = Array.from({ length: 6 }, (_, i) => ({
      slug: `s${i}`,
      title: `T${i}`,
      body: `b${i}`,
      concept_refs: ['theme'],
    }));
    const chat = stubChat('synthesized narrative');
    const result = await runPhaseSynthesizeConcepts(engine, {
      _atoms: atoms,
      _chat: chat,
      dryRun: true,
    });
    expect(result.details?.concepts_written).toBe(1);
    expect(result.details?.dry_run).toBe(true);
    const rows = await engine.executeRaw<{ count: number }>(
      `SELECT COUNT(*)::int AS count FROM pages WHERE type = 'concept' AND slug LIKE 'concepts/%'`,
    );
    expect(rows[0].count).toBe(0);
  });

  test('T1 concept gets LLM-synthesized narrative', async () => {
    const atoms = Array.from({ length: 12 }, (_, i) => ({
      slug: `a${i}`,
      title: `T${i}`,
      body: `b${i}`,
      concept_refs: ['theme'],
    }));
    const chat = stubChat('Custom synthesized narrative from LLM.');
    await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, _chat: chat });
    const rows = await engine.executeRaw<{ compiled_truth: string }>(
      `SELECT compiled_truth FROM pages WHERE slug = 'concepts/theme'`,
    );
    expect(rows[0].compiled_truth).toContain('Custom synthesized narrative');
  });

  test('prioritizes stronger concepts before spending the fixed LLM budget', async () => {
    const atoms = [
      ...Array.from({ length: 5 }, (_, i) => ({
        slug: `weak-${i}`,
        title: `Weak ${i}`,
        body: `Weak body ${i}`,
        concept_refs: ['weak-theme'],
      })),
      ...Array.from({ length: 10 }, (_, i) => ({
        slug: `strong-${i}`,
        title: `Strong ${i}`,
        body: `Strong body ${i}`,
        concept_refs: ['strong-theme'],
      })),
    ];
    const firstCalls: string[] = [];
    const firstChat = async (opts: ChatOpts) => {
      firstCalls.push(String(opts.messages[0]?.content));
      return stubChat('Strong model narrative.', {
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
      })(opts);
    };

    const first = await runPhaseSynthesizeConcepts(engine, {
      _atoms: atoms,
      _chat: firstChat as typeof import('../../src/core/ai/gateway.ts').chat,
    });
    expect(firstCalls).toHaveLength(1);
    expect(firstCalls[0]).toContain('Concept slug: strong-theme');
    expect((await engine.getPage('concepts/strong-theme'))?.frontmatter.synthesis_mode).toBe('llm');
    expect((await engine.getPage('concepts/weak-theme'))?.frontmatter.synthesis_mode).toBe('budget_fallback');
    expect(first.details?.synthesis_mode_counts).toEqual({
      llm: 1,
      deterministic_tier: 0,
      budget_fallback: 1,
      error_fallback: 0,
    });
  });

  test('marks LLM-error fallback output distinctly', async () => {
    const atoms = Array.from({ length: 5 }, (_, i) => ({
      slug: `error-${i}`,
      title: `Error ${i}`,
      body: `Error body ${i}`,
      concept_refs: ['error-theme'],
    }));
    await runPhaseSynthesizeConcepts(engine, {
      _atoms: atoms,
      _chat: (async () => { throw new Error('temporary provider failure'); }) as typeof import('../../src/core/ai/gateway.ts').chat,
    });
    expect((await engine.getPage('concepts/error-theme'))?.frontmatter.synthesis_mode).toBe('error_fallback');
  });

  test('an empty model response is a truthful warning and error fallback', async () => {
    const atoms = Array.from({ length: 5 }, (_, i) => ({
      slug: `empty-${i}`,
      title: `Empty ${i}`,
      body: `Empty body ${i}`,
      concept_refs: ['empty-theme'],
    }));
    await persistAtoms(atoms);
    const result = await runPhaseSynthesizeConcepts(engine, {
      _atoms: atoms,
      _chat: stubChat(''),
    });
    expect(result.status).toBe('warn');
    expect((result.details?.failures as unknown[])).toHaveLength(1);
    expect((await engine.getPage('concepts/empty-theme'))?.frontmatter.synthesis_mode).toBe('error_fallback');
  });

  test('equal-strength concepts use a stable slug tie-break', async () => {
    const atoms = [
      ...Array.from({ length: 5 }, (_, i) => ({
        slug: `z-${i}`, title: `Z ${i}`, body: `Z ${i}`, concept_refs: ['z-theme'],
      })),
      ...Array.from({ length: 5 }, (_, i) => ({
        slug: `a-${i}`, title: `A ${i}`, body: `A ${i}`, concept_refs: ['a-theme'],
      })),
    ];
    const calls: string[] = [];
    await runPhaseSynthesizeConcepts(engine, {
      _atoms: atoms,
      _chat: (async (opts: ChatOpts) => {
        calls.push(String(opts.messages[0]?.content));
        return stubChat('Stable narrative.')(opts);
      }) as typeof import('../../src/core/ai/gateway.ts').chat,
    });
    expect(calls).toHaveLength(2);
    expect(calls[0]).toContain('Concept slug: a-theme');
    expect(calls[1]).toContain('Concept slug: z-theme');
  });

  // #2163: concept pages must enter the retrieval surface. The write routes
  // through importFromContent (the same parse→chunk pipeline put_page uses),
  // so content_chunks rows exist and source-boost's 1.3× 'concepts/' weight
  // has something to boost. (Embeddings are skipped in this env — no
  // provider — but chunks + search_vector land regardless.)
  test('concept pages are chunked (#2163)', async () => {
    const atoms = Array.from({ length: 12 }, (_, i) => ({
      slug: `c${i}`,
      title: `Chunk atom ${i}`,
      body: `Chunky body ${i}.`,
      concept_refs: ['chunked-concept'],
    }));
    const chat = stubChat('A concept narrative long enough to produce at least one chunk.');
    await runPhaseSynthesizeConcepts(engine, { _atoms: atoms, _chat: chat });
    const rows = await engine.executeRaw<{ n: number }>(
      `SELECT count(*)::int AS n
         FROM content_chunks c JOIN pages p ON p.id = c.page_id
        WHERE p.slug = 'concepts/chunked-concept'`,
    );
    expect(Number(rows[0].n)).toBeGreaterThan(0);
    // Page metadata survives the importFromContent round-trip.
    const page = await engine.executeRaw<{ type: string; fm: Record<string, unknown> }>(
      `SELECT type, frontmatter AS fm FROM pages WHERE slug = 'concepts/chunked-concept'`,
    );
    expect(page[0].type).toBe('concept');
    expect((page[0].fm as Record<string, unknown>).tier).toBe('T1');
  });
});

// Canonical pricing: synthesize_concepts' estimated_spend_usd must derive
// from the model that actually answered (ChatResult.model) through
// canonicalLookup — not hardcoded Sonnet rates. A wrong per-model rate both
// trips the $1.50 budget gate early (deterministic-template fallback for
// work that had budget left) and persists an inflated cost into
// receipts/rollups. Canonical-miss models keep Sonnet-tier pricing (the
// same conservative fallback as skillopt/preflight's lookupPrice).
describe('synthesize_concepts: cost estimate uses canonical per-model pricing', () => {
  // 6 atoms on one concept → single T2 group → exactly one LLM call.
  const t2Atoms = Array.from({ length: 6 }, (_, i) => ({
    slug: `priced-${i}`,
    title: `Priced ${i}`,
    body: `Priced body ${i}.`,
    concept_refs: ['priced-concept'],
  }));

  // 1M input + 1M output tokens → estimated_spend_usd equals
  // (input_rate + output_rate) in dollars, read straight off the table.
  function pricedChat(model: string): (o: ChatOpts) => Promise<ChatResult> {
    return async (_o: ChatOpts) => ({
      text: 'Priced narrative.',
      blocks: [{ type: 'text', text: 'Priced narrative.' }],
      stopReason: 'end',
      usage: {
        input_tokens: 1_000_000,
        output_tokens: 1_000_000,
        cache_read_tokens: 0,
        cache_creation_tokens: 0,
      },
      model,
      providerId: model.split(':')[0] ?? 'anthropic',
    });
  }

  // Expected values derive from the canonical table (never hand-copied
  // dollar literals — the same invariant the fix enforces), so these tests
  // survive future price refreshes in model-pricing.ts.
  const sonnetRate = canonicalLookup('anthropic:claude-sonnet-4-6')!;
  const gpt52Rate = canonicalLookup('openai:gpt-5.2')!;

  test('non-Sonnet canonical model is priced at its own rates (openai:gpt-5.2)', async () => {
    const result = await runPhaseSynthesizeConcepts(engine, {
      _atoms: t2Atoms,
      _chat: pricedChat('openai:gpt-5.2') as typeof import('../../src/core/ai/gateway.ts').chat,
      dryRun: true,
    });
    // gpt-5.2's own canonical rates — NOT Sonnet's (the pre-fix hardcode).
    // Guard the guard: the two rate cards must actually differ, or this
    // test can't discriminate.
    expect(gpt52Rate.input + gpt52Rate.output).not.toBeCloseTo(
      sonnetRate.input + sonnetRate.output,
      6,
    );
    expect(result.details?.estimated_spend_usd).toBeCloseTo(
      gpt52Rate.input + gpt52Rate.output,
      6,
    );
  });

  test('canonical-miss model falls back to Sonnet-tier pricing', async () => {
    const result = await runPhaseSynthesizeConcepts(engine, {
      _atoms: t2Atoms,
      _chat: pricedChat('acme:unpriced-model-x') as typeof import('../../src/core/ai/gateway.ts').chat,
      dryRun: true,
    });
    // Not in CANONICAL_PRICING → conservative Sonnet-tier fallback.
    expect(result.details?.estimated_spend_usd).toBeCloseTo(
      sonnetRate.input + sonnetRate.output,
      6,
    );
  });

  test('control: Sonnet model estimate is unchanged by canonical routing', async () => {
    const result = await runPhaseSynthesizeConcepts(engine, {
      _atoms: t2Atoms,
      _chat: pricedChat('anthropic:claude-sonnet-4-6') as typeof import('../../src/core/ai/gateway.ts').chat,
      dryRun: true,
    });
    // Same Sonnet-tier rates the pre-canonical hardcode used ($3/$15 at
    // the time of writing) → identical estimate before and after the fix.
    expect(result.details?.estimated_spend_usd).toBeCloseTo(
      sonnetRate.input + sonnetRate.output,
      6,
    );
  });
});

// #2123 — extract_atoms must stamp `concepts` so synthesize_concepts has
// material. The pre-fix pipeline was broken end-to-end: the extractor
// never wrote the field, and every synthesize_concepts cycle skipped with
// "no atoms with concept refs". The earlier describe blocks feed
// synthesize via the `_atoms` seam, which is exactly how the gap survived
// — so the last test here goes extractor → REAL frontmatter → real DB
// query path → concept page.
describe('#2123: concepts label parsing', () => {
  test('keeps valid kebab-case labels', () => {
    const raw = `[{"title":"T","atom_type":"insight","body":"b","concepts":["captive-portal","tls-certificates"]}]`;
    expect(parseAtomsResponse(raw)[0].concepts).toEqual(['captive-portal', 'tls-certificates']);
  });

  test('filters non-kebab labels, keeps the rest', () => {
    const raw = `[{"title":"T","atom_type":"insight","body":"b","concepts":["Captive Portal","tp_link","UPPER","valid-label"]}]`;
    expect(parseAtomsResponse(raw)[0].concepts).toEqual(['valid-label']);
  });

  test('truncates to 3 labels', () => {
    const raw = `[{"title":"T","atom_type":"insight","body":"b","concepts":["a","b","c","d","e"]}]`;
    expect(parseAtomsResponse(raw)[0].concepts).toEqual(['a', 'b', 'c']);
  });

  test('absent / non-array / all-invalid → undefined', () => {
    expect(parseAtomsResponse(`[{"title":"T","atom_type":"insight","body":"b"}]`)[0].concepts).toBeUndefined();
    expect(parseAtomsResponse(`[{"title":"T","atom_type":"insight","body":"b","concepts":"not-an-array"}]`)[0].concepts).toBeUndefined();
    expect(parseAtomsResponse(`[{"title":"T","atom_type":"insight","body":"b","concepts":["Bad Label!"]}]`)[0].concepts).toBeUndefined();
  });
});

// #3044 adoption — a whole-run LLM outage must halt the phase instead of
// overwriting existing concept pages with error_fallback stub narratives.
// Non-global per-item errors keep the error_fallback behavior (pinned by
// 'marks LLM-error fallback output distinctly' above).
describe('runPhaseSynthesizeConcepts — global-error halt (#3044)', () => {
  // Equal-count T2 groups sort by slug, so call order is deterministic.
  const mkGroups = (themes: string[]) =>
    themes.flatMap((theme) =>
      Array.from({ length: 6 }, (_, i) => ({
        slug: `${theme}-${i}`,
        title: `${theme} ${i}`,
        body: `${theme} body ${i}`,
        concept_refs: [theme],
      })),
    );

  async function conceptCount(): Promise<number> {
    const rows = await engine.executeRaw<{ n: number }>(
      `SELECT COUNT(*)::int AS n FROM pages WHERE type = 'concept' AND slug LIKE 'concepts/%'`,
    );
    return Number(rows[0].n);
  }

  test('auth error halts on the FIRST hit — no stub narrative is written', async () => {
    let calls = 0;
    const result = await runPhaseSynthesizeConcepts(engine, {
      _atoms: mkGroups(['alpha-theme', 'beta-theme']),
      _chat: (async () => {
        calls++;
        throw Object.assign(new Error('invalid x-api-key'), { status: 401 });
      }) as typeof import('../../src/core/ai/gateway.ts').chat,
    });
    expect(calls).toBe(1); // beta-theme never called the LLM
    expect(result.details?.aborted_global_error).toBe('auth');
    expect(result.details?.concepts_written).toBe(0);
    expect(result.status).toBe('warn');
    const failures = result.details?.failures as Array<{ error: string }>;
    expect(failures).toHaveLength(1);
    expect(failures[0].error).toContain('whole-run condition');
    expect(await conceptCount()).toBe(0); // pre-fix: 2 error_fallback stubs
  });

  test('below-streak 429 skips the stub write for that group and continues', async () => {
    let calls = 0;
    const result = await runPhaseSynthesizeConcepts(engine, {
      _atoms: mkGroups(['alpha-theme', 'beta-theme', 'gamma-theme']),
      _chat: (async (opts) => {
        calls++;
        if (calls === 1) throw Object.assign(new Error('rate limited'), { status: 429 });
        return stubChat('Recovered narrative.')(opts as ChatOpts);
      }) as typeof import('../../src/core/ai/gateway.ts').chat,
    });
    expect(calls).toBe(3);
    expect(result.details?.aborted_global_error).toBeUndefined();
    expect(result.details?.concepts_written).toBe(2);
    // alpha-theme (the rate-limited group) keeps NO page — retried next run
    // instead of stubbed; the others synthesized normally.
    expect(await engine.getPage('concepts/alpha-theme')).toBeFalsy();
    expect((await engine.getPage('concepts/beta-theme'))?.frontmatter.synthesis_mode).toBe('llm');
    expect((await engine.getPage('concepts/gamma-theme'))?.frontmatter.synthesis_mode).toBe('llm');
  });

  test('3 consecutive 429s halt the phase with zero stub writes', async () => {
    let calls = 0;
    const result = await runPhaseSynthesizeConcepts(engine, {
      _atoms: mkGroups(['alpha-theme', 'beta-theme', 'gamma-theme', 'delta-theme']),
      _chat: (async () => {
        calls++;
        throw Object.assign(new Error('rate limited'), { status: 429 });
      }) as typeof import('../../src/core/ai/gateway.ts').chat,
    });
    expect(calls).toBe(3); // 4th group never called the LLM
    expect(result.details?.aborted_global_error).toBe('rate_limit');
    expect(result.details?.concepts_written).toBe(0);
    const failures = result.details?.failures as Array<{ error: string }>;
    expect(failures[2].error).toContain('3 consecutive rate_limit errors');
    expect(await conceptCount()).toBe(0);
  });
});

describe('#2123: extractor stamps concepts → synthesize_concepts consumes via real DB path', () => {
  test('end-to-end: atoms with shared label materialize a concept page', async () => {
    const chat = stubChat(`[
      {"title":"Cert warning on guest wifi","atom_type":"insight","body":"Portal redirects to an IP-based HTTPS URL.","concepts":["captive-portal"]},
      {"title":"iPhone portal popup is flaky","atom_type":"critique","body":"CNA probe behavior differs across iOS versions.","concepts":["captive-portal"]}
    ]`);
    const extract = await runPhaseExtractAtoms(engine, {
      _transcripts: [{ filePath: '/fake/notes.txt', content: 'content', contentHash: 'cc2123' }],
      _pages: [],
      _chat: chat,
    });
    expect(extract.status).toBe('ok');
    expect(extract.details?.atoms_extracted).toBe(2);

    // Frontmatter really carries the label (a jsonb array, not a string).
    const stamped = await engine.executeRaw<{ slug: string; concepts: unknown }>(
      `SELECT slug, frontmatter->'concepts' AS concepts FROM pages WHERE type = 'atom'`,
    );
    expect(stamped.length).toBe(2);
    for (const row of stamped) {
      const arr = typeof row.concepts === 'string' ? JSON.parse(row.concepts) : row.concepts;
      expect(arr).toEqual(['captive-portal']);
    }

    // NO _atoms seam: synthesize discovers the atoms through its own
    // DB query — this is the path that was dead before the fix.
    const synth = await runPhaseSynthesizeConcepts(engine, { _chat: stubChat('unused — T3 is deterministic') });
    expect(synth.status).toBe('ok');
    expect(synth.details?.concepts_written).toBe(1);
    const concept = await engine.executeRaw<{ slug: string }>(
      `SELECT slug FROM pages WHERE slug = 'concepts/captive-portal' AND type = 'concept'`,
    );
    expect(concept.length).toBe(1);

    // #4589 on the REAL path: the provenance edges are keyed on the atom slugs
    // the DB query returned (not `_atoms` seam input), so each extracted atom
    // must point back at the concept — 2 atoms, 2 'synthesizes' backlinks.
    const back = (await engine.getBacklinks('concepts/captive-portal', { sourceId: 'default' }))
      .filter((l) => l.link_source === 'concept-provenance');
    expect(back.length).toBe(2);
    expect(back.every((l) => l.link_type === 'synthesizes')).toBe(true);
    expect(back.map((l) => l.from_slug).sort()).toEqual(stamped.map((r) => r.slug).sort());
  });
});

// #4589 — synthesize_concepts held every member atom's slug in memory at write
// time and dropped it: the concept page was written through importFromContent
// (which links code refs only), the prompt forbids enumerating atoms in the
// body, and no frontmatter field maps to a link verb — so every concept page
// landed with 0 inbound + 0 outbound edges and dragged doctor's
// graph_signals_coverage / orphans down. The phase now banks
// concept -> atom ('synthesized_from') and atom -> concept ('synthesizes')
// edges under a dedicated link_source ('concept-provenance', so reconcile
// passes never prune them), scoped to the cycle's source. Mirrors #3961.
describe('#4589: synthesize_concepts persists concept<->atom provenance edges', () => {
  const CONCEPT = 'dive-entry-mechanics';
  const CONCEPT_SLUG = `concepts/${CONCEPT}`;
  const memberSlugs = [0, 1, 2].map((i) => `atoms/2026-01-01/member-${i}`);
  const memberAtoms = memberSlugs.map((slug, i) => ({
    slug,
    title: `Member ${i}`,
    body: `Body of member ${i}.`,
    concept_refs: [CONCEPT],
  }));

  async function seedMembers(sourceId?: string): Promise<void> {
    for (const a of memberAtoms) {
      await engine.putPage(
        a.slug,
        { type: 'atom', title: a.title, compiled_truth: a.body, timeline: '' },
        sourceId ? { sourceId } : undefined,
      );
    }
  }

  async function provenanceCount(): Promise<number> {
    const rows = await engine.executeRaw<{ n: number }>(
      `SELECT COUNT(*)::int AS n FROM links WHERE link_source = 'concept-provenance'`,
    );
    return rows[0].n;
  }

  test('writes synthesized_from (concept->atom) and synthesizes (atom->concept) edges', async () => {
    await seedMembers();
    // 3 atoms = T3 → deterministic path, no LLM call.
    const result = await runPhaseSynthesizeConcepts(engine, { _atoms: memberAtoms });
    expect(result.status).toBe('ok');

    const out = (await engine.getLinks(CONCEPT_SLUG, { sourceId: 'default' }))
      .filter((l) => l.link_source === 'concept-provenance');
    expect(out.map((l) => l.to_slug).sort()).toEqual([...memberSlugs].sort());
    expect(out.every((l) => l.link_type === 'synthesized_from')).toBe(true);

    const back = (await engine.getBacklinks(CONCEPT_SLUG, { sourceId: 'default' }))
      .filter((l) => l.link_source === 'concept-provenance');
    expect(back.map((l) => l.from_slug).sort()).toEqual([...memberSlugs].sort());
    expect(back.every((l) => l.link_type === 'synthesizes')).toBe(true);
  });

  test('re-running the phase is idempotent (ON CONFLICT DO NOTHING keeps 3+3 rows)', async () => {
    await seedMembers();
    await runPhaseSynthesizeConcepts(engine, { _atoms: memberAtoms });
    expect(await provenanceCount()).toBe(6);
    const second = await runPhaseSynthesizeConcepts(engine, { _atoms: memberAtoms });
    expect(second.status).toBe('ok');
    expect(await provenanceCount()).toBe(6);
  });

  test('dry-run writes zero provenance edges', async () => {
    await seedMembers();
    const result = await runPhaseSynthesizeConcepts(engine, { _atoms: memberAtoms, dryRun: true });
    expect(result.details?.concepts_written).toBe(1);
    expect(await provenanceCount()).toBe(0);
  });

  test('edges land in the cycle source only; an atom in another source drops out (no cross-source edge)', async () => {
    await engine.executeRaw(
      `INSERT INTO sources (id, name) VALUES ('repo-a', 'Repo A') ON CONFLICT (id) DO NOTHING`,
    );
    await seedMembers('repo-a');
    // A same-concept atom that lives in 'default' — the INNER JOIN on
    // (slug, source_id) must silently drop it rather than link across sources.
    const stray = { slug: 'atoms/2026-01-01/stray', title: 'Stray', body: 'b', concept_refs: [CONCEPT] };
    await engine.putPage(stray.slug, { type: 'atom', title: stray.title, compiled_truth: stray.body, timeline: '' });

    const result = await runPhaseSynthesizeConcepts(engine, {
      _atoms: [...memberAtoms, stray],
      sourceId: 'repo-a',
    });
    expect(result.status).toBe('ok');

    const inRepo = (await engine.getLinks(CONCEPT_SLUG, { sourceId: 'repo-a' }))
      .filter((l) => l.link_source === 'concept-provenance');
    expect(inRepo.map((l) => l.to_slug).sort()).toEqual([...memberSlugs].sort());
    expect(inRepo.every((l) => l.to_source_id === 'repo-a' && l.from_source_id === 'repo-a')).toBe(true);
    expect(
      (await engine.getLinks(CONCEPT_SLUG, { sourceId: 'default' }))
        .filter((l) => l.link_source === 'concept-provenance'),
    ).toHaveLength(0);
    expect((await engine.getLinks(stray.slug, { sourceId: 'default' })).length).toBe(0);
    expect(await provenanceCount()).toBe(6);
  });

  test('every member atom outside the cycle source → zero edges is warn, not a silent ok (wave review)', async () => {
    await engine.executeRaw(
      `INSERT INTO sources (id, name) VALUES ('repo-a', 'Repo A') ON CONFLICT (id) DO NOTHING`,
    );
    await seedMembers(); // atoms live in 'default' …
    const result = await runPhaseSynthesizeConcepts(engine, {
      _atoms: memberAtoms,
      sourceId: 'repo-a', // … but the phase writes to repo-a, so the batch JOIN drops every edge.
    });
    expect(await provenanceCount()).toBe(0);
    expect(result.status).toBe('warn');
    // Provenance problems ride `link_warnings`, not `failures` (which means
    // "LLM-failed → template fallback" downstream and would count a halt).
    expect(result.details?.failures).toEqual([]);
    const warnings = result.details?.link_warnings as Array<{ concept: string; warning: string }>;
    expect(warnings.some((w) => w.concept === CONCEPT && /0 of 6/.test(w.warning))).toBe(true);
    // The page write stands (best-effort edges, mirrors the thrown case below).
    expect(await engine.getPage(CONCEPT_SLUG, { sourceId: 'repo-a' })).not.toBeNull();
  });

  test('a failed edge write is reported as warn, not swallowed; the concept page still lands', async () => {
    await seedMembers();
    // Shadow the prototype method and delete the shadow afterwards: restoring a copy bound to the root engine would
    // leave it pinned there, and the edges are now written inside a transaction (GBRA-161 PR 5), where a call through
    // the root engine waits on the transaction's own connection.
    engine.addLinksBatch = async () => { throw new Error('links table unavailable'); };
    try {
      const result = await runPhaseSynthesizeConcepts(engine, { _atoms: memberAtoms });
      expect(result.status).toBe('warn');
      expect(result.details?.failures).toEqual([]);
      const warnings = result.details?.link_warnings as Array<{ concept: string; warning: string }>;
      expect(warnings.some((w) => w.concept === CONCEPT && /links table unavailable/.test(w.warning))).toBe(true);
      expect(await engine.getPage(CONCEPT_SLUG, { sourceId: 'default' })).not.toBeNull();
    } finally {
      delete (engine as { addLinksBatch?: unknown }).addLinksBatch;
    }
  });
});

// ─── wave review: provenance-link problems are warnings, not LLM failures ──
describe('synthesize_concepts — provenance-link warnings stay out of `failures`', () => {
  test('zero provenance edges landed → status warn, link_warnings recorded, narrative kept, no halt', async () => {
    // Atoms are NOT persisted, so the provenance batch JOIN drops every edge.
    // Pre-fix that was pushed into `failures`, which downstream reads as
    // "LLM-failed → template fallback": the summary lied about the narrative
    // (the LLM call succeeded and was persisted as-is), the rollup counted a
    // halt, and round_completed_delta flipped to 0.
    const atoms = Array.from({ length: 5 }, (_, i) => ({
      slug: `orphan-${i}`,
      title: `Orphan ${i}`,
      body: `Orphan body ${i}`,
      concept_refs: ['orphan-theme'],
    }));
    const result = await runPhaseSynthesizeConcepts(engine, {
      _atoms: atoms,
      _chat: stubChat('A real narrative.'),
    });
    expect(result.status).toBe('warn');
    expect(result.details?.failures).toEqual([]);
    const linkWarnings = result.details?.link_warnings as Array<{ concept: string; warning: string }>;
    expect(linkWarnings).toHaveLength(1);
    expect(linkWarnings[0].concept).toBe('orphan-theme');
    expect(linkWarnings[0].warning).toContain('provenance links');
    expect(result.summary).not.toContain('template fallback');
    expect((await engine.getPage('concepts/orphan-theme'))?.frontmatter.synthesis_mode).toBe('llm');

    const rollup = await engine.executeRaw<{ halt_count: number; round_completed_count: number }>(
      `SELECT halt_count, round_completed_count FROM extract_rollup_7d WHERE kind = 'concepts'`,
    );
    expect(rollup).toHaveLength(1);
    expect(Number(rollup[0].halt_count)).toBe(0);
    expect(Number(rollup[0].round_completed_count)).toBe(1);
  });
});