diff --git a/README.md b/README.md index adceecc91..5e33e04fe 100644 --- a/README.md +++ b/README.md @@ -5,9 +5,10 @@ Local mirror of every storytold issue and PR, the triage pipeline's state, and t - `craft-auto sync` fills a SQLite mirror (`~/.local/share/craft-automation/mirror.db`, or `$CRAFT_AUTO_DB`) from GitHub GraphQL. Agents and scripts query the mirror instead of calling `gh`. - `craft-auto whitelist` shows and edits which contributors' PRs may merge on green CI without a decision. - `craft-auto decide` turns items that need a maintainer's scope call into dashboard decisions, each with an AI summary (`docs/pipeline.md`, Scope decisions). +- `craft-auto labels ensure|plan|apply --repo R` is the pipeline's Label stage: puts each item's settled type label and flags on GitHub. `plan` and dry runs only read; `apply --apply` writes, and only for repos an operator approved on the dashboard Repos page. See docs/pipeline.md. - `craft-auto dash serve` serves the dashboard. -Schema: `src/schema.sql`. Mirror tables are overwritten by sync; work tables (classifications, stages, whitelist overrides, token use) are ours. +Schema: `src/schema.sql`. Full-text search uses the FTS5 tables `items_fts` and `comments_fts`, kept current by triggers; the first `connect()` after an upgrade builds them (about 16 s for 56k items and 65k comments). Mirror tables are overwritten by sync; work tables (classifications, stages, whitelist overrides, token use) are ours. TypeScript on Node 24, run directly (type stripping, no build step): `node src/cli.ts `. SQLite through the built-in `node:sqlite`. `pnpm check` type-checks; `pnpm test` runs the tests. @@ -44,6 +45,7 @@ The frontend in `web/` talks to `/api/`; the wire types are `web/src/api/types.t | Method and path | Who | |---|---| | `GET /api/me`, `/api/repos`, `/api/progress`, `/api/search?q=`, `/api/items//` | anyone signed in | +| `GET /api/items?q=&mode=text&repo=&kind=&state=&label=&status=&flag=&author=&since=&sort=&desc=&limit=&offset=&run=` (Items browser: full-text search over titles, bodies and comments, settled type labels, counts per settled status) | anyone signed in | | `GET /api/classifiers?run=&a=&b=` (agreement, confusion, confidence bands and flags for a run and classifier pair; defaults to the latest run), `/api/classifiers/disagreements?run=&a=&b=&label=&band=&limit=&offset=` | anyone signed in | | `GET /api/cost?run=` (token use, USD where recorded, and wall time per stage and model and per repo, plus spend over time; all runs when `run` is empty) | anyone signed in | | `GET /api/prompts` (every registered model prompt: template, model, call settings, output checks and a rendered example on made-up items, plus the commit the server runs) | anyone signed in | diff --git a/docs/dashboard-spec.md b/docs/dashboard-spec.md index 86cbd39a9..ccb380e35 100644 --- a/docs/dashboard-spec.md +++ b/docs/dashboard-spec.md @@ -60,13 +60,16 @@ Stage vocabulary (`stages.stage`, latest row per item wins): `classified`, `revi | Funnel step | Rule | |---|---| | Open | open in the mirror | -| Classified | has any `classifications` row | +| Classified | has a settled type label in the latest classification run (below) | +| Waiting for a second opinion / disagreement | Jev unsure and Haiku hasn't answered / Haiku gave another label | | Reviewed | has a `reviewed` stage or a `sonnet` classification | | Taken / held / to close / waiting for a decision | latest stage `take` / `hold` / `close` / `needs-decision` | | In a batch | latest stage `batched` | -| Done | item closed or merged since the run started, split by: merged by the pipeline, closed by the pipeline, closed by others | +| Done | item closed or merged since tracking began, split by: merged by the pipeline, closed by the pipeline, closed by others | -The run start is `settings.run_started_at`. +The settled type label (`src/classify/settled.ts`): Jev's label when its top probability is at least 0.9; otherwise Haiku's when Haiku agrees with Jev; otherwise the item is unsettled, waiting for Haiku or in disagreement. The latest run is the one with the newest Jev verdict. + +Done counts and trends start at `settings.tracking_started_at`, set when the database is first opened (the earliest repo sync, or that moment). ## Pages @@ -80,15 +83,19 @@ The run start is `settings.run_started_at`. ### Progress -- Org totals at the top: open now, done since run start (merged / closed), items per hour over the last 24 h, decisions open. +- Org totals at the top: open now, done by the pipeline since tracking began (merged / closed), closed by others, items closed per hour over the last 24 h, decisions open. Steps the pipeline hasn't reached yet say "not started yet". - Funnel chart for the org, then a table with one row per repo (sortable by open count, done count, decisions open). - Breakdowns: type label, size bucket (S ≤ 50 changed lines, M ≤ 300, L ≤ 1,000, XL above), contributor tier. -- Trend: open items per repo per day since run start (from `items` created/closed dates). +- Trend: open items per repo per day since tracking began (from `items` created/closed dates). ### Repo (`/repo/`) Same blocks as Progress, filtered to one repo, plus its decisions and its batches. +### Items (`/items`) + +One table over every tracked repo: ref, title, kind, state, author, updated, settled label with Jev's confidence, flags, latest stage. Filters, all kept in the URL: full-text query over titles, bodies and comments (words, "phrases", prefix\*, -excluded, OR; the matching snippet is shown), repo (several), kind, state (default open), settled label, settled status, flags, author, updated since. Sort by relevance, updated, created or number; 50 rows a page; cards on phones. The top-bar search jumps to `repo#n` and links here for full results. + ### Item (`/item//`) Title, link, author with tier, size, CI, mergeable state; the stage timeline; every classification side by side (classifier, type, want, reason); decisions about it; related items. This is where detail lives so cards can stay short. diff --git a/docs/pipeline.md b/docs/pipeline.md index b8e05ba05..90ea5eb43 100644 --- a/docs/pipeline.md +++ b/docs/pipeline.md @@ -9,13 +9,21 @@ The craft apps have about 21,000 open issues and PRs. The pipeline sorts all of | 1 | Mirror | Every issue, PR and comment of the tracked repos is copied into a local database. Later stages read the mirror, never GitHub directly. | `craft-auto sync`, every minute: one org-wide GitHub search for changes | Automatic | | 2 | Classify | Every open item gets one type label (bugfix, performance, missing feature, small extra, plugin candidate, infra) and two flags (security, needs decision). | Jev first. Where Jev is under 90 % sure, Haiku as well. Where they disagree, the item goes to a person or to Sonnet | Scripted, started by the operator (`craft-auto classify`) | | 3 | Decide | Items flagged "needs decision" (scope, wanted or not, reference-app behaviour), and items where Jev and Haiku disagree between scope labels, become decisions on this dashboard, each with an AI summary and the item's own text. | `craft-auto decide` asks them, with summaries by Sonnet. The operator answers; anyone signed in can comment and pick an option | Scripted, started by the operator | -| 4 | Label | The type label and flags go onto the item on GitHub. | Script, one repo at a time, after the operator agrees the timing for that repo | Planned | +| 4 | Label | The type label and flags go onto the item on GitHub. | `craft-auto labels`, one repo at a time. No model calls. Only items whose type is settled (Jev at 90 % or more, or Haiku agreeing with Jev) are labelled. A label a person set is never changed: an item that already has a different type label is skipped and reported. Writes to GitHub need the operator's approval for that repo, given on the Repos page | Built. `ensure` and `plan` are read-only; `apply` is a dry run unless `--apply` and refuses unapproved repos | | 5 | Review | PRs we want get a code review: take, take with fixes, hold, or close (duplicate, already fixed, superseded). | Sonnet, one reviewer per batch of related PRs; one per feature for large PRs. Tests are not reviewed, only code | Planned here; earlier rounds ran by hand | | 6 | Integrate | Taken PRs are assigned to us, fixed up on the contributor's branch where possible, grouped into integration branches and merged when GitHub CI is green. | Sonnet implementers; merges only through a checked merge script | Planned here; earlier rounds ran by hand | | 7 | Fix issues | Issues with a clear bug and a clear fix get a PR from us. | Sonnet implementers | Planned | Stages 5–7 go one or a few repos at a time, in turn. Stages 1–4 cover the whole org. +### Label stage commands + +- `craft-auto labels ensure --repo R [--apply]` creates the missing labels of the set (bugfix, performance, missing feature, small extra, plugin candidate, infra, security, needs decision) with colour and description. Without `--apply` it prints what it would create. +- `craft-auto labels plan --repo R [--run RUN] [--csv FILE|-]` prints counts (to add, already labelled, unsettled, conflicts) and writes a CSV of the labels per open item. +- `craft-auto labels apply --repo R --run RUN [--limit N] [--apply]` adds the planned labels in batches of 10 mutations, at most 60 writes a minute, waiting out rate limits. It writes a `labeled` stage row per item and one audit row per batch, and a re-run skips items already labelled. Without `--apply` it is a dry run. With `--apply` it refuses unless an operator approved the repo. + +Approval: the Repos page has a Label approval column with a confirm button, operators only, audited (`labels-approve`, `labels-revoke`). The CLI reads the approval and cannot set it. The column also shows the plan counts: to add, skipped, conflicts. + ## Which model does what | Model | Used for | Why | diff --git a/src/classify/settled.ts b/src/classify/settled.ts new file mode 100644 index 000000000..0f0b4a3b0 --- /dev/null +++ b/src/classify/settled.ts @@ -0,0 +1,139 @@ +// The settled type label of an item for one classification run. Jev judges +// every item; Haiku gives a second opinion on the items Jev is unsure about. +// +// - Jev's top probability >= SURE: Jev's label is settled. +// - Otherwise, Haiku agrees with Jev: settled with that label. +// - Otherwise unsettled: "waiting" while Haiku hasn't answered, "disagree" when +// it gave another label. +// - No Jev verdict in the run: "unclassified". +// +// settle() is the rule; settledOf() applies it to one item and settledTable() +// to a whole run for queries. +import type { DatabaseSync } from "node:sqlite"; + +export const SURE = 0.9; + +export type SettledStatus = "settled" | "waiting" | "disagree" | "unclassified"; + +export type Verdict = { label: string; flags: string[] }; + +export type Settled = { + status: SettledStatus; + label: string | null; // set only when status is "settled" + source: "jev" | "haiku" | null; + confidence: number | null; // Jev's top probability + jevLabel: string | null; + haikuLabel: string | null; + // Jev's flags when Jev is sure; otherwise every flag either classifier raised. + flags: string[]; +}; + +export function settle(jev: (Verdict & { top: number | null }) | null, haiku: Verdict | null): Settled { + if (!jev) return { status: "unclassified", label: null, source: null, confidence: null, jevLabel: null, haikuLabel: haiku?.label ?? null, flags: [] }; + const base = { confidence: jev.top, jevLabel: jev.label, haikuLabel: haiku?.label ?? null }; + if ((jev.top ?? 0) >= SURE) return { ...base, status: "settled", label: jev.label, source: "jev", flags: [...jev.flags] }; + const flags = [...new Set([...jev.flags, ...(haiku?.flags ?? [])])]; + if (!haiku) return { ...base, status: "waiting", label: null, source: null, flags }; + if (haiku.label === jev.label) return { ...base, status: "settled", label: jev.label, source: "haiku", flags }; + return { ...base, status: "disagree", label: null, source: null, flags }; +} + +// The run the dashboard shows: the one with the newest Jev verdict. +export function latestRun(db: DatabaseSync): string | null { + const r = db.prepare("SELECT run_id FROM classifications WHERE classifier = 'jev' ORDER BY at DESC LIMIT 1").get() as { run_id: string } | undefined; + return r?.run_id ?? null; +} + +const parseFlags = (s: string | null): string[] => { + try { + const f = JSON.parse(s ?? "[]") as unknown; + return Array.isArray(f) ? f.filter((x): x is string => typeof x === "string") : []; + } catch { return []; } +}; + +export function settledOf(db: DatabaseSync, repo: string, number: number, run = latestRun(db)): Settled { + if (!run) return settle(null, null); + const q = db.prepare("SELECT type_label, flags, probs FROM classifications WHERE repo = ? AND number = ? AND classifier = ? AND run_id = ?"); + const j = q.get(repo, number, "jev", run) as { type_label: string; flags: string | null; probs: string | null } | undefined; + const h = q.get(repo, number, "haiku", run) as { type_label: string; flags: string | null } | undefined; + return settle( + j ? { label: j.type_label, flags: parseFlags(j.flags), top: topOf(j.probs) } : null, + h ? { label: h.type_label, flags: parseFlags(h.flags) } : null, + ); +} + +function topOf(probs: string | null): number | null { + try { + const t = (JSON.parse(probs ?? "null") as { top?: unknown } | null)?.top; + return typeof t === "number" ? t : null; + } catch { return null; } +} + +// Settled verdicts of one run as a temp table on this connection, for queries +// that count or filter many items: +// temp.item_settled(repo, number, status, label, source, top, jev_label, haiku_label, flags JSON, security, needs_decision) +// Items without a Jev verdict have no row ("unclassified"). Classifiers only +// insert (INSERT OR REPLACE gives a new rowid), so verdicts with a rowid above +// the last one seen are applied item by item; a new run or fewer rows than +// expected rebuilds the table. +type Seen = { run: string | null; maxRowid: number; count: number }; +const seen = new WeakMap(); + +type VerdictRow = { repo: string; number: number; jl: string; jf: string | null; probs: string | null; hl: string | null; hf: string | null }; +const VERDICTS = `SELECT j.repo, j.number, j.type_label AS jl, j.flags AS jf, j.probs, h.type_label AS hl, h.flags AS hf + FROM main.classifications j + LEFT JOIN main.classifications h ON h.repo = j.repo AND h.number = j.number AND h.classifier = 'haiku' AND h.run_id = j.run_id + WHERE j.run_id = :run AND j.classifier = 'jev'`; + +export function settledTable(db: DatabaseSync, run: string | null): void { + const now = db.prepare("SELECT COALESCE(MAX(rowid), 0) AS maxRowid, COUNT(*) AS count FROM main.classifications").get() as { maxRowid: number; count: number }; + const prev = seen.get(db); + if (prev && prev.run === run && prev.maxRowid === now.maxRowid && prev.count === now.count) return; + db.exec(`CREATE TEMP TABLE IF NOT EXISTS item_settled (repo TEXT NOT NULL, number INTEGER NOT NULL, status TEXT NOT NULL, label TEXT, + source TEXT, top REAL, jev_label TEXT, haiku_label TEXT, flags TEXT NOT NULL, security INTEGER NOT NULL, needs_decision INTEGER NOT NULL, + PRIMARY KEY (repo, number))`); + const ins = db.prepare("INSERT OR REPLACE INTO temp.item_settled VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"); + const put = (r: VerdictRow) => { + const s = settle({ label: r.jl, flags: parseFlags(r.jf), top: topOf(r.probs) }, r.hl === null ? null : { label: r.hl, flags: parseFlags(r.hf) }); + ins.run(r.repo, r.number, s.status, s.label, s.source, s.confidence, s.jevLabel, s.haikuLabel, JSON.stringify(s.flags), + s.flags.includes("security") ? 1 : 0, s.flags.includes("needs decision") ? 1 : 0); + }; + db.exec("BEGIN"); + try { + const fresh = prev && prev.run === run + ? (db.prepare("SELECT DISTINCT repo, number FROM main.classifications WHERE rowid > ? AND run_id = ?").all(prev.maxRowid, run) as { repo: string; number: number }[]) + : null; + const added = prev ? (db.prepare("SELECT COUNT(*) AS n FROM main.classifications WHERE rowid > ?").get(prev.maxRowid) as { n: number }).n : 0; + // INSERT OR REPLACE removes one row for each it adds, so the count only falls when something was deleted. + if (fresh && run && now.count >= prev!.count && now.count <= prev!.count + added) { + const one = db.prepare(`${VERDICTS} AND j.repo = :repo AND j.number = :number`); + for (const k of fresh) { + const r = one.get({ run, repo: k.repo, number: k.number }) as VerdictRow | undefined; + if (r) put(r); + else db.prepare("DELETE FROM temp.item_settled WHERE repo = ? AND number = ?").run(k.repo, k.number); + } + } else { + db.exec("DELETE FROM temp.item_settled"); + if (run) for (const r of db.prepare(VERDICTS).all({ run }) as VerdictRow[]) put(r); + } + db.exec("COMMIT"); + } catch (e) { + db.exec("ROLLBACK"); + throw e; + } + seen.set(db, { run, ...now }); +} + +export type SettledRow = { + status: string | null; label: string | null; source: string | null; + top: number | null; jev_label: string | null; haiku_label: string | null; flags: string | null; +}; + +// A temp.item_settled row (or none) as the wire shape. +export function fromRow(r: Partial | undefined): Settled { + if (!r?.status) return settle(null, null); + return { + status: r.status as SettledStatus, label: r.label ?? null, source: (r.source as Settled["source"]) ?? null, + confidence: r.top ?? null, jevLabel: r.jev_label ?? null, haikuLabel: r.haiku_label ?? null, flags: parseFlags(r.flags ?? null), + }; +} diff --git a/src/cli.ts b/src/cli.ts index 9b30cf59a..d178007c2 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -3,7 +3,7 @@ type Command = { summary: string; run: (args: string[]) => Promise | void }; type Module = { commands: Record }; -const MODULES = ["./mirror.ts", "./whitelist.ts", "./decisions.ts", "./access.ts", "./repos.ts", "./classify/index.ts", "./decide/index.ts", "./dash/index.ts"]; +const MODULES = ["./mirror.ts", "./whitelist.ts", "./decisions.ts", "./access.ts", "./repos.ts", "./classify/index.ts", "./labels/index.ts", "./decide/index.ts", "./dash/index.ts"]; async function main(): Promise { const commands: Record = {}; diff --git a/src/dash/api/admin.ts b/src/dash/api/admin.ts index 54179b23a..05a93b551 100644 --- a/src/dash/api/admin.ts +++ b/src/dash/api/admin.ts @@ -4,9 +4,11 @@ // already checked the Origin, the CSRF header and the body size on POSTs. import type { DatabaseSync } from "node:sqlite"; import type { - AccessOverview, AuditEntry, AuditPage, Contributor, ContributorList, ContributorSort, RulePreview, Tier, TrackedRepo, WhitelistRule, + AccessOverview, AuditEntry, AuditPage, Contributor, ContributorList, ContributorSort, RulePreview, RepoLabels, Tier, TrackedRepo, WhitelistRule, } from "../../../web/src/api/types.ts"; import { AccessError, addLogin, isRole, listAccess, removeLogin, ROLES, setRole } from "../../access.ts"; +import { approvalOf, setApproval } from "../../labels/approval.ts"; +import { countPlan, planLabels } from "../../labels/plan.ts"; import { listAll, RepoError, trackRepo, untrackRepo } from "../../repos.ts"; import { contributors, getRule, setOverride, setRule, tierOf, type Contributor as Row, type Rule } from "../../whitelist.ts"; import { audit } from "../audit.ts"; @@ -18,7 +20,7 @@ const ACCESS_NOTE_MAX = 500; const AUDIT_PAGE = 50; export const AUDIT_ACTIONS = [ "answer", "undo", "adopt", "opinion", "opinion-retract", "comment", "override", "rule", "access-add", "access-remove", "access-role", - "session-revoke", "sign-in", "sign-in-refused", "repo-track", "repo-untrack", + "session-revoke", "sign-in", "sign-in-refused", "repo-track", "repo-untrack", "labels-approve", "labels-revoke", "labels-apply", ]; const isOperator = (req: Req): boolean => req.user.role === "operator"; @@ -183,9 +185,31 @@ export function allRepos(db: DatabaseSync, req: Req): TrackedRepo[] { requireOperator(req, "manage tracked repos"); return listAll(db).map((r) => ({ name: r.name, tracked: !!r.tracked, openPrs: r.open_prs, openIssues: r.open_issues, mirrored: r.rows, syncedAt: r.synced_at, + labels: r.tracked ? labelsInfo(db, r.name) : null, })); } +function labelsInfo(db: DatabaseSync, repo: string): RepoLabels { + const a = approvalOf(db, repo); + const c = countPlan(planLabels(db, repo)); + return { approved: !!a, approvedBy: a?.by ?? null, approvedAt: a?.at ?? null, toAdd: c.toAdd, skipped: c.already + c.unsettled, conflicts: c.conflicts }; +} + +// Only an operator lets the Label stage write to a repo on GitHub. +export function labelsApproval(db: DatabaseSync, req: Req, approved: boolean): TrackedRepo[] { + requireOperator(req, "approve labelling"); + const name = required(body(req).name, "name"); + const changed = refused(() => { + try { + return setApproval(db, req.user.login, name, approved); + } catch (e) { + throw new RepoError((e as Error).message); + } + }); + if (!changed) throw new HttpError(409, `${name} is ${approved ? "already" : "not"} approved for labelling`); + return allRepos(db, req); +} + export function track(db: DatabaseSync, req: Req, on: boolean): TrackedRepo[] { requireOperator(req, "manage tracked repos"); const name = required(body(req).name, "name"); diff --git a/src/dash/api/index.ts b/src/dash/api/index.ts index c5999743f..82cbe7465 100644 --- a/src/dash/api/index.ts +++ b/src/dash/api/index.ts @@ -4,17 +4,19 @@ // permissions themselves. Item and comment text is returned as data only. import type { DatabaseSync } from "node:sqlite"; import type { - CiState, Done, Funnel, Item, ItemComment, Mergeable, Progress, RepoProgress, SearchHit, Tier, User, + CiState, Done, Funnel, Item, ItemComment, Mergeable, Progress, RepoProgress, Tier, User, } from "../../../web/src/api/types.ts"; import { trackedNames } from "../../repos.ts"; import { contributors } from "../../whitelist.ts"; -import { doneByRepo, funnelByRepo, runStart, trend, type DoneRow, type FunnelRow } from "./stats.ts"; +import { doneByRepo, funnelByRepo, latestCte, trackingStart, trend, type DoneRow, type FunnelRow } from "./stats.ts"; import { HttpError, RateLimiter } from "../server/util.ts"; import type { Req, Res, Route } from "../types.ts"; import * as adm from "./admin.ts"; import * as dec from "./decisions.ts"; import * as insight from "./insight.ts"; import { prompts } from "./prompts.ts"; +import * as items from "./items.ts"; +import { settledOf } from "../../classify/settled.ts"; import { classificationsOf, itemState, relatedOf } from "./decisions.ts"; export type ApiOptions = { @@ -60,8 +62,8 @@ function trackedOnly(db: DatabaseSync, repo: string): void { type ItemRow = { repo: string; number: number; kind: string; state: string; title: string | null; body: string | null; author: string | null; - created_at: string | null; updated_at: string | null; labels: string | null; additions: number | null; deletions: number | null; - mergeable: string | null; ci_state: string | null; + created_at: string | null; updated_at: string | null; labels: string | null; additions: number | null; deletions: number | null; changed_files: number | null; + mergeable: string | null; ci_state: string | null; closed_at: string | null; merged_at: string | null; merged_by: string | null; }; function item(db: DatabaseSync, req: Req): Item { @@ -89,48 +91,24 @@ function item(db: DatabaseSync, req: Req): Item { title: it.title ?? "", body: it.body ?? "", state: itemState(it.state), author: it.author ?? "", tier: TIER[c?.tier ?? "not"] ?? "not", authorMerged: c?.merged ?? 0, authorClosedUnmerged: c?.closed ?? 0, additions: it.additions ?? 0, deletions: it.deletions ?? 0, + changedFiles: it.kind === "pr" ? it.changed_files : null, + // The mirror stores only the rollup state and the counts, not per-file or per-check rows. files: [], ciChecks: [], ci: it.kind === "pr" ? (CI[it.ci_state ?? ""] ?? "none") : "none", mergeable: MERGEABLE[it.mergeable ?? ""] ?? "unknown", labels, createdAt: it.created_at ?? "", updatedAt: it.updated_at ?? "", + closedAt: it.closed_at, mergedAt: it.merged_at, mergedBy: it.merged_by, related: relatedOf(db, repo, n), classifications: classificationsOf(db, repo, n), stages: stages.map((s) => ({ ...s, by: s.by ?? "" })), comments: comments.map((x) => ({ ...x, author: x.author ?? "", body: x.body ?? "" })), - decisionIds, + decisionIds, settled: settledOf(db, repo, n) as Item["settled"], }; } -const likeEscape = (s: string): string => s.replace(/[\\%_]/g, (c) => `\\${c}`); - -function search(db: DatabaseSync, req: Req): SearchHit[] { - const q = (req.query.get("q") ?? "").trim().slice(0, 200); - if (!q) return []; - const where: string[] = ["repo IN (SELECT name FROM main.tracked_repos)"]; - const params: Record = {}; - const ref = /^([A-Za-z0-9._-]+)?#(\d{1,9})$/.exec(q) ?? /^()(\d{1,9})$/.exec(q); - if (ref) { - if (ref[1]) { - where.push("repo LIKE :repo ESCAPE '\\'"); - params.repo = `${likeEscape(ref[1])}%`; - } - where.push("CAST(number AS TEXT) LIKE :num"); - params.num = `${ref[2]}%`; - } else { - q.split(/\s+/).slice(0, 8).forEach((w, i) => { - where.push(`title LIKE :w${i} ESCAPE '\\'`); - params[`w${i}`] = `%${likeEscape(w)}%`; - }); - } - const order = ref ? "length(CAST(number AS TEXT)), repo, number" : "state <> 'OPEN', updated_at DESC"; - const rows = db.prepare(`SELECT repo, number, kind, title, author, state FROM items WHERE ${where.join(" AND ")} ORDER BY ${order} LIMIT 20`).all(params) as - { repo: string; number: number; kind: string; title: string | null; author: string | null; state: string }[]; - return rows.map((r) => ({ repo: r.repo, number: r.number, kind: r.kind === "pr" ? "pr" : "issue", title: r.title ?? "", author: r.author ?? "", state: itemState(r.state) })); -} - // ---- progress ---------------------------------------------------------------- const toFunnel = (r: FunnelRow | undefined): Funnel => ({ - open: r?.open ?? 0, classified: r?.classified ?? 0, reviewed: r?.reviewed ?? 0, take: r?.take ?? 0, + open: r?.open ?? 0, classified: r?.classified ?? 0, secondOpinion: r?.second_opinion ?? 0, disagreement: r?.disagreement ?? 0, reviewed: r?.reviewed ?? 0, take: r?.take ?? 0, hold: r?.hold ?? 0, close: r?.close ?? 0, waiting: r?.needs_decision ?? 0, batched: r?.batched ?? 0, }); const toDone = (r: DoneRow | undefined): Done => ({ @@ -142,11 +120,56 @@ const sum = (xs: T[], zero: T): T => { return out as T; }; -function progress(db: DatabaseSync): Progress { - const start = runStart(db); +type Heavy = Omit; +const progressCache = new WeakMap(); +const PROGRESS_MAX_AGE = 60_000; + +// The item-based part of Progress: scans most of the mirror, so it is kept until +// the mirror, the stages or the tracked repos change, or for a minute at most +// (classifier verdicts and the hourly counts show within that minute). +function progressItems(db: DatabaseSync): Heavy { + const sig = db.prepare(`SELECT (SELECT MAX(synced_at) FROM main.repos) AS synced, + (SELECT value FROM main.settings WHERE key = 'org_high_water') AS hw, + (SELECT COUNT(*) || ':' || COALESCE(MAX(rowid), 0) FROM main.stages) AS st, + (SELECT group_concat(name) FROM main.tracked_repos) AS tr`).get() as Record; + const key = JSON.stringify(sig); + const hit = progressCache.get(db); + if (hit && hit.key === key && Date.now() - hit.at < PROGRESS_MAX_AGE) return hit.value; + + const start = trackingStart(db); const now = Date.now(); const funnels = new Map(funnelByRepo(db).map((r) => [r.repo, r])); const done = new Map(doneByRepo(db, start).map((r) => [r.repo, r])); + const perHour = new Array(24).fill(0); + const perHourPipeline = new Array(24).fill(0); + const since = now - 24 * 3600_000; + for (const r of db.prepare(`WITH ${latestCte()} SELECT i.closed_at, l.stage IN ('merged', 'closed', 'fixed-by-us') AS ours + FROM items i LEFT JOIN latest l ON l.repo = i.repo AND l.number = i.number + WHERE i.closed_at >= ? AND i.state <> 'OPEN'`).all(new Date(since).toISOString()) as { closed_at: string; ours: number | null }[]) { + const h = Math.floor((Date.parse(r.closed_at) - since) / 3600_000); + if (h >= 0 && h < 24) { + perHour[h]!++; + if (r.ours) perHourPipeline[h]!++; + } + } + const names = [...new Set([...trackedNames(db), ...funnels.keys(), ...done.keys()])].sort(); + const { series } = trend(db, start, new Map(names.map((n) => [n, funnels.get(n)?.open ?? 0]))); + const repos: RepoProgress[] = names.map((repo) => ({ + repo, funnel: toFunnel(funnels.get(repo)), done: toDone(done.get(repo)), + decisionsOpen: 0, openTrend: series.get(repo)!, + })); + const value: Heavy = { + trackingSince: start, now: new Date(now).toISOString(), + funnel: sum(repos.map((r) => r.funnel), toFunnel(undefined)), + done: sum(repos.map((r) => r.done), toDone(undefined)), + perHour, perHourPipeline, repos, + }; + progressCache.set(db, { key, at: now, value }); + return value; +} + +function progress(db: DatabaseSync): Progress { + const heavy = progressItems(db); const openDec = new Map(); let decisionsOpen = 0; for (const r of db.prepare("SELECT repo, number, items FROM decisions WHERE answer IS NULL").all() as { repo: string | null; number: number | null; items: string | null }[]) { @@ -159,25 +182,12 @@ function progress(db: DatabaseSync): Progress { } for (const x of repos) openDec.set(x, (openDec.get(x) ?? 0) + 1); } - const today = new Date(now).toISOString().slice(0, 10); + const today = new Date().toISOString().slice(0, 10); const answeredToday = (db.prepare("SELECT COUNT(*) AS n FROM decisions WHERE answered_at >= ?").get(`${today}T00:00:00`) as { n: number }).n; - const perHour = new Array(24).fill(0); - const since = now - 24 * 3600_000; - for (const r of db.prepare("SELECT closed_at FROM items WHERE closed_at >= ? AND state <> 'OPEN'").all(new Date(since).toISOString()) as { closed_at: string }[]) { - const h = Math.floor((Date.parse(r.closed_at) - since) / 3600_000); - if (h >= 0 && h < 24) perHour[h]!++; - } - const { series } = trend(db, start, new Map([...funnels].map(([k, v]) => [k, v.open]))); - const names = [...new Set([...trackedNames(db), ...funnels.keys(), ...done.keys()])].sort(); - const repos: RepoProgress[] = names.map((repo) => ({ - repo, funnel: toFunnel(funnels.get(repo)), done: toDone(done.get(repo)), - decisionsOpen: openDec.get(repo) ?? 0, openTrend: series.get(repo) ?? [], - })); return { - runStartedAt: start, now: new Date(now).toISOString(), - funnel: sum(repos.map((r) => r.funnel), toFunnel(undefined)), - done: sum(repos.map((r) => r.done), toDone(undefined)), - perHour, decisionsOpen, decisionsAnsweredToday: answeredToday, repos, + ...heavy, + repos: heavy.repos.map((r) => ({ ...r, decisionsOpen: openDec.get(r.repo) ?? 0 })), + decisionsOpen, decisionsAnsweredToday: answeredToday, }; } @@ -201,7 +211,8 @@ export function apiRoutes(opts: ApiOptions = {}): Route[] { post("/api/decisions/:id/comments", (db, req) => dec.comment(db, req, limiter)), post("/api/decisions/:id/claim", dec.claim), get("/api/items/:repo/:n", item), - get("/api/search", search), + get("/api/items", items.listItems), + get("/api/search", items.quickSearch), get("/api/progress", progress), get("/api/contributors", adm.listContributors), get("/api/contributors/rule-preview", adm.previewRule), @@ -210,6 +221,8 @@ export function apiRoutes(opts: ApiOptions = {}): Route[] { get("/api/repos/all", adm.allRepos), post("/api/repos/track", (db, req) => adm.track(db, req, true)), post("/api/repos/untrack", (db, req) => adm.track(db, req, false)), + post("/api/repos/labels-approve", (db, req) => adm.labelsApproval(db, req, true)), + post("/api/repos/labels-revoke", (db, req) => adm.labelsApproval(db, req, false)), get("/api/access", adm.accessOverview), post("/api/access/add", adm.accessAdd), post("/api/access/remove", adm.accessRemove), diff --git a/src/dash/api/insight.ts b/src/dash/api/insight.ts index c41c790f2..a634dd069 100644 --- a/src/dash/api/insight.ts +++ b/src/dash/api/insight.ts @@ -148,6 +148,7 @@ export function cost(db: DatabaseSync, req: Req): CostReport { runs: db.prepare(`SELECT run_id AS id, MIN(started_at) AS "from", MAX(COALESCE(ended_at, started_at)) AS "to" FROM token_usage GROUP BY run_id ORDER BY MAX(COALESCE(ended_at, started_at)) DESC`).all() as CostReport["runs"], run, total: { ...(total as object) } as UsageTotals, + itemsClassified: (db.prepare(`SELECT COUNT(*) AS n FROM (SELECT DISTINCT repo, number FROM classifications WHERE ${flt})`).get(p) as { n: number }).n, stages: q(`SELECT COALESCE(stage, '') AS stage, COALESCE(model, '') AS model, ${TOTALS} FROM token_usage WHERE ${flt} GROUP BY stage, model ORDER BY stage, model`), repos: q(`SELECT repo, ${TOTALS} FROM token_usage WHERE ${flt} AND repo IS NOT NULL GROUP BY repo ORDER BY COALESCE(SUM(COALESCE(input_tokens, 0) + COALESCE(output_tokens, 0) + COALESCE(cache_read_tokens, 0) + COALESCE(cache_write_tokens, 0)), 0) DESC`), series: q(`SELECT substr(COALESCE(ended_at, started_at), 1, ${len}) AS bucket, diff --git a/src/dash/api/items.ts b/src/dash/api/items.ts new file mode 100644 index 000000000..1b8fdcdc0 --- /dev/null +++ b/src/dash/api/items.ts @@ -0,0 +1,283 @@ +// The Items browser (`GET /api/items`) and the top-bar search (`GET /api/search`), +// both over the full-text tables items_fts and comments_fts (src/schema.sql). +import type { DatabaseSync, SQLInputValue } from "node:sqlite"; +import type { + ItemList, ItemListRow, ItemSort, SearchHit, SettledStatus, Snippet, Stage, +} from "../../../web/src/api/types.ts"; +import { fromRow, latestRun, settledTable, type SettledRow } from "../../classify/settled.ts"; +import { LABELS } from "../../classify/rules.ts"; +import { HttpError } from "../server/util.ts"; +import type { Req } from "../types.ts"; +import { itemState } from "./decisions.ts"; +import { latestCte } from "./stats.ts"; + +const HAS_WORD = /[\p{L}\p{N}]/u; +const quote = (s: string) => `"${s.replace(/"/g, "")}"`; + +/** + * Turns what a person types into an FTS5 query, or null when nothing is left + * to search for. Words must all match; "quoted text" is a phrase; a trailing * + * matches a prefix; -word excludes; OR between terms means either. Every term + * is quoted, so FTS5 syntax characters in the input are never operators. + * `prefixLast` makes the last word a prefix (for search-as-you-type). + */ +export function ftsQuery(input: string, prefixLast = false): string | null { + const pos: string[] = []; + const neg: string[] = []; + const re = /(-?)"([^"]*)"?|(\S+)/g; + const raw = input.slice(0, 300); + for (let m = re.exec(raw); m; m = re.exec(raw)) { + if (m[2] !== undefined) { + if (HAS_WORD.test(m[2])) (m[1] ? neg : pos).push(quote(m[2])); + continue; + } + let w = m[3]!; + if (w === "OR") { + if (pos.length && pos[pos.length - 1] !== "OR") pos.push("OR"); + continue; + } + const isNeg = w.startsWith("-") && w.length > 1; + if (isNeg) w = w.slice(1); + const atEnd = m.index + m[0].length === raw.length && !/\s$/.test(raw); + // a prefix of one or two letters would expand to most of the index + const prefix = w.endsWith("*") || (prefixLast && atEnd && !isNeg && w.length >= 3); + w = w.replace(/\*+$/, ""); + if (!HAS_WORD.test(w)) continue; + (isNeg ? neg : pos).push(quote(w) + (prefix ? "*" : "")); + if (pos.length + neg.length >= 16) break; + } + while (pos[pos.length - 1] === "OR") pos.pop(); + if (!pos.length) return null; + return [`(${pos.join(" ")})`, ...neg.map((n) => `NOT ${n}`)].join(" "); +} + +// Items matching the query bound as :q in their title, body or any comment. +const HIT_IDS = `hits AS ( + SELECT rowid AS rid FROM items_fts WHERE items_fts MATCH :q + UNION + SELECT it.rowid FROM comments_fts + JOIN main.comments c ON c.rowid = comments_fts.rowid + JOIN main.items it ON it.repo = c.repo AND it.number = c.number + WHERE comments_fts MATCH :q)`; + +// The same with the best bm25 score (lower is better): a title match weighs most, +// a comment match half as much as one in the body. +const HITS_SCORED = `hits AS ( + SELECT rid, MIN(score) AS score FROM ( + SELECT rowid AS rid, bm25(items_fts, 10.0, 1.0) AS score FROM items_fts WHERE items_fts MATCH :q + UNION ALL + SELECT it.rowid, bm25(comments_fts) * 0.5 FROM comments_fts + JOIN main.comments c ON c.rowid = comments_fts.rowid + JOIN main.items it ON it.repo = c.repo AND it.number = c.number + WHERE comments_fts MATCH :q) + GROUP BY rid)`; + +const STATUSES: SettledStatus[] = ["settled", "waiting", "disagree", "unclassified"]; +const STATES: Record = { open: "OPEN", closed: "CLOSED", merged: "MERGED" }; +const SORTS: ItemSort[] = ["relevance", "updated", "created", "number"]; +const FLAGS = ["security", "needs decision"]; + +const list = (req: Req, key: string): string[] => + req.query.getAll(key).flatMap((v) => v.split(",")).map((s) => s.trim()).filter(Boolean); + +type Built = { where: string[]; statusWhere: string | null; statuses: SettledStatus[]; params: Record; text: boolean }; + +function build(db: DatabaseSync, req: Req): Built & { sort: ItemSort; desc: boolean; run: string | null } { + const q = req.query; + const mode = q.get("mode") ?? "text"; + if (mode !== "text") throw new HttpError(400, "mode must be text"); + const run = q.get("run") || latestRun(db); + settledTable(db, run); + const params: Record = {}; + const where: string[] = []; + const fts = ftsQuery(q.get("q") ?? ""); + if (fts) params.q = fts; + const repos = list(req, "repo"); + if (repos.length) { + where.push(`i.repo IN (${repos.map((_, k) => `:repo${k}`).join(",")})`); + repos.forEach((r, k) => (params[`repo${k}`] = r)); + } + const kind = q.get("kind"); + if (kind) { + if (kind !== "pr" && kind !== "issue") throw new HttpError(400, "kind must be pr or issue"); + where.push("i.kind = :kind"); + params.kind = kind; + } + const state = q.get("state") ?? "open"; + if (state !== "all") { + if (!STATES[state]) throw new HttpError(400, "state must be open, closed, merged or all"); + where.push("i.state = :state"); + params.state = STATES[state]!; + } + const label = q.get("label"); + if (label) { + if (!(LABELS as readonly string[]).includes(label)) throw new HttpError(400, "unknown label"); + where.push("s.label = :label"); + params.label = label; + } + list(req, "flag").forEach((f) => { + if (!FLAGS.includes(f)) throw new HttpError(400, "flag must be security or needs decision"); + where.push(f === "security" ? "s.security = 1" : "s.needs_decision = 1"); + }); + const author = q.get("author")?.trim(); + if (author) { + where.push("i.author = :author COLLATE NOCASE"); // index items_author_nocase + params.author = author; + } + const since = q.get("since"); + if (since) { + if (!/^\d{4}-\d{2}-\d{2}$/.test(since)) throw new HttpError(400, "since must be YYYY-MM-DD"); + where.push("i.updated_at >= :since"); + params.since = since; + } + let statusWhere: string | null = null; + const st = new Set(list(req, "status").flatMap((s) => (s === "unsettled" ? ["waiting", "disagree"] : [s]))); + if (st.size) { + for (const s of st) if (!STATUSES.includes(s as SettledStatus)) throw new HttpError(400, "status must be settled, waiting, disagree, unsettled or unclassified"); + const named = [...st].filter((s) => s !== "unclassified").map((s) => `'${s}'`); + const parts = [...(named.length ? [`s.status IN (${named.join(",")})`] : []), ...(st.has("unclassified") ? ["s.status IS NULL"] : [])]; + statusWhere = `(${parts.join(" OR ")})`; + } + const sortQ = q.get("sort") as ItemSort | null; + if (sortQ && !SORTS.includes(sortQ)) throw new HttpError(400, "sort must be relevance, updated, created or number"); + let sort: ItemSort = sortQ ?? (fts ? "relevance" : "updated"); + if (sort === "relevance" && !fts) sort = "updated"; + const desc = q.get("desc") !== "0"; + return { where, statusWhere, statuses: [...st] as SettledStatus[], params, text: !!fts, sort, desc, run }; +} + +const ORDER: Record = { + relevance: "h.score", updated: "i.updated_at", created: "i.created_at", number: "i.number", +}; + +type Row = SettledRow & { + rid: number; repo: string; number: number; kind: string; state: string; title: string | null; author: string | null; + created_at: string | null; updated_at: string | null; comments_count: number | null; +}; + +const OPEN = "\u0002", CLOSE = "\u0003"; + +function snippets(db: DatabaseSync, fts: string, rows: Row[]): Map { + const out = new Map(); + if (!rows.length) return out; + const ids = rows.map((r) => r.rid); + const inList = ids.map(() => "?").join(","); + const sn = (t: string, col: number) => `snippet(${t}, ${col}, '${OPEN}', '${CLOSE}', '…', 24)`; + const own = db.prepare(`SELECT rowid AS rid, ${sn("items_fts", 0)} AS t, ${sn("items_fts", 1)} AS b + FROM items_fts WHERE items_fts MATCH ? AND rowid IN (${inList})`).all(fts, ...ids) as { rid: number; t: string | null; b: string | null }[]; + for (const r of own) { + if (r.b?.includes(OPEN)) out.set(r.rid, { field: "body", author: null, text: r.b }); + else if (r.t?.includes(OPEN)) out.set(r.rid, { field: "title", author: null, text: r.t }); + } + const rest = rows.filter((r) => !out.has(r.rid)); + if (!rest.length) return out; + const pairs = rest.map(() => "(?, ?)").join(","); + const cm = db.prepare(`SELECT c.repo, c.number, c.author, ${sn("comments_fts", 0)} AS t FROM comments_fts + JOIN main.comments c ON c.rowid = comments_fts.rowid + WHERE comments_fts MATCH ? AND (c.repo, c.number) IN (VALUES ${pairs}) ORDER BY rank`) + .all(fts, ...rest.flatMap((r) => [r.repo, r.number])) as { repo: string; number: number; author: string | null; t: string }[]; + const byRef = new Map(rest.map((r) => [`${r.repo}#${r.number}`, r.rid])); + for (const c of cm) { + const rid = byRef.get(`${c.repo}#${c.number}`); + if (rid !== undefined && !out.has(rid)) out.set(rid, { field: "comment", author: c.author, text: c.t }); + } + return out; +} + +export function listItems(db: DatabaseSync, req: Req): ItemList { + const b = build(db, req); + const limit = Math.min(100, Math.max(1, Number(req.query.get("limit")) || 50)); + const offset = Math.max(0, Number(req.query.get("offset")) || 0); + const from = (scored: boolean) => (b.text + ? `WITH ${scored ? HITS_SCORED : HIT_IDS} SELECT %COLS FROM hits h JOIN items i ON i.rowid = h.rid` + : "SELECT %COLS FROM items i") + " LEFT JOIN temp.item_settled s ON s.repo = i.repo AND s.number = i.number"; + const whereSql = (w: string[]) => (w.length ? ` WHERE ${w.join(" AND ")}` : ""); + + // Counts per status under every filter but the status one; the total follows from them. + const counts = db.prepare(from(false).replace("%COLS", "s.status, COUNT(*) AS n") + whereSql(b.where) + " GROUP BY 1") + .all(b.params) as { status: string | null; n: number }[]; + const byStatus = Object.fromEntries(STATUSES.map((s) => [s, 0])) as Record; + for (const c of counts) byStatus[(c.status ?? "unclassified") as SettledStatus] += c.n; + const total = (b.statuses.length ? b.statuses : STATUSES).reduce((a, s) => a + byStatus[s], 0); + + // The page as rowids first, so only its rows are read in full. + const where = [...b.where, ...(b.statusWhere ? [b.statusWhere] : [])]; + // bm25 is lower for better matches, so "most relevant first" sorts it ascending. + const order = b.sort === "relevance" ? `h.score ${b.desc ? "ASC" : "DESC"}` : `${ORDER[b.sort]} ${b.desc ? "DESC" : "ASC"}`; + const ids = (db.prepare(from(b.sort === "relevance").replace("%COLS", "i.rowid AS rid") + whereSql(where) + + ` ORDER BY ${order}, i.repo, i.number DESC LIMIT :limit OFFSET :offset`).all({ ...b.params, limit, offset }) as { rid: number }[]).map((r) => r.rid); + const byId = new Map((ids.length ? db.prepare(`SELECT i.rowid AS rid, i.repo, i.number, i.kind, i.state, i.title, i.author, + i.created_at, i.updated_at, i.comments_count, s.status, s.label, s.source, s.top, s.jev_label, s.haiku_label, s.flags + FROM items i LEFT JOIN temp.item_settled s ON s.repo = i.repo AND s.number = i.number WHERE i.rowid IN (${ids.map(() => "?").join(",")})`).all(...ids) as Row[] : []) + .map((r) => [r.rid, r])); + const rows = ids.map((id) => byId.get(id)).filter((r): r is Row => !!r); + + const stages = stagesOf(db, rows); + const snips = b.text ? snippets(db, b.params.q as string, rows) : new Map(); + return { + total, byStatus, run: b.run, + rows: rows.map((r): ItemListRow => ({ + repo: r.repo, number: r.number, kind: r.kind === "pr" ? "pr" : "issue", state: itemState(r.state), + title: r.title ?? "", author: r.author ?? "", createdAt: r.created_at ?? "", updatedAt: r.updated_at ?? "", + comments: r.comments_count ?? 0, settled: fromRow(r) as ItemListRow["settled"], + stage: (stages.get(`${r.repo}#${r.number}`) ?? null) as Stage | null, snippet: snips.get(r.rid) ?? null, + })), + }; +} + +// Latest stage of each listed item. +function stagesOf(db: DatabaseSync, rows: { repo: string; number: number }[]): Map { + const out = new Map(); + if (!rows.length) return out; + const pairs = rows.map(() => "(?, ?)").join(","); + const got = db.prepare(`WITH ${latestCte()} SELECT repo, number, stage FROM latest WHERE (repo, number) IN (VALUES ${pairs})`) + .all(...rows.flatMap((r) => [r.repo, r.number])) as { repo: string; number: number; stage: string }[]; + for (const g of got) out.set(`${g.repo}#${g.number}`, g.stage); + return out; +} + +const likeEscape = (s: string): string => s.replace(/[\\%_]/g, (c) => `\\${c}`); + +/** Top-bar search: `repo#n`, `#n` and bare numbers jump by number; a word may be an author's login; text goes through the full-text index. */ +type Hit = { repo: string; number: number; kind: string; title: string | null; author: string | null; state: string }; +const hitOf = (r: Hit): SearchHit => ({ repo: r.repo, number: r.number, kind: r.kind === "pr" ? "pr" : "issue", title: r.title ?? "", author: r.author ?? "", state: itemState(r.state) }); + +export function quickSearch(db: DatabaseSync, req: Req): SearchHit[] { + const q = (req.query.get("q") ?? "").trim().slice(0, 200); + if (!q) return []; + const ref = /^([A-Za-z0-9._-]+)?#(\d{1,9})$/.exec(q) ?? /^()(\d{1,9})$/.exec(q); + let rows: Hit[]; + if (ref) { + const where = ["CAST(number AS TEXT) LIKE :num"]; + const params: Record = { num: `${ref[2]}%` }; + if (ref[1]) { + where.push("repo LIKE :repo ESCAPE '\\'"); + params.repo = `${likeEscape(ref[1])}%`; + } + rows = db.prepare(`SELECT repo, number, kind, title, author, state FROM items WHERE ${where.join(" AND ")} + ORDER BY length(CAST(number AS TEXT)), repo, number LIMIT 20`).all(params) as Hit[]; + } else { + rows = []; + // A single word may be a login: that author's latest items first. + if (/^[A-Za-z0-9-]{2,39}$/.test(q)) { + // main.items with the index named: through the scoping view the planner picks the repo index. + rows = db.prepare(`SELECT repo, number, kind, title, author, state FROM main.items INDEXED BY items_author_nocase + WHERE author LIKE :p AND repo IN (SELECT name FROM main.tracked_repos) ORDER BY state <> 'OPEN', updated_at DESC LIMIT 5`).all({ p: `${q}%` }) as Hit[]; + } + const fts = ftsQuery(q, true); + if (!fts) return rows.map(hitOf); + const have = new Set(rows.map((r) => `${r.repo}#${r.number}`)); + // The newest 100 matches by title, then by body when titles give too few, open ones first. + // Ordered by rowid, which FTS5 stops early on; ranking every match is too slow for common words. + const look = db.prepare(`WITH hits AS (SELECT rowid AS rid FROM items_fts WHERE items_fts MATCH :q ORDER BY rowid DESC LIMIT 100) + SELECT i.repo, i.number, i.kind, i.title, i.author, i.state + FROM hits h JOIN items i ON i.rowid = h.rid ORDER BY i.state <> 'OPEN', i.updated_at DESC LIMIT 20`); + let text = look.all({ q: `title : ${fts}` }) as Hit[]; + if (text.length < 20) { + const seenT = new Set(text.map((r) => `${r.repo}#${r.number}`)); + text = [...text, ...(look.all({ q: fts }) as Hit[]).filter((r) => !seenT.has(`${r.repo}#${r.number}`))]; + } + rows = [...rows, ...text.filter((r) => !have.has(`${r.repo}#${r.number}`))].slice(0, 20); + } + return rows.map(hitOf); +} diff --git a/src/dash/api/stats.ts b/src/dash/api/stats.ts index 4201d096a..f9355b948 100644 --- a/src/dash/api/stats.ts +++ b/src/dash/api/stats.ts @@ -1,5 +1,6 @@ // Shared queries for the Progress, Repo and Run and cost pages. import type { DatabaseSync } from "node:sqlite"; +import { latestRun, settledTable } from "../../classify/settled.ts"; import { getRule, STATS_SQL, TIER_LABEL, TIER_SQL, type Tier } from "../../whitelist.ts"; // Latest stage row per item (latest wins; rowid breaks ties at the same time). @@ -13,36 +14,41 @@ export const latestCte = (repo?: string): string => LATEST_SQL.replace("%W", rep // One classification per item: the owner's, else Sonnet's, else Haiku's, else the newest other. export const PREF_ORDER = "CASE classifier WHEN 'owner' THEN 0 WHEN 'sonnet' THEN 1 WHEN 'haiku' THEN 2 ELSE 3 END, at DESC"; -export function runStart(db: DatabaseSync): string { - const r = db.prepare("SELECT value FROM settings WHERE key = 'run_started_at'").get() as { value: string } | undefined; - if (r?.value) return r.value; - const s = db.prepare("SELECT MIN(at) AS at FROM stages").get() as { at: string | null }; - return s.at ?? new Date(Date.now() - 7 * 86400_000).toISOString(); +// When tracking began: set by connect() (src/db.ts) on first use. +export function trackingStart(db: DatabaseSync): string { + const r = db.prepare("SELECT value FROM main.settings WHERE key = 'tracking_started_at'").get() as { value: string } | undefined; + return r?.value ?? new Date().toISOString(); } const p = (repo?: string, extra: Record = {}): Record => (repo ? { repo, ...extra } : extra); export type FunnelRow = { - repo: string; open: number; classified: number; reviewed: number; + repo: string; open: number; classified: number; second_opinion: number; disagreement: number; reviewed: number; take: number; hold: number; close: number; needs_decision: number; batched: number; }; +// "classified" counts settled type labels (src/classify/settled.ts) in the latest run. export function funnelByRepo(db: DatabaseSync, repo?: string): FunnelRow[] { + settledTable(db, latestRun(db)); return db.prepare(`WITH ${latestCte(repo)} SELECT i.repo, COUNT(*) AS open, - SUM(EXISTS (SELECT 1 FROM classifications c WHERE c.repo = i.repo AND c.number = i.number)) AS classified, + SUM(st.status = 'settled') AS classified, SUM(st.status = 'waiting') AS second_opinion, SUM(st.status = 'disagree') AS disagreement, SUM(EXISTS (SELECT 1 FROM stages s WHERE s.repo = i.repo AND s.number = i.number AND s.stage = 'reviewed') OR EXISTS (SELECT 1 FROM classifications c WHERE c.repo = i.repo AND c.number = i.number AND c.classifier = 'sonnet')) AS reviewed, SUM(l.stage = 'take') AS take, SUM(l.stage = 'hold') AS hold, SUM(l.stage = 'close') AS close, SUM(l.stage = 'needs-decision') AS needs_decision, SUM(l.stage = 'batched') AS batched FROM items i LEFT JOIN latest l ON l.repo = i.repo AND l.number = i.number + LEFT JOIN temp.item_settled st ON st.repo = i.repo AND st.number = i.number WHERE i.state = 'OPEN' ${repo ? "AND i.repo = :repo" : ""} - GROUP BY i.repo`).all(p(repo)).map((r) => ({ ...r, take: r.take ?? 0, hold: r.hold ?? 0, close: r.close ?? 0, needs_decision: r.needs_decision ?? 0, batched: r.batched ?? 0 })) as FunnelRow[]; + GROUP BY i.repo`).all(p(repo)).map((r) => ({ + ...r, classified: r.classified ?? 0, second_opinion: r.second_opinion ?? 0, disagreement: r.disagreement ?? 0, + take: r.take ?? 0, hold: r.hold ?? 0, close: r.close ?? 0, needs_decision: r.needs_decision ?? 0, batched: r.batched ?? 0, + })) as FunnelRow[]; } export type DoneRow = { repo: string; merged_pipeline: number; closed_pipeline: number; closed_others: number; total: number }; -// Done since run start. Merged PRs carry closed_at too, so one range covers both. +// Done since tracking began. Merged PRs carry closed_at too, so one range covers both. export function doneByRepo(db: DatabaseSync, start: string, repo?: string): DoneRow[] { return db.prepare(`WITH ${latestCte(repo)}, d AS ( SELECT i.repo, i.state, l.stage FROM items i LEFT JOIN latest l ON l.repo = i.repo AND l.number = i.number @@ -64,7 +70,7 @@ export const SIZE_SQL = `CASE WHEN kind = 'issue' THEN 'issue' export const SIZE_ORDER = ["S", "M", "L", "XL", "issue"]; -// Open items per repo per day since run start, rebuilt backwards from the +// Open items per repo per day since tracking began, rebuilt backwards from the // current open count and the created/closed dates. export function trend(db: DatabaseSync, start: string, openNow: Map, repo?: string): { days: string[]; series: Map } { const today = new Date().toISOString().slice(0, 10); @@ -86,6 +92,7 @@ export function trend(db: DatabaseSync, start: string, openNow: Map(); + // every repo in openNow gets a series, a repo with nothing open one of zeros for (const name of new Set([...openNow.keys(), ...delta.keys()])) { const m = delta.get(name) ?? new Map(); // value at the end of each day; walk back from today's open count diff --git a/src/dash/server/index.ts b/src/dash/server/index.ts index ace80e816..9bd6614a8 100644 --- a/src/dash/server/index.ts +++ b/src/dash/server/index.ts @@ -289,7 +289,7 @@ export function createApp(opts: AppOptions & { routes: Route[] }) { return { r: { redirect: "/auth/signed-out" }, cookies: [cookie(SESSION_COOKIE, "", 0)] }; } if (req.method === "GET" && path === "/auth/signed-out") { - return { r: { html: plainPage(nonce, "Signed out", `

