Skip to content

Non-invasive MCP accelerator plugin for Google Antigravity (CLI/Desktop/IDE): cuts LLM turns (-34%), token quota (-31%), and upload traffic (-40%) without affecting native UI or diffs.

59.2 KB
Raw Blame
import assert from "node:assert/strict";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { after, before, describe, it } from "node:test";
import { extractSymbols, runQuickOutline, runReadSlices } from "../src/tools/read-slices.js";

describe("read_slices", () => {
  let tmpDir: string;

  before(async () => {
    tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-slices-"));

    await fs.writeFile(
      path.join(tmpDir, "sample.ts"),
      [
        "export interface Config {",
        "  port: number;",
        "}",
        "",
        "export class Server {",
        "  start() {",
        "    return '{not a brace close}';",
        "  }",
        "",
        "  async stop(force: boolean): Promise<void> {",
        "    if (force) {",
        "      return;",
        "    }",
        "  }",
        "}",
        "",
        "export const createApp = (cfg: Config) => {",
        "  return new Server();",
        "};",
      ].join("\n"),
      "utf8",
    );

    await fs.writeFile(
      path.join(tmpDir, "sample.py"),
      [
        "class Worker:",
        "    def run(self):",
        "        return 42",
        "",
        "async def helper():",
        "    return True",
      ].join("\n"),
      "utf8",
    );

    await fs.writeFile(
      path.join(tmpDir, "sample.go"),
      [
        "package main",
        "",
        "type Engine struct {",
        "  Name string",
        "}",
        "",
        "func (e *Engine) Start() {",
        "  println(e.Name)",
        "}",
      ].join("\n"),
      "utf8",
    );

    await fs.writeFile(
      path.join(tmpDir, "sample.rs"),
      [
        "pub struct Cache {",
        "  size: usize,",
        "}",
        "",
        "impl Cache {",
        "  pub fn new(size: usize) -> Self {",
        "    Self { size }",
        "  }",
        "}",
      ].join("\n"),
      "utf8",
    );

    await fs.writeFile(
      path.join(tmpDir, "README.md"),
      [
        "# Title",
        "Intro line.",
        "```bash",
        "# not a heading",
        "```",
        "## Usage",
        "Details here.",
      ].join("\n"),
      "utf8",
    );
  });

  after(async () => {
    await fs.rm(tmpDir, { recursive: true, force: true });
  });

  it("extracts accurate multi-language symbol outlines with line spans", async () => {
    const tsSyms = extractSymbols(
      "sample.ts",
      await fs.readFile(path.join(tmpDir, "sample.ts"), "utf8"),
    );
    assert.deepEqual(
      tsSyms.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      [
        "interface:Config:1-3",
        "class:Server:5-15",
        "method:start:6-8",
        "method:stop:10-14",
        "function:createApp:17-19",
      ],
    );

    const pySyms = extractSymbols(
      "sample.py",
      await fs.readFile(path.join(tmpDir, "sample.py"), "utf8"),
    );
    assert.deepEqual(
      pySyms.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      [
        "class:Worker:1-3",
        "method:run:2-3",
        "function:helper:5-6",
      ],
    );

    const goSyms = extractSymbols(
      "sample.go",
      await fs.readFile(path.join(tmpDir, "sample.go"), "utf8"),
    );
    assert.equal(goSyms.length, 2);
    assert.equal(goSyms[0]?.name, "Engine");
    assert.equal(goSyms[1]?.kind, "method");

    const rsSyms = extractSymbols(
      "sample.rs",
      await fs.readFile(path.join(tmpDir, "sample.rs"), "utf8"),
    );
    assert.ok(rsSyms.some((s) => s.kind === "struct" && s.name === "Cache"));
    assert.ok(rsSyms.some((s) => s.kind === "fn" && s.name === "new"));

    const mdSyms = extractSymbols(
      "README.md",
      await fs.readFile(path.join(tmpDir, "README.md"), "utf8"),
    );
    assert.deepEqual(
      mdSyms.map((s) => s.name),
      ["Title", "Usage"],
    );
  });

  it("returns combined outlines and multi-range slices with clamping and bounds handling", async () => {
    const res = await runReadSlices({
      cwd: tmpDir,
      outlines: ["sample.ts", "sample.py"],
      slices: [
        {
          path: "sample.ts",
          ranges: [
            [1, 3],
            [17, 50], // clamped to EOF (19)
            [99, 120], // out of bounds
          ],
        },
        {
          path: "missing.ts",
          ranges: [[1, 5]],
        },
      ],
    });

    assert.equal(res.isError, false);
    assert.match(res.text, /## Outline: sample\.ts \(19 lines\)/);
    assert.match(res.text, /L5-L15 \[class\] Server/);
    assert.match(res.text, /--- L1-L3 \(of 19\) ---/);
    assert.match(res.text, /1: export interface Config \{/);
    assert.match(res.text, /--- L17-L19 \(of 19\) ---/);
    assert.match(res.text, /out of bounds; file has 19 lines/);
    assert.match(res.text, /## Slice: missing\.ts\nERROR:/);
  });

  it("rejects empty requests", async () => {
    const res = await runReadSlices({ cwd: tmpDir });
    assert.equal(res.isError, true);
  });

  it("handles regex/comment braces, multiline TS methods, Java/C functions, Python docstrings, and 4-space JSON", async () => {
    const tsComplex = [
      "export class Multi {",
      "  async send(",
      "    payload: string,",
      "  ): Promise<void> {",
      "    const re = /\\{not_a_brace\\}/;",
      "    /* { block comment brace }",
      "       another line { */",
      "    return;",
      "  }",
      "}",
      "",
      "export const build = (",
      "  a: number,",
      "  b: number,",
      ") => {",
      "  return a + b;",
      "};",
    ].join("\n");
    const tsSyms = extractSymbols("complex.ts", tsComplex);
    assert.deepEqual(
      tsSyms.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      [
        "class:Multi:1-10",
        "method:send:2-9",
        "function:build:12-17",
      ],
    );

    const javaSyms = extractSymbols(
      "Service.java",
      [
        "public class Service {",
        "  public int add(int a, int b) {",
        "    return a + b;",
        "  }",
        "}",
      ].join("\n"),
    );
    assert.deepEqual(
      javaSyms.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      ["class:Service:1-5", "method:add:2-4"],
    );

    const cSyms = extractSymbols(
      "main.c",
      [
        "int main(int argc, char **argv) {",
        "  return 0;",
        "}",
        "static void helper(void) {",
        "}",
      ].join("\n"),
    );
    assert.deepEqual(
      cSyms.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      ["function:main:1-3", "function:helper:4-5"],
    );

    const pySyms = extractSymbols(
      "doc.py",
      [
        "def foo():",
        '    """',
        "Column 0 docstring line",
        '    """',
        "    return 1",
        "",
        "def bar():",
        "    return 2",
      ].join("\n"),
    );
    assert.deepEqual(
      pySyms.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      ["function:foo:1-5", "function:bar:7-8"],
    );

    const jsonSyms = extractSymbols(
      "pkg.json",
      [
        "{",
        '    "name": "demo",',
        '    "scripts": {',
        '        "test": "node --test"',
        "    }",
        "}",
      ].join("\n"),
    );
    assert.deepEqual(
      jsonSyms.map((s) => `${s.kind}:${s.name}`),
      ["key:name", "key:scripts"],
    );
  });

  it("ends Python symbols after multi-line signatures and includes decorators", () => {
    const pySyms = extractSymbols(
      "model.py",
      [
        "class Model:",
        "    def __init__(",
        "        self,",
        "        size: int,",
        "    ) -> None:",
        "        self.size = size",
        "        self.table = {",
        "    'k': 1,",
        "        }",
        "",
        "    @property",
        "    @functools.lru_cache(",
        "        maxsize=8,",
        "    )",
        "    def area(self) -> int:",
        "        return self.size \\",
        "* 2",
        "",
        "# --- helpers ---",
        "",
        "def build(",
        "    size: int,",
        "):",
        "    return Model(size)",
      ].join("\n"),
    );
    assert.deepEqual(
      pySyms.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      [
        "class:Model:1-17",
        "method:__init__:2-9",
        "method:area:11-17",
        "function:build:21-24",
      ],
    );

    // Comment between stacked decorators still preserves the full decorator range
    const commentBetweenDecos = extractSymbols(
      "decos.py",
      [
        "@outer",
        "# keep outer decorator attached",
        "@inner",
        "def run():",
        '    """',
        "# not a trailing comment",
        '    """',
        "    return 1",
      ].join("\n"),
    );
    assert.deepEqual(
      commentBetweenDecos.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      ["function:run:1-8"],
    );

    // Backslash continuation inside a quoted string must not split the function or emit fake symbols
    const quotedBackslash = extractSymbols(
      "str_cont.py",
      [
        "def f():",
        '    s = "hello \\',
        'def fake(): pass" + (',
        "        1",
        "    )",
        "    return s",
        "",
        "def g():",
        "    return 2",
      ].join("\n"),
    );
    assert.deepEqual(
      quotedBackslash.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      ["function:f:1-6", "function:g:8-9"],
    );

    // Python 3.12+ PEP 701 f-strings (same-quote reuse, multiline expr, quote fill format spec)
    const pep701 = extractSymbols(
      "pep701.py",
      [
        "def first(s):",
        '    a = f"{s.split("(")[0]}"',
        '    b = f"{s:\'>10}"',
        '    c = f"a {(',
        "        1 + 2",
        '    )} b"',
        "    return a, b, c",
        "",
        "def second():",
        "    return 2",
      ].join("\n"),
    );
    assert.deepEqual(
      pep701.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      ["function:first:1-7", "function:second:9-10"],
    );

    // Mid-edit unclosed bracket recovers on subsequent def/class (including decorator)
    const midEdit = extractSymbols(
      "midedit.py",
      [
        "def editing():",
        "    x = compute(a, b",
        "",
        "@decorator",
        "def intact_after():",
        "    return 1",
      ].join("\n"),
    );
    assert.deepEqual(
      midEdit.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      ["function:editing:1-2", "function:intact_after:4-6"],
    );
  });

  it("extracts Vue SFC blocks, CSS structure, TS no-semi types, multiline object-param functions, and Fastify routes", () => {
    const vueSyms = extractSymbols(
      "App.vue",
      [
        '<script setup lang="ts">',
        "interface NavItem { label: string }",
        "function toggleMenu() {",
        "  return true",
        "}",
        "</script>",
        "",
        "<template>",
        "  <header class=\"top-bar\">",
        "    <template #slotA>nested</template>",
        "  </header>",
        ...Array.from({ length: 32 }, (_, i) => `  <div>row ${i}</div>`),
        "  <!-- Modal Section -->",
        "  <ConfirmModal />",
        "</template>",
        "",
        "<style scoped>",
        "/* Layout */",
        "@media (max-width: 768px) {",
        "  .top-bar { display: none; }",
        "}",
        "</style>",
      ].join("\n"),
    );
    assert.ok(vueSyms.some((s) => s.kind === "script" && s.startLine === 1 && s.endLine === 6));
    assert.ok(vueSyms.some((s) => s.kind === "function" && s.name === "toggleMenu" && s.startLine === 3));
    assert.ok(vueSyms.some((s) => s.kind === "template" && s.startLine === 8 && s.endLine === 46));
    assert.ok(vueSyms.some((s) => s.kind === "style" && s.startLine === 48 && s.endLine === 53));
    assert.ok(vueSyms.some((s) => s.kind === "@media" && s.startLine === 50));

    const cssSyms = extractSymbols(
      "base.css",
      [
        "/* === Design Tokens === */",
        ":root {",
        "  --accent: #111;",
        "}",
        '[data-theme="dark"] {',
        "  --accent: #fff;",
        "}",
        "@keyframes fadeIn {",
        "  from { opacity: 0; }",
        "  to { opacity: 1; }",
        "}",
        "@media (max-width: 900px) {",
        "  .grid { display: block; }",
        "}",
      ].join("\n"),
    );
    assert.ok(cssSyms.some((s) => s.kind === "section" && s.name === "Design Tokens"));
    assert.ok(cssSyms.some((s) => s.kind === "tokens" && s.name === ":root" && s.endLine === 4));
    assert.ok(cssSyms.some((s) => s.kind === "tokens" && s.name.includes("data-theme") && s.endLine === 7));
    assert.ok(cssSyms.some((s) => s.kind === "@keyframes" && s.name === "fadeIn"));
    assert.ok(cssSyms.some((s) => s.kind === "@media"));

    const tsNoSemiSyms = extractSymbols(
      "runtime.ts",
      [
        "export type RuntimeMode = 'simulation' | 'live'",
        "",
        "export interface EnvConfig {",
        "  dbPath: string",
        "}",
        "",
        "export async function startServer(",
        "  options: { port: number; host?: string },",
        "): Promise<{ ok: boolean }> {",
        ...Array.from({ length: 42 }, (_, i) => `  const line${i} = ${i}`),
        "  app.get('/api/health', async () => {",
        "    return { ok: true }",
        "  })",
        "  return { ok: true }",
        "}",
      ].join("\n"),
    );
    const modeSym = tsNoSemiSyms.find((s) => s.name === "RuntimeMode");
    const fnSym = tsNoSemiSyms.find((s) => s.name === "startServer");
    const routeSym = tsNoSemiSyms.find((s) => s.kind === "route" && s.name === "GET /api/health");
    assert.ok(modeSym && modeSym.startLine === 1 && modeSym.endLine === 1, `Bad type span: ${JSON.stringify(modeSym)}`);
    assert.ok(fnSym && fnSym.startLine === 7 && fnSym.endLine === 56, `Bad fn span: ${JSON.stringify(fnSym)}`);
    assert.ok(routeSym && routeSym.startLine === 52 && routeSym.endLine === 54, `Bad route: ${JSON.stringify(routeSym)}`);
  });

  it("supports up to 40 outlines with multi-file fairness and hard-caps explicit maxChars <= 8800 UTF-8 bytes", async () => {
    const manyDir = path.join(tmpDir, "many-outlines");
    await fs.mkdir(manyDir, { recursive: true });
    const paths: string[] = [];
    for (let i = 0; i < 24; i++) {
      const rel = `many-outlines/f${i}.ts`;
      paths.push(rel);
      const body =
        i === 0
          ? [
              "export class HugeStore {",
              ...Array.from({ length: 60 }, (_, m) => `  method${m}() { return ${m}; }`),
              "}",
              "export function tailHelper() { return 1; }",
            ].join("\n")
          : `export function fn${i}() { return ${i}; }\n`;
      await fs.writeFile(path.join(tmpDir, rel), body, "utf8");
    }

    const outlineRes = await runReadSlices({ cwd: tmpDir, outlines: paths });
    assert.equal(outlineRes.isError, false);
    assert.ok(Buffer.byteLength(outlineRes.text, "utf8") <= 8_800);
    // Water-filling returns unused budget from the 23 tiny sibling files to f0.ts,
    // preserving all 60 methods + depth-0 tailHelper + fn23 without premature cuts
    assert.match(outlineRes.text, /method0/);
    assert.match(outlineRes.text, /method59/);
    assert.match(outlineRes.text, /tailHelper/);
    assert.match(outlineRes.text, /fn23/);
    assert.doesNotMatch(outlineRes.text, /omitted/);

    const tooMany = await runReadSlices({
      cwd: tmpDir,
      outlines: Array.from({ length: 41 }, () => paths[0]!),
    });
    assert.equal(tooMany.isError, true);
    assert.match(tooMany.text, /max 40 outlines/);

    // Explicit maxChars: 42000 must still stay <= 8800 bytes and surface read_file tip
    const bigSliceFile = path.join(tmpDir, "big-slice.ts");
    await fs.writeFile(
      bigSliceFile,
      Array.from({ length: 300 }, (_, i) => `export const row_${i} = "${"中文测试".repeat(10)}";`).join("\n"),
      "utf8",
    );
    const capped = await runReadSlices({
      cwd: tmpDir,
      slices: [{ path: "big-slice.ts", ranges: [[1, 300]] }],
      maxChars: 42_000,
    });
    assert.equal(capped.isError, false);
    assert.ok(
      Buffer.byteLength(capped.text, "utf8") <= 8_800,
      `Expected <= 8800B, got ${Buffer.byteLength(capped.text, "utf8")}`,
    );
    assert.match(capped.text, /use parallel read_file/);

    // Outlining >20 dense files stays <= 8800 bytes and surfaces batch-size tip when over budget
    const denseDir = path.join(tmpDir, "dense-outlines");
    await fs.mkdir(denseDir, { recursive: true });
    const densePaths: string[] = [];
    for (let i = 0; i < 30; i++) {
      const rel = `dense-outlines/module_${String(i).padStart(2, "0")}.ts`;
      densePaths.push(rel);
      const body = Array.from(
        { length: 25 },
        (_, k) => `export function handler_${i}_${k}_veryLongSymbolNameForBudgetTest() { return ${k}; }`,
      ).join("\n");
      await fs.writeFile(path.join(tmpDir, rel), body, "utf8");
    }
    const denseRes = await runReadSlices({ cwd: tmpDir, outlines: densePaths });
    assert.equal(denseRes.isError, false);
    assert.ok(
      Buffer.byteLength(denseRes.text, "utf8") <= 8_800,
      `Expected <= 8800B, got ${Buffer.byteLength(denseRes.text, "utf8")}`,
    );
    assert.match(denseRes.text, /module_29\.ts/);
    assert.match(denseRes.text, /more top-level symbols in L\d+-L25 omitted; use batch_search or read_file/);
    assert.match(denseRes.text, /batch 10-20 files per call/);
  });

  it("extracts Godot GDScript (.gd) outlines across comments, triple strings, nested inner classes, multiline enums, and Windows BOM/CRLF", async () => {
    const gdLines = [
      "\uFEFF@tool",
      "class_name CharacterController extends CharacterBody2D",
      "## Base controller for playable characters.",
      "",
      "signal health_changed(current: int, maximum: int)",
      "signal combo_triggered(",
      "\tcombo_name: StringName,",
      "\thit_count: int,",
      ")",
      "",
      "enum MoveState { IDLE, RUN, AIR }",
      "",
      "enum DamageType {",
      "\tPHYSICAL = 0,",
      "\tMAGICAL = 1, # ignores { fake } braces in comment",
      "\tTRUE_DMG = 2,",
      "}",
      "",
      "enum {",
      "\tLAYER_WORLD = 1,",
      "\tLAYER_ACTOR = 2,",
      "}",
      "",
      'const SHADER_STUB := """',
      "class FakeShaderClass:",
      "\tfunc fake_func():",
      "\t\tpass",
      '"""',
      "",
      "const DOC_SINGLE := '''",
      "signal fake_signal",
      "enum FakeEnum { A, B }",
      "'''",
      "",
      "# func commented_out_func():",
      "# \tpass",
      "",
      "static func calc_mitigation(raw: float, armor: float) -> float:",
      "\treturn raw * (100.0 / (100.0 + armor))",
      "",
      "## Applies damage to this character.",
      '@rpc("any_peer", "call_local")',
      "func apply_damage(",
      "\tamount: int,",
      "\tkind: DamageType = DamageType.PHYSICAL,",
      ") -> void:",
      '\tvar note := """',
      "unindented multiline text inside function",
      '"""',
      "\tif amount > 0:",
      "\t\thealth_changed.emit(0, 100)",
      "",
      "class StateMachine:",
      "\tsignal state_entered(state_name: StringName)",
      "",
      "\tclass SubState:",
      "\t\tfunc tick(delta: float) -> void:",
      "\t\t\tpass",
      "",
      "\t## Transitions to target state.",
      "\tfunc transition_to(target: StringName) -> void:",
      "\t\tstate_entered.emit(target)",
    ];

    const gdContentCrlf = gdLines.join("\r\n");
    const gdSyms = extractSymbols("player.gd", gdContentCrlf);
    assert.deepEqual(
      gdSyms.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}:d${s.depth}`),
      [
        "class_name:CharacterController:2-2:d0",
        "signal:health_changed:5-5:d0",
        "signal:combo_triggered:6-9:d0",
        "enum:MoveState:11-11:d0",
        "enum:DamageType:13-17:d0",
        "enum:<anonymous>:19-22:d0",
        "function:calc_mitigation:38-39:d0",
        "function:apply_damage:43-51:d0",
        "class:StateMachine:53-62:d0",
        "signal:state_entered:54-54:d1",
        "class:SubState:56-58:d1",
        "method:tick:57-58:d2",
        "method:transition_to:61-62:d1",
      ],
    );

    // Also verify BOM on line 1 inline `@tool class_name` + 4-space indentation + runReadSlices formatting
    const spaceGdPath = path.join(tmpDir, "inventory.gd");
    await fs.writeFile(
      spaceGdPath,
      [
        "\uFEFF@tool class_name Inventory",
        "class Slot:",
        "    static func empty() -> Slot:",
        "        return Slot.new()",
        "",
        '@rpc("authority") func sync_slots() -> void:',
        "    pass",
      ].join("\r\n"),
      "utf8",
    );

    const sliceRes = await runReadSlices({
      cwd: tmpDir,
      outlines: ["inventory.gd"],
    });
    assert.equal(sliceRes.isError, false);
    assert.match(sliceRes.text, /L1 \[class_name\] Inventory/);
    assert.match(sliceRes.text, /L2-L4 \[class\] Slot/);
    assert.match(sliceRes.text, /  L3-L4 \[method\] empty/);
    assert.match(sliceRes.text, /L6-L7 \[function\] sync_slots/);
  });

  it("circuit-breaks corrupted outlines/slices arguments cleanly without throwing", async () => {
    const badOutlines = await runReadSlices({
      cwd: tmpDir,
      outlines: [true, null] as unknown as string[],
    });
    assert.equal(badOutlines.isError, true);
    assert.match(badOutlines.text, /nested argument serialization corruption/i);
    assert.match(badOutlines.text, /outlines\[0\]: received boolean \(true\)/);

    const badSlices = await runReadSlices({
      cwd: tmpDir,
      slices: [false] as unknown as never[],
    });
    assert.equal(badSlices.isError, true);
    assert.match(badSlices.text, /slices\[0\]: received boolean \(false\)/);
    assert.match(badSlices.text, /read_file/);

    const stringified = await runReadSlices({
      cwd: tmpDir,
      outlines: JSON.stringify(["inventory.gd"]) as unknown as string[],
    });
    assert.equal(stringified.isError, false);
    assert.match(stringified.text, /L1 \[class_name\] Inventory/);
  });

  it("handles JSX tags, TS template literals, Python multiline signatures, Rust lifetimes, Shell ${#var}, Go raw strings, non-finite maxChars, and lone surrogates", async () => {
    // 1. TSX closing </Tag> and self-closing /> must not enter regex mode and leak brace depth
    const tsxClose = extractSymbols(
      "App.tsx",
      [
        "export function A({ xs }: { xs: string[] }) {",
        "  return <ul>{xs.map((x) => <li>{x}</li>)}</ul>;",
        "}",
        "export function B() { return <div />; }",
      ].join("\n"),
    );
    assert.deepEqual(
      tsxClose.map((s) => `${s.name}:${s.startLine}-${s.endLine}`),
      ["A:1-3", "B:4-4"],
    );

    const tsxSelfClose = extractSymbols(
      "Icon.tsx",
      [
        "export function A() {",
        "  return <div>{ok && <Icon s={1} />}</div>;",
        "}",
        "export function B() { return null; }",
      ].join("\n"),
    );
    assert.deepEqual(
      tsxSelfClose.map((s) => `${s.name}:${s.startLine}-${s.endLine}`),
      ["A:1-3", "B:4-4"],
    );

    // JS/TS regex literals starting with `>` (e.g. `/>/g`, `/>}/`) must still enter regex mode
    for (const fname of ["escape.ts", "escape.tsx"]) {
      const gtRegex = extractSymbols(
        fname,
        [
          "export function escapeHtml(s: string) {",
          '  return s.replace(/>/g, "&gt;").replace(/{/g, "&#123;");',
          "}",
          "export function closeBraceRegex(s: string) {",
          "  return />}/.test(s);",
          "}",
          "export function after() { return 1; }",
        ].join("\n"),
      );
      assert.deepEqual(
        gtRegex.map((s) => `${s.name}:${s.startLine}-${s.endLine}`),
        ["escapeHtml:1-3", "closeBraceRegex:4-6", "after:7-7"],
      );
    }

    // 2. TS multiline backtick template must not emit fake symbols or swallow real classes below
    const tplSyms = extractSymbols(
      "tpl.ts",
      ["const s = `", "export class Fake {", "`;", "export class Real {", "  m() {}", "}"].join("\n"),
    );
    assert.deepEqual(
      tplSyms.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      ["class:Real:4-6", "method:m:5-5"],
    );

    // 3. Python multiline signatures & .pyi stubs
    const pyMulti = extractSymbols(
      "stub.pyi",
      ["def f(", "    a: int,", ") -> int:", "    return a"].join("\n"),
    );
    assert.deepEqual(
      pyMulti.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      ["function:f:1-4"],
    );

    // 4. Rust lifetimes, impl<T>, trait bounds, and block comments
    const rsSyms = extractSymbols(
      "lib.rs",
      [
        "/* pub fn commented_out() {} */",
        "pub struct View<'a> {",
        "  buf: &'a [u8],",
        "}",
        "impl<T> Cache<T> {",
        "  pub fn next<U: Clone + Send>() -> usize { 1 }",
        "}",
      ].join("\n"),
    );
    assert.deepEqual(
      rsSyms.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      ["struct:View<'a>:2-4", "impl:<T> Cache<T>:5-7", "fn:next<U: Clone + Send>:6-6"],
    );

    // 5. Shell parameter expansion with `#` inside `${...}`
    const shSyms = extractSymbols(
      "s.sh",
      ["f() {", "  local b=${1##*/}", "  local n=${#b}", '  echo "$b $n"', "}", "g() { :; }"].join("\n"),
    );
    assert.deepEqual(
      shSyms.map((s) => `${s.name}:${s.startLine}-${s.endLine}`),
      ["f:1-5", "g:6-6"],
    );

    // 6. Go raw backtick string ending in `\` & wrapped `interface{}` params & generic struct
    const goSyms = extractSymbols(
      "a.go",
      [
        "type Box[T any] struct {",
        "  Val T",
        "}",
        "func a() {",
        "  s := `dir\\`",
        "  _ = s",
        "}",
        "func c(",
        "  v interface{},",
        ") {",
        "  a()",
        "}",
      ].join("\n"),
    );
    assert.deepEqual(
      goSyms.map((s) => `${s.kind}:${s.name}:${s.startLine}-${s.endLine}`),
      ["struct:Box[T any]:1-3", "function:a:4-7", "function:c:8-12"],
    );

    // 7. Non-finite maxChars falls back cleanly instead of returning empty output, and single-line emoji truncation avoids lone surrogates
    const longEmoji = path.join(tmpDir, "long-emoji.md");
    await fs.writeFile(longEmoji, "a".repeat(938) + "🚀".repeat(50) + "\n", "utf8");
    const nanRes = await runReadSlices({
      cwd: tmpDir,
      outlines: ["sample.ts"],
      maxChars: "auto" as unknown as number,
    });
    assert.equal(nanRes.isError, false);
    assert.match(nanRes.text, /\[class\] Server/);

    const surrRes = await runReadSlices({
      cwd: tmpDir,
      slices: [{ path: "long-emoji.md", ranges: [[1, 1]] }],
      maxChars: 1000,
    });
    assert.equal(surrRes.isError, false);
    assert.equal(
      /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(surrRes.text),
      false,
      "read_slices output must not contain lone UTF-16 surrogates",
    );
  });

  it("supports quick_outline flat paths API, forgiving aliases, and corrupted-arg circuit-breaking", async () => {
    const res = await runQuickOutline({
      cwd: tmpDir,
      paths: ["sample.ts"],
    });
    assert.equal(res.isError, false);
    assert.match(res.text, /## Outline: sample\.ts/);
    assert.match(res.text, /\[class\] Server/);

    // Stringified JSON array compatibility
    const strRes = await runQuickOutline({
      cwd: tmpDir,
      paths: '["sample.ts"]' as unknown as string[],
    });
    assert.equal(strRes.isError, false);
    assert.match(strRes.text, /\[class\] Server/);

    // Forgiving alias fallback (`outlines` / `files`) and `paths` precedence
    const aliasRes = await runQuickOutline({
      cwd: tmpDir,
      outlines: ["sample.ts"],
    } as unknown as Parameters<typeof runQuickOutline>[0]);
    assert.equal(aliasRes.isError, false);
    assert.match(aliasRes.text, /\[class\] Server/);

    const filesAliasRes = await runQuickOutline({
      cwd: tmpDir,
      files: ["sample.ts"],
    } as unknown as Parameters<typeof runQuickOutline>[0]);
    assert.equal(filesAliasRes.isError, false);
    assert.match(filesAliasRes.text, /\[class\] Server/);

    const precedenceRes = await runQuickOutline({
      cwd: tmpDir,
      paths: ["sample.ts"],
      outlines: ["nonexistent-ignored.ts"],
    } as unknown as Parameters<typeof runQuickOutline>[0]);
    assert.equal(precedenceRes.isError, false);
    assert.match(precedenceRes.text, /\[class\] Server/);

    // Corrupted payloads (including mixed invalid + corrupted arrays) ALWAYS trigger circuit-breaker advice
    for (const bad of [false, null, "false", "null", [true], [null], [false, ""], ["", false], [123, true], [null, 123]]) {
      const badRes = await runQuickOutline({
        cwd: tmpDir,
        paths: bad as unknown as string[],
      });
      assert.equal(badRes.isError, true);
      assert.match(badRes.text, /serialization corruption detected/i);
      assert.match(badRes.text, /quick_outline/);
    }

    // Empty / missing / non-array / blank / >40 paths return clean validation errors
    for (const invalid of [[], "", "{}", {}, [123], ["   "]]) {
      const invalidRes = await runQuickOutline({
        cwd: tmpDir,
        paths: invalid as unknown as string[],
      });
      assert.equal(invalidRes.isError, true);
      assert.doesNotMatch(invalidRes.text, /serialization corruption detected/i);
    }

    const missingRes = await runQuickOutline({ cwd: tmpDir });
    assert.equal(missingRes.isError, true);

    const tooManyRes = await runQuickOutline({
      cwd: tmpDir,
      paths: Array.from({ length: 41 }, (_, i) => `f${i}.ts`),
    });
    assert.equal(tooManyRes.isError, true);
    assert.match(tooManyRes.text, /max 40/);

    // quick_outline inherits HTML closed-range extraction and BFS water-filling
    const htmlQuickPath = path.join(tmpDir, "quick.html");
    await fs.writeFile(
      htmlQuickPath,
      [
        "<body>",
        '  <main><section id="hero"><Modal /></section></main>',
        "</body>",
      ].join("\n"),
      "utf8",
    );
    const htmlQuickRes = await runQuickOutline({ cwd: tmpDir, paths: ["quick.html"] });
    assert.equal(htmlQuickRes.isError, false);
    assert.match(htmlQuickRes.text, /\[block\] <body>/);
    assert.match(htmlQuickRes.text, /\[block\] <section #hero>/);
    assert.match(htmlQuickRes.text, /\[component\] <Modal>/);
  });

  it("extracts .html/.htm, Vue, and Svelte closed-range outlines safely across edge cases and linear-time DoS guards", async () => {
    const htmlDoc = [
      "<!DOCTYPE html>", // 1
      '<html lang="en">', // 2
      "  <head>", // 3
      "    <title>Compare <section> vs <main></title>", // 4 (RCDATA: must NOT emit phantom landmarks)
      '    <meta charset="utf-8">', // 5
      "    <style>", // 6
      "      /* === Theme Tokens === */", // 7
      "      :root { --accent: #09f; }", // 8
      "      @media (max-width: 768px) {", // 9
      "        body { font-size: 14px; }", // 10
      "      }", // 11
      "    </style>", // 12
      '    <script src="/vendor/bundle.js"></script>', // 13
      "  </head>", // 14
      "  <body>", // 15
      "    <!-- === Header === -->", // 16
      "    <!--> <!-- bang comment --!>", // 17 (HTML5 comment edge cases must not swallow body)
      '    <header class="flex"><nav role="navigation"><ul><li><img src="/a.png"><br></li></ul></nav></header>', // 18
      "    <!--", // 19
      '      <section id="commented-out"></section>', // 20
      "    -->", // 21
      '    <textarea><section id="inside-ta">x</section><script>var a=1;</textarea>', // 22 (RCDATA: no phantom or swallow)
      '    <div class="plain-wrapper"><div id="app"><main><section id="settings"><form id="prefs-form"></form></section></main></div></div>', // 23
      '    <div id="multi\nline">x</div>', // 24-25 (multiline id normalized to single line)
      "    <footer id=\"real-footer\">ok</footer>", // 26
      '    <script type="module">/* banner */', // 27 (opening-line code + col-0 template + mixed tabs)
      "      const sql = `SELECT *", // 28
      "FROM users`;", // 29
      "      function bootApp() {", // 30
      "\t\treturn sql;", // 31
      "      }", // 32
      "    </script>", // 33
      "  </body>", // 34
      "</html>", // 35
    ].join("\n");

    const htmlSyms = extractSymbols("index.html", htmlDoc);
    assert.deepEqual(extractSymbols("legacy.htm", htmlDoc), htmlSyms);
    assert.ok(htmlSyms.every((s) => s.depth >= 0 && s.depth <= 2 && s.endLine >= s.startLine));
    assert.ok(htmlSyms.every((s) => !s.name.includes("\n")));
    assert.ok(htmlSyms.some((s) => s.kind === "block" && s.name === "<head>" && s.startLine === 3 && s.endLine === 14));
    assert.ok(htmlSyms.some((s) => s.kind === "tokens" && s.name === ":root"));
    assert.ok(htmlSyms.some((s) => s.kind === "script" && s.name === '<script src="/vendor/bundle.js">'));
    assert.ok(htmlSyms.some((s) => s.kind === "section" && s.name === "Header" && s.startLine === 16));
    assert.ok(htmlSyms.some((s) => s.kind === "block" && s.name === "<header>" && s.startLine === 18));
    assert.ok(htmlSyms.some((s) => s.kind === "block" && s.name === "<footer #real-footer>"));
    assert.ok(htmlSyms.some((s) => s.kind === "block" && s.name === "<div #multi line>"));
    // Dedent fix: inline script with opening-line comment + col-0 template literal + tabs keeps bootApp()!
    assert.ok(htmlSyms.some((s) => s.kind === "function" && s.name === "bootApp" && s.startLine === 30 && s.endLine === 32));
    // Exclusions: RCDATA inner tags, commented-out tags, plain-class wrapper
    assert.ok(!htmlSyms.some((s) => s.name.includes("inside-ta") || s.name.includes("commented-out") || s.name.includes("plain-wrapper")));
    assert.equal(htmlSyms.filter((s) => s.name === "<section>").length, 0);

    // Standalone component landmarks (<Modal />, <Drawer />, <Panel />, <Tabs.Panel />) + Vue body mustache + <template v-if> filtering
    const vueDoc = [
      '<script setup lang="ts">',
      "  function save() { return true; }",
      "</script>",
      "<template>",
      "  <main>",
      "    <p>{{ a<section && items.some(x => x.ok) }}</p>",
      '    <template v-if="ready"><Modal /><Drawer /><Panel /><Tabs.Panel /></template>',
      "    <template #footer><footer id=\"slot-footer\">ok</footer></template>",
      "  </main>",
      "</template>",
    ].join("\n");
    const vueSyms = extractSymbols("App.vue", vueDoc);
    assert.ok(vueSyms.some((s) => s.kind === "function" && s.name === "save"));
    assert.ok(vueSyms.some((s) => s.kind === "template" && s.name === "<template>"));
    assert.ok(vueSyms.some((s) => s.kind === "template" && s.name === "<template #footer>"));
    assert.equal(vueSyms.filter((s) => s.name === "<template>").length, 1); // <template v-if> skipped!
    assert.ok(vueSyms.some((s) => s.kind === "component" && s.name === "<Modal>"));
    assert.ok(vueSyms.some((s) => s.kind === "component" && s.name === "<Drawer>"));
    assert.ok(vueSyms.some((s) => s.kind === "component" && s.name === "<Panel>"));
    assert.ok(vueSyms.some((s) => s.kind === "component" && s.name === "<Tabs.Panel>"));
    assert.equal(vueSyms.filter((s) => s.name === "<section>").length, 0);

    // Svelte body expressions `{@html '</div>'}` and `{#if x<script && y>0}` must NOT corrupt stack or swallow EOF
    const svelteDoc = [
      "<main>",
      '  <div id="content">',
      "    {@html '</div>'}",
      "    {#if x<script && y>0}",
      '      <section id="inside"><SettingsModal /></section>',
      "    {/if}",
      "  </div>",
      '  <footer id="after">done</footer>',
      "</main>",
    ].join("\n");
    const svelteSyms = extractSymbols("Safe.svelte", svelteDoc);
    assert.deepEqual(
      svelteSyms.map((s) => `${s.name}:${s.startLine}-${s.endLine}:d${s.depth}`),
      [
        "<main>:1-9:d0",
        "<div #content>:2-7:d1",
        "<section #inside>:5-5:d2",
        "<SettingsModal>:5-5:d2",
        "<footer #after>:8-8:d1",
      ],
    );

    // Processing instruction with apostrophe `<?php // don't ?>` must NOT swallow file
    const phpSyms = extractSymbols(
      "view.html",
      "<?php // don't swallow ?>\n<main><footer id=\"ok\">x</footer></main>",
    );
    assert.ok(phpSyms.some((s) => s.name === "<footer #ok>"));

    // Linear-time DoS guards: 20k stray closes, 10k unclosed <script src>, 50k `{` in tag, 3k `<div {`, 150k unclosed Svelte/Vue body braces
    const t0 = performance.now();
    extractSymbols("dos1.html", "<div>".repeat(20_000) + "</span>".repeat(20_000));
    extractSymbols("dos2.html", '<script src="x.js">\n'.repeat(10_000));
    extractSymbols("dos3.html", `<div ${"{".repeat(50_000)}>`);
    extractSymbols("dos4.html", "<div {".repeat(3_000) + "}".repeat(3_000));
    const svelteDos = extractSymbols("dos5.svelte", "{".repeat(150_000) + "<main>ok</main>");
    const vueDos = extractSymbols("dos6.vue", "{{".repeat(75_000) + "<main>ok</main>");
    const dosMs = performance.now() - t0;
    assert.ok(dosMs < 2000, `Expected linear-time DoS handling (<2000ms total), got ${dosMs.toFixed(1)}ms`);
    assert.ok(svelteDos.some((s) => s.name === "<main>"));
    assert.ok(vueDos.some((s) => s.name === "<main>"));
  });

  it("packs overflowing outlines breadth-first with exact L<min>-L<max> ranges even under tight budgets", async () => {
    const bfDir = path.join(tmpDir, "breadth-first");
    await fs.mkdir(bfDir, { recursive: true });

    // 1. Breadth-first: depth 0 survives before depth 1 backfills
    const classRel = "breadth-first/giant_class.ts";
    const classBody = [
      "export class GiantEngine {",
      ...Array.from({ length: 100 }, (_, i) => `  method_${String(i).padStart(3, "0")}() { return ${i}; }`),
      "}",
      "export function trailingInit() { return 1; }",
      "export function trailingSync() { return 2; }",
      "export function trailingShutdown() { return 3; }",
    ].join("\n");
    await fs.writeFile(path.join(tmpDir, classRel), classBody, "utf8");

    const res = await runReadSlices({ cwd: tmpDir, outlines: [classRel], maxChars: 1_200 });
    assert.equal(res.isError, false);
    assert.ok(res.text.length <= 1_200);
    assert.match(res.text, /\[class\] GiantEngine/);
    assert.match(res.text, /\[function\] trailingInit/);
    assert.match(res.text, /\[function\] trailingShutdown/);
    assert.match(res.text, /method_000\b/);
    assert.doesNotMatch(res.text, /method_099\b/);
    assert.match(res.text, /\n\.\.\. \(\+\d+ nested symbols omitted\)$/);

    // 2. Tight per-file budget (10 single-class files at maxChars: 1000) must preserve class symbol without raw double-truncation
    const tightDir = path.join(tmpDir, "tight-class-batch");
    await fs.mkdir(tightDir, { recursive: true });
    const tightPaths: string[] = [];
    for (let i = 0; i < 10; i++) {
      const rel = `tight-class-batch/engine_${i}.ts`;
      tightPaths.push(rel);
      const body = [
        `export class Engine_${i} {`,
        ...Array.from({ length: 50 }, (_, m) => `  run_${m}() { return ${m}; }`),
        "}",
      ].join("\n");
      await fs.writeFile(path.join(tmpDir, rel), body, "utf8");
    }
    const tightRes = await runReadSlices({ cwd: tmpDir, outlines: tightPaths, maxChars: 1_000 });
    assert.equal(tightRes.isError, false);
    assert.ok(tightRes.text.length <= 1_000);
    assert.match(tightRes.text, /\[class\] Engine_0/);
    assert.match(tightRes.text, /\[class\] Engine_9/);
    assert.doesNotMatch(tightRes.text, /\[truncated: showed \d+ of/);

    // 3. Giant top-level file (ASCII + CJK + ##-only Markdown) emits exact L<min>-L<max>
    const asciiRel = "breadth-first/many_funcs.ts";
    const asciiLines: string[] = [];
    for (let i = 0; i < 300; i++) {
      asciiLines.push(`export function computePipelineStage_${String(i).padStart(3, "0")}() {`, `  return ${i};`, "}");
    }
    await fs.writeFile(path.join(tmpDir, asciiRel), asciiLines.join("\n"), "utf8");
    const asciiRes = await runReadSlices({ cwd: tmpDir, outlines: [asciiRel] });
    assert.equal(asciiRes.isError, false);
    assert.ok(Buffer.byteLength(asciiRes.text, "utf8") <= 8_800);
    const asciiMatch = /\n\.\.\. \(\+(\d+) more top-level symbols in L(\d+)-L(\d+) omitted; use batch_search or read_file\)$/.exec(asciiRes.text);
    assert.ok(asciiMatch);
    assert.equal(Number(asciiMatch[2]), (300 - Number(asciiMatch[1])) * 3 + 1);
    assert.equal(Number(asciiMatch[3]), 900);

    const h2Rel = "breadth-first/h2_only.md";
    const h2Lines: string[] = [];
    for (let i = 0; i < 80; i++) {
      h2Lines.push(`## Section_${String(i).padStart(2, "0")}_LongHeadingForBudgetTest`, "Body.");
    }
    await fs.writeFile(path.join(tmpDir, h2Rel), h2Lines.join("\n"), "utf8");
    const h2Res = await runReadSlices({ cwd: tmpDir, outlines: [h2Rel], maxChars: 1_200 });
    assert.equal(h2Res.isError, false);
    assert.ok(h2Res.text.length <= 1_200);
    const h2Match = /\n\.\.\. \(\+(\d+) more top-level symbols in L(\d+)-L(\d+) omitted; use batch_search or read_file\)$/.exec(h2Res.text);
    assert.ok(h2Match);
    assert.equal(Number(h2Match[2]), (80 - Number(h2Match[1])) * 2 + 1);
    assert.equal(Number(h2Match[3]), 160);
  });

  it("supports flat lineRanges and string slice shorthand including multi-range and single-line specs", async () => {
    const fileRel = "shorthand/sample.ts";
    await fs.mkdir(path.join(tmpDir, "shorthand"), { recursive: true });
    await fs.writeFile(
      path.join(tmpDir, fileRel),
      [
        "const line1 = 'one';",
        "const line2 = 'two';",
        "const line3 = 'three';",
        "const line4 = 'four';",
        "const line5 = 'five';",
        "const line6 = 'six';",
      ].join("\n") + "\n",
      "utf8",
    );

    // 1. Flat lineRanges parameter with multi-range and single-line spec
    const res1 = await runReadSlices({
      cwd: tmpDir,
      lineRanges: [`${fileRel}:1-2,5-6`, `${fileRel}:4`],
    });
    assert.equal(res1.isError, false);
    assert.match(res1.text, /const line1 = 'one'/);
    assert.match(res1.text, /const line2 = 'two'/);
    assert.doesNotMatch(res1.text, /const line3 = 'three'/);
    assert.match(res1.text, /const line4 = 'four'/);
    assert.match(res1.text, /const line5 = 'five'/);
    assert.match(res1.text, /const line6 = 'six'/);

    // 2. Runtime string shorthand inside slices[] alongside object form
    const res2 = await runReadSlices({
      cwd: tmpDir,
      slices: [`${fileRel}:2-3`, { path: fileRel, ranges: [[6, 6]] }],
    });
    assert.equal(res2.isError, false);
    assert.match(res2.text, /const line2 = 'two'/);
    assert.match(res2.text, /const line3 = 'three'/);
    assert.match(res2.text, /const line6 = 'six'/);

    // 3. Windows drive-letter path splits on the last colon before ranges (hits ENOENT, not format error)
    const driveRes = await runReadSlices({
      cwd: tmpDir,
      lineRanges: ["C:\\nonexistent-agy-dir\\sample.ts:1-2"],
    });
    assert.equal(driveRes.isError, false);
    assert.match(driveRes.text, /ERROR:.*ENOENT|no such file/i);
    assert.doesNotMatch(driveRes.text, /path:start-end/);

    // 4. Missing line range returns clear shorthand format error
    const badSpec = await runReadSlices({
      cwd: tmpDir,
      lineRanges: ["src/missing-range.ts"],
    });
    assert.equal(badSpec.isError, true);
    assert.match(badSpec.text, /path:start-end/);

    // 5. Boolean/null corruption in lineRanges still trips corrupted-array circuit breaker
    const corrupted = await runReadSlices({
      cwd: tmpDir,
      lineRanges: [null as unknown as string],
    });
    assert.equal(corrupted.isError, true);
    assert.match(corrupted.text, /Validation failed/);
  });

  it("strips UTF-8 BOM cleanly on line-1 TS/JSON/YAML outlines and slices, decodes UTF-16 LE/BE, and keeps UTF-32 binary errors", async () => {
    const bomDir = path.join(tmpDir, "bom-utf16");
    await fs.mkdir(bomDir, { recursive: true });

    const utf8Bom = Buffer.from([0xef, 0xbb, 0xbf]);
    await fs.writeFile(
      path.join(bomDir, "bom.ts"),
      Buffer.concat([
        utf8Bom,
        Buffer.from("export function greet(name: string): string {\r\n  return name;\r\n}\r\n", "utf8"),
      ]),
    );
    await fs.writeFile(
      path.join(bomDir, "bom.json"),
      Buffer.concat([
        utf8Bom,
        Buffer.from('{\n  "service": "api",\n  "port": 3000\n}\n', "utf8"),
      ]),
    );
    await fs.writeFile(
      path.join(bomDir, "bom.yaml"),
      Buffer.concat([
        utf8Bom,
        Buffer.from("services:\n  web:\n    port: 8080\n", "utf8"),
      ]),
    );

    const bomRes = await runReadSlices({
      cwd: bomDir,
      outlines: ["bom.ts", "bom.json", "bom.yaml"],
      lineRanges: ["bom.ts:1-1", "bom.yaml:1-1"],
    });
    assert.equal(bomRes.isError, false);
    assert.match(bomRes.text, /L1-L3 \[function\] greet/);
    assert.match(bomRes.text, /\[key\] service/);
    assert.match(bomRes.text, /L1-L3 \[key\] services/);
    assert.ok(!bomRes.text.includes("\uFEFF"), "Slices must not leak invisible UTF-8 BOM");

    // BOM-marked UTF-16 LE and BE files are decoded for read-only outlines (writes still reject them)
    const utf16LeBuf = Buffer.concat([
      Buffer.from([0xff, 0xfe]),
      Buffer.from("export const ok = true;\r\n", "utf16le"),
    ]);
    const utf16BeText = Buffer.from("export const ok = true;\n", "utf16le");
    utf16BeText.swap16();
    const utf16BeBuf = Buffer.concat([Buffer.from([0xfe, 0xff]), utf16BeText]);
    // UTF-32 LE BOM (FF FE 00 00) must NOT be misclassified as UTF-16 LE
    const utf32LeBuf = Buffer.from([0xff, 0xfe, 0x00, 0x00, 0x41, 0x00, 0x00, 0x00]);

    await fs.writeFile(path.join(bomDir, "le.ps1"), utf16LeBuf);
    await fs.writeFile(path.join(bomDir, "be.rc"), utf16BeBuf);
    await fs.writeFile(path.join(bomDir, "u32.txt"), utf32LeBuf);

    const encRes = await runReadSlices({
      cwd: bomDir,
      outlines: ["le.ps1", "be.rc", "u32.txt"],
    });
    assert.equal(encRes.isError, false);
    assert.doesNotMatch(encRes.text, /UTF-16 encoded file is not supported/);
    assert.match(encRes.text, /## Outline: le\.ps1 \(2 lines\)/);
    assert.match(encRes.text, /## Outline: be\.rc \(2 lines\)/);
    assert.match(encRes.text, /u32\.txt\nERROR: Binary file cannot be read as text:/);
  });

  it("coerces bare single strings for paths/outlines/lineRanges, preserves corruption guards, and appends 1-line examples on validation errors", async () => {
    const bareDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-bare-str-"));
    try {
      await fs.writeFile(
        path.join(bareDir, "app.ts"),
        "export function alpha() {\n  return 1;\n}\nexport function beta() {\n  return 2;\n}\n",
        "utf8",
      );

      // 1. Bare single-string coercion works for quick_outline.paths, read_slices.outlines, and read_slices.lineRanges
      const qoRes = await runQuickOutline({
        cwd: bareDir,
        paths: "app.ts" as unknown as string[],
      });
      assert.equal(qoRes.isError, false);
      assert.match(qoRes.text, /L1-L3 \[function\] alpha/);

      const rsOutlineRes = await runReadSlices({
        cwd: bareDir,
        outlines: "app.ts" as unknown as string[],
      });
      assert.equal(rsOutlineRes.isError, false);
      assert.match(rsOutlineRes.text, /L4-L6 \[function\] beta/);

      const rsRangeRes = await runReadSlices({
        cwd: bareDir,
        lineRanges: "app.ts:1-3,4-6" as unknown as string[],
      });
      assert.equal(rsRangeRes.isError, false);
      assert.match(rsRangeRes.text, /export function alpha/);
      assert.match(rsRangeRes.text, /export function beta/);

      // 2. Corrupted literals ("true"/"false"/"null") and malformed JSON fragments starting with "[" or "{" NEVER coerce
      for (const lit of ["true", "false", "null"]) {
        const qoLit = await runQuickOutline({ cwd: bareDir, paths: lit as unknown as string[] });
        assert.equal(qoLit.isError, true);
        assert.match(qoLit.text, /serialization corruption detected/i);

        const rsLit = await runReadSlices({ cwd: bareDir, lineRanges: lit as unknown as string[] });
        assert.equal(rsLit.isError, true);
        assert.match(rsLit.text, /serialization corruption detected/i);
      }

      for (const frag of ['["app.ts', '{"path":"app.ts"', "{}", ""]) {
        const qoFrag = await runQuickOutline({ cwd: bareDir, paths: frag as unknown as string[] });
        assert.equal(qoFrag.isError, true);
        assert.match(qoFrag.text, /\nExample: \{"paths":\["src\/app\.ts"\]\}/);

        const rsOutFrag = await runReadSlices({ cwd: bareDir, outlines: frag as unknown as string[] });
        assert.equal(rsOutFrag.isError, true);
        assert.match(rsOutFrag.text, /\nExample: \{"outlines":\["src\/app\.ts"\]/);

        const rsRangeFrag = await runReadSlices({ cwd: bareDir, lineRanges: frag as unknown as string[] });
        assert.equal(rsRangeFrag.isError, true);
        assert.match(rsRangeFrag.text, /\nExample: \{"lineRanges":\["src\/app\.ts:1-60"\]\}/);
      }

      // 3. Validation errors include parseable 1-line Example JSON
      const badRange = await runReadSlices({
        cwd: bareDir,
        lineRanges: "not-a-range" as unknown as string[],
      });
      assert.equal(badRange.isError, true);
      const rangeEx = badRange.text.match(/\nExample: (\{.*\})$/);
      assert.ok(rangeEx, badRange.text);
      assert.deepEqual(JSON.parse(rangeEx[1]!), { lineRanges: ["src/app.ts:1-60"] });

      const emptySlice = await runReadSlices({ cwd: bareDir });
      assert.equal(emptySlice.isError, true);
      const emptyEx = emptySlice.text.match(/\nExample: (\{.*\})$/);
      assert.ok(emptyEx, emptySlice.text);
      assert.ok(Array.isArray(JSON.parse(emptyEx[1]!).outlines));
    } finally {
      await fs.rm(bareDir, { recursive: true, force: true });
    }
  });

  it("extracts Python Flask/FastAPI route, dataclass, and fixture metadata safely across comments and string literals", async () => {
    const pyDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-py-routes-"));
    try {
      await fs.writeFile(
        path.join(pyDir, "routes.py"),
        [
          "from dataclasses import dataclass",
          "import pytest",
          "",
          "@app.route('/api/items', methods=['GET', 'POST'])",
          "def list_items():",
          "    return []",
          "",
          "@app.route(",
          "    '/api/inline-comment',  # don't change (v1)",
          "    methods=('PUT', 'DELETE'),  # trailing )",
          ")  # after closing paren @dataclass",
          "def update_inline():",
          "    return True",
          "",
          "@app.route(rule='/api/rule', methods=['PATCH'])",
          "def patch_rule():",
          "    return {}",
          "",
          "@app.route(methods=['POST'], rule='/api/reordered')",
          "def reordered_rule():",
          "    return {}",
          "",
          "@router.post('/items', dependencies=[Depends(load(path='/wrong'))])",
          "async def create_item():",
          "    return {}",
          "",
          "@router.api_route(path='/v2/items', methods=['GET'])",
          "def get_v2():",
          "    return {}",
          "",
          "@dataclass(frozen=True)",
          "class ItemModel:",
          "    name: str",
          "",
          "@pytest.fixture(scope='module')",
          "def sample_item():",
          "    return ItemModel('ok')",
          "",
          "# @app.get('/ignored')",
          "@other  # not @dataclass",
          "@deprecated(\"use @app.get('/v2') and @pytest.fixture\")",
          "def plain():",
          "    return 42",
        ].join("\n") + "\n",
        "utf8",
      );

      const content = await fs.readFile(path.join(pyDir, "routes.py"), "utf8");
      const syms = extractSymbols("routes.py", content);
      const byName = new Map(syms.map((s) => [s.name, s]));
      assert.equal(byName.get("list_items")?.detail, "(route GET|POST /api/items)");
      assert.equal(byName.get("update_inline")?.detail, "(route PUT|DELETE /api/inline-comment)");
      assert.equal(byName.get("patch_rule")?.detail, "(route PATCH /api/rule)");
      assert.equal(byName.get("reordered_rule")?.detail, "(route POST /api/reordered)");
      assert.equal(byName.get("create_item")?.detail, "(route POST /items)");
      assert.equal(byName.get("get_v2")?.detail, "(route GET /v2/items)");
      assert.equal(byName.get("ItemModel")?.detail, "(@dataclass)");
      assert.equal(byName.get("sample_item")?.detail, "(@pytest.fixture)");
      assert.equal(byName.get("plain")?.detail, undefined);

      const outRes = await runReadSlices({ cwd: pyDir, outlines: ["routes.py"] });
      assert.equal(outRes.isError, false);
      assert.match(outRes.text, /\[function\] list_items \(route GET\|POST \/api\/items\)/);
      assert.match(outRes.text, /\[function\] update_inline \(route PUT\|DELETE \/api\/inline-comment\)/);
      assert.match(outRes.text, /\[function\] patch_rule \(route PATCH \/api\/rule\)/);
      assert.match(outRes.text, /\[function\] reordered_rule \(route POST \/api\/reordered\)/);
      assert.match(outRes.text, /\[function\] create_item \(route POST \/items\)/);
      assert.match(outRes.text, /\[function\] get_v2 \(route GET \/v2\/items\)/);
      assert.match(outRes.text, /\[class\] ItemModel \(@dataclass\)/);
      assert.match(outRes.text, /\[function\] sample_item \(@pytest\.fixture\)/);
      assert.match(outRes.text, /\[function\] plain\s*$/m);
    } finally {
      await fs.rm(pyDir, { recursive: true, force: true });
    }
  });

  it("rejects non-route mock/cache decorators, backslash-newline continuations, PEP 614 spoofing, and supports PEP 701 f-strings + route length cap", async () => {
    const pyDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-py-routes-edge-"));
    try {
      const longPath = "/" + "segment/".repeat(20) + "tail";
      await fs.writeFile(
        path.join(pyDir, "edge_cases.py"),
        [
          "from unittest import mock",
          "import unittest.mock",
          "import pytest",
          "",
          '@mock.patch("my_app.services.send_email")',
          "def test_send_email(mock_send):",
          "    pass",
          "",
          '@unittest.mock.patch("app.db.connect")',
          "@pytest.fixture",
          "def db_fixture():",
          "    return None",
          "",
          '@mock.patch("/leading/slash/mock")',
          "@pytest.fixture(scope='function')",
          "def slash_mock_fixture():",
          "    return None",
          "",
          '@cache.get("user_profile_v1")',
          "def get_profile():",
          "    return {}",
          "",
          '@responses.get("https://api.example.com/v1/users")',
          "def test_users_stub():",
          "    pass",
          "",
          '@app.GET("/uppercase-method")',
          "def uppercase_non_route():",
          "    pass",
          "",
          '@app.get("/api/\\',
          'items")',
          "def continued_literal():",
          "    return []",
          "",
          "@my_table[",
          '    """',
          "@app.get('/spoofed')",
          '    """',
          "]",
          "def subscript_decorated():",
          "    return 1",
          "",
          '@app.get(summary=f"Items for {user["a)b"]}", path="/pep701-items")',
          "def pep701_route():",
          "    return []",
          "",
          `@app.get("${longPath}")`,
          "def long_route():",
          "    return []",
        ].join("\n") + "\n",
        "utf8",
      );

      const content = await fs.readFile(path.join(pyDir, "edge_cases.py"), "utf8");
      const syms = extractSymbols("edge_cases.py", content);
      const byName = new Map(syms.map((s) => [s.name, s]));

      // P1 #1: non-route decorators ignored & stacked @pytest.fixture preserved
      assert.equal(byName.get("test_send_email")?.detail, undefined);
      assert.equal(byName.get("db_fixture")?.detail, "(@pytest.fixture)");
      assert.equal(byName.get("slash_mock_fixture")?.detail, "(@pytest.fixture)");
      assert.equal(byName.get("get_profile")?.detail, undefined);
      assert.equal(byName.get("test_users_stub")?.detail, undefined);
      assert.equal(byName.get("uppercase_non_route")?.detail, undefined);

      // P1 #2: backslash-newline continuation rejected (no raw newline in detail)
      assert.equal(byName.get("continued_literal")?.detail, undefined);

      // P2 #1: PEP 614 subscript decorator containing triple-quoted spoofed route
      assert.equal(byName.get("subscript_decorated")?.detail, undefined);

      // P2 #2: PEP 701 same-quote f-string before path= + long route display cap
      assert.equal(byName.get("pep701_route")?.detail, "(route GET /pep701-items)");
      const longDetail = byName.get("long_route")?.detail;
      assert.ok(longDetail && longDetail.startsWith("(route GET /segment/"));
      assert.ok(longDetail.endsWith("...)"));
      assert.ok(longDetail.length <= 120);

      // Ensure every formatted outline line stays strictly single-line
      const outRes = await runReadSlices({ cwd: pyDir, outlines: ["edge_cases.py"] });
      assert.equal(outRes.isError, false);
      assert.doesNotMatch(outRes.text, /route PATCH/);
      assert.doesNotMatch(outRes.text, /spoofed/);
      assert.match(outRes.text, /\[function\] db_fixture \(@pytest\.fixture\)/);
      assert.match(outRes.text, /\[function\] pep701_route \(route GET \/pep701-items\)/);
    } finally {
      await fs.rm(pyDir, { recursive: true, force: true });
    }
  });

  it("reads BOM-marked UTF-16 LE/BE files (e.g. Windows PowerShell 5.1 `>` output) in outlines and slices", async () => {
    const dir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-utf16-"));
    try {
      const py = "def 计算总价(items):\r\n    return sum(items)\r\n\r\nclass Order:\r\n    def total(self):\r\n        return 1\r\n";
      const le = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(py, "utf16le")]);
      const beBody = Buffer.from("alpha\r\nWARN: low memory\r\nomega\r\n", "utf16le").swap16();
      await fs.writeFile(path.join(dir, "u16le.py"), le);
      await fs.writeFile(path.join(dir, "build.log"), Buffer.concat([Buffer.from([0xfe, 0xff]), beBody]));

      const res = await runReadSlices({
        cwd: dir,
        outlines: ["u16le.py"],
        lineRanges: ["u16le.py:1-2", "build.log:2-2"],
      });
      assert.equal(res.isError, false);
      assert.doesNotMatch(res.text, /UTF-16 encoded file is not supported/);
      assert.match(res.text, /## Outline: u16le\.py \(7 lines\)/);
      assert.match(res.text, /L4-L6 \[class\] Order/);
      assert.match(res.text, /1: def 计算总价\(items\):/);
      assert.match(res.text, /2: WARN: low memory/);

      const outline = await runQuickOutline({ cwd: dir, paths: ["u16le.py"] });
      assert.match(outline.text, /\[method\] total/);

      // Only the file BOM is removed: a leading U+FEFF in the content itself survives.
      await fs.writeFile(
        path.join(dir, "feff.txt"),
        Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from("\uFEFFkeep\r\n", "utf16le")]),
      );
      // BOM-only file, odd payload length, lone surrogate, and BOM-prefixed binary (decoded NUL).
      await fs.writeFile(path.join(dir, "bom-only.txt"), Buffer.from([0xff, 0xfe]));
      await fs.writeFile(path.join(dir, "odd.txt"), Buffer.from([0xff, 0xfe, 0x41, 0x00, 0x42]));
      await fs.writeFile(path.join(dir, "lone.txt"), Buffer.from([0xff, 0xfe, 0x00, 0xd8, 0x41, 0x00]));
      await fs.writeFile(path.join(dir, "bin.dat"), Buffer.from([0xff, 0xfe, 0x41, 0x00, 0x00, 0x00, 0x42, 0x00]));
      const edge = await runReadSlices({
        cwd: dir,
        lineRanges: ["feff.txt:1-1", "bom-only.txt:1-1", "odd.txt:1-1", "lone.txt:1-1", "bin.dat:1-1"],
      });
      assert.match(edge.text, /1: \uFEFFkeep/);
      assert.match(edge.text, /## Slice: bom-only\.txt \(1 lines\)/);
      assert.match(edge.text, /odd\.txt\nERROR: Malformed UTF-16 file cannot be read as text: .*\[UTF-16 LE\]/);
      assert.match(edge.text, /lone\.txt\nERROR: Malformed UTF-16 file cannot be read as text: .*\[UTF-16 LE\]/);
      assert.match(edge.text, /bin\.dat\nERROR: Binary file cannot be read as text:/);
    } finally {
      await fs.rm(dir, { recursive: true, force: true });
    }
  });
});