mirror of
https://github.com/storytold/autocraft.git
synced 2026-12-01 10:33:55 +01:00
Merge main into pipe-decide; use the shared settled rule, allow 5 options, gate bugfix decisions
This commit is contained in:
commit
659756434f
53 files changed
+2770
-265
No files matched your search
@@ -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 <command>`. 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/<repo>/<n>` | 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 |
|
||||
|
||||
+12
-5
@@ -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/<name>`)
|
||||
|
||||
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/<repo>/<n>`)
|
||||
|
||||
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.
|
||||
|
||||
+9
-1
@@ -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 |
|
||||
|
||||
@@ -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<DatabaseSync, Seen>();
|
||||
|
||||
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<SettledRow> | 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),
|
||||
};
|
||||
}
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
type Command = { summary: string; run: (args: string[]) => Promise<void> | void };
|
||||
type Module = { commands: Record<string, Command> };
|
||||
|
||||
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<void> {
|
||||
const commands: Record<string, Command> = {};
|
||||
|
||||
+26
-2
@@ -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");
|
||||
|
||||
+66
-53
@@ -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<string, string | number> = {};
|
||||
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 = <T extends object>(xs: T[], zero: T): T => {
|
||||
return out as T;
|
||||
};
|
||||
|
||||
function progress(db: DatabaseSync): Progress {
|
||||
const start = runStart(db);
|
||||
type Heavy = Omit<Progress, "decisionsOpen" | "decisionsAnsweredToday">;
|
||||
const progressCache = new WeakMap<DatabaseSync, { key: string; at: number; value: Heavy }>();
|
||||
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<string, string | null>;
|
||||
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<number>(24).fill(0);
|
||||
const perHourPipeline = new Array<number>(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<string, number>();
|
||||
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<number>(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),
|
||||
|
||||
@@ -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<CostReport["stages"][number]>(`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<CostReport["repos"][number]>(`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<CostReport["series"][number]>(`SELECT substr(COALESCE(ended_at, started_at), 1, ${len}) AS bucket,
|
||||
|
||||
@@ -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<string, string> = { 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<string, SQLInputValue>; 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<string, SQLInputValue> = {};
|
||||
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<ItemSort, string> = {
|
||||
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<number, Snippet> {
|
||||
const out = new Map<number, Snippet>();
|
||||
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<SettledStatus, number>;
|
||||
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<number, Snippet>();
|
||||
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<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
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<string, string> = { 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);
|
||||
}
|
||||
+17
-10
@@ -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<string, string | number> = {}): Record<string, string | number> => (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<string, number>, repo?: string): { days: string[]; series: Map<string, number[]> } {
|
||||
const today = new Date().toISOString().slice(0, 10);
|
||||
@@ -86,6 +92,7 @@ export function trend(db: DatabaseSync, start: string, openNow: Map<string, numb
|
||||
for (const x of created) add(x.repo, x.d, x.n);
|
||||
for (const x of closed) add(x.repo, x.d, -x.n);
|
||||
const series = new Map<string, number[]>();
|
||||
// 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<string, number>();
|
||||
// value at the end of each day; walk back from today's open count
|
||||
|
||||
@@ -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", `<p><a href="/auth/signin">Sign in again</a></p>`) } };
|
||||
return { r: { html: plainPage(nonce, "Signed out", `<p class="muted">You are signed out of the dashboard on this device.</p><p><a class="button" href="/auth/signin">Sign in again</a></p>`) } };
|
||||
}
|
||||
if (req.method === "GET" && path === "/auth/dev/authorize" && provider instanceof FakeProvider) {
|
||||
const q = url.searchParams;
|
||||
|
||||
+17
-8
@@ -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 `<!doctype html><html lang="en"><head><meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1"><title>${esc(title)}</title>
|
||||
<script nonce="${nonce}">try{var t=localStorage.getItem("craft-triage:theme");if(t==="dark"||t==="light")document.documentElement.dataset.theme=t}catch(e){}</script>
|
||||
<style nonce="${nonce}">
|
||||
:root{color-scheme:light dark;--bg:#fff;--fg:#1a1a1a;--muted:#666;--link:#0b5cad}
|
||||
@media (prefers-color-scheme:dark){:root{--bg:#141414;--fg:#e8e8e8;--muted:#aaa;--link:#7ab4f5}}
|
||||
body{background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,sans-serif;margin:0;padding:2rem 16px;max-width:36rem}
|
||||
a{color:var(--link)}p.muted{color:var(--muted)}
|
||||
input,button{font:inherit;min-height:44px;padding:0 12px}
|
||||
</style></head><body><h1>${esc(title)}</h1>${body}</body></html>`;
|
||||
: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}
|
||||
</style></head><body><main><p class="brand">Craft Triage</p><h1>${esc(title)}</h1>${body}</main></body></html>`;
|
||||
}
|
||||
|
||||
// Fixed-window counters, in memory: limits reset with the process, which is
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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 };
|
||||
}
|
||||
|
||||
+9
-23
@@ -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<string[]>(r.jf, []), top: typeof top === "number" ? top : null },
|
||||
r.hl === null ? null : { label: r.hl, flags: json<string[]>(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;
|
||||
|
||||
+2
-2
@@ -46,9 +46,9 @@ export function validateAsk(q: Record<string, unknown>): Record<string, string |
|
||||
if (!KINDS.includes(q.kind as Kind)) throw err(`kind must be one of ${KINDS.join(", ")}`);
|
||||
if (typeof q.question !== "string" || !q.question.trim()) throw err("question is required");
|
||||
const options = q.options as Option[];
|
||||
if (!Array.isArray(options) || options.length < 2 || options.length > 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[];
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<void>;
|
||||
|
||||
async function retrying<T>(f: () => Promise<T>, wait: Wait): Promise<T> {
|
||||
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<string, string> }; // lower-case name -> label id
|
||||
|
||||
export async function repoLabels(client: Querier, repo: string, wait: Wait = sleepMs as Wait): Promise<Repo> {
|
||||
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<string, string>();
|
||||
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<LabelDef[]> {
|
||||
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<ApplyResult> {
|
||||
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<Map<number, string | null>> {
|
||||
const out = new Map<number, string | null>();
|
||||
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<number, string | null>, have: Repo, wait: Wait): Promise<number[]> {
|
||||
const run = async (part: PlanRow[]): Promise<number[]> => {
|
||||
const vars: Record<string, unknown> = {};
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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 <command> --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<void> {
|
||||
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<void> {
|
||||
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<string, (args: string[]) => Promise<void> | 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));
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -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<number, ClsRow[]>();
|
||||
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";
|
||||
}
|
||||
@@ -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);
|
||||
@@ -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);
|
||||
}
|
||||
+13
-7
@@ -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) {
|
||||
|
||||
+38
-2
@@ -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);
|
||||
@@ -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<TrackedRepo[]>("/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<TrackedRepo[]>("/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();
|
||||
|
||||
+4
-1
@@ -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<User>("/api/me")).role, "viewer");
|
||||
const it = await boss.get<Item>("/api/items/photocraft/1");
|
||||
assert.equal(it.body, "<script>x</script> body");
|
||||
assert.deepEqual([it.changedFiles, it.additions, it.deletions], [7, 40, 3]);
|
||||
assert.equal((await boss.get<Item>("/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"]]);
|
||||
|
||||
+2
-1
@@ -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";
|
||||
|
||||
|
||||
+1
-1
@@ -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));
|
||||
|
||||
|
||||
@@ -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 }]);
|
||||
});
|
||||
|
||||
@@ -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')");
|
||||
});
|
||||
@@ -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<string, unknown> };
|
||||
function fakeClient(opts: { failNumber?: number } = {}) {
|
||||
const calls: Call[] = [];
|
||||
return {
|
||||
calls, spent: 0, remaining: 5000 as number | null,
|
||||
async query(query: string, variables: Record<string, unknown>) {
|
||||
calls.push({ query, variables });
|
||||
if (query.includes("label(name:")) {
|
||||
const l: Record<string, unknown> = { 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<string, unknown> = {};
|
||||
for (const m of query.matchAll(/n(\d+): issueOrPullRequest/g)) r[`n${m[1]}`] = { id: `N${m[1]}` };
|
||||
return { repository: r };
|
||||
}
|
||||
const out: Record<string, unknown> = {};
|
||||
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]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
// Raw HTML in untrusted bodies: <img> 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 <img> in a block becomes a proxied image", () => {
|
||||
const out = htmlBlock(`<p align="center"><a href="${IMG}"><img width="1202" height="761" alt="Screen" src="${IMG}" onerror="alert(1)" /></a></p>`);
|
||||
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(`<div onclick="x()"><script>alert(1)</script><style>p{}</style><iframe src="https://evil.example"></iframe>
|
||||
<details><summary>More & less</summary><span style="color:red">kept text</span><br><code><b></code></details></div>`);
|
||||
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, "<b>");
|
||||
});
|
||||
|
||||
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(`<img src="${src}" alt="x">`), "image");
|
||||
assert.equal(proxiedImage(safeUrl(img!.url!)), null, src);
|
||||
}
|
||||
const [link] = of(htmlBlock(`<a href="javascript:alert(1)">click</a>`), "link");
|
||||
assert.equal(safeUrl(link!.url!), "");
|
||||
});
|
||||
|
||||
test("inline tags inside a paragraph", () => {
|
||||
const kids = inlineChildren([
|
||||
{ type: "text", value: "before " },
|
||||
{ type: "html", value: `<img src="${IMG}" alt="a">` },
|
||||
{ type: "html", value: "<br/>" },
|
||||
{ type: "html", value: '<a href="https://example.com/x">' },
|
||||
{ type: "text", value: "link text" },
|
||||
{ type: "html", value: "</a>" },
|
||||
{ type: "html", value: "<sub>" },
|
||||
{ type: "text", value: " after" },
|
||||
{ type: "html", value: "</sub>" },
|
||||
]);
|
||||
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: `<img width="1202" alt="Image" src="${IMG}" />` },
|
||||
{ type: "html", value: '<video src="https://github.com/user-attachments/assets/demo.mp4" controls></video>' },
|
||||
],
|
||||
};
|
||||
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");
|
||||
});
|
||||
@@ -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<DecisionComment>;
|
||||
};
|
||||
item(repo: RepoName, number: number): Promise<Item>;
|
||||
/** Top bar: jumps by number, logins, words in titles and bodies. */
|
||||
search(q: string): Promise<SearchHit[]>;
|
||||
/** The Items browser: every tracked repo, full-text search over titles, bodies and comments. */
|
||||
items(filter: ItemFilter): Promise<ItemList>;
|
||||
progress(): Promise<Progress>;
|
||||
/** 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<TrackedRepo[]>;
|
||||
track(name: RepoName): Promise<TrackedRepo[]>;
|
||||
untrack(name: RepoName): Promise<TrackedRepo[]>;
|
||||
/** Lets the Label stage write labels to this repo on GitHub, or stops it. */
|
||||
approveLabels(name: RepoName, approved: boolean): Promise<TrackedRepo[]>;
|
||||
};
|
||||
/** Operator only. */
|
||||
access: {
|
||||
|
||||
+24
-3
@@ -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 = <T>(path: string) => call<T>("GET", path);
|
||||
// Views that mount together often ask for the same thing; they share one request.
|
||||
const inflight = new Map<string, Promise<unknown>>();
|
||||
const get = <T>(path: string): Promise<T> => {
|
||||
let p = inflight.get(path) as Promise<T> | undefined;
|
||||
if (!p) {
|
||||
p = call<T>("GET", path).finally(() => inflight.delete(path));
|
||||
inflight.set(path, p);
|
||||
}
|
||||
return p;
|
||||
};
|
||||
async function post<T>(path: string, body?: unknown): Promise<T> {
|
||||
const v = await call<T>("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"),
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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<string, string[]> = {
|
||||
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,
|
||||
|
||||
@@ -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" };
|
||||
}
|
||||
@@ -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<SettledStatus, number>;
|
||||
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 };
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -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 = <T>(v: T, ms = 60) => new Promise<T>((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
|
||||
|
||||
+120
-3
@@ -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<SettledStatus, number>;
|
||||
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. */
|
||||
|
||||
@@ -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(" · ")
|
||||
: "";
|
||||
|
||||
|
||||
@@ -30,7 +30,7 @@ function ReposView(_: ViewProps) {
|
||||
return (
|
||||
<Page title="Repos" sub={data && `${tracked} of ${data.length} repos tracked`}>
|
||||
<p className="mt-2 max-w-[80ch] text-sm text-ink/65">
|
||||
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.
|
||||
</p>
|
||||
|
||||
<div className="mt-4 flex flex-wrap items-center gap-2">
|
||||
@@ -84,13 +84,38 @@ function Toggle({ r, write }: { r: TrackedRepo; write: Write }) {
|
||||
return <ConfirmButton label="Untrack" confirmLabel="Untrack: hides its items" loading={write.busy === key} onConfirm={() => 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 <span className="text-ink/40">–</span>;
|
||||
const key = `labels:${r.name}`;
|
||||
return (
|
||||
<div className="flex items-center justify-end gap-2">
|
||||
{l.approved ? (
|
||||
<span title={`Approved by ${l.approvedBy} ${l.approvedAt ?? ""}`}>
|
||||
<Badge tone="ok">Approved</Badge>
|
||||
</span>
|
||||
) : (
|
||||
<Badge>Not approved</Badge>
|
||||
)}
|
||||
{l.approved ? (
|
||||
<ConfirmButton label="Stop" confirmLabel="Stop labelling here" loading={write.busy === key} onConfirm={() => void write.run(key, () => api.repoAdmin.approveLabels(r.name, false))} />
|
||||
) : (
|
||||
<ConfirmButton label="Approve" confirmLabel="Approve: writes to GitHub" loading={write.busy === key} onConfirm={() => void write.run(key, () => api.repoAdmin.approveLabels(r.name, true))} />
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[760px] border-collapse text-sm">
|
||||
<table className="w-full min-w-[1200px] border-collapse text-sm">
|
||||
<thead className="bg-ink/[0.03] text-xs">
|
||||
<tr className="border-b border-line">
|
||||
<SortTh>Repo</SortTh>
|
||||
@@ -99,6 +124,8 @@ function Table({ rows, write }: { rows: TrackedRepo[]; write: Write }) {
|
||||
<SortTh right className="w-[100px]">Open issues</SortTh>
|
||||
<SortTh right className="w-[120px]">Rows in mirror</SortTh>
|
||||
<SortTh className="w-[150px]">Last synced</SortTh>
|
||||
<SortTh className="w-[270px]">Labels plan</SortTh>
|
||||
<th className="w-[270px] px-3 text-right text-xs font-medium">Label approval</th>
|
||||
<th className="w-[190px]" aria-label="Change" />
|
||||
</tr>
|
||||
</thead>
|
||||
@@ -113,6 +140,10 @@ function Table({ rows, write }: { rows: TrackedRepo[]; write: Write }) {
|
||||
<td className="px-3 text-ink/60" title={r.syncedAt ?? undefined}>
|
||||
{synced(r)}
|
||||
</td>
|
||||
<td className="num whitespace-nowrap px-3 text-ink/70">{planText(r)}</td>
|
||||
<td className="px-3">
|
||||
<Approval r={r} write={write} />
|
||||
</td>
|
||||
<td className="px-3 text-right">
|
||||
<Toggle r={r} write={write} />
|
||||
</td>
|
||||
@@ -137,6 +168,12 @@ function Cards({ rows, write }: { rows: TrackedRepo[]; write: Write }) {
|
||||
<div className="num mt-0.5 text-xs text-ink/55">
|
||||
{maybe(r.openPrs)} PRs · {maybe(r.openIssues)} issues · synced {synced(r)}
|
||||
</div>
|
||||
{r.labels && (
|
||||
<div className="mt-1 flex items-center gap-2">
|
||||
<span className="num text-xs text-ink/55">Labels: {planText(r)}</span>
|
||||
<Approval r={r} write={write} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Toggle r={r} write={write} />
|
||||
</li>
|
||||
|
||||
@@ -93,8 +93,8 @@ function Disagreements({ r, label, band, setFilter }: { r: ClassifierReport; lab
|
||||
<tr>
|
||||
<Th>Item</Th>
|
||||
<Th>Title</Th>
|
||||
<Th>{r.a}</Th>
|
||||
<Th>{r.b}</Th>
|
||||
<Th className="hidden sm:table-cell">{r.a}</Th>
|
||||
<Th className="hidden sm:table-cell">{r.b}</Th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -103,11 +103,24 @@ function Disagreements({ r, label, band, setFilter }: { r: ClassifierReport; lab
|
||||
<td className="whitespace-nowrap px-3 py-1.5">
|
||||
<RefLink repo={d.repo} number={d.number} kind={d.kind} />
|
||||
</td>
|
||||
<td className="min-w-[16rem] px-3 py-1.5 text-ink/85">{d.title}</td>
|
||||
<td className="whitespace-nowrap px-3 py-1.5">
|
||||
<td className="px-3 py-1.5 text-ink/85 sm:min-w-[16rem]">
|
||||
{d.title}
|
||||
{/* Phones: the two answers under the title instead of in their own columns. */}
|
||||
<dl className="mt-1 grid grid-cols-[auto_1fr] gap-x-2 text-xs sm:hidden">
|
||||
<dt className="text-ink/50">{r.a}</dt>
|
||||
<dd>
|
||||
{d.a.label} <span className="num text-ink/50">{prob(d.a.prob)}</span>
|
||||
</dd>
|
||||
<dt className="text-ink/50">{r.b}</dt>
|
||||
<dd>
|
||||
{d.b.label} <span className="num text-ink/50">{prob(d.b.prob)}</span>
|
||||
</dd>
|
||||
</dl>
|
||||
</td>
|
||||
<td className="hidden whitespace-nowrap px-3 py-1.5 sm:table-cell">
|
||||
{d.a.label} <span className="num text-xs text-ink/50">{prob(d.a.prob)}</span>
|
||||
</td>
|
||||
<td className="whitespace-nowrap px-3 py-1.5">
|
||||
<td className="hidden whitespace-nowrap px-3 py-1.5 sm:table-cell">
|
||||
{d.b.label} <span className="num text-xs text-ink/50">{prob(d.b.prob)}</span>
|
||||
</td>
|
||||
</tr>
|
||||
@@ -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)})` }))}
|
||||
/>
|
||||
</div>
|
||||
{run && run !== r.run && (
|
||||
<p role="status" className="mt-2 rounded-md border border-warn/40 bg-warn/10 px-3 py-2 text-sm">
|
||||
There is no run <span className="code">{run}</span>. Showing the latest run, <span className="code">{r.run}</span>.
|
||||
</p>
|
||||
)}
|
||||
<p className="mt-1 text-sm text-ink/55">Agreement on the type label, per run. Rows are grouped by {r.a}'s answer.</p>
|
||||
|
||||
<div className="mt-4 grid grid-cols-2 gap-3 lg:grid-cols-4">
|
||||
@@ -181,8 +199,10 @@ function Classifiers(_: ViewProps) {
|
||||
<Block title={`By ${r.a}'s label`} aside="Click to filter disagreements" flush>
|
||||
<AgreementRows name="Label" rows={r.byLabel.map((x) => ({ key: x.label, n: x.n, agree: x.agree }))} picked={label} onPick={(k) => set({ label: label === k ? "" : k })} />
|
||||
</Block>
|
||||
<Block title="By repo" flush>
|
||||
<AgreementRows name="Repo" rows={r.byRepo.map((x) => ({ key: x.repo, n: x.n, agree: x.agree }))} />
|
||||
<Block title="By repo" aside={`${num(r.byRepo.length)} repos with items judged by both`} flush>
|
||||
<div className="max-h-[22rem] overflow-y-auto">
|
||||
<AgreementRows name="Repo" rows={r.byRepo.map((x) => ({ key: x.repo, n: x.n, agree: x.agree }))} />
|
||||
</div>
|
||||
</Block>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -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
|
||||
<td className="px-3 py-1.5 text-right">{num(u.output)}</td>
|
||||
<td className="px-3 py-1.5 text-right">{num(u.cacheRead)}</td>
|
||||
<td className="px-3 py-1.5 text-right">{num(u.cacheWrite)}</td>
|
||||
<td className="px-3 py-1.5 text-right">{usd(u.usd)}</td>
|
||||
<td className={cn("px-3 py-1.5 text-right", u.usd === null && "whitespace-nowrap text-xs text-ink/45")}>{u.usd === null ? "price not reported" : usd(u.usd)}</td>
|
||||
<td className="px-3 py-1.5 text-right">{per(tokens(u), u.items)}</td>
|
||||
<td className="px-3 py-1.5 text-right">{perUsd(u.usd, u.items)}</td>
|
||||
<td className="px-3 py-1.5 text-right">{wall(u.wallSeconds)}</td>
|
||||
@@ -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<string, ModelTotals>();
|
||||
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) => (
|
||||
<div key={m.model}>
|
||||
{m.model}: {perUsd(m.usd, m.items)} per item
|
||||
</div>
|
||||
))}
|
||||
{unpriced.length > 0 && <div>{unpriced.map((m) => m.model).join(", ")}: price not reported</div>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
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 <div className="p-6 text-ink/50">Loading…</div>;
|
||||
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 (
|
||||
<div className="h-full overflow-y-auto">
|
||||
<div className="mx-auto max-w-[1180px] px-4 pb-12 pt-5 md:px-6">
|
||||
@@ -107,15 +141,17 @@ function Cost(_: ViewProps) {
|
||||
<p className="mt-1 text-sm text-ink/55">Token use per agent call. USD appears where the agent reported a cost.</p>
|
||||
|
||||
<div className="mt-4 grid grid-cols-2 gap-3 lg:grid-cols-4">
|
||||
<Stat label="Calls" value={num(t.calls)} sub={`${num(t.items)} items handled`} />
|
||||
<Stat label="Tokens" value={num(tokens(t))} sub={`${per(tokens(t), t.items)} per item`} />
|
||||
<Stat label="Spend" value={usd(t.usd)} sub={t.usd === null ? "none reported" : `${perUsd(t.usd, t.items)} per item`} />
|
||||
<Stat label="Items" value={num(items)} sub={models.map((m) => `${m.model} ${num(m.items)}`).join(" · ")} />
|
||||
<Stat label="Tokens" value={num(tokens(t))} sub={`${num(t.calls)} calls · ${per(tokens(t), t.items)} per item and model`} />
|
||||
<Stat label="Spend" value={usd(t.usd)} sub={t.usd === null ? "price not reported" : <SpendSub models={models} />} />
|
||||
<Stat label="Wall time" value={wall(t.wallSeconds)} sub="first start to last end" />
|
||||
</div>
|
||||
|
||||
<Block title="Spend over time" className="mt-4">
|
||||
<SpendChart r={r} />
|
||||
</Block>
|
||||
{r.series.length >= 3 && (
|
||||
<Block title="Spend over time" className="mt-4">
|
||||
<SpendChart r={r} />
|
||||
</Block>
|
||||
)}
|
||||
<Block title="By stage and model" className="mt-4" flush>
|
||||
<UsageTable name="Stage" subName="Model" rows={r.stages.map((s) => ({ key: s.stage, sub: s.model, u: s }))} />
|
||||
</Block>
|
||||
|
||||
+132
-27
@@ -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) {
|
||||
<Files it={it} />
|
||||
</Section>
|
||||
)}
|
||||
{it.comments.length > 0 && (
|
||||
<Section title="Discussion" aside={`${it.comments.length} ${it.comments.length === 1 ? "comment" : "comments"}`}>
|
||||
<Discussion comments={it.comments} />
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
@@ -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 (
|
||||
<dl className="mt-4 grid grid-cols-[96px_1fr] gap-x-4 text-sm md:grid-cols-[96px_1fr_96px_1fr]">
|
||||
<Prop label="Author">
|
||||
@@ -151,34 +161,48 @@ function Properties({ it }: { it: Item }) {
|
||||
{it.authorMerged} merged · {it.authorClosedUnmerged} closed unmerged
|
||||
</span>
|
||||
</Prop>
|
||||
<Prop label="Type">
|
||||
<SettledBadge s={it.settled} detail />
|
||||
{it.settled.flags.map((f) => (
|
||||
<Badge key={f} tone={f === "security" ? "bad" : "warn"}>
|
||||
{f}
|
||||
</Badge>
|
||||
))}
|
||||
</Prop>
|
||||
<Prop label="Size">
|
||||
{it.kind === "pr" ? (
|
||||
<>
|
||||
<span className="code">
|
||||
<span className="text-ok">+{num(it.additions)}</span> <span className="text-bad">−{num(it.deletions)}</span>
|
||||
</span>
|
||||
<span className="text-ink/60">{it.files.length} files</span>
|
||||
{it.changedFiles !== null && (
|
||||
<span className="text-ink/60">
|
||||
{num(it.changedFiles)} {it.changedFiles === 1 ? "file" : "files"}
|
||||
</span>
|
||||
)}
|
||||
<Badge>{sizeBucket(total)}</Badge>
|
||||
</>
|
||||
) : (
|
||||
<span className="text-ink/60">Issue</span>
|
||||
)}
|
||||
</Prop>
|
||||
<Prop label="Checks">
|
||||
<span className={cn("inline-flex items-center gap-1 font-medium", ciCls)}>
|
||||
<CiIcon /> {it.ci === "none" ? "No checks" : it.ci[0].toUpperCase() + it.ci.slice(1)}
|
||||
</span>
|
||||
{it.ciChecks.length > 0 && (
|
||||
<span className="text-ink/55">
|
||||
{passing} of {it.ciChecks.length} passed
|
||||
{showCi && (
|
||||
<Prop label="Checks">
|
||||
<span className={cn("inline-flex items-center gap-1 font-medium", ciCls)}>
|
||||
<CiIcon /> {it.ci[0]!.toUpperCase() + it.ci.slice(1)}
|
||||
</span>
|
||||
)}
|
||||
</Prop>
|
||||
<Prop label="Mergeable">
|
||||
<span className={cn("font-medium", it.mergeable === "clean" ? "text-ok" : it.mergeable === "conflicts" ? "text-bad" : "text-ink/55")}>
|
||||
{it.mergeable === "clean" ? "No conflicts" : it.mergeable === "conflicts" ? "Has conflicts" : "Unknown"}
|
||||
</span>
|
||||
</Prop>
|
||||
{it.ciChecks.length > 0 && (
|
||||
<span className="text-ink/55">
|
||||
{passing} of {it.ciChecks.length} passed
|
||||
</span>
|
||||
)}
|
||||
</Prop>
|
||||
)}
|
||||
{showMergeable && (
|
||||
<Prop label="Mergeable">
|
||||
<span className={cn("font-medium", it.mergeable === "clean" ? "text-ok" : "text-bad")}>{it.mergeable === "clean" ? "No conflicts" : "Has conflicts"}</span>
|
||||
</Prop>
|
||||
)}
|
||||
<Prop label="Labels">
|
||||
{it.labels.map((l) => (
|
||||
<Badge key={l}>{l}</Badge>
|
||||
@@ -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 (
|
||||
<>
|
||||
<span>
|
||||
{label!.name} ({percent(label!.p)})
|
||||
</span>
|
||||
{flags.length > 0 && (
|
||||
<span className="block text-xs text-ink/55">
|
||||
{flags.map((f) => `${f.name[0]!.toUpperCase()}${f.name.slice(1)}: ${likelihood(f.p)} (${percent(f.p)})`).join(" · ")}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const WANT: Record<string, string> = { yes: "text-ok", no: "text-bad", unclear: "text-warn" };
|
||||
|
||||
function Verdicts({ cls }: { cls: Classification[] }) {
|
||||
@@ -223,7 +270,9 @@ function Verdicts({ cls }: { cls: Classification[] }) {
|
||||
<span className="ml-auto text-xs text-ink/45">{ago(c.at)}</span>
|
||||
</div>
|
||||
{c.reference && <div className="mt-0.5 text-xs text-ink/55">Reference: {c.reference}</div>}
|
||||
<p className="mt-1 text-sm text-ink/70">{c.reason}</p>
|
||||
<div className="mt-1 text-sm text-ink/70">
|
||||
<Reason reason={c.reason} />
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
@@ -232,8 +281,8 @@ function Verdicts({ cls }: { cls: Classification[] }) {
|
||||
{ label: "Type", render: (c) => c.typeLabel, off: (c) => c.typeLabel !== typeMaj },
|
||||
{ label: "Want", render: (c) => <span className={WANT[c.want]}>{c.want}</span>, off: (c) => c.want !== wantMaj },
|
||||
{ label: "Reference", render: (c) => c.reference ?? <span className="text-ink/35">none</span> },
|
||||
{ label: "Topics", render: (c) => c.topics },
|
||||
{ label: "Reason", render: (c) => <span className="text-ink/70">{c.reason}</span> },
|
||||
{ label: "Topics", render: (c) => (c.topics === "many" ? "several topics" : "one topic") },
|
||||
{ label: "Reason", render: (c) => <span className="text-ink/70"><Reason reason={c.reason} /></span> },
|
||||
];
|
||||
return (
|
||||
<div className="overflow-hidden rounded-md border border-line">
|
||||
@@ -280,23 +329,79 @@ const STAGE: Record<Stage, [string, LucideIcon]> = {
|
||||
"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 (
|
||||
<ol className="relative">
|
||||
<span className="absolute bottom-3 left-[11px] top-3 w-px bg-line-strong" aria-hidden />
|
||||
{it.stages.map((s, i) => {
|
||||
const last = i === it.stages.length - 1;
|
||||
const [label, Icon] = STAGE[s.stage];
|
||||
{evs.length > 1 && <span className="absolute bottom-3 left-[11px] top-3 w-px bg-line-strong" aria-hidden />}
|
||||
{evs.map((e, i) => {
|
||||
const last = i === evs.length - 1 && evs.length > 1;
|
||||
return (
|
||||
<li key={i} className="relative flex items-center gap-3 py-1.5">
|
||||
<span className={cn("z-[1] flex size-6 shrink-0 items-center justify-center rounded-full border", last ? "border-warn/50 bg-warn/15 text-warn" : "border-line-strong bg-panel text-ink/55")}>
|
||||
<Icon className="text-[12px]" />
|
||||
<e.Icon className="text-[12px]" />
|
||||
</span>
|
||||
<span className="min-w-0 flex-1 text-sm">
|
||||
<span className={cn(last ? "font-medium text-ink" : "text-ink/85")}>{label}</span> <span className="text-ink/55">by {s.by}</span>
|
||||
{s.note && <span className="text-ink/45"> · {s.note}</span>}
|
||||
<span className={cn(last ? "font-medium text-ink" : "text-ink/85")}>{e.label}</span>
|
||||
{e.by && <span className="text-ink/55"> by {e.by}</span>}
|
||||
{e.note && <span className="text-ink/45"> · {e.note}</span>}
|
||||
</span>
|
||||
<span className="shrink-0 text-xs text-ink/45">{ago(s.at)} ago</span>
|
||||
<span className="shrink-0 text-xs text-ink/45">{ago(e.at)} ago</span>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ol>
|
||||
);
|
||||
}
|
||||
|
||||
const REVIEW: Record<string, [string, Tone]> = {
|
||||
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 (
|
||||
<ol className="space-y-3">
|
||||
{comments.map((c) => {
|
||||
const review = c.kind === "review" ? (REVIEW[c.reviewState ?? ""] ?? REVIEW.COMMENTED!) : null;
|
||||
return (
|
||||
<li key={c.id} className="overflow-hidden rounded-md border border-line">
|
||||
<div className="flex flex-wrap items-center gap-x-2 gap-y-1 border-b border-line bg-ink/[0.03] px-3 py-1.5 text-sm">
|
||||
{c.author ? <Avatar login={c.author} size={18} /> : <MessageSquareIcon className="text-ink/40" />}
|
||||
<span className="font-medium">{c.author || "ghost"}</span>
|
||||
{review && <Badge tone={review[1]}>{review[0]}</Badge>}
|
||||
<span className="ml-auto text-xs text-ink/45" title={c.at}>
|
||||
{c.at ? ago(c.at, false) : ""}
|
||||
</span>
|
||||
</div>
|
||||
<div className="px-3 py-2">
|
||||
{c.body.trim() ? (
|
||||
<Collapsible lines={12}>
|
||||
<Markdown source={c.body} />
|
||||
</Collapsible>
|
||||
) : (
|
||||
<p className="text-sm text-ink/45">No text.</p>
|
||||
)}
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -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<SettledStatus, [string, Tone]> = {
|
||||
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<Stage, string> = {
|
||||
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<string, string | null>) => update({ ...patch, offset: null });
|
||||
const unsettled = data ? data.byStatus.waiting + data.byStatus.disagree : undefined;
|
||||
const statusOn = (s: StatusFilter) => filter.status?.includes(s) ?? false;
|
||||
|
||||
return (
|
||||
<Page title="Items" sub={data && <Summary list={data} filter={filter} />}>
|
||||
<div className="mt-4 flex flex-wrap items-center gap-2">
|
||||
<QueryField value={filter.q ?? ""} onChange={(q) => set({ q: q || null, sort: null })} />
|
||||
<select aria-label="State" value={filter.state} onChange={(e) => set({ state: e.target.value === "open" ? null : e.target.value })} className={cn(selectCls, "text-ink/80")}>
|
||||
{STATES.map(([k, l]) => (
|
||||
<option key={k} value={k}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select aria-label="Kind" value={filter.kind ?? ""} onChange={(e) => set({ kind: e.target.value || null })} className={cn(selectCls, filter.kind ? "text-accent-ink" : "text-ink/70")}>
|
||||
<option value="">Issues and PRs</option>
|
||||
<option value="pr">PRs</option>
|
||||
<option value="issue">Issues</option>
|
||||
</select>
|
||||
<RepoPicker value={filter.repo ?? []} onChange={(r) => set({ repo: r.length ? r.join(",") : null })} />
|
||||
<select aria-label="Type label" value={filter.label ?? ""} onChange={(e) => set({ label: e.target.value || null })} className={cn(selectCls, filter.label ? "text-accent-ink" : "text-ink/70")}>
|
||||
<option value="">Any type</option>
|
||||
{LABELS.map((l) => (
|
||||
<option key={l} value={l}>
|
||||
{l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<select
|
||||
aria-label="Sort"
|
||||
value={filter.sort ?? (filter.q ? "relevance" : "updated")}
|
||||
onChange={(e) => set({ sort: e.target.value })}
|
||||
className={cn(selectCls, "text-ink/70 sm:ml-auto")}
|
||||
>
|
||||
{SORTS.filter(([k]) => k !== "relevance" || filter.q).map(([k, l]) => (
|
||||
<option key={k} value={k}>
|
||||
Sort: {l}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button className="chip max-md:h-11" onClick={() => set({ desc: filter.desc ? "0" : null })} aria-label="Sort direction">
|
||||
{filter.desc ? (filter.sort === "number" ? "Highest first" : filter.sort === "relevance" || (!filter.sort && filter.q) ? "Best first" : "Newest first") : filter.sort === "number" ? "Lowest first" : filter.sort === "relevance" || (!filter.sort && filter.q) ? "Weakest first" : "Oldest first"}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||
<div role="group" aria-label="Classification" className="flex flex-wrap items-center gap-1">
|
||||
<button aria-pressed={!filter.status?.length} data-active={!filter.status?.length} className="chip max-md:h-11" onClick={() => set({ status: null })}>
|
||||
Any classification
|
||||
</button>
|
||||
<button aria-pressed={statusOn("unsettled")} data-active={statusOn("unsettled")} className="chip max-md:h-11" onClick={() => set({ status: statusOn("unsettled") ? null : "unsettled" })}>
|
||||
Unsettled <span className="num opacity-60">{unsettled !== undefined ? num(unsettled) : ""}</span>
|
||||
</button>
|
||||
{STATUS_KEYS.map((s) => (
|
||||
<button key={s} aria-pressed={statusOn(s)} data-active={statusOn(s)} className="chip max-md:h-11" onClick={() => set({ status: statusOn(s) ? null : s })}>
|
||||
{STATUS[s][0]} <span className="num opacity-60">{data ? num(data.byStatus[s]) : ""}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{FLAGS.map(([k, l]) => {
|
||||
const on = filter.flag?.includes(k) ?? false;
|
||||
const next = on ? filter.flag!.filter((f) => f !== k) : [...(filter.flag ?? []), k];
|
||||
return (
|
||||
<button key={k} aria-pressed={on} data-active={on} className="chip max-md:h-11" onClick={() => set({ flag: next.length ? next.join(",") : null })}>
|
||||
{l}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
<DebouncedInput value={filter.author ?? ""} onChange={(v) => set({ author: v || null })} placeholder="Author login" label="Author" className="w-36" />
|
||||
<label className="flex items-center gap-1.5 text-xs text-ink/60">
|
||||
Updated since
|
||||
<TextInput type="date" value={filter.since ?? ""} onChange={(e) => set({ since: e.target.value || null })} className="w-[150px]" />
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<Block
|
||||
className="mt-3"
|
||||
flush
|
||||
title={<span className="flex items-center gap-2">{filter.q ? `Matches for “${filter.q}”` : "Items"}</span>}
|
||||
aside={loading && data ? "Updating…" : phone ? undefined : filter.q ? 'Words must all match; use "a phrase", prefix*, -word, OR.' : undefined}
|
||||
>
|
||||
<ErrorLine error={error?.message} className="p-4" />
|
||||
{data && data.rows.length === 0 && <p className="px-4 py-6 text-sm text-ink/50">No item matches these filters.</p>}
|
||||
{data && data.rows.length > 0 && (phone ? <Cards rows={data.rows} /> : <Table rows={data.rows} />)}
|
||||
{data && <Pager offset={filter.offset ?? 0} limit={PAGE} total={data.total} onOffset={(o) => update({ offset: o ? String(o) : null })} />}
|
||||
</Block>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<label className={cn("flex h-8 items-center gap-2 rounded border border-line bg-sunken px-2.5 focus-within:border-accent/60 max-md:h-11", className)}>
|
||||
{icon && <SearchIcon className="text-ink/40" />}
|
||||
<input
|
||||
value={v}
|
||||
onChange={(e) => setV(e.target.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && onChange(v.trim())}
|
||||
placeholder={placeholder}
|
||||
aria-label={label}
|
||||
className="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-ink/40"
|
||||
/>
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
function QueryField({ value, onChange }: { value: string; onChange: (v: string) => void }) {
|
||||
return <DebouncedInput icon value={value} onChange={onChange} placeholder='Search titles, descriptions, comments' label="Search text" className="w-full sm:w-80" />;
|
||||
}
|
||||
|
||||
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 (
|
||||
<Popover.Root>
|
||||
<Popover.Trigger asChild>
|
||||
<button className={cn(selectCls, "inline-flex items-center gap-1.5 px-2.5", value.length ? "text-accent-ink" : "text-ink/70")} aria-label="Repos">
|
||||
{label} <ChevronDownIcon className="text-[11px] opacity-60" />
|
||||
</button>
|
||||
</Popover.Trigger>
|
||||
<Popover.Portal>
|
||||
<Popover.Content align="start" sideOffset={4} className="z-50 max-h-[60vh] w-[240px] overflow-y-auto rounded-md border border-line-strong bg-raised p-1.5 shadow-[0_12px_32px_rgba(0,0,0,0.28)] animate-rise">
|
||||
{value.length > 0 && (
|
||||
<button className="mb-1 w-full rounded px-2 py-1.5 text-left text-xs text-accent-ink hover:bg-ink/[0.06]" onClick={() => onChange([])}>
|
||||
Clear: every repo
|
||||
</button>
|
||||
)}
|
||||
{repos?.map((r) => (
|
||||
<label key={r} className="flex h-8 cursor-pointer items-center gap-2 rounded px-2 text-sm hover:bg-ink/[0.06] max-md:h-11">
|
||||
<input type="checkbox" checked={value.includes(r)} onChange={(e) => onChange(e.target.checked ? [...value, r] : value.filter((x) => x !== r))} />
|
||||
{r}
|
||||
</label>
|
||||
))}
|
||||
</Popover.Content>
|
||||
</Popover.Portal>
|
||||
</Popover.Root>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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 (
|
||||
<span className="text-xs text-ink/60">
|
||||
<span className="text-ink/45">{s.field === "comment" ? `Comment${s.author ? ` by ${s.author}` : ""}: ` : s.field === "title" ? "Title: " : ""}</span>
|
||||
{parts.map((p, i) =>
|
||||
p.startsWith("\u0002") ? (
|
||||
<mark key={i} className="rounded-sm bg-warn/25 px-0.5 text-ink">
|
||||
{p.slice(1, -1)}
|
||||
</mark>
|
||||
) : (
|
||||
<span key={i}>{p}</span>
|
||||
),
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function StateIcon({ it }: { it: ItemListRow }) {
|
||||
if (it.state === "merged") return <GitMergeIcon className="shrink-0 text-merged" aria-label="Merged" />;
|
||||
if (it.state === "closed") return <CircleSlashIcon className="shrink-0 text-ink/45" aria-label="Closed" />;
|
||||
return it.kind === "pr" ? <GitPullRequestIcon className="shrink-0 text-ok" aria-label="Open PR" /> : <CircleDotIcon className="shrink-0 text-ok" aria-label="Open issue" />;
|
||||
}
|
||||
|
||||
/** 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 (
|
||||
<span className="inline-flex min-w-0 items-center gap-1.5" title={s.source === "jev" ? `Jev is sure (top probability${conf})` : `Jev unsure (${conf.trim()}), Haiku agrees`}>
|
||||
<Badge tone="ok">{s.label}</Badge>
|
||||
<span className="num text-2xs text-ink/45">{s.source === "jev" ? `Jev${conf}` : `Jev${conf} + Haiku`}</span>
|
||||
</span>
|
||||
);
|
||||
const [text, tone] = STATUS[s.status];
|
||||
return (
|
||||
<span className="inline-flex min-w-0 flex-wrap items-center gap-1.5">
|
||||
<Badge tone={tone}>{s.status === "waiting" ? "Waiting" : s.status === "disagree" ? "Disagree" : text}</Badge>
|
||||
{s.jevLabel && (
|
||||
<span className="text-2xs text-ink/50">
|
||||
Jev {s.jevLabel}
|
||||
{conf}
|
||||
{s.status === "disagree" ? ` · Haiku ${s.haikuLabel}` : ""}
|
||||
</span>
|
||||
)}
|
||||
{detail && <span className="text-2xs text-ink/50">{text}</span>}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Flags({ flags }: { flags: string[] }) {
|
||||
if (!flags.length) return <span className="text-ink/30">–</span>;
|
||||
return (
|
||||
<span className="flex flex-wrap gap-1">
|
||||
{flags.includes("security") && (
|
||||
<Badge tone="bad" icon={<ShieldAlertIcon className="text-[10px]" />}>
|
||||
security
|
||||
</Badge>
|
||||
)}
|
||||
{flags.includes("needs decision") && (
|
||||
<Badge tone="warn" icon={<FlagIcon className="text-[10px]" />}>
|
||||
decision
|
||||
</Badge>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function Table({ rows }: { rows: ItemListRow[] }) {
|
||||
return (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[1000px] border-collapse text-sm">
|
||||
<thead className="bg-ink/[0.03] text-xs text-ink/55">
|
||||
<tr className="border-b border-line text-left">
|
||||
<th className="h-8 px-3 font-medium">Item</th>
|
||||
<th className="w-[120px] px-3 font-medium">Author</th>
|
||||
<th className="w-[80px] px-3 font-medium">Updated</th>
|
||||
<th className="w-[230px] px-3 font-medium">Type</th>
|
||||
<th className="w-[120px] px-3 font-medium">Flags</th>
|
||||
<th className="w-[120px] px-3 font-medium">Stage</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{rows.map((it) => (
|
||||
<tr key={`${it.repo}#${it.number}`} className="border-b border-line align-top last:border-0 hover:bg-ink/[0.03]">
|
||||
<td className="max-w-0 px-3 py-2">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<StateIcon it={it} />
|
||||
<RefLink repo={it.repo} number={it.number} kind={it.kind} className="shrink-0 text-xs" />
|
||||
<Link to={`/item/${it.repo}/${it.number}`} className="truncate font-medium hover:text-accent-ink hover:underline" title={it.title}>
|
||||
{it.title}
|
||||
</Link>
|
||||
</div>
|
||||
{it.snippet && it.snippet.field !== "title" && (
|
||||
<div className="mt-0.5 line-clamp-2 pl-6">
|
||||
<SnippetText s={it.snippet} />
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
<td className="truncate px-3 py-2 text-ink/70">{it.author}</td>
|
||||
<td className="num whitespace-nowrap px-3 py-2 text-ink/55" title={`created ${it.createdAt.slice(0, 10)}, updated ${it.updatedAt.slice(0, 16).replace("T", " ")}`}>
|
||||
{it.updatedAt ? `${ago(it.updatedAt)} ago` : "–"}
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<SettledBadge s={it.settled} />
|
||||
</td>
|
||||
<td className="px-3 py-2">
|
||||
<Flags flags={it.settled.flags} />
|
||||
</td>
|
||||
<td className="px-3 py-2 text-xs text-ink/60">{it.stage ? STAGE[it.stage] : <span className="text-ink/30">–</span>}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Cards({ rows }: { rows: ItemListRow[] }) {
|
||||
return (
|
||||
<ul>
|
||||
{rows.map((it) => (
|
||||
<li key={`${it.repo}#${it.number}`} className="border-b border-line last:border-0">
|
||||
<Link to={`/item/${it.repo}/${it.number}`} className="block px-4 py-2.5 active:bg-ink/[0.05]">
|
||||
<div className="flex items-center gap-2 text-xs text-ink/55">
|
||||
<StateIcon it={it} />
|
||||
<span className="code">
|
||||
{it.repo}#{it.number}
|
||||
</span>
|
||||
<span className="truncate">{it.author}</span>
|
||||
<span className="num ml-auto shrink-0">{it.updatedAt ? `${ago(it.updatedAt)} ago` : ""}</span>
|
||||
</div>
|
||||
<div className="mt-1 text-sm font-medium leading-5">{it.title}</div>
|
||||
{it.snippet && it.snippet.field !== "title" && (
|
||||
<div className="mt-1 line-clamp-2">
|
||||
<SnippetText s={it.snippet} />
|
||||
</div>
|
||||
)}
|
||||
<div className="mt-1.5 flex flex-wrap items-center gap-1.5">
|
||||
<SettledBadge s={it.settled} />
|
||||
{it.settled.flags.length > 0 && <Flags flags={it.settled.flags} />}
|
||||
{it.stage && <span className="text-2xs text-ink/55">{STAGE[it.stage]}</span>}
|
||||
</div>
|
||||
</Link>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
);
|
||||
}
|
||||
|
||||
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 }] } }],
|
||||
};
|
||||
@@ -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
|
||||
<div
|
||||
key={p.label}
|
||||
className={cn("h-full transition-opacity duration-fast", p.cls, hover !== null && hover !== i && "opacity-40")}
|
||||
style={{ width: `${(p.value / sum) * 100}%` }}
|
||||
style={{ width: `${sum ? (p.value / sum) * 100 : 0}%` }}
|
||||
onMouseEnter={() => 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 = <span className="text-xs text-ink/45">not started yet</span>;
|
||||
return (
|
||||
<div>
|
||||
<div className="space-y-2">
|
||||
{steps.map((s) => (
|
||||
<div key={s.label} className="grid grid-cols-[76px_1fr_64px] md:grid-cols-[96px_1fr_88px] items-center gap-3">
|
||||
<div key={s.label} className={row}>
|
||||
<span className="text-xs text-ink/60">{s.label}</span>
|
||||
<div className="h-5 overflow-hidden rounded-sm bg-ink/[0.05]">
|
||||
<div className="h-full rounded-sm bg-ink/55" style={{ width: `${(s.value / f.open) * 100}%` }} />
|
||||
</div>
|
||||
{s.value || s.label === "Open" ? (
|
||||
<div className="h-5 overflow-hidden rounded-sm bg-ink/[0.05]">
|
||||
<div className="h-full rounded-sm bg-ink/55" style={{ width: share(s.value) }} />
|
||||
</div>
|
||||
) : (
|
||||
notStarted
|
||||
)}
|
||||
<span className="num text-right text-sm">
|
||||
{num(s.value)}
|
||||
{s.note && <span className="ml-1.5 hidden text-xs text-ink/45 md:inline">{s.note}</span>}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
<div className="grid grid-cols-[76px_1fr_64px] md:grid-cols-[96px_1fr_88px] items-center gap-3">
|
||||
<div className={row}>
|
||||
<span className="text-xs text-ink/60">Routed</span>
|
||||
<div className="h-5" style={{ width: `${Math.max((f.reviewed / f.open) * 100, 45)}%` }}>
|
||||
<StackBar parts={outcome} height={20} total={Math.max(routed, f.reviewed)} />
|
||||
</div>
|
||||
{routed ? (
|
||||
<div className="h-5" style={{ width: `${Math.max(f.open ? (f.reviewed / f.open) * 100 : 0, 45)}%` }}>
|
||||
<StackBar parts={outcome} height={20} total={Math.max(routed, f.reviewed)} />
|
||||
</div>
|
||||
) : (
|
||||
notStarted
|
||||
)}
|
||||
<span className="num text-right text-sm">{num(routed)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mt-4 md:pl-[108px]">
|
||||
<Legend items={outcome} />
|
||||
</div>
|
||||
{(f.secondOpinion > 0 || f.disagreement > 0) && (
|
||||
<p className="mt-3 text-xs text-ink/60">
|
||||
Not yet classified: <span className="num font-medium text-ink">{num(f.secondOpinion)}</span> waiting for a second opinion,{" "}
|
||||
<span className="num font-medium text-ink">{num(f.disagreement)}</span> where the two classifiers disagree.{" "}
|
||||
<Link to="/items?status=unsettled" className="text-accent-ink hover:underline">
|
||||
See them
|
||||
</Link>
|
||||
</p>
|
||||
)}
|
||||
{routed > 0 && (
|
||||
<div className="mt-4 md:pl-[108px]">
|
||||
<Legend items={outcome} />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -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 <span className={cn("text-2xs text-ink/35", className)}>from today</span>;
|
||||
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(" ");
|
||||
|
||||
@@ -33,28 +33,36 @@ function Block({ title, aside, children, className, flush }: { title: string; as
|
||||
);
|
||||
}
|
||||
|
||||
const NOT_STARTED = <span className="text-xs text-ink/45">not started yet</span>;
|
||||
|
||||
function Overview(_: ViewProps) {
|
||||
const { data: p } = useQuery("progress", (api) => api.progress());
|
||||
const phone = useIsPhone();
|
||||
if (!p) return <div className="p-6 text-ink/50">Loading…</div>;
|
||||
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 (
|
||||
<div className="h-full overflow-y-auto">
|
||||
<div className="mx-auto max-w-[1180px] px-4 pb-12 pt-5 md:px-6">
|
||||
<div className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5">
|
||||
<h1 className="text-xl font-semibold">Progress</h1>
|
||||
<span className="text-sm text-ink/55">
|
||||
Started {p.runStartedAt.slice(0, 10)} · day {days} · {p.repos.length} repos
|
||||
Tracking since {since} · {p.repos.length} repos
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid grid-cols-2 gap-3 lg:grid-cols-4">
|
||||
<Stat label="Open now" value={num(p.funnel.open)} sub={<>from {num(startOpen)} at run start</>} />
|
||||
<Stat label="Done since start" value={num(done)} sub={`${pct(p.done.mergedByPipeline + p.done.closedByPipeline, done)} by the pipeline`} />
|
||||
<Stat label="Throughput" value={`${avg} / h`} sub={`${num(p.perHour.reduce((a, b) => a + b, 0))} in the last 24 h`} />
|
||||
<Stat label="Open now" value={num(p.funnel.open)} sub={<>{num(startOpen)} when tracking began</>} />
|
||||
<Stat
|
||||
label="Done by the pipeline"
|
||||
value={num(ours)}
|
||||
sub={ours ? `${num(p.done.mergedByPipeline)} merged · ${num(p.done.closedByPipeline)} closed` : "not started yet"}
|
||||
/>
|
||||
<Stat label="Closed by others" value={num(p.done.closedByOthers)} sub={`on GitHub since ${since}`} />
|
||||
<Stat
|
||||
label="Decisions waiting"
|
||||
value={String(p.decisionsOpen)}
|
||||
@@ -68,11 +76,11 @@ function Overview(_: ViewProps) {
|
||||
</div>
|
||||
|
||||
<div className="mt-4 grid gap-4 lg:grid-cols-[1.4fr_1fr]">
|
||||
<Block title="Open items" aside={`${pct(p.funnel.reviewed, p.funnel.open)} reviewed`}>
|
||||
<Block title="Open items" aside={p.funnel.reviewed ? `${pct(p.funnel.reviewed, p.funnel.open)} reviewed` : undefined}>
|
||||
<FunnelChart f={p.funnel} />
|
||||
</Block>
|
||||
<Block title="Done since run start" aside={num(done)}>
|
||||
<DoneSplit done={p.done} />
|
||||
<Block title="Closed or merged since tracking began" aside={num(done)}>
|
||||
{done ? <DoneSplit done={p.done} /> : <p className="text-sm text-ink/50">Nothing closed yet.</p>}
|
||||
<table className="mt-4 w-full text-sm">
|
||||
<tbody>
|
||||
{DONE_PARTS.map((d) => (
|
||||
@@ -82,7 +90,7 @@ function Overview(_: ViewProps) {
|
||||
<span className={cn("size-2 rounded-sm", d.cls)} /> {d.label}
|
||||
</span>
|
||||
</td>
|
||||
<td className="num py-1.5 text-right font-medium">{num(p.done[d.key])}</td>
|
||||
<td className="num py-1.5 text-right font-medium">{d.key !== "closedByOthers" && !ours ? NOT_STARTED : num(p.done[d.key])}</td>
|
||||
<td className="num w-14 py-1.5 text-right text-ink/50">{pct(p.done[d.key], done)}</td>
|
||||
</tr>
|
||||
))}
|
||||
@@ -91,7 +99,7 @@ function Overview(_: ViewProps) {
|
||||
</Block>
|
||||
</div>
|
||||
|
||||
<Block title="Items done per hour" aside="Last 24 h, UTC" className="mt-4">
|
||||
<Block title="Items closed or merged per hour, by anyone" aside={`Last 24 h, UTC · ${num(lastDay)} in all, ${num(lastDayOurs)} by the pipeline`} className="mt-4">
|
||||
<Throughput perHour={p.perHour} nowIso={p.now} />
|
||||
</Block>
|
||||
|
||||
@@ -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 }) => (
|
||||
<th className={cn("h-8 px-3 font-medium", right ? "text-right" : "text-left", className)} aria-sort={k && sort.k === k ? (sort.desc ? "descending" : "ascending") : undefined}>
|
||||
{k ? (
|
||||
@@ -139,14 +149,14 @@ function RepoTable({ p }: { p: Progress }) {
|
||||
<Th k="reviewed" className="w-[200px]">
|
||||
Classified / reviewed
|
||||
</Th>
|
||||
<Th className="w-[200px]">Routed</Th>
|
||||
<Th className="w-[200px]">Routed{routedAny ? "" : " · not started yet"}</Th>
|
||||
<Th k="done" className="w-[220px]">
|
||||
Done
|
||||
</Th>
|
||||
<Th k="decisions" right className="w-[90px]">
|
||||
Waiting
|
||||
</Th>
|
||||
<Th className="w-[110px]">Open, 7 days</Th>
|
||||
<Th className="w-[110px]">Open, by day</Th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@@ -164,21 +174,19 @@ function RepoTable({ p }: { p: Progress }) {
|
||||
<td className="px-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="relative h-1.5 flex-1 overflow-hidden rounded-full bg-ink/[0.07]">
|
||||
<div className="absolute inset-y-0 left-0 bg-ink/25" style={{ width: `${(f.classified / f.open) * 100}%` }} />
|
||||
<div className="absolute inset-y-0 left-0 bg-ink/70" style={{ width: `${(f.reviewed / f.open) * 100}%` }} />
|
||||
<div className="absolute inset-y-0 left-0 bg-ink/25" style={{ width: share(f.classified, f.open) }} />
|
||||
<div className="absolute inset-y-0 left-0 bg-ink/70" style={{ width: share(f.reviewed, f.open) }} />
|
||||
</div>
|
||||
<span className="num w-[72px] text-right text-xs text-ink/55">
|
||||
{pct(f.classified, f.open)} / {pct(f.reviewed, f.open)}
|
||||
</span>
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-3">
|
||||
<StackBar parts={OUTCOMES.map((o) => ({ ...o, value: f[o.key] }))} height={6} />
|
||||
</td>
|
||||
<td className="px-3">{routedAny ? <StackBar parts={OUTCOMES.map((o) => ({ ...o, value: f[o.key] }))} height={6} /> : <span className="text-ink/30">–</span>}</td>
|
||||
<td className="px-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<div className="flex-1">
|
||||
<div style={{ width: `${(d / maxDone) * 100}%` }}>
|
||||
<div style={{ width: share(d, maxDone) }}>
|
||||
<StackBar parts={DONE_PARTS.map((x) => ({ ...x, value: r.done[x.key] }))} height={6} />
|
||||
</div>
|
||||
</div>
|
||||
@@ -209,11 +217,15 @@ function RepoCards({ p }: { p: Progress }) {
|
||||
{r.decisionsOpen > 0 && <span className="text-xs text-warn">{r.decisionsOpen} waiting</span>}
|
||||
<span className="num ml-auto">{num(r.funnel.open)} open</span>
|
||||
</div>
|
||||
<div className="mt-1.5">
|
||||
<StackBar parts={OUTCOMES.map((o) => ({ ...o, value: r.funnel[o.key] }))} height={5} />
|
||||
</div>
|
||||
{OUTCOMES.some((o) => r.funnel[o.key] > 0) && (
|
||||
<div className="mt-1.5">
|
||||
<StackBar parts={OUTCOMES.map((o) => ({ ...o, value: r.funnel[o.key] }))} height={5} />
|
||||
</div>
|
||||
)}
|
||||
<div className="num mt-1 flex justify-between text-xs text-ink/50">
|
||||
<span>{pct(r.funnel.reviewed, r.funnel.open)} reviewed</span>
|
||||
<span>
|
||||
{pct(r.funnel.classified, r.funnel.open)} classified{r.funnel.reviewed ? ` · ${pct(r.funnel.reviewed, r.funnel.open)} reviewed` : ""}
|
||||
</span>
|
||||
<span>{num(doneTotal(r.done))} done</span>
|
||||
</div>
|
||||
</li>
|
||||
|
||||
@@ -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];
|
||||
+21
-13
@@ -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) => (
|
||||
<Route key={r.path} path={r.path} element={<RouteView route={r} />} />
|
||||
))}
|
||||
<Route path="*" element={<div className="p-8 text-ink/60">Nothing here.</div>} />
|
||||
<Route path="*" element={<NoRoute hidden={hiddenPaths} />} />
|
||||
</Routes>
|
||||
);
|
||||
|
||||
@@ -67,6 +69,7 @@ export function AppShell() {
|
||||
<header className="flex h-12 shrink-0 items-center gap-1 border-b border-line bg-bg pl-4 pr-1.5">
|
||||
<Wordmark />
|
||||
<div className="flex-1" />
|
||||
<RoleChip />
|
||||
<button aria-label="Search" onClick={() => setSearchOpen(true)} className="flex size-11 items-center justify-center text-ink/70">
|
||||
<SearchIcon className="text-[18px]" />
|
||||
</button>
|
||||
@@ -243,7 +246,7 @@ function Breadcrumb({ routes }: { routes: RouteDef[] }) {
|
||||
function LiveCounters() {
|
||||
const { data } = useQuery("progress", (api) => api.progress());
|
||||
if (!data) return null;
|
||||
const lastHour = data.perHour[data.perHour.length - 1];
|
||||
const lastHour = data.perHourPipeline[data.perHourPipeline.length - 1] ?? 0;
|
||||
return (
|
||||
<div className="hidden shrink-0 items-center gap-3 whitespace-nowrap text-xs text-ink/60 xl:flex">
|
||||
<span className="flex items-center gap-1.5">
|
||||
@@ -252,7 +255,7 @@ function LiveCounters() {
|
||||
</span>
|
||||
<span className="flex items-center gap-1.5">
|
||||
<span className="size-1.5 rounded-full bg-ok" />
|
||||
<span className="num font-medium text-ink">{lastHour}</span> done in the last hour
|
||||
<span className="num font-medium text-ink">{lastHour}</span> done by the pipeline in the last hour
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
@@ -389,32 +392,37 @@ function ShortcutSheet({ open, onOpenChange }: { open: boolean; onOpenChange: (o
|
||||
function RunMeter({ open }: { open: boolean }) {
|
||||
const { data } = useQuery("progress", (api) => api.progress());
|
||||
if (!data || !open) return null;
|
||||
const done = data.done.mergedByPipeline + data.done.closedByPipeline + data.done.closedByOthers;
|
||||
const all = done + data.funnel.open;
|
||||
const ours = data.done.mergedByPipeline + data.done.closedByPipeline;
|
||||
const f = data.funnel;
|
||||
return (
|
||||
<NavLink to="/progress" className="mx-2 mb-2 block rounded-md border border-line p-2.5 hover:border-line-strong">
|
||||
<div className="flex items-baseline justify-between text-xs">
|
||||
<span className="font-medium text-ink/80">Backlog</span>
|
||||
<span className="num text-ink/55">{Math.round((done / all) * 100)}%</span>
|
||||
<span className="font-medium text-ink/80">Classified</span>
|
||||
<span className="num text-ink/55">{f.open ? Math.round((f.classified / f.open) * 100) : 0}%</span>
|
||||
</div>
|
||||
<div className="mt-2 flex h-1 gap-px overflow-hidden rounded-full bg-ink/10">
|
||||
<div className="bg-c1" style={{ width: `${(data.done.mergedByPipeline / all) * 100}%` }} />
|
||||
<div className="bg-c2" style={{ width: `${(data.done.closedByPipeline / all) * 100}%` }} />
|
||||
<div className="bg-ink/40" style={{ width: `${(data.done.closedByOthers / all) * 100}%` }} />
|
||||
<div className="bg-c1" style={{ width: `${f.open ? (f.classified / f.open) * 100 : 0}%` }} />
|
||||
</div>
|
||||
<div className="num mt-1.5 text-2xs text-ink/50">
|
||||
{num(done)} done · {num(data.funnel.open)} open
|
||||
{num(f.open)} open · {ours ? `${num(ours)} done by the pipeline` : "pipeline not started yet"}
|
||||
</div>
|
||||
</NavLink>
|
||||
);
|
||||
}
|
||||
|
||||
/** A page this reader's role doesn't open says so; anything else is unknown. */
|
||||
function NoRoute({ hidden }: { hidden: string[] }) {
|
||||
const { pathname } = useLocation();
|
||||
const restricted = hidden.some((p) => matchPath({ path: `/${p}`, end: false }, pathname));
|
||||
return <div className="p-8 text-ink/60">{restricted ? "Operators only." : "Nothing here."}</div>;
|
||||
}
|
||||
|
||||
/** The reader's role decides what every button means, so it stays visible. */
|
||||
function RoleChip() {
|
||||
const user = useUser();
|
||||
const tone: Tone = user.role === "operator" ? "accent" : "neutral";
|
||||
return (
|
||||
<span className="hidden lg:inline-flex" title="Your role on this dashboard">
|
||||
<span className="inline-flex shrink-0" title="Your role on this dashboard">
|
||||
<Badge tone={tone}>{roleLabel(user)}</Badge>
|
||||
</span>
|
||||
);
|
||||
|
||||
@@ -18,6 +18,10 @@ export function SearchBox({ autoFocus, onPick, fullscreen }: { autoFocus?: boole
|
||||
|
||||
useEffect(() => {
|
||||
let live = true;
|
||||
if (!q.trim()) {
|
||||
setHits([]);
|
||||
return;
|
||||
}
|
||||
const t = setTimeout(() => api.search(q).then((h) => live && (setHits(h), setSel(0))), 90);
|
||||
return () => {
|
||||
live = false;
|
||||
@@ -25,13 +29,16 @@ export function SearchBox({ autoFocus, onPick, fullscreen }: { autoFocus?: boole
|
||||
};
|
||||
}, [q, api]);
|
||||
|
||||
const pick = (h: SearchHit) => {
|
||||
navigate(`/item/${h.repo}/${h.number}`);
|
||||
const go = (to: string) => {
|
||||
navigate(to);
|
||||
setQ("");
|
||||
onPick?.();
|
||||
(document.activeElement as HTMLElement | null)?.blur();
|
||||
};
|
||||
const open = (focus || fullscreen) && q.length > 0;
|
||||
const pick = (h: SearchHit) => go(`/item/${h.repo}/${h.number}`);
|
||||
const isRef = /^([A-Za-z0-9._-]+)?#?\d+$/.test(q.trim());
|
||||
const seeAll = () => go(`/items?${new URLSearchParams({ q: q.trim(), state: "all" })}`);
|
||||
const open = (focus || fullscreen) && q.trim().length > 0;
|
||||
|
||||
return (
|
||||
<div className={cn("relative", fullscreen && "flex-1")}>
|
||||
@@ -47,10 +54,13 @@ export function SearchBox({ autoFocus, onPick, fullscreen }: { autoFocus?: boole
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === "ArrowDown") (e.preventDefault(), setSel((s) => Math.min(s + 1, hits.length - 1)));
|
||||
if (e.key === "ArrowUp") (e.preventDefault(), setSel((s) => Math.max(s - 1, 0)));
|
||||
if (e.key === "Enter" && hits[sel]) pick(hits[sel]);
|
||||
if (e.key === "Enter") {
|
||||
if (hits[sel]) pick(hits[sel]);
|
||||
else if (!isRef) seeAll();
|
||||
}
|
||||
if (e.key === "Escape") (e.target as HTMLInputElement).blur();
|
||||
}}
|
||||
placeholder="photocraft#4127, title or author"
|
||||
placeholder="photocraft#4127, words or a login"
|
||||
aria-label="Search issues and PRs"
|
||||
className="min-w-0 flex-1 bg-transparent text-sm text-ink outline-none placeholder:text-ink/35"
|
||||
role="combobox"
|
||||
@@ -61,7 +71,7 @@ export function SearchBox({ autoFocus, onPick, fullscreen }: { autoFocus?: boole
|
||||
</label>
|
||||
{open && (
|
||||
<ul id="search-results" role="listbox" className={cn("z-50 rounded-md border border-line-strong bg-raised p-1 animate-fadeIn", fullscreen ? "mt-2" : "absolute inset-x-0 top-[calc(100%+4px)] shadow-[0_12px_32px_rgba(0,0,0,0.28)]")}>
|
||||
{hits.length === 0 && <li className="px-3 py-2 text-sm text-ink/50">No matches</li>}
|
||||
{hits.length === 0 && <li className="px-3 py-2 text-sm text-ink/50">No matches in titles, descriptions or logins</li>}
|
||||
{hits.map((h, i) => (
|
||||
<li key={`${h.repo}#${h.number}`} role="option" aria-selected={i === sel}>
|
||||
<div onMouseDown={() => pick(h)} onMouseEnter={() => setSel(i)} className={cn("flex w-full cursor-pointer items-center gap-2.5 rounded px-2 text-left", fullscreen ? "h-12" : "h-8", i === sel && "bg-ink/[0.07]")}>
|
||||
@@ -72,6 +82,13 @@ export function SearchBox({ autoFocus, onPick, fullscreen }: { autoFocus?: boole
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
{!isRef && (
|
||||
<li role="option" aria-selected={false}>
|
||||
<div onMouseDown={seeAll} className={cn("flex w-full cursor-pointer items-center gap-2 rounded border-t border-line px-2 text-sm text-accent-ink hover:bg-ink/[0.07]", fullscreen ? "h-12" : "h-8")}>
|
||||
<SearchIcon className="text-xs" /> See all results, comments included
|
||||
</div>
|
||||
</li>
|
||||
)}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
|
||||
+5
-25
@@ -3,28 +3,9 @@ import ReactMarkdown, { type Components } from "react-markdown";
|
||||
import remarkGfm from "remark-gfm";
|
||||
import { ImageIcon, ExternalLinkIcon } from "lucide-react";
|
||||
import { cn } from "./cn";
|
||||
import { proxiedImage, remarkHtmlToMarkdown, safeUrl } from "./markdownHtml";
|
||||
|
||||
// Images the server's proxy (GET /img, src/dash/server/images.ts) fetches:
|
||||
// the same hosts and path shapes. Anything else stays a link.
|
||||
const PROXIED: [string, RegExp][] = [
|
||||
["github.com", /^\/user-attachments\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i],
|
||||
["private-user-images.githubusercontent.com", /^\/./],
|
||||
["user-images.githubusercontent.com", /^\/./],
|
||||
["raw.githubusercontent.com", /^\/storytold\/./],
|
||||
["avatars.githubusercontent.com", /^\/./],
|
||||
];
|
||||
|
||||
export function proxiedImage(src: string): string | null {
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(src);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (u.protocol !== "https:" || u.username || u.password || u.port) return null;
|
||||
if (!PROXIED.some(([host, path]) => u.hostname === host && path.test(u.pathname))) return null;
|
||||
return `/img?${new URLSearchParams({ u: u.href })}`;
|
||||
}
|
||||
export { proxiedImage };
|
||||
|
||||
function ImageLink({ src, alt }: { src?: string; alt?: string }) {
|
||||
return (
|
||||
@@ -50,7 +31,8 @@ function Image({ src, alt }: { src?: string; alt?: string }) {
|
||||
}
|
||||
|
||||
// GitHub-flavoured Markdown from issue and PR bodies. Untrusted input:
|
||||
// raw HTML is dropped (skipHtml), links open in a new tab without referrer,
|
||||
// common HTML (images, links, breaks, block tags) becomes Markdown nodes and
|
||||
// all other raw HTML is dropped (markdownHtml.ts, skipHtml), links open in a new tab without referrer,
|
||||
// and only GitHub-hosted images load inline, through the same-origin proxy
|
||||
// (the CSP allows only same-origin images); others become a link the reader
|
||||
// can choose to open.
|
||||
@@ -63,12 +45,10 @@ const components: Components = {
|
||||
img: ({ src, alt }) => <Image src={typeof src === "string" ? src : undefined} alt={alt} />,
|
||||
};
|
||||
|
||||
const safeUrl = (url: string) => (/^(https?:|mailto:|#|\/)/i.test(url) ? url : "");
|
||||
|
||||
export function Markdown({ source, className }: { source: string; className?: string }) {
|
||||
return (
|
||||
<div className={cn("md", className)}>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm]} skipHtml components={components} urlTransform={safeUrl}>
|
||||
<ReactMarkdown remarkPlugins={[remarkGfm, remarkHtmlToMarkdown]} skipHtml components={components} urlTransform={safeUrl}>
|
||||
{source}
|
||||
</ReactMarkdown>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
// The safety rules for untrusted Markdown (issue, PR and comment bodies), kept
|
||||
// free of React so the server tests can run them.
|
||||
//
|
||||
// Raw HTML never reaches the page. `remarkHtmlToMarkdown` turns the HTML that
|
||||
// GitHub bodies commonly use into plain Markdown nodes instead: `<img>` becomes
|
||||
// an image (shown through the proxy or as a link chip, like ``),
|
||||
// `<video>` a link, `<a href>` a link, `<br>` a line break, `<b>`/`<i>`/`<code>`
|
||||
// their Markdown forms, and block tags (`<p>`, `<details>`, `<summary>`, `<li>`,
|
||||
// headings) paragraphs. Only src, alt and href are read from attributes; every
|
||||
// other tag is dropped and its text kept as text. The contents of script, style
|
||||
// and similar tags are dropped. URLs still pass `safeUrl` in the renderer.
|
||||
|
||||
// Images the server's proxy (GET /img, src/dash/server/images.ts) fetches:
|
||||
// the same hosts and path shapes. Anything else stays a link.
|
||||
const PROXIED: [string, RegExp][] = [
|
||||
["github.com", /^\/user-attachments\/assets\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i],
|
||||
["private-user-images.githubusercontent.com", /^\/./],
|
||||
["user-images.githubusercontent.com", /^\/./],
|
||||
["raw.githubusercontent.com", /^\/storytold\/./],
|
||||
["avatars.githubusercontent.com", /^\/./],
|
||||
];
|
||||
|
||||
export function proxiedImage(src: string): string | null {
|
||||
let u: URL;
|
||||
try {
|
||||
u = new URL(src);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (u.protocol !== "https:" || u.username || u.password || u.port) return null;
|
||||
if (!PROXIED.some(([host, path]) => u.hostname === host && path.test(u.pathname))) return null;
|
||||
return `/img?${new URLSearchParams({ u: u.href })}`;
|
||||
}
|
||||
|
||||
export const safeUrl = (url: string): string => (/^(https?:|mailto:|#|\/)/i.test(url) ? url : "");
|
||||
|
||||
// Minimal mdast shapes; the plugin builds only these.
|
||||
export type MdNode = {
|
||||
type: string;
|
||||
value?: string;
|
||||
url?: string;
|
||||
alt?: string;
|
||||
title?: string | null;
|
||||
children?: MdNode[];
|
||||
};
|
||||
|
||||
const PHRASING_PARENTS = new Set(["paragraph", "heading", "tableCell", "emphasis", "strong", "delete", "link", "linkReference"]);
|
||||
const BLOCK_TAGS = new Set([
|
||||
"p", "div", "center", "li", "ul", "ol", "details", "summary", "table", "thead", "tbody", "tr", "td", "th",
|
||||
"blockquote", "pre", "hr", "h1", "h2", "h3", "h4", "h5", "h6", "dl", "dt", "dd", "figure", "figcaption", "section",
|
||||
]);
|
||||
const HEADINGS = new Set(["summary", "h1", "h2", "h3", "h4", "h5", "h6"]);
|
||||
// Tags whose content is not text the reader should see.
|
||||
const SKIP_CONTENT = new Set(["script", "style", "template", "iframe", "object", "embed", "svg", "math", "noscript", "textarea", "select", "head", "title"]);
|
||||
|
||||
const TOKEN = /<!--[\s\S]*?(?:-->|$)|<(\/?)([a-zA-Z][a-zA-Z0-9-]*)((?:\s+[^\s"'>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'>]+))?)*)\s*\/?>/g;
|
||||
const ATTR = /([^\s"'>/=]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g;
|
||||
|
||||
const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " " };
|
||||
function decode(s: string): string {
|
||||
return s.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (m, e: string) => {
|
||||
if (e[0] === "#") {
|
||||
const cp = e[1] === "x" || e[1] === "X" ? parseInt(e.slice(2), 16) : parseInt(e.slice(1), 10);
|
||||
return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : m;
|
||||
}
|
||||
return ENTITIES[e.toLowerCase()] ?? m;
|
||||
});
|
||||
}
|
||||
|
||||
function attrs(s: string): Map<string, string> {
|
||||
const out = new Map<string, string>();
|
||||
for (const m of s.matchAll(ATTR)) out.set(m[1]!.toLowerCase(), decode(m[2] ?? m[3] ?? m[4] ?? "").trim());
|
||||
return out;
|
||||
}
|
||||
|
||||
const fileName = (url: string) => {
|
||||
try {
|
||||
return decodeURIComponent(new URL(url).pathname.split("/").pop() ?? "");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
// Builds Markdown nodes from a run of HTML strings and ready nodes. In block
|
||||
// mode the output is paragraphs; in inline mode block tags become line breaks.
|
||||
class Builder {
|
||||
private out: MdNode[] = [];
|
||||
private stack: MdNode[] = [];
|
||||
private skip: string[] = [];
|
||||
private code: MdNode | null = null;
|
||||
private pendingVideo: MdNode | null = null;
|
||||
private block: boolean;
|
||||
constructor(block: boolean) {
|
||||
this.block = block;
|
||||
}
|
||||
|
||||
private top(): MdNode {
|
||||
if (this.stack.length === 0) {
|
||||
const p: MdNode = this.block ? { type: "paragraph", children: [] } : { type: "fragment", children: [] };
|
||||
this.stack.push(p);
|
||||
}
|
||||
return this.stack[this.stack.length - 1]!;
|
||||
}
|
||||
|
||||
private add(n: MdNode) {
|
||||
this.top().children!.push(n);
|
||||
}
|
||||
|
||||
private text(s: string) {
|
||||
if (this.skip.length) return;
|
||||
if (this.code) {
|
||||
this.code.value += decode(s);
|
||||
return;
|
||||
}
|
||||
let t = decode(s).replace(/\s+/g, " ");
|
||||
const empty = this.stack.length === 0 || (this.stack.length === 1 && this.stack[0]!.children!.length === 0);
|
||||
if (empty) t = t.replace(/^ /, "");
|
||||
if (!t) return;
|
||||
const kids = this.top().children!;
|
||||
const last = kids[kids.length - 1];
|
||||
if (last?.type === "text") last.value += t;
|
||||
else kids.push({ type: "text", value: t });
|
||||
}
|
||||
|
||||
// Closes every open container and emits the paragraph (block mode) or its
|
||||
// children (inline mode).
|
||||
private flush() {
|
||||
while (this.stack.length > 1) this.pop();
|
||||
const root = this.stack.pop();
|
||||
this.code = null;
|
||||
if (!root) return;
|
||||
const kids = root.children!;
|
||||
while (kids.length && kids[kids.length - 1]!.type === "text" && !kids[kids.length - 1]!.value!.trim()) kids.pop();
|
||||
if (!kids.length) return;
|
||||
if (this.block) this.out.push(root);
|
||||
else this.out.push(...kids);
|
||||
}
|
||||
|
||||
private pop() {
|
||||
const n = this.stack.pop()!;
|
||||
if (n.type === "link" && n.children!.length === 0) n.children!.push({ type: "text", value: n.url! });
|
||||
this.top().children!.push(n);
|
||||
}
|
||||
|
||||
private popTo(type: string) {
|
||||
const i = this.stack.findLastIndex((n) => n.type === type);
|
||||
if (i <= 0) return;
|
||||
while (this.stack.length > i) this.pop();
|
||||
}
|
||||
|
||||
private open(type: string, extra: Partial<MdNode> = {}) {
|
||||
this.top();
|
||||
this.stack.push({ type, children: [], ...extra });
|
||||
}
|
||||
|
||||
private blockBreak() {
|
||||
if (this.block) this.flush();
|
||||
else {
|
||||
const kids = this.top().children!;
|
||||
if (kids.length && kids[kids.length - 1]!.type !== "break") this.add({ type: "break" });
|
||||
}
|
||||
}
|
||||
|
||||
private tag(close: boolean, name: string, rawAttrs: string) {
|
||||
if (this.skip.length) {
|
||||
if (name === this.skip[this.skip.length - 1]) {
|
||||
if (close) this.skip.pop();
|
||||
else this.skip.push(name);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (SKIP_CONTENT.has(name)) {
|
||||
if (!close && !/\/\s*$/.test(rawAttrs)) this.skip.push(name);
|
||||
return;
|
||||
}
|
||||
if (name === "code" || name === "tt" || name === "kbd") {
|
||||
if (close) this.code = null;
|
||||
else if (!this.code) {
|
||||
this.code = { type: "inlineCode", value: "" };
|
||||
this.add(this.code);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (this.code) return;
|
||||
const a = close ? new Map<string, string>() : attrs(rawAttrs);
|
||||
switch (name) {
|
||||
case "img": {
|
||||
const src = a.get("src");
|
||||
if (src) this.add({ type: "image", url: src, alt: a.get("alt") ?? "", title: null });
|
||||
return;
|
||||
}
|
||||
case "video": {
|
||||
if (close) {
|
||||
this.pendingVideo = null;
|
||||
return;
|
||||
}
|
||||
const src = a.get("src");
|
||||
const link: MdNode = { type: "link", url: src ?? "", title: null, children: [{ type: "text", value: "Video" }] };
|
||||
this.pendingVideo = src ? null : link;
|
||||
if (src) this.addVideo(link);
|
||||
return;
|
||||
}
|
||||
case "source": {
|
||||
const src = a.get("src");
|
||||
if (this.pendingVideo && src) {
|
||||
this.pendingVideo.url = src;
|
||||
this.addVideo(this.pendingVideo);
|
||||
this.pendingVideo = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
case "br":
|
||||
if (!close) this.add({ type: "break" });
|
||||
return;
|
||||
case "a": {
|
||||
if (close) return this.popTo("link");
|
||||
const href = a.get("href");
|
||||
if (href && !this.stack.some((n) => n.type === "link")) this.open("link", { url: href, title: null });
|
||||
return;
|
||||
}
|
||||
case "b":
|
||||
case "strong":
|
||||
return close ? this.popTo("strong") : this.open("strong");
|
||||
case "i":
|
||||
case "em":
|
||||
return close ? this.popTo("emphasis") : this.open("emphasis");
|
||||
}
|
||||
if (!BLOCK_TAGS.has(name)) return;
|
||||
this.blockBreak();
|
||||
if (close) return;
|
||||
if (HEADINGS.has(name)) this.open("strong");
|
||||
else if (name === "li") this.text("• ");
|
||||
else if (name === "td" || name === "th") this.text(" ");
|
||||
}
|
||||
|
||||
private addVideo(link: MdNode) {
|
||||
const name = fileName(link.url!);
|
||||
link.children = [{ type: "text", value: name ? `Video: ${name}` : "Video" }];
|
||||
this.add(link);
|
||||
}
|
||||
|
||||
html(s: string) {
|
||||
let last = 0;
|
||||
for (const m of s.matchAll(TOKEN)) {
|
||||
if (m.index > last) this.text(s.slice(last, m.index));
|
||||
last = m.index + m[0].length;
|
||||
if (m[2]) this.tag(m[1] === "/", m[2].toLowerCase(), m[3] ?? "");
|
||||
}
|
||||
if (last < s.length) this.text(s.slice(last));
|
||||
}
|
||||
|
||||
node(n: MdNode) {
|
||||
if (this.skip.length) return;
|
||||
if (this.code && (n.type === "text" || n.type === "inlineCode")) this.code.value += n.value ?? "";
|
||||
else this.add(n);
|
||||
}
|
||||
|
||||
done(): MdNode[] {
|
||||
this.flush();
|
||||
return this.out;
|
||||
}
|
||||
}
|
||||
|
||||
/** The nodes one block-level HTML string becomes. */
|
||||
export function htmlBlock(html: string): MdNode[] {
|
||||
const b = new Builder(true);
|
||||
b.html(html);
|
||||
return b.done();
|
||||
}
|
||||
|
||||
/** Rewrites a phrasing parent's children, where each HTML tag is its own node. */
|
||||
export function inlineChildren(children: MdNode[]): MdNode[] {
|
||||
const b = new Builder(false);
|
||||
for (const c of children) {
|
||||
if (c.type === "html") b.html(c.value ?? "");
|
||||
else b.node(c);
|
||||
}
|
||||
return b.done();
|
||||
}
|
||||
|
||||
function walk(n: MdNode) {
|
||||
const kids = n.children;
|
||||
if (!kids) return;
|
||||
for (const c of kids) walk(c);
|
||||
if (!kids.some((c) => c.type === "html")) return;
|
||||
if (PHRASING_PARENTS.has(n.type)) n.children = inlineChildren(kids);
|
||||
else n.children = kids.flatMap((c) => (c.type === "html" ? htmlBlock(c.value ?? "") : [c]));
|
||||
}
|
||||
|
||||
/** Remark plugin: replaces raw HTML nodes with the Markdown nodes above. */
|
||||
export function remarkHtmlToMarkdown() {
|
||||
return (tree: MdNode) => walk(tree);
|
||||
}
|
||||
Reference in new issue
Block a user