/**
 * SET 89 — per-case deterministic certification (replaces SET 40 aggregate born-red).
 *
 * These tests define the certification boundary:
 *   - a crash is NEVER born-red evidence;
 *   - `1/3 red` never certifies a suite that also carries vacuous siblings;
 *   - stub-derived throw expectations are rejected;
 *   - vacuous / registration / syntax cases are rejected with named dispositions;
 *   - licensed throws (invalid input / unauthorized) are certified;
 *   - shape-only `not.toThrow` is provisional, not behavioral certification;
 *   - substring case names attribute correctly.
 */
import { describe, expect, it } from 'vitest';
import type { FeatureNode, FeatureSpec, GeneratedFile } from '../src/core/types';
import {
  analyzeThrowExpectation,
  certifyCaseAgainstStubs,
} from '../src/tier1/caseCertification';
import { conformCaseBody } from '../src/tier1/caseBodyConformance';
import {
  certifyFrozenSuite,
  commitFrozenSuite,
} from '../src/tier1/frozenSuiteGateway';
import { scoreBornRed, stubArtifact } from '../src/tier1/bornRed';
import { makeEvalSuiteRunner } from '../src/tier1/testExec';

function feature(overrides: Partial<FeatureNode> = {}): FeatureNode {
  return {
    id: 'F1',
    name: 'formatter',
    description: 'format an input string',
    parentId: null,
    deps: [],
    files: ['src/formatter.ts'],
    testFile: 'tests/formatter.test.ts',
    edgeCases: ['reject empty input with InvalidInput'],
    envVars: [],
    exports: [{ file: 'src/formatter.ts', symbol: 'format' }],
    stubs: [{
      path: 'src/formatter.ts',
      content: `export function format(_s: string): string { throw new Error('stub: not implemented'); }\n`,
    }],
    ...overrides,
  } as FeatureNode;
}

function spec(f: FeatureNode = feature()): FeatureSpec {
  return {
    title: 'set89 fixtures',
    prompt: 'A formatter that formats a string, and rejects empty input with InvalidInput.',
    features: [f],
  } as unknown as FeatureSpec;
}

describe('SET 89 · scoreBornRed semantics', () => {
  it('crash is NEVER isRed — a crash proves absence of evidence, not absence of impl', () => {
    // The old semantics returned { isRed: true } for a crash; that is exactly
    // the acceptance-decision defect this set removes.
    const m = scoreBornRed({ total: 0, failures: [], crashed: 'boom' });
    expect(m.isRed).toBe(false);
    expect(m.crashed).toBe(true);
  });

  it('one red case does NOT confer suite-level isRed by itself — per-case certification is authoritative', () => {
    // scoreBornRed remains as a summary formatter but MUST NOT be used as a
    // freeze acceptance gate (isRed becomes a summary, not an authority).
    const m = scoreBornRed({
      total: 3,
      failures: [{ name: 'case A', message: 'expect(...).toBe failed' }],
    });
    // The summary reports the honest count …
    expect(m.red).toBe(1);
    expect(m.vacuous).toBe(2);
    // … but does not itself certify anything: acceptance is per-case.
    expect(m.aggregateRedGate).toBe(false);
  });
});