Sign in again

`) } }; + return { r: { html: plainPage(nonce, "Signed out", `

You are signed out of the dashboard on this device.

Sign in again

`) } }; } if (req.method === "GET" && path === "/auth/dev/authorize" && provider instanceof FakeProvider) { const q = url.searchParams; diff --git a/src/dash/server/util.ts b/src/dash/server/util.ts index 883f1e56e..bacb8ff8a 100644 --- a/src/dash/server/util.ts +++ b/src/dash/server/util.ts @@ -12,18 +12,27 @@ export function esc(s: unknown): string { return String(s ?? "").replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`); } -// Minimal page for the server's own responses (sign-in, errors). Pages use -// their own layout. +// Minimal page for the server's own responses (sign-in, sign-out, errors), in +// the dashboard's colours. The inline script applies the theme the reader chose +// in the dashboard (stored by web/src/shell/theme.ts); without it the page +// follows the system setting. export function plainPage(nonce: string, title: string, body: string): string { return ` ${esc(title)} +

${esc(title)}

${body}`; +:root{color-scheme:dark;--bg:#101014;--card:#141518;--fg:#f2f1ee;--muted:#9a9aa0;--line:rgba(255,255,255,.1);--link:#74aaff;--accent:#2d81ff} +@media (prefers-color-scheme:light){:root:not([data-theme=dark]){color-scheme:light;--bg:#f2f1ee;--card:#fbfaf8;--fg:#101014;--muted:#5f5f66;--line:rgba(16,16,20,.12);--link:#1454dc;--accent:#1b63f5}} +:root[data-theme=light]{color-scheme:light;--bg:#f2f1ee;--card:#fbfaf8;--fg:#101014;--muted:#5f5f66;--line:rgba(16,16,20,.12);--link:#1454dc;--accent:#1b63f5} +body{background:var(--bg);color:var(--fg);font:15px/1.5 Inter,system-ui,sans-serif;margin:0;min-height:100vh;display:flex;align-items:flex-start;justify-content:center;padding:12vh 16px 2rem;box-sizing:border-box} +main{width:100%;max-width:26rem;background:var(--card);border:1px solid var(--line);border-radius:10px;padding:24px} +.brand{font-size:13px;font-weight:600;color:var(--muted);margin:0 0 12px} +h1{font-size:20px;line-height:1.3;margin:0 0 8px} +p{margin:8px 0}a{color:var(--link)}p.muted{color:var(--muted)}code{font-size:13px} +input,button,a.button{font:inherit;min-height:40px;padding:0 14px;border-radius:6px;box-sizing:border-box} +input{border:1px solid var(--line);background:var(--bg);color:var(--fg)} +button,a.button{display:inline-flex;align-items:center;border:0;background:var(--accent);color:#fff;text-decoration:none;font-weight:500;cursor:pointer} +

Craft Triage

${esc(title)}

${body}
`; } // Fixed-window counters, in memory: limits reset with the process, which is diff --git a/src/db.ts b/src/db.ts index ad70fecb5..09d9dcfdb 100644 --- a/src/db.ts +++ b/src/db.ts @@ -37,13 +37,38 @@ function migrateValues(db: DatabaseSync): void { db.exec("UPDATE main.access SET role = 'operator' WHERE role = 'admin'"); } +// Fills the full-text tables once, for a database that had items before they existed. +function buildSearchIndex(db: DatabaseSync): void { + if (db.prepare("SELECT 1 FROM main.settings WHERE key = 'fts_built'").get()) return; + db.exec("BEGIN IMMEDIATE"); + try { + if (!db.prepare("SELECT 1 FROM main.settings WHERE key = 'fts_built'").get()) { + db.exec("INSERT INTO main.items_fts (items_fts) VALUES ('rebuild')"); + db.exec("INSERT INTO main.comments_fts (comments_fts) VALUES ('rebuild')"); + // ORDER BY rank: a title match weighs ten times one in the body + db.exec("INSERT INTO main.items_fts (items_fts, rank) VALUES ('rank', 'bm25(10.0, 1.0)')"); + db.exec("INSERT INTO main.settings (key, value) VALUES ('fts_built', '1')"); + } + db.exec("COMMIT"); + } catch (e) { + db.exec("ROLLBACK"); + throw e; + } +} + export function connect(path: string = dbPath()): DatabaseSync { mkdirSync(dirname(path), { recursive: true }); const db = new DatabaseSync(path, { timeout: 30_000 }); // WAL so the dashboard can read while a sync writes db.exec("PRAGMA journal_mode=WAL"); + // INSERT OR REPLACE then runs delete triggers, which keep the full-text index right + db.exec("PRAGMA recursive_triggers=ON"); db.exec(readFileSync(new URL("./schema.sql", import.meta.url), "utf8")); addColumns(db); migrateValues(db); + buildSearchIndex(db); + // Progress counts from here: the first sync, or now for a new database. + db.exec(`INSERT OR IGNORE INTO main.settings (key, value) SELECT 'tracking_started_at', + COALESCE((SELECT MIN(synced_at) FROM main.repos), strftime('%Y-%m-%dT%H:%M:%SZ', 'now'))`); return db; } diff --git a/src/decide/decision.ts b/src/decide/decision.ts index 691d5a7ed..8cc71eb9a 100644 --- a/src/decide/decision.ts +++ b/src/decide/decision.ts @@ -37,7 +37,7 @@ export function shapeOf(c: Candidate): Shape { const pair = new Set([s.jevLabel, s.haikuLabel]); if (pair.has("small extra") && pair.has("plugin candidate")) // The classify rules say: unsure between the two, plugin candidate. - return { question: "Keep this in core as a small extra, or treat it as a plug-in?", options: ["small-extra", "plugin", "take", "close"], recommended: "plugin" }; + return { question: "Keep this in core as a small extra, or treat it as a plug-in?", options: ["small-extra", "plugin", "take", "need-info", "close"], recommended: "plugin" }; const other = OPTION_OF_LABEL[pair.has("small extra") ? "small extra" : "plugin candidate"]!; return { question: "Does the reference app have this, and do we want it in core?", options: ["take", other, "need-info", "close"], recommended: null }; } diff --git a/src/decide/select.ts b/src/decide/select.ts index f516c386c..d2297d99f 100644 --- a/src/decide/select.ts +++ b/src/decide/select.ts @@ -9,32 +9,13 @@ // decision on it (answered ones too), or a stage row past "classified". import type { DatabaseSync } from "node:sqlite"; import { trackedNames } from "../repos.ts"; +import { settle, type Settled } from "../classify/settled.ts"; export const SCOPE_LABELS = ["missing feature", "small extra", "plugin candidate"] as const; const isScope = (l: string | null): boolean => l !== null && (SCOPE_LABELS as readonly string[]).includes(l); -// ---- Settled classification ------------------------------------------------- -// LOCAL COPY of the rule in src/classify/settled.ts (`settle`, from the -// dash-items branch). Once that lands, delete this block and import `settle`, -// `SURE` and `Settled` from "../classify/settled.ts": the signature and result -// fields used here are the same. -export const SURE = 0.9; -type Verdict = { label: string; flags: string[] }; -export type Settled = { - status: "settled" | "waiting" | "disagree" | "unclassified"; - label: string | null; source: "jev" | "haiku" | null; confidence: number | null; - jevLabel: string | null; haikuLabel: string | null; flags: string[]; -}; -export function settle(jev: (Verdict & { top: number | null }) | null, haiku: Verdict | null): Settled { - if (!jev) return { status: "unclassified", label: null, source: null, confidence: null, jevLabel: null, haikuLabel: haiku?.label ?? null, flags: [] }; - const base = { confidence: jev.top, jevLabel: jev.label, haikuLabel: haiku?.label ?? null }; - if ((jev.top ?? 0) >= SURE) return { ...base, status: "settled", label: jev.label, source: "jev", flags: [...jev.flags] }; - const flags = [...new Set([...jev.flags, ...(haiku?.flags ?? [])])]; - if (!haiku) return { ...base, status: "waiting", label: null, source: null, flags }; - if (haiku.label === jev.label) return { ...base, status: "settled", label: jev.label, source: "haiku", flags }; - return { ...base, status: "disagree", label: null, source: null, flags }; -} -// ---- end of local copy ------------------------------------------------------- +/** Jev's needs_decision probability a bugfix needs before it becomes a decision. */ +export const BUGFIX_NEEDS_DECISION = 0.7; export type Reason = "needs-decision" | "scope-disagreement"; @@ -94,7 +75,12 @@ export function selectCandidates(db: DatabaseSync, run: string, repos?: string[] { label: r.jl, flags: json(r.jf, []), top: typeof top === "number" ? top : null }, r.hl === null ? null : { label: r.hl, flags: json(r.hf, []) }, ); - const reason = reasonOf(s); + let reason = reasonOf(s); + // Jev raises needs_decision too freely on plain bugs: a bugfix needs a firm flag. + if (reason === "needs-decision" && s.label === "bugfix") { + const nd = json<{ needs_decision?: unknown } | null>(r.probs, null)?.needs_decision; + if (typeof nd !== "number" || nd < BUGFIX_NEEDS_DECISION) reason = null; + } if (reason) out.push({ repo: r.repo, number: r.number, reason, settled: s }); } return out; diff --git a/src/decisions.ts b/src/decisions.ts index 3ab8659ed..aa88fd567 100644 --- a/src/decisions.ts +++ b/src/decisions.ts @@ -46,9 +46,9 @@ export function validateAsk(q: Record): Record 4 || + if (!Array.isArray(options) || options.length < 2 || options.length > 5 || !options.every((o) => typeof o?.key === "string" && typeof o?.label === "string" && (o.hint === undefined || typeof o.hint === "string"))) - throw err("options must be 2–4 {key, label, hint?}"); + throw err("options must be 2–5 {key, label, hint?}"); if (new Set(options.map((o) => o.key)).size !== options.length) throw err("option keys must be unique"); if (q.recommended != null && !options.some((o) => o.key === q.recommended)) throw err("recommended must be an option key"); const facts = (q.facts ?? []) as unknown[]; diff --git a/src/labels/approval.ts b/src/labels/approval.ts new file mode 100644 index 000000000..6ed78953c --- /dev/null +++ b/src/labels/approval.ts @@ -0,0 +1,31 @@ +// Per-repo approval to write labels to GitHub. Set only from the dashboard by an +// operator (src/dash/api/admin.ts); the CLI reads it and has no way to set it. +import type { DatabaseSync } from "node:sqlite"; +import { audit } from "../dash/audit.ts"; + +export type Approval = { by: string; at: string }; +const key = (repo: string) => `labels_approved:${repo}`; + +export function approvalOf(db: DatabaseSync, repo: string): Approval | null { + const row = db.prepare("SELECT value FROM main.settings WHERE key = ?").get(key(repo)) as { value: string } | undefined; + if (!row) return null; + try { + return JSON.parse(row.value) as Approval; + } catch { + return null; + } +} + +// Returns false when nothing changed. +export function setApproval(db: DatabaseSync, by: string, repo: string, approved: boolean): boolean { + if (!db.prepare("SELECT 1 FROM main.tracked_repos WHERE name = ?").get(repo)) throw new Error(`${repo} is not tracked`); + const had = approvalOf(db, repo) !== null; + if (had === approved) return false; + if (approved) { + db.prepare("INSERT INTO main.settings (key, value) VALUES (?, ?)").run(key(repo), JSON.stringify({ by, at: new Date().toISOString() })); + } else { + db.prepare("DELETE FROM main.settings WHERE key = ?").run(key(repo)); + } + audit(db, by, approved ? "labels-approve" : "labels-revoke", repo); + return true; +} diff --git a/src/labels/github.ts b/src/labels/github.ts new file mode 100644 index 000000000..4c4e8050f --- /dev/null +++ b/src/labels/github.ts @@ -0,0 +1,164 @@ +// GitHub side of the Label stage: ensure the label set exists, add labels to items. +// Every call goes through the mirror's Querier (gh api graphql, rate-limit aware). +import { setTimeout as sleepMs } from "node:timers/promises"; +import type { DatabaseSync } from "node:sqlite"; +import { audit } from "../dash/audit.ts"; +import { Transient, type Querier } from "../mirror.ts"; +import { approvalOf } from "./approval.ts"; +import { planLabels, type PlanRow } from "./plan.ts"; +import { ALL_LABELS, type LabelDef } from "./set.ts"; + +const ORG = "storytold"; +export const BATCH = 10; // mutations per request +export const WRITES_PER_MIN = 60; // GitHub asks integrators to stay near this for content-creating writes +const NODE_LOOKUP = 25; + +export class LabelsError extends Error {} + +type Wait = (ms: number) => Promise; + +async function retrying(f: () => Promise, wait: Wait): Promise { + for (let i = 1; ; i++) { + try { + return await f(); + } catch (e) { + if (!(e instanceof Transient) || i >= 5) throw e; + await wait(5_000 * i); + } + } +} + +type Repo = { id: string; labels: Map }; // lower-case name -> label id + +export async function repoLabels(client: Querier, repo: string, wait: Wait = sleepMs as Wait): Promise { + const q = `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { id + ${ALL_LABELS.map((l, i) => `l${i}: label(name: ${JSON.stringify(l.name)}) { id name }`).join("\n")} } }`; + const d = await retrying(() => client.query(q, { owner: ORG, name: repo }), wait); + if (!d.repository) throw new LabelsError(`repo ${repo} not found`); + const labels = new Map(); + ALL_LABELS.forEach((l, i) => { + const hit = d.repository[`l${i}`]; + if (hit) labels.set(l.name.toLowerCase(), hit.id); + }); + return { id: d.repository.id, labels }; +} + +// Creates the missing labels of the set. Returns the names missing (created when apply). +export async function ensureLabels(client: Querier, repo: string, apply: boolean, wait: Wait = sleepMs as Wait): Promise { + const have = await repoLabels(client, repo, wait); + const missing = ALL_LABELS.filter((l) => !have.labels.has(l.name.toLowerCase())); + if (apply) { + for (const l of missing) { + await retrying(() => client.query( + `mutation($input: CreateLabelInput!) { createLabel(input: $input) { label { id } } }`, + { input: { repositoryId: have.id, name: l.name, color: l.color, description: l.description } }), wait); + await wait(1_000); + } + } + return missing; +} + +export type ApplyResult = { planned: number; labeled: number; failed: number[]; batches: number; dryRun: boolean }; +export type ApplyOpts = { runId: string; limit?: number; apply: boolean; login?: string; wait?: Wait; log?: (s: string) => void }; + +// Items a previous apply already labelled (resumability): the latest `labeled` stage row names every label we would add. +function alreadyApplied(db: DatabaseSync, repo: string, r: PlanRow): boolean { + const s = db.prepare("SELECT note FROM main.stages WHERE repo = ? AND number = ? AND stage = 'labeled' ORDER BY at DESC, rowid DESC LIMIT 1") + .get(repo, r.number) as { note: string | null } | undefined; + if (!s?.note) return false; + const done = s.note.replace(/^added: /, "").split(", "); + return r.add.every((a) => done.some((d) => d.toLowerCase() === a.toLowerCase())); +} + +export async function applyLabels(db: DatabaseSync, client: Querier, repo: string, o: ApplyOpts): Promise { + const wait = o.wait ?? (sleepMs as Wait); + const log = o.log ?? (() => {}); + const approval = approvalOf(db, repo); + if (o.apply && !approval) { + throw new LabelsError(`${repo} is not approved for labelling. An operator approves it on the dashboard Repos page.`); + } + let todo = planLabels(db, repo, o.runId).filter((r) => r.status === "add" && !alreadyApplied(db, repo, r)); + if (o.limit !== undefined) todo = todo.slice(0, o.limit); + const res: ApplyResult = { planned: todo.length, labeled: 0, failed: [], batches: 0, dryRun: !o.apply }; + if (!o.apply) { + for (const r of todo) log(`${repo}#${r.number}: would add ${r.add.join(", ")}`); + return res; + } + const have = await repoLabels(client, repo, wait); + const needed = new Set(todo.flatMap((r) => r.add.map((a) => a.toLowerCase()))); + const unknown = [...needed].filter((n) => !have.labels.has(n)); + if (unknown.length) throw new LabelsError(`missing labels on ${repo}: ${unknown.join(", ")}; run labels ensure --repo ${repo} --apply`); + + for (let i = 0; i < todo.length; i += BATCH) { + const chunk = todo.slice(i, i + BATCH); + const started = Date.now(); + const ids = await nodeIds(client, repo, chunk.map((r) => r.number), wait); + const writable = chunk.filter((r) => ids.get(r.number)); + for (const r of chunk) if (!ids.get(r.number)) res.failed.push(r.number); + const done = writable.length ? await mutate(client, writable, ids, have, wait) : []; + for (const r of writable) if (!done.includes(r.number)) res.failed.push(r.number); + const ok = writable.filter((r) => done.includes(r.number)); + if (ok.length) { + const at = new Date().toISOString(); + db.exec("BEGIN"); + for (const r of ok) { + db.prepare("INSERT INTO main.stages (repo, number, stage, at, actor, note) VALUES (?, ?, 'labeled', ?, 'labels', ?)") + .run(repo, r.number, at, `added: ${r.add.join(", ")}`); + } + audit(db, o.login ?? "cli", "labels-apply", repo, { run: o.runId, items: ok.map((r) => r.number), labels: ok.reduce((n, r) => n + r.add.length, 0) }); + db.exec("COMMIT"); + res.labeled += ok.length; + } + res.batches++; + log(`${repo}: batch ${res.batches}: labelled ${ok.length} of ${chunk.length}`); + const minMs = (chunk.length * 60_000) / WRITES_PER_MIN; + const spent = Date.now() - started; + if (spent < minMs && i + BATCH < todo.length) await wait(minMs - spent); + } + return res; +} + +async function nodeIds(client: Querier, repo: string, numbers: number[], wait: Wait): Promise> { + const out = new Map(); + for (let i = 0; i < numbers.length; i += NODE_LOOKUP) { + const part = numbers.slice(i, i + NODE_LOOKUP); + const q = `query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { + ${part.map((n) => `n${n}: issueOrPullRequest(number: ${n}) { ... on Labelable { id } }`).join("\n")} } }`; + const d = await retrying(() => client.query(q, { owner: ORG, name: repo }), wait); + for (const n of part) out.set(n, d.repository?.[`n${n}`]?.id ?? null); + } + return out; +} + +// Returns the numbers whose mutation succeeded. A failed batch is retried item by item. +async function mutate(client: Querier, rows: PlanRow[], ids: Map, have: Repo, wait: Wait): Promise { + const run = async (part: PlanRow[]): Promise => { + const vars: Record = {}; + const decl: string[] = []; + const body = part.map((r, k) => { + vars[`i${k}`] = ids.get(r.number); + vars[`l${k}`] = r.add.map((a) => have.labels.get(a.toLowerCase())); + decl.push(`$i${k}: ID!`, `$l${k}: [ID!]!`); + return `m${k}: addLabelsToLabelable(input: {labelableId: $i${k}, labelIds: $l${k}}) { clientMutationId }`; + }); + const d = await retrying(() => client.query(`mutation(${decl.join(", ")}) { ${body.join("\n")} }`, vars), wait); + return part.filter((_, k) => d && d[`m${k}`] !== null && d[`m${k}`] !== undefined).map((r) => r.number); + }; + try { + return await run(rows); + } catch (e) { + if (e instanceof Transient || rows.length === 1) { + if (e instanceof Transient) throw e; + return []; + } + const out: number[] = []; + for (const r of rows) { + try { + out.push(...(await run([r]))); + } catch (e2) { + if (e2 instanceof Transient) throw e2; + } + } + return out; + } +} diff --git a/src/labels/index.ts b/src/labels/index.ts new file mode 100644 index 000000000..1243ee40c --- /dev/null +++ b/src/labels/index.ts @@ -0,0 +1,91 @@ +// craft-auto labels ensure|plan|apply: the pipeline's Label stage (docs/pipeline.md, stage 4). +import { mkdirSync, writeFileSync } from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join } from "node:path"; +import { connect } from "../db.ts"; +import { Client } from "../mirror.ts"; +import { approvalOf } from "./approval.ts"; +import { applyLabels, ensureLabels, LabelsError } from "./github.ts"; +import { countPlan, planCsv, planLabels } from "./plan.ts"; + +const USAGE = `usage: craft-auto labels --repo NAME [options] + ensure --repo R [--apply] create the missing labels of the set (dry run without --apply) + plan --repo R [--run RUN] [--csv FILE|-] labels to add per open item; counts on stdout, CSV to FILE + apply --repo R --run RUN [--limit N] [--apply] add the planned labels; dry run without --apply; + --apply needs the repo approved on the dashboard`; + +function parse(args: string[]): { repo: string; run?: string; limit?: number; csv?: string; apply: boolean } { + const o: { repo?: string; run?: string; limit?: number; csv?: string; apply: boolean } = { apply: false }; + for (let i = 0; i < args.length; i++) { + const a = args[i]; + if (a === "--apply") o.apply = true; + else if (a === "--repo" || a === "--run" || a === "--limit" || a === "--csv") { + const v = args[++i]; + if (v === undefined) fail(`${a} needs a value`); + if (a === "--limit") o.limit = Number(v); + else o[a.slice(2) as "repo" | "run" | "csv"] = v; + } else fail(`unknown argument ${a}`); + } + if (!o.repo) fail("missing --repo"); + if (o.limit !== undefined && !(o.limit > 0)) fail("--limit must be a positive number"); + return o as { repo: string; run?: string; limit?: number; csv?: string; apply: boolean }; +} + +function fail(msg: string): never { + console.error(`${msg}\n${USAGE}`); + process.exit(1); +} + +const cacheDir = () => join(process.env.XDG_CACHE_HOME ?? join(homedir(), ".cache"), "craft-automation"); + +async function ensure(args: string[]): Promise { + const o = parse(args); + const missing = await ensureLabels(new Client(500), o.repo, o.apply); + if (!missing.length) return console.log(`${o.repo}: all labels exist`); + for (const l of missing) console.log(`${o.repo}: ${o.apply ? "created" : "would create"} "${l.name}" #${l.color} (${l.description})`); + if (!o.apply) console.log("dry run; add --apply to create them"); +} + +function plan(args: string[]): void { + const o = parse(args); + const rows = planLabels(connect(), o.repo, o.run); + const c = countPlan(rows); + const csv = planCsv(o.repo, rows); + if (o.csv === "-") return void process.stdout.write(csv); + const path = o.csv ?? join(cacheDir(), `labels-plan-${o.repo}.csv`); + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, csv); + const a = approvalOf(connect(), o.repo); + console.log(`${o.repo}: ${rows.length} open items; to add ${c.toAdd}, already labelled ${c.already}, unsettled ${c.unsettled}, conflicts ${c.conflicts}`); + console.log(`approved for labelling: ${a ? `yes (${a.by}, ${a.at})` : "no"}; csv: ${path}`); + for (const r of rows.filter((x) => x.status === "conflict")) console.log(` conflict ${o.repo}#${r.number}: settled ${r.settled}, ${r.note}`); +} + +async function apply(args: string[]): Promise { + const o = parse(args); + if (!o.run) fail("missing --run"); + try { + const client = new Client(500); + const r = await applyLabels(connect(), client, o.repo, { runId: o.run!, limit: o.limit, apply: o.apply, log: console.log }); + console.log(r.dryRun + ? `dry run: ${r.planned} items would be labelled; add --apply to write (needs operator approval)` + : `labelled ${r.labeled} of ${r.planned} items in ${r.batches} batches, ${r.failed.length} failed${r.failed.length ? ` (${r.failed.join(", ")})` : ""}; points ${client.spent}`); + } catch (e) { + if (!(e instanceof LabelsError)) throw e; + console.error(e.message); + process.exit(1); + } +} + +const sub: Record Promise | void> = { ensure, plan, apply }; + +export const commands = { + labels: { + summary: "the Label stage: ensure | plan | apply (writes only with --apply, and only for repos approved on the dashboard)", + run: async (args: string[]) => { + const f = args[0] ? sub[args[0]] : undefined; + if (!f) fail("unknown or missing subcommand"); + await f!(args.slice(1)); + }, + }, +}; diff --git a/src/labels/plan.ts b/src/labels/plan.ts new file mode 100644 index 000000000..a92cd0c2a --- /dev/null +++ b/src/labels/plan.ts @@ -0,0 +1,48 @@ +// Which labels each open item should get. Reads the mirror and classifications only. +import type { DatabaseSync } from "node:sqlite"; +import { forRun, settleRows, type ClsRow } from "./settled.ts"; +import { isTypeLabel, sameLabel } from "./set.ts"; + +export type PlanStatus = "add" | "already" | "unsettled" | "conflict"; +export type PlanRow = { + number: number; kind: string; url: string; status: PlanStatus; + settled: string; existing: string[]; add: string[]; note: string; +}; +export type PlanCounts = { toAdd: number; already: number; unsettled: number; conflicts: number }; + +export function planLabels(db: DatabaseSync, repo: string, runId?: string): PlanRow[] { + const items = db.prepare("SELECT number, kind, url, labels FROM main.items WHERE repo = ? AND state = 'OPEN' ORDER BY number").all(repo) as + { number: number; kind: string; url: string | null; labels: string | null }[]; + const byItem = new Map(); + const cls = db.prepare(`SELECT number, classifier, run_id, at, type_label, flags, probs FROM main.classifications WHERE repo = ? + ${runId ? "AND run_id = ?" : ""} ORDER BY at DESC`).all(...(runId ? [repo, runId] : [repo])) as (ClsRow & { number: number })[]; + for (const c of cls) (byItem.get(c.number) ?? byItem.set(c.number, []).get(c.number)!).push(c); + + return items.map((it) => { + let existing: string[] = []; + try { + existing = (JSON.parse(it.labels ?? "[]") as unknown[]).map(String); + } catch { /* unreadable labels count as none */ } + const row = { number: it.number, kind: it.kind, url: it.url ?? "", settled: "", existing, add: [] as string[], note: "" }; + const s = settleRows(forRun(byItem.get(it.number) ?? [], runId)); + if (!s) return { ...row, status: "unsettled" as const }; + row.settled = s.type; + const other = existing.filter((l) => isTypeLabel(l) && !sameLabel(l, s.type)); + if (other.length) return { ...row, status: "conflict" as const, note: `has ${other.join(", ")}` }; + const want = [s.type, ...(s.security ? ["security"] : []), ...(s.needsDecision ? ["needs decision"] : [])]; + const add = want.filter((w) => !existing.some((e) => sameLabel(e, w))); + return { ...row, add, status: add.length ? ("add" as const) : ("already" as const) }; + }); +} + +export function countPlan(rows: PlanRow[]): PlanCounts { + const n = (s: PlanStatus) => rows.filter((r) => r.status === s).length; + return { toAdd: n("add"), already: n("already"), unsettled: n("unsettled"), conflicts: n("conflict") }; +} + +const csvCell = (s: string | number) => (/[",\n]/.test(String(s)) ? `"${String(s).replace(/"/g, '""')}"` : String(s)); +export function planCsv(repo: string, rows: PlanRow[]): string { + const lines = [["repo", "number", "kind", "status", "settled_type", "existing_labels", "labels_to_add", "note", "url"].join(",")]; + for (const r of rows) lines.push([repo, r.number, r.kind, r.status, r.settled, r.existing.join("|"), r.add.join("|"), r.note, r.url].map(csvCell).join(",")); + return lines.join("\n") + "\n"; +} diff --git a/src/labels/set.ts b/src/labels/set.ts new file mode 100644 index 000000000..c133accd6 --- /dev/null +++ b/src/labels/set.ts @@ -0,0 +1,26 @@ +// The label set from the proposal to label community PRs instead of closing them. +// Type labels are exclusive (one per item); flags sit next to the type. + +export type LabelDef = { name: string; color: string; description: string }; + +export const TYPE_LABELS: LabelDef[] = [ + { name: "bugfix", color: "d73a4a", description: "Fixes something that is broken: wrong result, crash, data loss" }, + { name: "performance", color: "fbca04", description: "Same behaviour, faster or uses less memory" }, + { name: "missing feature", color: "0e8a16", description: "The reference application has it and we do not, or only part of it" }, + { name: "small extra", color: "c5def5", description: "Goes beyond the reference application, but is tiny and changes no default" }, + { name: "plugin candidate", color: "7057ff", description: "A good idea that is too specific or too big for the core" }, + { name: "infra", color: "bfd4f2", description: "Tests, CI, docs, build, packaging, tooling" }, +]; + +export const FLAG_LABELS: LabelDef[] = [ + { name: "security", color: "b60205", description: "A real security hole is fixed, or security hardening" }, + { name: "needs decision", color: "e99695", description: "Needs a product or scope decision by a maintainer" }, +]; + +export const ALL_LABELS: LabelDef[] = [...TYPE_LABELS, ...FLAG_LABELS]; + +const lower = (s: string) => s.toLowerCase(); +const TYPE_SET = new Set(TYPE_LABELS.map((l) => lower(l.name))); + +export const isTypeLabel = (name: string): boolean => TYPE_SET.has(lower(name)); +export const sameLabel = (a: string, b: string): boolean => lower(a) === lower(b); diff --git a/src/labels/settled.ts b/src/labels/settled.ts new file mode 100644 index 000000000..53e34f682 --- /dev/null +++ b/src/labels/settled.ts @@ -0,0 +1,49 @@ +// The settled type label and flags of one item, as the Label stage and the Items +// browser need them. The rule itself lives in ../classify/settled.ts. +import type { DatabaseSync } from "node:sqlite"; +import { settle } from "../classify/settled.ts"; + +export type Settled = { type: string; security: boolean; needsDecision: boolean }; +export type ClsRow = { classifier: string; run_id: string; at: string; type_label: string | null; flags: string | null; probs: string | null }; + +const flagList = (s: string | null): string[] => { + try { + const v = JSON.parse(s ?? "[]") as unknown; + return Array.isArray(v) ? v.map(String) : []; + } catch { + return []; + } +}; +const topOf = (s: string | null): number | null => { + try { + const t = (JSON.parse(s ?? "null") as { top?: unknown } | null)?.top; + return typeof t === "number" ? t : null; + } catch { + return null; + } +}; + +// rows: the classifications of one item in one run. +export function settleRows(rows: ClsRow[]): Settled | null { + const jev = rows.find((r) => r.classifier === "jev"); + const haiku = rows.find((r) => r.classifier === "haiku"); + if (!jev?.type_label) return null; + const s = settle( + { label: jev.type_label, flags: flagList(jev.flags), top: topOf(jev.probs) }, + haiku?.type_label ? { label: haiku.type_label, flags: flagList(haiku.flags) } : null, + ); + if (s.status !== "settled" || s.label === null) return null; + return { type: s.label, security: s.flags.includes("security"), needsDecision: s.flags.includes("needs decision") }; +} + +// Without a run, each classifier's latest row for the item counts, from the latest Jev run. +export function settledLabel(db: DatabaseSync, repo: string, number: number, runId?: string): Settled | null { + const all = db.prepare("SELECT classifier, run_id, at, type_label, flags, probs FROM main.classifications WHERE repo = ? AND number = ? ORDER BY at DESC") + .all(repo, number) as ClsRow[]; + return settleRows(forRun(all, runId)); +} + +export function forRun(rows: ClsRow[], runId?: string): ClsRow[] { + const id = runId ?? rows.find((r) => r.classifier === "jev")?.run_id; + return id === undefined ? [] : rows.filter((r) => r.run_id === id); +} diff --git a/src/mirror.ts b/src/mirror.ts index a399e6466..10e0bb5e2 100644 --- a/src/mirror.ts +++ b/src/mirror.ts @@ -71,7 +71,7 @@ query($name: String!, $first: Int!, $after: String, $states: [${stateType}!]) { }`; } -class Transient extends Error {} +export class Transient extends Error {} export class Client { reserve: number; @@ -127,10 +127,12 @@ export class Client { if (/502|503|504|timeout|eof|connection|unexpected end of json/.test(r.text)) throw new Transient(r.stderr.trim().slice(0, 200)); throw new Error(`gh failed: ${r.stderr.trim().slice(0, 500)}`); } - const rl = r.data.rateLimit; - this.remaining = rl.remaining; - this.spent += rl.cost; - this.resetAt = new Date(rl.resetAt); + const rl = r.data.rateLimit; // absent in mutation responses + if (rl) { + this.remaining = rl.remaining; + this.spent += rl.cost; + this.resetAt = new Date(rl.resetAt); + } return r.data; } } @@ -218,9 +220,13 @@ function commentRows(repo: string, kind: Kind, n: Node): SQLInputValue[][] { } function writePage(db: DatabaseSync, repo: string, kind: Kind, detail: Detail, nodes: Node[]): void { - const insert = db.prepare(`INSERT OR REPLACE INTO items (${COLUMNS.join(",")}) VALUES (${COLUMNS.map((c) => `:${c}`).join(",")})`); + // Upserts keep each row's rowid, which the full-text index (schema.sql) is keyed on. + const insert = db.prepare(`INSERT INTO items (${COLUMNS.join(",")}) VALUES (${COLUMNS.map((c) => `:${c}`).join(",")}) + ON CONFLICT (repo, number) DO UPDATE SET ${COLUMNS.filter((c) => c !== "repo" && c !== "number").map((c) => `${c}=excluded.${c}`).join(",")}`); const del = db.prepare("DELETE FROM comments WHERE repo=? AND number=?"); - const insComment = db.prepare("INSERT OR REPLACE INTO comments VALUES (?,?,?,?,?,?,?,?,?)"); + const insComment = db.prepare(`INSERT INTO comments VALUES (?,?,?,?,?,?,?,?,?) ON CONFLICT (id) DO UPDATE SET + repo=excluded.repo, number=excluded.number, kind=excluded.kind, author=excluded.author, created_at=excluded.created_at, + body=excluded.body, review_state=excluded.review_state, commit_oid=excluded.commit_oid`); db.exec("BEGIN"); try { for (const n of nodes) { diff --git a/src/schema.sql b/src/schema.sql index 0eb6bd71a..14226a566 100644 --- a/src/schema.sql +++ b/src/schema.sql @@ -71,7 +71,7 @@ CREATE TABLE IF NOT EXISTS classifications ( -- Where each item stands in the pipeline (latest row wins). CREATE TABLE IF NOT EXISTS stages ( repo TEXT NOT NULL, number INTEGER NOT NULL, - stage TEXT NOT NULL, -- classified | reviewed | take | hold | close | needs-decision | batched | merged | closed | fixed-by-us + stage TEXT NOT NULL, -- classified | labeled | reviewed | take | hold | close | needs-decision | batched | merged | closed | fixed-by-us at TEXT NOT NULL, actor TEXT, -- session or agent name note TEXT, -- one line, public-safe @@ -199,7 +199,7 @@ CREATE TABLE IF NOT EXISTS oauth_states ( CREATE TABLE IF NOT EXISTS audit ( at TEXT NOT NULL, login TEXT NOT NULL, - action TEXT NOT NULL, -- answer | undo | adopt | opinion | opinion-retract | comment | override | rule | access-add | access-remove | access-role | session-revoke | sign-in | sign-in-refused | repo-track | repo-untrack + action TEXT NOT NULL, -- answer | undo | adopt | opinion | opinion-retract | comment | override | rule | access-add | access-remove | access-role | session-revoke | sign-in | sign-in-refused | repo-track | repo-untrack | labels-approve | labels-revoke | labels-apply target TEXT, details TEXT -- JSON ); @@ -253,3 +253,39 @@ SELECT column1, 'seed', strftime('%Y-%m-%dT%H:%M:%SZ', 'now') FROM (VALUES ) WHERE NOT EXISTS (SELECT 1 FROM settings WHERE key = 'tracked_seeded') AND NOT EXISTS (SELECT 1 FROM tracked_repos); INSERT OR IGNORE INTO settings VALUES ('tracked_seeded', '1'); + +-- Full-text search over item titles and bodies and comment bodies. Both are +-- external-content tables (the text stays in items and comments only), kept +-- current by these triggers; db.ts builds them once for an existing database. +-- The sync writes items with an upsert, which keeps their rowids, and connect() +-- turns on recursive_triggers so an INSERT OR REPLACE also runs the delete triggers. +CREATE VIRTUAL TABLE IF NOT EXISTS items_fts USING fts5( + title, body, content='items', content_rowid='rowid', tokenize='porter unicode61 remove_diacritics 2'); +CREATE VIRTUAL TABLE IF NOT EXISTS comments_fts USING fts5( + body, content='comments', content_rowid='rowid', tokenize='porter unicode61 remove_diacritics 2'); + +CREATE TRIGGER IF NOT EXISTS items_fts_ai AFTER INSERT ON items BEGIN + INSERT INTO items_fts (rowid, title, body) VALUES (new.rowid, new.title, new.body); +END; +CREATE TRIGGER IF NOT EXISTS items_fts_ad AFTER DELETE ON items BEGIN + INSERT INTO items_fts (items_fts, rowid, title, body) VALUES ('delete', old.rowid, old.title, old.body); +END; +CREATE TRIGGER IF NOT EXISTS items_fts_au AFTER UPDATE OF title, body ON items +WHEN old.title IS NOT new.title OR old.body IS NOT new.body OR old.rowid <> new.rowid BEGIN + INSERT INTO items_fts (items_fts, rowid, title, body) VALUES ('delete', old.rowid, old.title, old.body); + INSERT INTO items_fts (rowid, title, body) VALUES (new.rowid, new.title, new.body); +END; +CREATE TRIGGER IF NOT EXISTS comments_fts_ai AFTER INSERT ON comments BEGIN + INSERT INTO comments_fts (rowid, body) VALUES (new.rowid, new.body); +END; +CREATE TRIGGER IF NOT EXISTS comments_fts_ad AFTER DELETE ON comments BEGIN + INSERT INTO comments_fts (comments_fts, rowid, body) VALUES ('delete', old.rowid, old.body); +END; +CREATE TRIGGER IF NOT EXISTS comments_fts_au AFTER UPDATE OF body ON comments +WHEN old.body IS NOT new.body OR old.rowid <> new.rowid BEGIN + INSERT INTO comments_fts (comments_fts, rowid, body) VALUES ('delete', old.rowid, old.body); + INSERT INTO comments_fts (rowid, body) VALUES (new.rowid, new.body); +END; +CREATE INDEX IF NOT EXISTS items_updated ON items(updated_at); +CREATE INDEX IF NOT EXISTS items_state_updated ON items(state, updated_at); +CREATE INDEX IF NOT EXISTS items_author_nocase ON items(author COLLATE NOCASE); diff --git a/test/admin.test.ts b/test/admin.test.ts index 59c581aaa..bddcb245c 100644 --- a/test/admin.test.ts +++ b/test/admin.test.ts @@ -183,6 +183,25 @@ describe("admin api", () => { assert.equal(lastAudit().action, "repo-untrack"); }); + test("only an operator approves labelling for a repo; it is audited and shown in the repo list", async () => { + const boss = await signedIn("boss"); + for (const who of ["maint", "viewer1"]) { + const c = await signedIn(who); + await c.post("/api/repos/labels-approve", { name: "photocraft" }, 403); + await c.post("/api/repos/labels-revoke", { name: "photocraft" }, 403); + } + const before = auditRows(); + const after = await boss.post("/api/repos/labels-approve", { name: "photocraft" }); + const l = after.find((r) => r.name === "photocraft")!.labels!; + assert.deepEqual([l.approved, l.approvedBy], [true, "boss"]); + assert.equal(lastAudit().action, "labels-approve"); + await boss.post("/api/repos/labels-approve", { name: "photocraft" }, 409); + await boss.post("/api/repos/labels-approve", { name: "not-yet" }, 400); + const off = await boss.post("/api/repos/labels-revoke", { name: "photocraft" }); + assert.equal(off.find((r) => r.name === "photocraft")!.labels!.approved, false); + assert.equal(auditRows(), before + 2); + }); + test("access: add, change role, revoke a session; the last operator can't be removed or demoted", async () => { const boss = await signedIn("boss"); const before = auditRows(); diff --git a/test/api.test.ts b/test/api.test.ts index 4c8226a28..0c48f4c7a 100644 --- a/test/api.test.ts +++ b/test/api.test.ts @@ -42,6 +42,7 @@ before(async () => { ins.run("photocraft", 4, "issue", "OPEN", "Crash on save", "d", "dave", now, now, null); ins.run("photocraft", 5, "issue", "OPEN", "Wave filter missing", "e", "erin", now, now, null); ins.run("untracked-repo", 6, "pr", "OPEN", "Add wave filter elsewhere", "f", "frank", now, now, null); + db.prepare("UPDATE items SET additions = 40, deletions = 3, changed_files = 7 WHERE repo = 'photocraft' AND number = 1").run(); db.prepare("INSERT INTO comments (repo, number, id, kind, author, created_at, body) VALUES ('photocraft', 1, 'c1', 'comment', 'alice', ?, 'looks good')").run(now); db.prepare("INSERT INTO classifications (repo, number, classifier, run_id, at, type_label, want, reason) VALUES ('photocraft', 1, 'haiku', 'r1', ?, 'small extra', 'yes', 'adds a filter')").run(now); ask(db, [P1, P2, F3, P4].map((id) => { @@ -118,7 +119,7 @@ describe("api", () => { const r = await c.req("GET", "/api/me"); assert.equal(r.status, 401); assert.deepEqual(await r.json(), { error: "sign-in required" }); - for (const path of ["/api/classifiers", "/api/classifiers/disagreements", "/api/cost"]) assert.equal((await c.req("GET", path)).status, 401, path); + for (const path of ["/api/classifiers", "/api/classifiers/disagreements", "/api/cost", "/api/items", "/api/items?q=wave"]) assert.equal((await c.req("GET", path)).status, 401, path); assert.equal((await c.req("POST", dpath(P1, "/opinion"), { body: { option: "small" }, csrf: "x" })).status, 401); }); @@ -130,6 +131,8 @@ describe("api", () => { assert.equal((await (await signedIn("maint")).get("/api/me")).role, "viewer"); const it = await boss.get("/api/items/photocraft/1"); assert.equal(it.body, " body"); + assert.deepEqual([it.changedFiles, it.additions, it.deletions], [7, 40, 3]); + assert.equal((await boss.get("/api/items/photocraft/4")).changedFiles, null); assert.deepEqual(it.comments.map((c) => c.body), ["looks good"]); assert.deepEqual(it.decisionIds, [P1]); assert.deepEqual(it.related.map((r) => [r.number, r.relation]), [[5, "fixes"]]); diff --git a/test/decide.test.ts b/test/decide.test.ts index aab4d46f3..a290446a3 100644 --- a/test/decide.test.ts +++ b/test/decide.test.ts @@ -11,7 +11,8 @@ import { LABELS } from "../src/classify/rules.ts"; import { connect } from "../src/db.ts"; import { buildDecision } from "../src/decide/decision.ts"; import { loadSummaryItems, runDecide } from "../src/decide/index.ts"; -import { settle, type Candidate } from "../src/decide/select.ts"; +import { settle } from "../src/classify/settled.ts"; +import type { Candidate } from "../src/decide/select.ts"; import { validateAsk, type DecisionRow } from "../src/decisions.ts"; import { claudeArgs, renderClaude } from "../src/prompts/index.ts"; diff --git a/test/fixture.ts b/test/fixture.ts index a8e33f11f..8612170cb 100644 --- a/test/fixture.ts +++ b/test/fixture.ts @@ -41,7 +41,7 @@ export function buildFixture(path: string, scale: Scale = FULL): DatabaseSync { const author = () => `user${String(Math.floor(3000 * r() ** 3)).padStart(4, "0")}`; db.exec("BEGIN"); - db.prepare("INSERT OR REPLACE INTO settings VALUES ('run_started_at', ?)").run(iso(start)); + db.prepare("INSERT OR REPLACE INTO settings VALUES ('tracking_started_at', ?)").run(iso(start)); const repoIns = db.prepare("INSERT INTO repos (name, visibility, default_branch, open_prs, open_issues, synced_at) VALUES (?, 'public', 'main', 0, 0, ?)"); for (const name of REPOS) repoIns.run(name, iso(now)); diff --git a/test/insight.test.ts b/test/insight.test.ts index f4e25303a..c6287985e 100644 --- a/test/insight.test.ts +++ b/test/insight.test.ts @@ -65,6 +65,7 @@ describe("insight", () => { test("cost totals, wall time and series", () => { const c = cost(db, rq("run=r1")); assert.deepEqual(c.total, { calls: 2, items: 6, input: 150, output: 30, cacheRead: 10, cacheWrite: 0, usd: 0.25, wallSeconds: 180 }); + assert.equal(c.itemsClassified, 6); assert.equal(c.stages.length, 1); assert.deepEqual(c.series, [{ bucket: "2026-11-01T10", tokens: 190, usd: 0.25 }]); }); diff --git a/test/items.test.ts b/test/items.test.ts new file mode 100644 index 000000000..c1d2f1f5e --- /dev/null +++ b/test/items.test.ts @@ -0,0 +1,155 @@ +// Settled type labels, the full-text index and the Items browser. +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import type { DatabaseSync } from "node:sqlite"; +import { describe, test } from "node:test"; +import type { ItemList } from "../web/src/api/types.ts"; +import { settle, settledOf } from "../src/classify/settled.ts"; +import { connect } from "../src/db.ts"; +import { listItems, quickSearch } from "../src/dash/api/items.ts"; +import { funnelByRepo } from "../src/dash/api/stats.ts"; +import { runSync } from "../src/mirror.ts"; +import { scopeToTracked } from "../src/repos.ts"; +import type { Req } from "../src/dash/types.ts"; + +const SCRATCH = join(homedir(), ".cache/craft-automation-scratch"); +mkdirSync(SCRATCH, { recursive: true }); +const freshPath = () => join(mkdtempSync(join(SCRATCH, "items-test-")), "m.db"); +const fresh = () => connect(freshPath()); +const req = (qs: string) => ({ query: new URLSearchParams(qs) }) as unknown as Req; +const refs = (l: ItemList) => l.rows.map((r) => `${r.repo}#${r.number}`).sort(); + +describe("settled type label", () => { + const jev = (label: string, top: number, flags: string[] = []) => ({ label, top, flags }); + test("Jev sure: Jev's label and flags", () => { + const s = settle(jev("bugfix", 0.95, ["security"]), { label: "infra", flags: ["needs decision"] }); + assert.deepEqual([s.status, s.label, s.source, s.flags], ["settled", "bugfix", "jev", ["security"]]); + }); + test("Jev unsure and Haiku agrees: settled by Haiku, flags of both", () => { + const s = settle(jev("small extra", 0.6, ["security"]), { label: "small extra", flags: ["needs decision"] }); + assert.deepEqual([s.status, s.label, s.source, s.flags], ["settled", "small extra", "haiku", ["security", "needs decision"]]); + }); + test("Jev unsure and Haiku pending: waiting", () => { + const s = settle(jev("small extra", 0.89), null); + assert.deepEqual([s.status, s.label], ["waiting", null]); + }); + test("Jev unsure and Haiku disagrees: disagree", () => { + const s = settle(jev("small extra", 0.5), { label: "plugin candidate", flags: [] }); + assert.deepEqual([s.status, s.label, s.jevLabel, s.haikuLabel], ["disagree", null, "small extra", "plugin candidate"]); + }); + test("no Jev verdict: unclassified", () => { + assert.equal(settle(null, { label: "bugfix", flags: [] }).status, "unclassified"); + }); +}); + +function seed(db: DatabaseSync): void { + const now = "2026-11-02T10:00:00Z"; + const ins = db.prepare("INSERT INTO items (repo, number, kind, state, title, body, author, created_at, updated_at) VALUES (?,?,?,?,?,?,?,?,?)"); + ins.run("photocraft", 1, "pr", "OPEN", "Add wave filter", "Distorts the layer", "alice", now, "2026-11-02T09:00:00Z"); + ins.run("photocraft", 2, "issue", "OPEN", "Crash on save", "Saving a big file crashes", "bob", now, "2026-11-01T09:00:00Z"); + ins.run("photocraft", 3, "pr", "CLOSED", "Faster export", "speed", "carol", now, "2026-10-01T09:00:00Z"); + ins.run("filmcraft", 4, "pr", "OPEN", "Timeline wave view", "audio", "Alice", now, "2026-11-02T08:00:00Z"); + ins.run("untracked-repo", 5, "pr", "OPEN", "Add wave filter elsewhere", "x", "dave", now, now); + const com = db.prepare("INSERT INTO comments (repo, number, id, kind, author, created_at, body) VALUES (?,?,?,?,?,?,?)"); + com.run("photocraft", 2, "c1", "comment", "erin", now, "The quokka plugin causes it"); + com.run("photocraft", 1, "c2", "comment", "erin", now, "looks good"); + const cls = db.prepare("INSERT INTO classifications (repo, number, classifier, run_id, at, type_label, flags, probs) VALUES (?,?,?,?,?,?,?,?)"); + const p = (top: number) => JSON.stringify({ top }); + cls.run("photocraft", 1, "jev", "r1", now, "small extra", '["needs decision"]', p(0.97)); + cls.run("photocraft", 2, "jev", "r1", now, "bugfix", "[]", p(0.6)); + cls.run("photocraft", 2, "haiku", "r1", now, "bugfix", '["security"]', null); + cls.run("photocraft", 3, "jev", "r1", now, "performance", "[]", p(0.5)); + cls.run("filmcraft", 4, "jev", "r1", now, "small extra", "[]", p(0.7)); + cls.run("filmcraft", 4, "haiku", "r1", now, "plugin candidate", "[]", null); + db.exec("DELETE FROM tracked_repos; INSERT INTO tracked_repos (name) VALUES ('photocraft'), ('filmcraft')"); +} + +describe("Items browser", () => { + const db = fresh(); + seed(db); + scopeToTracked(db); + + test("full text finds a word in a title and in a comment body, in tracked repos only", () => { + assert.deepEqual(refs(listItems(db, req("q=wave"))), ["filmcraft#4", "photocraft#1"]); + const c = listItems(db, req("q=quokka")); + assert.deepEqual(refs(c), ["photocraft#2"]); + assert.equal(c.rows[0]!.snippet?.field, "comment"); + assert.match(c.rows[0]!.snippet!.text, /\u0002quokka\u0003/); + assert.deepEqual(refs(listItems(db, req("q=%22wave+filter%22"))), ["photocraft#1"]); + assert.deepEqual(refs(listItems(db, req("q=quok*"))), ["photocraft#2"]); + assert.deepEqual(refs(listItems(db, req("q=wave+-timeline"))), ["photocraft#1"]); + assert.deepEqual(refs(listItems(db, req("q=%22unbalanced+NOT+("))), []); + }); + + test("filters combine and counts per status ignore the status filter", () => { + const all = listItems(db, req("state=all")); + assert.equal(all.total, 4); + assert.deepEqual(all.byStatus, { settled: 2, waiting: 1, disagree: 1, unclassified: 0 }); + assert.deepEqual(refs(listItems(db, req(""))), ["filmcraft#4", "photocraft#1", "photocraft#2"]); + assert.deepEqual(refs(listItems(db, req("status=unsettled&state=all"))), ["filmcraft#4", "photocraft#3"]); + assert.deepEqual(refs(listItems(db, req("label=bugfix"))), ["photocraft#2"]); + assert.deepEqual(refs(listItems(db, req("flag=security"))), ["photocraft#2"]); + assert.deepEqual(refs(listItems(db, req("q=wave&repo=photocraft&kind=pr&status=settled"))), ["photocraft#1"]); + assert.deepEqual(refs(listItems(db, req("author=alice"))), ["filmcraft#4", "photocraft#1"]); + assert.deepEqual(refs(listItems(db, req("since=2026-11-02"))), ["filmcraft#4", "photocraft#1"]); + const sorted = listItems(db, req("sort=number&desc=0")); + assert.deepEqual(sorted.rows.map((r) => r.number), [1, 2, 4]); + assert.equal(sorted.rows[1]!.settled.source, "haiku"); + assert.throws(() => listItems(db, req("mode=semantic")), /mode/); + }); + + test("Progress counts settled, waiting and disagreeing open items", () => { + const f = funnelByRepo(db); + const p = f.find((r) => r.repo === "photocraft")!, fc = f.find((r) => r.repo === "filmcraft")!; + assert.deepEqual([p.classified, p.second_opinion, p.disagreement], [2, 0, 0]); + assert.deepEqual([fc.classified, fc.second_opinion, fc.disagreement], [0, 0, 1]); + assert.equal(settledOf(db, "photocraft", 3).status, "waiting"); + }); + + test("a new verdict shows without a rebuild", () => { + db.prepare("INSERT INTO main.classifications (repo, number, classifier, run_id, at, type_label, flags) VALUES ('photocraft', 3, 'haiku', 'r1', ?, 'performance', '[]')") + .run("2026-11-02T10:00:01Z"); + assert.deepEqual(refs(listItems(db, req("label=performance&state=all"))), ["photocraft#3"]); + }); + + test("top-bar search: numbers, logins and words", () => { + assert.deepEqual(quickSearch(db, req("q=photocraft%232")).map((h) => h.number), [2]); + assert.deepEqual(quickSearch(db, req("q=carol")).map((h) => h.number), [3]); + assert.deepEqual(quickSearch(db, req("q=crash")).map((h) => h.number), [2]); + assert.deepEqual(quickSearch(db, req("q=timel")).map((h) => h.number), [4]); + }); +}); + +test("the index follows sync writes", async () => { + const path = freshPath(); + const db = connect(path); + // the sync writes on its own connection, as in production; the dashboard's is scoped + const dash = connect(path); + db.exec("DELETE FROM tracked_repos; INSERT INTO tracked_repos VALUES ('a','t','x')"); + db.exec("INSERT INTO repos (name, synced_at, high_water) VALUES ('a','2026-11-02T09:00:00Z','2026-11-02T09:00:00Z')"); + db.exec("INSERT INTO settings VALUES ('org_high_water','2026-11-02T09:30:00Z'),('repos_refreshed_at','2999-01-01T00:00:00Z')"); + const node = (title: string, comment: string, updatedAt: string) => ({ + __typename: "Issue", repository: { name: "a" }, number: 1, title, body: "", url: "u", author: { login: "a" }, + authorAssociation: "NONE", createdAt: "2026-01-01T00:00:00Z", updatedAt, closedAt: null, state: "OPEN", + labels: { nodes: [] }, assignees: { nodes: [] }, commentCount: { totalCount: 1 }, stateReason: null, + comments: { nodes: [{ id: "c1", author: { login: "b" }, createdAt: updatedAt, body: comment }] }, + }); + const client = (n: unknown) => ({ + spent: 0, remaining: 4000, + async query() { return { search: { issueCount: 1, pageInfo: { hasNextPage: false, endCursor: null }, nodes: [n] } }; }, + }); + const opts = { only: [], all: false, full: false, perRepo: false }; + await runSync(db, client(node("alpha title", "zebra comment", "2026-11-02T10:00:00Z")), opts, new Date("2026-11-02T10:05:00Z")); + scopeToTracked(dash); + assert.equal(listItems(dash, req("q=alpha")).total, 1); + assert.equal(listItems(dash, req("q=zebra")).total, 1); + await runSync(db, client(node("gamma title", "yak comment", "2026-11-02T10:06:00Z")), opts, new Date("2026-11-02T10:10:00Z")); + assert.equal(listItems(dash, req("q=alpha")).total, 0); + assert.equal(listItems(dash, req("q=zebra")).total, 0); + assert.equal(listItems(dash, req("q=gamma")).total, 1); + assert.equal(listItems(dash, req("q=yak")).total, 1); + db.exec("INSERT INTO items_fts (items_fts) VALUES ('integrity-check')"); + db.exec("INSERT INTO comments_fts (comments_fts) VALUES ('integrity-check')"); +}); diff --git a/test/labels.test.ts b/test/labels.test.ts new file mode 100644 index 000000000..b650f72fd --- /dev/null +++ b/test/labels.test.ts @@ -0,0 +1,121 @@ +// The Label stage: the plan, the approval gate and apply, with a fake Querier (nothing reaches GitHub). +import assert from "node:assert/strict"; +import { mkdirSync, mkdtempSync, rmSync } from "node:fs"; +import { homedir } from "node:os"; +import { join } from "node:path"; +import { after, describe, test } from "node:test"; +import { connect } from "../src/db.ts"; +import { applyLabels, BATCH, LabelsError } from "../src/labels/github.ts"; +import { setApproval } from "../src/labels/approval.ts"; +import { ALL_LABELS } from "../src/labels/set.ts"; +import { countPlan, planLabels } from "../src/labels/plan.ts"; + +const SCRATCH = join(homedir(), ".cache/craft-automation-scratch"); +mkdirSync(SCRATCH, { recursive: true }); +const dir = mkdtempSync(join(SCRATCH, "labels-test-")); +after(() => rmSync(dir, { recursive: true, force: true })); + +const RUN = "org-1"; +function setup(name: string) { + const db = connect(join(dir, `${name}.db`)); + const item = db.prepare("INSERT INTO items (repo, number, kind, state, title, url, labels) VALUES ('app', ?, 'pr', 'OPEN', 't', 'u', ?)"); + const cls = db.prepare("INSERT INTO classifications (repo, number, classifier, run_id, at, type_label, flags, probs) VALUES ('app', ?, ?, ?, '2026-01-01T00:00:00Z', ?, ?, ?)"); + const jev = (n: number, type: string, top: number, flags: string[] = []) => cls.run(n, "jev", RUN, type, JSON.stringify(flags), JSON.stringify({ top })); + const haiku = (n: number, type: string, flags: string[] = []) => cls.run(n, "haiku", RUN, type, JSON.stringify(flags), null); + return { db, item, jev, haiku }; +} + +describe("labels plan", () => { + test("skips unsettled, conflicting and already-labelled items; adds flags only when settled", () => { + const { db, item, jev, haiku } = setup("plan"); + item.run(1, "[]"); jev(1, "bugfix", 0.95, ["security"]); // settled by Jev: bugfix + security + item.run(2, "[]"); jev(2, "infra", 0.6); haiku(2, "infra"); // settled by agreement + item.run(3, "[]"); jev(3, "infra", 0.6); haiku(3, "bugfix"); // unsettled + item.run(4, '["performance"]'); jev(4, "bugfix", 0.99); // person set another type: conflict + item.run(5, '["Bugfix","security"]'); jev(5, "bugfix", 0.99, ["security"]); // already there (case-insensitive) + item.run(6, '["help wanted"]'); jev(6, "small extra", 0.99, ["needs decision"]); // other labels are left alone + item.run(7, "[]"); // never classified + const rows = planLabels(db, "app", RUN); + const by = Object.fromEntries(rows.map((r) => [r.number, r])); + assert.deepEqual(by[1]!.add, ["bugfix", "security"]); + assert.deepEqual(by[2]!.add, ["infra"]); + assert.equal(by[3]!.status, "unsettled"); + assert.equal(by[4]!.status, "conflict"); + assert.deepEqual(by[4]!.add, []); + assert.equal(by[5]!.status, "already"); + assert.deepEqual(by[6]!.add, ["small extra", "needs decision"]); + assert.equal(by[7]!.status, "unsettled"); + assert.deepEqual(countPlan(rows), { toAdd: 3, already: 1, unsettled: 2, conflicts: 1 }); + }); +}); + +type Call = { query: string; variables: Record }; +function fakeClient(opts: { failNumber?: number } = {}) { + const calls: Call[] = []; + return { + calls, spent: 0, remaining: 5000 as number | null, + async query(query: string, variables: Record) { + calls.push({ query, variables }); + if (query.includes("label(name:")) { + const l: Record = { id: "R1" }; + ALL_LABELS.map((x) => x.name).forEach((n, i) => (l[`l${i}`] = { id: `L-${n}`, name: n })); + return { repository: l }; + } + if (query.includes("issueOrPullRequest")) { + const r: Record = {}; + for (const m of query.matchAll(/n(\d+): issueOrPullRequest/g)) r[`n${m[1]}`] = { id: `N${m[1]}` }; + return { repository: r }; + } + const out: Record = {}; + for (const m of query.matchAll(/m(\d+): addLabelsToLabelable/g)) { + const id = variables[`i${m[1]}`] as string; + out[`m${m[1]}`] = id === `N${opts.failNumber}` ? null : { clientMutationId: null }; + } + return out; + }, + }; +} + +describe("labels apply", () => { + test("refuses an unapproved repo and writes nothing", async () => { + const { db, item, jev } = setup("refuse"); + item.run(1, "[]"); jev(1, "bugfix", 0.99); + const c = fakeClient(); + await assert.rejects(applyLabels(db, c, "app", { runId: RUN, apply: true, wait: async () => {} }), LabelsError); + assert.equal(c.calls.length, 0); + }); + + test("dry run by default: no calls, no rows", async () => { + const { db, item, jev } = setup("dry"); + item.run(1, "[]"); jev(1, "bugfix", 0.99); + const c = fakeClient(); + const r = await applyLabels(db, c, "app", { runId: RUN, apply: false, wait: async () => {} }); + assert.deepEqual([r.dryRun, r.planned, c.calls.length], [true, 1, 0]); + }); + + test("approved: batches mutations, writes stages and one audit row per batch, and resumes", async () => { + const { db, item, jev } = setup("apply"); + db.exec("INSERT INTO tracked_repos (name) VALUES ('app')"); + const n = BATCH + 3; + for (let i = 1; i <= n; i++) { item.run(i, "[]"); jev(i, "bugfix", 0.99, i === 1 ? ["security"] : []); } + setApproval(db, "boss", "app", true); + const waits: number[] = []; + const c = fakeClient({ failNumber: 2 }); + const r = await applyLabels(db, c, "app", { runId: RUN, apply: true, wait: async (ms) => void waits.push(ms) }); + assert.deepEqual([r.planned, r.labeled, r.failed, r.batches], [n, n - 1, [2], 2]); + const mutations = c.calls.filter((x) => x.query.startsWith("mutation")); + assert.equal(mutations.length, 2); + assert.equal((mutations[0]!.query.match(/addLabelsToLabelable/g) ?? []).length, BATCH); + assert.deepEqual(mutations[0]!.variables.l0, ["L-bugfix", "L-security"]); + assert.ok(waits.some((w) => w > 0), "paced between batches"); + const stages = db.prepare("SELECT number, note FROM stages WHERE stage = 'labeled' ORDER BY number").all() as { number: number; note: string }[]; + assert.equal(stages.length, n - 1); + assert.equal(stages[0]!.note, "added: bugfix, security"); + assert.equal((db.prepare("SELECT COUNT(*) AS n FROM audit WHERE action = 'labels-apply'").get() as { n: number }).n, 2); + + // second run: only the failed item remains + const again = fakeClient(); + const r2 = await applyLabels(db, again, "app", { runId: RUN, apply: true, wait: async () => {} }); + assert.deepEqual([r2.planned, r2.labeled], [1, 1]); + }); +}); diff --git a/test/markdown-html.test.ts b/test/markdown-html.test.ts new file mode 100644 index 000000000..f3bafd626 --- /dev/null +++ b/test/markdown-html.test.ts @@ -0,0 +1,74 @@ +// Raw HTML in untrusted bodies: and friends become Markdown nodes, and +// nothing else gets through. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { htmlBlock, inlineChildren, proxiedImage, remarkHtmlToMarkdown, safeUrl, type MdNode } from "../web/src/ui/markdownHtml.ts"; + +const ALLOWED = new Set(["paragraph", "text", "image", "link", "break", "strong", "emphasis", "inlineCode"]); +const IMG = "https://github.com/user-attachments/assets/52cc3f06-06ec-404f-94b5-74a9af1e1c7e"; + +function all(nodes: MdNode[]): MdNode[] { + return nodes.flatMap((n) => [n, ...all(n.children ?? [])]); +} +const of = (nodes: MdNode[], type: string) => all(nodes).filter((n) => n.type === type); + +test("an in a block becomes a proxied image", () => { + const out = htmlBlock(`

