Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

📝 docs(skills): add the alint rule-set lifecycle skill (#20262)

Arvin Xu2e1775906c62
diff --git a/.agents/skills/alint-ruleset/SKILL.md b/.agents/skills/alint-ruleset/SKILL.md
new file mode 100644
index 00000000000..630a5019780
--- /dev/null
+++ b/.agents/skills/alint-ruleset/SKILL.md
@@ -0,0 +1,103 @@
+---
+name: alint-ruleset
+description: "Maintain LobeHub's model-backed alint rule set in packages/alint: author a rule, calibrate its false positives against real source, decide its severity (warn vs error) from real PR data, and track its token cost. Use for adding or narrowing an alint rule, classifying findings as true/false positives, promoting or demoting a rule, or running the weekly rule-set review."
+argument-hint: "add <rule> | calibrate <rule> | promote | weekly"
+---
+
+# alint rule set
+
+`packages/alint` holds the model-backed lint rules for the judgement calls ESLint cannot
+express — semantic rules such as "fan-out over a runtime-sized list needs `pMap`" or "a
+secondary button is not `primary`". Each rule is a prompt that runs per file through
+[alint](https://github.com/moeru-ai/alint) and is cached by file content.
+
+This skill owns the **lifecycle** of that rule set: how a rule is written, how its false
+positives are removed, when it earns `error`, and what it costs. It does **not** own the
+rules themselves (they live in `packages/alint/rules`) and it does not restate the reading
+contract — that is `packages/alint/README.md`. Read that file once before editing a rule.
+
+## The loop
+
+Everything below is one cycle. An ad-hoc task runs the phase it needs; the
+[weekly review](references/weekly.md) runs the incremental phases on a schedule.
+
+| Phase | What it does | Reference |
+| ------------------------------ | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------- |
+| **A · Collect the standard** | Pull the owner's recent review rejections, read them, keep the part that recurs and one file decides | [calibration.md](references/calibration.md#a--collect-the-standard) |
+| **B · Author the rule** | `rule.alint.toml`: what to report, where to anchor, and an explicit "do not report" list | [rule-authoring.md](references/rule-authoring.md) |
+| **C · Calibrate** | Scan → sample → classify TP/FP → write the recurring FP patterns back as carve-outs → cold-run fixtures | [calibration.md](references/calibration.md#c--calibrate) |
+| **D · Map the problems** | Cluster findings across rules by file/area; that is the cleanup backlog | [calibration.md](references/calibration.md#d--map-the-problems) |
+| **E · Promote** | Read the rule's findings on real PRs; `warn → error` only at zero false positives | [promotion.md](references/promotion.md) |
+| **F · Account for the cost** | Token usage per run; cache invalidation is the cost driver | [cost.md](references/cost.md) |
+
+## Decision rules
+
+These are the calls that are easy to get wrong. They are not suggestions.
+
+- **The owner's words are the standard.** A rule quotes the rejection it comes from,
+ verbatim and in the original language; never paraphrase. If a comment is a requirement or
+ a taste call that no single file can decide, it does not become a rule.
+- **Deterministic checks belong in ESLint/stylelint, not alint.** If an AST or a path list
+ decides it, ESLint decides it. alint is only for what neither can express —
+ `no-node-in-browser` kept only the "does this npm package need Node at runtime" half and
+ handed the import-path half to ESLint.
+- **Carve-outs first.** Write the "do not report" list before the report list: the false
+ positives live in the carve-outs. Every carve-out observed in calibration gets a `good-*`
+ fixture, so the exemption stays true.
+- **Scope with `[[config.group]] files`, never `includeFiles` inside a rule.** `includeFiles`
+ only filters reports, so every file still runs (double the jobs) and the rule becomes
+ uncacheable.
+- **`error` is a promotion, not a starting point.** A new rule starts at `warn`, and is
+ promoted only after its findings have been read on real PRs and measured at zero false
+ positives. Fixture groups stay `warn` so a rule PR never fails on its own `bad-*` fixtures.
+- **A rule that is mostly true but not worth acting on per PR does not belong in the PR
+ check.** Too many findings, or weak precision, sends the rule to `alint.audit.toml`
+ (`bun run alint:audit`). `test-the-exit-not-the-entry` was deleted for producing 92% of all
+ findings and drowning the sharper rules.
+- **Rule changes and product changes are different PRs.** A rule PR contains rules, config
+ and fixtures only. A product fix that a rule surfaced gets its own PR **with acceptance**.
+- **Sample precision is optimistic.** It is measured on the same sample the carve-outs were
+ written from. Say so whenever the number is quoted.
+
+## Preflight — before any calibration run
+
+A calibration run fails expensively when the setup is not real. Check these in order; do not
+interpret a skipped suite as a pass.
+
+1. `.alint/config.toml` exists (gitignored; `bun run alint:setup`, needs `ALINT_API_KEY` or
+ `DEEPSEEK_API_KEY`). Without it the fixture suite **skips rather than fails** — silence is
+ not a pass.
+2. `bun run alint plugin install` has run, and is re-run after adding a rule or a
+ `packages/<pkg>/alint/rules` directory. A missing lock entry exits 2 with **no JSON**.
+3. In a git worktree, install dependencies for real. A symlinked `node_modules` resolves
+ `@lobechat/*` to the main checkout, so rule reads and type-checks lie.
+4. **Delete `.alintcache` after every rule edit** while calibrating. The local cache is keyed
+ by file content, so an edited rule otherwise replays the previous rule's findings.
+5. Confirm a run is cold when a count is quoted. A warm run replays the previous results and
+ costs nothing, which hides a regression.
+
+## Where the pieces live
+
+- **Rules** — `packages/alint/rules/<name>/rule.alint.toml` (repo-wide, plugin prefix
+ `lobehub`). A rule about one package lives in `packages/<pkg>/alint/rules` under its own
+ prefix (e.g. `hetero`) and is registered in the matching `[[config.group]]`.
+- **Fixtures** — `packages/alint/fixtures/<name>/` (mirrored next to a package-level rule):
+ `bad-*` with `// alint-expect` on the line above the anchor line (JSX children use
+ `{/* alint-expect */}`), and one `good-*` per carve-out.
+- **Scope** — root `alint.config.toml` (the PR check) and `alint.audit.toml` (the bulk
+ audit). Everything a repo-wide group needs is `files`, `ignores`, `plugins`, `rules`.
+- **Runner** — `bun run check --alint` (changed lines by default; explicit paths lint whole
+ files), `bun run alint --dirty`, `bun run alint:audit`.
+- **CI & reporting** — `.agents/scripts/check/alint.ts` (the `--alint` selector),
+ `packages/alint/report.ts` (the ALint check run, its annotations, one PR summary comment
+ with marker `<!-- alint-summary -->`, and a usage line), and the `ALint & Test Desktop App`
+ job in `.github/workflows/test.yml`. The check is not required, so a red check informs
+ rather than blocks.
+- **Scripts in this skill** — [`scripts/`](scripts/): `collect-rejections.ts`,
+ `sample-findings.ts`, `pull-alint-runs.ts`, `cost-report.ts`.
+
+## Related skills — read them, do not restate them
+
+`acceptance` (the rejection loop this rule set is fed by), `ux` (the design values the
+`ui-*` rules encode), `react` / `compose-atoms` / `data-fetching-architecture` (the sources
+of the engineering rules), `pr` (how a rule PR is opened and stacked on its base).
diff --git a/.agents/skills/alint-ruleset/references/calibration.md b/.agents/skills/alint-ruleset/references/calibration.md
new file mode 100644
index 00000000000..c4814bfed97
--- /dev/null
+++ b/.agents/skills/alint-ruleset/references/calibration.md
@@ -0,0 +1,118 @@
+# Calibration
+
+Calibration is the work that turns a plausible prompt into a rule worth running on every PR:
+scan the real repo, read a sample of findings against the source, and write the false-positive
+patterns back into the instruction as carve-outs. A rule is not calibrated until a cold run
+of its fixtures reproduces both the findings and the carve-outs.
+
+## A · Collect the standard
+
+The standard is the owner's review rejections, not our paraphrase of them. Pull the window
+with [`scripts/collect-rejections.ts`](../scripts/collect-rejections.ts), which wraps
+`lh acceptance list` + `lh acceptance feedback <id>` into one grouped dump:
+
+```bash
+bun .agents/skills/alint-ruleset/scripts/collect-rejections.ts --days 30 --out /tmp/alint-rejections
+```
+
+Read every comment. Then split them:
+
+- **Becomes a rule** — the complaint recurs, and a single file contains the evidence. Quote it
+ verbatim in the rule; keep the original language.
+- **Not a rule** — a requirement, a state the reviewer wanted that the file cannot reveal, or a
+ one-off taste call. These belong to review, the `ux` skill, or an acceptance check.
+- **Not alint at all** — decided by an AST or a path list. That is ESLint/stylelint.
+
+In the 2026-09-29 pass, 620 comments over 92 acceptances became 9 `ui-*` rules; about half the
+comments were requirement or taste calls no rule can hold.
+
+## C · Calibrate
+
+### 1. Scan
+
+```bash
+bun run alint plugin install
+rm -rf .alintcache # an edited rule must not replay old results
+node_modules/.bin/alint --format json --rule-concurrency 32 <scope...> > /tmp/alint-scan/raw.json
+```
+
+`--rule-concurrency 32` is the working figure for a whole-repo scan (about 10 min for
+`apps/server`, `packages`, `src`; ~14.7k model calls, ~40M input tokens). For a single rule
+being iterated, scan its scope only — a full cold scan is the cost driver (see
+[cost.md](cost.md)).
+
+### 2. Sample
+
+Use [`scripts/sample-findings.ts`](../scripts/sample-findings.ts) to turn `raw.json` into one
+`sample-<rule>.txt` per rule (default 20 findings each), in the form the classifier reads:
+
+```bash
+bun .agents/skills/alint-ruleset/scripts/sample-findings.ts /tmp/alint-scan/raw.json --sample 20 --out /tmp/alint-scan
+# → /tmp/alint-scan/sample-ui-button-hierarchy.txt : "file:line confidence message suggestion"
+```
+
+### 3. Classify — TP / FP / DUP
+
+Open the actual file at each line and judge. This is a **read-only** pass: do not edit the
+tree while classifying. Dispatch it to sub-agents, one batch of ~3 rules per agent, with this
+prompt:
+
+> You are calibrating model-backed lint rules for the LobeHub repo. Work read-only in
+> `<worktree>` (do not edit any file there).
+> For each of these rules: `<rule-a>`, `<rule-b>`, `<rule-c>`
+> 1. Read the rule definition at `packages/alint/rules/<rule>/rule.alint.toml`. It contains the
+> product owner's own review quotes; those quotes ARE the standard. Judge like that owner.
+> 2. Read `/tmp/alint-scan/sample-<rule>.txt` (20 sampled findings: file:line, confidence,
+> message, suggestion).
+> 3. For every finding, open the file at that line (read enough surrounding code) and classify:
+> **TP** (a real violation the owner would want changed, per the rule text),
+> **FP** (not a violation — name the exclusion or the misread),
+> **DUP** (same issue already reported by another finding in the sample).
+> Note repo conventions: UI comes from `@lobehub/ui/base-ui`; styles use `createStaticStyles`
+> + `cssVar`.
+> Report per rule: counts TP/FP/DUP and precision = TP/(TP+FP); one line per finding
+> (index, verdict, 1-sentence reason); the **recurring FP patterns, each phrased as a concrete
+> "do not report X" sentence**; and the 3 most valuable TPs (file:line and what is wrong).
+> Under 900 words.
+
+For a rule about links or routes, the classifier must check the real router
+(`src/spa/router/*`, redirects in `src/libs/next/config/define-config.ts`) — a link is only a
+TP if it truly does not resolve.
+
+### 4. Write the carve-outs back
+
+Each recurring FP pattern becomes one sentence in the instruction's **do not report** list,
+phrased the way a reviewer would say it ("a primary button inside an inline notice: when it is
+the notice's one way forward, primary is right"). Add one `good-*` fixture per carve-out, taken
+from the real false positive. Then re-read the rule end to end: a carve-out that contradicts a
+report pattern means the report pattern is too broad — narrow it (this is how
+`no-transactions-in-models` went from "writes two tables" to "writes another aggregate", and
+`ui-button-hierarchy` from "a primary per item" to three decidable patterns).
+
+### 5. Prove it cold
+
+```bash
+rm -rf .alintcache
+cd packages/alint && bunx vitest run fixtures.test.ts # the whole suite, not just the edited rule
+```
+
+Then re-scan the files that were reported and confirm the false positives are gone **and the
+carve-out did not eat the true positives** — read the diff of the two finding sets, not just
+the count.
+
+## D · Map the problems
+
+After a full scan, cluster the remaining findings by file and by feature area, across rules.
+The files hit by several rules are the cleanup backlog worth proposing first; a single rule's
+long tail is usually not. Report the map as a table (area, rules, count, example `file:line`).
+
+## Evidence boundary
+
+- Precision measured here is measured on the sample the carve-outs were written from, so it is
+ **optimistic**. Say so whenever it is quoted.
+- Findings on legacy code are expected: CI and `check --alint` only report **changed lines**, so
+ an old violation surfaces only when someone edits that line.
+- Two cold runs over the same files can differ by a finding — the model is not deterministic.
+ This is why fixtures exist and why only zero-false-positive rules are promoted.
+- One file at a time is the model's whole world. A rule cannot see who imports a symbol or what
+ a route table contains; do not promise it can.
diff --git a/.agents/skills/alint-ruleset/references/cost.md b/.agents/skills/alint-ruleset/references/cost.md
new file mode 100644
index 00000000000..970172590ed
--- /dev/null
+++ b/.agents/skills/alint-ruleset/references/cost.md
@@ -0,0 +1,88 @@
+# Cost
+
+alint spends model tokens per file per rule. Its cost is therefore **rules × files that
+changed**, minus cache hits. Two things dominate a bill: a rule edit that invalidates the
+cache, and a local whole-repo calibration scan.
+
+## What a run reports
+
+`alint --format json` returns, besides `diagnostics`:
+
+```jsonc
+"execution": { "cached": 0, "completed": 2, "failed": 0, "planned": 2, … },
+"usage": {
+ "inputTokens": 2626,
+ "outputTokens": 223,
+ "totalTokens": 2849,
+ "records": [
+ { "ruleId": "lobehub/ui-content-width", "modelId": "deepseek-flash",
+ "providerId": "api.deepseek.com", "inputTokens": 1347, "outputTokens": 189,
+ "totalTokens": 1536 }
+ ]
+}
+```
+
+`usage.records` is per rule, so it answers "which rule costs the most" directly. Summarise a
+saved run (or several) with [`scripts/cost-report.ts`](../scripts/cost-report.ts):
+
+```bash
+bun .agents/skills/alint-ruleset/scripts/cost-report.ts /tmp/alint-scan/raw.json --price-in 1 --price-in-hit 0.1 --price-out 2
+```
+
+CI reports the same numbers on every run: `packages/alint/report.ts` appends a usage line to
+the ALint check run summary and the PR comment, in the form
+
+```
+42 model calls, 12 cached · 12,345 input / 678 output tokens
+```
+
+`cost-report.ts` also reads that line out of a `runs.json` produced by
+`pull-alint-runs.ts`, so the weekly cost is read from CI rather than estimated.
+
+## Two keys, never one number
+
+- **CI key** — the `DEEPSEEK_API_KEY` repository secret, spent by the `ALint & Test Desktop
+ App` job on every push. This is the recurring cost.
+- **Local / calibration key** — whatever the operator uses for scans. A whole-repo cold
+ calibration pass is a one-off cost that dwarfs a normal CI day; never fold it into the CI
+ figure, and never quote a total without naming which key it came from.
+
+## Cache semantics — the cost driver
+
+alint caches by **file content**; unchanged files cost nothing on a repeat run.
+
+- Current `@alint-js/cli` (0.7.2+) keys a declarative rule's cache on its own instruction
+ (`cacheKey`), so editing one rule re-runs **only that rule**.
+- Earlier versions had no per-rule key: CI keyed the whole cache on the hash of **all** rule
+ files, so editing any one rule invalidated every rule for every file. That is why the bill
+ peaked on the days a rule changed, and why a release PR that day did a full cold run. Keep
+ the dependency current so this does not come back.
+- Locally, the cache is keyed by file content only: an edited rule replays the previous rule's
+ findings unless `.alintcache` is deleted. Clear it after every rule edit.
+
+## Reduce cost, in order of payoff
+
+1. **Stay on a current `@alint-js/cli`** so per-rule cache keys apply. Cheapest, largest win.
+2. **Calibrate on samples, not whole-repo cold scans.** A full scan is the single biggest
+ one-off cost (tens of millions of tokens). Calibrate the rule's scope, sample ~20 findings.
+3. **Prefer file-before-instruction in the prompt** so DeepSeek's context cache is reused
+ across the rules that read the same file (hit tokens are ~1/10 the price). As of 0.7.3 this
+ is upstream work, not yet in alint — verify before relying on it, and re-calibrate fixtures
+ after any prompt-order change.
+4. **Narrow a rule's scope, or move it to `alint.audit.toml`**, when its cost is dominated by a
+ wide scope with weak precision. A rule that reports on every backend file multiplies the
+ per-file calls; the `ui-*` audit rules are deliberately out of the PR check for this reason.
+
+## Unit prices
+
+Observed for DeepSeek flash, reverse-engineered from the bill: input miss ≈ ¥1 / M tokens,
+cache hit ≈ ¥0.1 / M, output ≈ ¥2 / M. Treat these as estimates — re-derive them from the
+actual bill each window, and always record the window and the key alongside any number.
+
+## A note on estimates
+
+Estimating cost by "every file each commit touched" over-counts several-fold: only the pushed
+head commit runs, file contents are cached, and files in a release PR were usually already run
+in their feature PR. Prefer the reported usage over any reconstruction; when reconstructing,
+say it is a reconstruction. Reverse-engineering the CI bill is what exposed the original
+4–5× over-estimate.
diff --git a/.agents/skills/alint-ruleset/references/promotion.md b/.agents/skills/alint-ruleset/references/promotion.md
new file mode 100644
index 00000000000..6b8d572a575
--- /dev/null
+++ b/.agents/skills/alint-ruleset/references/promotion.md
@@ -0,0 +1,62 @@
+# Promotion — `warn` → `error`
+
+`error` turns the ALint check red and reaches whoever watches CI, including agents woken by a
+CI failure. `warn` sits on a green check and is widely ignored — in the 2026-09 review pass,
+7 of 11 non-test findings were merged as-is. So promotion is how a rule acquires teeth, and it
+must be earned on real data, never on the calibration sample.
+
+## The evidence
+
+Promote from the rule's findings on **real pull requests**, not from a local scan. Gather the
+window with [`scripts/pull-alint-runs.ts`](../scripts/pull-alint-runs.ts), which reads the
+`ALint` check runs (and their annotations) plus the summary comment for each PR:
+
+```bash
+bun .agents/skills/alint-ruleset/scripts/pull-alint-runs.ts --days 7 --out /tmp/alint-ci
+# → /tmp/alint-ci/worksheet.json + /tmp/alint-ci/by-rule.md
+```
+
+Deduplicate on **PR + rule + file + message**, then keep whether the finding is still present
+in that PR's **latest** run. A finding that disappeared was fixed or explained; only standing
+findings count. Then read each standing finding against the source and mark it TP / FP /
+borderline. The script gathers and tallies; it never judges.
+
+## The gate
+
+Promote a rule to `error` only when **all** hold:
+
+1. Every standing finding in the window is a true positive (zero FP, allowing for the model's
+ run-to-run noise).
+2. The finding is worth surfacing on **every** PR that touches that line, not just worth
+ knowing once.
+3. There is enough volume to mean something — one or two findings is not evidence.
+4. Any FP already seen has been turned into a carve-out **with its `good-*` fixture** and
+ re-verified cold.
+
+If the shape is "mostly true but not worth acting on per PR" or precision is in the 50–70%
+band, the rule does not get `error`; it stays `warn`, or moves to `alint.audit.toml`.
+
+## What not to do
+
+- Do not promote on the calibration sample. Its precision is optimistic by construction.
+- Do not promote a judgement-call rule whose FP is a matter of context another file holds.
+- Do not promote a rule with no PR data yet — a brand-new rule waits for a window of real runs.
+- Do not bundle promotions with unrelated rule edits. Promotion is a small, reviewable PR that
+ changes severity (and, if needed, adds the carve-out + fixture). Combine only when the owner
+ asks for it.
+
+## After promotion
+
+- The rule now turns the check red **on changed lines**. Legacy findings do not fail CI, but
+ whoever edits one of those lines will go red — list the known legacy spots in the PR so it
+ is a known bill, not a surprise.
+- The check is not a required status: a red check informs and wakes watchers, it does not block
+ merging. Say that plainly instead of promising enforcement.
+- Promotion may create a real cost: a rule that reports on every backend file multiplies the
+ per-file calls. Re-check the cost after a promotion (see [cost.md](cost.md)).
+
+## Reading the window correctly
+
+Release PRs (base `main`) re-report days of changes as "changed lines", so they dominate the
+raw volume. Their findings are still real changed-line findings, so they count — but do not let
+them hide that a rule simply has no organic traffic. Check a rule's sample size before acting.
diff --git a/.agents/skills/alint-ruleset/references/rule-authoring.md b/.agents/skills/alint-ruleset/references/rule-authoring.md
new file mode 100644
index 00000000000..ad5cdff921e
--- /dev/null
+++ b/.agents/skills/alint-ruleset/references/rule-authoring.md
@@ -0,0 +1,96 @@
+# Authoring a rule
+
+A rule is a prompt plus a structured-output schema. Declarative rules carry their prompt in
+`rule.alint.toml` and need no TypeScript; `builtInAgent = "basic-structured"` runs them.
+
+## Anatomy
+
+```toml
+name = "ui-button-hierarchy" # must equal the directory name
+builtInAgent = "basic-structured"
+instruction = """
+You are reviewing one React component file from LobeHub's web client. … # role + surface
+
+Team rule, distilled from the product owner's review rejections ("按钮用 filled 而不是 primary", …):
+… # the standard, in the owner's words
+
+Report ONLY these three patterns … # what to report, when it is decidable
+1. … Anchor on the line of the button's opening tag. # anchor per pattern
+
+Do not report: # carve-outs first
+- …
+
+If an exclusion applies, return no finding. If uncertain, use low confidence.
+"""
+```
+
+The instruction is written to the model as a reviewer, not as a summary. It must state:
+what to report, **which line to anchor on**, what the message must name, what the suggestion
+must contain, and the explicit **do not report** list. The carve-outs are where the false
+positives live — write them before the report list, not after.
+
+## Two homes, two prefixes
+
+| Kind | Rule path | Fixtures path | Prefix |
+| ---------------- | ------------------------------------ | ---------------------------------------- | --------- |
+| Repo-wide | `packages/alint/rules/<name>/` | `packages/alint/fixtures/<name>/` | `lobehub` |
+| One package only | `packages/<pkg>/alint/rules/<name>/` | `packages/<pkg>/alint/fixtures/<name>/` | `<pkg>…` |
+
+A package-level rule is only ever scoped to its package (`hetero/*` rules live next to
+`heterogeneous-agents`). Put a rule in `packages/alint` only when more than one package or
+`src/` needs it.
+
+## Scoping — in the config, never in the rule
+
+Register scope as a `[[config.group]]` in the root config. A group can carry `ignores`,
+`files`, `plugins` and `rules`, and may extend another group (`extends`).
+
+```toml
+# PR check — alint.config.toml
+[[config.group]]
+files = ["src/**/*.tsx"]
+ignores = ["**/*.test.tsx"]
+
+[config.group.plugins]
+lobehub = "./packages/alint/rules"
+
+[config.group.rules]
+"lobehub/ui-button-hierarchy" = "warn"
+```
+
+Never scope a rule with `includeFiles` inside `rule.alint.toml`: it only filters reports, so
+every matched file still runs (double the jobs) and the rule is marked uncacheable. Give each
+fixture directory its own group so a fixture meets only its own rule.
+
+## Fixtures
+
+- One dir per rule, `bad-*` and `good-*` files, short and realistic (a real pattern, not a
+ minimal repro).
+- A `bad-*` file marks the expected finding with `// alint-expect` **on its own line above**
+ the line the finding must anchor to (`{/* alint-expect */}` inside JSX children). The test
+ accepts a hit within ±1 line.
+- Every carve-out in the instruction gets a `good-*` fixture taken from a real false positive.
+- `packages/alint/fixtures.test.ts` asserts both directions: `good-*` produces nothing,
+ `bad-*` produces a finding near each marker, and a fixture only ever meets its own rule.
+
+## Add-a-rule sequence
+
+```bash
+# 1. write rules/<name>/rule.alint.toml
+# 2. add the scope group in alint.config.toml and a fixture group for fixtures/<name>/**
+# 3. add fixtures/<name>/{bad-*,good-*}
+bun run alint plugin install # register the rule directory
+rm -rf .alintcache # an edited rule must not replay old results
+cd packages/alint && bunx vitest run fixtures.test.ts # skips silently without .alint/config.toml
+# 4. run it over a few dozen real files and read every finding before enabling the scope
+```
+
+The instruction is source, not documentation: changing it changes results. After any edit,
+clear the cache and re-run the fixtures cold.
+
+## Severity
+
+`error` is reserved for rules measured at zero false positives on real PRs, because an error
+turns the ALint check red. Everything else is `warn`. New rules start at `warn`; fixture
+groups stay `warn`. Promotion is a separate, evidence-based step — see
+[promotion.md](promotion.md).
diff --git a/.agents/skills/alint-ruleset/references/weekly.md b/.agents/skills/alint-ruleset/references/weekly.md
new file mode 100644
index 00000000000..efff9833d54
--- /dev/null
+++ b/.agents/skills/alint-ruleset/references/weekly.md
@@ -0,0 +1,93 @@
+# Weekly review
+
+The weekly run is the **incremental** half of the [loop](../SKILL.md#the-loop): it looks at what
+changed since the last run and produces a short report plus the decisions that need the owner.
+It does not re-do the initial calibration.
+
+Cadence: once a week. It changes nothing on the product and promotes nothing on its own — it
+recommends, and opens a PR only for a change that is already calibrated and unambiguously
+zero-false-positive.
+
+## Preflight
+
+1. `.alint/config.toml` exists and the provider answers; `bun run alint plugin install` is current.
+2. `lh` is authenticated (for acceptances) and `gh` is authenticated (for CI runs), or the
+ equivalent credentials are injected.
+3. Know the **window**: the 7 days since the last run, not "recently".
+
+## Segment A — new standard
+
+Pull the window's review feedback and classify it into rule candidates. Do **not** author rules
+in the weekly run; produce the list.
+
+```bash
+bun .agents/skills/alint-ruleset/scripts/collect-rejections.ts --days 7 --out /tmp/alint-rejections
+```
+
+For each recurring complaint, decide: already covered by a rule (name it) · a candidate for a
+new rule (with the verbatim quote and the file that would show it) · not a rule (requirement /
+taste / ESLint). Keep the "candidate" list short — a rule needs recurrence and single-file
+evidence.
+
+## Segment E — promotion from real data
+
+```bash
+bun .agents/skills/alint-ruleset/scripts/pull-alint-runs.ts --days 7 --out /tmp/alint-ci
+```
+
+Read the deduplicated standing findings against the source, then apply the
+[promotion gate](promotion.md#the-gate). Per rule, output one of: **promote to error** ·
+**demote to warn** · **add a carve-out (then re-evaluate)** · **move to audit** · **hold (no
+data)**. A rule with no organic findings is "hold", not "promote".
+
+## Segment F — cost
+
+```bash
+# per-run usage from saved JSON, or the usage line carried on each CI run summary
+bun .agents/skills/alint-ruleset/scripts/cost-report.ts <run.json> --price-in 1 --price-in-hit 0.1 --price-out 2
+```
+
+Report the CI key and the local key **separately**, and name the cause of any week-over-week
+jump: a rule edit invalidating the cache, a new rule widening a scope, or a release PR doing a
+cold run. See [cost.md](cost.md).
+
+## Output — the report
+
+Lead with the result, then the detail (business first, mechanics after). Keep it short.
+
+```markdown
+# alint 周报 — <window>
+
+<one or two sentences: what changed for the rule set this week, and whether anything needs a decision>
+
+## 本周期结论
+- 晋升 / 降级:<rule> → <severity>(依据:<n> 条真实结果,TP/FP)
+- 新规则候选:<n> 条(<names>)
+- 成本:CI ¥<x>(<key>),较上周 <±%>,原因 <…>
+
+## 需要你拍板
+- <decision> — 我的建议:<…>
+
+## 明细
+### 真实数据(<window>)
+| rule | 结果数 | 真/误 | 建议 |
+### 新打回意见
+| 类别 | 条数 | 例 | 去向 |
+### 成本
+| key | token | 金额 | 备注 |
+```
+
+## Non-goals
+
+- **No whole-repo cold scan.** It is the largest cost; calibrate on samples. If a full scan is
+ genuinely needed, run it as its own task and record it as a one-off.
+- **No product-code edits.** A product fix that a rule surfaced gets its own PR, with
+ acceptance.
+- **No automatic promotion.** Recommendations only; the owner decides, and the promotion PR is
+ separate.
+
+## First run vs later runs
+
+The first run establishes the baseline: current severities, the open candidate list, and a cost
+baseline. Every later run compares against it, so always store the previous report and diffs
+against it rather than re-deriving the whole picture.
diff --git a/.agents/skills/alint-ruleset/scripts/collect-rejections.ts b/.agents/skills/alint-ruleset/scripts/collect-rejections.ts
new file mode 100644
index 00000000000..768283eb7a1
--- /dev/null
+++ b/.agents/skills/alint-ruleset/scripts/collect-rejections.ts
@@ -0,0 +1,148 @@
+/**
+ * Pull the owner's review feedback in a window, grouped by acceptance — the raw material for
+ * new rules (see references/calibration.md, "Collect the standard").
+ *
+ * bun .agents/skills/alint-ruleset/scripts/collect-rejections.ts [--days 7] [--out <dir>] [--actionable]
+ *
+ * Wraps `lh acceptance list --json` + `lh acceptance feedback <id> --json`.
+ *
+ * Known cap: `lh acceptance list` returns a server-side-capped window (the CLI exposes no
+ * `--limit`), so a window wider than that cap silently loses the oldest acceptances. The script
+ * warns when it hits the cap; widen the window only after confirming the list is complete.
+ */
+import { execFileSync } from 'node:child_process';
+import { mkdir, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+/** Feedback entry as `lh acceptance feedback --json` emits it (subset we read). */
+interface FeedbackEntry {
+ actionable?: boolean;
+ /** Region notes; the actionable text often lives here, not in `comment`. */
+ annotations?: { comment?: string }[];
+ checkSeq?: number;
+ comment: string;
+ createdAt?: string;
+ kind?: string;
+ roundIndex?: number;
+ title?: string;
+}
+
+interface AcceptanceRow {
+ createdAt?: string;
+ id: string;
+ requirement?: string | null;
+ status?: string;
+ subjectId?: string;
+ subjectType?: string;
+}
+
+const parseArgs = (argv: string[]) => {
+ const flags = new Map<string, string>();
+ for (let index = 0; index < argv.length; index++) {
+ const arg = argv[index]!;
+ if (arg.startsWith('--')) {
+ const [key, inline] = arg.slice(2).split('=');
+ flags.set(key!, inline ?? argv[++index] ?? '');
+ }
+ }
+ return flags;
+};
+
+const lh = (args: string[]): unknown => JSON.parse(execFileSync('lh', args, { encoding: 'utf8' }));
+
+const flags = parseArgs(process.argv.slice(2));
+const days = Number(flags.get('days') ?? 7);
+const actionableOnly = flags.has('actionable');
+const outDir = path.resolve(flags.get('out') ?? '/tmp/alint-rejections');
+const since = new Date(Date.now() - days * 86_400_000);
+
+let list: AcceptanceRow[];
+try {
+ list = lh(['acceptance', 'list', '--json']) as AcceptanceRow[];
+} catch {
+ console.error('`lh acceptance list` failed. Run `lh whoami` to check authentication.');
+ process.exit(2);
+}
+
+/** Anything without a usable createdAt is kept: better to over-read than to drop a rejection. */
+const inWindow = list.filter((row) => !row.createdAt || new Date(row.createdAt) >= since);
+
+/** `lh acceptance feedback --json` → `{ acceptanceId, currentRoundIndex, entries }`. */
+const feedbackEntries = (value: unknown): FeedbackEntry[] => {
+ if (Array.isArray(value)) return value as FeedbackEntry[];
+ const entries = (value as { entries?: unknown }).entries;
+ return Array.isArray(entries) ? (entries as FeedbackEntry[]) : [];
+};
+
+/** A region note may be the only text; fall back to it when `comment` is empty. */
+const textOf = (entry: FeedbackEntry) =>
+ [entry.comment, ...(entry.annotations ?? []).map((annotation) => annotation.comment ?? '')]
+ .map((part) => part?.trim())
+ .filter(Boolean)
+ .join(' · ');
+
+const groups: { acceptance: AcceptanceRow; feedback: FeedbackEntry[] }[] = [];
+let total = 0;
+for (const acceptance of inWindow) {
+ let feedback: FeedbackEntry[];
+ try {
+ feedback = feedbackEntries(
+ lh([
+ 'acceptance', 'feedback', acceptance.id, '--json',
+ ...(actionableOnly ? ['--actionable'] : []),
+ ]),
+ );
+ } catch (error) {
+ console.warn(` ! ${acceptance.id}: ${String(error)}`);
+ continue;
+ }
+ const kept = feedback.filter((entry) => textOf(entry));
+ if (kept.length === 0) continue;
+ total += kept.length;
+ groups.push({ acceptance, feedback: kept });
+}
+
+groups.sort((a, b) => (b.acceptance.createdAt ?? '').localeCompare(a.acceptance.createdAt ?? ''));
+
+await mkdir(outDir, { recursive: true });
+await writeFile(
+ path.join(outDir, 'rejections.json'),
+ JSON.stringify({ generatedAt: new Date().toISOString(), since: since.toISOString(), groups }, null, 2) + '\n',
+);
+
+const lines: string[] = [
+ `# Review feedback — last ${days} day(s) (since ${since.toISOString().slice(0, 10)})`,
+ '',
+ `${groups.length} acceptances with feedback · ${total} comments`,
+ '',
+ '> Read every comment. Keep the ones that (a) recur and (b) can be decided from one file —',
+ '> those become rules, quoting the comment verbatim. Requirements, taste calls and',
+ '> AST/path decisions are not rules.',
+ '',
+];
+for (const { acceptance, feedback } of groups) {
+ const requirement = (acceptance.requirement ?? '').replaceAll('\n', ' ').slice(0, 100);
+ lines.push(
+ `## ${acceptance.subjectType ?? '?'} · ${acceptance.id} — ${acceptance.status ?? '?'}`,
+ '',
+ requirement ? `> ${requirement}` : '',
+ '',
+ );
+ for (const entry of feedback) {
+ const where = [entry.kind, entry.checkSeq !== undefined ? `C${entry.checkSeq}` : '', entry.title]
+ .filter(Boolean)
+ .join(' ');
+ const flag = entry.actionable ? '▶ ' : '';
+ lines.push(`- ${flag}${where ? `**${where}** ` : ''}${textOf(entry).replaceAll('\n', ' ')}`);
+ }
+ lines.push('');
+}
+await writeFile(path.join(outDir, 'rejections.md'), lines.join('\n') + '\n');
+
+console.info(lines.slice(0, 8).join('\n'));
+console.info(`\nrejections.json · rejections.md → ${outDir}`);
+if (list.length >= 50) {
+ console.warn(
+ `\n! list returned ${list.length} rows — this may be the CLI cap. The window may be truncated; narrow --days or paginate the API.`,
+ );
+}
diff --git a/.agents/skills/alint-ruleset/scripts/cost-report.ts b/.agents/skills/alint-ruleset/scripts/cost-report.ts
new file mode 100644
index 00000000000..c7d4613663f
--- /dev/null
+++ b/.agents/skills/alint-ruleset/scripts/cost-report.ts
@@ -0,0 +1,201 @@
+/**
+ * Summarise alint token usage and estimate cost.
+ *
+ * bun .agents/skills/alint-ruleset/scripts/cost-report.ts <run.json> [more.json ...]
+ * [--price-in 1] [--price-in-hit 0.1] [--price-out 2] [--currency ¥] [--out <dir>]
+ *
+ * Inputs are either `alint --format json` dumps (read `usage` + `execution` directly) or a
+ * `runs.json` produced by pull-alint-runs.ts (the usage line is parsed out of each run summary,
+ * e.g. `42 model calls, 12 cached · 12,345 input / 678 output tokens`). Prices are per million
+ * tokens; they are estimates to be re-derived from the bill, not constants. `--price-in-hit`
+ * applies only when a source reports cached input tokens separately; the default alint `usage`
+ * payload does not, so treat its number as an upper bound.
+ */
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+interface UsageRecord {
+ inputTokens?: number;
+ outputTokens?: number;
+ ruleId?: string;
+ totalTokens?: number;
+}
+
+interface AlintDump {
+ diagnostics?: unknown[];
+ execution?: { cached?: number; completed?: number; failed?: number; planned?: number };
+ usage?: {
+ cachedInputTokens?: number;
+ inputTokens?: number;
+ outputTokens?: number;
+ records?: UsageRecord[];
+ totalTokens?: number;
+ };
+}
+
+interface RunsFile {
+ runs?: { annotations?: number; pr: number; summary?: string; title?: string | null }[];
+}
+
+const parseArgs = (argv: string[]) => {
+ const flags = new Map<string, string>();
+ const positional: string[] = [];
+ for (let index = 0; index < argv.length; index++) {
+ const arg = argv[index]!;
+ if (arg.startsWith('--')) {
+ const [key, inline] = arg.slice(2).split('=');
+ flags.set(key!, inline ?? argv[++index] ?? '');
+ } else {
+ positional.push(arg);
+ }
+ }
+ return { flags, positional };
+};
+
+const { flags, positional } = parseArgs(process.argv.slice(2));
+if (positional.length === 0) {
+ console.error('usage: cost-report.ts <run.json ...> [--price-in 1] [--price-in-hit 0.1] [--price-out 2]');
+ process.exit(2);
+}
+
+const priceIn = Number(flags.get('price-in') ?? 1);
+const priceInHit = Number(flags.get('price-in-hit') ?? 0.1);
+const priceOut = Number(flags.get('price-out') ?? 2);
+const currency = flags.get('currency') ?? '¥';
+const outDir = flags.get('out') ? path.resolve(flags.get('out')!) : undefined;
+
+const perMillion = (tokens: number, price: number) => (tokens / 1_000_000) * price;
+
+interface Row {
+ cached: number;
+ completed: number;
+ cost: number;
+ input: number;
+ name: string;
+ output: number;
+ rules: number;
+}
+
+const toNumber = (value: string | undefined): number => {
+ if (!value) return 0;
+ const match = value.replaceAll(',', '').trim().match(/^([\d.]+)\s*([km])?$/i);
+ if (!match) return 0;
+ const unit = match[2]?.toLowerCase();
+ const scale = unit === 'm' ? 1_000_000 : unit === 'k' ? 1000 : 1;
+ return Number(match[1]) * scale;
+};
+
+/**
+ * Read usage out of an ALint run summary (`packages/alint/report.ts` → `toUsageLine`). The exact
+ * wording may drift, so pull each number with its own simple pattern instead of one
+ * backtracking-prone expression.
+ */
+const usageFromSummary = (summary: string) => {
+ const calls = summary.match(/(\d+)\s*model calls?/i);
+ const cached = summary.match(/(\d+)\s*(?:cache hits?|cached)/i);
+ const input = summary.match(/([\d.,]+[km]?)\s*(?:input|prompt)/i);
+ const output = summary.match(/([\d.,]+[km]?)\s*output/i);
+ if (!calls && !cached && !input && !output) return null;
+ return {
+ cached: cached ? Number(cached[1]) : 0,
+ input: toNumber(input?.[1]),
+ output: toNumber(output?.[1]),
+ };
+};
+
+const rows: Row[] = [];
+const ruleTotals = new Map<string, { input: number; output: number; total: number }>();
+
+for (const file of positional) {
+ const raw = JSON.parse(await readFile(file, 'utf8')) as AlintDump & RunsFile;
+ const name = path.basename(file);
+
+ if (raw.usage) {
+ const input = raw.usage.inputTokens ?? 0;
+ const output = raw.usage.outputTokens ?? 0;
+ const hit = raw.usage.cachedInputTokens ?? 0;
+ const records = raw.usage.records ?? [];
+ for (const record of records) {
+ if (!record.ruleId) continue;
+ const agg = ruleTotals.get(record.ruleId) ?? { input: 0, output: 0, total: 0 };
+ agg.input += record.inputTokens ?? 0;
+ agg.output += record.outputTokens ?? 0;
+ agg.total += record.totalTokens ?? 0;
+ ruleTotals.set(record.ruleId, agg);
+ }
+ rows.push({
+ cached: raw.execution?.cached ?? 0,
+ completed: raw.execution?.completed ?? 0,
+ cost: perMillion(input - hit, priceIn) + perMillion(hit, priceInHit) + perMillion(output, priceOut),
+ input,
+ name,
+ output,
+ rules: new Set(records.map((record) => record.ruleId)).size,
+ });
+ continue;
+ }
+
+ if (raw.runs) {
+ let input = 0;
+ let output = 0;
+ let cached = 0;
+ let unparsed = 0;
+ for (const run of raw.runs) {
+ const usage = run.summary ? usageFromSummary(run.summary) : null;
+ if (!usage) {
+ unparsed++;
+ continue;
+ }
+ cached += usage.cached;
+ input += usage.input;
+ output += usage.output;
+ }
+ rows.push({
+ cached,
+ completed: raw.runs.length,
+ cost: perMillion(input, priceIn) + perMillion(output, priceOut),
+ input,
+ name: `${name} (CI runs)`,
+ output,
+ rules: 0,
+ });
+ console.info(`${unparsed}/${raw.runs.length} runs had no parsable usage line — CI cost is unknown for those, not zero.`);
+ continue;
+ }
+
+ console.warn(`! ${name}: not an alint dump or a runs.json — skipped`);
+}
+
+const money = (value: number) => `${currency}${value.toFixed(2)}`;
+const table: string[] = [
+ '# alint cost report',
+ '',
+ `> Prices (per M tokens, as passed): input ${priceIn}, input-hit ${priceInHit}, output ${priceOut}. Estimates — re-derive from the bill and name the key.`,
+ '',
+ '| source | rules | planned/completed | cached | input | output | est. cost |',
+ '| --- | ---: | ---: | ---: | ---: | ---: | ---: |',
+];
+for (const row of rows) {
+ table.push(
+ `| ${row.name} | ${row.rules || '-'} | ${row.completed} | ${row.cached} | ${row.input.toLocaleString()} | ${row.output.toLocaleString()} | ${money(row.cost)} |`,
+ );
+}
+const totalCost = rows.reduce((sum, row) => sum + row.cost, 0);
+const totalInput = rows.reduce((sum, row) => sum + row.input, 0);
+const totalOutput = rows.reduce((sum, row) => sum + row.output, 0);
+table.push(`| **total** | | | | **${totalInput.toLocaleString()}** | **${totalOutput.toLocaleString()}** | **${money(totalCost)}** |`);
+
+if (ruleTotals.size > 0) {
+ table.push('', '## By rule', '', '| rule | input | output | total |', '| --- | ---: | ---: | ---: |');
+ for (const [rule, agg] of [...ruleTotals].sort((a, b) => b[1].total - a[1].total)) {
+ table.push(`| \`${rule}\` | ${agg.input.toLocaleString()} | ${agg.output.toLocaleString()} | ${agg.total.toLocaleString()} |`);
+ }
+}
+
+const body = table.join('\n') + '\n';
+console.info(body);
+if (outDir) {
+ await mkdir(outDir, { recursive: true });
+ await writeFile(path.join(outDir, 'cost-report.md'), body);
+ console.info(`\ncost-report.md → ${outDir}`);
+}
diff --git a/.agents/skills/alint-ruleset/scripts/pull-alint-runs.ts b/.agents/skills/alint-ruleset/scripts/pull-alint-runs.ts
new file mode 100644
index 00000000000..26421f7c83d
--- /dev/null
+++ b/.agents/skills/alint-ruleset/scripts/pull-alint-runs.ts
@@ -0,0 +1,200 @@
+/**
+ * Gather the ALint signal from real PRs in a window: the `ALint` check runs, their line
+ * annotations, and each run's summary (which carries the PR-comment table and the usage line).
+ * Deduplicated on PR + rule + file + message.
+ *
+ * bun .agents/skills/alint-ruleset/scripts/pull-alint-runs.ts [--days 7] [--out <dir>] [--repo owner/name] [--max-prs 200]
+ *
+ * This script only gathers and tallies — it never judges TP/FP. Read the worksheet against the
+ * source yourself (see references/promotion.md).
+ */
+import { execFileSync } from 'node:child_process';
+import { mkdir, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+interface CheckRun {
+ conclusion: string | null;
+ id: number;
+ name: string;
+ output?: { summary?: string | null; title?: string | null };
+ started_at: string;
+}
+
+interface Annotation {
+ annotation_level: string;
+ message: string;
+ path: string;
+ start_line: number;
+ title: string;
+}
+
+interface PullRequest {
+ baseRefName: string;
+ headRefOid: string;
+ number: number;
+ state: string;
+ title: string;
+ updatedAt: string;
+ url: string;
+}
+
+const parseArgs = (argv: string[]) => {
+ const flags = new Map<string, string>();
+ for (let index = 0; index < argv.length; index++) {
+ const arg = argv[index]!;
+ if (arg.startsWith('--')) {
+ const [key, inline] = arg.slice(2).split('=');
+ flags.set(key!, inline ?? argv[++index] ?? '');
+ }
+ }
+ return flags;
+};
+
+const gh = (args: string[]): unknown =>
+ JSON.parse(execFileSync('gh', args, { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 }));
+
+const ghText = (args: string[]): string => execFileSync('gh', args, { encoding: 'utf8' }).trim();
+
+const flags = parseArgs(process.argv.slice(2));
+const days = Number(flags.get('days') ?? 7);
+const maxPrs = Number(flags.get('max-prs') ?? 200);
+const outDir = path.resolve(flags.get('out') ?? '/tmp/alint-ci');
+const since = new Date(Date.now() - days * 86_400_000);
+
+let repo: string;
+try {
+ repo = flags.get('repo') ?? ghText(['repo', 'view', '--json', 'nameWithOwner', '-q', '.nameWithOwner']);
+} catch {
+ console.error('gh could not resolve the repository. Run `gh auth status` and `gh repo set-default`.');
+ process.exit(2);
+}
+
+const pulls = gh([
+ 'pr', 'list', '--state', 'all', '--limit', String(maxPrs),
+ '--json', 'number,headRefOid,baseRefName,updatedAt,title,url,state',
+]) as PullRequest[];
+
+const window = pulls
+ .filter((pull) => new Date(pull.updatedAt) >= since)
+ .sort((a, b) => a.updatedAt.localeCompare(b.updatedAt));
+
+interface WorksheetEntry {
+ baseRefName: string;
+ conclusion: string | null;
+ level: string;
+ line: number;
+ message: string;
+ path: string;
+ pr: number;
+ rule: string;
+ title: string;
+ url: string;
+}
+
+const runs: {
+ annotations: number;
+ conclusion: string | null;
+ pr: number;
+ sha: string;
+ summary: string;
+ title: string | null;
+ url: string;
+}[] = [];
+const findings = new Map<string, WorksheetEntry>();
+
+for (const pull of window) {
+ let checkRuns: CheckRun[];
+ try {
+ checkRuns = (gh(['api', `repos/${repo}/commits/${pull.headRefOid}/check-runs?per_page=100`]) as {
+ check_runs: CheckRun[];
+ }).check_runs;
+ } catch {
+ continue;
+ }
+
+ const alintRuns = checkRuns
+ .filter((run) => run.name === 'ALint')
+ .sort((a, b) => a.started_at.localeCompare(b.started_at));
+ const latest = alintRuns.at(-1);
+ if (!latest) continue;
+
+ let annotations: Annotation[];
+ try {
+ annotations = gh(['api', `repos/${repo}/check-runs/${latest.id}/annotations?per_page=100`]) as Annotation[];
+ } catch {
+ annotations = [];
+ }
+
+ runs.push({
+ annotations: annotations.length,
+ conclusion: latest.conclusion,
+ pr: pull.number,
+ sha: pull.headRefOid,
+ summary: latest.output?.summary ?? '',
+ title: latest.output?.title ?? null,
+ url: pull.url,
+ });
+
+ for (const annotation of annotations) {
+ const rule = annotation.title ?? '(unknown)';
+ const message = (annotation.message ?? '').split('\n')[0]!.trim();
+ const key = `${pull.number}|${rule}|${annotation.path}|${message}`;
+ // The latest run of a PR is the last word: a finding absent from it was fixed or explained.
+ findings.set(key, {
+ baseRefName: pull.baseRefName,
+ conclusion: latest.conclusion,
+ level: annotation.annotation_level,
+ line: annotation.start_line,
+ message,
+ path: annotation.path,
+ pr: pull.number,
+ rule,
+ title: pull.title,
+ url: pull.url,
+ });
+ }
+}
+
+const entries = [...findings.values()];
+const byRule = new Map<string, WorksheetEntry[]>();
+for (const entry of entries) {
+ const list = byRule.get(entry.rule) ?? [];
+ list.push(entry);
+ byRule.set(entry.rule, list);
+}
+
+await mkdir(outDir, { recursive: true });
+await writeFile(
+ path.join(outDir, 'worksheet.json'),
+ JSON.stringify(
+ { generatedAt: new Date().toISOString(), repo, runs, since: since.toISOString(), window: { days, prs: window.length } },
+ null,
+ 2,
+ ) + '\n',
+);
+await writeFile(path.join(outDir, 'findings.json'), JSON.stringify(entries, null, 2) + '\n');
+
+const table: string[] = [
+ `# ALint findings on real PRs — last ${days} day(s) (since ${since.toISOString().slice(0, 10)})`,
+ '',
+ `${window.length} PRs updated in the window · ${runs.length} with an ALint run · ${entries.length} standing findings (deduped).`,
+ '',
+ '| rule | standing findings | PRs | base `main`? |',
+ '| --- | ---: | ---: | ---: |',
+];
+for (const [rule, list] of [...byRule].sort((a, b) => b[1].length - a[1].length)) {
+ const pullCount = new Set(list.map((entry) => entry.pr)).size;
+ const release = list.filter((entry) => entry.baseRefName === 'main').length;
+ table.push(`| \`${rule}\` | ${list.length} | ${pullCount} | ${release} |`);
+}
+if (entries.length === 0) table.push('| _(none)_ | 0 | 0 | 0 |');
+table.push(
+ '',
+ "> Findings are deduped on PR + rule + file + message and kept only when present in the PR's **latest** run.",
+ '> Annotations are capped at 50 per run, so a rule with more is under-counted here; the run summary has the full table.',
+ '> Read each row against the source and mark TP / FP / borderline before promoting anything.',
+);
+await writeFile(path.join(outDir, 'by-rule.md'), table.join('\n') + '\n');
+
+console.info(table.join('\n'));
+console.info(`\nworksheet.json · findings.json · by-rule.md → ${outDir}`);
diff --git a/.agents/skills/alint-ruleset/scripts/sample-findings.ts b/.agents/skills/alint-ruleset/scripts/sample-findings.ts
new file mode 100644
index 00000000000..20e270249a5
--- /dev/null
+++ b/.agents/skills/alint-ruleset/scripts/sample-findings.ts
@@ -0,0 +1,98 @@
+/**
+ * Turn an `alint --format json` dump into one `sample-<rule>.txt` per rule — the slice a
+ * classifier reads against the source during calibration (see references/calibration.md).
+ *
+ * bun .agents/skills/alint-ruleset/scripts/sample-findings.ts <raw.json> [--sample 20] [--out <dir>]
+ *
+ * Produce the dump first:
+ * node_modules/.bin/alint --format json --rule-concurrency 32 <scope...> > raw.json
+ */
+import { mkdir, readFile, writeFile } from 'node:fs/promises';
+import path from 'node:path';
+
+interface AlintDiagnostic {
+ evidence?: { confidence?: string; suggestion?: string };
+ filePath: string;
+ loc?: { start?: { line?: number } };
+ message: string;
+ ruleId: string;
+ severity: 'error' | 'warn';
+}
+
+interface AlintOutput {
+ diagnostics?: AlintDiagnostic[];
+}
+
+/** Minimal `--flag value` / `--flag=value` / positional parser. */
+const parseArgs = (argv: string[]) => {
+ const flags = new Map<string, string>();
+ const positional: string[] = [];
+ for (let index = 0; index < argv.length; index++) {
+ const arg = argv[index]!;
+ if (arg.startsWith('--')) {
+ const [key, inline] = arg.slice(2).split('=');
+ flags.set(key!, inline ?? argv[++index] ?? '');
+ } else {
+ positional.push(arg);
+ }
+ }
+ return { flags, positional };
+};
+
+const { flags, positional } = parseArgs(process.argv.slice(2));
+const input = positional[0];
+if (!input) {
+ console.error('usage: sample-findings.ts <raw.json> [--sample 20] [--out <dir>]');
+ process.exit(2);
+}
+
+const sampleSize = Number(flags.get('sample') ?? 20);
+const outDir = path.resolve(flags.get('out') ?? path.join(path.dirname(path.resolve(input)), 'samples'));
+const root = process.cwd();
+
+const output = JSON.parse(await readFile(input, 'utf8')) as AlintOutput;
+const diagnostics = output.diagnostics ?? [];
+
+const byRule = new Map<string, AlintDiagnostic[]>();
+for (const diagnostic of diagnostics) {
+ const list = byRule.get(diagnostic.ruleId) ?? [];
+ list.push(diagnostic);
+ byRule.set(diagnostic.ruleId, list);
+}
+
+await mkdir(outDir, { recursive: true });
+
+/** Cells are tab-separated; strip tabs/newlines from free text so a row stays one line. */
+const cell = (value: string) => value.replaceAll('\t', ' ').replaceAll('\n', ' ').trim();
+
+const table: string[] = ['| rule | findings | sampled | sample file |', '| --- | ---: | ---: | --- |'];
+const index: Record<string, { findings: number; sampleFile: string; sampled: number }> = {};
+
+for (const [rule, list] of [...byRule].sort((a, b) => b[1].length - a[1].length)) {
+ const picked = list.slice(0, sampleSize);
+ const header = ['index', 'location', 'confidence', 'severity', 'message', 'suggestion'].join('\t');
+ const rows = picked.map((diagnostic, position) => {
+ const location = `${path.relative(root, diagnostic.filePath)}:${diagnostic.loc?.start?.line ?? 0}`;
+ return [
+ position,
+ location,
+ cell(diagnostic.evidence?.confidence ?? '-'),
+ diagnostic.severity,
+ cell(diagnostic.message.split('\n')[0] ?? ''),
+ cell(diagnostic.evidence?.suggestion ?? ''),
+ ].join('\t');
+ });
+ const fileName = `sample-${rule.replaceAll('/', '__')}.txt`;
+ await writeFile(path.join(outDir, fileName), [header, ...rows].join('\n') + '\n');
+ index[rule] = { findings: list.length, sampleFile: fileName, sampled: picked.length };
+ table.push(`| \`${rule}\` | ${list.length} | ${picked.length} | \`${fileName}\` |`);
+}
+
+await writeFile(
+ path.join(outDir, 'index.json'),
+ JSON.stringify({ byRule: index, generatedAt: new Date().toISOString(), source: path.resolve(input) }, null, 2) + '\n',
+);
+
+console.info(table.join('\n'));
+console.info(`\n${diagnostics.length} findings · ${byRule.size} rules · samples in ${outDir}`);
+if (diagnostics.length === 0) console.info('No findings. If this was meant to be a scan, check the scope and the cache.');