describe('SET 89 · case-body conformance', () => {
  it('exact `it("…", () => { … })` unwrap succeeds and re-checks the inner body', () => {
    const raw = "it('sums', () => { expect(add(1,2)).toBe(3); })";
    const r = conformCaseBody(raw);
    expect(r.disposition).toBe('ok');
    expect(r.body).toContain('expect(add(1,2)).toBe(3)');
    expect(r.unwrapped).toBe('outer-it');
  });

  it('exact `test("…", () => { … })` unwrap succeeds', () => {
    const raw = "test('sums', () => { expect(add(1,2)).toBe(3); })";
    const r = conformCaseBody(raw);
    expect(r.disposition).toBe('ok');
    expect(r.unwrapped).toBe('outer-test');
  });

  it('`describe` containing exactly one `it` unwraps two levels', () => {
    const raw = "describe('g', () => { it('t', () => { expect(1+1).toBe(2); }); })";
    const r = conformCaseBody(raw);
    expect(r.disposition).toBe('ok');
    expect(r.unwrapped).toBe('outer-describe-it');
  });

  it('`describe` with two `it`s is REJECTED (never partially discarded)', () => {
    const raw = "describe('g', () => { it('a', () => {}); it('b', () => {}); })";
    const r = conformCaseBody(raw);
    expect(r.disposition).toBe('rejected-registration');
  });

  it('nested `it(` inside an `if` (token-aware, ignore strings/comments) is REJECTED', () => {
    const raw = `
      const x = 1;
      // it('fake', () => {}) — this is a comment
      if (x) { it('nested', () => {}); }
      expect(x).toBe(1);
    `;
    const r = conformCaseBody(raw);
    expect(r.disposition).toBe('rejected-registration');
  });

  it('registration-like text inside comments and strings is IGNORED', () => {
    const raw = `
      // it('fake', () => {})
      /* describe('also fake', () => {}) */
      const s = "it('in a string', () => {})";
      const t = \`test('template', () => {})\`;
      expect(s.length).toBeGreaterThan(0);
      expect(t.length).toBeGreaterThan(0);
    `;
    const r = conformCaseBody(raw);
    expect(r.disposition).toBe('ok');
  });

  it('member calls like `obj.test()` do not trip registration rejection', () => {
    const raw = "expect(obj.test()).toBe(true);";
    const r = conformCaseBody(raw);
    expect(r.disposition).toBe('ok');
  });

  it('returned body with setup PLUS an outer `it` is rejected (never partial-discard)', () => {
    const raw = `
      const store = new Store();
      it('composite', () => { expect(store.size()).toBe(0); });
    `;
    const r = conformCaseBody(raw);
    expect(r.disposition).toBe('rejected-registration');
  });

  it('unterminated string body → rejected-syntax', () => {
    const raw = "expect('unterminated).toBe(true);";
    const r = conformCaseBody(raw);
    expect(r.disposition).toBe('rejected-syntax');
  });
});

describe('SET 89 · analyzeThrowExpectation (token-aware)', () => {
  it('distinguishes .toThrow(), .toThrow(msg), rejects.toThrow, and not.toThrow', () => {
    const bare = analyzeThrowExpectation('expect(() => f()).toThrow();');
    expect(bare.hasThrowAssertion).toBe(true);
    expect(bare.negated).toBe(false);
    expect(bare.expectedLiteral).toBeNull();

    const literal = analyzeThrowExpectation('expect(() => f()).toThrow("InvalidInput");');
    expect(literal.expectedLiteral).toBe('InvalidInput');

    const rejects = analyzeThrowExpectation('await expect(fn()).rejects.toThrow(/Unauthorized/);');
    expect(rejects.async).toBe(true);
    expect(rejects.expectedLiteral).toBe('Unauthorized');

    const notThrow = analyzeThrowExpectation('expect(() => f()).not.toThrow();');
    expect(notThrow.negated).toBe(true);
    expect(notThrow.hasThrowAssertion).toBe(true);
  });

  it('ignores toThrow-like text inside strings and comments', () => {
    const r = analyzeThrowExpectation(`
      // .toThrow('fake')
      const s = ".toThrow('not real')";
      expect(s.length).toBeGreaterThan(0);
    `);
    expect(r.hasThrowAssertion).toBe(false);
  });

  it('flags multi-assertion bodies where the throw assertion is not the whole contract', () => {
    const r = analyzeThrowExpectation(`
      const out = fn();
      expect(out.count).toBe(1);
      expect(() => fn()).toThrow();
    `);
    expect(r.hasThrowAssertion).toBe(true);
    expect(r.isSoleAssertion).toBe(false);
  });
});

