import { describe, expect, test } from "vitest";
import {
cleanQuestion,
extractMarkedAnswer,
hasQuestionMark,
heuristicExtract,
} from "../extract.js";
// ─── helpers ───────────────────────────────────────────────────────
/** Extract question texts only */
function qs(text: string): string[] {
return heuristicExtract(text).map((q) => q.question);
}
/** Extract a single question's suggestions */
function _suggestionsFor(text: string, idx = 0): string[] {
return heuristicExtract(text)[idx]?.suggestions ?? [];
}
// ─── Code fences ───────────────────────────────────────────────────
describe("code fences", () => {
test("#1 ternary ? inside backtick fence", () => {
expect(qs("```\nconst x = a ? b : c;\n```")).toEqual([]);
});
test("#2 ? inside backtick fence", () => {
expect(qs("```\nreturn what?\n```")).toEqual([]);
});
test("#3 question outside fence after code", () => {
expect(qs("```\nconst x = 1;\n```\n\nWhat should we do next?")).toEqual([
"What should we do next?",
]);
});
test("#4 tilde fence skips content", () => {
expect(qs("~~~\nwhat?\n~~~")).toEqual([]);
});
test("#5 fence with language tag", () => {
expect(qs("```typescript\ntype X = Y | null?;\n```")).toEqual([]);
});
test("#6 multiple fences extract only outside", () => {
expect(qs("```\nwhat?\n```\nReal question?\n```\nother?\n```")).toEqual([
"Real question?",
]);
});
test("#7 SQL LIKE in fence", () => {
expect(qs("```sql\nSELECT * WHERE name LIKE '%what?%';\n```")).toEqual([]);
});
test("#8 URL in fence", () => {
expect(qs('```bash\ncurl "https://api.com?query=test"\n```')).toEqual([]);
});
test("#9 regex in fence", () => {
expect(qs("```\n/pattern?/\n```")).toEqual([]);
});
test("#10 optional chaining in fence", () => {
expect(qs("```\nobj?.method()?.chain()\n```")).toEqual([]);
});
test("#11 question before and after fence", () => {
expect(qs("What port?\n```\nx = 1\n```\nWhat host?")).toEqual([
"What port?",
"What host?",
]);
});
test("#12 unclosed fence skips everything after", () => {
expect(qs("```\nwhat?\nno closing")).toEqual([]);
});
test("#13 fence with 4 backticks", () => {
expect(qs("````\nwhat?\n````")).toEqual([]);
});
test("#14 question in fence, real question after", () => {
const originalTableInput = `
\`\`\`
error: not found?
\`\`\`
What should we do?`;
expect(qs(originalTableInput)).toEqual(["What should we do?"]);
});
test("#15 diff in code fence", () => {
expect(qs("```diff\n- old code?\n+ new code\n```")).toEqual([]);
});
});
// ─── URL stripping ─────────────────────────────────────────────────
describe("URLs", () => {
test("#16 standalone URL with query param", () => {
expect(qs("https://example.com?foo=bar")).toEqual([]);
});
test("#17 URL with query in sentence", () => {
expect(qs("See https://example.com?foo=bar for details.")).toEqual([]);
});
test("#18 API URL with auth param", () => {
expect(qs("The URL is https://api.example.com/v2?auth=token")).toEqual([]);
});
test("#19 multiple URLs with ?", () => {
expect(qs("Try https://a.com?x=1 and https://b.com?y=2")).toEqual([]);
});
test("#20 HTTP URL", () => {
expect(qs("http://example.com?query=test")).toEqual([]);
});
test("#21 URL at end of real question", () => {
expect(qs("Which endpoint? https://api.com?x=1")).toEqual([
"Which endpoint?",
]);
});
test("#22 URL then real question on next line", () => {
expect(qs("See https://api.com?x=1\nWhat should we do?")).toEqual([
"What should we do?",
]);
});
test("#23 URL with fragment and query", () => {
expect(qs("https://docs.com/page?section=intro#top")).toEqual([]);
});
test("#24 URL with multiple params", () => {
expect(qs("https://api.com?a=1&b=2&c=what?")).toEqual([]);
});
test("#25 real question with URL context", () => {
expect(qs("Visit https://status.com for info.\n\nWhich service?")).toEqual([
"Which service?",
]);
});
});
// ─── Markdown / pipe tables ────────────────────────────────────────
describe("tables", () => {
test("#26 pipe table header", () => {
expect(qs("| Header | Col? |")).toEqual([]);
});
test("#27 pipe table separator", () => {
expect(qs("|---|---|")).toEqual([]);
});
test("#28 pipe table row with ?", () => {
expect(qs("| does | this | work? |")).toEqual([]);
});
test("#29 unicode box table with ?", () => {
const table = `┌──────┬──────┐
│ Col1 │ Col? │
├──────┼──────┤
│ a │ b │
└──────┴──────┘`;
expect(qs(table)).toEqual([]);
});
test("#30 double-line box table", () => {
expect(qs("╔══════╗\n║ What? ║\n╚══════╝")).toEqual([]);
});
test("#31 ASCII art table", () => {
expect(qs("+------+------+------+")).toEqual([]);
});
test("#32 ASCII art table border with content", () => {
expect(qs("+------+\n| What |\n+------+")).toEqual([]);
});
test("#33 table then real question", () => {
expect(qs("| a | b |\n|---|---|\n| 1 | 2 |\n\nWhich column?")).toEqual([
"Which column?",
]);
});
test("#34 markdown table with bold", () => {
expect(qs("| **does** | **work?** |")).toEqual([]);
});
test("#35 full markdown table", () => {
const table = `| Name | Type |
|------|------|
| id | int |
| name | text |`;
expect(qs(table)).toEqual([]);
});
test("#36 original failing input from user", () => {
const input = ` Here's every failure mode in order of the flow:
┌──────────────────────────────┬────────────────┬──────────────────────────────────────────┐
│ What goes wrong │ Prompt │ Gap? │
│ │ reaction │ │
├──────────────────────────────┼────────────────┼──────────────────────────────────────────┤
│ Dirty worktree │ Stops │ ✅ │
└──────────────────────────────┴────────────────┴──────────────────────────────────────────┘
Want me to patch these into the prompt?`;
expect(qs(input)).toEqual(["Want me to patch these into the prompt?"]);
});
});
// ─── Headings ──────────────────────────────────────────────────────
describe("headings", () => {
test("#37 heading with question word, no ?", () => {
expect(qs("## How to install")).toEqual([]);
});
test("#38 heading with question word, no ? (what)", () => {
expect(qs("### What's new in v2")).toEqual([]);
});
test("#39 heading with question word, no ? (when)", () => {
expect(qs("## When to use this")).toEqual([]);
});
test("#40 heading with question word, no ? (where)", () => {
expect(qs("### Where to find docs")).toEqual([]);
});
test("#41 heading with question word, no ? (why)", () => {
expect(qs("## Why this approach")).toEqual([]);
});
test("#42 heading WITH ? is a question", () => {
expect(qs("## Which database?")).toEqual(["Which database?"]);
});
test("#43 heading with # prefix and ?", () => {
expect(qs("# What port?")).toEqual(["What port?"]);
});
test("#44 multiple headings mixed", () => {
expect(qs("## How to install\n### Which version?\n## Why")).toEqual([
"Which version?",
]);
});
});
// ─── Blockquotes ───────────────────────────────────────────────────
describe("blockquotes", () => {
test("#45 blockquote statement (no ?)", () => {
expect(qs("> Should work fine in production")).toEqual([]);
});
test("#46 blockquote statement with can", () => {
expect(qs("> Can be configured via env vars")).toEqual([]);
});
test("#47 blockquote with real question", () => {
expect(qs("> What do you think?")).toEqual(["What do you think?"]);
});
test("#48 blockquote with which question", () => {
expect(qs("> Which approach?")).toEqual(["Which approach?"]);
});
test("#49 nested blockquote with ?", () => {
expect(qs("> > What about this?")).toEqual(["What about this?"]);
});
test("#50 admonition is not a question (no ?)", () => {
expect(qs("> [!NOTE] Some info")).toEqual([]);
});
});
// ─── Unicode question marks ───────────────────────────────────────
describe("unicode question marks", () => {
test("#51 CJK fullwidth ?", () => {
expect(qs("用哪个数据库?")).toEqual(["用哪个数据库?"]);
});
test("#52 Arabic ؟", () => {
expect(qs("ما هذا؟")).toEqual(["ما هذا؟"]);
});
test("#53 irony mark ⸮", () => {
expect(qs("Oh really⸮")).toEqual(["Oh really⸮"]);
});
test("#54 inverted + normal ¿...?", () => {
expect(qs("¿Cuál base de datos?")).toEqual(["¿Cuál base de datos?"]);
});
test("#55 Japanese ?", () => {
expect(qs("どれを選びますか?")).toEqual(["どれを選びますか?"]);
});
test("#56 Korean with ASCII ?", () => {
expect(qs("어느 것을 사용합니까?")).toEqual(["어느 것을 사용합니까?"]);
});
test("#57 Hindi ?", () => {
expect(qs("कौन सा डेटाबेस?")).toEqual(["कौन सा डेटाबेस?"]);
});
test("#58 Thai ?", () => {
expect(qs("ใช้ฐานข้อมูลใด?")).toEqual(["ใช้ฐานข้อมูลใด?"]);
});
test("#59 Vietnamese ?", () => {
expect(qs("Dùng cơ sở dữ liệu nào?")).toEqual(["Dùng cơ sở dữ liệu nào?"]);
});
test("#60 mixed Unicode question marks", () => {
expect(qs("Which one?\n用哪个?\nما هذا؟")).toEqual([
"Which one?",
"用哪个?",
"ما هذا؟",
]);
});
});
// ─── QUESTION_WORD_RE removal ──────────────────────────────────────
describe("no question-word heuristic", () => {
test("#61 should-statement without ?", () => {
expect(qs("This should work fine.")).toEqual([]);
});
test("#62 does-statement without ?", () => {
expect(qs("That does the trick.")).toEqual([]);
});
test("#63 can-statement without ?", () => {
expect(qs("You can use this pattern.")).toEqual([]);
});
test("#64 will-statement without ?", () => {
expect(qs("It will be available soon.")).toEqual([]);
});
test("#65 would-statement without ?", () => {
expect(qs("This would be the approach.")).toEqual([]);
});
test("#66 could-statement without ?", () => {
expect(qs("We could try both.")).toEqual([]);
});
test("#67 did-statement without ?", () => {
expect(qs("I did the migration.")).toEqual([]);
});
test("#68 heading with how (no ?)", () => {
expect(qs("## How to configure")).toEqual([]);
});
test("#69 heading with should (no ?)", () => {
expect(qs("### Should work")).toEqual([]);
});
test("#70 heading with does (no ?)", () => {
expect(qs("## Does not apply")).toEqual([]);
});
});
// ─── Suggestion scoping ───────────────────────────────────────────
describe("suggestion scoping", () => {
test("#71 two questions with separate suggestions", () => {
const result = heuristicExtract(`Which DB?
- Postgres
- SQLite
Which port?
- 5432
- 3306`);
expect(result).toEqual([
{ question: "Which DB?", suggestions: ["Postgres", "SQLite"] },
{ question: "Which port?", suggestions: ["5432", "3306"] },
]);
});
test("#72 suggestions after blank line attach to latest", () => {
const result = heuristicExtract(`Which DB?
- Postgres`);
expect(result[0]?.suggestions).toEqual(["Postgres"]);
});
test("#73 suggestions before first question ignored", () => {
const result = heuristicExtract(`- Postgres\n\nWhich DB?`);
expect(result[0]?.suggestions).toEqual([]);
});
test("#74 three questions, suggestion on last only", () => {
const result = heuristicExtract(`Abc?
Def?
Ghi?
- X`);
expect(result[2]?.suggestions).toEqual(["X"]);
});
test("#75 alternating Q-suggestion-Q-suggestion", () => {
const result = heuristicExtract(`Q1 here?
- A
Q2 here?
- B`);
expect(result[0]?.suggestions).toEqual(["A"]);
expect(result[1]?.suggestions).toEqual(["B"]);
});
test("#76 prose between suggestions still attaches", () => {
const result = heuristicExtract(`Which DB?\n- A\n\ntext\n- B`);
expect(result[0]?.suggestions).toEqual(["A", "B"]);
});
test("#77 heading between question and suggestion", () => {
const result = heuristicExtract(`Which DB?\n### Section\n- Postgres`);
expect(result[0]?.suggestions).toEqual(["Postgres"]);
});
test("#78 MAX_SUGGESTIONS caps at 8", () => {
const result = heuristicExtract(
`Which?\n${Array.from({ length: 20 }, (_, i) => `- opt${i}`).join("\n")}`,
);
expect(result[0]?.suggestions.length).toBe(8);
});
test("#79 code fence between question and suggestion", () => {
const result = heuristicExtract(
`Which DB?\n\`\`\`\ncode\n\`\`\`\n- Postgres`,
);
expect(result[0]?.suggestions).toEqual(["Postgres"]);
});
test("#80 table between question and suggestion", () => {
const result = heuristicExtract(
`Which DB?\n| a | b |\n---|---|\n- Postgres`,
);
expect(result[0]?.suggestions).toEqual(["Postgres"]);
});
});
// ─── looksLikeQuestion direct tests ───────────────────────────────
// (now uses hasQuestionMark + cleanQuestion directly)
describe("hasQuestionMark + cleanQuestion", () => {
test("#81 standard question", () => {
expect(hasQuestionMark("What port?")).toBe(true);
});
test("#82 heading without ?", () => {
expect(hasQuestionMark(cleanQuestion("## How to install"))).toBe(false);
});
test("#83 blockquote without ?", () => {
expect(hasQuestionMark(cleanQuestion("> Should work fine"))).toBe(false);
});
test("#84 URL only", () => {
expect(hasQuestionMark(cleanQuestion("https://example.com?x=1"))).toBe(
false,
);
});
test("#85 ternary without fence", () => {
expect(hasQuestionMark("Use value ? yes : no")).toBe(true);
});
test("#86 CJK fullwidth ?", () => {
expect(hasQuestionMark("用哪个?")).toBe(true);
});
test("#87 Arabic ؟", () => {
expect(hasQuestionMark("ما هذا؟")).toBe(true);
});
test("#88 heading with ? IS a question", () => {
expect(hasQuestionMark(cleanQuestion("## Which database?"))).toBe(true);
});
test("#89 blockquote with ? IS a question", () => {
expect(hasQuestionMark(cleanQuestion("> What do you think?"))).toBe(true);
});
test("#90 numbered question", () => {
expect(hasQuestionMark(cleanQuestion("1. What port?"))).toBe(true);
});
});
// ─── Real LLM output patterns ─────────────────────────────────────
describe("real LLM patterns", () => {
test("#91 error in code + real question", () => {
const input = `I got an error:
\`\`\`
Error: file not found?
\`\`\`
What should I do?`;
expect(qs(input)).toEqual(["What should I do?"]);
});
test("#92 numbered options after question", () => {
const input = `Which approach?
1. Quick fix
2. Full refactor`;
const result = heuristicExtract(input);
expect(result[0]?.question).toBe("Which approach?");
expect(result[0]?.suggestions).toEqual(["Quick fix", "Full refactor"]);
});
test("#93 standard Q&A pattern", () => {
const input = `What would you like?
- Option A
- Option B`;
const result = heuristicExtract(input);
expect(result[0]?.question).toBe("What would you like?");
expect(result[0]?.suggestions).toEqual(["Option A", "Option B"]);
});
test("#94 let me know is not a question", () => {
expect(qs("Let me know if you have questions.")).toEqual([]);
});
test("#95 rhetorical question IS a question", () => {
expect(qs("Does that make sense?")).toEqual(["Does that make sense?"]);
});
test("#96 any questions IS a question", () => {
expect(qs("Any questions?")).toEqual(["Any questions?"]);
});
test("#97 multi-section with multiple questions", () => {
const input = `## Preflight
What branch?
main
develop
## Deploy
Which environment?
- staging
- production`;
expect(qs(input)).toEqual(["What branch?", "Which environment?"]);
});
test("#98 question with inline suggestion format", () => {
expect(qs("Which DB? (Postgres/SQLite)")).toEqual([
"Which DB? (Postgres/SQLite)",
]);
});
test("#99 diff in code then question", () => {
const input = `Here's the change:
\`\`\`diff
- old code?
+ new code
\`\`\`
Does this look correct?
- Yes
- No`;
const result = heuristicExtract(input);
expect(result[0]?.question).toBe("Does this look correct?");
expect(result[0]?.suggestions).toEqual(["Yes", "No"]);
});
test("#100 question with emoji prefix", () => {
expect(qs("❓ Which database?")).toEqual(["❓ Which database?"]);
});
});
// ─── Inline and inverted answer choices ───────────────────────────
describe("inline and inverted answer choices", () => {
test("#101 parenthesized slash choices", () => {
const result = heuristicExtract("Which DB? (Postgres/SQLite)");
expect(result).toEqual([
{
question: "Which DB? (Postgres/SQLite)",
suggestions: ["Postgres", "SQLite"],
},
]);
});
test("#102 parenthesized pipe choices", () => {
const result = heuristicExtract("Pick mode? (fast | safe | full)");
expect(result[0]?.suggestions).toEqual(["fast", "safe", "full"]);
});
test("#103 labelled A/B/C inline choices", () => {
const result = heuristicExtract(
"Choose UI: A attached morph, B modal, or C drawer?",
);
expect(result[0]?.suggestions).toEqual([
"attached morph",
"modal",
"drawer",
]);
});
test("#104 binary approval question", () => {
const result = heuristicExtract("Approve starting quickshell.service?");
expect(result[0]?.suggestions).toEqual(["yes", "no"]);
});
test("#105 simple or choices", () => {
const result = heuristicExtract(
"Apply to all popups or only bar-widget popups?",
);
expect(result[0]?.suggestions).toEqual([
"all popups",
"only bar-widget popups",
]);
});
test("#106 file paths are not slash choices", () => {
const result = heuristicExtract("Update README/EXTERNALS?");
expect(result[0]?.suggestions).toEqual([]);
});
test("#107 URLs are stripped, not slash choices", () => {
const result = heuristicExtract(
"Use https://example.com/a/b?x=1 or local docs?",
);
expect(result[0]?.question).toBe("Use or local docs?");
expect(result[0]?.suggestions).toEqual([]);
});
test("#108 one preceding bullet is ignored", () => {
const result = heuristicExtract("- Postgres\n\nWhich DB?");
expect(result[0]?.suggestions).toEqual([]);
});
test("#109 two preceding bullets attach to choice question", () => {
const result = heuristicExtract("- Postgres\n- SQLite\n\nWhich DB?");
expect(result[0]?.suggestions).toEqual(["Postgres", "SQLite"]);
});
test("#110 previous question suggestions are not stolen by next question", () => {
const result = heuristicExtract("First?\n- A\n- B\nSecond?");
expect(result[0]?.suggestions).toEqual(["A", "B"]);
expect(result[1]?.suggestions).toEqual([]);
});
test("#111 options heading creates synthetic choice question", () => {
const result = heuristicExtract(
"Options:\n1. Fix blocker now\n2. Revert addition\n3. Skip validation",
);
expect(result).toEqual([
{
question: "Choose an option?",
suggestions: ["Fix blocker now", "Revert addition", "Skip validation"],
},
]);
});
test("#112 next steps heading is not a choice question", () => {
const result = heuristicExtract(
"Next steps:\n1. Run tests\n2. Commit changes",
);
expect(result).toEqual([]);
});
test("#113 heading needs at least two options", () => {
const result = heuristicExtract("Options:\n1. Fix blocker now");
expect(result).toEqual([]);
});
test("#114 options heading after question attaches to that question", () => {
const result = heuristicExtract("Which path?\nOptions:\n1. Fast\n2. Safe");
expect(result).toEqual([
{ question: "Which path?", suggestions: ["Fast", "Safe"] },
]);
});
test("#115 question mark inside balanced parens is not a question", () => {
expect(qs("Registers tool forget(target?, reason?).")).toEqual([]);
});
test("#116 outer question with parenthesized optional marker stays question", () => {
expect(qs("Use forget(target?, reason?) now?")).toEqual([
"Use forget(target?, reason?) now?",
]);
});
test("#117 question mark inside inline code is not a question", () => {
expect(qs("Middle-slash patterns wrongly use `(?:.*\\/)?` prefix")).toEqual(
[],
);
});
test("#118 outer question after inline code stays question", () => {
expect(qs("Use `target?` marker now?")).toEqual([
"Use `target?` marker now?",
]);
});
test("#119 question mark inside arrow flow is not a question", () => {
expect(qs("retry → reduce scope → switch model? → ask user")).toEqual([]);
});
test("#120 quoted summary question before arrow is not a question", () => {
expect(qs("Skill = “am I on real Linux console?” → inspect docs")).toEqual(
[],
);
});
test("#121 arrow context with prose after question stays question", () => {
expect(
qs("provider unsupported → extension falls back? Prefer fail-soft"),
).toEqual([
"provider unsupported → extension falls back? Prefer fail-soft",
]);
});
test("#122 oversized internal planning paragraph is not a question", () => {
expect(
qs(
`${"Need maybe state if no wrapper possible? ".repeat(16)}No option fixes it. If no wrapper and no separate dprint task, drop upstream or accept diffs.`,
),
).toEqual([]);
});
test("#123 short internal planning note is not a question", () => {
expect(qs("Need maybe state if no wrapper possible?")).toEqual([]);
expect(qs("Need audit. Stack offset? Use anchor rect?")).toEqual([]);
});
test("#124 short confirmation question is a question", () => {
expect(qs("Go?")).toEqual(["Go?"]);
});
test("#125 debug exclamation question mark is not a question", () => {
expect(qs("Wait — y=60?! This is CSS leaking.")).toEqual([]);
});
test("#126 hedged command marker is not a question", () => {
expect(qs("• left click: `makoctl history`? / maybe launcher")).toEqual([]);
});
test("#127 ready prompt with trailing sentence stays question", () => {
expect(qs("Ready to merge? With fixes.")).toEqual([
"Ready to merge? With fixes.",
]);
});
test("#128 now/also direct prompts stay questions", () => {
expect(qs("Now verify exclusions — is that okay?")).toEqual([
"Now verify exclusions — is that okay?",
]);
expect(
qs("Also replace inline command. Proceed with shared script?"),
).toEqual(["Also replace inline command. Proceed with shared script?"]);
});
});
// ─── Edge cases / boundary ────────────────────────────────────────
describe("edge cases", () => {
test("#101 empty input", () => {
expect(qs("")).toEqual([]);
});
test("#102 only whitespace", () => {
expect(qs(" \n \n ")).toEqual([]);
});
test("#103 only newlines", () => {
expect(qs("\n\n\n")).toEqual([]);
});
test("#104 ??? too short after clean", () => {
expect(qs("???")).toEqual([]);
});
test("#105 Why? is 4 chars, extracted", () => {
expect(qs("Why?")).toEqual(["Why?"]);
});
test("#106 How? is 4 chars, extracted", () => {
expect(qs("How?")).toEqual(["How?"]);
});
test("#107 BOM prefix", () => {
expect(qs("\uFEFFWhat port?")).toEqual(["What port?"]);
});
test("#108 ANSI escape codes", () => {
expect(qs("\x1B[31mWhat port?\x1B[0m")).toEqual(["What port?"]);
});
test("#109 non-breaking space", () => {
expect(qs("What\u00A0port?")).toEqual(["What port?"]);
});
test("#110 zero-width space", () => {
expect(qs("\u200BWhat\u200Bport?")).toEqual(["What port?"]);
});
});
// ─── extractMarkedAnswer (kept from original) ─────────────────────
describe("extractMarkedAnswer", () => {
test("returns latest q-answer marker", () => {
const result = extractMarkedAnswer(`draft
text
final answer
`);
expect(result).toBe("final answer");
});
test("returns undefined without marker", () => {
expect(extractMarkedAnswer("final answer")).toBeUndefined();
});
});