Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(skills): add a pull request review skill
Elian Doran12120ff865b0
diff --git a/.claude/skills/reviewing-pull-requests/SKILL.md b/.claude/skills/reviewing-pull-requests/SKILL.mdnew file mode 100644index 0000000000..097e362b3b--- /dev/null+++ b/.claude/skills/reviewing-pull-requests/SKILL.md@@ -0,0 +1,244 @@+---+name: reviewing-pull-requests+description: Use whenever a Trilium pull request is to be judged — "review PR N", "is #N good?", "which PRs should I merge?", "list the merge candidates", "triage the open PRs", "does this fit Trilium?", "compare #A and #B", "draft feedback for this contributor", or any PR number or link with an evaluative question attached. Also use when asked what is mergeable, what to close, or whether a contributor's fix targets the bug it names. The judgement is about fit and shape (philosophy, targeting, complexity, spec, docs), never about CI, conflicts or the description; every candidate is checked out in a temporary worktree and its specs run red/green against the base. Provides review.mjs (list / dossier / verify / dupes / issue / clean) and references on the philosophy as the maintainers apply it, why PRs get closed here, and what an accepted change looks like. Never writes to GitHub. Not for an uncommitted local diff (/code-review) and not for CKEditor-plugin internals (ckeditor5-reviewing, which this skill delegates to).+---++# Reviewing pull requests++A PR arrives with a title, a description and a green check mark, and all three are the author's+claims. This skill judges a PR from three things instead: the **issue** (what is actually wrong or+wanted), the **diff read in the context of the code around it**, and a **verification run** on a+checkout of the branch. The verdict is about whether the change fits this project and has the shape+the maintainers would have given it — because the most common fate of a working contribution here+is not "declined" but "re-done smaller by the maintainer" (33 of 126 closed PRs with a discussion).++Everything mechanical is [review.mjs](review.mjs):++```bash+R=.claude/skills/reviewing-pull-requests/review.mjs+node $R list # every open PR: kind, age, size by file kind, issues, flags, rivals+node $R dupes # open PRs competing for the same issue or subject+node $R dossier 11536 # the PR in full: body, linked issues + their discussion, commits,+ # files by kind, human review threads (bots folded), rivals+node $R verify 11536 # worktree at .claude/worktrees/pr-11536, install, typecheck, the+ # PR's specs green on the branch and red with production reverted,+ # sibling specs, dependency lines, docs impact — ~25 s for a small PR+node $R issue 6853 # an issue with its human comments: the problem statement itself+node $R clean 11536 # remove the worktree (all of them without a number)+```++`dossier` and `verify` save their reports under `.claude/reviews/pr-N/` (gitignored). Nothing here+writes to GitHub — see **Conduct**.++## What is not a factor++State these plainly in a report when the author or a bot leans on them:++- **CI status.** Informational. Forks fail on missing tokens, runners flake, and a green run+ proves the spec passed, not that it tests anything. `verify` answers the real question.+- **Merge conflicts.** The maintainer merges `main` into the branch himself; a PR is merged with+ a merge commit, never squashed. Conflicts matter only when they span the whole change (a branch+ thousands of commits behind, like the MapLibre PR that was rebuilt instead).+- **Age, `size:*` and `lgtm` labels.** `size:*` is a bot's line count; `lgtm` is a bot mirroring a+ maintainer's APPROVED seconds later, not a judgement of its own. `don't merge yet` and `State:*`+ are issue labels; on PRs the state toggle is draft ↔ ready.+- **Bot reviews.** greptile, gemini and codecov comment on every PR. Their findings are unverified+ suggestions; a bot's "approve" is nothing.+- **The description.** Read it last, after the issue and the diff, so it cannot frame the reading.+ Accepted PR bodies are structured prose (`## Why / ## What`, `## Problem / ## Fix`); a body longer+ than the diff is a warning, not a virtue.+- **Whether the author used an agent.** Thirteen agent-assisted PRs by one contributor merged with+ a single APPROVED each. What the maintainers refuse is bulk that does not integrate — additions+ only, planning artifacts in the tree, "vibe coded" — not the tool.++## The dimensions, in the order they decide outcomes++1. **Fit.** Does this belong in Trilium's core at all, and in this shape? The questions are in+ [references/philosophy.md](references/philosophy.md), one per principle: script/widget material?+ an option for one use case? one surface of an app-wide behavior? a workaround for a library?+ outside the data/sync model? an undiscussed design in a maintainer-led area (mobile, sync,+ encryption, storage, `trilium://`)? a changed default or convention? a dependency? Fit decides+ more closed PRs than everything else combined; 40 of the closed PRs had specs.+2. **Problem and cause.** Is the problem real (an issue, a reproduction), is the cause the one the+ diff changes, and does the diff fix *what the reporter described*? The maintainer tests every PR+ by hand and the most common substantive review comment is "it doesn't fix the issue" / "it+ crashes on `00:aa:00`" / "doesn't work on this theme". A fix at the place a symptom is *seen*+ rather than *produced* is `REWORK`.+3. **Targeting and scope.** A bugfix changes the cause and nothing else: no riding feature ("not+ part of the fix, it's a completely separate feature so it deserves its own PR"), no reformatting+ ("makes it really hard to see what actually got changed"), no "while I was here", no labels or+ options beyond what the feature needs. A feature does what the issue thread agreed to, not more.+4. **Size and complexity, against the yardstick.** An accepted bugfix is a median **26 production+ lines in 2 files with a spec larger than the fix**; a feature commit ~74 lines, a feature PR+ ~370. Numbers and exemplars in [references/accepted-shape.md](references/accepted-shape.md).+ Beyond the median, ask the maintainer's question: *which of these files is the bug, and which is+ the refactor you took the opportunity for?* Count abstractions, not lines: a wrapper class, a+ helper with one caller, a new module beside one that does the job, a regex where a parser+ exists, a third mechanism next to two. "Too complicated. Extract to a function with simple `if`s+ and `return`s" is a verdict this project gives.+5. **Robustness.** Bad input ("Always validate user data"), a database with 100 000 notes ("my+ Trilium board has 581 tasks"), other themes and platforms (Windows paths, the flatpak), sync+ peers on an older version, a hidden loss of an existing capability (the sort dialog that lost+ "folders at the bottom"). Look for the branch the author did not test.+6. **Spec.** `verify` says whether the PR's tests fail without the production change and pass+ with it. A new test that passes both ways covers existing behavior, not this fix. A core change+ is proven under `apps/server` **and** `apps/standalone`. No spec on a covered module is a gap;+ a spec that is "quite a bit complicated" is a gap too — the house writes concise ones.+7. **Docs and i18n.** A user-facing change ships with its User Guide page in the same PR, "even if+ it's niche"; `docs/User Guide/**` Markdown and the generated `doc_notes/**` move together+ (hand-edited HTML or unsynced Markdown is a gap); only the `en` catalogues are edited; a new+ option is whitelisted, defaulted and has a control (the seven-file recipe in accepted-shape).+ `verify` runs `docs.mjs impact` for the diff; run it with the feature's name too.+8. **Conventions.** The mechanical checks at the end of accepted-shape (`!`, `forEach`, inline+ `style`, hand-rolled `<input>` where `FormTextBox` exists, `localStorage`, Node built-ins in+ core, comment style, ~10-SLOC modules). Each is a "you finish" gap. They change a verdict only+ in bulk, when they show the code was written beside the codebase rather than in it.++For a diff under `packages/ckeditor5`, load the `ckeditor5-reviewing` skill for the plugin-level+defects; this skill still owns the verdict.++## Workflow A — one PR++1. `node $R dossier N`. Read in this order: the **linked issue and its comments** (the problem, in+ the reporter's and the maintainer's words — if there is none, decide whether the problem is real+ before anything else), the **commits** (subject and body per commit; they land verbatim on+ `main`), the **files by kind and the flags**, the **human review threads** (what a maintainer+ already asked; whether it was done), the **rivals**, and only then the description.+2. `node $R verify N`. Read the report: install, typecheck, each spec's green/red result and which+ tests prove the change, sibling specs, dependency lines, docs impact.+3. **Read the diff in the worktree**, not on GitHub: `git -C .claude/worktrees/pr-N diff+ $(git -C .claude/worktrees/pr-N merge-base HEAD origin/main)` and then the changed files whole,+ with what surrounds them. This is where "reuse the existing helper" (`useNoteLabel`,+ `isCtrlKey`, `FormTextBox`, an existing option) and "wrong layer" are visible and a diff view+ hides them. For a bugfix, find the cause yourself first, then compare.+4. Run the mechanical checks from accepted-shape in the worktree that apply to the touched areas.+5. Judge the eight dimensions. Write findings ordered by weight — a fit problem first, a missing+ `en-GB` twin last.+6. Verdict, with the gaps list, and the report block below.++When the PR has a rival (`dupes`), do both and write one comparison: the smaller change that fixes+the cause usually wins; the earlier one has no precedence by age; sometimes the right answer is a+third, smaller change that neither made — say so, and name it.++## Workflow B — merge candidates (triage)++The question "what should I merge?" is answered in two passes, because verifying 60 PRs costs an+hour and most verdicts do not depend on the code running.++1. `node $R list` and `node $R dupes`. Note what the list hides (bots, the maintainers' own drafts+ and spikes — those are the maintainer's business, not candidates).+2. **Screen on dossiers.** `dossier` each PR (the saved reports accumulate under+ `.claude/reviews/`). Decide from the issue, the commits, the file mix and the review threads+ which PRs cannot be candidates whatever the code does: fit failures, undiscussed designs in+ maintainer-led areas, bulk, riding features, a use case nobody asked for, a rival already+ superseded. Give each a one-line reason and its verdict (`DECLINE`, `REWORK` or `YOUR CALL`).+ Do not read code yet.+3. **Verify the rest.** Everything that survives the screen gets Workflow A in full, `verify`+ included — nothing is called a candidate on a description. For more than a handful, fan out one+ agent per PR with this skill's path and the dossier, each returning the report block; keep the+ ranking and the rival comparisons for yourself.+4. **Resolve rivals** side by side (Workflow A's last step).+5. **Rank the candidates by cost to land**, then by value: no gaps < a subject line or a doc+ paragraph < a spec to write < a fix to make. Value is the issue behind it — a regression, a+ reported bug with traction, a feature a maintainer said yes to — never the PR's own claims.+6. Report with the triage block below. Say which PRs were verified and which were screened out on+ the dossier alone, so the maintainer knows what was and was not run.++## Verdicts++- **MERGE** — right problem, right cause, right shape, fits. The spec proves the change and+ typecheck passes. Gaps, if any, are what the maintainer finishes on the branch in minutes: the+ `(closes #N)` subject, a rename, a doc paragraph, an `en-GB` twin, a redundant comment. List+ them under *You finish*; they do not lower the verdict.+- **MERGE AFTER FIXES** — the same, but something is not right yet and the fix is local: a crash on+ bad input, a missing validation, a test for a well-covered module, a riding change to drop, the+ feature in the wrong menu. The shape stays. List each fix; the contributor or the maintainer does+ them before it lands.+- **REWORK** — the goal is right (and, for a feature, agreed), the shape is wrong: too big for the+ bug, the wrong seam or layer, one surface of an app-wide behavior, a toggle where the default+ should change, a parallel mechanism, a workaround. Name the target shape concretely — the+ maintainer's habit is to write that smaller change himself, so "the fix is the one condition in+ `link.ts:142`, the rest is a refactor" saves a round trip. The *yes, but* table in philosophy.md+ is the catalogue of target shapes.+- **DECLINE** — does not fit: script or widget material, a use case that is not the project's,+ duplicates what exists, an undiscussed architecture from a first-time contributor in a+ maintainer-led area, a workaround for a library the project would rather remove, bulk that does+ not integrate, or a rival that lost. Quote the principle and the precedent (issue or PR number).+- **YOUR CALL** — the code could be fine but the question is direction, and only the maintainer+ settles it: a new default, a convention change, a dependency, a real proposal in a maintainer-led+ area, a plausible feature nobody requested, a behavior change users will notice. State the+ question in one sentence, give a recommendation, and do not call it a merge candidate.++`MERGE` and `MERGE AFTER FIXES` are the merge candidates. A `YOUR CALL` becomes one only after the+maintainer answers.++## Claims to check, not read++| The PR says | Check |+|---|---|+| "Fixes #N" | Read #N. Does the diff address what the reporter described, or a neighbor of it? (#11063 fixed the cursor position, not the duplicated text.) A `(closes #N)` in the title counts as a link even when GitHub did not parse it. |+| "Tested manually", "works for me" | `verify`. Then ask which platform, theme, database size and sync setup — the untested branch is usually the one that breaks. |+| "No user-facing change" | `verify`'s docs impact; grep the diff for `t("`, JSX, CSS, keyboard actions, options, hidden-subtree launchers. |+| "Small change", `size:S` | Production lines and files from the dossier, not the total; then count abstractions. |+| "Added tests" | `verify`'s red run. Tests that pass without the production change do not test it. |+| "Refactor, no behavior change" | Every call site of what moved; a capability quietly lost (folders-at-the-bottom in #11424). |+| "Docs updated" | Both the Markdown and the generated help, produced by `edit-docs`/`docs.mjs sync`, not hand-edited HTML. |+| "Will add docs/tests/UI in a follow-up" | It is a gap now; the PR is judged as it is. The maintainer sometimes allows "a separate PR if needed" — that is his call to make, not the author's. |+| `fix(…)` in the title | Is it a feature? A new plugin, component or module under a `fix(` subject is judged as a feature (discussed? documented? agreed?). |+| "Minimal", "simple" | New classes, wrappers, single-caller helpers, new modules, regexes where a parser exists. |+| "Same as #X but better" | `dupes`; judge both side by side. |+| Bot approval, `lgtm` | A mirror of a human APPROVED at best; nothing on its own. |++## Report block — one PR++```+## #N — <title>+Verdict: MERGE | MERGE AFTER FIXES | REWORK | DECLINE | YOUR CALL+Problem: <the issue in one sentence; whether the diff addresses that, in your words>+Change: <what the diff does, in your words; prod +A/−B in F files, spec, docs>+Fit: <principle engaged, with the precedent, or "fits">+Verified: <spec proves N tests / passes without the change / none; typecheck; runtimes run>+Findings:+- <heaviest first: fit, cause, scope, size, robustness, spec, docs, conventions>+You finish: <gaps the maintainer closes on the branch> [MERGE]+Fixes before merge: <local fixes> [MERGE AFTER FIXES]+Target shape: <the smaller/other change, concretely> [REWORK]+Question: <one sentence> — recommendation: <one sentence> [YOUR CALL]+```++## Report block — triage++```+# Merge candidates — <date> · <N> open PRs, <V> verified, <S> screened on the dossier+## Merge (ranked by cost to land, then value)+1. #N <title> — <value in five words> — you finish: <gaps> — verified: <one line>+## Merge after fixes+## Rework — goal right, shape wrong+## Your call+## Decline+## Rivals — one issue, several PRs+- #A vs #B (issue #I): <which, why, in two lines>+## Not assessed: maintainer drafts and spikes, bots+```++## Conduct++- **Read-only on GitHub.** No comments, no reviews, no labels, no draft toggles, no closes — not+ on PRs, not on issues. The maintainer speaks to contributors; a bot-shaped comment under his name+ is exactly what he objects to in others.+- **Feedback for a contributor is drafted, not sent.** When asked, write it in the maintainer's+ register — short, concrete, the reason with the ask ("Always validate user data. If I enter+ `00:aa:00`, the calendar crashes. Report invalid values via toast; write a test for it.") — and+ hand it over as text to paste.+- **Never write to the PR branch.** The worktree is a reading copy; `verify` restores it and reports+ if it could not.+- **Say what was run.** A verdict without a `verify` run says so; a spec that could not run under+ standalone says so.++## Reference map++| File | Use it for |+|---|---|+| [references/philosophy.md](references/philosophy.md) | The fit dimension: 18 principles as review questions, each with the maintainers' own words and the issue/PR numbers; the *yes, but* table of shapes a request is accepted in. |+| [references/rejection-patterns.md](references/rejection-patterns.md) | Why 126 PRs were closed, as spot-in-a-diff patterns with quotes; the priors (superseded by a smaller change, size, fit over specs). |+| [references/accepted-shape.md](references/accepted-shape.md) | The yardstick: measured size and shape of accepted fixes and features, exemplar commits, how PRs land, what the maintainer asks for vs fixes himself vs sends back, and the mechanical checks. |diff --git a/.claude/skills/reviewing-pull-requests/references/accepted-shape.md b/.claude/skills/reviewing-pull-requests/references/accepted-shape.mdnew file mode 100644index 0000000000..1563d30701--- /dev/null+++ b/.claude/skills/reviewing-pull-requests/references/accepted-shape.md@@ -0,0 +1,188 @@+# What an accepted change looks like++Measured on `main` between March and September 2026: 65 bugfix commits, 30 feature commits, 15+feature PRs, and the last 250 merged PRs. These numbers are the yardstick the complexity and+targeting dimensions measure against. They describe the median, not a limit — a larger diff is+accepted when its body proves the smaller one was wrong.++## A bugfix++| metric | fixes with an issue (n=45) | all fixes (n=65) |+|---|---|---|+| production lines changed (+/−), median | **26** (Q1 13, Q3 44) | ~24 |+| production files, median | **2** | 2 (Q3 4) |+| spec added or changed in the same commit | 80 % | **78 %** |+| spec lines when present, median | 57 (larger than the fix) | — |+| User Guide touched | 0 % | 1.5 % |+| commit body present / median length | 89 % / 21 lines | 88 % |++The template: **one or two production files, 5–30 changed production lines, a spec in the same+commit that is larger than the fix, and a body that explains the cause well enough that the diff+needs no comments.** Exemplars (`git show <hash>`):++| hash | subject | prod | spec | why |+|---|---|---|---|---|+| `1ff82b4195` | fix(client): don't open a target=_blank link on right-click (regression of #3971) | +1 −1 | +16 | names the commit that fixed #3971 and the one that re-broke it; the fix is one condition |+| `4159c782fd` | fix(table): re-widen the row number column past 99 rows (closes #11590) | +5 −1 | +14 | explains why the existing spec missed it and uses the real payload |+| `61d924d53e` | fix(client): stop keystrokes reaching the note while a dialog opens (closes #7996) | +9 | +47 | external, agent-assisted: Cause / Fix / Verification (red before, green after) / Known remainder; merged with one APPROVED |+| `cd381e09fe` | fix(search): keep result paths out of the bookmarks clone (closes #10021) | +13 −10 | +35 | traces the bug through two path prefixes, names the PR that introduced the tiebreaker and keeps its intent |+| `b4266ad816` | (a `key={noteId}`) | **+1** | +65 | one production line and a lifecycle spec |++Fixes that carried more than the bug still landed, at a price — a body that justifies every extra+file: `3c7362888a` (a new 220-line scanner module, with why not a CSSOM walk and two follow-ups),+`b387bbf5ba` (collapses five listeners into one, with a timing table), `d9877c20e9` (9 files, adds+a shared prop and moves a hook, and admits a gate left "narrower than it should be"). Feature-shaped+diffs under a `fix(` subject (`3f8ae20781`, a whole CKEditor plugin; `e355c5840d`, a new component)+are the exception, not the pattern. The question a large `fix(` must answer: **which of these files+is the bug, and which is the refactor you took the opportunity for?**++### The commit body++The canonical body has three movements: (1) what the user saw and why the code did it, with the+offending identifier named and, for a regression, the hash that caused it; (2) what changes and why+that shape — often "X rather than Y because …"; (3) what is unchanged or out of scope. Over the+sample: 82 % name the cause, 42 % weigh an alternative, 23 % describe verification, 12 % cite the+regressing hash. Contributors who write `Cause:` / `Fix:` / `Verification:` / `Known remainder:`+headings are accepted as-is.++### The subject++98 % are `fix(<area>): …` with an area (`search`, `share`, `desktop`, `collections/table`), not a+file. The close keyword is always `closes`, always in the subject: `(closes #N)`, bare `(#N)` when+the issue stays open, `(regression of #N)`. The subject describes the user-visible outcome in the+imperative, not the mechanism.++## A feature++| metric | per feat commit (n=30) | per feat PR (n=15) |+|---|---|---|+| production lines, median (Q1–Q3) | 74 (30–133) | **367** (70–1085) |+| production files / total files, median | 3 / 5 | 8 / 16 |+| spec in the same change | 87 % | **93 %** |+| `docs/User Guide/**` in the same change | 13 % | **53 %** — 8/8 of the PRs with a UI surface |+| generated help (`doc_notes`) regenerated | — | always together with the User Guide edit, never one without the other |+| `translations/en/*` touched | 37 % | 53 % |++Docs usually arrive as their own `docs(user): …` commit on the branch, which is why the per-commit+rate is low and the per-PR rate is what counts. The 7 feature PRs without a User Guide change were+ETAPI (the OpenAPI file is the doc), standalone internals and build changes (Developer Guide+touched instead), and two tiny UI tweaks.++Options: 48 keys added to `options_interface.ts` since March; 45 whitelisted in `ALLOWED_OPTIONS`+in the same commit (the three exceptions are server-internal state that must not be+client-writable), 42 with the default in `options_init.ts`, 12 of the last 17 with the settings+control and its English key in the same commit. A user-facing option that misses any of these is+incomplete, not wrong.++Exemplars: `433a238751` (core + two specs + translation + User Guide in one commit), `31cc8a825b`+(client + specs + the `.md` + the regenerated `.html`), `c9dec8e2cd` (the full seven-file option+recipe in +56 lines), `8e876786e6` (ETAPI route + `etapi.openapi.yaml` + spec), `07aaf5ef8f`+(`.tsx` + its `.css` twin + `.spec.tsx` + i18n). PRs: #11667, #11521, #11440, #11424, #11652.++## How a PR lands++- **Always a merge commit**, never squash or rebase (60/60). The branch commits survive verbatim on+ `main`, so each commit's subject and body is what history keeps — a PR is judged commit by+ commit, not as one blob. External PRs carry a median of 4 commits.+- **The merge subject is the PR title + ` (#N)`**, body empty. The title was rewritten on merge+ once in 49; so the PR title has to already be the conventional subject with `(closes #N)`.+- **The maintainer finishes rather than sends back.** 10 of 32 external PRs got maintainer commits+ before merging (renames, a spec, a doc line, a moved control); only one PR in the sample carried+ a CHANGES_REQUESTED review, and it still merged after maintainer commits. 22 of 49 external PRs+ merged with no formal review. Time to merge: 0.7 h for the maintainer's own, a median of 20.6 h+ for external.+- **27 % of landings bypass a PR**: small fixes pushed straight to `main` by maintainers. A+ contributor's small fix competes with "I could push this myself in ten minutes" — which is why a+ correct 5-line fix with a good spec merges within a day, and a 300-line one for the same bug gets+ re-done.+- **Bots are not reviewers.** `greptile-apps` comments on every PR and gates nothing; `codecov`+ posts coverage deltas. Neither is evidence of review.+- **Accepted PR bodies** are structured prose: `## Why / ## What`, `## Problem / ## Fix`,+ `## Tests / ## Verification`, one heading per cause. The maintainer's own PR bodies are the commit+ bodies regrouped by subsystem.++## What gets asked, fixed silently, or sent back++From 147 merged external PRs (November 2025 → September 2026). **108 merged silently** — no+maintainer text, or an empty APPROVED with "Nice." / "Thanks!" / "Good job!" — and 10 of the 19+zero-text merges were 100–250-line self-contained fixes with a spec and `(closes #N)`. Only 39 drew+a substantive comment. What those comments asked for, ranked:++1. **Robustness (12)** — "Always validate user data. If I enter `#calendar:slotLabelInterval=+ "00:aa:00"`, the calendar crashes." / "the fix is good but it doesn't fix the issue reported+ in #10663. This fixes only mis-positioning of the cursor, it does not cure duplicated text." /+ "It doesn't seem to work, at least on the Trilium Next theme." / "This is not platform-agnostic+ since it will fail on Windows." / a hidden capability loss caught in review (#11424).+2. **Docs (9)** — "Please also mention it somewhere in the documentation. Even if it's niche." /+ "an important feature such as recurrence needs its own heading in the Calendar documentation" /+ "No need to modify the HTML file directly, please follow the `edit-docs` process."+3. **Questions (8)** — "what's the use case here? Is there an issue related to it?" / "what happens+ if you add too many items in the launch bar?" / "Why were the `if` conditions removed?"+4. **Simplify (6)** — "Too complicated. Extract to a function with simple `if`s and `return`s." /+ "There's no benefit of having a wrapper class" / "This doesn't make sense as a standalone method,+ it needs to be inline." / "This whole resize mechanism feels overengineered. Do we actually need+ it? I tried remove part of it and it worked just fine."+5. **Scope (5)** — "It's not part of the fix, it's a completely separate feature so it deserves its+ own PR." / "the tree is for note-related options, there are no other content-copy operations in+ it." / "could you please try to separate the features into multiple PRs?"+6. **Tests (5)** — "Missing tests. The event builder has pretty decent coverage and I would like to+ keep it that way." / "The test is OK-ish, although I feel it's quite a bit complicated."+7. **i18n (5)**, **diff noise (3)** — "I see you re-formatted the entire file and this makes it+ really hard to see what actually got changed." — **offline/privacy/size (3)**, **where a value+ lives (3)** — "All new options/configurations in Trilium must also be exposed to the user+ through the UI, not just through attributes." / "We don't expose additional widgets to the+ front end API, only widgets that are actually used by Trilium." — **naming (3)** — a syntax+ colliding with attribute names — **consistency (2)**, **reuse (2)** — "Let's just use+ `useNoteLabel` instead." / "Why not simply use `<FormTextBox>` with `type=datetime-local`".++Never asked on a merged PR: commit-message format, squash or rebase, sync implications. The+regulars follow the subject convention; nobody else is held to it — the maintainer fixes it.++**Fixed by the maintainer on the branch** (42 of 147 PRs carry his commits; 16 of the 28+substantive ones merged with no review text — he edits rather than asks): typecheck and lock+files; renames (`textarea` → `multiline text`); inlining single-caller helpers and shortening+comments; the `docs(user): …` and `test(…): …` commits the contributor did not write; the bot's+suggestion; a second-order bug found while testing; widening to the sibling platform or API (a+backend script-API method gets its frontend twin); moving a control to where it belongs. Three+contributions became seeds he rewrote wholesale (link previews: 17 of 20 commits his; the Ollama+provider: 22 of 31; the iOS app: 20 of 43).++**Sent back instead**: a crash on bad input; an unrequested feature riding along; missing tests on+a covered module; an unreviewable reformatted diff; a feature in the wrong menu; a syntax that+collides with attribute names. Closed outright: an undiscussed design in a maintainer-led area, a+bounty attempt, and anything he preferred to re-do at a different seam.++He also merges imperfect work that moves in the right direction and says so: "OK as a first+implementation, although the long-term fix is to get rid of the jQuery" / "Please note that this+will not be the final form" — then polishes on `main` within the week rather than holding the PR.++## Mechanical checks on a diff++The house rules from `CLAUDE.md` that a diff can be checked for. Each is a gap for the maintainer's+"you finish" list — a verdict changes only when they are pervasive enough to show the code was+written beside the codebase rather than in it. Run them in the verify worktree+(`.claude/worktrees/pr-N`) with `R=$(git merge-base HEAD origin/main)..HEAD`:++| rule | check |+|---|---|+| bugfix subject carries `(closes #N)` | `git log --format=%s $R \| grep -E '^fix' \| grep -vE '\((closes\|regression of) #[0-9]+\)'` |+| no non-null assertion `!` | added lines: `git diff -U0 $R -- '*.ts' '*.tsx' \| grep '^+' \| grep -P '[A-Za-z0-9_)\]]!(?=[.\[);,]\|$)'` (strings and `!==` excluded by eye) |+| no `forEach` | `git diff -U0 $R \| grep '^+' \| grep -E '\.forEach\('` |+| no inline `style=` in JSX | `git diff -U0 $R -- '*.tsx' \| grep '^+' \| grep -E '\bstyle=\{'` |+| a `.css` twin per new component | each added `*.tsx` outside specs has `${f%.tsx}.css` |+| reuse the react components | added `<(input\|select\|button\|textarea\|a)\b` or `form-control\|input-group\|btn btn-` in `.tsx` under `apps/client` |+| no `localStorage` / secure-context crypto in the client | `grep -E 'localStorage\|sessionStorage\|crypto\.randomUUID\|crypto\.subtle'` on added lines |+| safe-area insets via the custom property | added `env(safe-area-inset` without `var(--safe-area` |+| new option: whitelist + default + control | a key added in `options_interface.ts` ⇒ the same diff touches `routes/api/options.ts` (`ALLOWED_OPTIONS`), `options_init.ts`, an options pane and the English catalogue |+| core has no Node built-ins or `process.env` | `git diff -U0 $R -- 'packages/trilium-core/src/**' \| grep '^+' \| grep -E 'process\.env\|from "(node:)?(fs\|path\|os\|crypto\|child_process\|url)"'` |+| server assets never via `import.meta.url` / `__dirname` | added lines under `apps/server/src` |+| the client never imports core | `git diff --name-only $R -- 'apps/client/**' \| xargs grep -l '@triliumnext/core'` is empty |+| core specs run in both runtimes | a core change is verified by `verify` under `apps/server` **and** `apps/standalone` |+| generated help never alone | `doc_notes/**` or `help_meta.json` changed ⇔ `docs/User Guide/**` changed |+| only the `en` catalogues edited | `git diff --name-only $R \| grep -P 'translations/(?!en/)'` is empty |+| `en-GB` twin for US spellings | an added `en` string with `color\|center\|meter\|recogni[sz]e\|labell?ed\|cancell?ed` needs the `en-GB` entry |+| comment style | added comment lines with `—`, ` may `, `was \|previously\|no longer\|moved from\|removed\|intentionally not`; CSS `/* was Npx */` |+| no ~10-SLOC module | `git diff --diff-filter=A --numstat $R \| awk '$1 <= 15 && $3 !~ /spec/'` |+| helpers below the primary export | in an added module, the first non-exported `function` comes after the first `export` |+| CJS dynamic-import interop in split ESM | `const mod = await import("pkg"); const { x } = mod.default ?? mod;` — a plain destructure is the trap (`analyzing-backend-bundle` skill) |+| formatting | `pnpm dev:format-check` in the worktree (never ESLint) |diff --git a/.claude/skills/reviewing-pull-requests/references/philosophy.md b/.claude/skills/reviewing-pull-requests/references/philosophy.mdnew file mode 100644index 0000000000..b32f2d1df2--- /dev/null+++ b/.claude/skills/reviewing-pull-requests/references/philosophy.md@@ -0,0 +1,343 @@+# Trilium's philosophy, as the maintainers apply it++The "fit" dimension of a review. Each principle: what it is, the question it turns into when a PR+is on the table, and the evidence — issue and PR numbers, with the maintainer's own words. The+numbers are TriliumNext/Trilium issues and PRs (`gh issue view N`, `gh pr view N`); migrated+zadam-era issues keep their original numbers. `CONTRIBUTING.md` is the closest thing to a charter+and says most of this in the maintainers' voice; this file adds how each rule is applied.++Read it as the maintainer's habits, not as a rulebook: a PR that breaks one principle with a good+reason is a `YOUR CALL`, a PR that breaks one without noticing is a `DECLINE` or `REWORK`.++## 1. A hierarchical *personal* knowledge base — not Word, not a Markdown editor, not a block editor, not a team wiki++Ask: does the PR pull Trilium toward another product's model (free-flow pages, pagination, a+Markdown dialect, per-block attributes, multi-user collaboration)?++- #6272: "Trilium will never be a full-fleged, general-purpose editor such as Microsoft Word."+- #6799: "You have to think of Trilium not as a WYSIWYG editor, but as a personal wiki system. That+ means it gets to have its own conventions that you might or might not agree with." The conflict+ (H1 handling) was resolved by adding a *separate Markdown note type*, not by changing the text+ note's convention.+- #9472: "Trilium is by design tree-based, changing this would go against its philosophy."+- Discussion #10967 (block-based features): block-level attributes "would be the largest change+ … Unless there is significant demand for it".+- `FAQ.md` on multi-user: "the assumption that only single person has access to the app simplifies+ many things, or just outright makes them possible."++## 2. The note is the only building block; structure lives in branches++Ask: does the PR invent a second kind of thing (a "container", a "block", a "user", a "folder")+that is not a note with attributes, or store placement on the note rather than in a branch?++- `Notes.md`: "In Trilium there's no specific 'folder' note type. Any note can have children."+- PR #7734: "you can just change the Note Type from Text to Collection. This more clearly specifies+ the intent of a container."+- PR #7441 (multi-user): "The user management doesn't seem to match Trilium's model for the becca,+ where each user is a model. How are the users synchronized across multiple instances?"++## 3. Attributes and templates are the configuration surface++Ask: could the behavior be a label, an inheritable label, a promoted attribute or a template, and+does the PR reach for a setting or new UI instead?++- #7290 (note color): "you can simply implement what you requested by using promoted attributes+ … `#label:color(inheritable)="promoted,alias=Color,single,color"`".+- #6494: "change `language=foo` to `#language(inheritable)=foo`".+- #9756: "Prefer using promoted attributes and just changing the label and keeping the attribute+ name the same."+- PR #9687 (checklist progress on board cards): "you could theoretically make use of promoted+ attributes to show the number of checked vs unchecked items."+- The other direction holds too — an attribute is not a substitute for UI on an app-level+ setting. PR #8880: "All new options/configurations in Trilium must also be exposed to the user+ through the UI, not just through attributes." PR #7878: existing attributes stay as they are+ "since at some point they'll become system attributes and mostly be used through the UI."++## 4. Workflow-specific needs go to scripts, custom widgets, render notes, `#appCss` or ETAPI — not core++The single most common decline, for issues and PRs alike. The maintainer routinely answers with a+working snippet.++Ask: does the feature assume a particular workflow, and would a script or widget serve the people+who want it?++- `CONTRIBUTING.md`: a feature "will likely be declined when it: can be built as a user script or+ custom widget instead."+- PR #10308 (`#openAtBottom`): "better served as a custom widget instead of being part of the+ core." (a full widget draft was pasted into the comment)+- PR #11102 (mouse-wheel tab switching): "better suited as a custom script instead … a Linux-only+ convention that has generated user complaints in various apps, especially if it's not+ toggleable."+- #9442 (auto-date notes under Calendar): "not something that should be part of Trilium because it+ assumes a particular workflow." → a `runOnChildNoteCreation` backend script.+- #5189: "We need to keep the code base as lean as possible, so we will not add a custom option for+ this."+- #7006, #715, #2485, #991, #9943, #1386, #8600, #9029, #11175, #8159, #9006, #242.+- The counterweight, #4269: features still land in core rather than as shipped scripts because+ "there's no distribution mechanism. Scripts can only come from the demo … Without a central+ plugin registry, scripts are fragmented". A *generally useful* behavior can be core; a+ *personal* one cannot.++## 5. No setting for a single use case; fix the default and stay opinionated++Ask: does the PR add an option, a toggle, a per-note switch? Every one is a branch to test forever.+The bar is "many users want opposite defaults", not "someone might".++- #5364: "toggles are quite expensive in terms of maintenance. From the moment you add it you now+ have two more branches in the application … we will have to start to get opinionated in order to+ get the project going."+- #9584: "Adding a new option is a commitment, every single change branches off the logic of the+ application."+- #9682: "the fix is to simply **get rid of said recursion**, not make it user toggleable."+- #8368: "adding an option to various tweaks and preferences would explode our number of options."+- #1181 (zadam): "Having things configurable is very expensive in terms of effort and future+ maintenance, so I'm trying to avoid that wherever possible."+- Accepted counter-example #5309: a one-line CKEditor flag with no branching UI.++## 6. Everything works offline; libraries are embedded; no online services in core++Ask: does the PR load anything from a CDN, call a remote service, or need a network to work?+The LLM integration is the one opt-in, off-by-default exception, and it was removed once (v0.102.0)+when it could not be maintained.++- `CONTRIBUTING.md` constraint 1: "Everything must work offline. Features that need an online+ service cannot go into the core … libraries must always be embedded in the application, never+ loaded from a CDN."+- #10093 (draw.io): "everything in Trilium must work offline. Draw.io is a few hundred megabytes."+- #3865: "Bundling a third-party commercial handwriting API is out of scope for a local-first PKM+ tool." #6553: remote (S3) stores "we have no plan to implement".+- Discussion #10555 on cloud LLM providers: "people should be allowed to make their own decisions+ … it's pretty well contained in the project".++## 7. Bundle size and data longevity gate every dependency++Ask: does the PR add a dependency, and is it small, used in more than one place, and free of a+proprietary format? Where does it land — core (server, desktop *and* standalone's worker), the+client bundle, or a lazy chunk?++- `CONTRIBUTING.md` constraints 2–3: "A new dependency cannot be added without checking that it+ does not negatively impact the bundle size." / "We avoid dependencies with proprietary formats,+ unless the data can be fully imported or exported."+- #676 (zadam, draw.io): "I want to keep the data in Trilium usable for decades."+- #6710: per-locale fonts "would increase our binary size significantly."+- PR #9076: "Check the impact on the delivery size."+- PR #10825: "SQLite artifacts are **intentionally** trimmed … 4.4 MB for a piece of code that+ never gets executed."+- `Compression libraries.md`: fflate over jszip, "roughly 30 KB against ~95 KB, in a bundle where+ that matters".++## 8. Off-the-shelf components stay unmodified; their limits go upstream; no workarounds for a library++Ask: does the PR patch around CKEditor, Excalidraw, MindElixir, CodeMirror, FullCalendar,+Tabulator, Electron? Does it add a CKEditor plugin? Is it the third workaround for the same library?++- #8382: "We are already spending a huge amount of time maintaining the plugins we have to CKEditor+ … and we don't have the bandwidth to add more."+- #7848: "We have to use off-the-shelf solutions in order to avoid the maintenance burden."+- PR #11548 (a *working* mermaid fix): "this is already the third or the fourth workaround we+ needed to implement due to the underlying library. As such, I prefer to get rid of that library+ entirely."+- PR #9960: "If the diagram fails to render, then we must fix that issue instead of having a+ work-around." `CONTRIBUTING.md`: "a manual refresh button that hides a rendering bug will not be+ accepted."+- `Technologies used.md` (Excalidraw): "We are using an unmodified version of it."++## 9. SQLite plus entity-change sync is load-bearing++Ask: does the PR write outside becca (direct SQL, `localStorage`, files), skip `EntityChange`+records, add a note type without a sync-version bump, or assume one instance?++- PR #7056: "Trilium does not use the local storage feature at all. All data in Trilium is managed+ within the SQL database … we store it in an attachment inside the note. We must not break this+ functionality."+- PR #7879: "creating a new note type also implies increasing the sync version, because a sync with+ an old server (pretty common case) will transform the gallery into a File note type otherwise."+- PR #7441: "syncing does not work when multi-user is enabled? This is critical as the core of+ Trilium is based on this." deajan: "one of the goals of Trilium is to be able to work offline."+- #10035, #5347, #2654, #10085 (newest-wins, no merge), `CLAUDE.md` ("Always use cache methods").+- PR #7757: "we prefer computation on the server (which already has rapid access to all notes)+ instead of the client." PR #6764: "no need to have the server involved for a client-side-only+ affair (CKEditor)." — the layer follows where the data is.++## 10. The single user is the trust boundary; no security theatre++Ask: does the PR add friction that only protects the owner from themselves?++- `SECURITY.md`: "Users can intentionally create notes containing scripts, HTML, or other+ executable content. This is by design."+- #10453: "this would bring in a false sense of security. If someone gets temporary access to an+ already unlocked session, they can still do that through other means."+- #4995: a separate password for protected notes "would add too much complexity to the+ application without much of a benefit in security."+- PR #10013: the sync host on the About dialog "is a privacy breach" (screenshots in bug reports).++## 11. Defaults and conventions are deliberate, preferably at parity with an external standard++Ask: does the PR change a default, a shortcut, a convention, a menu? Was the current one a choice+(usually yes), and does the PR argue against the reason for it or just against the outcome?++- #5589: admonitions are "at 1:1 parity … with GitHub's admonitions support".+- #8219: font icon packs, not SVG/PNG: "The gap is intentional."+- #6799: single H1 → "If we allow h1 in imports, then we also have to allow them in the text+ editor … case in which it is a breaking change."+- #11522: "the menu itself is already quite a bit cluttered … Adding yet one more option is+ probably a step in the wrong direction."+- PR #6918: "this is a change in behaviour that many people will be surprised to see. We can't+ simply remove it."+- PR #9634: removing the default-shortcut column loses "the information on whether the user made+ changes … simply removing it is not a solution."+- `CONTRIBUTING.md`: easier to accept when it "keeps current behavior unchanged by default (new+ behavior is opt-in)".++## 12. Frequent-action behavior is app-wide or nowhere++Ask: does the PR add a behavior (ctrl+click, drag, a badge, a shortcut) to one surface when the+same action exists in the tree, collections, the geo map, the note map?++- PR #8677 (13 lines, correct): "if we add support for this feature of opening in a split we have to+ add support for it everywhere (tree, geo map, list/grid collections). We cannot introduce+ inconsistent behaviour when it comes to frequent user actions."+- PR #9687: "specific to the board collection, which means that the user cannot benefit from it+ anywhere else."+- PR #8864 (drag-and-drop toolbar editor): "it would align with the rest of the application" beats+ "more user-friendly".+- PR #9680: light/dark "can't be treated as a separate theme because that would limit the user+ selection".++## 13. Big designs are made on the maintainers' side, after a discussion++Ask: is this a first-time contributor landing an architecture (a protocol, storage, sync, mobile,+multi-user, a new note type) that no issue thread agreed on?++- `CONTRIBUTING.md`: "Some areas are maintainer-led … the mobile apps, sync and encryption+ architecture, the `trilium://` protocol, the storage model, and areas under active maintainer+ redesign." And: "first open or find a feature request or idea and wait for maintainer feedback."+- PR #9244: "Especially since you are a first time contributor to the Trilium code base and this+ was not discussed beforehand, this is a big design choice that we should ideally make on our+ side."+- PR #7828: "please take the time to discuss first the request and perhaps even the+ implementation … it also decreases the chances of being rejected after the work has already been+ done." / "I would also appreciate it if we keep the PRs minimal."+- PR #7879: "For big features such as this, I would appreciate it if we can have a discussion+ about it beforehand."+- #6799: "open-source does not mean open governance, or decision by committee."+- PR #11064 (the `CONTRIBUTING.md` review): "Feature implementations should ALWAYS be discussed+ in a feature request or idea first … there are perfectly valid PRs that we have to let go just+ because they don't fit the philosophy of Trilium. Discussing first avoids that risk … Bugfixes+ and documentation changes are OK." A bugfix needs no prior discussion; a feature does.++## 14. Maintainer bandwidth decides scope; maintenance cost is a first-class reason++Ask: who maintains this in two years? Does it add a parallel mechanism to one that exists?++- PR #7828: "Why have three different mechanisms in place for content accessors? This creates a+ maintenance burden … choose one and stick to it."+- PR #6839: "I would remove the old search mechanism to avoid having two big parallel+ implementations."+- PR #6867: "I would prefer not to have the maintenance burden of handling this edge case."+- PR #10649 (the maintainer's own spike): "Conceptually nice, but a lot of work to do for+ something that was not even requested."+- #6804, #5574, #5813, #2637: "the effort outweighs the demand" / "if the request gains a+ significant traction".+- Whole subsystems go when unmaintainable: the LLM integration (v0.102.0), then back once a+ library carried the provider differences (v0.103.0).+- No surface is added for a hypothetical consumer. PR #10526: "We don't expose additional widgets+ to the front end API, only widgets that are actually used by Trilium." PR #7704: "for a component+ to be useful, it has to be used in multiple places."+- The counterweight: work in the right direction merges imperfect. PR #9104: "OK as a first+ implementation, although the long-term fix is to get rid of the jQuery and use a custom dialog."+ PR #8484: "I will merge this because I appreciate some of the features … this will not be the+ final form." The maintainer then polishes on `main` rather than holding the PR.++## 15. Environment problems are solved in the environment++Ask: is this a reverse-proxy, Electron, OS, theme or plugin problem dressed as a Trilium fix?++- #7968: a Traefik breaking change → "won't fix. I've documented the necessary changes … in the+ User Guide".+- #8401: "Adding an empty search would be an incorrect solution since it would return a different+ set of results."+- #5768: base URL "The proper way is to handle it via the reverse proxy".+- `CONTRIBUTING.md`: "better handled outside Trilium, for example HTTP Basic Authentication at a+ reverse proxy, or packaging-only concerns."++## 16. Mobile means the mobile layout on the shared code base++Ask: does the PR add a desktop-view fix for phones, or a native path where the standalone/worker+architecture is the strategy?++- #5325: "Using the desktop view on mobile is not supported."+- #7447: "We can't afford the cost of maintaining both a Node.js + TypeScript and a Kotlin+ implementation."++## 17. A fix fixes the cause, in the layer that owns it++Ask: does the diff change the place that produces the symptom, or the place where it is seen?+Would the maintainer name a different root cause?++- PR #11553: "The 'proper' solution here is to not refresh the table at all when the change comes+ from the same editor."+- PR #11296: "the issue in #11244 lies somewhere else: it's not the event handling or focus+ stealing, it's the the fact that we have two titles."+- PR #11176: "the PR title mentions infinite scrolling but nothing is done about that and the root+ cause appears incorrect."+- PR #9076: "Handling the actual formatting should not be the responsibility of the CKEditor plugin+ … move the formatting part into the client and provide an API."++## 17b. Bad input never crashes; the untested branch is the one that breaks++The maintainer tests every PR by hand, and the most common substantive review comment is about+what he saw: a crash, a theme, a platform, an older sync peer, a big database.++- PR #8880: "**Always validate user data.** If I enter `#calendar:slotLabelInterval="00:aa:00"`,+ the calendar crashes."+- PR #8799: "Report invalid values via toast, without crashing and without affecting other valid+ calendar events. Make sure to write tests for this scenario."+- PR #11321: "It doesn't seem to work, at least on the Trilium Next theme." PR #8668: "This is not+ platform-agnostic since it will fail on Windows."+- PR #9687: "for big boards this can be awfully slow as it needs to download the blobs of all the+ notes. For reference, my Trilium board has 581 tasks in it." PR #9419: "For big databases, this+ can be quite a cost for the user with not that great of a benefit."+- PR #10856: "Heuristics can produce false positives, and I feel that the value vs risk is not high+ enough."++## 18. Agent-assisted is fine; bulk that does not integrate is not++Ask: does the diff delete anything? Does it reuse the codebase's helpers, components and+conventions, or sit beside them? Are there planning artifacts, playbooks or PR-description files+in the tree? Is the description longer than the diff?++- PR #8843: "The code does not integrate at all with the code base, which is evident from the fact+ that there are zero deletions and only additions. In reality, all feature changes require+ adjusting at least a few sources of code."+- PR #7441: "It is my expectation to be discussing with a human."+- PR #7139: "This file is an artifact of the LLM used to develop this functionality, so we should+ remove it."+- `CONTRIBUTING.md`: "Bulk or unverified submissions may be closed without detailed review."+- The other side: 13 PRs by one contributor carry `Agent-Signature:` trailers with house-style+ bodies (cause / fix / verification / remainder); 9 merged with a single APPROVED and no maintainer+ commits. #10924 (a Claude-made Turkish translation) merged once the author described the quality+ check. The bar is the body and the spec, not the tool.++## "Yes, but" — the shape an accepted request takes++When the idea is fine and the shape is not, the verdict is `REWORK` and this table says toward what.++| Request | Accepted shape | Ref |+|---|---|---|+| Note color / per-note property | A promoted attribute now; a menu entry "at some point" | #7290 |+| Behavior inherited by children | An inheritable label, not a setting | #6494 |+| A different key for an action | The existing keyboard-shortcut settings, not a new option | #5684 |+| Auto-apply on child creation | A backend script (`runOnChildNoteCreation`) | #9442 |+| Longer labels in a map | Support more characters; no option | #5656 |+| Stop nested include-notes | Remove the recursion; no toggle | #9682, #10340 |+| A new heavyweight editor (spreadsheet) | A note type, maintained library, no lock-in, sync version bumped, disclaimer | #1841 |+| Syntax highlighting for a language | Only where an off-the-shelf grammar exists | #7848 |+| Custom icons | Font-based icon packs only | #8219, #5145 |+| Fonts | Custom fonts synced across instances; never system fonts | #8590, #9443 |+| Trigger sync from a script | `fetch("api/sync/now", { method: "POST" })`, no new API | #10085 |+| External attachment storage | Local external store yes, remote no | #6553 |+| Share-page customization | CSS/JS first, templates as a last resort | #3429 |+| Draw.io | A third-party widget, never core | #10093 |+| Dependency for scripting (Day.js plugin) | Accepted by size and by use inside Trilium itself | `Day.js.md` |+| A behavior change users will notice | Opt-in, with the old default kept | `CONTRIBUTING.md`, #6918 |diff --git a/.claude/skills/reviewing-pull-requests/references/rejection-patterns.md b/.claude/skills/reviewing-pull-requests/references/rejection-patterns.mdnew file mode 100644index 0000000000..b308c1e0f2--- /dev/null+++ b/.claude/skills/reviewing-pull-requests/references/rejection-patterns.md@@ -0,0 +1,212 @@+# Why pull requests get closed here++Read from 151 closed-unmerged PRs (2024 → September 2026, 126 with a discussion). Each pattern:+how to spot it in a dossier or diff, and the maintainer's own words. Counts are PRs carrying the+pattern; one PR often carries several. Quotes are eliandoran's unless another login is given.++The headline numbers, because they set the priors:++- **The maintainer re-does it (29 + 4 duplicates).** The most common outcome is not "declined"+ but "superseded by my own smaller change at a different seam". The contributor's diagnosis is+ reused; the code is not, once it exceeds roughly a screen.+- **Size predicts the outcome.** 32 PRs exceeded 1000 lines; almost none landed except by being+ split (#9316 → six PRs, three merged) or rebuilt by a maintainer.+- **Specs and docs do not gate acceptance; fit does.** 40 closed PRs had specs, 17 touched the+ User Guide. What closed them was where the code belongs, app-wide consistency, the storage/sync+ model, and who gets to decide a design.+- **A correct, tested fix still closes** when it works around a library the maintainer would+ rather remove, fixes one surface of an app-wide behavior, or fixes a symptom whose cause the+ maintainer places elsewhere.++## 1. Superseded: the maintainer prefers a smaller change at a different seam (33)++Spot: a fix larger than the bug; a regex where a parser exists; a client-side computation the+server already does; a change to core behavior when the caller could adapt.++- #11406: "I would prefer a simpler approach that does not use regexes. I'll fix it in #11410."+- #10477: "thanks for your implementation, I've tried to simplify it a bit in #10481."+- #11553: "The 'proper' solution here is to not refresh the table at all when the change comes+ from the same editor."+- #11434: "The PR is conceptually good but I would prefer not to change the core behavior. Made a+ replacement PR here: #11668"+- #7757: "we prefer computation on the server (which already has rapid access to all notes)+ instead of the client."+- #11101 (287 lines, 7 rounds of self-review), #11247 (1065 lines), #7287 (37 files, 185+ comments, 11 months): all superseded by the maintainer's own implementation.++Review consequence: when the right fix is a third the size, the verdict is `REWORK` with the seam+named — the maintainer's habit is to write that smaller change himself, so pointing at it saves the+round trip.++## 2. Does not integrate: additions only, artifacts in the tree, bulk (17)++Spot: zero deletions; new modules beside existing ones that do the same job; planning documents,+playbooks, PR-description files or check scripts committed; a description longer than the diff;+English catalogue rewritten wholesale; i18n or conventions ignored.++- #8843: "The code does not integrate at all with the code base, which is evident from the fact+ that there are zero deletions and only additions. In reality, all feature changes require+ adjusting at least a few sources of code."+- #7139 (inline): "This file is an artifact of the LLM used to develop this functionality, so we+ should remove it." / "it describes a single pull request. These should most likely go in the PR+ description and not in the repo."+- #9716: "especially evident from the complete destruction of the English translations."+- #8878: "Why wouldn't you have a video recording of the app? I suppose the app was tested, yes?"+- #7441: "The initial work was severely lacking, without having any functional elements (e.g. a+ login screen, sync completely disregarded)."++Context: all 17 arrived in a ten-week window against four bounty issues; the project then refunded+the bounties. Agent-assisted PRs with house-style bodies and real specs merge routinely — the+pattern is bulk, not tooling.++## 3. A design decision made without the maintainers (9)++Spot: a first-time contributor's PR that establishes an architecture — a protocol, storage,+mobile, multi-user, a new note type, caching semantics — with no issue thread where a maintainer+agreed to the plan.++- #9244: "this does not meet our architectural criteria. Especially since you are a first time+ contributor to the Trilium code base and this was not discussed beforehand, this is a big design+ choice that we should ideally make on our side."+- #9708: "this kind of deep modification needs to be discussed beforehand as there are a lot of+ intricacies, for example the caching of values."+- #9707, #9712, #9714, #9715: "we'd like to implement this feature on our own since it needs to be+ done on an agreed-upon plan" / "Mobile is a topic we'd like to address on our side."+- #6918: "we need first to discuss why removing the title in a Markdown file is needed. We can+ reopen the PR if needed, until them let's continue the discussion over in the related issue."++Review consequence: `YOUR CALL`, with the design question stated in one sentence, never `MERGE`+on code quality alone.++## 4. Belongs in a script, widget or plugin (7)++Spot: a behavior that assumes one workflow; a UI addition useful to the author's setup; a+component "reusable" nowhere else; a render-widget-shaped feature.++- #10308: "better served as a custom widget instead of being part of the core."+- #11102: "better suited as a custom script instead."+- #9687: "I would suggest to try to extract this as a plugin if it's for personal use."+- #7704: "for a component to be useful, it has to be used in multiple places; which is currently+ not the case … If you maintain a custom fork, it's not a bad idea but we can't make decisions on+ the main repo based on that."+- #8474 / #5833 / #7270: "The work can be used as a plugin once we implement a proper plugin+ system."++## 5. One surface of an app-wide behavior, or the wrong layer (7)++Spot: a frequent action (open in split, ctrl+click, a progress badge) added to one view; a+client-only concern routed through the server; formatting logic inside a CKEditor plugin; a+customization mechanism unlike the launch bar's.++- #8677 (13 lines, correct): "We cannot introduce inconsistent behaviour when it comes to frequent+ user actions. I will take note of it and implement it globally at some point."+- #9687: "specific to the board collection … The value is not cached in anyway, which means that+ for big boards this can be awfully slow as it needs to download the blobs of all the notes. For+ reference, my Trilium board has 581 tasks in it."+- #9076: "Handling the actual formatting should not be the responsibility of the CKEditor plugin."+- #6764: "there's no need to have the server involved for a client-side-only affair (CKEditor).+ This seems like it could be a service inside the client."+- #7879: "Since it supports child notes, I think it would make more sense to implement it as a+ Collection instead of a new note type … creating a new note type also implies increasing the+ sync version."+- #8864: "it would align with the rest of the application" over "more user-friendly".++## 6. Data or storage model violated (3, each severe)++Spot: `localStorage`; writes that bypass becca; a model that does not sync; a feature that only+works online.++- #7056: "Trilium does not use the local storage feature at all. All data in Trilium is managed+ within the SQL database." / "we store it in an attachment inside the note. We must not break this+ functionality." / "There are many debug logs inside the PR, please get rid of them."+- #7441: "How are the users synchronized across multiple instances?" deajan: "multi user support+ still needs to work with sync".++## 7. Maintenance burden, workaround, not worth it (9)++Spot: a third mechanism beside two existing ones; a guard around a library bug; a refresh/retry+button; a runtime check for a pinned version; tooling nobody asked for; parallel implementations+left in place.++- #11548 (the fix worked): "this is already the third or the fourth workaround we needed to+ implement due to the underlying library. As such, I prefer to get rid of that library entirely."+- #9960: "The Mermaid diagram is supposed to re-render on change, so what case would there big to+ manually refresh? If the diagram fails to render, then we must fix that issue."+- #7828: "Why have three different mechanisms in place for content accessors?"+- #6839 (inline): "Do we really need this performance monitoring mechanism?" / "I would remove the+ old search mechanism to avoid having two big parallel implementations." / "Our server uses pinned+ versions so as long as the version is correct, there's no need for runtime check."+- #11386: "Our workflows are generally hand-maintained so we don't see much of a benefit in+ automating it."+- #6736 (21.6k lines of docs): "it adds more complexity and verbosity to the documentation than I+ believe is necessary. There are also subtle things that are hard to validate."++## 8. Not needed, already possible, use case unconvincing (11)++Spot: the PR's own description states a problem the app already solves; the feature removes+information (a default column) rather than reorganizing it; a URL that will stop meaning anything.++- #9634: "this is **already** supported … simply removing it is not a solution."+- #11211: "PUT /etapi/attachments/{id}/content with Content-Type: application/octet-stream already+ stores binary content."+- #7704: "Can't this be replicated with already existing functionality such as Saved Search?"+- #9119: "the only reason why the desktop exposes a port is ETAPI and the web clipper API."+- #9963: "we have already had an attempt at implementing full-text search using FTS5 and we+ haven't seen a significant improvement."++## 9. Bundled changes; split it (5)++Spot: several features in one PR; labels or options beyond what the feature needs; a "while I was+here" refactor next to a fix.++- #9316 (33 files): "could you please try to separate the features into multiple PRs? There are+ quite a few overlapping concerns … perhaps not all features can go into Trilium without further+ changes." → split into #9338–#9343; three merged.+- #7828: "in this PR there's also 5 different new labels that were introduced, with only 2 of+ them actually relating to the work at hand." Inline ×4: "This is part of #7828 and should not be+ present in this PR."+- #9960: "we might want to pick out only a few of them."++## 10. Behavior change users will notice; breaking; privacy (3)++Spot: a removed default, a changed URL format, data shown in a dialog users screenshot.++- #6918: "this is a change in behaviour that many people will be surprised to see."+- #7759: "it's best to avoid breaking changes. We have to balance the benefit of the change versus+ the impact." / "we are not going to change the sharing path twice."+- #10013: "Having the sync server show up is a privacy breach."++## 11. Wrong root cause (3)++Spot: the subject names a symptom the diff does not touch; a fix in event handling for a bug that+is really two competing elements; a value-level fix for a structural gap.++- #11176: "the PR title mentions infinite scrolling but nothing is done about that and the root+ cause appears incorrect."+- #11296: "the issue in #11244 lies somewhere else: it's not the event handling or focus stealing,+ it's the the fact that we have two titles."++## 12. Process: docs, translations, third parties (7)++Spot: generated help HTML edited by hand or Markdown edited without regenerating; non-English+catalogues touched; a hosting provider added to a list.++- #9719: "the HTML files also need to be regenerated (using `edit-docs` instead of manually+ modifying the Markdown file)."+- #7766: "I would prefer to keep the reference link notation since it renders better in the in-app+ help."+- #6539: translations go through Weblate.+- #10837: "Trilium works based on trust and we would need to build that trust first."++## 13. Stale after change requests (10)++What the maintainer asked for before a PR could proceed, and the contributor never delivered:+unit tests (#9203 "Please add unit tests. Make sure to cover the case indicated by the Copilot+comment"), the User Guide (#9203 "And most important, add documentation in the user guide."; #7704;+#9076), functional completeness (#7441 "as a user I can't use it to create users or to log in"),+evidence of testing (#9316 "Did you test it thoroughly? Which models were used to test Ollama?").++#6677 (external blobs, 50 files, four months) is the cautionary case: two CHANGES_REQUESTED rounds+("There are two bugs: The first is a critical one (data loss)"), then the author: "the long gaps+between review cycles have made it hard to keep the branch up to date". A large PR that needs+rounds of review is at risk from its size alone.diff --git a/.claude/skills/reviewing-pull-requests/review.mjs b/.claude/skills/reviewing-pull-requests/review.mjsnew file mode 100644index 0000000000..9abda0dac4--- /dev/null+++ b/.claude/skills/reviewing-pull-requests/review.mjs@@ -0,0 +1,695 @@+#!/usr/bin/env node+/**+ * Review workbench for Trilium pull requests: the facts a merge decision needs, fetched and+ * computed once, so a review never argues from a PR's title or description.+ *+ * node .claude/skills/reviewing-pull-requests/review.mjs <command> [args]+ *+ * list [--all] [--json] [--sort=age|size] every open PR: kind, size by file kind, linked+ * issues, flags, rivals (bots and maintainer drafts+ * skipped unless --all)+ * dossier <N> [--diff] one PR in full: description, linked issues with their discussion,+ * commits, files by kind, human review threads (bots folded), rivals+ * verify <N> [--no-typecheck] [--no-standalone] [--no-siblings]+ * fetch the PR into .claude/worktrees/pr-N, install, typecheck, run+ * its specs green on the branch and red with the production files+ * reverted to the merge-base, run the touched modules' own specs,+ * list dependency and docs impact+ * issue <N> an issue with its human comments: the problem statement itself+ * dupes open PRs that compete for the same issue or the same subject+ * clean [N] remove the verify worktree(s) and their refs+ *+ * `dossier` and `verify` also save their report under .claude/reviews/pr-N/ (gitignored) so a+ * triage can come back to it. Nothing here writes to GitHub: a review is reading, and the+ * maintainer speaks to contributors in person.+ */+import { execFileSync, spawnSync } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import { fileURLToPath } from "node:url";++const SKILL_DIR = path.dirname(fileURLToPath(import.meta.url));+const ROOT = path.resolve(SKILL_DIR, "../../..");+const WORKTREES = path.join(ROOT, ".claude/worktrees");+const REVIEWS = path.join(ROOT, ".claude/reviews");+const DOCS_MJS = path.join(ROOT, ".claude/skills/writing-documentation/docs.mjs");+let repoSlug;++const BOT_LOGIN = /\[bot\]$|^(greptile|codecov|renovate|dependabot|weblate|coderabbit|copilot|github-actions)/i;+const MAINTAINER_ASSOC = new Set(["OWNER", "MEMBER"]);+const PR_FIELDS = [+ "number", "title", "body", "url", "author", "isDraft", "createdAt", "updatedAt", "baseRefName",+ "headRefName", "headRepositoryOwner", "isCrossRepository", "additions", "deletions",+ "changedFiles", "labels", "reviewDecision", "closingIssuesReferences", "files", "commits",+ "reviews", "comments", "statusCheckRollup", "maintainerCanModify"+];+/** Words too common in this repo's PR titles to say two of them are about the same thing. */+const TITLE_NOISE = new Set([+ "note", "notes", "trilium", "with", "from", "that", "this", "into", "when", "then", "than",+ "after", "before", "only", "also", "over", "instead", "should", "adds", "added", "make",+ "makes", "support", "feature", "option", "allow", "allows", "using", "users", "user", "their"+]);++/** Where a spec file's runner lives, and the extra CLI it needs. */+const RUNNERS = {+ "packages/trilium-core": ["apps/server", "apps/standalone"],+ "apps/server": ["apps/server"],+ "apps/client": ["apps/client"],+ "apps/standalone": ["apps/standalone"],+ "apps/desktop": ["apps/desktop"],+ "packages/commons": ["packages/commons"],+ "packages/ckeditor5": ["packages/ckeditor5"]+};+const RUNNER_ARGS = { "apps/desktop": ["--config", "vitest.config.mts"] };++const args = process.argv.slice(2);+const command = args.shift();+const flags = parseFlags(args);++const COMMANDS = { list, dossier, verify, issue, dupes, clean, help };+if (!command || !(command in COMMANDS)) {+ help();+ process.exit(command ? 1 : 0);+}+await COMMANDS[command]();++// ---------------------------------------------------------------------------------------------+// list++async function list() {+ const prs = openPrs();+ const rows = prs.map((pr) => describePr(pr, prs));+ const shown = flags.all ? rows : rows.filter((r) => !r.bot && !(r.isDraft && r.maintainer));+ if (flags.sort === "age") shown.sort((a, b) => b.ageDays - a.ageDays);+ else if (flags.sort === "size") shown.sort((a, b) => b.mix.prod.lines - a.mix.prod.lines);+ if (flags.json) {+ console.log(JSON.stringify(shown, null, 2));+ return;+ }+ const hidden = rows.length - shown.length;+ console.log(`${shown.length} open PR(s)${hidden ? ` (${hidden} bot/maintainer-draft hidden; --all shows them)` : ""}\n`);+ for (const r of shown) console.log(listRow(r));+ const byKind = countBy(shown, (r) => r.kind);+ const rivals = shown.filter((r) => r.rivals.length);+ console.log(`\nby kind: ${Object.entries(byKind).map(([k, n]) => `${k} ${n}`).join(" · ")}`);+ console.log(`without a spec change: ${shown.filter((r) => r.mix.spec.files === 0 && r.kind !== "docs").length}`+ + ` · without docs among feat: ${shown.filter((r) => r.kind === "feat" && r.mix.docs.files === 0).length}`+ + ` · first-time contributors: ${shown.filter((r) => r.association === "FIRST_TIME_CONTRIBUTOR").length}`+ + ` · with rivals: ${rivals.length} (see \`dupes\`)`);+ console.log(`\nA row is a fact sheet, not a verdict: \`dossier <N>\` then \`verify <N>\` before judging one.`);+}++function listRow(r) {+ const who = `${r.author}${r.maintainer ? "·maint" : r.association === "FIRST_TIME_CONTRIBUTOR" ? "·first" : r.association === "COLLABORATOR" ? "·collab" : ""}`;+ const size = (m) => (m.files ? `+${m.add}/-${m.del} (${m.files}f)` : "—");+ const issues = r.issues.closing.length ? `closes #${r.issues.closing.join(",#")}` : r.issues.mentioned.length ? `mentions #${r.issues.mentioned.slice(0, 3).join(",#")}` : "no issue";+ const extra = [+ r.flags.length ? `flags: ${r.flags.join(",")}` : "",+ r.rivals.length ? `rivals: #${r.rivals.join(",#")}` : "",+ r.isDraft ? "DRAFT" : ""+ ].filter(Boolean).join(" ");+ return `#${String(r.number).padEnd(6)} ${r.kind.padEnd(8)} ${`${r.ageDays}d`.padEnd(5)} ${who.padEnd(24)} `+ + `prod ${size(r.mix.prod).padEnd(18)} spec ${size(r.mix.spec).padEnd(16)} docs ${size(r.mix.docs).padEnd(14)} `+ + `${issues.padEnd(22)} ${extra}\n ${r.title}`;+}++// ---------------------------------------------------------------------------------------------+// dossier++async function dossier() {+ const number = requireNumber();+ const pr = ghJson(["pr", "view", String(number), "--json", PR_FIELDS.join(",")]);+ const rest = ghJson(["api", `repos/${repo()}/pulls/${number}`]);+ const prs = openPrs();+ const d = describePr({ ...pr, authorAssociation: rest.author_association }, prs);+ const threads = reviewThreads(number);+ const out = [];+ const p = (s = "") => out.push(s);++ p(`# PR #${d.number} — ${d.title}`);+ p(pr.url);+ const head = pr.isCrossRepository ? `${pr.headRepositoryOwner?.login}:${pr.headRefName} (fork${pr.maintainerCanModify ? ", maintainers can push" : ", maintainers cannot push"})` : pr.headRefName;+ p(`author ${d.author} (${d.association}) · opened ${d.ageDays}d ago · last update ${d.staleDays}d ago · ${pr.baseRefName} ← ${head}`);+ p(`labels: ${d.labels.join(", ") || "—"} · draft: ${pr.isDraft ? "yes" : "no"} · review decision: ${pr.reviewDecision || "—"}`+ + ` · mergeable: ${rest.mergeable_state ?? "?"} · checks: ${checkSummary(pr.statusCheckRollup)} (informational only)`);+ p(`kind: ${d.kind} · conventional subject: ${d.conventional ? "yes" : "NO"} · \`(closes #N)\` in subject: ${d.closesInSubject ? "yes" : "no"}`);+ p();+ p(`## Size`);+ p(`+${pr.additions}/-${pr.deletions} in ${pr.changedFiles} files: ${mixLine(d.mix)}${d.files.length < pr.changedFiles ? ` (GitHub lists only ${d.files.length} of ${pr.changedFiles} files; the file table and flags below are incomplete — \`git diff --stat\` in the verify worktree has them all)` : ""}`);+ p(`areas: ${d.areas.join(", ") || "—"}`);+ p(`flags: ${d.flags.length ? d.flags.join(", ") : "(none)"}`);+ if (d.rivals.length) p(`rivals: ${d.rivals.map((n) => `#${n}`).join(", ")} (see below)`);+ p();+ p(`## Files`);+ for (const f of d.files) p(` ${f.kind.padEnd(14)} ${f.path} +${f.additions}/-${f.deletions} ${f.changeType?.[0] ?? ""}`);+ p();+ p(`## Commits (${pr.commits.length})`);+ for (const c of pr.commits) {+ p(` ${c.oid.slice(0, 8)} ${c.messageHeadline} [${c.authors.map((a) => a.login || a.name).join(", ")}]`);+ if (c.messageBody?.trim()) p(indent(c.messageBody.trim(), 4));+ }+ p();+ p(`## Description (verbatim, by the author)`);+ p(pr.body?.trim() ? clip(pr.body.trim(), 8000) : "(empty)");+ p();+ p(`## Linked issues`);+ if (!d.issues.closing.length && !d.issues.mentioned.length) p("(none — the PR itself is the only statement of the problem; check whether one exists: `gh issue list --search \"<keywords>\"`)");+ for (const n of d.issues.closing) p(issueText(n, "closes"));+ for (const n of d.issues.mentioned.slice(0, 5)) p(issueText(n, "mentions", true));+ p();+ p(`## Discussion (humans; bots folded)`);+ const bots = {};+ for (const c of pr.comments) {+ if (isBot(c.author?.login)) { bots[c.author.login] = (bots[c.author.login] ?? 0) + 1; continue; }+ p(`- comment by ${c.author?.login} (${c.authorAssociation}) ${c.createdAt?.slice(0, 10)}:`);+ p(indent(clip(c.body.trim(), 2500), 4));+ }+ for (const r of pr.reviews) {+ if (isBot(r.author?.login)) { bots[r.author.login] = (bots[r.author.login] ?? 0) + 1; continue; }+ p(`- review by ${r.author?.login} (${r.authorAssociation}) ${r.submittedAt?.slice(0, 10)}: ${r.state}${r.body?.trim() ? "" : " (no summary)"}`);+ if (r.body?.trim()) p(indent(clip(r.body.trim(), 2500), 4));+ }+ for (const t of threads) {+ const first = t.comments[0];+ if (!first || isBot(first.author)) { if (first) bots[first.author] = (bots[first.author] ?? 0) + 1; continue; }+ p(`- thread ${t.path}:${t.line ?? "?"} [${t.isResolved ? "resolved" : "OPEN"}${t.isOutdated ? ", outdated" : ""}] ${first.author} (${first.authorAssociation}), ${t.comments.length - 1} repl${t.comments.length === 2 ? "y" : "ies"}:`);+ p(indent(clip(first.body.trim(), 1500), 4));+ for (const c of t.comments.slice(1, 4)) p(indent(`↳ ${c.author}: ${clip(c.body.trim(), 600)}`, 4));+ }+ const botLine = Object.entries(bots).map(([k, n]) => `${k} ×${n}`).join(", ");+ if (botLine) p(`bots: ${botLine} — not reviewers; their findings are unverified suggestions, not maintainer asks`);+ if (!pr.comments.some((c) => !isBot(c.author?.login)) && !pr.reviews.some((r) => !isBot(r.author?.login)) && !threads.some((t) => t.comments[0] && !isBot(t.comments[0].author))) p("(no human has commented yet)");+ if (d.rivals.length) {+ p();+ p(`## Competing PRs`);+ for (const n of d.rivals) {+ const other = prs.find((x) => x.number === n);+ if (other) p(`- #${n} ${other.title} — ${other.author?.login}, ${daysSince(other.createdAt)}d, +${other.additions}/-${other.deletions}, closes ${other.closingIssuesReferences.map((i) => `#${i.number}`).join(",") || "—"}`);+ }+ p(`One issue, several PRs: judge them side by side and pick one; the others are declined or superseded, not "also fine".`);+ }+ p();+ p(`## Diff`);+ if (flags.diff) p(gh(["pr", "diff", String(number)]));+ else p(`Not inlined. \`gh pr diff ${number}\` prints it; after \`verify ${number}\` the branch is checked out in .claude/worktrees/pr-${number}, where the changed code can be read in the context of what surrounds it.`);++ const text = out.join("\n");+ console.log(text);+ save(number, "dossier.md", text);+}++function issueText(n, relation, brief = false) {+ let iss;+ try {+ iss = ghJson(["issue", "view", String(n), "--json", "number,title,state,stateReason,labels,author,body,comments,createdAt,url"]);+ } catch {+ return `### #${n} (${relation}) — not an issue in this repo, or not readable`;+ }+ const head = `### #${n} ${iss.title} (${relation} · ${iss.state}${iss.stateReason ? "/" + iss.stateReason : ""} · ${iss.labels.map((l) => l.name).join(", ") || "no labels"} · by ${iss.author?.login} ${iss.createdAt?.slice(0, 10)})`;+ if (brief) return head;+ const lines = [head, iss.body?.trim() ? clip(iss.body.trim(), 5000) : "(no body)"];+ const humans = iss.comments.filter((c) => !isBot(c.author?.login));+ if (humans.length) {+ lines.push(`comments (${humans.length}):`);+ for (const c of humans) {+ const tag = MAINTAINER_ASSOC.has(c.authorAssociation) ? "MAINTAINER" : c.authorAssociation;+ lines.push(`- **${c.author?.login}** (${tag}) ${c.createdAt?.slice(0, 10)}:`);+ lines.push(indent(clip(c.body.trim(), 2000), 4));+ }+ }+ return lines.join("\n");+}++// ---------------------------------------------------------------------------------------------+// issue++async function issue() {+ console.log(issueText(requireNumber(), "issue"));+}++// ---------------------------------------------------------------------------------------------+// dupes++async function dupes() {+ const prs = openPrs().filter((pr) => !isBot(pr.author?.login));+ const rows = prs.map((pr) => describePr(pr, prs));+ const groups = [];+ const seen = new Set();+ for (const r of rows) {+ if (seen.has(r.number) || !r.rivals.length) continue;+ const group = [r.number];+ const queue = [...r.rivals];+ while (queue.length) {+ const n = queue.shift();+ if (group.includes(n)) continue;+ group.push(n);+ const other = rows.find((x) => x.number === n);+ if (other) queue.push(...other.rivals);+ }+ for (const n of group) seen.add(n);+ groups.push(group.sort((a, b) => a - b));+ }+ if (!groups.length) { console.log("no open PRs compete for the same issue or subject"); return; }+ console.log(`${groups.length} group(s) of competing PRs:\n`);+ for (const g of groups) {+ const members = g.map((n) => rows.find((x) => x.number === n)).filter(Boolean);+ const shared = members.map((m) => m.issues.closing).reduce((a, b) => a.filter((x) => b.includes(x)));+ console.log(shared.length ? `same issue #${shared.join(", #")}:` : "similar subject:");+ for (const m of members) {+ console.log(` #${m.number} ${m.title}`);+ console.log(` ${m.author} (${m.association}) · ${m.ageDays}d · prod +${m.mix.prod.add}/-${m.mix.prod.del} (${m.mix.prod.files}f) · spec ${m.mix.spec.files ? `+${m.mix.spec.add}/-${m.mix.spec.del}` : "—"} · docs ${m.mix.docs.files ? "yes" : "—"}${m.flags.length ? ` · ${m.flags.join(",")}` : ""}`);+ }+ console.log();+ }+ console.log("Review the members of a group together: the smaller change that fixes the cause usually wins, and the earlier PR earns no precedence by age alone.");+}++// ---------------------------------------------------------------------------------------------+// verify++async function verify() {+ const number = requireNumber();+ const pr = ghJson(["pr", "view", String(number), "--json", "number,title,headRefOid,baseRefName,files"]);+ const ref = `refs/pr/${number}`;+ const dir = path.join(WORKTREES, `pr-${number}`);+ const report = [];+ const p = (s = "") => report.push(s);+ const t0 = Date.now();++ step(`fetch #${number} and ${pr.baseRefName}`);+ git(["fetch", "-q", "origin", `+refs/pull/${number}/head:${ref}`, `+refs/heads/${pr.baseRefName}:refs/remotes/origin/${pr.baseRefName}`]);+ if (fs.existsSync(dir)) git(["worktree", "remove", "--force", dir]);+ fs.mkdirSync(WORKTREES, { recursive: true });+ git(["worktree", "add", "--detach", "-q", dir, ref]);+ const wt = (argv, opts = {}) => execFileSync("git", argv, { cwd: dir, encoding: "utf-8", maxBuffer: 64 * 1024 * 1024, ...opts });+ const head = wt(["rev-parse", "HEAD"]).trim();+ const baseTip = git(["rev-parse", `origin/${pr.baseRefName}`]).trim();+ const mergeBase = wt(["merge-base", "HEAD", baseTip]).trim();+ const ahead = wt(["rev-list", "--count", `${mergeBase}..HEAD`]).trim();+ const behind = wt(["rev-list", "--count", `${mergeBase}..${baseTip}`]).trim();+ const changed = wt(["diff", "--name-status", "-M", mergeBase, "HEAD"]).trim().split("\n").filter(Boolean).map((line) => {+ const [status, a, b] = line.split("\t");+ return { status: status[0], path: b ?? a, oldPath: b ? a : undefined };+ });+ const specs = changed.filter((f) => f.status !== "D" && classify(f.path) === "spec" && !f.path.startsWith("packages/trilium-e2e/"));+ const prod = changed.filter((f) => classify(f.path) !== "spec" && /^(apps|packages)\//.test(f.path));+ const e2e = changed.filter((f) => f.path.startsWith("packages/trilium-e2e/"));++ p(`# verify #${number} — ${pr.title}`);+ p(`worktree ${path.relative(ROOT, dir)} @ ${head.slice(0, 10)} · ${pr.baseRefName} @ ${baseTip.slice(0, 10)} · merge-base ${mergeBase.slice(0, 10)} · ${ahead} commit(s) ahead, ${behind} behind`);+ p(`changed: ${changed.length} file(s) — ${specs.length} spec, ${prod.length} production/other under apps|packages, ${e2e.length} e2e`);+ p();++ step("pnpm install");+ const lockChanged = changed.some((f) => /pnpm-lock\.yaml$/.test(f.path));+ let install = run("pnpm", ["install", "--frozen-lockfile", "--prefer-offline"], dir);+ if (install.status !== 0) install = run("pnpm", ["install", "--frozen-lockfile", "--offline"], dir);+ p(`## Toolchain`);+ p(`install: ${install.status === 0 ? "ok" : "FAILED"} in ${install.seconds}s${lockChanged ? " (the PR changes pnpm-lock.yaml)" : ""}`);+ if (install.status !== 0) p(indent(tail(install.output, 15), 4));++ if (!flags["no-typecheck"]) {+ step("pnpm typecheck");+ const tc = run("pnpm", ["typecheck"], dir);+ p(`typecheck: ${tc.status === 0 ? "ok" : "FAILED"} in ${tc.seconds}s`);+ if (tc.status !== 0) p(indent(tail(tc.output, 30), 4));+ } else p("typecheck: skipped (--no-typecheck)");+ p();++ // Test names the PR adds: the ones that must fail without the production change.+ const newTests = new Map();+ for (const s of specs) {+ const diff = s.status === "A" ? fs.readFileSync(path.join(dir, s.path), "utf-8").split("\n").map((l) => "+" + l).join("\n") : wt(["diff", mergeBase, "HEAD", "--", s.path]);+ const names = new Set();+ for (const m of diff.matchAll(/^\+\s*(?:it|test)(?:\.(?:each|only|concurrent))?\(\s*["'`](.+?)["'`]/gm)) names.add(m[1]);+ newTests.set(s.path, names);+ }++ p(`## Specs in the PR`);+ if (!specs.length) p(`NONE — the PR changes no spec file${e2e.length ? ` (it does change ${e2e.length} e2e file(s), not run here)` : ""}. A fix without a failing-then-passing spec is unverified by its author too.`);+ const plans = plan(specs.map((s) => s.path));+ const green = new Map();+ for (const [runner, files] of plans) {+ step(`green: ${runner} ← ${files.length} spec(s)`);+ green.set(runner, vitest(dir, runner, files, `green-${runner.replace("/", "-")}`));+ }++ let red = new Map();+ if (specs.length && prod.length) {+ step("red: revert production files to the merge-base");+ for (const f of prod) {+ if (f.status === "A") fs.rmSync(path.join(dir, f.path), { force: true });+ else if (f.status === "R") { fs.rmSync(path.join(dir, f.path), { force: true }); wt(["checkout", mergeBase, "--", f.oldPath]); }+ else wt(["checkout", mergeBase, "--", f.path]);+ }+ for (const [runner, files] of plans) {+ step(`red: ${runner} ← ${files.length} spec(s)`);+ red.set(runner, vitest(dir, runner, files, `red-${runner.replace("/", "-")}`));+ }+ step("restore the branch");+ for (const f of prod) {+ if (f.status === "D") fs.rmSync(path.join(dir, f.path), { force: true });+ else if (f.status === "R") { fs.rmSync(path.join(dir, f.oldPath), { force: true }); wt(["checkout", "HEAD", "--", f.path]); }+ else wt(["checkout", "HEAD", "--", f.path]);+ }+ } else if (specs.length) p("red run skipped: the PR changes no production file under apps|packages, so the specs have nothing to prove.");++ for (const [runner, files] of plans) {+ const g = green.get(runner);+ const r = red.get(runner);+ for (const file of files) {+ const gf = g.files.get(file);+ const rf = r?.files.get(file);+ p(`${file} [${runner}]`);+ if (!gf) { p(` green: NOT RUN — vitest did not pick the file up (wrong runner, or an include glob excludes it)`); continue; }+ p(` green: ${gf.passed} passed, ${gf.failed} failed${gf.error ? ` — file error: ${clip(gf.error, 300)}` : ""} (${g.seconds}s)`);+ if (!rf) { if (r) p(` red: NOT RUN`); continue; }+ p(` red (production reverted): ${rf.passed} passed, ${rf.failed} failed${rf.error ? ` — file error: ${clip(rf.error, 300)}` : ""} (${r.seconds}s)`);+ const added = newTests.get(file) ?? new Set();+ const proves = [], vacuous = [], broken = [], unchanged = [];+ for (const [name, gs] of gf.tests) {+ const rs = rf.tests.get(name) ?? (rf.error ? "failed" : "missing");+ const isNew = [...added].some((n) => name.endsWith(n));+ if (gs === "passed" && rs === "failed") proves.push(name);+ else if (gs === "passed" && rs === "passed") (isNew ? vacuous : unchanged).push(name);+ else if (gs !== "passed") broken.push(name);+ }+ if (rf.error && !rf.tests.size) p(` red: the whole file failed to load without the production change (a new module) — proves existence, not behavior`);+ p(` proves the change (fails without it, passes with it): ${proves.length}`);+ for (const n of proves) p(` ✓ ${n}${[...added].some((a) => n.endsWith(a)) ? "" : " (pre-existing test)"}`);+ if (vacuous.length) {+ p(` NEW tests that also pass WITHOUT the change (they cover existing behavior, not this fix): ${vacuous.length}`);+ for (const n of vacuous) p(` ○ ${n}`);+ }+ if (broken.length) {+ p(` failing on the PR branch: ${broken.length}`);+ for (const n of broken) p(` ✗ ${n}`);+ }+ if (unchanged.length) p(` pre-existing tests unaffected by the change: ${unchanged.length}`);+ if (!proves.length && !rf.error && !broken.length) p(` VERDICT: the spec does not test this change — nothing in it fails with the production code reverted`);+ }+ }+ p();++ if (!flags["no-siblings"]) {+ const siblings = [];+ for (const f of prod) {+ if (f.status === "D") continue;+ const base = f.path.replace(/\.(ts|tsx|mts)$/, "");+ if (base === f.path) continue;+ for (const cand of [`${base}.spec.ts`, `${base}.spec.tsx`, `${base}.test.ts`, `${base}.test.tsx`]) {+ if (fs.existsSync(path.join(dir, cand)) && !specs.some((s) => s.path === cand) && !siblings.includes(cand)) siblings.push(cand);+ }+ }+ p(`## Specs of touched modules not in the PR (regression, green only)`);+ if (!siblings.length) p("(none: no touched module has a sibling spec the PR left alone)");+ for (const [runner, files] of plan(siblings)) {+ step(`siblings: ${runner} ← ${files.length} spec(s)`);+ const res = vitest(dir, runner, files, `siblings-${runner.replace("/", "-")}`);+ for (const file of files) {+ const rf = res.files.get(file);+ p(`${file} [${runner}] ${rf ? `${rf.passed} passed, ${rf.failed} failed${rf.error ? ` — ${clip(rf.error, 200)}` : ""}` : "NOT RUN"}`);+ if (rf) for (const [name, s] of rf.tests) if (s !== "passed" && s !== "skipped" && s !== "todo") p(` ✗ ${name}`);+ }+ }+ p();+ }++ p(`## Dependencies`);+ const depLines = wt(["diff", mergeBase, "HEAD", "--", "package.json", "apps/*/package.json", "packages/*/package.json", "pnpm-workspace.yaml"])+ .split("\n").filter((l) => /^[-+]\s*"[^"]+":\s*"/.test(l) && !/^[-+]\s*"(name|version|description|main|types|type|license|private|scripts?)"/.test(l));+ p(depLines.length ? indent(depLines.join("\n"), 2) : "(no package.json dependency lines changed)");+ p();++ p(`## Docs impact (writing-documentation skill, \`docs.mjs impact\`)`);+ const impact = spawnSync("node", [DOCS_MJS, "impact", "--diff", `${mergeBase}..${ref}`], { cwd: ROOT, encoding: "utf-8" });+ const impactText = (impact.stdout + impact.stderr).trim();+ p(indent(/no changed UI strings or help pages/.test(impactText) ? "no UI string or help-page reference changes in the diff; if the change is user-facing anyway, run `docs.mjs impact \"<feature name>\"`" : impactText || "(no output)", 2));+ const docsFiles = changed.filter((f) => classify(f.path) === "docs").length;+ const genFiles = changed.filter((f) => classify(f.path) === "docs-generated").length;+ p(`User Guide files in the PR: ${docsFiles} · generated help files: ${genFiles}${docsFiles && !genFiles ? " (docs edited but not synced: run `docs.mjs sync` before merging)" : ""}${!docsFiles && genFiles ? " (generated help edited by hand — the Markdown is the source)" : ""}`);+ p();++ const status = wt(["status", "--porcelain"]).trim();+ p(`## Worktree`);+ p(status ? `left DIRTY (restore failed?):\n${indent(status, 2)}` : `clean; read the code in ${path.relative(ROOT, dir)}. \`clean ${number}\` removes it.`);+ p(`total ${((Date.now() - t0) / 1000).toFixed(0)}s`);++ const text = report.join("\n");+ console.log("\n" + text);+ save(number, "verify.md", text);+}++/** Groups spec paths by the package whose Vitest config runs them. */+function plan(paths) {+ const out = new Map();+ for (const file of paths) {+ const key = Object.keys(RUNNERS).find((k) => file.startsWith(k + "/"));+ let runners = key ? RUNNERS[key] : [];+ if (!key) {+ const pkg = file.split("/").slice(0, 2).join("/");+ if (["vite.config.mts", "vite.config.ts", "vitest.config.mts", "vitest.config.ts"].some((c) => fs.existsSync(path.join(ROOT, pkg, c)))) runners = [pkg];+ else { console.error(` ! no runner known for ${file}; skipped`); continue; }+ }+ if (flags["no-standalone"]) runners = runners.filter((r) => r !== "apps/standalone" || key === "apps/standalone");+ for (const r of runners) out.set(r, [...(out.get(r) ?? []), file]);+ }+ return out;+}++/** Runs vitest once in a package and returns per-file, per-test results. */+function vitest(dir, runner, files, label) {+ const outFile = path.join(REVIEWS, "tmp", `${label}-${Date.now()}.json`);+ fs.mkdirSync(path.dirname(outFile), { recursive: true });+ // Vitest matches a filter against the path relative to the package, so `../../packages/...` for core.+ const relative = files.map((f) => path.relative(path.join(dir, runner), path.join(dir, f)));+ const res = run("pnpm", ["exec", "vitest", "run", ...(RUNNER_ARGS[runner] ?? []), "--reporter=json", `--outputFile=${outFile}`, ...relative], path.join(dir, runner));+ const result = { seconds: res.seconds, files: new Map(), raw: res.output };+ let json;+ try { json = JSON.parse(fs.readFileSync(outFile, "utf-8")); } catch { console.error(` ! vitest produced no JSON in ${runner}: ${tail(res.output, 8)}`); return result; }+ fs.rmSync(outFile, { force: true });+ for (const tr of json.testResults ?? []) {+ const rel = path.relative(dir, tr.name).replace(/\\/g, "/");+ const file = files.find((f) => rel === f) ?? rel;+ const entry = { passed: 0, failed: 0, tests: new Map(), error: tr.status === "failed" && !tr.assertionResults?.length ? (tr.message || "").split("\n")[0] : "" };+ for (const a of tr.assertionResults ?? []) {+ entry.tests.set(a.fullName, a.status);+ if (a.status === "passed") entry.passed++;+ else if (a.status === "failed") entry.failed++;+ }+ if (entry.error) entry.failed = Math.max(entry.failed, 1);+ result.files.set(file, entry);+ }+ return result;+}++// ---------------------------------------------------------------------------------------------+// clean++async function clean() {+ const which = flags._[0] ? [`pr-${flags._[0]}`] : fs.existsSync(WORKTREES) ? fs.readdirSync(WORKTREES).filter((d) => /^pr-\d+$/.test(d)) : [];+ for (const name of which) {+ const dir = path.join(WORKTREES, name);+ if (fs.existsSync(dir)) { git(["worktree", "remove", "--force", dir]); console.log(`removed ${path.relative(ROOT, dir)}`); }+ try { git(["update-ref", "-d", `refs/pr/${name.slice(3)}`]); } catch { /* no ref */ }+ }+ git(["worktree", "prune"]);+ if (!which.length) console.log("no verify worktrees");+}++// ---------------------------------------------------------------------------------------------+// facts++function openPrs() {+ const prs = ghJson(["pr", "list", "--state", "open", "--limit", "300", "--json", PR_FIELDS.filter((f) => !["body", "commits", "reviews", "comments", "statusCheckRollup"].includes(f)).join(",")]);+ const assoc = new Map();+ for (const r of ghJson(["api", `repos/${repo()}/pulls?state=open&per_page=100`, "--paginate"])) assoc.set(r.number, r.author_association);+ for (const pr of prs) pr.authorAssociation = assoc.get(pr.number) ?? "?";+ return prs;+}++function describePr(pr, allOpen) {+ const files = (pr.files ?? []).map((f) => ({ ...f, kind: classify(f.path), area: area(f.path) }));+ const mix = {};+ for (const kind of ["prod", "spec", "docs", "docs-generated", "i18n-en", "i18n-locale", "deps", "ci", "other"]) {+ const of = files.filter((f) => f.kind === kind);+ mix[kind] = { files: of.length, add: sum(of, "additions"), del: sum(of, "deletions"), lines: sum(of, "additions") + sum(of, "deletions") };+ }+ const m = /^(fix|feat|refactor|chore|docs|test|perf|build|ci|style|spike)(\(([^)]+)\))?!?:\s/i.exec(pr.title);+ const kind = m ? m[1].toLowerCase() : /^spike\b/i.test(pr.title) ? "spike" : "other";+ // GitHub links an issue from the body, not from a `(closes #N)` subject; the subject counts here.+ const closing = [...new Set([...(pr.closingIssuesReferences ?? []).map((i) => i.number), ...[...pr.title.matchAll(/\((?:closes|fixes|resolves) #(\d+)\)/gi)].map((x) => Number(x[1]))])];+ const mentioned = [...new Set([...(pr.body ?? "").matchAll(/(?:^|[^\w/])#(\d{3,6})\b/g), ...pr.title.matchAll(/#(\d{3,6})\b/g)].map((x) => Number(x[1])))].filter((n) => !closing.includes(n));+ const areas = [...new Set(files.map((f) => f.area).filter(Boolean))];+ const fl = [];+ if (mix.deps.files) fl.push("deps");+ if (files.some((f) => /packages\/trilium-core\/src\/(migrations\/|assets\/schema\.sql)/.test(f.path))) fl.push("migration");+ if (files.some((f) => /options_interface\.ts|options_init\.ts|routes\/api\/options\.ts/.test(f.path))) fl.push("options");+ if (files.some((f) => /apps\/server\/src\/etapi\//.test(f.path))) fl.push("etapi");+ if (files.some((f) => /services\/(sync|entity_changes)|sync_/.test(f.path))) fl.push("sync");+ if (mix["i18n-locale"].files) fl.push("locales(weblate-owned)");+ if (mix["docs-generated"].files && !mix.docs.files) fl.push("generated-docs-only");+ if (mix.docs.files && !mix["docs-generated"].files) fl.push("docs-unsynced");+ if (files.some((f) => f.changeType === "ADDED" && f.kind === "prod")) fl.push(`new-files:${files.filter((f) => f.changeType === "ADDED" && f.kind === "prod").length}`);+ if (areas.length > 2) fl.push(`areas:${areas.length}`);+ if (kind === "fix" && mix.prod.add > 150) fl.push("big-for-a-fix");+ if (kind !== "fix" && files.some((f) => /^apps\/client\/src\/.*\.(tsx|ts)$/.test(f.path) && /widgets|menus|dialogs|components/.test(f.path)) && !mix.docs.files) fl.push("ui-without-docs");+ if (files.some((f) => f.path.startsWith("packages/ckeditor5/"))) fl.push("ckeditor5");+ if (files.some((f) => /^apps\/(desktop|mobile)\//.test(f.path))) fl.push("platform-specific");+ const rivals = allOpen.filter((o) => o.number !== pr.number && !isBot(o.author?.login)).filter((o) => {+ const oc = (o.closingIssuesReferences ?? []).map((i) => i.number);+ if (oc.some((n) => closing.includes(n))) return true;+ const a = titleTokens(pr.title), b = titleTokens(o.title);+ const shared = [...a].filter((x) => b.has(x)).length;+ const union = new Set([...a, ...b]).size;+ return shared >= 3 || (shared >= 2 && union && shared / union >= 0.4);+ }).map((o) => o.number);+ if (files.length < (pr.changedFiles ?? 0)) fl.push(`files-capped:${files.length}/${pr.changedFiles}`);+ return {+ number: pr.number, title: pr.title, url: pr.url, author: pr.author?.login, bot: isBot(pr.author?.login),+ association: pr.authorAssociation, maintainer: MAINTAINER_ASSOC.has(pr.authorAssociation), isDraft: pr.isDraft,+ ageDays: daysSince(pr.createdAt), staleDays: daysSince(pr.updatedAt), labels: (pr.labels ?? []).map((l) => l.name),+ kind, conventional: Boolean(m), closesInSubject: /\((closes|fixes|resolves) #\d+\)/i.test(pr.title),+ files, mix, areas, issues: { closing, mentioned }, flags: fl, rivals+ };+}++function classify(p) {+ if (/^packages\/trilium-e2e\//.test(p) || /\.(spec|test)\.[cm]?[jt]sx?$/.test(p) || /^apps\/server\/spec\//.test(p) || /\/spec\/|\/test\/|__tests__\//.test(p)) return "spec";+ if (/^docs\//.test(p)) return "docs";+ if (/^apps\/server\/src\/assets\/doc_notes\//.test(p) || p === "apps/standalone/src/assets/help_meta.json") return "docs-generated";+ if (/translations\/en\/[^/]+\.json$/.test(p)) return "i18n-en";+ if (/translations\/[^/]+\/[^/]+\.json$/.test(p)) return "i18n-locale";+ if (/(^|\/)package\.json$|pnpm-lock\.yaml$|pnpm-workspace\.yaml$/.test(p)) return "deps";+ if (/^\.github\//.test(p)) return "ci";+ if (/^(apps|packages)\/[^/]+\/src\//.test(p)) return "prod";+ return "other";+}++function area(p) {+ const m = /^(apps|packages)\/([^/]+)\//.exec(p);+ if (!m) return /^docs\//.test(p) ? "docs" : "";+ return m[2].replace(/^trilium-/, "");+}++function reviewThreads(number) {+ const [owner, name] = repo().split("/");+ const q = `query($owner:String!,$name:String!,$n:Int!){ repository(owner:$owner,name:$name){ pullRequest(number:$n){ reviewThreads(first:100){ nodes{ isResolved isOutdated path line comments(first:20){ nodes{ author{login} authorAssociation body } } } } } } }`;+ const data = ghJson(["api", "graphql", "-f", `query=${q}`, "-F", `owner=${owner}`, "-F", `name=${name}`, "-F", `n=${number}`]);+ return (data.data?.repository?.pullRequest?.reviewThreads?.nodes ?? []).map((t) => ({+ ...t, comments: t.comments.nodes.map((c) => ({ author: c.author?.login ?? "?", authorAssociation: c.authorAssociation, body: c.body }))+ }));+}++function titleTokens(title) {+ return new Set(title.toLowerCase().replace(/^\w+(\([^)]*\))?!?:\s*/, "").replace(/\(closes #\d+\)/g, "").split(/[^a-z0-9]+/).filter((w) => w.length >= 4 && !TITLE_NOISE.has(w)));+}++function checkSummary(rollup) {+ const by = countBy(rollup ?? [], (c) => (c.conclusion || c.status || "pending").toLowerCase());+ return Object.entries(by).map(([k, n]) => `${n} ${k}`).join(", ") || "none";+}++function mixLine(mix) {+ const s = (k, label) => (mix[k].files ? `${label} +${mix[k].add}/-${mix[k].del} (${mix[k].files}f)` : `${label} —`);+ return [s("prod", "prod"), s("spec", "spec"), s("docs", "docs"), s("docs-generated", "generated-help"), s("i18n-en", "i18n"), s("i18n-locale", "other-locales"), s("deps", "deps"), s("ci", "ci"), s("other", "other")].join(" · ");+}++// ---------------------------------------------------------------------------------------------+// plumbing++function help() {+ console.log(fs.readFileSync(fileURLToPath(import.meta.url), "utf-8").split("\n").slice(1).join("\n").split(" */")[0].replace(/^ \* ?/gm, ""));+}++function parseFlags(argv) {+ const out = { _: [] };+ for (const a of argv) {+ if (a.startsWith("--")) {+ const [key, value] = a.slice(2).split("=");+ out[key] = value ?? true;+ } else out._.push(a);+ }+ return out;+}++function requireNumber() {+ const n = Number(String(flags._[0] ?? "").replace(/^#/, ""));+ if (!Number.isInteger(n) || n <= 0) die(`usage: ${command} <PR number>`);+ return n;+}++function repo() {+ repoSlug ??= ghJson(["repo", "view", "--json", "nameWithOwner"]).nameWithOwner;+ return repoSlug;+}++function gh(argv) {+ return execFileSync("gh", argv, { cwd: ROOT, encoding: "utf-8", maxBuffer: 256 * 1024 * 1024 });+}++function ghJson(argv) {+ const text = gh(argv);+ // `--paginate` on a REST list endpoint concatenates arrays; join them into one.+ if (argv.includes("--paginate")) return JSON.parse(`[${text.trim().replace(/\]\s*\[/g, ",").slice(1, -1)}]`);+ return JSON.parse(text);+}++function git(argv) {+ return execFileSync("git", argv, { cwd: ROOT, encoding: "utf-8", maxBuffer: 64 * 1024 * 1024 });+}++function run(cmd, argv, cwd) {+ const t0 = Date.now();+ const res = spawnSync(cmd, argv, { cwd, encoding: "utf-8", maxBuffer: 256 * 1024 * 1024, env: { ...process.env, CI: "1", FORCE_COLOR: "0" } });+ return { status: res.status, output: (res.stdout ?? "") + (res.stderr ?? ""), seconds: ((Date.now() - t0) / 1000).toFixed(1) };+}++function step(msg) {+ console.error(`▸ ${msg}`);+}++function save(number, name, text) {+ const dir = path.join(REVIEWS, `pr-${number}`);+ fs.mkdirSync(dir, { recursive: true });+ fs.writeFileSync(path.join(dir, name), text + "\n");+ console.error(`saved ${path.relative(ROOT, path.join(dir, name))}`);+}++function isBot(login) {+ return Boolean(login) && BOT_LOGIN.test(login);+}++function daysSince(iso) {+ return iso ? Math.floor((Date.now() - Date.parse(iso)) / 86400000) : -1;+}++function sum(arr, key) {+ let n = 0;+ for (const x of arr) n += x[key] ?? 0;+ return n;+}++function countBy(arr, fn) {+ const out = {};+ for (const x of arr) { const k = fn(x); out[k] = (out[k] ?? 0) + 1; }+ return out;+}++function indent(text, n) {+ const pad = " ".repeat(n);+ return text.split("\n").map((l) => pad + l).join("\n");+}++function clip(text, max) {+ return text.length > max ? `${text.slice(0, max)}\n… [${text.length - max} more chars]` : text;+}++function tail(text, n) {+ return text.trim().split("\n").slice(-n).join("\n");+}++function die(msg) {+ console.error(msg);+ process.exit(1);+}