describe('SET 89 · per-case certification against stubs', () => {
  const runSuite = makeEvalSuiteRunner();
  const s = spec();
  const stubs = stubArtifact(s);
  const prompt = s.prompt as string;

  it('honest behavioral case that expects a value → certified-behavior-red', async () => {
    const cert = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: {
        name: 'formats "hi"',
        kind: 'behavior',
        body: 'expect(format("hi")).toBe("HI");',
      },
      runSuite,
      stubs,
    });
    expect(cert.disposition).toBe('certified-behavior-red');
    expect(cert.attributedToCase).toBe(true);
  });

  it('vacuous `expect(1).toBe(1)` → rejected-vacuous (never freeze-eligible)', async () => {
    const cert = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: { name: 'trivial', kind: 'behavior', body: 'expect(1).toBe(1);' },
      runSuite,
      stubs,
    });
    expect(cert.disposition).toBe('rejected-vacuous');
  });

  it('stub-derived throw assertion → rejected-stub-derived', async () => {
    const cert = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: {
        name: 'throws when unimplemented',
        kind: 'edge',
        body: 'expect(() => format("hi")).toThrow("stub: not implemented");',
      },
      runSuite,
      stubs,
    });
    expect(cert.disposition).toBe('rejected-stub-derived');
  });

  it('bare `.toThrow()` with no licensing chain → rejected-unlicensed-throw', async () => {
    // No edge case licenses a bare throw for "sums two things"; the case name
    // does not trace to prompt/edge either.
    const cert = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: {
        name: 'random shape',
        kind: 'edge',
        body: 'expect(() => format("x")).toThrow();',
      },
      runSuite,
      stubs,
    });
    expect(cert.disposition).toBe('rejected-unlicensed-throw');
  });

  it('invalid-input throw with licensed literal → certified-licensed-throw', async () => {
    const cert = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: {
        name: 'reject empty input',
        kind: 'edge',
        body: 'expect(() => format("")).toThrow("InvalidInput");',
      },
      runSuite,
      stubs,
    });
    expect(cert.disposition).toBe('certified-licensed-throw');
  });

  it('legitimate error case whose expected message is absent from prompt → rejected-unlicensed-throw', async () => {
    const cert = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: {
        name: 'errors on quantum uncertainty',
        kind: 'edge',
        body: 'expect(() => format("q")).toThrow("QuantumUncertainty");',
      },
      runSuite,
      stubs,
    });
    expect(cert.disposition).toBe('rejected-unlicensed-throw');
  });

  it('nested `it()` inside case body → rejected-registration (never certified)', async () => {
    const cert = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: {
        name: 'nested reg',
        kind: 'behavior',
        body: `it('inner', () => { expect(format("x")).toBe("X"); });`,
      },
      runSuite,
      stubs,
    });
    // The nested `it(` is either unwrapped (canonical exact-outer) OR rejected
    // when it is not the canonical single-block form. Either way the
    // disposition must never be a generic red.
    expect(['certified-behavior-red', 'rejected-registration']).toContain(cert.disposition);
  });

  it('unterminated string body → rejected-syntax', async () => {
    const cert = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: {
        name: 'syntax poison',
        kind: 'behavior',
        body: 'expect("unterminated).toBe("x");',
      },
      runSuite,
      stubs,
    });
    expect(cert.disposition).toBe('rejected-syntax');
  });

  it('generic `not.toThrow()` deterministic anchor → provisional shape-only (not behavioral certification)', async () => {
    const cert = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: {
        name: 'callable',
        kind: 'behavior',
        body: 'expect(() => format("hi")).not.toThrow();',
      },
      runSuite,
      stubs,
    });
    expect(cert.provisional).toBe(true);
    expect(cert.disposition).toBe('certified-behavior-red');
  });

  it('two cases where one name is a substring of the other are attributed exactly', async () => {
    // Two cases: "sums" and "sums two positives". Their failures must attribute
    // to the exact name, not via a substring match against the shorter sibling.
    // The certification path only sees ONE case at a time by construction
    // (it assembles a suite containing exactly that case), so substring
    // attribution can never happen. This test pins that shape.
    const cert1 = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: {
        name: 'sums',
        kind: 'behavior',
        body: 'expect(format("hi")).toBe("HI");',
      },
      runSuite,
      stubs,
    });
    const cert2 = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: {
        name: 'sums two positives',
        kind: 'behavior',
        body: 'expect(format("hi")).toBe("HI");',
      },
      runSuite,
      stubs,
    });
    expect(cert1.attributedToCase).toBe(true);
    expect(cert2.attributedToCase).toBe(true);
    expect(cert1.caseName).toBe('sums');
    expect(cert2.caseName).toBe('sums two positives');
  });
});

describe('SET 89 · crash never certifies', () => {
  const s = spec();

  it('run.crashed = "boom" → rejected-crash, never freeze-eligible', async () => {
    // Synthetic runner that always crashes — the CERTIFICATION path must not
    // interpret this as evidence-of-absence-of-implementation.
    const crashRunner = async () => ({ total: 0, failures: [], crashed: 'boom' });
    const cert = await certifyCaseAgainstStubs({
      spec: s,
      feature: s.features[0]!,
      prompt: s.prompt as string,
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      caseGen: { name: 'x', kind: 'behavior', body: 'expect(format("hi")).toBe("HI");' },
      runSuite: crashRunner,
      stubs: stubArtifact(s),
    });
    expect(cert.disposition).toBe('rejected-crash');
    expect(cert.crashSignature).toBe('boom');
  });
});