Screen

`); + const [img] = of(out, "image"); + assert.deepEqual(img, { type: "image", url: IMG, alt: "Screen", title: null }); + assert.equal(proxiedImage(safeUrl(img!.url!)), `/img?${new URLSearchParams({ u: IMG })}`); + assert.ok(all(out).every((n) => ALLOWED.has(n.type))); + assert.ok(!JSON.stringify(out).includes("onerror")); +}); + +test("no other HTML gets through", () => { + const out = htmlBlock(`
+
More & lesskept text
<b>
`); + assert.ok(all(out).every((n) => ALLOWED.has(n.type)), JSON.stringify(out)); + const text = JSON.stringify(out); + for (const bad of ["alert", "p{}", "evil", "onclick", "style"]) assert.ok(!text.includes(bad), bad); + assert.ok(all(out).every((n) => Object.keys(n).every((k) => ["type", "value", "url", "alt", "title", "children"].includes(k)))); + assert.equal(of(out, "strong")[0]!.children![0]!.value, "More & less"); + assert.ok(of(out, "text").some((n) => n.value === "kept text")); + assert.equal(of(out, "inlineCode")[0]!.value, ""); +}); + +test("a javascript: or foreign src stays a chip or link, never a proxied image", () => { + for (const src of ["javascript:alert(1)", "https://evil.example/a.png", "http://github.com/user-attachments/assets/x", "data:image/png;base64,AAAA"]) { + const [img] = of(htmlBlock(`x`), "image"); + assert.equal(proxiedImage(safeUrl(img!.url!)), null, src); + } + const [link] = of(htmlBlock(`click`), "link"); + assert.equal(safeUrl(link!.url!), ""); +}); + +test("inline tags inside a paragraph", () => { + const kids = inlineChildren([ + { type: "text", value: "before " }, + { type: "html", value: `a` }, + { type: "html", value: "
" }, + { type: "html", value: '' }, + { type: "text", value: "link text" }, + { type: "html", value: "" }, + { type: "html", value: "" }, + { type: "text", value: " after" }, + { type: "html", value: "" }, + ]); + assert.deepEqual(kids.map((k) => k.type), ["text", "image", "break", "link", "text"]); + assert.equal(kids[3]!.children![0]!.value, "link text"); +}); + +test("the plugin replaces html nodes in a tree", () => { + const tree: MdNode = { + type: "root", + children: [ + { type: "paragraph", children: [{ type: "text", value: "Requested in chat." }] }, + { type: "html", value: `Image` }, + { type: "html", value: '' }, + ], + }; + remarkHtmlToMarkdown()(tree); + assert.ok(!all(tree.children!).some((n) => n.type === "html")); + assert.equal(of(tree.children!, "image").length, 1); + assert.equal(of(tree.children!, "link")[0]!.children![0]!.value, "Video: demo.mp4"); +}); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 5d8121060..a831f200e 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -16,6 +16,8 @@ import type { DisagreementFilter, DisagreementList, Item, + ItemFilter, + ItemList, OverrideInput, Progress, PromptsReport, @@ -47,7 +49,10 @@ export interface Api { comment(id: string, body: string): Promise; }; item(repo: RepoName, number: number): Promise; + /** Top bar: jumps by number, logins, words in titles and bodies. */ search(q: string): Promise; + /** The Items browser: every tracked repo, full-text search over titles, bodies and comments. */ + items(filter: ItemFilter): Promise; progress(): Promise; /** Anyone signed in reads; writes and the preview are for operators. Override notes come only to operators. */ contributors: { @@ -61,6 +66,8 @@ export interface Api { list(): Promise; track(name: RepoName): Promise; untrack(name: RepoName): Promise; + /** Lets the Label stage write labels to this repo on GitHub, or stops it. */ + approveLabels(name: RepoName, approved: boolean): Promise; }; /** Operator only. */ access: { diff --git a/web/src/api/http.ts b/web/src/api/http.ts index 4513168e6..7f6626cf9 100644 --- a/web/src/api/http.ts +++ b/web/src/api/http.ts @@ -1,5 +1,5 @@ import type { Api } from "./client"; -import type { DecisionFilter } from "./types"; +import type { DecisionFilter, ItemFilter } from "./types"; /** Query string from the set fields; booleans as 1 / 0. */ function qs(f: object): string { @@ -57,7 +57,16 @@ export function createHttpApi(): Api { return (await r.json()) as T; } - const get = (path: string) => call("GET", path); + // Views that mount together often ask for the same thing; they share one request. + const inflight = new Map>(); + const get = (path: string): Promise => { + let p = inflight.get(path) as Promise | undefined; + if (!p) { + p = call("GET", path).finally(() => inflight.delete(path)); + inflight.set(path, p); + } + return p; + }; async function post(path: string, body?: unknown): Promise { const v = await call("POST", path, body); changed(); @@ -78,6 +87,16 @@ export function createHttpApi(): Api { return s ? `?${s}` : ""; } + function itemQuery(f: ItemFilter): string { + const q = new URLSearchParams(); + for (const [k, v] of Object.entries(f)) { + if (v === undefined || v === "" || (Array.isArray(v) && !v.length)) continue; + q.set(k, Array.isArray(v) ? v.join(",") : typeof v === "boolean" ? (v ? "1" : "0") : String(v)); + } + const s = q.toString(); + return s ? `?${s}` : ""; + } + return { me: () => get("/api/me"), repos: () => get("/api/repos"), @@ -95,7 +114,8 @@ export function createHttpApi(): Api { comment: (id, body) => post(dec(id, "/comments"), { body }), }, item: (repo, number) => get(`/api/items/${encodeURIComponent(repo)}/${encodeURIComponent(String(number))}`), - search: (q) => get(`/api/search?${new URLSearchParams({ q })}`), + search: (q) => (q.trim() ? get(`/api/search?${new URLSearchParams({ q })}`) : Promise.resolve([])), + items: (f) => get(`/api/items${itemQuery(f)}`), progress: () => get("/api/progress"), contributors: { list: (filter) => get(`/api/contributors${qs(filter)}`), @@ -107,6 +127,7 @@ export function createHttpApi(): Api { list: () => get("/api/repos/all"), track: (name) => post("/api/repos/track", { name }), untrack: (name) => post("/api/repos/untrack", { name }), + approveLabels: (name, approved) => post(approved ? "/api/repos/labels-approve" : "/api/repos/labels-revoke", { name }), }, access: { overview: () => get("/api/access"), diff --git a/web/src/api/mock/adminMock.ts b/web/src/api/mock/adminMock.ts index 723da4d44..c0bea2418 100644 --- a/web/src/api/mock/adminMock.ts +++ b/web/src/api/mock/adminMock.ts @@ -97,9 +97,11 @@ function buildRepos(): TrackedRepo[] { const r = rng(77); const tracked = REPO_OPEN.map(([name, open]) => { const prs = Math.round(open * (0.3 + r() * 0.2)); - return { name, tracked: true, openPrs: prs, openIssues: open - prs, mirrored: Math.round(open * (3.5 + r())), syncedAt: iso((2 + r() * 40) * 60_000) }; + const toAdd = Math.round(prs * (0.4 + r() * 0.3)); + const labels = { approved: false, approvedBy: null, approvedAt: null, toAdd, skipped: Math.round(prs * 0.2), conflicts: r() < 0.3 ? Math.floor(r() * 4) : 0 }; + return { name, tracked: true, openPrs: prs, openIssues: open - prs, mirrored: Math.round(open * (3.5 + r())), syncedAt: iso((2 + r() * 40) * 60_000), labels }; }); - const rest = UNTRACKED.map((name) => ({ name, tracked: false, openPrs: Math.floor(r() * 30), openIssues: Math.floor(r() * 80), mirrored: name === "craft-docs-archive" ? 412 : 0, syncedAt: name === "craft-docs-archive" ? iso(12 * D) : null })); + const rest = UNTRACKED.map((name) => ({ name, tracked: false, openPrs: Math.floor(r() * 30), openIssues: Math.floor(r() * 80), mirrored: name === "craft-docs-archive" ? 412 : 0, syncedAt: name === "craft-docs-archive" ? iso(12 * D) : null, labels: null })); return [...tracked, ...rest]; } @@ -257,8 +259,9 @@ export function createAdminMock(me: User, changed: () => void): AdminApi { if (!/^[A-Za-z0-9._-]{1,100}$/.test(name)) throw new Error("Not a repo name."); let r = repos.find((x) => x.name === name); if (r?.tracked) throw new Error(`${name} is already tracked`); - if (!r) repos.push((r = { name, tracked: true, openPrs: null, openIssues: null, mirrored: 0, syncedAt: null })); + if (!r) repos.push((r = { name, tracked: true, openPrs: null, openIssues: null, mirrored: 0, syncedAt: null, labels: null })); r.tracked = true; + r.labels ??= { approved: false, approvedBy: null, approvedAt: null, toAdd: 0, skipped: 0, conflicts: 0 }; log("repo-track", name); changed(); return this.list(); @@ -268,10 +271,21 @@ export function createAdminMock(me: User, changed: () => void): AdminApi { const r = repos.find((x) => x.name === name); if (!r?.tracked) throw new Error(`${name} is not tracked`); r.tracked = false; + r.labels = null; log("repo-untrack", name); changed(); return this.list(); }, + async approveLabels(name, approved) { + requireOperator("approve labelling"); + const r = repos.find((x) => x.name === name); + if (!r?.labels) throw new Error(`${name} is not tracked`); + if (r.labels.approved === approved) throw new Error(`${name} is ${approved ? "already" : "not"} approved for labelling`); + Object.assign(r.labels, approved ? { approved, approvedBy: me.login, approvedAt: nowIso() } : { approved, approvedBy: null, approvedAt: null }); + log(approved ? "labels-approve" : "labels-revoke", name); + changed(); + return this.list(); + }, }, access: { overview() { diff --git a/web/src/api/mock/fixtures.ts b/web/src/api/mock/fixtures.ts index db262bda2..0d070174d 100644 --- a/web/src/api/mock/fixtures.ts +++ b/web/src/api/mock/fixtures.ts @@ -20,7 +20,7 @@ import type { } from "../types"; export const NOW = Date.parse("2026-11-02T10:40:00Z"); -export const RUN_STARTED = "2026-10-27T08:00:00Z"; +export const TRACKING_SINCE = "2026-10-27T08:00:00Z"; const iso = (msAgo: number) => new Date(NOW - msAgo).toISOString(); const H = 3600_000; @@ -720,6 +720,7 @@ export function itemFor(repo: string, number: number): Item { authorClosedUnmerged: closedUn, additions: s.size?.[0] ?? 0, deletions: s.size?.[1] ?? 0, + changedFiles: isIssue ? null : filesFor(s).length, files: filesFor(s), ci, ciChecks: checks, @@ -727,11 +728,16 @@ export function itemFor(repo: string, number: number): Item { labels: isIssue ? ["bug"] : ["enhancement", ...(s.kind === "scope" ? ["needs-scope"] : [])], createdAt: iso(s.ageH * H + 26 * H), updatedAt: iso(s.ageH * H - 2 * H), + closedAt: null, + mergedAt: null, + mergedBy: null, related: s.related ?? [], classifications: d.classifications, stages: stagesFor(s, d), comments: [], decisionIds: seed ? [d.id] : [], + // mockApi fills this in from itemsFixtures + settled: { status: "unclassified", label: null, source: null, confidence: null, jevLabel: null, haikuLabel: null, flags: [] }, }; } @@ -747,7 +753,7 @@ const TITLE_PARTS: Record = { const TITLE_VERBS = ["fix crash when", "add support for", "improve performance of", "keep state after", "handle HiDPI in", "fix undo for", "add keyboard access to"]; const TITLE_TAILS = ["large documents", "multiple selections", "copy and paste", "dark theme", "RTL text", "touch input", "autosave"]; -function titleFor(repo: string, n: number) { +export function titleFor(repo: string, n: number) { const parts = TITLE_PARTS[repo] ?? TITLE_PARTS.default; return `${parts[n % parts.length]}: ${TITLE_VERBS[(n >> 2) % TITLE_VERBS.length]} ${TITLE_TAILS[(n >> 4) % TITLE_TAILS.length]}`; } @@ -774,11 +780,13 @@ export const SEARCH_POOL: SearchHit[] = (() => { export function progress(decisionsOpen: number): Progress { const r = rng(7); - const days = Math.ceil((NOW - Date.parse(RUN_STARTED)) / D); + const days = Math.ceil((NOW - Date.parse(TRACKING_SINCE)) / D); const repos: RepoProgress[] = REPO_OPEN.map(([repo, open]) => { const cls = 0.62 + r() * 0.36; const rev = 0.18 + r() * 0.3; const classified = Math.round(open * cls); + const secondOpinion = Math.round((open - classified) * 0.7); + const disagreement = Math.round((open - classified) * 0.1); const reviewed = Math.round(classified * rev); const take = Math.round(reviewed * (0.25 + r() * 0.15)); const hold = Math.round(reviewed * (0.1 + r() * 0.1)); @@ -794,7 +802,7 @@ export function progress(decisionsOpen: number): Progress { const startOpen = open + Math.round((done.mergedByPipeline + done.closedByPipeline + done.closedByOthers) * 0.82); const openTrend = Array.from({ length: days }, (_, i) => Math.round(startOpen - ((startOpen - open) * (i + 1)) / days + (r() - 0.5) * open * 0.01)); openTrend[days - 1] = open; - return { repo, funnel: { open, classified, reviewed, take, hold, close, waiting, batched }, done, decisionsOpen: 0, openTrend }; + return { repo, funnel: { open, classified, secondOpinion, disagreement, reviewed, take, hold, close, waiting, batched }, done, decisionsOpen: 0, openTrend }; }); for (const d of DECISIONS) if (!d.answer) { const rp = repos.find((x) => x.repo === d.repo); @@ -808,11 +816,12 @@ export function progress(decisionsOpen: number): Progress { return Math.round(28 + 52 * day + r() * 14); }); return { - runStartedAt: RUN_STARTED, + trackingSince: TRACKING_SINCE, now: new Date(NOW).toISOString(), - funnel: sum((x) => x.funnel, ["open", "classified", "reviewed", "take", "hold", "close", "waiting", "batched"]), + funnel: sum((x) => x.funnel, ["open", "classified", "secondOpinion", "disagreement", "reviewed", "take", "hold", "close", "waiting", "batched"]), done: sum((x) => x.done, ["mergedByPipeline", "closedByPipeline", "closedByOthers"]), perHour, + perHourPipeline: perHour.map((n) => Math.round(n * 0.55)), decisionsOpen, decisionsAnsweredToday: 64, repos, diff --git a/web/src/api/mock/insightFixtures.ts b/web/src/api/mock/insightFixtures.ts index f4514a09e..abe20047c 100644 --- a/web/src/api/mock/insightFixtures.ts +++ b/web/src/api/mock/insightFixtures.ts @@ -122,5 +122,5 @@ export function costReport(run = ""): CostReport { tokens: Math.round((900_000 + r() * 6_000_000) * k), usd: Math.round((0.4 + r() * 4.5) * k * 100) / 100, })); - return { runs: [{ id: RUN, from: "2026-10-27T08:00:00Z", to: "2026-11-02T10:30:00Z" }, { id: "pilot-1029", from: "2026-10-29T14:00:00Z", to: "2026-10-29T15:10:00Z" }], run, total, stages, repos, series, bucketSize: "hour" }; + return { runs: [{ id: RUN, from: "2026-10-27T08:00:00Z", to: "2026-11-02T10:30:00Z" }, { id: "pilot-1029", from: "2026-10-29T14:00:00Z", to: "2026-10-29T15:10:00Z" }], run, total, itemsClassified: Math.round(21000 * k), stages, repos, series, bucketSize: "hour" }; } diff --git a/web/src/api/mock/itemsFixtures.ts b/web/src/api/mock/itemsFixtures.ts new file mode 100644 index 000000000..daef88b81 --- /dev/null +++ b/web/src/api/mock/itemsFixtures.ts @@ -0,0 +1,90 @@ +// Fake rows for the Items browser and the settled label on the Item page. +import type { ItemFilter, ItemList, ItemListRow, Settled, SettledStatus, Stage, TypeLabel } from "../types"; +import { AUTHORS, NOW, REPOS, rng, titleFor } from "./fixtures"; + +const LABELS: TypeLabel[] = ["bugfix", "performance", "missing feature", "small extra", "plugin candidate", "infra"]; +const STATUSES: SettledStatus[] = ["settled", "waiting", "disagree", "unclassified"]; +const COMMENTS = ["Same here on the latest build, with a large document", "This also breaks copy and paste between windows", "Could we keep the old default behind a setting?", "Tested on Linux and Windows, works for me"]; +const H = 3600_000; + +export function settledFor(seed: number): Settled { + const r = rng(seed * 7919 + 13); + const jev = LABELS[Math.floor(r() * LABELS.length)]; + const top = Math.round((0.45 + r() * 0.55) * 100) / 100; + const flags = r() < 0.08 ? ["security"] : r() < 0.2 ? ["needs decision"] : []; + if (r() < 0.04) return { status: "unclassified", label: null, source: null, confidence: null, jevLabel: null, haikuLabel: null, flags: [] }; + if (top >= 0.9) return { status: "settled", label: jev, source: "jev", confidence: top, jevLabel: jev, haikuLabel: null, flags }; + const x = r(); + if (x < 0.35) return { status: "waiting", label: null, source: null, confidence: top, jevLabel: jev, haikuLabel: null, flags }; + const haiku = x < 0.85 ? jev : LABELS[(LABELS.indexOf(jev) + 1) % LABELS.length]; + return haiku === jev + ? { status: "settled", label: jev, source: "haiku", confidence: top, jevLabel: jev, haikuLabel: haiku, flags } + : { status: "disagree", label: null, source: null, confidence: top, jevLabel: jev, haikuLabel: haiku, flags }; +} + +const POOL: (ItemListRow & { comment: string })[] = (() => { + const r = rng(2024); + const out: (ItemListRow & { comment: string })[] = []; + for (const repo of REPOS.slice(0, 16)) + for (let i = 0; i < 40; i++) { + const number = 120 + Math.floor(r() * 4800); + if (out.some((o) => o.repo === repo && o.number === number)) continue; + const updatedH = Math.floor(r() * 24 * 40); + const st = r(); + const kind = r() > 0.45 ? "pr" : "issue"; + out.push({ + repo, number, kind, + state: st < 0.72 ? "open" : st < 0.86 && kind === "pr" ? "merged" : "closed", + title: titleFor(repo, number), + author: AUTHORS[Math.floor(r() * AUTHORS.length)][0], + createdAt: new Date(NOW - (updatedH + 24 + Math.floor(r() * 2000)) * H).toISOString(), + updatedAt: new Date(NOW - updatedH * H).toISOString(), + comments: Math.floor(r() * 9), + settled: settledFor(number), + stage: (r() < 0.1 ? (["reviewed", "take", "needs-decision", "hold"] as Stage[])[Math.floor(r() * 4)] : null), + snippet: null, + comment: COMMENTS[Math.floor(r() * COMMENTS.length)], + }); + } + return out; +})(); + +const mark = (text: string, word: string) => { + const k = text.toLowerCase().indexOf(word.toLowerCase()); + return k < 0 ? null : `${text.slice(0, k)}\u0002${text.slice(k, k + word.length)}\u0003${text.slice(k + word.length)}`; +}; + +export function itemList(f: ItemFilter): ItemList { + const words = (f.q ?? "").toLowerCase().replace(/["*]/g, "").split(/\s+/).filter((w) => w && !w.startsWith("-") && w !== "or"); + const base = POOL.filter((it) => { + if (f.repo?.length && !f.repo.includes(it.repo)) return false; + if (f.kind && it.kind !== f.kind) return false; + if ((f.state ?? "open") !== "all" && it.state !== (f.state ?? "open")) return false; + if (f.label && it.settled.label !== f.label) return false; + if (f.flag?.some((x) => !it.settled.flags.includes(x))) return false; + if (f.author && it.author.toLowerCase() !== f.author.toLowerCase()) return false; + if (f.since && it.updatedAt < f.since) return false; + return words.every((w) => `${it.title} ${it.comment}`.toLowerCase().includes(w)); + }); + const byStatus = Object.fromEntries(STATUSES.map((s) => [s, base.filter((it) => it.settled.status === s).length])) as Record; + const want = new Set((f.status ?? []).flatMap((s) => (s === "unsettled" ? ["waiting", "disagree"] : [s]))); + const rows = base.filter((it) => !want.size || want.has(it.settled.status)); + const sort = f.sort ?? (words.length ? "relevance" : "updated"); + const key = (it: ItemListRow): string | number => + sort === "number" ? it.number : sort === "created" ? it.createdAt : sort === "relevance" ? (it.title.toLowerCase().includes(words[0] ?? "") ? 1 : 0) : it.updatedAt; + rows.sort((a, b) => { + const x = key(a), y = key(b); + const c = typeof x === "number" ? x - (y as number) : x.localeCompare(y as string); + return f.desc === false ? c : -c; + }); + const from = f.offset ?? 0; + return { + total: rows.length, byStatus, run: "org-1102", + rows: rows.slice(from, from + (f.limit ?? 50)).map(({ comment, ...it }) => { + if (!words.length) return it; + const t = mark(it.title, words[0]); + const c = mark(comment, words[0]); + return { ...it, snippet: t ? { field: "title" as const, author: null, text: t } : c ? { field: "comment" as const, author: "larkspur-dev", text: c } : null }; + }), + }; +} diff --git a/web/src/api/mock/mockApi.ts b/web/src/api/mock/mockApi.ts index d01fe1393..7beda3836 100644 --- a/web/src/api/mock/mockApi.ts +++ b/web/src/api/mock/mockApi.ts @@ -5,6 +5,7 @@ import { setClock } from "../../lib/format"; import { createAdminMock } from "./adminMock"; import { promptsReport } from "../../../../src/prompts/index.ts"; import { classifierReport, costReport, disagreementList } from "./insightFixtures"; +import { itemList, settledFor } from "./itemsFixtures"; import { DECISIONS, MOCK_USERS, NOW, REPOS, SEARCH_POOL, THREADS, itemFor, permFor, progress, type MockRole } from "./fixtures"; const wait = (v: T, ms = 60) => new Promise((r) => setTimeout(() => r(structuredClone(v)), ms)); @@ -136,10 +137,11 @@ export function createMockApi(): Api { return wait(c, 30); }, }, - item: (repo, number) => wait(itemFor(repo, number)), + item: (repo, number) => wait({ ...itemFor(repo, number), settled: settledFor(number) }), + items: (f) => wait(itemList(f), 70), search(q) { const s = q.trim().toLowerCase(); - if (!s) return wait([]); + if (!s) return Promise.resolve([]); const ref = s.match(/^([a-z-]+)?#(\d+)$/); const hits = SEARCH_POOL.filter((h) => ref diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 277f09a56..3aac9b56b 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -156,18 +156,110 @@ export interface Item extends ItemRef { authorClosedUnmerged: number; additions: number; deletions: number; + /** PRs: how many files the PR changes, from the mirror; null when unknown. */ + changedFiles: number | null; + /** Per-file changes; empty when the mirror has none. */ files: ChangedFile[]; + /** "none" also when the mirror has no check data for the item. */ ci: CiState; ciChecks: { name: string; state: CiState; minutes: number }[]; mergeable: Mergeable; labels: string[]; createdAt: string; updatedAt: string; + closedAt: string | null; + mergedAt: string | null; + mergedBy: string | null; related: RelatedItem[]; classifications: Classification[]; stages: StageEntry[]; comments: ItemComment[]; decisionIds: string[]; + /** For the latest classification run. */ + settled: Settled; +} + +/** + * Settled type label for one classification run: Jev's label when its top + * probability is at least 0.9, else Haiku's when Haiku agrees with Jev. + * `waiting`: Jev unsure, Haiku hasn't answered; `disagree`: Haiku gave another label. + */ +export type SettledStatus = "settled" | "waiting" | "disagree" | "unclassified"; + +export interface Settled { + status: SettledStatus; + /** Set only when `status` is `settled`. */ + label: TypeLabel | null; + source: "jev" | "haiku" | null; + /** Jev's top probability. */ + confidence: number | null; + jevLabel: TypeLabel | null; + haikuLabel: TypeLabel | null; + /** Jev's flags when Jev is sure, otherwise every flag either classifier raised. */ + flags: string[]; +} + +/** Where a text query matched. `text` marks each match with U+0002 before and U+0003 after it. */ +export interface Snippet { + field: "title" | "body" | "comment"; + /** The comment's author. */ + author: string | null; + text: string; +} + +export type ItemSort = "relevance" | "updated" | "created" | "number"; + +/** `status: "unsettled"` stands for waiting and disagree together. */ +export type StatusFilter = SettledStatus | "unsettled"; + +export interface ItemFilter { + /** Full-text query: words (all must match), "quoted phrases", prefix*, -excluded, OR. */ + q?: string; + /** Only `text`; other search modes may be added. */ + mode?: "text"; + repo?: RepoName[]; + kind?: "pr" | "issue"; + /** Default `open`. */ + state?: ItemState | "all"; + /** Settled label. */ + label?: TypeLabel; + status?: StatusFilter[]; + /** Every flag listed must be set. */ + flag?: string[]; + author?: string; + /** Updated on or after this date (YYYY-MM-DD). */ + since?: string; + /** Default `relevance` with a query, else `updated`. */ + sort?: ItemSort; + /** Default true. */ + desc?: boolean; + limit?: number; + offset?: number; + /** Classification run; default the latest. */ + run?: string; +} + +export interface ItemListRow extends ItemRef { + kind: "pr" | "issue"; + state: ItemState; + title: string; + author: string; + createdAt: string; + updatedAt: string; + comments: number; + settled: Settled; + /** Latest pipeline stage. */ + stage: Stage | null; + /** With a text query only. */ + snippet: Snippet | null; +} + +export interface ItemList { + total: number; + rows: ItemListRow[]; + /** Matches per settled status, under every filter except `status`. */ + byStatus: Record; + run: string | null; } export interface SearchHit extends ItemRef { @@ -185,7 +277,12 @@ export interface Done { export interface Funnel { open: number; + /** Settled type label (see `Settled`). */ classified: number; + /** Jev unsure, Haiku hasn't answered yet. */ + secondOpinion: number; + /** Jev unsure and Haiku gave another label. */ + disagreement: number; reviewed: number; take: number; hold: number; @@ -199,17 +296,20 @@ export interface RepoProgress { funnel: Funnel; done: Done; decisionsOpen: number; - /** open items at the end of each day since the run started */ + /** open items at the end of each day since tracking began */ openTrend: number[]; } export interface Progress { - runStartedAt: string; + /** When tracking began; done counts and trends start here. */ + trackingSince: string; now: string; funnel: Funnel; done: Done; - /** items done per hour, oldest first, last 24 h */ + /** items closed or merged per hour by anyone, oldest first, last 24 h */ perHour: number[]; + /** the same, by the pipeline only */ + perHourPipeline: number[]; decisionsOpen: number; decisionsAnsweredToday: number; repos: RepoProgress[]; @@ -324,6 +424,19 @@ export interface OverrideInput { note?: string; } +/** The Label stage for one repo: approval and what the plan holds. */ +export interface RepoLabels { + approved: boolean; + approvedBy: string | null; + approvedAt: string | null; + /** open items that would get labels */ + toAdd: number; + /** open items with nothing to add: already labelled or not settled */ + skipped: number; + /** open items with a different type label set by a person */ + conflicts: number; +} + export interface TrackedRepo { name: RepoName; tracked: boolean; @@ -332,6 +445,8 @@ export interface TrackedRepo { /** issue and PR rows in the mirror */ mirrored: number; syncedAt: string | null; + /** null for repos that are not tracked */ + labels: RepoLabels | null; } export interface AccessEntry { @@ -482,6 +597,8 @@ export interface CostReport { /** A run id, or "" for all runs. */ run: string; total: UsageTotals; + /** Distinct items with a classification in the run (or all runs); `total.items` counts an item once per model. */ + itemsClassified: number; stages: ({ stage: string; model: string } & UsageTotals)[]; repos: ({ repo: string } & UsageTotals)[]; /** Spend per time bucket; `bucket` is an ISO hour or day. */ diff --git a/web/src/modules/admin/access.tsx b/web/src/modules/admin/access.tsx index 49d585bac..3caf4eb46 100644 --- a/web/src/modules/admin/access.tsx +++ b/web/src/modules/admin/access.tsx @@ -260,11 +260,15 @@ function Sessions({ sessions }: { sessions: SessionInfo[] }) { ); } +// Rows written before the role was renamed say "admin" for operator. +const ROLE_KEYS = new Set(["role", "from", "to"]); +const detailValue = (k: string, v: unknown) => (ROLE_KEYS.has(k) && v === "admin" ? "operator" : typeof v === "object" ? JSON.stringify(v) : String(v)); + const detailText = (d: AuditEntry["details"]) => d ? Object.entries(d) .filter(([, v]) => v !== null && v !== undefined) - .map(([k, v]) => `${k}: ${typeof v === "object" ? JSON.stringify(v) : String(v)}`) + .map(([k, v]) => `${k}: ${detailValue(k, v)}`) .join(" · ") : ""; diff --git a/web/src/modules/admin/repos.tsx b/web/src/modules/admin/repos.tsx index 76ff51008..1eeaa8917 100644 --- a/web/src/modules/admin/repos.tsx +++ b/web/src/modules/admin/repos.tsx @@ -30,7 +30,7 @@ function ReposView(_: ViewProps) { return (

- Sync, the pipeline and every page work on tracked repos only. Switching a repo on takes effect at the next sync. Rows of an untracked repo stay in the mirror but are hidden. + Sync, the pipeline and every page work on tracked repos only. Switching a repo on takes effect at the next sync. Rows of an untracked repo stay in the mirror but are hidden. The Label stage writes labels to GitHub only for repos approved here; the plan counts show what it would do.

@@ -84,13 +84,38 @@ function Toggle({ r, write }: { r: TrackedRepo; write: Write }) { return void write.run(key, () => api.repoAdmin.untrack(r.name))} />; } +function Approval({ r, write }: { r: TrackedRepo; write: Write }) { + const api = useApi(); + const l = r.labels; + if (!l) return –; + const key = `labels:${r.name}`; + return ( +
+ {l.approved ? ( + + Approved + + ) : ( + Not approved + )} + {l.approved ? ( + void write.run(key, () => api.repoAdmin.approveLabels(r.name, false))} /> + ) : ( + void write.run(key, () => api.repoAdmin.approveLabels(r.name, true))} /> + )} +
+ ); +} + +const planText = (r: TrackedRepo) => (r.labels ? `${num(r.labels.toAdd)} to add · ${num(r.labels.skipped)} skipped · ${num(r.labels.conflicts)} conflicts` : "–"); + const synced = (r: TrackedRepo) => (r.syncedAt ? `${ago(r.syncedAt, false)}` : "never"); const maybe = (n: number | null) => (n === null ? "–" : num(n)); function Table({ rows, write }: { rows: TrackedRepo[]; write: Write }) { return (
- +
Repo @@ -99,6 +124,8 @@ function Table({ rows, write }: { rows: TrackedRepo[]; write: Write }) { Open issuesRows in mirrorLast synced + Labels plan + @@ -113,6 +140,10 @@ function Table({ rows, write }: { rows: TrackedRepo[]; write: Write }) { + + @@ -137,6 +168,12 @@ function Cards({ rows, write }: { rows: TrackedRepo[]; write: Write }) {
{maybe(r.openPrs)} PRs · {maybe(r.openIssues)} issues · synced {synced(r)}
+ {r.labels && ( +
+ Labels: {planText(r)} + +
+ )} diff --git a/web/src/modules/classifiers/index.tsx b/web/src/modules/classifiers/index.tsx index 2995400c7..4a230632a 100644 --- a/web/src/modules/classifiers/index.tsx +++ b/web/src/modules/classifiers/index.tsx @@ -93,8 +93,8 @@ function Disagreements({ r, label, band, setFilter }: { r: ClassifierReport; lab - - + + @@ -103,11 +103,24 @@ function Disagreements({ r, label, band, setFilter }: { r: ClassifierReport; lab - - + - @@ -168,6 +181,11 @@ function Classifiers(_: ViewProps) { options={cur.pairs.map((p) => ({ value: `${p.a}|${p.b}`, label: `${p.a} vs ${p.b} (${num(p.items)})` }))} /> + {run && run !== r.run && ( +

+ There is no run {run}. Showing the latest run, {r.run}. +

+ )}

Agreement on the type label, per run. Rows are grouped by {r.a}'s answer.

@@ -181,8 +199,10 @@ function Classifiers(_: ViewProps) { ({ key: x.label, n: x.n, agree: x.agree }))} picked={label} onPick={(k) => set({ label: label === k ? "" : k })} /> - - ({ key: x.repo, n: x.n, agree: x.agree }))} /> + +
+ ({ key: x.repo, n: x.n, agree: x.agree }))} /> +
diff --git a/web/src/modules/cost/index.tsx b/web/src/modules/cost/index.tsx index 1396d770b..6c90dce55 100644 --- a/web/src/modules/cost/index.tsx +++ b/web/src/modules/cost/index.tsx @@ -4,6 +4,7 @@ import { useQuery } from "../../api/client"; import type { CostReport, UsageTotals } from "../../api/types"; import type { FeatureModule, ViewProps } from "../../registry/types"; import { num } from "../../lib/format"; +import { cn } from "../../ui/cn"; import { Block, Select, Stat, Th } from "../insight/parts"; const tokens = (u: UsageTotals) => u.input + u.output + u.cacheRead + u.cacheWrite; @@ -44,7 +45,7 @@ function UsageTable({ rows, name, subName }: { rows: Row[]; name: string; subNam - + @@ -86,12 +87,45 @@ function SpendChart({ r }: { r: CostReport }) { ); } +type ModelTotals = { model: string; items: number; usd: number | null }; + +// Totals per model across stages. USD stays null for a model that never reported a price. +function byModel(r: CostReport): ModelTotals[] { + const m = new Map(); + for (const s of r.stages) { + const cur = m.get(s.model) ?? { model: s.model || "unknown model", items: 0, usd: null }; + cur.items += s.items; + if (s.usd !== null) cur.usd = (cur.usd ?? 0) + s.usd; + m.set(s.model, cur); + } + return [...m.values()].sort((a, b) => b.items - a.items); +} + +// Spend per item counts only the items of models that report a price. +function SpendSub({ models }: { models: ModelTotals[] }) { + const priced = models.filter((m) => m.usd !== null); + const unpriced = models.filter((m) => m.usd === null); + return ( + <> + {priced.map((m) => ( +
+ {m.model}: {perUsd(m.usd, m.items)} per item +
+ ))} + {unpriced.length > 0 &&
{unpriced.map((m) => m.model).join(", ")}: price not reported
} + + ); +} + function Cost(_: ViewProps) { const [sp, setSp] = useSearchParams(); const run = sp.get("run") ?? ""; const { data: r } = useQuery(`cost:${run}`, (api) => api.cost(run)); if (!r) return
Loading…
; const t = r.total; + const models = byModel(r); + // Each model's calls count the same item again, so the headline uses distinct classified items. + const items = r.itemsClassified || Math.max(0, ...models.map((m) => m.items)); return (
@@ -107,15 +141,17 @@ function Cost(_: ViewProps) {

Token use per agent call. USD appears where the agent reported a cost.

- - - + `${m.model} ${num(m.items)}`).join(" · ")} /> + + } />
- - - + {r.series.length >= 3 && ( + + + + )} ({ key: s.stage, sub: s.model, u: s }))} /> diff --git a/web/src/modules/item/index.tsx b/web/src/modules/item/index.tsx index 3229932b1..092713f27 100644 --- a/web/src/modules/item/index.tsx +++ b/web/src/modules/item/index.tsx @@ -13,10 +13,11 @@ import { FlagIcon, CircleCheckIcon, CircleSlashIcon, + MessageSquareIcon, type LucideIcon, } from "lucide-react"; import { useQuery } from "../../api/client"; -import type { CiState, Classification, Item, Stage, Tier } from "../../api/types"; +import type { CiState, Classification, Item, ItemComment, Stage, Tier } from "../../api/types"; import type { FeatureModule, ViewProps } from "../../registry/types"; import { Slot } from "../../registry/Slot"; import { Avatar } from "../../ui/Avatar"; @@ -28,6 +29,7 @@ import { ago, num } from "../../lib/format"; import { KindTag, tallyOf } from "../decisions/parts"; import { Markdown, Collapsible } from "../../ui/Markdown"; import { useIsPhone } from "../../shell/useMedia"; +import { SettledBadge } from "../items"; function useItem(params: ViewProps["params"]) { const repo = params.repo!; @@ -91,6 +93,11 @@ function ItemMain({ params }: ViewProps) { )} + {it.comments.length > 0 && ( +
+ +
+ )}
); @@ -142,6 +149,9 @@ function Properties({ it }: { it: Item }) { const total = it.additions + it.deletions; const passing = it.ciChecks.filter((c) => c.state === "passing").length; const [CiIcon, ciCls] = CI_ICON[it.ci]; + // The mirror records checks and mergeability only for open PRs; without them the rows are left out. + const showCi = it.kind === "pr" && it.ci !== "none"; + const showMergeable = it.kind === "pr" && it.state === "open" && it.mergeable !== "unknown"; return (
@@ -151,34 +161,48 @@ function Properties({ it }: { it: Item }) { {it.authorMerged} merged · {it.authorClosedUnmerged} closed unmerged + + + {it.settled.flags.map((f) => ( + + {f} + + ))} + {it.kind === "pr" ? ( <> +{num(it.additions)} −{num(it.deletions)} - {it.files.length} files + {it.changedFiles !== null && ( + + {num(it.changedFiles)} {it.changedFiles === 1 ? "file" : "files"} + + )} {sizeBucket(total)} ) : ( Issue )} - - - {it.ci === "none" ? "No checks" : it.ci[0].toUpperCase() + it.ci.slice(1)} - - {it.ciChecks.length > 0 && ( - - {passing} of {it.ciChecks.length} passed + {showCi && ( + + + {it.ci[0]!.toUpperCase() + it.ci.slice(1)} - )} - - - - {it.mergeable === "clean" ? "No conflicts" : it.mergeable === "conflicts" ? "Has conflicts" : "Unknown"} - - + {it.ciChecks.length > 0 && ( + + {passing} of {it.ciChecks.length} passed + + )} + + )} + {showMergeable && ( + + {it.mergeable === "clean" ? "No conflicts" : "Has conflicts"} + + )} {it.labels.map((l) => ( {l} @@ -203,6 +227,29 @@ function agreement(cls: Classification[]) { return n === cls.length ? "all agree on type" : `${n} of ${cls.length} agree on type`; } +const likelihood = (p: number) => (p < 0.2 ? "unlikely" : p < 0.5 ? "possible" : p < 0.8 ? "likely" : "very likely"); +const percent = (p: number) => `${Math.round(p * 100)}%`; + +// Classifiers that score labels write "bugfix 0.84; security 0.03; needs decision 0.27": +// the chosen label's probability, then flag probabilities. Other reasons are prose. +function Reason({ reason }: { reason: string }) { + const parts = reason.split(";").map((x) => /^\s*([a-z][a-z -]*?)\s+(0(?:\.\d+)?|1(?:\.0+)?)\s*$/i.exec(x)); + if (!parts.length || parts.some((m) => !m)) return <>{reason}; + const [label, ...flags] = parts.map((m) => ({ name: m![1]!, p: Number(m![2]) })); + return ( + <> + + {label!.name} ({percent(label!.p)}) + + {flags.length > 0 && ( + + {flags.map((f) => `${f.name[0]!.toUpperCase()}${f.name.slice(1)}: ${likelihood(f.p)} (${percent(f.p)})`).join(" · ")} + + )} + + ); +} + const WANT: Record = { yes: "text-ok", no: "text-bad", unclear: "text-warn" }; function Verdicts({ cls }: { cls: Classification[] }) { @@ -223,7 +270,9 @@ function Verdicts({ cls }: { cls: Classification[] }) { {ago(c.at)} {c.reference &&
Reference: {c.reference}
} -

{c.reason}

+
+ +
))} @@ -232,8 +281,8 @@ function Verdicts({ cls }: { cls: Classification[] }) { { label: "Type", render: (c) => c.typeLabel, off: (c) => c.typeLabel !== typeMaj }, { label: "Want", render: (c) => {c.want}, off: (c) => c.want !== wantMaj }, { label: "Reference", render: (c) => c.reference ?? none }, - { label: "Topics", render: (c) => c.topics }, - { label: "Reason", render: (c) => {c.reason} }, + { label: "Topics", render: (c) => (c.topics === "many" ? "several topics" : "one topic") }, + { label: "Reason", render: (c) => }, ]; return (
@@ -280,23 +329,79 @@ const STAGE: Record = { "fixed-by-us": ["Fixed by us", CircleCheckIcon], }; +type Event = { label: string; Icon: LucideIcon; at: string; by: string; note: string | null }; + +// GitHub's own events from the mirror, merged with the pipeline's stages. +// A pipeline merge or close already says who did it, so GitHub's copy is left out. +function events(it: Item): Event[] { + const out: Event[] = [{ label: "Opened", Icon: it.kind === "pr" ? GitPullRequestIcon : CircleDotIcon, at: it.createdAt, by: it.author, note: null }]; + for (const s of it.stages) { + const [label, Icon] = STAGE[s.stage]; + out.push({ label, Icon, at: s.at, by: s.by, note: s.note }); + } + const has = (st: Stage) => it.stages.some((s) => s.stage === st); + if (it.state === "merged" && it.mergedAt && !has("merged")) out.push({ label: "Merged", Icon: GitMergeIcon, at: it.mergedAt, by: it.mergedBy ?? "", note: null }); + else if (it.state === "closed" && it.closedAt && !has("closed")) out.push({ label: "Closed", Icon: CircleSlashIcon, at: it.closedAt, by: "", note: null }); + return out.filter((e) => e.at).sort((a, b) => Date.parse(a.at) - Date.parse(b.at)); +} + function Timeline({ it }: { it: Item }) { + const evs = events(it); return (
    - - {it.stages.map((s, i) => { - const last = i === it.stages.length - 1; - const [label, Icon] = STAGE[s.stage]; + {evs.length > 1 && } + {evs.map((e, i) => { + const last = i === evs.length - 1 && evs.length > 1; return (
  1. - + - {label} by {s.by} - {s.note && · {s.note}} + {e.label} + {e.by && by {e.by}} + {e.note && · {e.note}} - {ago(s.at)} ago + {ago(e.at)} ago +
  2. + ); + })} +
+ ); +} + +const REVIEW: Record = { + APPROVED: ["approved", "ok"], + CHANGES_REQUESTED: ["requested changes", "bad"], + COMMENTED: ["reviewed", "neutral"], + DISMISSED: ["review dismissed", "neutral"], +}; + +// GitHub comments and reviews, oldest first. Bodies are untrusted: the same Markdown renderer as the description. +function Discussion({ comments }: { comments: ItemComment[] }) { + return ( +
    + {comments.map((c) => { + const review = c.kind === "review" ? (REVIEW[c.reviewState ?? ""] ?? REVIEW.COMMENTED!) : null; + return ( +
  1. +
    + {c.author ? : } + {c.author || "ghost"} + {review && {review[0]}} + + {c.at ? ago(c.at, false) : ""} + +
    +
    + {c.body.trim() ? ( + + + + ) : ( +

    No text.

    + )} +
  2. ); })} diff --git a/web/src/modules/items/index.tsx b/web/src/modules/items/index.tsx new file mode 100644 index 000000000..8b3e215df --- /dev/null +++ b/web/src/modules/items/index.tsx @@ -0,0 +1,378 @@ +// Items: every issue and PR in the tracked repos, with full-text search and the +// settled type label. Every filter lives in the URL. +import { useEffect, useState } from "react"; +import { Link } from "react-router-dom"; +import { Popover } from "radix-ui"; +import { ChevronDownIcon, CircleDotIcon, GitMergeIcon, GitPullRequestIcon, ListIcon, SearchIcon, CircleSlashIcon, ShieldAlertIcon, FlagIcon } from "lucide-react"; +import { useQuery } from "../../api/client"; +import type { ItemFilter, ItemList, ItemListRow, ItemSort, Settled, SettledStatus, Snippet, Stage, StatusFilter, TypeLabel } from "../../api/types"; +import type { FeatureModule, ViewProps } from "../../registry/types"; +import { Badge, type Tone } from "../../ui/Badge"; +import { RefLink } from "../../ui/RefLink"; +import { cn } from "../../ui/cn"; +import { ago, num } from "../../lib/format"; +import { useIsPhone } from "../../shell/useMedia"; +import { Block, ErrorLine, Page, Pager, selectCls, TextInput, useUrlState } from "../admin/parts"; + +const PAGE = 50; +const LABELS: TypeLabel[] = ["bugfix", "performance", "missing feature", "small extra", "plugin candidate", "infra"]; +const STATUS: Record = { + settled: ["Settled", "ok"], + waiting: ["Waiting for a second opinion", "warn"], + disagree: ["Classifiers disagree", "bad"], + unclassified: ["Not classified", "neutral"], +}; +const STATUS_KEYS = Object.keys(STATUS) as SettledStatus[]; +const FLAGS: [string, string][] = [["security", "Security"], ["needs decision", "Needs a decision"]]; +const SORTS: [ItemSort, string][] = [["relevance", "Relevance"], ["updated", "Updated"], ["created", "Created"], ["number", "Number"]]; +const STATES = [["open", "Open"], ["closed", "Closed"], ["merged", "Merged"], ["all", "Any state"]] as const; +const STAGE: Record = { + classified: "Classified", reviewed: "Reviewed", take: "Taken", hold: "Held", close: "To close", "needs-decision": "Waiting for a decision", + batched: "In a batch", merged: "Merged by the pipeline", closed: "Closed by the pipeline", "fixed-by-us": "Fixed by us", +}; + +const csv = (v: string | undefined) => (v ? v.split(",").filter(Boolean) : []); + +function useFilter() { + const { state, update } = useUrlState(); + const q = state.q?.trim() || undefined; + const sort = SORTS.some(([k]) => k === state.sort) ? (state.sort as ItemSort) : undefined; + const filter: ItemFilter = { + q, + repo: csv(state.repo), + kind: state.kind === "pr" || state.kind === "issue" ? state.kind : undefined, + state: STATES.some(([k]) => k === state.state) ? (state.state as ItemFilter["state"]) : "open", + label: LABELS.includes(state.label as TypeLabel) ? (state.label as TypeLabel) : undefined, + status: csv(state.status).filter((s): s is StatusFilter => s === "unsettled" || STATUS_KEYS.includes(s as SettledStatus)), + flag: csv(state.flag).filter((f) => FLAGS.some(([k]) => k === f)), + author: state.author?.trim() || undefined, + since: /^\d{4}-\d{2}-\d{2}$/.test(state.since ?? "") ? state.since : undefined, + sort: sort === "relevance" && !q ? undefined : sort, + desc: state.desc !== "0", + limit: PAGE, + offset: Math.max(0, Number(state.offset) || 0), + }; + return { filter, update }; +} + +function ItemsView(_: ViewProps) { + const { filter, update } = useFilter(); + const { data, error, loading } = useQuery(`items:${JSON.stringify(filter)}`, (api) => api.items(filter)); + const phone = useIsPhone(); + const set = (patch: Record) => update({ ...patch, offset: null }); + const unsettled = data ? data.byStatus.waiting + data.byStatus.disagree : undefined; + const statusOn = (s: StatusFilter) => filter.status?.includes(s) ?? false; + + return ( + }> +
    + set({ q: q || null, sort: null })} /> + + + set({ repo: r.length ? r.join(",") : null })} /> + + + +
    + +
    +
    + + + {STATUS_KEYS.map((s) => ( + + ))} +
    + {FLAGS.map(([k, l]) => { + const on = filter.flag?.includes(k) ?? false; + const next = on ? filter.flag!.filter((f) => f !== k) : [...(filter.flag ?? []), k]; + return ( + + ); + })} + set({ author: v || null })} placeholder="Author login" label="Author" className="w-36" /> + +
    + + {filter.q ? `Matches for “${filter.q}”` : "Items"}} + aside={loading && data ? "Updating…" : phone ? undefined : filter.q ? 'Words must all match; use "a phrase", prefix*, -word, OR.' : undefined} + > + + {data && data.rows.length === 0 &&

    No item matches these filters.

    } + {data && data.rows.length > 0 && (phone ? :
Label approval
{synced(r)} {planText(r)} + +
Item Title{r.a}{r.b}{r.a}{r.b}
{d.title} + + {d.title} + {/* Phones: the two answers under the title instead of in their own columns. */} +
+
{r.a}
+
+ {d.a.label} {prob(d.a.prob)} +
+
{r.b}
+
+ {d.b.label} {prob(d.b.prob)} +
+
+
{d.a.label} {prob(d.a.prob)} + {d.b.label} {prob(d.b.prob)}
{num(u.output)} {num(u.cacheRead)} {num(u.cacheWrite)}{usd(u.usd)}{u.usd === null ? "price not reported" : usd(u.usd)} {per(tokens(u), u.items)} {perUsd(u.usd, u.items)} {wall(u.wallSeconds)}
)} + {data && update({ offset: o ? String(o) : null })} />} + + + ); +} + +function Summary({ list, filter }: { list: ItemList; filter: ItemFilter }) { + const all = Object.values(list.byStatus).reduce((a, b) => a + b, 0); + return ( + <> + {num(list.total)} {list.total === 1 ? "item" : "items"} + {filter.status?.length ? ` of ${num(all)}` : ""} · {num(list.byStatus.settled)} settled, {num(list.byStatus.waiting)} waiting for a second opinion,{" "} + {num(list.byStatus.disagree)} disagreements + {list.run ? ` (run ${list.run})` : ""} + + ); +} + +function DebouncedInput({ value, onChange, placeholder, label, className, icon }: { value: string; onChange: (v: string) => void; placeholder: string; label: string; className?: string; icon?: boolean }) { + const [v, setV] = useState(value); + useEffect(() => setV(value), [value]); + useEffect(() => { + if (v.trim() === value) return; + const t = setTimeout(() => onChange(v.trim()), 300); + return () => clearTimeout(t); + }, [v, value, onChange]); + return ( + + ); +} + +function QueryField({ value, onChange }: { value: string; onChange: (v: string) => void }) { + return ; +} + +function RepoPicker({ value, onChange }: { value: string[]; onChange: (v: string[]) => void }) { + const { data: repos } = useQuery("repos", (api) => api.repos()); + const label = value.length === 0 ? "Every repo" : value.length === 1 ? value[0] : `${value.length} repos`; + return ( + + + + + + + {value.length > 0 && ( + + )} + {repos?.map((r) => ( + + ))} + + + + ); +} + +/** A snippet with its matches marked (U+0002 … U+0003 from the server). */ +function SnippetText({ s }: { s: Snippet }) { + const parts = s.text.split(/(\u0002[^\u0003]*\u0003)/); + return ( + + {s.field === "comment" ? `Comment${s.author ? ` by ${s.author}` : ""}: ` : s.field === "title" ? "Title: " : ""} + {parts.map((p, i) => + p.startsWith("\u0002") ? ( + + {p.slice(1, -1)} + + ) : ( + {p} + ), + )} + + ); +} + +function StateIcon({ it }: { it: ItemListRow }) { + if (it.state === "merged") return ; + if (it.state === "closed") return ; + return it.kind === "pr" ? : ; +} + +/** The settled label, or why there is none. */ +export function SettledBadge({ s, detail }: { s: Settled; detail?: boolean }) { + const conf = s.confidence !== null ? ` ${s.confidence.toFixed(2)}` : ""; + if (s.status === "settled") + return ( + + {s.label} + {s.source === "jev" ? `Jev${conf}` : `Jev${conf} + Haiku`} + + ); + const [text, tone] = STATUS[s.status]; + return ( + + {s.status === "waiting" ? "Waiting" : s.status === "disagree" ? "Disagree" : text} + {s.jevLabel && ( + + Jev {s.jevLabel} + {conf} + {s.status === "disagree" ? ` · Haiku ${s.haikuLabel}` : ""} + + )} + {detail && {text}} + + ); +} + +function Flags({ flags }: { flags: string[] }) { + if (!flags.length) return –; + return ( + + {flags.includes("security") && ( + }> + security + + )} + {flags.includes("needs decision") && ( + }> + decision + + )} + + ); +} + +function Table({ rows }: { rows: ItemListRow[] }) { + return ( +
+
+ + + + + + + + + + + + {rows.map((it) => ( + + + + + + + + + ))} + +
ItemAuthorUpdatedTypeFlagsStage
+
+ + + + {it.title} + +
+ {it.snippet && it.snippet.field !== "title" && ( +
+ +
+ )} +
{it.author} + {it.updatedAt ? `${ago(it.updatedAt)} ago` : "–"} + + + + + {it.stage ? STAGE[it.stage] : –}
+
+ ); +} + +function Cards({ rows }: { rows: ItemListRow[] }) { + return ( +
    + {rows.map((it) => ( +
  • + +
    + + + {it.repo}#{it.number} + + {it.author} + {it.updatedAt ? `${ago(it.updatedAt)} ago` : ""} +
    +
    {it.title}
    + {it.snippet && it.snippet.field !== "title" && ( +
    + +
    + )} +
    + + {it.settled.flags.length > 0 && } + {it.stage && {STAGE[it.stage]}} +
    + +
  • + ))} +
+ ); +} + +export const itemsModule: FeatureModule = { + id: "items", + permission: "viewer", + nav: { label: "Items", icon: ListIcon, to: "/items", group: "work", order: 2 }, + commands: [{ id: "go-items", keys: "g i", label: "Go to items", group: "Go to" }], + routes: [{ path: "items", view: { id: "items", title: "Items", panels: [{ id: "main", title: "Items", component: ItemsView, defaultSize: 100 }] } }], +}; diff --git a/web/src/modules/progress/charts.tsx b/web/src/modules/progress/charts.tsx index f140dc512..4f1601bd3 100644 --- a/web/src/modules/progress/charts.tsx +++ b/web/src/modules/progress/charts.tsx @@ -2,6 +2,7 @@ // marks, mono labels. Colours come from the --st-c* slots (validated for // colour-vision separation on both theme surfaces). import { useLayoutEffect, useRef, useState } from "react"; +import { Link } from "react-router-dom"; import type { Done, Funnel } from "../../api/types"; import { cn } from "../../ui/cn"; import { num, pct } from "../../lib/format"; @@ -45,7 +46,7 @@ export function StackBar({ parts, height = 10, total }: { parts: { label: string
setHover(i)} role="img" aria-label={`${p.label}: ${num(p.value)}`} @@ -72,6 +73,7 @@ export function DoneSplit({ done }: { done: Done }) { /** Funnel for open items: the three filter steps as bars, then how the reviewed ones split. */ export function FunnelChart({ f }: { f: Funnel }) { + const share = (n: number) => `${f.open ? (n / f.open) * 100 : 0}%`; const steps = [ { label: "Open", value: f.open, note: "" }, { label: "Classified", value: f.classified, note: pct(f.classified, f.open) }, @@ -79,32 +81,53 @@ export function FunnelChart({ f }: { f: Funnel }) { ]; const outcome = OUTCOMES.map((o) => ({ ...o, value: f[o.key] })); const routed = outcome.reduce((a, o) => a + o.value, 0); + const row = "grid grid-cols-[76px_1fr_64px] md:grid-cols-[96px_1fr_88px] items-center gap-3"; + const notStarted = not started yet; return (
{steps.map((s) => ( -
+
{s.label} -
-
-
+ {s.value || s.label === "Open" ? ( +
+
+
+ ) : ( + notStarted + )} {num(s.value)} {s.note && {s.note}}
))} -
+
Routed -
- -
+ {routed ? ( +
+ +
+ ) : ( + notStarted + )} {num(routed)}
-
- -
+ {(f.secondOpinion > 0 || f.disagreement > 0) && ( +

+ Not yet classified: {num(f.secondOpinion)} waiting for a second opinion,{" "} + {num(f.disagreement)} where the two classifiers disagree.{" "} + + See them + +

+ )} + {routed > 0 && ( +
+ +
+ )}
); } @@ -172,6 +195,8 @@ export function Throughput({ perHour, nowIso }: { perHour: number[]; nowIso: str export function Sparkline({ values, className }: { values: number[]; className?: string }) { const W = 72; const H = 18; + // one day of tracking has no trend yet + if (values.length < 2) return from today; const min = Math.min(...values); const max = Math.max(...values); const pts = values.map((v, i) => `${(i / (values.length - 1)) * W},${H - 2 - ((v - min) / (max - min || 1)) * (H - 4)}`).join(" "); diff --git a/web/src/modules/progress/index.tsx b/web/src/modules/progress/index.tsx index 8b9b957b5..7644333bd 100644 --- a/web/src/modules/progress/index.tsx +++ b/web/src/modules/progress/index.tsx @@ -33,28 +33,36 @@ function Block({ title, aside, children, className, flush }: { title: string; as ); } +const NOT_STARTED = not started yet; + function Overview(_: ViewProps) { const { data: p } = useQuery("progress", (api) => api.progress()); const phone = useIsPhone(); if (!p) return
Loading…
; const done = doneTotal(p.done); - const avg = Math.round(p.perHour.reduce((a, b) => a + b, 0) / p.perHour.length); - const startOpen = p.repos.reduce((a, r) => a + r.openTrend[0], 0); - const days = Math.ceil((Date.parse(p.now) - Date.parse(p.runStartedAt)) / 86400_000); + const ours = p.done.mergedByPipeline + p.done.closedByPipeline; + const lastDay = p.perHour.reduce((a, b) => a + b, 0); + const lastDayOurs = p.perHourPipeline.reduce((a, b) => a + b, 0); + const startOpen = p.repos.reduce((a, r) => a + (r.openTrend[0] ?? 0), 0); + const since = p.trackingSince.slice(0, 10); return (

Progress

- Started {p.runStartedAt.slice(0, 10)} · day {days} · {p.repos.length} repos + Tracking since {since} · {p.repos.length} repos
- from {num(startOpen)} at run start} /> - - a + b, 0))} in the last 24 h`} /> + {num(startOpen)} when tracking began} /> + +
- + - - + + {done ? :

Nothing closed yet.

} {DONE_PARTS.map((d) => ( @@ -82,7 +90,7 @@ function Overview(_: ViewProps) { {d.label} - + ))} @@ -91,7 +99,7 @@ function Overview(_: ViewProps) { - + @@ -107,14 +115,16 @@ type SortKey = "repo" | "open" | "done" | "decisions" | "reviewed"; function RepoTable({ p }: { p: Progress }) { const [sort, setSort] = useState<{ k: SortKey; desc: boolean }>({ k: "open", desc: true }); - const val = (r: RepoProgress): number | string => ({ repo: r.repo, open: r.funnel.open, done: doneTotal(r.done), decisions: r.decisionsOpen, reviewed: r.funnel.reviewed / r.funnel.open })[sort.k]; + const val = (r: RepoProgress): number | string => ({ repo: r.repo, open: r.funnel.open, done: doneTotal(r.done), decisions: r.decisionsOpen, reviewed: r.funnel.open ? r.funnel.reviewed / r.funnel.open : 0 })[sort.k]; const rows = [...p.repos].sort((a, b) => { const x = val(a); const y = val(b); const c = typeof x === "string" ? x.localeCompare(y as string) : x - (y as number); return sort.desc ? -c : c; }); - const maxDone = Math.max(...p.repos.map((r) => doneTotal(r.done))); + const maxDone = Math.max(1, ...p.repos.map((r) => doneTotal(r.done))); + const routedAny = OUTCOMES.some((o) => p.funnel[o.key] > 0); + const share = (n: number, d: number) => `${d ? (n / d) * 100 : 0}%`; const Th = ({ k, children, className, right }: { k?: SortKey; children: ReactNode; className?: string; right?: boolean }) => ( - + - + @@ -164,21 +174,19 @@ function RepoTable({ p }: { p: Progress }) { - +
{num(p.done[d.key])}{d.key !== "closedByOthers" && !ours ? NOT_STARTED : num(p.done[d.key])} {pct(p.done[d.key], done)}
{k ? ( @@ -139,14 +149,14 @@ function RepoTable({ p }: { p: Progress }) { Classified / reviewed RoutedRouted{routedAny ? "" : " · not started yet"} Done Waiting Open, 7 daysOpen, by day
-
-
+
+
{pct(f.classified, f.open)} / {pct(f.reviewed, f.open)}
- ({ ...o, value: f[o.key] }))} height={6} /> - {routedAny ? ({ ...o, value: f[o.key] }))} height={6} /> : –}
-
+
({ ...x, value: r.done[x.key] }))} height={6} />
@@ -209,11 +217,15 @@ function RepoCards({ p }: { p: Progress }) { {r.decisionsOpen > 0 && {r.decisionsOpen} waiting} {num(r.funnel.open)} open
-
- ({ ...o, value: r.funnel[o.key] }))} height={5} /> -
+ {OUTCOMES.some((o) => r.funnel[o.key] > 0) && ( +
+ ({ ...o, value: r.funnel[o.key] }))} height={5} /> +
+ )}
- {pct(r.funnel.reviewed, r.funnel.open)} reviewed + + {pct(r.funnel.classified, r.funnel.open)} classified{r.funnel.reviewed ? ` · ${pct(r.funnel.reviewed, r.funnel.open)} reviewed` : ""} + {num(doneTotal(r.done))} done
diff --git a/web/src/registry/index.ts b/web/src/registry/index.ts index 65191b69d..0b88fe9fc 100644 --- a/web/src/registry/index.ts +++ b/web/src/registry/index.ts @@ -4,10 +4,11 @@ import type { FeatureModule } from "./types"; import { decisionsModule } from "../modules/decisions"; import { itemModule } from "../modules/item"; import { progressModule } from "../modules/progress"; +import { itemsModule } from "../modules/items"; import { classifiersModule } from "../modules/classifiers"; import { costModule } from "../modules/cost"; import { accessModule, contributorsModule, reposModule } from "../modules/admin"; import { aboutModule } from "../modules/about"; import { promptsModule } from "../modules/prompts"; -export const modules: FeatureModule[] = [decisionsModule, itemModule, progressModule, contributorsModule, classifiersModule, costModule, reposModule, accessModule, aboutModule, promptsModule]; +export const modules: FeatureModule[] = [decisionsModule, itemModule, progressModule, itemsModule, contributorsModule, classifiersModule, costModule, reposModule, accessModule, aboutModule, promptsModule]; diff --git a/web/src/shell/AppShell.tsx b/web/src/shell/AppShell.tsx index ac3facbd1..5f6f2d720 100644 --- a/web/src/shell/AppShell.tsx +++ b/web/src/shell/AppShell.tsx @@ -1,5 +1,5 @@ import { lazy, Suspense, useMemo, useState } from "react"; -import { NavLink, Route, Routes, useLocation, useNavigate, useParams, Navigate } from "react-router-dom"; +import { NavLink, Route, Routes, matchPath, useLocation, useNavigate, useParams, Navigate } from "react-router-dom"; import { Dialog, DropdownMenu } from "radix-ui"; import { LogOutIcon, MonitorIcon, MoonIcon, MoreHorizontalIcon, PanelLeftIcon, SearchIcon, SunIcon, KeyboardIcon, XIcon, CheckIcon } from "lucide-react"; import { modules } from "../registry"; @@ -41,6 +41,7 @@ export function AppShell() { const visible = useMemo(() => modules.filter((m) => can(user, m.permission)), [user]); const nav = visible.flatMap((m) => (m.nav ? [m.nav] : [])).sort((a, b) => a.order - b.order); const routes = visible.flatMap((m) => m.routes); + const hiddenPaths = useMemo(() => modules.filter((m) => !can(user, m.permission)).flatMap((m) => m.routes.map((r) => r.path)), [user]); useHotkeys({ "/": () => (phone ? setSearchOpen(true) : document.getElementById("global-search")?.focus()), @@ -49,6 +50,7 @@ export function AppShell() { "[": () => setRailOpen(!railOpen), "g d": () => navigate("/decisions"), "g p": () => navigate("/progress"), + "g i": () => navigate("/items"), }); const content = ( @@ -57,7 +59,7 @@ export function AppShell() { {routes.map((r) => ( } /> ))} - Nothing here.
} /> +