Files
seal-use/src/cli/read-only.ts
T
gitea d3c44e02d7 Add local human adjudication store that computes human review accuracy
The report previously could not compute human accuracy because upstream only
says whether AI and human agree, never who was right. This adds an append-only
local store so a reviewer judges each (typically diverged) document across
weekly passes, and report monthly folds those judgments back in.

- review-store.ts: JSONL per tenant+month (~/.config/seal-use/reviews/
  <corpId>-<YYYY-MM>.jsonl), append-only (weekly passes never rewrite), one
  record per SN; last write wins on re-adjudication. Verdicts: ai_correct,
  human_correct, both_correct, both_wrong, undecided. Env-overridable root
  (SEAL_USE_REVIEWS_DIR) for tests; corrupt lines skipped.
- collect.ts: load the store, join verdicts onto fetched blocks, compute
  humanAccuracy = (human_right / reviewed) * 100 over adjudicated samples,
  expose reviewedCount/divergedCount, and flip humanAccuracyAvailable. No
  reviews -> honest gap (still unavailable), never fabricated.
- render.ts: when available, fill the §1.2 human row with real accuracy and
  replace the gap warning with a coverage note; when not, keep the warning.
- CLI: `report review set/list --month ... [--sn --verdict --note
  --reviewed-by]` (set writes local store, list reads it). Help registers
  both as separate commands; read-only list vs mutating set classified
  accordingly. Prefix help (`report review --help`) now lists subcommands
  instead of erroring.
- parser: register --template/--report-id/--max-runs/--verdict/--reviewed-by
  (the first three were previously rejected as unknown, breaking report
  monthly's own flags); reviewed-by moves to VALUE_FLAGS so it consumes its
  argument.
- SKILL.md: document the adjudication workflow and storage semantics.

Verified: 639 tests (6 new review tests incl. tenant/month isolation, corrupt
line skip, join + accuracy math, honest no-review gap, render coverage note),
tsc clean, oxlint 0 warnings.
2026-09-30 18:59:26 +08:00

146 lines
5.7 KiB
TypeScript

import { parseArgs } from "./parser.js";
/**
* Read-only classification for CLI commands, used to decide whether a command may be executed
* through the read-only MCP tool.
*
* This is an allow-list: anything not listed here — including a command added to the CLI later —
* is treated as mutating. The failure mode is therefore a refused read, never an unsafe write.
*
* Matching is token-wise prefix, because positional arguments are parsed into the command: a
* command line of `approval-runs get 01a09dac...` must still match the allowed `approval-runs get`.
* Prefix matching is boundary-safe by construction: `list-evil` does not match `list`.
*/
/** Area aliases the CLI dispatches under an alternative name; mirrors the pairs in runner.ts. */
const AREA_ALIASES: Record<string, string> = {
corp: "corps",
webhooks: "webhook",
preferences: "preference"
};
/**
* Commands that only read tenant state, produce a local file, or inspect local configuration.
* Deliberately excluded even though they look harmless: anything that writes local config
* (`corps switch`, `config test-dir`, `config mode <value>`, `config lint <subaction>`), mints
* or prints credentials (`auth keys`, `corps keys`),
* self-updates (`update`), or stands up a long-running server (`mcp`).
*/
const READ_ONLY_COMMANDS: Record<string, string[]> = {
corps: ["list", "search", "get", "current"],
rules: ["count", "list", "versions", "version", "diff", "get", "search", "lint", "linters", "pull", "map"],
documents: ["list", "get", "search"],
webhook: ["ready", "status", "list", "get", "resource-pack export", "resource-pack preview"],
"approval-runs": [
"summary",
"stats",
"count",
"export",
"flow",
"list",
// `search` is an accepted alias of `list` in the dispatcher but has no help-registry entry.
"search",
"pick",
"bridge",
"get",
"cited-rules",
"diagnose",
"document-summary",
"attachments",
"result",
"link",
"url"
],
simulation: [
"batch-records",
"status",
"wait",
"specifications",
"approval-definitions",
"list",
"get",
"templates",
"integrations"
],
deploy: ["hosecloud requirements", "hosecloud list", "hosecloud get", "hosecloud status"],
preference: ["get", "thinking-depth policies list"],
// `config mode`/`config lint` are omitted: classification is token-prefix based, so their
// read forms cannot be separated from the value-taking write forms. `config get` returns
// the same summary (mode + lint included), so read access loses nothing.
config: ["paths", "get"],
auth: ["check", "diagnose", "status", "test", "doctor", "link list"],
users: ["search", "get", "delegation"],
contacts: ["departments", "children", "users", "sync-time"],
data: ["expenses", "invoices"],
llm: ["config", "providers"],
permissions: ["available", "configs"],
billing: ["status", "plans", "features"],
// `analyze` is deliberately absent: it POSTs and starts an analysis server-side, so it is a
// mutation despite reading like a query. See SEAL_MUTATING_CAPABILITIES.
analytics: ["insight", "risks", "performance", "export"],
report: ["monthly", "review list"],
source: ["config"],
skill: ["dump", "status"],
doctor: ["", "guide", "paths", "tenant", "auth"],
// Bare form only; the optional trailing `<corpId>` selector is handled by
// SELECTOR_POSITIONAL_AREAS below, since a bare entry matches no tokens.
probe: [""]
};
/**
* Areas whose trailing positional is an enterprise selector, not a subcommand:
* `seal-use probe [<corpId>]` has no verb to list, so its read form is the bare
* command plus at most that one selector. A second token is not a form the area
* accepts at all, and falls through to the refusal below.
*/
const SELECTOR_POSITIONAL_AREAS = new Set(["probe"]);
/**
* Read-only commands handled by the CLI outside the help registry (no area/subcommand shape).
* `help` is limited to the bare form on purpose: `help <topic>` adds nothing over the skill docs.
*/
const TOP_LEVEL_READ_ONLY = new Set(["version", "v", "help", "changelog", "mcp-config"]);
export function describeCliCommand(argv: string[]): { area: string; actionTokens: string[] } {
const { command } = parseArgs(argv);
const area = (command[0] ?? "").toLowerCase();
return {
area: AREA_ALIASES[area] ?? area,
actionTokens: command.slice(1).map((token) => token.toLowerCase())
};
}
export function isReadOnlyCliCommand(argv: string[]): boolean {
let area: string;
let actionTokens: string[];
try {
({ area, actionTokens } = describeCliCommand(argv));
} catch {
// Unparsable command lines are refused rather than guessed at.
return false;
}
if (actionTokens.length === 0 && TOP_LEVEL_READ_ONLY.has(area)) return true;
// The `<corpId>` selector form; the bare form falls through to the `""` entry.
if (SELECTOR_POSITIONAL_AREAS.has(area) && actionTokens.length === 1) return true;
const allowed = READ_ONLY_COMMANDS[area];
if (!allowed) return false;
return allowed.some((entry) => {
const allowedTokens = entry.split(" ").filter(Boolean);
// A bare command (empty entry) matches only when no subcommand was given, so that listing
// `doctor` does not also cover every `doctor <subcommand>`.
if (allowedTokens.length === 0) return actionTokens.length === 0;
if (allowedTokens.length > actionTokens.length) return false;
return allowedTokens.every((token, index) => token === actionTokens[index]);
});
}
/** Registry-backed entries only; the top-level commands above have no registry row. */
export function listReadOnlyCommands(): Array<{ area: string; action: string }> {
return Object.entries(READ_ONLY_COMMANDS).flatMap(([area, actions]) =>
actions.map((action) => ({ area, action }))
);
}