describe('SET 89 · frozen suite gateway (certifyFrozenSuite + commitFrozenSuite)', () => {
  const runSuite = makeEvalSuiteRunner();

  it('rejects a suite with a nested `it()` in a case body (never partial-commit)', async () => {
    const s = spec();
    const parts = {
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      cases: [
        { name: 'nested', kind: 'behavior' as const, body: `it('inner', () => { expect(format('x')).toBe('X'); })` },
      ],
    };
    const state = { frozenTests: [] as GeneratedFile[], frozenByFeature: new Map<string, string>(), irPartsByFeature: new Map() };
    const commit = await commitFrozenSuite({
      spec: s,
      feature: s.features[0]!,
      prompt: s.prompt as string,
      parts,
      state,
      reason: 'test-commit',
      runSuite,
      stubs: stubArtifact(s),
    });
    // Either the exact-outer unwrap happened and it accepted, OR the gateway
    // rejected. What must NOT happen is a partial commit that only touches
    // one of {irPartsByFeature, frozenTests, frozenByFeature}.
    if (commit.status === 'rejected') {
      expect(state.frozenTests).toHaveLength(0);
      expect(state.frozenByFeature.size).toBe(0);
      expect(state.irPartsByFeature.size).toBe(0);
    } else {
      // Acceptance requires ALL three representations to move atomically.
      expect(state.frozenTests).toHaveLength(1);
      expect(state.frozenByFeature.has('F1')).toBe(true);
      expect(state.irPartsByFeature.has('F1')).toBe(true);
    }
  });

  it('rejects a suite that fails standalone parse — nothing is written', async () => {
    const s = spec();
    const parts = {
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      cases: [
        { name: 'poison', kind: 'behavior' as const, body: 'expect("unterminated).toBe("x")' },
      ],
    };
    const state = { frozenTests: [] as GeneratedFile[], frozenByFeature: new Map<string, string>(), irPartsByFeature: new Map() };
    const commit = await commitFrozenSuite({
      spec: s,
      feature: s.features[0]!,
      prompt: s.prompt as string,
      parts,
      state,
      reason: 'test-commit',
      runSuite,
      stubs: stubArtifact(s),
    });
    expect(commit.status).toBe('rejected');
    expect(state.frozenTests).toHaveLength(0);
    expect(state.frozenByFeature.size).toBe(0);
    expect(state.irPartsByFeature.size).toBe(0);
  });

  it('accepts a suite whose every case has a successful case certification', async () => {
    const s = spec();
    const parts = {
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      cases: [
        { name: 'formats hi', kind: 'behavior' as const, body: 'expect(format("hi")).toBe("HI");' },
        { name: 'reject empty input', kind: 'edge' as const, body: 'expect(() => format("")).toThrow("InvalidInput");' },
      ],
    };
    const state = { frozenTests: [] as GeneratedFile[], frozenByFeature: new Map<string, string>(), irPartsByFeature: new Map() };
    const commit = await commitFrozenSuite({
      spec: s,
      feature: s.features[0]!,
      prompt: s.prompt as string,
      parts,
      state,
      reason: 'test-commit',
      runSuite,
      stubs: stubArtifact(s),
    });
    expect(commit.status).toBe('accepted');
    expect(state.frozenTests).toHaveLength(1);
    expect(state.frozenByFeature.get('F1')).toBeDefined();
    expect(state.irPartsByFeature.get('F1')).toBeDefined();
  });

  it('SET 91b — `1/3 red with two vacuous siblings` CERTIFIES with the two vacuous cases dropped-with-disclosure', async () => {
    // Historical (pre-91) shape: any rejected case → whole suite refused. That
    // was the operative cause of the 78e36cc1 collapse (0/10 features frozen).
    // Under SET 91b the load-bearing red case carries the suite, and the two
    // vacuous cases move into `droppedCases` with disclosure. The suite still
    // freezes atomically and downstream build proceeds.
    const s = spec();
    const parts = {
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      cases: [
        { name: 'formats hi', kind: 'behavior' as const, body: 'expect(format("hi")).toBe("HI");' },
        { name: 'vac 1', kind: 'behavior' as const, body: 'expect(1).toBe(1);' },
        { name: 'vac 2', kind: 'behavior' as const, body: 'expect(true).toBe(true);' },
      ],
    };
    const state = { frozenTests: [] as GeneratedFile[], frozenByFeature: new Map<string, string>(), irPartsByFeature: new Map() };
    const commit = await commitFrozenSuite({
      spec: s,
      feature: s.features[0]!,
      prompt: s.prompt as string,
      parts,
      state,
      reason: 'test-commit',
      runSuite,
      stubs: stubArtifact(s),
    });
    expect(commit.status).toBe('accepted');
    expect(commit.report.status).toBe('certified');
    // All three representations moved atomically.
    expect(state.frozenTests).toHaveLength(1);
    expect(state.frozenByFeature.has('F1')).toBe(true);
    expect(state.irPartsByFeature.has('F1')).toBe(true);
    // The two vacuous cases are named in droppedCases; the load-bearing case
    // is NOT.
    const dropped = commit.report.droppedCases.map(d => d.caseName);
    expect(dropped).toEqual(expect.arrayContaining(['vac 1', 'vac 2']));
    expect(dropped).not.toContain('formats hi');
  });

  it('late re-freeze that INJECTS a parse defect keeps the incumbent byte-identical', async () => {
    const s = spec();
    const state = { frozenTests: [] as GeneratedFile[], frozenByFeature: new Map<string, string>(), irPartsByFeature: new Map() };
    // Initial valid freeze.
    const goodParts = {
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      cases: [
        { name: 'formats hi', kind: 'behavior' as const, body: 'expect(format("hi")).toBe("HI");' },
      ],
    };
    const c1 = await commitFrozenSuite({
      spec: s,
      feature: s.features[0]!,
      prompt: s.prompt as string,
      parts: goodParts,
      state,
      reason: 'initial',
      runSuite,
      stubs: stubArtifact(s),
    });
    expect(c1.status).toBe('accepted');
    const incumbentText = state.frozenByFeature.get('F1')!;

    // Late re-freeze with a poisoned string literal.
    const badParts = {
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      cases: [
        { name: 'poison', kind: 'behavior' as const, body: 'expect("unterminated).toBe("x")' },
      ],
    };
    const c2 = await commitFrozenSuite({
      spec: s,
      feature: s.features[0]!,
      prompt: s.prompt as string,
      parts: badParts,
      state,
      reason: 'late-re-freeze',
      runSuite,
      stubs: stubArtifact(s),
    });
    expect(c2.status).toBe('rejected');
    // Incumbent is BYTE-IDENTICAL.
    expect(state.frozenByFeature.get('F1')).toBe(incumbentText);
    expect(state.frozenTests[0]!.content).toBe(incumbentText);
  });

  it('late re-freeze injecting nested registration keeps the incumbent byte-identical', async () => {
    const s = spec();
    const state = { frozenTests: [] as GeneratedFile[], frozenByFeature: new Map<string, string>(), irPartsByFeature: new Map() };
    const goodParts = {
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      cases: [
        { name: 'formats hi', kind: 'behavior' as const, body: 'expect(format("hi")).toBe("HI");' },
      ],
    };
    await commitFrozenSuite({
      spec: s,
      feature: s.features[0]!,
      prompt: s.prompt as string,
      parts: goodParts,
      state,
      reason: 'initial',
      runSuite,
      stubs: stubArtifact(s),
    });
    const incumbentText = state.frozenByFeature.get('F1')!;
    const badParts = {
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      cases: [
        // Setup + outer it — the "returned body with setup plus an outer it" shape.
        { name: 'nested', kind: 'behavior' as const, body: `const x = 1; it('inner', () => { expect(x).toBe(1); });` },
      ],
    };
    const c = await commitFrozenSuite({
      spec: s,
      feature: s.features[0]!,
      prompt: s.prompt as string,
      parts: badParts,
      state,
      reason: 'late-re-freeze',
      runSuite,
      stubs: stubArtifact(s),
    });
    expect(c.status).toBe('rejected');
    expect(state.frozenByFeature.get('F1')).toBe(incumbentText);
  });
});

