diff --git a/CHANGELOG.md b/CHANGELOG.md index d30de343..0bd67d5f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ grouped by area, with links to the docs for the details. ### Added +- **Datasets.** `coding.sh dataset mine --proof-steps` mines redacted, deduplicated formal-verification proof-step cases (solved error-to-diff transitions and stuck proof goals) across Lean, Rocq, Dafny, Verus, Isabelle, and TLA+/TLC, with `--proof-lang` and `--proof-outcome` filters. ([docs](https://github.com/jackulau/coding.sh/blob/main/docs/guides/evals.md#mining-formal-proof-steps)) - **Work.** `coding.sh handoff --work ` builds a deterministic $0, secret-redacted multi-day handoff brief across every session in a work item, with direction pivots, timeline, changed files, passing checks, deduplicated dead ends, proof rollup, and context resets. `work show ` adds a `Timeline` (`timeline` in `--json`) and suggests `handoff --work` on multi-session high-risk items. ([docs](https://github.com/jackulau/coding.sh/blob/main/docs/guides/evals.md#resetting-context-with-a-handoff-brief)) - **Viewer.** At-risk sessions (`#/s/`) show a collapsible Live Steer card (expanded on `intervene`, collapsed on `nudge`) with prioritized directives, a copyable `suggestedSteer` prompt, and a `coding.sh handoff` hint on context resets; blocked, failed, or at-risk work items (`#/w/`) show the same advice for their cause session, while healthy items make zero `/steer` requests. [Evals](https://github.com/jackulau/coding.sh/blob/main/docs/guides/evals.md#live-session-steering) - **Steer.** `coding.sh steer ` and `GET /api/sessions/{id}/steer` read live verification, proof loop, context hygiene, tamper and wait telemetry to return `continue`, `nudge` or `intervene` with prioritized directives and a paste-ready steer prompt (`--prompt`, `--strict`, `--fresh`, `--json`). [Evals](https://github.com/jackulau/coding.sh/blob/main/docs/guides/evals.md#live-session-steering) diff --git a/docs/guides/evals.md b/docs/guides/evals.md index 85f85f07..f623ce6c 100644 --- a/docs/guides/evals.md +++ b/docs/guides/evals.md @@ -482,6 +482,19 @@ Mined cases carry deterministic `difficulty` (`easy`, `medium`, or `hard`), `tur `coding.sh dataset stats ` reports version, case counts by split, kind, tag, and difficulty, input length min/median/max, and near-duplicate pair count at `--near-threshold` (default `0.8`). `coding.sh dataset filter --out ` writes a new immutable child dataset filtered by `--split`, `--tag`, `--difficulty`, `--min-chars`, `--max-chars`, `--dedupe-near`, and `--limit`. +#### Mining formal proof steps + +`coding.sh dataset mine --proof-steps` mines formal-verification proof-step cases from Lean, Rocq, Dafny, Verus, Isabelle, and TLA+/TLC checker runs instead of whole-session prompts. + +```sh +coding.sh dataset mine proof-bench --proof-steps --proof-lang lean,rocq +coding.sh dataset mine stuck-proofs --proof-steps --proof-outcome stuck --dry-run +``` + +- **Solved transitions** (`outcome: "solved"`): a failing proof check followed by proof-file edits and a clean passing check with no net new escape hatches. +- **Stuck goals** (`outcome: "stuck"`): a failing proof check that repeats or remains unresolved at session end, giving eval suites a benchmark of real unresolved proof goals. +- **Filtering and safety**: pass `--proof-lang` to limit languages and `--proof-outcome solved|stuck|all` to pick outcomes. Every error, goal snippet, command, path, and winning diff is redacted and deduplicated before storage. + ### Case kinds: bad, guard, control When a dataset tests a change (a new prompt, new tool text, a new model), give its cases a `kind`. diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 84a99a97..b2e95c4d 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -2002,6 +2002,9 @@ coding.sh dataset mine [options] | `--dedupe-near <0..1>` | | Drop near-duplicate inputs at or above this 5-shingle Jaccard similarity, e.g. 0.8 (in addition to exact dedup) | | `--split ` | | Split for the mined cases (default: stable hash of the case id, 60/20/20) One of: `train`, `dev`, `test`. | | `--tag ` | | Extra tag for every mined case (repeatable, or a comma list: a,b) | +| `--proof-steps` | | Mine formal-verification proof-step cases (failing proof goals with winning diffs or stuck goals) instead of whole-session cases. | +| `--proof-lang ` | | With --proof-steps: only these proof languages (repeatable, or a comma list: lean,rocq) One of: `lean`, `rocq`, `dafny`, `verus`, `isabelle`, `tla`, `tlc`. | +| `--proof-outcome ` | `all` | With --proof-steps: mine only solved transitions, only stuck goals, or all. One of: `solved`, `stuck`, `all`. | | `--note ` | | Version note. | | `--dry-run` | | Show the exact changes without writing anything. | | `--fresh` | | Wait for every pending capture to be ingested (default: answer after 1.5 s) | @@ -2009,6 +2012,8 @@ coding.sh dataset mine [options] ```sh coding.sh dataset mine clean --where 'agent:claude-code' --min-turns 2 --exclude-flagged --dedupe-near 0.8 coding.sh dataset mine high-score --min-score quality>=0.8 --limit 50 --dry-run +coding.sh dataset mine proof-bench --proof-steps --proof-lang lean,rocq +coding.sh dataset mine stuck-proofs --proof-steps --proof-outcome stuck --dry-run ``` ### `coding.sh dataset stats` diff --git a/packages/coding.sh/src/cli/commands/dataset.ts b/packages/coding.sh/src/cli/commands/dataset.ts index 76d3da48..a4b41529 100644 --- a/packages/coding.sh/src/cli/commands/dataset.ts +++ b/packages/coding.sh/src/cli/commands/dataset.ts @@ -2,6 +2,7 @@ import { resolve } from "node:path"; import { setTimeout as delay } from "node:timers/promises"; import { scoreNumber } from "../../alerts/measure.ts"; +import { isProofLang, PROOF_LANGS, type ProofLang } from "../../core/proof.ts"; import type { IndexStore, SessionFilter } from "../../core/types.ts"; import { computeDatasetStats, @@ -14,6 +15,7 @@ import { type MinScoreFilter, } from "../../datasets/curate.ts"; import { addCases, assignSplits, caseFromSession, createDataset, DatasetError, loadDatasetFile, slugify } from "../../datasets/dataset.ts"; +import { isProofStepOutcomeFilter, mineProofSteps, PROOF_STEP_OUTCOMES, type ProofStepOutcomeFilter } from "../../datasets/proof-mine.ts"; import { FileEvalStore } from "../../datasets/store.ts"; import type { CaseKind, Dataset, Split } from "../../datasets/types.ts"; import { findSessions } from "../../query/run.ts"; @@ -150,6 +152,23 @@ export async function run(c: CommandContext): Promise { positiveInt(c.flags.limit, "limit"); nonNegativeInt(c.flags["min-turns"], "min-turns"); thresholdFlag(c.flags["dedupe-near"], "dedupe-near"); + const proofSteps = c.flags["proof-steps"] === true; + const rawProofLangs = list(c.flags["proof-lang"]); + const rawProofOutcome = str(c.flags["proof-outcome"]); + if (rawProofLangs.length && !proofSteps) { + throw new UsageError("--proof-lang requires --proof-steps", { reason: "invalid_argument" }); + } + if (rawProofOutcome !== undefined && !proofSteps) { + throw new UsageError("--proof-outcome requires --proof-steps", { reason: "invalid_argument" }); + } + for (const lang of rawProofLangs) { + if (!isProofLang(lang)) { + throw new UsageError(`--proof-lang must be one of ${PROOF_LANGS.join(", ")}, got ${JSON.stringify(lang)}`, { reason: "invalid_argument" }); + } + } + if (rawProofOutcome !== undefined && !isProofStepOutcomeFilter(rawProofOutcome)) { + throw new UsageError(`--proof-outcome must be one of ${PROOF_STEP_OUTCOMES.join(", ")}, got ${JSON.stringify(rawProofOutcome)}`, { reason: "invalid_argument" }); + } for (const raw of list(c.flags["min-score"])) { try { parseMinScore(raw); @@ -278,6 +297,9 @@ export async function run(c: CommandContext): Promise { const dedupeNear = thresholdFlag(c.flags["dedupe-near"], "dedupe-near"); const split = str(c.flags.split) as Split | undefined; const tags = list(c.flags.tag); + const proofSteps = c.flags["proof-steps"] === true; + const proofLangs = list(c.flags["proof-lang"]) as ProofLang[]; + const proofOutcome = str(c.flags["proof-outcome"]) as ProofStepOutcomeFilter | undefined; const dryRun = c.flags["dry-run"] === true; const note = str(c.flags.note); @@ -309,6 +331,24 @@ export async function run(c: CommandContext): Promise { }; const runMine = (existing: Dataset | undefined) => { + if (proofSteps) { + const proofOpts: Parameters[0] = { + sessions, + getEvents, + scores, + minScores, + excludeFlagged, + }; + if (minTurns !== undefined) proofOpts.minTurns = minTurns; + if (dedupeNear !== undefined) proofOpts.dedupeNear = dedupeNear; + if (split) proofOpts.split = split; + if (tags.length) proofOpts.tags = tags; + if (limit !== undefined) proofOpts.limit = limit; + if (proofLangs.length) proofOpts.proofLangs = proofLangs; + if (proofOutcome !== undefined) proofOpts.outcome = proofOutcome; + if (existing) proofOpts.existing = existing.cases; + return mineProofSteps(proofOpts); + } const mineOpts: Parameters[0] = { sessions, getEvents, @@ -325,11 +365,14 @@ export async function run(c: CommandContext): Promise { return mineDatasetSessions(mineOpts); }; + const matchedLabel = (n: number) => + proofSteps ? `${plural(n, "proof step")} across ${plural(sessions.length, "session")}` : plural(n, "session"); + if (dryRun) { const existing = await store.getDataset(id); const report = await runMine(existing); if (out.json) { - out.data({ + const doc: Record = { outcome: "dry-run", dataset: { id, name }, matched: report.matched, @@ -337,9 +380,11 @@ export async function run(c: CommandContext): Promise { dropped: report.dropped, droppedBy: report.droppedBy, duplicates: report.duplicates.length, - }); + }; + if (proofSteps) doc.sessions = sessions.length; + out.data(doc); } else { - out.print(`Matched ${plural(report.matched, "session")}: ${report.kept} kept, ${report.dropped} dropped`); + out.print(`Matched ${matchedLabel(report.matched)}: ${report.kept} kept, ${report.dropped} dropped`); const detail = formatBreakdown(report.droppedBy); if (detail) out.note(`Dropped: ${detail}`); out.note("Dry run: nothing written"); @@ -385,7 +430,7 @@ export async function run(c: CommandContext): Promise { if (!saved) { const outcome = existingWhenEmpty ? "unchanged" : "empty"; if (out.json) { - out.data({ + const doc: Record = { outcome, dataset: existingWhenEmpty ? summary(existingWhenEmpty) : null, matched: report.matched, @@ -393,9 +438,11 @@ export async function run(c: CommandContext): Promise { dropped: report.dropped, droppedBy: report.droppedBy, duplicates: report.duplicates.length, - }); + }; + if (proofSteps) doc.sessions = sessions.length; + out.data(doc); } else { - out.note(`Matched ${plural(report.matched, "session")}: 0 kept, ${report.dropped} dropped`); + out.note(`Matched ${matchedLabel(report.matched)}: 0 kept, ${report.dropped} dropped`); const detail = formatBreakdown(report.droppedBy); if (detail) out.note(`Dropped: ${detail}`); if (existingWhenEmpty) out.ok(`${existingWhenEmpty.name} is unchanged`); @@ -404,7 +451,7 @@ export async function run(c: CommandContext): Promise { } if (out.json) { - out.data({ + const doc: Record = { outcome: saved.created ? "created" : "unchanged", dataset: { ...summary(saved.ds), version: saved.version }, matched: report.matched, @@ -412,7 +459,9 @@ export async function run(c: CommandContext): Promise { dropped: report.dropped, droppedBy: report.droppedBy, duplicates: report.duplicates.length, - }); + }; + if (proofSteps) doc.sessions = sessions.length; + out.data(doc); } else { const detail = formatBreakdown(report.droppedBy); if (detail) out.note(`Dropped ${report.dropped} (${detail})`); diff --git a/packages/coding.sh/src/cli/registry.ts b/packages/coding.sh/src/cli/registry.ts index 81dc8e7e..40b1d453 100644 --- a/packages/coding.sh/src/cli/registry.ts +++ b/packages/coding.sh/src/cli/registry.ts @@ -1266,6 +1266,9 @@ export const COMMANDS: CommandSpec[] = [ { name: "dedupe-near", type: "number", value: "<0..1>", desc: "Drop near-duplicate inputs at or above this 5-shingle Jaccard similarity, e.g. 0.8 (in addition to exact dedup)" }, { name: "split", type: "string", value: "", choices: ["train", "dev", "test"], desc: "Split for the mined cases (default: stable hash of the case id, 60/20/20)" }, { name: "tag", type: "list", commas: true, value: "", desc: "Extra tag for every mined case (repeatable, or a comma list: a,b)" }, + { name: "proof-steps", type: "boolean", desc: "Mine formal-verification proof-step cases (failing proof goals with winning diffs or stuck goals) instead of whole-session cases" }, + { name: "proof-lang", type: "list", commas: true, value: "", choices: ["lean", "rocq", "dafny", "verus", "isabelle", "tla", "tlc"], desc: "With --proof-steps: only these proof languages (repeatable, or a comma list: lean,rocq)" }, + { name: "proof-outcome", type: "string", value: "", choices: ["solved", "stuck", "all"], default: "all", desc: "With --proof-steps: mine only solved transitions, only stuck goals, or all" }, { name: "note", type: "string", value: "", desc: "Version note" }, DRY_RUN, FRESH, @@ -1273,6 +1276,8 @@ export const COMMANDS: CommandSpec[] = [ examples: [ "coding.sh dataset mine clean --where 'agent:claude-code' --min-turns 2 --exclude-flagged --dedupe-near 0.8", "coding.sh dataset mine high-score --min-score quality>=0.8 --limit 50 --dry-run", + "coding.sh dataset mine proof-bench --proof-steps --proof-lang lean,rocq", + "coding.sh dataset mine stuck-proofs --proof-steps --proof-outcome stuck --dry-run", ], }, { diff --git a/packages/coding.sh/src/datasets/curate.ts b/packages/coding.sh/src/datasets/curate.ts index fe3f157c..972ba9fc 100644 --- a/packages/coding.sh/src/datasets/curate.ts +++ b/packages/coding.sh/src/datasets/curate.ts @@ -136,7 +136,7 @@ interface KeptEntry { sh: Set; } -class CaseDeduper { +export class CaseDeduper { private readonly threshold: number | undefined; private readonly shingleSize: number; private readonly byHash = new Map(); diff --git a/packages/coding.sh/src/datasets/index.ts b/packages/coding.sh/src/datasets/index.ts index b42cd7c5..70d98ef2 100644 --- a/packages/coding.sh/src/datasets/index.ts +++ b/packages/coding.sh/src/datasets/index.ts @@ -3,5 +3,6 @@ export * from "./curate.ts"; export * from "./dataset.ts"; export * from "./hash.ts"; export * from "./kinds.ts"; +export * from "./proof-mine.ts"; export * from "./store.ts"; export * from "./types.ts"; diff --git a/packages/coding.sh/src/datasets/proof-mine.ts b/packages/coding.sh/src/datasets/proof-mine.ts new file mode 100644 index 00000000..150719f7 --- /dev/null +++ b/packages/coding.sh/src/datasets/proof-mine.ts @@ -0,0 +1,654 @@ +// Formal-verification proof-step dataset mining: extracts solved proof-step +// transitions (failing proof check -> proof edit(s) -> passing check with no +// net new escape hatches) and stuck/unresolved proof goals from stored sessions. +// Every string field passes through createRedactor() before leaving this module. +import { isFailureFlag } from "../core/failure-flags.ts"; +import { + checkOutcome, + isProofConfig, + isProofLang, + isProofOutput, + isProofTestPath, + isRocqOutput, + outText, + PROOF_LANGS, + proofChange, + proofCheck, + proofEnd, + proofLang, + proofOutputLang, + proofStart, + proofWrite, + readProofDiff, + type HasProof, + type ProofCheck, + type ProofLang, +} from "../core/proof.ts"; +import { createRedactor, type Redactor } from "../core/redact.ts"; +import { normalizeTracePath, shellCommand, shellDiffOrigin, shellWrites } from "../core/shell-diff.ts"; +import { isShellCall } from "../core/shell-tools.ts"; +import type { AgentEvent, Session } from "../schema/index.ts"; +import { CaseDeduper, DEFAULT_SHINGLE_SIZE, validateThreshold, type MinScoreFilter, type NearDedupeDrop } from "./curate.ts"; +import { caseContentHash, DatasetError, normalizeCase } from "./dataset.ts"; +import type { Case, Split } from "./types.ts"; + +export const PROOF_STEP_OUTCOMES = ["solved", "stuck", "all"] as const; +export type ProofStepOutcomeFilter = (typeof PROOF_STEP_OUTCOMES)[number]; +export type ProofStepOutcome = "solved" | "stuck"; + +export const MAX_ERROR_CHARS = 600; +export const MAX_GOAL_SNIPPET_CHARS = 800; +export const MAX_WINNING_DIFF_CHARS = 2000; +export const MAX_COMMAND_CHARS = 500; + +export interface ProofStepInput { + kind: "proof-step"; + lang: ProofLang; + file?: string; + command: string; + error: string; + goalSnippet?: string; +} + +export interface ProofStepExpectedSolved { + resolved: true; + winningDiff?: string; + winningCheck: string; + attempts: number; +} + +export interface ProofStepExpectedStuck { + resolved: false; + attempts: number; +} + +export type ProofStepExpected = ProofStepExpectedSolved | ProofStepExpectedStuck; + +export type ProofMineDropReason = + | "min-turns" + | "min-score" + | "flagged" + | "proof-lang" + | "proof-outcome" + | "proof-escape" + | "exact-duplicate" + | "near-duplicate" + | "limit"; + +export interface MineProofStepsOpts { + sessions: readonly Session[]; + getEvents: (sessionId: string) => Promise; + /** Session id to score name to mean numeric score (required only when `minScores` is set). */ + scores?: ReadonlyMap>; + minTurns?: number; + minScores?: readonly MinScoreFilter[]; + excludeFlagged?: boolean; + /** Optional filter of proof languages to keep. */ + proofLangs?: readonly ProofLang[]; + /** Keep solved transitions, stuck goals, or both (default "all"). */ + outcome?: ProofStepOutcomeFilter; + dedupeNear?: number; + split?: Split; + tags?: string[]; + limit?: number; + existing?: readonly Case[]; + shingleSize?: number; +} + +export interface MineProofStepsReport { + cases: Case[]; + /** Number of sessions scanned. */ + sessions: number; + /** Total proof-step episodes discovered before filtering. */ + matched: number; + kept: number; + dropped: number; + droppedBy: Partial>; + duplicates: NearDedupeDrop[]; +} + +interface ExtractedProofStep { + lang: ProofLang; + outcome: ProofStepOutcome; + escapesAdded: number; + case: Case; +} + +interface PendingEpisode { + key: string; + lang: ProofLang; + file?: string; + firstCommand: string; + firstError: string; + lastErrorSig: string; + goalSnippet?: string; + attempts: number; + edits: { file: string; diff: string }[]; + editedViaShell: boolean; + hatches: Map; +} + +const TIMED_OUT_TEXT = /\b(?:exec )?command timed out\b|\btimed out after\b|\bexit code 124\b/i; +const EXIT_LINE_RE = /^(?:Error:\s*)?Exit code -?\d+\s*$/i; +const ERROR_LINE_RE = /\berror:|\bError:|\b[1-9]\d* errors?\b|^\*\*\* |\bis violated\b|\[ERROR\]|EXITCODE: ERROR|\b(?:unsolved goals|type mismatch|tactic .* failed|unable to unify|assertion failed|postcondition|precondition|invariant|failed to finish proof|obligations? failed)\b/i; + +const FILE_BY_LANG: Record = { + lean: /([^\s:'"()[\]]+\.lean):\d+:\d+:/, + rocq: /File "([^"\n]+\.v)", line \d+/, + dafny: /([^\s:'"()[\]]+\.dfy)\(\d+,\d+\):/, + verus: /(?:-->\s*|^|\s)([^\s:'"()[\]]+\.rs):\d+:\d+/m, + isabelle: /"([^"\n]+\.thy)"|([^\s:'"()[\]]+\.thy)/, + tla: /([^\s:'"()[\]]+\.tla)\b/, + tlc: /([^\s:'"()[\]]+\.(?:cfg|tla))\b/, +}; + +const STMT_LINE_RE = /^[+-]?\s*(?:@\[[^\]]*\]\s*|#\[[^\]]*\]\s*)?(?:(?:private|protected|local|global|noncomputable|ghost|static|pub(?:\([^)]*\))?|proof|spec|exec)\s+)*(?:theorem|lemma|corollary|proposition|fact|example|method|function|predicate|THEOREM|LEMMA|PROPOSITION|COROLLARY|fn)\b/i; + +const str = (v: unknown): string | undefined => (typeof v === "string" ? v : undefined); + +export function isProofStepOutcomeFilter(v: string): v is ProofStepOutcomeFilter { + return (PROOF_STEP_OUTCOMES as readonly string[]).includes(v); +} + +function clip(text: string, max: number): string { + const trimmed = text.trim(); + if (trimmed.length <= max) return trimmed; + return `${trimmed.slice(0, Math.max(0, max - 1)).trimEnd()}…`; +} + +function bumpReason(counts: Partial>, reason: ProofMineDropReason, delta = 1): void { + counts[reason] = (counts[reason] ?? 0) + delta; +} + +/** Extracts the proof file path referenced by a checker command or its output. */ +function extractFileFromOutput(lang: ProofLang, output: string, cwd: string | undefined): string | undefined { + if (!output) return undefined; + const re = FILE_BY_LANG[lang]; + const m = re.exec(output); + const raw = m ? (m[1] ?? m[2]) : undefined; + return raw ? normalizeTracePath(raw, cwd) : undefined; +} + +function firstCheckFile(check: ProofCheck, cwd: string | undefined): string | undefined { + if (!check.path) return undefined; + const first = check.path.split(/\s+/).find(Boolean); + return first ? normalizeTracePath(first, cwd) : undefined; +} + +/** Extracts the primary proof error lines from failing checker output. */ +function extractProofError(output: string, timedOut: boolean): string { + const lines = output + .split(/\r?\n/) + .map((l) => l.trimEnd()) + .filter((l) => l.trim().length > 0 && !EXIT_LINE_RE.test(l.trim())); + if (!lines.length) return timedOut ? "proof check timed out" : "proof check failed"; + const start = lines.findIndex((l) => ERROR_LINE_RE.test(l)); + const slice = start >= 0 ? lines.slice(start, start + 6) : lines.slice(0, 6); + return slice.join("\n").trim(); +} + +/** Normalizes an error string for comparing repeat failures. */ +function normalizeErrorSig(lang: ProofLang, error: string): string { + const first = error.split(/\r?\n/)[0] ?? error; + return `${lang}:${first + .replace(/\b\d+\b/g, "#") + .replace(/\s+/g, " ") + .trim() + .slice(0, 160)}`; +} + +/** Extracts a proof goal or theorem context snippet from checker output or recent proof diff. */ +function extractGoalSnippet(lang: ProofLang, output: string, fallbackDiff: string | undefined): string | undefined { + const lines = output.split(/\r?\n/).map((l) => l.trimEnd()); + + if (lang === "lean") { + const turnstile = lines.findIndex((l) => l.includes("⊢")); + if (turnstile >= 0) { + let from = turnstile; + while (from > 0 && turnstile - from < 5) { + const prev = lines[from - 1]!.trim(); + if (!prev || /:\d+:\d+:\s*error:/i.test(prev) || EXIT_LINE_RE.test(prev)) break; + from--; + } + const snippet = lines.slice(from, Math.min(lines.length, turnstile + 4)).filter((l) => l.trim()).join("\n"); + if (snippet) return snippet; + } + } else if (lang === "isabelle") { + const goalIdx = lines.findIndex((l) => /\bgoal\s*\(\d+\s+subgoals?\)/i.test(l)); + if (goalIdx >= 0) { + const snippet = lines.slice(goalIdx, Math.min(lines.length, goalIdx + 6)).filter((l) => l.trim()).join("\n"); + if (snippet) return snippet; + } + } else if (lang === "rocq") { + const eqIdx = lines.findIndex((l) => /^={4,}/.test(l.trim())); + if (eqIdx >= 0) { + const from = Math.max(0, eqIdx - 4); + const snippet = lines.slice(from, Math.min(lines.length, eqIdx + 4)).filter((l) => l.trim()).join("\n"); + if (snippet) return snippet; + } + } else if (lang === "verus") { + const arrowIdx = lines.findIndex((l) => /^\s*-->/.test(l)); + if (arrowIdx >= 0) { + const snippet = lines.slice(arrowIdx, Math.min(lines.length, arrowIdx + 6)).filter((l) => l.trim()).join("\n"); + if (snippet) return snippet; + } + } else if (lang === "dafny") { + const relIdx = lines.findIndex((l) => /Related location:/i.test(l)); + if (relIdx >= 0) { + const snippet = lines.slice(Math.max(0, relIdx - 1), Math.min(lines.length, relIdx + 3)).filter((l) => l.trim()).join("\n"); + if (snippet) return snippet; + } + } else if (lang === "tlc" || lang === "tla") { + const stateIdx = lines.findIndex((l) => /^State \d+:/i.test(l.trim())); + if (stateIdx >= 0) { + const snippet = lines.slice(stateIdx, Math.min(lines.length, stateIdx + 6)).filter((l) => l.trim()).join("\n"); + if (snippet) return snippet; + } + } + + // Fallback: theorem/lemma header or context from the most recent diff on this file. + if (fallbackDiff) { + const dLines = fallbackDiff.split(/\r?\n/).filter((l) => l.trim() && !l.startsWith("@@") && !l.startsWith("---") && !l.startsWith("+++")); + const stmtIdx = dLines.findIndex((l) => STMT_LINE_RE.test(l)); + if (stmtIdx >= 0) { + return dLines.slice(stmtIdx, Math.min(dLines.length, stmtIdx + 5)).join("\n").trim(); + } + } + + return undefined; +} + +/** Builds a bounded, redacted winning diff from the edits made between failure and pass. */ +function buildWinningDiff(edits: readonly { file: string; diff: string }[], redactor: Redactor): string | undefined { + const nonEmpty = edits.filter((e) => e.diff.trim().length > 0); + if (!nonEmpty.length) return undefined; + const distinctFiles = new Set(nonEmpty.map((e) => e.file)); + const raw = + distinctFiles.size > 1 + ? nonEmpty.map((e) => `--- ${e.file}\n${e.diff.trim()}`).join("\n\n") + : nonEmpty.map((e) => e.diff.trim()).join("\n"); + // Redact before clipping so a secret crossing the length boundary is never left partial. + const redacted = redactor.string(raw); + return clip(redacted, MAX_WINNING_DIFF_CHARS); +} + +function buildProofCase( + session: Session, + ep: PendingEpisode, + outcome: ProofStepOutcome, + winningCheck: string | undefined, + redactor: Redactor, + opts: { split?: Split; tags?: readonly string[] }, +): Case { + const command = clip(redactor.string(ep.firstCommand), MAX_COMMAND_CHARS); + const error = clip(redactor.string(ep.firstError), MAX_ERROR_CHARS); + const file = ep.file ? redactor.string(ep.file) : undefined; + const goalSnippet = ep.goalSnippet ? clip(redactor.string(ep.goalSnippet), MAX_GOAL_SNIPPET_CHARS) : undefined; + + const input: ProofStepInput = { + kind: "proof-step", + lang: ep.lang, + command, + error, + }; + if (file) input.file = file; + if (goalSnippet) input.goalSnippet = goalSnippet; + + let expected: ProofStepExpected; + if (outcome === "solved") { + const solved: ProofStepExpectedSolved = { + resolved: true, + winningCheck: clip(redactor.string(winningCheck ?? ep.firstCommand), MAX_COMMAND_CHARS), + attempts: ep.attempts, + }; + const diff = buildWinningDiff(ep.edits, redactor); + if (diff) solved.winningDiff = diff; + expected = solved; + } else { + expected = { + resolved: false, + attempts: ep.attempts, + }; + } + + const metadata: Record = { + sourceSessionId: session.id, + lang: ep.lang, + outcome, + attempts: ep.attempts, + command, + startedAt: session.startedAt, + }; + if (file) metadata.file = file; + if (session.repo?.root) metadata.repo = redactor.string(session.repo.root); + + const tags = [...new Set(["proof-step", `proof:${ep.lang}`, `outcome:${outcome}`, `agent:${session.agent}`, ...(opts.tags ?? [])])]; + const id = `ps_${caseContentHash({ input, expected }).slice(0, 16)}`; + + const raw: Record = { + id, + input, + expected, + metadata, + tags, + sourceSessionId: session.id, + }; + if (opts.split) raw.split = opts.split; + return normalizeCase(raw, `session ${session.id} proof-step`); +} + +/** + * Extracts solved proof-step transitions and stuck/unresolved proof goals from a single session. + * Pure over `(session, events)` with full redaction of all emitted text fields. + */ +export function extractSessionProofSteps( + session: Session, + events: readonly AgentEvent[], + opts: { split?: Split; tags?: readonly string[]; redactor?: Redactor } = {}, +): ExtractedProofStep[] { + const sorted = events.map((e, i) => ({ e, i })).sort((a, b) => (a.e.ts ?? 0) - (b.e.ts ?? 0) || a.i - b.i).map((x) => x.e); + const redactor = opts.redactor ?? createRedactor(); + const baseCwd = session.repo?.root ?? session.cwd; + + const proof: HasProof = {}; + const starts = new Map(); + const activeChecks = new Map(); + const buildLangs = new Map(); + const lastProofFileByLang = new Map(); + const lastDiffByFile = new Map(); + const pending = new Map(); + const extracted: ExtractedProofStep[] = []; + + for (const e of sorted) { + const p = e.payload ?? {}; + const cwd = baseCwd ?? e.cwd; + + if (e.kind === "tool.start") { + const id = str(p.toolUseId); + if (id) starts.set(id, e); + const tool = str(p.tool); + const cmd = shellCommand(tool, p.input); + if (cmd === undefined) continue; + + if (isShellCall(tool ?? "", p.input)) { + proofStart(proof, id, cmd, p.input); + const check = proofCheck(cmd, p.input); + if (check && id) activeChecks.set(id, { check, cmd, cwd }); + } + + for (const w of shellWrites(cmd)) { + const path = normalizeTracePath(w.path, cwd); + const renamedTo = w.renamedTo === undefined ? undefined : normalizeTracePath(w.renamedTo, cwd); + proofWrite(proof, e, w, path, renamedTo, id, false); + const known = proof.proof?.files?.get(path)?.lang; + const lang = isProofConfig(path) ? undefined : proofLang(path, "", known); + if (lang) { + lastProofFileByLang.set(lang, path); + for (const ep of pending.values()) { + if (ep.lang === lang && (ep.file === undefined || ep.file === path)) { + ep.editedViaShell = true; + if (ep.file === undefined) ep.file = path; + } + } + } + } + } else if (e.kind === "file.change") { + const raw = str(p.path); + if (!raw) continue; + const path = normalizeTracePath(raw, cwd); + const id = str(p.toolUseId); + const start = id ? starts.get(id) : undefined; + const origin = shellDiffOrigin(e, start, cwd); + const moved = str(p.movedTo); + const to = moved ? normalizeTracePath(moved, cwd) : undefined; + const diff = str(p.diff) ?? ""; + const truncated = p.diffTruncated === true; + const priorLang = proof.proof?.files?.get(path)?.lang; + + proofChange(proof, e, { path, to, origin, prot: false, test: false }); + + const finalPath = to ?? path; + const recordedLang = proof.proof?.files?.get(finalPath)?.lang ?? priorLang; + const isConfig = isProofConfig(finalPath); + const lang = isConfig ? undefined : proofLang(finalPath, diff, recordedLang); + const rocqOrTlcConfirmed = + lang !== "rocq" && lang !== "tlc" + ? true + : proof.proof?.files?.has(finalPath) || + (lang === "rocq" && proof.proof?.rocq === true) || + (lang === "tlc" && proof.proof?.tlc === true); + + if (!lang || !rocqOrTlcConfirmed) continue; + + lastProofFileByLang.set(lang, finalPath); + if (diff) lastDiffByFile.set(finalPath, diff); + + const parsed = !isProofTestPath(finalPath) && diff ? readProofDiff(finalPath, lang, diff, truncated) : undefined; + for (const ep of pending.values()) { + if (ep.lang !== lang) continue; + if (ep.file !== undefined && ep.file !== finalPath) continue; + if (ep.file === undefined) ep.file = finalPath; + ep.edits.push({ file: finalPath, diff }); + if (!ep.goalSnippet && diff) { + const fallbackGoal = extractGoalSnippet(lang, "", diff); + if (fallbackGoal) ep.goalSnippet = fallbackGoal; + } + if (parsed) { + for (const [hatchName, delta] of parsed.hatches) { + ep.hatches.set(hatchName, (ep.hatches.get(hatchName) ?? 0) + delta); + } + } + } + } else if (e.kind === "tool.end") { + proofEnd(proof, e); + const id = str(p.toolUseId); + const active = id ? activeChecks.get(id) : undefined; + if (!active) continue; + activeChecks.delete(id!); + + const { check, cmd } = active; + const text = outText(p.output ?? p.error); + let lang: ProofLang | undefined; + if (isProofLang(check.lang)) { + lang = check.lang; + } else if (check.lang === "make" || check.lang === "dune") { + const bkey = `${check.lang}\u0000${check.target ?? ""}\u0000${check.path ?? ""}`; + const detected = isRocqOutput(text) ? "rocq" : proofOutputLang(text); + if (detected) { + buildLangs.set(bkey, detected); + lang = detected; + } else if (buildLangs.has(bkey)) { + lang = buildLangs.get(bkey); + } else if (!isProofOutput(text)) { + continue; + } + } + if (!lang) continue; + + const outcome = checkOutcome(check, p); + const timedOut = p.timedOut === true || (p.ok === false && TIMED_OUT_TEXT.test(text)); + if (outcome === undefined && !timedOut) continue; + + const isRed = outcome === "red" || timedOut; + const isGreen = outcome === "green" && !timedOut; + const explicitFile = firstCheckFile(check, active.cwd) ?? extractFileFromOutput(lang, text, active.cwd); + + if (isRed) { + const file = explicitFile ?? lastProofFileByLang.get(lang); + const error = extractProofError(text, timedOut); + const errSig = normalizeErrorSig(lang, error); + const goalSnippet = extractGoalSnippet(lang, text, file ? lastDiffByFile.get(file) : undefined); + + const exactKey = `${lang}\u0000${file ?? ""}`; + let ep = pending.get(exactKey); + if (!ep && file !== undefined) { + const untargetedKey = `${lang}\u0000`; + const untargeted = pending.get(untargetedKey); + if (untargeted) { + pending.delete(untargetedKey); + untargeted.key = exactKey; + untargeted.file = file; + pending.set(exactKey, untargeted); + ep = untargeted; + } + } + + if (ep) { + ep.attempts++; + ep.lastErrorSig = errSig; + if (!ep.goalSnippet && goalSnippet) ep.goalSnippet = goalSnippet; + } else { + const created: PendingEpisode = { + key: exactKey, + lang, + firstCommand: cmd, + firstError: error, + lastErrorSig: errSig, + attempts: 1, + edits: [], + editedViaShell: false, + hatches: new Map(), + }; + if (file) created.file = file; + if (goalSnippet) created.goalSnippet = goalSnippet; + pending.set(exactKey, created); + } + } else if (isGreen) { + // Bypassed checks (e.g. --no-verify, -o quick_and_dirty) never resolve a failing proof. + if (check.bypass) continue; + + const matchedKeys: string[] = []; + for (const [k, ep] of pending) { + if (ep.lang !== lang) continue; + if (explicitFile !== undefined && ep.file !== undefined && ep.file !== explicitFile) continue; + matchedKeys.push(k); + } + + for (const k of matchedKeys) { + const ep = pending.get(k)!; + pending.delete(k); + if (ep.edits.length === 0 && !ep.editedViaShell) continue; + + let escapesAdded = 0; + for (const delta of ep.hatches.values()) { + if (delta > 0) escapesAdded += delta; + } + + extracted.push({ + lang: ep.lang, + outcome: "solved", + escapesAdded, + case: buildProofCase(session, ep, "solved", cmd, redactor, opts), + }); + } + } + } + } + + for (const ep of pending.values()) { + extracted.push({ + lang: ep.lang, + outcome: "stuck", + escapesAdded: 0, + case: buildProofCase(session, ep, "stuck", undefined, redactor, opts), + }); + } + + return extracted; +} + +/** + * Mines formal-verification proof-step cases from stored sessions, applying + * optional session quality filters, proof language/outcome filters, escape-hatch + * hygiene, exact and optional near-duplicate filtering, and cap. + */ +export async function mineProofSteps(opts: MineProofStepsOpts): Promise { + if (opts.dedupeNear !== undefined) validateThreshold(opts.dedupeNear, "--dedupe-near"); + if (opts.minTurns !== undefined && (!Number.isSafeInteger(opts.minTurns) || opts.minTurns < 0)) { + throw new DatasetError(`--min-turns must be a whole number of at least 0, got ${opts.minTurns}`); + } + if (opts.limit !== undefined && (!Number.isSafeInteger(opts.limit) || opts.limit < 1)) { + throw new DatasetError(`--limit must be a whole number of at least 1, got ${opts.limit}`); + } + if (opts.proofLangs?.length) { + for (const lang of opts.proofLangs) { + if (!isProofLang(lang)) { + throw new DatasetError(`invalid proof language ${JSON.stringify(lang)}; must be one of ${PROOF_LANGS.join(", ")}`); + } + } + } + const wantOutcome: ProofStepOutcomeFilter = opts.outcome ?? "all"; + if (!isProofStepOutcomeFilter(wantOutcome)) { + throw new DatasetError(`invalid --proof-outcome ${JSON.stringify(wantOutcome)}; must be one of ${PROOF_STEP_OUTCOMES.join(", ")}`); + } + + const langSet = opts.proofLangs?.length ? new Set(opts.proofLangs) : undefined; + const deduper = new CaseDeduper(opts.dedupeNear, opts.shingleSize ?? DEFAULT_SHINGLE_SIZE, opts.existing); + const redactor = createRedactor(); + const droppedBy: Partial> = {}; + const duplicates: NearDedupeDrop[] = []; + let matched = 0; + let kept = 0; + + for (const s of opts.sessions) { + if (opts.minTurns !== undefined && (s.stats.turns ?? 0) < opts.minTurns) { + bumpReason(droppedBy, "min-turns"); + continue; + } + if (opts.excludeFlagged && (s.flags ?? []).some(isFailureFlag)) { + bumpReason(droppedBy, "flagged"); + continue; + } + if (opts.minScores?.length) { + const sScores = opts.scores?.get(s.id); + const ok = opts.minScores.every((f) => { + const v = sScores?.get(f.name); + return v !== undefined && v >= f.min; + }); + if (!ok) { + bumpReason(droppedBy, "min-score"); + continue; + } + } + + const events = await opts.getEvents(s.id); + const extractOpts: { split?: Split; tags?: readonly string[]; redactor: Redactor } = { redactor }; + if (opts.split) extractOpts.split = opts.split; + if (opts.tags?.length) extractOpts.tags = opts.tags; + const steps = extractSessionProofSteps(s, events, extractOpts); + + for (const step of steps) { + matched++; + if (langSet && !langSet.has(step.lang)) { + bumpReason(droppedBy, "proof-lang"); + continue; + } + if (wantOutcome !== "all" && step.outcome !== wantOutcome) { + bumpReason(droppedBy, "proof-outcome"); + continue; + } + if (step.outcome === "solved" && step.escapesAdded > 0) { + bumpReason(droppedBy, "proof-escape"); + continue; + } + if (opts.limit !== undefined && kept >= opts.limit) { + bumpReason(droppedBy, "limit"); + continue; + } + const drop = deduper.consider(step.case); + if (drop) { + duplicates.push(drop); + bumpReason(droppedBy, drop.kind === "exact" ? "exact-duplicate" : "near-duplicate"); + continue; + } + kept++; + } + } + + const cases = deduper.keptCases(); + let dropped = 0; + for (const n of Object.values(droppedBy)) { + if (typeof n === "number") dropped += n; + } + return { cases, sessions: opts.sessions.length, matched, kept: cases.length, dropped, droppedBy, duplicates }; +} diff --git a/packages/coding.sh/test/datasets/proof-mine.test.ts b/packages/coding.sh/test/datasets/proof-mine.test.ts new file mode 100644 index 00000000..921e099a --- /dev/null +++ b/packages/coding.sh/test/datasets/proof-mine.test.ts @@ -0,0 +1,567 @@ +// Unit and end-to-end CLI tests for formal-verification proof-step dataset mining +// (`mineProofSteps` and `coding.sh dataset mine --proof-steps`). +// Uses throwaway temp HOME / USERPROFILE / CODING_SH_HOME only. +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { after, before, describe, it } from "node:test"; +import { findCommand } from "../../src/cli/registry.ts"; +import { PROOF_LANGS } from "../../src/core/proof.ts"; +import { DatasetError } from "../../src/datasets/dataset.ts"; +import { + extractSessionProofSteps, + MAX_WINNING_DIFF_CHARS, + mineProofSteps, + type ProofStepExpectedSolved, + type ProofStepExpectedStuck, + type ProofStepInput, +} from "../../src/datasets/proof-mine.ts"; +import { FileEvalStore } from "../../src/datasets/store.ts"; +import type { Dataset } from "../../src/datasets/types.ts"; +import type { AgentEvent, Session } from "../../src/schema/index.ts"; +import { SqliteIndexStore } from "../../src/store/sqlite.ts"; +import { CLI as MAIN } from "../_cli.ts"; + +// Build synthetic secret tokens via join() so no vendor-shaped literal appears in source. +const FAKE_ANTHROPIC_KEY = ["sk-ant-", "api03-1234567890abcdef1234567890abcdef"].join(""); +const FAKE_GH_TOKEN = ["ghp_", "1234567890abcdef1234567890abcdef1234"].join(""); + +function makeSession(id: string, overrides: Partial = {}): Session { + return { + id, + agent: "claude-code", + cwd: "/work/demo", + repo: { root: "/work/demo", head: "abc123" }, + startedAt: 1_700_000_000_000, + stats: { events: 6, turns: 2, toolCalls: 4, toolErrors: 1, filesChanged: 1 }, + flags: [], + ...overrides, + }; +} + +function ev(sessionId: string, id: string, ts: number, kind: AgentEvent["kind"], payload: Record, cwd = "/work/demo"): AgentEvent { + return { id, v: 0, sessionId, ts, agent: "claude-code", kind, cwd, payload }; +} + +function leanSolvedEvents(sessionId: string, opts: { withSecrets?: boolean; longDiff?: boolean; repoRoot?: string } = {}): AgentEvent[] { + const repoRoot = opts.repoRoot ?? "/work/demo"; + const filePath = `${repoRoot.replace(/\\/g, "/")}/Proofs/Add.lean`; + const secretErr = opts.withSecrets ? `\n-- token: ${FAKE_ANTHROPIC_KEY}` : ""; + const secretDiff = opts.withSecrets ? `\n+ -- key ${FAKE_GH_TOKEN}` : ""; + const padding = opts.longDiff ? `\n+${" ".repeat(2)}-- ${"x".repeat(2500)}` : ""; + return [ + ev(sessionId, `${sessionId}-s1`, 1000, "tool.start", { + toolUseId: "t1", + tool: "Bash", + input: { command: `lake env lean ${filePath}` }, + }, repoRoot), + ev(sessionId, `${sessionId}-e1`, 1100, "tool.end", { + toolUseId: "t1", + tool: "Bash", + ok: false, + exitCode: 1, + output: `Exit code 1\nProofs/Add.lean:12:4: error: unsolved goals\na b : Nat\n⊢ a + b = b + a${secretErr}`, + }, repoRoot), + ev(sessionId, `${sessionId}-c1`, 1200, "file.change", { + toolUseId: "t2", + path: filePath, + op: "modify", + diff: `@@ -10,4 +10,5 @@\n theorem add_comm' (a b : Nat) : a + b = b + a := by\n- simp\n+ exact Nat.add_comm a b${secretDiff}${padding}`, + }, repoRoot), + ev(sessionId, `${sessionId}-s2`, 1300, "tool.start", { + toolUseId: "t3", + tool: "Bash", + input: { command: `lake env lean ${filePath}` }, + }, repoRoot), + ev(sessionId, `${sessionId}-e2`, 1400, "tool.end", { + toolUseId: "t3", + tool: "Bash", + ok: true, + exitCode: 0, + output: "", + }, repoRoot), + ]; +} + +function rocqStuckEvents(sessionId: string): AgentEvent[] { + return [ + ev(sessionId, `${sessionId}-c0`, 1000, "file.change", { + toolUseId: "r0", + path: "/work/demo/Arithmetic.v", + op: "modify", + diff: "@@ -1,3 +1,4 @@\n Lemma add_zero : forall n : nat, n + 0 = n.\n Proof.\n+ intros n. simpl.\n", + }), + ev(sessionId, `${sessionId}-s1`, 1100, "tool.start", { + toolUseId: "r1", + tool: "Bash", + input: { command: "coqc Arithmetic.v" }, + }), + ev(sessionId, `${sessionId}-e1`, 1200, "tool.end", { + toolUseId: "r1", + tool: "Bash", + ok: false, + exitCode: 1, + output: 'File "./Arithmetic.v", line 4, characters 2-12:\nError: Unable to unify "n + 0" with "n".', + }), + ev(sessionId, `${sessionId}-c1`, 1300, "file.change", { + toolUseId: "r2", + path: "/work/demo/Arithmetic.v", + op: "modify", + diff: "@@ -2,2 +2,2 @@\n- intros n. simpl.\n+ intros n. reflexivity.", + }), + ev(sessionId, `${sessionId}-s2`, 1400, "tool.start", { + toolUseId: "r3", + tool: "Bash", + input: { command: "coqc Arithmetic.v" }, + }), + ev(sessionId, `${sessionId}-e2`, 1500, "tool.end", { + toolUseId: "r3", + tool: "Bash", + ok: false, + exitCode: 1, + output: 'File "./Arithmetic.v", line 4, characters 2-14:\nError: Unable to unify "n + 0" with "n".', + }), + ]; +} + +function dafnyStuckEvents(sessionId: string): AgentEvent[] { + return [ + ev(sessionId, `${sessionId}-s1`, 2000, "tool.start", { + toolUseId: "d1", + tool: "Bash", + input: { command: "dafny verify Verify.dfy" }, + }), + ev(sessionId, `${sessionId}-e1`, 2100, "tool.end", { + toolUseId: "d1", + tool: "Bash", + ok: false, + exitCode: 4, + output: + "Verify.dfy(15,12): Error: a postcondition could not be proved on this return path\nVerify.dfy(10,10): Related location: this is the postcondition that could not be proved", + }), + ev(sessionId, `${sessionId}-s2`, 2200, "tool.start", { + toolUseId: "d2", + tool: "Bash", + input: { command: "dafny verify --no-verify Verify.dfy" }, + }), + ev(sessionId, `${sessionId}-e2`, 2300, "tool.end", { + toolUseId: "d2", + tool: "Bash", + ok: true, + exitCode: 0, + output: "Dafny program verifier finished with 0 verified, 0 errors", + }), + ]; +} + +describe("extractSessionProofSteps & mineProofSteps", () => { + it("keeps registry --proof-lang choices in sync with PROOF_LANGS", () => { + const mine = findCommand("dataset")?.actions?.find((a) => a.name === "mine"); + const langFlag = mine?.flags?.find((f) => f.name === "proof-lang"); + assert.deepEqual(langFlag?.choices, PROOF_LANGS); + }); + + it("extracts Lean solved transition with winningDiff, goalSnippet, normalized file, and secret redaction", async () => { + const s = makeSession("s-lean-solved"); + const events = leanSolvedEvents(s.id, { withSecrets: true }); + const report = await mineProofSteps({ + sessions: [s], + getEvents: async () => events, + tags: ["formal"], + }); + + assert.equal(report.sessions, 1); + assert.equal(report.matched, 1); + assert.equal(report.kept, 1); + assert.equal(report.dropped, 0); + + const c = report.cases[0]!; + const input = c.input as ProofStepInput; + const expected = c.expected as ProofStepExpectedSolved; + + assert.equal(input.kind, "proof-step"); + assert.equal(input.lang, "lean"); + assert.equal(input.file, "Proofs/Add.lean"); + assert.equal(input.command, "lake env lean /work/demo/Proofs/Add.lean"); + assert.match(input.error, /unsolved goals/); + assert.match(input.goalSnippet ?? "", /⊢ a \+ b = b \+ a/); + assert.equal(input.error.includes(FAKE_ANTHROPIC_KEY), false, "secret in error must be redacted"); + assert.match(input.error, /\[redacted:anthropic-key\]/); + + assert.equal(expected.resolved, true); + assert.equal(expected.attempts, 1); + assert.equal(expected.winningCheck, "lake env lean /work/demo/Proofs/Add.lean"); + assert.ok(expected.winningDiff); + assert.match(expected.winningDiff, /Nat\.add_comm/); + assert.equal(expected.winningDiff.includes(FAKE_GH_TOKEN), false, "secret in winningDiff must be redacted"); + assert.match(expected.winningDiff, /\[redacted:github-token\]/); + + assert.equal(c.sourceSessionId, s.id); + assert.equal(c.metadata?.sourceSessionId, s.id); + assert.equal(c.metadata?.lang, "lean"); + assert.equal(c.metadata?.file, "Proofs/Add.lean"); + assert.equal(c.metadata?.outcome, "solved"); + assert.equal(c.metadata?.attempts, 1); + assert.equal(c.metadata?.startedAt, s.startedAt); + assert.equal(c.metadata?.repo, "/work/demo"); + assert.ok(c.tags?.includes("proof-step")); + assert.ok(c.tags?.includes("proof:lean")); + assert.ok(c.tags?.includes("outcome:solved")); + assert.ok(c.tags?.includes("formal")); + }); + + it("caps winningDiff safely to MAX_WINNING_DIFF_CHARS", async () => { + const s = makeSession("s-lean-long"); + const report = await mineProofSteps({ + sessions: [s], + getEvents: async () => leanSolvedEvents(s.id, { longDiff: true }), + }); + assert.equal(report.kept, 1); + const expected = report.cases[0]!.expected as ProofStepExpectedSolved; + assert.ok(expected.winningDiff); + assert.ok(expected.winningDiff.length <= MAX_WINNING_DIFF_CHARS); + assert.ok(expected.winningDiff.endsWith("…")); + }); + + it("drops solved transitions that introduce an unremoved escape hatch and keeps ones that remove temporary escapes", async () => { + const sEscape = makeSession("s-lean-sorry"); + const escapeEvents: AgentEvent[] = [ + ev(sEscape.id, "e1", 1000, "tool.start", { toolUseId: "t1", tool: "Bash", input: { command: "lake env lean Proofs/Bad.lean" } }), + ev(sEscape.id, "e2", 1100, "tool.end", { toolUseId: "t1", tool: "Bash", ok: false, exitCode: 1, output: "Proofs/Bad.lean:5:2: error: unsolved goals\n⊢ True" }), + ev(sEscape.id, "e3", 1200, "file.change", { toolUseId: "t2", path: "Proofs/Bad.lean", op: "modify", diff: "@@ -4,2 +4,2 @@\n- omega\n+ sorry" }), + ev(sEscape.id, "e4", 1300, "tool.start", { toolUseId: "t3", tool: "Bash", input: { command: "lake env lean Proofs/Bad.lean" } }), + ev(sEscape.id, "e5", 1400, "tool.end", { toolUseId: "t3", tool: "Bash", ok: true, exitCode: 0, output: "warning: declaration uses 'sorry'" }), + ]; + + const sTempEscape = makeSession("s-lean-temp-sorry"); + const tempEscapeEvents: AgentEvent[] = [ + ev(sTempEscape.id, "e1", 1000, "tool.start", { toolUseId: "t1", tool: "Bash", input: { command: "lake env lean Proofs/Good.lean" } }), + ev(sTempEscape.id, "e2", 1100, "tool.end", { toolUseId: "t1", tool: "Bash", ok: false, exitCode: 1, output: "Proofs/Good.lean:5:2: error: unsolved goals\n⊢ 1 = 1" }), + ev(sTempEscape.id, "e3", 1200, "file.change", { toolUseId: "t2", path: "Proofs/Good.lean", op: "modify", diff: "@@ -4,2 +4,2 @@\n- omega\n+ sorry" }), + ev(sTempEscape.id, "e4", 1250, "file.change", { toolUseId: "t3", path: "Proofs/Good.lean", op: "modify", diff: "@@ -4,2 +4,2 @@\n- sorry\n+ rfl" }), + ev(sTempEscape.id, "e5", 1300, "tool.start", { toolUseId: "t4", tool: "Bash", input: { command: "lake env lean Proofs/Good.lean" } }), + ev(sTempEscape.id, "e6", 1400, "tool.end", { toolUseId: "t4", tool: "Bash", ok: true, exitCode: 0, output: "" }), + ]; + + const byId = new Map([ + [sEscape.id, escapeEvents], + [sTempEscape.id, tempEscapeEvents], + ]); + const report = await mineProofSteps({ + sessions: [sEscape, sTempEscape], + getEvents: async (id) => byId.get(id) ?? [], + }); + + assert.equal(report.matched, 2); + assert.equal(report.kept, 1); + assert.equal(report.droppedBy["proof-escape"], 1); + assert.equal(report.cases[0]?.sourceSessionId, sTempEscape.id); + }); + + it("extracts Rocq and Dafny stuck goals and ignores bypassed green checks", async () => { + const sRocq = makeSession("s-rocq-stuck"); + const sDafny = makeSession("s-dafny-stuck"); + const byId = new Map([ + [sRocq.id, rocqStuckEvents(sRocq.id)], + [sDafny.id, dafnyStuckEvents(sDafny.id)], + ]); + + const report = await mineProofSteps({ + sessions: [sRocq, sDafny], + getEvents: async (id) => byId.get(id) ?? [], + }); + + assert.equal(report.matched, 2); + assert.equal(report.kept, 2); + + const rocq = report.cases.find((c) => c.sourceSessionId === sRocq.id)!; + const rocqIn = rocq.input as ProofStepInput; + const rocqExp = rocq.expected as ProofStepExpectedStuck; + assert.equal(rocqIn.lang, "rocq"); + assert.equal(rocqIn.file, "Arithmetic.v"); + assert.match(rocqIn.error, /Unable to unify/); + assert.match(rocqIn.goalSnippet ?? "", /Lemma add_zero/); + assert.equal(rocqExp.resolved, false); + assert.equal(rocqExp.attempts, 2); + assert.equal(rocq.metadata?.outcome, "stuck"); + + const dafny = report.cases.find((c) => c.sourceSessionId === sDafny.id)!; + const dafnyIn = dafny.input as ProofStepInput; + const dafnyExp = dafny.expected as ProofStepExpectedStuck; + assert.equal(dafnyIn.lang, "dafny"); + assert.equal(dafnyIn.file, "Verify.dfy"); + assert.match(dafnyIn.error, /postcondition could not be proved/); + assert.match(dafnyIn.goalSnippet ?? "", /Related location/); + assert.equal(dafnyExp.resolved, false); + assert.equal(dafnyExp.attempts, 1); + }); + + it("filters by proofLangs and outcome, and deduplicates on incremental re-mining", async () => { + const sLean = makeSession("s-lean"); + const sRocq = makeSession("s-rocq"); + const sDafny = makeSession("s-dafny"); + const byId = new Map([ + [sLean.id, leanSolvedEvents(sLean.id)], + [sRocq.id, rocqStuckEvents(sRocq.id)], + [sDafny.id, dafnyStuckEvents(sDafny.id)], + ]); + const sessions = [sLean, sRocq, sDafny]; + const getEvents = async (id: string) => byId.get(id) ?? []; + + const onlySolved = await mineProofSteps({ sessions, getEvents, outcome: "solved" }); + assert.equal(onlySolved.kept, 1); + assert.equal(onlySolved.droppedBy["proof-outcome"], 2); + assert.equal(onlySolved.cases[0]?.metadata?.lang, "lean"); + + const onlyStuck = await mineProofSteps({ sessions, getEvents, outcome: "stuck" }); + assert.equal(onlyStuck.kept, 2); + assert.equal(onlyStuck.droppedBy["proof-outcome"], 1); + + const onlyRocq = await mineProofSteps({ sessions, getEvents, proofLangs: ["rocq"] }); + assert.equal(onlyRocq.kept, 1); + assert.equal(onlyRocq.droppedBy["proof-lang"], 2); + assert.equal(onlyRocq.cases[0]?.metadata?.lang, "rocq"); + + const first = await mineProofSteps({ sessions, getEvents }); + assert.equal(first.kept, 3); + + const second = await mineProofSteps({ sessions, getEvents, existing: first.cases }); + assert.equal(second.kept, 0); + assert.equal(second.droppedBy["exact-duplicate"], 3); + }); + + it("rejects invalid proofLangs and invalid outcome in JS API", async () => { + await assert.rejects( + () => + mineProofSteps({ + sessions: [], + getEvents: async () => [], + proofLangs: ["agda" as never], + }), + DatasetError, + ); + await assert.rejects( + () => + mineProofSteps({ + sessions: [], + getEvents: async () => [], + outcome: "broken" as never, + }), + DatasetError, + ); + }); + + it("does not emit a solved case when a green check runs with no proof-file edit after failure", () => { + const s = makeSession("s-no-edit"); + const events: AgentEvent[] = [ + ev(s.id, "e1", 1000, "tool.start", { toolUseId: "t1", tool: "Bash", input: { command: "lake env lean A.lean" } }), + ev(s.id, "e2", 1100, "tool.end", { toolUseId: "t1", tool: "Bash", ok: false, exitCode: 1, output: "A.lean:1:1: error: unknown identifier" }), + ev(s.id, "e3", 1200, "tool.start", { toolUseId: "t2", tool: "Bash", input: { command: "lake env lean A.lean" } }), + ev(s.id, "e4", 1300, "tool.end", { toolUseId: "t2", tool: "Bash", ok: true, exitCode: 0, output: "" }), + ]; + assert.equal(extractSessionProofSteps(s, events).length, 0); + }); +}); + +describe("coding.sh dataset mine --proof-steps CLI", () => { + let root = ""; + let env: Record = {}; + + function runCli(args: string[]) { + return spawnSync(process.execPath, ["--no-warnings", MAIN, ...args], { + env, + cwd: root, + encoding: "utf8", + timeout: 30_000, + }); + } + + function runJson>(args: string[]): T { + const r = runCli([...args, "--json"]); + assert.equal(r.status, 0, `coding.sh ${args.join(" ")} failed (exit ${r.status}):\n${r.stderr}\n${r.stdout}`); + return JSON.parse(r.stdout) as T; + } + + async function readDataset(id: string): Promise { + const index = await SqliteIndexStore.open(join(env.CODING_SH_HOME!, "index.db")); + try { + return await new FileEvalStore({ env, index }).getDataset(id); + } finally { + await index.close(); + } + } + + before(async () => { + root = realpathSync(mkdtempSync(join(tmpdir(), "csh-proof-mine-cli-"))); + const home = join(root, "home"); + mkdirSync(join(root, "tmp"), { recursive: true }); + mkdirSync(home); + env = { + HOME: home, + USERPROFILE: home, + CODING_SH_HOME: join(home, ".coding.sh"), + XDG_CONFIG_HOME: join(home, ".config"), + XDG_DATA_HOME: join(home, ".local", "share"), + TMPDIR: join(root, "tmp"), + PATH: dirname(process.execPath), + NO_COLOR: "1", + CODING_SH_NO_AUTO_INGEST: "1", + }; + mkdirSync(env.CODING_SH_HOME!, { recursive: true }); + + const now = Date.now(); + const repo = join(root, "proof-repo"); + mkdirSync(repo, { recursive: true }); + + const index = await SqliteIndexStore.open(join(env.CODING_SH_HOME!, "index.db")); + try { + const sLean = makeSession("cli-lean-solved", { cwd: repo, repo: { root: repo, head: "aaa111" }, startedAt: now - 60_000 }); + const sRocq = makeSession("cli-rocq-stuck", { cwd: repo, repo: { root: repo, head: "aaa111" }, startedAt: now - 120_000 }); + const sDafny = makeSession("cli-dafny-stuck", { cwd: repo, repo: { root: repo, head: "aaa111" }, startedAt: now - 180_000 }); + + await index.upsertSession(sLean); + await index.putEvents(leanSolvedEvents(sLean.id, { withSecrets: true, repoRoot: repo })); + + await index.upsertSession(sRocq); + await index.putEvents( + rocqStuckEvents(sRocq.id).map((e) => ({ + ...e, + cwd: repo, + payload: + e.kind === "file.change" + ? { ...e.payload, path: join(repo, "Arithmetic.v") } + : e.payload, + })), + ); + + await index.upsertSession(sDafny); + await index.putEvents(dafnyStuckEvents(sDafny.id).map((e) => ({ ...e, cwd: repo }))); + } finally { + await index.close(); + } + }); + + after(() => rmSync(root, { recursive: true, force: true })); + + it("mines proof steps end to end, deduplicates on re-run, and shows up in dataset stats and list", async () => { + const dry = runJson<{ outcome: string; sessions: number; matched: number; kept: number; dropped: number }>([ + "dataset", + "mine", + "proof-bench", + "--proof-steps", + "--dry-run", + ]); + assert.equal(dry.outcome, "dry-run"); + assert.equal(dry.sessions, 3); + assert.equal(dry.matched, 3); + assert.equal(dry.kept, 3); + assert.equal(await readDataset("proof-bench"), undefined); + + const mined = runJson<{ + outcome: string; + sessions: number; + matched: number; + kept: number; + dataset: { id: string; version: string; cases: number }; + }>(["dataset", "mine", "proof-bench", "--proof-steps"]); + assert.equal(mined.outcome, "created"); + assert.equal(mined.sessions, 3); + assert.equal(mined.kept, 3); + assert.equal(mined.dataset.id, "proof-bench"); + assert.equal(mined.dataset.cases, 3); + + const ds = await readDataset("proof-bench"); + assert.ok(ds); + assert.equal(ds.cases.length, 3); + const leanCase = ds.cases.find((c) => c.metadata?.lang === "lean")!; + assert.ok(leanCase); + const leanIn = leanCase.input as ProofStepInput; + const leanExp = leanCase.expected as ProofStepExpectedSolved; + assert.equal(leanIn.file, "Proofs/Add.lean"); + assert.equal(leanIn.error.includes(FAKE_ANTHROPIC_KEY), false); + assert.equal((leanExp.winningDiff ?? "").includes(FAKE_GH_TOKEN), false); + + // Incremental re-mining adds 0 duplicates. + const repeat = runJson<{ outcome: string; kept: number; droppedBy: Record }>([ + "dataset", + "mine", + "proof-bench", + "--proof-steps", + ]); + assert.equal(repeat.outcome, "unchanged"); + assert.equal(repeat.kept, 0); + assert.equal(repeat.droppedBy["exact-duplicate"], 3); + + // Inspect via dataset stats and dataset list. + const stats = runJson<{ id: string; total: number; tags: Record }>(["dataset", "stats", "proof-bench"]); + assert.equal(stats.id, "proof-bench"); + assert.equal(stats.total, 3); + assert.equal(stats.tags["proof-step"], 3); + assert.equal(stats.tags["proof:lean"], 1); + assert.equal(stats.tags["outcome:solved"], 1); + assert.equal(stats.tags["outcome:stuck"], 2); + + const listed = runJson<{ datasets: { id: string; cases: number }[] }>(["dataset", "list"]); + assert.ok(listed.datasets.some((d) => d.id === "proof-bench" && d.cases === 3)); + }); + + it("supports --proof-lang and --proof-outcome filters via CLI", () => { + const leanOnly = runJson<{ outcome: string; kept: number; droppedBy: Record }>([ + "dataset", + "mine", + "proof-lean", + "--proof-steps", + "--proof-lang", + "lean", + ]); + assert.equal(leanOnly.outcome, "created"); + assert.equal(leanOnly.kept, 1); + assert.equal(leanOnly.droppedBy["proof-lang"], 2); + + const stuckOnly = runJson<{ outcome: string; kept: number; droppedBy: Record }>([ + "dataset", + "mine", + "proof-stuck", + "--proof-steps", + "--proof-outcome", + "stuck", + "--proof-lang", + "rocq,dafny", + ]); + assert.equal(stuckOnly.outcome, "created"); + assert.equal(stuckOnly.kept, 2); + assert.equal(stuckOnly.droppedBy["proof-lang"], 1); + + const solvedOnly = runJson<{ outcome: string; kept: number; droppedBy: Record }>([ + "dataset", + "mine", + "proof-solved", + "--proof-steps", + "--proof-outcome", + "solved", + ]); + assert.equal(solvedOnly.outcome, "created"); + assert.equal(solvedOnly.kept, 1); + assert.equal(solvedOnly.droppedBy["proof-outcome"], 2); + }); + + it("exits 2 on invalid --proof-lang, invalid --proof-outcome, or proof flags without --proof-steps", () => { + const badLang = runCli(["dataset", "mine", "bad", "--proof-steps", "--proof-lang", "agda"]); + assert.equal(badLang.status, 2); + assert.match(badLang.stderr, /--proof-lang/); + + const badOutcome = runCli(["dataset", "mine", "bad", "--proof-steps", "--proof-outcome", "invalid"]); + assert.equal(badOutcome.status, 2); + assert.match(badOutcome.stderr, /--proof-outcome/); + + const missingStepsLang = runCli(["dataset", "mine", "bad", "--proof-lang", "lean"]); + assert.equal(missingStepsLang.status, 2); + assert.match(missingStepsLang.stderr, /--proof-steps/); + + const missingStepsOutcome = runCli(["dataset", "mine", "bad", "--proof-outcome", "stuck"]); + assert.equal(missingStepsOutcome.status, 2); + assert.match(missingStepsOutcome.stderr, /--proof-steps/); + }); +});