From 4df80046cc97c546476ae43d5e6962790a820d9c Mon Sep 17 00:00:00 2001 From: Jack <72348727+Jack-GitHub12@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:23:58 -0600 Subject: [PATCH 1/2] feat(query): add risk, unverified edits, and formal proof --where keys --- CHANGELOG.md | 1 + docs/reference/cli.md | 4 +- docs/reference/query.md | 8 +- packages/coding.sh/src/query/where.ts | 99 +++- .../test/query/where-risk-proof.test.ts | 452 ++++++++++++++++++ packages/store-clickhouse/src/where.ts | 8 + packages/store-postgres/src/where.ts | 8 + 7 files changed, 570 insertions(+), 10 deletions(-) create mode 100644 packages/coding.sh/test/query/where-risk-proof.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index c4abdb85..6505efa0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ grouped by area, with links to the docs for the details. ### Added +- **Query.** `--where` adds session keys `risk`, `risk.reason`, `proof.lang`, `proof.escapes`, `proof.oscillating` and `unverified.edits` (plus `risk`, `risk.reason` and `proof.lang` facets) across `sessions`, `dataset mine`, `export`, `usage`, `stats`, the viewer and MCP. [Query language](https://coding.sh/docs/query#session-keys) - **Work.** Work items surface `supervisionRisk` (`medium` or `high`), `riskReasons`, and aggregated formal-verification `proof` stats across `coding.sh work`, `work show`, `GET /api/work`, the MCP `work` tool, and the Work page (`#/work`, `#/w/`). `--risk` and `risk=` include still-running sessions matching that risk. [Work](https://github.com/jackulau/coding.sh/blob/main/docs/design/work.md#supervision-risk-and-proof-status) - **Work.** `coding.sh work`, `GET /api/work` and the MCP `work` tool filter by `--kind`, `--bucket` and `--q`. `coding.sh work ack` and `POST /api/work/ack-batch` acknowledge items in batch by `--probably-closed`, `--group` or `--bucket` with `--dry-run`. The Work page adds search, kind filters, one-click batch ack banners and a snooze duration picker. [Work](https://github.com/jackulau/coding.sh/blob/main/docs/design/work.md#surfaces) - **Scores.** `coding.sh export scores` streams typed scores as JSONL or CSV (with `--name`, `--source`, `--since`, `--until`, `--out` and text redaction). `GET /api/metrics?measure=score:`, `coding.sh stats --measure score:` and the viewer's Explore page compute bucketed and grouped means over numeric and boolean session scores. [API reference](https://github.com/jackulau/coding.sh/blob/main/docs/reference/api.md#get-apimetrics) diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 212196a3..d4b10bc4 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -558,7 +558,7 @@ coding.sh sessions [options] | `--where ` | | Only sessions matching a query, e.g. 'agent:codex cost>0.5 tool:Bash -flag:compaction' (keys: coding.sh sessions --help) | | `--view ` | | Only sessions matching this saved view's query (coding.sh views list); with --where, both must hold. | | `--fields ` | | With --json: print only these fields, as a comma list of dotted paths (id,title,stats.usage.costUsd). A path through a list picks from each item. Repeatable. | -| `--facets []` | | Count sessions per value instead of listing them: agent, model, provider, repo, launch, branch, flag, skill, hook, kind, tool, mcp (default: agent, model, repo, flag, skill, tool) | +| `--facets []` | | Count sessions per value instead of listing them: agent, model, provider, repo, launch, branch, flag, skill, hook, risk, risk.reason, proof.lang, kind, tool, mcp (default: agent, model, repo, flag, skill, tool) | | `--fresh` | | Wait for every pending capture to be ingested (default: answer after 1.5 s) | ```sh @@ -570,7 +570,7 @@ coding.sh sessions --agent codex --since 7d ``` - --where: key:value clauses, AND by default; OR between clauses; ( ) to group; - to negate; a,b for either value; \* as a wildcard in text; > >= < <= and a..b on numbers. Bare words search prompts, replies, tool calls and errors (every word in one event). -- Session keys: agent, model, provider, repo, launch, branch, dir, title, id, run, parent, flag, skill, hook, hook.tokens, weights.edits, weights.changed, weights.checkpoint, since, until, duration, turns, tools, tool.errors, llm.errors, files, events, tests.passed, tests.failed, tokens, tokens.in, tokens.out, cost, cache.breaks, cache.lost, cache.cost, unapproved, has, is. Event keys (the session has a matching event; event keys in one group match the same event): kind, tool, ok, mcp, error, event.duration, user, env, release (user, env and release read the session's start event and match on their own). Also sort:-cost and limit:N. Full list with examples: https://coding.sh/docs/query. +- Session keys: agent, model, provider, repo, launch, branch, dir, title, id, run, parent, flag, skill, hook, hook.tokens, weights.edits, weights.changed, weights.checkpoint, since, until, duration, turns, tools, tool.errors, llm.errors, files, events, tests.passed, tests.failed, risk, risk.reason, proof.lang, proof.escapes, proof.oscillating, unverified.edits, tokens, tokens.in, tokens.out, cost, cache.breaks, cache.lost, cache.cost, unapproved, has, is. Event keys (the session has a matching event; event keys in one group match the same event): kind, tool, ok, mcp, error, event.duration, user, env, release (user, env and release read the session's start event and match on their own). Also sort:-cost and limit:N. Full list with examples: https://coding.sh/docs/query. - --facets counts each key over the query without that key's own clauses, so every value of a picked key still shows. --limit sets the values per key (default 10). - With --json each session is a digest: no stats.phases, no turn times in stats.turnsByModel, and each derail without the event it started at (eventId, index). show <id> --json has them all; --fields stats.phases, stats.turnsByModel or stats.derails prints them here. - In --json, repo is the root of the checkout the session ran in. A session in a linked worktree also has repoMain, the main checkout's root. diff --git a/docs/reference/query.md b/docs/reference/query.md index 59fdcb06..82da9d74 100644 --- a/docs/reference/query.md +++ b/docs/reference/query.md @@ -81,6 +81,12 @@ test each hit. | `events` | session | Events captured | `events<10` | | `tests.passed` | session | Passing tests seen | `tests.passed>0` | | `tests.failed` | session | Failing tests seen | `tests.failed>0` | +| `risk` | session | Supervision risk level: `medium` or `high` | `risk:high` | +| `risk.reason` | session | Supervision risk reason (`unverified-edits`, `tactic-oscillation`, `post-compaction-repeats`, `dead-end-loop`, `compaction-churn`) | `risk.reason:tactic-oscillation` | +| `proof.lang` | session | Formal proof language: `lean`, `rocq`, `dafny`, `verus`, `isabelle`, `tla` or `tlc` | `proof.lang:lean` | +| `proof.escapes` | session | Remaining proof escape hatches (`sorry`, `Admitted`, …) in proof sessions | `proof.escapes>0` | +| `proof.oscillating` | session | Consecutive repeated failing proof checks in proof sessions | `proof.oscillating>=2` | +| `unverified.edits` | session | Longest streak of file edits with no mechanical check in between | `unverified.edits>=5` | ### Cost and token keys @@ -307,7 +313,7 @@ no-verification 6 | Option | Default | |---|---| -| Keys | `agent`, `model`, `provider`, `repo`, `launch`, `branch`, `flag`, `skill`, `hook`, `kind`, `tool`, `mcp` | +| Keys | `agent`, `model`, `provider`, `repo`, `launch`, `branch`, `flag`, `skill`, `hook`, `risk`, `risk.reason`, `proof.lang`, `kind`, `tool`, `mcp` | | With no keys | `agent`, `model`, `repo`, `flag`, `skill`, `tool` | | `--limit` | 10 values per key | diff --git a/packages/coding.sh/src/query/where.ts b/packages/coding.sh/src/query/where.ts index 8d013fed..61fad5d6 100644 --- a/packages/coding.sh/src/query/where.ts +++ b/packages/coding.sh/src/query/where.ts @@ -8,7 +8,7 @@ // every surface. This file imports no store, so the CLI registry can load the // key docs for help without one. import { CONTEXT_FLAGS, isFailureFlag } from "../core/failure-flags.ts"; -import type { AgentEvent, Session } from "../schema/index.ts"; +import type { AgentEvent, ProofLang, Session, SupervisionRisk } from "../schema/index.ts"; import { parseWhen } from "./time.ts"; export type Op = ":" | ">" | ">=" | "<" | "<="; @@ -116,6 +116,8 @@ export interface KeyDef { unit?: Unit; /** Text keys: equals (default) or contains (case-insensitive substring). */ match?: "exact" | "contains"; + /** Text keys with a fixed enum of allowed values (normalized to lowercase). */ + choices?: readonly string[]; /** Text keys: the one spelling stored values have, applied to each typed value (repo: windowsSpelling). */ spell?: (raw: string) => string; /** Time keys: since = at or after, until = before. */ @@ -265,6 +267,13 @@ const sqlGroupPath = (dir: string, main: string): string => `coalesce(${main}, C const stat = (path: string) => `json_extract(s.stats, '$.${path}')`; const num = (v: unknown): number | undefined => (typeof v === "number" && Number.isFinite(v) ? v : undefined); +const RISK_LEVELS: readonly SupervisionRisk[] = ["medium", "high"]; +const PROOF_LANGS: readonly ProofLang[] = ["lean", "rocq", "dafny", "verus", "isabelle", "tla", "tlc"]; +const proofNum = (s: Session, field: "escapeRemaining" | "oscillatingChecks"): number | undefined => { + const p = s.stats?.verification?.proof; + if (!p) return undefined; + return num(p[field]) ?? 0; +}; const tokensTotal = (s: Session): number | undefined => { const u = s.stats?.usage; if (!u) return undefined; @@ -346,6 +355,70 @@ const KEY_LIST: KeyDef[] = [ { name: "events", level: "session", type: "number", unit: "count", doc: "Events captured", example: "events<10", sql: [stat("events")], get: (s) => [num(s.stats?.events)] }, { name: "tests.passed", level: "session", type: "number", unit: "count", doc: "Passing tests seen", example: "tests.passed>0", sql: [stat("testsPassed")], get: (s) => [num(s.stats?.testsPassed)] }, { name: "tests.failed", level: "session", type: "number", unit: "count", doc: "Failing tests seen", example: "tests.failed>0", sql: [stat("testsFailed")], get: (s) => [num(s.stats?.testsFailed)] }, + { + name: "risk", + level: "session", + type: "text", + choices: RISK_LEVELS, + doc: "Supervision risk level: medium or high", + example: "risk:high", + sql: [stat("contextHygiene.supervisionRisk")], + get: (s) => [s.stats?.contextHygiene?.supervisionRisk], + facet: {}, + }, + { + name: "risk.reason", + level: "session", + type: "text", + doc: "Supervision risk reason (unverified-edits, tactic-oscillation, post-compaction-repeats, dead-end-loop, compaction-churn)", + example: "risk.reason:tactic-oscillation", + sql: ["j.value"], + multi: { from: stat("contextHygiene.riskReasons"), prefix: "" }, + get: (s) => s.stats?.contextHygiene?.riskReasons ?? [], + facet: {}, + }, + { + name: "proof.lang", + level: "session", + type: "text", + choices: PROOF_LANGS, + doc: "Formal proof language (lean, rocq, dafny, verus, isabelle, tla, tlc)", + example: "proof.lang:lean", + sql: ["j.value"], + multi: { from: stat("verification.proof.langs"), prefix: "" }, + get: (s) => s.stats?.verification?.proof?.langs ?? [], + facet: {}, + }, + { + name: "proof.escapes", + level: "session", + type: "number", + unit: "count", + doc: "Remaining proof escape hatches (sorry, Admitted, ...) in proof sessions", + example: "proof.escapes>0", + sql: [`CASE WHEN json_type(s.stats, '$.verification.proof') = 'object' THEN coalesce(${stat("verification.proof.escapeRemaining")}, 0) END`], + get: (s) => [proofNum(s, "escapeRemaining")], + }, + { + name: "proof.oscillating", + level: "session", + type: "number", + unit: "count", + doc: "Consecutive repeated failing proof checks in proof sessions", + example: "proof.oscillating>=2", + sql: [`CASE WHEN json_type(s.stats, '$.verification.proof') = 'object' THEN coalesce(${stat("verification.proof.oscillatingChecks")}, 0) END`], + get: (s) => [proofNum(s, "oscillatingChecks")], + }, + { + name: "unverified.edits", + level: "session", + type: "number", + unit: "count", + doc: "Longest consecutive streak of file edits with no mechanical check in between", + example: "unverified.edits>=5", + sql: [stat("verification.maxUnverifiedEdits")], + get: (s) => [num(s.stats?.verification?.maxUnverifiedEdits)], + }, { name: "tokens", level: "session", @@ -446,12 +519,16 @@ export interface KeyGuide { export function keyGuide(): KeyGuide[] { const enumOf = (r: Record) => Object.entries(r).map(([value, d]) => ({ value, doc: d.doc })); return [ - ...KEY_LIST.map((k): KeyGuide => ({ - name: k.name, level: k.level, type: k.type, doc: k.doc, example: k.example, - ...(k.facet ? { facet: true as const } : {}), - ...(k.type === "bool" ? { values: [{ value: "true" }, { value: "false" }] } : {}), - ...(k.type === "time" ? { values: ["1h", "24h", "7d", "30d"].map((value) => ({ value })) } : {}), - })), + ...KEY_LIST.map((k): KeyGuide => { + const g: KeyGuide = { + name: k.name, level: k.level, type: k.type, doc: k.doc, example: k.example, + ...(k.facet ? { facet: true as const } : {}), + ...(k.type === "bool" ? { values: [{ value: "true" }, { value: "false" }] } : {}), + ...(k.type === "time" ? { values: ["1h", "24h", "7d", "30d"].map((value) => ({ value })) } : {}), + }; + if (k.choices) g.values = k.choices.map((value) => ({ value })); + return g; + }), { name: "is", level: "session", type: "enum", doc: "Is a kind of session", example: "is:root", values: enumOf(IS) }, { name: "has", level: "session", type: "enum", doc: "Has a field", example: "has:tests", values: enumOf(HAS) }, { name: "sort", level: "query", type: "enum", doc: "Order by; - for descending", example: "sort:-cost", values: SORT_KEYS.flatMap((k) => [{ value: `-${k}` }, { value: k }]) }, @@ -648,6 +725,14 @@ function resolveValue(def: KeyDef, op: Op, part: Part, now: number, tzOffsetMin? if (text === "") throw bad("needs a value"); if (def.type === "text") { if (op !== ":") throw bad(`compares text with ':' only, not '${op}'`); + if (def.choices) { + const lower = text.toLowerCase(); + if (part.wild?.length || !def.choices.includes(lower)) { + throw bad(`must be one of ${def.choices.join(", ")}, got ${JSON.stringify(text)}`); + } + v.raw = lower; + return v; + } // `*` is a wildcard, quoted or not; `\*` inside quotes is a literal star. const wild = part.wild ?? starsIn(text); if (wild.length) { diff --git a/packages/coding.sh/test/query/where-risk-proof.test.ts b/packages/coding.sh/test/query/where-risk-proof.test.ts new file mode 100644 index 00000000..3379262c --- /dev/null +++ b/packages/coding.sh/test/query/where-risk-proof.test.ts @@ -0,0 +1,452 @@ +// `--where` keys for supervision risk, unverified edits, and formal proof stats: +// parser + enum validation, exact parity between SqliteIndexStore and MemoryIndexStore +// (positive, negated, comma lists, numeric operators/ranges, sorting, facets), and +// end-to-end CLI coverage (`coding.sh sessions --where` and `coding.sh dataset mine --where`). +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, realpathSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { after, before, describe, test } from "node:test"; +import { PROOF_LANGS } from "../../src/core/proof.ts"; +import type { IndexStore } from "../../src/core/types.ts"; +import { SUPERVISION_RISKS } from "../../src/core/work.ts"; +import { FileEvalStore } from "../../src/datasets/store.ts"; +import { facetCounts, findSessions } from "../../src/query/run.ts"; +import { KEYS, keyGuide, parseWhere, printWhere, QueryError } from "../../src/query/where.ts"; +import type { AgentEvent, Session } from "../../src/schema/index.ts"; +import { MemoryIndexStore } from "../../src/store/memory.ts"; +import { SqliteIndexStore } from "../../src/store/sqlite.ts"; +import { tmpEnv, type TmpEnv } from "../adapters/_helpers.ts"; +import { cli, event, ok, seed, session, T0 } from "./_seed.ts"; + +const H = 3_600_000; + +function stripAt(x: unknown): unknown { + if (Array.isArray(x)) return x.map(stripAt); + if (x && typeof x === "object") { + const out: Record = {}; + for (const [k, v] of Object.entries(x)) if (k !== "at") out[k] = stripAt(v); + return out; + } + return x; +} + +function riskProofFixture(repoRoot = "/work/proofs"): { sessions: Session[]; events: AgentEvent[] } { + const repo = { root: repoRoot, head: "abc123", branch: "main" }; + const sessions: Session[] = [ + session("s-lean-high", { + agent: "claude-code", + cwd: repoRoot, + repo, + startedAt: T0, + endedAt: T0 + 15 * 60_000, + title: "Prove ring homomorphism lemma in Lean", + stats: { + events: 10, + turns: 4, + toolCalls: 9, + toolErrors: 4, + filesChanged: 2, + verification: { + checks: 6, + passed: 1, + failed: 5, + maxUnverifiedEdits: 6, + proof: { + langs: ["lean"], + checks: 6, + passed: 1, + failed: 5, + escapeAdded: 2, + escapeRemaining: 2, + oscillatingChecks: 4, + }, + }, + contextHygiene: { + compactions: 1, + deadEndStreak: 3, + supervisionRisk: "high", + riskReasons: ["unverified-edits", "tactic-oscillation"], + }, + }, + }), + session("s-lean-clean", { + agent: "claude-code", + cwd: repoRoot, + repo, + startedAt: T0 + H, + endedAt: T0 + H + 8 * 60_000, + title: "Prove list reversal involution in Lean", + stats: { + events: 8, + turns: 3, + toolCalls: 6, + toolErrors: 0, + filesChanged: 1, + verification: { + checks: 2, + passed: 2, + failed: 0, + maxUnverifiedEdits: 1, + proof: { + langs: ["lean"], + checks: 2, + passed: 2, + failed: 0, + }, + }, + }, + }), + session("s-rocq-dafny", { + agent: "codex", + cwd: repoRoot, + repo, + startedAt: T0 + 2 * H, + endedAt: T0 + 2 * H + 12 * 60_000, + title: "Verify sorting invariant in Rocq and Dafny", + stats: { + events: 9, + turns: 3, + toolCalls: 8, + toolErrors: 2, + filesChanged: 2, + verification: { + checks: 4, + passed: 2, + failed: 2, + maxUnverifiedEdits: 3, + proof: { + langs: ["dafny", "rocq"], + checks: 4, + passed: 2, + failed: 2, + escapeAdded: 1, + escapeRemaining: 1, + oscillatingChecks: 2, + }, + }, + contextHygiene: { + supervisionRisk: "medium", + riskReasons: ["tactic-oscillation"], + }, + }, + }), + session("s-med-nonproof", { + agent: "claude-code", + cwd: repoRoot, + repo, + startedAt: T0 + 3 * H, + endedAt: T0 + 3 * H + 10 * 60_000, + title: "Refactor parser pipeline with long edit streak", + stats: { + events: 10, + turns: 4, + toolCalls: 10, + toolErrors: 2, + filesChanged: 5, + verification: { + checks: 1, + passed: 1, + failed: 0, + maxUnverifiedEdits: 5, + }, + contextHygiene: { + compactions: 1, + postCompactionFailedRepeats: 1, + supervisionRisk: "medium", + riskReasons: ["unverified-edits", "post-compaction-repeats"], + }, + }, + }), + session("s-verified-zero", { + agent: "codex", + cwd: repoRoot, + repo, + startedAt: T0 + 4 * H, + endedAt: T0 + 4 * H + 5 * 60_000, + title: "Run test suite cleanly without edits", + stats: { + events: 6, + turns: 2, + toolCalls: 4, + toolErrors: 0, + filesChanged: 0, + verification: { + checks: 3, + passed: 3, + failed: 0, + maxUnverifiedEdits: 0, + }, + }, + }), + session("s-plain", { + agent: "gemini", + cwd: repoRoot, + repo, + startedAt: T0 + 5 * H, + endedAt: T0 + 5 * H + 2 * 60_000, + title: "Explain architecture overview", + stats: { + events: 4, + turns: 2, + toolCalls: 1, + toolErrors: 0, + filesChanged: 0, + }, + }), + ]; + + const events: AgentEvent[] = sessions.flatMap((s) => [ + event(s.id, 1, { agent: s.agent, ts: s.startedAt + 1000, kind: "user.message", payload: { text: `${s.title} with full verification` } }), + event(s.id, 2, { agent: s.agent, ts: s.startedAt + 2000, kind: "assistant.message", payload: { text: `Completed work for ${s.id}.` } }), + ]); + return { sessions, events }; +} + +describe("risk and proof --where parser and validation", () => { + test("enum keys stay aligned with SUPERVISION_RISKS, PROOF_LANGS, and keyGuide()", () => { + assert.deepEqual(KEYS.get("risk")?.choices, SUPERVISION_RISKS); + assert.deepEqual(KEYS.get("proof.lang")?.choices, PROOF_LANGS); + const guide = new Map(keyGuide().map((g) => [g.name, g])); + assert.deepEqual(guide.get("risk")?.values?.map((v) => v.value), [...SUPERVISION_RISKS]); + assert.equal(guide.get("risk")?.facet, true); + assert.equal(guide.get("risk.reason")?.facet, true); + assert.deepEqual(guide.get("proof.lang")?.values?.map((v) => v.value), [...PROOF_LANGS]); + assert.equal(guide.get("proof.lang")?.facet, true); + }); + + const valid: [string, string][] = [ + ["risk:high", "risk:high"], + ["risk:medium", "risk:medium"], + ["risk:medium,high", "risk:medium,high"], + ["risk:HIGH", "risk:high"], + ["-risk:high", "-risk:high"], + ["risk.reason:tactic-oscillation", "risk.reason:tactic-oscillation"], + ["risk.reason:tactic-oscillation,post-compaction-repeats", "risk.reason:tactic-oscillation,post-compaction-repeats"], + ["risk.reason:*compaction*", "risk.reason:*compaction*"], + ["-risk.reason:dead-end-loop", "-risk.reason:dead-end-loop"], + ["proof.lang:lean", "proof.lang:lean"], + ["proof.lang:Lean,ROCQ", "proof.lang:lean,rocq"], + ["proof.lang:lean,rocq,dafny,verus,isabelle,tla,tlc", "proof.lang:lean,rocq,dafny,verus,isabelle,tla,tlc"], + ["-proof.lang:lean", "-proof.lang:lean"], + ["proof.escapes>0", "proof.escapes>0"], + ["proof.escapes:0", "proof.escapes:0"], + ["proof.escapes:1..3", "proof.escapes:1..3"], + ["-proof.escapes>0", "-proof.escapes>0"], + ["proof.oscillating>=2", "proof.oscillating>=2"], + ["proof.oscillating<4", "proof.oscillating<4"], + ["proof.oscillating:0", "proof.oscillating:0"], + ["unverified.edits>=5", "unverified.edits>=5"], + ["unverified.edits<=3", "unverified.edits<=3"], + ["unverified.edits:0", "unverified.edits:0"], + ["unverified.edits:2..6", "unverified.edits:2..6"], + ["sort:-proof.escapes", "sort:-proof.escapes"], + ["sort:-proof.oscillating", "sort:-proof.oscillating"], + ["sort:-unverified.edits", "sort:-unverified.edits"], + ]; + + for (const [q, norm] of valid) { + test(`parses and round-trips ${q}`, () => { + const ast = parseWhere(q); + assert.equal(printWhere(ast), norm); + assert.deepEqual(stripAt(parseWhere(printWhere(ast))), stripAt(ast)); + }); + } + + const invalid: [string, string, number][] = [ + ["risk:low", "bad_value", 5], + ["risk:none", "bad_value", 5], + ["risk:critical", "bad_value", 5], + ["risk:h*", "bad_value", 5], + ["risk:medium,bogus", "bad_value", 12], + ["risk>medium", "bad_value", 5], + ["risk:", "bad_value", 5], + ["proof.lang:python", "bad_value", 11], + ["proof.lang:coq", "bad_value", 11], + ["proof.lang:lean*", "bad_value", 11], + ["proof.lang:lean,invalid", "bad_value", 16], + ["proof.lang>lean", "bad_value", 11], + ["proof.lang:", "bad_value", 11], + ["risk.reason>tactic-oscillation", "bad_value", 12], + ["risk.reason:", "bad_value", 12], + ["proof.escapes:abc", "bad_value", 14], + ["proof.escapes:>0", "bad_value", 14], + ["proof.escapes:5..2", "bad_value", 14], + ["proof.oscillating:abc", "bad_value", 18], + ["proof.oscillating:>=2", "bad_value", 18], + ["unverified.edits:abc", "bad_value", 17], + ["unverified.edits:>=5", "bad_value", 17], + ["unverified.edits:10..3", "bad_value", 17], + ]; + + for (const [q, reason, offset] of invalid) { + test(`rejects invalid query ${q}`, () => { + assert.throws(() => parseWhere(q), (e: unknown) => e instanceof QueryError && e.reason === reason && e.offset === offset); + }); + } +}); + +describe("SQLite and MemoryIndexStore parity for risk and proof keys", () => { + let dir = ""; + let sqlite: SqliteIndexStore; + let memory: MemoryIndexStore; + + before(async () => { + dir = mkdtempSync(join(tmpdir(), "csh-where-risk-proof-")); + sqlite = await SqliteIndexStore.open(join(dir, "index.db")); + memory = new MemoryIndexStore(); + const { sessions, events } = riskProofFixture(); + for (const st of [sqlite, memory] as IndexStore[]) { + await st.putEvents(events); + for (const s of sessions) await st.upsertSession(s); + } + }); + + after(async () => { + await sqlite?.close(); + rmSync(dir, { recursive: true, force: true }); + }); + + const ids = async (st: IndexStore, q: string) => (await findSessions(st, parseWhere(q))).sessions.map((s) => s.id); + + // Ordered newest first (s-plain -> s-verified-zero -> s-med-nonproof -> s-rocq-dafny -> s-lean-clean -> s-lean-high). + const cases: [string, string[]][] = [ + ["risk:high", ["s-lean-high"]], + ["risk:medium", ["s-med-nonproof", "s-rocq-dafny"]], + ["risk:medium,high", ["s-med-nonproof", "s-rocq-dafny", "s-lean-high"]], + ["risk:HIGH", ["s-lean-high"]], + ["-risk:high", ["s-plain", "s-verified-zero", "s-med-nonproof", "s-rocq-dafny", "s-lean-clean"]], + ["-risk:medium,high", ["s-plain", "s-verified-zero", "s-lean-clean"]], + ["risk.reason:tactic-oscillation", ["s-rocq-dafny", "s-lean-high"]], + ["risk.reason:post-compaction-repeats", ["s-med-nonproof"]], + ["risk.reason:tactic-oscillation,post-compaction-repeats", ["s-med-nonproof", "s-rocq-dafny", "s-lean-high"]], + ["risk.reason:*compaction*", ["s-med-nonproof"]], + ["-risk.reason:tactic-oscillation", ["s-plain", "s-verified-zero", "s-med-nonproof", "s-lean-clean"]], + ["proof.lang:lean", ["s-lean-clean", "s-lean-high"]], + ["proof.lang:rocq", ["s-rocq-dafny"]], + ["proof.lang:dafny", ["s-rocq-dafny"]], + ["proof.lang:lean,rocq", ["s-rocq-dafny", "s-lean-clean", "s-lean-high"]], + ["proof.lang:verus", []], + ["-proof.lang:lean", ["s-plain", "s-verified-zero", "s-med-nonproof", "s-rocq-dafny"]], + ["proof.escapes>0", ["s-rocq-dafny", "s-lean-high"]], + ["proof.escapes>=2", ["s-lean-high"]], + ["proof.escapes<2", ["s-rocq-dafny", "s-lean-clean"]], + ["proof.escapes<=1", ["s-rocq-dafny", "s-lean-clean"]], + ["proof.escapes:0", ["s-lean-clean"]], + ["proof.escapes:1..2", ["s-rocq-dafny", "s-lean-high"]], + ["-proof.escapes>0", ["s-plain", "s-verified-zero", "s-med-nonproof", "s-lean-clean"]], + ["proof.oscillating>0", ["s-rocq-dafny", "s-lean-high"]], + ["proof.oscillating>=2", ["s-rocq-dafny", "s-lean-high"]], + ["proof.oscillating>2", ["s-lean-high"]], + ["proof.oscillating<3", ["s-rocq-dafny", "s-lean-clean"]], + ["proof.oscillating<=2", ["s-rocq-dafny", "s-lean-clean"]], + ["proof.oscillating:0", ["s-lean-clean"]], + ["proof.oscillating:2..4", ["s-rocq-dafny", "s-lean-high"]], + ["-proof.oscillating>=2", ["s-plain", "s-verified-zero", "s-med-nonproof", "s-lean-clean"]], + ["unverified.edits>=5", ["s-med-nonproof", "s-lean-high"]], + ["unverified.edits>5", ["s-lean-high"]], + ["unverified.edits<3", ["s-verified-zero", "s-lean-clean"]], + ["unverified.edits<=3", ["s-verified-zero", "s-rocq-dafny", "s-lean-clean"]], + ["unverified.edits:0", ["s-verified-zero"]], + ["unverified.edits:3..6", ["s-med-nonproof", "s-rocq-dafny", "s-lean-high"]], + ["-unverified.edits>=5", ["s-plain", "s-verified-zero", "s-rocq-dafny", "s-lean-clean"]], + ["proof.lang:lean risk:high", ["s-lean-high"]], + ["proof.lang:lean proof.escapes:0", ["s-lean-clean"]], + ["(risk:high OR proof.escapes>0) -proof.lang:rocq", ["s-lean-high"]], + ["sort:-unverified.edits", ["s-lean-high", "s-med-nonproof", "s-rocq-dafny", "s-lean-clean", "s-verified-zero", "s-plain"]], + ["sort:-proof.escapes", ["s-lean-high", "s-rocq-dafny", "s-lean-clean", "s-plain", "s-verified-zero", "s-med-nonproof"]], + ["sort:-proof.oscillating", ["s-lean-high", "s-rocq-dafny", "s-lean-clean", "s-plain", "s-verified-zero", "s-med-nonproof"]], + ]; + + for (const [q, expected] of cases) { + test(q, async () => { + const a = await ids(sqlite, q); + const b = await ids(memory, q); + assert.deepEqual(a, expected, `sqlite ${q}`); + assert.deepEqual(b, expected, `memory ${q}`); + }); + } + + test("facets for risk, risk.reason, and proof.lang agree on SQLite and Memory", async () => { + for (const q of ["", "risk:high", "proof.lang:lean", "unverified.edits>=3"]) { + for (const key of ["risk", "risk.reason", "proof.lang"]) { + const a = await facetCounts(sqlite, parseWhere(q), [key]); + const b = await facetCounts(memory, parseWhere(q), [key]); + assert.deepEqual(a, b, `${key} over ${JSON.stringify(q)}`); + } + } + const all = await facetCounts(sqlite, parseWhere(""), ["risk", "risk.reason", "proof.lang"]); + assert.deepEqual(all.risk, [{ value: "medium", count: 2 }, { value: "high", count: 1 }]); + assert.deepEqual(all["risk.reason"], [ + { value: "tactic-oscillation", count: 2 }, + { value: "unverified-edits", count: 2 }, + { value: "post-compaction-repeats", count: 1 }, + ]); + assert.deepEqual(all["proof.lang"], [ + { value: "lean", count: 2 }, + { value: "dafny", count: 1 }, + { value: "rocq", count: 1 }, + ]); + }); +}); + +describe("end-to-end CLI sessions and dataset mine with risk and proof --where keys", () => { + let env: TmpEnv; + let repoRoot = ""; + + before(async () => { + env = tmpEnv(); + repoRoot = join(realpathSync(env.root), "proof-repo"); + mkdirSync(repoRoot, { recursive: true }); + const { sessions, events } = riskProofFixture(repoRoot); + await seed(env.dataHome, { sessions, events }); + }); + + after(() => { + env.restore(); + }); + + test("coding.sh sessions --where filters by risk, proof, and unverified edit keys", () => { + const queryIds = (q: string) => + (JSON.parse(ok(["sessions", "--limit", "50", "--where", q, "--json"]).stdout) as { sessions: { id: string }[] }).sessions.map((s) => s.id); + + assert.deepEqual(queryIds("proof.lang:lean risk:high"), ["s-lean-high"]); + assert.deepEqual(queryIds("risk:medium,high"), ["s-med-nonproof", "s-rocq-dafny", "s-lean-high"]); + assert.deepEqual(queryIds("risk.reason:post-compaction-repeats"), ["s-med-nonproof"]); + assert.deepEqual(queryIds("proof.lang:lean proof.escapes:0"), ["s-lean-clean"]); + assert.deepEqual(queryIds("proof.oscillating>=2"), ["s-rocq-dafny", "s-lean-high"]); + assert.deepEqual(queryIds("unverified.edits>=5"), ["s-med-nonproof", "s-lean-high"]); + assert.deepEqual(queryIds("-risk:high proof.lang:lean"), ["s-lean-clean"]); + + const facets = JSON.parse(ok(["sessions", "--facets", "risk,proof.lang", "--json"]).stdout) as { + facets: { risk: { value: string; count: number }[]; "proof.lang": { value: string; count: number }[] }; + }; + assert.deepEqual(facets.facets.risk, [{ value: "medium", count: 2 }, { value: "high", count: 1 }]); + assert.deepEqual(facets.facets["proof.lang"], [{ value: "lean", count: 2 }, { value: "dafny", count: 1 }, { value: "rocq", count: 1 }]); + + const bad = cli(["sessions", "--where", "risk:extreme", "--json"]); + assert.equal(bad.status, 2); + const err = JSON.parse(bad.stderr.trim().split("\n").pop()!) as { reason: string; message: string }; + assert.equal(err.reason, "bad_value"); + assert.match(err.message, /medium, high/); + }); + + test('coding.sh dataset mine --where "proof.lang:lean risk:high" mines only matching sessions', async () => { + const res = JSON.parse( + ok(["dataset", "mine", "lean-high-risk", "--where", "proof.lang:lean risk:high", "--json"]).stdout, + ) as { outcome: string; matched: number; kept: number; dataset: { id: string; cases: number } }; + assert.equal(res.outcome, "created"); + assert.equal(res.matched, 1); + assert.equal(res.kept, 1); + assert.equal(res.dataset.cases, 1); + + const index = await SqliteIndexStore.open(join(env.dataHome, "index.db")); + try { + const ds = await new FileEvalStore({ env: process.env, index }).getDataset(res.dataset.id, "latest"); + assert.ok(ds); + assert.deepEqual(ds.cases.map((c) => c.sourceSessionId), ["s-lean-high"]); + } finally { + await index.close(); + } + }); +}); diff --git a/packages/store-clickhouse/src/where.ts b/packages/store-clickhouse/src/where.ts index dfca690a..d6395f92 100644 --- a/packages/store-clickhouse/src/where.ts +++ b/packages/store-clickhouse/src/where.ts @@ -99,6 +99,12 @@ export const KEY_SQL: Record = { events: [stat("events")], "tests.passed": [stat("testsPassed")], "tests.failed": [stat("testsFailed")], + risk: [jstr("stats", "contextHygiene.supervisionRisk")], + "risk.reason": ["f"], + "proof.lang": ["f"], + "proof.escapes": [`if(JSONType(stats, 'verification', 'proof') = 'Object', ifNull(${stat("verification.proof.escapeRemaining")}, 0), NULL)`], + "proof.oscillating": [`if(JSONType(stats, 'verification', 'proof') = 'Object', ifNull(${stat("verification.proof.oscillatingChecks")}, 0), NULL)`], + "unverified.edits": [stat("verification.maxUnverifiedEdits")], tokens: [`if(JSONType(stats, 'usage') = 'Object', ${tokens}, NULL)`], "tokens.in": [stat("usage.inputTokens")], "tokens.out": [stat("usage.outputTokens")], @@ -167,6 +173,8 @@ export function assertSupported(n: Node): void { const MULTI_FROM: Record = { // An empty array when the session recorded no checkpoint. "weights.checkpoint": "JSONExtract(stats, 'weightEdits', 'checkpoints', 'Array(String)')", + "risk.reason": "JSONExtract(stats, 'contextHygiene', 'riskReasons', 'Array(String)')", + "proof.lang": "JSONExtract(stats, 'verification', 'proof', 'langs', 'Array(String)')", }; const multiFrom = (key: string): string => MULTI_FROM[key] ?? "flags"; diff --git a/packages/store-postgres/src/where.ts b/packages/store-postgres/src/where.ts index 1cdd25cb..7a896cd1 100644 --- a/packages/store-postgres/src/where.ts +++ b/packages/store-postgres/src/where.ts @@ -91,6 +91,12 @@ export const KEY_SQL: Record = { events: [stat("events")], "tests.passed": [stat("testsPassed")], "tests.failed": [stat("testsFailed")], + risk: [jstr("s.stats", "contextHygiene,supervisionRisk")], + "risk.reason": ["f.v"], + "proof.lang": ["f.v"], + "proof.escapes": [`(CASE WHEN json_typeof(s.stats::json #> '{verification,proof}') = 'object' THEN coalesce(${stat("verification,proof,escapeRemaining")}, 0) END)`], + "proof.oscillating": [`(CASE WHEN json_typeof(s.stats::json #> '{verification,proof}') = 'object' THEN coalesce(${stat("verification,proof,oscillatingChecks")}, 0) END)`], + "unverified.edits": [stat("verification,maxUnverifiedEdits")], tokens: [`(CASE WHEN json_typeof(s.stats::json -> 'usage') = 'object' THEN ${tokens} END)`], "tokens.in": [stat("usage,inputTokens")], "tokens.out": [stat("usage,outputTokens")], @@ -158,6 +164,8 @@ export function assertSupported(n: Node): void { /** The JSON array a list-valued key reads, one row per item: the session's flags, unless the key is named here. */ const MULTI_FROM: Record = { "weights.checkpoint": jarr("s.stats", "weightEdits,checkpoints"), + "risk.reason": jarr("s.stats", "contextHygiene,riskReasons"), + "proof.lang": jarr("s.stats", "verification,proof,langs"), }; const multiFrom = (key: string): string => MULTI_FROM[key] ?? "s.flags::json"; From e0545baef8fa54d1442df8d2bb23912d99656e02 Mon Sep 17 00:00:00 2001 From: Jack <72348727+Jack-GitHub12@users.noreply.github.com> Date: Sat, 28 Nov 2026 04:37:19 -0600 Subject: [PATCH 2/2] fix(mcp): tighten where description to keep tool surface within budget --- packages/coding.sh/src/mcp/tools.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/coding.sh/src/mcp/tools.ts b/packages/coding.sh/src/mcp/tools.ts index 3c41f2b5..39812670 100644 --- a/packages/coding.sh/src/mcp/tools.ts +++ b/packages/coding.sh/src/mcp/tools.ts @@ -80,7 +80,7 @@ const EXP_SESSION = { type: "string", description: "Default: the project's sessi const WHERE = { type: "string", description: - "Filter query: key:value clauses ANDed; OR, ( ), - negates; a,b either; * wildcard; > >= < <= and a..b on numbers; bare words search text. Keys: agent model repo branch title flag skill cost tokens duration turns tools tool.errors since until has:tests|cost|error is:root|child|flagged; event keys tool kind ok mcp error. E.g. model:claude-* cost>0.5 tool:Bash ok:false", + "Query: key:value (AND; OR, (), - negates, a,b either, * wildcard, > >= < <= a..b on numbers; bare words search text). Keys: agent model repo branch title flag skill risk proof.lang cost tokens duration turns tools tool.errors since until has:tests|cost|error is:root|child|flagged; event: tool kind ok mcp error.", }; const WHERE_SAME = (what: string) => ({ type: "string", description: `Filter query, same language as sessions_list where${what}.` }); const SESSION_ID = { type: "string", minLength: 1, description: 'Id, prefix or "latest".' };