describe('SET 89 · certifyFrozenSuite reports named rejection reasons', () => {
  const runSuite = makeEvalSuiteRunner();

  it('names every case rejection reason (no generic "red")', async () => {
    const s = spec();
    const parts = {
      imports: [{ from: 'src/formatter', symbols: ['format'] }],
      cases: [
        { name: 'stub-derived', kind: 'edge' as const, body: 'expect(() => format("x")).toThrow("stub: not implemented");' },
        { name: 'vacuous', kind: 'behavior' as const, body: 'expect(1).toBe(1);' },
        { name: 'ok', kind: 'behavior' as const, body: 'expect(format("hi")).toBe("HI");' },
      ],
    };
    const report = await certifyFrozenSuite({
      spec: s,
      feature: s.features[0]!,
      prompt: s.prompt as string,
      parts,
      runSuite,
      stubs: stubArtifact(s),
    });
    const dispositions = report.cases.map(c => c.disposition);
    expect(dispositions).toContain('rejected-stub-derived');
    expect(dispositions).toContain('rejected-vacuous');
    expect(dispositions).toContain('certified-behavior-red');
    // No generic 'red' disposition — the taxonomy is closed.
    for (const d of dispositions) {
      expect(d).not.toBe('red');
    }
  });
});

describe('SET 89F · candidate ledger conservation', () => {
  it('per-layer accepted counters sum to `candidatesAccepted` (subset of `candidatesDrawn`)', async () => {
    const { runTier1Job } = await import('../src/tier1/runner');
    const RIGHT = `export function format(s: string): string {
      if (!s) throw new Error('InvalidInput');
      return s.toUpperCase();
    }`;
    const specFixture = spec();
    const llm = {
      async encodeFeatures() { return specFixture; },
      async generateTests() { return { content: '', parts: { imports: [], cases: [] } }; },
      async generateImplementation() { return [{ path: 'src/formatter.ts', content: RIGHT }]; },
      async repair() { return [{ path: 'src/formatter.ts', content: RIGHT }]; },
      async fixTestCases(_s: unknown, _f: unknown, req: { name: string }[]) {
        const name = req[0]!.name;
        const body = /empty|invalid/i.test(name)
          ? `expect(() => format("")).toThrow("InvalidInput");`
          : `expect(format("hi")).toBe("HI");`;
        return { cases: [{ name, kind: 'behavior' as const, body }] };
      },
    } as unknown as Parameters<typeof runTier1Job>[0]['llm'];
    const res = await runTier1Job({
      prompt: specFixture.prompt as string,
      llm,
      runSuite: makeEvalSuiteRunner(),
    });
    // SET 89 §8.5 invariant: accepted ⊆ drawn.
    expect(res.metrics.candidatesAccepted).toBeLessThanOrEqual(res.metrics.candidatesDrawn);
    // Per-layer accepted counters sum to aggregate accepted.
    expect(
      res.metrics.fillCandidatesAccepted + res.metrics.repairCandidatesAccepted,
    ).toBe(res.metrics.candidatesAccepted);
    // Per-layer drawn counters sum to aggregate drawn.
    expect(
      res.metrics.fillCandidatesDrawn + res.metrics.repairCandidatesDrawn,
    ).toBe(res.metrics.candidatesDrawn);
  });
});

