Skip to content

armgit / Pake

Public Imported from GitHub
0

Turn any website into a lightweight desktop app with one command, on macOS, Windows and Linux.

docs(guidance): fix dangling rule pointers, route docs rules, add source-ban gate

Tw93605568eab427
diff --git a/.agents/skills/release/SKILL.md b/.agents/skills/release/SKILL.md
index 0884fa01..62a4fc16 100644
--- a/.agents/skills/release/SKILL.md
+++ b/.agents/skills/release/SKILL.md
@@ -12,7 +12,7 @@ allowed-tools:
# Release Skill
-Use this skill when preparing or executing a Pake release. Shared facts live in `.claude/rules/release.md` and are not repeated here: the four version files and tag format (Version Management), CI jobs, Trusted Publishing, surface separation, and the contributors bot (Release Workflow), and issue closeout (Issue Closeout After a Fix).
+Use this skill when preparing or executing a Pake release. Shared facts live in `.claude/rules/release.md` and are not repeated here: the four version files and tag format, CI jobs, Trusted Publishing, surface separation, and the contributors bot. Issue closeout lives in AGENTS.md (Issue Closeout After a Fix).
## Pre-Release
diff --git a/.claude/references/hotspots.md b/.claude/references/hotspots.md
new file mode 100644
index 00000000..69d084f3
--- /dev/null
+++ b/.claude/references/hotspots.md
@@ -0,0 +1,19 @@
+# Hotspot Map
+
+Moved verbatim from AGENTS.md (2026-12-04). AGENTS.md points here for proactive latent-bug sweeps.
+
+For proactive latent-bug sweeps, pick one row and go deep; do not invent a whole-repo scope. The third column is **historical failure modes / regression risks**, not a claim that the tree is broken today. Prefer the matching Current Risk Areas invariant when judging a change.
+
+| Hotspot | Paths | Regression risk if reintroduced |
+| -------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------ |
+| Link / download heuristics | `src-tauri/src/inject/event.js` | SPA routes or Cmd/Ctrl+click treated as downloads; path roots too broad |
+| Download success semantics | `invoke.rs`, `window.rs` `on_download` | Non-2xx toasted as success; toast/IPC hardcoded to `"pake"`; request drops session cookies |
+| Menu / focused window | `menu.rs` | Commands hit the main window, not the focused one; eval dead on error pages |
+| Startup visibility | `lib.rs`, `setup.rs` | Blank shell, `about:blank` false ready, user hide racing fallback reveal |
+| Auth / popup | `auth.js`, `event.js` | Sign-in popup loses its opener or stays open, abort on its close, SSO in system browser |
+| Clipboard | `event.js` | keydown steals native paste; double-paste fallback |
+| Multi-window / icon | `window.rs`, `setup.rs` | Missing `reapply_window_icon` on show; secondary window toast/target; Cmd+N blank flash |
+| Platform capability | `auth.rs`, proxy, WebKit flags | Flag name present, platform no-op |
+| CLI / config contract | `bin/`, `schema/` | Config smuggles out-of-range values CLI rejects |
+
+Oracles per row live under `tests/unit/` (for example `event-link-guard.test.js`, `download-http-status.test.ts`, `menu-focused-window.test.ts`, `startup-window-reveal.test.ts`, `window-icon-reapply.test.ts`); Linux WebKit flag decisions are covered by the `dmabuf_renderer_*` and `legacy_x11_*` `cargo test` cases in `src-tauri/src/lib.rs`.
diff --git a/.claude/rules/cli.md b/.claude/rules/cli.md
index 306403af..484afc0c 100644
--- a/.claude/rules/cli.md
+++ b/.claude/rules/cli.md
@@ -21,3 +21,15 @@ paths:
- Build workspaces preserve an existing root `rust-toolchain.toml` or legacy `rust-toolchain`; otherwise rustup may select a different default without the installed cross-compilation targets. Keep full stderr in real-build tests so compilation success cannot conceal a later target or bundling failure. GNU build flags must respect Cargo precedence: append required arguments to `CARGO_ENCODED_RUSTFLAGS` when present (including empty), otherwise to `RUSTFLAGS`; preserve user arguments and keep the override local to the build subprocess.
- New user-visible CLI surface (a new flag, alias, subcommand, or extra help variant) needs a stated justification before implementation: name the user problem and why an existing flag, config key, or default cannot cover it, then get maintainer sign-off. Prefer quieter defaults over new options; never split help output into parallel variants.
- Per-app optional fields in `default_app_list.json` currently take their defaults in Actions expressions in `release.yml` (`matrix.config.x || false` and the numeric ones), which works because every field so far is default-false or numeric. The first default-true field cannot use that path and must move its default into the jq read step: GitHub expressions cast both `null` and `false` to `0`, so `matrix.config.x != false` cannot express "default true" and would silently flip every app missing the field.
+
+## CLI error handling and config types
+
+Moved from `rust.md` (2026-12-04), which only loads for `src-tauri/**`.
+
+- Silent `catch {}` in TS or `let _ = ...` in Rust must surface the real error through `logger.warn` at minimum. Note `logger.warn` also feeds the `--json` warnings array; status lines belong in `logger.info`.
+- Predictable CLI failures throw `PakeError` with `{code, hint}` (`bin/utils/error.ts`); the code maps to a stable exit code and the `--json` error object. Plain `Error` gets classified by build phase in `bin/cli.ts`.
+- In machine mode (`--json`) stdout is reserved for the single JSON result. Never `console.log` / `process.stdout.write` in `bin/`; subprocess stdout is rerouted to stderr by `shellExec`. Gate: `scripts/check-source-bans.mjs` (`output.ts` writes the one JSON result).
+- `shellExec` runs subprocesses with `stdio: 'inherit'`, so their output (linuxdeploy, cargo, npm) never reaches `error.message`; only the failed command line does. Do NOT classify a build failure by grepping `error.message`; you would be matching the command, not the diagnostics. Drive failure guidance off a structured fact the caller holds (e.g. `target === 'appimage'`). Owners: `bin/utils/shell.ts` + `bin/builders/BaseBuilder.ts`.
+- Pass executable, argument array, and working directory separately to `shellExec`; quoted shell strings still interpret command substitutions in paths. Platform builders derive version/language from current options and merge cloned templates, never mutable module-level config. Keep shared dependency directories read-only during workspace builds.
+- No `tauriConf: any` or other untyped config bags. Use `PakeTauriConfig`.
+- Window options live in `bin/helpers/cli-program.ts`, `bin/types.ts`, `bin/defaults.ts`, `bin/helpers/merge.ts`. Adding an option means touching all four plus `schema/pake.schema.json` and `docs/cli-usage*.md`. Forgetting any is a regression; the schema half is caught by `tests/unit/config-file.test.ts`.
diff --git a/.claude/rules/docs.md b/.claude/rules/docs.md
new file mode 100644
index 00000000..e335b7c2
--- /dev/null
+++ b/.claude/rules/docs.md
@@ -0,0 +1,16 @@
+---
+paths:
+ - "README*.md"
+ - "docs/**"
+ - "default_app_list.json"
+ - "gallery/**"
+---
+
+# Documentation Guidelines
+
+- **Main README**: keep only common, frequently-used parameters to avoid clutter.
+- **CLI Documentation** (`docs/cli-usage.md` and locale variants): include **all** CLI parameters with detailed usage examples.
+- **Rare or advanced parameters**: should have full documentation in `docs/cli-usage*.md` but minimal or no mention in the main README. Examples: `--title`, `--incognito`, `--system-tray-icon`, `--multi-window`, `--min-width`, `--min-height`.
+- **README popular-packages showcase**: apps render in pairs of `<td>` cells, each with a 600px-wide screenshot from `https://raw.githubusercontent.com/tw93/static/main/pake/<Title>.png` or `.jpg` (the showcase currently mixes both; source spec 2624x1784, a Retina window capture). Upload the screenshot to `tw93/static` before pushing the README row, and note the app's download links stay 404 until the next `V*` release builds its assets.
+- **App list curation**: judge showcase or `default_app_list.json` additions and removals with real demand from `gh release view <tag> --json assets` download counts, not intuition. Keep both README locales in the same order.
+- **No WeChat** (maintainer 2026-11-25): WeChat forbids sign-in from unofficial clients and restricts accounts that do it, so no WeChat app goes in `default_app_list.json`, the gallery or site styles, and the FAQ points users to the official client. A UOS-header workaround signed in once, then the account lost QR sign-in on new devices for about two weeks; it was reverted in `be66cccb`. Do not restore WeChat or suggest packaging wx.qq.com. Gate: `scripts/check-source-bans.mjs` rejects `wx.qq.com` in the app list, gallery, READMEs and source.
diff --git a/.claude/rules/release.md b/.claude/rules/release.md
index c9272c6b..74759ec0 100644
--- a/.claude/rules/release.md
+++ b/.claude/rules/release.md
@@ -19,7 +19,7 @@ Four files must be updated in sync for every release:
| `src-tauri/Cargo.lock` | `version` for package `pake` |
| `src-tauri/tauri.conf.json` | `"version"` |
-A version bump must also rebuild and commit `dist/cli.js` (it embeds the package version); see Troubleshooting.
+A version bump must also rebuild and commit `dist/cli.js` (it embeds the package version); see AGENTS.md Working Principles.
Tag format: `V<major.minor.patch>` with uppercase `V` (e.g. `V3.13.1`). Current version: check `package.json`.
diff --git a/.claude/rules/rust.md b/.claude/rules/rust.md
index 2bd06a21..492023c1 100644
--- a/.claude/rules/rust.md
+++ b/.claude/rules/rust.md
@@ -5,7 +5,7 @@ paths:
# Pake Rust + Tauri Rules
-> Pake-specific Rust + Tauri rules. Standard Rust hygiene is assumed: `?` over `unwrap()`, `cargo clippy` clean, `cargo fmt` before commit. The `dist/cli.js` rebuild rule, CN mirror policy, and platform-sensitivity rules (Linux/Wayland WebKit compositing, AppImage warning noise, `--incognito`, embedded-WebView OAuth) live in AGENTS.md (Current Risk Areas / Network Mirror Behavior) and are not repeated here.
+> Pake-specific Rust + Tauri rules. Standard Rust hygiene is assumed: `?` over `unwrap()`, `cargo clippy` clean, `cargo fmt` before commit. The `dist/cli.js` rebuild rule and CN mirror policy live in AGENTS.md (Working Principles / Network Mirror Behavior); the platform-sensitivity rules live in `.claude/rules/tauri-runtime.md` (Linux/Wayland WebKit compositing, AppImage warning noise), `.claude/rules/tauri-windows-inject.md` (`--incognito`) and `.claude/rules/tauri-popups-auth.md` (embedded-WebView OAuth). None are repeated here. The CLI (`bin/`) error-handling and config-type rules live in `.claude/rules/cli.md`.
## Pake-Specific
@@ -13,15 +13,6 @@ paths:
- No `panic!` / `.unwrap()` / `.expect()` on user-reachable paths: CLI options, config loading, event handlers, IPC commands. Use `?` and surface clear messages.
- Silent `catch {}` in TS or `let _ = ...` in Rust must surface the real error through `logger.warn` at minimum. Note `logger.warn` also feeds the `--json` warnings array; status lines belong in `logger.info`.
-- Predictable CLI failures throw `PakeError` with `{code, hint}` (`bin/utils/error.ts`); the code maps to a stable exit code and the `--json` error object. Plain `Error` gets classified by build phase in `bin/cli.ts`.
-- In machine mode (`--json`) stdout is reserved for the single JSON result. Never `console.log` / `process.stdout.write` in `bin/`; subprocess stdout is rerouted to stderr by `shellExec`.
-- `shellExec` runs subprocesses with `stdio: 'inherit'`, so their output (linuxdeploy, cargo, npm) never reaches `error.message`; only the failed command line does. Do NOT classify a build failure by grepping `error.message`; you would be matching the command, not the diagnostics. Drive failure guidance off a structured fact the caller holds (e.g. `target === 'appimage'`). Owners: `bin/utils/shell.ts` + `bin/builders/BaseBuilder.ts`.
-- Pass executable, argument array, and working directory separately to `shellExec`; quoted shell strings still interpret command substitutions in paths. Platform builders derive version/language from current options and merge cloned templates, never mutable module-level config. Keep shared dependency directories read-only during workspace builds.
-
-### Config types
-
-- No `tauriConf: any` or other untyped config bags. Use `PakeTauriConfig`.
-- Window options live in `bin/helpers/cli-program.ts`, `bin/types.ts`, `bin/defaults.ts`, `bin/helpers/merge.ts`. Adding an option means touching all four plus `schema/pake.schema.json` and `docs/cli-usage*.md`. Forgetting any is a regression; the schema half is caught by `tests/unit/config-file.test.ts`.
### Tauri trust boundary
diff --git a/.claude/rules/tauri-macos-native.md b/.claude/rules/tauri-macos-native.md
index 7398423e..767c52c3 100644
--- a/.claude/rules/tauri-macos-native.md
+++ b/.claude/rules/tauri-macos-native.md
@@ -14,6 +14,6 @@ paths:
- A page's `alert()`, `confirm()` and `prompt()` show nothing in a WKWebView unless its UI delegate implements the three `runJavaScript…Panel` methods, and Wry's does not (through 0.57.2): `alert` returned at once, `confirm` returned false and `prompt` null in a millisecond, so a site that confirms before logging out did nothing (a user's report, 2026-11-17; WebView2 and WebKitGTK show their own). `src-tauri/src/app/script_dialogs.rs` adds the three methods to the delegate's class where it lacks them, for every webview from `build_window`, and then sets the same delegate on the webview again: WebKit records which methods a delegate answers when it is set, and without the reset the added methods are never called. Each panel is an NSAlert sheet on the page's window whose completion calls WebKit's handler exactly once (WebKit raises on zero or two calls), which keeps the script waiting as a browser does. The sheet goes on the window even when it is hidden, as a closed window is with hide-on-close: AppKit then shows the window with its sheet (measured: a window hidden with Cmd+W came back on screen when its page called `confirm()`), where an app-modal panel would float over whatever else the user is doing; only a webview with no window falls back to `runModal`. Cancel carries an explicit Escape key equivalent, because AppKit gives Escape only to a button titled Cancel and the Chinese title is 取消. Verify on a real bundle with a page that calls all three and writes what it got back: OK gives `true`, Cancel `false`, a prompt its field's text or `null`, and each wait is seconds, not a millisecond. Send the keys with a CGEvent tool of your own: Escape must give `false` and `null`, Return `true`. Cover it with `tests/unit/macos-script-dialogs.test.ts` and the `script_panel_encodings_match_their_selectors` Rust test, which keeps each selector's colons and its type encoding in step.
- Passkeys on macOS (2026-11-19): WKWebView refuses WebAuthn in an app that neither lists the site under `webcredentials` nor holds Apple's browser entitlement, which an ad hoc signed app never can, so `create` and `get` failed in 30 ms with `NotAllowedError`. `src-tauri/src/inject/passkey.js` (main frame; not incognito, nor with `ignore_certificate_errors`, where a stand-in on the network would get a signature for the real origin; `passkey::enabled`) hands a `publicKey` request to the `pakePasskey` `WKScriptMessageHandlerWithReply` in `src-tauri/src/app/passkey/macos.rs`, which takes the origin from WebKit's `WKFrameInfo` (main frames only, never from the page), checks the rpId against the public suffix list (`resolve_rp_id`), makes a non-permanent Secure Enclave P-256 key gated by `userPresence` (Touch ID, or the login password), keeps its token (`toid`) in `<app data>/passkeys.json`, and writes `none` attestation itself; no keychain entitlement is needed. The passkeys stay in that app on that Mac, outside iCloud Keychain; a sign-in with none shows a sheet saying so. Any process of the same user can read the store and sign after a prompt that names that process, as with Chrome's profile authenticator. Only the key window of the active app may start a ceremony, and a Mac without an enclave refuses without a sheet. One ceremony runs at a time under a token (`OWNER`); leaving the page (`pagehide`) cancels it like an abort; the page's abort or timeout (5 minutes when the site gives none) sends `cancel`, which counts only from the webview that started it, frees it at once, invalidates the LAContext and ends the sheet; a key made after that is not saved; a sheet left on a closed or close-hidden window (not a minimized one, nor while the app is hidden) gives way to the next request, since the sheet keeps its `Reply` alive. The credential object must read as a browser's: its fields are enumerable getters with no setter and its methods writable, one prototype step up (`shaped`), so `Object.keys` is empty, `for...in` lists the fields (FIDO's webauthn-demo serialises that way) and a page may replace a method, because GitHub's webauthn-json assigns `credential.toJSON = ...` in strict mode and a read-only property made every registration fail after the key was saved (found on github.com with a probe that reported `unhandledrejection`; GitHub's error said only "Passkey registration failed"). Verify on a real bundle: a localhost page backed by py_webauthn for register, sign-in with and without `allowCredentials`, the account picker, cancel then retry; then add and use a passkey on github.com. Cover it with the `app::passkey` Rust tests and `tests/unit/passkey-bridge.test.js`.
-- `navigation_buttons` is a runtime-only macOS window field (no CLI flag; the paid apps set it, off by default): `src-tauri/src/app/nav_buttons.rs` adds Back and Forward to the title bar in a leading accessory beside the traffic lights, for people with a plain mouse who have neither the swipe nor Cmd-[. The buttons call `history_step`, the native step the Navigation menu uses, so they work on a blank error page; their action lives on the window's class as `tab_bar.rs`'s does. Enabled state follows the WKWebView's `canGoBack` and `canGoForward` by key-value observing; do not poll. The webview owns the observer through an associated object, which means the observer drops only while the webview is deallocating, when a weak reference to it already reads nil: removal in `Drop` never runs, so the observer unregisters on `NSWindowWillCloseNotification`, behind one flag because removing an unregistered observer raises (`auth.rs`'s delegate still has only the `Drop` removal). Alignment is to ink, checked on a 2x capture: each chevron's middle goes on the close button's centre line, read from `standardWindowButton:` (the lights sit 16 points down a 32 point bar on macOS 26) and from the cell's `imageRectForBounds:` (NSButton sets a 16 point image half a point above a 22 point button's middle), and redone on resize and around full screen. The chevrons are drawn, not `chevron.left`, because that symbol sits on a text baseline 1.5 points high. Labels are the system's own, 返回 and 前进, 上一頁 and 下一頁, through `UiLanguage`. A real-bundle check measures the rows of the red light and of each chevron in a `screencapture -l` PNG, whose centres must be equal, and opens then closes a Cmd+N window with the app still running. Under `hide_title_bar` the buttons sit over the page beside the lights, and the per-site `immersive` paddings in `style.js` clear only the lights' width. Cover it with `tests/unit/macos-navigation-buttons.test.ts` and the `navigation_buttons_are_opt_in` Rust test.
-- `transparent_title_bar` is a runtime-only macOS window field (no CLI flag; the paid apps set it): Tauri's `Transparent` title bar keeps the page below the bar, and `src-tauri/src/inject/title_bar.js` paints the window background with the page's top-edge color through `set_title_bar_color`. `hide_title_bar` keeps precedence and its overlay behavior. The color is the majority of three top-edge samples, resolved through a canvas so `oklch()`/`color()` values work; do not skip sampling for `document.hidden`, or windows revealed after load stay uncolored: only the 1.5 s poll rests while the page is hidden, page events still sample, and the poll picks up again once the page shows, with or without a `visibilitychange` event. Cover it with `tests/unit/title-bar-color.test.js`; when checking a real bundle, window captures carry the display profile, so convert the sRGB page color before comparing pixels.
+- `navigation_buttons` is a runtime-only macOS window field (no CLI flag; downstream builds set it, off by default): `src-tauri/src/app/nav_buttons.rs` adds Back and Forward to the title bar in a leading accessory beside the traffic lights, for people with a plain mouse who have neither the swipe nor Cmd-[. The buttons call `history_step`, the native step the Navigation menu uses, so they work on a blank error page; their action lives on the window's class as `tab_bar.rs`'s does. Enabled state follows the WKWebView's `canGoBack` and `canGoForward` by key-value observing; do not poll. The webview owns the observer through an associated object, which means the observer drops only while the webview is deallocating, when a weak reference to it already reads nil: removal in `Drop` never runs, so the observer unregisters on `NSWindowWillCloseNotification`, behind one flag because removing an unregistered observer raises (`auth.rs`'s delegate still has only the `Drop` removal). Alignment is to ink, checked on a 2x capture: each chevron's middle goes on the close button's centre line, read from `standardWindowButton:` (the lights sit 16 points down a 32 point bar on macOS 26) and from the cell's `imageRectForBounds:` (NSButton sets a 16 point image half a point above a 22 point button's middle), and redone on resize and around full screen. The chevrons are drawn, not `chevron.left`, because that symbol sits on a text baseline 1.5 points high. Labels are the system's own, 返回 and 前进, 上一頁 and 下一頁, through `UiLanguage`. A real-bundle check measures the rows of the red light and of each chevron in a `screencapture -l` PNG, whose centres must be equal, and opens then closes a Cmd+N window with the app still running. Under `hide_title_bar` the buttons sit over the page beside the lights, and the per-site `immersive` paddings in `style.js` clear only the lights' width. Cover it with `tests/unit/macos-navigation-buttons.test.ts` and the `navigation_buttons_are_opt_in` Rust test.
+- `transparent_title_bar` is a runtime-only macOS window field (no CLI flag; downstream builds set it): Tauri's `Transparent` title bar keeps the page below the bar, and `src-tauri/src/inject/title_bar.js` paints the window background with the page's top-edge color through `set_title_bar_color`. `hide_title_bar` keeps precedence and its overlay behavior. The color is the majority of three top-edge samples, resolved through a canvas so `oklch()`/`color()` values work; do not skip sampling for `document.hidden`, or windows revealed after load stay uncolored: only the 1.5 s poll rests while the page is hidden, page events still sample, and the poll picks up again once the page shows, with or without a `visibilitychange` event. Cover it with `tests/unit/title-bar-color.test.js`; when checking a real bundle, window captures carry the display profile, so convert the sRGB page color before comparing pixels.
- A WKWebView whose web content process dies goes white and stays white, with no URL. `recovery.rs` reloads it from Tauri's `on_web_content_process_terminate` hook, set in `lib.rs`, at most `MAX_RELOADS` times in `RELOAD_WINDOW` as on Windows and Linux. The hook must stay set: without one Tauri 2.12 reloads every time with no limit, and when Pake still replaced Wry's delegate method and called the original first (the route under Tauri 2.10, which passed no handler down), the upgrade made the third death in a minute reload as well (measured on a real bundle, 2026-11-18). Read a window's address only through `page_url`: Wry's getter unwrapped WKWebView's `URL` through 0.54.2, which is nil for such a web view, and the panic aborted the app under `panic = "abort"`; Wry 0.57 returns an error instead, and `page_url` stays the one reader, asking the web view first. A user's X app went white and then crashed on Cmd+Q, in `save_last_url` on `RunEvent::Exit` (2026-11-18); `page_url` in `window.rs` asks the web view first and is the only reader. Verify on a real bundle by killing the app's own `com.apple.WebKit.WebContent` process (the one that appears after launch): the page comes back twice, the third time it stays white, and quitting then leaves no crash report.
diff --git a/.claude/rules/tauri-runtime.md b/.claude/rules/tauri-runtime.md
index fb09820b..ec696118 100644
--- a/.claude/rules/tauri-runtime.md
+++ b/.claude/rules/tauri-runtime.md
@@ -20,9 +20,9 @@ paths:
# Tauri runtime risk areas (core, IPC, downloads, blocking)
-- Native IPC is gated by the application command manifest in `src-tauri/build.rs`. Keep every registered app command in that manifest and grant only its required permissions. The packaged capability is local-only; `PakeConfig::remote_capability` grants the same permission set to exact configured entry origins (scheme, host, and port) before webviews load. Navigation flags, login redirects, subdomains, and restored URLs must not expand that grant. Keep local pages, secondary windows, loopback/IPv6 URLs, and literal hostname handling covered. ACL-denied downloads may fall back to browser attachments, but transient download anchors must bypass the IPC click interceptor to avoid recursion. Fullscreen must acquire native permission before mutating the player DOM; untrusted frame messages must never gain a top-level navigation fallback. Run `cargo test --lib` and `node tests/integration/ipc-security.mjs` (real macOS WebView, which passes on a Mac whose system proxy is on, as the test Mac's is: hyper-util reads that proxy without its exceptions list, so `macos_system_proxy` and `system_proxy_bypasses` in `invoke.rs` read the list themselves and send loopback direct; before c454d938 the probe's loopback payload got a 502 from the proxy and it died reading `request.headers`); hiding `window.__TAURI__` or narrowing plugin capabilities alone does not gate application commands.
+- Native IPC is gated by the application command manifest in `src-tauri/build.rs`. Keep every registered app command in that manifest and grant only its required permissions. The packaged capability is local-only; `PakeConfig::remote_capability` grants the same permission set to exact configured entry origins (scheme, host, and port) before webviews load. Navigation flags, login redirects, subdomains, and restored URLs must not expand that grant. Keep local pages, secondary windows, loopback/IPv6 URLs, and literal hostname handling covered. ACL-denied downloads may fall back to browser attachments, but transient download anchors must bypass the IPC click interceptor to avoid recursion. Fullscreen must acquire native permission before mutating the player DOM; untrusted frame messages must never gain a top-level navigation fallback. Run `cargo test --lib` and `node tests/integration/ipc-security.mjs` (real macOS WebView, which passes on a Mac whose system proxy is on: hyper-util reads that proxy without its exceptions list, so `macos_system_proxy` and `system_proxy_bypasses` in `invoke.rs` read the list themselves and send loopback direct; before c454d938 the probe's loopback payload got a 502 from the proxy and it died reading `request.headers`); hiding `window.__TAURI__` or narrowing plugin capabilities alone does not gate application commands.
- The `runtime-template` Cargo feature builds a prebuilt runtime that a separate builder customizes without a compiler: at launch it reads `pake-runtime/{pake.json, app.json, custom.js?, tray.png?}` from `Contents/Resources` on macOS or next to the executable elsewhere, and applies app.json's `identifier` and `productName` to the Tauri context before build. The CLI never enables the feature, so CLI-built apps keep their compiled configuration even if such a folder appears. A present but invalid override exits with a `[Pake]` message instead of falling back to the template's identity. A runtime app keys its WebView profile folder under the config dir (`%APPDATA%\<identifier>\EBWebView` on Windows) by identifier instead of product name (`data_dir_name`), so a rename keeps logins and a generated name cannot share another program's folder; CLI apps keep the product-name folder. On Windows a runtime app also sets the process AppUserModelID to its identifier before any window exists, so shortcuts carrying that ID group with the running window and toasts are attributed to it. Logic and tests live in `src-tauri/src/util.rs` (`apply_runtime_override`, `data_dir_name`, `set_app_user_model_id`); `PakeConfig::runtime_app` is the single runtime-app flag, and `run_app` copies the overridden identity from the returned Tauri config into the context; keep `cargo clippy` and `cargo test --lib` green both with and without `--features runtime-template`.
-- A runtime app can carry its own pages (2026-11-25): with `url_type: "local"` the window's `url` names a file inside `pake-runtime/site/` (`tool.html`, `index.html`), and `apply_runtime_override` sets `PakeConfig::runtime_site` only when that file exists, refusing an empty, absolute or `..` path. `run_app` then swaps the context's assets for `src-tauri/src/app/local_site.rs`, which reads files from that folder on each request and refuses any path, `..` or symbolic link, that resolves outside it, so the pages keep the origin and local-page behaviour of a CLI local app (`tauri://localhost`, `http://tauri.localhost` on Windows) without a compiler. Covered by `runtime_override_serves_a_local_window_from_its_site_folder` and the `local_site` tests; measured on the test Mac with a page, a script in a subfolder, a `fetch` of a JSON file and localStorage across a relaunch.
+- A runtime app can carry its own pages (2026-11-25): with `url_type: "local"` the window's `url` names a file inside `pake-runtime/site/` (`tool.html`, `index.html`), and `apply_runtime_override` sets `PakeConfig::runtime_site` only when that file exists, refusing an empty, absolute or `..` path. `run_app` then swaps the context's assets for `src-tauri/src/app/local_site.rs`, which reads files from that folder on each request and refuses any path, `..` or symbolic link, that resolves outside it, so the pages keep the origin and local-page behaviour of a CLI local app (`tauri://localhost`, `http://tauri.localhost` on Windows) without a compiler. Covered by `runtime_override_serves_a_local_window_from_its_site_folder` and the `local_site` tests; measured on a real macOS bundle with a page, a script in a subfolder, a `fetch` of a JSON file and localStorage across a relaunch.
- `--download-dir` / `downloadDir` is embedded as trusted `pake.download_dir`, shared by native and IPC downloads through `get_download_dir`. Empty means system Downloads; quoted `~/path` expands against the runtime user home. Reject relative paths and absolute tilde suffixes, create missing directories on download, and surface directory creation plus file open/write failures without redirecting to another folder. Do not accept a directory from remote-page IPC arguments.
- Do not open a synchronous native save dialog inside `on_download(Requested)`. Wry (through 0.57.2) holds a `RefCell` mutable borrow across that callback; a modal panel allows another download callback to reenter and panic. A native two-download probe reproduced this with 100 ms and 500 ms spacing. The macOS completion event also omits the destination path, so URL-only bookkeeping cannot safely identify concurrent downloads of the same URL.
- Notification flows cross injected JS, Tauri invokes, capabilities, and native notification plugins. Verify the Rust capability and JS caller together. macOS clicks and withdrawals use the originating window label plus a validated notification id; closed or tag-replaced objects must remain closed when IPC replies arrive late. Queue `close` events as tasks so handlers cannot mutate a live Map during replacement. Safari before 14 exposes an `EventTarget` interface without a usable constructor; retain a native DOM event target fallback for the macOS 10.13 deployment floor, and cover both paths with `node --test tests/browser/notification-bridge.mjs`. Windows/Linux retain a limited focus heuristic, not a native click callback. Cover deferred replies and close-handler reentry in `tests/unit/notification-bridge.test.js`, and verify macOS click routing, hidden-window reveal, and withdrawal with a real bundled app.
@@ -34,4 +34,4 @@ paths:
- The release profile is `panic = "unwind"` (2026-11-19), not `abort`: under abort an Objective-C exception that crosses a Rust frame ends the app, since Wry's `objc2::exception::catch` cannot hold, and WebKit raises one whenever an `ipc://` answer arrives for a request a closing or leaving page had out. Measured on macOS 26.7 with both mitigations off (no `deferWindowClose`, `CLOSE_GRACE` 0): the abort build died on the first sign-in popup with a crash report, the unwind build finished all three flows of `tests/integration/signin-popup-server.mjs` and stayed up. It costs about 1.9 MB per architecture on macOS (12.8 to 14.7 MB on arm64). Windows and Linux have no such exception and pay more (the Windows x64 binary went from 11.9 to 16.4 MB), so the CLI passes `CARGO_PROFILE_RELEASE_PANIC=abort` to their release builds (`getPanicStrategyEnvironment` in `bin/builders/env.ts`), as any other builder of those platforms should; the profile's default stays unwind so that a builder that forgets is only larger, never back to the crash. Do not switch the profile back for size; `tests/unit/popup-close.test.ts` holds it. The close delay and the grace stay: they let the popup's last calls finish, which unwinding does not.
- Built-in ad blocking (`content-blocking` feature, `src-tauri/src/app/content_blocking.rs`) embeds the lists of `filters/`, which `node scripts/update-filter-lists.mjs` downloads; they age within days, so update them before a runtime release. A change to the lists or to their conversion is then run on real pages with `node tests/blocking/run.mjs` (macOS, about 15 minutes for the 60 pages of `tests/blocking/sites.txt`), because unit tests on the conversion let I-23 ship: it loads each page in an offscreen WKWebView without blocking, with the two WebKit lists a Mac or Linux app compiles and with the hiding script a Windows app injects, and fails a page that loses its icons, most of its elements or most of a long text. It first proves it can fail, on a list that hides every `svg`. Pages change from one load to the next, so a difference is loaded three times before it counts, and a cookie notice that is half of a short page's text is the cookies list working. Measured in a Windows 11 VM on 2026-11-21: the 644 KB generic hiding style costs about 12 ms to add on a page and 2 to 8 ms more on a full style recalculation (stackoverflow.com, bilibili.com, theguardian.com), so it is not trimmed per site. Scriptlet rules (`+js(...)`) and procedural selectors are dropped on purpose: the scriptlets that block YouTube's ads change every few days, and lists embedded at build time would be stale and could stop playback instead; they need a way to update lists in installed apps first.
- IPC reaches only the packaged entry origins (`remote_capability` in `config.rs`): once the window is on another site, every `invoke` from an injected script is rejected, so the script's fallback is what actually runs there and has to be right by itself. `window.pakeConfig.url` is absolute for a web app but only a file name for a local one, so a fallback that assigns it to `location.href` loads that name from the site the window is on; `packagedHomeUrl()` in `event.js` builds the bundled page's address instead (`http://tauri.localhost/` on Windows, `tauri://localhost/` elsewhere, as `resolve_home_url` in `navigation.rs`). Unit tests with a resolving `invoke` mock do not see this: a shortcut or command a page can use off the packaged origin gets a test with a rejecting `invoke`, and is pressed in a built app after navigating away, for a web app and a local-file app. Without CI that is a cross-built Windows runtime in a VM (`SendKeys` after `AppActivate`, the page writing `location.href` into `document.title`) and a `--no-bundle` runtime under `xvfb-run` on Linux (`xdotool key` after a click, the page reporting to a local HTTP server, since a title is not readable there). Before V3.20.0 this caught Ctrl+Shift+H sending a local app on example.org to `example.org/index.html`.
-- `popover` is a runtime-only field on `windows[0]` (no CLI flag; the paid apps set it, 2026-12-03), honoured on macOS and Windows and compiled out on Linux (`PakeConfig::is_popover`). It turns the tray on, drops the Dock icon (accessory policy), turns multi-window and fullscreen off, anchors the window to the tray icon in `setup.rs` (`position_popover_at_tray`: macOS always under the menu bar icon, `menu_bar_popover_position`, in points with `LogicalPosition`, since tao's physical coordinates are each monitor's own scale and overlap on mixed-DPI displays, and a side Dock or an auto-hiding menu bar must not move it beside the icon; Windows in physical pixels, `popover_window_position`, by the taskbar edge or above the tray overflow flyout), and hides it on blur in `lib.rs` (`auto_hide_popover`) unless it is pinned, another app window is up or a page dialog took the focus (macOS: an attached sheet or `NSApp.modalWindow`, which covers the `runModal` file panel; Windows: the main window disabled, or the foreground window owned by it, read 150 ms after the blur because the dialog takes focus first; the check is stamped with `POPOVER_FOCUS_SEQ` so a later focus change voids it, and asks whether the popover is the foreground window, since tao's `is_focused` reads false while the WebView2 child holds the keyboard). The tray, the shortcut and Show decide on the popover window alone (`popover_visible`), not on any app window, so an extension page left open does not turn the next tray click into a close; the tray's Always on Top check always shows the main window's state. A tray press records at mouse-down whether it lands on a visible or just blur-hidden popover, so the press closes it instead of hiding and reopening. The macOS window carries `NSWindowCollectionBehavior::Stationary`: without it a click on the wallpaper (Show Desktop, on by default since macOS 14) pushed the hidden popover to the screen edge and the next tray click opened it above the screen while AppKit still reported it under the icon; a desktop click is therefore not a neutral blur in a test, click another app's window as well. Verify on a real bundle: on the test Mac, tray show, re-click, blur by wallpaper and by another app's window (each several times, reading `CGWindowListCopyWindowInfo` bounds, not tao's position), the file panel and `confirm()` keeping it, Cmd+W; on Windows (the ThinkPad when the VM's taskbar is not drawn), show from the overflow flyout, a slow press, blur, the file dialog and `confirm()`, and no taskbar button after hide and show. WebView2's own `confirm()` is wider than the 420 px window and clips its buttons; Enter and Escape still answer it.
+- `popover` is a runtime-only field on `windows[0]` (no CLI flag; downstream builds set it, 2026-12-03), honoured on macOS and Windows and compiled out on Linux (`PakeConfig::is_popover`). It turns the tray on, drops the Dock icon (accessory policy), turns multi-window and fullscreen off, anchors the window to the tray icon in `setup.rs` (`position_popover_at_tray`: macOS always under the menu bar icon, `menu_bar_popover_position`, in points with `LogicalPosition`, since tao's physical coordinates are each monitor's own scale and overlap on mixed-DPI displays, and a side Dock or an auto-hiding menu bar must not move it beside the icon; Windows in physical pixels, `popover_window_position`, by the taskbar edge or above the tray overflow flyout), and hides it on blur in `lib.rs` (`auto_hide_popover`) unless it is pinned, another app window is up or a page dialog took the focus (macOS: an attached sheet or `NSApp.modalWindow`, which covers the `runModal` file panel; Windows: the main window disabled, or the foreground window owned by it, read 150 ms after the blur because the dialog takes focus first; the check is stamped with `POPOVER_FOCUS_SEQ` so a later focus change voids it, and asks whether the popover is the foreground window, since tao's `is_focused` reads false while the WebView2 child holds the keyboard). The tray, the shortcut and Show decide on the popover window alone (`popover_visible`), not on any app window, so an extension page left open does not turn the next tray click into a close; the tray's Always on Top check always shows the main window's state. A tray press records at mouse-down whether it lands on a visible or just blur-hidden popover, so the press closes it instead of hiding and reopening. The macOS window carries `NSWindowCollectionBehavior::Stationary`: without it a click on the wallpaper (Show Desktop, on by default since macOS 14) pushed the hidden popover to the screen edge and the next tray click opened it above the screen while AppKit still reported it under the icon; a desktop click is therefore not a neutral blur in a test, click another app's window as well. Verify on a real bundle: on macOS, tray show, re-click, blur by wallpaper and by another app's window (each several times, reading `CGWindowListCopyWindowInfo` bounds, not tao's position), the file panel and `confirm()` keeping it, Cmd+W; on Windows (a real Windows machine when a VM's taskbar is not drawn), show from the overflow flyout, a slow press, blur, the file dialog and `confirm()`, and no taskbar button after hide and show. WebView2's own `confirm()` is wider than the 420 px window and clips its buttons; Enter and Escape still answer it.
diff --git a/.claude/rules/tauri-windows-inject.md b/.claude/rules/tauri-windows-inject.md
index 0020b938..a806c0be 100644
--- a/.claude/rules/tauri-windows-inject.md
+++ b/.claude/rules/tauri-windows-inject.md
@@ -15,7 +15,7 @@ paths:
- Injected CSS uses `src-tauri/src/inject/styles.js`: preserve DOM stylesheet order on ordinary pages; use constructable sheets only when CSP blocks the style element. `replaceSync` silently drops `@import`, so keep import-bearing CSS on its original DOM path, including escaped/case-insensitive at-keywords. Strict CSP plus imports remains unsupported. Run `node tests/browser/style-injection.mjs` with an installed Playwright runtime; mock CSSStyleSheet tests do not validate CSP or cascade behavior.
- The app is built with `withGlobalTauri: false`: a page can read `window.__TAURI__`, and DeepSeek's front end shows "Abnormal usage environment" when `"__TAURI__" in window` holds (measured on a real bundle, 2026-11-18; its other tests are a user agent naming Tauri or Electron). Injected scripts reach the native side only through `window.__PAKE_NATIVE__` from `src-tauri/src/inject/bridge.js`, which keeps the shape they used (`core.invoke`, `shell.open` and `window.getCurrentWindow()` with the nine window commands the capability grants) over `__TAURI_INTERNALS__`; a new window call is added there with the command and argument names Tauri's own API sends, and needs its permission in the capability. Tauri decides the global API at compile time, so a prebuilt runtime cannot switch it per app: the user's own code, a bundled local page or an injected script that names `__TAURI__`, gets the name pointed at the bridge instead (`global_api_name_script` in `window.rs`): a local app only on its own `tauri:` pages, so a site it links out to stays clean, while an app with such a script shows the name to its site again. The rest of Tauri's global API (events, paths, DPI types) is gone for such code; the capability never granted a page most of it. `isTauri`, `__TAURI_INTERNALS__` and the plugins' `__TAURI_PLUGIN_*` names remain and are not configurable from a script; hiding them means patching the tauri crate, to do only when a site is shown to read them. `tests/unit/native-bridge.test.js` holds the scripts and the config to this.
-- `site_styles` is a runtime-only window field (no CLI flag; default true): the paid apps write false when the app carries a browser extension that restyles its site (Minimal Theme for Twitter on X), and `style.js` then leaves out that site's `content` rules, keeping the global and `immersive` ones. On X the runtime's 700 px column, `!important` under `#react-root`, overrode the extension's own width setting. `page_config` in `window.rs` forces it back to true wherever the app's extensions do not run (no `pake-runtime/extensions`, macOS before 15.4, Linux), so a site never loses both. Covered by `site_styles_stay_on_unless_the_builder_turns_them_off`, `site_styles_turn_off_only_where_extensions_run` and `tests/unit/site-styles.test.js`.
+- `site_styles` is a runtime-only window field (no CLI flag; default true): downstream builds write false when the app carries a browser extension that restyles its site (Minimal Theme for Twitter on X), and `style.js` then leaves out that site's `content` rules, keeping the global and `immersive` ones. On X the runtime's 700 px column, `!important` under `#react-root`, overrode the extension's own width setting. `page_config` in `window.rs` forces it back to true wherever the app's extensions do not run (no `pake-runtime/extensions`, macOS before 15.4, Linux), so a site never loses both. Covered by `site_styles_stay_on_unless_the_builder_turns_them_off`, `site_styles_turn_off_only_where_extensions_run` and `tests/unit/site-styles.test.js`.
- Window/runtime options with platform-sensitive behavior include `--incognito`, `--new-window`, `--min-width`, `--min-height`, `--maximize`, multi-window behavior, notification click handling, and Linux/Wayland WebKit compositing defaults.
- `--incognito` intentionally trades persistence for clean private sessions; be careful around login, cookies, local storage, and sites that detect the WebView.
- Web apps restore the main window's last URL by default. `--no-restore-last-url` / config `restoreLastUrl: false` disables both reading and saving that URL without changing cookie or local-storage persistence. Legacy native configs missing `restore_last_url` default to true. Startup and close/exit persistence share `WindowConfig::remembers_last_url`, which excludes incognito sessions and local pages. Verify with `cargo test --lib` and `node tests/integration/last-url.mjs` (real macOS WebView).
diff --git a/AGENTS.md b/AGENTS.md
index 36291542..c37c394f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -17,6 +17,12 @@
`gallery/` holds site recipes for the Pake apps' gallery, `schema/pake.schema.json` the `--config` schema, `plugins/` the Claude Code and Codex plugin source, and `llms.txt` the agent-facing contract.
`default_app_list.json` lists the popular apps for release builds; `docs/` has `cli-usage.md`, `advanced-usage.md` and `faq.md`.
+**Key configuration files**:
+
+- `src-tauri/pake.json` - default app configuration (CLI options are merged into it at build time).
+- `src-tauri/tauri.conf.json` - shared Tauri settings.
+- `src-tauri/tauri.{macos,windows,linux}.conf.json` - per-platform overrides.
+
## Development Commands
| Command | Purpose |
@@ -36,11 +42,11 @@
## Code Conventions
-- No Chinese comments in any source (Rust / TypeScript / any file). Comments and identifiers in English; follow the existing language of surrounding prose.
+- No Chinese comments in any source (Rust / TypeScript / any file). Comments and identifiers in English; follow the existing language of surrounding prose. Gate: `scripts/check-source-bans.mjs` (run by `npx vitest run`).
## Working Principles
-- Generated areas (`dist/`, `node_modules/`, `src-tauri/target/`, `.app/`, `src-tauri/icons/`, `src-tauri/png/`) are not source. Exception: `dist/cli.js` is the shipped CLI build artifact (see `package.json` `files`); rebuild it via `pnpm run cli:build` and commit the regenerated file alongside the source change. Two things trigger a rebuild, not one: any change under `bin/`, and **any** change to `package.json`. Rollup inlines the whole manifest, so a dependency bump, a `pnpm.overrides` edit, an `engines` change, or a reworded `description` all leave `dist/cli.js` stale with no `bin/` diff to hint at it. Dependency-only PRs are the usual place this is missed.
+- Generated areas (`dist/`, `node_modules/`, `src-tauri/target/`, `.app/`, `src-tauri/icons/`, `src-tauri/png/`) are not source. Exception: `dist/cli.js` is the shipped CLI build artifact (see `package.json` `files`); rebuild it via `pnpm run cli:build` and commit the regenerated file alongside the source change. Two things trigger a rebuild, not one: any change under `bin/`, and **any** change to `package.json`. Rollup inlines the whole manifest, so a dependency bump, a `pnpm.overrides` edit, an `engines` change, or a reworded `description` all leave `dist/cli.js` stale with no `bin/` diff to hint at it. Dependency-only PRs are the usual place this is missed. Note `dist/` is gitignored while `dist/cli.js` is tracked, so stage it with `git add -f dist/cli.js`. `quality-and-test.yml` catches this on Linux by failing when `git diff -- dist/` is non-empty after a rebuild, so an unrebuilt artifact fails CI rather than shipping quietly.
- Release status, issue closeout, npm delivery, and GitHub assets are separate truth surfaces. Verify each one live (source commit/tag, workflow run, npm registry, GitHub Release/assets, issue state); never let one passing surface imply another.
## Review Hard Stops
@@ -48,28 +54,14 @@
Beyond the rebuild, version-sync, surface, CLI-flag, WebKit, and popup-routing invariants in this file and `.claude/rules/`, a review blocks on:
- npm release workflow changes that drop Trusted Publishing: `.github/workflows/npm-publish.yml`, `id-token: write`, canonical `git+https://github.com/tw93/Pake.git`, and `scripts/check-release-version.mjs` must survive.
-- A new helper in `bin/utils/` or `bin/helpers/` without a matching `tests/unit/<basename>.test.ts`.
+- A new helper in `bin/utils/` or `bin/helpers/` without a matching `tests/unit/<basename>.test.ts` (gate: `scripts/check-source-bans.mjs`, which accepts `tests/unit/<basename>.test.ts`, `<basename>-*.test.ts` or `<basename>.*.test.ts`).
- A binary parser without a round-trip test.
## Hotspot Map
-For proactive latent-bug sweeps, pick one row and go deep; do not invent a whole-repo scope. The third column is **historical failure modes / regression risks**, not a claim that the tree is broken today. Prefer the matching risk areas in `.claude/rules/` invariant when judging a change.
-
-| Hotspot | Paths | Regression risk if reintroduced |
-| -------------------------- | -------------------------------------- | ------------------------------------------------------------------------------------------ |
-| Link / download heuristics | `src-tauri/src/inject/event.js` | SPA routes or Cmd/Ctrl+click treated as downloads; path roots too broad |
-| Download success semantics | `invoke.rs`, `window.rs` `on_download` | Non-2xx toasted as success; toast/IPC hardcoded to `"pake"`; request drops session cookies |
-| Menu / focused window | `menu.rs` | Commands hit the main window, not the focused one; eval dead on error pages |
-| Startup visibility | `lib.rs`, `setup.rs` | Blank shell, `about:blank` false ready, user hide racing fallback reveal |
-| Auth / popup | `auth.js`, `event.js` | Sign-in popup loses its opener or stays open, abort on its close, SSO in system browser |
-| Clipboard | `event.js` | keydown steals native paste; double-paste fallback |
-| Multi-window / icon | `window.rs`, `setup.rs` | Missing `reapply_window_icon` on show; secondary window toast/target; Cmd+N blank flash |
-| Platform capability | `auth.rs`, proxy, WebKit flags | Flag name present, platform no-op |
-| CLI / config contract | `bin/`, `schema/` | Config smuggles out-of-range values CLI rejects |
+For a proactive latent-bug sweep, read `.claude/references/hotspots.md` first: pick one row of its table and go deep, do not invent a whole-repo scope.
-Oracles per row live under `tests/unit/` (for example `event-link-guard.test.js`, `download-http-status.test.ts`, `menu-focused-window.test.ts`, `startup-window-reveal.test.ts`, `window-icon-reapply.test.ts`); Linux WebKit flag decisions are covered by the `dmabuf_renderer_*` and `legacy_x11_*` `cargo test` cases in `src-tauri/src/lib.rs`.
-
-## risk areas in `.claude/rules/`
+## Current Risk Areas
- Release state can be split. npm Trusted Publishing can succeed before the popular-app release workflow finishes, and GitHub Release assets can exist while a workflow run still shows queued or in progress. Report each surface explicitly.
- Local app builds and test runs mutate tracked files as build state: `src-tauri/pake.json`, `src-tauri/tauri.conf.json`, `src-tauri/tauri.macos.conf.json`, and regenerated icons under `src-tauri/png/` and `src-tauri/icons/`. Record `git status --short` for these paths before running the command. Afterwards, restore only paths that were clean in that baseline and whose new diff is provably generated by this run. If a path was already dirty or ownership is ambiguous, leave it untouched and rerun verification in an isolated worktree; never let a feature or release commit absorb this churn.
@@ -86,6 +78,7 @@ Claude Code loads each `.claude/rules/*.md` when a file matching its `paths:` is
- `.claude/rules/cli.md`: CLI surface, `--json`, build workspaces, caches.
- `.claude/rules/ci.md`: workflows, and which green CI steps are not evidence.
- `.claude/rules/release.md`: read before any release, version bump or tag.
+- `.claude/rules/docs.md`: READMEs, `docs/`, `default_app_list.json` and `gallery/`: README parameter scope, the popular-packages showcase, app list curation, no WeChat. Also read it when replying to a request to add or remove an app or to package WeChat.
## Platform-Specific Development
@@ -95,7 +88,7 @@ Claude Code loads each `.claude/rules/*.md` when a file matching its `paths:` is
- Runtime depends on `libwebkit2gtk` and its companion libraries.
- Icons: `.png`.
- WebKit compositing is platform-sensitive on Wayland; see `.claude/rules/tauri-runtime.md` before changing defaults.
-- Maintainer agents verify Linux-only behavior (GNU tools, `cargo test` on Linux cfg paths, `.deb`/AppImage builds, Linux issue repros) on a real Debian x86_64 machine through the private `linux-devbox` skill rather than reasoning from macOS. Contributors without it use any Ubuntu 24.04 machine, matching CI.
+- Maintainer agents verify Linux-only behavior (GNU tools, `cargo test` on Linux cfg paths, `.deb`/AppImage builds, Linux issue repros) on a real Debian x86_64 machine rather than reasoning from macOS. Contributors without one use any Ubuntu 24.04 machine, matching CI.
## Release Workflow (CI)
@@ -110,7 +103,7 @@ Pake uses official npm and Rust sources by default. CN mirrors are explicit opt-
## Issue Closeout After a Fix
-Default loop for a fixed user-reported CLI bug: ship the fix as an npm patch release first, then reply to the reporter with the concrete upgrade command (`npm install -g pake-cli@latest`, or `[email protected]` when `latest` may point elsewhere), then close the issue noting it can be reopened if the problem persists. Do not reply "fixed" pointing at an unreleased commit; the npm registry must return the fix version first. The publish itself follows the authorization rule in Release Workflow above.
+Default loop for a fixed user-reported CLI bug: ship the fix as an npm patch release first, then reply to the reporter with the concrete upgrade command (`npm install -g pake-cli@latest`, or `[email protected]` when `latest` may point elsewhere), then close the issue noting it can be reopened if the problem persists. Do not reply "fixed" pointing at an unreleased commit; the npm registry must return the fix version first. The publish itself follows the authorization rule in `.claude/rules/release.md` (each publish, tag, or issue-close action needs maintainer authorization in the current turn).
Keep `closes #N` / `fixes #N` out of commit messages for user-reported bugs. GitHub closes the issue the moment the commit reaches `main`, which is before npm has the fix, so the reporter sees a silent closure while still unable to get it. Reference the issue as a bare `#N` and close it by hand after the registry returns the fix version.
@@ -145,17 +138,4 @@ This file is already in `.gitignore`.
### `dist/cli.js` out of sync with its sources
-Symptom: tests or release builds use stale CLI behavior after a `bin/` or `package.json` edit. Fix with `pnpm run cli:build` and commit the regenerated `dist/cli.js`. Note `dist/` is gitignored while `dist/cli.js` is tracked, so stage it with `git add -f dist/cli.js`. `quality-and-test.yml` catches this on Linux by failing when `git diff -- dist/` is non-empty after a rebuild, so an unrebuilt artifact fails CI rather than shipping quietly.
-
-## Documentation Guidelines
-
-- **Main README**: keep only common, frequently-used parameters to avoid clutter.
-- **CLI Documentation** (`docs/cli-usage.md` and locale variants): include **all** CLI parameters with detailed usage examples.
-- **Rare or advanced parameters**: should have full documentation in `docs/cli-usage*.md` but minimal or no mention in the main README. Examples: `--title`, `--incognito`, `--system-tray-icon`, `--multi-window`, `--min-width`, `--min-height`.
-- **README popular-packages showcase**: apps render in pairs of `<td>` cells, each with a 600px-wide screenshot from `https://raw.githubusercontent.com/tw93/static/main/pake/<Title>.png` or `.jpg` (the showcase currently mixes both; source spec 2624x1784, a Retina window capture). Upload the screenshot to `tw93/static` before pushing the README row, and note the app's download links stay 404 until the next `V*` release builds its assets.
-- **App list curation**: judge showcase or `default_app_list.json` additions and removals with real demand from `gh release view <tag> --json assets` download counts, not intuition. Keep both README locales in the same order.
-- **No WeChat** (maintainer 2026-11-25): WeChat forbids sign-in from unofficial clients and restricts accounts that do it, so no WeChat app goes in `default_app_list.json`, the gallery or site styles, and the FAQ points users to the official client. A UOS-header workaround signed in once, then the account lost QR sign-in on new devices for about two weeks; it was reverted in `be66cccb`. Do not restore WeChat or suggest packaging wx.qq.com.
-- **Key configuration files**:
- - `src-tauri/pake.json` - default app configuration (CLI options are merged into it at build time).
- - `src-tauri/tauri.conf.json` - shared Tauri settings.
- - `src-tauri/tauri.{macos,windows,linux}.conf.json` - per-platform overrides.
+Symptom: tests or release builds use stale CLI behavior after a `bin/` or `package.json` edit. Fix with `pnpm run cli:build` and commit the regenerated `dist/cli.js`; staging and the CI check are in Working Principles above.
diff --git a/scripts/check-source-bans.mjs b/scripts/check-source-bans.mjs
new file mode 100644
index 00000000..d1102e1a
--- /dev/null
+++ b/scripts/check-source-bans.mjs
@@ -0,0 +1,474 @@
+// Source patterns the guidance forbids, held by a gate instead of prose.
+//
+// node scripts/check-source-bans.mjs [--self-test]
+//
+// Each ban below is written in AGENTS.md or a `.claude/rules/` file and is
+// mechanical enough that a scan decides it:
+//
+// - No Chinese comments in any source (AGENTS.md Code Conventions): CJK text
+// inside a comment. Strings are data (menu titles, dialog text, fixtures)
+// and never count. The comments listed in CJK_COMMENTS quote the literal
+// text a test or parser matches.
+// - A helper in `bin/utils/` or `bin/helpers/` needs a matching test in
+// `tests/unit/`: `<basename>.test.ts`, `<basename>-*.test.ts` or
+// `<basename>.*.test.ts` (AGENTS.md Review Hard Stops). The helpers listed
+// in UNTESTED_HELPERS predate the gate.
+// - In machine mode stdout carries one JSON result, so code in `bin/` never
+// names `process.stdout` (reading `isTTY`, `columns` or `rows` aside),
+// destructures `stdout` from `process`, or names a console method that
+// writes to stdout (`log`, `info`, `debug`, `dir`, `dirxml`, `table`,
+// `count`, `group`, `groupCollapsed`, `timeLog`, `timeEnd`), whether as
+// `console.x`, `console["x"]` or `const { x } = console`
+// (`.claude/rules/cli.md`). `warn`, `error`, `trace` and `assert` write to
+// stderr. STDOUT_WRITERS lists the one writer of the JSON result.
+// - No WeChat (`.claude/rules/docs.md`): `wx.qq.com` never appears in the app
+// list, the gallery, the READMEs, `.github/` or the source.
+//
+// The comment splitter is a line scanner, not a parser. It knows `//` and
+// `/* */` comments, `#` comments in shell, Python, YAML and TOML, quoted
+// strings, JS template literals, JS regex literals (by the token before the
+// slash), Rust multi-line and raw strings (`r"..."`, `r#"..."#`), Rust char
+// literals versus lifetimes, and an apostrophe inside a word in shell, YAML and
+// TOML (`don't`). Known limits: Python and Swift triple-quoted strings are
+// read as an empty string followed by code, a regex literal after `)` (as in
+// `if (x) /re/.test(s)`) is read as division, and a shell heredoc body is
+// read as code. A miss there can only hide a comment, never invent one in a
+// string, except a `#` inside a Python or Swift triple-quoted string.
+//
+// A list only shrinks: an entry that no longer matches fails, so drop it.
+// tests/unit/check-source-bans.test.ts runs the check and the self-test, so
+// `npx vitest run` (in release:check and the CI fast suite) fails on a ban.
+
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+export const ROOT = path.resolve(
+ path.dirname(fileURLToPath(import.meta.url)),
+ "..",
+);
+
+// file -> exact trimmed comment lines allowed to carry CJK text.
+export const CJK_COMMENTS = {
+ "src-tauri/src/app/invoke.rs": [
+ "/// `(3) Inbox`, `[12] Slack`, `(5)消息`, `【8】通知`, or `(99+) Chat`.",
+ ],
+ "src-tauri/src/app/nav_buttons.rs": [
+ "/// Back and Forward as the system's own web views name them: 返回 and 前进",
+ "/// in Simplified Chinese, 上一頁 and 下一頁 in Traditional (WebCore's strings).",
+ ],
+ "tests/unit/macos-script-dialogs.test.ts": [
+ '// AppKit binds Escape only to a button titled "Cancel"; 取消 is not.',
+ ],
+ "tests/unit/xiaohongshu-recipe.test.js": [
+ '// User intentionally clicks the "点点 AI" button -> manual open stays open!',
+ ],
+};
+
+export const UNTESTED_HELPERS = [
+ "bin/helpers/cli-program.ts",
+ "bin/helpers/tauriConfig.ts",
+ "bin/utils/dir.ts",
+ "bin/utils/info.ts",
+ "bin/utils/mirror.ts",
+ "bin/utils/output.ts",
+ "bin/utils/platform.ts",
+ "bin/utils/targets.ts",
+];
+
+// file -> exact trimmed code lines allowed to write to stdout.
+export const STDOUT_WRITERS = {
+ "bin/utils/output.ts": [
+ "process.stdout.write(`${JSON.stringify(result)}\\n`);",
+ ],
+};
+
+const CJK = new RegExp(
+ "[\\u3000-\\u303f\\u3040-\\u30ff\\u3400-\\u4dbf\\u4e00-\\u9fff\\uac00-\\ud7af\\uff00-\\uffef]",
+);
+const STDOUT_METHODS =
+ "log|info|debug|dir|dirxml|table|count|group|groupCollapsed|timeLog|timeEnd";
+const STDOUT = new RegExp(
+ [
+ `\\bconsole\\s*(?:\\.\\s*|\\[\\s*["'\`])(?:${STDOUT_METHODS})\\b`,
+ `\\{[^}]*\\b(?:${STDOUT_METHODS})\\b[^}]*\\}\\s*=\\s*console\\b`,
+ "\\bprocess\\s*\\.\\s*stdout\\b(?!\\s*\\.\\s*(?:isTTY|columns|rows)\\b)",
+ "\\{[^}]*\\bstdout\\b[^}]*\\}\\s*=\\s*process\\b",
+ ].join("|"),
+);
+const WECHAT = /wx\.qq\.com/;
+
+const SLASH_COMMENTS = /\.(?:rs|ts|tsx|js|mjs|cjs|swift|css)$/;
+const HASH_COMMENTS = /\.(?:sh|py|yml|yaml|toml)$/;
+const HELPER = /^bin\/(?:utils|helpers)\/([^/]+)\.ts$/;
+const WECHAT_SCOPE =
+ /^(?:default_app_list\.json|README[^/]*\.md|gallery\/|bin\/|src-tauri\/src\/|\.github\/)/;
+
+const JS = /\.(?:ts|tsx|js|mjs|cjs)$/;
+const REGEX_BEFORE =
+ /(?:^|[(,=:[!&|?{};+\-*%<>~^]|\b(?:return|typeof|case|in|of|delete|void|throw|new|yield|await))\s*$/;
+
+// Split a source file into comment text and code text, line by line, so a
+// ban can look at one without the other. Strings stay in the code text; a
+// comment marker inside a string is not a comment. The header lists what the
+// scanner knows and where it stops.
+export function splitComments(rel, text) {
+ const slash = SLASH_COMMENTS.test(rel);
+ const hash = HASH_COMMENTS.test(rel);
+ const rust = rel.endsWith(".rs");
+ const js = JS.test(rel);
+ const python = rel.endsWith(".py");
+ const out = [];
+ let block = false;
+ // An open string carried across lines: { close, raw, hashes }.
+ let open = null;
+ for (const line of text.split("\n")) {
+ let comment = "";
+ let code = "";
+ let continued = false;
+ for (let i = 0; i < line.length; i++) {
+ const ch = line[i];
+ const next = line[i + 1];
+ if (block) {
+ if (ch === "*" && next === "/") {
+ comment += "*/";
+ block = false;
+ i++;
+ } else comment += ch;
+ continue;
+ }
+ if (open) {
+ code += ch;
+ if (open.raw) {
+ if (ch === '"' && line.startsWith("#".repeat(open.hashes), i + 1)) {
+ code += "#".repeat(open.hashes);
+ i += open.hashes;
+ open = null;
+ }
+ } else if (ch === "\\") {
+ if (i + 1 >= line.length) continued = true;
+ code += next ?? "";
+ i++;
+ } else if (ch === open.close) open = null;
+ continue;
+ }
+ if (slash && ch === "/" && next === "/") {
+ comment += line.slice(i);
+ break;
+ }
+ if (slash && ch === "/" && next === "*") {
+ block = true;
+ comment += "/*";
+ i++;
+ continue;
+ }
+ if (hash && ch === "#") {
+ comment += line.slice(i);
+ break;
+ }
+ if (js && ch === "/" && REGEX_BEFORE.test(code)) {
+ // A regex literal runs to the next unescaped slash outside a class.
+ let j = i + 1;
+ let inClass = false;
+ for (; j < line.length; j++) {
+ if (line[j] === "\\") j++;
+ else if (line[j] === "[") inClass = true;
+ else if (line[j] === "]") inClass = false;
+ else if (line[j] === "/" && !inClass) break;
+ }
+ code += line.slice(i, j + 1);
+ i = j;
+ continue;
+ }
+ if (rust && (ch === "r" || ch === "b") && !/[\w]$/.test(code)) {
+ const raw = /^b?r(#*)"/.exec(line.slice(i));
+ if (raw) {
+ code += raw[0];
+ i += raw[0].length - 1;
+ open = { raw: true, hashes: raw[1].length };
+ continue;
+ }
+ }
+ if (rust && ch === "'") {
+ // A char literal ('x', '\n', a full-width bracket); anything else is a
+ // lifetime.
+ const literal = /^'(?:\\.|[^\\'])'/u.exec(line.slice(i));
+ if (literal) {
+ code += literal[0];
+ i += literal[0].length - 1;
+ continue;
+ }
+ code += ch;
+ continue;
+ }
+ if (hash && !python && ch === "'" && /\w$/.test(code)) {
+ // An apostrophe inside a word (don't), not a quote.
+ code += ch;
+ continue;
+ }
+ if (ch === '"' || ch === "'" || (ch === "`" && (js || slash))) {
+ open = { close: ch, raw: false };
+ code += ch;
+ continue;
+ }
+ code += ch;
+ }
+ // Template literals, Rust strings and an escaped line end span lines.
+ if (
+ open &&
+ !open.raw &&
+ !continued &&
+ open.close !== "`" &&
+ !(rust && open.close === '"')
+ ) {
+ open = null;
+ }
+ out.push({ comment, code });
+ }
+ return out;
+}
+
+function listedLines(found, rel, allowed, seen, label) {
+ for (const line of allowed[rel] ?? []) {
+ if (!seen.has(line)) {
+ found.push(`${rel}: listed in ${label} but no longer has: ${line}`);
+ }
+ }
+}
+
+export function problems(files) {
+ const found = [];
+ const helperTests = Object.keys(files).filter((rel) =>
+ /^tests\/unit\/[^/]+\.test\.ts$/.test(rel),
+ );
+ const untested = new Set();
+ for (const rel of Object.keys(files).sort()) {
+ const text = files[rel];
+ const commented =
+ SLASH_COMMENTS.test(rel) || HASH_COMMENTS.test(rel)
+ ? splitComments(rel, text)
+ : null;
+
+ if (commented) {
+ const seen = new Set();
+ const allowed = new Set(CJK_COMMENTS[rel] ?? []);
+ commented.forEach(({ comment }, i) => {
+ if (!CJK.test(comment)) return;
+ const line = text.split("\n")[i].trim();
+ if (allowed.has(line)) seen.add(line);
+ else found.push(`${rel}:${i + 1}: Chinese text in a comment`);
+ });
+ listedLines(found, rel, CJK_COMMENTS, seen, "CJK_COMMENTS");
+ }
+
+ const helper = HELPER.exec(rel);
+ if (helper && !/\.(?:test|spec|d)\.ts$/.test(rel)) {
+ const name = helper[1];
+ const matching = (test) =>
+ test === `tests/unit/${name}.test.ts` ||
+ test.startsWith(`tests/unit/${name}-`) ||
+ test.startsWith(`tests/unit/${name}.`);
+ if (!helperTests.some(matching)) {
+ untested.add(rel);
+ if (!UNTESTED_HELPERS.includes(rel)) {
+ found.push(
+ `${rel}: helper without a tests/unit/${name}.test.ts, ${name}-*.test.ts or ${name}.*.test.ts`,
+ );
+ }
+ }
+ }
+
+ if (rel.startsWith("bin/") && rel.endsWith(".ts") && commented) {
+ const seen = new Set();
+ const allowed = new Set(STDOUT_WRITERS[rel] ?? []);
+ commented.forEach(({ code }, i) => {
+ if (!STDOUT.test(code)) return;
+ const line = text.split("\n")[i].trim();
+ if (allowed.has(line)) seen.add(line);
+ else found.push(`${rel}:${i + 1}: writes to stdout in bin/`);
+ });
+ listedLines(found, rel, STDOUT_WRITERS, seen, "STDOUT_WRITERS");
+ }
+
+ if (WECHAT_SCOPE.test(rel)) {
+ const body = commented
+ ? commented.map(({ code }) => code).join("\n")
+ : text;
+ if (WECHAT.test(body))
+ found.push(`${rel}: packages wx.qq.com (No WeChat)`);
+ }
+ }
+ for (const rel of UNTESTED_HELPERS) {
+ if (!untested.has(rel)) {
+ found.push(
+ `${rel}: listed in UNTESTED_HELPERS but now tested or gone; drop the entry`,
+ );
+ }
+ }
+ for (const rel of [
+ ...Object.keys(CJK_COMMENTS),
+ ...Object.keys(STDOUT_WRITERS),
+ ]) {
+ if (!(rel in files))
+ found.push(`${rel}: listed but no longer exists; drop the entry`);
+ }
+ return found;
+}
+
+const SCANNED = new RegExp(
+ `${SLASH_COMMENTS.source}|${HASH_COMMENTS.source}|^default_app_list\\.json$|^README[^/]*\\.md$|^gallery/`,
+);
+
+export function load() {
+ const out = spawnSync(
+ "git",
+ ["-C", ROOT, "ls-files", "--cached", "--others", "--exclude-standard"],
+ { encoding: "utf8" },
+ );
+ if (out.status !== 0) throw new Error("git ls-files failed");
+ const files = {};
+ for (const rel of out.stdout.split("\n").filter(Boolean)) {
+ if (rel.startsWith("dist/") || rel.startsWith("filters/")) continue;
+ if (!SCANNED.test(rel)) continue;
+ const full = path.join(ROOT, rel);
+ if (!fs.existsSync(full) || fs.lstatSync(full).isSymbolicLink()) continue;
+ files[rel] = fs.readFileSync(full, "utf8");
+ }
+ return files;
+}
+
+// One bad sample per ban, each of which must be caught, plus the forms each
+// ban must leave alone.
+export const SELF_TEST = {
+ caught: {
+ "Chinese comment": [
+ "src-tauri/src/app/sample.rs",
+ "// 中文注释\nfn a() {}\n",
+ ],
+ "Chinese block comment": ["bin/sample.ts", "/* 中文\n */\nexport {};\n"],
+ "untested helper": ["bin/utils/sample-helper.ts", "export const a = 1;\n"],
+ "stdout write": ["bin/builders/Sample.ts", 'console.log("built");\n'],
+ "stdout write via process": [
+ "bin/builders/Sample.ts",
+ "process.stdout.write('x');\n",
+ ],
+ "WeChat recipe": [
+ "default_app_list.json",
+ '[{"name": "wechat", "url": "https://wx.qq.com/"}]\n',
+ ],
+ "WeChat in a workflow": [
+ ".github/workflows/sample.yml",
+ "env:\n URL: https://wx.qq.com/\n",
+ ],
+ "Chinese # comment in Python": ["scripts/sample.py", "x = 1 # 中文\n"],
+ "Chinese # comment in YAML": [
+ ".github/workflows/sample.yml",
+ "on: push # 中文\n",
+ ],
+ "Chinese comment after an apostrophe": [
+ ".github/workflows/sample.yml",
+ "run: echo don't # 中文\n",
+ ],
+ "Chinese comment after a regex holding a backtick": [
+ "bin/sample.ts",
+ "const r = /`/; // 中文\n",
+ ],
+ "Chinese comment after a raw string ending in a backslash": [
+ "src-tauri/src/app/sample.rs",
+ 'let p = r"C:\\"; // 中文\n',
+ ],
+ "helper matched only by a longer name": [
+ "bin/helpers/icon-compose.ts",
+ "export const a = 1;\n",
+ ],
+ "stdout via a bracketed console method": [
+ "bin/builders/Sample.ts",
+ 'console["log"]("x");\n',
+ ],
+ "stdout via a console alias": [
+ "bin/builders/Sample.ts",
+ "const { log } = console;\n",
+ ],
+ "stdout via console.table": [
+ "bin/builders/Sample.ts",
+ "console.table(x);\n",
+ ],
+ "stdout as a pipe target": [
+ "bin/builders/Sample.ts",
+ "child.stdout.pipe(process.stdout);\n",
+ ],
+ },
+ ignored: {
+ "Chinese string": [
+ "src-tauri/src/app/sample.rs",
+ 'let s = "中文"; // ok\n',
+ ],
+ "Chinese char literal": [
+ "src-tauri/src/app/sample.rs",
+ "let c = '('; // x\n",
+ ],
+ "comment marker in a string": [
+ "src-tauri/src/app/sample.rs",
+ 'let u = "https://例子.测试/app";\n',
+ ],
+ "stdout in a comment": ["bin/builders/Sample.ts", "// console.log(x)\n"],
+ "WeChat in a comment": [
+ "src-tauri/src/app/sample.rs",
+ "// never wx.qq.com\n",
+ ],
+ "comment marker inside a Rust multi-line string": [
+ "src-tauri/src/app/sample.rs",
+ 'let s = "line one\n // 中文 still the string";\n',
+ ],
+ "Chinese in a YAML string": [
+ ".github/workflows/sample.yml",
+ 'default: "推特" # ok\n',
+ ],
+ "a stdout TTY check": [
+ "bin/builders/Sample.ts",
+ "const tty = process.stdout.isTTY;\n",
+ ],
+ "console.warn": ["bin/builders/Sample.ts", 'console.warn("x");\n'],
+ "a helper with a separated test name": [
+ "bin/utils/merge.ts",
+ "export const a = 1;\n",
+ ],
+ },
+};
+
+export function selfTest(base = load()) {
+ const failures = [];
+ if (problems(base).length) failures.push("the current tree is not clean");
+ for (const [name, [rel, text]] of Object.entries(SELF_TEST.caught)) {
+ if (problems({ ...base, [rel]: text }).length === 0) {
+ failures.push(`${name} was not caught`);
+ }
+ }
+ for (const [name, [rel, text]] of Object.entries(SELF_TEST.ignored)) {
+ if (problems({ ...base, [rel]: text }).length !== 0) {
+ failures.push(`${name} was flagged`);
+ }
+ }
+ return failures;
+}
+
+if (
+ process.argv[1] &&
+ path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)
+) {
+ if (process.argv.includes("--self-test")) {
+ const failures = selfTest();
+ for (const line of failures) console.log(`self-test: ${line}`);
+ console.log(
+ failures.length
+ ? "source-bans-self-test-failed"
+ : "source-bans-self-test-ok",
+ );
+ process.exit(failures.length ? 1 : 0);
+ }
+ const found = problems(load());
+ for (const line of found) console.log(`source ban: ${line}`);
+ if (!found.length) console.log("source-bans-ok");
+ process.exit(found.length ? 1 : 0);
+}
diff --git a/scripts/risk-tier.mjs b/scripts/risk-tier.mjs
index 21856b01..e1b19b11 100644
--- a/scripts/risk-tier.mjs
+++ b/scripts/risk-tier.mjs
@@ -14,6 +14,8 @@
//
// --self-check exits 1 when a tier pattern matches no tracked file: a rename
// would otherwise drop that file to the default tier without anyone noticing.
+// It also fails when a `paths:` glob in a `.claude/rules/*.md` file matches no
+// tracked file, since that rule would then never load.
// tests/unit/risk-tier.test.ts runs it.
import { spawnSync } from "node:child_process";
@@ -65,6 +67,7 @@ export const TIERS = [
".github/actions/*",
"tests/index.js",
"scripts/check-incidents.mjs",
+ "scripts/check-source-bans.mjs",
"scripts/risk-tier.mjs",
],
},
@@ -155,6 +158,77 @@ export function deadPatterns(
);
}
+// The `paths:` globs of every `.claude/rules/*.md` file, as Claude Code reads
+// them: `**` spans directories, `*` and `?` stay inside one path segment.
+export function ruleGlobs(dir = path.join(ROOT, ".claude", "rules")) {
+ let names;
+ try {
+ names = fs.readdirSync(dir).filter((name) => name.endsWith(".md"));
+ } catch {
+ return [];
+ }
+ return names.sort().flatMap((name) => {
+ const front = /^---\n([\s\S]*?)\n---/.exec(
+ fs.readFileSync(path.join(dir, name), "utf8"),
+ );
+ if (!front) return [];
+ return [...front[1].matchAll(/^\s+-\s+["']?([^"'\n]+?)["']?\s*$/gm)].map(
+ (match) => ({ rule: name, glob: match[1] }),
+ );
+ });
+}
+
+// `{a,b}` alternatives, expanded before matching (nested braces included).
+export function expandBraces(glob) {
+ const open = glob.indexOf("{");
+ if (open === -1) return [glob];
+ let depth = 0;
+ let start = open + 1;
+ const options = [];
+ for (let i = open; i < glob.length; i++) {
+ if (glob[i] === "{") depth++;
+ else if (glob[i] === "}" && --depth === 0) {
+ options.push(glob.slice(start, i));
+ const rest = glob.slice(i + 1);
+ return options.flatMap((option) =>
+ expandBraces(glob.slice(0, open) + option + rest),
+ );
+ } else if (glob[i] === "," && depth === 1) {
+ options.push(glob.slice(start, i));
+ start = i + 1;
+ }
+ }
+ return [glob];
+}
+
+export function globMatches(file, glob) {
+ const globs = expandBraces(glob);
+ if (globs.length > 1 || globs[0] !== glob) {
+ return globs.some((one) => globMatches(file, one));
+ }
+ let source = "";
+ for (let i = 0; i < glob.length; i++) {
+ const ch = glob[i];
+ if (ch === "*" && glob[i + 1] === "*") {
+ const slash = glob[i + 2] === "/";
+ source += slash ? "(?:.*/)?" : ".*";
+ i += slash ? 2 : 1;
+ } else if (ch === "*") source += "[^/]*";
+ else if (ch === "?") source += "[^/]";
+ else source += ch.replace(/[.+^${}()|[\]\\]/g, "\\$&");
+ }
+ return new RegExp(`^${source}$`).test(file);
+}
+
+export function deadRuleGlobs(
+ tracked = git("ls-files", "--cached", "--others", "--exclude-standard"),
+ globs = ruleGlobs(),
+) {
+ return globs
+ .filter(({ glob }) => !tracked.some((file) => globMatches(file, glob)))
+ .map(({ rule, glob }) => `.claude/rules/${rule}: ${glob}`);
+}
+
// Circuit breaker: once users met BREAKER_ROWS defects within BREAKER_DAYS (docs/incidents.md, by Reported
// date), every change that reaches a tier also needs the full gate, and the layers those defects slipped past are
// named so they are tightened first. It clears on its own as the rows age out; a future date is never counted.
@@ -230,7 +304,7 @@ if (
) {
const args = process.argv.slice(2);
if (args.length === 1 && args[0] === "--self-check") {
- const dead = deadPatterns();
+ const dead = [...deadPatterns(), ...deadRuleGlobs()];
for (const row of dead) console.log(`${row} matches no tracked file`);
process.exit(dead.length ? 1 : 0);
}
diff --git a/tests/unit/check-source-bans.test.ts b/tests/unit/check-source-bans.test.ts
new file mode 100644
index 00000000..cb1cf832
--- /dev/null
+++ b/tests/unit/check-source-bans.test.ts
@@ -0,0 +1,44 @@
+import { describe, it, expect } from 'vitest';
+import {
+ CJK_COMMENTS,
+ SELF_TEST,
+ UNTESTED_HELPERS,
+ load,
+ problems,
+ selfTest,
+} from '../../scripts/check-source-bans.mjs';
+
+const base = load();
+
+describe('source bans', () => {
+ it('passes on the current tree', () => {
+ expect(problems(base)).toEqual([]);
+ });
+
+ it.each(Object.entries(SELF_TEST.caught))('catches %s', (_, [rel, text]) => {
+ expect(problems({ ...base, [rel]: text })).not.toEqual([]);
+ });
+
+ it.each(Object.entries(SELF_TEST.ignored))(
+ 'leaves alone %s',
+ (_, [rel, text]) => {
+ expect(problems({ ...base, [rel]: text })).toEqual([]);
+ },
+ );
+
+ it('fails a stale allowlist entry', () => {
+ const [rel] = Object.keys(CJK_COMMENTS);
+ expect(problems({ ...base, [rel]: '' })).toContainEqual(
+ expect.stringContaining('listed in CJK_COMMENTS'),
+ );
+ const helper = UNTESTED_HELPERS[0];
+ const name = helper.split('/').pop()!.replace(/\.ts$/, '');
+ expect(
+ problems({ ...base, [`tests/unit/${name}.test.ts`]: '' }),
+ ).toContainEqual(expect.stringContaining('listed in UNTESTED_HELPERS'));
+ });
+
+ it('passes its own self-test', () => {
+ expect(selfTest(base)).toEqual([]);
+ });
+});
diff --git a/tests/unit/risk-tier.test.ts b/tests/unit/risk-tier.test.ts
index af9f282d..96bc1aad 100644
--- a/tests/unit/risk-tier.test.ts
+++ b/tests/unit/risk-tier.test.ts
@@ -6,6 +6,9 @@ import {
TIERS,
tiersFor,
deadPatterns,
+ deadRuleGlobs,
+ expandBraces,
+ globMatches,
matches,
recentIncidents,
breakerLine,
@@ -21,6 +24,28 @@ describe('risk tiers', () => {
expect(deadPatterns()).toEqual([]);
});
+ it('matches every rule paths glob against a tracked file', () => {
+ expect(deadRuleGlobs()).toEqual([]);
+ });
+
+ it('reports a rule glob that a rename left behind', () => {
+ expect(
+ deadRuleGlobs(['README.md'], [{ rule: 'x.md', glob: 'gone/**' }]),
+ ).toEqual(['.claude/rules/x.md: gone/**']);
+ expect(globMatches('src-tauri/src/app/menu.rs', 'src-tauri/**')).toBe(true);
+ expect(globMatches('README_CN.md', 'README*.md')).toBe(true);
+ expect(globMatches('docs/README.md', 'README*.md')).toBe(false);
+ expect(globMatches('src/a.rs', 'src/*.{rs,toml}')).toBe(true);
+ expect(globMatches('src/a.toml', 'src/*.{rs,toml}')).toBe(true);
+ expect(globMatches('src/a.js', 'src/*.{rs,toml}')).toBe(false);
+ expect(globMatches('src/{a,b}.rs', 'src/{a,b}.rs')).toBe(false);
+ });
+
+ it('expands nested brace alternatives', () => {
+ expect(expandBraces('a.{x,{y,z}}')).toEqual(['a.x', 'a.y', 'a.z']);
+ expect(expandBraces('plain')).toEqual(['plain']);
+ });
+
it('reports a pattern that a rename left behind', () => {
expect(deadPatterns(['README.md'])).toContain(
'publish: .github/workflows/npm-publish.yml',