describe('SET 89D · whole-artifact certification (end-to-end)', () => {
  it('runTier1Job surfaces `artifactCertification` when a runSuite is provided', async () => {
    const { runTier1Job } = await import('../src/tier1/runner');
    const RIGHT = `export function format(s: string): string {
      if (!s) throw new Error('InvalidInput');
      return s.toUpperCase();
    }`;
    const specFixture = spec();
    const llm = {
      async encodeFeatures() { return specFixture; },
      async generateTests() { return { content: '', parts: { imports: [], cases: [] } }; },
      async generateImplementation() { return [{ path: 'src/formatter.ts', content: RIGHT }]; },
      async repair() { return [{ path: 'src/formatter.ts', content: RIGHT }]; },
      async fixTestCases(_s: unknown, _f: unknown, req: { name: string }[]) {
        const name = req[0]!.name;
        // Every case honestly asserts observable behavior; none are vacuous.
        const body = /empty|invalid/i.test(name)
          ? `expect(() => format("")).toThrow("InvalidInput");`
          : `expect(format("hi")).toBe("HI");`;
        return { cases: [{ name, kind: 'behavior' as const, body }] };
      },
    } as unknown as Parameters<typeof runTier1Job>[0]['llm'];
    const res = await runTier1Job({
      prompt: specFixture.prompt as string,
      llm,
      runSuite: makeEvalSuiteRunner(),
    });
    expect(res.artifactCertification).toBeDefined();
    // The artifact certification report is a first-class field on the result.
    expect(typeof res.artifactCertification!.artifactCertified).toBe('boolean');
    expect(Array.isArray(res.artifactCertification!.unresolved)).toBe(true);
  });
});
