Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(ok): harden the no-comments substrate and gate shell (#4262)

Nick Gomez4f9545ca0556
diff --git a/.changeset/no-comments-substrate-hardening.md b/.changeset/no-comments-substrate-hardening.md
new file mode 100644
index 000000000..925b0e2e7
--- /dev/null
+++ b/.changeset/no-comments-substrate-hardening.md
@@ -0,0 +1,10 @@
+---
+'@inkeep/open-knowledge': patch
+---
+
+Internal tooling and repository hygiene, with one adopter-visible behavior change: the
+no-comments scope config now refuses to load a hash family whose declared extensions map to
+a dialect with no measured lexer reference, instead of silently gating verdicts (and `--write`
+strip ranges) on a lexer nothing checks. No configuration in this repo or its mirror trips it
+(`no-comments.config.jsonc` declares only `shell` and `yaml`, both referenced), but a fork that
+declared a `.py` hash family goes from loading to a hard refusal with no deprecation window.
diff --git a/AGENTS.md b/AGENTS.md
index c5ae5b146..6e09ef96f 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -51,11 +51,12 @@ pnpm run dev
Keep only these, and nothing else:
-- **Directives a tool parses**, anchored at the comment's first line: `biome-ignore lint/style/noVar: reason`, `@ts-expect-error the fixture is deliberately malformed` (a reason is required), `oxlint-disable-next-line`, `@vitest-environment jsdom`, `@ts-nocheck`, `prettier-ignore`, `@vite-ignore`, `/// <reference types="vite/client" />`, `SPDX-License-Identifier: GPL-3.0-or-later`, `/* @lintignore knip cannot see the dynamic import site */` (block or JSDoc form only; the line-comment form is rejected because knip does not read it). If a tool reads it, it is code.
+- **Directives a tool parses**, anchored at the comment's first line: `biome-ignore lint/style/noVar: reason`, `@ts-expect-error the fixture is deliberately malformed` (a reason is required), `oxlint-disable-next-line`, `@vitest-environment jsdom`, `@ts-nocheck`, `@vite-ignore`, `/// <reference types="vite/client" />`, `SPDX-License-Identifier: GPL-3.0-or-later`, `/* @lintignore knip cannot see the dynamic import site */` (block or JSDoc form only; the line-comment form is rejected because knip does not read it). If a tool reads it, it is code.
- **JSDoc carrying `@deprecated`.** The allowlist also defines an audit-tag class, but its tag list is empty in this repo, so that class admits nothing here: a tag-bearing JSDoc block is rejected as prose.
- **Contract markers**, which the comment must BEGIN with: `STOP: a cross-file contract a reader must not break`, `WARN: a sibling that silently drifts if this changes`, `UPSTREAM(electron/electron#19920): a code shape forced on us from outside this repo`.
-- **A validated citation**, as in `precedent #42`.
-- **Registered guard markers**, each of which a specific checker reads: `error-log-shape-ok: <why>`, `presence-exempt: <why>`, and `documented exemption from Precedent #30`. The set is fixed — you cannot invent a new one.
+- **A validated citation**, as in `precedent #42`; the numbered titles are listed in [`PRECEDENTS.md`](./PRECEDENTS.md) at the repo root.
+- **Registered guard markers**: write `error-log-shape-ok: <why>` and `presence-exempt: <why>` only. The predicate also admits `documented exemption from Precedent #30`, `Defect class: <slug>` and `TOLERATED: <why>`, but their checkers live in test trees the mirror does not carry, so lint accepts them here while nothing reads them — that is prose wearing a marker, and it is a review finding even though the gate is green. The set is fixed; you cannot invent a new one.
+- **Type-only JSDoc**, in a .mjs or .js file only: a JSDoc block whose every line is a bare type annotation, which is the only typing mechanism the JavaScript strata have. Two hard edges: a description after the identifier makes the block prose, and the same block in a .ts file is prose, because TypeScript has real syntax there.
An `UPSTREAM` referent must be one of four shapes, so it always resolves to something a reader can look up: a GitHub issue (`electron/electron#19920`), an RFC (`RFC 9457`), a CommonMark section (`CommonMark §6.5`), or a package version (`[email protected]`). Anything else fails lint.
@@ -65,6 +66,8 @@ A marker is not a license, and passing lint is not the same as being legitimate.
If `pnpm run lint` fails on a comment, the diagnostic names the class, the fix, and a link into [`lint-plugins/no-comments/README.md`](./lint-plugins/no-comments/README.md), which is the full policy. Delete the comment, or convert it to one of the forms above.
+Shell scripts are declared in scope by `no-comments.config.jsonc`, but the sweep that reads the hash grammars is not part of this mirror, so `pnpm run lint` here checks the JavaScript and TypeScript families only. A `.sh` file is gated upstream; the same policy applies to it, and a reviewer will hold it to that.
+
## Public Mirror Rules
- This repo is generated from an allowlist. Do not rely on hidden source-only folders being present.
diff --git a/PRECEDENTS.md b/PRECEDENTS.md
new file mode 100644
index 000000000..cfab60ba1
--- /dev/null
+++ b/PRECEDENTS.md
@@ -0,0 +1,143 @@
+# Architectural Precedents
+
+Titles index for the architectural precedents that Open Knowledge code cites as `precedent #N`. Numbers are a stability contract: a slot is never renumbered and never reused, so a citation resolves to the same rule for as long as the code carries it. A rule that was withdrawn keeps its slot and is marked below.
+
+60 numbered slots, 57 active, 3 retracted.
+
+## Convention & discipline (precedents 1–8)
+
+1. **Typed transaction origins.**
+2. **Generic primitives over specific ones.**
+3. **Structured event schemas.**
+4. **Shared computation, per-surface rendering.**
+5. **Contract-first MCP tools.**
+6. **Mode state as enums.**
+7. **Remove broken capabilities rather than shipping them.**
+8. **Separate long-lived identity from short-lived session concerns.**
+
+## CRDT bridge & schema (precedents 9–14, 28, 38)
+
+9. **Schema is add-only forever.**
+10. **Opaque-but-content-bearing nodes for Y.Item identity.**
+11. **Minimize CRDT mutation in sync bridges.**
+12. **[RETRACTED — superseded by precedent #38 (Y.Text-is-truth contract).]**
+13. **Bridge invariants are auto-enforced and property-verified.**
+14. **Cross-CRDT sync is single-writer, server-side.**
+28. **Direct PM dispatch for nested editors.**
+38. **Y.Text-is-truth contract: Y.Text holds user-intended source-form bytes; XmlFragment derives via `parse(ytext)`.**
+
+## Markdown pipeline (precedents 15–17)
+
+15. **Idempotent micromark-extension attachers.**
+16. **Phase-ordered visitor dispatchers when passes consume each other's output.**
+17. **Byte-for-byte equivalence validators gate high-risk refactors.**
+
+## UI / React patterns (precedents 18, 19, 21, 29, 30)
+
+18. **Hybrid Activity + Suspense + `use(promise)` for subscription-source async primitives.**
+19. **Clipboard pipeline is mdast-canonical with per-view hook mechanisms.**
+21. **Ancestor-priority for auto-revealing tree-state derivations.**
+29. **Compound components use DOM data-attributes to bridge across NodeView portal boundaries.** RETRACTED.
+30. **All user content visible and editable (no hidden content).**
+
+## Testing, tooling, infra (precedents 20, 22, 23)
+
+20. **E2E test infrastructure conventions.**
+22. **Shell-script conventions for repo tooling.**
+23. **Async socket errors on closing sockets are caught at the boundary, not pre-filtered in userspace.**
+
+## Actor identity & attribution (precedents 24, 25)
+
+24. **Per-session actor identity at the CRDT origin layer.**
+25. **Classified writer IDs + subject-prefix action encoding in the shadow repo.**
+
+## Perf + V2 editor architecture (precedents 26–27)
+
+26. **Perf instrumentation as first-class.**
+27. **V2 editor cache + InteractionLayer + Option E split walker (2026-04-20) + cv-auto block-chunked render (2026-04-30).**
+
+## Selection & chrome architecture (precedents 31–37)
+
+31. **Selection state as typed PM PluginState.**
+32. **`data-*` attributes over className toggling for composable states in React-rendered NodeViews.**
+33. **CSS custom-property tokens scoped via `[data-component-type]` for per-block-type theming.**
+34. **Innermost-wins visible chrome, ancestor propagation via state (not `:has()`).**
+35. **Floating UI is the canonical positioning primitive for selection-anchored overlays.**
+36. **A11y codified in the selection plugin, not retrofitted per-block.**
+37. **Asset-click dispatch is a single shared surface.**
+
+## API surface discipline (precedent 39)
+
+39. **HTTP `/api` routes emit RFC 9457 problem details on errors and a flat success body keyed by HTTP status.**
+
+## Cross-process state mirroring (precedent 40)
+
+40. **Renderer-state↔main-state propagation: typed-IPC push + show-gate dual-signal + build-time token resolution for cross-process value sharing.**
+
+## Connection-admission stacking (precedent 41)
+
+41. **Connection-admission policies stack via `hocuspocus.configuration.extensions.push()` after identity threading; admission decisions that depend on a recently-removed cache consult the cache FIRST and use the on-disk file as a disambiguator only when the cache has an entry.**
+
+## Custom lint enforcement (precedent 42)
+
+42. **Custom lint enforcement is oxlint JS-plugin rules.**
+
+## Tier-3 React-runtime test substrate (precedent 43)
+
+43. **Tier-3 React-runtime tests (RTL mount under jsdom 29) run in a dedicated Vitest project (`packages/app/vitest.dom.config.ts`) with per-project `setupFiles` — never a global preload.**
+
+## Editor DOM-tree exclusivity + delete-then-recreate coordination (precedent 44)
+
+44. **TipTap `view.dom` DOM-tree exclusivity is a load-bearing OK invariant — `<EditorContent>` MUST render via `React.createPortal` to a per-Activity exclusively-owned DOM target; parked-state cache entries MUST own per-entry parking nodes; client `closeAndClearPersistence` and concurrent `pool.open` MUST coordinate via `pendingClears`; server-side `shouldUnloadDocument` MUST honor `forceUnload` unconditionally.**
+
+## JSX selection UX corrections (precedents 45–48)
+
+45. **`--selection-halo-inset` is uniform across substrates; per-substrate inset overrides are precluded.**
+46. **Customer-facing JSX descriptors with required string props key off key-absence, not empty-string, to surface the missing-decision state.**
+47. **Test-file substrate vocabulary is structurally checked against the registry via a meta-test.**
+48. **Block-level keyboard contract is structural, not mode-based; `KeyboardNav` is the canonical home.**
+
+## Electron host chrome safe area (precedent 49)
+
+49. **In-window full-viewport overlays must reserve the macOS traffic-light footprint via `--ok-titlebar-reserve-left`.**
+
+## Project locality for LLM-functional resources (precedents 50, 51)
+
+50. **Project locality for LLM-functional + reproducibility-sensitive resources.**
+51. **Every overlay primitive carries a one-line `motion-reduce:` opt-in inline on its Content (and SubContent where present) — the only OK divergence from shadcn `radix-nova` upstream motion across the 7 overlay primitives (Dialog, Sheet, Popover, Select, Dropdown-menu, Context-menu, Tooltip).**
+
+## ~~Two-tier overlay-motion system — documented forks of the radix-nova preset~~ (precedent 52 — RETRACTED)
+
+52. **The 7 overlay primitives in the design system are organized into a two-tier motion system: a snappy tier (100ms transition-based enter / 0ms exit) for the 5 high-frequency primitives (Popover, Select, Dropdown-menu, Context-menu, Tooltip) — implemented as documented forks of the radix-nova shadcn preset's animation utilities — and a standard tier (200ms enter / 150ms exit) for the 2 low-frequency primitives (Dialog, Sheet), with Dialog additionally exposing a typed two-tier `transition?: 'standard' | 'snappy'` prop on DialogOverlay + DialogContent so the palette can opt into the snappy tier without forking the modal class set.** RETRACTED.
+
+## Category-aware overlay placement — generic dialogs center, command/search palettes top-anchor (precedent 53)
+
+**Overlay placement is category-aware, expressed via an inline className on the palette-category primitive (`CommandDialog`) — mirroring shadcn `radix-nova` upstream's own pattern.**
+
+## Structural lifecycle gates on mutating write spines (precedent 54)
+
+54. **Lifecycle-state refusal on mutating write spines is structural, expressed via a single typed-throw class + a single HTTP-response helper + a meta-test that scans every mutating route.**
+
+## Content scope predicate symmetry (precedent 55)
+
+55. **`ContentFilter` is the single source of truth for whether a path is in OK content scope; walkers may not augment it with local admission rules.**
+
+## Canonical link contract (precedent 56)
+
+56. **OK has two valid internal-link forms — relative (`./sibling.md`, `../folder/doc.md`) and root-absolute (`/folder/doc.md`, leading slash = content root) — and the substrate VALIDATES every outbound link at write time so a broken hybrid never ships silently.**
+
+## Per-write-path fidelity bar (precedent 57)
+
+57. **Every write surface declares its fidelity bar at the intake layer — byte-sacred or construct-canonical — never inside the serializer.**
+
+## One-transaction menu insertions (precedent 58)
+
+58. **A menu that deletes its trigger range and then inserts content MUST land both in one transaction; the menu item contributes steps, never a dispatch of its own.**
+
+## Project scoping for renderer storage names (precedent 59)
+
+59. **Every client-side persistent storage name whose collision domain is the ORIGIN must be scoped to the project through `scopedStorageKey` (`packages/app/src/lib/storage-scope.ts`), or explicitly justify itself as app-global.**
+
+## Native-handoff transport carries path and prompt only (precedent 60)
+
+60. **A native-handoff deep link carries a folder or workspace path plus a short directive prompt — never a `file=` attach param and never whole-doc bytes; the receiving agent grounds by reading the doc through the OpenKnowledge MCP server.**
diff --git a/knip.config.ts b/knip.config.ts
index 177c46d2e..54958b470 100644
--- a/knip.config.ts
+++ b/knip.config.ts
@@ -1,14 +1,23 @@
-import { existsSync } from 'node:fs';
+import { existsSync, readdirSync } from 'node:fs';
import type { KnipConfig } from 'knip';
const fidelityOnlyAppDeps = existsSync('packages/app/tests/fidelity')
? []
: ['fast-check', 'commonmark.json', 'remark-mdx', 'remark-parse'];
+const PREDICATE_DIR = 'lint-plugins/no-comments';
+
+const differentialOnlyRootDeps =
+ existsSync(PREDICATE_DIR) &&
+ readdirSync(PREDICATE_DIR).some((entry) => entry.includes('.private.'))
+ ? []
+ : ['yaml'];
+
export default {
tags: ['-lintignore'],
ignore: ['plugins/*/skills/*/scripts/**'],
ignoreDependencies: [
+ ...differentialOnlyRootDeps,
'lint-staged', // not sure if it's false positive
'husky',
'@lingui/babel-plugin-lingui-macro',
diff --git a/lint-plugins/no-comments/README.md b/lint-plugins/no-comments/README.md
index 6081f3e21..982931504 100644
--- a/lint-plugins/no-comments/README.md
+++ b/lint-plugins/no-comments/README.md
@@ -9,11 +9,18 @@ module so that every consumer runs the *same* predicate:
| Consumer | Lane | Why it exists |
|---|---|---|
-| `oxlint` JS-plugin rule | `pnpm lint`, pre-push, CI, editor squiggles | blocking feedback where you already read diagnostics |
-| backstop sweep (`scripts/no-comments-sweep.test.mjs`) | `pnpm check` | suppression-blind and oxlint-version-independent — a rule disable cannot silence it |
+| `oxlint` JS-plugin rule | `pnpm lint`, pre-push, CI, editor squiggles | blocking feedback where you already read diagnostics; the JS families only, since oxlint parses no hash grammar |
+| backstop sweep (`scripts/no-comments-sweep.mjs`) | `pnpm lint`, `pnpm check`, `lint-staged` | suppression-blind and oxlint-version-independent — a rule disable, a plugin-host regression, or a distribution that drops JS plugins cannot leave the declared scope unguarded |
| comment codemod | one-shot cleanup + rebase recipe | gate and codemod agree by construction, not by transcription |
| `PreToolUse` hook | write time | denies the comment before it is ever written |
+No off-the-shelf multi-language comment-*allowlist* linter was found when this was built, which
+is why it exists rather than being configured. The nearest single-language artifact is
+`eslint-plugin-no-comments`, a prefix-match allowlist; the nearest cross-language tool is
+`uncomment`, a tree-sitter deleter. The difference is the rule set: `uncomment` preserves
+TODO/FIXME and doc comments by default, a permissive blanket keyed on comment shape, where this
+registry admits a comment only when a tool this repository actually runs parses it.
+
## Running the rule
`pnpm lint` runs `oxlint --max-warnings 0 .`, which loads this plugin from the `jsPlugins`
@@ -44,13 +51,38 @@ quietly drops JS plugins cannot leave the repo unguarded.
## Running the sweep
-`pnpm check` runs the sweep as `scripts/no-comments-sweep.test.mjs`, which the Vitest script
-project picks up by glob. `node scripts/no-comments-sweep.mjs` runs the same pass by hand and
-prints a per-stratum report — files, comment lines, violations — which is where the cleanup's
-before-and-after numbers come from; `--all` lists every violation rather than the first 25.
+`pnpm lint` runs the sweep as its `lint:no-comments` step, and `pnpm check` runs it again as
+`scripts/no-comments-sweep.test.mjs`, which the Vitest script project picks up by glob.
+`node scripts/no-comments-sweep.mjs` runs the same pass by hand and prints a per-unit report —
+files, comment lines, violations — which is where the cleanup's before-and-after numbers come
+from; `--all` lists every violation rather than the first 25.
+
+Two flags aim it somewhere else. `--root <dir>` sweeps another tree, judged by that tree's own
+config, which is how an adopter runs this predicate without vendoring it. `--file <path>` judges
+only the paths it names and skips discovery, so the per-unit non-vacuity floor does not apply and
+a path no unit claims exits 0 with an `out-of-scope:` line rather than a silent pass. The monorepo root's
+`lint-staged` block uses both in a single extension-free route, `public/open-knowledge/**`, so the
+config alone decides membership and the glob cannot drift from it. That block is this repository's;
+the public tree's own root block carries no such route. Every staged path reaches the
+sweep; one no unit claims prints `out-of-scope: <path> (no unit claims it; nothing was read)` and
+exits 0. That is how shell gets judged at commit, since the oxc language server hosts no shell
+grammar — and it puts a suppression-blind second read on the JS families too.
+
+`--help` prints the accepted grammar and exits 0; any other token the parser does not claim is
+refused rather than dropped. The three exit codes are the same contract the codemod's are, so one
+caller can branch on both:
+
+| code | meaning |
+| --- | --- |
+| 0 | the sweep ran and found no violation. In `--file` mode a path no unit claims lands here too, named on an `out-of-scope:` line |
+| 1 | the corpus is dirty: a violation was reported, or a declared unit that the config requires to be non-empty discovered no file. `--all` lists every violation rather than the first 25 |
+| 2 | the invocation was refused before any work: an unrecognized or repeated argument, a value-taking flag with no path, a `--file` outside `--root`, a scope config that does not load, or a precedent registry that does not load, printed as `precedent-registry: UNREADABLE` with the manifest key or the PRECEDENTS.md numbering problem behind it. Same meaning as the codemod's 2 |
-That script lives in the monorepo's `scripts/`, which is enumerated rather than mirrored, so this
-lane is upstream-only; the public tree keeps the oxlint rule.
+`scripts/no-comments-sweep.mjs` is upstream-only: `scripts/` is enumerated in the mirror manifest
+rather than globbed, and the sweep is not one of the entries, so it does not ship to the public
+repository; the public tree keeps the oxlint rule. The mirror strips both the
+`lint:no-comments` entry and its composite from the exported `package.json`, since a mirrored
+script naming an unmirrored file is the PR #599 bug class.
Both lanes enforce at `error` severity over a corpus at zero violations, and a test pins them
to the same value so neither can be turned off without the other.
@@ -65,10 +97,31 @@ uncleaned stock is never blocked by comments it did not write.
`ALLOW_OK_COMMENT_EDIT=<repo-relative-path>` waves one edit through, and only for the paths it
names (comma-separate several). The bare `=1` form is retired: a wholesale valve silenced the
-lane for every path at once, which is exactly when it should still be speaking. The hook fails open — no `jq`, no `node`, or no
-evaluator means it exits silently — because `pnpm lint` and `pnpm check` are the blocking floors
-and this lane only moves the feedback earlier. Harnesses that do not run hooks are covered by the
-staged `oxlint` pass in `lint-staged`.
+lane for every path at once, which is exactly when it should still be speaking. The hook fails open — for instance no `jq`,
+no `node`, no evaluator, or a payload its own `jq` probe cannot read means it exits silently — because `pnpm lint` and
+`pnpm check` are the blocking floors and this lane only moves the feedback earlier. It also exits silently on any
+GitHub Actions runner (`GITHUB_ACTIONS` set to a non-empty value), for a different reason: the evaluator is
+discovered by walking up from the edited file, so on a runner that tree is a PR checkout and the hook would execute
+PR-authored node inside a session that holds a review token. In
+this monorepo, harnesses that do not run hooks are covered at
+commit by the staged sweep: the extension-free `public/open-knowledge/**` route in the monorepo
+root's `lint-staged` block sends every staged in-scope path through it, whatever its family, and a
+suppression cannot silence it; the staged `oxlint` pass adds the rule's own diagnostics on top, for
+the `{ts,tsx,mjs}` paths it names. In the public repository none of that lane exists, and no other
+commit-time lane replaces it: the mirror ships the rule but not the sweep, the codemod or the hook,
+and it ships no `.husky/` directory either, so `prepare` returns without installing a git hook and
+the `lint-staged` block the mirrored `package.json` still carries is never invoked. There the rule
+is reached by running `pnpm run lint` — or `pnpm run check`, which begins with it — and by the
+monorepo-side gate a bridged pull request reaches.
+
+Where the hook fails open for a reason the author can act on — for instance a scope config it
+cannot read, a valve that suppressed a deny, or an evaluator that threw or crashed — it
+says so through `hookSpecificOutput.additionalContext`, the
+one `PreToolUse` field the host hands to the agent alongside the tool result. It emits no
+`permissionDecision` on those paths, so the edit still meets the host's ordinary permission
+evaluation rather than being waved past it; only a deny carries a decision. The same broken
+config is a hard failure in `pnpm lint`, the sweep and the codemod, each naming the config file
+and the key.
Like the sweep, the hook lives outside the mirrored tree, so it is upstream-only.
@@ -76,28 +129,66 @@ Like the sweep, the hook lives outside the mirrored tree, so it is upstream-only
### Tool-parsed directives
-`@ts-expect-error <reason>` (a reason is required), `biome-ignore <rule>: <reason>`,
-`oxlint-disable*` / `eslint-disable*`, `@vite-ignore`, `prettier-ignore`,
-`/// <reference …>`, `@vitest-environment`, `@ts-nocheck`, `@__PURE__`,
-`@__NO_SIDE_EFFECTS__`, `@preserve`, the JSX pragmas (`@jsx`, `@jsxFrag`, `@jsxRuntime`,
-`@jsxImportSource`), webpack magic comments, `//# sourceMappingURL=` / `//# sourceURL=`,
-`v8|c8|istanbul ignore`, `@ts-check`, `@lintignore <reason>` in JSDoc block form
-(knip reads it because `knip.config.ts` declares `tags: ['-lintignore']`, and knip only parses
-JSDoc, so a `// @lintignore` line comment is not machine-consumed and stays banned), and SPDX /
-`@license` headers.
+`@ts-expect-error <reason>` is judged ahead of the registry because its reason is mandatory: a bare
+one is `unreasoned-directive` rather than a directive. Every other admitted shape is a row below.
+
+| id | admitted shape | where the shape has to sit |
+|---|---|---|
+| `biome-ignore` | `biome-ignore {rule}: {reason}` | first body line |
+| `oxlint-disable` | `oxlint-disable` · `oxlint-enable` · `oxlint-disable-next-line` · `oxlint-disable-line` | first body line |
+| `eslint-disable` | `eslint-disable` · `eslint-enable` · `eslint-disable-next-line` · `eslint-disable-line` | first body line |
+| `vite-ignore` | `@vite-ignore` | first body line |
+| `triple-slash-reference` | `/// <reference types="x" />` | anywhere in the body |
+| `vitest-environment` | `@vitest-environment {env}` | first body line |
+| `ts-nocheck` | `@ts-nocheck` | first body line |
+| `ts-check` | `@ts-check` | first body line |
+| `license-header` | `SPDX-License-Identifier: {expression}` · `@license {terms}` | the opening lines |
+| `legal-comment` | `//! {banner}` · `/*! {banner} */` | the delimiter itself |
+| `pure-annotation` | `@__PURE__` · `#__PURE__` | first body line |
+| `no-side-effects-annotation` | `@__NO_SIDE_EFFECTS__` · `#__NO_SIDE_EFFECTS__` | first body line |
+| `preserve` | `@preserve` | first body line |
+| `jsx-pragma` | `@jsxRuntime {runtime}` · `@jsxImportSource {source}` | first body line |
+| `bundler-ignore` | `webpackIgnore: true` · `turbopackIgnore: true` · `turbopackOptional: true` | first body line |
+| `coverage-ignore` | `v8 ignore {what}` · `c8 ignore {what}` · `istanbul ignore {what}` | first body line |
+| `knip-lintignore` | `/** @lintignore {reason} */` | first body line, block form only |
+
+That table is not a summary of the code, it is compared to it: a drift test reads these rows and
+`DIRECTIVE_PATTERNS` in `allowlist.mjs` and fails when either carries an id or a shape the other does
+not. Documenting a shape here does not admit it, and admitting one there without a row reds.
+
+`knip-lintignore` is block-form only because knip reads it that way: `knip.config.ts` declares
+`tags: ['-lintignore']` and knip parses JSDoc, so a `// @lintignore` line comment is not
+machine-consumed and stays banned.
The build annotations are read by the bundlers this repo actually ships through: rolldown — the
engine under `tsdown`, which builds `core`, `server`, and `cli` — declares `@__PURE__`,
-`@__NO_SIDE_EFFECTS__`, and `@vite-ignore` as one `comments.annotation` class, and that option is
-the repo-side revocation knob the governability test asks for. Deleting one is the silent-green
-failure this allowlist exists to prevent: bundle output changes while typecheck, lint, and tests
-all stay green. The JSX pragmas are TypeScript's own per-file `commentPragmas`, and
-`//# sourceMappingURL=` detaches a source map when it is dropped.
+`@__NO_SIDE_EFFECTS__`, and `@vite-ignore` as one `comments.annotation` class, and `@license`,
+`@preserve`, `//!` and `/*!` as one `comments.legal` class. Both options are the repo-side
+revocation knob the governability test asks for. Deleting one is the silent-green failure this
+allowlist exists to prevent: bundle output changes while typecheck, lint, and tests all stay
+green. The JSX pragmas are TypeScript's own per-file `commentPragmas`. The bundler ignore keys are
+Turbopack's, measured on the version `docs` builds with: it rejects an unknown key and a wrong
+value alike, so `webpackIgnore: false` is prose and `webpackIgnore: true` is not.
+
+The legal-comment openers are the one class the gate cannot bound, and the reason is the consumer:
+rolldown preserves a comment because of the bang in its delimiter, whatever follows it. An essay
+behind `//!` therefore survives the gate, and it is a gaming finding at review rather than a
+gate failure — the same disposition every marker-as-license shape gets.
Directives must **begin** the comment, exactly as the tool that reads them requires. Prose that
merely mentions a directive (`// we should biome-ignore this later`) is prose. Shapes whose
-grammar takes exactly one argument are anchored on both ends, so `// @jsx is the pragma we should
-add` is prose while `/** @jsx h */` is a directive.
+grammar takes exactly one argument are anchored on both ends, so
+`// @jsxImportSource is what the app config already sets` is prose while
+`/** @jsxImportSource preact */` is a directive.
+
+"Begin the comment" means the directive is the comment's first non-blank body line, not merely a
+line somewhere inside it. A block comment that opens with a sentence and reaches its directive
+three lines down is an essay wearing a directive, and it is prose: the directive still reaches its
+tool, but the paragraph in front of it is exactly what this ban exists to delete. `@lintignore` is
+the one shape whose grammar forces a wrinkle here, since knip reads JSDoc blocks and not line
+comments: it is admitted only when the comment is block-form AND the tag is its headline, which is
+what the `block-headline` target in `DIRECTIVE_PATTERNS` means. Write
+`/** @lintignore <reason> */` and put the description in the type's name or the commit message.
A comment is code when three things hold: (1) a tool THIS REPO RUNS parses it; (2) the behavior
it buys is one the repo wants and can govern — a suppression the repo's own config cannot revoke
@@ -108,27 +199,98 @@ wherever the tool's grammar has room for one, as `@ts-expect-error <reason>`,
`biome-ignore <rule>: <reason>`, and `@lintignore <reason>` already do. A shape that satisfies
all three is added to `DIRECTIVE_PATTERNS` in `allowlist.mjs`, not argued about.
-Three shapes that look like directives are **excluded**, each failing part (1). `/* eslint-env … */`
-and `/* globals … */`: no ESLint is installed here, and oxlint 1.66 emits the identical `no-undef`
+Shapes that look like directives and are **excluded**. `/* eslint-env … */` and `/* globals … */`
+fail part (1): no ESLint is installed here, and oxlint 1.66 emits the identical `no-undef`
diagnostics whether or not the pragmas are present, so they buy nothing — its governable channel is
-the `env` / `globals` block in `.oxlintrc`, not a comment. `// #region` / `// #endregion`: an editor
-folding marker, read by no tool this repo runs, and the section-divider shape the ban exists to kill.
+the `env` / `globals` block in `.oxlintrc`, not a comment. `// #region` / `// #endregion` fails part
+(1) too: an editor folding marker, read by no tool this repo runs, and the section-divider shape the
+ban exists to kill. `//# sourceMappingURL=` / `//# sourceURL=` fail part (2): a bundler writes them
+into `dist/`, which this scope excludes, so no authored file in scope carries one and the class only
+ever admitted hand-written prose that happened to look like a pragma. `prettier-ignore` fails part
+(1): no workspace declares Prettier, and Biome reformats straight through the directive. The
+classic-runtime `@jsx` and `@jsxFrag` fail the reachability axis: every tsconfig here compiles with
+the automatic runtime, under which a factory pragma cannot apply. The eight non-`Ignore` webpack
+keys fail part (1): no workspace declares webpack, and Turbopack rejects them. `node-coverage ignore`
+was never a grammar at all — Node's own form is `node:coverage disable` — so it named no tool.
+
+### The two-axis admission table
+
+The three-part test above is enforced, not merely stated. Every entry in `DIRECTIVE_PATTERNS`
+carries its consumer as structured data, and `directive-consumers.test.mjs` resolves that claim
+against declarations already committed to this repository — never against `node_modules`, because
+resolution leaks across sibling worktrees and because an installed transitive is not a declared
+dependency. Four claim kinds cover the table:
+
+| kind | the bar it has to clear |
+|---|---|
+| `declared` | some workspace manifest declares the package, and a manifest that declares it runs the named script |
+| `transitive` | the carrier is declared and invoked, and the committed lockfile's `snapshots:` resolves the package under it |
+| `latent` | every named package is **absent**; the row carries what would activate it |
+| `external` | the consumer is outside this repo entirely, and the row records what it was admitted on |
+
+The latent bar is deliberately inverted. There is no consumer to reach, so the row asserts absence:
+wiring the tool in reddens the test and forces the row to be promoted to a claim someone recorded a
+reason for, rather than letting it become quietly true for a reason nobody wrote down.
+
+The second axis is reachability, and it is recorded per entry rather than derived, because two
+entries are kept in spite of it. `@ts-check` has a present consumer and no reach: no tsconfig sets
+`checkJs`, and it is admitted as the sibling of the live `@ts-nocheck`. `/// <reference …>` has a
+present consumer and a reach failure that is an encoded judgment about where the shape occurs, not a
+derived fact, so it stays. Both verdicts have a test behind them: a tsconfig that switches on
+`checkJs`, or one that goes back to the classic JSX runtime, reddens the table and names the row to
+revisit.
`@ts-ignore` is **banned** — it silently outlives the error it suppresses. Use
`@ts-expect-error <reason>`.
+### Which directives a file class admits
+
+A directive is licensed by the tool that parses it, and which tools reach a file is a property of
+that file's grammar and its role, not of the repository as a whole. So the registry is keyed twice —
+by grammar family, and by the file class within it — and every declared pair answers for itself:
+
+| grammar family | file class | the shapes it admits |
+|---|---|---|
+| `c-family` | `typescript` | the directive registry above |
+| `c-family` | `esm-script` | the directive registry above |
+| `hash-family` | `shell` | none |
+| `hash-family` | `yaml` | none |
+| `hash-family` | `python` | none |
+
+An undeclared pair is refused by name rather than defaulted, because a file class with no answer is
+a question nobody asked yet, and silently handing it the JavaScript registry would admit `@ts-nocheck`
+in a shell script.
+
+The three empty rows are the two-axis table applied per family, not an oversight. `# shellcheck` is
+the shape to reason about: it is a real directive with a real consumer, and nothing in this
+repository runs ShellCheck, so here it is prose and the cleanup deleted every one of them. Wire
+ShellCheck in and the row earns a shape through the same table every other row passed. A repository
+that already runs it starts with that row filled — the registry is data, and the file class is the
+level the data belongs at, since the same `# shellcheck` line inside a workflow's `run:` block is
+read by actionlint while the one in a `.sh` file here is read by nobody.
+
### Sanctioned audit tags
-A JSDoc block carrying one of the repo's sanctioned audit tags survives whole. The vocabulary is
-whatever `SANCTIONED_TAGS` holds in `allowlist.mjs`, pinned against its owning audit framework by a
-drift test. A repo that ships no such framework has an empty list, and then this class admits
-nothing — do not assume a tag-bearing JSDoc is allowed without checking `SANCTIONED_TAGS`.
+A JSDoc block carrying one of the repo's sanctioned audit tags survives whole, **but only in a
+file the framework that reads the tag actually scans**. The vocabulary is whatever
+`SANCTIONED_TAGS` holds in `allowlist.mjs`; the paths are `no-comments.tag-globs.generated.json`
+at the repo root, which lists one entry per consumer surface (its globs and the tags that surface
+reads). Both are pinned against the owning framework by drift tests, and the artifact is
+regenerated with `pnpm run generate:tag-globs`, which is upstream-only.
+
+The artifact is a per-repo registry, so it is deliberately absent from the public mirror: the
+public vocabulary is empty by construction, and a surface list naming private paths would put
+them on a public surface. A repo that ships no such framework has an empty vocabulary, an absent
+artifact, or both, and then this class admits nothing — do not assume a tag-bearing JSDoc is
+allowed without checking where the file sits.
-### `jsdoc-type` (`.mjs` / `.cjs` / `.js` only)
+### `jsdoc-type` (the `esm-script` family only)
A JSDoc block whose every line is a bare type annotation (`@type {…}`, `@param {…} x`,
`@returns {…}`, `@typedef`, `@template`, `@satisfies`, `@import {…} from '…'`) is admitted in
-the JavaScript strata, where it is the only typing mechanism the language has. Two hard edges:
+the JavaScript strata, where it is the only typing mechanism the language has. The class is
+gated on the file class rather than on a hard-coded extension list, so it follows whatever
+`esm-script` declares in `no-comments.config.jsonc` — `.mjs` and `.js` here. Two hard edges:
a description after the identifier makes the block prose (the `{type}` is the machine payload;
the sentence after it is exactly what the ban exists to kill), and the same block in a `.ts`
file is prose, because TypeScript has real syntax there.
@@ -148,23 +310,58 @@ A comment may begin with one of three markers:
- `WARN: <drift warning>` — a sibling that silently drifts if this changes.
- `UPSTREAM(<referent>): <constraint>` — a code shape forced from **outside** the repo.
-`UPSTREAM` referents are shape-validated: `owner/repo#N`, `RFC <n>`, `CommonMark §<n>`, or
-`pkg@<version>`. One shape-valid referent goes in the parentheses; supporting links (a fix PR,
-a second issue) belong in the marker body, where they survive untouched. The legitimacy line: the constraint's origin must be outside the repo — we
+`UPSTREAM` referents are shape-validated against a registry of their own:
+
+| id | referent form |
+|---|---|
+| `github-issue` | `owner/repo#N`, or a `github.com` issue or pull URL normalized to it |
+| `rfc` | `RFC <n>`, optionally with a section |
+| `commonmark` | `CommonMark §<n>` |
+| `package-version` | `pkg@<version>`, checked against the version this repo declares |
+
+Normalizing the URL form means the referent a browser hands you is accepted without rewriting. Several referents may be
+listed comma-separated when one constraint genuinely has two sources; each part is validated on its
+own and one unresolvable part rejects the marker, naming that part rather than the whole list. Prose
+about the referents still belongs in the marker body. The legitimacy line: the constraint's origin must be outside the repo — we
patch a dependency, work around its bug, conform to its spec, or absorb a platform quirk.
A surprise in *our own* code never earns a comment; reshape the code instead. Restating a
dependency's own documentation dies. Our bug in third-party costume dies.
### Validated precedent citations
-A comment containing `precedent #N` survives when `N` is a real slot in `PRECEDENTS.md`.
-Numbers come from the `## Section (precedents A, B, C)` headings — never from list ordinals,
-which drift. Retracted slots (`#12`, `#29`, `#52`) keep their numbers and stay citable.
-`PRECEDENTS.md` is not part of the public mirror; validation there runs from
-`precedent-numbers.generated.json`, a numbers-only manifest regenerated by
-`pnpm run generate:precedent-numbers` and pinned fresh by a drift test, so a fabricated
-citation is rejected on both surfaces. A tree with neither file fails loud rather than
-admitting citations.
+A comment containing `precedent #N` survives when `N` is a slot some entry in `PRECEDENTS.md`
+actually writes, and that entry is not retracted. Numbers come from the entries themselves — a
+list ordinal, or the section heading where the section body *is* the entry (`#53` is the only
+one of those today). Section headings are read too, but only to cross-check: a slot a heading
+claims and no entry writes, an entry no heading claims, and a number written twice are all
+parse errors, because each is half of an accidental renumbering. Retracted slots (`#12`, `#29`,
+`#52`) keep their numbers so the citations already in the tree still resolve, but a *new*
+citation of one is a violation — see `retracted-precedent` below.
+
+A citation licenses the reference, not the essay around it, so the class is capped: more than
+`CITATION_LINE_CAP` non-blank body lines and the comment is over it. Three lines at the repository's
+100-column width is about 280 characters, which holds a citing sentence and refuses a chapter. The
+cap is a cleanup-lane rule rather than a lint diagnostic — the codemod refuses an over-cap site,
+leaves its bytes untouched, and writes one record per site to a proposals channel of its own
+(`--proposals <path>`), never into the deletion manifest and never back into the file. Where the
+citing sentences already fit, the record carries a candidate built from those sentences alone and
+machine-checked three ways: it still classifies `precedent-citation`, it cites the same number set,
+and it sits inside the cap. Where they do not fit, or the comment shares its line with code, or the
+trimmed form would carry rot, the record is marked needs-judgment and carries no machine-authored
+prose. Applying a candidate and authoring the rest are an agent's job; the codemod has no
+comment-rewriting write mode, because the kept-comment survival net looks for a comment's bytes and
+a rewritten comment is not the bytes it kept.
+
+The registry itself is not part of the public mirror; the `PRECEDENTS.md` at the public root is a
+generated index of titles that no lane validates against. Validation runs from
+`precedent-numbers.generated.json`, an object manifest carrying a schema major and one record
+per slot (number, entry form, retracted flag), regenerated upstream by
+`pnpm run generate:precedent-numbers` - its generator is not mirrored - and pinned fresh by a
+drift test. Every lane reads that
+manifest — the in-tree lanes too, because the hook pays for `PRECEDENTS.md` on every keystroke
+and the drift test is what keeps the cheaper read honest. A manifest whose schema major this
+predicate does not know is named and refused, never silently coerced, so an older mirrored
+predicate meeting a newer manifest fails loud instead of admitting everything.
The manifest describes the tree it ships in, so it only stands in for that tree's
`PRECEDENTS.md`. Point the predicate at a different repository that has no `PRECEDENTS.md`
@@ -174,10 +371,42 @@ numbering has no authority over it.
### Guard-defined metacomment markers
-Machine-consumed escape channels owned by a specific guard: the `documented exemption from
-Precedent #30` marker, `error-log-shape-ok: <why>`, and `presence-exempt: <why>` (the
-agent-presence structural guard subtracts the sites it marks from its expected count). A new
-guard marker is only legal once it is registered in `GUARD_MARKERS`.
+Machine-consumed escape channels owned by a specific guard:
+
+| id | what reads it |
+|---|---|
+| `precedent-30-exemption` | the Precedent #30 static invariant, which strips the block a marked comment introduces before scanning for forbidden shapes |
+| `error-log-shape-ok` | the error-log discipline guard, which skips a marked log call |
+| `presence-exempt` | the agent-presence structural guard, which subtracts marked sites from its expected count |
+| `defect-class` | the lume rot-tier guard, which pairs each rostered runner with the class of rot it catches by reading the slug out of that runner's own header |
+| `tolerated-call-site` | the lume call-site polarity and failure-propagation guards, which read it as the written-down opt-out for a remote command whose status is deliberately discarded |
+
+Registering an id in `GUARD_MARKERS` is what makes a marker legal; an unregistered one is prose.
+Registration alone is not enough to keep it honest, so a companion test resolves each id to the guard
+that reads it and to the paths that guard scans, then fails on any marker sitting outside them — a
+copy pasted where no guard looks is prose wearing a marker, which is how this class gets gamed.
+
+### Markers that lead a comment are read only where a comment leads
+
+A guard marker and a licence header are the two classes whose token may legitimately sit below the
+first body line: a licence banner runs product line, copyright line, then `@license`, and a guard
+marker is often the second half of a short note. Matching them anywhere in the body is what let a
+twenty-six line essay survive on one marker buried two thirds of the way down — the marker as a
+license, which is the shape the anti-gaming rule calls high severity.
+
+So both classes read only the comment's **opening lines**: the first `OPENING_LINE_WINDOW` non-blank
+body lines, blank framing skipped. Three lines admits every real banner and refuses every essay, and
+the boundary is pinned in both directions — a marker on the last opening line is read, the same
+marker one line further down is prose. The residue is honest and worth stating: two lines of
+narration can still precede a marker inside the window, because nothing distinguishes a narration
+line from a banner line. What the window buys is that the laundering is bounded by a constant
+instead of by the author's patience.
+
+The SPDX form is anchored at both ends on its own line, so narration behind the identifier is prose
+too. That end anchor is why classification never sees a carriage return: `classificationText`
+strips it once, at the single site where the classifier reads a comment, so an end-anchored pattern
+is safe on a CRLF checkout by construction rather than by every future author remembering. The
+extractor is untouched — `comment.text` stays the byte-exact span the codemod looks for.
## Violation classes
@@ -195,13 +424,21 @@ disappears.
### unreasoned-directive
-`@ts-expect-error` with nothing after it. Append the reason inline.
+`@ts-expect-error` or `@lintignore` with nothing after it. Append the reason inline.
### invalid-precedent
A `precedent #N` citation whose number is not a slot in `PRECEDENTS.md`. Cite a real precedent
or drop the citation.
+### retracted-precedent
+
+A `precedent #N` citation whose slot was retracted. The slot survives so the citations written
+before the retraction still resolve to something, but the rule it names no longer holds, so the
+citation no longer licenses the comment. Cite the entry that superseded it, or state the
+constraint without a citation. Where neither is true the comment was never carrying a contract
+and goes.
+
### invalid-upstream-referent
`UPSTREAM(…)` whose referent matches none of the four accepted shapes. A referent that cannot be
@@ -237,19 +474,72 @@ the mirror cannot resolve. The infix is not an escape hatch from this policy —
file still ships INTERNALLY, still rots, and review holds it to the same bar; the gate skips it
only because the mirrored predicate cannot see it anyway.
-Source files across the package, script, docs, lint-plugin and root-config strata, minus an
-exclusion set that covers the audit framework's own tree, `*.private.*` files, the fidelity and
-lume-qa suites, fixtures, declaration files, generated locales, build output, and specific
-single-file carve-outs. `scope.mjs` holds both lists, and it is the one place they are written
-down; the gate, the sweep, the codemod, and the hook all read it from there. Read that file
-rather than a restatement here: this paragraph has drifted from it twice, because an enumeration
-in prose has nothing checking it.
+Scope is declared, not compiled in: `no-comments.config.jsonc` at the repository root names the
+grammar families (an extension list plus an extractor id), the named units that cross a family
+with a list of roots, and the exclusion set. Membership is DERIVED from `units[].roots` crossed
+with the family's extensions, plus any explicit `units[].files`; the walk roots and the
+directories discovery prunes derive from the same declaration. `scope.mjs` compiles that config
+and nothing else, so an adopter points the predicate at their own root and gets their own scope.
+Read the config rather than a restatement here: this paragraph has drifted from the real scope
+twice, because an enumeration in prose has nothing checking it.
+
+`scope.test.mjs` also pins discovery against `git ls-files`, so an in-scope file git does not
+track yet fails it by name: track it if it is source, move it outside the declared roots if it is
+scratch, or add it to `exclude` if it is generated output.
+
+A family that no unit names is declared but ungated: it gives the extractor a grammar to read
+that extension under, while contributing nothing to membership. That is how a family reaches the
+predicate before it reaches the gate, and it is what the yaml family is today.
+
+A `**/<name>/**` exclusion additionally prunes any directory called `<name>` during discovery —
+without it the walk descends into `node_modules` and its symlink farm. A path-shaped exclusion
+(`docs/.source/**`) filters but does not prune. `version` names the schema major the
+file is written against: a major the predicate does not recognise is refused by name, while an
+unknown additive key under a recognised major loads and is reported. A root or file the config
+declares but the tree lacks is recorded as declared-absent rather than raised as an error, which
+is what lets the public mirror ship a config naming roots the export drops.
+
+Every path-shaped value the config carries -- `units[].roots`, `units[].files` and `exclude` --
+is canonicalized once at load, so the matcher, the existence probe, the walk and the sweep all
+read one spelling: a leading `./` is stripped, repeated slashes collapse, a trailing `/` is
+dropped, and `.` is the only spelling of the repository root. Braces expand first, so a `./`
+hiding inside an alternation member is canonicalized too. Two spellings that name the same path
+therefore declare the same membership; before this was done at load, a `./`-prefixed entry
+reached the existence probe through the filesystem and the matcher as a literal, and the two
+disagreed silently. An absolute path or a `..` segment is refused by name with its key path
+instead of being normalized: both name a tree the root does not own, discovery only ever
+descends from the root, and rewriting either one would move a unit somewhere nobody declared.
+
+The matcher is hand-rolled for the same reason the two lexers are, and the reason is a constraint
+rather than a preference: `scope.mjs` sits inside the write-time hook's import closure, which
+`scripts/no-comments-hook.test.mjs` pins to `node:` built-ins and this directory's own modules, so
+nothing it reaches may import an installed package. Like the hook itself, that test is
+upstream-only and no mirrored test replaces it, so on a public clone the constraint is a rule
+without a gate: adding an installed dependency here reds nothing locally and surfaces only when
+the change is bridged back. The named analog is `picomatch` — zero runtime
+dependencies, `makeRe(glob)` returning a `RegExp` — already resolved in this workspace's lockfile,
+so availability is not what rules it out. It is also the referent the refusals measure against:
+where `expandBraces` says "the reference expanders", the expanders are `picomatch` and
+`micromatch`. Only `*`, `**`, literal segments and comma alternations are implemented, and every
+other shape is refused by name rather than compiled into a pattern that governs a set the config
+never wrote.
This directory ships to the public mirror, which means its own tests may not *spell* a
`*.private.*` path: the mirror's content-leak gate rejects a named reference to one in any
shipping file. `scope.test.mjs` composes those paths from parts for that reason, and a test
added here has to do the same.
+### Symlinks are refused, never followed
+
+Discovery walks real entries only. Any symlink it meets that would otherwise have contributed —
+one whose own path is in scope, and one that resolves to a directory the walk would have descended
+— is recorded as a skip, and `discoverInScopeFiles` throws rather than return a list that quietly
+lost a subtree. `discoverInScopeFilesWithSkips` is the exported escape hatch for a caller that
+wants to handle skips itself. Both refuse to run without `lstatSync` and `statSync`: `lstatSync`
+is what tells a link from a real entry, `statSync` is what tells a link-to-a-directory from a
+link-to-a-file, and passing one where the other belongs makes the whole branch unreachable while
+the corpus silently widens to whatever the links point at.
+
## The lexer
### Why not `context.sourceCode.getAllComments()`
@@ -288,6 +578,63 @@ ambiguities by leaning toward comment recall:
A `.private.` differential test pins the lexer against a TypeScript-backed oracle across every
in-scope file in the repository.
+### The hash family
+
+`extract-hash.mjs` is the second lexer, reading the families whose comment opens with `#`. It
+shares the position model and the zero-dependency property, and it dispatches on a dialect
+resolved from the file's extension — or, for an extensionless unit member, from the extensions
+its family declares. An extension no dialect claims is refused by name rather than read under a
+neighbouring grammar, because reading one family's bytes with another family's lexer does not
+fail quietly: the slash lexer over shell source finds no `#` comment at all and invents one out
+of the `//` in a URL.
+
+Three dialects: `shell`, whose word-initial rule and frame stack are the hard case (heredoc
+queue, command substitution, parameter expansion, arithmetic, ANSI-C quoting); `yaml`, which
+adds block scalars and narrows the word rule to whitespace; and `python`, whose `#` needs no
+word rule at all. `shell` and `yaml` each carry their own comment-position
+reference — the pinned `shfmt` differential and the `yaml` package's CST. `python` carries none
+yet, and is the one dialect no family declares: it reaches a family only once a reference lands,
+because a pinned Python tokenizer is a heavier provisioning step than shfmt's one static binary,
+and CPython's own `tokenize` changed its f-string tokens in 3.12, so an unpinned interpreter
+would give a version-dependent verdict. The lexer is measurably wrong on that same change: it
+carries no replacement-field awareness and closes a string at the next occurrence of the opening
+quote, so PEP 701 same-quote nesting ends it early and the remainder is scanned as top-level code.
+`x = f"{d["a#b"]}"` yields a line comment `#b"]}"` at column 12, which a `--write` strip would
+delete, leaving the truncated `x = f"{d["a`; Black shipped the same class of bug
+(`psf/black#4056`). So a family declaring `.py` is not merely undeclared by convention: the
+grammar contract refuses it at config load, naming the dialect and the reference it lacks, because
+an adopter pointing `--root` at their own config would otherwise take gate verdicts and strip
+ranges from a lexer nothing measures. Line one is structural in the dialects that have a line-one grammar —
+a shell or python shebang, and python's PEP 263 coding cookie on either line the PEP allows —
+so the extractor emits it under its own kind and no lane ever reports it as a comment.
+
+Multi-line markers work differently here. A `#` comment is one line, so a marker whose
+continuation is indented under its head is joined into one comment by the classifier, never by
+the extractor; the join keeps the byte-exact span, so a stripper deletes exactly what it read.
+An unindented following line stays a separate comment and is prose.
+
+The shell dialect's reference is `shfmt`, the Go binary. The npm port weighed when the pin was
+chosen, `mvdan-sh`, is 0.10.1, published 2022, and lags the build this pin names by roughly four
+years, so it would have been a different oracle rather than the same one packaged differently.
+That reasoning covers that package and not the class: whether some port that does track this build
+could replace the binary is an open engine question, not a settled one. Its pin is a second
+registry no dependency automation watches: a `SHFMT_VERSION` constant in `scripts/shfmt.mjs` plus a hand-maintained
+four-platform sha256 table beside it, which the resolver checks the provisioned copy against and
+`scripts/provision-shfmt.mjs` checks the download against, neither reachable from
+`package.json`, the lockfile, or Dependabot. A platform the table has no row for is the one case
+the two read differently: the provisioner refuses to download at all, while the resolver keeps the
+version check and warns that this copy went unverified, naming the missing row — the pin's job is
+to let a divergence be attributed to the printer it names, and an unverified copy cannot carry that
+attribution quietly. Refreshing it means replacing four release-asset
+digests — mvdan/sh publishes no checksums file, signature or build attestation with its releases,
+so those four pin one observed download rather than a publisher's statement, and the only
+non-circular check available is an independent rebuild from the recipe the release notes state —
+moving the version constant the differential asserts, and re-running the whole shell
+unit under the new build to confirm `-mn` output is byte-identical before the pin moves. That
+re-measure has been run once, for 3.14.0: the pin held at 3.13.1 because
+`scripts/lume-bake/probe-chromium-prefs.sh` emits its `then` on a different line under the newer
+printer.
+
## Rebasing an in-flight branch across the cleanup
The cleanup commit deletes comment lines across the whole scope at once, so a branch that forked
@@ -305,18 +652,36 @@ Two conflict shapes, two resolutions:
then merge again. The codemod is idempotent, so both sides now carry the same deletions and the
remaining conflict is your own change with no comments in it - resolve it by taking your side.
+Run these from the repository root of the monorepo checkout (`public/open-knowledge/` there); a
+public clone carries the oxlint rule and a `lint` with no sweep leg, but neither the codemod, the
+shfmt provisioner nor the write-time hook, so the recipe below does not apply to it:
+
+```bash
+pnpm run provision:shfmt
+node scripts/comment-codemod.mjs --write
```
-node scripts/comment-codemod.mjs --root <your-repo> --write
-```
+
+`provision:shfmt` is only needed when the branch touches a shell file: the codemod's shell oracle
+reads the pinned build by absolute path and refuses rather than guessing when it is absent.
The exit code is the machine half of that recipe, so a chained command can branch on it:
| code | meaning |
|---|---|
-| 0 | clean: everything in scope was stripped, nothing was declined |
-| 1 | a file's token stream diverged, so nothing was written for it - the tree is unchanged and this is a bug to report, not a rebase step |
-| 2 | the invocation was refused before any work: `--file` with no path, an out-of-scope `--file`, or `--write` with no protected-region net |
-| 3 | wrote successfully, and a human still has work: a rot token inside an otherwise legitimate marker was left in place for you to strip by hand |
+| 0 | clean: nothing was refused, and with `--write` everything in scope was stripped. `--write` is opt-in, so a plain invocation is a dry run that reaches this code having written nothing — 0 means "no file was refused", never "the tree was rewritten". The report's first line says which of the two ran, and a dry run labels its counters `would change` / `would remove`. A protected-region hit is reported but does not change the code, so a run whose only outstanding item is a protected region also exits 0 |
+| 1 | a file was refused, so nothing was written for it and the run carried on. Each reason prints as the literal below. `identity-divergence`, the strip failed its family's oracle — a significant-token mismatch for the c-family; a `shfmt -mn` canonical-form mismatch, a changed shebang or a `bash -n` rejection for shell — and `kept-comment-lost`, an allowlisted comment the strip removed: both are bugs to report rather than rebase steps. `non-utf8-bytes`, a file whose bytes do not round-trip UTF-8 (decoding it would rewrite them as U+FFFD, so the codemod never decodes it) — convert or exclude it by hand. `no-grammar`, a path no family claims — declare it in the config or leave it out. `no-identity-oracle`, a family the codemod cannot prove a strip invariant for. `source-changed-since-plan`, a file another writer rewrote between the read that planned the strip and the write — re-run. `source-unreadable-at-flush`, a planned file that could not be re-read before its write — fix the permission or the missing path; re-running alone will not clear it. Where a reason carries more detail the report prints it in parentheses after the name. A refusal outranks pending human work, so a run that also leaves rot survivors or over-cap citations exits 1, not 3 — branch on 1 before 3, and read `--proposals` on both, since it is written whenever the flag is passed and the run completed, whatever the code |
+| 2 | the invocation was refused before any work: an argument the parser does not claim (printed as `unrecognized argument(s): <tokens>`, followed by the accepted grammar), including a bare path — name files with `--file <path>` — a value-taking flag other than `--file` passed twice (`repeated argument(s): <flags>`, since the parser resolves one to its first occurrence), a value-taking flag (`--root`, `--file`, `--manifest`, `--proposals`, `--reader-probe`) with no path after it, a `--file` outside `--root`, a `--file` no unit claims, a scope config that does not load (printed as `scope-config: UNREADABLE` with the offending key, or `scope-config: NOT FOUND` on a root that declares none), a precedent registry that does not load (printed as `precedent-registry: UNREADABLE` with the manifest key or the PRECEDENTS.md numbering problem behind it), an absent pinned `shfmt` when a target is shell (printed as `shfmt v<version> is not available` — run `node scripts/provision-shfmt.mjs`; the tree is untouched in both lanes), `--write` with no protected-region net, or `--write` where a target's family has no registered identity oracle — under `--allow-unscoped`, no family at all. Oracle availability is knowable before a byte is read, so it refuses the whole invocation rather than skipping the file. Any other internal error also exits 2; every file is planned and verified before the first is written, so an error while planning leaves the tree untouched, and an error while writing names every file whose rewrite landed; the file that aborted is untouched, because each write is staged beside its target and renamed over it only after the staged bytes are read back and matched |
+| 3 | a human still has work, and with `--write` everything writable was written: `rot-in-survivor`, a rot token inside an otherwise legitimate marker, left in place for you to strip by hand and counted in the summary as `rot-refused`; or `citation-over-cap`, a citation comment past the three-line cap, counted as `over-cap`, whose trimmed candidates the `--proposals <path>` channel carries — and nothing was refused; a refusal outranks this and takes the run to 1 with the same records still written. A dry run reaches this code too, having written nothing |
+
+`--manifest <path>` writes the deletion manifest, and `--reader-probe <path>` writes the
+machine-read probe's record — the one that says whether a removed marker still has a reader, and
+whether it could enumerate the tree to find out at all.
+
+Two of the exit-2 refusals have an override, and neither is a default. `--allow-unprotected`
+writes without the mirror's protected-region net. `--allow-unscoped` strips `--file`-named paths
+in a tree carrying no `no-comments.config.jsonc`, reading them under a fixed fallback family map
+that the run announces; it does not enable enumeration, so an unscoped tree with no `--file` is
+refused outright.
A protected-region collision exits 0 by design. It means the comment overlaps a span the mirror
manifest pins, so declining to touch it is the correct terminal state rather than pending work -
diff --git a/lint-plugins/no-comments/__fixtures__/hash-shapes.fixture.mjs b/lint-plugins/no-comments/__fixtures__/hash-shapes.fixture.mjs
new file mode 100644
index 000000000..d7251b582
--- /dev/null
+++ b/lint-plugins/no-comments/__fixtures__/hash-shapes.fixture.mjs
@@ -0,0 +1,219 @@
+export const SHELL_SENTINEL = '# ok';
+
+export const SHELL_MUST_NOT_FIRE = [
+ {
+ id: 'F02',
+ label: 'a hash inside double quotes',
+ source: 'echo "a#b"\n# ok\n',
+ },
+ {
+ id: 'F03',
+ label: 'a hash inside single quotes',
+ source: "printf '\\n# Auto-added by bootstrap\\n'\n# ok\n",
+ },
+ {
+ id: 'F04',
+ label: 'a hash inside an ANSI-C quoted string',
+ source: "note=$'\\n# Note: detected a git worktree'\n# ok\n",
+ },
+ {
+ id: 'F05',
+ label: 'an unquoted heredoc body',
+ source: 'cat <<END\n# body\nEND\n# ok\n',
+ },
+ {
+ id: 'F06',
+ label: 'a quoted heredoc body',
+ source: "cat <<'END'\n# body\nEND\n# ok\n",
+ },
+ {
+ id: 'F07',
+ label: 'a tab-stripped heredoc body',
+ source: 'cat <<-END\n\t# body\n\tEND\n# ok\n',
+ },
+ {
+ id: 'F08',
+ label: 'two heredocs queued on one line',
+ source: 'cat <<A <<B\n# not1\nA\n# not2\nB\n# ok\n',
+ },
+ {
+ id: 'F09',
+ label: 'a parameter length expansion',
+ source: 'v=abc; echo "${#v} ${#arr[@]}"\n# ok\n',
+ },
+ {
+ id: 'F10',
+ label: 'the positional-count parameter',
+ source: 'echo $#\n# ok\n',
+ },
+ {
+ id: 'F11',
+ label: 'a prefix-stripping parameter expansion',
+ source: 'repo=a/b; echo "${repo##*/} ${repo#a}"\n# ok\n',
+ },
+ {
+ id: 'F12',
+ label: 'a hash mid-word',
+ source: 'echo A#x https://example.com#frag\n# ok\n',
+ },
+ {
+ id: 'F13',
+ label: 'a backslash-escaped hash',
+ source: 'echo \\#x\n# ok\n',
+ },
+ {
+ id: 'F15',
+ label: 'a line continuation that joins mid-word',
+ source: 'echo A\\\n#x\n# ok\n',
+ },
+ {
+ id: 'F20',
+ label: 'a multi-line double-quoted string carrying a hash line',
+ source: 'x="line1\n# not a comment\nline3"\n# ok\n',
+ },
+ {
+ id: 'F21',
+ label: 'a hash inside a case pattern',
+ source: 'case "$f" in\n *#*) echo hash ;;\nesac\n# ok\n',
+ },
+ {
+ id: 'F23',
+ label: 'a hash inside a regex word',
+ source: 's="#tag"\nif [[ $s =~ ^#+ ]]; then echo m; fi\n# ok\n',
+ },
+ {
+ id: 'F24',
+ label: 'a hash used as a sed delimiter',
+ source: "echo abc | sed 's#b#Z#'\n# ok\n",
+ },
+ {
+ id: 'D5a',
+ label: 'arithmetic base notation',
+ source: 'n=8; echo "$((10#$n)) $((16#ff))"\n# ok\n',
+ },
+ {
+ id: 'D5a2',
+ label: 'a hash inside an arithmetic command, which is an operand and not a comment',
+ source: 'x=1\n(( x = 3 + 16#ff ))\n# ok\n',
+ },
+ {
+ id: 'HS1',
+ label: 'a here-string, which is not a heredoc opener',
+ source: 'while read -r l; do echo "$l"; done <<< "$ips"\n# ok\n',
+ },
+ {
+ id: 'D5b',
+ label: 'a quoted hash inside a process substitution',
+ source: 'cat <(printf "a#b\\n")\n# ok\n',
+ },
+ {
+ id: 'D5c',
+ label: 'a hash mid-word inside an unquoted regex in a conditional',
+ source: 'x=a#b\nif [[ $x =~ a#b ]]; then echo m; fi\n# ok\n',
+ },
+];
+
+export const SHELL_MUST_FIRE = [
+ {
+ id: 'F01',
+ label: 'the shebang on line one',
+ source: '#!/usr/bin/env bash\necho hi\n',
+ comments: [],
+ structural: ['#!/usr/bin/env bash'],
+ },
+ {
+ id: 'F01b',
+ label: 'a hash on line two, which is an ordinary comment',
+ source: '#!/usr/bin/env bash\n# real\necho hi\n',
+ comments: ['# real'],
+ structural: ['#!/usr/bin/env bash'],
+ },
+ {
+ id: 'F14',
+ label: 'a hash after a line continuation that ends a word',
+ source: 'echo A \\\n#x\n',
+ comments: ['#x'],
+ },
+ {
+ id: 'F16',
+ label: 'a word-initial hash inside a conditional expression',
+ source: 'if [[ -n "$x" #why\n]]; then echo in; fi\n',
+ comments: ['#why'],
+ },
+ {
+ id: 'F17',
+ label: 'a hash inside a command substitution',
+ source: 'echo $(echo hi # inner\n)\n',
+ comments: ['# inner'],
+ },
+ {
+ id: 'F18',
+ label: 'a hash inside a backtick substitution',
+ source: 'echo `echo hi # inner\n`\n',
+ comments: ['# inner'],
+ },
+ {
+ id: 'F18b',
+ label: 'a hash inside a backtick substitution that closes on the same line',
+ source: 'echo `echo hi # inner` after\n',
+ comments: ['# inner'],
+ },
+ {
+ id: 'F18c',
+ label: 'a comment after a backtick substitution that carries one of its own',
+ source: 'echo `echo a # c1` # real\n',
+ comments: ['# c1', '# real'],
+ },
+ {
+ id: 'F18d',
+ label: 'a hash inside a backtick substitution that runs past an escaped backtick',
+ source: 'echo `echo hi # a \\` b` after\n',
+ comments: ['# a \\` b'],
+ },
+ {
+ id: 'F19',
+ label: 'a hash right after a metacharacter',
+ source: 'echo A;#a\necho B|#b\ncat\necho C &#c\nwait\n(#d\n:\n)\n',
+ comments: ['#a', '#b', '#c', '#d'],
+ },
+ {
+ id: 'D5b2',
+ label: 'a word-initial hash inside a process substitution',
+ source: 'cat <(echo hi # inner\n)\n',
+ comments: ['# inner'],
+ },
+];
+
+export const YAML_GENERALIZABILITY_FIXTURE = [
+ '# top of file',
+ 'name: build # trailing on a mapping value',
+ 'on:',
+ ' push:',
+ ' branches: [main] # a flow sequence keeps its comment',
+ 'env:',
+ ' URL: https://example.com/x#frag',
+ ' QUOTED: "a # b"',
+ " LITERAL: 'c # d'",
+ ' EMPTY: "" # an empty scalar still takes a comment',
+ 'jobs:',
+ ' lint:',
+ ' steps:',
+ ' - run: |',
+ ' set -eu',
+ ' # this is shell inside a block scalar, not a yaml comment',
+ ' echo "done"',
+ ' - run: >-',
+ ' folded text # still block-scalar body',
+ ' second line',
+ " - name: Smoke the candidate's DMG # a comment after an apostrophe",
+ ' - name: after the block scalar # a comment again',
+ ' with:',
+ ' args: "--flag=1 #2"',
+ '',
+ ' # an indented whole-line comment',
+ ' test:',
+ ' needs: lint',
+ '',
+ '# end of file',
+ '',
+].join('\n');
diff --git a/lint-plugins/no-comments/__fixtures__/jsdoc-types.fixture.ts b/lint-plugins/no-comments/__fixtures__/jsdoc-types.fixture.ts
new file mode 100644
index 000000000..ac16f5de2
--- /dev/null
+++ b/lint-plugins/no-comments/__fixtures__/jsdoc-types.fixture.ts
@@ -0,0 +1,13 @@
+/** @type {Set<number>} */
+export const slots = new Set<number>();
+
+/**
+ * @param {string} name
+ * @returns {string}
+ */
+export function normalize(name: string): string {
+ return name.trim();
+}
+
+/** @import { Verdict } from './allowlist.mjs' */
+export const usesImport = 1;
diff --git a/lint-plugins/no-comments/__fixtures__/must-fire.fixture.ts b/lint-plugins/no-comments/__fixtures__/must-fire.fixture.ts
index f41082cf9..d8ac1c3f3 100644
--- a/lint-plugins/no-comments/__fixtures__/must-fire.fixture.ts
+++ b/lint-plugins/no-comments/__fixtures__/must-fire.fixture.ts
@@ -70,3 +70,37 @@ export const launderedDeprecatedInline = 19;
// see the `@deprecated` discussion in the RFC thread
export const launderedDeprecatedBackticked = 20;
+
+//# sourceMappingURL=must-fire.fixture.ts.map
+export const sourceMappingUrlPragma = 21;
+
+//# sourceURL=must-fire-evaluated.js
+export const sourceUrlPragma = 22;
+
+/**
+ * A JSDoc essay that narrates the export and then ends on a directive line.
+ * @lintignore union member of the exported result type; no direct importer
+ */
+export const jsdocEssayEndingOnLintignore = 23;
+
+/*
+ * A block essay in the same shape, without the JSDoc opener.
+ * @lintignore referenced by the exported verdict type; no direct importer
+ */
+export const blockEssayEndingOnLintignore = 24;
+
+// prettier-ignore
+export const prettierIgnore = 25;
+
+/** @jsx h */
+export const classicJsxFactoryPragma = 26;
+
+/** @jsxFrag Fragment */
+export const classicJsxFragmentPragma = 27;
+
+export const webpackChunkNameMagic = () => import(/* webpackChunkName: "editor" */ './editor.js');
+
+export const bundlerIgnoreWrongValue = (path: string) => import(/* webpackIgnore: false */ path);
+
+// node-coverage ignore next
+export const nodeCoverageIgnore = 28;
diff --git a/lint-plugins/no-comments/__fixtures__/must-not-fire.fixture.ts b/lint-plugins/no-comments/__fixtures__/must-not-fire.fixture.ts
index bc8cc7b68..0cd03845d 100644
--- a/lint-plugins/no-comments/__fixtures__/must-not-fire.fixture.ts
+++ b/lint-plugins/no-comments/__fixtures__/must-not-fire.fixture.ts
@@ -17,15 +17,8 @@ export const tsExpectError = 4;
export const pureAnnotation = /* @__PURE__ */ Object.freeze({ a: 1 });
-export const magicComment = () => import(/* webpackChunkName: "editor" */ './editor.js');
-
export const viteIgnore = (path: string) => import(/* @vite-ignore */ path);
-// prettier-ignore
-export const prettierIgnore = [1,2,3];
-
-export const sanctionedTag = 5;
-
/** @deprecated use `sanctionedTag` instead */
export const deprecated = 6;
@@ -50,9 +43,6 @@ export const upstreamPackage = 12;
// The alignment here follows precedent #42.
export const validPrecedent = 13;
-// The retracted slot still resolves: precedent #52 kept its number.
-export const retractedPrecedent = 14;
-
// error-log-shape-ok: the message snapshot is the assertion subject here
export const errorLogShapeOk = 15;
@@ -68,14 +58,6 @@ export const knipLintignore = 17;
// presence-exempt: no CRDT write, no agent identity
export const presenceExempt = 18;
-export const descriptionThenTags = 19;
-
-// entity-ref-preservation
-export const lineCommentTag = 20;
-
-// list-marker-indent
-export const indentedTagLine = 21;
-
/* STOP: a multi-line marker in block form survives whole, because the
extractor reads the block as one comment and the marker is its first
body line. */
@@ -97,26 +79,20 @@ export function noSideEffectsHashForm() {
return 25;
}
-/** @jsx h */
-export const jsxFactoryPragma = 26;
-
-/** @jsxFrag Fragment */
-export const jsxFragmentPragma = 27;
-
/** @jsxRuntime automatic */
export const jsxRuntimePragma = 28;
/** @jsxImportSource preact */
export const jsxImportSourcePragma = 29;
-export const webpackExportsMagic = () =>
- import(/* webpackExports: ["parse"] */ './parser.js');
+export const bundlerIgnore = (path: string) => import(/* webpackIgnore: true */ path);
+
+export const turbopackIgnore = (path: string) => import(/* turbopackIgnore: true */ path);
-export const webpackFetchPriorityMagic = () =>
- import(/* webpackFetchPriority: "high" */ './urgent.js');
+export const turbopackOptional = () => import(/* turbopackOptional: true */ './maybe.js');
-//# sourceMappingURL=must-not-fire.fixture.ts.map
-export const sourceMappingUrlPragma = 30;
+//! Bundled banner text the bundler preserves verbatim in the output.
+export const legalLineComment = 26;
-//# sourceURL=must-not-fire-evaluated.js
-export const sourceUrlPragma = 31;
+/*! Bundled banner in block form, preserved on the same rule. */
+export const legalBlockComment = 27;
diff --git a/lint-plugins/no-comments/__fixtures__/sanctioned-tag.fixture.ts b/lint-plugins/no-comments/__fixtures__/sanctioned-tag.fixture.ts
new file mode 100644
index 000000000..7f857c7e3
--- /dev/null
+++ b/lint-plugins/no-comments/__fixtures__/sanctioned-tag.fixture.ts
@@ -0,0 +1,11 @@
+export const header = 1;
+
+export const sanctionedTag = 2;
+
+export const descriptionThenTags = 3;
+
+// entity-ref-preservation
+export const lineCommentTag = 4;
+
+// list-marker-indent
+export const indentedTagLine = 5;
diff --git a/lint-plugins/no-comments/allowlist.mjs b/lint-plugins/no-comments/allowlist.mjs
index 96becf046..8c0e622c9 100644
--- a/lint-plugins/no-comments/allowlist.mjs
+++ b/lint-plugins/no-comments/allowlist.mjs
@@ -1,4 +1,4 @@
-import { citedPrecedentNumbers } from './precedents.mjs';
+import { citedPrecedentNumbers, PrecedentRegistry } from './precedents.mjs';
import { findRotMatches } from './rot.mjs';
export const SANCTIONED_TAGS = [];
@@ -36,44 +36,249 @@ function tagOnOwnLine(text, tag) {
return re.test(text);
}
+const TSC = { kind: 'declared', package: 'typescript', invokedBy: 'typecheck' };
+const ROLLDOWN = { kind: 'transitive', package: 'rolldown', via: 'tsdown', invokedBy: 'build' };
+const OXLINT = { kind: 'declared', package: 'oxlint', invokedBy: 'lint' };
+
+export const OPENING_LINE_WINDOW = 3;
+
export const DIRECTIVE_PATTERNS = [
- { id: 'biome-ignore', target: 'headline', regex: /^biome-ignore(?:-all|-start|-end)?\s+\S+\s*:\s*\S/ },
- { id: 'oxlint-disable', target: 'headline', regex: /^oxlint-(?:disable|enable)(?:-next-line|-line)?\b/ },
- { id: 'eslint-disable', target: 'headline', regex: /^eslint-(?:disable|enable)(?:-next-line|-line)?\b/ },
- { id: 'vite-ignore', target: 'headline', regex: /^@vite-ignore\b/ },
- { id: 'prettier-ignore', target: 'headline', regex: /^prettier-ignore\b/ },
- { id: 'triple-slash-reference', target: 'text', regex: /^\/\/\/\s*<reference\b/ },
- { id: 'vitest-environment', target: 'headline', regex: /^@vitest-environment\s+\S/ },
- { id: 'ts-nocheck', target: 'headline', regex: /^@ts-nocheck\b/ },
- { id: 'ts-check', target: 'headline', regex: /^@ts-check\b/ },
{
- id: 'license-header',
+ id: 'biome-ignore',
+ target: 'headline',
+ regex: /^biome-ignore(?:-all|-start|-end)?\s+\S+\s*:\s*\S/,
+ shapes: ['biome-ignore {rule}: {reason}'],
+ consumer: { kind: 'declared', package: '@biomejs/biome', invokedBy: 'lint' },
+ reach: { verdict: 'reached', note: '' },
+ },
+ {
+ id: 'oxlint-disable',
+ target: 'headline',
+ regex: /^oxlint-(?:disable|enable)(?:-next-line|-line)?\b/,
+ shapes: ['oxlint-disable', 'oxlint-enable', 'oxlint-disable-next-line', 'oxlint-disable-line'],
+ consumer: OXLINT,
+ reach: { verdict: 'reached', note: '' },
+ },
+ {
+ id: 'eslint-disable',
+ target: 'headline',
+ regex: /^eslint-(?:disable|enable)(?:-next-line|-line)?\b/,
+ shapes: ['eslint-disable', 'eslint-enable', 'eslint-disable-next-line', 'eslint-disable-line'],
+ consumer: OXLINT,
+ reach: {
+ verdict: 'reached',
+ note: 'oxlint core honours the eslint grammar; no ESLint is installed and none is needed.',
+ },
+ },
+ {
+ id: 'vite-ignore',
+ target: 'headline',
+ regex: /^@vite-ignore\b/,
+ shapes: ['@vite-ignore'],
+ consumer: ROLLDOWN,
+ reach: { verdict: 'reached', note: '' },
+ },
+ {
+ id: 'triple-slash-reference',
target: 'text',
- regex: /SPDX-License-Identifier:|@license\b/,
+ regex: /^\/\/\/\s*<reference\b/,
+ shapes: ['/// <reference types="x" />'],
+ consumer: TSC,
+ reach: {
+ verdict: 'unreached',
+ note:
+ 'The canonical host is a .d.ts, which scope excludes. tsc reads the directive in any .ts, ' +
+ 'so the reach failure is an encoded judgment about where the shape occurs rather than a ' +
+ 'derived fact, and the entry stays.',
+ },
+ },
+ {
+ id: 'vitest-environment',
+ target: 'headline',
+ regex: /^@vitest-environment\s+\S/,
+ shapes: ['@vitest-environment {env}'],
+ consumer: { kind: 'declared', package: 'vitest', invokedBy: 'test' },
+ reach: { verdict: 'reached', note: '' },
+ },
+ {
+ id: 'ts-nocheck',
+ target: 'headline',
+ regex: /^@ts-nocheck\b/,
+ shapes: ['@ts-nocheck'],
+ consumer: TSC,
+ reach: { verdict: 'reached', note: '' },
},
- { id: 'pure-annotation', target: 'headline', regex: /^[@#]__PURE__/ },
- { id: 'no-side-effects-annotation', target: 'headline', regex: /^[@#]__NO_SIDE_EFFECTS__\s*$/ },
- { id: 'preserve', target: 'headline', regex: /^@preserve\b/ },
- { id: 'jsx-pragma', target: 'headline', regex: /^@jsx(?:Frag|Runtime|ImportSource)?\s+\S+\s*$/ },
{
- id: 'webpack-magic',
+ id: 'ts-check',
target: 'headline',
+ regex: /^@ts-check\b/,
+ shapes: ['@ts-check'],
+ consumer: TSC,
+ reach: {
+ verdict: 'unreached',
+ note:
+ 'No tsconfig sets checkJs, so the opt-in has nothing to opt into today. It is the sibling ' +
+ 'of the live @ts-nocheck, and the asymmetry between admitting one and banning the other ' +
+ 'is what the admission rule was written to settle.',
+ },
+ },
+ {
+ id: 'license-header',
+ target: 'opening-lines',
regex:
- /^webpack(?:ChunkName|Ignore|Include|Exclude|Mode|Prefetch|Preload|Exports|FetchPriority)\s*:/,
+ /^(?:SPDX-License-Identifier:[ \t]*\(*[A-Za-z0-9.-]+(?::[A-Za-z0-9.-]+)?\+?\)*(?:[ \t]+(?:AND|OR|WITH)[ \t]+\(*[A-Za-z0-9.-]+(?::[A-Za-z0-9.-]+)?\+?\)*)*[ \t]*|@license\b.*)$/m,
+ shapes: ['SPDX-License-Identifier: {expression}', '@license {terms}'],
+ consumer: {
+ kind: 'external',
+ consumer: 'SPDX tooling and copyright law',
+ admittedOn:
+ 'Dropping a real licence notice is a legal harm no in-repo tool can undo, and the asymmetry ' +
+ 'against keeping a false positive is total.',
+ },
+ reach: { verdict: 'reached', note: '' },
},
{
- id: 'source-map-pragma',
- target: 'text',
- regex: /^\/\/[#@][ \t]*source(?:MappingURL|URL)=\S+$/,
+ id: 'legal-comment',
+ target: 'opener',
+ regex: /^\/(?:\*|\/)!/,
+ shapes: ['//! {banner}', '/*! {banner} */'],
+ consumer: ROLLDOWN,
+ reach: { verdict: 'reached', note: '' },
+ },
+ {
+ id: 'pure-annotation',
+ target: 'headline',
+ regex: /^[@#]__PURE__/,
+ shapes: ['@__PURE__', '#__PURE__'],
+ consumer: ROLLDOWN,
+ reach: { verdict: 'reached', note: '' },
+ },
+ {
+ id: 'no-side-effects-annotation',
+ target: 'headline',
+ regex: /^[@#]__NO_SIDE_EFFECTS__\s*$/,
+ shapes: ['@__NO_SIDE_EFFECTS__', '#__NO_SIDE_EFFECTS__'],
+ consumer: ROLLDOWN,
+ reach: { verdict: 'reached', note: '' },
+ },
+ {
+ id: 'preserve',
+ target: 'headline',
+ regex: /^@preserve\b/,
+ shapes: ['@preserve'],
+ consumer: ROLLDOWN,
+ reach: { verdict: 'reached', note: '' },
+ },
+ {
+ id: 'jsx-pragma',
+ target: 'headline',
+ regex: /^@jsx(?:Runtime|ImportSource)\s+\S+\s*$/,
+ shapes: ['@jsxRuntime {runtime}', '@jsxImportSource {source}'],
+ consumer: TSC,
+ reach: {
+ verdict: 'reached',
+ note:
+ 'The classic-runtime pair @jsx and @jsxFrag is gone: every tsconfig here compiles with the ' +
+ 'automatic runtime, under which the factory pragmas cannot apply.',
+ },
+ },
+ {
+ id: 'bundler-ignore',
+ target: 'headline',
+ regex: /^(?:webpackIgnore|turbopackIgnore|turbopackOptional)\s*:\s*true\s*$/,
+ shapes: ['webpackIgnore: true', 'turbopackIgnore: true', 'turbopackOptional: true'],
+ consumer: { kind: 'declared', package: 'next', invokedBy: 'build' },
+ reach: {
+ verdict: 'reached',
+ note:
+ 'Turbopack honours all three on the version this repo builds with, and rejects both a ' +
+ 'wrong value and a wrong key, so the value is part of the shape. The eight non-Ignore ' +
+ 'webpack keys buy nothing here and are gone.',
+ },
+ },
+ {
+ id: 'coverage-ignore',
+ target: 'headline',
+ regex: /^(?:v8|c8|istanbul) ignore\b/,
+ shapes: ['v8 ignore {what}', 'c8 ignore {what}', 'istanbul ignore {what}'],
+ consumer: {
+ kind: 'latent',
+ packages: ['@vitest/coverage-v8', '@vitest/coverage-istanbul', 'c8', 'nyc'],
+ activatesWhen: 'a workspace declares one of those packages and wires a coverage run',
+ },
+ reach: {
+ verdict: 'latent',
+ note:
+ 'Reachability cannot be asserted here, because there is no consumer to reach. The bar is ' +
+ 'inverted instead: the named packages must all be absent, so wiring one in reddens this ' +
+ 'row and forces it to be promoted to a claim someone recorded a reason for.',
+ },
},
- { id: 'coverage-ignore', target: 'headline', regex: /^(?:v8|c8|istanbul|node-coverage) ignore\b/ },
{
id: 'knip-lintignore',
- target: 'text',
- regex: LINTIGNORE_WITH_REASON_RE,
+ target: 'block-headline',
+ regex: /^@lintignore[ \t]+(?!\*\/)\S/,
+ shapes: ['/** @lintignore {reason} */'],
+ consumer: { kind: 'declared', package: 'knip', invokedBy: 'knip' },
+ reach: { verdict: 'reached', note: '' },
},
];
+const DIRECTIVE_REGISTRIES = {
+ 'c-family': { typescript: DIRECTIVE_PATTERNS, 'esm-script': DIRECTIVE_PATTERNS },
+ 'hash-family': { shell: [], yaml: [], python: [] },
+};
+
+export const DIRECTIVE_REGISTRY_KEYS = Object.entries(DIRECTIVE_REGISTRIES).flatMap(
+ ([extractor, fileClasses]) =>
+ Object.keys(fileClasses).map((fileClass) => ({ extractor, fileClass })),
+);
+
+export function directivesFor(extractor, fileClass) {
+ const registry = DIRECTIVE_REGISTRIES[extractor]?.[fileClass];
+ if (registry === undefined) {
+ throw new Error(
+ `no directive registry is declared for ${extractor} x ${fileClass}. A file class admits the ` +
+ 'shapes its own tools parse, so an undeclared one has no answer to give; declare it, ' +
+ 'empty if this repository runs nothing that reads a directive there.',
+ );
+ }
+ return registry;
+}
+
+function openingLines(text) {
+ const lines = [];
+ for (const line of commentBodyLines(text)) {
+ const trimmed = line.trim();
+ if (trimmed === '') continue;
+ lines.push(trimmed);
+ if (lines.length === OPENING_LINE_WINDOW) break;
+ }
+ return lines.join('\n');
+}
+
+const DIRECTIVE_SUBJECTS = {
+ __proto__: null,
+ headline: (headline) => headline,
+ 'block-headline': (headline, text) => (text.startsWith('/*') ? headline : null),
+ 'opening-lines': (_headline, text) => openingLines(text),
+ opener: (_headline, text) => text,
+ text: (_headline, text) => text,
+};
+
+function directiveSubject(target, headline, text) {
+ const subject = DIRECTIVE_SUBJECTS[target];
+ if (subject === undefined) {
+ throw new Error(
+ `no comment subject is declared for the directive target ${JSON.stringify(target)}. A ` +
+ 'target names the slice of a comment a shape is anchored to, so an undeclared one has no ' +
+ 'answer to give; declare it in DIRECTIVE_SUBJECTS beside the others rather than falling ' +
+ 'back to the whole comment, which silently widens every shape that names it.',
+ );
+ }
+ return subject(headline, text);
+}
+
const TS_EXPECT_ERROR_RE = /^@ts-expect-error\s*(.*)$/;
const TS_IGNORE_RE = /@ts-ignore\b/;
@@ -81,19 +286,44 @@ export const UPSTREAM_REFERENT_SHAPES = [
{ id: 'github-issue', regex: /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+#\d+$/ },
{ id: 'rfc', regex: /^RFC \d+(?: §[\w.§-]+)?$/ },
{ id: 'commonmark', regex: /^CommonMark §[\w.§-]+$/ },
- { id: 'package-version', regex: /^@?[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)?@\d[\w.+-]*$/i },
+ {
+ id: 'package-version',
+ regex: /^@?[a-z0-9][a-z0-9._-]*(?:\/[a-z0-9][a-z0-9._-]*)?@\d[\w.+-]*$/i,
+ },
];
+const TRACKER_URL_RE =
+ /^(?:https?:\/\/)?(?:www\.)?github\.com\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)\/(?:issues|pull)\/(\d+)\/?$/;
+
+export function parseUpstreamReferent(referent) {
+ return referent.split(',').map((part) => {
+ const raw = part.trim();
+ const url = TRACKER_URL_RE.exec(raw);
+ const resolved = url ? `${url[1]}/${url[2]}#${url[3]}` : raw;
+ const shape = UPSTREAM_REFERENT_SHAPES.find((candidate) => candidate.regex.test(resolved));
+ return { raw, referent: resolved, shape: shape?.id ?? null };
+ });
+}
+
export const GUARD_MARKERS = [
{ id: 'precedent-30-exemption', regex: /documented exemption from Precedent #30/i },
{ id: 'error-log-shape-ok', regex: /\berror-log-shape-ok:\s*\S/ },
{ id: 'presence-exempt', regex: /\bpresence-exempt:\s*\S/ },
+ { id: 'defect-class', regex: /\bDefect class:\s*\S/ },
+ { id: 'tolerated-call-site', regex: /\bTOLERATED:\s*\S/ },
];
+const GUARD_MARKER_TARGET = 'opening-lines';
+
const UPSTREAM_PREFIX_RE = /^UPSTREAM\(([^)]*)\):/;
const CONTRACT_PREFIX_RE = /^(STOP|WARN):\s*\S/;
+const HASH_BODY_LINE_RE = /^\s*#\s?/;
+
export function commentBodyLines(text) {
+ if (text.startsWith('#')) {
+ return text.split('\n').map((line) => line.replace(HASH_BODY_LINE_RE, '').trimEnd());
+ }
let body = text;
if (body.startsWith('/*')) {
body = body.slice(body.startsWith('/**') ? 3 : 2);
@@ -106,6 +336,10 @@ export function commentBodyLines(text) {
return body.split('\n').map((line) => line.replace(/^\s*\*?\s?/, '').trimEnd());
}
+export function classificationText(text) {
+ return text.includes('\r') ? text.replaceAll('\r', '') : text;
+}
+
export function commentHeadline(text) {
for (const line of commentBodyLines(text)) {
if (line.trim() !== '') return line.trim();
@@ -138,13 +372,19 @@ function withRotScan(verdict, text) {
);
}
+export function isMarkerHead(text) {
+ const headline = commentHeadline(classificationText(text));
+ return CONTRACT_PREFIX_RE.test(headline) || UPSTREAM_PREFIX_RE.test(headline);
+}
+
export function classifyComment(comment, options = {}) {
const {
- precedentNumbers,
+ precedentRegistry,
jsdocTypes = false,
sanctionedTags = SANCTIONED_TAGS,
+ directives = DIRECTIVE_PATTERNS,
} = options;
- const text = comment.text;
+ const text = classificationText(comment.text);
const headline = commentHeadline(text);
if (TS_IGNORE_RE.test(text)) {
@@ -176,16 +416,19 @@ export function classifyComment(comment, options = {}) {
return withRotScan(allowed('directive', '@ts-expect-error'), text);
}
- for (const directive of DIRECTIVE_PATTERNS) {
- const subject = directive.target === 'headline' ? headline : text;
- if (directive.regex.test(subject)) return withRotScan(allowed('directive', directive.id), text);
+ for (const directive of directives) {
+ const subject = directiveSubject(directive.target, headline, text);
+ if (subject !== null && directive.regex.test(subject)) {
+ return withRotScan(allowed('directive', directive.id), text);
+ }
}
for (const tag of sanctionedTags) {
if (tagOnOwnLine(text, tag)) return withRotScan(allowed('sanctioned-tag', tag), text);
}
- if (DEPRECATED_TAG_LINE_RE.test(text)) return withRotScan(allowed('deprecated', '@deprecated'), text);
+ if (DEPRECATED_TAG_LINE_RE.test(text))
+ return withRotScan(allowed('deprecated', '@deprecated'), text);
if (CONTRACT_PREFIX_RE.test(headline)) {
return withRotScan(allowed('contract-marker', headline.slice(0, headline.indexOf(':'))), text);
@@ -193,31 +436,36 @@ export function classifyComment(comment, options = {}) {
const upstream = UPSTREAM_PREFIX_RE.exec(headline);
if (upstream) {
- const referent = upstream[1].trim();
- const shape = UPSTREAM_REFERENT_SHAPES.find((candidate) => candidate.regex.test(referent));
- if (!shape) {
+ const parts = parseUpstreamReferent(upstream[1]);
+ const unresolved = parts.filter((part) => part.shape === null);
+ if (unresolved.length > 0) {
return violation(
'invalid-upstream-referent',
- 'The parenthesized referent must be shape-valid; supporting links belong in the marker body. Use a resolvable referent: `owner/repo#N`, `RFC <n>`, `CommonMark §<n>`, or `pkg@<version>`.',
- `UPSTREAM referent "${referent}" matches no accepted shape`,
+ 'Every parenthesized referent must be shape-valid; supporting links belong in the marker body. Use a resolvable referent: `owner/repo#N`, a github.com issue or pull URL, `RFC <n>`, `CommonMark §<n>`, or `pkg@<version>`. Separate several with commas.',
+ `UPSTREAM referent ${unresolved.map((part) => `"${part.raw}"`).join(', ')} matches no accepted shape`,
);
}
- return withRotScan(allowed('contract-marker', `UPSTREAM/${shape.id}`), text);
+ return withRotScan(
+ allowed('contract-marker', `UPSTREAM/${parts.map((part) => part.shape).join('+')}`),
+ text,
+ );
}
+ const guardSubject = directiveSubject(GUARD_MARKER_TARGET, headline, text);
for (const marker of GUARD_MARKERS) {
- if (marker.regex.test(text)) return withRotScan(allowed('guard-marker', marker.id), text);
+ if (marker.regex.test(guardSubject))
+ return withRotScan(allowed('guard-marker', marker.id), text);
}
const cited = citedPrecedentNumbers(text);
if (cited.length > 0) {
- if (!(precedentNumbers instanceof Set)) {
+ if (!(precedentRegistry instanceof PrecedentRegistry)) {
throw new TypeError(
- 'classifyComment needs a precedentNumbers Set to judge a precedent citation; ' +
- 'load one with loadPrecedentNumbers(repoRoot).',
+ 'classifyComment needs a PrecedentRegistry to judge a precedent citation; load one ' +
+ 'with loadPrecedentRegistry(repoRoot).',
);
}
- const unknown = cited.filter((number) => !precedentNumbers.has(number));
+ const unknown = cited.filter((number) => !precedentRegistry.has(number));
if (unknown.length > 0) {
return violation(
'invalid-precedent',
@@ -225,6 +473,15 @@ export function classifyComment(comment, options = {}) {
`precedent #${unknown[0]} is not a numbered slot in PRECEDENTS.md`,
);
}
+ const retracted = cited.filter((number) => precedentRegistry.isRetracted(number));
+ if (retracted.length > 0) {
+ return violation(
+ 'retracted-precedent',
+ 'Cite the entry that superseded it, or state the constraint without a citation.',
+ `precedent #${retracted[0]} is a retracted slot; it keeps its number for citation ` +
+ 'stability, but its rule no longer holds',
+ );
+ }
return withRotScan(allowed('precedent-citation', `precedent #${cited[0]}`), text);
}
diff --git a/lint-plugins/no-comments/config-schema.test.mjs b/lint-plugins/no-comments/config-schema.test.mjs
new file mode 100644
index 000000000..bbd334de9
--- /dev/null
+++ b/lint-plugins/no-comments/config-schema.test.mjs
@@ -0,0 +1,285 @@
+import { readFileSync } from 'node:fs';
+import { dirname, join, relative } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+import {
+ parseScopeConfig,
+ SCOPE_CONFIG_FILENAME,
+ SUPPORTED_CONFIG_MAJOR,
+ stripJsonc,
+ UNSUPPORTED_GLOB_SYNTAX,
+} from './config.mjs';
+
+const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = join(MODULE_DIR, '..', '..');
+const SCHEMA_PATH = join(MODULE_DIR, 'no-comments.config.schema.json');
+const CONFIG_PATH = join(REPO_ROOT, SCOPE_CONFIG_FILENAME);
+
+const schema = JSON.parse(readFileSync(SCHEMA_PATH, 'utf8'));
+const configText = readFileSync(CONFIG_PATH, 'utf8');
+
+const ANNOTATION_KEYWORDS = new Set(['$ref', 'title', 'description', 'examples', 'default']);
+
+const SUPPORTED_KEYWORDS = new Set([
+ '$ref',
+ '$schema',
+ '$id',
+ 'title',
+ 'description',
+ 'type',
+ 'required',
+ 'anyOf',
+ 'minProperties',
+ 'properties',
+ 'additionalProperties',
+ 'minItems',
+ 'items',
+ 'enum',
+ 'minLength',
+ 'pattern',
+ '$defs',
+ 'examples',
+ 'default',
+]);
+
+function validate(value, node = schema, path = '') {
+ const errors = [];
+ const at = (suffix) => (path === '' ? suffix : `${path}${suffix}`);
+ const unsupported = Object.keys(node).filter((keyword) => !SUPPORTED_KEYWORDS.has(keyword));
+ if (unsupported.length > 0) {
+ throw new Error(
+ `this validator implements ${[...SUPPORTED_KEYWORDS].sort().join(', ')} and the schema now ` +
+ `uses ${unsupported.join(', ')} at ${at('') || '<root>'}. An unimplemented keyword is ` +
+ 'silently ignored, so the fidelity this test claims to pin would be fiction.',
+ );
+ }
+ if (node.$ref) {
+ const applied = Object.keys(node).filter((keyword) => !ANNOTATION_KEYWORDS.has(keyword));
+ if (applied.length > 0) {
+ throw new Error(
+ `${at('') || '<root>'} places ${applied.join(', ')} beside a $ref. Draft 2020-12 applies ` +
+ 'such siblings and this validator does not, so the schema would assert more than the ' +
+ 'test can see; inline the constraint or extend this validator.',
+ );
+ }
+ return validate(value, resolveRef(node.$ref), path);
+ }
+ if (Array.isArray(node.anyOf)) {
+ const branches = node.anyOf.map((branch) => validate(value, branch, path));
+ if (branches.every((branch) => branch.length > 0)) {
+ errors.push(`${at('') || '<root>'} matches no anyOf branch: ${branches.flat().join('; ')}`);
+ }
+ }
+ const isPlainObject = value !== null && typeof value === 'object' && !Array.isArray(value);
+ if (node.type === 'object' && !isPlainObject) {
+ return [`${at('') || '<root>'} must be an object`];
+ }
+ if (node.type === 'array' && !Array.isArray(value)) return [`${at('')} must be an array`];
+ if (isPlainObject) {
+ for (const key of node.required ?? []) {
+ if (!Object.hasOwn(value, key)) errors.push(`${at(`.${key}`)} is required`);
+ }
+ if (typeof node.minProperties === 'number' && Object.keys(value).length < node.minProperties) {
+ errors.push(`${at('') || '<root>'} needs at least ${node.minProperties} entries`);
+ }
+ for (const [key, member] of Object.entries(value)) {
+ const child = node.properties?.[key] ?? node.additionalProperties;
+ if (child === false) errors.push(`${at(`.${key}`)} is not an allowed key`);
+ else if (child && child !== true) errors.push(...validate(member, child, at(`.${key}`)));
+ }
+ }
+ if (Array.isArray(value)) {
+ if (typeof node.minItems === 'number' && value.length < node.minItems) {
+ errors.push(`${at('')} needs at least ${node.minItems} items`);
+ }
+ if (node.items !== undefined && node.items !== true) {
+ value.forEach((item, index) => errors.push(...validate(item, node.items, at(`[${index}]`))));
+ }
+ }
+ if (node.type === 'integer' && !Number.isInteger(value))
+ errors.push(`${at('')} must be an integer`);
+ if (node.type === 'string' && typeof value !== 'string')
+ errors.push(`${at('')} must be a string`);
+ if (node.type === 'boolean' && typeof value !== 'boolean')
+ errors.push(`${at('')} must be a boolean`);
+ if (node.enum && !node.enum.includes(value))
+ errors.push(`${at('')} must be one of ${node.enum.join(', ')}`);
+ if (typeof value === 'string') {
+ if (typeof node.minLength === 'number' && value.length < node.minLength) {
+ errors.push(`${at('')} is shorter than ${node.minLength}`);
+ }
+ if (node.pattern && !new RegExp(node.pattern).test(value)) {
+ errors.push(`${at('')} does not match ${node.pattern}`);
+ }
+ }
+ return errors;
+}
+
+function resolveRef(ref) {
+ return ref
+ .replace(/^#\//, '')
+ .split('/')
+ .reduce((node, segment) => node[segment], schema);
+}
+
+describe('the vendored schema an editor completes against', () => {
+ test('the committed config declares it, by a path that resolves on disk', () => {
+ const declared = JSON.parse(stripJsonc(configText)).$schema;
+ expect(relative(REPO_ROOT, join(REPO_ROOT, declared))).toBe(
+ relative(REPO_ROOT, SCHEMA_PATH).split('\\').join('/'),
+ );
+ expect(() => readFileSync(join(REPO_ROOT, declared), 'utf8')).not.toThrow();
+ });
+
+ test('the schema and the loader agree on which schema major is readable', () => {
+ expect(schema.properties.version.enum).toEqual([SUPPORTED_CONFIG_MAJOR]);
+ });
+
+ test('the committed config validates against it', () => {
+ expect(validate(JSON.parse(stripJsonc(configText)))).toEqual([]);
+ });
+
+ test('the validator is not vacuous: it rejects each shape the loader rejects', () => {
+ const good = JSON.parse(stripJsonc(configText));
+ const mutants = {
+ 'an extension that is a bare dot': {
+ ...good,
+ families: { ...good.families, dotless: { extensions: ['.'], extractor: 'c-family' } },
+ },
+ 'a version the schema does not know': { ...good, version: 2 },
+ 'a missing units key': { ...good, units: undefined },
+ 'an extension with no leading dot': {
+ ...good,
+ families: { ts: { extensions: ['ts'], extractor: 'c-family' } },
+ },
+ 'a family with no extractor': {
+ ...good,
+ families: { ts: { extensions: ['.ts'] } },
+ },
+ 'an empty units array': { ...good, units: [] },
+ 'a unit with no id': { ...good, units: [{ family: 'typescript', roots: ['packages'] }] },
+ 'an exclude that is not an array': { ...good, exclude: '**/dist/**' },
+ 'a root that walks out of the repository root': {
+ ...good,
+ units: [{ id: 'escape', family: 'typescript', roots: ['../sibling/src'] }],
+ },
+ 'a root that is an absolute path': {
+ ...good,
+ units: [{ id: 'absolute', family: 'typescript', roots: ['/etc'] }],
+ },
+ 'an exclude that walks out of the repository root': {
+ ...good,
+ exclude: ['packages/../../elsewhere/**'],
+ },
+ 'a unit that declares neither roots nor files': {
+ ...good,
+ units: [{ id: 'empty', family: 'typescript' }],
+ },
+ 'a unit whose only membership key is an empty roots array': {
+ ...good,
+ units: [{ id: 'empty', family: 'typescript', roots: [] }],
+ },
+ 'a unit whose only membership key is an empty files array': {
+ ...good,
+ units: [{ id: 'empty', family: 'typescript', files: [] }],
+ },
+ 'an exclude entry that is an array, not a string': { ...good, exclude: [['dist']] },
+ 'a version that is an array, not an integer': { ...good, version: [1] },
+ };
+ for (const [label, mutant] of Object.entries(mutants)) {
+ const scrubbed = JSON.parse(JSON.stringify(mutant));
+ expect({ label, errors: validate(scrubbed).length > 0 }).toEqual({ label, errors: true });
+ expect({ label, loader: throwsOnLoad(scrubbed) }).toEqual({ label, loader: true });
+ }
+ });
+
+ test('every shape the loader accepts, the schema accepts too', () => {
+ const good = JSON.parse(stripJsonc(configText));
+ const accepted = {
+ 'a unit carried entirely by explicit files': {
+ ...good,
+ units: [{ id: 'hooks', family: 'shell', files: ['.husky/pre-commit'] }],
+ },
+ 'a unit that declares both roots and files': {
+ ...good,
+ units: [{ id: 'both', family: 'shell', roots: ['scripts'], files: ['.husky/pre-commit'] }],
+ },
+ 'a files entry whose extension its own family declares': {
+ ...good,
+ units: [{ id: 'app', family: 'esm-script', roots: ['scripts'], files: ['tools/one.mjs'] }],
+ },
+ 'a unit that opts out of the non-vacuity floor': {
+ ...good,
+ units: [{ id: 'app', family: 'typescript', roots: ['packages/*/src'], allowEmpty: true }],
+ },
+ };
+ for (const [label, shape] of Object.entries(accepted)) {
+ const scrubbed = JSON.parse(JSON.stringify(shape));
+ expect({ label, loader: throwsOnLoad(scrubbed) }).toEqual({ label, loader: false });
+ expect({ label, errors: validate(scrubbed) }).toEqual({ label, errors: [] });
+ }
+ });
+
+ test('the validator refuses to run against a keyword it does not implement', () => {
+ expect(() => validate({}, { type: 'object', maxProperties: 1 })).toThrow(/maxProperties/);
+ expect(() => validate({}, { type: 'object', maxProperties: 1 })).toThrow(/fiction/);
+ });
+
+ test('the validator refuses an applied keyword beside a $ref rather than ignoring it', () => {
+ expect(() => validate('x', { $ref: '#/$defs/glob', minLength: 99 })).toThrow(/beside a \$ref/);
+ expect(() => validate('x', { $ref: '#/$defs/glob', description: 'fine' })).not.toThrow();
+ });
+
+ test('every shape the schema accepts, the loader accepts too', () => {
+ const good = JSON.parse(stripJsonc(configText));
+ const schemaLegal = {
+ 'a brace alternation in roots': {
+ ...good,
+ units: [{ id: 'app', family: 'typescript', roots: ['packages/{app,core}/src'] }],
+ },
+ 'a brace alternation in exclude': { ...good, exclude: ['**/{dist,build}/**'] },
+ 'a dot root': { ...good, units: [{ id: 'root', family: 'typescript', roots: ['.'] }] },
+ 'a trailing slash on a root': {
+ ...good,
+ units: [{ id: 'app', family: 'typescript', roots: ['packages/'] }],
+ },
+ };
+ for (const [label, shape] of Object.entries(schemaLegal)) {
+ const scrubbed = JSON.parse(JSON.stringify(shape));
+ expect({ label, errors: validate(scrubbed) }).toEqual({ label, errors: [] });
+ expect({ label, loader: throwsOnLoad(scrubbed) }).toEqual({ label, loader: false });
+ }
+ });
+
+ test('every character the loader refuses in a glob, the schema refuses by name', () => {
+ const printable = Array.from({ length: 95 }, (_, index) => String.fromCharCode(32 + index));
+ const preExpansion = printable.filter(
+ (char) => UNSUPPORTED_GLOB_SYNTAX.test(char) && char !== '{' && char !== '}',
+ );
+ expect(preExpansion.length).toBeGreaterThan(0);
+
+ const good = JSON.parse(stripJsonc(configText));
+ for (const char of preExpansion) {
+ const scrubbed = JSON.parse(
+ JSON.stringify({
+ ...good,
+ units: [{ id: 'probe', family: 'typescript', roots: [`packages/a${char}b/src`] }],
+ }),
+ );
+ expect({ char, schema: validate(scrubbed).join('\n') }).toEqual({
+ char,
+ schema: expect.stringContaining('.units[0].roots[0] does not match'),
+ });
+ expect({ char, loader: throwsOnLoad(scrubbed) }).toEqual({ char, loader: true });
+ }
+ });
+});
+
+function throwsOnLoad(value) {
+ try {
+ parseScopeConfig(JSON.stringify(value), { configPath: CONFIG_PATH });
+ return false;
+ } catch {
+ return true;
+ }
+}
diff --git a/lint-plugins/no-comments/config.mjs b/lint-plugins/no-comments/config.mjs
new file mode 100644
index 000000000..1bcec4a2a
--- /dev/null
+++ b/lint-plugins/no-comments/config.mjs
@@ -0,0 +1,437 @@
+import { existsSync as nodeExistsSync, readFileSync as nodeReadFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { extractComments } from './extract.mjs';
+
+export const SCOPE_CONFIG_FILENAME = 'no-comments.config.jsonc';
+
+const SCOPE_CONFIG_SCHEMA_PATH = 'lint-plugins/no-comments/no-comments.config.schema.json';
+
+export const SUPPORTED_CONFIG_MAJOR = 1;
+
+export class ScopeConfigError extends Error {
+ constructor({ configPath, key, detail }) {
+ super(`${configPath}: ${key ? `${key}: ` : ''}${detail}`);
+ this.name = 'ScopeConfigError';
+ this.configPath = configPath;
+ this.key = key;
+ this.detail = detail;
+ }
+}
+
+export class ScopeConfigMissingError extends Error {
+ constructor({ root, configPath }) {
+ super(
+ `scope-config: NOT FOUND at ${root}. The predicate reads its scope from a ${SCOPE_CONFIG_FILENAME} ` +
+ 'at the root it is pointed at; enumerating a tree with none would silently apply another ' +
+ "repository's scope to it. " +
+ `Write one at ${configPath}: it validates against ${SCOPE_CONFIG_SCHEMA_PATH} beside this ` +
+ `predicate, whose own ${SCOPE_CONFIG_FILENAME} is a working example.`,
+ );
+ this.name = 'ScopeConfigMissingError';
+ this.root = root;
+ this.configPath = configPath;
+ }
+}
+
+export function stripJsonc(text) {
+ let blanked = '';
+ let cursor = 0;
+ for (const comment of extractComments(text, { jsx: false })) {
+ blanked += text.slice(cursor, comment.start);
+ blanked += text.slice(comment.start, comment.end).replace(/[^\n]/g, ' ');
+ cursor = comment.end;
+ }
+ blanked += text.slice(cursor);
+
+ let stripped = '';
+ let inString = false;
+ for (let index = 0; index < blanked.length; index += 1) {
+ const char = blanked[index];
+ if (inString) {
+ stripped += char;
+ if (char === '\\') {
+ index += 1;
+ stripped += blanked[index] ?? '';
+ } else if (char === '"') {
+ inString = false;
+ }
+ continue;
+ }
+ if (char === '"') {
+ inString = true;
+ stripped += char;
+ continue;
+ }
+ if (char === ',') {
+ let ahead = index + 1;
+ while (ahead < blanked.length && /\s/.test(blanked[ahead])) ahead += 1;
+ stripped += blanked[ahead] === '}' || blanked[ahead] === ']' ? ' ' : char;
+ continue;
+ }
+ stripped += char;
+ }
+ return stripped;
+}
+
+export function expandBraces(glob) {
+ const open = glob.indexOf('{');
+ if (open === -1) {
+ if (glob.includes('}')) throw new Error(`unbalanced brace in glob ${glob}`);
+ return [glob];
+ }
+ let depth = 0;
+ for (let index = open; index < glob.length; index += 1) {
+ if (glob[index] === '{') depth += 1;
+ else if (glob[index] === '}') depth -= 1;
+ if (depth !== 0) continue;
+ const body = glob.slice(open + 1, index);
+ const members = splitTopLevel(body);
+ if (glob[open - 1] === '\\') {
+ throw new Error(
+ `escaped brace in glob ${glob}. Only comma alternations are implemented, and an escaped ` +
+ 'brace is a literal everywhere else; expanding it here would govern a set the config ' +
+ 'never named.',
+ );
+ }
+ if (body.includes('\\')) {
+ throw new Error(
+ `escaped character in the brace body of glob ${glob}. Only comma alternations are ` +
+ 'implemented, and the reference expanders treat a backslash as an escape, so splitting ' +
+ 'on the comma it protects would govern a set the config never named.',
+ );
+ }
+ if (members.length === 1 && members[0].includes('..')) {
+ throw new Error(
+ `sequence expression in glob ${glob}. Only comma alternations are implemented; a range ` +
+ 'here compiles to a pattern that matches nothing rather than the paths it names.',
+ );
+ }
+ if (members.length < 2) {
+ throw new Error(
+ `${body === '' ? 'empty brace' : 'single-member brace'} in glob ${glob}. Only comma ` +
+ 'alternations are implemented; every other reference treats this as a literal, so ' +
+ 'expanding it away silently governs a different directory than the one written.',
+ );
+ }
+ const head = glob.slice(0, open);
+ const tail = glob.slice(index + 1);
+ return members.flatMap((member) => expandBraces(`${head}${member}${tail}`));
+ }
+ throw new Error(`unbalanced brace in glob ${glob}`);
+}
+
+function splitTopLevel(body) {
+ const members = [];
+ let depth = 0;
+ let start = 0;
+ for (let index = 0; index < body.length; index += 1) {
+ if (body[index] === '{') depth += 1;
+ else if (body[index] === '}') depth -= 1;
+ else if (body[index] === ',' && depth === 0) {
+ members.push(body.slice(start, index));
+ start = index + 1;
+ }
+ }
+ members.push(body.slice(start));
+ return members;
+}
+
+const CONFIG_KEYS = new Set(['$schema', 'version', 'families', 'units', 'exclude']);
+const FAMILY_KEYS = new Set(['extensions', 'extractor']);
+const UNIT_KEYS = new Set(['id', 'family', 'roots', 'files', 'allowEmpty']);
+const DIRECTORY_SHAPED_EXCLUDE = /^\*\*\/([^/*]+)\/\*\*$/;
+
+const REPOSITORY_ROOT = '.';
+
+const ABSOLUTE_PATH = /^(?:[/\\]|[A-Za-z]:[/\\])/;
+
+function canonicalizeConfigPath(value, key, fail) {
+ if (ABSOLUTE_PATH.test(value)) {
+ fail(
+ key,
+ `is the absolute path ${JSON.stringify(value)}. Every path here is relative to the root the ` +
+ 'predicate is pointed at, and an absolute one names a location that root does not own. ' +
+ 'Normalizing it would have to guess which prefix to drop, and guessing wrong moves a whole ' +
+ 'unit somewhere nobody declared, so an absolute path is refused rather than rewritten.',
+ );
+ }
+ let path = value.replace(/\/{2,}/g, '/');
+ while (path.startsWith('./')) path = path.slice(2);
+ path = path.replace(/\/+$/, '');
+ if (path === '' || path === REPOSITORY_ROOT) return REPOSITORY_ROOT;
+ if (path.split('/').includes('..')) {
+ fail(
+ key,
+ `walks out of the root with a .. segment (${JSON.stringify(value)}). Discovery only ever ` +
+ 'descends from the root, so a path that leaves it can never name a member; resolving the ' +
+ '.. would silently retarget the unit at a tree this config does not govern, so it is ' +
+ 'refused rather than rewritten.',
+ );
+ }
+ return path;
+}
+
+export function parseScopeConfig(text, { configPath }) {
+ const fail = (key, detail) => {
+ throw new ScopeConfigError({ configPath, key, detail });
+ };
+ let raw;
+ try {
+ raw = JSON.parse(stripJsonc(text));
+ } catch (error) {
+ fail(undefined, `is not parseable as JSONC (${error.message})`);
+ }
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
+ fail(undefined, 'must be a JSON object');
+ }
+ if (!Number.isInteger(raw.version)) {
+ fail('version', 'must be an integer naming the schema major this file is written against');
+ }
+ if (raw.version !== SUPPORTED_CONFIG_MAJOR) {
+ fail(
+ 'version',
+ `declares schema major ${raw.version}; this predicate reads major ${SUPPORTED_CONFIG_MAJOR}. ` +
+ 'Upgrade the predicate rather than loading a shape it cannot represent.',
+ );
+ }
+
+ const unknownKeys = Object.keys(raw).filter((key) => !CONFIG_KEYS.has(key));
+ const families = readFamilies(raw.families, fail, unknownKeys);
+ const exclude = readGlobList(raw.exclude, 'exclude', fail);
+ const units = readUnits(raw.units, families, fail, unknownKeys);
+
+ const include = units.flatMap((unit) => unit.include);
+
+ return {
+ version: raw.version,
+ configPath,
+ families,
+ units,
+ exclude,
+ include,
+ unknownKeys,
+ walkRoots: [
+ ...new Set(
+ units
+ .flatMap((unit) => unit.roots)
+ .filter((root) => root !== REPOSITORY_ROOT)
+ .map(firstSegment),
+ ),
+ ].sort(),
+ pruneDirectories: [
+ ...new Set(
+ exclude
+ .map((glob) => DIRECTORY_SHAPED_EXCLUDE.exec(glob)?.[1])
+ .filter((name) => name !== undefined),
+ ),
+ ].sort(),
+ declaredPaths: units.flatMap((unit) => [
+ ...unit.roots
+ .map((root) => literalPrefix(root))
+ .filter((prefix) => prefix !== REPOSITORY_ROOT)
+ .map((prefix) => ({ unit: unit.id, kind: 'root', path: prefix })),
+ ...unit.files.map((file) => ({ unit: unit.id, kind: 'file', path: file })),
+ ]),
+ };
+}
+
+function includeGlobFor(root, extension) {
+ return root === REPOSITORY_ROOT ? `*${extension}` : `${root}/**/*${extension}`;
+}
+
+function firstSegment(root) {
+ return root.split('/')[0];
+}
+
+function literalPrefix(root) {
+ const literal = [];
+ for (const segment of root.split('/')) {
+ if (segment.includes('*')) break;
+ literal.push(segment);
+ }
+ return literal.length === 0 ? REPOSITORY_ROOT : literal.join('/');
+}
+
+function readFamilies(value, fail, unknownKeys) {
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
+ fail('families', 'must be an object mapping a family id to its extensions and extractor');
+ }
+ const families = {};
+ for (const [id, family] of Object.entries(value)) {
+ if (family === null || typeof family !== 'object' || Array.isArray(family)) {
+ fail(`families.${id}`, 'must be an object');
+ }
+ const extensions = family.extensions;
+ if (!Array.isArray(extensions) || extensions.length === 0) {
+ fail(`families.${id}.extensions`, 'must be a non-empty array of file extensions');
+ }
+ extensions.forEach((extension, index) => {
+ if (typeof extension !== 'string' || !extension.startsWith('.') || extension.length < 2) {
+ fail(
+ `families.${id}.extensions[${index}]`,
+ 'must be a file extension with a leading dot and at least one character after it, got ' +
+ JSON.stringify(extension),
+ );
+ }
+ });
+ if (typeof family.extractor !== 'string' || family.extractor === '') {
+ fail(`families.${id}.extractor`, 'must name the extractor that reads this grammar family');
+ }
+ unknownKeys.push(
+ ...Object.keys(family)
+ .filter((key) => !FAMILY_KEYS.has(key))
+ .map((key) => `families.${id}.${key}`),
+ );
+ families[id] = { id, extensions: [...extensions], extractor: family.extractor };
+ }
+ return families;
+}
+
+function readUnits(value, families, fail, unknownKeys) {
+ if (!Array.isArray(value) || value.length === 0) {
+ fail('units', 'must be an array carrying at least one unit');
+ }
+ const seen = new Set();
+ return value.map((unit, index) => {
+ const at = `units[${index}]`;
+ if (unit === null || typeof unit !== 'object' || Array.isArray(unit))
+ fail(at, 'must be an object');
+ if (typeof unit.id !== 'string' || unit.id === '')
+ fail(`${at}.id`, 'must be a non-empty string');
+ if (seen.has(unit.id)) fail(`${at}.id`, `duplicate unit id ${unit.id}`);
+ seen.add(unit.id);
+ if (!Object.hasOwn(families, unit.family)) {
+ fail(
+ `${at}.family`,
+ `names family ${JSON.stringify(unit.family)}, which no families entry declares`,
+ );
+ }
+ const roots = readGlobList(unit.roots, `${at}.roots`, fail, { allowEmpty: true });
+ const files =
+ unit.files === undefined
+ ? []
+ : readGlobList(unit.files, `${at}.files`, fail, {
+ allowEmpty: true,
+ expand: false,
+ wildcards: false,
+ });
+ if (roots.length === 0 && files.length === 0) {
+ fail(`${at}.roots`, 'a unit with no roots and no files can never discover anything');
+ }
+ if (unit.allowEmpty !== undefined && typeof unit.allowEmpty !== 'boolean') {
+ fail(`${at}.allowEmpty`, 'must be a boolean');
+ }
+ unknownKeys.push(
+ ...Object.keys(unit)
+ .filter((key) => !UNIT_KEYS.has(key))
+ .map((key) => `${at}.${key}`),
+ );
+ return {
+ id: unit.id,
+ family: unit.family,
+ roots,
+ files,
+ allowEmpty: unit.allowEmpty === true,
+ include: [
+ ...roots.flatMap((root) =>
+ families[unit.family].extensions.map((extension) => includeGlobFor(root, extension)),
+ ),
+ ...files,
+ ],
+ };
+ });
+}
+
+export const UNSUPPORTED_GLOB_SYNTAX = /[?!{}[\]()]/;
+
+function assertLiteralPath(entry) {
+ if (!entry.includes('*')) return;
+ throw new Error(
+ `wildcard in ${entry}. A files entry names one path: discovery stats it literally, so a ` +
+ 'wildcard never adds a member, while the matcher still routes anything it matches into ' +
+ "this unit's family. That reads a file under a grammar its own extension did not choose, " +
+ 'which reports it clean rather than refusing. Name each path, or declare a root.',
+ );
+}
+
+function assertSupportedGlobSyntax(glob) {
+ if (!UNSUPPORTED_GLOB_SYNTAX.test(glob)) return;
+ throw new Error(
+ `unsupported glob syntax in ${glob}. The matcher implements literals, * and ** only, so a ` +
+ 'character class, a single-character wildcard, a negation, a group or an unexpanded brace ' +
+ 'would be read as a literal rather than refused, and the unit would govern a set nobody ' +
+ 'declared.',
+ );
+}
+
+function readGlobList(
+ value,
+ key,
+ fail,
+ { allowEmpty = false, expand = true, wildcards = true } = {},
+) {
+ if (value === undefined && allowEmpty) return [];
+ if (!Array.isArray(value)) fail(key, 'must be an array of globs');
+ value.forEach((glob, index) => {
+ if (typeof glob !== 'string' || glob === '')
+ fail(`${key}[${index}]`, 'must be a non-empty string');
+ });
+ let expanded;
+ try {
+ expanded = value.map((glob) => {
+ const members = expand ? expandBraces(glob) : [glob];
+ for (const member of members) {
+ assertSupportedGlobSyntax(member);
+ if (!wildcards) assertLiteralPath(member);
+ }
+ return members;
+ });
+ } catch (error) {
+ fail(key, error.message);
+ }
+ return expanded.flatMap((members, index) =>
+ members.map((member) => canonicalizeConfigPath(member, `${key}[${index}]`, fail)),
+ );
+}
+
+export function loadScopeConfig(
+ root,
+ { readFileSync = nodeReadFileSync, existsSync = nodeExistsSync } = {},
+) {
+ const configPath = join(root, SCOPE_CONFIG_FILENAME);
+ let text;
+ try {
+ text = readFileSync(configPath, 'utf8');
+ } catch (error) {
+ if (error?.code === 'ENOENT') return null;
+ throw new ScopeConfigError({
+ configPath,
+ detail: `could not be read (${error?.code ?? error?.message ?? 'unknown error'})`,
+ });
+ }
+ const config = parseScopeConfig(text, { configPath });
+ return {
+ ...config,
+ root,
+ declaredAbsent: config.declaredPaths.filter(({ path }) => !existsSync(join(root, path))),
+ };
+}
+
+export function unitsRequiringFiles(config) {
+ if (!Array.isArray(config?.declaredAbsent)) {
+ throw new TypeError(
+ 'unitsRequiringFiles needs a config carrying declaredAbsent, which only loadScopeConfig ' +
+ 'computes; a parseScopeConfig result has never stat-ed the tree, so every declared path ' +
+ 'would read as present.',
+ );
+ }
+ const key = ({ unit, kind, path }) => `${unit}\u0000${kind}\u0000${path}`;
+ const absent = new Set(config.declaredAbsent.map(key));
+ return config.units
+ .filter((unit) => !unit.allowEmpty)
+ .filter((unit) => {
+ const declared = config.declaredPaths.filter((entry) => entry.unit === unit.id);
+ return !(declared.length > 0 && declared.every((entry) => absent.has(key(entry))));
+ })
+ .map((unit) => unit.id);
+}
diff --git a/lint-plugins/no-comments/config.test.mjs b/lint-plugins/no-comments/config.test.mjs
new file mode 100644
index 000000000..f14f0bc4d
--- /dev/null
+++ b/lint-plugins/no-comments/config.test.mjs
@@ -0,0 +1,301 @@
+import { describe, expect, test } from 'vitest';
+import { expandBraces, parseScopeConfig, ScopeConfigError, stripJsonc } from './config.mjs';
+
+const MINIMAL = {
+ version: 1,
+ families: { ts: { extensions: ['.ts'], extractor: 'c-family' } },
+ units: [{ id: 'src', family: 'ts', roots: ['packages/**/src'] }],
+ exclude: [],
+};
+
+const parse = (value) => parseScopeConfig(JSON.stringify(value), { configPath: '/t/cfg.jsonc' });
+
+describe('stripJsonc', () => {
+ test('blanks comments in place so JSON.parse reports the authored position', () => {
+ const text = '{\n // a line comment\n "version": 1 /* trailing */\n}';
+ const stripped = stripJsonc(text);
+ expect(JSON.parse(stripped)).toEqual({ version: 1 });
+ expect(stripped.split('\n')).toHaveLength(4);
+ });
+
+ test('leaves comment-shaped text inside strings alone', () => {
+ const text = '{"a": "https://example.test/x", "b": "/* not a comment */"}';
+ expect(JSON.parse(stripJsonc(text))).toEqual({
+ a: 'https://example.test/x',
+ b: '/* not a comment */',
+ });
+ });
+
+ test('blanks by UTF-16 code unit, so an astral character does not shift the span', () => {
+ const text = '{\n // \u{1D106} comment\n "a": "\u{1D106}"\n}';
+ const stripped = stripJsonc(text);
+ expect(stripped).toHaveLength(text.length);
+ expect(JSON.parse(stripped)).toEqual({ a: '\u{1D106}' });
+ });
+
+ test('drops trailing commas an editor may leave behind', () => {
+ expect(JSON.parse(stripJsonc('{"a": [1, 2,], "b": 3,}'))).toEqual({ a: [1, 2], b: 3 });
+ });
+
+ test('keeps a comma that only looks trailing because a string contains a brace', () => {
+ expect(JSON.parse(stripJsonc('{"a": "x,}", "b": 1}'))).toEqual({ a: 'x,}', b: 1 });
+ });
+});
+
+describe('expandBraces', () => {
+ test('expands one alternation into one glob per member', () => {
+ expect(expandBraces('**/*.fixture.{ts,tsx,mjs}')).toEqual([
+ '**/*.fixture.ts',
+ '**/*.fixture.tsx',
+ '**/*.fixture.mjs',
+ ]);
+ });
+
+ test('expands nested alternations to their cross product', () => {
+ expect(expandBraces('{a,b}/{c,d}')).toEqual(['a/c', 'a/d', 'b/c', 'b/d']);
+ });
+
+ test('leaves a brace-free glob as a single member', () => {
+ expect(expandBraces('packages/**/src/**/*.ts')).toEqual(['packages/**/src/**/*.ts']);
+ });
+
+ test('refuses an unbalanced brace rather than emitting it for the matcher to reject', () => {
+ expect(() => expandBraces('a/{b,c')).toThrow(/unbalanced/);
+ });
+});
+
+describe('membership derivation', () => {
+ test('include is roots times the family extensions, never restated', () => {
+ const config = parse({
+ ...MINIMAL,
+ families: { ts: { extensions: ['.ts', '.tsx'], extractor: 'c-family' } },
+ units: [{ id: 'src', family: 'ts', roots: ['packages/**/src', 'docs'] }],
+ });
+ expect(config.include).toEqual([
+ 'packages/**/src/**/*.ts',
+ 'packages/**/src/**/*.tsx',
+ 'docs/**/*.ts',
+ 'docs/**/*.tsx',
+ ]);
+ });
+
+ test('the repository root is the one non-recursive root', () => {
+ const config = parse({
+ ...MINIMAL,
+ families: { cfg: { extensions: ['.ts', '.mts'], extractor: 'c-family' } },
+ units: [{ id: 'root-configs', family: 'cfg', roots: ['.'] }],
+ });
+ expect(config.include).toEqual(['*.ts', '*.mts']);
+ });
+
+ test('explicit files are members whatever their extension', () => {
+ const config = parse({
+ ...MINIMAL,
+ units: [
+ { id: 'hooks', family: 'ts', roots: [], files: ['.husky/pre-push'], allowEmpty: true },
+ ],
+ });
+ expect(config.include).toEqual(['.husky/pre-push']);
+ expect(config.units[0].files).toEqual(['.husky/pre-push']);
+ });
+
+ test('walk roots are the first segment of each declared root', () => {
+ const config = parse({
+ ...MINIMAL,
+ units: [
+ { id: 'a', family: 'ts', roots: ['packages/**/src', '.github/scripts'] },
+ { id: 'b', family: 'ts', roots: ['packages/**/tests', '.'] },
+ ],
+ });
+ expect(config.walkRoots).toEqual(['.github', 'packages']);
+ });
+
+ test('a directory-name-shaped exclude becomes a walk prune, a path-shaped one does not', () => {
+ const config = parse({
+ ...MINIMAL,
+ exclude: ['**/node_modules/**', '**/dist/**', 'packages/app/src/build/**', '**/*.d.ts'],
+ });
+ expect(config.pruneDirectories).toEqual(['dist', 'node_modules']);
+ });
+
+ test('brace forms in exclude expand at load so the matcher never sees a brace', () => {
+ const config = parse({ ...MINIMAL, exclude: ['**/*.fixture.{ts,tsx}'] });
+ expect(config.exclude).toEqual(['**/*.fixture.ts', '**/*.fixture.tsx']);
+ });
+});
+
+describe('path-shaped values are canonical after load', () => {
+ test('a leading ./ is stripped from roots, files and exclude alike', () => {
+ const config = parse({
+ ...MINIMAL,
+ units: [
+ {
+ id: 'src',
+ family: 'ts',
+ roots: ['./packages/**/src'],
+ files: ['./.husky/pre-push'],
+ },
+ ],
+ exclude: ['.//**/dist/**'],
+ });
+ expect(config.units[0].roots).toEqual(['packages/**/src']);
+ expect(config.units[0].files).toEqual(['.husky/pre-push']);
+ expect(config.exclude).toEqual(['**/dist/**']);
+ expect(config.include).toEqual(['packages/**/src/**/*.ts', '.husky/pre-push']);
+ });
+
+ test('a trailing slash on a root normalizes to the root without one', () => {
+ const slashed = parse({
+ ...MINIMAL,
+ units: [{ id: 'src', family: 'ts', roots: ['packages/'] }],
+ });
+ const bare = parse({ ...MINIMAL, units: [{ id: 'src', family: 'ts', roots: ['packages'] }] });
+ expect(slashed.units[0].roots).toEqual(['packages']);
+ expect(slashed.include).toEqual(bare.include);
+ expect(slashed.walkRoots).toEqual(bare.walkRoots);
+ expect(slashed.declaredPaths).toEqual(bare.declaredPaths);
+ });
+
+ test('repeated slashes collapse', () => {
+ const config = parse({
+ ...MINIMAL,
+ units: [{ id: 'src', family: 'ts', roots: ['packages//app//src'] }],
+ });
+ expect(config.units[0].roots).toEqual(['packages/app/src']);
+ });
+
+ test('every spelling of the repository root canonicalizes to the one the matcher reads', () => {
+ for (const spelling of ['.', './', './/', './//']) {
+ const config = parse({
+ ...MINIMAL,
+ units: [{ id: 'root', family: 'ts', roots: [spelling] }],
+ });
+ expect({ spelling, roots: config.units[0].roots }).toEqual({ spelling, roots: ['.'] });
+ expect({ spelling, include: config.include }).toEqual({ spelling, include: ['*.ts'] });
+ expect({ spelling, walkRoots: config.walkRoots }).toEqual({ spelling, walkRoots: [] });
+ expect({ spelling, declared: config.declaredPaths }).toEqual({ spelling, declared: [] });
+ }
+ });
+
+ test('canonicalization survives brace expansion, which can hide a ./ inside a member', () => {
+ const config = parse({ ...MINIMAL, exclude: ['{./docs,packages/}/**'] });
+ expect(config.exclude).toEqual(['docs/**', 'packages/**']);
+ });
+});
+
+describe('a path that leaves the root is refused, not normalized', () => {
+ const cases = [
+ ['units[0].roots[0]', { roots: ['../sibling/src'] }, /\.\. segment/],
+ ['units[0].roots[1]', { roots: ['packages', 'packages/../../escape'] }, /\.\. segment/],
+ ['units[0].roots[0]', { roots: ['./../sibling'] }, /\.\. segment/],
+ ['units[0].roots[0]', { roots: ['/abs/path'] }, /absolute path/],
+ ['units[0].roots[0]', { roots: ['C:/abs/path'] }, /absolute path/],
+ ['units[0].files[0]', { roots: ['packages'], files: ['../outside'] }, /\.\. segment/],
+ ['units[0].files[0]', { roots: ['packages'], files: ['/etc/passwd'] }, /absolute path/],
+ ];
+
+ test.each(cases)('%s', (key, unit, detail) => {
+ let thrown;
+ try {
+ parse({ ...MINIMAL, units: [{ id: 'src', family: 'ts', ...unit }] });
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toBeInstanceOf(ScopeConfigError);
+ expect(thrown.key).toBe(key);
+ expect(thrown.message).toMatch(detail);
+ expect(thrown.message).toContain('/t/cfg.jsonc');
+ });
+
+ test('an escaping exclude is refused by its own key path', () => {
+ let thrown;
+ try {
+ parse({ ...MINIMAL, exclude: ['**/dist/**', '../elsewhere/**'] });
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toBeInstanceOf(ScopeConfigError);
+ expect(thrown.key).toBe('exclude[1]');
+ });
+
+ test('a .. that is only a filename prefix is an ordinary path', () => {
+ const config = parse({ ...MINIMAL, exclude: ['packages/..hidden/**', 'a/..b'] });
+ expect(config.exclude).toEqual(['packages/..hidden/**', 'a/..b']);
+ });
+});
+
+describe('declared paths', () => {
+ test('a glob-bearing root declares only its literal prefix, so existence stays checkable', () => {
+ const config = parse({
+ ...MINIMAL,
+ units: [
+ { id: 'a', family: 'ts', roots: ['packages/**/src', '.github/scripts', '.'] },
+ { id: 'b', family: 'ts', roots: [], files: ['.husky/pre-push'], allowEmpty: true },
+ ],
+ });
+ expect(config.declaredPaths).toEqual([
+ { unit: 'a', kind: 'root', path: 'packages' },
+ { unit: 'a', kind: 'root', path: '.github/scripts' },
+ { unit: 'b', kind: 'file', path: '.husky/pre-push' },
+ ]);
+ });
+});
+
+describe('config errors name the file and the key', () => {
+ const cases = [
+ ['version', { ...MINIMAL, version: 2 }, /version/],
+ ['version', { ...MINIMAL, version: '1' }, /version/],
+ ['units[0].family', { ...MINIMAL, units: [{ id: 'x', family: 'nope', roots: ['a'] }] }, /nope/],
+ ['units', { ...MINIMAL, units: [] }, /at least one/],
+ ['units[1].id', { ...MINIMAL, units: [...MINIMAL.units, MINIMAL.units[0]] }, /duplicate/],
+ [
+ 'families.ts.extensions[0]',
+ { ...MINIMAL, families: { ts: { extensions: ['ts'], extractor: 'c-family' } } },
+ /leading dot/,
+ ],
+ [
+ 'families.ts.extractor',
+ { ...MINIMAL, families: { ts: { extensions: ['.ts'] } } },
+ /extractor/,
+ ],
+ ['exclude', { ...MINIMAL, exclude: 'nope' }, /array/],
+ ];
+
+ test.each(cases)('%s', (key, value, detail) => {
+ let thrown;
+ try {
+ parse(value);
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toBeInstanceOf(ScopeConfigError);
+ expect(thrown.configPath).toBe('/t/cfg.jsonc');
+ expect(thrown.key).toBe(key);
+ expect(thrown.message).toMatch(detail);
+ expect(thrown.message).toContain('/t/cfg.jsonc');
+ });
+
+ test('a syntax error carries the config path', () => {
+ expect(() => parseScopeConfig('{', { configPath: '/t/cfg.jsonc' })).toThrow(ScopeConfigError);
+ });
+
+ test('an unrecognized major is refused by name, not silently coerced', () => {
+ expect(() => parse({ ...MINIMAL, version: 99 })).toThrow(/major 99/);
+ });
+});
+
+describe('tolerance', () => {
+ test('an unknown additive key under a recognized major loads and is reported', () => {
+ const config = parse({ ...MINIMAL, futureKnob: { on: true } });
+ expect(config.unknownKeys).toEqual(['futureKnob']);
+ expect(config.include).toEqual(['packages/**/src/**/*.ts']);
+ });
+
+ test('an unknown key inside a unit is tolerated the same way', () => {
+ const config = parse({
+ ...MINIMAL,
+ units: [{ id: 'src', family: 'ts', roots: ['packages/**/src'], futureKnob: 1 }],
+ });
+ expect(config.unknownKeys).toEqual(['units[0].futureKnob']);
+ });
+});
diff --git a/lint-plugins/no-comments/directive-consumers.test.mjs b/lint-plugins/no-comments/directive-consumers.test.mjs
new file mode 100644
index 000000000..cfe38e19c
--- /dev/null
+++ b/lint-plugins/no-comments/directive-consumers.test.mjs
@@ -0,0 +1,180 @@
+import { readdirSync, readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+import { classifyComment, DIRECTIVE_PATTERNS } from './allowlist.mjs';
+import { extractComments } from './extract.mjs';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+const DEPENDENCY_FIELDS = [
+ 'dependencies',
+ 'devDependencies',
+ 'peerDependencies',
+ 'optionalDependencies',
+];
+
+function readJson(path) {
+ try {
+ return JSON.parse(readFileSync(join(REPO_ROOT, path), 'utf8'));
+ } catch (error) {
+ if (error?.code === 'ENOENT') return null;
+ throw error;
+ }
+}
+
+function listDirectories(relPath) {
+ try {
+ return readdirSync(join(REPO_ROOT, relPath), { withFileTypes: true })
+ .filter((entry) => entry.isDirectory())
+ .map((entry) => `${relPath}/${entry.name}`);
+ } catch (error) {
+ if (error?.code === 'ENOENT') return [];
+ throw error;
+ }
+}
+
+const WORKSPACE_MANIFESTS = ['.', 'docs', ...listDirectories('packages')]
+ .map((dir) => ({ dir, manifest: readJson(dir === '.' ? 'package.json' : `${dir}/package.json`) }))
+ .filter((entry) => entry.manifest !== null);
+
+const LOCKFILE = readFileSync(join(REPO_ROOT, 'pnpm-lock.yaml'), 'utf8');
+
+function manifestsDeclaring(name) {
+ return WORKSPACE_MANIFESTS.filter(({ manifest }) =>
+ DEPENDENCY_FIELDS.some((field) => manifest[field]?.[name] !== undefined),
+ );
+}
+
+function snapshotResolves(carrier, dependency) {
+ const snapshots = LOCKFILE.slice(LOCKFILE.indexOf('\nsnapshots:\n'));
+ const entry = new RegExp(
+ `\\n ${carrier}@[^\\n]*:\\n(?<body>(?: [^\\n]*\\n|\\n)+)`,
+ 'g',
+ );
+ for (const match of snapshots.matchAll(entry)) {
+ if (new RegExp(`^ ${dependency}: \\S`, 'm').test(match.groups.body)) return true;
+ }
+ return false;
+}
+
+const RESOLVERS = {
+ declared(consumer) {
+ const declaring = manifestsDeclaring(consumer.package);
+ expect(declaring.map(({ dir }) => dir), `nothing declares ${consumer.package}`).not.toEqual([]);
+ const invoking = declaring.filter(({ manifest }) => manifest.scripts?.[consumer.invokedBy]);
+ expect(
+ invoking.map(({ dir }) => dir),
+ `no package declaring ${consumer.package} runs a "${consumer.invokedBy}" script`,
+ ).not.toEqual([]);
+ },
+ transitive(consumer) {
+ const declaring = manifestsDeclaring(consumer.via);
+ expect(declaring.map(({ dir }) => dir), `nothing declares ${consumer.via}`).not.toEqual([]);
+ const invoking = declaring.filter(({ manifest }) => manifest.scripts?.[consumer.invokedBy]);
+ expect(
+ invoking.map(({ dir }) => dir),
+ `no package declaring ${consumer.via} runs a "${consumer.invokedBy}" script`,
+ ).not.toEqual([]);
+ expect(
+ snapshotResolves(consumer.via, consumer.package),
+ `the lockfile does not resolve ${consumer.package} under ${consumer.via}`,
+ ).toBe(true);
+ },
+ latent(consumer) {
+ const present = consumer.packages.filter((name) => manifestsDeclaring(name).length > 0);
+ expect(present, 'a latent consumer arrived; promote this row to a declared claim').toEqual([]);
+ expect(consumer.activatesWhen.length).toBeGreaterThan(0);
+ },
+ external(consumer) {
+ expect(consumer.consumer.length).toBeGreaterThan(0);
+ expect(consumer.admittedOn.length).toBeGreaterThan(0);
+ },
+};
+
+function tsconfigSources() {
+ const sources = ['.', 'docs', ...listDirectories('packages')]
+ .map((dir) => (dir === '.' ? 'tsconfig.json' : `${dir}/tsconfig.json`))
+ .map((path) => {
+ try {
+ return readFileSync(join(REPO_ROOT, path), 'utf8');
+ } catch (error) {
+ if (error?.code === 'ENOENT') return null;
+ throw error;
+ }
+ })
+ .filter((source) => source !== null);
+ expect(sources.length).toBeGreaterThan(0);
+ return sources;
+}
+
+describe('every admitted directive shape names a consumer this repo runs', () => {
+ test('the workspace surface the claims resolve against is really there', () => {
+ expect(WORKSPACE_MANIFESTS.length).toBeGreaterThan(3);
+ expect(LOCKFILE).toContain('\nsnapshots:\n');
+ });
+
+ test.each(DIRECTIVE_PATTERNS.map((pattern) => [pattern.id, pattern]))(
+ '%s carries a claim, a reach verdict, and the shapes it governs',
+ (_id, pattern) => {
+ expect(pattern.shapes.length).toBeGreaterThan(0);
+ expect(Object.keys(RESOLVERS)).toContain(pattern.consumer.kind);
+ expect(['reached', 'unreached', 'latent']).toContain(pattern.reach.verdict);
+ if (pattern.reach.verdict !== 'reached') {
+ expect(pattern.reach.note.length, `${_id} records no reach verdict`).toBeGreaterThan(0);
+ }
+ },
+ );
+
+ test.each(DIRECTIVE_PATTERNS.map((pattern) => [pattern.id, pattern.consumer]))(
+ '%s resolves its consumer claim',
+ (_id, consumer) => {
+ RESOLVERS[consumer.kind](consumer);
+ },
+ );
+
+ test('every claim kind the table uses has a resolver, and every resolver is used', () => {
+ const used = new Set(DIRECTIVE_PATTERNS.map((pattern) => pattern.consumer.kind));
+ expect([...used].sort()).toStrictEqual(Object.keys(RESOLVERS).sort());
+ });
+
+ test.each(
+ DIRECTIVE_PATTERNS.flatMap((pattern) =>
+ pattern.shapes.map((shape) => [`${pattern.id} governs ${shape}`, pattern.id, shape]),
+ ),
+ )('%s', (_label, id, shape) => {
+ const source = shape.startsWith('/') ? shape : `// ${shape}`;
+ const [comment] = extractComments(source.replace(/\{[^}]+\}/g, 'x'), { jsx: false });
+ const verdict = classifyComment(comment, { precedentRegistry: new Set() });
+ expect({ allowed: verdict.allowed, detail: verdict.detail }).toStrictEqual({
+ allowed: true,
+ detail: id,
+ });
+ });
+
+ test('no shape is claimed by two entries', () => {
+ const shapes = DIRECTIVE_PATTERNS.flatMap((pattern) => pattern.shapes);
+ expect(shapes.length).toBe(new Set(shapes).size);
+ });
+
+ test('one entry per governable shape: no id is spelled twice', () => {
+ const ids = DIRECTIVE_PATTERNS.map((pattern) => pattern.id);
+ expect(ids.length).toBe(new Set(ids).size);
+ });
+});
+
+describe('the dispositions that removed a shape stay justified by the config that removed it', () => {
+ test('no tsconfig selects a classic JSX runtime, so the factory pragmas stay out', () => {
+ const classic = tsconfigSources().filter((source) =>
+ /"jsx"\s*:\s*"(?:react|preserve|react-native)"/.test(source),
+ );
+ expect(classic, 're-admit @jsx and @jsxFrag: a tsconfig went back to the classic runtime').toEqual(
+ [],
+ );
+ });
+
+ test('no tsconfig sets checkJs, which is what leaves @ts-check unreached', () => {
+ const checking = tsconfigSources().filter((source) => /"checkJs"\s*:\s*true/.test(source));
+ expect(checking, 'promote the @ts-check reach verdict: checkJs is on somewhere').toEqual([]);
+ });
+});
diff --git a/lint-plugins/no-comments/discovery-symlinks.test.mjs b/lint-plugins/no-comments/discovery-symlinks.test.mjs
new file mode 100644
index 000000000..59a90164d
--- /dev/null
+++ b/lint-plugins/no-comments/discovery-symlinks.test.mjs
@@ -0,0 +1,286 @@
+import {
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ rmSync,
+ statSync,
+ symlinkSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { afterAll, describe, expect, test } from 'vitest';
+import * as scope from './scope.mjs';
+import { discoverInScopeFiles, discoverInScopeFilesWithSkips } from './scope.mjs';
+
+const roots = [];
+
+afterAll(() => {
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+});
+
+function file(root, relPath, contents = 'export const a = 1;\n') {
+ const abs = join(root, relPath);
+ mkdirSync(dirname(abs), { recursive: true });
+ writeFileSync(abs, contents);
+}
+
+function link(root, relPath, target) {
+ const abs = join(root, relPath);
+ mkdirSync(dirname(abs), { recursive: true });
+ symlinkSync(target, abs);
+}
+
+const ADOPTER_CONFIG = {
+ version: 1,
+ families: {
+ typescript: { extensions: ['.ts'], extractor: 'c-family' },
+ 'esm-script': { extensions: ['.mjs'], extractor: 'c-family' },
+ },
+ units: [
+ { id: 'packages-src', family: 'typescript', roots: ['packages/**/src'] },
+ { id: 'docs', family: 'typescript', roots: ['docs'] },
+ { id: 'root-configs', family: 'typescript', roots: ['.'] },
+ { id: 'scripts', family: 'esm-script', roots: ['scripts'] },
+ { id: 'lint-plugins', family: 'esm-script', roots: ['lint-plugins'] },
+ ],
+ exclude: ['**/node_modules/**'],
+};
+
+function adopterRoot(prefix) {
+ const root = mkdtempSync(join(tmpdir(), prefix));
+ roots.push(root);
+ writeFileSync(join(root, 'no-comments.config.jsonc'), JSON.stringify(ADOPTER_CONFIG, null, 2));
+ return root;
+}
+
+function syntheticRoot() {
+ const root = adopterRoot('no-comments-symlinks-');
+
+ file(root, 'packages/realpkg/src/real.ts');
+ file(root, 'scripts/real.mjs');
+ file(root, 'scripts/notes.txt', 'not a source file\n');
+ file(root, 'real-root-config.ts');
+ file(root, 'real-target-file.mjs');
+ file(root, 'real-target-dir/src/inner.ts');
+ file(root, 'real-docs-target/page.ts');
+
+ link(root, 'scripts/linked.mjs', '../real-target-file.mjs');
+ link(root, 'packages/linkedpkg', '../real-target-dir');
+ link(root, 'lint-plugins/linkdir.mjs', '../real-target-dir');
+ link(root, 'linked-root.ts', 'real-root-config.ts');
+ link(root, 'dangling-root.ts', 'nowhere-at-all.ts');
+ link(root, 'docs', 'real-docs-target');
+ link(root, 'scripts/broken.mjs', 'nowhere-at-all.mjs');
+
+ file(root, 'packages/realpkg/node_modules/dep/src/dep.ts');
+ link(root, 'packages/realpkg/node_modules/loop', '../../..');
+
+ return root;
+}
+
+const realFs = { readdirSync, statSync, lstatSync };
+
+describe('discovery over a root that carries every symlink shape', () => {
+ const root = syntheticRoot();
+ const result = discoverInScopeFilesWithSkips(root, realFs);
+
+ test('the real in-scope files are still found, and the out-of-scope sibling is not', () => {
+ expect(result.files).toStrictEqual([
+ 'packages/realpkg/src/real.ts',
+ 'real-root-config.ts',
+ 'scripts/real.mjs',
+ ]);
+ });
+
+ test('every symlink that would have contributed to discovery is a recorded skip', () => {
+ expect(result.skips).toStrictEqual([
+ { path: 'dangling-root.ts', reason: 'symlink' },
+ { path: 'docs', reason: 'symlink' },
+ { path: 'linked-root.ts', reason: 'symlink' },
+ { path: 'lint-plugins/linkdir.mjs', reason: 'symlink' },
+ { path: 'packages/linkedpkg', reason: 'symlink-directory' },
+ { path: 'scripts/broken.mjs', reason: 'symlink' },
+ { path: 'scripts/linked.mjs', reason: 'symlink' },
+ ]);
+ });
+
+ test('the public discoverer refuses the root rather than reporting a short list as clean', () => {
+ expect(() => discoverInScopeFiles(root, realFs)).toThrow(/discovery could not read 7/);
+ });
+
+ test('the remedy the refusal names is a function a caller can import', () => {
+ expect(() => discoverInScopeFiles(root, realFs)).toThrow(/discoverInScopeFilesWithSkips/);
+ expect(typeof scope.discoverInScopeFilesWithSkips).toBe('function');
+ });
+});
+
+describe('a directory the exclude names is pruned, not walked and filtered', () => {
+ const root = syntheticRoot();
+ const prune = scope.scopeForRoot(root).pruneDirectories;
+
+ const observe = () => {
+ const pruned = [];
+ const read = [];
+ const result = discoverInScopeFilesWithSkips(root, {
+ readdirSync: (dir) => {
+ read.push(dir);
+ const entries = readdirSync(dir);
+ for (const entry of entries) if (prune.has(entry)) pruned.push(entry);
+ return entries;
+ },
+ statSync,
+ lstatSync,
+ });
+ return { pruned, read, result };
+ };
+
+ test('the walk meets the vendored tree and prunes exactly the names the exclude declares', () => {
+ expect([...prune]).toStrictEqual(['node_modules']);
+ expect(observe().pruned).toStrictEqual(['node_modules']);
+ });
+
+ test('no directory inside the pruned tree is ever read, so its link farm cannot be reached', () => {
+ const { read, result } = observe();
+ expect(read.filter((dir) => dir.includes('node_modules'))).toStrictEqual([]);
+ expect(result.files).toStrictEqual([
+ 'packages/realpkg/src/real.ts',
+ 'real-root-config.ts',
+ 'scripts/real.mjs',
+ ]);
+ expect(result.skips.map((skip) => skip.path)).not.toContain(
+ 'packages/realpkg/node_modules/loop',
+ );
+ });
+});
+
+describe('a root that declares no scope is refused rather than judged by another tree', () => {
+ const root = mkdtempSync(join(tmpdir(), 'no-comments-unscoped-'));
+ roots.push(root);
+ file(root, 'packages/realpkg/src/real.ts');
+
+ test('discovery names the missing config and the root it looked in', () => {
+ expect(() => discoverInScopeFilesWithSkips(root, realFs)).toThrow(/scope-config: NOT FOUND/);
+ expect(() => discoverInScopeFilesWithSkips(root, realFs)).toThrow(/no-comments\.config\.jsonc/);
+ });
+});
+
+describe('the symlink branch cannot be turned off by the caller', () => {
+ const root = syntheticRoot();
+
+ test('omitting lstatSync is refused instead of silently following every link', () => {
+ expect(() => discoverInScopeFiles(root, { readdirSync, statSync })).toThrow(/lstatSync/);
+ expect(() => discoverInScopeFilesWithSkips(root, { readdirSync, statSync })).toThrow(
+ /lstatSync/,
+ );
+ });
+
+ test('omitting statSync is refused too, since a link to a directory needs a follow', () => {
+ expect(() => discoverInScopeFiles(root, { readdirSync, lstatSync })).toThrow(/statSync/);
+ });
+});
+
+describe('a tree with no symlinks discovers cleanly', () => {
+ const root = adopterRoot('no-comments-nosymlinks-');
+ file(root, 'packages/realpkg/src/real.ts');
+ file(root, 'scripts/real.mjs');
+
+ test('no skip is recorded and the public discoverer returns', () => {
+ expect(discoverInScopeFilesWithSkips(root, realFs).skips).toStrictEqual([]);
+ expect(discoverInScopeFiles(root, realFs)).toStrictEqual([
+ 'packages/realpkg/src/real.ts',
+ 'scripts/real.mjs',
+ ]);
+ });
+});
+
+describe('a declared file that exists but cannot be read is refused, never dropped', () => {
+ const declaringRoot = () => {
+ const root = mkdtempSync(join(tmpdir(), 'no-comments-unreadable-'));
+ roots.push(root);
+ writeFileSync(
+ join(root, 'no-comments.config.jsonc'),
+ JSON.stringify({
+ version: 1,
+ families: { shell: { extensions: ['.sh'], extractor: 'hash-family' } },
+ units: [
+ {
+ id: 'shell',
+ family: 'shell',
+ roots: ['scripts'],
+ files: ['.husky/pre-commit', '.husky/never-written'],
+ },
+ ],
+ exclude: [],
+ }),
+ );
+ file(root, 'scripts/build.sh', '#!/usr/bin/env bash\n');
+ file(root, '.husky/pre-commit', '#!/usr/bin/env bash\n');
+ return root;
+ };
+
+ const unreadable = (relPath, code) => ({
+ readdirSync,
+ statSync,
+ lstatSync: (path) => {
+ if (String(path).endsWith(`/${relPath}`)) {
+ const error = new Error(`${code}: simulated failure, lstat '${path}'`);
+ error.code = code;
+ throw error;
+ }
+ return lstatSync(path);
+ },
+ });
+
+ test('the unreadable entry becomes a skip carrying its errno, distinct from declared-absent', () => {
+ const root = declaringRoot();
+ const result = discoverInScopeFilesWithSkips(root, unreadable('.husky/pre-commit', 'EACCES'));
+ expect(result.skips).toStrictEqual([{ path: '.husky/pre-commit', reason: 'EACCES' }]);
+ expect(result.files).toStrictEqual(['scripts/build.sh']);
+ expect(result.declaredAbsent).toStrictEqual([
+ { unit: 'shell', kind: 'file', path: '.husky/never-written' },
+ ]);
+ });
+
+ test('the public discoverer refuses the root rather than reporting the short list as clean', () => {
+ const root = declaringRoot();
+ expect(() => discoverInScopeFiles(root, unreadable('.husky/pre-commit', 'EACCES'))).toThrow(
+ /\.husky\/pre-commit \(EACCES\)/,
+ );
+ });
+
+ test('an errno-less read failure still records a skip instead of vanishing', () => {
+ const root = declaringRoot();
+ const brokenFs = {
+ readdirSync,
+ statSync,
+ lstatSync: (path) => {
+ if (String(path).endsWith('/.husky/pre-commit')) throw new Error('no errno on this one');
+ return lstatSync(path);
+ },
+ };
+ expect(discoverInScopeFilesWithSkips(root, brokenFs).skips).toStrictEqual([
+ { path: '.husky/pre-commit', reason: 'stat-failed' },
+ ]);
+ });
+
+ test('ENOENT from that same call site stays silent, so a merely absent file is no error', () => {
+ const root = declaringRoot();
+ expect(
+ discoverInScopeFilesWithSkips(root, unreadable('.husky/pre-commit', 'ENOENT')).skips,
+ ).toStrictEqual([]);
+ expect(discoverInScopeFiles(root, unreadable('.husky/pre-commit', 'ENOENT'))).toStrictEqual([
+ 'scripts/build.sh',
+ ]);
+ });
+
+ test('the genuinely absent declared file is silent against the real filesystem too', () => {
+ const root = declaringRoot();
+ expect(discoverInScopeFilesWithSkips(root, realFs).skips).toStrictEqual([]);
+ expect(discoverInScopeFiles(root, realFs)).toStrictEqual([
+ '.husky/pre-commit',
+ 'scripts/build.sh',
+ ]);
+ });
+});
diff --git a/lint-plugins/no-comments/documented-classes.test-helper.mjs b/lint-plugins/no-comments/documented-classes.test-helper.mjs
index b866f236c..2ea7ee0db 100644
--- a/lint-plugins/no-comments/documented-classes.test-helper.mjs
+++ b/lint-plugins/no-comments/documented-classes.test-helper.mjs
@@ -2,11 +2,16 @@ import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
-const README = join(dirname(fileURLToPath(import.meta.url)), 'README.md');
+const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
+const README = join(MODULE_DIR, 'README.md');
const SECTION = '## Violation classes';
+function readmeLines() {
+ return readFileSync(README, 'utf8').split('\n');
+}
+
export function documentedViolationClasses() {
- const lines = readFileSync(README, 'utf8').split('\n');
+ const lines = readmeLines();
const start = lines.indexOf(SECTION);
if (start === -1) throw new Error(`README.md has no "${SECTION}" section`);
@@ -19,3 +24,32 @@ export function documentedViolationClasses() {
if (classes.length === 0) throw new Error(`README.md's "${SECTION}" section documents none`);
return classes;
}
+
+export function documentedRegistryRows(heading) {
+ const lines = readmeLines();
+ const start = lines.indexOf(`### ${heading}`);
+ if (start === -1) throw new Error(`README.md has no "### ${heading}" section`);
+
+ const rows = [];
+ for (const line of lines.slice(start + 1)) {
+ if (line.startsWith('#')) break;
+ if (!line.startsWith('|')) continue;
+ const cells = [...line.matchAll(/`([^`]+)`/g)].map((match) => match[1]);
+ if (cells.length > 0) rows.push(cells);
+ }
+ if (rows.length === 0) throw new Error(`README.md's "### ${heading}" section tabulates none`);
+ return rows;
+}
+
+function classLiterals(pattern) {
+ const source = readFileSync(join(MODULE_DIR, 'allowlist.mjs'), 'utf8');
+ return [...new Set([...source.matchAll(pattern)].map((match) => match[1]))];
+}
+
+export function admittedClasses() {
+ return classLiterals(/\ballowed\('([a-z-]+)'/g);
+}
+
+export function emittedViolationClasses() {
+ return classLiterals(/\bviolation\(\s*'([a-z-]+)'/g);
+}
diff --git a/lint-plugins/no-comments/extract-hash.mjs b/lint-plugins/no-comments/extract-hash.mjs
new file mode 100644
index 000000000..a63b60f67
--- /dev/null
+++ b/lint-plugins/no-comments/extract-hash.mjs
@@ -0,0 +1,532 @@
+import { commentFactory } from './text-position.mjs';
+
+export class UnknownHashDialectError extends Error {
+ constructor(subject) {
+ super(
+ `no hash-family dialect is registered for ${subject}. The hash lexer reads one grammar per ` +
+ 'file class and each class needs its own comment-position reference before it can be ' +
+ 'trusted; register the dialect with its reference rather than falling through to another.',
+ );
+ this.name = 'UnknownHashDialectError';
+ this.subject = subject;
+ }
+}
+
+const DIALECT_BY_EXTENSION = new Map([
+ ['.sh', 'shell'],
+ ['.bash', 'shell'],
+ ['.yml', 'yaml'],
+ ['.yaml', 'yaml'],
+ ['.py', 'python'],
+]);
+
+export function hashDialectsFor(extensions) {
+ return [...new Set(extensions.map((extension) => DIALECT_BY_EXTENSION.get(extension)))];
+}
+
+function extensionOf(path) {
+ const name = path.slice(path.lastIndexOf('/') + 1);
+ const dot = name.lastIndexOf('.');
+ return dot <= 0 ? '' : name.slice(dot);
+}
+
+export function hashDialectFor(path, { extensions = [] } = {}) {
+ const own = DIALECT_BY_EXTENSION.get(extensionOf(path));
+ if (own !== undefined) return own;
+ const declared = [...new Set(extensions.map((ext) => DIALECT_BY_EXTENSION.get(ext)))];
+ if (declared.length === 1 && declared[0] !== undefined) return declared[0];
+ throw new UnknownHashDialectError(path);
+}
+
+const CODING_COOKIE_RE = /^[ \t\f]*#.*?coding[:=][ \t]*[-_.a-zA-Z0-9]+/;
+const COMMENT_LINE_RE = /^[ \t\f]*(?:#|$)/;
+
+function lineEndAt(source, start) {
+ const nl = source.indexOf('\n', start);
+ return nl === -1 ? source.length : nl;
+}
+
+function backtickCloserBefore(source, start, limit) {
+ let i = start;
+ while (i < limit) {
+ if (source[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ if (source[i] === '`') return i;
+ i += 1;
+ }
+ return limit;
+}
+
+function readStructuralPrefix(source, kinds, emit) {
+ const tokens = [];
+ let offset = 0;
+ if (kinds.includes('shebang') && source.startsWith('#!')) {
+ const end = lineEndAt(source, 0);
+ tokens.push(emit('shebang', 0, end));
+ offset = Math.min(end + 1, source.length);
+ }
+ if (kinds.includes('coding-cookie')) {
+ let cursor = offset;
+ for (let line = tokens.length + 1; line <= 2 && cursor < source.length; line += 1) {
+ const end = lineEndAt(source, cursor);
+ const text = source.slice(cursor, end);
+ if (CODING_COOKIE_RE.test(text)) {
+ tokens.push(emit('coding-cookie', cursor, end));
+ offset = Math.min(end + 1, source.length);
+ break;
+ }
+ if (!COMMENT_LINE_RE.test(text)) break;
+ cursor = end + 1;
+ }
+ }
+ return { tokens, offset };
+}
+
+const SHELL_METACHARACTERS = new Set([' ', '\t', '\n', '|', '&', ';', '(', ')', '<', '>']);
+
+const CODE_FRAMES = new Set(['code', 'cmdsub', 'backtick']);
+
+function lexShell(source, from, emit) {
+ const comments = [];
+ const stack = [{ kind: 'code', atWordStart: true, parens: 0, braces: 0 }];
+ const heredocs = [];
+ let i = from;
+
+ const top = () => stack[stack.length - 1];
+ const push = (kind) => stack.push({ kind, atWordStart: true, parens: 0, braces: 0 });
+ const popInto = () => {
+ stack.pop();
+ if (stack.length === 0) stack.push({ kind: 'code', atWordStart: true, parens: 0, braces: 0 });
+ top().atWordStart = false;
+ };
+
+ const consumeHeredocBodies = () => {
+ while (heredocs.length > 0 && i < source.length) {
+ const { delimiter, stripTabs } = heredocs.shift();
+ while (i < source.length) {
+ const end = lineEndAt(source, i);
+ const raw = source.slice(i, end);
+ const candidate = stripTabs ? raw.replace(/^\t+/, '') : raw;
+ i = Math.min(end + 1, source.length);
+ if (candidate === delimiter) break;
+ }
+ }
+ };
+
+ const readHeredocOpener = () => {
+ i += 2;
+ const stripTabs = source[i] === '-';
+ if (stripTabs) i += 1;
+ while (i < source.length && (source[i] === ' ' || source[i] === '\t')) i += 1;
+ let delimiter = '';
+ while (i < source.length) {
+ const c = source[i];
+ if (c === '\\') {
+ delimiter += source[i + 1] ?? '';
+ i += 2;
+ continue;
+ }
+ if (c === "'" || c === '"') {
+ i += 1;
+ while (i < source.length && source[i] !== c) {
+ if (c === '"' && source[i] === '\\') {
+ delimiter += source[i + 1] ?? '';
+ i += 2;
+ continue;
+ }
+ delimiter += source[i];
+ i += 1;
+ }
+ i += 1;
+ continue;
+ }
+ if (SHELL_METACHARACTERS.has(c)) break;
+ delimiter += c;
+ i += 1;
+ }
+ heredocs.push({ delimiter, stripTabs });
+ top().atWordStart = false;
+ };
+
+ while (i < source.length) {
+ const frame = top();
+ const c = source[i];
+
+ if (frame.kind === 'single') {
+ if (c === "'") popInto();
+ i += 1;
+ continue;
+ }
+
+ if (frame.kind === 'ansi') {
+ if (c === '\\') {
+ i += 2;
+ continue;
+ }
+ if (c === "'") popInto();
+ i += 1;
+ continue;
+ }
+
+ if (frame.kind === 'dquote' || frame.kind === 'paramexp' || frame.kind === 'arith') {
+ if (c === '\\') {
+ i += 2;
+ continue;
+ }
+ if (frame.kind === 'dquote' && c === '"') {
+ popInto();
+ i += 1;
+ continue;
+ }
+ if (frame.kind === 'paramexp') {
+ if (c === '{') {
+ frame.braces += 1;
+ i += 1;
+ continue;
+ }
+ if (c === '}') {
+ if (frame.braces === 0) popInto();
+ else frame.braces -= 1;
+ i += 1;
+ continue;
+ }
+ }
+ if (frame.kind === 'arith') {
+ if (c === '(') {
+ frame.parens += 1;
+ i += 1;
+ continue;
+ }
+ if (c === ')') {
+ if (frame.parens > 0) {
+ frame.parens -= 1;
+ i += 1;
+ continue;
+ }
+ popInto();
+ i += source[i + 1] === ')' ? 2 : 1;
+ continue;
+ }
+ }
+ if (frame.kind !== 'dquote' && (c === "'" || c === '"')) {
+ push(c === "'" ? 'single' : 'dquote');
+ i += 1;
+ continue;
+ }
+ if (c === '`') {
+ push('backtick');
+ i += 1;
+ continue;
+ }
+ if (c === '$') {
+ if (source[i + 1] === '(' && source[i + 2] === '(') {
+ push('arith');
+ i += 3;
+ continue;
+ }
+ if (source[i + 1] === '(') {
+ push('cmdsub');
+ i += 2;
+ continue;
+ }
+ if (source[i + 1] === '{') {
+ push('paramexp');
+ i += 2;
+ continue;
+ }
+ if (frame.kind !== 'dquote' && source[i + 1] === "'") {
+ push('ansi');
+ i += 2;
+ continue;
+ }
+ }
+ i += 1;
+ continue;
+ }
+
+ if (!CODE_FRAMES.has(frame.kind)) {
+ i += 1;
+ continue;
+ }
+
+ if (c === '\\') {
+ if (source[i + 1] !== '\n') frame.atWordStart = false;
+ i += 2;
+ continue;
+ }
+ if (c === '\n') {
+ i += 1;
+ consumeHeredocBodies();
+ top().atWordStart = true;
+ continue;
+ }
+ if (c === '#' && frame.atWordStart) {
+ const lineEnd = lineEndAt(source, i);
+ const end =
+ frame.kind === 'backtick' ? backtickCloserBefore(source, i, lineEnd) : lineEnd;
+ comments.push(emit('line', i, end));
+ i = end;
+ continue;
+ }
+ if (c === "'") {
+ push('single');
+ i += 1;
+ continue;
+ }
+ if (c === '"') {
+ push('dquote');
+ i += 1;
+ continue;
+ }
+ if (c === '`') {
+ if (frame.kind === 'backtick') popInto();
+ else push('backtick');
+ i += 1;
+ continue;
+ }
+ if (c === '$') {
+ if (source[i + 1] === '(' && source[i + 2] === '(') {
+ push('arith');
+ i += 3;
+ continue;
+ }
+ if (source[i + 1] === '(') {
+ push('cmdsub');
+ i += 2;
+ continue;
+ }
+ if (source[i + 1] === '{') {
+ push('paramexp');
+ i += 2;
+ continue;
+ }
+ if (source[i + 1] === "'") {
+ push('ansi');
+ i += 2;
+ continue;
+ }
+ if (source[i + 1] === '"') {
+ push('dquote');
+ i += 2;
+ continue;
+ }
+ frame.atWordStart = false;
+ i += 1;
+ continue;
+ }
+ if (c === '(') {
+ if (source[i + 1] === '(' && frame.atWordStart) {
+ push('arith');
+ i += 2;
+ continue;
+ }
+ if (frame.kind === 'cmdsub') frame.parens += 1;
+ frame.atWordStart = true;
+ i += 1;
+ continue;
+ }
+ if (c === ')') {
+ if (frame.kind === 'cmdsub') {
+ if (frame.parens === 0) {
+ popInto();
+ i += 1;
+ continue;
+ }
+ frame.parens -= 1;
+ }
+ frame.atWordStart = true;
+ i += 1;
+ continue;
+ }
+ if (c === '<' && source[i + 1] === '<') {
+ if (source[i + 2] === '<') {
+ frame.atWordStart = true;
+ i += 3;
+ continue;
+ }
+ readHeredocOpener();
+ continue;
+ }
+ frame.atWordStart = SHELL_METACHARACTERS.has(c);
+ i += 1;
+ }
+
+ return comments;
+}
+
+function lexPython(source, from, emit) {
+ const comments = [];
+ let i = from;
+ while (i < source.length) {
+ const c = source[i];
+ if (c === '#') {
+ const end = lineEndAt(source, i);
+ comments.push(emit('line', i, end));
+ i = end;
+ continue;
+ }
+ if (c === '"' || c === "'") {
+ const triple = source.startsWith(c.repeat(3), i);
+ const quote = triple ? c.repeat(3) : c;
+ i += quote.length;
+ while (i < source.length) {
+ if (source[i] === '\\') {
+ i += 2;
+ continue;
+ }
+ if (source.startsWith(quote, i)) {
+ i += quote.length;
+ break;
+ }
+ if (!triple && source[i] === '\n') break;
+ i += 1;
+ }
+ continue;
+ }
+ i += 1;
+ }
+ return comments;
+}
+
+const YAML_BLOCK_HEADER_RE = /^[|>][0-9]*[-+]?[0-9]*[ \t]*(?:#.*)?$/;
+
+function indentOf(source, lineStart) {
+ let width = 0;
+ while (source[lineStart + width] === ' ') width += 1;
+ return width;
+}
+
+function lexYaml(source, from, emit) {
+ const comments = [];
+ let i = from;
+ let quote = null;
+ let lineStart = from;
+ let blockParentIndent = null;
+ let atNodeStart = true;
+ let flowDepth = 0;
+
+ const skipBlockBody = () => {
+ while (blockParentIndent !== null && i < source.length) {
+ const end = lineEndAt(source, i);
+ const raw = source.slice(i, end);
+ if (raw.trim() !== '' && indentOf(source, i) <= blockParentIndent) {
+ blockParentIndent = null;
+ return;
+ }
+ i = Math.min(end + 1, source.length);
+ lineStart = i;
+ }
+ };
+
+ while (i < source.length) {
+ const c = source[i];
+ if (quote !== null) {
+ if (quote === "'" && c === "'" && source[i + 1] === "'") {
+ i += 2;
+ continue;
+ }
+ if (quote === '"' && c === '\\') {
+ i += 2;
+ continue;
+ }
+ if (c === quote) {
+ quote = null;
+ atNodeStart = false;
+ }
+ if (c === '\n') lineStart = i + 1;
+ i += 1;
+ continue;
+ }
+ if (c === '\n') {
+ i += 1;
+ lineStart = i;
+ atNodeStart = true;
+ flowDepth = 0;
+ skipBlockBody();
+ continue;
+ }
+ if (c === ' ' || c === '\t') {
+ i += 1;
+ continue;
+ }
+ if (atNodeStart && (c === "'" || c === '"')) {
+ quote = c;
+ i += 1;
+ continue;
+ }
+ if (c === '#' && (i === lineStart || source[i - 1] === ' ' || source[i - 1] === '\t')) {
+ const end = lineEndAt(source, i);
+ comments.push(emit('line', i, end));
+ i = end;
+ continue;
+ }
+ if (
+ (c === '|' || c === '>') &&
+ (source[i - 1] === ' ' || source[i - 1] === '\t') &&
+ YAML_BLOCK_HEADER_RE.test(source.slice(i, lineEndAt(source, i)))
+ ) {
+ blockParentIndent = indentOf(source, lineStart);
+ }
+ if (c === '[' || c === '{') {
+ flowDepth += 1;
+ atNodeStart = true;
+ i += 1;
+ continue;
+ }
+ if (c === ']' || c === '}') {
+ if (flowDepth > 0) flowDepth -= 1;
+ atNodeStart = false;
+ i += 1;
+ continue;
+ }
+ if (c === ',' && flowDepth > 0) {
+ atNodeStart = true;
+ i += 1;
+ continue;
+ }
+ if (
+ (c === '-' || c === '?') &&
+ atNodeStart &&
+ (source[i + 1] === ' ' || source[i + 1] === '\t' || source[i + 1] === '\n')
+ ) {
+ i += 1;
+ continue;
+ }
+ if (c === ':' && (flowDepth > 0 || source[i + 1] === ' ' || source[i + 1] === '\t' || source[i + 1] === '\n' || i + 1 >= source.length)) {
+ atNodeStart = true;
+ i += 1;
+ continue;
+ }
+ atNodeStart = false;
+ i += 1;
+ }
+ return comments;
+}
+
+const DIALECTS = {
+ shell: { structural: ['shebang'], lex: lexShell, reference: 'the pinned shfmt differential' },
+ python: { structural: ['shebang', 'coding-cookie'], lex: lexPython, reference: null },
+ yaml: { structural: [], lex: lexYaml, reference: "the yaml package's CST" },
+};
+
+export const HASH_DIALECT_REGISTRY = Object.entries(DIALECTS).map(([dialect, entry]) => ({
+ dialect,
+ declaresReference: Object.hasOwn(entry, 'reference'),
+ reference: entry.reference ?? null,
+}));
+
+export function hashDialectsWithoutReference(extensions, { dialects = DIALECTS } = {}) {
+ return hashDialectsFor(extensions).filter(
+ (dialect) => (dialects[dialect]?.reference ?? null) === null,
+ );
+}
+
+export function extractHashComments(source, { dialect } = {}) {
+ const entry = DIALECTS[dialect];
+ if (entry === undefined) throw new UnknownHashDialectError(`dialect ${JSON.stringify(dialect)}`);
+ const emit = commentFactory(source);
+ const { tokens, offset } = readStructuralPrefix(source, entry.structural, emit);
+ return [...tokens, ...entry.lex(source, offset, emit)];
+}
diff --git a/lint-plugins/no-comments/extract-hash.test.mjs b/lint-plugins/no-comments/extract-hash.test.mjs
new file mode 100644
index 000000000..70d7a0600
--- /dev/null
+++ b/lint-plugins/no-comments/extract-hash.test.mjs
@@ -0,0 +1,174 @@
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+import {
+ SHELL_MUST_FIRE,
+ SHELL_MUST_NOT_FIRE,
+ SHELL_SENTINEL,
+} from './__fixtures__/hash-shapes.fixture.mjs';
+import {
+ extractHashComments,
+ HASH_DIALECT_REGISTRY,
+ hashDialectFor,
+ hashDialectsWithoutReference,
+ UnknownHashDialectError,
+} from './extract-hash.mjs';
+import { analyzeSource, loadPrecedentRegistry } from './index.mjs';
+
+const shell = (source) => extractHashComments(source, { dialect: 'shell' });
+const reportable = (source) => shell(source).filter((c) => c.kind === 'line');
+const structural = (source) => shell(source).filter((c) => c.kind !== 'line');
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+const PRECEDENTS = loadPrecedentRegistry(REPO_ROOT);
+const PYTHON_FAMILY = { extractor: 'hash-family', extensions: ['.py'] };
+
+const pythonReported = (source) =>
+ analyzeSource({
+ source,
+ relPath: 'tools/probe.py',
+ precedentRegistry: PRECEDENTS,
+ family: PYTHON_FAMILY,
+ }).violations.map((violation) => violation.comment.text);
+
+describe('the shell dialect never reads a hash that bash does not read as a comment', () => {
+ test.each(SHELL_MUST_NOT_FIRE.map((f) => [`${f.id} ${f.label}`, f]))('%s', (_name, fixture) => {
+ expect(shell(fixture.source).map((c) => c.text)).toEqual([SHELL_SENTINEL]);
+ });
+
+ test('the polarity is the one the evidence recorded', () => {
+ expect(SHELL_MUST_NOT_FIRE).toHaveLength(22);
+ expect(SHELL_MUST_NOT_FIRE.every((f) => f.source.endsWith(`${SHELL_SENTINEL}\n`))).toBe(true);
+ });
+});
+
+describe('the shell dialect reads every hash that bash does read as a comment', () => {
+ test.each(SHELL_MUST_FIRE.map((f) => [`${f.id} ${f.label}`, f]))('%s', (_name, fixture) => {
+ expect(reportable(fixture.source).map((c) => c.text)).toEqual(fixture.comments);
+ expect(structural(fixture.source).map((c) => c.text)).toEqual(fixture.structural ?? []);
+ });
+
+ test('the polarity is the one the evidence recorded', () => {
+ expect(SHELL_MUST_FIRE).toHaveLength(11);
+ });
+});
+
+describe('a hash comment carries the same span and position model as a slash comment', () => {
+ test('offsets are exact and the text is the byte-exact span', () => {
+ const source = 'echo one\necho two # trailing\n';
+ const [comment] = reportable(source);
+ expect(source.slice(comment.start, comment.end)).toBe('# trailing');
+ expect(comment).toMatchObject({
+ kind: 'line',
+ text: '# trailing',
+ line: 2,
+ column: 10,
+ precededByCode: true,
+ });
+ });
+
+ test('a whole-line comment reports no preceding code', () => {
+ expect(reportable('# alone\n')[0].precededByCode).toBe(false);
+ });
+});
+
+describe('line one is structural, and only line one', () => {
+ test('the shebang is its own kind, so no lane reports it as a comment', () => {
+ expect(structural('#!/bin/sh\n# real\n').map((c) => c.kind)).toEqual(['shebang']);
+ });
+
+ test('a hash on line one that is not a shebang is an ordinary comment', () => {
+ expect(structural('# plain\n')).toEqual([]);
+ expect(reportable('# plain\n').map((c) => c.text)).toEqual(['# plain']);
+ });
+
+ test("python's coding cookie is structural on either of the lines PEP 263 allows", () => {
+ const cookieFirst = extractHashComments('# -*- coding: utf-8 -*-\n# real\n', {
+ dialect: 'python',
+ });
+ expect(cookieFirst.map((c) => c.kind)).toEqual(['coding-cookie', 'line']);
+
+ const afterShebang = extractHashComments('#!/usr/bin/env python3\n# coding=latin-1\n# real\n', {
+ dialect: 'python',
+ });
+ expect(afterShebang.map((c) => c.kind)).toEqual(['shebang', 'coding-cookie', 'line']);
+ });
+
+ test('a cookie on either line PEP 263 allows reaches no report, and the prose below it does', () => {
+ expect(pythonReported('# -*- coding: utf-8 -*-\nimport os\n# narration\n')).toEqual([
+ '# narration',
+ ]);
+ expect(
+ pythonReported('#!/usr/bin/env python3\n# coding=latin-1\nimport os\n# narration\n'),
+ ).toEqual(['# narration']);
+ });
+
+ test('a coding cookie on the third line is prose, not a cookie', () => {
+ const late = extractHashComments('import os\nimport sys\n# coding: utf-8\n', {
+ dialect: 'python',
+ });
+ expect(late.map((c) => c.kind)).toEqual(['line']);
+ });
+
+ test('a shell file gets no cookie rule, because no shell reads one', () => {
+ expect(shell('# -*- coding: utf-8 -*-\n').map((c) => c.kind)).toEqual(['line']);
+ });
+});
+
+describe('a dialect the extractor does not implement fails loud', () => {
+ test('an unmapped extension names itself rather than defaulting to a grammar', () => {
+ expect(() => hashDialectFor('config/app.toml')).toThrow(UnknownHashDialectError);
+ expect(() => hashDialectFor('config/app.toml')).toThrow(/app\.toml/);
+ expect(() => extractHashComments('# x\n', { dialect: 'toml' })).toThrow(
+ UnknownHashDialectError,
+ );
+ });
+
+ test('the dialects with a measured reference are mapped by extension', () => {
+ expect(hashDialectFor('scripts/build.sh')).toBe('shell');
+ expect(hashDialectFor('.github/workflows/ci.yml')).toBe('yaml');
+ expect(hashDialectFor('.github/workflows/ci.yaml')).toBe('yaml');
+ });
+
+ test('python is mapped by extension though no reference measures it yet', () => {
+ expect(hashDialectFor('tools/gen.py')).toBe('python');
+ });
+
+ test('an extensionless member resolves through the extensions its unit declares', () => {
+ expect(hashDialectFor('.husky/pre-commit', { extensions: ['.sh'] })).toBe('shell');
+ expect(() => hashDialectFor('.husky/pre-commit', { extensions: ['.sh', '.yml'] })).toThrow(
+ UnknownHashDialectError,
+ );
+ });
+});
+
+describe('a dialect is measured only through a reference field it actually declares', () => {
+ const lex = () => [];
+
+ test('over the shipped table the unmeasured dialect is python and nothing else', () => {
+ expect(hashDialectsWithoutReference(['.sh', '.yml', '.py'])).toStrictEqual(['python']);
+ });
+
+ test('a dialect entry written with no reference key at all reads as unmeasured', () => {
+ expect(
+ hashDialectsWithoutReference(['.sh'], { dialects: { shell: { structural: [], lex } } }),
+ ).toStrictEqual(['shell']);
+ });
+
+ test('a reference recorded under a mistyped key is no reference', () => {
+ expect(
+ hashDialectsWithoutReference(['.yml'], {
+ dialects: { yaml: { structural: [], lex, references: "the yaml package's CST" } },
+ }),
+ ).toStrictEqual(['yaml']);
+ });
+
+ test('every registered dialect declares the key, so an omission is caught where it is written', () => {
+ expect(HASH_DIALECT_REGISTRY.length).toBeGreaterThan(0);
+ expect(
+ HASH_DIALECT_REGISTRY.filter((entry) => !entry.declaresReference).map(
+ (entry) => entry.dialect,
+ ),
+ ).toStrictEqual([]);
+ });
+});
diff --git a/lint-plugins/no-comments/extract.mjs b/lint-plugins/no-comments/extract.mjs
index d311f0095..263e5e65f 100644
--- a/lint-plugins/no-comments/extract.mjs
+++ b/lint-plugins/no-comments/extract.mjs
@@ -1,3 +1,5 @@
+import { commentFactory } from './text-position.mjs';
+
const KEYWORDS_BEFORE_REGEX = new Set([
'return',
'typeof',
@@ -54,32 +56,6 @@ const IDENT_START = /[A-Za-z_$]/;
const IDENT_PART = /[A-Za-z0-9_$]/;
const DIGIT = /[0-9]/;
-function buildLineStarts(source) {
- const starts = [0];
- for (let i = 0; i < source.length; i += 1) {
- if (source.charCodeAt(i) === 10) starts.push(i + 1);
- }
- return starts;
-}
-
-function positionAt(lineStarts, offset) {
- let lo = 0;
- let hi = lineStarts.length - 1;
- while (lo < hi) {
- const mid = (lo + hi + 1) >> 1;
- if (lineStarts[mid] <= offset) lo = mid;
- else hi = mid - 1;
- }
- return { line: lo + 1, column: offset - lineStarts[lo] + 1 };
-}
-
-function precededByCodeOnLine(source, offset) {
- for (let i = offset - 1; i >= 0 && source.charCodeAt(i) !== 10; i -= 1) {
- if (!/\s/.test(source[i])) return true;
- }
- return false;
-}
-
const TYPE_PARAM_SCAN_LIMIT = 300;
const NEVER_IN_TYPE_PARAMS = /[{};]/;
@@ -108,7 +84,7 @@ function looksLikeTypeParameterList(source, afterAngle) {
export function extractComments(source, { jsx = false } = {}) {
const comments = [];
- const lineStarts = buildLineStarts(source);
+ const emit = commentFactory(source);
const stack = [{ kind: 'code', braceDepth: 0, closing: false }];
let lastTok = '';
let i = 0;
@@ -119,16 +95,7 @@ export function extractComments(source, { jsx = false } = {}) {
}
const pushComment = (kind, start, end) => {
- const { line, column } = positionAt(lineStarts, start);
- comments.push({
- kind,
- text: source.slice(start, end),
- start,
- end,
- line,
- column,
- precededByCode: precededByCodeOnLine(source, start),
- });
+ comments.push(emit(kind, start, end));
};
const readLineComment = (start) => {
diff --git a/lint-plugins/no-comments/extractors.mjs b/lint-plugins/no-comments/extractors.mjs
new file mode 100644
index 000000000..1214716de
--- /dev/null
+++ b/lint-plugins/no-comments/extractors.mjs
@@ -0,0 +1,46 @@
+import { extractComments, jsxModeForPath } from './extract.mjs';
+import { extractHashComments, hashDialectFor } from './extract-hash.mjs';
+
+export class UnknownFamilyError extends Error {
+ constructor(relPath, extractor) {
+ super(
+ extractor === undefined
+ ? `no family in the scope config claims ${relPath}, so no grammar can read it. Reading it ` +
+ 'under a guessed grammar is worse than refusing: the slash lexer over shell source ' +
+ 'finds no hash comment and invents one out of a URL.'
+ : `${relPath} resolves to extractor ${JSON.stringify(extractor)}, which this predicate ` +
+ 'does not implement. A family reaches the gate only once its extractor and that ' +
+ "extractor's own comment-position reference are both in the tree.",
+ );
+ this.name = 'UnknownFamilyError';
+ this.relPath = relPath;
+ this.extractor = extractor;
+ }
+}
+
+const ESM_FILE_CLASS_RE = /\.(?:mjs|cjs|js)$/;
+
+const GRAMMAR_FAMILIES = {
+ 'c-family': {
+ fileClassFor: (relPath) => (ESM_FILE_CLASS_RE.test(relPath) ? 'esm-script' : 'typescript'),
+ extract: (source, { relPath }) => extractComments(source, { jsx: jsxModeForPath(relPath) }),
+ },
+ 'hash-family': {
+ fileClassFor: (relPath, extensions) => hashDialectFor(relPath, { extensions }),
+ extract: (source, { relPath, extensions }) =>
+ extractHashComments(source, { dialect: hashDialectFor(relPath, { extensions }) }),
+ },
+};
+
+export const GRAMMAR_EXTRACTORS = Object.keys(GRAMMAR_FAMILIES);
+
+export function grammarFor(relPath, family) {
+ if (family === null || family === undefined) throw new UnknownFamilyError(relPath);
+ const grammar = GRAMMAR_FAMILIES[family.extractor];
+ if (grammar === undefined) throw new UnknownFamilyError(relPath, family.extractor);
+ return {
+ extractor: family.extractor,
+ fileClass: grammar.fileClassFor(relPath, family.extensions),
+ extract: (source) => grammar.extract(source, { relPath, extensions: family.extensions }),
+ };
+}
diff --git a/lint-plugins/no-comments/family-dispatch.test.mjs b/lint-plugins/no-comments/family-dispatch.test.mjs
new file mode 100644
index 000000000..6e9677639
--- /dev/null
+++ b/lint-plugins/no-comments/family-dispatch.test.mjs
@@ -0,0 +1,117 @@
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { describe, expect, test } from 'vitest';
+import { DIRECTIVE_PATTERNS, directivesFor } from './allowlist.mjs';
+import { extractComments } from './extract.mjs';
+import { analyzeSource, loadPrecedentRegistry, UnknownFamilyError } from './index.mjs';
+
+const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = join(MODULE_DIR, '..', '..');
+const PRECEDENTS = loadPrecedentRegistry(REPO_ROOT);
+
+const analyze = (source, relPath) =>
+ analyzeSource({ source, relPath, precedentRegistry: PRECEDENTS });
+
+const reported = (source, relPath) =>
+ analyze(source, relPath).comments.map((comment) => `${comment.kind}:${comment.text}`);
+
+describe('the extractor is chosen by the family the config gives the path', () => {
+ const SHELL = 'curl https://example.com/x # narration\n';
+
+ test('shell source is read by the hash lexer, not by the slash lexer', () => {
+ expect(
+ analyze(SHELL, 'scripts/probe.sh').violations.map((v) => `${v.class}:${v.comment.text}`),
+ ).toEqual(['prose:# narration']);
+ });
+
+ test('the slash lexer over the same bytes invents a URL comment and misses the real one', () => {
+ expect(extractComments(SHELL, { jsx: false }).map((c) => c.text)).toEqual([
+ '//example.com/x # narration',
+ ]);
+ });
+
+ test('a path no family claims is named rather than read with a guessed grammar', () => {
+ expect(() => analyze('# x\n', 'scripts/probe.toml')).toThrow(UnknownFamilyError);
+ expect(() => analyze('# x\n', 'scripts/probe.toml')).toThrow(/probe\.toml/);
+ });
+
+ test('the shebang is extracted but never reported', () => {
+ expect(reported('#!/usr/bin/env bash\n# narration\n', 'scripts/probe.sh')).toEqual([
+ 'line:# narration',
+ ]);
+ });
+});
+
+describe('directive registries are keyed by grammar family and file class', () => {
+ const headlineOf = (registry, headline) =>
+ registry.filter((entry) => entry.target === 'headline' && entry.regex.test(headline));
+
+ test('the shell registry carries no ShellCheck shape, because nothing here runs ShellCheck', () => {
+ expect(directivesFor('hash-family', 'shell')).toEqual([]);
+ expect(headlineOf(directivesFor('hash-family', 'shell'), 'shellcheck disable=SC2086')).toEqual(
+ [],
+ );
+ });
+
+ test('the same probe finds a shape in the registry that does carry one', () => {
+ expect(
+ headlineOf(directivesFor('c-family', 'typescript'), 'biome-ignore lint/x: reason').map(
+ (entry) => entry.id,
+ ),
+ ).toEqual(['biome-ignore']);
+ expect(directivesFor('c-family', 'typescript')).toBe(DIRECTIVE_PATTERNS);
+ });
+
+ test('a ShellCheck directive in a shell file is prose', () => {
+ expect(
+ analyze('# shellcheck disable=SC2086\nrun $args\n', 'scripts/probe.sh').violations.map(
+ (v) => v.class,
+ ),
+ ).toEqual(['prose']);
+ });
+
+ test('every declared file class resolves to a list, and an undeclared one is named', () => {
+ expect(directivesFor('hash-family', 'yaml')).toEqual([]);
+ expect(directivesFor('hash-family', 'python')).toEqual([]);
+ expect(() => directivesFor('hash-family', 'toml')).toThrow(/toml/);
+ });
+});
+
+describe('a hash marker run is one marker when its continuation is indented', () => {
+ const classesOf = (source) =>
+ analyze(source, 'scripts/probe.sh').kept.map((entry) => entry.class);
+
+ test('an indented continuation joins the marker it heads', () => {
+ const source = '# STOP: the caller owns the lock\n# release it before returning\nrun\n';
+ expect(classesOf(source)).toEqual(['contract-marker']);
+ expect(analyze(source, 'scripts/probe.sh').violations).toEqual([]);
+ });
+
+ test('an unindented following line is a separate comment, and it is prose', () => {
+ const source = '# STOP: the caller owns the lock\n# release it before returning\nrun\n';
+ const { violations, kept } = analyze(source, 'scripts/probe.sh');
+ expect(kept.map((entry) => entry.class)).toEqual(['contract-marker']);
+ expect(violations.map((v) => v.class)).toEqual(['prose']);
+ });
+
+ test('the run keeps byte-exact spans, so a stripper deletes what it read', () => {
+ const source = '# STOP: one\n# two\nrun\n';
+ const [marker] = analyze(source, 'scripts/probe.sh').kept;
+ expect(source.slice(marker.comment.start, marker.comment.end)).toBe('# STOP: one\n# two');
+ });
+
+ test('a run only forms under a marker head, never under plain prose', () => {
+ const source = '# plain narration\n# more narration\nrun\n';
+ expect(analyze(source, 'scripts/probe.sh').violations.map((v) => v.class)).toEqual([
+ 'prose',
+ 'prose',
+ ]);
+ });
+
+ test('slash comments keep the one-line marker rule they already had', () => {
+ const source = '// STOP: the caller owns the lock\n// release it before returning\nrun();\n';
+ const { violations } = analyze(source, 'packages/app/src/probe.ts');
+ expect(violations.map((v) => v.class)).toEqual(['prose']);
+ expect(violations[0].fix).toMatch(/one line/);
+ });
+});
diff --git a/lint-plugins/no-comments/freshness.mjs b/lint-plugins/no-comments/freshness.mjs
new file mode 100644
index 000000000..130bec3a9
--- /dev/null
+++ b/lint-plugins/no-comments/freshness.mjs
@@ -0,0 +1,16 @@
+import { createHash } from 'node:crypto';
+import { readFileSync } from 'node:fs';
+
+const ABSENT_SOURCE = 'absent';
+
+export function sourceDigest(path) {
+ try {
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
+ } catch (error) {
+ return error?.code === 'ENOENT' ? ABSENT_SOURCE : null;
+ }
+}
+
+export function isFresh(cached, digest) {
+ return cached !== undefined && digest !== null && cached.digest === digest;
+}
diff --git a/lint-plugins/no-comments/index.mjs b/lint-plugins/no-comments/index.mjs
index 54646fb4e..4636a4169 100644
--- a/lint-plugins/no-comments/index.mjs
+++ b/lint-plugins/no-comments/index.mjs
@@ -1,16 +1,28 @@
import { readFileSync, realpathSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-import { classifyComment } from './allowlist.mjs';
-import { extractComments, jsxModeForPath } from './extract.mjs';
-import { parsePrecedentNumbers, UnvalidatedPrecedentRegistry } from './precedents.mjs';
-import { isInScope, normalizeRelativePath } from './scope.mjs';
+import { classifyComment, commentBodyLines, directivesFor, isMarkerHead } from './allowlist.mjs';
+import { grammarFor } from './extractors.mjs';
+import { isFresh, sourceDigest } from './freshness.mjs';
+import {
+ entriesFromManifest,
+ PrecedentManifestError,
+ PrecedentRegistry,
+ precedentEntriesFrom,
+ UnvalidatedPrecedentRegistry,
+} from './precedents.mjs';
+import { normalizeRelativePath, SUBJECT_ROOT, scopeForRoot } from './scope.mjs';
+import { sanctionedTagsForPath } from './tag-scope.mjs';
export * from './allowlist.mjs';
+export * from './config.mjs';
export * from './extract.mjs';
+export * from './extract-hash.mjs';
+export * from './extractors.mjs';
export * from './precedents.mjs';
export * from './rot.mjs';
export * from './scope.mjs';
+export * from './tag-scope.mjs';
const precedentCache = new Map();
const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
@@ -30,60 +42,125 @@ function manifestDescribesRoot(repoRoot) {
return canonicalPath(repoRoot) === MANIFEST_SUBJECT_ROOT;
}
-function readPrecedentsMarkdown(precedentsPath) {
+function readPrecedentsIfPresent(absPath) {
try {
- return readFileSync(precedentsPath, 'utf8');
+ return readFileSync(absPath, 'utf8');
} catch (error) {
- if (error?.code !== 'ENOENT') throw error;
- return null;
+ if (error?.code === 'ENOENT') return null;
+ throw new PrecedentManifestError(
+ `could not be read (${error?.code ?? error?.message ?? 'read-failed'}).`,
+ { source: absPath },
+ );
}
}
-function requireNonEmpty(numbers, source) {
- if (numbers.size > 0) return numbers;
- throw new Error(
- `${source} parsed to zero precedent numbers. Refusing to validate citations ` +
- `against an empty set, which would classify every precedent #N citation as invalid and ` +
- `delete it. Check the file for conflict markers or reworded section headings.`,
+export function isUnvalidatedPrecedentRegistry(registry) {
+ return registry instanceof UnvalidatedPrecedentRegistry;
+}
+
+export function readPrecedentManifest() {
+ let manifest;
+ try {
+ manifest = JSON.parse(readFileSync(PRECEDENT_MANIFEST_PATH, 'utf8'));
+ } catch (error) {
+ throw new PrecedentManifestError(
+ `could not be read or parsed as JSON (${error?.code ?? error?.message ?? 'read-failed'}).`,
+ { source: PRECEDENT_MANIFEST_PATH },
+ );
+ }
+ return entriesFromManifest(manifest, PRECEDENT_MANIFEST_PATH);
+}
+
+function unvalidatedRegistryFor(repoRoot, notify) {
+ notify(
+ `no-comments: ${repoRoot} carries no PRECEDENTS.md and is not the tree the shipped ` +
+ 'precedent manifest describes, so `precedent #N` citations there are admitted unvalidated. ' +
+ "Open Knowledge's numbering has no authority over another repository.",
);
+ return new UnvalidatedPrecedentRegistry();
}
-export function isUnvalidatedPrecedentRegistry(registry) {
- return registry instanceof UnvalidatedPrecedentRegistry;
+function precedentSourcePath(repoRoot) {
+ return manifestDescribesRoot(repoRoot)
+ ? PRECEDENT_MANIFEST_PATH
+ : join(repoRoot, 'PRECEDENTS.md');
}
-function readPrecedentRegistry(repoRoot) {
+function readPrecedentRegistry(repoRoot, notify) {
+ if (manifestDescribesRoot(repoRoot)) return new PrecedentRegistry(readPrecedentManifest());
const precedentsPath = join(repoRoot, 'PRECEDENTS.md');
- const markdown = readPrecedentsMarkdown(precedentsPath);
- if (markdown !== null) return requireNonEmpty(parsePrecedentNumbers(markdown), precedentsPath);
- if (!manifestDescribesRoot(repoRoot)) return new UnvalidatedPrecedentRegistry();
- return requireNonEmpty(
- new Set(JSON.parse(readFileSync(PRECEDENT_MANIFEST_PATH, 'utf8'))),
- PRECEDENT_MANIFEST_PATH,
- );
+ const markdown = readPrecedentsIfPresent(precedentsPath);
+ if (markdown === null) return unvalidatedRegistryFor(repoRoot, notify);
+ return new PrecedentRegistry(precedentEntriesFrom(markdown, precedentsPath));
}
-export function loadPrecedentNumbers(repoRoot) {
+export function loadPrecedentRegistry(repoRoot, { notify = (line) => console.warn(line) } = {}) {
+ const digest = sourceDigest(precedentSourcePath(repoRoot));
const cached = precedentCache.get(repoRoot);
- if (cached) return cached;
- const registry = readPrecedentRegistry(repoRoot);
- precedentCache.set(repoRoot, registry);
+ if (isFresh(cached, digest)) return cached.registry;
+ const registry = readPrecedentRegistry(repoRoot, notify);
+ precedentCache.set(repoRoot, { registry, digest });
return registry;
}
-const MARKER_LINE_HINT =
- 'A `//` marker is one line - use a `/* ... */` block for a multi-line marker.';
+const REPORTABLE_KINDS = new Set(['line', 'block']);
-export function analyzeSource({ source, relPath, precedentNumbers }) {
+const MARKER_LINE_HINT = {
+ 'c-family': 'A `//` marker is one line - use a `/* ... */` block for a multi-line marker.',
+ 'hash-family': 'Indent the continuation under the marker head so the two read as one marker.',
+};
+
+function lineSpan(comment) {
+ return comment.text.split('\n').length;
+}
+
+function leadingIndent(comment) {
+ return /^\s*/.exec(commentBodyLines(comment.text)[0] ?? '')[0].length;
+}
+
+function joinHeadedRuns(comments, source) {
+ const runs = [];
+ for (const comment of comments) {
+ const head = runs[runs.length - 1];
+ const joinable =
+ head !== undefined &&
+ comment.kind === 'line' &&
+ head.kind === 'line' &&
+ isMarkerHead(head.text) &&
+ comment.line === head.line + lineSpan(head) &&
+ comment.column === head.column &&
+ leadingIndent(comment) > leadingIndent(head);
+ if (!joinable) {
+ runs.push(comment);
+ continue;
+ }
+ runs[runs.length - 1] = {
+ ...head,
+ text: source.slice(head.start, comment.end),
+ end: comment.end,
+ };
+ }
+ return runs;
+}
+
+export function analyzeSource({ source, relPath, precedentRegistry, root = SUBJECT_ROOT, family }) {
const path = normalizeRelativePath(relPath);
- const comments = extractComments(source, { jsx: jsxModeForPath(path) });
+ const resolved = family === undefined ? scopeForRoot(root).familyFor(path) : family;
+ const grammar = grammarFor(path, resolved);
+ const extracted = grammar.extract(source).filter((comment) => REPORTABLE_KINDS.has(comment.kind));
+ const comments =
+ grammar.extractor === 'hash-family' ? joinHeadedRuns(extracted, source) : extracted;
+ const sanctionedTags = sanctionedTagsForPath(path, root);
+ const directives = directivesFor(grammar.extractor, grammar.fileClass);
const violations = [];
const kept = [];
let previous = null;
for (const comment of comments) {
const verdict = classifyComment(comment, {
- precedentNumbers,
- jsdocTypes: /\.(?:mjs|cjs|js)$/.test(path),
+ precedentRegistry,
+ jsdocTypes: grammar.fileClass === 'esm-script',
+ sanctionedTags,
+ directives,
});
if (verdict.allowed) {
kept.push({ comment, class: verdict.class, detail: verdict.detail });
@@ -95,29 +172,32 @@ export function analyzeSource({ source, relPath, precedentNumbers }) {
previous.class === 'contract-marker' &&
previous.comment.kind === 'line' &&
comment.kind === 'line' &&
- comment.line === previous.comment.line + 1 &&
+ comment.line === previous.comment.line + lineSpan(previous.comment) &&
comment.column === previous.comment.column;
violations.push(
continuationOfMarker
- ? { ...verdict, fix: `${MARKER_LINE_HINT} ${verdict.fix}`, comment }
+ ? { ...verdict, fix: `${MARKER_LINE_HINT[grammar.extractor]} ${verdict.fix}`, comment }
: { ...verdict, comment },
);
}
previous = { ...verdict, comment };
}
- return { comments, violations, kept };
+ return { comments, violations, kept, extractor: grammar.extractor, fileClass: grammar.fileClass };
}
export function analyzeFile({ repoRoot, relPath }) {
const path = normalizeRelativePath(relPath);
- if (!isInScope(path)) return { skipped: true, comments: [], violations: [], kept: [] };
+ if (!scopeForRoot(repoRoot).isInScope(path)) {
+ return { skipped: true, comments: [], violations: [], kept: [] };
+ }
return {
skipped: false,
...analyzeSource({
source: readFileSync(join(repoRoot, path), 'utf8'),
relPath: path,
- precedentNumbers: loadPrecedentNumbers(repoRoot),
- }),
+ precedentRegistry: loadPrecedentRegistry(repoRoot),
+ root: repoRoot,
+ }),
};
}
diff --git a/lint-plugins/no-comments/jsdoc-types.test.mjs b/lint-plugins/no-comments/jsdoc-types.test.mjs
index ae8ddcf54..1e6df20c8 100644
--- a/lint-plugins/no-comments/jsdoc-types.test.mjs
+++ b/lint-plugins/no-comments/jsdoc-types.test.mjs
@@ -2,16 +2,16 @@ import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { describe, expect, test } from 'vitest';
-import { analyzeSource, loadPrecedentNumbers } from './index.mjs';
+import { analyzeSource, loadPrecedentRegistry } from './index.mjs';
const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = join(MODULE_DIR, '..', '..');
-const PRECEDENTS = loadPrecedentNumbers(REPO_ROOT);
+const PRECEDENTS = loadPrecedentRegistry(REPO_ROOT);
const FIXTURE = readFileSync(join(MODULE_DIR, '__fixtures__', 'jsdoc-types.fixture.mjs'), 'utf8');
function violationsFor(source, relPath) {
- return analyzeSource({ source, relPath, precedentNumbers: PRECEDENTS }).violations;
+ return analyzeSource({ source, relPath, precedentRegistry: PRECEDENTS }).violations;
}
describe('the jsdoc-type class: the only typing mechanism the untyped strata have', () => {
diff --git a/lint-plugins/no-comments/no-comments.config.schema.json b/lint-plugins/no-comments/no-comments.config.schema.json
new file mode 100644
index 000000000..95642f261
--- /dev/null
+++ b/lint-plugins/no-comments/no-comments.config.schema.json
@@ -0,0 +1,92 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "$id": "https://openknowledge.ai/schemas/no-comments.config.schema.json",
+ "title": "no-comments scope configuration",
+ "description": "Declares which files the comment-policy predicate governs at this repository root. Membership is derived from units[].roots crossed with the extensions of each unit's family, plus any explicit units[].files; it is never restated as a list of globs.",
+ "type": "object",
+ "required": ["version", "families", "units", "exclude"],
+ "additionalProperties": true,
+ "properties": {
+ "$schema": { "type": "string" },
+ "version": {
+ "description": "The schema major this file is written against. A predicate that does not recognise the major refuses to load rather than reading a shape it cannot represent; unknown additive keys under a recognised major load and are reported.",
+ "type": "integer",
+ "enum": [1]
+ },
+ "families": {
+ "description": "Grammar families, keyed by id. A family names the extensions it owns and the extractor that reads its comment grammar.",
+ "type": "object",
+ "minProperties": 1,
+ "additionalProperties": { "$ref": "#/$defs/family" }
+ },
+ "units": {
+ "description": "Named scope units. Each crosses one family with a list of roots.",
+ "type": "array",
+ "minItems": 1,
+ "items": { "$ref": "#/$defs/unit" }
+ },
+ "exclude": {
+ "description": "Globs removed from membership, evaluated before include. A `**/<name>/**` entry additionally prunes any directory called <name> during discovery.",
+ "type": "array",
+ "items": { "$ref": "#/$defs/glob" }
+ }
+ },
+ "$defs": {
+ "literalPath": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": "^(?![/\\\\])(?![A-Za-z]:[/\\\\])(?!(?:.*/)?\\.\\.(?:/|$))[^*?!{}\\[\\]()]+$",
+ "description": "A repository-relative path naming exactly one file. Unlike a glob it is never expanded and never matched: discovery stats it, so a wildcard or a brace could not add a member while the matcher would still route whatever it matched into this unit. The same canonicalization as `glob` applies, and an absolute path or a `..` segment is refused by name at load."
+ },
+ "glob": {
+ "type": "string",
+ "minLength": 1,
+ "pattern": "^(?![/\\\\])(?![A-Za-z]:[/\\\\])(?!(?:.*/)?\\.\\.(?:/|$))[^?!\\[\\]()]+$",
+ "description": "A repository-relative glob over `*`, `**`, brace alternations and literal segments. Braces expand at load, and the loader canonicalizes each expansion before anything reads it: a leading `./` is stripped, repeated slashes collapse, and a trailing `/` is dropped, so `./packages/` and `packages` are the same declaration and `.` is the only spelling of the repository root. The matcher sees no braces and no `./`. An absolute path or a `..` segment is refused by name at load rather than normalized, because either one names a tree the root does not own."
+ },
+ "family": {
+ "type": "object",
+ "required": ["extensions", "extractor"],
+ "additionalProperties": true,
+ "properties": {
+ "extensions": {
+ "type": "array",
+ "minItems": 1,
+ "items": { "type": "string", "pattern": "^\\.", "minLength": 2 }
+ },
+ "extractor": {
+ "description": "Id of the comment extractor that reads this grammar family.",
+ "type": "string",
+ "minLength": 1
+ }
+ }
+ },
+ "unit": {
+ "type": "object",
+ "required": ["id", "family"],
+ "anyOf": [
+ { "required": ["roots"], "properties": { "roots": { "type": "array", "minItems": 1 } } },
+ { "required": ["files"], "properties": { "files": { "type": "array", "minItems": 1 } } }
+ ],
+ "additionalProperties": true,
+ "properties": {
+ "id": { "type": "string", "minLength": 1 },
+ "family": { "type": "string", "minLength": 1 },
+ "roots": {
+ "description": "Directory prefixes, optionally carrying `*` or `**`. `.` means the repository root itself and is the one non-recursive root.",
+ "type": "array",
+ "items": { "$ref": "#/$defs/glob" }
+ },
+ "files": {
+ "description": "Paths that are members without matching a root, for scripts an extension-keyed rule can never discover. Each names one file: wildcards and braces are refused at load. A path carrying an extension must carry one whose extractor matches its own family, since the unit reads it under that extractor regardless. An extensionless path is the intended case under a hash family whose extensions resolve to a single dialect, and is refused under c-family, which takes its file class from the extension.",
+ "type": "array",
+ "items": { "$ref": "#/$defs/literalPath" }
+ },
+ "allowEmpty": {
+ "description": "Set when a unit is expected to discover nothing. Without it, a unit that matches no file is a loud failure rather than a silent zero.",
+ "type": "boolean"
+ }
+ }
+ }
+ }
+}
diff --git a/lint-plugins/no-comments/plugin.mjs b/lint-plugins/no-comments/plugin.mjs
index d5b1acd93..26da0b1bf 100644
--- a/lint-plugins/no-comments/plugin.mjs
+++ b/lint-plugins/no-comments/plugin.mjs
@@ -1,7 +1,12 @@
import { dirname, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { DOCS_URL_BASE } from './allowlist.mjs';
-import { analyzeSource, describeViolation, loadPrecedentNumbers } from './index.mjs';
+import {
+ analyzeSource,
+ describeViolation,
+ diagnosePrecedentRegistry,
+ loadPrecedentRegistry,
+} from './index.mjs';
import { isInScope, normalizeRelativePath } from './scope.mjs';
export const PLUGIN_NAME = 'no-comments';
@@ -38,14 +43,25 @@ export const noCommentsRule = {
const relPath = relativePathFor(context);
if (options.scope !== 'all' && !isInScope(relPath)) return {};
- const precedentNumbers = loadPrecedentNumbers(REPO_ROOT);
+ const registryDiagnosis = diagnosePrecedentRegistry(() => loadPrecedentRegistry(REPO_ROOT));
+ if (registryDiagnosis.status !== 'ok') {
+ return {
+ Program() {
+ context.report({
+ node: { range: [0, 0] },
+ message: `${registryDiagnosis.message} No comment in this file was judged.`,
+ });
+ },
+ };
+ }
+ const precedentRegistry = registryDiagnosis.registry;
return {
Program() {
const { violations } = analyzeSource({
source: context.sourceCode.text,
relPath,
- precedentNumbers,
+ precedentRegistry,
});
for (const violation of violations) {
context.report({
diff --git a/lint-plugins/no-comments/portability.test.mjs b/lint-plugins/no-comments/portability.test.mjs
new file mode 100644
index 000000000..d07f16704
--- /dev/null
+++ b/lint-plugins/no-comments/portability.test.mjs
@@ -0,0 +1,107 @@
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { afterAll, describe, expect, test } from 'vitest';
+import { SCOPE_CONFIG_FILENAME } from './config.mjs';
+import { isInScope, scopeForRoot, subjectScope } from './scope.mjs';
+
+const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
+
+const predicateModules = readdirSync(MODULE_DIR)
+ .filter((name) => name.endsWith('.mjs') && !name.includes('.test.'))
+ .sort();
+
+const config = subjectScope().config;
+
+const declaredGlobs = [
+ ...new Set([
+ ...config.units.flatMap((unit) => [...unit.roots, ...unit.files]),
+ ...config.walkRoots,
+ ...config.include,
+ ...config.exclude,
+ ]),
+]
+ .filter((glob) => glob !== '.')
+ .sort();
+
+const roots = [];
+afterAll(() => {
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+});
+
+describe('the predicate carries no scope of its own', () => {
+ test('the config declares enough for the assertion to bite', () => {
+ expect(predicateModules).toContain('scope.mjs');
+ expect(declaredGlobs.length).toBeGreaterThan(20);
+ });
+
+ const restates = (source, glob) =>
+ /[/*]/.test(glob)
+ ? source.includes(glob)
+ : new RegExp(`(['"\`])${glob.replace(/[.*+?^$**{}()|[\]\\]/g, '\\$&')}\\1`).test(source);
+
+ test.each(predicateModules)('%s restates no glob the config declares', (name) => {
+ const source = readFileSync(join(MODULE_DIR, name), 'utf8');
+ const restated = declaredGlobs.filter((glob) => restates(source, glob));
+ expect({ name, restated }).toEqual({ name, restated: [] });
+ });
+
+ test('the restatement check bites: a hardcoded roots array is caught', () => {
+ const planted = "const SCOPE_ROOTS = ['packages', 'scripts'];";
+ expect(declaredGlobs.filter((glob) => restates(planted, glob))).toEqual([
+ 'packages',
+ 'scripts',
+ ]);
+ const plantedGlob = "const INCLUDE = ['packages/**/src/**/*.ts'];";
+ expect(declaredGlobs.filter((glob) => restates(plantedGlob, glob))).toContain(
+ 'packages/**/src/**/*.ts',
+ );
+ });
+
+ test('the repo-specific data left inside the predicate is one named registry', () => {
+ const trees = ['md-conformance', 'lume-qa'];
+ const carriers = predicateModules.filter((name) =>
+ trees.some((tree) => readFileSync(join(MODULE_DIR, name), 'utf8').includes(tree)),
+ );
+ expect(carriers).toEqual(['rot.mjs']);
+ });
+});
+
+describe('another root runs the same code against its own declaration', () => {
+ const adopterRoot = () => {
+ const root = mkdtempSync(join(tmpdir(), 'no-comments-adopter-'));
+ roots.push(root);
+ writeFileSync(
+ join(root, SCOPE_CONFIG_FILENAME),
+ JSON.stringify({
+ version: 1,
+ families: { go: { extensions: ['.go'], extractor: 'c-family' } },
+ units: [{ id: 'cmd', family: 'go', roots: ['cmd'] }],
+ exclude: ['**/vendor/**'],
+ }),
+ );
+ mkdirSync(join(root, 'cmd/serve'), { recursive: true });
+ writeFileSync(join(root, 'cmd/serve/main.go'), 'package main\n');
+ mkdirSync(join(root, 'cmd/vendor'), { recursive: true });
+ writeFileSync(join(root, 'cmd/vendor/dep.go'), 'package dep\n');
+ return root;
+ };
+
+ test('the adopter scope admits its own tree and refuses this one, and the reverse', () => {
+ const adopter = scopeForRoot(adopterRoot());
+ expect(adopter.isInScope('cmd/serve/main.go')).toBe(true);
+ expect(adopter.isInScope('cmd/vendor/dep.go')).toBe(false);
+ expect(adopter.isInScope(config.include[0].replace(/\*\*/g, 'x').replace('*', 'a'))).toBe(
+ false,
+ );
+ expect(isInScope('cmd/serve/main.go')).toBe(false);
+ });
+
+ test('two roots resolve independently rather than sharing one compiled scope', () => {
+ const first = scopeForRoot(adopterRoot());
+ const second = scopeForRoot(adopterRoot());
+ expect(first).not.toBe(second);
+ expect(first.config.root).not.toBe(second.config.root);
+ });
+});
diff --git a/lint-plugins/no-comments/precedent-manifest.test.mjs b/lint-plugins/no-comments/precedent-manifest.test.mjs
index 6696d0207..4c4be2612 100644
--- a/lint-plugins/no-comments/precedent-manifest.test.mjs
+++ b/lint-plugins/no-comments/precedent-manifest.test.mjs
@@ -1,22 +1,36 @@
-import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import {
+ cpSync,
+ existsSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ utimesSync,
+ writeFileSync,
+} from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
-import { fileURLToPath } from 'node:url';
+import { fileURLToPath, pathToFileURL } from 'node:url';
import { afterAll, describe, expect, test } from 'vitest';
import { classifyComment } from './allowlist.mjs';
import { extractComments } from './extract.mjs';
-import { loadPrecedentNumbers } from './index.mjs';
-import { parsePrecedentNumbers, UnvalidatedPrecedentRegistry } from './precedents.mjs';
+import { loadPrecedentRegistry, readPrecedentManifest } from './index.mjs';
+import {
+ buildPrecedentManifest,
+ PrecedentRegistry,
+ precedentEntriesFrom,
+ UnvalidatedPrecedentRegistry,
+} from './precedents.mjs';
const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
const MANIFEST_SUBJECT_ROOT = join(MODULE_DIR, '..', '..');
-const manifest = new Set(
- JSON.parse(readFileSync(join(MODULE_DIR, 'precedent-numbers.generated.json'), 'utf8')),
-);
+const MANIFEST_PATH = join(MODULE_DIR, 'precedent-numbers.generated.json');
+const entries = readPrecedentManifest();
+const manifest = new PrecedentRegistry(entries);
-function verdictFor(citation, precedentNumbers) {
+function verdictFor(citation, precedentRegistry) {
const [comment] = extractComments(citation);
- return classifyComment(comment, { precedentNumbers });
+ return classifyComment(comment, { precedentRegistry });
}
describe('precedent validation runs from the shipped numbers manifest alone', () => {
@@ -28,30 +42,52 @@ describe('precedent validation runs from the shipped numbers manifest alone', ()
}
});
+ test('the manifest carries the retraction the classifier needs, not only the numbers', () => {
+ const retracted = entries.filter((entry) => entry.retracted).map((entry) => entry.number);
+ expect(retracted).toStrictEqual([12, 29, 52]);
+ for (const slot of retracted) expect(manifest.isRetracted(slot)).toBe(true);
+ });
+
+ test('it carries the one entry whose section heading is the entry', () => {
+ expect(entries.filter((entry) => entry.form === 'heading').map((e) => e.number)).toStrictEqual([
+ 53,
+ ]);
+ });
+
test('a real citation is admitted and a fabricated one is rejected', () => {
const [real] = extractComments('// The alignment here follows precedent #42.');
- expect(classifyComment(real, { precedentNumbers: manifest }).allowed).toBe(true);
+ expect(classifyComment(real, { precedentRegistry: manifest }).allowed).toBe(true);
const [fake] = extractComments('// Long design rationale, see precedent #999');
- const verdict = classifyComment(fake, { precedentNumbers: manifest });
+ const verdict = classifyComment(fake, { precedentRegistry: manifest });
expect(verdict.allowed).toBe(false);
expect(verdict.class).toBe('invalid-precedent');
});
+ test('a citation of a slot that kept its number but lost its rule is rejected too', () => {
+ const [comment] = extractComments('// held here per precedent #52');
+ const verdict = classifyComment(comment, { precedentRegistry: manifest });
+ expect(verdict.allowed).toBe(false);
+ expect(verdict.class).toBe('retracted-precedent');
+ expect(verdict.detail).toContain('#52');
+ });
+
const precedentsPath = join(MODULE_DIR, '..', '..', 'PRECEDENTS.md');
test.skipIf(!existsSync(precedentsPath))(
'the manifest is regenerated whenever PRECEDENTS.md changes',
() => {
- const live = parsePrecedentNumbers(readFileSync(precedentsPath, 'utf8'));
+ const live = precedentEntriesFrom(readFileSync(precedentsPath, 'utf8'), precedentsPath);
- expect([...manifest].sort((a, b) => a - b)).toStrictEqual([...live].sort((a, b) => a - b));
+ expect(readFileSync(MANIFEST_PATH, 'utf8')).toBe(
+ `${JSON.stringify(buildPrecedentManifest(live), null, 2)}\n`,
+ );
},
);
test('a caller that skips loading a registry fails loud instead of admitting citations', () => {
const [comment] = extractComments('// as in precedent #7');
- expect(() => classifyComment(comment, {})).toThrow(/precedentNumbers/);
+ expect(() => classifyComment(comment, {})).toThrow(/loadPrecedentRegistry/);
});
});
@@ -72,22 +108,58 @@ describe('a repo root the shipped manifest does not describe', () => {
});
test('loads a registry that validates nothing rather than borrowing this tree numbers', () => {
- const registry = loadPrecedentNumbers(foreignRoot);
+ const registry = loadPrecedentRegistry(foreignRoot);
expect(registry).toBeInstanceOf(UnvalidatedPrecedentRegistry);
expect([...registry]).toStrictEqual([]);
});
+ test('says so rather than degrading in silence, naming the root and the missing file', () => {
+ const announced = [];
+ const uncachedRoot = mkdtempSync(join(tmpdir(), 'no-comments-foreign-root-'));
+ try {
+ loadPrecedentRegistry(uncachedRoot, { notify: (line) => announced.push(line) });
+ } finally {
+ rmSync(uncachedRoot, { recursive: true, force: true });
+ }
+
+ expect(announced).toHaveLength(1);
+ expect(announced[0]).toContain(uncachedRoot);
+ expect(announced[0]).toContain('PRECEDENTS.md');
+ });
+
+ test('says so once, not once per lane: the absent file is a cached state, not a miss', () => {
+ const announced = [];
+ const uncachedRoot = mkdtempSync(join(tmpdir(), 'no-comments-foreign-root-'));
+ try {
+ const first = loadPrecedentRegistry(uncachedRoot, { notify: (line) => announced.push(line) });
+ const second = loadPrecedentRegistry(uncachedRoot, {
+ notify: (line) => announced.push(line),
+ });
+ expect(second).toBe(first);
+ } finally {
+ rmSync(uncachedRoot, { recursive: true, force: true });
+ }
+
+ expect(announced).toHaveLength(1);
+ });
+
+ test('admits a retracted slot there too, because retraction is this tree ruling', () => {
+ const verdict = verdictFor('// per precedent #52', loadPrecedentRegistry(foreignRoot));
+ expect(verdict.allowed).toBe(true);
+ expect(verdict.class).toBe('precedent-citation');
+ });
+
test('admits a citation this tree never issued instead of marking it invalid for deletion', () => {
const verdict = verdictFor(
`// per precedent #${slotThisTreeNeverIssued}`,
- loadPrecedentNumbers(foreignRoot),
+ loadPrecedentRegistry(foreignRoot),
);
expect(verdict.allowed).toBe(true);
expect(verdict.class).toBe('precedent-citation');
});
test('reaches that verdict for every citation, so no verdict turns on this tree numbering', () => {
- const registry = loadPrecedentNumbers(foreignRoot);
+ const registry = loadPrecedentRegistry(foreignRoot);
const shape = (slot) => {
const verdict = verdictFor(`// per precedent #${slot}`, registry);
return { allowed: verdict.allowed, class: verdict.class };
@@ -97,7 +169,7 @@ describe('a repo root the shipped manifest does not describe', () => {
});
test('the root the manifest does describe still rejects a fabricated citation', () => {
- const registry = loadPrecedentNumbers(MANIFEST_SUBJECT_ROOT);
+ const registry = loadPrecedentRegistry(MANIFEST_SUBJECT_ROOT);
expect(registry).not.toBeInstanceOf(UnvalidatedPrecedentRegistry);
const verdict = verdictFor(`// per precedent #${slotThisTreeNeverIssued}`, registry);
@@ -105,3 +177,129 @@ describe('a repo root the shipped manifest does not describe', () => {
expect(verdict.class).toBe('invalid-precedent');
});
});
+
+describe('the tree the manifest describes is read from the manifest, not from the markdown', () => {
+ const scratch = mkdtempSync(join(tmpdir(), 'no-comments-manifest-first-'));
+ const slotOnlyTheMarkdownKnows = 991;
+
+ afterAll(() => {
+ rmSync(scratch, { recursive: true, force: true });
+ });
+
+ test('a citation only PRECEDENTS.md backs is rejected, so the markdown is never opened', async () => {
+ cpSync(join(MODULE_DIR, '..'), join(scratch, 'lint-plugins'), { recursive: true });
+ writeFileSync(
+ join(scratch, 'PRECEDENTS.md'),
+ `## Scratch (precedent ${slotOnlyTheMarkdownKnows})\n\n${slotOnlyTheMarkdownKnows}. **A slot the shipped manifest never carried.** Body.\n`,
+ );
+ const scratchIndex = await import(
+ pathToFileURL(join(scratch, 'lint-plugins/no-comments/index.mjs')).href
+ );
+
+ const registry = scratchIndex.loadPrecedentRegistry(scratch);
+ expect(registry.has(slotOnlyTheMarkdownKnows)).toBe(false);
+ expect(registry.size).toBe(entries.length);
+
+ const [comment] = scratchIndex.extractComments(`// per precedent #${slotOnlyTheMarkdownKnows}`);
+ expect(scratchIndex.classifyComment(comment, { precedentRegistry: registry }).class).toBe(
+ 'invalid-precedent',
+ );
+ });
+});
+
+describe('a long-lived host reads PRECEDENTS.md as it is now, not as it was at first load', () => {
+ const root = mkdtempSync(join(tmpdir(), 'no-comments-precedents-mtime-'));
+ const precedentsPath = join(root, 'PRECEDENTS.md');
+ const slotWrittenFirst = 992;
+ const slotAddedLater = 993;
+ const PINNED_EPOCH_SECONDS = 1_700_000_000;
+
+ afterAll(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ const registrySource = (slots) =>
+ `## Scratch (precedents ${slots.join(', ')})\n\n${slots
+ .map((slot) => `${slot}. **Slot ${slot}.** Body.\n`)
+ .join('')}`;
+
+ let pinsIssued = 0;
+ const pinDistinctMtime = (path) => {
+ pinsIssued += 1;
+ const seconds = PINNED_EPOCH_SECONDS + pinsIssued;
+ utimesSync(path, seconds, seconds);
+ };
+
+ const writeRegistry = (slots) => {
+ writeFileSync(precedentsPath, registrySource(slots));
+ pinDistinctMtime(precedentsPath);
+ };
+
+ test('a slot added between two calls in one process is admitted by the second', () => {
+ writeRegistry([slotWrittenFirst]);
+ const first = loadPrecedentRegistry(root);
+ expect(first.has(slotWrittenFirst)).toBe(true);
+ expect(first.has(slotAddedLater)).toBe(false);
+
+ writeRegistry([slotWrittenFirst, slotAddedLater]);
+
+ const second = loadPrecedentRegistry(root);
+ expect(second.has(slotAddedLater)).toBe(true);
+ expect(verdictFor(`// per precedent #${slotAddedLater}`, second).class).toBe(
+ 'precedent-citation',
+ );
+ });
+
+ test('an unedited registry keeps serving the parse it already paid for', () => {
+ expect(loadPrecedentRegistry(root)).toBe(loadPrecedentRegistry(root));
+ });
+
+ test('a PRECEDENTS.md that appears after an unvalidated load starts validating', () => {
+ const bare = mkdtempSync(join(tmpdir(), 'no-comments-precedents-late-'));
+ try {
+ expect(loadPrecedentRegistry(bare, { notify: () => {} })).toBeInstanceOf(
+ UnvalidatedPrecedentRegistry,
+ );
+
+ writeFileSync(
+ join(bare, 'PRECEDENTS.md'),
+ `## Scratch (precedent ${slotWrittenFirst})\n\n${slotWrittenFirst}. **Slot ${slotWrittenFirst}.** Body.\n`,
+ );
+
+ const registry = loadPrecedentRegistry(bare, { notify: () => {} });
+ expect(registry).not.toBeInstanceOf(UnvalidatedPrecedentRegistry);
+ expect(registry.has(slotWrittenFirst)).toBe(true);
+ } finally {
+ rmSync(bare, { recursive: true, force: true });
+ }
+ });
+
+ test('a slot added by a write that leaves the mtime unchanged is admitted by the second call', () => {
+ const collidingRoot = mkdtempSync(join(tmpdir(), 'no-comments-precedents-same-mtime-'));
+ const collidingPath = join(collidingRoot, 'PRECEDENTS.md');
+ const writeAtOneInstant = (slots) => {
+ writeFileSync(collidingPath, registrySource(slots));
+ utimesSync(collidingPath, PINNED_EPOCH_SECONDS, PINNED_EPOCH_SECONDS);
+ };
+
+ try {
+ writeAtOneInstant([slotWrittenFirst]);
+ const mtimeAtFirstLoad = statSync(collidingPath).mtimeMs;
+ const first = loadPrecedentRegistry(collidingRoot);
+ expect(first.has(slotWrittenFirst)).toBe(true);
+ expect(first.has(slotAddedLater)).toBe(false);
+
+ writeAtOneInstant([slotWrittenFirst, slotAddedLater]);
+ expect(statSync(collidingPath).mtimeMs).toBe(mtimeAtFirstLoad);
+ expect(readFileSync(collidingPath, 'utf8')).toContain(`${slotAddedLater}. **Slot`);
+
+ const second = loadPrecedentRegistry(collidingRoot);
+ expect(second.has(slotAddedLater)).toBe(true);
+ expect(verdictFor(`// per precedent #${slotAddedLater}`, second).class).toBe(
+ 'precedent-citation',
+ );
+ } finally {
+ rmSync(collidingRoot, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/lint-plugins/no-comments/precedent-numbers.generated.json b/lint-plugins/no-comments/precedent-numbers.generated.json
index c671a8941..d5c6d9888 100644
--- a/lint-plugins/no-comments/precedent-numbers.generated.json
+++ b/lint-plugins/no-comments/precedent-numbers.generated.json
@@ -1 +1,305 @@
-[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59]
+{
+ "version": 1,
+ "entries": [
+ {
+ "number": 1,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 2,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 3,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 4,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 5,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 6,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 7,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 8,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 9,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 10,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 11,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 12,
+ "form": "list",
+ "retracted": true
+ },
+ {
+ "number": 13,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 14,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 15,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 16,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 17,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 18,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 19,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 20,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 21,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 22,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 23,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 24,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 25,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 26,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 27,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 28,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 29,
+ "form": "list",
+ "retracted": true
+ },
+ {
+ "number": 30,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 31,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 32,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 33,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 34,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 35,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 36,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 37,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 38,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 39,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 40,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 41,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 42,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 43,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 44,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 45,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 46,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 47,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 48,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 49,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 50,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 51,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 52,
+ "form": "list",
+ "retracted": true
+ },
+ {
+ "number": 53,
+ "form": "heading",
+ "retracted": false
+ },
+ {
+ "number": 54,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 55,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 56,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 57,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 58,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 59,
+ "form": "list",
+ "retracted": false
+ },
+ {
+ "number": 60,
+ "form": "list",
+ "retracted": false
+ }
+ ]
+}
diff --git a/lint-plugins/no-comments/precedents.mjs b/lint-plugins/no-comments/precedents.mjs
index b674b873f..5a2db84a3 100644
--- a/lint-plugins/no-comments/precedents.mjs
+++ b/lint-plugins/no-comments/precedents.mjs
@@ -1,31 +1,311 @@
-const HEADING_PRECEDENTS_RE = /^##\s+.*\(precedents?\s+([^()]*)\)\s*$/gm;
+const SECTION_RE = /^##\s+/;
+const HEADING_CLAIM_RE = /^##\s+.*\(precedents?\s+([^()]*)\)\s*$/;
const RANGE_RE = /^\s*(\d+)\s*[-–—]\s*(\d+)\s*$/;
const LEADING_NUMBER_RE = /^\s*(\d+)\b/;
+const LIST_ENTRY_RE = /^(\d+)\.\s+\S/;
+const RETRACTION_RE = /\bRETRACTED\b/;
+const BOLD_LEAD_RE = /\*\*([\s\S]*?)\*\*/;
const PRECEDENT_CITATION_RE = /\bprecedent\s+#(\d+)/gi;
-export function parsePrecedentNumbers(markdown) {
- const numbers = new Set();
- for (const match of markdown.matchAll(HEADING_PRECEDENTS_RE)) {
- for (const part of match[1].split(',')) {
- const range = RANGE_RE.exec(part);
- if (range) {
- const from = Number(range[1]);
- const to = Number(range[2]);
- for (let n = from; n <= to; n += 1) numbers.add(n);
- continue;
+export const PRECEDENT_MANIFEST_VERSION = 1;
+
+export class PrecedentManifestError extends Error {
+ constructor(message, { source, key }) {
+ super(`${source}${key ? ` (${key})` : ''}: ${message}`);
+ this.name = 'PrecedentManifestError';
+ this.source = source;
+ this.key = key;
+ }
+}
+
+export function diagnosePrecedentRegistry(load) {
+ try {
+ return { status: 'ok', registry: load() };
+ } catch (error) {
+ if (!(error instanceof PrecedentManifestError)) throw error;
+ return {
+ status: 'unreadable',
+ source: error.source,
+ key: error.key,
+ message: `precedent-registry: UNREADABLE. ${error.message}`,
+ };
+ }
+}
+
+const ENTRY_FORMS = new Set(['list', 'heading']);
+
+function claimedSlots(spec) {
+ const slots = [];
+ for (const part of spec.split(',')) {
+ const range = RANGE_RE.exec(part);
+ if (range) {
+ for (let n = Number(range[1]); n <= Number(range[2]); n += 1) slots.push(n);
+ continue;
+ }
+ const single = LEADING_NUMBER_RE.exec(part);
+ if (single) slots.push(Number(single[1]));
+ }
+ return slots;
+}
+
+function readSections(markdown) {
+ const sections = [];
+ let section = null;
+ markdown.split('\n').forEach((line, index) => {
+ if (SECTION_RE.test(line)) {
+ const claim = HEADING_CLAIM_RE.exec(line);
+ section = {
+ line: index + 1,
+ heading: line,
+ claims: claim ? claimedSlots(claim[1]) : [],
+ items: [],
+ body: [],
+ };
+ sections.push(section);
+ return;
+ }
+ if (section === null) return;
+ section.body.push(line);
+ const item = LIST_ENTRY_RE.exec(line);
+ if (item) section.items.push({ number: Number(item[1]), line: index + 1, text: line });
+ });
+ return sections;
+}
+
+export function readsAsRetracted(text) {
+ return RETRACTION_RE.test(text);
+}
+
+function titleOf(text) {
+ const bold = BOLD_LEAD_RE.exec(text);
+ if (bold === null) return null;
+ const title = bold[1].replace(/~~/g, '').replace(/\s+/g, ' ').trim();
+ return title === '' ? null : title;
+}
+
+function readRegistry(markdown) {
+ const sections = readSections(markdown);
+ const claimed = new Set(sections.flatMap((section) => section.claims));
+ const written = new Map();
+ const problems = [];
+ const outline = [];
+
+ for (const section of sections) {
+ const placed = [];
+ const write = (number, definition) => {
+ const already = written.get(number);
+ if (already) {
+ problems.push({
+ kind: 'duplicate',
+ number,
+ detail: `precedent #${number} is written twice, at line ${already.line} and line ${definition.line}`,
+ });
+ return;
}
- const single = LEADING_NUMBER_RE.exec(part);
- if (single) numbers.add(Number(single[1]));
+ written.set(number, definition);
+ placed.push({ number, ...definition });
+ };
+
+ for (const item of section.items) {
+ write(item.number, { line: item.line, form: 'list', text: item.text });
}
+ const headingIsTheEntry =
+ section.claims.length === 1 && section.items.length === 0 && section.body.join('').trim() !== '';
+ if (headingIsTheEntry) {
+ write(section.claims[0], {
+ line: section.line,
+ form: 'heading',
+ text: section.body.join('\n'),
+ });
+ }
+ outline.push({ heading: section.heading, placed });
+ }
+
+ for (const number of [...claimed].sort((a, b) => a - b)) {
+ if (written.has(number)) continue;
+ problems.push({
+ kind: 'claimed-but-unwritten',
+ number,
+ detail: `a section heading claims precedent #${number}, but no entry writes it`,
+ });
+ }
+ for (const [number, definition] of [...written].sort((a, b) => a[0] - b[0])) {
+ if (claimed.has(number)) continue;
+ problems.push({
+ kind: 'unclaimed',
+ number,
+ detail: `precedent #${number} is written at line ${definition.line}, but no section heading claims it`,
+ });
}
- return numbers;
+
+ return { outline, written, problems };
+}
+
+export function parsePrecedentEntries(markdown) {
+ const { written, problems } = readRegistry(markdown);
+ const entries = [...written]
+ .sort((a, b) => a[0] - b[0])
+ .map(([number, definition]) => ({
+ number,
+ form: definition.form,
+ retracted: readsAsRetracted(definition.text),
+ }));
+
+ return { entries, problems };
+}
+
+export function parsePrecedentOutline(markdown) {
+ const { outline, problems } = readRegistry(markdown);
+ const untitled = [];
+ const sections = outline.map(({ heading, placed }) => ({
+ heading,
+ entries: placed.map((definition) => {
+ const title = titleOf(definition.text);
+ if (title === null) {
+ untitled.push({
+ kind: 'untitled',
+ number: definition.number,
+ detail:
+ `precedent #${definition.number} at line ${definition.line} opens with no bold lead, ` +
+ 'so the public titles stub would have no title to show for it',
+ });
+ }
+ return {
+ number: definition.number,
+ form: definition.form,
+ retracted: readsAsRetracted(definition.text),
+ title,
+ };
+ }),
+ }));
+
+ return { sections, problems: [...problems, ...untitled] };
}
-export class UnvalidatedPrecedentRegistry extends Set {
+function refuseUnsoundRegistry(problems, source) {
+ if (problems.length === 0) return;
+ throw new PrecedentManifestError(
+ 'not a sound precedent registry, so citations cannot be judged against it:\n' +
+ `${problems.map((problem) => ` - ${problem.detail}`).join('\n')}\n` +
+ 'Repair the numbering rather than renumbering the entries; numbers are a citation contract.',
+ { source },
+ );
+}
+
+export function precedentEntriesFrom(markdown, source) {
+ const { entries, problems } = parsePrecedentEntries(markdown);
+ refuseUnsoundRegistry(problems, source);
+ if (entries.length === 0) {
+ throw new PrecedentManifestError(
+ 'parsed to zero precedent entries. Refusing to validate citations against an empty ' +
+ 'registry, which would classify every precedent #N citation as invalid and delete it. ' +
+ 'Check the file for conflict markers or reworded section headings.',
+ { source },
+ );
+ }
+ return entries;
+}
+
+export function precedentOutlineFrom(markdown, source) {
+ const { sections, problems } = parsePrecedentOutline(markdown);
+ refuseUnsoundRegistry(problems, source);
+ if (sections.every((section) => section.entries.length === 0)) {
+ throw new PrecedentManifestError(
+ 'parsed to zero precedent entries, so a titles index built from it would be empty. ' +
+ 'Check the file for conflict markers or reworded section headings.',
+ { source },
+ );
+ }
+ return sections;
+}
+
+export function buildPrecedentManifest(entries) {
+ return { version: PRECEDENT_MANIFEST_VERSION, entries };
+}
+
+export function entriesFromManifest(manifest, source) {
+ if (manifest === null || typeof manifest !== 'object' || Array.isArray(manifest)) {
+ throw new PrecedentManifestError(
+ 'not a precedent manifest object. Regenerate it with `pnpm run generate:precedent-numbers`.',
+ { source },
+ );
+ }
+ if (manifest.version !== PRECEDENT_MANIFEST_VERSION) {
+ throw new PrecedentManifestError(
+ `declares precedent manifest version ${JSON.stringify(manifest.version)}, and this ` +
+ `predicate reads version ${PRECEDENT_MANIFEST_VERSION}. Upgrade the predicate rather ` +
+ 'than validating citations against a schema it cannot read.',
+ { source, key: 'version' },
+ );
+ }
+ if (!Array.isArray(manifest.entries) || manifest.entries.length === 0) {
+ throw new PrecedentManifestError(
+ 'carries no precedent entries. Regenerate it from PRECEDENTS.md.',
+ { source, key: 'entries' },
+ );
+ }
+ return manifest.entries.map((entry, index) => {
+ const key = `entries[${index}]`;
+ if (!Number.isInteger(entry?.number) || entry.number <= 0) {
+ throw new PrecedentManifestError(
+ `carries no positive integer number: ${JSON.stringify(entry)}.`,
+ { source, key },
+ );
+ }
+ if (!ENTRY_FORMS.has(entry.form)) {
+ throw new PrecedentManifestError(
+ `precedent #${entry.number} has form ${JSON.stringify(entry.form)}, which is not one of ` +
+ `${[...ENTRY_FORMS].map((form) => JSON.stringify(form)).join(', ')}.`,
+ { source, key },
+ );
+ }
+ if (typeof entry.retracted !== 'boolean') {
+ throw new PrecedentManifestError(
+ `precedent #${entry.number} has no boolean retracted flag.`,
+ { source, key },
+ );
+ }
+ return { number: entry.number, form: entry.form, retracted: entry.retracted };
+ });
+}
+
+export class PrecedentRegistry {
+ #numbers;
+ #retracted;
+
+ constructor(entries = []) {
+ this.#numbers = new Set(entries.map((entry) => entry.number));
+ this.#retracted = new Set(
+ entries.filter((entry) => entry.retracted).map((entry) => entry.number),
+ );
+ }
+
+ has(number) {
+ return this.#numbers.has(number);
+ }
+
+ isRetracted(number) {
+ return this.#retracted.has(number);
+ }
+
+ get size() {
+ return this.#numbers.size;
+ }
+
+ [Symbol.iterator]() {
+ return this.#numbers[Symbol.iterator]();
+ }
+}
+
+export class UnvalidatedPrecedentRegistry extends PrecedentRegistry {
has() {
return true;
}
+
+ isRetracted() {
+ return false;
+ }
}
export function citedPrecedentNumbers(commentText) {
diff --git a/lint-plugins/no-comments/precedents.test.mjs b/lint-plugins/no-comments/precedents.test.mjs
new file mode 100644
index 000000000..352a3d9b3
--- /dev/null
+++ b/lint-plugins/no-comments/precedents.test.mjs
@@ -0,0 +1,223 @@
+import { describe, expect, test } from 'vitest';
+import {
+ buildPrecedentManifest,
+ entriesFromManifest,
+ parsePrecedentEntries,
+ parsePrecedentOutline,
+ precedentOutlineFrom,
+ PRECEDENT_MANIFEST_VERSION,
+ PrecedentManifestError,
+ PrecedentRegistry,
+ UnvalidatedPrecedentRegistry,
+} from './precedents.mjs';
+
+const SOUND = [
+ '# Registry',
+ '',
+ 'Two numbered slots, one active.',
+ '',
+ '## Conventions (precedents 1-2)',
+ '',
+ '1. **A live rule.** Body text.',
+ '2. ~~**A withdrawn rule.**~~ **RETRACTED 2026-01-01** for citation stability.',
+ '',
+ '## A section that is itself the entry (precedent 3)',
+ '',
+ '**The rule states itself in the section body.**',
+ '',
+].join('\n');
+
+const problemKinds = (markdown) =>
+ parsePrecedentEntries(markdown).problems.map((problem) => problem.kind);
+
+const numbered = (markdown) =>
+ parsePrecedentEntries(markdown).entries.map((entry) => entry.number);
+
+describe('the registry parser reads numbered entries, not heading ranges', () => {
+ test('an entry carries its number, its form and whether it was retracted', () => {
+ const { entries, problems } = parsePrecedentEntries(SOUND);
+
+ expect(problems).toStrictEqual([]);
+ expect(entries).toStrictEqual([
+ { number: 1, form: 'list', retracted: false },
+ { number: 2, form: 'list', retracted: true },
+ { number: 3, form: 'heading', retracted: false },
+ ]);
+ });
+
+ test('a heading that claims a range and writes every slot needs no per-slot heading', () => {
+ expect(numbered(SOUND)).toStrictEqual([1, 2, 3]);
+ });
+
+ test('a heading claiming one slot with a list entry under it is a list entry, not a heading entry', () => {
+ const markdown = SOUND.replace(
+ '**The rule states itself in the section body.**',
+ '3. **The rule is a list item.** Body.',
+ );
+
+ expect(parsePrecedentEntries(markdown).entries.at(-1)).toStrictEqual({
+ number: 3,
+ form: 'list',
+ retracted: false,
+ });
+ });
+
+ test('an empty section claiming a slot writes no entry, so the slot reads as unwritten', () => {
+ const markdown = SOUND.replace('**The rule states itself in the section body.**', '');
+
+ expect(numbered(markdown)).toStrictEqual([1, 2]);
+ expect(problemKinds(markdown)).toStrictEqual(['claimed-but-unwritten']);
+ });
+
+ test('a number written twice is a problem, because no reader can tell which entry it means', () => {
+ const markdown = SOUND.replace('2. ~~**A withdrawn', '1. ~~**A withdrawn');
+ const [problem] = parsePrecedentEntries(markdown).problems;
+
+ expect(problem.kind).toBe('duplicate');
+ expect(problem.number).toBe(1);
+ expect(problem.detail).toMatch(/line/);
+ });
+
+ test('an entry no heading claims is a problem, the other half of a renumbering', () => {
+ const markdown = SOUND.replace('1. **A live rule.**', '9. **A live rule.**');
+
+ expect(problemKinds(markdown).sort()).toStrictEqual(['claimed-but-unwritten', 'unclaimed']);
+ });
+
+ test('gaps in the numbering are a repository convention, not a parse problem', () => {
+ const markdown = SOUND.replace('(precedents 1-2)', '(precedents 1, 2)').replace(
+ '## A section that is itself the entry (precedent 3)',
+ '## A section that is itself the entry (precedent 9)',
+ );
+
+ expect(numbered(markdown)).toStrictEqual([1, 2, 9]);
+ expect(problemKinds(markdown)).toStrictEqual([]);
+ });
+});
+
+describe('the registry answers both questions the classifier asks of it', () => {
+ const registry = new PrecedentRegistry(parsePrecedentEntries(SOUND).entries);
+
+ test('a written slot exists and a fabricated one does not', () => {
+ expect(registry.has(1)).toBe(true);
+ expect(registry.has(999)).toBe(false);
+ });
+
+ test('a retracted slot still exists, and says so separately', () => {
+ expect(registry.has(2)).toBe(true);
+ expect(registry.isRetracted(2)).toBe(true);
+ expect(registry.isRetracted(1)).toBe(false);
+ });
+
+ test('the registry a foreign root gets validates nothing and retracts nothing', () => {
+ const unvalidated = new UnvalidatedPrecedentRegistry();
+
+ expect(unvalidated.has(999)).toBe(true);
+ expect(unvalidated.isRetracted(2)).toBe(false);
+ expect([...unvalidated]).toStrictEqual([]);
+ });
+});
+
+describe('the shipped manifest is versioned, and an older reader survives a newer one', () => {
+ const entries = parsePrecedentEntries(SOUND).entries;
+
+ test('a manifest carries its schema major beside the entries', () => {
+ expect(buildPrecedentManifest(entries)).toStrictEqual({
+ version: PRECEDENT_MANIFEST_VERSION,
+ entries,
+ });
+ });
+
+ test('keys this reader does not know are additive, so a newer manifest still loads', () => {
+ const newer = {
+ version: PRECEDENT_MANIFEST_VERSION,
+ generatedFrom: 'PRECEDENTS.md',
+ entries: entries.map((entry) => ({ ...entry, title: 'a title this reader ignores' })),
+ };
+
+ expect(entriesFromManifest(newer, 'newer.json')).toStrictEqual(entries);
+ });
+
+ test('a schema major this reader does not recognize is named, never silently ignored', () => {
+ const future = { ...buildPrecedentManifest(entries), version: PRECEDENT_MANIFEST_VERSION + 1 };
+
+ expect(() => entriesFromManifest(future, 'future.json')).toThrow(PrecedentManifestError);
+ expect(() => entriesFromManifest(future, 'future.json')).toThrow('future.json');
+ expect(() => entriesFromManifest(future, 'future.json')).toThrow(
+ new RegExp(`version ${PRECEDENT_MANIFEST_VERSION + 1}`),
+ );
+ });
+
+ test('the flat number array of the previous schema is rejected by name, not coerced', () => {
+ expect(() => entriesFromManifest([1, 2, 3], 'legacy.json')).toThrow(PrecedentManifestError);
+ expect(() => entriesFromManifest([1, 2, 3], 'legacy.json')).toThrow('legacy.json');
+ });
+
+ test('an entry missing a field the classifier reads is rejected rather than defaulted', () => {
+ const broken = { version: PRECEDENT_MANIFEST_VERSION, entries: [{ number: 1, form: 'list' }] };
+
+ expect(() => entriesFromManifest(broken, 'broken.json')).toThrow(PrecedentManifestError);
+ expect(() => entriesFromManifest(broken, 'broken.json')).toThrow(/retracted/);
+ });
+});
+
+describe('the parser also reads the title of each entry, which is its bold lead', () => {
+ const outline = () => parsePrecedentOutline(SOUND);
+
+ test('every section keeps its heading line and the entries written under it', () => {
+ expect(outline().sections.map((section) => section.heading)).toStrictEqual([
+ '## Conventions (precedents 1-2)',
+ '## A section that is itself the entry (precedent 3)',
+ ]);
+ expect(outline().sections.map((section) => section.entries.map((entry) => entry.number))).toStrictEqual([
+ [1, 2],
+ [3],
+ ]);
+ });
+
+ test('an entry carries its title beside the fields the manifest reads', () => {
+ expect(outline().sections.flatMap((section) => section.entries)).toStrictEqual([
+ { number: 1, form: 'list', retracted: false, title: 'A live rule.' },
+ { number: 2, form: 'list', retracted: true, title: 'A withdrawn rule.' },
+ {
+ number: 3,
+ form: 'heading',
+ retracted: false,
+ title: 'The rule states itself in the section body.',
+ },
+ ]);
+ });
+
+ test('a title that wraps across lines reads as one line', () => {
+ const wrapped = SOUND.replace(
+ '**The rule states itself in the section body.**',
+ '**The rule states itself\nin the section body.**',
+ );
+
+ expect(parsePrecedentOutline(wrapped).sections.at(-1).entries[0].title).toBe(
+ 'The rule states itself in the section body.',
+ );
+ });
+
+ test('an entry with no bold lead is a problem, because the stub would have nothing to show', () => {
+ const untitled = SOUND.replace('1. **A live rule.** Body text.', '1. A live rule with no lead.');
+
+ expect(parsePrecedentOutline(untitled).problems.map((problem) => problem.kind)).toStrictEqual([
+ 'untitled',
+ ]);
+ });
+
+ test('reading titles does not change what the numbers path reports', () => {
+ const untitled = SOUND.replace('1. **A live rule.** Body text.', '1. A live rule with no lead.');
+
+ expect(parsePrecedentEntries(untitled).problems).toStrictEqual([]);
+ expect(numbered(untitled)).toStrictEqual([1, 2, 3]);
+ });
+
+ test('a registry the parser cannot read soundly is refused by name before any title is used', () => {
+ const duplicated = SOUND.replace('2. ~~**A withdrawn', '1. ~~**A withdrawn');
+
+ expect(() => precedentOutlineFrom(duplicated, 'duplicated.md')).toThrow(PrecedentManifestError);
+ expect(() => precedentOutlineFrom(duplicated, 'duplicated.md')).toThrow('duplicated.md');
+ });
+});
diff --git a/lint-plugins/no-comments/registry-drift.test.mjs b/lint-plugins/no-comments/registry-drift.test.mjs
new file mode 100644
index 000000000..3ba45c37a
--- /dev/null
+++ b/lint-plugins/no-comments/registry-drift.test.mjs
@@ -0,0 +1,80 @@
+import { describe, expect, test } from 'vitest';
+import {
+ DIRECTIVE_PATTERNS,
+ DIRECTIVE_REGISTRY_KEYS,
+ GUARD_MARKERS,
+ UPSTREAM_REFERENT_SHAPES,
+ directivesFor,
+} from './allowlist.mjs';
+import {
+ documentedRegistryRows,
+ documentedViolationClasses,
+ emittedViolationClasses,
+} from './documented-classes.test-helper.mjs';
+
+const firstCells = (heading) => documentedRegistryRows(heading).map((row) => row[0]);
+
+describe('the README is the registry, not a summary of it', () => {
+ test('it tabulates every directive the predicate admits, and no other', () => {
+ expect(firstCells('Tool-parsed directives')).toStrictEqual(
+ DIRECTIVE_PATTERNS.map((directive) => directive.id),
+ );
+ });
+
+ test('each directive row shows shapes the predicate declares for that id', () => {
+ const documented = new Map(
+ documentedRegistryRows('Tool-parsed directives').map((row) => [row[0], row.slice(1)]),
+ );
+ const wrong = DIRECTIVE_PATTERNS.flatMap((directive) =>
+ (documented.get(directive.id) ?? [])
+ .filter((shape) => !directive.shapes.includes(shape))
+ .map((shape) => `${directive.id}: ${shape}`),
+ );
+ expect(wrong).toStrictEqual([]);
+ });
+
+ test('every declared shape reaches a reader, so no row hides one', () => {
+ const documented = new Map(
+ documentedRegistryRows('Tool-parsed directives').map((row) => [row[0], row.slice(1)]),
+ );
+ const undocumented = DIRECTIVE_PATTERNS.flatMap((directive) =>
+ directive.shapes
+ .filter((shape) => !(documented.get(directive.id) ?? []).includes(shape))
+ .map((shape) => `${directive.id}: ${shape}`),
+ );
+ expect(undocumented).toStrictEqual([]);
+ });
+
+ test('it tabulates every guard marker the predicate registers, and no other', () => {
+ expect(firstCells('Guard-defined metacomment markers')).toStrictEqual(
+ GUARD_MARKERS.map((marker) => marker.id),
+ );
+ });
+
+ test('it tabulates every upstream referent shape the predicate accepts, and no other', () => {
+ expect(firstCells('Contract markers')).toStrictEqual(
+ UPSTREAM_REFERENT_SHAPES.map((shape) => shape.id),
+ );
+ });
+
+ test('it tabulates every family and file class the predicate answers for, and no other', () => {
+ const documented = documentedRegistryRows('Which directives a file class admits').map(
+ (row) => `${row[0]}/${row[1]}`,
+ );
+ expect(documented).toStrictEqual(
+ DIRECTIVE_REGISTRY_KEYS.map(({ extractor, fileClass }) => `${extractor}/${fileClass}`),
+ );
+ });
+
+ test('it heads a section for every violation class the source names, and no other', () => {
+ const emitted = emittedViolationClasses();
+ expect(emitted.length).toBeGreaterThan(0);
+ expect([...documentedViolationClasses()].sort()).toStrictEqual([...emitted].sort());
+ });
+
+ test('a file class the README calls empty admits nothing, and one it points at the table admits it', () => {
+ const admits = (extractor, fileClass) => directivesFor(extractor, fileClass).length;
+ expect(admits('hash-family', 'shell')).toBe(0);
+ expect(admits('c-family', 'typescript')).toBe(DIRECTIVE_PATTERNS.length);
+ });
+});
diff --git a/lint-plugins/no-comments/rot.mjs b/lint-plugins/no-comments/rot.mjs
index 9086c8324..9da184a44 100644
--- a/lint-plugins/no-comments/rot.mjs
+++ b/lint-plugins/no-comments/rot.mjs
@@ -109,6 +109,18 @@ export const ROT_SIGNATURES = [
},
];
+export const CITATION_LINE_CAP = 3;
+
+export const CITATION_CAP_FIX =
+ 'Keep the sentence that carries the citation and drop the rest: a citation licenses the ' +
+ 'reference, not the essay around it. The reasoning belongs in the commit message, the PR ' +
+ 'body, or the precedent entry itself.';
+
+export function citationCapOverflow(bodyLines) {
+ const lines = bodyLines.filter((line) => line.trim() !== '').length;
+ return lines > CITATION_LINE_CAP ? { lines, cap: CITATION_LINE_CAP } : null;
+}
+
export const CONTEXT_TERMS = new Map([
[
"milestone-tag",
diff --git a/lint-plugins/no-comments/scope.mjs b/lint-plugins/no-comments/scope.mjs
index fef4f815b..3801a7e10 100644
--- a/lint-plugins/no-comments/scope.mjs
+++ b/lint-plugins/no-comments/scope.mjs
@@ -1,48 +1,24 @@
-export const SCOPE_STRATA = [
- { id: 'packages-src', include: ['packages/**/src/**/*.ts', 'packages/**/src/**/*.tsx'] },
- { id: 'packages-tests', include: ['packages/**/tests/**/*.ts', 'packages/**/tests/**/*.tsx'] },
- { id: 'scripts', include: ['scripts/**/*.mjs'] },
- { id: 'github-scripts', include: ['.github/scripts/**/*.mjs'] },
- {
- id: 'docs',
- include: ['docs/**/*.ts', 'docs/**/*.tsx', 'docs/**/*.mts', 'docs/**/*.cts'],
- },
- { id: 'root-configs', include: ['*.ts', '*.mts', '*.cts'] },
- { id: 'lint-plugins', include: ['lint-plugins/**/*.mjs'] },
-];
-
-export const SCOPE_INCLUDE = SCOPE_STRATA.flatMap((stratum) => stratum.include);
-
-export const SCOPE_EXCLUDE = [
- 'packages/md-conformance/**',
- 'packages/app/tests/fidelity/**',
- 'packages/desktop/tests/lume-qa/**',
- 'packages/app/src/locales/**',
- '**/*.private.*',
- '**/*.fixture.ts',
- '**/*.fixture.tsx',
- '**/*.fixture.mjs',
- '**/*.d.ts',
- '**/*.d.mts',
- '**/*.d.cts',
- '**/fixtures/**',
- '**/__fixtures__/**',
- 'knip.config.ts',
- '**/node_modules/**',
- '**/dist/**',
- '**/build/**',
- '**/.next/**',
-];
+import { realpathSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import {
+ UNSUPPORTED_GLOB_SYNTAX,
+ loadScopeConfig,
+ SCOPE_CONFIG_FILENAME,
+ ScopeConfigError,
+ ScopeConfigMissingError,
+} from './config.mjs';
+import { hashDialectsFor, hashDialectsWithoutReference } from './extract-hash.mjs';
+import { GRAMMAR_EXTRACTORS } from './extractors.mjs';
+import { isFresh, sourceDigest } from './freshness.mjs';
const REGEX_METACHARACTERS = /[.+^${}()|[\]\\]/g;
-const UNSUPPORTED_GLOB_SYNTAX = /[?!{}[\]()]/;
-
export function globToRegExp(glob) {
if (UNSUPPORTED_GLOB_SYNTAX.test(glob)) {
throw new Error(
`unsupported glob syntax in ${glob}: this matcher implements only *, **, and literal segments. ` +
- 'Compiling anything else to a literal or a live regex silently mis-scopes a stratum; extend the matcher deliberately instead.',
+ 'Compiling anything else to a literal or a live regex silently mis-scopes a unit; extend the matcher deliberately instead.',
);
}
const segments = glob.split('/');
@@ -59,53 +35,291 @@ export function globToRegExp(glob) {
return new RegExp(`${pattern}$`);
}
-const compile = (globs) => globs.map(globToRegExp);
-const INCLUDE_RES = compile(SCOPE_INCLUDE);
-const EXCLUDE_RES = compile(SCOPE_EXCLUDE);
-const STRATUM_RES = SCOPE_STRATA.map((stratum) => ({
- id: stratum.id,
- regexes: compile(stratum.include),
-}));
-
export function normalizeRelativePath(relPath) {
return relPath.replace(/\\/g, '/').replace(/^\.\//, '');
}
+const compile = (globs) => globs.map(globToRegExp);
+
+function extensionOf(relPath) {
+ const name = relPath.slice(relPath.lastIndexOf('/') + 1);
+ const dot = name.lastIndexOf('.');
+ return dot <= 0 ? '' : name.slice(dot);
+}
+
+function familiesByExtension(config) {
+ const byExtension = new Map();
+ for (const family of Object.values(config.families)) {
+ for (const extension of family.extensions) {
+ const claimed = byExtension.get(extension);
+ if (claimed === undefined) {
+ byExtension.set(extension, {
+ extractor: family.extractor,
+ extensions: new Set(family.extensions),
+ });
+ continue;
+ }
+ if (claimed.extractor !== family.extractor) {
+ throw new ScopeConfigError({
+ configPath: config.configPath,
+ key: `families.${family.id}.extractor`,
+ detail:
+ `claims ${extension} for extractor ${family.extractor}, which another family already ` +
+ `claims for ${claimed.extractor}. One extension reads under one grammar; two would ` +
+ 'make the extractor a coin flip over which family matched first.',
+ });
+ }
+ for (const other of family.extensions) claimed.extensions.add(other);
+ }
+ }
+ return new Map(
+ [...byExtension].map(([extension, claim]) => [
+ extension,
+ { extractor: claim.extractor, extensions: [...claim.extensions] },
+ ]),
+ );
+}
+
+function assertGrammarContract(config) {
+ const byExtension = new Map();
+ for (const [id, family] of Object.entries(config.families)) {
+ if (!GRAMMAR_EXTRACTORS.includes(family.extractor)) {
+ throw new ScopeConfigError({
+ configPath: config.configPath,
+ key: `families.${id}.extractor`,
+ detail:
+ `names ${family.extractor}, which no extractor implements. The declared extractors are ` +
+ `${GRAMMAR_EXTRACTORS.join(', ')}; a family the predicate cannot read would fail at the ` +
+ 'first file rather than here, where the config can still be corrected.',
+ });
+ }
+ if (family.extractor === 'hash-family') {
+ const unreadable = family.extensions.filter(
+ (extension) => hashDialectsFor([extension])[0] === undefined,
+ );
+ if (unreadable.length > 0) {
+ throw new ScopeConfigError({
+ configPath: config.configPath,
+ key: `families.${id}.extensions`,
+ detail:
+ `declare ${unreadable.join(', ')}, which no hash dialect reads. Each dialect ships ` +
+ 'with its own comment-position reference, so a file under an unregistered extension ' +
+ 'would be lexed under a neighbouring grammar rather than refused.',
+ });
+ }
+ const unmeasured = hashDialectsWithoutReference(family.extensions);
+ if (unmeasured.length > 0) {
+ const unreferenced = family.extensions.filter((extension) =>
+ unmeasured.includes(hashDialectsFor([extension])[0]),
+ );
+ throw new ScopeConfigError({
+ configPath: config.configPath,
+ key: `families.${id}.extensions`,
+ detail:
+ `resolve to the ${unmeasured.join(', ')} dialect, which carries no comment-position ` +
+ 'reference. A dialect ships with one so an oracle measures where it reads a comment; ' +
+ 'declaring this family would take gate verdicts, and strip ranges under --write, from ' +
+ `a lexer nothing checks. Drop ${unreferenced.join(', ')} from this family until a ` +
+ 'reference lands, or contribute one upstream: the dialect table is DIALECTS in ' +
+ 'lint-plugins/no-comments/extract-hash.mjs, and its reference field is what this ' +
+ 'refusal reads.',
+ });
+ }
+ }
+ for (const extension of family.extensions) byExtension.set(extension, family.extractor);
+ }
+ config.units.forEach((unit, index) => {
+ const family = config.families[unit.family];
+ for (const file of unit.files) {
+ const extension = extensionOf(file);
+ if (extension === '' && family.extractor === 'c-family') {
+ throw new ScopeConfigError({
+ configPath: config.configPath,
+ key: `units[${index}].files`,
+ detail:
+ `unit ${unit.id} lists ${file}, which carries no extension, under c-family. That ` +
+ 'extractor takes its file class from the extension, so an extensionless path silently ' +
+ 'reads as TypeScript; a shell hook listed here would report clean rather than being ' +
+ 'refused. Give the path an extension its family declares, or declare it under a ' +
+ 'family whose extractor matches its grammar.',
+ });
+ }
+ if (extension === '') continue;
+ const claimed = byExtension.get(extension);
+ if (claimed === family.extractor) continue;
+ throw new ScopeConfigError({
+ configPath: config.configPath,
+ key: `units[${index}].files`,
+ detail:
+ `unit ${unit.id} lists ${file}, whose extension ${extension} ${
+ claimed === undefined
+ ? 'no family claims'
+ : `family extractor ${claimed} claims, while this unit declares ${family.extractor}`
+ }. The unit would read it under ${family.extractor} regardless, and reading a file under ` +
+ 'the wrong grammar reports a clean file rather than refusing.',
+ });
+ }
+ if (family.extractor !== 'hash-family') return;
+ if (!unit.files.some((file) => extensionOf(file) === '')) return;
+ const dialects = hashDialectsFor(family.extensions);
+ if (dialects.length === 1) return;
+ throw new ScopeConfigError({
+ configPath: config.configPath,
+ key: `families.${unit.family}.extensions`,
+ detail:
+ `resolve to ${dialects.length} hash dialects (${dialects.join(', ')}), and unit ${unit.id} ` +
+ 'carries an extensionless file whose dialect can only come from that set. A member with ' +
+ 'no extension of its own needs exactly one dialect to fall back to; split the family so ' +
+ 'each carries a single dialect.',
+ });
+ });
+}
+
+function compileScope(config) {
+ assertGrammarContract(config);
+ const excludeRes = compile(config.exclude);
+ const includeRes = compile(config.include);
+ const unitRes = config.units.map((unit) => ({
+ id: unit.id,
+ family: config.families[unit.family],
+ regexes: compile(unit.include),
+ }));
+ const byExtension = familiesByExtension(config);
+ const isExcluded = (relPath) => excludeRes.some((re) => re.test(normalizeRelativePath(relPath)));
+ const isInScope = (relPath) => {
+ const path = normalizeRelativePath(relPath);
+ if (excludeRes.some((re) => re.test(path))) return false;
+ return includeRes.some((re) => re.test(path));
+ };
+ const unitEntryFor = (relPath) => {
+ const path = normalizeRelativePath(relPath);
+ if (isExcluded(path)) return null;
+ return unitRes.find((unit) => unit.regexes.some((re) => re.test(path))) ?? null;
+ };
+ return {
+ config,
+ isExcluded,
+ isInScope,
+ unitFor(relPath) {
+ return unitEntryFor(relPath)?.id ?? null;
+ },
+ familyFor(relPath) {
+ const path = normalizeRelativePath(relPath);
+ const unit = unitEntryFor(path);
+ if (unit !== null) {
+ return { extractor: unit.family.extractor, extensions: unit.family.extensions };
+ }
+ return byExtension.get(extensionOf(path)) ?? null;
+ },
+ pruneDirectories: new Set(config.pruneDirectories),
+ };
+}
+
+function canonicalPath(path) {
+ try {
+ return realpathSync.native(path);
+ } catch {
+ return resolve(path);
+ }
+}
+
+const MODULE_DIR = dirname(fileURLToPath(import.meta.url));
+
+export const SUBJECT_ROOT = canonicalPath(join(MODULE_DIR, '..', '..'));
+
+const scopeCache = new Map();
+
+export function scopeForRoot(root) {
+ const key = canonicalPath(root);
+ const configPath = join(root, SCOPE_CONFIG_FILENAME);
+ const digest = sourceDigest(configPath);
+ const cached = scopeCache.get(key);
+ if (isFresh(cached, digest)) return cached.scope;
+ const config = loadScopeConfig(root);
+ if (config === null) {
+ scopeCache.delete(key);
+ throw new ScopeConfigMissingError({ root, configPath });
+ }
+ const scope = compileScope(config);
+ scopeCache.set(key, { scope, digest });
+ return scope;
+}
+
+export function diagnoseScope(root) {
+ try {
+ return { status: 'ok', root, scope: scopeForRoot(root) };
+ } catch (error) {
+ if (error instanceof ScopeConfigMissingError) {
+ return {
+ status: 'missing',
+ root,
+ configPath: error.configPath,
+ message: error.message,
+ };
+ }
+ if (error instanceof ScopeConfigError) {
+ return {
+ status: 'invalid',
+ root,
+ configPath: error.configPath,
+ key: error.key,
+ message: `scope-config: UNREADABLE. ${error.message}`,
+ };
+ }
+ throw error;
+ }
+}
+
+export function subjectScope() {
+ return scopeForRoot(SUBJECT_ROOT);
+}
+
export function isExcluded(relPath) {
- const path = normalizeRelativePath(relPath);
- return EXCLUDE_RES.some((re) => re.test(path));
+ return subjectScope().isExcluded(relPath);
}
export function isInScope(relPath) {
- const path = normalizeRelativePath(relPath);
- if (EXCLUDE_RES.some((re) => re.test(path))) return false;
- return INCLUDE_RES.some((re) => re.test(path));
+ return subjectScope().isInScope(relPath);
}
-export function stratumFor(relPath) {
- const path = normalizeRelativePath(relPath);
- if (isExcluded(path)) return null;
- for (const stratum of STRATUM_RES) {
- if (stratum.regexes.some((re) => re.test(path))) return stratum.id;
- }
- return null;
+export function unitFor(relPath) {
+ return subjectScope().unitFor(relPath);
}
-const WALK_SKIP_DIRS = new Set([
- 'node_modules',
- 'dist',
- 'build',
- '.next',
- '.turbo',
- '.git',
- 'coverage',
-]);
+export function familyFor(relPath) {
+ return subjectScope().familyFor(relPath);
+}
-const SCOPE_ROOTS = ['packages', 'scripts', '.github', 'docs', 'lint-plugins'];
+function requireWalker({ readdirSync, statSync, lstatSync }) {
+ for (const [name, fn] of [
+ ['readdirSync', readdirSync],
+ ['statSync', statSync],
+ ['lstatSync', lstatSync],
+ ]) {
+ if (typeof fn === 'function') continue;
+ throw new TypeError(
+ `discovery needs a ${name}. lstatSync is what tells a symlink from a real entry, and ` +
+ `statSync is what tells a link to a directory from a link to a file; substituting one for ` +
+ `the other makes the symlink branch unreachable and silently widens the corpus to whatever ` +
+ `the links point at.`,
+ );
+ }
+}
-function discoverInScopeFilesWithSkips(repoRoot, { readdirSync, lstatSync }) {
- const found = [];
+export function discoverInScopeFilesWithSkips(repoRoot, options) {
+ requireWalker(options);
+ const { readdirSync, statSync, lstatSync } = options;
+ const scope = scopeForRoot(repoRoot);
+ const { isInScope: inScope, pruneDirectories } = scope;
+ const found = new Set();
const skips = [];
+ const linksToDirectory = (abs) => {
+ try {
+ return statSync(abs).isDirectory();
+ } catch {
+ return false;
+ }
+ };
const walk = (absDir, relDir) => {
let entries;
try {
@@ -115,7 +329,7 @@ function discoverInScopeFilesWithSkips(repoRoot, { readdirSync, lstatSync }) {
return;
}
for (const entry of entries) {
- if (WALK_SKIP_DIRS.has(entry)) continue;
+ if (pruneDirectories.has(entry)) continue;
const abs = `${absDir}/${entry}`;
const rel = relDir === '' ? entry : `${relDir}/${entry}`;
let stat;
@@ -126,31 +340,56 @@ function discoverInScopeFilesWithSkips(repoRoot, { readdirSync, lstatSync }) {
continue;
}
if (stat.isSymbolicLink()) {
- if (isInScope(rel)) skips.push({ path: rel, reason: 'symlink' });
+ if (inScope(rel)) skips.push({ path: rel, reason: 'symlink' });
+ else if (linksToDirectory(abs)) skips.push({ path: rel, reason: 'symlink-directory' });
continue;
}
if (stat.isDirectory()) walk(abs, rel);
- else if (isInScope(rel)) found.push(rel);
+ else if (inScope(rel)) found.add(rel);
}
};
+ const walkRoots = new Set(scope.config.walkRoots);
for (const entry of readdirSync(repoRoot)) {
+ const isRoot = walkRoots.has(entry);
+ if (!isRoot && !inScope(entry)) continue;
const abs = `${repoRoot}/${entry}`;
- if (SCOPE_ROOTS.includes(entry)) {
- walk(abs, entry);
+ let stat;
+ try {
+ stat = lstatSync(abs);
+ } catch (error) {
+ skips.push({ path: entry, reason: error?.code ?? 'stat-failed' });
+ continue;
+ }
+ if (stat.isSymbolicLink()) {
+ skips.push({ path: entry, reason: 'symlink' });
continue;
}
- if (isInScope(entry)) found.push(entry);
+ if (isRoot) walk(abs, entry);
+ else if (!stat.isDirectory()) found.add(entry);
+ }
+ for (const unit of scope.config.units) {
+ for (const file of unit.files) {
+ if (found.has(file) || !inScope(file)) continue;
+ const abs = `${repoRoot}/${file}`;
+ let stat;
+ try {
+ stat = lstatSync(abs);
+ } catch (error) {
+ if (error?.code !== 'ENOENT') {
+ skips.push({ path: file, reason: error?.code ?? 'stat-failed' });
+ }
+ continue;
+ }
+ if (stat.isSymbolicLink()) skips.push({ path: file, reason: 'symlink' });
+ else if (stat.isFile()) found.add(file);
+ }
}
- found.sort();
skips.sort((a, b) => (a.path < b.path ? -1 : 1));
- return { files: found, skips };
+ return { files: [...found].sort(), skips, declaredAbsent: scope.config.declaredAbsent };
}
-export function discoverInScopeFiles(repoRoot, { readdirSync, statSync, lstatSync }) {
- const { files, skips } = discoverInScopeFilesWithSkips(repoRoot, {
- readdirSync,
- lstatSync: lstatSync ?? statSync,
- });
+export function discoverInScopeFiles(repoRoot, options) {
+ const { files, skips } = discoverInScopeFilesWithSkips(repoRoot, options);
if (skips.length > 0) {
const preview = skips
.slice(0, 5)
diff --git a/lint-plugins/no-comments/scope.test.mjs b/lint-plugins/no-comments/scope.test.mjs
index 5ee0bfc24..3de4552cd 100644
--- a/lint-plugins/no-comments/scope.test.mjs
+++ b/lint-plugins/no-comments/scope.test.mjs
@@ -1,19 +1,44 @@
-import { lstatSync, readdirSync, statSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import { fileURLToPath } from 'node:url';
-import { describe, expect, test } from 'vitest';
+import { execFileSync } from 'node:child_process';
import {
+ lstatSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ utimesSync,
+ writeFileSync,
+} from 'node:fs';
+import { tmpdir } from 'node:os';
+import { basename, dirname, join } from 'node:path';
+import { afterAll, describe, expect, test } from 'vitest';
+import {
+ loadScopeConfig,
+ SCOPE_CONFIG_FILENAME,
+ ScopeConfigError,
+ ScopeConfigMissingError,
+ unitsRequiringFiles,
+} from './config.mjs';
+import {
+ diagnoseScope,
discoverInScopeFiles,
+ discoverInScopeFilesWithSkips,
globToRegExp,
isExcluded,
isInScope,
- SCOPE_EXCLUDE,
- SCOPE_INCLUDE,
- SCOPE_STRATA,
- stratumFor,
+ SUBJECT_ROOT as REPO_ROOT,
+ scopeForRoot,
+ subjectScope,
+ unitFor,
} from './scope.mjs';
+import {
+ configWith,
+ createScratchRoot,
+ removeScratchRoots,
+} from './scratch-root.test-helper.mjs';
-const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+const CONFIG = subjectScope().config;
const privateTestPath = (dir, stem) => `${dir}/${stem}.private.test.ts`;
@@ -51,12 +76,29 @@ describe('scope membership', () => {
'docs/lib/a.cts',
'oxlint.config.ts',
'vitest.scripts.config.mts',
+ 'packages/desktop/scripts/afterPack.mjs',
+ 'packages/app/src/build/app-version.ts',
+ 'packages/app/src/build/rejection-loop-guard-script.js',
+ 'packages/desktop/tests/unit/packaged-report-path.test.mjs',
+ 'packages/app/tests/perf/fixtures/cache-regime-rotation/vault.ts',
+ 'packages/core/src/markdown/fixtures/index.ts',
+ 'test-support/vitest.base.ts',
+ 'test-support/strip-comments.test-helper.mjs',
+ 'plugins/ok/skills/bug-triage/scripts/linear-issue.mjs',
+ 'packages/app/src/lib/a.mjs',
+ 'packages/app/tests/fidelity/invariant-i17.test.ts',
+ 'packages/desktop/tests/lume-qa/scenarios/ok-e2e-claude.ts',
+ 'packages/desktop/tests/lume-qa/lume-qa-happy-path.e2e.ts',
+ 'scripts/lume-bake/bake.sh',
+ 'packages/app/scripts/perf-prod.sh',
+ 'packages/desktop/build/deb-postinst.sh',
+ 'plugins/ok/skills/linux-vm/scripts/linuxvm.sh',
+ '.husky/pre-commit',
+ '.husky/pre-push',
];
const outOfScope = [
'knip.config.ts',
'packages/md-conformance/md-audit/src/lib/tags.ts',
- 'packages/app/tests/fidelity/invariant-i17.test.ts',
- 'packages/desktop/tests/lume-qa/orchestrator.ts',
privateTestPath('packages/core/src/markdown', 'a'),
'packages/app/src/locales/en/messages.ts',
'docs/next-env.d.ts',
@@ -64,9 +106,15 @@ describe('scope membership', () => {
'docs/lib/types.d.cts',
'types.d.mts',
'lint-plugins/no-comments/__fixtures__/must-fire.fixture.ts',
- 'packages/app/src/lib/a.mjs',
'packages/app/node_modules/x/src/a.ts',
- 'test-support/vitest.base.ts',
+ 'tech-probes/r1-preflight-gate/probe.mjs',
+ 'packages/native-config/index.js',
+ 'packages/md-conformance/md-audit/src/lib/registry.mjs',
+ '.claude/hooks/no-comments-guard.sh',
+ 'reports/comment-policy-adoption/scripts/measure.sh',
+ 'specs/2026-09-02-no-comments-substrate-hardening/probe.sh',
+ 'sandbox-recipes/claude-code/setup.sh',
+ 'packages/md-conformance/scripts/tournament-orchestrate.sh',
];
test.each(inScope)('%s is in scope', (path) => expect(isInScope(path)).toBe(true));
@@ -77,8 +125,51 @@ describe('scope membership', () => {
});
test('the fixture corpus is excluded so the gate cannot self-trip', () => {
- expect(SCOPE_EXCLUDE).toContain('**/__fixtures__/**');
- expect(SCOPE_EXCLUDE).toContain('**/*.fixture.ts');
+ expect(CONFIG.exclude).toContain('**/__fixtures__/**');
+ expect(CONFIG.exclude).toContain('**/*.fixture.ts');
+ });
+
+ test('an authored fixtures/ directory is ordinary source, not a carve-out', () => {
+ expect(CONFIG.exclude).not.toContain('**/fixtures/**');
+ expect(isInScope('packages/app/tests/perf/fixtures/generate-view-count-fixtures.ts')).toBe(
+ true,
+ );
+ });
+});
+
+describe('the non-vacuity floor excuses a unit this tree does not carry', () => {
+ const unitsFor = (roots) =>
+ unitsRequiringFiles(
+ loadScopeConfig(
+ createScratchRoot({
+ prefix: 'no-comments-floor-',
+ config: configWith({
+ units: [
+ { id: 'app', family: 'typescript', roots: ['packages/*/src'] },
+ { id: 'absent', family: 'typescript', roots },
+ ],
+ }),
+ files: { 'packages/a/src/a.ts': 'export const a = 1;\n' },
+ }),
+ ),
+ );
+
+ test('a unit whose every declared root is absent is excused', () => {
+ expect(unitsFor(['plugins'])).toEqual(['app']);
+ });
+
+ test('a unit whose root exists but holds no in-scope file is still required', () => {
+ expect(unitsFor(['packages/*/src'])).toEqual(['app', 'absent']);
+ });
+
+ test('a unit carrying one present root and one absent root is still required', () => {
+ expect(unitsFor(['plugins', 'packages/*/src'])).toEqual(['app', 'absent']);
+ });
+
+ test('a config that never stat-ed the tree is refused rather than read as all-present', () => {
+ expect(() => unitsRequiringFiles({ units: CONFIG.units, declaredPaths: [] })).toThrow(
+ /declaredAbsent/,
+ );
});
});
@@ -89,12 +180,35 @@ describe('discovery over the real tree', () => {
expect(discovered.length).toBeGreaterThan(1000);
});
- test.each(SCOPE_STRATA.map((s) => s.id))('stratum %s is non-vacuous', (id) => {
- expect(discovered.filter((path) => stratumFor(path) === id).length).toBeGreaterThan(0);
+ const required = unitsRequiringFiles(CONFIG);
+
+ test('the non-vacuity floor itself covers units', () => {
+ expect(required.length).toBeGreaterThan(0);
});
- test('every discovered file belongs to exactly one declared stratum', () => {
- expect(discovered.filter((path) => stratumFor(path) === null)).toEqual([]);
+ test.each(required)('unit %s is non-vacuous', (id) => {
+ expect(discovered.filter((path) => unitFor(path) === id).length).toBeGreaterThan(0);
+ });
+
+ test('every discovered file belongs to exactly one declared unit', () => {
+ expect(discovered.filter((path) => unitFor(path) === null)).toEqual([]);
+ });
+
+ test('every file discovery finds is a file git tracks', () => {
+ const tracked = new Set(
+ execFileSync('git', ['ls-files', '-z'], {
+ cwd: REPO_ROOT,
+ encoding: 'utf8',
+ maxBuffer: 1 << 28,
+ })
+ .split('\0')
+ .filter(Boolean),
+ );
+ expect(
+ discovered.filter((path) => !tracked.has(path)),
+ 'track it if it is source, move it outside the declared roots if it is scratch, or add it ' +
+ 'to exclude if it is generated output',
+ ).toEqual([]);
});
test('no excluded tree leaks into discovery', () => {
@@ -111,8 +225,19 @@ describe('discovery over the real tree', () => {
});
describe('the scope definition is derived, not restated', () => {
- test('SCOPE_INCLUDE is exactly the union of the declared strata', () => {
- expect(SCOPE_INCLUDE).toEqual(SCOPE_STRATA.flatMap((stratum) => stratum.include));
+ test('include is the flatten of the per-unit globs the matcher itself compiles', () => {
+ expect(CONFIG.include).toEqual(CONFIG.units.flatMap((unit) => unit.include));
+ });
+
+ test('isInScope admits exactly the paths some unit claims', () => {
+ const probes = CONFIG.include
+ .map((glob) => glob.replace(/\*\*\//g, 'x/').replace(/\*/g, 'a'))
+ .concat(['README.md', 'packages/md-conformance/anything.ts', 'packages/app/src/a.md']);
+ expect(probes.filter((path) => isInScope(path) !== (unitFor(path) !== null))).toEqual([]);
+ });
+
+ test('the config the predicate reads is the one committed at the repository root', () => {
+ expect(loadScopeConfig(REPO_ROOT).include).toEqual(CONFIG.include);
});
test('isExcluded reports the exclusion independently of the include set', () => {
@@ -122,6 +247,292 @@ describe('the scope definition is derived, not restated', () => {
});
});
+describe('a directory-name-shaped exclude prunes that directory during the walk', () => {
+ const roots = [];
+ afterAll(() => {
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+ });
+
+ const syntheticRoot = (excludeGlob) => {
+ const root = mkdtempSync(join(tmpdir(), 'no-comments-prune-'));
+ roots.push(root);
+ for (const rel of [
+ 'packages/pkg/src/real.ts',
+ 'packages/pkg/src/vendored/deep/one.ts',
+ 'packages/pkg/src/vendored/deep/two.ts',
+ ]) {
+ mkdirSync(dirname(join(root, rel)), { recursive: true });
+ writeFileSync(join(root, rel), 'export const a = 1;\n');
+ }
+ writeFileSync(
+ join(root, 'no-comments.config.jsonc'),
+ JSON.stringify({
+ version: 1,
+ families: { ts: { extensions: ['.ts'], extractor: 'c-family' } },
+ units: [{ id: 'src', family: 'ts', roots: ['packages/**/src'] }],
+ exclude: [excludeGlob],
+ }),
+ );
+ return root;
+ };
+
+ const discoverCountingReads = (root) => {
+ const read = [];
+ const files = discoverInScopeFiles(root, {
+ readdirSync: (dir) => {
+ read.push(basename(dir));
+ return readdirSync(dir);
+ },
+ statSync,
+ lstatSync,
+ });
+ return { files, read };
+ };
+
+ test('the same membership is reachable with and without the prune, so the rule is observable', () => {
+ const pruned = discoverCountingReads(syntheticRoot('**/vendored/**'));
+ const walked = discoverCountingReads(syntheticRoot('packages/pkg/src/vendored/**'));
+ expect(pruned.files).toEqual(['packages/pkg/src/real.ts']);
+ expect(walked.files).toEqual(pruned.files);
+ expect(pruned.read).not.toContain('vendored');
+ expect(walked.read).toContain('vendored');
+ expect(walked.read).toContain('deep');
+ });
+
+ test('no directory a real-tree exclude names is ever read, and the walk did meet some', () => {
+ const read = [];
+ const met = [];
+ discoverInScopeFiles(REPO_ROOT, {
+ readdirSync: (dir) => {
+ read.push(basename(dir));
+ const entries = readdirSync(dir);
+ for (const entry of entries) {
+ if (CONFIG.pruneDirectories.includes(entry)) met.push(entry);
+ }
+ return entries;
+ },
+ statSync,
+ lstatSync,
+ });
+ expect(read.filter((name) => CONFIG.pruneDirectories.includes(name))).toEqual([]);
+ expect(met).toContain('node_modules');
+ expect(met.length).toBeGreaterThan(1);
+ });
+});
+
+describe('a unit can name files no extension would reach', () => {
+ const roots = [];
+ afterAll(() => {
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+ });
+
+ const rootWithHooks = () => {
+ const root = mkdtempSync(join(tmpdir(), 'no-comments-files-'));
+ roots.push(root);
+ writeFileSync(
+ join(root, 'no-comments.config.jsonc'),
+ JSON.stringify({
+ version: 1,
+ families: { shell: { extensions: ['.sh'], extractor: 'hash-family' } },
+ units: [
+ {
+ id: 'shell',
+ family: 'shell',
+ roots: ['scripts'],
+ files: ['.husky/pre-commit', '.husky/never-written'],
+ },
+ ],
+ exclude: [],
+ }),
+ );
+ for (const rel of ['scripts/build.sh', '.husky/pre-commit']) {
+ mkdirSync(dirname(join(root, rel)), { recursive: true });
+ writeFileSync(join(root, rel), '#!/usr/bin/env bash\n');
+ }
+ return root;
+ };
+
+ test('an extensionless member is discovered and attributed to the unit that names it', () => {
+ const root = rootWithHooks();
+ expect(discoverInScopeFiles(root, { readdirSync, statSync, lstatSync })).toStrictEqual([
+ '.husky/pre-commit',
+ 'scripts/build.sh',
+ ]);
+ const scope = scopeForRoot(root);
+ expect(scope.isInScope('.husky/pre-commit')).toBe(true);
+ expect(scope.unitFor('.husky/pre-commit')).toBe('shell');
+ });
+
+ test('a named file the tree lacks is recorded as declared-absent, never as an error', () => {
+ const root = rootWithHooks();
+ const { declaredAbsent } = discoverInScopeFilesWithSkips(root, {
+ readdirSync,
+ statSync,
+ lstatSync,
+ });
+ expect(declaredAbsent).toStrictEqual([
+ { unit: 'shell', kind: 'file', path: '.husky/never-written' },
+ ]);
+ });
+});
+
+describe('a hash family may not declare a dialect no reference measures', () => {
+ afterAll(removeScratchRoots);
+
+ const rootDeclaring = (extensions) =>
+ createScratchRoot({
+ prefix: 'no-comments-unmeasured-dialect-',
+ config: configWith({
+ families: { probe: { extensions, extractor: 'hash-family' } },
+ units: [{ id: 'probe', family: 'probe', roots: ['scripts'] }],
+ }),
+ });
+
+ test('a .py family is refused at load, naming the dialect and what it lacks', () => {
+ let thrown;
+ try {
+ scopeForRoot(rootDeclaring(['.py']));
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toBeInstanceOf(ScopeConfigError);
+ expect(thrown.key).toBe('families.probe.extensions');
+ expect(thrown.message).toContain('python');
+ expect(thrown.message).toContain('comment-position reference');
+ });
+
+ test('the refusal is the missing reference, not the hash family: a .sh family loads', () => {
+ expect(scopeForRoot(rootDeclaring(['.sh'])).isInScope('scripts/build.sh')).toBe(true);
+ });
+
+ test('it names a move the adopter can make, not only one a contributor to this file can', () => {
+ let thrown;
+ try {
+ scopeForRoot(rootDeclaring(['.sh', '.py']));
+ } catch (error) {
+ thrown = error;
+ }
+ expect(thrown).toBeInstanceOf(ScopeConfigError);
+ expect(thrown.message).toContain('Drop .py from this family');
+ expect(thrown.message).not.toContain('.sh from this family');
+ expect(thrown.message).toContain('lint-plugins/no-comments/extract-hash.mjs');
+ expect(thrown.message).toContain('DIALECTS');
+ });
+});
+
+describe('a ./ prefix is a spelling, never a membership decision', () => {
+ afterAll(removeScratchRoots);
+
+ const TREE = {
+ 'packages/pkg/src/a.ts': 'export const a = 1;\n',
+ 'packages/pkg/src/vendored/deep/b.ts': 'export const b = 2;\n',
+ 'tools/present.ts': 'export const present = true;\n',
+ };
+
+ const rootDeclaring = ({ roots = ['packages/**/src'], files, exclude = [] }) =>
+ createScratchRoot({
+ prefix: 'no-comments-spelling-',
+ config: {
+ version: 1,
+ families: { ts: { extensions: ['.ts'], extractor: 'c-family' } },
+ units: [{ id: 'src', family: 'ts', roots, ...(files === undefined ? {} : { files }) }],
+ exclude,
+ },
+ files: TREE,
+ });
+
+ const discover = (root) =>
+ discoverInScopeFilesWithSkips(root, { readdirSync, statSync, lstatSync });
+
+ const cells = [
+ ['canonical spelling of a file the tree has', 'tools/present.ts', true],
+ ['./ spelling of a file the tree has', './tools/present.ts', true],
+ ['canonical spelling of a file the tree lacks', 'tools/missing.ts', false],
+ ['./ spelling of a file the tree lacks', './tools/missing.ts', false],
+ ];
+
+ test.each(cells)('%s', (_label, entry, exists) => {
+ const root = rootDeclaring({ files: [entry] });
+ const { files, declaredAbsent } = discover(root);
+ const canonical = entry.replace(/^\.\//, '');
+ expect(scopeForRoot(root).unitFor(canonical)).toBe('src');
+ expect(files.includes(canonical)).toBe(exists);
+ expect(declaredAbsent).toStrictEqual(
+ exists ? [] : [{ unit: 'src', kind: 'file', path: canonical }],
+ );
+ });
+
+ test('a ./-prefixed exclude excludes exactly what its canonical spelling excludes', () => {
+ const canonical = discover(rootDeclaring({ exclude: ['**/vendored/**'] }));
+ const dotted = discover(rootDeclaring({ exclude: ['./**/vendored/**'] }));
+ expect(canonical.files).toStrictEqual(['packages/pkg/src/a.ts']);
+ expect(dotted.files).toStrictEqual(canonical.files);
+ });
+
+ test('a trailing-slash root discovers exactly what the bare root discovers', () => {
+ const bare = discover(rootDeclaring({ roots: ['packages'] }));
+ const slashed = discover(rootDeclaring({ roots: ['packages/'] }));
+ expect(bare.files.length).toBeGreaterThan(0);
+ expect(slashed.files).toStrictEqual(bare.files);
+ expect(slashed.declaredAbsent).toStrictEqual(bare.declaredAbsent);
+ });
+
+ test('a root that leaves the tree is refused by name rather than walked', () => {
+ const root = rootDeclaring({ roots: ['../outside'] });
+ const diagnosis = diagnoseScope(root);
+ expect(diagnosis.status).toBe('invalid');
+ expect(diagnosis.key).toBe('units[0].roots[0]');
+ expect(diagnosis.message).toContain('scope-config: UNREADABLE');
+ });
+});
+
+describe('every directory-name-shaped exclude is pinned to what it hides', () => {
+ const SHAPED = [
+ '**/node_modules/**',
+ '**/dist/**',
+ '**/.next/**',
+ '**/.turbo/**',
+ '**/.git/**',
+ '**/coverage/**',
+ '**/__fixtures__/**',
+ ];
+
+ const tracked = execFileSync('git', ['ls-files', '-z'], {
+ cwd: REPO_ROOT,
+ encoding: 'utf8',
+ maxBuffer: 1 << 28,
+ })
+ .split('\0')
+ .filter(Boolean);
+
+ const includeRes = CONFIG.include.map(globToRegExp);
+ const hiddenBy = (glob) => {
+ const own = globToRegExp(glob);
+ const others = CONFIG.exclude.filter((other) => other !== glob).map(globToRegExp);
+ return tracked.filter(
+ (path) =>
+ includeRes.some((re) => re.test(path)) &&
+ own.test(path) &&
+ !others.some((re) => re.test(path)),
+ );
+ };
+
+ test('the pinned list is exactly the directory-name-shaped excludes the config declares', () => {
+ const shaped = CONFIG.exclude.filter((glob) => /^\*\*\/[^/*]+\/\*\*$/.test(glob));
+ expect(shaped.slice().sort()).toEqual(SHAPED.slice().sort());
+ });
+
+ test.each(SHAPED)('%s hides no tracked in-scope file', (glob) => {
+ expect(hiddenBy(glob)).toEqual([]);
+ });
+
+ test('no build-named glob hides tracked source under packages/app/src/build/', () => {
+ expect(CONFIG.exclude).not.toContain('**/build/**');
+ expect(CONFIG.exclude).not.toContain('packages/app/src/build/**');
+ expect(isInScope('packages/app/src/build/rejection-loop-guard-plugin.ts')).toBe(true);
+ });
+});
+
test('globToRegExp refuses syntax it does not implement instead of mis-compiling it', () => {
for (const glob of [
'packages/**/{src,tests}/**/*.ts',
@@ -132,3 +543,79 @@ test('globToRegExp refuses syntax it does not implement instead of mis-compiling
expect(() => globToRegExp(glob), glob).toThrow(/unsupported glob syntax/);
}
});
+
+describe('a long-lived host reads the config as it is now, not as it was at first compile', () => {
+ afterAll(removeScratchRoots);
+
+ const PINNED_EPOCH_SECONDS = 1_700_000_000;
+
+ const configScoping = (unitRoot) =>
+ configWith({ units: [{ id: 'app', family: 'typescript', roots: [unitRoot] }] });
+
+ let pinsIssued = 0;
+ const pinDistinctMtime = (configPath) => {
+ pinsIssued += 1;
+ const seconds = PINNED_EPOCH_SECONDS + pinsIssued;
+ utimesSync(configPath, seconds, seconds);
+ return configPath;
+ };
+
+ const rootScoping = (unitRoot) => {
+ const root = createScratchRoot({
+ prefix: 'no-comments-config-mtime-',
+ config: configScoping(unitRoot),
+ });
+ pinDistinctMtime(join(root, SCOPE_CONFIG_FILENAME));
+ return root;
+ };
+
+ const writeConfig = (configPath, unitRoot) => {
+ writeFileSync(configPath, `${JSON.stringify(configScoping(unitRoot), null, 2)}\n`);
+ return configPath;
+ };
+
+ const rewrite = (root, unitRoot) =>
+ pinDistinctMtime(writeConfig(join(root, SCOPE_CONFIG_FILENAME), unitRoot));
+
+ test('an edit between two calls in one process moves the scope boundary with it', () => {
+ const root = rootScoping('packages/*/src');
+ expect(scopeForRoot(root).isInScope('packages/app/src/a.ts')).toBe(true);
+ expect(scopeForRoot(root).isInScope('tools/a.ts')).toBe(false);
+
+ rewrite(root, 'tools');
+
+ expect(scopeForRoot(root).isInScope('tools/a.ts')).toBe(true);
+ expect(scopeForRoot(root).isInScope('packages/app/src/a.ts')).toBe(false);
+ });
+
+ test('an unedited config keeps serving the compile it already paid for', () => {
+ const root = rootScoping('packages/*/src');
+ expect(scopeForRoot(root)).toBe(scopeForRoot(root));
+ });
+
+ test('a config deleted after it was compiled raises rather than serving the stale compile', () => {
+ const root = rootScoping('packages/*/src');
+ expect(scopeForRoot(root).isInScope('packages/app/src/a.ts')).toBe(true);
+
+ rmSync(join(root, SCOPE_CONFIG_FILENAME));
+
+ expect(() => scopeForRoot(root)).toThrow(ScopeConfigMissingError);
+ });
+
+ test('an edit that leaves the config mtime unchanged still moves the scope boundary', () => {
+ const root = rootScoping('packages/*/src');
+ const configPath = join(root, SCOPE_CONFIG_FILENAME);
+ const mtimeAtFirstCompile = statSync(configPath).mtimeMs;
+
+ expect(scopeForRoot(root).isInScope('packages/app/src/a.ts')).toBe(true);
+ expect(scopeForRoot(root).isInScope('tools/a.ts')).toBe(false);
+
+ writeConfig(configPath, 'tools');
+ utimesSync(configPath, mtimeAtFirstCompile / 1000, mtimeAtFirstCompile / 1000);
+ expect(statSync(configPath).mtimeMs).toBe(mtimeAtFirstCompile);
+ expect(readFileSync(configPath, 'utf8')).toContain('"tools"');
+
+ expect(scopeForRoot(root).isInScope('tools/a.ts')).toBe(true);
+ expect(scopeForRoot(root).isInScope('packages/app/src/a.ts')).toBe(false);
+ });
+});
diff --git a/lint-plugins/no-comments/scratch-root.test-helper.mjs b/lint-plugins/no-comments/scratch-root.test-helper.mjs
new file mode 100644
index 000000000..2351caa78
--- /dev/null
+++ b/lint-plugins/no-comments/scratch-root.test-helper.mjs
@@ -0,0 +1,56 @@
+import { cpSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join, resolve } from 'node:path';
+
+const PREDICATE_DIR = import.meta.dirname;
+const SUBJECT_ROOT = resolve(PREDICATE_DIR, '..', '..');
+
+export const SCOPE_CONFIG_NAME = 'no-comments.config.jsonc';
+
+export const NO_CONFIG = Symbol('no scope config at this root');
+
+const WORKING_CONFIG = {
+ version: 1,
+ families: { typescript: { extensions: ['.ts'], extractor: 'c-family' } },
+ units: [{ id: 'app', family: 'typescript', roots: ['packages/*/src'] }],
+ exclude: [],
+};
+
+export function configWith(overrides) {
+ return { ...WORKING_CONFIG, ...overrides };
+}
+
+const roots = new Set();
+
+export function createScratchRoot({ prefix = 'no-comments-lane-', config, files = {}, nest } = {}) {
+ const base = realpathSync(mkdtempSync(join(tmpdir(), prefix)));
+ roots.add(base);
+ const root = nest === undefined ? base : join(base, nest);
+ mkdirSync(root, { recursive: true });
+ cpSync(PREDICATE_DIR, join(root, 'lint-plugins/no-comments'), { recursive: true });
+ if (config !== NO_CONFIG) {
+ const text =
+ config === undefined
+ ? readFileSync(join(SUBJECT_ROOT, SCOPE_CONFIG_NAME), 'utf8')
+ : typeof config === 'string'
+ ? config
+ : `${JSON.stringify(config, null, 2)}\n`;
+ writeFileSync(join(root, SCOPE_CONFIG_NAME), text);
+ }
+ writeScratchFiles(root, files);
+ return root;
+}
+
+function writeScratchFiles(root, files) {
+ for (const [relPath, source] of Object.entries(files)) {
+ const absPath = join(root, relPath);
+ mkdirSync(dirname(absPath), { recursive: true });
+ writeFileSync(absPath, source);
+ }
+ return root;
+}
+
+export function removeScratchRoots() {
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+ roots.clear();
+}
diff --git a/lint-plugins/no-comments/tag-scope.mjs b/lint-plugins/no-comments/tag-scope.mjs
new file mode 100644
index 000000000..ee8783c79
--- /dev/null
+++ b/lint-plugins/no-comments/tag-scope.mjs
@@ -0,0 +1,119 @@
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { SANCTIONED_TAGS } from './allowlist.mjs';
+import { UNSUPPORTED_GLOB_SYNTAX } from './config.mjs';
+import { globToRegExp, normalizeRelativePath, SUBJECT_ROOT } from './scope.mjs';
+
+export const TAG_SURFACE_FILENAME = 'no-comments.tag-globs.generated.json';
+export const SUPPORTED_TAG_SURFACE_MAJOR = 1;
+
+export class TagSurfaceError extends Error {
+ constructor(message, { surfacePath, key }) {
+ super(`${surfacePath}${key ? ` (${key})` : ''}: ${message}`);
+ this.name = 'TagSurfaceError';
+ this.surfacePath = surfacePath;
+ this.key = key;
+ }
+}
+
+function requireStringArray(value, { surfacePath, key }) {
+ if (!Array.isArray(value) || value.some((entry) => typeof entry !== 'string' || entry === '')) {
+ throw new TagSurfaceError('must be an array of non-empty strings', { surfacePath, key });
+ }
+ return value;
+}
+
+export function parseTagSurfaces(text, { surfacePath }) {
+ let raw;
+ try {
+ raw = JSON.parse(text);
+ } catch (error) {
+ throw new TagSurfaceError(error.message, { surfacePath });
+ }
+ if (raw?.version !== SUPPORTED_TAG_SURFACE_MAJOR) {
+ throw new TagSurfaceError(
+ `unsupported version ${JSON.stringify(raw?.version)}; this predicate reads major ` +
+ `${SUPPORTED_TAG_SURFACE_MAJOR}. Regenerate the artifact against this predicate.`,
+ { surfacePath, key: 'version' },
+ );
+ }
+ if (!Array.isArray(raw.surfaces) || raw.surfaces.length === 0) {
+ throw new TagSurfaceError(
+ 'must list at least one consumer surface; an empty artifact strands every tag comment ' +
+ 'in the tree rather than scoping admission.',
+ { surfacePath, key: 'surfaces' },
+ );
+ }
+ return raw.surfaces.map((surface, index) => {
+ const key = `surfaces[${index}]`;
+ if (typeof surface?.id !== 'string' || surface.id === '') {
+ throw new TagSurfaceError('needs an id naming the consumer', { surfacePath, key });
+ }
+ return {
+ id: surface.id,
+ tags: requireStringArray(surface.tags, { surfacePath, key: `${key}.tags` }),
+ include: requireGlobArray(surface.include, { surfacePath, key: `${key}.include` }),
+ exclude: requireGlobArray(surface.exclude ?? [], { surfacePath, key: `${key}.exclude` }),
+ };
+ });
+}
+
+function requireGlobArray(value, { surfacePath, key }) {
+ const globs = requireStringArray(value, { surfacePath, key });
+ for (const glob of globs) {
+ if (!UNSUPPORTED_GLOB_SYNTAX.test(glob)) continue;
+ throw new TagSurfaceError(
+ `carries ${glob}, which the matcher does not implement. It compiles literals, * and ** ` +
+ 'only, so anything else would be read as a literal and scope tag admission to a surface ' +
+ 'the generator never named.',
+ { surfacePath, key },
+ );
+ }
+ return globs;
+}
+
+export function compileTagSurfaces(surfaces, { vocabulary = SANCTIONED_TAGS } = {}) {
+ const compiled = surfaces.map((surface) => ({
+ tags: surface.tags.filter((tag) => vocabulary.includes(tag)),
+ include: surface.include.map(globToRegExp),
+ exclude: surface.exclude.map(globToRegExp),
+ }));
+ return (relPath) => {
+ const path = normalizeRelativePath(relPath);
+ const admitted = new Set();
+ for (const surface of compiled) {
+ if (surface.exclude.some((pattern) => pattern.test(path))) continue;
+ if (!surface.include.some((pattern) => pattern.test(path))) continue;
+ for (const tag of surface.tags) admitted.add(tag);
+ }
+ return vocabulary.filter((tag) => admitted.has(tag));
+ };
+}
+
+const NO_SURFACE = () => [];
+
+function readTagSurfaces(root) {
+ const surfacePath = join(root, TAG_SURFACE_FILENAME);
+ let text;
+ try {
+ text = readFileSync(surfacePath, 'utf8');
+ } catch (error) {
+ if (error?.code !== 'ENOENT') throw error;
+ return NO_SURFACE;
+ }
+ return compileTagSurfaces(parseTagSurfaces(text, { surfacePath }));
+}
+
+const matcherCache = new Map();
+
+export function tagSurfaceMatcherForRoot(root) {
+ const cached = matcherCache.get(root);
+ if (cached) return cached;
+ const matcher = readTagSurfaces(root);
+ matcherCache.set(root, matcher);
+ return matcher;
+}
+
+export function sanctionedTagsForPath(relPath, root = SUBJECT_ROOT) {
+ return tagSurfaceMatcherForRoot(root)(relPath);
+}
diff --git a/lint-plugins/no-comments/tag-scope.test.mjs b/lint-plugins/no-comments/tag-scope.test.mjs
new file mode 100644
index 000000000..9de9463f5
--- /dev/null
+++ b/lint-plugins/no-comments/tag-scope.test.mjs
@@ -0,0 +1,138 @@
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { afterAll, describe, expect, test } from 'vitest';
+import {
+ compileTagSurfaces,
+ parseTagSurfaces,
+ SUPPORTED_TAG_SURFACE_MAJOR,
+ TAG_SURFACE_FILENAME,
+ TagSurfaceError,
+ tagSurfaceMatcherForRoot,
+} from './tag-scope.mjs';
+
+const VOCABULARY = ['@alpha-mark', '@beta-mark'];
+
+const SURFACES = [
+ {
+ id: 'declarations',
+ tags: ['@alpha-mark', '@beta-mark'],
+ include: ['src/audited/**/*.ts'],
+ exclude: ['**/*.contract.ts'],
+ },
+ {
+ id: 'anchors',
+ tags: ['@beta-mark'],
+ include: ['src/engine/**/*.ts'],
+ exclude: ['**/*.test.ts'],
+ },
+];
+
+const roots = [];
+const rootWith = (contents) => {
+ const root = mkdtempSync(join(tmpdir(), 'no-comments-tag-scope-'));
+ roots.push(root);
+ if (contents !== null) writeFileSync(join(root, TAG_SURFACE_FILENAME), contents);
+ return root;
+};
+afterAll(() => {
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
+});
+
+describe('a tag is admitted where a surface that reads it covers the path', () => {
+ const tagsAt = compileTagSurfaces(SURFACES, { vocabulary: VOCABULARY });
+
+ test('a path inside a surface admits exactly that surface vocabulary', () => {
+ expect(tagsAt('src/audited/round-trip.ts')).toEqual(['@alpha-mark', '@beta-mark']);
+ expect(tagsAt('src/engine/pipeline.ts')).toEqual(['@beta-mark']);
+ });
+
+ test('a path no surface covers admits nothing', () => {
+ expect(tagsAt('src/other/helper.ts')).toEqual([]);
+ });
+
+ test('a surface exclude wins over its own include', () => {
+ expect(tagsAt('src/audited/wire.contract.ts')).toEqual([]);
+ expect(tagsAt('src/engine/pipeline.test.ts')).toEqual([]);
+ });
+
+ test('overlapping surfaces union their tags rather than shadowing', () => {
+ const overlapping = compileTagSurfaces(
+ [
+ { id: 'a', tags: ['@alpha-mark'], include: ['src/**/*.ts'], exclude: [] },
+ { id: 'b', tags: ['@beta-mark'], include: ['src/engine/**/*.ts'], exclude: [] },
+ ],
+ { vocabulary: VOCABULARY },
+ );
+
+ expect(overlapping('src/engine/pipeline.ts')).toEqual(['@alpha-mark', '@beta-mark']);
+ });
+
+ test('the live vocabulary bounds the artifact, so a retired tag stays retired', () => {
+ const retired = compileTagSurfaces(
+ [{ id: 'a', tags: ['@alpha-mark', '@retired'], include: ['src/**/*.ts'], exclude: [] }],
+ { vocabulary: VOCABULARY },
+ );
+
+ expect(retired('src/audited/round-trip.ts')).toEqual(['@alpha-mark']);
+ });
+});
+
+describe('a malformed surface artifact is loud, and an absent one is the empty scope', () => {
+ const parse = (text) => parseTagSurfaces(text, { surfacePath: '/repo/artifact.json' });
+
+ test('an unreadable artifact names the file', () => {
+ expect(() => parse('{')).toThrow(TagSurfaceError);
+ expect(() => parse('{')).toThrow('/repo/artifact.json');
+ });
+
+ test('a version this predicate does not read names the key', () => {
+ const ahead = SUPPORTED_TAG_SURFACE_MAJOR + 1;
+
+ expect(() => parse(`{"version":${ahead},"surfaces":[]}`)).toThrow(
+ new RegExp(`version.*${ahead}`, 's'),
+ );
+ });
+
+ test('an artifact with no surface is refused rather than read as "scope nothing"', () => {
+ expect(() => parse('{"version":1,"surfaces":[]}')).toThrow(/at least one consumer surface/);
+ });
+
+ test('a surface missing its globs names the entry', () => {
+ expect(() => parse('{"version":1,"surfaces":[{"id":"a","tags":["@beta-mark"]}]}')).toThrow(
+ /surfaces\[0\]\.include/,
+ );
+ });
+
+ test('a root carrying no artifact admits no tag anywhere', () => {
+ expect(tagSurfaceMatcherForRoot(rootWith(null))('src/audited/round-trip.ts')).toEqual([]);
+ });
+
+ test('a root carrying a broken artifact throws instead of silently admitting nothing', () => {
+ const root = rootWith('{"version":1,"surfaces":[{"id":"a"}]}');
+
+ expect(() => tagSurfaceMatcherForRoot(root)).toThrow(TagSurfaceError);
+ });
+});
+
+const privateTestGlob = (dir, stem) => `${dir}/${stem}.private.test.ts`;
+
+describe('the tag artifact is held to the same glob grammar as the scope config', () => {
+ const parse = (text) => parseTagSurfaces(text, { surfacePath: '/repo/artifact.json' });
+ const withGlob = (glob) =>
+ JSON.stringify({
+ version: SUPPORTED_TAG_SURFACE_MAJOR,
+ surfaces: [{ id: 'a', tags: ['@alpha-mark'], include: [glob], exclude: [] }],
+ });
+
+ test('a surface glob the matcher cannot compile is refused by name, not as a raw Error', () => {
+ expect(() => parse(withGlob('packages/{a,b}/**'))).toThrow(TagSurfaceError);
+ expect(() => parse(withGlob('packages/{a,b}/**'))).toThrow(/does not implement/);
+ expect(() => parse(withGlob('packages/(x)/**'))).toThrow(TagSurfaceError);
+ });
+
+ test('the glob shapes the generator actually emits still compile', () => {
+ expect(() => parse(withGlob('packages/app/tests/fidelity/**/*.test.ts'))).not.toThrow();
+ expect(() => parse(withGlob(privateTestGlob('packages/core/src/markdown', '*.precision')))).not.toThrow();
+ });
+});
diff --git a/lint-plugins/no-comments/text-position.mjs b/lint-plugins/no-comments/text-position.mjs
new file mode 100644
index 000000000..e85a6ceae
--- /dev/null
+++ b/lint-plugins/no-comments/text-position.mjs
@@ -0,0 +1,41 @@
+function buildLineStarts(source) {
+ const starts = [0];
+ for (let i = 0; i < source.length; i += 1) {
+ if (source.charCodeAt(i) === 10) starts.push(i + 1);
+ }
+ return starts;
+}
+
+function positionAt(lineStarts, offset) {
+ let lo = 0;
+ let hi = lineStarts.length - 1;
+ while (lo < hi) {
+ const mid = (lo + hi + 1) >> 1;
+ if (lineStarts[mid] <= offset) lo = mid;
+ else hi = mid - 1;
+ }
+ return { line: lo + 1, column: offset - lineStarts[lo] + 1 };
+}
+
+function precededByCodeOnLine(source, offset) {
+ for (let i = offset - 1; i >= 0 && source.charCodeAt(i) !== 10; i -= 1) {
+ if (!/\s/.test(source[i])) return true;
+ }
+ return false;
+}
+
+export function commentFactory(source) {
+ const lineStarts = buildLineStarts(source);
+ return (kind, start, end) => {
+ const { line, column } = positionAt(lineStarts, start);
+ return {
+ kind,
+ text: source.slice(start, end),
+ start,
+ end,
+ line,
+ column,
+ precededByCode: precededByCodeOnLine(source, start),
+ };
+ };
+}
diff --git a/no-comments.config.jsonc b/no-comments.config.jsonc
new file mode 100644
index 000000000..f7d4d0a53
--- /dev/null
+++ b/no-comments.config.jsonc
@@ -0,0 +1,56 @@
+{
+ "$schema": "./lint-plugins/no-comments/no-comments.config.schema.json",
+ "version": 1,
+ "families": {
+ "typescript": { "extensions": [".ts", ".tsx"], "extractor": "c-family" },
+ "typescript-multi-suffix": {
+ "extensions": [".ts", ".tsx", ".mts", ".cts"],
+ "extractor": "c-family"
+ },
+ "typescript-config": { "extensions": [".ts", ".mts", ".cts"], "extractor": "c-family" },
+ "esm-script": { "extensions": [".mjs", ".js"], "extractor": "c-family" },
+ "shell": { "extensions": [".sh"], "extractor": "hash-family" },
+ "yaml": { "extensions": [".yml", ".yaml"], "extractor": "hash-family" }
+ },
+ "units": [
+ { "id": "packages-src", "family": "typescript", "roots": ["packages/**/src"] },
+ { "id": "packages-tests", "family": "typescript", "roots": ["packages/**/tests"] },
+ { "id": "packages-esm", "family": "esm-script", "roots": ["packages"] },
+ { "id": "test-support", "family": "typescript", "roots": ["test-support"] },
+ { "id": "test-support-esm", "family": "esm-script", "roots": ["test-support"] },
+ { "id": "scripts", "family": "esm-script", "roots": ["scripts"] },
+ { "id": "github-scripts", "family": "esm-script", "roots": [".github/scripts"] },
+ { "id": "docs", "family": "typescript-multi-suffix", "roots": ["docs"] },
+ { "id": "root-configs", "family": "typescript-config", "roots": ["."] },
+ { "id": "lint-plugins", "family": "esm-script", "roots": ["lint-plugins"] },
+ { "id": "plugins", "family": "esm-script", "roots": ["plugins"] },
+ {
+ "id": "shell",
+ "family": "shell",
+ "roots": ["packages", "scripts", ".github", "lint-plugins", "plugins"],
+ "files": [".husky/pre-commit", ".husky/pre-push"]
+ }
+ ],
+ "exclude": [
+ "packages/md-conformance/**",
+ "packages/app/src/locales/**",
+ "packages/native-config/index.js",
+ "docs/.source/**",
+ "docs/.source-vitest/**",
+ "knip.config.ts",
+ "reports/**",
+ "specs/**",
+ "sandbox-recipes/**",
+ ".claude/**",
+ "**/*.private.*",
+ "**/*.fixture.{ts,tsx,mjs}",
+ "**/*.d.{ts,mts,cts}",
+ "**/__fixtures__/**",
+ "**/node_modules/**",
+ "**/dist/**",
+ "**/.next/**",
+ "**/.turbo/**",
+ "**/.git/**",
+ "**/coverage/**"
+ ]
+}
diff --git a/package.json b/package.json
index 0ad029225..d6095787e 100644
--- a/package.json
+++ b/package.json
@@ -77,7 +77,8 @@
"tsx": "^4.20.0",
"turbo": "^2.7.0",
"typescript": "~6.0.3",
- "vitest": "^4.1.0"
+ "vitest": "^4.1.0",
+ "yaml": "^2.8.3"
},
"puppeteer": {
"skipDownload": true
diff --git a/packages/app/scripts/_measure-lib.sh b/packages/app/scripts/_measure-lib.sh
index cb45775d3..707d5c275 100755
--- a/packages/app/scripts/_measure-lib.sh
+++ b/packages/app/scripts/_measure-lib.sh
@@ -1,37 +1,11 @@
#!/usr/bin/env bash
-#
-# _measure-lib.sh — shared helpers for the measure-*.sh / perf-*.sh producer scripts
-#
-# Source this from any producer script after `set -euo pipefail` to pick
-# up the functions below. Keeps host detection, epoch-ms resolution, JSONL
-# append serialization, and numeric-flag validation in one place so a
-# future schema change or portability fix touches one file, not each consumer.
-#
-# **This file is not directly invokable.** Source it. `bash _measure-lib.sh`
-# exits 1 with a diagnostic.
-#
-# Convention: functions live in one place; callers set a handful of
-# well-named variables (CONTEXT, SEED, etc.) before sourcing and consume
-# the functions afterward. No hidden globals — every function is pure
-# modulo its explicit arguments.
-# Refuse to run as a standalone command — sourcing is the only supported
-# invocation. Detects via BASH_SOURCE[0] (the script file) vs $0 (the
-# invoking entry point); when they match, we're being run directly.
-# shellcheck disable=SC2128
if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then
echo "error: _measure-lib.sh is a library meant to be sourced, not executed directly." >&2
echo " Use measure-fuzz.sh or measure-stress.sh as the entry point." >&2
exit 1
fi
-# ── Portable epoch-ms ──────────────────────────────────────────────────────
-# GNU `date +%s%3N` is preferred but macOS BSD `date` emits the literal
-# string "%3N" instead of milliseconds. Detect format validity and fall
-# back to seconds-times-1000 when the primary form doesn't work. Hard
-# failure (both paths yield non-numeric) exits non-zero — timing
-# infrastructure that silently returns 0 is worse than timing that
-# loudly breaks (would record nonsensical durationMs in the JSONL).
epoch_ms() {
local ms
ms="$(date +%s%3N 2>/dev/null || true)"
@@ -39,7 +13,6 @@ epoch_ms() {
printf '%s\n' "$ms"
return 0
fi
- # Fallback: seconds * 1000 (millisecond precision lost but still valid).
local sec
sec="$(date +%s 2>/dev/null || true)"
if [[ "$sec" =~ ^[0-9]+$ ]]; then
@@ -50,9 +23,6 @@ epoch_ms() {
exit 5
}
-# ── Host tag ───────────────────────────────────────────────────────────────
-# Returns "ci-<runner>" on GitHub Actions, "local-macos" / "local-linux"
-# on developer machines, or the lowercased kernel name as a fallback.
detect_host() {
if [[ -n "${GITHUB_ACTIONS:-}" ]]; then
printf '%s\n' "ci-${RUNNER_NAME:-${RUNNER_OS:-github}}"
@@ -65,11 +35,6 @@ detect_host() {
fi
}
-# ── Numeric-flag validation ────────────────────────────────────────────────
-# Usage: assert_numeric_flag <flag-name> <value> [--signed]
-# Exits 2 with a consistent error message on non-numeric input. Used to
-# prevent STRESS_FUZZ_SEED=abc silently coercing to NaN→1 at the PRNG
-# layer, producing deterministic-looking runs unrelated to the seed.
assert_numeric_flag() {
local flag_name="$1"
local value="$2"
@@ -86,39 +51,6 @@ assert_numeric_flag() {
fi
}
-# ── Atomic JSONL append ────────────────────────────────────────────────────
-# Shell `>>` append is only atomic for payloads ≤ PIPE_BUF (4096 bytes on
-# Linux) and is NOT atomic at any size on macOS. A fuzz record with many
-# failing seeds + long --context can exceed 4 KB and would interleave with
-# a concurrent measure:stress run appending to the same log, corrupting
-# the JSONL trend record. Guard with flock on Linux; fall back to mkdir-
-# based mutex on macOS (flock is not in the BSD toolchain).
-#
-# On lock failure (timeout, crash-left lockdir, filesystem error), the
-# helper now EXITS NON-ZERO rather than warn-and-proceed. The JSONL is
-# the spec-named evidence trail (NG6 of the CI signal quality spec) —
-# silently dropping or non-atomically appending to it is worse than
-# surfacing the failure to the caller who can decide whether to retry,
-# investigate, or escalate.
-#
-# Stale-lock recovery: on the mkdir fallback path, if the lockdir exists
-# and its mtime is older than 60s, treat it as a crashed-writer artifact
-# (a Ctrl-C between mkdir and rmdir would leave this behind). Remove it
-# and retry once before giving up. 60s is conservative — a real writer
-# completes its jsonl append in well under a second.
-#
-# flock vs mkdir-mutex asymmetry (both paths hit the same 10-second
-# timeout budget):
-# - `flock -w 10`: kernel-managed wait, no CPU cost while blocked.
-# Cheapest and preferred. Linux-only (flock is not in the BSD
-# toolchain).
-# - mkdir-mutex (macOS fallback): busy-waits with `sleep 0.1`
-# (100ms) polling, up to 100 iterations. CPU cost is negligible
-# at this polling frequency but NOT zero — the shell wakes ~10×/s
-# to re-attempt mkdir. Functional parity with flock for
-# correctness; lower efficiency under contention. Not worth
-# optimizing (concurrent measurement runs are rare and the budget
-# is bounded).
append_jsonl_atomic() {
local log="$1"
local record="$2"
@@ -136,9 +68,6 @@ append_jsonl_atomic() {
fi
else
local lockdir="${log}.lock"
- # Stale-lock recovery: if the lockdir is older than 60s, it's almost
- # certainly from a crashed writer. `stat -f %m` (BSD) / `stat -c %Y`
- # (GNU) returns mtime; we use portable `find -prune` with `-mmin`.
if [[ -d "$lockdir" ]]; then
local stale
stale="$(find "$lockdir" -maxdepth 0 -mmin +1 -print 2>/dev/null || true)"
@@ -158,13 +87,6 @@ append_jsonl_atomic() {
fi
sleep 0.1
done
- # Scope the lockdir-cleanup EXIT trap to a subshell so it cannot clobber
- # the caller's own EXIT trap. Setting `trap ... EXIT` here at function
- # scope would replace the caller's trap (e.g. measure-fuzz.sh's tmpfile
- # cleanup), and `trap - EXIT` afterward would not restore it — bash has
- # no native trap-stack. The subshell's trap fires on subshell exit
- # (success or failure), guaranteeing rmdir without touching the parent
- # script's trap state. Mirrors the flock branch above.
(
trap "rmdir '$lockdir' 2>/dev/null || true" EXIT
printf '%s\n' "$record" >> "$log"
@@ -172,9 +94,6 @@ append_jsonl_atomic() {
fi
}
-# ── jq pre-flight ──────────────────────────────────────────────────────────
-# Fail loud and early if the script's hard dependencies are missing. Keeps
-# the callers symmetric — neither has to reimplement the check.
require_jq() {
if ! command -v jq >/dev/null 2>&1; then
echo "error: jq is required (JSONL composition)" >&2
@@ -183,16 +102,6 @@ require_jq() {
fi
}
-# ── OK workspace root ──────────────────────────────────────────────────────
-# Derive the workspace root structurally from this lib's own location
-# (packages/app/scripts → three levels up). git's toplevel is the wrong
-# oracle here: it coincides with the workspace root only in a standalone
-# clone — inside the agents-private monorepo the toplevel is the monorepo
-# root, one level above public/open-knowledge. Marker validation fails
-# loud if the derived directory is not an OK workspace (e.g. the lib was
-# copied somewhere with a different shape). The walk is physical
-# (`cd -P`/`pwd -P`) so a symlinked invocation path — including macOS's
-# /var → /private/var TMPDIR — resolves to one canonical root.
resolve_repo_root() {
local lib_dir root
lib_dir="$(cd -P "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)"
diff --git a/packages/app/scripts/check-dev-harness-absent.mjs b/packages/app/scripts/check-dev-harness-absent.mjs
index 98a028860..13770f528 100644
--- a/packages/app/scripts/check-dev-harness-absent.mjs
+++ b/packages/app/scripts/check-dev-harness-absent.mjs
@@ -1,38 +1,12 @@
#!/usr/bin/env node
-/**
- * Production-artifact gate for the DEV-only ACP thread-injection harness.
- *
- * The harness is kept out of shipped code by two independent
- * `import.meta.env.DEV` guards, either of which is enough for the bundler to
- * fold the publish away. That gating lives in source, so it can regress
- * without a single suite going red: every unit, DOM, integration and browser
- * tier runs against source or a dev server, never against an emitted chunk.
- * This reads the emitted `dist/`, which is the bundle a user actually runs —
- * the CLI copies it to `cli/dist/public` and the desktop package ships that as
- * the renderer its packaged window loads. It is the only automatic check that
- * still discriminates once both guards are gone; the sentinel list in
- * `tests/perf/lib/bundle-check.ts` covers the same string but no tier collects
- * it, so it only discriminates when someone runs it by hand.
- *
- * Non-zero on a hit, on a missing build, and on a walk that found nothing to
- * read — an absence check that inspected no bytes is not a pass.
- */
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { argv, exit, stderr, stdout } from 'node:process';
import { fileURLToPath } from 'node:url';
-/**
- * The global the harness publishes itself on. A property name survives
- * minification verbatim, so it is the one part of the module guaranteed to
- * appear in an emitted chunk if any of it leaks. A DOM test pins that the
- * harness still uses this exact name, so a rename cannot leave this scanning
- * for a string nothing writes any more.
- */
export const DEV_HARNESS_SENTINEL = '__acpThreadHarness';
-/** Extensions Vite emits code or markup into. Fonts and images cannot carry it. */
const SCANNED_EXTENSIONS = ['.js', '.mjs', '.cjs', '.css', '.html', '.map'];
const APP_ROOT = join(fileURLToPath(import.meta.url), '..', '..');
@@ -107,7 +81,6 @@ function main() {
return 0;
}
-// Importers want the sentinel alone; only a direct invocation is the gate.
if (argv[1] !== undefined && resolve(argv[1]) === fileURLToPath(import.meta.url)) {
exit(main());
}
diff --git a/packages/app/scripts/copy-excalidraw-assets.mjs b/packages/app/scripts/copy-excalidraw-assets.mjs
index 5338dc3e7..3aa11e075 100644
--- a/packages/app/scripts/copy-excalidraw-assets.mjs
+++ b/packages/app/scripts/copy-excalidraw-assets.mjs
@@ -1,18 +1,4 @@
#!/usr/bin/env node
-/**
- * Copy Excalidraw's `dist/prod/fonts` tree into `public/excalidraw-assets/fonts`
- * so vite (dev) and the built dist both serve them from `/excalidraw-assets/`.
- *
- * The alternative — leaving `window.EXCALIDRAW_ASSET_PATH` unset — makes
- * Excalidraw fall back to its hardcoded `esm.sh` CDN URL for every font file
- * (see `createUrls` in `chunk-K2UTITRG.js`). That is a posture change for a
- * local-first editor: offline / air-gapped users silently render with system-
- * font fallbacks and every online use ships another vendor a request the app
- * did not previously make. Vendoring keeps the existing self-hosted stance.
- *
- * Idempotent — if the destination already has a marker matching the installed
- * Excalidraw version, do nothing. Cheap to run on every `predev`/`prebuild`.
- */
import {
cpSync,
existsSync,
@@ -28,11 +14,6 @@ import { fileURLToPath } from 'node:url';
const HERE = dirname(fileURLToPath(import.meta.url));
const APP_ROOT = join(HERE, '..');
-// Resolve the installed package root directly rather than via
-// `require.resolve('@excalidraw/excalidraw/package.json', ...)` — the package
-// declares an `exports` map that does not expose `./package.json`, so ESM
-// resolution rejects it (`ERR_PACKAGE_PATH_NOT_EXPORTED`). `realpathSync`
-// follows the pnpm workspace symlink to the actual store path.
const pkgDir = realpathSync(join(APP_ROOT, 'node_modules', '@excalidraw', 'excalidraw'));
const pkgPath = join(pkgDir, 'package.json');
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8'));
diff --git a/packages/app/scripts/i18n-compile-unless-skipped.sh b/packages/app/scripts/i18n-compile-unless-skipped.sh
index 8f8301d5e..ee8cfe933 100644
--- a/packages/app/scripts/i18n-compile-unless-skipped.sh
+++ b/packages/app/scripts/i18n-compile-unless-skipped.sh
@@ -1,13 +1,4 @@
#!/bin/sh
-# predev i18n gate: e2e fixture-spawned dev servers set
-# OK_TEST_SKIP_I18N_COMPILE=1 because N concurrent boots otherwise run
-# `lingui compile` + `biome format --write` against the SHARED
-# src/locales/*/messages.json — racing writers tear the JSON for any
-# concurrent reader (the corrupted-catalog playwright failure in CI run
-# 27182560489, reproduced locally by check:full:parallel booting the
-# e2e/visual/a11y projects together). The catalogs are committed and
-# drift-checked in CI, and the e2e warm-cache globalSetup boot (single,
-# uncontended, before any worker) compiles them once per run.
if [ -n "$OK_TEST_SKIP_I18N_COMPILE" ]; then
echo "[predev] i18n:compile skipped (OK_TEST_SKIP_I18N_COMPILE set)"
exit 0
diff --git a/packages/app/scripts/make-sweep-fixture.mjs b/packages/app/scripts/make-sweep-fixture.mjs
index 2bb5f1baa..0064f6bd8 100644
--- a/packages/app/scripts/make-sweep-fixture.mjs
+++ b/packages/app/scripts/make-sweep-fixture.mjs
@@ -1,72 +1,9 @@
#!/usr/bin/env node
-//
-// make-sweep-fixture.mjs — generate the content fixtures the sweep measurement
-// and manual QA run against.
-//
-// Why this exists
-// ---------------
-// `measure-sweep.sh` and the Fix-all QA scenarios both need a large corpus with
-// a known number of fixable lint findings. Those corpora used to be hand-built
-// outside the repo, which made `pnpm run measure:sweep` reproducible only on the
-// machine that happened to still have them. This script makes the fixture a
-// derived artifact: same seed in, same corpus out, on any machine.
-//
-// Output is a plain content directory — no `.ok/`, no git. The consumer copies
-// it to a scratch dir and points a server at the copy.
-//
-// Usage
-// -----
-// node scripts/make-sweep-fixture.mjs --preset realistic --out ~/ok-validation/realistic
-// node scripts/make-sweep-fixture.mjs --preset small --out ~/ok-validation/small
-// node scripts/make-sweep-fixture.mjs --preset subchunk --out ~/ok-validation/subchunk
-//
-// Flags
-// -----
-// --preset NAME realistic | small | subchunk (required unless --docs given)
-// --out DIR destination directory (required). Refuses a non-empty dir
-// unless --force.
-// --docs N override the preset's document count.
-// --seed N PRNG seed (default 7714) — same seed, same corpus.
-// --force replace a non-empty directory. Refuses unless the target
-// carries this script's `.ok-sweep-fixture` marker and has no
-// `.git` — a mistyped --out must not delete real work.
-// --quiet suppress the per-preset summary.
-//
-// Presets
-// -------
-// realistic 2,400 docs shaped to match the corpus the spec's §7 numbers were
-// measured on: ~2,341 docs carrying at least one finding, ~2,083 of
-// those carrying at least one FIXABLE finding, ~8,300 findings total.
-// small 36 docs, 6 of them fixable — the "small project" QA fixture.
-// subchunk 45 docs, all fixable, deliberately long so a sub-chunk sweep still
-// takes multiple seconds (the progress-visibility scenario).
-//
-// No wiki-links are emitted. The corpus is intentionally link-free: the doc-scoped
-// audit walks the backward link index, so a link-dense corpus measures the link
-// graph rather than the sweep.
-//
-// Calibration
-// -----------
-// `realistic` was tuned against a real `GET /api/audit` rather than by reasoning
-// about which rules fire. Measured at seed 7714:
-//
-// docs scanned 2400 · groups 2341 · fixable files 2083 · findings 8734 · 2.31 MB
-//
-// The first three are exact (they follow from role assignment) and are what drive
-// render cost; the finding total runs ~5% above the 8,304 of the corpus the spec's
-// §7 numbers came from, and the response size matches its stated 2.3 MB.
-//
-// Two calibration findings are baked into the emitters below, both of which had
-// silently inflated an earlier draft of this corpus:
-// - a frontmatter `title:` makes MD025 fire on EVERY document, so no document is
-// ever genuinely clean (see buildDoc);
-// - a heading block deeper than the document's h1 trips MD001 as collateral.
import { existsSync, mkdirSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
-// ── PRNG (mulberry32) — deterministic across platforms/Node versions ─────────
function makeRng(seed) {
let a = seed >>> 0;
return () => {
@@ -78,33 +15,16 @@ function makeRng(seed) {
};
}
-// ── Violation blocks ────────────────────────────────────────────────────────
-// Each block is written to yield exactly ONE finding, and is separated from its
-// neighbours by blank lines so heading/list spacing rules (MD022/MD031/MD032)
-// do not fire as collateral and inflate the count. The `fixable` flag records
-// whether markdownlint ships an autofix for that rule — the sweep only acts on
-// findings that carry one, so the two groups are what make a doc land in the
-// "fixable" bucket or merely the "has problems" bucket.
-
const FIXABLE_BLOCKS = [
- // MD009 — trailing spaces (one trailing space; br_spaces default of 2 makes a
- // 2-space line a legal hard break, so one space is the unambiguous violation).
(i) => `Paragraph ${i} carries a single trailing space. `,
- // MD010 — hard tabs.
(i) => `Paragraph ${i}\tcontains a hard tab character.`,
- // MD018 — no space after hash in an ATX heading. Level 2, so it does not trip
- // MD001 (heading-increment) against the document's h1.
(i) => `##Section ${i} heading without a space after the hash`,
- // MD019 — multiple spaces after hash. Level 2 for the same reason.
(i) => `## Section ${i} heading with two spaces after the hash`,
];
const NON_FIXABLE_BLOCKS = [
- // MD040 — fenced code block without a language.
(i) => `\`\`\`\nplain fenced block ${i} with no language\n\`\`\``,
- // MD042 — empty link.
(i) => `Paragraph ${i} links to [nothing here]().`,
- // MD045 — image with no alternate text.
(i) => `Paragraph ${i} shows ![](/assets/diagram-${i}.png) inline.`,
];
@@ -115,21 +35,8 @@ const FILLER = [
'The corpus needs bulk so the audit walk and the render both do real work.',
];
-/**
- * Build one document.
- *
- * @param index doc number, used for stable titles/paths
- * @param fixableCount how many fixable-rule blocks to inject
- * @param brokenCount how many non-fixable-rule blocks to inject
- * @param fillerParas how many clean paragraphs to pad with
- * @param rng seeded PRNG
- */
function buildDoc(index, fixableCount, brokenCount, fillerParas, rng) {
const lines = [];
- // No `title:` key: MD025's front_matter_title default treats a frontmatter
- // title as the document's top-level heading, which would make the `# ...`
- // below a second h1 and fire MD025 on EVERY doc — including the ones this
- // fixture needs to be genuinely clean.
lines.push('---');
lines.push(`index: ${index}`);
lines.push('---');
@@ -152,7 +59,6 @@ function buildDoc(index, fixableCount, brokenCount, fillerParas, rng) {
blocks.push(FILLER[(index + i) % FILLER.length]);
}
- // Shuffle so violations are not all clustered at the top of every doc.
for (let i = blocks.length - 1; i > 0; i--) {
const j = Math.floor(rng() * (i + 1));
[blocks[i], blocks[j]] = [blocks[j], blocks[i]];
@@ -163,19 +69,14 @@ function buildDoc(index, fixableCount, brokenCount, fillerParas, rng) {
lines.push('');
}
- // Trailing newline is present, so MD047 does not fire as an uncounted extra.
return lines.join('\n').replace(/\n+$/, '\n');
}
-// ── Presets ─────────────────────────────────────────────────────────────────
-// `fixablePerDoc` / `brokenPerDoc` are ranges [min, max] inclusive.
const PRESETS = {
realistic: {
docs: 2400,
- cleanDocs: 59, // 2400 - 2341 docs-with-problems
- fixableDocs: 2083, // of the 2,341 with problems, these carry an autofixable one
- // Calibrated against the real audit: each block yields ~1 finding, so
- // 2,083 × ~2.5 + 2,341 × ~1.5 lands near the 8,304 the spec's §7 corpus had.
+ cleanDocs: 59,
+ fixableDocs: 2083,
fixablePerDoc: [1, 4],
brokenPerDoc: [1, 2],
fillerParas: [3, 8],
@@ -198,16 +99,6 @@ const PRESETS = {
},
};
-// ── Arg parsing ─────────────────────────────────────────────────────────────
-
-/**
- * Reject a non-numeric or non-positive flag value instead of letting it become
- * NaN. `Number('abc')` is NaN, which silently degrades two different ways: as
- * `--docs` it makes the generation loop never iterate, so the script writes only
- * `.ok/config.yml` and still exits 0; as `--seed` it becomes 0 via `NaN >>> 0`,
- * quietly breaking the same-seed-same-corpus contract this file promises. The
- * shell siblings reject the same shape (`assert_numeric_flag` in _measure-lib.sh).
- */
function numericFlag(name, raw) {
const n = Number(raw);
if (!Number.isFinite(n) || n <= 0) {
@@ -255,11 +146,6 @@ if (!outDir) {
outDir = resolve(outDir.replace(/^~(?=$|\/)/, homedir()));
-// Marker this script drops into every corpus it generates. `--force` will only
-// delete a directory carrying it, so a mistyped --out (the parent
-// ~/ok-validation, or `.` from inside a checkout) fails loudly instead of
-// recursively destroying someone's work. The documented invocations re-target
-// directories this script itself produced, so they keep working unchanged.
const FIXTURE_MARKER = '.ok-sweep-fixture';
if (existsSync(outDir) && readdirSync(outDir).length > 0) {
@@ -291,15 +177,12 @@ writeFileSync(
'utf8',
);
-// ── Generate ────────────────────────────────────────────────────────────────
const cfg = { ...PRESETS[preset] };
if (docsOverride !== null) cfg.docs = docsOverride;
const rng = makeRng(seed);
const pickRange = ([lo, hi]) => lo + Math.floor(rng() * (hi - lo + 1));
-// Assign each doc a role up front, then shuffle so the roles are not contiguous
-// (a contiguous block of clean docs would sort to one end of the panel).
const roles = [];
for (let i = 0; i < cfg.docs; i++) {
if (i < cfg.cleanDocs) roles.push('clean');
@@ -311,8 +194,6 @@ for (let i = roles.length - 1; i > 0; i--) {
[roles[i], roles[j]] = [roles[j], roles[i]];
}
-// Spread docs over subdirectories so the tree resembles a real KB rather than
-// one flat directory of several thousand entries.
const PER_DIR = 50;
let written = 0;
@@ -331,10 +212,6 @@ for (let i = 0; i < cfg.docs; i++) {
written++;
}
-// A fixture is only usable if a server will actually lint it. `ok init` writes a
-// config whose keys are all commented out, and the markdownlint plugin defaults
-// to disabled — so a fixture without this file audits to zero findings and looks
-// like a passing sweep of nothing.
mkdirSync(join(outDir, '.ok'), { recursive: true });
writeFileSync(
join(outDir, '.ok', 'config.yml'),
diff --git a/packages/app/scripts/measure-fuzz.sh b/packages/app/scripts/measure-fuzz.sh
index 3e00aab2e..04356aea6 100755
--- a/packages/app/scripts/measure-fuzz.sh
+++ b/packages/app/scripts/measure-fuzz.sh
@@ -1,106 +1,86 @@
#!/usr/bin/env bash
-#
-# measure-fuzz.sh — ad-hoc sampling wrapper for bridge-convergence.fuzz.test.ts
-#
-# Purpose
-# -------
-# Sample the architectural CRDT residual rate across an arbitrary seed budget
-# and append a structured JSONL record to
-# specs/2026-04-16-bridge-correctness/evidence/residual-measurements.jsonl.
-# The git history of that file IS the trend record — no CI automation exists
-# to flag rate drift (accepted cost per NG6 in
-# specs/2026-04-19-ci-signal-quality/SPEC.md).
-#
-# Usage
-# -----
-# bash scripts/measure-fuzz.sh --seeds 1000 --context "pre-PR-218 baseline"
-# bash scripts/measure-fuzz.sh --seed-replay 1776559905522 --context "reproduce PR #206 failing seed"
-# pnpm run measure:fuzz --seeds 100 --context "investigate fuzz rate shift"
-#
-# Flags
-# -----
-# --seeds N Total seed budget (default: 1000 — matches AGENTS.md
-# §Measurement scripts canonical example and the
-# pre-merge bridge-touching-PR convention). Maps to
-# BRIDGE_FUZZ_SEEDS=N on the test invocation.
-# --seed-replay SEED Single-seed replay mode — invokes with
-# STRESS_FUZZ_SEED=SEED. Overrides --seeds.
-# --context "..." Free-text annotation for the JSONL record's context
-# field (required — this is what lets future readers
-# understand WHY a measurement was taken).
-#
-# Output
-# ------
-# On success:
-# - Appends one JSONL record to
-# specs/2026-04-16-bridge-correctness/evidence/residual-measurements.jsonl
-# - Prints human-readable summary to stdout (seed count, pass/fail, rate,
-# failing seeds with replay commands).
-# On test failure:
-# - Still appends JSONL record (failure is a valid measurement).
-# - Exit code matches the test runner (non-zero).
-# On a non-measurement (RESULT line never emitted, or a clean-sweep RESULT
-# contradicted by a non-zero runner exit):
-# - Appends NOTHING — a run whose evidence is missing or self-
-# contradictory is not a measurement. Exits non-zero with a diagnostic.
-#
-# JSONL schema (see specs/2026-04-16-bridge-correctness/evidence/residual-measurements-SCHEMA.md)
-# ---------------------------------------------------------------------------
-# {
-# "timestamp": "2026-04-19T14:23:15Z", // ISO 8601 UTC at run start
-# "commit": "abc1234", // short git SHA
-# "script": "deep-fuzz", // fixed for this script
-# "seedCount": 500,
-# "seedsFailed": 23,
-# "convergedLate": 0, // seeds that settled within tolerance late
-# "rate": 0.046, // seedsFailed / seedCount
-# "invokedBy": "ci-user", // $USER or CI identifier
-# "context": "pre-PR-218 baseline",
-# "failingSeeds":[1776559905522],
-# "durationMs": 8912000,
-# "host": "local-macos",
-# "nodeVersion": "v24.18.0",
-# "extra": { "outcome": "pass", // "pass" | "fail"
-# "failClasses": [] } // per-failing-seed oracle class
-# } // [{seed, class}, ...]
-#
-# outcome field (in extra)
-# ------------------------
-# "pass" — RESULT line emitted, seedsFailed == 0, runner exit 0
-# "fail" — RESULT line emitted, seedsFailed >= 1 (replayable seeds in
-# failingSeeds array)
-# A run whose RESULT line never appeared (setup failure, OOM, worker
-# death) — or whose clean-sweep RESULT is contradicted by a non-zero
-# runner exit — aborts without appending. Appended records carry only
-# "pass" | "fail".
-#
-# Query patterns (same as script header for discoverability via `head`)
-# ---------------------------------------------------------------------
-# # 7-day rolling average rate across all runs:
-# jq -s 'sort_by(.timestamp) | map(select(.timestamp > (now - 7*86400 | todate))) | [.[].rate] | add/length' \
-# specs/2026-04-16-bridge-correctness/evidence/residual-measurements.jsonl
-#
-# # Recent spikes (>5% rate):
-# jq 'select(.rate > 0.05)' specs/2026-04-16-bridge-correctness/evidence/residual-measurements.jsonl
-#
-# # Summary by script:
-# jq -s 'group_by(.script) | map({script: .[0].script, runs: length, avgRate: (map(.rate) | add/length)})' \
-# specs/2026-04-16-bridge-correctness/evidence/residual-measurements.jsonl
set -euo pipefail
-# Shared helpers — keeps host detection, epoch-ms resolution, JSONL
-# append serialization, and numeric-flag validation in one place. See
-# `_measure-lib.sh` for each function's contract.
-# shellcheck source=./_measure-lib.sh
source "$(dirname "${BASH_SOURCE[0]}")/_measure-lib.sh"
-# ── Defaults ───────────────────────────────────────────────────────────────
+usage() {
+ cat <<'EOF'
+Usage: bash scripts/measure-fuzz.sh --context "<why>" [options]
+
+Ad-hoc sampling wrapper for tests/stress/bridge-convergence.fuzz.test.ts. Samples
+the architectural CRDT residual rate across a seed budget and appends one JSONL
+record to specs/2026-04-16-bridge-correctness/evidence/residual-measurements.jsonl.
+The git history of that file IS the trend record — no CI automation flags rate
+drift (accepted cost per NG6 in specs/2026-04-19-ci-signal-quality/SPEC.md).
+
+Every specs/ path in this message lives in Inkeep's internal tree and is absent
+from the open-source repository. The script creates the evidence directory it
+writes to, so a clone without them still measures; only the schema notes and the
+trend history are unavailable.
+
+Required:
+ --context "..." Free-text annotation for the record's context field. This
+ is what lets a future reader understand WHY a measurement
+ was taken.
+
+Optional:
+ --seeds N Total seed budget (default: 1000). Sets BRIDGE_FUZZ_SEEDS=N
+ on the test invocation.
+ --seed-replay SEED Single-seed replay. Sets STRESS_FUZZ_SEED=SEED and unsets
+ BRIDGE_FUZZ_SEEDS, so it overrides --seeds.
+ -h, --help Show this message.
+
+Examples:
+ bash scripts/measure-fuzz.sh --seeds 1000 --context "pre-PR-218 baseline"
+ bash scripts/measure-fuzz.sh --seed-replay 1776559905522 --context "reproduce PR #206 failing seed"
+ pnpm run measure:fuzz --seeds 100 --context "investigate fuzz rate shift"
+
+Output:
+ Appends one record (script "deep-fuzz") to the evidence log, then prints a
+ summary — context, commit, host, outcome, seedCount, seedsFailed, rate,
+ durationMs, logFile — plus a replay command per failing seed. A test failure is
+ still a measurement: the record is appended and the script exits with the
+ runner's code.
+ A run that measured nothing appends NOTHING and leaves the trend log untouched:
+ the RESULT line never appeared, or a clean-sweep RESULT was contradicted by a
+ non-zero runner exit.
+
+Record shape:
+ Field-by-field contract in
+ specs/2026-04-16-bridge-correctness/evidence/residual-measurements-SCHEMA.md.
+ extra.outcome is "pass" (RESULT emitted, seedsFailed 0, runner exit 0) or
+ "fail" (RESULT emitted, seedsFailed >= 1); nothing else is ever appended.
+ extra.failClasses carries one {seed, class} entry per failing seed.
+
+Exit codes:
+ 0 measurement appended, every seed passed
+ 1 nothing measured: no RESULT line on a run the runner exited 0
+ 2 usage error: unknown flag, missing --context, non-integer flag value
+ 3 jq is not installed
+ 4 the derived workspace root lacks its packages/app + package.json markers
+ 5 neither date path produced a numeric epoch
+ 6 the JSONL append could not take its lock; the record was NOT committed
+ * otherwise the test runner's exit code: seeds failed (record appended), the
+ harness crashed before RESULT, or RESULT was contradicted post-hoc (both
+ append nothing)
+
+Query patterns over the evidence log:
+ LOG=specs/2026-04-16-bridge-correctness/evidence/residual-measurements.jsonl
+
+ 7-day rolling average rate:
+ jq -s 'sort_by(.timestamp) | map(select(.timestamp > (now - 7*86400 | todate))) | [.[].rate] | add/length' "$LOG"
+ Runs above a 5% rate:
+ jq 'select(.rate > 0.05)' "$LOG"
+ Summary by script:
+ jq -s 'group_by(.script) | map({script: .[0].script, runs: length, avgRate: (map(.rate) | add/length)})' "$LOG"
+EOF
+}
+
SEEDS=1000
SEED_REPLAY=""
CONTEXT=""
-# ── Arg parsing ────────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
case "$1" in
--seeds)
@@ -110,11 +90,7 @@ while [[ $# -gt 0 ]]; do
--context)
CONTEXT="$2"; shift 2 ;;
-h|--help)
- # Print the full header comment block — from line 1 through the
- # first blank-comment-line sentinel `^$` after the `Query patterns`
- # heading. Using a sentinel (rather than a fixed line range) keeps
- # --help accurate when the header grows.
- sed -n '1,/^$/p' "$0"; exit 0 ;;
+ usage; exit 0 ;;
*)
echo "error: unknown flag: $1" >&2
echo "run with --help for usage" >&2
@@ -128,15 +104,11 @@ if [[ -z "$CONTEXT" ]]; then
exit 2
fi
-# Validate numeric inputs via shared helper. Non-numeric inputs would
-# export a non-numeric env to the child test run and silently coerce
-# to NaN→1 at the PRNG layer.
assert_numeric_flag "--seeds" "$SEEDS"
if [[ -n "$SEED_REPLAY" ]]; then
assert_numeric_flag "--seed-replay" "$SEED_REPLAY" --signed
fi
-# ── Environment ────────────────────────────────────────────────────────────
require_jq
REPO_ROOT="$(resolve_repo_root)"
@@ -147,7 +119,6 @@ TEST_FILE="tests/stress/bridge-convergence.fuzz.test.ts"
mkdir -p "$LOG_DIR"
-# ── Compose test invocation ────────────────────────────────────────────────
if [[ -n "$SEED_REPLAY" ]]; then
export STRESS_FUZZ_SEED="$SEED_REPLAY"
unset BRIDGE_FUZZ_SEEDS
@@ -158,7 +129,6 @@ else
echo "[measure-fuzz] sampling mode: BRIDGE_FUZZ_SEEDS=$SEEDS"
fi
-# ── Capture metadata at run start ──────────────────────────────────────────
TIMESTAMP="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
COMMIT="$(git rev-parse --short HEAD)"
INVOKED_BY="${USER:-unknown}"
@@ -166,7 +136,6 @@ NODE_VERSION="$(node --version 2>/dev/null || echo unknown)"
HOST="$(detect_host)"
-# ── Run test, capture output ───────────────────────────────────────────────
OUT_FILE="$(mktemp -t measure-fuzz-XXXXXX)"
trap 'rm -f "$OUT_FILE"' EXIT
@@ -174,74 +143,25 @@ echo "[measure-fuzz] running $TEST_FILE ..."
START_MS="$(epoch_ms)"
-# We want the test to run but don't want its exit code to kill the script —
-# a test failure is a valid measurement; the classifier below decides what,
-# if anything, gets recorded.
TEST_EXIT=0
(
- # Explicit exit: errexit is suppressed inside a piped compound, so a bare
- # failed cd would let the test run from the wrong cwd.
cd "$APP_DIR" || exit 1
- # No --conditions flag: packages/app/vitest.config.ts spreads
- # test-support/vitest.base.ts, which pins the `development` export condition
- # in both resolve and ssr.resolve. That pin is what resolves workspace deps
- # from source exports instead of an unbuilt dist/ (the fresh-worktree
- # state) — without it the run dies on missing build artifacts.
pnpm exec vitest run "$TEST_FILE" 2>&1
) | tee "$OUT_FILE" || TEST_EXIT=$?
END_MS="$(epoch_ms)"
DURATION_MS=$(( END_MS - START_MS ))
-# ── Parse results ──────────────────────────────────────────────────────────
-# Preferred signal: the machine-parseable RESULT line emitted by
-# `bridge-convergence.fuzz.test.ts`'s after-all hook:
-# [fuzz] RESULT seeds=<n> passed=<n> failed=<n> failingSeeds=[<s1>,<s2>,...]
-# Written via `process.stdout.write`, stdout-only. Parsing this decouples
-# the script from the runner's human-readable summary format (which is
-# fragile to output drift and stderr conflation via 2>&1). Mirrors
-# `measure-stress.sh`'s RESULT-line strategy for sibling-script symmetry.
-#
-# When RESULT is missing the test crashed before the after-all hook could
-# run — the classifier below aborts the script without appending.
-
-# Optional appended field (newer harness): converged-late count — seeds that
-# exhausted the convergence budget but settled within tolerance. Counted as
-# passes by the harness; recorded here as a perf signal.
-# (`.*` not `[^\n]*`: grep is line-oriented so `.` cannot cross a newline,
-# and in POSIX ERE `[^\n]` is a bracket expression excluding literal `\`/`n`
-# — it stops at the `n` in `failingSeeds` and the anchor never reaches the
-# appended fields on GNU grep.)
CONVERGED_LATE="$(grep -oE '^\[fuzz\] RESULT .*convergedLate=[0-9]+' "$OUT_FILE" | grep -oE 'convergedLate=[0-9]+' | tail -1 | cut -d= -f2 || true)"
CONVERGED_LATE="${CONVERGED_LATE:-0}"
-# Optional appended field (newer harness): per-failing-seed oracle class —
-# `failClasses=[<seed>:<class>,...]` where class is one of the harness's
-# failure classes (content-preservation | oracle-e | convergence-stalled
-# | bridge-invariant | byte-budget | origin | setup | other). Parsed into
-# extra.failClasses so trend-record readers can attribute each failure to an
-# oracle without a manual seed replay. Empty (or absent, on an older harness)
-# parses to [].
FAIL_CLASSES_RAW="$(grep -oE '^\[fuzz\] RESULT .*failClasses=\[[0-9a-z:,-]*\]' "$OUT_FILE" | grep -oE 'failClasses=\[[0-9a-z:,-]*\]' | tail -1 | sed -E 's/^failClasses=\[//; s/\]$//' || true)"
FAIL_CLASSES_JSON="$(jq -c -n --arg raw "$FAIL_CLASSES_RAW" \
'[ $raw | select(length > 0) | split(",")[] | split(":") | { seed: (.[0] | tonumber), class: (.[1] // "unknown") } ]')"
FUZZ_RESULT_LINE="$(grep -oE '^\[fuzz\] RESULT seeds=[0-9]+ passed=[0-9]+ failed=[0-9]+ failingSeeds=\[[0-9,]*\]' "$OUT_FILE" | tail -1 || true)"
-# Outcome classifier (parallels measure-stress.sh's pass/fail):
-# "pass" — RESULT line printed, failed=0, test exit 0
-# "fail" — RESULT line printed, failed>=1 (real seed failures with
-# replayable seeds in failingSeeds array)
-# anything else — not a measurement: no RESULT line (the harness
-# crashed before afterAll could emit — setup failure, OOM,
-# worker death), or a clean-sweep RESULT contradicted by a
-# non-zero exit (post-RESULT teardown failure, sibling test).
-# Abort without appending so the trend log stays a record of
-# true measurements.
if [[ -n "$FUZZ_RESULT_LINE" ]]; then
- # Parse each field by name (not by position) via separate grep passes —
- # robust against future field reorderings (within reason — extending the
- # format still requires updating this regex, but position changes don't).
RESULT_SEEDS="$(echo "$FUZZ_RESULT_LINE" | grep -oE 'seeds=[0-9]+' | awk -F= '{print $2}')"
RESULT_PASSED="$(echo "$FUZZ_RESULT_LINE" | grep -oE 'passed=[0-9]+' | awk -F= '{print $2}')"
RESULT_FAILED="$(echo "$FUZZ_RESULT_LINE" | grep -oE 'failed=[0-9]+' | awk -F= '{print $2}')"
@@ -281,25 +201,15 @@ else
exit 1
fi
-# rate with 4-digit precision. Use awk for portability; Bun/bash arithmetic
-# doesn't do floats. Division-by-zero guard. `LC_ALL=C` is load-bearing —
-# without it, awk's `%.4f` honors the current locale's LC_NUMERIC and emits
-# `0,0460` on e.g. de_DE.UTF-8, producing invalid JSON when jq reads the
-# record back. Force C locale for numeric formatting only.
if [[ "$SEED_COUNT" == "0" ]]; then
RATE="0.0000"
else
RATE="$(LC_ALL=C awk -v a="$SEEDS_FAILED" -v b="$SEED_COUNT" 'BEGIN{ printf "%.4f", a/b }')"
fi
-# ── Compose extra (script-specific fields) ─────────────────────────────────
-# `outcome` parallels measure-stress.sh so `jq 'select(.extra.outcome=="fail")'`
-# works uniformly across both producers. Per SCHEMA.md, extending `extra`
-# does not require a schema version bump — readers ignore unknown keys.
EXTRA_JSON="$(jq -c -n --arg outcome "$OUTCOME" --argjson failClasses "$FAIL_CLASSES_JSON" \
'{ outcome: $outcome, failClasses: $failClasses }')"
-# ── Compose JSONL record ───────────────────────────────────────────────────
RECORD="$(jq -c -n \
--arg timestamp "$TIMESTAMP" \
--arg commit "$COMMIT" \
@@ -334,7 +244,6 @@ RECORD="$(jq -c -n \
append_jsonl_atomic "$LOG_FILE" "$RECORD"
-# ── Summary ────────────────────────────────────────────────────────────────
echo ""
echo "──────── measure-fuzz summary ────────"
echo " context: $CONTEXT"
@@ -349,8 +258,6 @@ echo " logFile: $LOG_FILE"
echo ""
if [[ "$SEEDS_FAILED" != "0" ]]; then
- # Derive replay commands from FAILING_SEEDS_JSON (authoritative) — always
- # populated from the parsed RESULT line, the only seed source.
FAILING_SEEDS_LIST="$(jq -r '.[]' <<< "$FAILING_SEEDS_JSON" 2>/dev/null || true)"
if [[ -n "$FAILING_SEEDS_LIST" ]]; then
echo "──────── failing seed replay commands ────────"
@@ -362,5 +269,4 @@ if [[ "$SEEDS_FAILED" != "0" ]]; then
fi
fi
-# Propagate test exit code so CI / users see failure signal.
exit "$TEST_EXIT"
diff --git a/packages/app/scripts/measure-stress.sh b/packages/app/scripts/measure-stress.sh
index b619e92aa..63bb43021 100755
--- a/packages/app/scripts/measure-stress.sh
+++ b/packages/app/scripts/measure-stress.sh
@@ -1,67 +1,83 @@
#!/usr/bin/env bash
-#
-# measure-stress.sh — ad-hoc sampling wrapper for server-authoritative-stress.test.ts
-#
-# Purpose
-# -------
-# Sample the architectural CRDT residual in the 5-client × 30s stress load
-# scenario, with optional seed replay for triaging known-bad seeds, and append
-# a structured JSONL record to
-# specs/2026-04-16-bridge-correctness/evidence/residual-measurements.jsonl.
-#
-# Unlike measure-fuzz.sh (which sweeps N seeds in one run), this script is
-# typically run one seed at a time — the underlying test is a 30-second
-# multi-client convergence scenario, not a seeded-PBT loop. Seed replay is
-# powered by the STRESS_SEED env override shipped in PR #212.
-#
-# Usage
-# -----
-# bash scripts/measure-stress.sh --seed 42 --context "pre-PR-218 baseline"
-# bash scripts/measure-stress.sh --context "investigate 2026-04 rate shift"
-# pnpm run measure:stress --seed 1776381158793 --context "reproduce CI flake"
-#
-# Flags
-# -----
-# --seed N STRESS_SEED override. Default: omitted (test uses its
-# internal Date.now() seed, recorded in the JSONL).
-# --context "..." Free-text annotation for the JSONL record's context
-# field (required).
-#
-# The underlying test's run duration is hard-coded to 30s internally. There is
-# no run-time override flag for duration — the script enforces no knob that
-# the test does not honor, per feedback-driven principle "no config that lies."
-# If a future test parameterizes duration, add a flag here that sets the
-# corresponding env var.
-#
-# Output
-# ------
-# Same JSONL schema as measure-fuzz.sh, with these differences:
-# - script: "deep-stress"
-# - seedCount: 1 (one run per invocation)
-# - seedsFailed: 0 on pass, 1 on fail
-# - outcome: "pass" | "fail" (inside extra)
-# - failingSeeds: [<seed>] on a real test failure where the seed banner
-# was captured; [] on pass
-# - extra: { stressSeed: <seed>, outcome: "pass"|"fail" }
-#
-# A run that measured nothing appends nothing: harness crashed before its
-# banner, RESULT line missing on a zero exit, RESULT-pass contradicted by
-# a non-zero exit, or no attributable seed — each aborts with a diagnostic
-# and a non-zero exit, leaving the log untouched.
-#
-# See measure-fuzz.sh for the full schema + query pattern examples.
set -euo pipefail
-# Shared helpers — see measure-fuzz.sh for the rationale.
-# shellcheck source=./_measure-lib.sh
source "$(dirname "${BASH_SOURCE[0]}")/_measure-lib.sh"
-# ── Defaults ───────────────────────────────────────────────────────────────
+usage() {
+ cat <<'EOF'
+Usage: bash scripts/measure-stress.sh --context "<why>" [--seed N]
+
+Ad-hoc sampling wrapper for tests/stress/server-authoritative-stress.test.ts.
+Samples the architectural CRDT residual in the 5-client × 30s stress-load
+scenario, with optional seed replay for triaging a known-bad seed, and appends
+one JSONL record to
+specs/2026-04-16-bridge-correctness/evidence/residual-measurements.jsonl.
+
+Every specs/ path in this message lives in Inkeep's internal tree and is absent
+from the open-source repository. The script creates the evidence directory it
+writes to, so a clone without them still measures; only the schema notes and the
+trend history are unavailable.
+
+Unlike measure-fuzz.sh, which sweeps N seeds in one run, this script measures one
+seed per invocation — the underlying test is a 30-second multi-client
+convergence scenario, not a seeded-PBT loop.
+
+Required:
+ --context "..." Free-text annotation for the record's context field.
+
+Optional:
+ --seed N STRESS_SEED override. Default: omitted, so the test picks its
+ own Date.now() seed; whichever seed ran is recorded.
+ -h, --help Show this message.
+
+The test's run duration is hard-coded to 30s internally with no env knob, so this
+script deliberately exposes no --duration flag rather than accepting one it
+cannot honor. If the test ever parameterizes duration, add the flag here and in
+the test body together.
+
+Examples:
+ bash scripts/measure-stress.sh --seed 42 --context "pre-PR-218 baseline"
+ bash scripts/measure-stress.sh --context "investigate a residual rate shift"
+ pnpm run measure:stress --seed 1776381158793 --context "reproduce a CI flake"
+
+Output:
+ Appends one record, then prints a summary — context, commit, host, stressSeed,
+ outcome, durationMs, logFile — plus a replay command on failure. The record
+ uses the measure-fuzz schema with these differences:
+ script: "deep-stress"
+ seedCount: 1
+ seedsFailed: 0 on pass, 1 on fail
+ rate: 0.0000 on pass, 1.0000 on fail
+ failingSeeds: [<seed>] on fail, [] on pass
+ extra: { stressSeed, outcome }, with no convergedLate and no failClasses
+ A non-zero exit with an attributable seed records outcome "fail". The seed is
+ attributable from --seed alone, so under an explicit --seed even a harness
+ crash records a fail rather than aborting.
+ A run that measured nothing appends NOTHING: the RESULT line is missing on a
+ zero exit, a RESULT-pass is contradicted by a non-zero exit, or no seed could
+ be attributed at all (no banner, no RESULT seed, no --seed).
+ Full schema + query patterns: `bash scripts/measure-fuzz.sh --help` and
+ specs/2026-04-16-bridge-correctness/evidence/residual-measurements-SCHEMA.md.
+
+Exit codes:
+ 0 measurement appended, the stress run passed
+ 1 nothing measured: no RESULT line on a run the runner exited 0, or an outcome
+ was classified but no seed could be attributed
+ 2 usage error: unknown flag, missing --context, non-integer --seed
+ 3 jq is not installed
+ 4 the derived workspace root lacks its packages/app + package.json markers
+ 5 neither date path produced a numeric epoch
+ 6 the JSONL append could not take its lock; the record was NOT committed
+ * otherwise the test runner's exit code: a stress failure or a crash with an
+ attributable seed (record appended), or a RESULT-pass contradicted by a
+ non-zero exit / a crash with no attributable seed (nothing appended)
+EOF
+}
+
SEED=""
CONTEXT=""
-# ── Arg parsing ────────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
case "$1" in
--seed)
@@ -69,10 +85,7 @@ while [[ $# -gt 0 ]]; do
--context)
CONTEXT="$2"; shift 2 ;;
-h|--help)
- # Print the full header comment block up to the first blank-comment-
- # line sentinel `^$`. Sentinel-based extraction so --help stays
- # accurate as the header grows.
- sed -n '1,/^$/p' "$0"; exit 0 ;;
+ usage; exit 0 ;;
*)
echo "error: unknown flag: $1" >&2
echo "run with --help for usage" >&2
@@ -86,12 +99,10 @@ if [[ -z "$CONTEXT" ]]; then
exit 2
fi
-# Validate --seed via shared helper (see _measure-lib.sh).
if [[ -n "$SEED" ]]; then
assert_numeric_flag "--seed" "$SEED" --signed
fi
-# ── Environment ────────────────────────────────────────────────────────────
require_jq
REPO_ROOT="$(resolve_repo_root)"
@@ -102,7 +113,6 @@ TEST_FILE="tests/stress/server-authoritative-stress.test.ts"
mkdir -p "$LOG_DIR"
-# ── Compose test invocation ────────────────────────────────────────────────
if [[ -n "$SEED" ]]; then
export STRESS_SEED="$SEED"
echo "[measure-stress] seed-replay mode: STRESS_SEED=$SEED"
@@ -111,7 +121,6 @@ else
echo "[measure-stress] fresh seed (test picks via Date.now())"
fi
-# ── Capture metadata at run start ──────────────────────────────────────────
TIMESTAMP="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
COMMIT="$(git rev-parse --short HEAD)"
INVOKED_BY="${USER:-unknown}"
@@ -119,7 +128,6 @@ NODE_VERSION="$(node --version 2>/dev/null || echo unknown)"
HOST="$(detect_host)"
-# ── Run test, capture output ───────────────────────────────────────────────
OUT_FILE="$(mktemp -t measure-stress-XXXXXX)"
trap 'rm -f "$OUT_FILE"' EXIT
@@ -129,42 +137,15 @@ START_MS="$(epoch_ms)"
TEST_EXIT=0
(
- # Explicit exit: errexit is suppressed inside a piped compound, so a bare
- # failed cd would let the test run from the wrong cwd.
cd "$APP_DIR" || exit 1
- # No --conditions flag: packages/app/vitest.config.ts spreads
- # test-support/vitest.base.ts, which pins the `development` export condition
- # in both resolve and ssr.resolve. That pin is what resolves workspace deps
- # from source exports instead of an unbuilt dist/ (the fresh-worktree
- # state) — without it the run dies on missing build artifacts.
pnpm exec vitest run "$TEST_FILE" 2>&1
) | tee "$OUT_FILE" || TEST_EXIT=$?
END_MS="$(epoch_ms)"
DURATION_MS=$(( END_MS - START_MS ))
-# ── Parse results ──────────────────────────────────────────────────────────
-# Two stable signals the stress test emits:
-#
-# (1) Startup banner — printed BEFORE any setup work in the test body:
-# [server-authoritative stress] seed=<n>
-# [server-authoritative stress] seed=<n> (replay)
-# Emitted before the loop, so present unless a crash precedes the
-# banner. Primary source for stressSeed.
-#
-# (2) Machine-parseable result line — printed AFTER all assertions pass:
-# [stress] RESULT outcome=pass seed=<n> edits=<n> convergenceMs=<n>
-# Written via `process.stdout.write`, stdout-only (never stderr), so
-# the grep below is unambiguous and insensitive to runner output drift.
-#
-# Parsing the test's own structured lines — not the runner's human summary —
-# decouples the script from the runner's output format.
-
ACTUAL_SEED_BANNER="$(grep -oE '\[server-authoritative stress\] seed=[0-9]+' "$OUT_FILE" \
| awk -F= '{print $2}' | head -1 || true)"
-# Secondary source: the RESULT line carries the same seed. It is emitted only on
-# a pass, so it cannot replace the banner for crash runs, but it keeps a passing
-# run attributable if the banner is ever lost again.
ACTUAL_SEED_RESULT="$(grep -oE '^\[stress\] RESULT .*seed=[0-9]+' "$OUT_FILE" \
| grep -oE 'seed=[0-9]+' | awk -F= '{print $2}' | head -1 || true)"
if [[ -n "$ACTUAL_SEED_BANNER" ]]; then
@@ -177,27 +158,9 @@ else
ACTUAL_SEED=""
fi
-# Machine-parseable result line — only emitted on a successful run (after
-# all assertions pass). Absence = test failed or crashed before reaching
-# the summary.
HAS_RESULT_PASS="$(grep -cE '^\[stress\] RESULT outcome=pass' "$OUT_FILE" || true)"
HAS_RESULT_PASS="${HAS_RESULT_PASS:-0}"
-# Classify outcome:
-# "pass" — test exit 0 AND the RESULT line printed
-# "fail" — test exit != 0 AND the seed banner printed AND no RESULT
-# line (real test failure with a known seed for replay)
-# anything else — not a measurement. Either the harness never reached
-# its seed banner (setup failure, OOM, pre-banner crash), or
-# the evidence is contradictory: exit 0 without a RESULT line
-# (no tests matched, or the RESULT emission moved or its
-# format drifted), or a RESULT line with a non-zero exit
-# (post-test teardown failure). Abort without appending so
-# the trend log stays a record of true measurements.
-#
-# Note: on a successful run, exit code alone is not sufficient — a runner
-# test that ran but reported an assertion failure still has exit != 0.
-# A pass requires both the RESULT line AND exit 0; they corroborate.
SEED_COUNT=1
if [[ "$TEST_EXIT" -eq 0 && "$HAS_RESULT_PASS" -ge 1 ]]; then
OUTCOME="pass"
@@ -228,11 +191,6 @@ else
exit 1
fi
-# ── Compose extra (script-specific fields) ─────────────────────────────────
-# SCHEMA.md promises a replayable stressSeed in every appended record. A
-# classified run can reach this point seedless only when the banner regex
-# matched nothing and no --seed pinned a value (banner format drift) — that
-# run is unattributable, so abort rather than record a null seed.
if [[ -z "$ACTUAL_SEED" ]]; then
echo "" >&2
echo "error: outcome \"$OUTCOME\" but no seed was captured — the seed banner regex" >&2
@@ -243,7 +201,6 @@ fi
EXTRA_JSON="$(jq -c -n --argjson stressSeed "$ACTUAL_SEED" --arg outcome "$OUTCOME" \
'{ stressSeed: $stressSeed, outcome: $outcome }')"
-# ── Compose JSONL record ───────────────────────────────────────────────────
RECORD="$(jq -c -n \
--arg timestamp "$TIMESTAMP" \
--arg commit "$COMMIT" \
@@ -276,7 +233,6 @@ RECORD="$(jq -c -n \
append_jsonl_atomic "$LOG_FILE" "$RECORD"
-# ── Summary ────────────────────────────────────────────────────────────────
echo ""
echo "──────── measure-stress summary ────────"
echo " context: $CONTEXT"
diff --git a/packages/app/scripts/measure-sweep.sh b/packages/app/scripts/measure-sweep.sh
index b9c32826c..1faed9e7b 100755
--- a/packages/app/scripts/measure-sweep.sh
+++ b/packages/app/scripts/measure-sweep.sh
@@ -1,79 +1,88 @@
#!/usr/bin/env bash
-#
-# measure-sweep.sh — ad-hoc measurement of the project-scope Fix-all sweep.
-#
-# Purpose
-# -------
-# Drive one full project-scope "Fix all" sweep through the real Problems panel
-# against a prod-fidelity server, and report the five numbers the shipping
-# configuration's success metrics turn on: panel-open time, full-sweep
-# duration, successful-fix count, capacity-refusal count, and main-thread
-# blocked time. Each run appends a structured JSONL record to
-# specs/2026-07-30-fix-all-sweep-performance/evidence/sweep-measurements.jsonl —
-# the git history of that file IS the trend record, exactly like the sibling
-# measure:fuzz / measure:stress producers. Explicitly NOT a CI job: a sweep
-# takes tens of seconds and needs a large on-disk fixture.
-#
-# The measured configuration is the shipping stack (R1 collapse + R2 chunk +
-# R3 pace/retry) as built from the current worktree; the record labels it so a
-# reader never confuses it with the spec's earlier single-lever numbers.
-#
-# Usage
-# -----
-# bash scripts/measure-sweep.sh --context "shipping-config baseline"
-# bash scripts/measure-sweep.sh --context "smoke" --fixture ~/ok-validation/small
-# pnpm run measure:sweep --context "re-measure after retune"
-#
-# Flags
-# -----
-# --context "..." Free-text annotation for the JSONL record (required).
-# --fixture DIR Content fixture to sweep. Default
-# ~/ok-validation/realistic (2,400 docs). NEVER mutated
-# — copied to a scratch dir first.
-# --sweep-timeout MS Max wait for the sweep to finish. Default 300000.
-# --skip-build Reuse the current packages/cli + packages/app dist.
-# --keep-scratch Leave the scratch fixture copy on disk (debugging).
-#
-# Output
-# ------
-# On a completed measurement:
-# - Appends one JSONL record to the evidence log (script "sweep-fixall").
-# - Prints a human summary comparing each metric to its §7 target; any MISS
-# is surfaced prominently rather than silently recorded.
-# A run whose browser measurement did not produce a SWEEP_RESULT line appends
-# NOTHING and exits non-zero — a run with no evidence is not a measurement.
-#
-# JSONL schema
-# ------------
-# {
-# "timestamp": "2026-07-31T04:20:00Z", // ISO 8601 UTC at run start
-# "commit": "abc1234",
-# "script": "sweep-fixall",
-# "config": "R1+R2+R3 (shipping)",
-# "fixture": "realistic",
-# "context": "shipping-config baseline",
-# "metrics": { ...the browser SWEEP_RESULT object... },
-# "targets": { panelOpenWarmMs, sweepDurationMs, mainThreadBlockedPct, filesFailedTerminal },
-# "targetMisses":[ { name, target, value, cmp } ],
-# "durationMs": 74210,
-# "host": "local-macos",
-# "invokedBy": "user",
-# "nodeVersion":"v24.x"
-# }
set -euo pipefail
-# shellcheck source=./_measure-lib.sh
source "$(dirname "${BASH_SOURCE[0]}")/_measure-lib.sh"
-# ── Defaults ───────────────────────────────────────────────────────────────
+usage() {
+ cat <<'EOF'
+Usage: bash scripts/measure-sweep.sh --context "<why>" [options]
+
+Ad-hoc measurement of the project-scope Fix-all sweep. Drives one full sweep
+through the real Problems panel against a prod-fidelity server and reports the
+five numbers the shipping configuration's success metrics turn on: panel-open
+time, full-sweep duration, successful-fix count, capacity-refusal count, and
+main-thread blocked time. Each completed run appends one JSONL record to
+specs/2026-07-30-fix-all-sweep-performance/evidence/sweep-measurements.jsonl —
+the git history of that file IS the trend record, exactly like the sibling
+measure:fuzz / measure:stress producers. Explicitly NOT a CI job: a sweep takes
+tens of seconds and needs a large on-disk fixture.
+
+Every specs/ path in this message lives in Inkeep's internal tree and is absent
+from the open-source repository. The script creates the evidence directory it
+writes to, so a clone without them still measures; only the schema notes and the
+trend history are unavailable.
+
+The measured configuration is the shipping stack (R1 collapse + R2 chunk + R3
+pace/retry) built from the current worktree; the record labels it
+"R1+R2+R3 (shipping)" so a reader never confuses it with the spec's earlier
+single-lever numbers.
+
+Required:
+ --context "..." Free-text annotation for the record's context field.
+
+Optional:
+ --fixture DIR Content fixture to sweep. Default ~/ok-validation/realistic
+ (2,400 docs — scripts/make-sweep-fixture.mjs --preset
+ realistic). NEVER mutated: rsync'd to a scratch dir first.
+ --sweep-timeout MS Max wait for the sweep to finish. Default 300000.
+ --skip-build Reuse the current packages/cli + packages/app dist.
+ --keep-scratch Leave the scratch fixture copy on disk (debugging).
+ -h, --help Show this message.
+
+Examples:
+ bash scripts/measure-sweep.sh --context "shipping-config baseline"
+ bash scripts/measure-sweep.sh --context "smoke" --fixture ~/ok-validation/small
+ pnpm run measure:sweep --context "re-measure after retune"
+
+Output:
+ Prints the measured metrics, then each target as ✓ pass or ⚠ MISS:
+ panelOpenWarmMs < 1000
+ sweepDurationMs < 90000
+ mainThreadBlockedPct < 5
+ filesFailedTerminal == 0
+ Misses are surfaced prominently and recorded in the record's targetMisses
+ array; they do not fail the run.
+ On a completed sweep, appends one record (script "sweep-fixall") carrying
+ timestamp, commit, script, config, fixture, context, metrics (the browser
+ SWEEP_RESULT object verbatim), targets, targetMisses, durationMs, host,
+ invokedBy, nodeVersion.
+ A run whose browser measurement emitted no parseable SWEEP_RESULT, and a run
+ whose sweep did not complete, both append NOTHING and exit non-zero — a run
+ with no evidence is not a measurement.
+
+Exit codes:
+ 0 sweep completed, record appended (target misses do NOT fail the run)
+ 2 usage error: unknown flag, missing --context, non-integer --sweep-timeout,
+ or --fixture directory not found
+ 3 jq is not installed, or tsx is missing from node_modules/.bin
+ 4 the workspace-root markers are missing, the build failed, or the CLI binary
+ is absent after the build
+ 5 no markdown docs under the copied fixture, or no numeric epoch was available
+ 6 the server exited before binding a port or never bound one within 60s, or
+ the JSONL append could not take its lock
+ 7 the browser measurement produced no parseable SWEEP_RESULT
+ 8 the sweep did not finish within --sweep-timeout; the printed numbers are
+ partial
+EOF
+}
+
CONTEXT=""
FIXTURE="$HOME/ok-validation/realistic"
SWEEP_TIMEOUT_MS=300000
SKIP_BUILD=0
KEEP_SCRATCH=0
-# ── Arg parsing ────────────────────────────────────────────────────────────
while [[ $# -gt 0 ]]; do
case "$1" in
--context) CONTEXT="$2"; shift 2 ;;
@@ -82,7 +91,7 @@ while [[ $# -gt 0 ]]; do
--skip-build) SKIP_BUILD=1; shift ;;
--keep-scratch) KEEP_SCRATCH=1; shift ;;
-h|--help)
- sed -n '1,/^$/p' "$0"; exit 0 ;;
+ usage; exit 0 ;;
*)
echo "error: unknown flag: $1" >&2
echo "run with --help for usage" >&2
@@ -103,7 +112,6 @@ if [[ ! -d "$FIXTURE" ]]; then
exit 2
fi
-# ── Environment ────────────────────────────────────────────────────────────
require_jq
REPO_ROOT="$(resolve_repo_root)"
CLI_BIN="$REPO_ROOT/packages/cli/dist/cli.mjs"
@@ -117,7 +125,6 @@ if [[ ! -f "$TSX_BIN" ]]; then
exit 3
fi
-# ── 1. Build (turbo-cached; no-op when clean) ──────────────────────────────
if [[ "$SKIP_BUILD" -eq 0 ]]; then
echo "[measure-sweep] building cli + app (turbo-cached)…"
( cd "$REPO_ROOT" && pnpm exec turbo run build \
@@ -129,7 +136,6 @@ if [[ ! -f "$CLI_BIN" ]]; then
exit 4
fi
-# ── 2. Copy fixture to scratch (source is never mutated) ───────────────────
SCRATCH="$(mktemp -d -t ok-sweep-XXXXXX)"
SERVER_LOG="$(mktemp -t ok-sweep-server-XXXXXX.log)"
SERVER_PID=""
@@ -160,11 +166,8 @@ cleanup() {
trap cleanup EXIT INT TERM
echo "[measure-sweep] copying fixture → $SCRATCH …"
-# Exclude .git (large, unneeded) and .ok/local (runtime state the server recreates).
rsync -a --exclude='.git' --exclude='.ok/local' "$FIXTURE/" "$SCRATCH/"
-# Nav doc: any doc works — project scope audits the whole content dir. Pick the
-# first markdown file outside .ok, as an extension-less content-relative name.
NAV_MD="$(find "$SCRATCH" -name '*.md' -not -path '*/.ok/*' | sort | head -1 || true)"
if [[ -z "$NAV_MD" ]]; then
echo "error: no markdown docs found under $SCRATCH" >&2
@@ -175,13 +178,10 @@ NAV_DOC="${NAV_DOC%.md}"
DOC_COUNT="$(find "$SCRATCH" -name '*.md' -not -path '*/.ok/*' | wc -l | tr -d ' ')"
echo "[measure-sweep] fixture: $DOC_COUNT docs · nav-doc: $NAV_DOC"
-# ── 3. Boot the server (serves both API and the Editor SPA) ────────────────
echo "[measure-sweep] starting ok server on a kernel-assigned port…"
( cd "$SCRATCH" && exec node "$CLI_BIN" start --port 0 ) >"$SERVER_LOG" 2>&1 &
SERVER_PID=$!
-# Single-listener topology: one `server.lock` port (written under
-# <content>/.ok/local) serves both the Editor SPA and the API.
read_server_port() {
local lock port
lock="$(find "$SCRATCH/.ok" -name server.lock 2>/dev/null | head -1 || true)"
@@ -211,7 +211,6 @@ if [[ -z "$EDITOR_PORT" ]]; then
exit 6
fi
-# ── 4. Run the browser measurement ─────────────────────────────────────────
TIMESTAMP="$(date -u +%Y-%m-%dT%H:%M:%SZ)"
COMMIT="$(git -C "$REPO_ROOT" rev-parse --short HEAD 2>/dev/null || echo unknown)"
HOST="$(detect_host)"
@@ -239,9 +238,6 @@ if [[ -z "$JSON" ]] || ! jq -e . >/dev/null 2>&1 <<<"$JSON"; then
exit 7
fi
-# ── 5. Compare to §7 targets; surface misses ───────────────────────────────
-# panel-open target uses the warm (render-bound) number — the metric R1 moves —
-# not the cold-audit-inclusive first activation.
CHECKS_JSON="$(jq -c -n --argjson m "$JSON" '
[ {name:"panelOpenWarmMs", target:1000, value:$m.panelOpenWarmMs, cmp:"<"},
{name:"sweepDurationMs", target:90000, value:$m.sweepDurationMs, cmp:"<"},
@@ -250,7 +246,6 @@ CHECKS_JSON="$(jq -c -n --argjson m "$JSON" '
] | map(. + {miss: (if .cmp=="<" then (.value >= .target) else (.value != .target) end)})')"
MISSES_JSON="$(jq -c '[ .[] | select(.miss) | {name,target,value,cmp} ]' <<<"$CHECKS_JSON")"
-# ── 6. Compose + append JSONL record ───────────────────────────────────────
mkdir -p "$EVIDENCE_DIR"
RECORD="$(jq -c -n \
--arg timestamp "$TIMESTAMP" \
@@ -270,12 +265,6 @@ RECORD="$(jq -c -n \
context:$context, metrics:$metrics, targets:$targets, targetMisses:$targetMisses,
durationMs:$durationMs, host:$host, invokedBy:$invokedBy, nodeVersion:$nodeVersion}')"
-# Only a COMPLETED sweep earns a row in the trend log. An incomplete run still
-# emits SWEEP_RESULT — with sweepDurationMs pinned at the timeout ceiling — so
-# appending before this check would file a schema-identical row that a naive
-# aggregation reads as a real duration. The summary below still prints the
-# partial numbers, and step 7 still exits non-zero; the log just stays clean.
-# Same contract measure-fuzz.sh states for its own evidence file.
if [[ "$(jq -r '.sweepCompleted' <<<"$JSON")" == "true" ]]; then
append_jsonl_atomic "$LOG_FILE" "$RECORD"
APPENDED_TO_LOG=1
@@ -283,7 +272,6 @@ else
APPENDED_TO_LOG=0
fi
-# ── 7. Summary ─────────────────────────────────────────────────────────────
echo ""
echo "──────── measure-sweep summary ────────"
echo " context: $CONTEXT"
@@ -318,8 +306,6 @@ else
fi
echo ""
-# A completed-but-target-missing run is still a valid measurement (exit 0 —
-# the miss is surfaced, not swallowed). Only an incomplete sweep is a failure.
if [[ "$(jq -r '.sweepCompleted' <<<"$JSON")" != "true" ]]; then
echo "error: the sweep did not complete within ${SWEEP_TIMEOUT_MS}ms — numbers above are partial." >&2
exit 8
diff --git a/packages/app/scripts/perf-compare.sh b/packages/app/scripts/perf-compare.sh
index 09d85f031..5463d28c8 100755
--- a/packages/app/scripts/perf-compare.sh
+++ b/packages/app/scripts/perf-compare.sh
@@ -1,52 +1,4 @@
#!/usr/bin/env bash
-#
-# perf-compare.sh — diff two committed perf baseline JSONs (US-006)
-#
-# Purpose
-# -------
-# Future perf experiments diff a "post-change" baseline against the M0.5
-# anchor (or any prior baseline) to mechanically answer "did this improve
-# perf?". Output is an advisory markdown table — exit code reflects only
-# I/O / parse errors, never regression severity (per AC 5).
-#
-# Usage
-# -----
-# bash scripts/perf-compare.sh \
-# --from tests/perf/baselines/2026-04-23-post-v2-baseline.json \
-# --to tests/perf/baselines/2026-05-15-content-visibility-auto.json
-#
-# # Filter to a single scenario or doc
-# bun run perf:compare -- --from a.json --to b.json --scenario=cold-pool-warm
-# bun run perf:compare -- --from a.json --to b.json --doc=PROJECT
-#
-# # Tighten variance threshold (default 5%)
-# bun run perf:compare -- --from a.json --to b.json --variance-threshold=0.10
-#
-# Output shape
-# ------------
-# Markdown table:
-# | Scenario | Doc | Metric | From | To | Δ (abs) | Δ (%) |
-#
-# Per-row tag (last column when applicable):
-# ⬆️ IMPROVED — change beyond threshold AND in the favorable direction
-# ⬇️ REGRESSED — change beyond threshold AND in the unfavorable direction
-# ➡️ UNCHANGED — within ±threshold (treated as noise)
-#
-# Direction semantics:
-# - Metric names ending in `Ms` are latency — lower is better.
-# - All other metrics — higher is better (counts, throughput, etc.).
-# This heuristic is intentionally simple; refine in this script's
-# `direction_for_metric` function if a future metric breaks the rule.
-#
-# Exit codes
-# ----------
-# 0 success (regardless of any IMPROVED / REGRESSED rows)
-# 1 malformed input (jq parse failure)
-# 2 missing file or missing required argument
-# 64 --help requested
-#
-# Dependencies: jq (must be on PATH).
-#
set -euo pipefail
@@ -74,8 +26,6 @@ Output: markdown table on stdout.
EOF
}
-# -- argument parsing -------------------------------------------------------
-
FROM=""
TO=""
SCENARIO=""
@@ -150,7 +100,6 @@ if [ ! -f "$TO" ]; then
exit 2
fi
-# Validate JSON parse early so we can exit 1 cleanly on malformed input.
if ! jq -e . "$FROM" >/dev/null 2>&1; then
echo "perf-compare: malformed JSON in --from: $FROM" >&2
exit 1
@@ -160,16 +109,6 @@ if ! jq -e . "$TO" >/dev/null 2>&1; then
exit 1
fi
-# -- diff computation -------------------------------------------------------
-#
-# We pull out tuples (scenario, doc, metric, p50_value) from each side, then
-# join them in jq. The shape of a baseline is per SPEC §13.2:
-# { scenarios: { <name>: { docs: { <key>: { <metric>: { p50, p95, runs } } } } } }
-#
-# We compare p50 only — the canonical comparator per the same SPEC. Future
-# extensions can add p95 by widening the jq projection.
-
-# Build filter expressions to apply scenario / doc filters in jq.
SCENARIO_FILTER='select(true)'
if [ -n "$SCENARIO" ]; then
SCENARIO_FILTER="select(.scenario == \"$SCENARIO\")"
@@ -179,7 +118,6 @@ if [ -n "$DOC" ]; then
DOC_FILTER="select(.doc == \"$DOC\")"
fi
-# jq pipeline: flatten to {scenario, doc, metric, p50} tuples on each side.
flatten_jq='
.scenarios as $scenarios
| $scenarios | to_entries[] as $sc
@@ -189,12 +127,9 @@ flatten_jq='
| {scenario: $sc.key, doc: $d.key, metric: $m.key, p50: $m.value.p50}
'
-# Materialize both sides into JSON arrays so we can join them.
FROM_TUPLES=$(jq -c "[$flatten_jq]" "$FROM")
TO_TUPLES=$(jq -c "[$flatten_jq]" "$TO")
-# Join on (scenario, doc, metric); emit one row per pair and `null` placeholders
-# for rows present in only one side.
JOINED=$(
jq -n \
--argjson from "$FROM_TUPLES" \
@@ -218,10 +153,7 @@ JOINED=$(
'
)
-# -- markdown table emission ------------------------------------------------
-
direction_for_metric() {
- # Returns 'lower' or 'higher' — which direction is "better".
local metric="$1"
case "$metric" in
*Ms|*ms) echo "lower" ;;
@@ -230,7 +162,6 @@ direction_for_metric() {
}
format_num() {
- # 1 decimal place, trailing zero stripped if integer.
local n="$1"
if [ "$n" = "null" ] || [ -z "$n" ]; then
echo "(missing)"
@@ -256,7 +187,6 @@ while IFS= read -r row; do
continue
fi
- # Compute deltas via awk for portability (bash arithmetic doesn't do floats).
read -r delta_abs delta_pct <<EOF
$(awk -v f="$from_raw" -v t="$to_raw" 'BEGIN { d=t-f; if (f != 0) p=(d/f)*100; else p=0; printf "%.2f %.2f", d, p }')
EOF
diff --git a/packages/app/scripts/perf-prod.sh b/packages/app/scripts/perf-prod.sh
index 5d4782f9a..3655d5930 100755
--- a/packages/app/scripts/perf-prod.sh
+++ b/packages/app/scripts/perf-prod.sh
@@ -1,56 +1,76 @@
#!/usr/bin/env bash
-#
-# perf-prod.sh — prod-fidelity perf measurement wrapper.
-#
-# Orchestrates build → start CLI → run perf:profile N times → tear down.
-# Gives developers a one-command path to measure against the built artifact
-# (equivalent to what ships to users) instead of `pnpm run dev` (Vite HMR
-# + transform overhead, uncomparable).
-#
-# Usage:
-# packages/app/scripts/perf-prod.sh --scenario=<name> [--runs=5] [--env="KEY=value"]
-#
-# Examples:
-# # G2 regression-gate capture (canonical reference per V2 SPEC §11):
-# packages/app/scripts/perf-prod.sh --scenario=cold-pool-warm \
-# --env="OK_PERF_BIG_DOC=perf-fixtures/medium-doc"
-#
-# # G4 mode-toggle with 10 runs:
-# packages/app/scripts/perf-prod.sh --scenario=mode-toggle --runs=10
-#
-# What it does (precedent #22 shell-script conventions):
-# 1. Runs `pnpm run build` from repo root (turbo-cached; no-op when clean).
-# 2. Starts ONE CLI process on a kernel-assigned port:
-# `open-knowledge start --port 0` — the project server (React shell +
-# Hocuspocus + /api/* on one listener). Polls `.ok/local/server.lock`
-# for the bound port. Playwright navigates against that same port.
-# 3. Runs `pnpm run perf:profile --scenario=<name> --target=http://localhost:<port> --headless`
-# N times. Results land at `packages/app/tests/perf/results/<scenario>.<ts>.json`.
-# 4. Sends SIGTERM; the CLI's shutdown ordering releases the lock cleanly.
-# Waits up to 5s for the lock to disappear.
-# 5. Parses the N most recent result files, extracts the scenario's
-# primary metric, reports individual values + median.
-#
-# Exit codes:
-# 0 — N runs completed, median reported
-# 1 — usage error (missing --scenario, bad flag value)
-# 2 — build failure
-# 3 — server failed to start / lock never populated
-# 4 — perf:profile run failure
-# 5 — results parsing / median computation failure
-#
-# Not a replacement for the CI-based baseline-capture protocol — see
-# packages/app/tests/stress/perf-baseline-update.md §"Local prod-fidelity
-# dry-run." Runner hardware differs; local medians are directional signal
-# only.
+# Follows the shell-script conventions of precedent #22.
set -euo pipefail
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
-# shellcheck source=./_measure-lib.sh
source "$HERE/_measure-lib.sh"
-# ── Arg parsing ──────────────────────────────────────────────────────────────
+usage() {
+ cat <<'EOF'
+Usage: packages/app/scripts/perf-prod.sh --scenario=<name> [--runs=N] [--env="K=V ..."]
+
+Prod-fidelity perf measurement wrapper. Orchestrates build → start CLI → run
+perf:profile N times → tear down, so a developer measures against the built
+artifact (equivalent to what ships to users) instead of `pnpm run dev`, whose
+Vite HMR and transform overhead make the numbers uncomparable.
+
+Required:
+ --scenario=<name> Scenario to profile. Names come from
+ packages/app/tests/perf/scenarios/; omitting the flag
+ prints the available list.
+
+Optional:
+ --runs=N Number of profile runs (default: 5). Must be >= 1.
+ --env="K=V ..." Extra environment for each perf:profile run. Word-split, so
+ several assignments can share one flag.
+ -h, --help Show this message.
+
+All three value flags are =-form only: `--scenario cold-pool-warm` is an unknown
+argument, not a scenario.
+
+Examples:
+ packages/app/scripts/perf-prod.sh --scenario=cold-pool-warm \
+ --env="OK_PERF_BIG_DOC=perf-fixtures/medium-doc"
+ packages/app/scripts/perf-prod.sh --scenario=mode-toggle --runs=10
+
+What it does:
+ 1. Runs `pnpm run build` from the repo root (turbo-cached; a no-op when clean).
+ 2. Starts ONE CLI process on a kernel-assigned port —
+ `node packages/cli/dist/cli.mjs start --port 0`, the project server (React
+ shell + Hocuspocus + /api/* on one listener) — and polls .ok/local/server.lock
+ for up to 30s for the bound port. perf:profile targets that same port.
+ 3. Runs `pnpm run perf:profile --scenario=<name> --target=http://localhost:<port>
+ --headless` N times. Results land at
+ packages/app/tests/perf/results/<scenario>.<timestamp>.json. A run that exits
+ non-zero is counted and the loop continues.
+ 4. Sends SIGTERM, waits up to 5s for the process to exit and the lock to
+ disappear, then SIGKILLs.
+ 5. Reads the N most recent result files. For a scenario with a registered
+ primary metric, prints each value and the median; otherwise lists the files
+ and the jq expression for extracting a custom metric.
+
+Output:
+ Progress lines, a SUMMARY block, and `MEDIAN: <n> ms` when a primary metric is
+ registered and at least one non-negative value parsed. Partial run failures are
+ reported and the median is computed from what remains.
+
+Exit codes:
+ 0 the run finished; median reported when a primary metric exists
+ 1 usage error: unknown argument, missing --scenario, or --runs < 1
+ 2 --runs is not a non-negative integer, `pnpm run build` failed, or the CLI
+ binary is missing after the build
+ 3 jq is not installed, or the server never populated .ok/local/server.lock
+ with a bound port
+ 4 the workspace-root markers are missing, or all N perf:profile runs failed
+ 5 no result files found for the scenario
+
+Not a replacement for the CI-based baseline-capture protocol — see
+packages/app/tests/stress/perf-baseline-update.md §"Local prod-fidelity dry-run",
+which lives in Inkeep's internal tree and is absent from the open-source
+repository. Runner hardware differs; local medians are directional signal only.
+EOF
+}
SCENARIO=""
RUNS=5
@@ -62,7 +82,7 @@ while [[ $# -gt 0 ]]; do
--runs=*) RUNS="${1#--runs=}"; shift ;;
--env=*) EXTRA_ENV="${1#--env=}"; shift ;;
-h|--help)
- sed -n '3,40p' "${BASH_SOURCE[0]}" | sed 's/^# \{0,1\}//'
+ usage
exit 0
;;
*) echo "error: unknown arg: $1" >&2; exit 1 ;;
@@ -88,8 +108,6 @@ CLI_BIN="$REPO_ROOT/packages/cli/dist/cli.mjs"
SERVER_LOCK="$REPO_ROOT/.ok/local/server.lock"
RESULTS_DIR="$REPO_ROOT/packages/app/tests/perf/results"
-# ── 1. Build (turbo-cached) ──────────────────────────────────────────────────
-
echo "[perf-prod] Building app + cli (turbo cache-friendly; no-op when clean)…"
cd "$REPO_ROOT"
if ! pnpm run build >/dev/null 2>&1; then
@@ -103,14 +121,6 @@ if [[ ! -x "$CLI_BIN" && ! -f "$CLI_BIN" ]]; then
exit 2
fi
-# ── 2. Start the CLI in background ──────────────────────────────────────────
-#
-# One listener, one origin: `ok start` serves the React shell, /api/*, and
-# the collab WebSocket on a single kernel-assigned port, advertised via
-# `.ok/local/server.lock`. Playwright navigates against that port.
-
-# Remove stale locks from crashed prior runs. The CLI has stale-PID recovery
-# but starting clean is simpler; skip only when the lock references a live pid.
for lock in "$SERVER_LOCK"; do
if [[ -f "$lock" ]]; then
STALE_PID="$(jq -r '.pid // "0"' "$lock" 2>/dev/null || echo "0")"
@@ -123,25 +133,6 @@ done
SERVER_LOG="$(mktemp -t perf-prod-server.XXXXXX.log)"
-# Pre-flight WORKAROUND for the totalist/sirv broken-symlink crash.
-#
-# The server serves its content tree via `sirv` → `[email protected]`, which
-# does synchronous statSync on every entry and propagates ENOENT. A
-# single broken symlink anywhere under the walked tree crashes the
-# static-serve path before it binds a port. `/review-local`'s plugin bundle at
-# `tmp/ship/pr-review-plugin/skills/` routinely creates broken symlinks
-# (relative paths like `../../../plugins/eng/skills/<name>` that assume
-# a non-monorepo layout).
-#
-# Auto-clean scoped to `tmp/` only — it's gitignored (never legitimate
-# content) and is where review-local/ship artifacts accumulate. Broader
-# scans of node_modules/ would hit legitimate cross-package symlinks.
-#
-# TODO: replace with upstream totalist fix — see tmp/ship/
-# totalist-sirv-crash-brief.md for the full repro + fix options. The
-# brief proposes a `pnpm patch [email protected]` that wraps readdirSync +
-# statSync in try/catch (ENOENT/EACCES/ENOTDIR → skip). Once that patch
-# lands, this pre-flight becomes dead code and can be deleted.
if [[ -d "$REPO_ROOT/tmp" ]]; then
BROKEN_LINKS=()
while IFS= read -r -d '' link; do
@@ -168,8 +159,6 @@ cleanup() {
echo "[perf-prod] Stopping server (pid $SERVER_PID)…"
kill -TERM "$SERVER_PID" 2>/dev/null || true
fi
- # Wait up to 5s for the process to exit + the lock to release per the
- # CLI's shutdown protocol.
for _ in 1 2 3 4 5 6 7 8 9 10; do
if ! kill -0 "${SERVER_PID:-0}" 2>/dev/null && [[ ! -f "$SERVER_LOCK" ]]; then break; fi
sleep 0.5
@@ -188,17 +177,12 @@ cleanup() {
}
trap cleanup EXIT INT TERM
-# ── 3. Wait for the server lock ──────────────────────────────────────────────
-
wait_for_lock() {
local lock="$1"
local pid="$2"
local label="$3"
local log="$4"
local port=""
- # NOTE: informational messages go to stderr (>&2); only the port number
- # goes to stdout. Caller captures this function via `PORT="$(wait_for_lock ...)"`,
- # so any stdout write other than the port number would corrupt the value.
for i in $(seq 1 60); do
if [[ -f "$lock" ]]; then
port="$(jq -r '.port // 0' "$lock" 2>/dev/null || echo "0")"
@@ -223,18 +207,13 @@ wait_for_lock() {
echo "[perf-prod] Waiting for $SERVER_LOCK with a bound port…"
PORT="$(wait_for_lock "$SERVER_LOCK" "$SERVER_PID" "server" "$SERVER_LOG")" || exit 3
-# ── 4. Run perf:profile N times ──────────────────────────────────────────────
-
APP_DIR="$REPO_ROOT/packages/app"
cd "$APP_DIR"
run_failures=0
for i in $(seq 1 "$RUNS"); do
echo "[perf-prod] Run $i/$RUNS — scenario=$SCENARIO target=http://localhost:$PORT"
- # Build the env-prefix command. `env $EXTRA_ENV` takes zero or more
- # KEY=value tokens space-separated. An empty string is a no-op.
if [[ -n "$EXTRA_ENV" ]]; then
- # shellcheck disable=SC2086
if ! env $EXTRA_ENV pnpm run perf:profile --scenario="$SCENARIO" --target="http://localhost:$PORT" --headless; then
run_failures=$((run_failures + 1))
echo "[perf-prod] WARN: run $i exited non-zero — continuing" >&2
@@ -255,15 +234,6 @@ if (( run_failures > 0 )); then
echo "[perf-prod] NOTE: $run_failures/$RUNS runs failed (median computed from remaining)" >&2
fi
-# ── 5. Extract primary metric + median ───────────────────────────────────────
-
-# Map scenario → jq path for the metric we care about most. When a
-# scenario doesn't have a canonical primary metric, the script reports
-# all result filenames and leaves median computation to the caller.
-# Names here must match exactly what the scenario emits via
-# ctx.recordMetric(...). Verified against packages/app/tests/perf/scenarios/
-# on 2026-04-21 — `warm-switch-cached` emits `warmSwitchCachedMs` (not
-# `warmSwitchMs` — that's the separate `warm-switch` scenario).
case "$SCENARIO" in
warm-switch-cached) METRIC=".metrics.warmSwitchCachedMs" ;;
cold-pool-warm) METRIC=".metrics.coldPoolWarmMs" ;;
@@ -275,11 +245,7 @@ case "$SCENARIO" in
*) METRIC="" ;;
esac
-# Take the N most-recent result files for this scenario (mtime order). If an
-# older measurement session left more than N files, only the freshest N — the
-# ones this run just produced — feed the median.
cd "$RESULTS_DIR"
-# shellcheck disable=SC2012 # ls with -t is intentional; file names have no spaces/newlines.
latest_files="$(ls -t "$SCENARIO".*.json 2>/dev/null | head -n "$RUNS" || true)"
if [[ -z "$latest_files" ]]; then
echo "error: no result files found for scenario=$SCENARIO in $RESULTS_DIR" >&2
@@ -307,15 +273,7 @@ else
values+="$v"$'\n'
done <<< "$latest_files"
- # Compute median of non-negative values. Negative values (scenario
- # sentinel for "could not measure") are excluded from the median but
- # still reported above as -1 for visibility.
- #
- # Portability note (precedent #22(d)): GNU awk has `asort()`, BSD awk
- # (macOS default) does not. The POSIX-compatible path is an explicit
- # insertion sort over the collected array — a handful of lines, no
- # external dependency. `LC_ALL=C` keeps `.`-as-decimal-separator so a
- # non-US locale doesn't break numeric parsing.
+ # The median uses a POSIX awk insertion sort rather than GNU asort() (precedent #22(d)).
median="$(printf '%s' "$values" | LC_ALL=C awk '
/^-?[0-9]+(\.[0-9]+)?$/ && $1 >= 0 { a[c++] = $1 + 0 }
END {
@@ -343,7 +301,7 @@ else
fi
echo ""
echo "[perf-prod] NOTE: For the canonical baseline capture, follow the CI-based"
-echo "[perf-prod] protocol in packages/app/tests/stress/perf-baseline-update.md."
+echo "[perf-prod] protocol in packages/app/tests/stress/perf-baseline-update.md"
+echo "[perf-prod] (Inkeep-internal; absent from the open-source repository)."
echo "[perf-prod] Local medians are directional signal, not the authority."
-# Cleanup runs via the trap.
diff --git a/packages/app/src/build/app-version.test.ts b/packages/app/src/build/app-version.test.ts
index c0ae732df..f677c9e52 100644
--- a/packages/app/src/build/app-version.test.ts
+++ b/packages/app/src/build/app-version.test.ts
@@ -1,8 +1,14 @@
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
+import { CLIENT_RUNTIME_VERSION_FALLBACK } from '@inkeep/open-knowledge-core';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
-import { APP_VERSION_ENV_VAR, injectAppVersionEnv, resolveAppVersion } from './app-version.ts';
+import {
+ APP_VERSION_ENV_VAR,
+ APP_VERSION_UNKNOWN,
+ injectAppVersionEnv,
+ resolveAppVersion,
+} from './app-version.ts';
const here = dirname(fileURLToPath(import.meta.url));
const appPkgVersion = (
@@ -11,13 +17,18 @@ const appPkgVersion = (
}
).version;
+describe('the unresolved-version sentinel', () => {
+ test('matches the core client-version fallback it is duplicated from', () => {
+ expect(APP_VERSION_UNKNOWN).toBe(CLIENT_RUNTIME_VERSION_FALLBACK);
+ });
+});
+
describe('resolveAppVersion', () => {
test('returns the real packages/app/package.json version, not a sentinel', () => {
const version = resolveAppVersion();
expect(version).toBe(appPkgVersion);
- // A build must never silently inject a placeholder.
expect(version).not.toBe('dev');
- expect(version).not.toBe('0.0.0-unknown');
+ expect(version).not.toBe(APP_VERSION_UNKNOWN);
});
});
@@ -38,12 +49,6 @@ describe('injectAppVersionEnv', () => {
});
});
-// guard: the injection must be wired into EVERY build path or the browser
-// silently falls back to the sentinel. The two configs cannot be imported in
-// the unit tier (vite.config pulls in the full server via hocuspocusPlugin;
-// electron.vite runs a top-level `await babel()` and needs the electron-vite
-// runner) — runtime coverage here is infeasible, so we assert the wiring at the
-// source level instead.
describe('build-path wiring (R-3)', () => {
const repoConfigs = [
resolve(here, '..', '..', 'vite.config.ts'),
diff --git a/packages/app/src/build/app-version.ts b/packages/app/src/build/app-version.ts
index 1adb60a8e..cbfec6da3 100644
--- a/packages/app/src/build/app-version.ts
+++ b/packages/app/src/build/app-version.ts
@@ -1,58 +1,23 @@
-/**
- * Build-time resolution of the web app's own version, for injection into the
- * browser bundle.
- *
- * The browser cannot read its own `package.json` at runtime, and it must NOT
- * fetch its version from the server — a stale tab that asks the *current*
- * server would always report itself compatible, defeating drift detection.
- * So the version is injected at build time and read from `import.meta.env`.
- *
- * Mechanism: every build path (the `packages/app` Vite config — which serves
- * both `bun run dev` and the bundle `ok ui` ships — and the `packages/desktop`
- * electron-vite renderer config) calls {@link injectAppVersionEnv} at config
- * module load. That sets `process.env.VITE_APP_VERSION`, which Vite then
- * surfaces on `import.meta.env.VITE_APP_VERSION` for both readers (the OTel
- * telemetry resource and the client-version wire builder). One build-time
- * source, two readers, divergent fallbacks (`'dev'` for telemetry, the
- * server-matching `'0.0.0-unknown'` for client-version).
- */
import { readFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
-/** The env var both browser readers consume via `import.meta.env`. */
export const APP_VERSION_ENV_VAR = 'VITE_APP_VERSION';
-/**
- * Read the app's semver from `packages/app/package.json` (the install version
- * under the fixed-group lockstep). Returns the `'0.0.0-unknown'` sentinel —
- * matching the server's `readRuntimeVersion()` convention — if it can't be
- * resolved, so a build never injects a bogus value silently.
- */
+export const APP_VERSION_UNKNOWN = '0.0.0-unknown';
+
export function resolveAppVersion(): string {
try {
- // src/build/app-version.ts → ../../package.json (packages/app/package.json)
const here = dirname(fileURLToPath(import.meta.url));
const pkgPath = resolve(here, '..', '..', 'package.json');
const pkg = JSON.parse(readFileSync(pkgPath, 'utf-8')) as { version?: unknown };
if (typeof pkg.version === 'string' && pkg.version.length > 0) {
return pkg.version;
}
- } catch {
- // Fall through to sentinel.
- }
- // Keep in sync with `CLIENT_RUNTIME_VERSION_FALLBACK` in
- // `@inkeep/open-knowledge-core` and the server's `readRuntimeVersion()`
- // sentinel. Not imported from core: this runs at Vite config-load time and
- // must not pull the core barrel (and its unrelated modules) into the build.
- return '0.0.0-unknown';
+ } catch {}
+ return APP_VERSION_UNKNOWN;
}
-/**
- * Inject the resolved app version onto `process.env.VITE_APP_VERSION` so Vite
- * exposes it on `import.meta.env`. Call once at the top of each build's config
- * module. Returns the value it set (handy for logging / tests).
- */
export function injectAppVersionEnv(): string {
const version = resolveAppVersion();
process.env[APP_VERSION_ENV_VAR] = version;
diff --git a/packages/app/src/build/chrome-tokens-vite-plugin.ts b/packages/app/src/build/chrome-tokens-vite-plugin.ts
index 14baad228..e279a4bc4 100644
--- a/packages/app/src/build/chrome-tokens-vite-plugin.ts
+++ b/packages/app/src/build/chrome-tokens-vite-plugin.ts
@@ -1,25 +1,3 @@
-/**
- * Vite plugin: substitute `__OK_CHROME_BG_LIGHT__` and `__OK_CHROME_BG_DARK__`
- * placeholders in `index.html` (and any `.html` Vite is transforming) with the
- * sRGB hex resolved from the `--sidebar` Tailwind v4 token.
- *
- * The plugin reads `packages/app/src/globals.css` at build start, resolves
- * OKLCH→sRGB via culori, then runs in `transformIndexHtml` with `enforce:
- * 'pre'` so the substitution applies before Vite's HTML rewriter touches the
- * inline `<style>`. The same resolved values are committed to
- * `packages/core/src/constants/chrome.ts` (regenerated by
- * `packages/core/scripts/generate-chrome-tokens.ts`); the drift test in
- * `packages/core/src/constants/chrome.test.ts` ensures the file stays in
- * sync with globals.css.
- *
- * Both pieces — `transformIndexHtml` inline-`<style>` substitution and
- * Tailwind v4 OKLCH→sRGB resolution via culori — were verified locally
- * against the existing `oklch(0.985 0 0)` / `oklch(0.205 0 0)` values;
- * both resolve to the existing literals (`#fafafa` / `#171717`). No
- * fallback path required; this Vite plugin is the canonical pipeline,
- * with `packages/core/scripts/generate-chrome-tokens.ts` as the
- * one-shot regenerator the drift test calls into.
- */
import { resolve } from 'node:path';
import type { Plugin } from 'vite';
import { resolveChromeTokensFromCss } from '../../../core/scripts/chrome-resolver.ts';
@@ -28,7 +6,6 @@ const LIGHT_PLACEHOLDER = '__OK_CHROME_BG_LIGHT__';
const DARK_PLACEHOLDER = '__OK_CHROME_BG_DARK__';
interface ChromeTokensPluginOptions {
- /** Absolute path to the globals.css file. Defaults to `<app>/src/globals.css`. */
globalsCssPath?: string;
}
@@ -47,8 +24,6 @@ export function chromeTokensVitePlugin(options: ChromeTokensPluginOptions = {}):
name: 'ok:chrome-tokens',
enforce: 'pre',
buildStart() {
- // Eager-resolve on every build so a failure surfaces in the build log
- // rather than later at the first index.html transform.
resolveOnce();
},
transformIndexHtml: {
diff --git a/packages/app/src/build/electron-mode-class.test.ts b/packages/app/src/build/electron-mode-class.test.ts
index 6944e2fcb..d235c8846 100644
--- a/packages/app/src/build/electron-mode-class.test.ts
+++ b/packages/app/src/build/electron-mode-class.test.ts
@@ -1,29 +1,3 @@
-/**
- * Source-level guards for the FOUC-time `html.electron-mode` class addition.
- *
- * Repo convention: no @testing-library / happy-dom. The class addition runs
- * in the inline `<script>` block of `packages/app/index.html` — DOM-bound
- * runtime behavior is exercised end-to-end via Playwright in the Electron
- * host context. These guards lock the structural choices a future refactor
- * would silently break:
- *
- * - The class name is exactly `electron-mode` (CSS rules in globals.css
- * scope to `html.electron-mode`; renaming here without renaming there
- * is silent regression).
- * - The detection condition is `window.okDesktop` truthy (the canonical
- * idiom — matches `OpenInAgentMenu`, `FileTree`, `EditorHeader`,
- * `EditorTabs`, `FileSidebar`).
- * - The class is added on `document.documentElement` (the `<html>` element
- * — globals.css selector is `html.electron-mode`, NOT `body.electron-mode`).
- * - The addition runs INSIDE the existing FOUC inline `<script>`, NOT in a
- * React effect or main.tsx. Per FOUC discipline, the class must be on
- * `<html>` BEFORE first paint so the alpha-aware CSS rules engage from
- * byte 1.
- * - The script body remains single-line (biome's HTML formatter reindents
- * inline-script content; multi-line bodies create an infinite reformat
- * loop at pre-commit).
- */
-
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, test } from 'vitest';
@@ -32,17 +6,12 @@ const HTML = readFileSync(join(__dirname, '..', '..', 'index.html'), 'utf8');
describe('index.html FOUC inline script — electron-mode class', () => {
test('inline FOUC script adds the electron-mode class to documentElement when window.okDesktop is present', () => {
- // Braced form: the okDesktop branch now adds electron-mode AND the
- // per-platform class (electron-platform-<platform>) in one block.
expect(HTML).toMatch(
/if\s*\(\s*window\.okDesktop\s*\)\s*\{\s*document\.documentElement\.classList\.add\(\s*['"]electron-mode['"]\s*\)/,
);
});
test('inline FOUC script also stamps the per-platform class (win/linux chrome CSS keys off it)', () => {
- // globals.css scopes the Windows/Linux window-controls reserve to
- // html.electron-mode.electron-platform-{win32,linux}; the class must be
- // present before first paint, in the same okDesktop-gated block.
expect(HTML).toMatch(
/classList\.add\(\s*`electron-platform-\$\{window\.okDesktop\.platform\}`\s*\)/,
);
diff --git a/packages/app/src/build/rejection-loop-guard-plugin.test.ts b/packages/app/src/build/rejection-loop-guard-plugin.test.ts
index 873d7ef71..966d0e3f8 100644
--- a/packages/app/src/build/rejection-loop-guard-plugin.test.ts
+++ b/packages/app/src/build/rejection-loop-guard-plugin.test.ts
@@ -10,8 +10,6 @@ describe('rejectionLoopGuardPlugin', () => {
});
test('plugin is dev-only via apply: serve', () => {
- // `apply: 'serve'` is the structural gate — runtime `command` checks
- // would still let the plugin object enter the production plugin graph.
expect(plugin.apply).toBe('serve');
});
@@ -33,12 +31,6 @@ describe('rejectionLoopGuardPlugin', () => {
});
test('script tag is type="text/javascript" (classic, not module) so it runs before deferred @vite/client', () => {
- // Load-bearing: classic scripts execute synchronously during HTML
- // parsing; module scripts (`type="module"`) are deferred until after
- // parsing completes. `@vite/client` is a module script, so a classic
- // script — regardless of its position in source order — registers its
- // listener first at runtime. Switching this to `type="module"` would
- // re-introduce a registration race against `@vite/client`.
const transform = plugin.transformIndexHtml as {
handler: () => Array<{ attrs?: Record<string, string> }>;
};
@@ -46,12 +38,17 @@ describe('rejectionLoopGuardPlugin', () => {
expect(tags[0].attrs?.type).toBe('text/javascript');
});
+ test('the injected bytes carry the STOP marker that guards the classic-script contract', () => {
+ const transform = plugin.transformIndexHtml as {
+ handler: () => Array<{ children: string }>;
+ };
+ const injected = transform.handler()[0].children;
+ expect(injected).toMatch(/STOP: /);
+ expect(injected).toContain('rejection-loop-guard-plugin.ts');
+ expect(injected).toContain('type="module"');
+ });
+
test('plugin children match the guard-script file byte-for-byte', () => {
- // Locks the wiring: the plugin loads the script via `readFileSync`;
- // this test loads it via `?raw`. They must yield identical bytes.
- // If the script file is renamed or a build step starts mutating it,
- // this catches the drift before the injected payload silently
- // diverges from the source.
const transform = plugin.transformIndexHtml as {
handler: () => Array<{ children: string }>;
};
@@ -61,31 +58,21 @@ describe('rejectionLoopGuardPlugin', () => {
test('injected script installs idempotently via window flag', () => {
expect(GUARD_SCRIPT).toContain('window.__okViteRejectionGuardInstalled');
- // Both the early-return and the set-flag must be present so HMR
- // re-injection doesn't double-register the listener.
expect(GUARD_SCRIPT).toMatch(/if \(window\.__okViteRejectionGuardInstalled\) return;/);
expect(GUARD_SCRIPT).toMatch(/window\.__okViteRejectionGuardInstalled = true;/);
});
test('match condition checks both message string and @vite/client stack', () => {
- // Belt-and-braces: a Vite wording change must not silently disable
- // the guard. The stack-trace fallback survives version bumps.
expect(GUARD_SCRIPT).toContain("'send was called before connect'");
expect(GUARD_SCRIPT).toContain("'@vite/client'");
});
test('listener calls stopImmediatePropagation and preventDefault', () => {
- // Both are required: stopImmediatePropagation prevents Vite's listener
- // from running (breaking the loop), preventDefault suppresses the
- // browser's default console error.
expect(GUARD_SCRIPT).toContain('event.stopImmediatePropagation();');
expect(GUARD_SCRIPT).toContain('event.preventDefault();');
});
test('warning logs at most once per session plus a 5-second bucket counter', () => {
- // At ~22,000 rejections/sec, an unbounded warn-per-event would itself
- // become a CPU hot-path. Initial warn-once + 5-second flush keeps
- // operational visibility without recreating the original storm.
expect(GUARD_SCRIPT).toContain('warned = false');
expect(GUARD_SCRIPT).toContain('warned = true');
expect(GUARD_SCRIPT).toContain('setInterval');
@@ -93,15 +80,10 @@ describe('rejectionLoopGuardPlugin', () => {
});
test('script is parseable JavaScript', () => {
- // The injected body is a plain IIFE — no TypeScript, no module
- // imports. A syntax error here would silently disable the guard at
- // runtime; parse-check at test time catches that.
expect(() => new Function(GUARD_SCRIPT)).not.toThrow();
});
test('guard behavior — simulated unhandledrejection flow', () => {
- // Set up a fake window with addEventListener so we can exercise the
- // script body and observe what it would do at runtime.
const listeners: Array<(event: PromiseRejectionEvent) => void> = [];
const fakeWindow = {
__okViteRejectionGuardInstalled: undefined as boolean | undefined,
@@ -140,26 +122,21 @@ describe('rejectionLoopGuardPlugin', () => {
listeners[0](event);
}
- // Literal-message match
fireWith({ message: 'send was called before connect' });
expect(stopped).toBe(1);
expect(prevented).toBe(1);
expect(warnCalls).toHaveLength(1);
expect(warnCalls[0]).toContain('[ok-dev]');
- // Stack-trace match (survives a future Vite wording change)
fireWith({ message: 'something else', stack: 'at @vite/client:518' });
expect(stopped).toBe(2);
expect(prevented).toBe(2);
- // Still only one warn — initial-warn-once contract holds.
expect(warnCalls).toHaveLength(1);
- // Unrelated rejection passes through untouched
fireWith({ message: 'unrelated app bug', stack: 'at App.tsx:42' });
expect(stopped).toBe(2);
expect(prevented).toBe(2);
- // Defensive: null reason must not crash
fireWith(null);
expect(stopped).toBe(2);
});
diff --git a/packages/app/src/build/rejection-loop-guard-plugin.ts b/packages/app/src/build/rejection-loop-guard-plugin.ts
index 9725340d0..12f415beb 100644
--- a/packages/app/src/build/rejection-loop-guard-plugin.ts
+++ b/packages/app/src/build/rejection-loop-guard-plugin.ts
@@ -1,53 +1,7 @@
-/**
- * Vite plugin: inject an `unhandledrejection` guard before `@vite/client` to
- * break a self-amplifying feedback loop in Vite's dev-only error forwarder.
- *
- * The loop: Vite's `@vite/client` registers a `window.addEventListener(
- * 'unhandledrejection', ...)` handler that forwards browser errors to the
- * dev server. The handler calls `sendError()` → `transport.send()`. The
- * `send` method is `async` and synchronously throws `new Error("send was
- * called before connect")` when the Vite module-runner transport is
- * disconnected. Because Vite's `sendError` drops the returned promise, that
- * throw becomes another unhandled rejection — which triggers the same
- * handler, which throws again. Observed in a Chrome DevTools trace at
- * ~22,000 iterations/sec, growing the renderer process to >1.5 GB before
- * GC keeps up.
- *
- * We cannot fix Vite's source directly. Instead we inject the contents of
- * `./rejection-loop-guard-script.js` (read via `readFileSync` at plugin
- * startup — see rolldown constraint below) as an inline
- * `<script type="text/javascript">`. The `type="text/javascript"` choice
- * is load-bearing: classic scripts execute synchronously during HTML
- * parsing, while module scripts (`type="module"`, like `@vite/client`)
- * are deferred until after parsing completes. So even though Vite's
- * `<script>` tag appears earlier in source order than ours, our listener
- * registers first at runtime. Do not change this to `type="module"` —
- * doing so would put our listener on the same deferred queue as Vite's
- * and registration order would become dependent on plugin ordering and
- * Vite version.
- *
- * When the loop-causing rejection fires our listener calls
- * `stopImmediatePropagation()` — on a `window`-targeted event with no
- * DOM propagation path, this stops every remaining listener regardless
- * of capture/bubble phase — and `preventDefault()` to suppress the
- * browser's default console error. One initial `console.warn` and a
- * 5-second-bucketed counter give operational visibility without
- * re-creating the storm.
- *
- * `apply: 'serve'` keeps the plugin out of production builds entirely —
- * `@vite/client` does not ship in `vite build` output, so the guard is
- * irrelevant there.
- */
import { readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import type { Plugin } from 'vite';
-// `?raw` would be the natural import, but rolldown — used to bundle
-// `vite.config.ts` itself before Vite starts — does not resolve `?raw`
-// in the config-load path and exits with `UNLOADABLE_DEPENDENCY`.
-// `readFileSync` at module load is the same shape `chrome-tokens-vite-plugin.ts`
-// uses (it reads `globals.css`) and is the established workaround in this
-// build/ directory.
const GUARD_SCRIPT_PATH = resolve(
import.meta.dirname ?? new URL('.', import.meta.url).pathname,
'./rejection-loop-guard-script.js',
@@ -57,9 +11,6 @@ export function rejectionLoopGuardPlugin(): Plugin {
const guardScript = readFileSync(GUARD_SCRIPT_PATH, 'utf-8');
return {
name: 'ok:rejection-loop-guard',
- // `apply: 'serve'` is Vite's first-class mechanism for keeping a plugin
- // out of production builds. We do not check `command` inside the hook —
- // the gate is structural.
apply: 'serve',
transformIndexHtml: {
order: 'pre',
diff --git a/packages/app/src/build/rejection-loop-guard-script.js b/packages/app/src/build/rejection-loop-guard-script.js
index a7cd2060f..e3876ddfb 100644
--- a/packages/app/src/build/rejection-loop-guard-script.js
+++ b/packages/app/src/build/rejection-loop-guard-script.js
@@ -1,24 +1,7 @@
-/**
- * Inline guard injected at `head-prepend` by `rejectionLoopGuardPlugin`.
- * Read by the plugin via `readFileSync` at startup and injected verbatim
- * as `<script>` children. Tests import this file via `?raw` to assert
- * byte-equality with what the plugin emits — see
- * `rejection-loop-guard-plugin.ts` for why the plugin itself can't use
- * `?raw` (rolldown's config-load path doesn't resolve query imports).
- *
- * IIFE — no module imports, ever. This runs as a classic
- * <script type="text/javascript"> so it registers its `unhandledrejection`
- * listener BEFORE `@vite/client` (a deferred module script). Do not introduce
- * `import` or `export` here, and do not switch the consuming <script> tag in
- * `rejection-loop-guard-plugin.ts` to `type="module"` — both would put this
- * script on the same deferred queue as `@vite/client` and re-introduce the
- * registration race. `readFileSync` delivers the bytes as-authored. Targets
- * evergreen Chromium (Electron renderer + dev Chrome) so ES2020+ is fine.
- *
- * Match condition is belt-and-braces: literal message string OR `@vite/client`
- * substring in the stack. A future Vite wording change must not silently
- * disable the guard.
- */
+/* STOP: rejection-loop-guard-plugin.ts injects this file verbatim as a classic
+ <script type="text/javascript"> so its listener registers before the deferred
+ @vite/client module script. An import or export here, or type="module" on that
+ tag, puts this on the same deferred queue and loses the race it exists to win. */
(() => {
if (window.__okViteRejectionGuardInstalled) return;
window.__okViteRejectionGuardInstalled = true;
diff --git a/packages/app/src/components/AssetPreview.dom.test.tsx b/packages/app/src/components/AssetPreview.dom.test.tsx
index d33da6ebc..ff9790e96 100644
--- a/packages/app/src/components/AssetPreview.dom.test.tsx
+++ b/packages/app/src/components/AssetPreview.dom.test.tsx
@@ -1,21 +1,4 @@
-/**
- * RTL behavioral tests for AssetPreview's loading-state contract. Sibling to
- * Image.dom.test.tsx — both surfaces consume the same shared `LoadingImage`
- * primitive, so the testids (`image-loading-skeleton` / `image-slot`) are
- * shared by design; distinct testids would fragment the contract for one
- * underlying primitive.
- *
- * Pins the no-intrinsic-dimensions branch: AssetPreview passes neither
- * `width` nor `height`, so the slot reserves space via an `aspect-[16/9]`
- * className rather than inline `style.width` / `style.aspectRatio` — that's
- * why test 2 below pins className, where Image.dom.test.tsx test 2 pins style.
- * The reservation is released post-load (test 3) so the consumer's
- * `object-contain / max-h-full` styling can govern the image's natural shape;
- * keeping the 16:9 class forever would letterbox portrait assets in the
- * sidebar — a regression vs. the bare `<img object-contain>` it replaces.
- *
- * Runs under `bun run test:dom` (jsdom substrate per precedent #43).
- */
+/** Runs under the jsdom substrate (precedent #43). */
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
diff --git a/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx b/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx
index ba14e2d6d..1c572b00a 100644
--- a/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx
+++ b/packages/app/src/components/AssetPreview.text-dispatch.dom.test.tsx
@@ -1,26 +1,4 @@
-/**
- * Pin the `mediaKind === 'text'` dispatch in `AssetPreview`. Cases:
- *
- * 1. Natural default — extensions in `SIDEBAR_TEXT_EXTENSIONS` (json /
- * toml) parse through `mediaKindForSidebarAssetExtension` as
- * `'text'`, and the preview pane mounts the `TextViewer` rather
- * than the generic "Open file" fallback.
- * 2. Text-viewer fallback set — `.base` / `.canvas` also resolve to
- * `mediaKind:'text'` via the separate fallback set and mount the
- * TextViewer directly (no chooser).
- * 3. Override path — the user clicks "View as text"
- * from the fallback pane (e.g. a `.zip` / `.yaml` / `.DS_Store`).
- * The local `forceText` state flips and the same preview pane
- * re-renders through the text branch.
- * 4. Negative control — `mediaKind: null` on an unknown extension
- * shows the fallback, which offers "Open file" (dispatched via
- * dispatchAssetClick, not a raw anchor) and "View as text". The
- * "Open file" must NOT be a raw <a href="/api/asset">
- * same-frame navigation — that would surface a 415/404 error envelope
- * as the page content.
- *
- * Runs under `bun run test:dom` (jsdom substrate per precedent #43).
- */
+/** Runs under the jsdom substrate (precedent #43). */
import { cleanup, fireEvent, render } from '@testing-library/react';
import { afterEach, describe, expect, test, vi } from 'vitest';
diff --git a/packages/app/src/components/DiffViewBoundary.tsx b/packages/app/src/components/DiffViewBoundary.tsx
index 1e6f04328..bad14b3a4 100644
--- a/packages/app/src/components/DiffViewBoundary.tsx
+++ b/packages/app/src/components/DiffViewBoundary.tsx
@@ -1,26 +1,6 @@
/**
- * DiffViewBoundary — peer of the editor branch inside each `<Activity>`
- * slot of EditorActivityPool. Mounted when the active doc's
- * `lifecycle.status === 'conflict'`. Sibling to (NOT a replacement of) the
- * editor `DocumentBoundary` mount; the hybrid render tree per
+ * Sibling to (NOT a replacement of) the editor `DocumentBoundary` mount; the hybrid render tree per
* precedent #18(b) stays intact.
- *
- * Responsibilities:
- * 1. Provider-sync gating is inherited from the outer `DocumentBoundary`
- * wrap (the conditional swap happens INSIDE that boundary's children),
- * so Suspense / error scopes compose unchanged.
- * 2. Fetch `GET /api/sync/conflict-content?file=<path>&source=ytext` for
- * `ours` + `theirs`. The server's `?source=ytext` branch prefers the
- * live Y.Text snapshot for `ours` (preserves pre-conflict unflushed
- * edits) and falls back to git-index (`git show :2:`) when Y.Text
- * contains conflict markers — which happens on editor reopen because
- * the file watcher seeds Y.Text with the disk's marker bytes.
- * `theirs` always comes from `git show :3:`.
- * 3. Render `<ConflictView ours theirs base onResolve />` for both-modified
- * conflicts. ConflictView owns a Pierre UnresolvedFile instance and
- * calls onResolve with the resolved content when all hunks are accepted.
- * 4. Emit `editor-area-swap-to-diffview` / `editor-area-swap-from-diffview`
- * structured log events on mount / unmount.
*/
import type { HocuspocusProvider } from '@hocuspocus/provider';
import { Trans, useLingui } from '@lingui/react/macro';
diff --git a/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx b/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx
index 91f79676d..234f863be 100644
--- a/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx
+++ b/packages/app/src/components/DocumentErrorBoundary.dom.test.tsx
@@ -1,9 +1,6 @@
/**
- * RTL mount tests for the DocumentErrorBoundary contract:
- * fallback render on throw, retry-handler invalidation. Exercises `render`
- * + `userEvent` under the jsdom substrate (precedent #43); invocation via
- * `bun run test:dom`. Throw injection follows the MaybeThrow Pattern C
- * documented in precedent #43(d).
+ * Exercises `render` + `userEvent` under the jsdom substrate (precedent #43). Throw injection
+ * follows the MaybeThrow Pattern C documented in precedent #43(d).
*/
import type { OkBugReportCreateResult } from '@inkeep/open-knowledge-core';
diff --git a/packages/app/src/components/EditorActivityPool.tsx b/packages/app/src/components/EditorActivityPool.tsx
index b9d38e3c8..f4395a1c8 100644
--- a/packages/app/src/components/EditorActivityPool.tsx
+++ b/packages/app/src/components/EditorActivityPool.tsx
@@ -81,50 +81,12 @@ const TextDocEditor = lazy(async () => ({
}));
/**
- * Large-doc threshold in Y.Text characters. Above this, the non-active editor
- * is defer-mounted on cold load instead of pre-mounting both per
- * precedent #18(b)'s small-to-medium-doc default. Once the user toggles to
- * the deferred mode, that editor mounts and stays mounted — so subsequent
- * toggles remain CSS-only and cost nothing.
- *
- * Value rationale (500_000 chars ≈ 500 KB plain text):
- * - README.md / AGENTS.md / CLAUDE.md (≤150 KB) — BELOW. No change from
- * pre-mount-both default; toggle stays instant.
- * - perf-fixtures/big-doc.md (3.25 MB, generated) — ABOVE. Cold load skips the non-active
- * editor's initial mount+parse; first toggle pays the cost; subsequent
- * toggles are instant.
- *
- * The threshold is a tuning knob, not a contract. Moving it UP regresses
- * the fix for smaller "large" docs; moving it DOWN unnecessarily delays
- * first-toggle UX for medium docs where pre-mount-both was already fast
- * enough.
- *
- * FIRST-TOGGLE COST: On a 3.25 MB doc, the first mode toggle after cold
- * load pays the deferred editor's cold mount — measured at
- * `toSourceMs ≈ 223 ms`. Proportional scaling to a ~9.7 MB doc puts first
- * toggle in the 500–800 ms range. Perceptible but well below the ~1 s
- * hang threshold. Subsequent toggles remain CSS-only. Future engineers:
- * do not assume defer-mount is free at the toggle boundary; it trades
- * cold-load latency for one-time first-toggle latency on the deferred
- * mode. See `ACTIVITY_MOUNT_LIMIT` — both constants are parts of
- * the same Activity-mount hygiene pattern.
+ * Above this, the non-active editor is defer-mounted on cold load instead of pre-mounting both per
+ * precedent #18(b)'s small-to-medium-doc default.
*/
export const LARGE_DOC_CHAR_THRESHOLD = readNumericOverride('LARGE_DOC_CHAR_THRESHOLD', 500_000);
-/**
- * Pure helper — given the doc size and the current mode-visit history,
- * compute which editors should be rendered.
- *
- * Below the threshold: always both (pre-mount-both, precedent #18(b) default).
- * Above the threshold: only modes that have been visited at least once.
- * Active mode is ALWAYS considered visited for the purpose of this computation,
- * so the call site never sees `renderSource=false && renderVisual=false`.
- *
- * `isLarge` surfaces the threshold branch taken so the caller can emit an
- * `ok/activity/defer-mount` mark for observability. It is NOT load-bearing
- * for the gating decision itself — always derive render flags from this
- * helper's output.
- */
+/** Below the threshold: always both (pre-mount-both, precedent #18(b) default). */
interface EditorMountGateArgs {
ytextLength: number;
isSourceMode: boolean;
@@ -189,48 +151,8 @@ export function computeIsNewDoc(args: {
}
/**
- * Minimum number of editors mounted concurrently inside `<Activity>`
- * boundaries. Decoupled from `MAX_POOL` (exported from `provider-pool.ts`,
- * default 10) per precedent #18(c): every visible split-pane document is
- * mandatory, then MRU hidden documents fill this warm floor. Pool-resident
- * docs outside that list keep their warm provider (so revisiting is fast via
- * Suspense-gated remount with `syncPromise` resolving immediately from
- * `hasSynced=true`) but skip the per-editor memory + observer-CPU cost of
- * keeping the TipTap + CodeMirror instances alive.
- *
- * 3 covers the "alt-tab between recent docs" pattern dominant for the
- * primary personas.
- *
- * Changing either this value or `MAX_POOL` is an ASK_FIRST boundary — they're
- * coupled by design. If one moves, audit the other for sympathetic impact.
- *
- * **LIMIT=3 is a stable decision, not a temporary holdpoint.** Both the
- * TipTap-editor-cost argument (LIMIT=1 doesn't avoid `createEditor` cost
- * because `@tiptap/react`'s `useEditor` destroys on effect-cleanup anyway)
- * and the scroll-state argument (scroll preservation requires refs to
- * survive, which requires Activity hidden not full unmount) stand
- * independently of the V2 editor cache. A module-level editor cache changes
- * the first argument's mechanics but not the second — LIMIT stays at 3 to
- * keep ScrollPreservingContainer's `useRef` alive across navigation.
- *
- * Reducing this value to 1 was attempted as a warm-switch fix, then
- * REVERTED — LIMIT=1 broke scroll-position survival across A→B→A because
- * `ScrollPreservingContainer` stores its saved scrollTop in a `useRef`, and
- * refs persist across `<Activity>` mode flips but are lost on full unmount.
- * With LIMIT=3, ScrollPreservingContainer stays mounted for non-active docs
- * (effects paused via Activity-hidden; ref state preserved), so revisiting
- * restores scroll position. With LIMIT=1, the container unmounts on nav and
- * the ref is destroyed. TipTap editor state WAS being destroyed regardless
- * (its `useEditor` schedules destroy on effect-cleanup, so LIMIT=3 + hidden
- * transition = same destroy path as LIMIT=1 + unmount), but scroll state was
- * load-bearing. Conclusion: warm-switch latency is architecturally bounded
- * by TipTap's `createEditor` overhead (~350 ms schema + Yjs bind + DOM attach,
- * fixed cost regardless of doc size or `ACTIVITY_MOUNT_LIMIT`); unlocking
- * <100 ms warm-switch requires a module-level Editor cache outside React's
- * lifecycle.
- *
- * See `LARGE_DOC_CHAR_THRESHOLD` — both constants are parts of the same
- * Activity-mount hygiene pattern (precedent #18(c) / precedent #24).
+ * `ACTIVITY_MOUNT_LIMIT` and `MAX_POOL` in `provider-pool.ts` are coupled by design; changing
+ * either requires auditing the other (precedent #18(c) / precedent #24).
*/
export const ACTIVITY_MOUNT_LIMIT = readNumericOverride('ACTIVITY_MOUNT_LIMIT', 3);
@@ -394,7 +316,10 @@ function EditorActivityPoolInner({
evicted,
});
priorMountKeyRef.current = mountKey;
- // cached-but-not-Activity-mounted editors (precedent #27(b)). Bounds
+ /**
+ * Drives provider connect/disconnect for cached-but-not-Activity-mounted editors, bounding
+ * remote-peer CRDT load to the top ACTIVITY_MOUNT_LIMIT (precedent #27(b)).
+ */
setActivityMountList(mounted);
}, [mountKey, activeDocName]);
@@ -815,7 +740,10 @@ function ActivityEntry({
}: ActivityEntryProps) {
const recoveryView = getServerRestartRecoveryView(entry.docName, serverRestartRecovery);
- // (preserving precedent #18(b)'s hybrid render tree — Suspense + error
+ /**
+ * A conflicted doc swaps the editor children for the diff view inside the same
+ * DocumentBoundary, preserving precedent #18(b)'s hybrid render tree.
+ */
const lifecycleStatus = useLifecycleStatus(entry.docName);
const isConflict = lifecycleStatus === 'conflict';
const isMermaid = isMermaidDocFile(entry.docName);
@@ -831,7 +759,7 @@ function ActivityEntry({
const bodyAnchorRef = useRef<HTMLDivElement>(null);
- // Small/medium docs keep pre-mount-both (precedent #18(b) default): mode swap
+ /** Small and medium docs keep pre-mount-both, the precedent #18(b) default. */
const ytextLength = entry.provider.document.getText('source').length;
const [lastVisibleIsSourceMode, setLastVisibleIsSourceMode] = useState(isSourceMode);
@@ -953,22 +881,20 @@ function ActivityEntry({
>
<DocumentBoundary docName={entry.docName} provider={entry.provider}>
{isConflict ? (
- /* While `lifecycle.status === 'conflict'` the
- DiffViewBoundary replaces the editor children. The
- outer DocumentBoundary's syncPromise gate + the
- Suspense/error scopes above stay intact (precedent
- #18(b) hybrid render tree preserved — we swap children,
- not boundaries). Y.Doc identity is unchanged across
- the swap, so Y.Text content + undo history survive. */
+ /*
+ * The outer DocumentBoundary's syncPromise gate + the Suspense/error scopes
+ * above stay intact (precedent #18(b) hybrid render tree preserved — we swap
+ * children, not boundaries).
+ */
<Suspense fallback={<EditorSkeleton />}>
<LazyDiffViewBoundary docName={entry.docName} provider={entry.provider} />
</Suspense>
) : isMermaid ? (
- /* Standalone Mermaid doc: dedicated diagram (wysiwyg) + editable
- source editor, both bound to this doc's Y.Text('source').
- Swaps the editor CHILDREN inside the same DocumentBoundary
- (like the conflict branch above) so the precedent #18(b)
- hybrid render tree + Y.Doc identity are preserved. */
+ /*
+ * Swaps the editor CHILDREN inside the same DocumentBoundary (like the conflict
+ * branch above) so the precedent #18(b) hybrid render tree + Y.Doc identity are
+ * preserved.
+ */
<MermaidDocEditor
docName={entry.docName}
provider={entry.provider}
diff --git a/packages/app/src/components/EditorBreadcrumb.dom.test.tsx b/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
index c824f282b..1a7566d82 100644
--- a/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
+++ b/packages/app/src/components/EditorBreadcrumb.dom.test.tsx
@@ -1,14 +1,5 @@
/**
- * RTL behavioral tests for EditorBreadcrumb.
- *
- * Pins the rendered shape the source-grep `.test.ts` companion can't
- * cheaply assert: which segments render for which paths, that the
- * separator only appears BETWEEN segments (not before the first one),
- * that root-level docs render nothing, and that the per-segment title
- * tooltip carries the full segment text for truncation reveal.
- *
- * Exercises `render` under the jsdom substrate (precedent #43); invocation
- * via `bunx turbo run test:dom`.
+ * Exercises `render` under the jsdom substrate (precedent #43).
*/
import { cleanup, render, screen } from '@testing-library/react';
diff --git a/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx b/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
index 5e2b63110..823add82a 100644
--- a/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
+++ b/packages/app/src/components/FileTree.selection-mirror.dom.test.tsx
@@ -1,20 +1,4 @@
-/**
- * RTL behavioral counterpart to the source-grep
- * `FileTree.selection-mirror.test.ts`. Pins the singleton-selection invariant
- * at runtime through the extracted
- * `useSelectionMirror` hook.
- *
- * The full FileTree component requires 8+ contexts plus Pierre shadow DOM,
- * which exceeds the <500ms budget. This test exercises the hook
- * directly with a minimal stub that satisfies the model interface
- * (`getItem`, `getSelectedPaths`) plus the per-item handles the hook calls
- * (`getPath`, `isSelected`, `select`, `deselect`, `isExpanded`, `expand`,
- * `focus`). Production callers always pass real Pierre models — the cast
- * through `unknown` makes that boundary explicit.
- *
- * Exercises `render` + `userEvent` under the jsdom substrate (precedent #43);
- * invocation via `bun run test:dom`.
- */
+/** Exercises `render` + `userEvent` under the jsdom substrate (precedent #43). */
import { cleanup, render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
diff --git a/packages/app/src/components/FileTreeFilteredToZeroNotice.dom.test.tsx b/packages/app/src/components/FileTreeFilteredToZeroNotice.dom.test.tsx
index 213a89c87..0cbd74d74 100644
--- a/packages/app/src/components/FileTreeFilteredToZeroNotice.dom.test.tsx
+++ b/packages/app/src/components/FileTreeFilteredToZeroNotice.dom.test.tsx
@@ -1,12 +1,4 @@
-/**
- * Behavioral tests for the filtered-to-zero tree notice: the reset action's
- * config payload (tree-content toggles to defaults, Skills section untouched),
- * the disabled state while the project-local binding is unavailable, and the
- * rejection toast — the same write-path contract as every other sidebar
- * visibility surface.
- *
- * Runs under `bun run test:dom` (jsdom substrate per precedent #43).
- */
+/** Runs under the jsdom substrate (precedent #43). */
import * as actualLinguiMacro from '@lingui/react/macro';
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
diff --git a/packages/app/src/components/GraphPanel.tsx b/packages/app/src/components/GraphPanel.tsx
index b45dfd750..97b712a52 100644
--- a/packages/app/src/components/GraphPanel.tsx
+++ b/packages/app/src/components/GraphPanel.tsx
@@ -424,23 +424,10 @@ export function GraphPanel({ activeDocName }: { activeDocName: string }) {
isExpanded && isElectronHost && '[-webkit-app-region:drag]',
)}
>
- {/* Fullscreen header anatomy (expanded only):
- • `pl-[var(--ok-titlebar-reserve-left,1rem)]` reserves the macOS
- traffic-light footprint on the chrome row (precedent #49). The
- arbitrary `pl-` wins over PanelHeader's base `px-4` by Tailwind
- emit order (measured: resolves to 78px under electron-mode); the
- `,1rem` fallback keeps web layout at the base `px-4`. Because `pl-`
- *replaces* the base `px-4` rather than stacking on it, 78px alone
- leaves the title touching the buttons — the title cluster adds
- `ml-4` below for the 16px of breathing room (94px total, measured).
- • `mt-2 h-12 py-0` land the row on the editor chrome midline: the
- overlay is pinned to the whole window, so it starts at the raw
- window top, 8px above EditorHeader's SidebarInset-`m-2` band.
- `mt-2` reproduces that inset, `h-12` matches the 48px band, `py-0`
- drops the inherited `py-3` so content centers in the full band —
- title at y=32, exactly where the traffic lights are tuned (measured).
- • Electron: the header row is the window-drag region (so graph mode
- stays draggable); the controls cluster opts back out below. */}
+ {/**
+ * The fullscreen chrome row reserves the macOS traffic-light footprint via
+ * `--ok-titlebar-reserve-left` (precedent #49).
+ */}
<div
data-slot="graph-title-cluster"
className={cn('flex min-w-0 items-center gap-1.5', isExpanded && 'ml-4')}
diff --git a/packages/app/src/components/InteractionPropPanel.tsx b/packages/app/src/components/InteractionPropPanel.tsx
index c1d7dac38..562343759 100644
--- a/packages/app/src/components/InteractionPropPanel.tsx
+++ b/packages/app/src/components/InteractionPropPanel.tsx
@@ -1,27 +1,6 @@
/**
- * InteractionPropPanel — shared primitive for InteractionLayer PropPanels.
- *
- * Wraps shadcn `Popover` (Radix Popover) with a virtual anchor that tracks
- * the active chip's bounding rect via `@floating-ui/dom` `autoUpdate`. We
- * can't use `<PopoverTrigger>` directly because chips render as plain DOM
- * (precedent #18 — 768 React portals collapses
- * to one singleton). Instead, a zero-pointer-events `<PopoverAnchor>` span
- * follows the chip's rect; Radix anchors `<PopoverContent>` to it with
- * built-in flip + shift collision handling and focus management.
- *
- * **Trigger model:** open state is controlled externally by the
- * InteractionLayer's hover/focus state machine — chips don't toggle the
- * popover directly. The layer calls `store.setActiveNode(id)` from
- * pointerover/focusin/long-press; Radix sees `open=true` and mounts content.
- * Radix's own `onInteractOutside` / Escape handling routes to
- * `onOpenChange(false)` → `onDeactivate()` → `setActiveNode(null)`.
- *
- * **Focus discipline:** `onOpenAutoFocus={(e) => e.preventDefault()}` keeps
- * focus on the originating chip when the popover opens via hover. Keyboard
- * focus into the popover is driven by the layer's Tab interception (see
- * `interaction-layer.tsx`) so the chip stays the keyboard tabstop.
- * `onCloseAutoFocus={(e) => e.preventDefault()}` lets our own focus-
- * restoration in the layer handle the post-close target.
+ * We can't use `<PopoverTrigger>` directly because chips render as plain DOM (precedent #18 — 768
+ * React portals collapses to one singleton).
*/
import { autoUpdate, type VirtualElement } from '@floating-ui/dom';
diff --git a/packages/app/src/components/MermaidDocEditor.tsx b/packages/app/src/components/MermaidDocEditor.tsx
index 8781df7c9..669da2203 100644
--- a/packages/app/src/components/MermaidDocEditor.tsx
+++ b/packages/app/src/components/MermaidDocEditor.tsx
@@ -1,23 +1,7 @@
/**
- * Editor for a standalone Mermaid doc (`.mmd` / `.mermaid`). These are real
- * Y.Text('source')-only CRDT docs (the markdown bridge is gated off server-side
- * — see `isMermaidDoc`), so both panes bind to the same `Y.Text` and stay in
- * sync live:
- *
- * - Diagram (wysiwyg) mode → the editor's `<MermaidView>` with an `editBinding`
- * that splices click-to-edit label changes back into `Y.Text` — exact parity
- * with codefenced ` ```mermaid ` editing.
- * - Source mode → an editable CodeMirror bound to the same `Y.Text` via
- * `yCollab`, with real Mermaid syntax highlighting (`codemirror-lang-mermaid`,
- * already in the editor bundle) on the shared `propEditorHighlight` style.
- *
- * Driven by the global `isSourceMode` (the toolbar's wysiwyg/source toggle):
- * for a diagram doc, "wysiwyg" == the rendered, editable diagram — consistent
- * with the app's rendered-vs-raw mental model, so no bespoke toggle is needed.
- *
- * Mounted by `EditorActivityPool` inside the doc's `DocumentBoundary` (peer to
- * the conflict `DiffViewBoundary` branch), so `provider` is sync-gated and the
- * precedent #18(b) hybrid render tree is preserved.
+ * Mounted by `EditorActivityPool` inside the doc's `DocumentBoundary` (peer to the conflict
+ * `DiffViewBoundary` branch), so `provider` is sync-gated and the precedent #18(b) hybrid render
+ * tree is preserved.
*/
import { syntaxHighlighting } from '@codemirror/language';
diff --git a/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx b/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx
index 42bc8140b..2642c29ba 100644
--- a/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx
+++ b/packages/app/src/components/NotInSidebarIndicator.dom.test.tsx
@@ -1,11 +1,4 @@
-/**
- * Behavioral tests for the not-in-sidebar indicator: per-axis attribution
- * rendering, per-axis flip patches, recompute after a flip that leaves the
- * doc hidden by the other axis, and the silent cases (visible docs, skills /
- * templates / `.ok` docs, which never have a row the toggles govern).
- *
- * Runs under `bun run test:dom` (jsdom substrate per precedent #43).
- */
+/** Runs under the jsdom substrate (precedent #43). */
import type { Config } from '@inkeep/open-knowledge-core';
import * as actualLinguiMacro from '@lingui/react/macro';
diff --git a/packages/app/src/components/OutlinePanel.tsx b/packages/app/src/components/OutlinePanel.tsx
index efa94a48f..780598115 100644
--- a/packages/app/src/components/OutlinePanel.tsx
+++ b/packages/app/src/components/OutlinePanel.tsx
@@ -29,10 +29,9 @@ import { ProfilerBoundary } from '@/lib/perf';
import { cn } from '@/lib/utils';
/**
- * Debounce window for Y.Doc update → page-headings invalidation. Matches the
- * `TYPING_DEFER_MS` convention from precedent #11 — a 300 ms trailing-edge
- * window coalesces bursts of keystrokes into a single fetch while still
- * updating the outline fast enough to feel live.
+ * Matches the `TYPING_DEFER_MS` convention from precedent #11 — a 300 ms trailing-edge window
+ * coalesces bursts of keystrokes into a single fetch while still updating the outline fast enough
+ * to feel live.
*/
const OUTLINE_INVALIDATE_DEBOUNCE_MS = 300;
diff --git a/packages/app/src/components/PageHeader.tsx b/packages/app/src/components/PageHeader.tsx
index 53f3ea103..0e77a510d 100644
--- a/packages/app/src/components/PageHeader.tsx
+++ b/packages/app/src/components/PageHeader.tsx
@@ -1,38 +1,7 @@
/**
- * PageHeader — the cover banner + page-icon surface above the editor body.
- *
- * Reads `icon` + (`banner` ?? `cover`) from the document's frontmatter
- * (Y.Text('source') YAML region) via the same `bindFrontmatterDoc` binding
- * `PropertyPanel` uses. `banner` (Obsidian convention) is preferred over
- * `cover` (Notion convention) — vaults imported from either substrate render
- * without a rename. When only one is set, that key wins.
- *
- * Vertical focal position (`banner_y` / `cover_y`, 0.0–1.0) rides on the
- * source key. A drag interaction on the cover updates the paired `_y` key —
- * commit-on-release, single CRDT write per drag.
- *
- * Renders three states (driven by which frontmatter keys resolve to
- * supported values per `page-header-utils.ts`):
- *
- * 1. **cover + icon**: full-width cover banner; icon overlays the bottom-
- * left of the cover (Notion-style — half the icon sits on top of the
- * cover, half hangs below into the property panel's gutter).
- * 2. **cover only**: just the banner.
- * 3. **icon only**: a small icon row above the property panel (no
- * banner).
- * 4. **neither**: render nothing — zero layout shift for docs that
- * don't opt in.
- *
- * Mount site: `EditorActivityPool`'s per-document column, BETWEEN
- * `DocumentBoundary` and `PropertyPanel`, so the cover/icon shares the
- * Y.Doc lifecycle of the open document AND scrolls with the editor
- * body (precedent #18(b) — keep all per-doc UI inside the boundary).
- *
- * The H1 inside the TipTap body remains the document's actual title —
- * assistive tech sees the drag slider (a real interactive control with
- * `role="slider"` + keyboard support) as the only exposed element in this
- * region; the decorative cover image and icon are unnamed `<img>` tags with
- * empty alt.
+ * Mount site: `EditorActivityPool`'s per-document column, BETWEEN `DocumentBoundary` and
+ * `PropertyPanel`, so the cover/icon shares the Y.Doc lifecycle of the open document AND scrolls
+ * with the editor body (precedent #18(b) — keep all per-doc UI inside the boundary).
*/
import type { HocuspocusProvider } from '@hocuspocus/provider';
diff --git a/packages/app/src/components/TextDocEditor.tsx b/packages/app/src/components/TextDocEditor.tsx
index c67009bf6..ef30f1a75 100644
--- a/packages/app/src/components/TextDocEditor.tsx
+++ b/packages/app/src/components/TextDocEditor.tsx
@@ -1,24 +1,6 @@
/**
- * Editor for an editable text doc (`.ts` / `.json` / `.css` / `.txt` / … —
- * see `EDITABLE_TEXT_FILE_EXTENSIONS`). These are verbatim
- * Y.Text('source')-only CRDT docs, the same doc class as standalone Mermaid
- * docs (markdown bridge gated off server-side; bytes stored verbatim), so a
- * plain-text file edits like a normal IDE buffer: CodeMirror bound to the
- * shared `Y.Text` via `yCollab`, collaborative cursors included.
- *
- * Language highlighting resolves lazily from the file extension through the
- * same `text-viewer-languages` loader the read-only asset `TextViewer` uses —
- * grammars stay out of the main bundle and unknown extensions fall back to
- * plain text.
- *
- * There is no wysiwyg mode for a code file, so the editor renders the same
- * CodeMirror surface regardless of the global source-mode toggle (mirrors how
- * a diagram doc treats "wysiwyg" as its rendered form; here source IS the
- * only form).
- *
- * Mounted by `EditorActivityPool` inside the doc's `DocumentBoundary` (peer
- * to the MermaidDocEditor branch), so `provider` is sync-gated and the
- * precedent #18(b) hybrid render tree is preserved.
+ * Mounted by `EditorActivityPool` inside the doc's `DocumentBoundary` (peer to the MermaidDocEditor
+ * branch), so `provider` is sync-gated and the precedent #18(b) hybrid render tree is preserved.
*/
import { type Language, syntaxHighlighting } from '@codemirror/language';
diff --git a/packages/app/src/components/editor/SelectionAnnouncer.tsx b/packages/app/src/components/editor/SelectionAnnouncer.tsx
index 9b99f5e4f..bd90d2801 100644
--- a/packages/app/src/components/editor/SelectionAnnouncer.tsx
+++ b/packages/app/src/components/editor/SelectionAnnouncer.tsx
@@ -1,28 +1,6 @@
/**
- * SelectionAnnouncer — `aria-live="polite"` region that announces block
- * selection changes to assistive technologies (Precedent #34).
- *
- * Renders a single visually-hidden `<div role="status" aria-live="polite">`
- * whose `textContent` updates 200ms after each selection change. Debounce
- * prevents screen-reader queue flooding during rapid keyboard navigation
- * (arrow-key bursts would otherwise queue dozens of announcements).
- *
- * Imperative textContent write (not React state): React batching has been
- * observed to swallow rapid aria-live updates — the region only re-announces
- * when the DOM text actually changes. Writing imperatively via ref gives
- * AT a clean mutation to latch onto every time.
- *
- * Message format:
- * - ancestorChain.length === 1: "Selected: Card"
- * - ancestorChain.length > 1: "Selected: Step, 2 of 4 in Steps"
- * - selection cleared after a non-empty selection: "Outside any block"
- * (prevents AT silence on arrow-out — users would otherwise have no
- * audible cue that they have left the prior selected block)
- * - no selection at mount: "" (don't announce on initial load)
- *
- * The index-in-parent is derived from the PM doc at read time: we use the
- * selected wrapper's pos and its parent's childCount. This is cheap; the
- * computation runs once per debounce tick, not per render.
+ * SelectionAnnouncer — `aria-live="polite"` region that announces block selection changes to
+ * assistive technologies (Precedent #34).
*/
import type { Editor } from '@tiptap/core';
diff --git a/packages/app/src/components/settings/SettingsDialogErrorBoundary.dom.test.tsx b/packages/app/src/components/settings/SettingsDialogErrorBoundary.dom.test.tsx
index 1d192db79..370e1fb1a 100644
--- a/packages/app/src/components/settings/SettingsDialogErrorBoundary.dom.test.tsx
+++ b/packages/app/src/components/settings/SettingsDialogErrorBoundary.dom.test.tsx
@@ -1,13 +1,4 @@
-/**
- * RTL mount tests for SettingsDialogErrorBoundary: the containment
- * contract for a failed lazy Settings-body chunk. Without this boundary a
- * `React.lazy` dynamic-import rejection propagates to the React root and
- * unmounts the whole app (white screen, unrecoverable). These tests pin
- * that (a) the fallback renders on a child throw and (b) a sibling
- * rendered OUTSIDE the boundary stays mounted — i.e. the failure is
- * contained, the app survives. Throw injection follows the MaybeThrow
- * (precedent #43(d)); invocation via `bun run test:dom`.
- */
+/** Throw injection follows the MaybeThrow (precedent #43(d)). */
import { cleanup, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
diff --git a/packages/app/src/components/ui/sidebar.partition.dom.test.tsx b/packages/app/src/components/ui/sidebar.partition.dom.test.tsx
index 8195c4f89..0ae2fd6cd 100644
--- a/packages/app/src/components/ui/sidebar.partition.dom.test.tsx
+++ b/packages/app/src/components/ui/sidebar.partition.dom.test.tsx
@@ -1,20 +1,4 @@
-/**
- * RTL behavioral tests for SidebarProvider's responsive partition
- * model + Per-Partition Pins store + auto-collapse focus safety.
- *
- * The companion `sidebar.test.ts` is a raw-source structural guard
- * (single-render-path, no-mobile-translate, no-sidebar_state-cookie). This
- * file mounts the provider against jsdom + RTL and asserts the runtime
- * contract those source guards can't reach:
- *
- * 1. Synchronous first-paint state from (embedded host UA × innerWidth × pin).
- * 2. matchMedia('(min-width: 1024px)') change re-resolves the partition + state.
- * 3. Auto-collapse moves focus from inside the sidebar to the toggle.
- * 4. Trigger click writes the slot for the current partition WITHOUT clearing
- * the slot for any other partition (partition-isolated memory).
- *
- * Substrate: jsdom (precedent #43); invocation via `bunx turbo run test:dom`.
- */
+/** Substrate: jsdom (precedent #43). */
import { act, cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test } from 'vitest';
diff --git a/packages/app/src/editor/TiptapEditor.tsx b/packages/app/src/editor/TiptapEditor.tsx
index eecccab26..0d7a852b7 100644
--- a/packages/app/src/editor/TiptapEditor.tsx
+++ b/packages/app/src/editor/TiptapEditor.tsx
@@ -398,34 +398,9 @@ export function buildPatternDConstructorOptions(
}
/**
- * TiptapEditor — Pattern D (Suspense + `use(promise)`) mount path. The only
- * editor mount path in the app; precedent #18(d) substrate is the production
- * default since the rollout retirement.
- *
- * Editor reference is stable from render 1: `use(mountTiptapEditorPromise(...))`
- * suspends until the editor is constructed AND mounted (mount-promise.ts owns
- * `await scheduler.yield()` → `new Editor({element: null})` →
- * `await scheduler.yield()` → `editor.mount(transient)`).
- * `<EditorContent>` only ever sees a fully-mounted editor — no null-state hop,
- * no `EditorContentWithKey` random-key cascade.
- *
- * Suspense fallback: the parent `EditorActivityPool` already wraps with
- * `<Suspense fallback={<EditorSkeleton/>}>` (same skeleton precedent #18(d)
- * source-mode-defer uses); user sees one atomic skeleton-to-editor transition.
- *
- * Mount failure: promise rejects → `use()` throws → `DocumentErrorBoundary`
- * catches → "Try again" recycles cache.
- *
- * Cancellation: `parkTiptapEditor(entry)` on unmount → mount-promise cache is
- * preserved across V2-admit park (so warm reopen returns the same resolved
- * promise reference and `use()` short-circuits without Suspense). On
- * V2-refuse park or kill-switch, `invalidateMountPromise(docName)` aborts
- * any in-flight construction via AbortController.
- *
- * StrictMode: editor reference is stable across the dev-mode double-invoke —
- * the V2 cache HIT path on remount returns the same parked entry, and
- * mount-promise's module-level cache returns the same promise reference within
- * a single mount lifecycle.
+ * The only editor mount path in the app: Suspense plus `use(mountTiptapEditorPromise(...))` per
+ * precedent #18(d), so `<EditorContent>` only ever sees a fully mounted editor and a mount
+ * failure surfaces through `DocumentErrorBoundary`.
*/
export const TiptapEditor: FC<TiptapEditorProps> = ({
provider,
@@ -1239,19 +1214,9 @@ const TiptapEditorChrome: FC<TiptapEditorChromeProps> = ({
)}
{}
<SelectionAnnouncer editor={editor} />
- {/*
- * <InteractionLayerView> renders the singleton PropPanel / Toolbar /
- * Breadcrumb subtree FOR THE ACTIVE chip — inside the main React tree
- * so PropPanel renderers (InternalLinkPropPanel, WikiLinkPropPanel)
- * inherit context providers like <PageListProvider> + <ThemeProvider>.
- * The layer host (per-editor WeakMap) provides the store; the View
- * subscribes via useState + subscribe and renders the active
- * registration's controls. RawMdxFallback is handled inline
- * via `RawMdxFallbackCMView` (per precedent #30 "all user content
- * visible and editable") and does not register with InteractionLayer.
- *
- * Rendered AFTER EditorContent so its absolute-positioned PropPanels
- * stack above editor content (z-index handled in CSS).
+ {/**
+ * RawMdxFallback renders inline via `RawMdxFallbackCMView` (precedent #30) and never
+ * registers with InteractionLayer.
*/}
<InteractionLayerView store={getInteractionLayer(editor).store} />
</div>
diff --git a/packages/app/src/editor/clipboard/handle-paste.ts b/packages/app/src/editor/clipboard/handle-paste.ts
index 8a254e8a5..04f2eeacc 100644
--- a/packages/app/src/editor/clipboard/handle-paste.ts
+++ b/packages/app/src/editor/clipboard/handle-paste.ts
@@ -1,69 +1,4 @@
-/**
- * WYSIWYG paste/drop dispatcher — 5-branch router per precedent #19(b).
- *
- * Branch A: `vscode-editor-data` MIME → fenced code block with language.
- * Branch B: `text/x-gfm` MIME → MarkdownManager.parse (markdown path).
- * Markdown-first ambiguity tiebreak: both text/plain (markdown-shaped) and
- * text/html present → MarkdownManager.parse on text/plain. Runs
- * BEFORE Branch C so OK→OK paste of JSX descriptors (`<img/>`,
- * `<Callout>`) routes through the canonical text/plain markdown
- * path and preserves descriptor identity, instead of falling to
- * PM-native parseFromClipboard where TipTap's parseDOM rules can
- * win over `jsxComponent`.
- * Branch C: HTML contains `data-pm-slice` → PM native parseFromClipboard
- * (return false and let PM handle). Cross-PM-editor interop:
- * Linear/Outline/BlockNote also emit canonical markdown to
- * text/plain, so the markdown-first tiebreak above catches them
- * with equivalent results — Branch C remains the fallback for
- * PM payloads whose text/plain isn't markdown-shaped.
- * Branch D: generic HTML → htmlToMdast → remark-stringify → MarkdownManager.parse.
- * Branch E: text/plain only → markdown-first if isMarkdown threshold hit;
- * else verbatim plain-text insert.
- *
- * Placement: the markdown branches insert the re-parsed JSON as a closed
- * slice, EXCEPT when the caret is inside a list item — then a list-aware
- * splice runs instead of letting the fitter nest or orphan the content
- * (issue #609). All-list payloads splice as item siblings at the caret's
- * list level (`buildListSiblingSpliceTr`); mixed payloads split the list at
- * the caret and place non-list blocks as siblings of the list itself
- * (`buildMixedSiblingSpliceTr`).
- *
- * codeBlock short-circuit: cursor inside a codeBlock → skip all branches,
- * insert text/plain verbatim.
- *
- * Lone-URL step: after those two gates and before the MIME branches, a
- * payload whose text/plain is a single URL token linkifies instead of
- * falling into the branch tree. Over a one-block text selection the
- * selected text is kept and link-marked (trust-the-gesture policy — see
- * lone-url.ts); at a cursor only GFM autolink shapes convert, routed
- * through MarkdownManager.parse so the mark and bytes are exactly what the
- * pipeline itself produces. Everything else falls through unchanged. The
- * step runs before Branch A/D so a browser link-copy (which also carries
- * text/html) converts the selection rather than replacing it.
- *
- * Every dispatcher-minted transaction carries `preventAutolink` meta:
- * paste output is never re-scanned by the typed-autolink plugin, so a URL
- * inside pasted prose stays exactly as pasted.
- *
- * Cmd+Shift+V (paste): detected via `pasteShiftHeld(event)` which checks
- * the most-recent keyboard event (real browsers don't set `shiftKey` on
- * ClipboardEvent) plus a Playwright-test-style injected property. Drop
- * surface reads `shiftKey` directly off the DragEvent (DragEvent extends
- * MouseEvent → modifier flags are first-class).
- *
- * Drop surface: `createHandleDrop` runs the same dispatcher against
- * `event.dataTransfer`. Drag-from-Finder of any file (.md or otherwise)
- * carries `dataTransfer.files` — that path is owned by the FileHandler
- * extension's `onDrop` callback (`extensions/shared.ts`); the dispatcher
- * defers by returning `false` whenever files are present so PM continues
- * to the next handler.
- *
- * Error-path: every conversion call is try/caught; on throw, fall through
- * to the next layer, never silently drop content. Per-stage telemetry
- * emitted as structured `clipboard-html-conversion-fail` events so log
- * aggregators see which stage failed instead of a single bracket-prefixed
- * string.
- */
+/** WYSIWYG paste/drop dispatcher — 5-branch router per precedent #19(b). */
import type { MarkdownManager } from '@inkeep/open-knowledge-core';
import { htmlToMdast, mdastToMarkdown } from '@inkeep/open-knowledge-core';
diff --git a/packages/app/src/editor/clipboard/source-clipboard.ts b/packages/app/src/editor/clipboard/source-clipboard.ts
index 6dc39a7cc..f3bd2721a 100644
--- a/packages/app/src/editor/clipboard/source-clipboard.ts
+++ b/packages/app/src/editor/clipboard/source-clipboard.ts
@@ -1,39 +1,7 @@
/**
- * Source-view clipboard extension — `EditorView.domEventHandlers` for copy,
- * cut, and paste per precedent #19(c).
- *
- * CodeMirror 6 has no equivalent to PM's `clipboardTextSerializer` /
- * `clipboardSerializer` hooks, so we override the DOM events directly.
- * This is the only view where DOM-level override is acceptable (WYSIWYG
- * uses PM's hooks instead per precedent #19(b)). User-facing behavior is
- * symmetric across both views:
- *
- * - Copy/cut write text/plain = markdown source AND text/html =
- * source-shaped HTML wrapper (via `buildSourceModeHtml` — a
- * `<pre class="mdx-component"><code>` envelope, NOT rendered output).
- *
- * - Paste routes through a branch dispatcher parallel to WYSIWYG paste,
- * except source-mode never upgrades editor-origin text into a fenced code
- * block. Source's insertion IS markdown text, so the
- * source-wrapper tiebreak (Branch B-wrapper), the markdown-first
- * tiebreak (Branch B), the Branch C `data-pm-slice` check, and Branch E
- * all resolve to "let CM6 default text/plain verbatim insert run";
- * Branch D remains the converter for generic HTML.
- * The dispatcher's value here is structural, not behavioral. The
- * tiebreak fires AHEAD of Branch C and Branch D for the narrow case
- * where external markdown carries a rich-HTML preview; without it
- * Branch D's `htmlToMdast` would normalize bytes that the user pasted
- * as canonical markdown.
- *
- * - Cmd+Shift+V detected via `pasteShiftHeld(event)` (keyboard-event
- * tracker — ClipboardEvent does not expose shiftKey natively).
- *
- * - Large-paste chunked insert: payloads >500KB bypass the CM6 dispatch
- * and land via `chunkedYTextInsert` directly. A Y.RelativePosition is
- * pinned before the first chunk so concurrent peers writing at offsets
- * ≤ writeIndex during rAF yields do not shift the target. Mid-stream
- * failure surfaces as a structured `clipboard-chunked-insert-failed`
- * event with partial-progress fields.
+ * Source-view clipboard extension — `EditorView.domEventHandlers` for copy, cut, and paste per
+ * precedent #19(c). This is the only view where DOM-level override is acceptable (WYSIWYG uses PM's
+ * hooks instead per precedent #19(b)).
*/
import type { Extension } from '@codemirror/state';
diff --git a/packages/app/src/editor/components/Accordion.tsx b/packages/app/src/editor/components/Accordion.tsx
index ad47c50db..a6c0cdc5d 100644
--- a/packages/app/src/editor/components/Accordion.tsx
+++ b/packages/app/src/editor/components/Accordion.tsx
@@ -1,35 +1,7 @@
/**
- * Accordion — DIY renderer for the 5-pack foundation.
- *
- * Standalone expand/collapse via native HTML5 `<details>`/`<summary>` — no
- * `<Accordions>` parent wrapper required. Renders the descriptor's 6-prop
- * surface: `title` (required), `defaultOpen`, `icon` (namespaced lucide),
- * `description`, `id`, `name` (for HTML5 exclusive-accordion grouping), plus
- * `children` (PM-managed NodeViewContent slot).
- *
- * ── Constraints (load-bearing) ───────────────────────────────
- *
- * - NO `variant` prop → Notion color-map absorption deferred.
- * - STANDALONE → no parent wrapper required. Exclusive grouping via HTML5
- * `<details name="group">` (Chrome 120+, Safari 17.2+, Firefox 130+);
- * siblings sharing a name auto-close each other on open.
- * - HTML5 native collapse/expand → no JS state, no Radix-style animation
- * machine, no toggle handler. Rotation on open/close via CSS transform
- * keyed on the `[open]` attribute.
- * - Matches Mintlify Accordion surface + HTML5 `name` attr; diverges from
- * Fumadocs's Radix-requires-parent pattern.
- *
- * ── `children` semantics ─────────────────────────────────────────────────────
- *
- * `hasChildren: true` on the descriptor. The summary carries icon + title +
- * optional description as non-editable chrome (contentEditable=false). Body
- * renders inside `.accordion-body` unconditionally — browsers display:none
- * the content when `[open]` is unset, but PM's DOM is retained so children
- * stay live per Precedent #30 (all user content visible / editable).
- *
- * Zero upstream-docs-lib React imports — all styling flows
- * through the `[data-component-type="accordion"]` selector in globals.css
- * with OK shadcn semantic tokens.
+ * Body renders inside `.accordion-body` unconditionally — browsers display:none the content when
+ * `[open]` is unset, but PM's DOM is retained so children stay live per Precedent #30 (all user
+ * content visible / editable).
*/
import { ChevronRight } from 'lucide-react';
diff --git a/packages/app/src/editor/components/Callout.tsx b/packages/app/src/editor/components/Callout.tsx
index 9bd392687..35a037509 100644
--- a/packages/app/src/editor/components/Callout.tsx
+++ b/packages/app/src/editor/components/Callout.tsx
@@ -1,38 +1,6 @@
/**
- * Callout — DIY renderer for the 15-type callout system (5 GFM + 10
- * Obsidian-parity).
- *
- * Renders the descriptor's 7-prop surface: `type` (15-value enum),
- * `title`, `icon` (namespaced lucide), `color` (hex accent override),
- * `collapsible`, `defaultOpen`, and `children` (the PM-managed
- * NodeViewContent slot).
- *
- * Two render branches:
- *
- * 1. Static (collapsible !== true): flex container with a left-border accent,
- * type-inferred icon, optional title row, and the body.
- *
- * 2. Collapsible (collapsible === true): native HTML5 <details>/<summary>.
- * `defaultOpen` maps to the `open` attribute. The summary carries the
- * icon + title (no editable chrome — PM does not mount inside <summary>).
- * Body renders unconditionally; browsers display:none the content when
- * collapsed but DOM is retained, so PM children stay live.
- *
- * The component accepts `children` (NodeViewContent injected by JsxComponentView)
- * as an opaque React element and places it inside the body region. The
- * surrounding chrome is non-editable; clicking the summary toggles the open
- * state via native browser behavior (no JS handler needed).
- *
- * Zero upstream-docs-lib React imports — all styling flows
- * through Tailwind utility classes + the `[data-component-type="callout"]`
- * selector in globals.css (OK shadcn semantic tokens). An inline
- * `--callout-type-color` CSS variable drives the left-border accent +
- * selection-halo; when the user authors a `color` prop, the inline style
- * overrides the per-type default.
- *
- * Precedent #30 (all user content visible): children slot is ALWAYS rendered,
- * never `display: none` via React. Native `<details>` does its own
- * display-toggle inside the browser — that is orthogonal to the precedent.
+ * Precedent #30 (all user content visible): children slot is ALWAYS rendered, never `display: none`
+ * via React.
*/
import { Trans } from '@lingui/react/macro';
diff --git a/packages/app/src/editor/components/Image.dom.test.tsx b/packages/app/src/editor/components/Image.dom.test.tsx
index ac7fde321..d7ee00076 100644
--- a/packages/app/src/editor/components/Image.dom.test.tsx
+++ b/packages/app/src/editor/components/Image.dom.test.tsx
@@ -1,34 +1,4 @@
-/**
- * Tier-3 RTL behavioral tests for the Image component's loading-state contract
- * embedded images must render a loading-state placeholder that
- * reserves the layout slot until the inner <img>.load event fires, then swap to
- * the real <img>. Without this contract the rendered DOM transitions through a
- * "empty / 0×0 box → bytes arrive → reflow" sequence — the symptom the
- * reporter observed in the WYSIWYG editor.
- *
- * Invocation via `pnpm run test:dom`; jsdom substrate per precedent #43.
- * Sibling: DocumentErrorBoundary.dom.test.tsx, FileTree.selection-mirror.dom.test.tsx.
- *
- * Selector contract:
- * - data-testid="image-loading-skeleton" — the loading-state element. Distinct
- * from shadcn Skeleton's default data-slot="skeleton" so the Image surface
- * stays queryable independent of any other Skeleton on the page.
- * - data-testid="image-slot" — the layout-reserving wrapper carrying the
- * intrinsic dimensions as inline style (style.width + style.aspectRatio).
- * Inline `style` is the only path that resolves under jsdom AND supports
- * dynamic numeric dimensions (Tailwind's `w-[400px]` would not resolve in
- * jsdom's computed style and cannot be authored statically for arbitrary
- * author-supplied widths in any case).
- *
- * Mocking discipline: react-medium-image-zoom IS mocked as a
- * pass-through wrapper. The wrap is orthogonal to the loading-state contract,
- * and the real <Zoom> attaches a ResizeObserver on mount — jsdom doesn't ship
- * ResizeObserver, so a real render throws `ReferenceError: ResizeObserver is
- * not defined` from inside RTL's act bridge before any of our assertions run.
- * The pass-through preserves the inner <img> shape (which IS under test) and
- * defeats the infrastructure noise without changing what the Image component
- * promises its callers.
- */
+/** Runs under the jsdom substrate (precedent #43). */
import { cleanup, fireEvent, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
diff --git a/packages/app/src/editor/components/Tabs.dom.test.tsx b/packages/app/src/editor/components/Tabs.dom.test.tsx
index e6228c446..e713feaaf 100644
--- a/packages/app/src/editor/components/Tabs.dom.test.tsx
+++ b/packages/app/src/editor/components/Tabs.dom.test.tsx
@@ -1,28 +1,7 @@
/**
- * Tabs — DOM-walk contracts.
- *
- * Two helpers live in `Tabs.tsx`, both keyed off the same SLOT_SELECTOR walk:
- *
- * 1. `readTabSlots` — counts the Tabs's OWN direct Tab renderers, the same
- * set the CSS active-panel reveal counts. Pinned against the regression
- * where a recursive walk would sweep in every nested nodeview's
- * `.react-renderer` and emit phantom strip pills (the user-visible
- * "6 pills instead of 2" on the quickstart, whose Tab 1 nests a Callout
- * and a multi-Step Steps).
- * 2. `findNthTabGearButton` — resolves the chrome-bar gear button at slot N
- * so the Notion-style rename gesture (active-pill click → open Tab
- * PropPanel) can dispatch `.click()` on it. Pins three contracts the
- * editor relies on: `[data-jsx-gear]` is the canonical selector; slot
- * index alignment matches `readTabSlots`'s index space (the SAME index
- * space the strip's pills are rendered with); nested-Tabs scoping
- * prevents inner Tabs's gears from bleeding into the outer slot set.
- *
- * jsdom substrate per precedent #43 (`bun run test:dom`). Tests build DOM
- * directly via `document.body.innerHTML` rather than rendering through RTL
- * because the helpers are pure DOM-in/values-out — no React state, no PM.
- * `cleanup` from RTL satisfies the *.dom.test.tsx → @testing-library/react
- * value-import contract (precedent #43); it is a no-op against this
- * fixture style.
+ * DOM-walk contracts for `readTabSlots` and `findNthTabGearButton`, on the jsdom tier per
+ * precedent #43; RTL's `cleanup` satisfies that tier's value-import contract and is a no-op
+ * against this fixture style.
*/
import { cleanup } from '@testing-library/react';
diff --git a/packages/app/src/editor/components/Tabs.tsx b/packages/app/src/editor/components/Tabs.tsx
index f4d2ffe5b..201a6e4d8 100644
--- a/packages/app/src/editor/components/Tabs.tsx
+++ b/packages/app/src/editor/components/Tabs.tsx
@@ -1,80 +1,7 @@
/**
- * Tabs — Notion-style horizontal tab strip + active panel container.
- *
- * Mirrors Accordion's shape: single jsxComponent descriptor in
- * `core/registry/built-ins.ts` (canonical, hasChildren), paired with the Tab
- * descriptor for individual panels. NO HTML5 `<details>` substrate (Tabs is
- * exclusive-active, not collapse-each), NO MutationObserver (kept simple),
- * NO mutation of PM-managed child DOM (CSS rules handle hiding).
- *
- * ── Active-tab lifecycle ─────────────────────────────────────────────────────
- *
- * `activeIndex` lives in this component's `useState`, defaults to 0. Not in
- * the PM doc — selection is ephemeral, same as Notion / Mintlify / fumadocs.
- * The wrapper element carries `data-active-index={N}`; CSS rules in
- * `globals.css` hide all `.react-renderer` siblings under
- * `.component-children > [data-node-view-content-react]` and re-show the
- * N+1-th one. The chain hops twice because Tiptap renders each child
- * NodeView inside a `.react-renderer.node-jsxComponent` div (from
- * @tiptap/react's ReactRenderer) which itself lives inside PM's
- * `contentDOMElement` (a `[data-node-view-content-react]` div that
- * ReactNodeViewRenderer appends inside the React `NodeViewContent` element).
- * PM children stay live (Precedent #30) — they're just not painted.
- *
- * ── Strip rendering & index space ────────────────────────────────────────────
- *
- * The strip needs each Tab's `label` and a stable `id` (for ARIA pairing). We
- * read this Tabs's OWN direct Tab renderers — scoped with `:scope >` to mirror
- * the CSS `:nth-of-type` reveal chain in `globals.css` exactly — and extract
- * the inline `data-tab-label` / `data-tab-id` set by Tab.tsx's render (no
- * setAttribute mutations). The direct-child scoping is load-bearing: a Tab is
- * itself a PM container with its own contentDOM, so a recursive `.react-renderer`
- * walk would sweep in every nested nodeview (a Callout, a Steps and its Steps,
- * a nested Tabs) and emit a phantom pill per grandchild, drifting the strip
- * index space away from the CSS reveal. A non-Tab block legally allowed by the
- * `block*` content expression still occupies one slot with a fallback label,
- * so the two index spaces stay aligned and the correct panel reveals.
- *
- * ── Auto-switch on add ───────────────────────────────────────────────────────
- *
- * When the user clicks the `+ Add Tab` pill (JsxComponentView's container
- * affordance), a new Tab lands at the END of the Tabs's content. PM then
- * fires `focusInsertedComponent` → `requestAnimationFrame(setNodeSelection)`,
- * which is what eventually flips `selected` true on the new Tab and triggers
- * its mount-effect `consumeAutoOpen` → `setPopoverOpen(true)`. If
- * `activeIndex` still points at the previous active when the popover opens,
- * the new wrapper is `display: none` and Radix can't compute a position
- * (it pins to the viewport top-left).
- *
- * Both the label-read AND the count-grew-→-bump-active updates live in
- * `useLayoutEffect`s here. That settles the cascade (read labels → setState
- * → re-render → snap activeIndex → re-render) BEFORE the browser paints and
- * therefore before the deferred `setNodeSelection` rAF runs. By the time
- * `selected` flips and the popover opens, the new Tab's wrapper is visible.
- * Using `useEffect` for the label-read would defer the cascade past paint,
- * leaving a one-frame window where the rAF could fire against a still-hidden
- * wrapper.
- *
- * ── Deep-link via `#hash` ────────────────────────────────────────────────────
- *
- * `<Tab id="foo">` writes `id="foo"` on its `<section>`. If the Tab isn't
- * active, the section is `display: none` and browsers refuse to scroll. We
- * listen to `hashchange` (and run once on mount) — when the hash matches a
- * Tab id, snap `activeIndex` to that Tab and `scrollIntoView` after the
- * paint. The Tabs container's own `id` activates index 0 (matches the
- * descriptor description claim that `<Tabs id="x">` is deep-linkable).
- *
- * ── Notion-style rename gesture ──────────────────────────────────────────────
- *
- * Clicking an INACTIVE pill activates that tab (standard tablist behavior).
- * Clicking the pill that is ALREADY active opens its `<Tab>` properties
- * popover — the same popover the chrome-bar gear opens. Solves the
- * discoverability gap UX research caught: users could not figure out how to
- * rename a tab and got stuck before finding the gear inside the tab body's
- * hover chrome. The active-pill onClick dispatches `.click()` on the
- * resolved gear button (`findNthTabGearButton`), which fires the Radix
- * `PopoverTrigger` whose `<Tab>` Label PropDef has `autoFocus: true` — so
- * focus lands on the Label input ready to type.
+ * PM children stay live (Precedent #30) — they're just not painted. ── Strip rendering & index
+ * space ──────────────────────────────────────────── The strip needs each Tab's `label` and a
+ * stable `id` (for ARIA pairing).
*/
import { useLingui } from '@lingui/react/macro';
diff --git a/packages/app/src/editor/components/Video.dom.test.tsx b/packages/app/src/editor/components/Video.dom.test.tsx
index aea7b5b1d..4fcc64ffe 100644
--- a/packages/app/src/editor/components/Video.dom.test.tsx
+++ b/packages/app/src/editor/components/Video.dom.test.tsx
@@ -1,12 +1,4 @@
-/**
- * RTL behavioral tests for the `Video` canonical's dispatch contract.
- * Pins the three render branches: native `<video>` for file-served media,
- * `<LiteYouTubeEmbed>` (thumbnail-first facade — iframe mounts on click)
- * for recognized YouTube URLs, and `@u-wave/react-vimeo` (eager iframe via
- * Vimeo's Player SDK) for recognized Vimeo URLs.
- *
- * Runs under `bun run test:dom` (jsdom substrate per precedent #43).
- */
+/** Runs under the jsdom substrate (precedent #43). */
import { cleanup, fireEvent, render } from '@testing-library/react';
import { useEffect, useRef } from 'react';
diff --git a/packages/app/src/editor/components/componentMap.tsx b/packages/app/src/editor/components/componentMap.tsx
index e7a7fbfe6..b43a398b6 100644
--- a/packages/app/src/editor/components/componentMap.tsx
+++ b/packages/app/src/editor/components/componentMap.tsx
@@ -1,48 +1,6 @@
/**
- * Maps component name → React component for the descriptor registry.
- *
- * The registered inventory is the `componentMap` object below — the
- * canonical descriptor list lives in core's `built-ins.ts`. The notes
- * that follow call out renderer-specific quirks for a subset of entries;
- * they are not an exhaustive inventory (the map itself is).
- * Each canonical entry is a DIY renderer — Callout is a 7-prop GFM shape
- * at `./Callout`, Image wraps `react-medium-image-zoom` (8-prop at
- * `./Image`), Video is a pure HTML5 `<video>` wrapper (9-prop at `./Video`
- * — no URL sniffing, no iframe emission), Audio is a pure HTML5
- * `<audio>` wrapper (7-prop at `./Audio`, `hasChildren: true` for
- * `<source>` / `<track>` passthrough), Accordion is a standalone HTML5
- * `<details>`/`<summary>` wrapper (6-prop at `./Accordion`
- * — no `variant`, no `<Accordions>` parent wrapper; cross-browser exclusive
- * grouping via HTML5 `<details name>`), Math is a KaTeX-lazy renderer at
- * `./Math`, MermaidFence is a mermaid-js v11 lazy renderer at `./Mermaid`
- * (re-introduces support that was removed — replaces the
- * placeholder stub deleted; the descriptor
- * is named `MermaidFence` so `<Mermaid />` JSX falls through to the
- * wildcard, enforcing fence-only authoring), Pdf is a
- * `pdfjs-dist`-backed multi-page canvas viewer with our own toolbar
- * (3-prop shape at `./Pdf`; `anchor`-string parsed at render time for
- * `#page=N` / `#height=N` viewer parameters), and File is a generic
- * file-attachment row (1-prop canonical at `./File`; styled `<a>`
- * link with icon + filename + optional dim size — Notion-style inline
- * row, no card chrome). The pdfjs library is dynamic-imported via a
- * module-level singleton so it stays out of the main app bundle.
- *
- * Compound-component machinery (Tabs/Tab + Accordions/Accordion)
- * was cut along with the Context Bridge Registry. Tabs/Tab
- * returned with an ephemeral-state design: `Tabs.tsx`'s
- * `useState(activeIndex)` plus a single `data-active-index` attribute on
- * the content wrapper drive CSS-only panel visibility — no cross-NodeView
- * React context, no DOM mutation on PM-managed children. Tab and Tabs are
- * the canonical pack's only compound parent today (Tabs declares
- * `emptyChildName: 'Tab'`).
- *
- * Descriptor names no longer in `componentMap` — Banner, Card, Cards, Step,
- * Steps, Accordions (fumadocs compound parent), Files, Folder, TypeTable,
- * InlineTOC — fall through to the `'*'` wildcard per
- * `registry/index.ts:getDescriptor`. Per-Precedent #30 the children of those
- * unregistered components stay editable (wildcard `hasChildren: true`).
- *
- * '*' maps to UnregisteredBadgeRender for the wildcard fallback.
+ * Per-Precedent #30 the children of those unregistered components stay editable (wildcard
+ * `hasChildren: true`).
*/
import { Accordion } from './Accordion.tsx';
import { AlignBlock } from './AlignBlock.tsx';
diff --git a/packages/app/src/editor/composer-mention/composer-slash-input.dom.test.tsx b/packages/app/src/editor/composer-mention/composer-slash-input.dom.test.tsx
index 9fc708f01..49709f06d 100644
--- a/packages/app/src/editor/composer-mention/composer-slash-input.dom.test.tsx
+++ b/packages/app/src/editor/composer-mention/composer-slash-input.dom.test.tsx
@@ -1,9 +1,6 @@
/**
- * Tier-3 tests for the composer's `/` slash-command surface end to end through
- * `ComposerMentionInput`: host gating (no corpus prop → `/` stays inert), the
- * token decoration's recognized/unresolved states, the hint line's three-way
- * copy, live command-list updates re-resolving both, the picker's suggestion
- * lifecycle (message-start trigger, keyboard selection), and the
+ * Tier-3 coverage of the composer's `/` slash-command surface end to end: host gating, token
+ * decoration states, hint copy, live command-list updates, the picker lifecycle, and the
* one-transaction insertion pin (precedent #58).
*/
diff --git a/packages/app/src/editor/editor-cache.ts b/packages/app/src/editor/editor-cache.ts
index b522e81aa..611c2f783 100644
--- a/packages/app/src/editor/editor-cache.ts
+++ b/packages/app/src/editor/editor-cache.ts
@@ -1,47 +1,14 @@
/**
- * V2 editor cache — module-level `Map<docName, Entry>` that survives React
- * unmount, SPA navigation, Activity mode flips, StrictMode double-invoke, HMR.
- *
- * Contract (precedent #27(a)):
- *
- * mount{Tiptap,Cm}Editor({ docName, container, factory })
- * — CACHE HIT: reparent editor.editorView.dom / view.dom into `container`,
- * restore scrollTop + focus, set activeMountKey = docName.
- * — CACHE MISS: factory(container) constructs a fresh editor that mounts
- * itself into container; the returned tuple is cached.
- * — CACHE_ENABLED=false: always calls factory, never caches (pre-V2 path).
- *
- * park{Tiptap,Cm}Editor(entry)
- * — detach DOM from parent, capture scrollTop, clear activeMountKey.
- * NEVER destroys. Editor keeps running — local Y.js observers still
- * fire, plugin state survives, only DOM painting stops.
- * — CACHE_ENABLED=false: destroys (restores pre-V2 destroy-on-unmount
- * semantic — the consumer's cleanup path still runs).
- *
- * evict{Tiptap,Cm}Editor(docName)
- * — THE ONLY PATH that calls provider.destroy() / ydoc.destroy().
- * editor.destroy() / view.destroy() are also called on the
- * __uncached / kill-switch park branch (see park{Tiptap,Cm}Editor).
- * Called on LRU eviction (MAX_CACHE) or explicit tear-down.
- *
- * Why raw `editor.editorView.dom` reparent and NOT `Editor.mount()/unmount()`:
- * @tiptap/[email protected] captures the `editor` ref in a plugin
- * closure, reads `editor.view.dom.parentElement` from the `view(view)`
- * lifecycle callback, and hits TipTap's throwing-proxy during the
- * re-create path (the proxy throws while the new `EditorView` is
- * mid-construction). STOP rule: this module MUST NOT call `editor.mount()`
- * or `editor.unmount()`.
- *
- * Why CM6 uses the symmetric pattern: `EditorView.setRoot()` is only needed
- * for cross-Document reparent (iframe/ShadowRoot); within-Document reparent
- * needs no API call at all — W3C DOM observers (Mutation / Resize /
- * Intersection) survive reparent by spec.
- *
- * Emergency kill switch: flip `CACHE_ENABLED = false`,
- * redeploy. mount() short-circuits to factory-only (no storage); park()
- * destroys immediately. This is NOT a feature flag — no config system, no
- * rollout percentage, no user targeting. One-line edit for fire-drill
- * rollback during a production incident.
+ * Module-level editor cache that survives React unmount, SPA navigation, Activity mode flips,
+ * StrictMode double-invoke and HMR, per precedent #27(a): mount reparents, park detaches without
+ * destroying, and evict is the only path that destroys the provider and Y.Doc.
+ */
+
+/**
+ * STOP: this module must not call `editor.mount()` or `editor.unmount()`.
+ * `@tiptap/extension-drag-handle` captures the editor ref in a plugin closure and reads
+ * `editor.view.dom.parentElement` from its `view()` callback, which hits TipTap's throwing proxy
+ * while the replacement `EditorView` is mid-construction. Reparent `editor.editorView.dom`.
*/
import type { Compartment } from '@codemirror/state';
@@ -113,14 +80,8 @@ export interface CmCacheEntry {
ytext: Y.Text;
provider: HocuspocusProvider;
/**
- * The theme `Compartment` embedded in `view` at construction. Stored on the
- * entry — NOT held per React component — because the view is cached and
- * reparented across Activity flips while its consuming `SourceEditor`
- * component remounts (precedent #27(a)). A per-component compartment would
- * not be part of the reused view's config, so a theme-change reconfigure
- * dispatched against it is a silent no-op and the cached view keeps the
- * theme it was built with (stale syntax highlight after a dark/light toggle
- * on backgrounded docs). Consumers reconfigure THIS compartment.
+ * Stored on the entry — NOT held per React component — because the view is cached and reparented
+ * across Activity flips while its consuming `SourceEditor` component remounts (precedent #27(a)).
*/
themeCompartment: Compartment;
wordWrapCompartment: Compartment;
diff --git a/packages/app/src/editor/extensions/CodeBlockView.tsx b/packages/app/src/editor/extensions/CodeBlockView.tsx
index dc94a7d46..625a3f4f7 100644
--- a/packages/app/src/editor/extensions/CodeBlockView.tsx
+++ b/packages/app/src/editor/extensions/CodeBlockView.tsx
@@ -1,11 +1,6 @@
/**
- * React NodeView for the visual-mode code block.
- *
- * Visual design — zero permanent chrome: the code body renders solo, with a
- * hover/selection-revealed chrome bar floating above the block edge that
- * carries the language picker, edit-source, preview toggle, settings, Ask AI,
- * copy, and delete affordances. Mirrors the JsxComponentView chrome pattern
- * (precedent #30) so codeblocks compose visually with other rich blocks.
+ * Mirrors the JsxComponentView chrome pattern (precedent #30) so codeblocks compose visually with
+ * other rich blocks.
*/
import { Trans, useLingui } from '@lingui/react/macro';
diff --git a/packages/app/src/editor/extensions/JsxComponentView.tsx b/packages/app/src/editor/extensions/JsxComponentView.tsx
index b1357b975..1173d331f 100644
--- a/packages/app/src/editor/extensions/JsxComponentView.tsx
+++ b/packages/app/src/editor/extensions/JsxComponentView.tsx
@@ -1,37 +1,7 @@
/**
- * JsxComponentView — overlay-based descriptor-dispatch NodeView.
- *
- * **Design principle:** Zero permanent chrome in document flow. Components
- * render exactly like production. All editor affordances are hover-revealed
- * overlays at top-right (move up/down, delete, settings gear) plus an
- * "add child" pill at the bottom edge of container descriptors.
- *
- * A persistent component-name chip was proposed but dropped — the
- * "zero permanent chrome" principle won. The
- * descriptor identity is surfaced through: (a) the rendered fumadocs
- * component's own visual style (every built-in has a distinct shape), (b)
- * the `SelectionAnnouncer` aria-live region announcing the block name on
- * selection change, (c) the `aria-label` group summary announced to AT on
- * focus.
- *
- * Three render branches:
- * Branch 1 (Wildcard `'*'`): does NOT render a persistent chip — the
- * NodeView immediately schedules a rAF-auto-convert into an editable
- * `rawMdxFallback` (nested CodeMirror source editor, Precedent #28
- * direct PM dispatch + #30 all user content visible). A transient
- * "Unknown component: X — source editable below"
- * placeholder flashes for at most one frame while the conversion
- * dispatch lands.
- * Branch 2 (Registered healthy): live React component + hover chrome
- * (move/delete/gear→Popover PropPanel, add-child pill) + NodeViewContent.
- * Branch 3 (Invalid-state / render error): same rAF-auto-convert into
- * `rawMdxFallback` — the error boundary catches, logs a structured
- * `jsx-render-failure` event, and the NodeView replaces itself with
- * the source editor. Identical UX shape to Branch 1 by design
- * (Precedent #28: parse failures AND render failures surface the same
- * embedded source editor).
- *
- * Per Precedent #30: NodeViewContent is ALWAYS rendered, never display:none.
+ * Descriptor-dispatch NodeView with zero permanent chrome: unknown and render-failed descriptors
+ * auto-convert to an editable `rawMdxFallback` through direct PM dispatch (precedent #28), and
+ * NodeViewContent is always rendered rather than hidden (precedent #30).
*/
import {
diff --git a/packages/app/src/editor/extensions/RawMdxFallbackCMView.test.ts b/packages/app/src/editor/extensions/RawMdxFallbackCMView.test.ts
index 3c24bfa78..8b0fe0ee4 100644
--- a/packages/app/src/editor/extensions/RawMdxFallbackCMView.test.ts
+++ b/packages/app/src/editor/extensions/RawMdxFallbackCMView.test.ts
@@ -1,11 +1,7 @@
/**
- * Nested CodeMirror sync math tests.
- *
- * Tests the `computeChange` function that computes minimal string diffs
- * for PM→CM and CM→PM synchronization, the `shouldEscapeNestedCM` boundary
- * predicate that drives arrow-key escape from nested CM to outer PM, and
- * `computeCMSelectionForwarding` — the PM→CM selection mirror decision
- * (Precedent #31 "Selection state as typed PM PluginState").
+ * Nested CodeMirror sync math: `computeChange`'s minimal diffs, the `shouldEscapeNestedCM`
+ * boundary predicate, and `computeCMSelectionForwarding`, the PM-to-CM selection mirror decision
+ * (precedent #31, selection state as typed PM PluginState).
*/
import { EditorState as CMEditorState } from '@codemirror/state';
diff --git a/packages/app/src/editor/extensions/RawMdxFallbackCMView.tsx b/packages/app/src/editor/extensions/RawMdxFallbackCMView.tsx
index f1ad93b76..99d7f16e5 100644
--- a/packages/app/src/editor/extensions/RawMdxFallbackCMView.tsx
+++ b/packages/app/src/editor/extensions/RawMdxFallbackCMView.tsx
@@ -1,18 +1,7 @@
/**
- * RawMdxFallback NodeView with embedded CodeMirror 6.
- *
- * Implements the canonical ProseMirror + CodeMirror pattern
- * (prosemirror.net/examples/codemirror/) adapted for TipTap's React NodeView.
- *
- * Architecture (Precedent #28 — direct PM dispatch, NOT y-codemirror.next):
- * CM keystroke → forwardUpdate → PM transaction → y-prosemirror → CRDT
- * PM change → NodeView.update(node) → computeChange → CM transaction
- * Single `updating` boolean prevents feedback loops.
- *
- * This NodeView embeds a CodeMirror EditorView inside a React component.
- * The CM instance is NOT mounted via React (would conflict with PM's DOM management).
- * Instead, CM is mounted imperatively into a ref'd container, and React
- * renders the chrome (badge, border) around it.
+ * Architecture (Precedent #28 — direct PM dispatch, NOT y-codemirror.next): CM keystroke →
+ * forwardUpdate → PM transaction → y-prosemirror → CRDT PM change → NodeView.update(node) →
+ * computeChange → CM transaction Single `updating` boolean prevents feedback loops.
*/
import { Compartment } from '@codemirror/state';
@@ -87,43 +76,9 @@ export function computeCMSelectionForwarding(opts: {
}
/**
- * Attempt to upgrade a `rawMdxFallback`'s source back to its parsed form.
- * Given the current CM source and the PM schema, returns an array of PM
- * Nodes to replace the rawMdxFallback with, or `null` if the upgrade
- * shouldn't happen.
- *
- * Called on CM blur — matches Obsidian's live-preview cursor-exit
- * trigger, which for our nested-CM architecture collapses to browser
- * blur because nested CM focus IS the source reveal.
- *
- * **Multi-block upgrades are supported** — `parseWithFallback`'s
- * recovery often absorbs adjacent blocks into one fallback (a broken
- * MDX tag's scope isn't cleanly bounded, so the parser keeps
- * consuming until it finds a valid close or EOF, swallowing following
- * paragraphs). If the user fixes the broken tag, the source parses to
- * multiple VALID blocks. Returning all of them lets the caller splice
- * them all back in — matches the user's mental model ("I fixed the
- * broken thing; the whole fallback should go away").
- *
- * Returns `null` (= no-op, preserve the existing rawMdxFallback) when:
- * - Parse produces zero blocks (empty source → let caller decide;
- * `MarkdownManager.parse("")` actually short-circuits to one empty
- * paragraph, so this branch is rarely hit in practice)
- * - Parse result contains ANY `rawMdxFallback` child (source still
- * invalid — the fallback recovery tried the fix and still failed
- * on some part of the block; preserving the existing fallback
- * beats churning Y.XmlElement identity for the same parse state
- * per Precedent #10 on Item-preservation)
- * - `parseWithFallback` is contractually never-throws, but
- * `schema.nodeFromJSON` CAN throw on future schema-drift edges
- * ("Invalid content for node ..."). Such throws are caught here
- * and surface as a structured `raw-mdx-upgrade-failure` log event;
- * the fallback stays in place so the user can keep editing.
- * Silent throws would otherwise escape to CodeMirror's
- * updateListener catch and leave the user with no signal.
- *
- * The caller must guard dispatch with `updatingRef` to prevent feedback
- * loops — this function is pure state inspection.
+ * Attempts to upgrade a `rawMdxFallback`'s source back to its parsed form on CM blur, returning
+ * `null` to preserve the existing fallback when the source still parses to one, which beats
+ * churning Y.XmlElement identity for the same parse state (precedent #10).
*/
export function tryParseUpgrade(source: string, schema: Schema): PmNode[] | null {
const mgr = getSharedMarkdownManager();
diff --git a/packages/app/src/editor/extensions/autonomous-fragment-edit.ts b/packages/app/src/editor/extensions/autonomous-fragment-edit.ts
index 186914d28..26f91140b 100644
--- a/packages/app/src/editor/extensions/autonomous-fragment-edit.ts
+++ b/packages/app/src/editor/extensions/autonomous-fragment-edit.ts
@@ -1,24 +1,7 @@
/**
- * Which ProseMirror transactions the user is responsible for, and when a
- * NodeView is allowed to issue one they are not.
- *
- * DISPATCH GATE. An autonomous (non-user-initiated) structural fragment rewrite
- * issued from a source-mode-hidden WYSIWYG editor races Observer B's
- * per-keystroke re-derive and double-materializes the span at the
- * Y.XmlFragment CRDT level (precedent #14: Observer B is the sole fragment
- * writer during source typing). Gate every autonomous structural dispatch on
- * the editor being the visible/authoritative surface — in source mode the
- * WYSIWYG is hidden, so its structural rewrites serve no user and only create
- * the double-write race.
- *
- * Checked at DISPATCH time (not effect entry): the mode can flip between
- * scheduling a rAF/timeout and its firing, and a stale-scheduled dispatch is
- * exactly the hazard.
- *
- * ORIGIN CLASSIFICATION. `isUserIntentOrigin` is where "did the user do this?"
- * is answered, so a consumer asking it does not carry its own copy of the
- * origin taxonomy. See that function for the canonical enumeration, and
- * `markAutonomousFragmentEdit` for what the second arm is and why it exists.
+ * Gates autonomous structural fragment dispatches on the editor being the visible surface:
+ * Observer B is the sole fragment writer during source typing (precedent #14), so a
+ * source-mode-hidden WYSIWYG rewrite double-materializes the span at the CRDT level.
*/
import type { Editor } from '@tiptap/core';
import type { Node as PmNode } from '@tiptap/pm/model';
diff --git a/packages/app/src/editor/extensions/chunk-wrapper-decoration.ts b/packages/app/src/editor/extensions/chunk-wrapper-decoration.ts
index df2f41f4e..07b751d0b 100644
--- a/packages/app/src/editor/extensions/chunk-wrapper-decoration.ts
+++ b/packages/app/src/editor/extensions/chunk-wrapper-decoration.ts
@@ -1,90 +1,7 @@
/**
- * chunk-wrapper-decoration plugin.
- *
- * Applies `class="ok-chunk-wrapper"` to every top-level direct child of the
- * doc via PM `Decoration.node`. The CSS rule at
- * `globals.css:.ProseMirror .ok-chunk-wrapper` carries
- * `content-visibility: auto` + `contain-intrinsic-size: 0 var(--ok-cv-h, 80px)`,
- * which makes off-viewport blocks structurally skipped by Chromium's
- * containment optimizations.
- *
- * Why per-block (chunk size N=1) instead of grouped chunks
- * --------------------------------------------------------
- * PM's Decoration API has three forms — `inline`, `node`, `widget`. None
- * supports "wrap N consecutive sibling nodes in a shared parent without
- * touching schema." Slate-based editors like Plate use a structural-node
- * chunking model; PM forbids that without a schema change (precedent #9
- * add-only).
- * So we apply CV:auto to each top-level block as its own chunk — chunk
- * size N=1 — and rely on Chromium's implementation handling thousands of
- * CV:auto-classed elements without superlinear overhead.
- *
- * Top-level only: nested elements (text inside paragraph, listItem inside
- * list, tableRow inside tableCell) DON'T get CV:auto, because their parent's
- * containment skip handles them. Walking `state.doc.forEach((node, offset))`
- * gives exactly the top-level direct children.
- *
- * `jsxComponent` exclusion
- * ------------------------
- * `content-visibility: auto` implies `contain: paint`, which clips at the
- * decorated element's border box. `.jsx-component-wrapper` (the DOM node
- * TipTap renders for `jsxComponent`) paints visual chrome OUTSIDE its own
- * border box in three places — the `::before` hover hit-zone at `top:-12px`,
- * the `::after` selection halo at `inset:-4px`, and the `.jsx-component-chrome`
- * toolbar child at `top:-11px` (all in `globals.css` §7/§7a). Decorating these
- * with `.ok-chunk-wrapper` would clip the halo (left/right) and the chrome
- * bar (top), so we skip them. JsxComponent blocks are a small fraction of
- * typical doc content; the layout-work win on the remaining 95%+ of top-level
- * blocks is essentially preserved.
- *
- * Marks
- * -----
- * `ok/render/cv-auto-skip` — fires once per session (module-global flag) on
- * the first decoration emit. The mark is a "track active" signal for
- * DevTools-Performance-tab visibility — one entry per session is sufficient;
- * per-emit would flood the trace.
- *
- * System / config doc safety
- * --------------------------
- * The CLAUDE.md STOP rule "isSystemDoc()/isConfigDoc() gates at every
- * documentName-keyed entry point" doesn't apply directly because this plugin
- * keys off `state.doc` (PM structure), not `documentName`. Safety is enforced
- * upstream:
- * - `__system__` is rejected at ProviderPool admission and filtered out of
- * the editor mount list. It never reaches a TiptapEditor instance, so
- * this plugin's `props.decorations` is never called for it.
- * - `__config__/workspace` and `__user__/config.yml` use Y.Text-only
- * Settings-pane transport (CLAUDE.md §STOP rules). No `Y.XmlFragment`
- * exists for TipTap to bind to, so no editor mount, no plugin call.
- * No in-plugin gate is required.
- *
- * Plugin design
- * -------------
- * `props.decorations` walks `state.doc.forEach` and emits a `Decoration.node`
- * per top-level block child with `class: 'ok-chunk-wrapper'`. PM merges the
- * class with any existing classes the node renders (e.g., heading anchors);
- * the decoration is additive. Inline-only root children are skipped (rare —
- * the doc schema forbids inlines at the root in normal use).
- *
- * The `DecorationSet` is rebuilt on every state transition. PM's diffing
- * means re-emit cost is per-block (the decorations are pure shape; no
- * cached instance). For ~11K top-level blocks this is sub-ms on each
- * transaction.
- *
- * Cross-browser graceful degradation
- * ----------------------------------
- * Browsers that don't support `content-visibility: auto` (Firefox <123,
- * Safari <18) treat the property as unknown and drop it; the CSS rule
- * becomes a no-op. The plugin would then walk the doc and emit decorations
- * on every transaction for no observable benefit (just a stale wrapper
- * class on every top-level block + a per-transaction DOM mutation). The
- * feature-detection short-circuit at module init returns a no-op plugin
- * on those browsers — zero per-transaction CPU, zero unnecessary class
- * attributes in the rendered DOM.
- *
- * SSR / non-browser environments (unit tests with EditorState only) have
- * no `CSS` global; the helper returns `true` there so the plugin still
- * emits decorations for test assertions.
+ * None supports "wrap N consecutive sibling nodes in a shared parent without touching schema."
+ * Slate-based editors like Plate use a structural-node chunking model; PM forbids that without a
+ * schema change (precedent #9 add-only).
*/
import { Plugin, PluginKey } from '@tiptap/pm/state';
diff --git a/packages/app/src/editor/extensions/internal-link.ts b/packages/app/src/editor/extensions/internal-link.ts
index 1d5cbde9c..678b0942c 100644
--- a/packages/app/src/editor/extensions/internal-link.ts
+++ b/packages/app/src/editor/extensions/internal-link.ts
@@ -1,39 +1,4 @@
-/**
- * App-layer LinkFidelity extension — plain-DOM chip routed via the shared
- * InteractionLayer.
- *
- * `renderHTML` emits a plain `<span data-link role="link" tabindex="0">`
- * with an `aria-label`. The mark-identity / mark-interaction-bridge /
- * decoration plugin stack attaches `data-mark-id` and `data-resolution-state`
- * decoration attrs at PM render time. The InteractionLayer's event delegation
- * routes pointer AND keyboard activation to the shared PropPanel at editor
- * root. (Previously: per-instance `ReactMarkViewRenderer(InternalLinkView)`
- * mounted one React subtree per `<a>` mark — hundreds of portals per large
- * doc with seconds of React reconciliation cost.)
- *
- * **Click / hover / keyboard semantics**:
- * - Bare click + Enter on a focused chip navigates via `handlePrimary` —
- * external opens in a new tab; doc/anchor uses same-tab hash routing.
- * Unresolved page links (target missing OR folder without index) return
- * false so the popover surfaces "Create page" / "Create index" actions.
- * - Cmd/Ctrl+click + middle-click route through `handlePrimary` with
- * `newTab: true` to open in a new tab.
- * - Mouse hover (with 300 ms open delay, 150 ms close delay) opens the
- * singleton `InternalLinkPropPanel`; keyboard focus opens it
- * immediately. Touch long-press (500 ms) is the touch equivalent.
- * - Escape dismisses the active PropPanel (handled at the layer).
- * - The `<a href>` child the React MarkView wrapped its text in
- * is deliberately omitted — clicking an anchor navigates synchronously
- * and races the InteractionLayer's click handler.
- *
- * **docName threading:** consumers call `InternalLink.configure({docName})`
- * to bind the active doc name (used by the link-resolution decoration
- * plugin to compute `data-resolution-state` against the page-list cache).
- * `TiptapEditor.tsx` invokes `.configure` with `provider.configuration.name`.
- *
- * Schema unchanged (precedent #9 add-only). All identity + resolution state
- * lives in PluginState / decoration attrs.
- */
+/** Schema unchanged (precedent #9 add-only). */
import {
assertNeverLinkTarget,
classifyMarkdownHref,
diff --git a/packages/app/src/editor/extensions/link-resolution-decoration.ts b/packages/app/src/editor/extensions/link-resolution-decoration.ts
index 01ce09354..13815ed3e 100644
--- a/packages/app/src/editor/extensions/link-resolution-decoration.ts
+++ b/packages/app/src/editor/extensions/link-resolution-decoration.ts
@@ -1,52 +1,7 @@
/**
- * linkResolutionDecorationPlugin — decorates tracked link marks with caller-computed
- * attributes (typically `data-resolution-state`), refreshed whenever the module-level
- * page-list cache changes.
- *
- * Why this plugin exists
- * ----------------------
- * Plain-DOM link chips render via `renderHTML` at PM-parse time, which has no React
- * context access. The chip still needs live resolution-state classification —
- * `resolved` / `folder` / `unresolved` / `loading` / `external` — so CSS can drive
- * its visual appearance.
- *
- * Three moving pieces:
- * 1. `markIdentityPlugin` — assigns stable `m${n}` IDs in appendTransaction.
- * 2. `page-list-cache` — module-level store with pages + folderPaths sets,
- * written by PageListProvider on every render.
- * 3. This plugin — reads `markIdentityPlugin`'s byId + page-list-cache; calls
- * caller's `computeAttrs(markInfo, cache)`; emits one `Decoration.inline`
- * per matching mark carrying BOTH `data-mark-id` AND any caller-computed
- * resolution-state attrs (merged-plugin shape).
- *
- * A consumer installs #1 and #3 together. #3's refresh cadence is:
- * - Every doc-changing transaction (PM re-runs `props.decorations` unconditionally).
- * - Every page-list-cache write (handler dispatches a meta transaction that triggers
- * PM to re-run decorations; the meta itself is a no-op for other plugins because
- * it is keyed by this plugin's own PluginKey).
- *
- * Consumer pattern
- * ----------------
- * addProseMirrorPlugins() {
- * return [
- * markIdentityPlugin({
- * markTypes: ['link'],
- * onRegister: (evt) => getInteractionLayer(editor).register(...),
- * onDeregister: (evt) => getInteractionLayer(editor).deregister(...),
- * }),
- * linkResolutionDecorationPlugin({
- * markTypes: ['link'],
- * computeAttrs: (info, cache) => {
- * const href = info.attrs.href as string | undefined;
- * if (!href) return null;
- * return { 'data-resolution-state': resolveLinkState(href, cache) };
- * },
- * }),
- * ];
- * }
- *
- * Precedent #9 (add-only schema) preserved — no mark attr added or narrowed; the
- * resolution-state lives in decoration attrs only.
+ * Decorates tracked link marks with caller-computed attributes, refreshed whenever the
+ * module-level page-list cache changes. Precedent #9's add-only schema is preserved: the
+ * resolution state lives in decoration attrs, never in a mark attr.
*/
import type { Node as PmNode } from '@tiptap/pm/model';
@@ -79,26 +34,8 @@ interface LinkResolutionDecorationOptions {
}
/**
- * Pure helper — given a byId map + markTypes + cache + computeAttrs, produce the
- * DecorationSet. Exported so tests can exercise the core logic without owning a
- * full EditorState + PluginKey plumbing.
- *
- * Returns null when no decorations would be emitted (mirrors PM's convention for
- * `props.decorations` returning a cheap "nothing to render" signal).
- *
- * Merged-plugin design: every emitted decoration carries `data-mark-id`
- * ALONGSIDE caller-computed resolution-state attrs. Merging the
- * markIdentityDecorationPlugin walk into this one — instead of emitting two
- * stacked Decoration.inline per mark — halves the per-link wrapper-span
- * count.
- *
- * Null-attrs fallback: when `computeAttrs(info, cache)` returns null, the
- * merged decoration STILL emits — carrying just `data-mark-id`. The
- * mark-identity-decoration legacy behavior (every mark gets `data-mark-id`
- * regardless of resolution state) is preserved by this fallback.
- *
- * Precedent #9 add-only schema invariant preserved — no mark schema
- * attributes added; the merge stays at the decoration-attr layer.
+ * Precedent #9 add-only schema invariant preserved — no mark schema attributes added; the merge
+ * stays at the decoration-attr layer.
*/
export function computeLinkResolutionDecorations(
doc: PmNode,
diff --git a/packages/app/src/editor/extensions/mark-identity-decoration.ts b/packages/app/src/editor/extensions/mark-identity-decoration.ts
index 63734de34..56ce4657f 100644
--- a/packages/app/src/editor/extensions/mark-identity-decoration.ts
+++ b/packages/app/src/editor/extensions/mark-identity-decoration.ts
@@ -1,32 +1,7 @@
/**
- * markIdentityDecorationPlugin — materializes `markIdentityPlugin`'s stable IDs
- * as PM inline decorations carrying `data-mark-id="m${n}"` attributes.
- *
- * Why a separate plugin? `markIdentityPlugin` assigns IDs in `appendTransaction`
- * — which runs AFTER a mark's `renderHTML` has already emitted DOM. There is
- * no transform that lets `renderHTML` read the post-appendTransaction ID at
- * render time. PM's decoration system is the canonical escape hatch: a plugin
- * returning `Decoration.inline(from, to, attrs)` attaches `attrs` to the DOM
- * for the decorated range on every view update, bypassing the render cycle
- * that produced the mark's initial DOM.
- *
- * Pairs with:
- * - `markIdentityPlugin` — owner of the ID assignment state
- * - InteractionLayer — event delegation reads `data-mark-id`
- * via `closest('[data-mark-id]')` to resolve click/hover targets
- *
- * Consumers (InternalLink, WikiLink-if-mark) register BOTH plugins:
- *
- * addProseMirrorPlugins() {
- * return [
- * markIdentityPlugin({ markTypes: ['link'], onRegister, onDeregister }),
- * markIdentityDecorationPlugin(),
- * ];
- * }
- *
- * precedent #9 (add-only schema): IDs live in PluginState only;
- * the schema is not mutated. Decoration attributes are a view-layer concern,
- * not schema state.
+ * Materializes `markIdentityPlugin`'s stable IDs as PM inline decorations carrying
+ * `data-mark-id`, because the IDs are assigned in `appendTransaction` after `renderHTML` has run.
+ * Precedent #9 add-only schema holds: the IDs live in PluginState, not in the schema.
*/
import { Plugin, PluginKey } from '@tiptap/pm/state';
diff --git a/packages/app/src/editor/extensions/mark-identity.ts b/packages/app/src/editor/extensions/mark-identity.ts
index 1096738c1..a5c564ba5 100644
--- a/packages/app/src/editor/extensions/mark-identity.ts
+++ b/packages/app/src/editor/extensions/mark-identity.ts
@@ -1,28 +1,5 @@
/**
- * markIdentityPlugin — stable IDs for PM marks without touching the schema.
- *
- * Problem: PM marks have no identity across transactions — `mark.type.create(attrs)`
- * can be called afresh anywhere in the PM pipeline, and text-node splits/merges
- * on every keystroke hand back marks whose Object identity differs from before.
- * InteractionLayer needs a stable string id to key `data-mark-id`
- * chip attributes and to fire register/deregister on mark lifecycle.
- *
- * Solution: a PM plugin maintains
- * PluginState<{ byId: Map<id, MarkInfo>, counter: number }>. On every
- * `docChanged` transaction, it carries prior IDs forward via
- * `tr.mapping` and walks the new doc to produce the updated map:
- *
- * - already-known range that remains in the doc → keep its ID
- * - new marked span → assign `m${++counter}` fresh ID
- * - deleted range → ID evicted (view layer fires onDeregister)
- *
- * **Schema is NOT touched** — no mark attr added, narrowed, or removed.
- * Precedent #9 add-only schema preserved (bridgeId stored in
- * PluginState rather than schema attr).
- *
- * Pattern mirrors the existing PM plugins in `heading-anchors.ts` (decoration)
- * and `wiki-link-suggestion.ts` (PluginKey). Registration callbacks wire
- * into InteractionLayer.
+ * Precedent #9 add-only schema preserved (bridgeId stored in PluginState rather than schema attr).
*/
import type { Mark, Node as PmNode } from '@tiptap/pm/model';
diff --git a/packages/app/src/editor/extensions/mark-interaction-bridge.ts b/packages/app/src/editor/extensions/mark-interaction-bridge.ts
index 09af39a2e..d52ec913f 100644
--- a/packages/app/src/editor/extensions/mark-interaction-bridge.ts
+++ b/packages/app/src/editor/extensions/mark-interaction-bridge.ts
@@ -1,61 +1,6 @@
/**
- * mark-interaction-bridge — wires markIdentityPlugin's register/deregister
- * lifecycle to an InteractionLayerHandle so mark chip extensions
- * (InternalLink) can route per-mark interactions through the shared editor-root
- * React plane.
- *
- * Sits between two already-shipped primitives:
- * - `markIdentityPlugin` assigns stable IDs to PM marks and fires
- * register/deregister callbacks on mark lifecycle via its view update.
- * - `InteractionLayer` hosts the singleton PropPanel/Toolbar/
- * Breadcrumb subtree at editor root, routed by active nodeId.
- *
- * Concentrates three subtle correctness points that every mark chip extension
- * would otherwise re-solve:
- *
- * 1. **Live position lookup** — a mark's `from`/`to` captured at register
- * time goes stale as the user edits. `getCurrentMarkInfo(state, id)`
- * resolves the latest MarkInfo from the identity plugin's state on
- * demand, so PropPanel renderers never operate on stale positions.
- *
- * 2. **Context bridging** — the layer's `InteractionContext` exposes only
- * `{ nodeId, type, deactivate }`. Mark chip renderers typically want
- * `{ editor, nodeId, deactivate }` so they can reach back into the
- * editor for commands / state. The bridge augments the context for
- * `renderPropPanel` without forcing the layer to know about editors.
- *
- * 3. **Deregister ordering** — onDeregister fires synchronously from the
- * plugin's view update after a transaction. The bridge calls
- * `layer.deregister(id)` inline so the singleton PropPanel (if active)
- * unmounts before the next render.
- *
- * Consumer pattern (targeted by `internal-link.ts` port):
- *
- * addProseMirrorPlugins() {
- * return [
- * createMarkInteractionBridgePlugin({
- * editor: this.editor,
- * markTypes: ['link'],
- * renderPropPanel: ({ editor, nodeId, deactivate }) => (
- * <InternalLinkPropPanel
- * editor={editor}
- * nodeId={nodeId}
- * onClose={deactivate}
- * />
- * ),
- * }),
- * markIdentityDecorationPlugin(),
- * ];
- * }
- *
- * The PropPanel component reads live MarkInfo via `getCurrentMarkInfo(editor.state, nodeId)`.
- *
- * No consumers wired in this module today — ships as scope-reduction:
- * concentrates the wiring pattern + correctness handling
- * in one tested place so the eventual atomic refactor is smaller.
- *
- * Precedent #9 (add-only schema) is preserved — all identity lives in
- * PluginState, never in mark attrs.
+ * Precedent #9 (add-only schema) is preserved — all identity lives in PluginState, never in mark
+ * attrs.
*/
import type { Editor } from '@tiptap/core';
diff --git a/packages/app/src/editor/extensions/raw-mdx-fallback.ts b/packages/app/src/editor/extensions/raw-mdx-fallback.ts
index 72bb46c23..4564bb158 100644
--- a/packages/app/src/editor/extensions/raw-mdx-fallback.ts
+++ b/packages/app/src/editor/extensions/raw-mdx-fallback.ts
@@ -1,19 +1,6 @@
/**
- * App-specific RawMdxFallback extension — extends core with React NodeView.
- *
- * The core RawMdxFallback handles schema + markdown. This version adds
- * the React NodeView renderer for the browser editor.
- *
- * NodeView embeds a CodeMirror 6 editor for inline editing
- * of raw MDX source, replacing the plain-text badge view.
- * Direct PM dispatch pattern (Precedent #28), NOT y-codemirror.next.
- *
- * Outer arrow-into handler (canonical PM+CM pattern per
- * <https://prosemirror.net/examples/codemirror/>): when the outer PM cursor
- * is at a textblock boundary and the user presses an arrow key whose
- * natural target is this fallback block, nudge PM to land selection inside
- * the node. The RawMdxFallbackView's selectionUpdate effect (Precedent #31)
- * then forwards focus + caret into the nested CM.
+ * Direct PM dispatch pattern (Precedent #28), NOT y-codemirror.next. The RawMdxFallbackView's
+ * selectionUpdate effect (Precedent #31) then forwards focus + caret into the nested CM.
*/
import { RawMdxFallback as BaseRawMdxFallback } from '@inkeep/open-knowledge-core';
import type { Editor } from '@tiptap/core';
diff --git a/packages/app/src/editor/extensions/selection-state-plugin.ts b/packages/app/src/editor/extensions/selection-state-plugin.ts
index ec608b0df..f874ee16c 100644
--- a/packages/app/src/editor/extensions/selection-state-plugin.ts
+++ b/packages/app/src/editor/extensions/selection-state-plugin.ts
@@ -1,43 +1,6 @@
/**
- * SelectionStatePlugin — the canonical block-selection state store (Precedent #31).
- *
- * Derives a typed {selectedBlockId, ancestorChain, selectionOrigin, isDragging}
- * state from the current PM selection + event-classified origin. One source of
- * truth for every selection-adjacent surface — NodeView `data-*` attrs,
- * aria-live announcer, selection-anchored popovers.
- *
- * Replaces three patterns formerly duplicated across the codebase:
- * - `.is-selected` className toggled from `NodeViewProps.selected`.
- * - Per-NodeView `$pos.node(depth)` walks to compute ancestor chains.
- * - Ad-hoc `:has()`-based innermost-wins CSS rules.
- *
- * Read-only over the PM doc: never mutates document content. Meta-only
- * transactions ARE dispatched (see `scheduleRefresh` below) to flow
- * drag/selection signalling through PM's standard apply pipeline —
- * these carry no doc steps and leave the bridge invariant
- * unchanged.
- *
- * Origin classification is event-driven (not tx-heuristic): DOM
- * pointerdown/mousedown → 'pointer'; keydown on nav keys → 'keyboard'; a
- * transaction stamped with `SELECTION_ORIGIN_META_KEY` → 'programmatic'
- * (covers agent writes + imperative test-harness `setNodeSelection`). The
- * discipline of one typed meta key per origin category extends Precedent #1
- * (typed transaction origins).
- *
- * Drag tracking: HTML5 `dragstart` / `dragend` / `drop` on
- * `view.dom.parentElement` (the editor container — capture phase)
- * toggle `isDragging`. The CSS layer uses this to suppress the halo
- * mid-drag. `drop` is included because a cancelled drag sometimes ends
- * in a drop without a preceding dragend in current browser behavior.
- * The parentElement target is load-bearing: BlockDragHandle mounts its
- * draggable container as a sibling of view.dom — see the view() block
- * below for the bubble-vs-capture topology.
- *
- * Subscription model: the canonical React integration is
- * `useBlockSelection(editor)` (see `../hooks/use-block-selection.ts`), which
- * wires through TipTap's `transaction` + `selectionUpdate` events — the same
- * path used by BubbleMenu and SideMenu. Non-React callers read imperatively
- * via `getBlockSelection(editor)` and listen directly to TipTap events.
+ * SelectionStatePlugin — the canonical block-selection state store (Precedent #31). The discipline
+ * of one typed meta key per origin category extends Precedent #1 (typed transaction origins).
*/
import { type Editor, Extension } from '@tiptap/core';
@@ -63,17 +26,10 @@ export interface BlockSelection {
readonly rangeEncompassedBlockIds: ReadonlySet<string>;
}
-/** PM transaction meta key — consumers that want to override origin
- * classification set `tr.setMeta(SELECTION_ORIGIN_META_KEY, 'programmatic')`.
- * The plugin's `apply` checks this before consulting the DOM-event-derived
- * `pendingOrigin`. Used by agent writes and imperative `setNodeSelection`
- * in the test harness.
- *
- * Note on Precedent #1: that precedent governs Y.Doc transaction origins
- * (typed `LocalTransactionOrigin` objects, identity-matched). PM tr-meta
- * keys are a different surface — PM's `tr.getMeta(key)` API takes string
- * or PluginKey instances. We use a unique namespaced string here, in line
- * with PM convention. */
+/**
+ * Note on Precedent #1: that precedent governs Y.Doc transaction origins (typed
+ * `LocalTransactionOrigin` objects, identity-matched).
+ */
export const SELECTION_ORIGIN_META_KEY = 'selectionStatePlugin/origin';
const SELECTION_REFRESH_META_KEY = 'selectionStatePlugin/refresh';
diff --git a/packages/app/src/editor/extensions/source-dirty-observer.origin-guard.test.ts b/packages/app/src/editor/extensions/source-dirty-observer.origin-guard.test.ts
index bd05b8573..b7151a68b 100644
--- a/packages/app/src/editor/extensions/source-dirty-observer.origin-guard.test.ts
+++ b/packages/app/src/editor/extensions/source-dirty-observer.origin-guard.test.ts
@@ -1,34 +1,7 @@
/**
- * SourceDirtyObserver origin-guard regression test.
- *
- * Precedent #1 (typed transaction origins) exists because three shipped
- * three observer-bridge correctness bugs that all hinged on whether a CRDT
- * sync transaction was properly identified and skipped. This test drives
- * the source-dirty plugin at the PM-state level (the same surface the plugin
- * runs against in production inside a real EditorView + y-prosemirror). The
- * guard's truth table has three arms; this file owns the first two, and the
- * sibling suite `source-dirty-observer.autonomous-swap.test.ts` owns the third:
- *
- * 1. Transaction WITH `ySyncPluginKey` meta set → appendTransaction must
- * return null. This covers every CRDT-origin path: Observer A/B,
- * agent-write, rollback-apply, file-watcher, remote WebSocket. None
- * of these should flip `sourceDirty` on the local view.
- * 2. Transaction with NEITHER `ySyncPluginKey` meta nor the autonomous
- * stamp → appendTransaction must return a new tr that sets
- * `sourceDirty: true` on mutated jsxComponent nodes ONLY. Siblings with
- * no prop or content change must stay pristine (the reconstruction path
- * applies per-node, so any false-positive dirty on a sibling silently
- * corrupts unrelated content on save).
- * 3. Transaction carrying the autonomous stamp but no sync meta → must NOT
- * mark dirty; absence of sync meta alone is not user intent. Covered by
- * the sibling suite, not here.
- *
- * A future refactor that renames `ySyncPluginKey`, strips meta via an
- * intermediate plugin, or replaces the meta check with something else fails
- * this test before it can ship. Runs at the PM-state level rather than
- * through Hocuspocus because the guard's correctness is a per-transaction
- * property of the plugin itself — the multi-client integration harness
- * would add orders of magnitude of wall time without adding signal.
+ * Precedent #1 (typed transaction origins) exists because three shipped three observer-bridge
+ * correctness bugs that all hinged on whether a CRDT sync transaction was properly identified and
+ * skipped.
*/
import { getSchema } from '@tiptap/core';
diff --git a/packages/app/src/editor/extensions/suggestion-atomicity.dom.test.tsx b/packages/app/src/editor/extensions/suggestion-atomicity.dom.test.tsx
index d1d362a0a..6fea7f255 100644
--- a/packages/app/src/editor/extensions/suggestion-atomicity.dom.test.tsx
+++ b/packages/app/src/editor/extensions/suggestion-atomicity.dom.test.tsx
@@ -1,29 +1,6 @@
/**
- * Generalized one-transaction pin for every non-slash `@tiptap/suggestion`
- * surface (precedent #58): tag (`#`), wiki-link (`[[`), and the Ask-AI
- * composer's `@`-mention. The slash menu has its own pin with an
- * interleaved-transaction consequence test in
- * `slash-command-atomicity.dom.test.tsx`.
- *
- * The invariant: selecting a suggestion item must land the trigger-range
- * delete and the content insert as ONE doc-changing transaction. If they land
- * as two, a transaction dispatched re-entrantly during the delete's own
- * dispatch (a plugin `appendTransaction`, a view update, or the y-prosemirror
- * binding reacting to the delete) can remap the selection onto an adjacent
- * `selectable: true` node, and the insert then REPLACES that node — silent
- * data loss.
- *
- * This is the runtime complement to the `no-split-suggestion-dispatch`
- * oxlint rule: the lint catches a bare trigger-delete dispatch statically;
- * this test drives each surface through a real Enter keydown (the production
- * `command` callbacks are closure-held inside the Suggestion plugins, so the
- * keydown path is the only way to run them) and asserts the
- * exactly-one-doc-changing-transaction oracle end to end — including any
- * second dispatch the lint cannot see.
- *
- * Corpus fetches (`/api/tags`, `/api/pages`) are stubbed at `global.fetch`;
- * every other endpoint returns a non-ok response, which each surface
- * tolerates by design (ranking context and asset lists degrade to empty).
+ * One-transaction pin for every non-slash `@tiptap/suggestion` surface (precedent #58): tag,
+ * wiki-link and the Ask-AI `@`-mention each land trigger delete and insert as one transaction.
*/
import { cleanup } from '@testing-library/react';
diff --git a/packages/app/src/editor/hooks/use-block-selection.ts b/packages/app/src/editor/hooks/use-block-selection.ts
index d94c5cb84..427025591 100644
--- a/packages/app/src/editor/hooks/use-block-selection.ts
+++ b/packages/app/src/editor/hooks/use-block-selection.ts
@@ -1,26 +1,6 @@
/**
- * useBlockSelection — React hook that exposes `SelectionStatePlugin` state
- * (Precedent #31) to the React tree.
- *
- * Implementation: subscribes to TipTap's `transaction` + `selectionUpdate`
- * events — the canonical TipTap integration pattern (same path used by
- * BubbleMenu, official example at tiptap.dev/guide/node-views#react).
- *
- * Stores the plugin snapshot in local state; the local state is updated
- * inside an event handler on every transaction/selection tick. React
- * re-renders whenever the snapshot reference changes (plugin's
- * `deriveBlockSelection` preserves identity on structural no-op so unrelated
- * text edits don't trigger re-renders).
- *
- * Why not `useSyncExternalStore` via the plugin's view.update notifier:
- * empirically, React 19 + Strict Mode +
- * the plugin-view update timing produced cases where the listener fired
- * on an effect instance whose setState didn't propagate to a re-render.
- * Wiring through `editor.on('transaction')` makes the subscription
- * lifecycle TipTap-owned, which is proven out by the existing BubbleMenu
- * + SideMenu implementations in this codebase.
- *
- * Returns `null` for a null editor (safe pre-mount rendering).
+ * useBlockSelection — React hook that exposes `SelectionStatePlugin` state (Precedent #31) to the
+ * React tree.
*/
import type { Editor } from '@tiptap/core';
diff --git a/packages/app/src/editor/mount-promise.test.ts b/packages/app/src/editor/mount-promise.test.ts
index ef056286c..32b52d8e1 100644
--- a/packages/app/src/editor/mount-promise.test.ts
+++ b/packages/app/src/editor/mount-promise.test.ts
@@ -1,12 +1,4 @@
-/**
- * Unit tests for mount-promise: module-level promise cache for the Pattern D
- * (Suspense + `use(promise)`) TipTap mount-split. Mirrors precedent #18(d)
- * sync-promise.test.ts shape.
- *
- * Tests use the same fake-DOM + fake-Editor harness as editor-cache.test.ts
- * (Bun test env has no DOM globals; we install a minimal `globalThis.document`
- * stub before the suites that exercise the cache-MISS path).
- */
+/** Mirrors precedent #18(d) sync-promise.test.ts shape. */
import type { HocuspocusProvider } from '@hocuspocus/provider';
import type { Editor } from '@tiptap/core';
diff --git a/packages/app/src/editor/mount-promise.ts b/packages/app/src/editor/mount-promise.ts
index 8d5f6e5d9..9f67fcb2a 100644
--- a/packages/app/src/editor/mount-promise.ts
+++ b/packages/app/src/editor/mount-promise.ts
@@ -1,73 +1,6 @@
/**
- * mountTiptapEditorPromise — Suspense + `use(promise)` primitive that splits
- * TipTap's monolithic `new Editor({ element })` cold-mount task into
- * [yield → construct → yield → mount] so the longest synchronous task drops
- * below the perception band on PROJECT-class docs. The pre-construct yield
- * is load-bearing for sibling-subtree paint (sidebar, top bar) — without it,
- * construct()'s synchronous initProseMirrorDoc walk shares a task with the
- * entry-setup microtask and blocks paint for the whole window.
- *
- * Mirrors precedent #18(d) (`sync-promise.ts`) shape — one Suspense-async
- * substrate for "wait for one-shot lifecycle event" across the codebase, not
- * two. Module-level `Map<docName, Entry>` cache; promise identity stable
- * across renders (React Compiler-safe — module state is out of compiler
- * scope, and `use(promise)` requires the same reference across remounts /
- * StrictMode double-invoke to avoid infinite suspension).
- *
- * Differs from `sync-promise.ts` by intentional omission: no
- * `rejectMountPromise` external-injection helper. All mount-promise failures
- * originate inside its own body (construct / yield / mount / register), so
- * the test surface that sync-promise needs for ProviderPool's
- * `BridgeSetupError` injection has no equivalent here.
- *
- * Lifecycle:
- * - `mountTiptapEditorPromise({ docName, mountId, construct, sizeStats })`
- * - V2 cache HIT (entry already cached): returns Promise.resolve(entry)
- * after delegating to `mountTiptapEditor` for the reparent path. No
- * construction, no yield, no mount() call.
- * - V2 cache MISS: runs `await scheduler.yield()` → `construct()` →
- * `await scheduler.yield()` (native on Chromium/Electron, polyfilled
- * via MessageChannel → requestIdleCallback → setTimeout on
- * Safari/Firefox) → `editor.mount(transientDiv)` → registers with V2
- * cache via `mountTiptapEditor` with a no-op factory → resolves with
- * entry.
- * - `invalidateMountPromise(docName)` silently tears down the entry: aborts
- * in-flight construction so the body destroys the pre-mount editor; the
- * promise is left orphaned (NOT settled) so React's `use()` consumers
- * that have already unmounted (the typical cancellation path) never see
- * a rejection. Cache-driven invalidation must be invisible — surfacing
- * a `MountAbortError` for an LRU eviction the user never requested is
- * wrong UX. UI-explicit cancellation routes through
- * `getMountAbortController(docName)?.abort()` which DOES reject.
- *
- * Stalled-but-pending observability (precedent 41):
- * - At `MOUNT_STALLED_THRESHOLD_MS` (10s default), the substrate emits
- * `ok/mount/stalled` ONCE per entry and the promise STAYS pending.
- * Slow IDB hydrate, network partition, hung WebSocket — none are an
- * auto-failure signal. The substrate emits the observability mark and
- * waits; the user (via the cancel affordance, which subscribes to
- * the stalled mark) decides whether to abort.
- * - `__reapStalledOnVisible(now)` re-checks every pending entry on
- * `document.visibilitychange → 'visible'` so a tab that backgrounded
- * past the threshold while `setTimeout` was throttled still emits the
- * stalled mark on tab restore. Idempotent install/uninstall — the
- * handler registers once when the cache becomes non-empty and
- * uninstalls when the cache empties (so test-harness leak checks pass).
- *
- * Cache-entry persistence — load-bearing for two correctness properties
- * (mirrors `syncPromise` lifecycle docstring rationale):
- * 1. Rejection (from explicit `controller.abort()`) survives React
- * re-render so use() re-throws synchronously to DocumentErrorBoundary
- * instead of fresh warm-path-resolving on a next render.
- * 2. Resolved entry stays in cache so repeat calls return the same
- * reference — once React has marked it `.status='fulfilled'`,
- * subsequent use() calls short-circuit without a Suspense cycle.
- *
- * Pre-mount editors count toward `ACTIVITY_MOUNT_LIMIT` from the moment
- * `mountTiptapEditorPromise` returns the promise — the V2 cache treats the
- * factory-return point as the activity boundary, not mount-completion. This
- * keeps the concurrent-active-editor budget bounded across the construction-
- * to-mount window.
+ * Mirrors precedent #18(d) (`sync-promise.ts`) shape — one Suspense-async substrate for "wait for
+ * one-shot lifecycle event" across the codebase, not two.
*/
import type { HocuspocusProvider } from '@hocuspocus/provider';
@@ -329,17 +262,8 @@ interface MountBodyParams {
}
/**
- * Destroy a pre-mount editor with the same UndoManager-restore cleanup that
- * `editor-cache.ts` applies at park / evict (precedent #18(c) leak-cleanup).
- * Capturing the UndoManager BEFORE `editor.destroy()` is required because
- * `editor.state` is only safely readable while the editor is alive; clearing
- * `restore` AFTER destroy breaks the @tiptap/extension-collaboration closure
- * that retains the full editor graph (~30 MB per cycle on multi-MB docs).
- *
- * Idempotent on pre-mount editors per TipTap source verification. Emits a
- * telemetry mark on destroy() failure so a regression in TipTap's pre-mount-
- * destroy idempotency surfaces in traces rather than vanishing — mirrors
- * `editor-cache.ts`'s `ok/cache/evict-failed` discipline.
+ * Destroy a pre-mount editor with the same UndoManager-restore cleanup that `editor-cache.ts`
+ * applies at park / evict (precedent #18(c) leak-cleanup).
*/
function destroyPreMountEditor(
docName: string,
diff --git a/packages/app/src/editor/observer-sync.test.ts b/packages/app/src/editor/observer-sync.test.ts
index bec36b78c..51e6b163c 100644
--- a/packages/app/src/editor/observer-sync.test.ts
+++ b/packages/app/src/editor/observer-sync.test.ts
@@ -1,9 +1,7 @@
/**
- * Observer sync tests — shimmer prevention.
- *
- * Cross-CRDT sync tests (Observer A writing Y.Text, Observer B writing XmlFragment)
- * live in server-observers.test.ts and C1-C10 integration tests (server-authoritative
- * architecture, precedent #14). This file covers client-side shimmer prevention only.
+ * Cross-CRDT sync tests (Observer A writing Y.Text, Observer B writing XmlFragment) live in
+ * server-observers.test.ts and C1-C10 integration tests (server-authoritative architecture,
+ * precedent #14).
*/
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/src/editor/observers.ts b/packages/app/src/editor/observers.ts
index 8add32251..c976ba054 100644
--- a/packages/app/src/editor/observers.ts
+++ b/packages/app/src/editor/observers.ts
@@ -1,33 +1,7 @@
/**
- * Client-side observer shell for Y.XmlFragment and Y.Text.
- *
- * Cross-CRDT sync writes run exclusively on the server observer module at
- * `packages/server/src/server-observers.ts` (precedent #14). The
- * historical client-side debounce + per-doc `TypingState` machinery was
- * deleted. Precedent #13(b) — no wall-clock `setTimeout` in bridge
- * observer files; the grep gate at
- * `packages/server/src/bridge-no-wallclock.test.ts` pins this.
- *
- * The shell's surface reduces to:
- * 1. Own the `ORIGIN_TREE_TO_TEXT` / `ORIGIN_TEXT_TO_TREE` object
- * identities required by the bridge-invariant watcher's enforcing
- * set (precedent #1 identity match).
- * 2. Record keystroke timestamps via `markUserTyping` for the
- * `SystemDocSubscriber` agent-presence typing guard (global wall-clock
- * timestamp, not per-doc state).
- *
- * The observer callbacks themselves are intentionally empty: the server
- * owns cross-CRDT propagation (precedent #14), and the server's Observer
- * B already performs parse validation with the same `MarkdownManager`
- * and the same transient-error classification. A redundant client-side
- * parse per Y.Text transaction was blocking the main thread on every
- * source-mode keystroke and on every chunk of `chunkedYTextInsert` —
- * the rAF yields in `chunked-insert.ts` intended to keep a >500 KB paste
- * at 60fps were ineffective because the observer callback ran
- * synchronously inside each `ydoc.transact()` before the yield. Deleting
- * the client-side parse restores the intended responsiveness. Errors
- * still surface via the server-side path (`serverObserverErrorsB`
- * counter + structured logs) with a ~5-10 ms WebSocket RTT delay.
+ * Client-side observer shell. Cross-CRDT sync writes run exclusively on the server observer
+ * module (precedent #14), so the callbacks here are intentionally empty; the shell owns only the
+ * `ORIGIN_TREE_TO_TEXT` / `ORIGIN_TEXT_TO_TREE` identities the bridge watcher matches (#1).
*/
import type { LocalTransactionOrigin } from '@hocuspocus/server';
@@ -36,21 +10,9 @@ import type { Schema } from '@tiptap/pm/model';
import type * as Y from 'yjs';
/**
- * Transaction origin for Observer A (historical tree → text direction).
- *
- * Precedent #1 (CLAUDE.md): all Y.Doc transaction origins are
- * `LocalTransactionOrigin` OBJECT references, never raw strings.
- * `Set.has()` matching in `trackedOrigins` or the bridge-invariant
- * watcher's `BRIDGE_ENFORCING_ORIGINS` set is identity-based — a string
- * literal would silently fail to match the production tx.origin object.
- *
- * `as const satisfies` (Matt Pocock's "deeply read-only config" pattern)
- * produces a `Readonly<...>` sentinel whose field types are all narrow
- * literals — makes the singleton-immutability intent explicit at the type
- * level alongside the identity-match guarantee.
- *
- * Kept for identity-stable membership in the enforcing set even though
- * client observers no longer write the derived CRDT (precedent #14).
+ * Precedent #1 (CLAUDE.md): all Y.Doc transaction origins are `LocalTransactionOrigin` OBJECT
+ * references, never raw strings. Kept for identity-stable membership in the enforcing set even
+ * though client observers no longer write the derived CRDT (precedent #14).
*/
export const ORIGIN_TREE_TO_TEXT = {
source: 'local',
@@ -71,15 +33,8 @@ export function getLastUserKeystroke(): number {
}
/**
- * Mark that the local user just typed. Call from the editor's DOM event
- * handlers (keydown, paste, drop, etc.). Updates the global keystroke
- * timestamp consumed by `SystemDocSubscriber`'s agent-presence typing guard.
- *
- * Previous iterations accepted a `Y.Doc` parameter that drove per-doc
- * typing-defer state; that state was deleted under server-authoritative
- * bridge + settlement dispatch (precedent #14). The
- * zero-arg shape pins the reduced surface so callers don't hold onto
- * `provider.document` unnecessarily.
+ * Previous iterations accepted a `Y.Doc` parameter that drove per-doc typing-defer state; that
+ * state was deleted under server-authoritative bridge + settlement dispatch (precedent #14).
*/
export function markUserTyping(): void {
lastGlobalUserKeystrokeMs = Date.now();
@@ -91,26 +46,17 @@ interface ObserverDeps {
ytext: Y.Text;
mdManager: MarkdownManager;
/**
- * ProseMirror schema — retained in the interface for call-site
- * compatibility with the prior client-observer signature. No longer
- * used by the observer body under precedent #14; the server observer
- * owns all schema-involving mutations.
+ * No longer used by the observer body under precedent #14; the server observer owns all
+ * schema-involving mutations.
*/
schema?: Schema;
onSyncError?: (direction: 'tree-to-text' | 'text-to-tree', error: Error) => void;
}
/**
- * Attach the client observer shell to a Y.Doc.
- *
- * Both callbacks are intentionally empty — the server owns cross-CRDT
- * propagation (precedent #14) and also runs parse validation on Y.Text
- * via its own Observer B (`packages/server/src/server-observers.ts`).
- * Subscribing here keeps the callback slots wired for future read-side
- * instrumentation and makes the teardown path symmetric.
- *
- * Returns a cleanup function that detaches both callbacks. No timers to
- * clear — precedent #13(b) forbids wall-clock `setTimeout` here.
+ * Attaches the client observer shell to a Y.Doc. Both callbacks are intentionally empty because
+ * the server owns cross-CRDT propagation (precedent #14); the returned cleanup detaches them and
+ * has no timers to clear, since precedent #13(b) forbids wall-clock `setTimeout` here.
*/
export function setupObservers(deps: ObserverDeps): () => void {
const { xmlFragment, ytext } = deps;
diff --git a/packages/app/src/editor/page-list-cache.ts b/packages/app/src/editor/page-list-cache.ts
index 3b3bc2d2b..f94dca1fa 100644
--- a/packages/app/src/editor/page-list-cache.ts
+++ b/packages/app/src/editor/page-list-cache.ts
@@ -1,39 +1,7 @@
/**
- * Page-list side-channel for plain-DOM chip consumers.
- *
- * InternalLink + WikiLink chips render via renderHTML (PM layer, no React
- * context access). They still need live resolution-state classification —
- * `pages: Set<string>` + `folderPaths: Set<string>` — normally provided by
- * <PageListProvider /> via React context + usePageList().
- *
- * This module is the bridge:
- * - PageListProvider calls setPageListCache({pages, folderPaths, assetPaths}) on value change.
- * - Chip PM plugins call subscribePageListCache(fn) to dispatch decoration refresh
- * when page list mutates; they read via getPageListCache() inside decorations(state).
- *
- * Design notes
- * ------------
- * - Change detection via Set-content equality so render-frequent setPageListCache
- * calls with stable content don't storm subscribers. Single writer (provider);
- * many readers (PM plugins). No locking required — React renders and PM plugin
- * dispatches both run on the main thread synchronously.
- * - Reads are synchronous + cheap. Subscribers receive the snapshot on invocation
- * so they don't need a separate getPageListCache() call.
- * - DEV-only `window.__okPageListCache` write (gated on import.meta.env?.DEV per
- * the repo's DEV-gated test-hook convention — precedent #20(b)). Debug-visible
- * in devtools; stripped in production bundles.
- *
- * Scope carve-outs
- * ----------------
- * - This module is purely a store. The PageListProvider → setPageListCache
- * wiring lives in `PageListContext.tsx` (a useEffect that publishes
- * {pages, folderPaths} on every render — no-ops absorbed by the equality gate).
- * - Consumer renderDecorationRefresh is a separate concern (the PM plugin in
- * internal-link.ts will subscribe here and dispatch a transaction carrying
- * a custom meta to force mark-identity-decoration re-run).
- *
- * @see packages/app/src/editor/extensions/mark-identity-decoration.ts
- * @see packages/app/src/editor/extensions/mark-interaction-bridge.ts
+ * Subscribers receive the snapshot on invocation so they don't need a separate getPageListCache()
+ * call. - DEV-only `window.__okPageListCache` write (gated on import.meta.env?.DEV per the repo's
+ * DEV-gated test-hook convention — precedent #20(b)).
*/
import { buildPagesByBasenameIndex, buildPagesBySlugIndex } from '@inkeep/open-knowledge-core';
diff --git a/packages/app/src/editor/provider-pool.ts b/packages/app/src/editor/provider-pool.ts
index 49ee1e2bd..bdf900197 100644
--- a/packages/app/src/editor/provider-pool.ts
+++ b/packages/app/src/editor/provider-pool.ts
@@ -206,20 +206,9 @@ export const FORCE_SYNC_INTERVAL_MS = 5_000;
const MAX_BUFFER_BYTES = readNumericOverride('MAX_BUFFER_BYTES', 1 * 1024 * 1024);
/**
- * Default pool capacity. Exported so the single point of truth lives in this
- * module (the pool that owns the constraint), and so callers that construct
- * a `ProviderPool` can reference the same name rather than a magic literal.
- *
- * Coupled to `ACTIVITY_MOUNT_LIMIT = 3` (exported from `EditorActivityPool.tsx`)
- * per precedent #18(c): `MAX_POOL` bounds how many warm
- * providers we keep; `ACTIVITY_MOUNT_LIMIT` bounds how many editor subtrees
- * are Activity-mounted inside those providers. The two constraints are
- * intentionally independent — pool-resident-but-not-Activity-mounted docs
- * keep their warm provider (≈5–10 MB) for fast Suspense-gated remount
- * without paying per-editor memory or observer-CPU cost.
- *
- * Changing either constant is an ASK_FIRST boundary. If one moves,
- * audit the other for sympathetic impact.
+ * Default pool capacity, coupled to `EditorActivityPool.tsx`'s `ACTIVITY_MOUNT_LIMIT` per
+ * precedent #18(c): this bounds warm providers, that one bounds Activity-mounted editor subtrees.
+ * Moving either constant needs the other audited.
*/
export const MAX_POOL = readNumericOverride('MAX_POOL', 10);
diff --git a/packages/app/src/editor/registry/index.ts b/packages/app/src/editor/registry/index.ts
index b65010a4d..f348eb135 100644
--- a/packages/app/src/editor/registry/index.ts
+++ b/packages/app/src/editor/registry/index.ts
@@ -1,40 +1,6 @@
/**
- * App-side descriptor registry — decorates core's `ComponentRegistry`
- * with React component implementations from `componentMap`.
- *
- * Core owns the wildcard-fallback semantic (`getOrWildcard`) and the
- * built-in manifest. The app layer adds a per-name `{ Component,
- * reactNodePropNames }` decoration lookup and routes meta reads through
- * the core factory.
- *
- * ## Extensibility (today: the 5-pack only)
- *
- * The current 5-pack ships fully sealed: `componentMap` is a static
- * `Record<string, ComponentType>` populated at module init from the
- * built-in imports (Callout/Image/Video/Audio/Accordion + wildcard).
- * The decoration `Map` is also populated once at module init by walking
- * `coreRegistry.entries()`, so a post-init `coreRegistry.set('Widget',
- * meta)` would land `meta` in the metadata registry but produce NO
- * matching decoration — `getDescriptor('Widget')` would fall through to
- * the `'*'` wildcard, ignoring the new metadata's `props` / `Component`
- * /`hasChildren`.
- *
- * User-registered custom components (deferred) would convert
- * `coreRegistry.set` into a true runtime extensibility surface. Two paths
- * are open and both stay additive:
- * (a) Lazy-build decorations: `getDescriptor` looks up
- * `coreRegistry.get(name)` on miss and synthesizes a
- * decoration from a registered React component AND a future
- * `registerComponent(name, Component)` API on `componentMap`.
- * (b) Hand the `componentMap` registration responsibility to the
- * embedder via a host-API wrapper — same shape as fumadocs's
- * `mdxComponents` registry.
- * Either path is greenfield-compatible with the precedent #9
- * schema-add-only contract; the choice depends on whether the
- * extension surface lands as a host-API (b) or in-product (a).
- *
- * Callers MUST treat the registry as read-only at runtime —
- * `coreRegistry.set` exists for module-init seeding only.
+ * Either path is greenfield-compatible with the precedent #9 schema-add-only contract; the choice
+ * depends on whether the extension surface lands as a host-API (b) or in-product (a).
*/
import { createRegistry, type JsxComponentMeta, type PropDef } from '@inkeep/open-knowledge-core';
import { componentMap } from '../components/componentMap.tsx';
diff --git a/packages/app/src/editor/replay-outbox.ts b/packages/app/src/editor/replay-outbox.ts
index 2a6229af2..ebcf0848e 100644
--- a/packages/app/src/editor/replay-outbox.ts
+++ b/packages/app/src/editor/replay-outbox.ts
@@ -1,110 +1,7 @@
/**
- * Durable, epoch-agnostic replay outbox for the `server-instance-mismatch`
- * recycle.
- *
- * The provider pool's in-memory `bufferedUpdates` map loses its content if the
- * tab dies inside the recycle window (`clearData()` → recycle → first
- * `synced`). This outbox is the durable carrier: the unsynced edit's full
- * pre-recycle state is written here BEFORE `clearData()` wipes the y-indexeddb
- * store, and read back on the next open of the doc — surviving a tab crash at
- * any point up to the replay.
- *
- * It is a SEPARATE IndexedDB database
- * (`ok-replay-outbox[:<project digest>]:<branch>:<docName>` — the project
- * segment is absent on a null namespace), NEVER the y-indexeddb
- * `updates` store: hydrating the pre-recycle bytes back into the fresh Y.Doc
- * is exactly the content-duplication class `clearData` exists to prevent. The
- * reopen path reads this store explicitly and feeds the bytes through the
- * CONTENT-level replay (rebuild a replica, splice the recovered string) rather
- * than a Y.Doc merge.
- *
- * The db name is project+branch+docName scoped (not epoch-scoped): the
- * post-recycle `serverInstanceId` is unknown when the buffer is captured (the
- * client nulls its cached id and only relearns it from the reconnect
- * handshake), so the epoch cannot be part of the key.
- *
- * The project component is REQUIRED for every desktop window, and omitted
- * only for a null namespace, where the origin already isolates — that is
- * `precedent #59`, applied here through `scopedStorageKey`
- * (`lib/storage-scope.ts`), not re-derived. What is specific to THIS
- * store: `docName` is repo-root-relative and branch names repeat, so two
- * worktrees of one repository on the same branch address the same doc path,
- * and the payload here is buffered document content — so a collision crosses
- * edits between projects rather than raising an error. The sibling
- * y-indexeddb store in `client-persistence.ts` is safe without a project
- * component only because its name carries the per-process `serverInstanceId`,
- * which this one cannot have; the omission of the epoch does not license
- * omitting project identity.
- *
- * `namespace` is threaded in from the caller rather than resolved in here, and
- * travels in a NAMED field (`ReplayOutboxKey`) rather than a positional slot.
- * Requiredness only forces a value to be supplied; naming is what stops a
- * wrong one — three bare strings in a row compile in any order.
- *
- * A namespace change renames the database, so an entry written under a
- * different one is not read back. That has three causes, all accepted:
- *
- * 1. The one-time upgrade from the pre-scoping name. Deliberately NOT
- * migrated: adopting an unscoped record would import the cross-project
- * content this scoping removes, which is the bug. Electron only, since a
- * null namespace reproduces the old name exactly. The stranded set is
- * every LIVE pre-scoping record, not just one caught mid-recycle. Every
- * consume path runs INSIDE a live session: a reopen's replay, or an
- * intentional discard through `discardBufferedUpdate` (see its docblock for
- * the full trigger set). The RAM buffer's `durable` flag
- * gates every one of those EXCEPT the reopen that finds no RAM buffer at
- * all — the tab-died case this outbox exists for, which reads the record
- * directly and claims it unconditionally. Ordinary app termination — quit,
- * force-quit, `quitAndInstall` — runs none of them. So a doc not reopened
- * between its write and the upgrade keeps an unreachable record. Stranding
- * is also silent: a null read is indistinguishable from "nothing to
- * recover".
- * 2. Ongoing: the namespace is the project path AS THE USER PICKED IT, not
- * its realpath (`window-manager.ts` keeps `projectPath` and `canonicalKey`
- * deliberately distinct, and the renderer is handed the former). So
- * reopening one project under a different spelling of the same path
- * (`/tmp` vs `/private/tmp`, a symlinked cwd, Windows drive-letter case)
- * reads a different name and misses its own parked edit.
- * 3. A revert of this change orphans records written under the NEW name, for
- * the same reason as (1) — the desktop updater rolls forward only, so a
- * rollback ships as a revert.
- *
- * Case 2 costs a missed recovery on a best-effort mechanism; the collision it
- * replaces silently applied ANOTHER project's content. Canonicalizing is
- * additive rather than blocked — `window-manager.ts` already computes
- * `canonicalKey`, and identity reaches the renderer as independently-parsed
- * spawn args — but it touches the desktop spawn surface and every
- * editor-window path, so it is deferred rather than bundled here.
- *
- * Durable recovery requires `indexedDB.databases()` (Baseline). On engines
- * without it EVERY operation no-ops (degrade to RAM-only): the read/consume
- * because they cannot probe for existence without `open` creating an empty
- * database on a normal doc open, and the WRITE because a record no reader can
- * ever see is a full doc-state payload stranded in storage forever. The write
- * reports that with a `false` return so the caller knows the buffer is
- * RAM-only.
- *
- * The single `(namespace, branch, docName)` record is also the CROSS-TAB
- * exactly-once token: tabs resolving the same namespace share it, so
- * `consumeReplayOutboxEntry` reports whether THIS caller was the one that
- * removed a live record. Its count+delete run in one `readwrite` transaction,
- * and IndexedDB serializes overlapping readwrite transactions across
- * connections, which makes the pair an atomic compare-and-claim rather than a
- * check-then-act.
- *
- * Consumed entries leave an empty outbox database behind (record deleted, DB
- * kept) rather than racing a `deleteDatabase` against a concurrent reopen —
- * a bounded, per-docName storage-hygiene cost matching the `_unknown_`-branch
- * orphan note in `client-persistence.ts`.
- *
- * Every operation is deadline-bounded. The recycle path awaits the write
- * BEFORE `clearData()`, so an IDB stall that never settles would strand the
- * whole recovery (no clear, no recycle, `mismatchInFlight` pinned, flush-on-
- * hide inert) — the same hazard `withClearDataTimeout` already bounds on the
- * sibling clear. Note the bound is NOT an `onblocked` substitute: these opens
- * are versionless, so they never request a version change and can never fire
- * `blocked` (only `deleteDatabase` and an upgrading open can). The deadline
- * covers the general stall, not a version-change block.
+ * The project component is REQUIRED for every desktop window, and omitted only for a null
+ * namespace, where the origin already isolates — that is `precedent #59`, applied here through
+ * `scopedStorageKey` (`lib/storage-scope.ts`), not re-derived.
*/
import { scopedStorageKey } from '@/lib/storage-scope';
diff --git a/packages/app/src/editor/selection/entry-label.ts b/packages/app/src/editor/selection/entry-label.ts
index 6c9eaf73a..12e7b4852 100644
--- a/packages/app/src/editor/selection/entry-label.ts
+++ b/packages/app/src/editor/selection/entry-label.ts
@@ -1,18 +1,7 @@
/**
- * Shared label resolver for `BlockChainEntry` consumers (SelectionAnnouncer,
- * and any future selection-consuming UI — link editor, image caption,
- * collaborator presence pin, per Precedent #31).
- *
- * Fallback ladder:
- * 1. registered descriptor's `displayName`
- * 2. registered descriptor's `name`
- * 3. entry's `componentName` (wildcard case — descriptor name/displayName
- * are both `'*'`, useless as trail labels)
- *
- * `unregisteredSuffix: true` appends ` (unregistered)` in the wildcard case —
- * appropriate for assistive-technology announcements where AT users benefit
- * from knowing why a label is unfamiliar. Visual surfaces leave it off to
- * avoid repeated noise.
+ * Shared label resolver for `BlockChainEntry` consumers, per precedent #31: descriptor
+ * `displayName`, then `name`, then the entry's `componentName` for the wildcard case, with
+ * `unregisteredSuffix` appending ` (unregistered)` for assistive-technology surfaces.
*/
import type { BlockChainEntry } from '../extensions/selection-state-plugin.ts';
diff --git a/packages/app/src/editor/slash-command/apply-item.dom.test.tsx b/packages/app/src/editor/slash-command/apply-item.dom.test.tsx
index 789c130c5..ea5e8c8a9 100644
--- a/packages/app/src/editor/slash-command/apply-item.dom.test.tsx
+++ b/packages/app/src/editor/slash-command/apply-item.dom.test.tsx
@@ -1,24 +1,4 @@
-/**
- * Error-path pins for `applySlashCommandItem` (precedent #58 boundary).
- *
- * The happy-path single-transaction semantics are pinned in
- * `../extensions/slash-command-atomicity.dom.test.tsx`; this file pins the
- * three deliberate failure-mode behaviors of the boundary:
- *
- * 1. An item whose `command` throws must NOT roll back the trigger-range
- * delete — the chain's `.command()` step returns true unconditionally so
- * the user's `/query` text does not survive a broken item. The failure
- * is surfaced via `console.error` after the dispatch.
- * 2. A throwing `afterCommit` callback must not starve the remaining
- * deferred callbacks, and its log message must be distinguishable from
- * an item-command failure (the two share a catch-shaped code path but
- * mean different things when debugging).
- * 3. A throwing item must not poison the dispatch: the delete still lands
- * as a doc-changing transaction and the editor stays usable.
- *
- * Tier: `.dom.test.tsx` (jsdom) — `applySlashCommandItem` drives a real
- * `editor.chain()`, so it needs a mounted TipTap Editor.
- */
+/** Error-path pins for `applySlashCommandItem` (precedent #58 boundary). */
import { cleanup } from '@testing-library/react';
import { Editor } from '@tiptap/core';
diff --git a/packages/app/src/editor/sync-promise.ts b/packages/app/src/editor/sync-promise.ts
index a59be4472..84eca3802 100644
--- a/packages/app/src/editor/sync-promise.ts
+++ b/packages/app/src/editor/sync-promise.ts
@@ -143,44 +143,9 @@ function detach(entry: CacheEntry): void {
}
/**
- * Returns the cached promise for `docName`, creating one if absent.
- *
- * **Cache lifecycle:** entries persist across resolution and rejection — they
- * are removed only by `invalidateSyncPromise` (or by `ProviderPool.destroyEntry`
- * which calls invalidate). This is load-bearing for two distinct correctness
- * properties:
- *
- * 1. **Rejection survives React re-render.** When a syncPromise rejects, the
- * DocumentBoundary's `use()` re-throws and the React error boundary
- * schedules a re-render. During that re-render, DocumentBoundary calls
- * `syncPromise(docName, provider)` again. If the cache had been cleared
- * on rejection, syncPromise would create a NEW promise — and for a
- * warm provider (`provider.synced=true`), the warm-path would resolve
- * immediately, masking the prior rejection. The boundary would never
- * catch and the user would see a broken editor instead of the error UI.
- * Keeping the rejected promise in cache means React's `use()` sees the
- * same `.status='rejected'` thenable and throws synchronously.
- *
- * 2. **Warm-path stability.** Repeat calls return the same resolved promise
- * reference — once React has marked it `.status='fulfilled'`, subsequent
- * `use()` calls short-circuit without a Suspense cycle.
- *
- * The promise resolves when the given provider next emits `synced`, rejects
- * with `PreSyncDisconnectError` if the provider emits `close` before `synced`,
- * and rejects with `SyncTimeoutError` after 30s. Call `invalidateSyncPromise`
- * to tear down (drops the entry; the orphaned promise neither resolves nor
- * rejects further).
- *
- * **Warm-provider fast path:** if the provider has already synced (e.g.
- * pool-resident from a prior mount), `provider.synced` is true and the
- * `'synced'` event has already fired and will not fire again — Hocuspocus's
- * `set synced(value)` is a no-op when the value is unchanged. Returning a
- * pre-resolved promise here is what makes the "cold mount, warm content" path
- * (precedent #18(c)) work — without this gate, every
- * Activity-evicted-but-pool-resident revisit would hang for 30s waiting on a
- * listener that can never fire. The first call still pays one Suspense cycle
- * (Promise.resolve has no React `.status` field on first read); subsequent calls
- * return the same cached reference and short-circuit.
+ * Returning a pre-resolved promise here is what makes the "cold mount, warm content" path
+ * (precedent #18(c)) work — without this gate, every Activity-evicted-but-pool-resident revisit
+ * would hang for 30s waiting on a listener that can never fire.
*/
export function syncPromise(docName: string, provider: HocuspocusProvider): Promise<void> {
const existing = cache.get(docName);
diff --git a/packages/app/src/editor/utils/editor-visible-region.ts b/packages/app/src/editor/utils/editor-visible-region.ts
index aaa73ea15..7b3d92254 100644
--- a/packages/app/src/editor/utils/editor-visible-region.ts
+++ b/packages/app/src/editor/utils/editor-visible-region.ts
@@ -30,39 +30,9 @@ interface EditorSizeOptions {
}
/**
- * Floating-UI clipping options that keep selection-anchored menus inside the
- * editor's *visible* content region, not just inside the viewport.
- *
- * `.editor-doc-scroll` clips the document, but the region where a selection
- * actually reads as visible is smaller than the container's box: the
- * EditorToolbar overlays the container's top exclusion zone, and the Ask AI
- * bottom composer (stacked above the conflict-resolution footer when one is
- * up) floats over the container's bottom edge. None of these are clipping
- * ancestors, so a body-appended `position: fixed` bubble menu keeps tracking
- * a selection that has scrolled behind them — sliding over the composer card
- * and the status footer below the container.
- *
- * Pass the result to `flip()` so placement decisions stay inside the visible
- * region, to `hide()` (default strategy `referenceHidden`) so the menu
- * disappears once the selection itself is fully occluded — matching what the
- * user can see rather than what the DOM clips — and to
- * `deriveEditorShiftOptions` below, which converts this description of the
- * region into the clamp that keeps a surface inside it. A boundary handed to
- * `flip()`/`hide()` alone detects the overflow and then declines to correct
- * it, so the producers are consumed together — and where the surface can be
- * wider than the pane, with `deriveEditorSizeOptions` as well, since the
- * clamp has nowhere to put a surface that does not fit.
- *
- * Floating UI is the canonical positioning primitive for selection-anchored
- * overlays (precedent #35), and this module owns the visible-region half of
- * that contract for any surface anchored inside the editor's scrollable
- * content. It lives under `editor/utils/` rather than beside any one consumer
- * because comments, menus, suggestions, and lint surfaces all read it.
- *
- * Shaped as a floating-ui derivable (re-evaluated on every `computePosition`
- * pass) because the composer publishes a live height — its card grows with
- * the draft and collapses to nothing — and the scroll container can be
- * remounted across document switches.
+ * Floating-UI clipping options that keep selection-anchored menus inside the editor's visible
+ * content region rather than the viewport, since the toolbar and composer overlay the container
+ * without clipping it. Owns the visible-region half of precedent #35.
*/
export function deriveEditorClipOptions(editor: Editor): () => EditorClipOptions {
return () => {
diff --git a/packages/app/src/editor/utils/get-editor-view.ts b/packages/app/src/editor/utils/get-editor-view.ts
index 1742e9723..06bea9830 100644
--- a/packages/app/src/editor/utils/get-editor-view.ts
+++ b/packages/app/src/editor/utils/get-editor-view.ts
@@ -1,23 +1,7 @@
import type { Editor } from '@tiptap/core';
import type { EditorView } from '@tiptap/pm/view';
-/**
- * Non-throwing alternative to `editor.view`.
- *
- * TipTap v3's `editor.view` is a proxy that throws when accessed before the
- * underlying ProseMirror EditorView has been mounted — and during recycle/
- * remount races (Activity visible→hidden→visible cycle, DocumentErrorBoundary
- * retry, any race where React runs a passive effect on an editor mid-creation).
- * The proxy intercepts property access on `editor.view`; the underlying field
- * `editor.editorView` is the real reference and returns `undefined` pre-mount.
- *
- * Use this helper anywhere you would otherwise reach for `editor.view`. The
- * returned value is either a fully-mounted EditorView or `undefined` — callers
- * guard with `if (!view) return` and the call site is safe across the
- * recycle-race window.
- *
- * Reference: precedent #18(b) on hybrid Activity + Suspense render trees.
- */
+/** Reference: precedent #18(b) on hybrid Activity + Suspense render trees. */
export function getEditorView(editor: Editor): EditorView | undefined {
return (editor as unknown as { editorView?: EditorView }).editorView;
}
diff --git a/packages/app/src/editor/utils/md-singleton.ts b/packages/app/src/editor/utils/md-singleton.ts
index 594cc9dc8..19b4988bb 100644
--- a/packages/app/src/editor/utils/md-singleton.ts
+++ b/packages/app/src/editor/utils/md-singleton.ts
@@ -1,17 +1,6 @@
/**
- * Shared module-level `MarkdownManager` singleton for client-side parse /
- * serialize. Multiple NodeViews and utility paths need this — every fresh
- * allocation builds a parse + serialize processor, so
- * allocating one per-call was measurably expensive on component-heavy
- * docs. Per precedent #15, the underlying remark plugins are idempotent
- * under re-entry, so one manager safely serves every call.
- *
- * Consumers today:
- * - `utils/reconstruct-source.ts` — serializes a jsxComponent node back
- * to MDX source for the wildcard / render-error auto-convert path.
- * - `extensions/RawMdxFallbackCMView.tsx` — parses the nested CM source
- * on blur to upgrade `rawMdxFallback` → `jsxComponent` when the user
- * fixes broken MDX.
+ * Per precedent #15, the underlying remark plugins are idempotent under re-entry, so one manager
+ * safely serves every call.
*/
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
diff --git a/packages/app/src/hooks/use-theme-bridge.dom.test.tsx b/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
index 7b206b8c8..95f0e3398 100644
--- a/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
+++ b/packages/app/src/hooks/use-theme-bridge.dom.test.tsx
@@ -1,12 +1,7 @@
/**
- * RTL mount tests for the useThemeBridge hook — `.finally(...)`
- * chain ordering and cleanup-on-unmount. Exercises the `render` API
- * surface (via `<HookProbe>` wrapper) under the jsdom substrate
- * (precedent #43); invocation via `bun run test:dom`. Pairs with the
- * verbatim user-intent contract documented in precedent #40(a).
- *
- * The DOM Vitest project keeps `isolate: true` so the module mock in the
- * sibling config-provider suite cannot replace this hook's real implementation.
+ * Exercises the `render` API surface (via `<HookProbe>` wrapper) under the jsdom substrate
+ * (precedent #43). Pairs with the verbatim user-intent contract
+ * documented in precedent #40(a).
*/
import { act, cleanup, render, waitFor } from '@testing-library/react';
diff --git a/packages/app/src/lib/config-provider.dom.test.tsx b/packages/app/src/lib/config-provider.dom.test.tsx
index de1cae1c3..1e379ba80 100644
--- a/packages/app/src/lib/config-provider.dom.test.tsx
+++ b/packages/app/src/lib/config-provider.dom.test.tsx
@@ -1,9 +1,4 @@
-/**
- * Tier-3 RTL mount tests for ConfigProvider Context propagation —
- * sibling to the structural-grep `config-provider.test.tsx`. Exercises `render` + the
- * React Context API surface under the jsdom substrate (precedent #43);
- * invocation via `bun run test:dom`.
- */
+/** Exercises `render` + the React Context API surface under the jsdom substrate (precedent #43). */
import { cleanup, render, screen } from '@testing-library/react';
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
diff --git a/packages/app/src/lib/handoff/dispatch.test.ts b/packages/app/src/lib/handoff/dispatch.test.ts
index 8107adcb2..8c93799fc 100644
--- a/packages/app/src/lib/handoff/dispatch.test.ts
+++ b/packages/app/src/lib/handoff/dispatch.test.ts
@@ -42,7 +42,7 @@ describe('dispatchHandoff — claude-cowork', () => {
expect(body.url).toMatch(/^claude:\/\/cowork\/new\?q=/);
expect(body.url).toContain('folder=');
expect(body.url).toContain('q=');
- // precedent #25 invariant: no native file-attach.
+ // precedent #60 invariant: no native file-attach.
expect(body.url).not.toContain('file=');
expect(body.workspacePath).toBeUndefined();
});
@@ -79,7 +79,7 @@ describe('dispatchHandoff — codex', () => {
expect(body.url).toMatch(/^codex:\/\/new\?prompt=/);
expect(body.url).toContain('path=');
expect(body.url).toContain('prompt=');
- // precedent #25 invariant: no native file-attach.
+ // precedent #60 invariant: no native file-attach.
expect(body.url).not.toContain('file=');
expect(body.workspacePath).toBeUndefined();
});
@@ -101,7 +101,7 @@ describe('dispatchHandoff — cursor', () => {
expect(body.url).toContain('text=');
expect(body.url).toContain('workspace=');
expect(body.url).toContain('mode=agent');
- // precedent #25 invariant: no native file-attach.
+ // precedent #60 invariant: no native file-attach.
expect(body.url).not.toContain('file=');
expect(body.workspacePath).toBe(BASE_PAYLOAD.projectDir);
});
diff --git a/packages/app/src/lib/perf/index.ts b/packages/app/src/lib/perf/index.ts
index 19e575765..6a507b40c 100644
--- a/packages/app/src/lib/perf/index.ts
+++ b/packages/app/src/lib/perf/index.ts
@@ -1,12 +1,3 @@
-/**
- * Public surface of the perf emission layer.
- *
- * Import from `@/lib/perf` (or the relative path) — never reach into the
- * individual files, so we can refactor the internals without breaking callers.
- *
- * See CLAUDE.md precedent #20.
- */
-
export { getHistogramSnapshot } from './collector';
export type { HistogramSnapshot } from './hdr-histogram';
export { mark } from './mark';
diff --git a/packages/app/src/lib/storage-scope.ts b/packages/app/src/lib/storage-scope.ts
index 712b05205..17afdb677 100644
--- a/packages/app/src/lib/storage-scope.ts
+++ b/packages/app/src/lib/storage-scope.ts
@@ -1,9 +1,7 @@
/**
- * Project scoping for the renderer's persistent storage names — the
- * implementation of `precedent #59`, which is the citable statement of the
- * rule. Home of the one thing every client storage surface has to obey, so a
- * new one adopts it instead of rediscovering the bug (`provider-pool.ts` used
- * to own this privately, which is why `replay-outbox.ts` shipped without it).
+ * Project scoping for the renderer's persistent storage names, the implementation of
+ * precedent #59: every client storage surface adopts it here instead of rediscovering the
+ * collision `provider-pool.ts` used to own privately.
*/
import { fnv1aDigest } from '@inkeep/open-knowledge-core';
diff --git a/packages/app/src/lib/use-boolean-frontmatter-field.ts b/packages/app/src/lib/use-boolean-frontmatter-field.ts
index 696730ce0..0588568c6 100644
--- a/packages/app/src/lib/use-boolean-frontmatter-field.ts
+++ b/packages/app/src/lib/use-boolean-frontmatter-field.ts
@@ -1,18 +1,7 @@
/**
- * Live-read a boolean frontmatter flag off `Y.Text('source')`, re-reading as
- * the user edits frontmatter. Boolean sibling of `useFrontmatterField`
- * (string-only — it reads '' for a boolean).
- *
- * Strict identity: only the YAML boolean `true` yields `true`. The string
- * "true" and the number `1` yield `false`, so a coincidentally-truthy value
- * can't trip a gate this drives.
- *
- * The subscription lives in a `useEffect` so React tears it down on unmount and
- * when an enclosing `<Activity>` flips to hidden — a Y.js observer attached off
- * the effect lifecycle (a ref, a module singleton) would keep processing remote
- * updates for every hidden document (precedent #18(c)). The `useState`
- * initializer's one-shot binding is created, read, and disposed in the same
- * breath, so it leaves nothing attached.
+ * The subscription lives in a `useEffect` so React tears it down on unmount and when an enclosing
+ * `<Activity>` flips to hidden — a Y.js observer attached off the effect lifecycle (a ref, a module
+ * singleton) would keep processing remote updates for every hidden document (precedent #18(c)).
*/
import type { HocuspocusProvider } from '@hocuspocus/provider';
diff --git a/packages/app/src/lib/use-collab-url.ts b/packages/app/src/lib/use-collab-url.ts
index 309effdae..13d7dd465 100644
--- a/packages/app/src/lib/use-collab-url.ts
+++ b/packages/app/src/lib/use-collab-url.ts
@@ -1,30 +1,6 @@
/**
- * React hook that resolves the collab WebSocket URL from `ok ui`'s
- * `/api/config` endpoint.
- *
- * Resolution flow:
- * 1. Fetch `/api/config` on mount.
- * 2. If `collabUrl` is a string: resolved → return it.
- * 3. If `collabUrl` is null: server.lock is absent/stale → retry with
- * bounded exponential backoff (2s → 4s → 8s → 15s cap).
- * 4. If the fetch itself 404s or network-errors: fall back to the
- * same-origin WebSocket URL so `bun run dev` (Vite + Hocuspocus on one
- * port) keeps working without plugin changes.
- * 5. After `TERMINAL_AFTER_MS` elapsed wall-clock with no resolution, the
- * hook transitions to a `terminal` state: automatic retries stop, the
- * consumer banner surfaces an actionable error + manual-retry button.
- * A terminal retry resets the wall-clock and delay back to start.
- *
- * The terminal state exists because a silent-forever banner is itself a
- * form of ceremony — users hit-refresh, kill the tab, or file issues. The
- * zero-ceremony promise assumes silent recovery, but bounded recovery with
- * a diagnostic surface is the correct fallback for a permanently-broken
- * configuration (misconfigured proxy, crashed-and-unrespawned `ok start`).
- *
- * The poll loop is extracted as `runCollabUrlPoll` so tests can drive it
- * with fake clocks + mocked fetch — the hook is a thin React wrapper. This
- * follows precedent #13b: implicit time-coupling is a test smell,
- * so the primitive accepts `now / setTimeout / clearTimeout` as deps.
+ * This follows precedent #13b: implicit time-coupling is a test smell, so the primitive accepts
+ * `now / setTimeout / clearTimeout` as deps.
*/
import { useEffect, useRef, useState } from 'react';
import { type FetchApiConfigResult, fetchApiConfig } from '@/lib/api-config';
diff --git a/packages/app/src/lib/use-server-keepalive.dom.test.tsx b/packages/app/src/lib/use-server-keepalive.dom.test.tsx
index b50949e95..4c183855d 100644
--- a/packages/app/src/lib/use-server-keepalive.dom.test.tsx
+++ b/packages/app/src/lib/use-server-keepalive.dom.test.tsx
@@ -1,11 +1,4 @@
-/**
- * RTL mount tests for `useServerKeepalive` — start-once lifecycle,
- * presence-invisible options, the Electron gate, latest-collabUrl resolution
- * without socket churn, and teardown on unmount. Invoked via `bun run test:dom`
- * (jsdom substrate, precedent #43). Behavior-only per AGENTS.md React-test
- * discipline: we assert what the hook does (start/skip/close, resolver output),
- * never its source text.
- */
+/** Runs under the jsdom substrate (precedent #43). */
import type { KeepaliveHandle, KeepaliveOptions } from '@inkeep/open-knowledge-core/keepalive';
import { act, cleanup, render, waitFor } from '@testing-library/react';
diff --git a/packages/app/src/presence/participant-model.ts b/packages/app/src/presence/participant-model.ts
index 32358f85c..5c746cf06 100644
--- a/packages/app/src/presence/participant-model.ts
+++ b/packages/app/src/presence/participant-model.ts
@@ -10,10 +10,8 @@ export interface HumanParticipant {
}
/**
- * An agent participant — publishes presence via the `__system__` Y.Doc's
- * `agentPresence` map (never per-doc awareness; see precedent #3).
- * `presence` carries everything the bar needs: displayName, icon, color,
- * currentDoc, mode, ts.
+ * An agent participant — publishes presence via the `__system__` Y.Doc's `agentPresence` map (never
+ * per-doc awareness; see precedent #3).
*/
export interface AgentParticipant {
kind: 'agent';
diff --git a/packages/app/tests/integration/c12-nested-frontmatter.test.ts b/packages/app/tests/integration/c12-nested-frontmatter.test.ts
index 09dda2d4b..01121fa1a 100644
--- a/packages/app/tests/integration/c12-nested-frontmatter.test.ts
+++ b/packages/app/tests/integration/c12-nested-frontmatter.test.ts
@@ -1,23 +1,7 @@
/**
- * C12: Multi-client nested frontmatter convergence + bridge invariant at depth.
- *
- * Validates that two clients editing nested frontmatter (objects, arrays-of-
- * objects) converge under the server-authoritative observer bridge, with the
- * precedent #38 invariant
- *
- * normalizeBridge(ytext) === normalizeBridge(prependFrontmatter(fm, serialize(fragment)))
- *
- * holding at arbitrary nesting depth. Panel-side
- * edits go through `bindFrontmatterDoc.patchPath` (LOCAL path-addressed,
- * single-leaf), which writes a byte-range replace of the fenced FM region in
- * `Y.Text('source')` under FORM_WRITE_ORIGIN. The body bytes are untouched,
- * so server Observer B (Y.Text → XmlFragment) is a no-op for pure FM edits;
- * the invariant still holds because Y.Text's FM region encodes the new fm
- * and `prependFrontmatter(extractFm(ytext), serialize(fragment))` recomposes
- * to the same bytes.
- *
- * Per-test docName isolation via createTestClients(port, { count }) default.
- * Client lifecycle in try/finally (not afterEach).
+ * C12: two clients editing nested frontmatter converge under the server-authoritative observer
+ * bridge, with precedent #38's invariant holding at arbitrary nesting depth. Panel edits write a
+ * byte-range replace of the fenced FM region under FORM_WRITE_ORIGIN, leaving the body untouched.
*/
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/c16-lazy-continuation.test.ts b/packages/app/tests/integration/c16-lazy-continuation.test.ts
index 5c33099c7..15e89da76 100644
--- a/packages/app/tests/integration/c16-lazy-continuation.test.ts
+++ b/packages/app/tests/integration/c16-lazy-continuation.test.ts
@@ -1,25 +1,7 @@
/**
- * C16: CommonMark lazy-continuation docs — multi-client convergence without
- * bridge health-check churn.
- *
- * A doc whose source carries a lazy continuation (an unindented wrapped
- * line inside a list item) rests byte-divergent beyond every normalizeBridge
- * class by design; the fragment still IS `parse(ytext)` (precedent #38).
- * Multi-client coverage per the observer-bridge rule: single-client rigs
- * miss remote-peer divergence, and this changeset touches
- * `server-observers.ts`.
- *
- * Pins, through the real client → server → client collab pipeline:
- * - a WYSIWYG edit on a resting lazy-continuation doc converges on every
- * peer with the authored bytes preserved verbatim (no sanitize, no
- * canonical rewrite) and no `bridge-split-brain-rederive` emission for
- * the doc;
- * - the harness bridge-invariant watcher's parse-equivalence fallback
- * does NOT swallow genuine divergence — a paired-origin transaction
- * that moves Y.Text without the fragment still throws.
- *
- * Per-test docName isolation via createTestClients(port, { count }) default.
- * Client lifecycle in try/finally (not afterEach) per R8a.
+ * A doc whose source carries a lazy continuation (an unindented wrapped line inside a list item)
+ * rests byte-divergent beyond every normalizeBridge class by design; the fragment still IS
+ * `parse(ytext)` (precedent #38).
*/
import { setTimeout as wait } from 'node:timers/promises';
diff --git a/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts b/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts
index e3f986002..f78217246 100644
--- a/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts
+++ b/packages/app/tests/integration/c4-agent-plus-wysiwyg.test.ts
@@ -1,17 +1,3 @@
-/**
- * C4: Agent write + concurrent WYSIWYG (XmlFragment) edits.
- *
- * Validates that agent writes via the HTTP API (applyAgentMarkdownWrite under
- * AGENT_WRITE_ORIGIN) and concurrent client WYSIWYG edits both survive the
- * server-authoritative observer bridge. The server applies agent writes to
- * XmlFragment via updateYFragment and mirrors to Y.Text via applyByPrefixSuffix
- * (precedent #12). Client WYSIWYG edits propagate via CRDT sync and the server
- * observer handles cross-CRDT writes under OBSERVER_SYNC_ORIGIN.
- *
- * Per-test docName isolation via createTestClient/createTestClients.
- * Client lifecycle in try/finally (not afterEach).
- */
-
import { setTimeout as wait } from 'node:timers/promises';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/c5-agent-plus-source.test.ts b/packages/app/tests/integration/c5-agent-plus-source.test.ts
index c582dbc7e..7b29fb916 100644
--- a/packages/app/tests/integration/c5-agent-plus-source.test.ts
+++ b/packages/app/tests/integration/c5-agent-plus-source.test.ts
@@ -1,17 +1,3 @@
-/**
- * C5: Agent write + concurrent source mode (Y.Text) edits.
- *
- * Symmetric to C4 but validates the Y.Text write surface. Agent writes via
- * the HTTP API use applyAgentMarkdownWrite (XmlFragment-authoritative,
- * precedent #12) which mirrors to Y.Text via applyByPrefixSuffix. Client
- * source-mode edits write directly to Y.Text. The server observer (Observer B
- * under OBSERVER_SYNC_ORIGIN) parses the merged Y.Text and applies to
- * XmlFragment via updateYFragment.
- *
- * Per-test docName isolation via createTestClient/createTestClients.
- * Client lifecycle in try/finally (not afterEach).
- */
-
import { setTimeout as wait } from 'node:timers/promises';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
import { HARNESS_BOOT_TIMEOUT_MS } from './harness-boot-timeout';
diff --git a/packages/app/tests/integration/contended-typing-fragment-duplication.test.ts b/packages/app/tests/integration/contended-typing-fragment-duplication.test.ts
index 7abeebe0a..f4770a4b6 100644
--- a/packages/app/tests/integration/contended-typing-fragment-duplication.test.ts
+++ b/packages/app/tests/integration/contended-typing-fragment-duplication.test.ts
@@ -1,44 +1,6 @@
/**
- * A stale client structural fragment replace must never end up as duplicated
- * authoritative Y.Text bytes.
- *
- * The race: while a user types per-keystroke into `Y.Text('source')`, server
- * Observer B rewrites the `Y.XmlFragment('default')` on every keystroke drain.
- * The keystroke that closes an unregistered `<Steps>`/`<Step>` block flips the
- * span's parse from a rawMdxFallback node to a valid wildcard jsxComponent — a
- * STRUCTURAL delete+insert of the span, not an item-preserving content update.
- * Concurrently, the hidden-but-mounted client WYSIWYG editor's wildcard
- * JsxComponentView auto-convert dispatches its own plain client-origin
- * `replaceWith` (also a structural delete+insert) of the SAME span, computed
- * against a fragment state that has lagged the server's rewrites. At the
- * Y.XmlFragment CRDT level the two concurrent delete+insert pairs merge as one
- * agreed delete plus BOTH inserts surviving, so the Step subtree materializes
- * twice. Observer A then serializes the doubled fragment and faithfully
- * persists the duplicated bytes into the authoritative Y.Text.
- *
- * Why raw Y.js emulation instead of driving the React editor: the invariant
- * under test is server-side — a stale client structural fragment replace must
- * not survive into authoritative Y.Text, regardless of which client surface
- * minted it. Emulating the auto-convert directly at the `client.fragment`
- * delete/insert level pins that server/bridge contract without coupling the
- * test to JsxComponentView's rAF scheduling, its per-instance idempotence
- * guard, or any editor mount lifecycle. It is the stronger contract: any
- * client that issues a concurrent structural replace of a bridge-derived span
- * reproduces this, not just the one dispatcher that happens to exist today.
- *
- * Why the assertion is at the server Y.Text level: that is the authoritative
- * source persisted to disk and converged to every peer (precedent #38,
- * Y.Text-is-truth). The corruption is real bytes there, self-stabilizing, with
- * no downstream self-heal — so the server Y.Text multiplicity is the invariant
- * that matters.
- *
- * The interleave is staged deterministically with syncControl: the client
- * pauses INBOUND sync (so it never sees Observer B's rewrites — the stale
- * replica), types the closing tags per-keystroke (outbound still flows, so the
- * server rewrites the span per keystroke), then performs the
- * auto-convert-equivalent structural replace against its stale fragment. On
- * resume the server fragment holds two copies of the Step subtree and the
- * authoritative Y.Text duplicates the typed body line.
+ * Why the assertion is at the server Y.Text level: that is the authoritative source persisted to
+ * disk and converged to every peer (precedent #38, Y.Text-is-truth).
*/
import { afterAll, beforeAll, expect, test } from 'vitest';
import * as Y from 'yjs';
diff --git a/packages/app/tests/integration/e2e-stop-rules.test.ts b/packages/app/tests/integration/e2e-stop-rules.test.ts
index d19adab5e..3cfb5b954 100644
--- a/packages/app/tests/integration/e2e-stop-rules.test.ts
+++ b/packages/app/tests/integration/e2e-stop-rules.test.ts
@@ -1,46 +1,6 @@
/**
- * Mechanical guard for the E2E suite's zero-allowlist anti-pattern bans.
- *
- * Each banned pattern is enforced by a per-pattern test. Failure messages
- * list `<file>:<line>` for every violation so the developer can fix without
- * having to re-grep.
- *
- * Template: `packages/app/src/editor/clipboard/wysiwyg-stop-rule.test.ts` —
- * same per-pattern shape, same string-grep enforcement (cheapest mechanical
- * check that catches both spellings of each banned construct).
- *
- * Patterns enforced:
- * 1. `page.waitForTimeout(`
- * 2. `waitUntil: 'networkidle'`
- * 3. `new Promise(r => setTimeout(r,`
- * 4. `page.pause(`
- * 5. `test.skip(browserName === 'webkit'` — ratchet
- * 6. Inner-file helper imports — barrel contract
- * 7. Ungated `window.__` writes outside the allowlist
- * 8. `window.__activeEditor` writes outside DocumentContext.tsx
- * (regression — merge collision: TiptapEditor direct
- * assignment clashed with main's getter-only defineProperty
- * and threw TypeError on any doc open in DEV)
- * 9. `:has()` in selection-halo CSS rules (precedent #34 — innermost-wins
- * via plugin state, not `:has()` cascade; Firefox compat + large-doc
- * perf + SSR parity)
- * 10. Selection halo transition uses bare `ease-out` instead of
- * `var(--ease-out-strong)` — consistency with the repo's custom
- * easing token
- * 11. Static value imports of the DEV ACP thread harness, which would
- * defeat the dynamic-import gate that keeps it out of production
- * 12. Remote placeholder-image hosts anywhere under
- * tests/{stress,visual,a11y} — every `.ts`, not just `*.e2e.ts`,
- * because entry 6 channels shared logic into `_helpers/` and the stub
- * this rule replaced lived exactly there. Local fixtures decode
- * deterministically; remote ones flake offline.
- * Host-scoped deliberately, not lazily. The three hosts are the ones
- * this repo actually contains in image-source position (docs' img
- * reference, CM6-ELEMENTS.md, showcase/), not a guess at vendors; and
- * an image-source-scoped predicate would miss the spellings that carry
- * a host here, while redding the specs that put a reserved-name URL in
- * genuine image-source position, where the decode is either irrelevant
- * or required to fail — see the self-test below, which pins both halves
+ * Selection-halo chrome comes from plugin state and never from the `:has()` cascade, and this
+ * suite is the mechanical guard for that ban (precedent #34).
*/
import { type Dirent, readdirSync, readFileSync } from 'node:fs';
diff --git a/packages/app/tests/integration/error-envelope-coverage.test.ts b/packages/app/tests/integration/error-envelope-coverage.test.ts
index c8b4d4e2a..69c38738f 100644
--- a/packages/app/tests/integration/error-envelope-coverage.test.ts
+++ b/packages/app/tests/integration/error-envelope-coverage.test.ts
@@ -1,23 +1,3 @@
-/**
- * Error-envelope coverage meta-test — fail-on-any-occurrence mode.
- *
- * Mirrors the precedent #20 / `attribution-sweep-coverage.test.ts` style:
- * static source scan over `api-extension.ts` plus every lifted handler source
- * (`skills-sh-handlers.ts`, `http/*-routes.ts` — see `HANDLER_SOURCES`),
- * enforcing that
- *
- * 1. Every handler emits errors via `errorResponse(...)` and never via an
- * inline `json(res, NNN, { ok: false, ... })` envelope.
- * 2. No handler emits an inline `json(res, NNN, { ok: true, ... })` success
- * wrapper either (the `ok: true` wrapper is dropped from success bodies).
- * 3. No handler emits a bare `json(res, 2xx, ...)` success body — every
- * success emit must flow through `successResponse(...)` so the
- * schema-vs-server drift class is closed structurally at the wire
- * boundary regardless of fixture coverage.
- *
- * Failure mode: file:line + handler name + the offending pattern.
- */
-
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/keyboard-nav-catch-contract.test.ts b/packages/app/tests/integration/keyboard-nav-catch-contract.test.ts
index fe2876db1..d75a2acb5 100644
--- a/packages/app/tests/integration/keyboard-nav-catch-contract.test.ts
+++ b/packages/app/tests/integration/keyboard-nav-catch-contract.test.ts
@@ -1,36 +1,7 @@
/**
- * Pins the structural contract for L0 + L2 catch sites in `KeyboardNav`
- * (precedent #48). Synthesizing the concurrent CRDT-edit race that
- * produces the `RangeError` is hard to make deterministic without
- * test-only injection hooks in production code (refused under greenfield
- * posture). The STATIC commitments around the catch site are pinnable
- * here as a source-grep meta-test (precedent #20(g)):
- *
- * - the counter signature `incrementJsxArrowNodeSelectFailed(dir)` is
- * invoked from every catch site (per-direction observability)
- * - the structured warn shape carries
- * `event: 'jsx-component-arrow-node-select-failed'` + `direction`
- * + `reason` + `tier`
- * - every catch narrows to `err instanceof RangeError` — bare
- * `catch { return false }` widening regresses observability and
- * hides genuine bugs
- * - the `tier: 'L0' | 'L2' | 'L2c' | 'L2d'` field on the event JSON disambiguates
- * auto-NodeSelect failures from block-step failures for the same
- * direction (both tiers can fail with the same direction; the
- * discriminator lets observability cleanly split them)
- *
- * The test reads `keyboard-nav.ts` as bytes (no module-level import — the
- * goal is structural enforcement, not behavioral). It locates the five
- * catch blocks (L0 tryL0NodeSelect helper, L2 ArrowUp keymap, L2 ArrowDown
- * keymap, L2c tryExitCompoundJsxUp helper, L2d tryEnterCompoundJsx helper)
- * and asserts each carries the required keywords. A reviewer who
- * widens `catch (err)` to a bare catch, or removes the counter call, or
- * strips the structured warn, fails this test — even if every Playwright
- * scenario still passes (because the race condition is rare in CI).
- *
- * Cross-references precedent #20(g) (source-grep STOP-rule pattern),
- * precedent #46 (tri-state predicate), precedent #48 (KeyboardNav as
- * canonical home for block-level keyboard contract).
+ * Pins the structural contract for `KeyboardNav`'s L0 and L2 catch sites (precedent #48) as a
+ * source-grep meta-test (precedent #20(g)): every catch narrows to `RangeError`, calls the
+ * per-direction counter, and emits the structured warn with its `tier` discriminator.
*/
import { readFileSync } from 'node:fs';
diff --git a/packages/app/tests/integration/managed-rename-loaded-doc.test.ts b/packages/app/tests/integration/managed-rename-loaded-doc.test.ts
index 4b29ede80..4f89f7563 100644
--- a/packages/app/tests/integration/managed-rename-loaded-doc.test.ts
+++ b/packages/app/tests/integration/managed-rename-loaded-doc.test.ts
@@ -1,16 +1,7 @@
/**
- * Loaded-Y.Doc rewrite path through real Hocuspocus.
- *
- * The unit harness in api-rename-rollback-summary.test.ts stubs
- * `hocuspocus.documents = new Map()` so the loaded-Y.Doc branch of
- * `applyManagedRenameMapToLoadedDocument` is never exercised end-to-end.
- *
- * This test boots a real server + connected client, opens a doc that
- * contains a wiki-link to another renamed doc, and asserts:
- * - the client's Y.Text observably mutates from `[[old]]` → `[[new]]`
- * - the disk file matches
- * - bridge invariant holds (Y.Text and XmlFragment converge through the
- * server-authoritative observer A path; precedent #14)
+ * Loaded-Y.Doc rewrite path through a real Hocuspocus server: a connected client's Y.Text mutates
+ * from `[[old]]` to `[[new]]`, the disk file matches, and Y.Text and XmlFragment converge through
+ * the server-authoritative Observer A path (precedent #14).
*/
import { readFileSync, writeFileSync } from 'node:fs';
diff --git a/packages/app/tests/integration/marked-inline-leaf-bridge.test.ts b/packages/app/tests/integration/marked-inline-leaf-bridge.test.ts
index 9a7343e40..d89167293 100644
--- a/packages/app/tests/integration/marked-inline-leaf-bridge.test.ts
+++ b/packages/app/tests/integration/marked-inline-leaf-bridge.test.ts
@@ -1,18 +1,7 @@
/**
- * Marked inline leaf nodes survive the live server bridge.
- *
- * An inline *leaf* node — an inline node with no inline content, so ProseMirror
- * computes an empty mark set for it — can still carry a mark when it arrives
- * from parsed markdown: `**[[a]]**` yields a `wikiLink` node with `marks:
- * [strong]`. The PM ⇄ Y.XmlFragment conversion is the only hop on the write
- * path that can lose that mark, and losing it breaks precedent #38: the
- * fragment no longer derives from Y.Text, so the persistence write-back reports
- * a bridge-invariant violation and the doc re-derives its fragment on every
- * drain without ever converging.
- *
- * Assertions here read the settled server state rather than the conversion
- * functions directly, so they pin the user-visible outcome: what the editor
- * renders and what the server considers a healthy document.
+ * Marked inline leaf nodes survive the live server bridge. Losing the mark on the PM to
+ * Y.XmlFragment hop breaks precedent #38: the fragment stops deriving from Y.Text, so the
+ * write-back reports a bridge-invariant violation and the doc never converges.
*/
import { randomUUID } from 'node:crypto';
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/microcopy-ellipsis.test.ts b/packages/app/tests/integration/microcopy-ellipsis.test.ts
index d7fef8f35..e1440147c 100644
--- a/packages/app/tests/integration/microcopy-ellipsis.test.ts
+++ b/packages/app/tests/integration/microcopy-ellipsis.test.ts
@@ -1,25 +1,4 @@
-/**
- * Microcopy ellipsis convention — `microcopy-ellipsis` oxlint rule.
- *
- * Rule: `lint-plugins/ok-rules/rules/microcopy-ellipsis.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/microcopy-ellipsis.fixture.tsx`
- *
- * The codebase reserves U+2026 (`…`) for two surfaces only:
- * 1. macOS native menu items (`packages/desktop/src/main/menu.ts`)
- * 2. Truncation indicators
- *
- * Per precedent #42. The fixture pairs 2 positive cases (JSX text + JSX
- * attribute containing `…`) with 3 negative cases (clean text, clean
- * attribute, and `…` inside a non-UI attribute that the rule must skip);
- * the test asserts the rule fires exactly 2 times.
- *
- * Exact equality (`toBe(2)`) catches drift in both directions:
- * - false-negative: a weakened pattern drops below 2 → fails
- * - false-positive: a widened pattern fires on a clean case → above 2 → fails
- *
- * Test shape: real input → public
- * interface (`oxlintFixtureArgs()` → `pnpm exec oxlint`) → observable outcome (diagnostic count).
- */
+/** The `microcopy-ellipsis` oxlint rule fixture test, per precedent #42. */
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/nbsp-wysiwyg-preservation.test.ts b/packages/app/tests/integration/nbsp-wysiwyg-preservation.test.ts
index f74d3d05d..a7f671dec 100644
--- a/packages/app/tests/integration/nbsp-wysiwyg-preservation.test.ts
+++ b/packages/app/tests/integration/nbsp-wysiwyg-preservation.test.ts
@@ -1,14 +1,5 @@
/**
- * Document NBSP (U+00A0) preservation through a WYSIWYG edit.
- *
- * Agent writes land raw bytes into Y.Text verbatim (byte-sacred), so a document
- * NBSP is intact at rest. The XmlFragment is a re-parse of the body, and a WYSIWYG
- * edit triggers a server Observer A settlement that re-serializes the fragment
- * over the Y.Text region — so the NBSP must survive the full mdast<->PM
- * round-trip, not just the write. Per precedent #57, an agent-authored byte the
- * human never touched must survive that settlement. Observer A fires on any
- * fragment change, so both a SAME-block and a DIFFERENT-block edit are covered;
- * the no-edit control pins the byte-sacred write path itself.
+ * Per precedent #57, an agent-authored byte the human never touched must survive that settlement.
*/
import { afterAll, beforeAll, describe, expect, test } from 'vitest';
diff --git a/packages/app/tests/integration/no-unportaled-editor-content.test.ts b/packages/app/tests/integration/no-unportaled-editor-content.test.ts
index 44822a917..68b53c5aa 100644
--- a/packages/app/tests/integration/no-unportaled-editor-content.test.ts
+++ b/packages/app/tests/integration/no-unportaled-editor-content.test.ts
@@ -1,22 +1,4 @@
-/**
- * `no-unportaled-editor-content` oxlint rule test.
- *
- * Rule: `lint-plugins/ok-rules/rules/no-unportaled-editor-content.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/no-unportaled-editor-content.fixture.tsx`
- *
- * Per precedent #42 (custom lint enforcement is oxlint JS-plugin rules). The
- * fixture pairs 3 positive cases (bare/paired/nested `<EditorContent />`)
- * with 3 negative cases (canonical portaled site with inline suppression,
- * `<PureEditorContent />` sibling, bare import). The test asserts the
- * rule fires exactly 3 times.
- *
- * Exact equality (`toBe(3)`) catches drift in both directions:
- * - false-negative: a weakened pattern drops below 3 → fails
- * - false-positive: a widened pattern fires on a negative case → above 3 → fails
- *
- * real input → public
- * interface (`oxlintFixtureArgs()` → `pnpm exec oxlint`) → observable outcome (diagnostic count).
- */
+/** The `no-unportaled-editor-content` oxlint rule fixture test, per precedent #42. */
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
diff --git a/packages/app/tests/integration/test-harness.ts b/packages/app/tests/integration/test-harness.ts
index 38bd95a44..99af7df64 100644
--- a/packages/app/tests/integration/test-harness.ts
+++ b/packages/app/tests/integration/test-harness.ts
@@ -414,36 +414,7 @@ export async function assertIDBEmpty(
}
}
-/**
- * Structural quiescence gate — resolves once the doc has NO in-flight
- * transactions AND no `afterAllTransactions` listener fires for N
- * consecutive microtasks. Use instead of wall-clock `wait(ms)` when a test
- * needs to wait for a local doc's pending observer work (including the
- * settlement dispatcher's inner OBSERVER_SYNC_ORIGIN writes) to settle.
- *
- * Precedent #13(b): settlement-based, NOT wall-clock. Under the
- * server-authoritative bridge, observer work fires
- * synchronously inside `afterAllTransactions` — but some paths kick a
- * follow-up `doc.transact(..., OBSERVER_SYNC_ORIGIN)` which starts a new
- * drain. This helper waits until a short quiet window passes with no new
- * drains to catch that cascade deterministically.
- *
- * The `idleTicks` count (default 2) must be >= 2 so the first tick can
- * observe an in-flight drain and the second confirms the drain finished
- * without a follow-up. `idleTicks: 1` is INSUFFICIENT for the seed-class
- * races this helper exists to catch: Observer A's inner
- * `OBSERVER_SYNC_ORIGIN` write scheduled via `queueMicrotask` can land on
- * a later tick than the outer drain, so a single idle observation can
- * return before the cascade completes. Raise `idleTicks` for particularly
- * nested observer cascades; lower is unsafe.
- *
- * `timeoutMs` (default 2000) guards against hangs; throws a clear error
- * pointing at the doc if quiescence is never reached.
- *
- * Does NOT cover inter-doc / inter-client WebSocket propagation — for
- * multi-client convergence, combine with `assertAllConverged` or equivalent
- * polling gates.
- */
+/** Precedent #13(b): settlement-based, NOT wall-clock. */
export async function awaitDocQuiescence(
doc: Y.Doc,
opts?: { timeoutMs?: number; idleTicks?: number },
@@ -491,12 +462,11 @@ export function stripTrailingWhitespace(s: string): string {
.replace(/\n+$/, '');
}
-/** Assert bridge invariant: normalized Y.Text === serialized XmlFragment,
- * with the parse-equivalence fallback for byte forms beyond every
- * normalizeBridge class whose parse matches the fragment (CommonMark lazy
- * continuations et al. — fragment ≡ parse(ytext) holds, precedent #38).
- * Normalization includes: blank-line count between blocks may normalize
- * (ProseMirror schema limitation). Collapse 3+ consecutive newlines to 2. */
+/**
+ * Assert bridge invariant: normalized Y.Text === serialized XmlFragment, with the parse-equivalence
+ * fallback for byte forms beyond every normalizeBridge class whose parse matches the fragment
+ * (CommonMark lazy continuations et al. — fragment ≡ parse(ytext) holds, precedent #38).
+ */
export function assertBridgeInvariant(ytext: Y.Text, fragment: Y.XmlFragment): void {
const ytextStr = ytext.toString();
const fragMd = serializeFragment(fragment);
@@ -915,18 +885,9 @@ export interface ItemOriginProbe {
}
/**
- * Create a probe wrapping Y.UndoManager that records stack state and asserts
- * Items-remained-captured. Replaces scattered inline `new Y.UndoManager(...)`
- * in test code.
- *
- * `trackedOrigins` must contain `LocalTransactionOrigin` OBJECT references per
- * precedent #1 (AGENTS.md) — e.g., per-session `session.origin`, `ORIGIN_TREE_TO_TEXT`,
- * `ORIGIN_TEXT_TO_TREE`, `FILE_WATCHER_ORIGIN`, `ROLLBACK_ORIGIN`. `Y.UndoManager`'s
- * internal `trackedOrigins.has(tx.origin)` is identity-based for objects — a raw
- * string literal would silently fail to match the production tx.origin object.
- * Note: in multi-client server-authoritative tests, server-side writes arrive
- * at clients as remote transactions (undefined origin) — pass `session.origin`
- * from a server-side `AgentSessionManager.getSession()` call to track local writes.
+ * `trackedOrigins` must contain `LocalTransactionOrigin` OBJECT references per precedent #1
+ * (AGENTS.md) — e.g., per-session `session.origin`, `ORIGIN_TREE_TO_TEXT`, `ORIGIN_TEXT_TO_TREE`,
+ * `FILE_WATCHER_ORIGIN`, `ROLLBACK_ORIGIN`.
*/
export function createItemOriginProbe(
ytext: Y.Text,
diff --git a/packages/app/tests/lint-plugins/no-blind-agent-host-fanout.test.ts b/packages/app/tests/lint-plugins/no-blind-agent-host-fanout.test.ts
index 7d143711f..4bb76076f 100644
--- a/packages/app/tests/lint-plugins/no-blind-agent-host-fanout.test.ts
+++ b/packages/app/tests/lint-plugins/no-blind-agent-host-fanout.test.ts
@@ -1,24 +1,4 @@
-/**
- * no-blind-agent-host-fanout — oxlint rule fixture test.
- *
- * Rule: `lint-plugins/ok-rules/rules/no-blind-agent-host-fanout.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/no-blind-agent-host-fanout.fixture.tsx`
- *
- * Per precedent #42 (custom lint enforcement is oxlint JS-plugin rules). Forbids
- * re-introducing the `npx skills … --agent '*'` shell-out that made `ok init`
- * create skill directories in every host the third-party CLI knows about,
- * including ~51 for tools the user had never installed (issue #820). OK now
- * writes the user-global bundle itself, gated on `detectUserSkillHosts`.
- *
- * Three guarantees, each its own test:
- * 1. Fires on exactly the planted positives (and on no negative) — the
- * bidirectional `toBe(5)` count, plus the diagnostic-message contract.
- * 2. Scoped via its RULE_SCOPES entry to the packages that own the install,
- * with tests deliberately IN scope.
- * 3. The banned npm-spec arms cover every range shape of the pinned spec the
- * incident shipped with, so a caret/exact/latest variant can't slip past a
- * guard written only against the tilde form.
- */
+/** The `no-blind-agent-host-fanout` oxlint rule fixture test, per precedent #42. */
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
diff --git a/packages/app/tests/lint-plugins/no-comments.test.ts b/packages/app/tests/lint-plugins/no-comments.test.ts
index ceababd90..a4c347bcf 100644
--- a/packages/app/tests/lint-plugins/no-comments.test.ts
+++ b/packages/app/tests/lint-plugins/no-comments.test.ts
@@ -37,22 +37,22 @@ function runOxlint(config: string, fixture: string): Run {
type Violation = { class: string; comment: { line: number; column: number } };
type NoCommentsModule = {
- analyzeSource: (input: { source: string; relPath: string; precedentNumbers: unknown }) => {
+ analyzeSource: (input: { source: string; relPath: string; precedentRegistry: unknown }) => {
violations: Violation[];
};
- loadPrecedentNumbers: (repoRoot: string) => unknown;
+ loadPrecedentRegistry: (repoRoot: string) => unknown;
};
async function predicateViolations(fixture: string): Promise<Violation[]> {
const moduleUrl = pathToFileURL(join(REPO_ROOT, 'lint-plugins/no-comments/index.mjs')).href;
- const { analyzeSource, loadPrecedentNumbers } = (await import(
+ const { analyzeSource, loadPrecedentRegistry } = (await import(
/* @vite-ignore */ moduleUrl
)) as NoCommentsModule;
const relPath = `${FIXTURE_DIR}/${fixture}`;
return analyzeSource({
source: readFileSync(join(REPO_ROOT, relPath), 'utf-8'),
relPath,
- precedentNumbers: loadPrecedentNumbers(REPO_ROOT),
+ precedentRegistry: loadPrecedentRegistry(REPO_ROOT),
}).violations;
}
@@ -61,6 +61,7 @@ const PARITY_FIXTURES = [
'must-not-fire.fixture.ts',
'jsx-text.fixture.tsx',
'jsdoc-types.fixture.mjs',
+ 'jsdoc-types.fixture.ts',
];
const runs = new Map<string, Run>();
@@ -87,7 +88,7 @@ describe('no-comments oxlint plugin', () => {
test('fires once per non-allowlisted comment, naming the class, the fix and the docs anchor', () => {
const { status, diagnostics, raw } = run('must-fire.fixture.ts');
expect(status).toBe(1);
- expect(diagnostics).toHaveLength(21);
+ expect(diagnostics).toHaveLength(31);
const classes = diagnostics.map((d) => d.class);
expect(classes).toStrictEqual([
@@ -112,10 +113,21 @@ describe('no-comments oxlint plugin', () => {
'prose',
'prose',
'prose',
+ 'prose',
+ 'prose',
+ 'prose',
+ 'prose',
+ 'prose',
+ 'prose',
+ 'prose',
+ 'prose',
+ 'prose',
+ 'prose',
]);
expect(diagnostics.map((d) => d.line)).toStrictEqual([
- 1, 4, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 47, 53, 56, 59, 63, 66, 69, 72,
+ 1, 4, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 47, 53, 56, 59, 63, 66, 69, 72, 75, 78, 81,
+ 87, 93, 96, 99, 102, 104, 106,
]);
expect(raw).toContain(
@@ -162,20 +174,30 @@ describe('no-comments oxlint plugin', () => {
});
test('agrees with the shared predicate on every fixture, class for class and line for line', async () => {
- let compared = 0;
+ const compared: Record<string, number> = {};
for (const fixture of PARITY_FIXTURES) {
- const { diagnostics } = run(fixture);
+ const { diagnostics, raw } = run(fixture);
const violations = await predicateViolations(fixture);
+ expect(raw, fixture).toContain('"number_of_files": 1');
expect(diagnostics.map((d) => `${d.line}:${d.column}:${d.class}`)).toStrictEqual(
violations.map((v) => `${v.comment.line}:${v.comment.column}:${v.class}`),
);
- compared += violations.length;
+ compared[fixture] = violations.length;
}
- expect(compared).toBe(22);
+ expect(compared).toStrictEqual({
+ 'must-fire.fixture.ts': 31,
+ 'must-not-fire.fixture.ts': 0,
+ 'jsx-text.fixture.tsx': 1,
+ 'jsdoc-types.fixture.mjs': 0,
+ 'jsdoc-types.fixture.ts': 3,
+ });
+ });
- const admitted = run('jsdoc-types.fixture.mjs');
- expect(admitted.raw).toContain('"number_of_files": 1');
- expect(admitted.diagnostics).toStrictEqual([]);
+ test('the same JSDoc type block is a directive in .mjs and prose in .ts', () => {
+ expect(run('jsdoc-types.fixture.mjs').diagnostics).toStrictEqual([]);
+ expect(
+ run('jsdoc-types.fixture.ts').diagnostics.map((d) => `${d.line}:${d.class}`),
+ ).toStrictEqual(['1:prose', '4:prose', '12:prose']);
});
test('is registered in the repo oxlint config as a JS plugin with a staged severity', async () => {
diff --git a/packages/app/tests/lint-plugins/no-demoted-dialog-confirm.test.ts b/packages/app/tests/lint-plugins/no-demoted-dialog-confirm.test.ts
index 859088c45..e6b823a7b 100644
--- a/packages/app/tests/lint-plugins/no-demoted-dialog-confirm.test.ts
+++ b/packages/app/tests/lint-plugins/no-demoted-dialog-confirm.test.ts
@@ -1,24 +1,4 @@
-/**
- * no-demoted-dialog-confirm — oxlint rule fixture test.
- *
- * Rule: `lint-plugins/ok-rules/rules/no-demoted-dialog-confirm.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/no-demoted-dialog-confirm.fixture.tsx`
- *
- * Per precedent #42 (custom lint enforcement is oxlint JS-plugin rules). Forbids a
- * dialog footer whose confirm sits on `secondary`, whose near-invisible fill
- * loses the emphasis contest with the `outline` dismiss standing beside it.
- * `ghost`, `link` and `link-muted` are flat at rest too but are not plausible
- * footer confirms; the rule's README section records why the pattern stays narrow.
- *
- * The fixture pairs 3 positive cases (the reported shape, the same inversion
- * with the dismiss wrapped in `DialogClose asChild`, and the
- * `AlertDialogFooter` sibling) with 4 negative cases (the canonical
- * variant-omitted confirm, a `destructive` confirm, a `secondary` button
- * outside any footer, and an inline-suppressed tertiary control).
- * Exact-equality (`toBe(3)`) catches both false-negative regressions (a
- * weakened pattern drops below 3) and false-positive widenings (a negative
- * starts firing, rising above 3).
- */
+/** The `no-demoted-dialog-confirm` oxlint rule fixture test, per precedent #42. */
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
diff --git a/packages/app/tests/lint-plugins/no-hand-rolled-spinner.test.ts b/packages/app/tests/lint-plugins/no-hand-rolled-spinner.test.ts
index 6d8445c5a..b93e2a0e4 100644
--- a/packages/app/tests/lint-plugins/no-hand-rolled-spinner.test.ts
+++ b/packages/app/tests/lint-plugins/no-hand-rolled-spinner.test.ts
@@ -1,24 +1,4 @@
-/**
- * no-hand-rolled-spinner — oxlint rule fixture test.
- *
- * Rule: `lint-plugins/ok-rules/rules/no-hand-rolled-spinner.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/no-hand-rolled-spinner.fixture.tsx`
- *
- * Per precedent #42 (custom lint enforcement is oxlint JS-plugin rules), which
- * requires every rule to ship with a fixture-file test. This rule was the one
- * exception: it shipped without a fixture under both the retired GritQL plugin
- * and the initial oxlint port, so the contract named a guarantee it did not have.
- *
- * Three guarantees, each its own test:
- * 1. Fires on exactly the planted positives and on no negative — the
- * bidirectional `toBe(5)` count, plus the diagnostic-message contract.
- * 2. Registered and enabled, and deliberately unscoped: a class string can
- * appear anywhere, so this rule belongs in `UNSCOPED_RULES` rather than
- * carrying a `RULE_SCOPES` entry.
- * 3. The `\b` delimiter admits `animate-spin-slow` but not `animate-spinner`.
- * The two look symmetric and are not, so the asymmetry is pinned directly
- * rather than left to the aggregate count.
- */
+/** The `no-hand-rolled-spinner` oxlint rule fixture test, per precedent #42. */
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
diff --git a/packages/app/tests/lint-plugins/no-inline-tolerance-class.test.ts b/packages/app/tests/lint-plugins/no-inline-tolerance-class.test.ts
index 5ad4de233..c40bbe73b 100644
--- a/packages/app/tests/lint-plugins/no-inline-tolerance-class.test.ts
+++ b/packages/app/tests/lint-plugins/no-inline-tolerance-class.test.ts
@@ -1,27 +1,4 @@
-/**
- * no-inline-tolerance-class — oxlint rule fixture test.
- *
- * Rule: `lint-plugins/ok-rules/rules/no-inline-tolerance-class.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/no-inline-tolerance-class.fixture.tsx`
- *
- * Per precedent #42 (custom lint enforcement is oxlint JS-plugin rules). Forbids a
- * public-mirrored test from writing a bridge tolerance-class catalog value
- * (`BRIDGE_TOLERANCE_CLASSES`) inline as a string literal. Importing the catalog
- * symbol into a public test is already blocked by `check-mirror-test-policy`
- * Check B (moat-import); this rule closes the complementary gap where a test
- * re-encodes a class value inline, bypassing the import check.
- *
- * Three guarantees, each its own test:
- * 1. Fires on exactly the planted positives (and on no negative) — the
- * bidirectional `toBe(8)` count, plus the diagnostic-message contract.
- * 2. Scoped via its `RULE_SCOPES` entry to the public test surface rather than
- * left unscoped, which would fire on the excluded clusters where the
- * catalog legitimately lives.
- * 3. The matched fidelity classes plus the four universal text-encoding
- * classes partition `BRIDGE_TOLERANCE_CLASSES` exactly — a class added to
- * the catalog reddens here until it is classified into one bucket, so the
- * guard can never silently cover a stale subset.
- */
+/** The `no-inline-tolerance-class` oxlint rule fixture test, per precedent #42. */
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
diff --git a/packages/app/tests/lint-plugins/no-physical-direction-utility.test.ts b/packages/app/tests/lint-plugins/no-physical-direction-utility.test.ts
index d299d6328..aee033c2d 100644
--- a/packages/app/tests/lint-plugins/no-physical-direction-utility.test.ts
+++ b/packages/app/tests/lint-plugins/no-physical-direction-utility.test.ts
@@ -1,29 +1,4 @@
-/**
- * no-physical-direction-utility — oxlint rule fixture test.
- *
- * Rule: `lint-plugins/ok-rules/rules/no-physical-direction-utility.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/no-physical-direction-utility.fixture.tsx`
- *
- * Per precedent #42 (custom lint enforcement is oxlint JS-plugin rules). The rule keeps
- * left-to-right assumptions from hardening into the chrome while right-to-left
- * layout is deferred — the plumbing is inert without an RTL locale, but the rule
- * works every day.
- *
- * The fixture pairs 7 positive cases (plain string, multi-line `cn()`, inset,
- * arbitrary value, `auto`, a `*ClassName` prop, a prefixed negative margin) with
- * 6 negative groups (the logical forms, `inset-x-*`, the `left-1/2` centering
- * anchor, side-free spacing, a side named outside a utility, and well-formed
- * utilities sitting in attributes that are not class props). Exact equality
- * catches a weakened pattern (count drops) and a widened one (a negative starts
- * firing). The rule has a single branch, so a total alone would still pass if one
- * positive went silent while one negative began firing — the flagged-line
- * assertions below close that by naming what must and must not be reported.
- *
- * Negative group 6 exists because every other case clears the rule on its VALUE:
- * remove the name predicate that scopes the rule to class props and the fixture
- * count does not move, so nothing would hold that predicate in place. Those three
- * attributes match the value pattern and are excluded by the name alone.
- */
+/** The `no-physical-direction-utility` oxlint rule fixture test, per precedent #42. */
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
diff --git a/packages/app/tests/lint-plugins/no-roundtrip-identity-oracle.test.ts b/packages/app/tests/lint-plugins/no-roundtrip-identity-oracle.test.ts
index a3b08f9e7..8496ac7b5 100644
--- a/packages/app/tests/lint-plugins/no-roundtrip-identity-oracle.test.ts
+++ b/packages/app/tests/lint-plugins/no-roundtrip-identity-oracle.test.ts
@@ -1,25 +1,6 @@
/**
- * no-roundtrip-identity-oracle — oxlint rule fixture test.
- *
- * Rule: `lint-plugins/ok-rules/rules/no-roundtrip-identity-oracle.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/no-roundtrip-identity-oracle.fixture.tsx`
- *
- * Per precedent #42 (custom lint enforcement is oxlint JS-plugin rules). Forbids the
- * byte-fidelity round-trip oracle — `serialize(parse(x))` (or the
- * MarkdownManager method form) asserted equal to the same input `x` — in
- * public-mirrored tests, so a new public test can't reintroduce the engine's
- * byte-identity correctness oracle that the engine fidelity suite owns
- * privately.
- *
- * The fixture pairs 10 positive cases (the identity oracle through toBe /
- * toEqual / toStrictEqual and `===`, in both bare `serialize(parse(...))` and
- * MarkdownManager method forms) with 7 negative cases (a fixed-literal contract
- * assertion, the `normalizeBridge(a) === normalizeBridge(b)` Bridge-invariant
- * contract from precedent #38, the `!==` normalizing-construct detector, the
- * helper-wrapped and two-statement round-trip forms, and a two-different-manager
- * comparison). Exact-equality (`toBe(10)`) catches both false-negative
- * regressions (a weakened pattern drops below 10) and false-positive widenings
- * (a negative starts firing, rising above 10).
+ * The `no-roundtrip-identity-oracle` oxlint rule fixture test, per precedent #42; its negative
+ * cases include the `normalizeBridge(a) === normalizeBridge(b)` contract from precedent #38.
*/
import { spawnSync } from 'node:child_process';
diff --git a/packages/app/tests/lint-plugins/no-split-suggestion-dispatch.test.ts b/packages/app/tests/lint-plugins/no-split-suggestion-dispatch.test.ts
index 117229ebe..fc1e98f56 100644
--- a/packages/app/tests/lint-plugins/no-split-suggestion-dispatch.test.ts
+++ b/packages/app/tests/lint-plugins/no-split-suggestion-dispatch.test.ts
@@ -1,26 +1,6 @@
/**
- * One-transaction suggestion insertion enforcement — `no-split-suggestion-dispatch`
- * oxlint rule (precedent #58).
- *
- * Rule: `lint-plugins/ok-rules/rules/no-split-suggestion-dispatch.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/no-split-suggestion-dispatch.fixture.tsx`
- *
- * The fixture pairs 3 positive cases (bare trigger-delete chain dispatch with
- * and without `.focus()`, plus the immediately-dispatching `commands.deleteRange`
- * form — all inside a `Suggestion({ ... })` config) with 4 negative cases (the
- * atomic single chain, the `.command()` boundary composition, delegation to
- * `applySlashCommandItem`, and a delete-only chain outside any Suggestion
- * config). The test asserts the rule fires exactly 3 times.
- *
- * Exact equality (`toBe(3)`) catches drift in both directions:
- * - false-negative: a weakened pattern drops below 3 → fails
- * - false-positive: a widened pattern fires on a negative case → above 3 → fails
- *
- * The runtime complement lives in `suggestion-atomicity.dom.test.tsx` and
- * `slash-command-atomicity.dom.test.tsx`, which drive the real surfaces through
- * a real Enter and assert exactly one doc-changing transaction — the lint rule
- * catches the bare-delete dispatch shape statically; the dom tests catch any
- * second dispatch the lint can't see (e.g. inside a delegated item).
+ * The `no-split-suggestion-dispatch` oxlint rule fixture test: one-transaction suggestion
+ * insertion per precedent #58.
*/
import { spawnSync } from 'node:child_process';
diff --git a/packages/app/tests/lint-plugins/no-unwrapped-user-facing-string.test.ts b/packages/app/tests/lint-plugins/no-unwrapped-user-facing-string.test.ts
index ca3511dbb..1d33985df 100644
--- a/packages/app/tests/lint-plugins/no-unwrapped-user-facing-string.test.ts
+++ b/packages/app/tests/lint-plugins/no-unwrapped-user-facing-string.test.ts
@@ -1,23 +1,4 @@
-/**
- * no-unwrapped-user-facing-string — oxlint rule fixture test.
- *
- * Rule: `lint-plugins/ok-rules/rules/no-unwrapped-user-facing-string.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/no-unwrapped-user-facing-string.fixture.tsx`
- *
- * Per precedent #42 (custom lint enforcement is oxlint JS-plugin rules). The rule makes
- * a hardcoded user-facing string a build-visible defect instead of a convention
- * a contributor has to remember.
- *
- * The fixture pairs 15 positive cases across the rule's four branches (2 toast
- * arguments, 2 JSX text nodes, 4 UI-facing attributes, 7 UI-facing object
- * properties) with 9 negative groups (`<Trans>` children direct and nested,
- * the `t` macro in child / attribute / object position, shortcut/code/path/
- * brand tokens, `<Brand> icon` marks, format-token placeholders, non-literal
- * toast arguments, unscoped property names, and TypeScript member positions).
- * Exact equality catches a weakened pattern (count drops) and a widened one (a
- * negative starts firing). The per-branch counts catch the compensating case a
- * total cannot: one branch losing a case while another gains one.
- */
+/** The `no-unwrapped-user-facing-string` oxlint rule fixture test, per precedent #42. */
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
diff --git a/packages/app/tests/lint-plugins/ok-rules-vocabulary.test.ts b/packages/app/tests/lint-plugins/ok-rules-vocabulary.test.ts
index 406b818e4..b1fb3cca6 100644
--- a/packages/app/tests/lint-plugins/ok-rules-vocabulary.test.ts
+++ b/packages/app/tests/lint-plugins/ok-rules-vocabulary.test.ts
@@ -1,46 +1,6 @@
/**
- * The `ok` rule corpus carries no vocabulary from the mechanism it replaced.
- *
- * Corpus: `CORPUS_DIRS` and `TEST_DIRS`. Read the constants, not a paraphrase.
- * The conformance property catalogs are in scope because they describe rules
- * in prose and one of them drifted. That package does not ship, so its two
- * entries are the ones in `ABSENT_ON_MIRROR`; every other entry must
- * contribute a scanned file or the corpus test reds with the directory named.
- * The exemption is gated on the PACKAGE root rather than on those leaves,
- * because a leaf that vanishes is the condition being detected.
- *
- * Per precedent #42 (custom lint enforcement is oxlint JS-plugin rules), which
- * names the rule corpus this scans. Two vocabularies are banned and they come
- * from different retirements: `gritql` / `.grit` / `biome-plugins` are the
- * Biome GritQL mechanism precedent #42 was rewritten away from, and `bun run`
- * is Bun syntax retired by the earlier remove-bun migration. `biome-ignore`
- * and `biome check` are deliberately NOT banned: Biome is still a live linter
- * here alongside oxlint.
- *
- * `judgeDemotion` blanks true plugin references in two passes and tests for a
- * demotion between them. Every strip is length-preserving, because two of the
- * checks are bounded-distance patterns and deleting text would pull unrelated
- * words inside a window they were never in.
- *
- * 1. `REAL_PLUGIN_NAMES` — this repo's own plugin directories, read from
- * disk so a third plugin needs no edit here. This one MUST run first:
- * the names are kebab-cased, so ``no-comments plugin`` would otherwise
- * false-fire `DEMOTED_UNAMBIGUOUS`'s kebab-identifier alternative.
- * 2. `DEMOTED_UNAMBIGUOUS` — a rule identifier next to `plugin`, optionally
- * through an engine qualifier (`<rule> oxlint plugin`), or `plugin test`
- * / `plugin fixture`. It runs BEFORE the remaining strips because either
- * of them can span a demotion and delete the token this keys on. Two
- * pinned cases assert exactly that, by running the same function with
- * the order inverted.
- * 3. `ENGINE_PLUGINS` then `PLUGIN_AS_MODULE`, then `NEAR_RULE_VOCABULARY`
- * on what survives. `ENGINE_PLUGINS` is a PHRASE strip rather than a
- * line verdict: one unrelated engine token must not immunise a real
- * demotion sitting beside it.
- *
- * `PLUGIN_AS_MODULE` holds module referents (a path, a file name, `plugin`
- * qualified by the module it names), the config key and code identifiers that
- * spell one, and `JS-plugin`, the one sanctioned category term, which about a
- * dozen corpus lines use for the rule mechanism itself.
+ * The rule corpus precedent #42 names carries no vocabulary from the retired GritQL plugin or
+ * the Bun runner; the corpus is `CORPUS_DIRS` and `TEST_DIRS`, read from the constants.
*/
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
diff --git a/packages/app/tests/lint-plugins/playwright-prefer-to-have-count.test.ts b/packages/app/tests/lint-plugins/playwright-prefer-to-have-count.test.ts
index abf0d8669..fc4e80f5f 100644
--- a/packages/app/tests/lint-plugins/playwright-prefer-to-have-count.test.ts
+++ b/packages/app/tests/lint-plugins/playwright-prefer-to-have-count.test.ts
@@ -1,23 +1,4 @@
-/**
- * playwright-prefer-to-have-count — oxlint rule fixture test.
- *
- * Rule: `lint-plugins/ok-rules/rules/playwright-prefer-to-have-count.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/playwright-prefer-to-have-count.fixture.tsx`
- *
- * Per precedent #42 (custom lint enforcement is oxlint JS-plugin rules). Bans the
- * one-shot `expect(await locator.count())` snapshot read in the browser
- * e2e suites — the no-retry assertion shape behind hidden flakes — in
- * favor of the web-first auto-retrying
- * `await expect(locator).toHaveCount(n)`. Upstream precedent:
- * eslint-plugin-playwright `prefer-to-have-count`.
- *
- * The fixture pairs 3 positive cases (one-shot reads through different
- * matchers — the rule must fire) with 5 negative cases (toHaveCount,
- * expect.poll, bare count read, different awaited method, two-statement
- * read-then-assert — rule must NOT fire). Exact-equality (`toBe(3)`)
- * catches both false-negative regressions (weakened pattern drops below 3)
- * and false-positive widenings (above 3).
- */
+/** The `playwright-prefer-to-have-count` oxlint rule fixture test, per precedent #42. */
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/asymmetric.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/asymmetric.ts
index dd9d0087f..cb73204dd 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/asymmetric.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/asymmetric.ts
@@ -1,22 +1,3 @@
-/**
- * Asymmetric fixture — 6-doc skewed-working-set, 5-minute envelope.
- *
- * 1 large PROJECT-class doc visited many times + 5 small docs visited
- * once each. The constraint-varied shape that surfaces
- * cap-vector divergence the symmetric fixtures hide — the pganalyze
- * TPROC-C/H smoking gun: same architecture, same knob, opposite-shaped
- * curves on different workload skew. If the verdict picks a different
- * cap-vector for asymmetric than for tight+broad, the sweep runner
- * flags it for per-cap-shipping consideration.
- *
- * rotationDocs is built with buildCorpus's small→large ordering
- * (small-001..small-005, large-001). The sweep runner finds the hot
- * doc by `sizeClass === 'large'`, not by index — so the layout here
- * follows the corpus convention rather than a fixture-specific override.
- *
- * Size mix: 5 small / 0 medium / 1 large = 6 docs.
- */
-
import { buildCorpus } from './generator.ts';
import type { SizeMix, WorkloadFixture } from './types.ts';
import { vault } from './vault.ts';
@@ -31,7 +12,6 @@ const ASYMMETRIC_SEED = 3003;
const ASYMMETRIC_NAME_PREFIX = 'asymmetric';
const FIVE_MINUTES_MS = 5 * 60 * 1000;
-/** 5 min envelope dominated by repeated visits to the single large doc. */
export const ASYMMETRIC_CYCLE_DURATION_MS = FIVE_MINUTES_MS;
export const asymmetricFixture: WorkloadFixture = Object.freeze({
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/broad.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/broad.ts
index f61c6b961..2d29e65ab 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/broad.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/broad.ts
@@ -1,14 +1,3 @@
-/**
- * Broad fixture — 60-doc random-eviction rotation, 20-minute total envelope.
- *
- * Tests the eviction-storm regime where the rotation size exceeds the
- * MAX_CACHE search-space ceiling (50) so the sweep
- * harness measures cold-mount cost + eviction-replay cost across the
- * cap-vector. ~30s/doc over 60 docs = 20-min total envelope.
- *
- * Size mix: 10 small / 30 medium / 20 large = 60 docs.
- */
-
import { buildCorpus } from './generator.ts';
import type { SizeMix, WorkloadFixture } from './types.ts';
import { vault } from './vault.ts';
@@ -24,7 +13,6 @@ const BROAD_NAME_PREFIX = 'broad';
const THIRTY_SECONDS_MS = 30 * 1000;
const BROAD_DOC_COUNT = 60;
-/** 20 min total envelope: ~30s/doc × 60 docs. */
export const BROAD_CYCLE_DURATION_MS = THIRTY_SECONDS_MS * BROAD_DOC_COUNT;
export const broadFixture: WorkloadFixture = Object.freeze({
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.test.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.test.ts
index a4fc9fbb7..d90151e7b 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.test.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.test.ts
@@ -52,7 +52,6 @@ describe('computeMedianRotationDistance', () => {
});
test('measures distinct docs between repeat visits', () => {
- // a → b → c → a distance between a-visits = 2 distinct ('b' and 'c')
const events = [
{ docName: 'a', contentBytes: 1000, openedAt: 1 },
{ docName: 'b', contentBytes: 1000, openedAt: 2 },
@@ -63,7 +62,6 @@ describe('computeMedianRotationDistance', () => {
});
test('median of multiple repeat distances', () => {
- // distances: a@4→a@1 = 2, b@5→b@2 = 2, c@6→c@3 = 2 (all 2)
const events = [
{ docName: 'a', contentBytes: 1000, openedAt: 1 },
{ docName: 'b', contentBytes: 1000, openedAt: 2 },
@@ -121,19 +119,15 @@ describe('loadTraces', () => {
});
test('skips truly malformed (unparseable) JSONL lines silently', () => {
- // Interrupted dogfood-trace captures can truncate the final line
- // mid-write. The loader must tolerate that without throwing — the
- // JSDoc contract is silent-skip for both missing-field AND
- // parse-failure shapes.
const dir = mkdtempSync(join(tmpdir(), 'cache-regime-rotation-calibrate-truncated-'));
try {
writeFileSync(
join(dir, 'truncated.jsonl'),
[
JSON.stringify({ docName: 'first', contentBytes: 500, openedAt: 1 }),
- '{"docName":"second","contentBytes":600,"opene', // truncated mid-key
+ '{"docName":"second","contentBytes":600,"opene',
JSON.stringify({ docName: 'third', contentBytes: 700, openedAt: 3 }),
- '{broken json[', // unrelated garbage
+ '{broken json[',
'totally not json',
].join('\n'),
);
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.ts
index 79f4f6831..a9cde5949 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.ts
@@ -1,31 +1,4 @@
#!/usr/bin/env -S npx tsx
-/**
- * Engineer-local realism check for the cache-regime rotation fixtures.
- *
- * Reads dogfood traces the engineer captured from their own OK usage
- * and compares the size distribution + rotation distance against the
- * three fixtures' declared shapes. Prints a drift summary to stdout —
- * never writes trace data, derived data, or output files. The fixtures
- * remain defensible without this step (the parallel-design verdict-
- * robustness check across 3 shapes carries the transferability claim).
- * This script is a local affordance for the engineer to
- * cross-check the engineered shapes against their own usage before
- * committing the campaign cost; it is NOT part of the verdict gate.
- *
- * Local-only by architectural constraint: OK is fully self-hostable and
- * has no production-telemetry channel. Trace capture is the
- * engineer's responsibility; this script consumes whatever they have.
- *
- * Trace format (JSONL, one event per line):
- * { "docName": "<string>", "contentBytes": <number>, "openedAt": <epoch-ms> }
- *
- * Trace path: $OK_DOGFOOD_TRACE_DIR (default $HOME/.ok/perf-traces/).
- *
- * Usage:
- * bun run packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.ts
- * bun run packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.ts --trace-dir <path>
- * bun run packages/app/tests/perf/fixtures/cache-regime-rotation/calibrate.ts --fixture tight
- */
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
@@ -56,7 +29,6 @@ interface RealismStats {
readonly totalEvents: number;
readonly distinctDocs: number;
readonly sizeDistributionPct: SizeDistribution;
- /** Median # of distinct docs between repeat visits; null when no repeats observed. */
readonly medianRotationDistance: number | null;
}
@@ -95,11 +67,6 @@ export function computeSizeDistributionPct(
};
}
-/**
- * Stack-distance variant: distinct docs touched between two consecutive
- * visits to the same doc. Median across all observed repeats provides
- * a robust central tendency for skewed (asymmetric) workloads.
- */
export function computeMedianRotationDistance(events: ReadonlyArray<TraceEvent>): number | null {
const lastVisit = new Map<string, number>();
const distances: number[] = [];
@@ -141,12 +108,6 @@ export function loadTraces(traceDir: string): TraceEvent[] {
for (const line of lines) {
const trimmed = line.trim();
if (trimmed === '') continue;
- // Truncated trace files (interrupted dogfood-capture sessions) can
- // produce malformed JSONL lines like `{"docName":"foo","cont`. A raw
- // JSON.parse error here would abort the whole calibration run with
- // a SyntaxError stack — the loader contract is silent-skip per the
- // JSDoc, so we honor that contract for both missing-field and parse-
- // failure shapes uniformly.
let parsed: Partial<TraceEvent>;
try {
parsed = JSON.parse(trimmed) as Partial<TraceEvent>;
@@ -181,16 +142,6 @@ export function summarizeTraces(events: ReadonlyArray<TraceEvent>): RealismStats
};
}
-/**
- * Heuristic expected rotation distance for each pattern.
- *
- * `hot-pocket` revisits the working set; expected distance ≈ size - 1.
- * `random-eviction` samples without intentional reuse; expected
- * distance ≈ size / 2 (mean stack distance under uniform random).
- * Asymmetric biases heavily toward one doc, so its harness-side
- * expected distance ≈ small_count for the hot-doc revisits (visits to
- * the 5 small docs interleaved with the large).
- */
export function expectedRotationDistance(fixture: WorkloadFixture): number {
const size = fixture.rotationDocs.length;
if (fixture.ref === 'asymmetric') {
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/generator.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/generator.ts
index e938a93bd..9715e947e 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/generator.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/generator.ts
@@ -1,27 +1,6 @@
-/**
- * Deterministic synthetic-corpus generator for the cache-regime fixtures.
- *
- * Same seed → byte-identical corpus across runs (verified by sha256 in
- * vault.test.ts). The generator is intentionally synthetic + parameterized
- * rather than scraping real OK content: OK is fully self-hostable
- * with no production-telemetry channel, so transferability of the verdict
- * rests on consistency across three engineered working-set shapes,
- * not on matching aggregated empirical traces.
- *
- * `calibrate.ts` is the local affordance for the engineer to check that
- * the engineered shapes plausibly mirror their own dogfood usage before
- * committing to a multi-hour campaign.
- */
-
import type { DocSpec, SizeMix } from './types.ts';
import { SIZE_ENVELOPES, totalDocsInMix } from './types.ts';
-/**
- * `mulberry32` — a 32-bit PRNG with full 2^32 period. Tiny, deterministic,
- * uniform enough for picking byte counts within an envelope. Cited
- * everywhere from Stack Overflow to JSFiddle since 2017; the contract
- * here is determinism, not cryptographic randomness.
- */
export function makePrng(seed: number): () => number {
let state = seed >>> 0;
return () => {
@@ -33,11 +12,6 @@ export function makePrng(seed: number): () => number {
};
}
-/**
- * Inclusive-low / exclusive-high integer sample from a unit-uniform `rng`.
- * Rejects `lo >= hi` rather than silently saturating — generator-misconfig
- * surfaces as a thrown error at corpus-build time, not as a malformed cell.
- */
export function sampleIntInRange(
rng: () => number,
loInclusive: number,
@@ -52,25 +26,11 @@ export function sampleIntInRange(
return loInclusive + Math.floor(rng() * span);
}
-/**
- * Pick a `contentBytes` value within the envelope for the given size class.
- *
- * Distribution is uniform within the envelope. The sweep harness does NOT
- * care about the precise distribution shape — only that cells span the
- * envelope so cache cost surfaces across the doc-size range. Uniform is
- * the simplest defensible choice and produces a corpus with visible spread.
- */
export function pickContentBytes(rng: () => number, sizeClass: DocSpec['sizeClass']): number {
const env = SIZE_ENVELOPES[sizeClass];
return sampleIntInRange(rng, env.minBytes, env.maxBytes + 1);
}
-/**
- * Frontmatter density is correlated with doc size: small docs rarely
- * carry rich frontmatter; large PROJECT-class docs almost always do.
- * The probabilities are calibrated against staff-reviewed OK fixture
- * intuition — not a tunable axis, just a generator default.
- */
export function pickFrontmatterDensity(
rng: () => number,
sizeClass: DocSpec['sizeClass'],
@@ -78,24 +38,20 @@ export function pickFrontmatterDensity(
const draw = rng();
switch (sizeClass) {
case 'small':
- // 70% none / 25% minimal / 5% heavy
if (draw < 0.7) return 'none';
if (draw < 0.95) return 'minimal';
return 'heavy';
case 'medium':
- // 20% none / 55% minimal / 25% heavy
if (draw < 0.2) return 'none';
if (draw < 0.75) return 'minimal';
return 'heavy';
case 'large':
- // 5% none / 35% minimal / 60% heavy
if (draw < 0.05) return 'none';
if (draw < 0.4) return 'minimal';
return 'heavy';
}
}
-/** Image-count caps per size class; sampled inclusively. */
const IMAGE_COUNT_CAPS = {
small: { min: 0, max: 1 },
medium: { min: 0, max: 3 },
@@ -110,17 +66,10 @@ export function pickImageCount(rng: () => number, sizeClass: DocSpec['sizeClass'
interface BuildDocSpecOpts {
readonly rng: () => number;
readonly namePrefix: string;
- /** 1-based ordinal so generated names sort intuitively. */
readonly index: number;
readonly sizeClass: DocSpec['sizeClass'];
}
-/**
- * Build one DocSpec deterministically from `rng`. The order of PRNG calls
- * is fixed (contentBytes → frontmatterDensity → imageCount) so a corpus
- * generated with the same seed and the same prefix sequence produces
- * byte-identical DocSpec records across runs.
- */
export function buildDocSpec(opts: BuildDocSpecOpts): DocSpec {
const { rng, namePrefix, index, sizeClass } = opts;
const contentBytes = pickContentBytes(rng, sizeClass);
@@ -135,11 +84,6 @@ export function buildDocSpec(opts: BuildDocSpecOpts): DocSpec {
};
}
-/**
- * `vault-001`, `vault-002`, … — width sized to the largest expected
- * corpus (3 digits covers up to 999 docs). Stable across builds so the
- * sweep harness's per-cell staging keys are stable too.
- */
export function formatDocName(prefix: string, oneBasedIndex: number): string {
const padded = String(oneBasedIndex).padStart(3, '0');
return `${prefix}-${padded}`;
@@ -151,14 +95,6 @@ interface BuildCorpusOpts {
readonly mix: SizeMix;
}
-/**
- * Build a corpus matching `mix` deterministically from `seed`.
- *
- * Layout is small → medium → large within `namePrefix` ordinals so the
- * caller can reason about the corpus by index range (e.g. `vault[0..14]`
- * are small). Tests rely on this ordering when computing the size mix
- * from the produced array.
- */
export function buildCorpus(opts: BuildCorpusOpts): DocSpec[] {
const { seed, namePrefix, mix } = opts;
const rng = makePrng(seed);
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/index.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/index.ts
index 7c9f7ad86..ce982560f 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/index.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/index.ts
@@ -1,11 +1,3 @@
-/**
- * Re-export surface for the cache-regime-rotation fixtures.
- *
- * Sweep harness consumers import { tightFixture, broadFixture,
- * asymmetricFixture, vault, WorkloadFixture, DocSpec } from this index
- * rather than reaching into the per-file modules directly.
- */
-
export { ASYMMETRIC_CYCLE_DURATION_MS, asymmetricFixture } from './asymmetric.ts';
export { BROAD_CYCLE_DURATION_MS, broadFixture } from './broad.ts';
export {
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/tight.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/tight.ts
index c9cfa98ee..d74314cb9 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/tight.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/tight.ts
@@ -1,14 +1,3 @@
-/**
- * Tight fixture — 8-doc hot-pocket rotation, 20-minute total envelope.
- *
- * Tests the small-working-set regime where every doc in the rotation
- * should plausibly stay cache-resident across the cycle. Sub-cycle
- * intent is "visit each over ~4 min, cycle ~5×" so
- * the sweep harness sees warm-reopen hit rates dominate.
- *
- * Size mix: 2 small / 4 medium / 2 large = 8 docs.
- */
-
import { buildCorpus } from './generator.ts';
import type { SizeMix, WorkloadFixture } from './types.ts';
import { vault } from './vault.ts';
@@ -24,11 +13,6 @@ const TIGHT_NAME_PREFIX = 'tight';
const FOUR_MINUTES_MS = 4 * 60 * 1000;
const FIVE_CYCLES = 5;
-/**
- * 20 min total envelope: ~4 min visit-each pass × 5 sub-cycles.
- * The cycle-count semantics live with the sweep runner; the fixture
- * declares the total time window only.
- */
export const TIGHT_CYCLE_DURATION_MS = FOUR_MINUTES_MS * FIVE_CYCLES;
export const tightFixture: WorkloadFixture = Object.freeze({
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/types.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/types.ts
index b7e1ce30a..f3a6bffaa 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/types.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/types.ts
@@ -1,59 +1,13 @@
-/**
- * Workload-fixture types for the cap-graduation cache-regime sweep harness.
- *
- * Three fixtures (tight / broad / asymmetric) plus a shared 100-doc vault
- * back the parallel-design verdict-robustness check — the
- * sweep harness considers the winning cap-vector defensible only if its
- * verdict is consistent across all three working-set shapes.
- *
- * `WorkloadFixture` carries the descriptive metadata the sweep runner
- * needs to schedule visits + the corpus the rotation touches. The visit
- * schedule itself (how the runner orders + revisits docs over the cycle
- * window) is the runner's responsibility, not the fixture's.
- */
-
-/** Discriminator tag for the three parallel-design fixtures. */
export type WorkloadFixtureRef = 'tight' | 'broad' | 'asymmetric';
-/**
- * Three-cap regime under test: MAX_POOL (ProviderPool warm-back size),
- * MAX_CACHE (V2 editor cache size), ACTIVITY_MOUNT_LIMIT (concurrent
- * Activity-mounted editors). The three caps are coupled per the
- * editor-cache architectural invariant — the sweep harness sweeps them
- * jointly with the cap-ordering constraint (per-cap with prior-stage
- * winner pinned).
- *
- * Canonical home for this shape — both the sweep runner (orchestration)
- * and cell-measurement library (instrumentation) import it from here so
- * adding a fourth coupled cap is a one-file edit.
- */
export interface CapRegime {
readonly maxPool: number;
readonly maxCache: number;
readonly activityMountLimit: number;
}
-/**
- * Rotation pattern the sweep runner applies over `rotationDocs`.
- *
- * - `hot-pocket` — high reuse rate on a bounded working set (cycle the
- * rotation set with revisits). Tight + asymmetric both use this; the
- * asymmetric working set is just heavily skewed toward one entry.
- * - `random-eviction` — sampling without intentional reuse, sized to
- * guarantee eviction at every cap value the sweep covers (broad).
- */
export type RotationPattern = 'hot-pocket' | 'random-eviction';
-/**
- * Per-doc envelope. `contentBytes` is the synthetic body size (UTF-8
- * bytes) the sweep harness materializes when it stages this doc; the
- * actual on-disk byte count includes frontmatter + image-shortcode
- * overhead the harness adds at materialization time.
- *
- * `large` envelope anchors at the defer-mount threshold so PROJECT-class
- * cells exercise the lazy-mount code path (LARGE_DOC_CHAR_THRESHOLD =
- * 500_000 in EditorActivityPool.tsx).
- */
export interface DocSpec {
readonly name: string;
readonly sizeClass: 'small' | 'medium' | 'large';
@@ -62,13 +16,6 @@ export interface DocSpec {
readonly contentBytes: number;
}
-/**
- * The design-contract shape.
- *
- * `vault` is shared by reference across all three fixtures so the sweep
- * runner can stage the background corpus once per harness invocation
- * rather than re-materializing 100 docs per fixture.
- */
export interface WorkloadFixture {
readonly ref: WorkloadFixtureRef;
readonly rotationDocs: ReadonlyArray<DocSpec>;
@@ -78,14 +25,12 @@ export interface WorkloadFixture {
readonly seed: number;
}
-/** Size-class byte envelopes. Used by the generator + calibration script. */
export const SIZE_ENVELOPES = {
small: { minBytes: 500, maxBytes: 5_000 },
medium: { minBytes: 5_000, maxBytes: 50_000 },
large: { minBytes: 50_000, maxBytes: 500_000 },
} as const satisfies Record<DocSpec['sizeClass'], { minBytes: number; maxBytes: number }>;
-/** Convenience tuple for fixture/vault size-mix declarations. */
export interface SizeMix {
readonly small: number;
readonly medium: number;
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.test.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.test.ts
index d1ae33f1d..31ef0876c 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.test.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.test.ts
@@ -5,8 +5,6 @@ import { SIZE_ENVELOPES, totalDocsInMix } from './types.ts';
import { VAULT_MIX, VAULT_NAME_PREFIX, VAULT_SEED, vault } from './vault.ts';
function sha256OfCorpus(docs: ReadonlyArray<unknown>): string {
- // Stable serialization: explicit key order so the digest doesn't drift
- // if a future TypeScript pass reorders object literals.
const stable = docs.map((d) => {
const spec = d as {
name: string;
diff --git a/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.ts b/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.ts
index 3c89e487b..cc0c3f9aa 100644
--- a/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.ts
+++ b/packages/app/tests/perf/fixtures/cache-regime-rotation/vault.ts
@@ -1,39 +1,16 @@
-/**
- * Shared 100-doc background corpus.
- *
- * Every cache-regime fixture (tight / broad / asymmetric) imports
- * `vault` by reference — the sweep harness can stage the 100-doc
- * background once per cell rather than re-materializing per fixture.
- * Referential identity is asserted in fixtures.test.ts.
- *
- * 15/60/25 mix — modest small/large tails with a thick
- * medium body so the sidebar + index workload exerts realistic pressure
- * on the rotation cap-vector under test.
- */
-
import { buildCorpus } from './generator.ts';
import type { DocSpec, SizeMix } from './types.ts';
-/** Vault size-mix (15 small + 60 medium + 25 large = 100 docs). */
export const VAULT_MIX = {
small: 15,
medium: 60,
large: 25,
} as const satisfies SizeMix;
-/** Fixed seed so vault doc-specs are stable across runs. */
export const VAULT_SEED = 42;
-/** Stable per-vault name prefix. */
export const VAULT_NAME_PREFIX = 'vault';
-/**
- * Eagerly-generated background corpus, sealed to its readonly contract.
- *
- * The eager-at-module-load shape is intentional: the sweep harness imports
- * `vault` from multiple fixture files and the referential-identity
- * invariant in fixtures.test.ts depends on the module being a singleton.
- */
export const vault: ReadonlyArray<DocSpec> = Object.freeze(
buildCorpus({ seed: VAULT_SEED, namePrefix: VAULT_NAME_PREFIX, mix: VAULT_MIX }),
);
diff --git a/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts b/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts
index d49567789..2c467990b 100644
--- a/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts
+++ b/packages/app/tests/perf/fixtures/generate-view-count-fixtures.test.ts
@@ -1,14 +1,3 @@
-/**
- * Unit tests for the view-count fixture generator.
- *
- * These are sanity tests for the convergence loop — we don't re-validate
- * every committed bucket here (that's checked at fixture-generation time).
- * The committed fixture dirs themselves are spot-checked via the
- * `generates fixtures within ±5% of target` test below, which runs the
- * generator across a range of targets and asserts the output measure
- * matches.
- */
-
import { existsSync, readFileSync } from 'node:fs';
import { resolve } from 'node:path';
import { MarkdownManager, OK_DIR, sharedExtensions } from '@inkeep/open-knowledge-core';
@@ -70,7 +59,6 @@ describe('generateFixture — convergence', () => {
const maxOk = Math.ceil(target * 1.05);
expect(measured).toBeGreaterThanOrEqual(minOk);
expect(measured).toBeLessThanOrEqual(maxOk);
- // Sanity: convergence terminated with a real result.
expect(result.iterations).toBeGreaterThan(0);
}
});
@@ -95,8 +83,6 @@ describe('generateFixture — convergence', () => {
const linkCount = countMarkType(pm, 'link');
const wikiCount = countNodeType(pm, 'wikiLink');
const total = linkCount + wikiCount;
- // Expect approximately 75/25 split; allow ±10% slack to absorb any
- // pipeline normalization (autolink-promotion etc.).
const linkRatio = linkCount / total;
expect(linkRatio).toBeGreaterThanOrEqual(0.65);
expect(linkRatio).toBeLessThanOrEqual(0.85);
diff --git a/packages/app/tests/perf/fixtures/generate-view-count-fixtures.ts b/packages/app/tests/perf/fixtures/generate-view-count-fixtures.ts
index d630d3eab..8476c5436 100644
--- a/packages/app/tests/perf/fixtures/generate-view-count-fixtures.ts
+++ b/packages/app/tests/perf/fixtures/generate-view-count-fixtures.ts
@@ -1,76 +1,21 @@
#!/usr/bin/env -S npx tsx
-/**
- * Synthetic view-count fixture generator.
- *
- * Produces markdown fixtures whose measured PM-view count is within ±5% of
- * a target. Used by the cache-hit reparent latency curve scenario to
- * probe `VIEW_COUNT_CACHE_THRESHOLD` calibration without depending on
- * real-world docs that drift over time.
- *
- * Mark mix is ~75% InternalLink + ~25% WikiLink (matches
- * production ratio of 6 internalLinks : 2 wikilinks per
- * production docs). Both render as plain-DOM chips
- * so view-count cost
- * attribution is comparable to real docs.
- *
- * Usage:
- * bun run tests/perf/fixtures/generate-view-count-fixtures.ts \
- * --target-views 100 --out-dir tests/perf/fixtures/views-100
- *
- * # Regenerate the canonical 5 buckets from scratch:
- * bun run tests/perf/fixtures/generate-view-count-fixtures.ts --all
- *
- * The generator validates the output by parsing it through
- * MarkdownManager (core's pipeline) and counting `link`-marked text +
- * `wikiLink` nodes in the resulting PM JSON. Iteration converges on the
- * target via additive adjustment.
- *
- * Generator-vs-fixture pinning
- * ----------------------------
- * The committed fixtures under `views-{25,50,100,200,400}/` are
- * intentionally pinned at the generator state when they were last
- * regenerated. They are NOT regenerated on every test run — that would
- * defeat the cross-time reproducibility the measurement depends on.
- * If the generator's mark-mix ratio or convergence logic changes, the
- * committed fixtures will drift relative to fresh generator output —
- * that drift is BY DESIGN: the scenarios still consume the pinned
- * fixtures so prior measurements remain comparable. Any intentional
- * regeneration must be paired with re-baselining the measurement
- * against the new fixtures.
- */
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { MarkdownManager, OK_DIR, sharedExtensions } from '@inkeep/open-knowledge-core';
-// ---------------------------------------------------------------------------
-// Config
-// ---------------------------------------------------------------------------
-
-/** Approximate total fixture byte target (~50 KB). */
const TARGET_BYTES = 50_000;
-/** Tolerance for the actual-view-count vs target check. */
-const TOLERANCE_RATIO = 0.05; // ±5%
+const TOLERANCE_RATIO = 0.05;
-/** Mix ratio — 75% internal links, 25% wikilinks. */
const INTERNAL_LINK_RATIO = 0.75;
-/** Maximum iterations to converge on target. Generator backs off if exceeded. */
const MAX_ITERATIONS = 12;
-/** Canonical view-count buckets when invoked with --all. */
const CANONICAL_TARGETS = [25, 50, 100, 200, 400] as const;
-/** Output dir naming convention. */
const FIXTURE_DIR_PREFIX = 'views-';
-// ---------------------------------------------------------------------------
-// Filler content — short prose stanzas inserted between chips so the doc
-// is not just a chip-dump. Length scales inversely with chip count to keep
-// the total around TARGET_BYTES.
-// ---------------------------------------------------------------------------
-
const PROSE_STANZAS = [
'The architecture remains stable across iterations of the schema.',
'Each layer publishes its constraints in writing for the next reader.',
@@ -98,14 +43,8 @@ function makeFiller(targetBytes: number): string {
return stanzas.join('\n');
}
-// ---------------------------------------------------------------------------
-// Markdown construction
-// ---------------------------------------------------------------------------
-
interface BuildArgs {
- /** Number of chips to emit (caller's planned chip count). */
chips: number;
- /** Approximate total bytes for the entire fixture. */
totalBytes: number;
}
@@ -113,8 +52,6 @@ function buildFixtureMarkdown(args: BuildArgs): string {
const { chips, totalBytes } = args;
const internalCount = Math.round(chips * INTERNAL_LINK_RATIO);
- // Build a flat sequence of chip markers (alternating-style — interleaved
- // so the mix is uniform across the doc rather than 75% then 25%).
const chipSequence: string[] = [];
for (let i = 0; i < chips; i++) {
if (i < internalCount) {
@@ -123,9 +60,6 @@ function buildFixtureMarkdown(args: BuildArgs): string {
chipSequence.push(`[[Chip ${i + 1}]]`);
}
}
- // Interleave by alternating the two slices (FY-shuffle would inflate the
- // generator surface and is not required — the measurement does not
- // care about chip ordering, only the count).
const interleaved: string[] = [];
let internalIdx = 0;
let wikiIdx = internalCount;
@@ -134,9 +68,6 @@ function buildFixtureMarkdown(args: BuildArgs): string {
if (wikiIdx < chips) interleaved.push(chipSequence[wikiIdx++]);
}
- // Approximate chip byte cost so filler fills the rest. Each chip is on its
- // own line embedded in a sentence; we estimate ~50 bytes per line including
- // surrounding prose.
const chipBytes = interleaved.join(' ').length + interleaved.length * 5;
const fillerBudget = Math.max(0, totalBytes - chipBytes);
const fillerPerSection = chips > 0 ? Math.floor(fillerBudget / (chips + 1)) : fillerBudget;
@@ -148,16 +79,11 @@ function buildFixtureMarkdown(args: BuildArgs): string {
sections.push(makeFiller(fillerPerSection));
}
- // Minimal frontmatter so the doc looks like a real OK page.
return `---\ntitle: View Fixture (${chips} chips)\n---\n\n${sections
.filter((s) => s.length > 0)
.join('\n\n')}\n`;
}
-// ---------------------------------------------------------------------------
-// PM-view counting
-// ---------------------------------------------------------------------------
-
interface PmJson {
type?: string;
marks?: { type: string }[];
@@ -176,10 +102,6 @@ function countViewsInPmJson(node: PmJson): number {
return count;
}
-// ---------------------------------------------------------------------------
-// Iteration loop — converge on the target
-// ---------------------------------------------------------------------------
-
interface ConvergeResult {
markdown: string;
measuredViews: number;
@@ -189,9 +111,6 @@ interface ConvergeResult {
function convergeOnTarget(targetViews: number): ConvergeResult {
const mgr = new MarkdownManager({ extensions: sharedExtensions });
- // Each chip registers approximately one PM view (one wikiLink node OR one
- // link-marked text). Start with chips = targetViews and adjust by the
- // delta until within tolerance.
let chips = targetViews;
let lastResult: ConvergeResult | null = null;
for (let iter = 0; iter < MAX_ITERATIONS; iter++) {
@@ -210,20 +129,14 @@ function convergeOnTarget(targetViews: number): ConvergeResult {
if (measured >= minOk && measured <= maxOk) {
return result;
}
- // Adjust chips by the delta (one chip ≈ one view, so additive correction).
const delta = targetViews - measured;
chips += delta;
if (chips < 0) chips = 0;
}
- // Failed to converge — return the last attempt so the caller can decide.
if (!lastResult) throw new Error('[gen-fixtures] convergence loop produced no result');
return lastResult;
}
-// ---------------------------------------------------------------------------
-// Filesystem
-// ---------------------------------------------------------------------------
-
const OK_CONFIG_YML = `content:
dir: .
include:
@@ -237,10 +150,6 @@ function writeFixture(outDir: string, markdown: string): void {
writeFileSync(resolve(outDir, OK_DIR, 'config.yml'), OK_CONFIG_YML);
}
-// ---------------------------------------------------------------------------
-// CLI
-// ---------------------------------------------------------------------------
-
interface Args {
targetViews?: number;
outDir?: string;
diff --git a/packages/app/tests/perf/scenarios/cold-pool-warm.ts b/packages/app/tests/perf/scenarios/cold-pool-warm.ts
index 8c27427e8..55c7c6fb0 100644
--- a/packages/app/tests/perf/scenarios/cold-pool-warm.ts
+++ b/packages/app/tests/perf/scenarios/cold-pool-warm.ts
@@ -1,45 +1,7 @@
/**
- * Cold-pool-warm reproduction — target the specific state where the big-doc
- * is provider-pool-resident but Activity-evicted, so revisiting it forces
- * a fresh TipTap mount without the provider/Y.Doc re-sync.
- *
- * Rationale: the ~9.7s single-main-thread-task cost was measured on this
- * state, not a fresh cold-load. A fresh cold-load ALSO pays Y.Doc sync cost
- * (instrumentation has measured it at 1.7-2.3s).
- * "Cold-pool-warm" isolates the TipTap+PM+React cost from the Y.Doc sync.
- *
- * Scenario flow:
- * 1. Cold-load README (small, 5 KB) — warms ProviderPool for README.
- * 2. Navigate to BIG_DOC (large) — warms pool for BIG_DOC, mounts Activity
- * entry for BIG_DOC.
- * 3. Navigate to 3 OTHER docs (to force Activity eviction of BIG_DOC via
- * ACTIVITY_MOUNT_LIMIT=3). BIG_DOC's provider stays pool-resident.
- * 4. Navigate BACK to BIG_DOC — measure time until PM content visible.
- *
- * The measured boundary is step 4. BIG_DOC's provider is still pool-resident
- * (ytext already hydrated), so the measurement is:
- * [useState lazy init (new Editor → new EditorView → _forceRerender → docView)
- * → React commit → EditorContent.init (createNodeViews) → portal reconcile →
- * browser layout/paint]
- *
- * No Y.Doc sync on this path. Any difference vs `cold-load-big-doc` is the
- * sync cost. The monkey-patched `ok/cold/*` marks decompose the TipTap/PM/React
- * cost within this window.
- *
- * Regression-gate invocation (canonical):
- * OK_PERF_BIG_DOC=perf-fixtures/medium-doc bun run perf:profile --scenario=cold-pool-warm
- *
- * perf-fixtures/medium-doc is the designated reference doc (≈176 MarkView portals, fits
- * the ≤200-view target band). Baseline: 541 ms. Target:
- * < 300 ms. Depends on doc-markers.ts entry for perf-fixtures/medium-doc — without it the
- * scenario falls through to a content-length heuristic that races against
- * still-Activity-mounted previous docs and produces pmLen numbers matching
- * the wrong editor.
- *
* Default (BIG_DOC=perf-fixtures/big-doc) is a 768-view stress case used for attribution
- * measurements and precedent #27 validation — informative but outside the
- * regression-gate target scope. Use it for "how bad was the worst case" and
- * the perf-fixtures/medium-doc invocation for "does the current code still hit the gate."
+ * measurements and precedent #27 validation — informative but outside the regression-gate target
+ * scope.
*/
import { markerFor } from '../lib/doc-markers.ts';
diff --git a/packages/app/tests/perf/scenarios/warm-switch.ts b/packages/app/tests/perf/scenarios/warm-switch.ts
index 14bbe5d65..6ab1a49e9 100644
--- a/packages/app/tests/perf/scenarios/warm-switch.ts
+++ b/packages/app/tests/perf/scenarios/warm-switch.ts
@@ -1,23 +1,7 @@
/**
- * Reproduction — warm switch-back to a previously-loaded small doc after
- * visiting a large doc.
- *
- * Workflow:
- * 1. Cold-load README (small, 5 KB).
- * 2. Navigate to PROJECT (large, multi-MB) — waits for PROJECT content.
- * 3. Click sidebar's README entry — measure wall-clock until README's
- * visible ProseMirror is rendered with README-specific content.
- *
- * The user-visible symptom is "click a sidebar entry → noticeable hitch"
- * after visiting a big doc, so the scenario measures the full click→content
- * pipeline. The timing starts at the sidebar click and ends when the visible
- * editor contains README content — which is the user-perceived "switch
- * completed" moment.
- *
- * Pre-fix baseline: warmSwitchMs ≥ 500.
- * Post-fix target: warmSwitchMs < 100 AND README content continuity
- * preserved during the transition (precedent #18 G2 — verified by Playwright
- * E2E tests `docs-open.e2e.ts` which aren't re-run here, just not regressed).
+ * Post-fix target: warmSwitchMs < 100 AND README content continuity preserved during the transition
+ * (precedent #18 G2 — verified by Playwright E2E tests `docs-open.e2e.ts` which aren't re-run here,
+ * just not regressed).
*/
import { markerFor } from '../lib/doc-markers.ts';
diff --git a/packages/app/tests/stress/_helpers/clipboard.ts b/packages/app/tests/stress/_helpers/clipboard.ts
index 843cebe15..24ec1caed 100644
--- a/packages/app/tests/stress/_helpers/clipboard.ts
+++ b/packages/app/tests/stress/_helpers/clipboard.ts
@@ -1,17 +1,6 @@
/**
- * Clipboard interaction helpers for E2E tests.
- *
- * Dispatches synthetic `ClipboardEvent`s with an intercepted
- * `DataTransfer.setData` so the test can read the MIME map the app's copy /
- * cut handlers wrote, without depending on the real browser clipboard. The
- * programmatic approach bypasses `navigator.clipboard` permission prompts
- * and browser-specific clipboard quirks — same-machine-same-clipboard
- * pollution between concurrent Playwright workers is impossible with this
- * pattern.
- *
- * Precedent #19 (clipboard pipeline is mdast-canonical with per-view hook
- * mechanisms) is what these helpers exercise. See paste-fidelity.e2e.ts for
- * the MIME-shape assertions that rely on this.
+ * Precedent #19 (clipboard pipeline is mdast-canonical with per-view hook mechanisms) is what these
+ * helpers exercise.
*/
import type { Page } from '@playwright/test';
diff --git a/packages/app/tests/stress/_helpers/editor-state.ts b/packages/app/tests/stress/_helpers/editor-state.ts
index b64267946..821170606 100644
--- a/packages/app/tests/stress/_helpers/editor-state.ts
+++ b/packages/app/tests/stress/_helpers/editor-state.ts
@@ -137,69 +137,7 @@ export async function selectAllAndWaitForSelection(
});
}
-/**
- * Commit DOM focus on the active PM editor AND sync the browser's DOM
- * selection to match PM's `state.selection`. Required between
- * `page.evaluate(() => editor.chain().focus().setTextSelection(...).run())`
- * and any subsequent `page.keyboard.press(...)` whose effect must be
- * observed by PM's keymap from the freshly-set cursor position.
- *
- * Two compounding gaps this closes:
- *
- * 1. **DOM-focus deferral**: TipTap's `editor.commands.focus()` defers
- * `view.focus()` to `requestAnimationFrame` on Chromium / Firefox
- * (only iOS/Android/Safari run it synchronously — see `@tiptap/core`
- * `delayedFocus`). The chain returns before the rAF fires, so the
- * next `page.keyboard.press(...)` may land on `document.body` (the
- * focus fallback after the prior test's editor was unmounted by
- * `page.goto`). PM's keymap is wired to
- * `view.dom.addEventListener('keydown', ...)`, so an event on
- * `body` bypasses every L0/L1 handler.
- *
- * 2. **DOM-selection-not-synced**: PM's `selectionToDOM` early-returns
- * when `editorOwnsSelection(view)` is false, and that check goes
- * through `view.hasFocus()`. So `editor.chain().focus().setTextSelection(pos).run()`
- * updates PM `state.selection` to the target position, but the
- * browser's `document.getSelection()` is NOT synced to match. The
- * next ArrowUp / ArrowRight / ... dispatches against the STALE DOM
- * cursor position; the browser's default key-handling moves the
- * cursor from the wrong origin, and PM's DOMObserver reads back the
- * resulting (still wrong) cursor into PM state — the assertion sees
- * "cursor didn't move" because the wrong-origin motion looks like a
- * no-op or moves the cursor to an unexpected destination.
- *
- * Fix (mirrors PM's own focus path):
- *
- * a. Call `view.focus()` (PM's `EditorView` method, NOT raw
- * `view.dom.focus()`). PM's `view.focus()` focuses `view.dom` AND
- * calls `selectionToDOM(view)` internally — that's the call that
- * actually moves the browser's DOM cursor to match `editor.state.selection`.
- *
- * b. Poll until `view.hasFocus()` is true (Chromium's `element.focus()`
- * updates `activeElement` after a microtask tick — Playwright sends
- * keyboard events over CDP and the focus event may not have
- * propagated to `root.activeElement` yet). On each poll iteration,
- * RE-INVOKE `view.focus()` so `selectionToDOM` runs again now that
- * `editorOwnsSelection(view)` actually returns true (it checks
- * `view.hasFocus()`).
- *
- * For programmatic cursor positions INSIDE NodeView-wrapped paragraphs
- * (e.g. inside a Callout body's `<p>`), `domAtPos` / `getSelection`
- * alignment is brittle (programmatic placement here remained flaky at
- * `--repeat-each=5`, so those cases were refactored to a real
- * `page.locator().click()` + `Home` + `waitForPmSelectionInNode('jsxComponent')`
- * pattern with a reliable contract). This helper is
- * suited to programmatic cursor placement at TOP-LEVEL textblock
- * boundaries (heading, top-level paragraph).
- *
- * Bounded by `view.hasFocus() === true`. Default upper bound 5s; DOM
- * focus events fire within ~1 rAF / 16ms in practice, but under CI
- * `workers=4` CPU contention a cold worker has been observed to exceed
- * 2s. The bound is the
- * actual observable condition, not a magic sleep.
- *
- * Category C (cursor / focus flush) per precedent #20(a).
- */
+/** Category C (cursor / focus flush) per precedent #20(a). */
export async function focusEditor(page: Page, timeoutMs = 5_000): Promise<void> {
await page.evaluate(() => {
const editor = window.__activeEditor;
@@ -257,30 +195,9 @@ export async function selectText(page: Page, text: string): Promise<void> {
);
}
-/**
- * Wait until ProseMirror's `editor.state.selection` has an ancestor of the
- * given `nodeType` name — i.e. the cursor is INSIDE that node type per PM's
- * internal state, not merely per the DOM.
- *
- * Use this after a `click()` that should land the cursor inside a specific
- * node (tableCell, listItem, codeBlock, ...) and BEFORE the subsequent
- * `keyboard.press(...)` that reads PM state. Under `workers>1` CPU
- * contention, PM's DOMObserver can lag behind the DOM selection update by
- * tens of ms — a double-rAF yield reports "frame painted" but PM's state
- * is still stale. The TipTap table extension's Tab handler reads
- * `editor.state.selection`, sees no tableCell ancestor, calls
- * `goToNextCell()` → returns false → falls through to `addRowAfter()`
- * which creates an empty trailing row (the exact
- * flake that surfaced under full-suite `workers=4`).
- *
- * Requires `window.__activeEditor` exposure from `DocumentContext.tsx`
- * (DEV-gated — tree-shaken from production bundles). Category C per
- * precedent #20(a).
- *
- * WARN: walks `$from` ancestors, so it can never match a NodeSelection —
- * there the selected node is `selection.node`, not an ancestor of `$from`.
- * A caller arming a NodeSelection needs its own predicate.
- */
+/** Category C per precedent #20(a). */
+/* WARN: walks `$from` ancestors, so it can never match a NodeSelection; a caller arming a
+ NodeSelection needs its own predicate. */
export async function waitForPmSelectionInNode(
page: Page,
nodeType: string,
diff --git a/packages/app/tests/stress/cv-auto-paint-lock-click.e2e.ts b/packages/app/tests/stress/cv-auto-paint-lock-click.e2e.ts
index 29cee1d64..a9e6f3d1b 100644
--- a/packages/app/tests/stress/cv-auto-paint-lock-click.e2e.ts
+++ b/packages/app/tests/stress/cv-auto-paint-lock-click.e2e.ts
@@ -1,194 +1,7 @@
/**
- * Renderer-survival pin for the SECOND display-lock site: `.ok-chunk-wrapper`
- * (`content-visibility: auto`), which `cv-paint-lock-click.e2e.ts` leaves
- * explicitly unpinned.
- *
- * Blink hard-CHECKs (`third_party/blink/renderer/core/layout/hit_test_result.cc`,
- * `LockedAncestorPreventingPaint` inside `HitTestResult::GetPosition()`) when a
- * mouse press's hit-tested node has a paint-blocked ANCESTOR at the moment the
- * click's default selection resolution reads a caret position out of the
- * already-captured hit result. The whole renderer dies; the desktop shell
- * auto-reloads the window, which users experience as an app reboot. Note the
- * asymmetry that makes this a crash rather than a no-op: one line below the
- * CHECK, Blink returns gracefully when the hit node's own CHILDREN are
- * lock-blocked. Only the ancestor case aborts.
- *
- * `.ok-mode-hidden` (`content-visibility: hidden`) is the site the sibling test
- * pins. This file covers the other one: OK stamps `.ok-chunk-wrapper` on EVERY
- * top-level ProseMirror block (`chunk-wrapper-decoration.ts`) with a bare
- * `content-visibility: auto` and no deferral.
- *
- * A field renderer crash landed on exactly that CHECK, on a build that already
- * carried the `.ok-mode-hidden` fix, with a recovered stack showing the click
- * dispatched as RAF-aligned input from inside `BeginMainFrame` — the input
- * dispatch happening *within* a rendering update.
- *
- * WHY THE CRASH NEEDS A DESCENDANT HIT. A locked cv:auto wrapper does not lay
- * out its contents, so a hit inside it resolves to the wrapper itself and takes
- * the graceful child-blocked path. The CHECK is only reachable if the hit test
- * resolves to a DESCENDANT while the wrapper is unlocked, and the wrapper then
- * locks before the caret is read.
- *
- * WHAT IS AND IS NOT OBSERVABLE FROM A TEST. The window between the hit result
- * being captured and `GetPosition()` reading it is real, and script plus several
- * forced style/layout flushes run inside it. But the two ways a cv:auto element
- * can lock behave differently there:
- *
- * - Intersection-driven (scrolling it out of the render margin) cannot land in
- * the window. The mousedown path's flushes stop at pre-paint, before the
- * post-layout intersection-observer step, and a scroll only marks
- * intersection state dirty rather than delivering synchronously. CSS
- * Contain 2 corroborates: skipped-state updates are deferred to the
- * rendering update's own step, so a forced `offsetHeight` cannot deliver a
- * relevance change.
- * - Style-driven can, in principle: a newly created display-lock context
- * starts with its viewport-intersection flag false, so applying cv:auto to
- * an element that did not have it locks it during the next style recalc,
- * even fully on-screen.
- *
- * NO TEST HERE CAN PROVE A LOCK DID NOT COMMIT INSIDE THE DISPATCH, and this
- * file deliberately does not claim to. `contentvisibilityautostatechange` is
- * dispatched by POSTING A TASK, not inline with the lock flip
- * (`DisplayLockContext::ScheduleStateChangeEventIfNeeded`), so run-to-completion
- * guarantees it lands after any synchronous handler finishes. An earlier draft
- * timed the event against a window stamped inside the handler and asserted the
- * count was zero; that assertion was structurally incapable of failing and has
- * been removed rather than left to read as evidence.
- *
- * THE SAFETY PROPERTY THIS FILE DISCOVERED AND NOW PINS. A clicked block cannot
- * enter the cv:auto paint lock at all, because the click places the caret in it
- * and `content-visibility: auto` keeps a selection-containing element relevant
- * to the user indefinitely. The committed arm measures this within-subject:
- * scrolled two viewports away UNCLICKED the target locks; clicked first and
- * scrolled FOUR TIMES that distance it does not, while dozens of sibling blocks
- * lock in the same run. (An investigation run, not committed here, also found
- * no lock for a clicked block at the control's own two viewports — so the
- * result is not an artifact of the larger distance.) So it is the selection
- * pin, not scroll distance. That
- * pin is what keeps this site safe, it is a Chromium behavior rather than
- * anything OK controls, and the first test below fails loudly if a future
- * Chromium drops it.
- *
- * PRECONDITIONS ARE MEASURED, NOT ASSUMED. `landing.ts` warns that "whether
- * Chromium actually skips an off-screen chunk in a headless run is a runtime
- * decision", and a green here would be worthless if nothing ever locked. Two
- * plausible oracles are blind and must not be used. Measured, not reasoned:
- * the box-height probe `landing.ts` uses for materialization reported a
- * non-zero child height for EVERY block, including one 12,543px off-screen —
- * so it cannot distinguish skipped from painted here. (The mechanism behind
- * that is not established. Reading a descendant's rect inside a skipped
- * subtree plausibly forces the layout it is trying to observe, but this file
- * does not claim that; what it relies on is the observation.) Separately,
- * `Element.checkVisibility({contentVisibilityAuto:true})`
- * reported 0 skipped of 389 off-screen wrappers because it answers about the
- * wrapper, which stays visible while its CONTENTS are skipped. The spec'd
- * `contentvisibilityautostatechange` event is the honest signal for WHETHER a
- * relevance flip happened, with the caveat above that it cannot time one.
- * Measured on this harness (400-block doc): a mid-document scroll jump produces
- * 42 `skipped: true` transitions, identically headless and headed — so headless
- * is a faithful substrate and this pin belongs in CI.
- *
- * WHAT WAS TRIED AND SURVIVED. Six shapes, all leaving the renderer alive:
- * scrolling the clicked block out of relevance mid-dispatch; applying a fresh
- * cv:auto to an on-screen ancestor inside the capture-phase mousedown; a
- * remove/flush/re-add of the app's own wrapper class (the shape a ProseMirror
- * decoration recompute produces); an `auto -> visible -> flush -> auto`
- * retoggle; clicks under scroll churn on a congested main thread; and
- * CDP-batched move+press so the press dispatches from inside `BeginMainFrame`.
- * None reproduced the CHECK. Note for anyone re-running these: removing and
- * re-adding a cv:auto class inside ONE task is a no-op, because Blink's
- * requested-state setter early-returns when the computed value did not change.
- * An experiment built that way tests nothing and reads exactly like proof of
- * safety.
- *
- * This seam only exists in a real Chromium layout/paint engine — jsdom has no
- * display-lock machinery — so the pin lives at Playwright fidelity.
- *
- * WHY THIS FILE OPTS OUT OF THE SUITE'S CI RETRIES. `playwright.config.ts` sets
- * `retries: isCI ? 2 : 0` with `failOnFlakyTests: false`, so in CI a test runs
- * up to three times and failed-then-passed is classified flaky and let through.
- * For an intermittent renderer abort that masks almost everything: the run goes
- * red only when the crash reproduces on ALL THREE attempts, and two-of-three is
- * hidden exactly as thoroughly as one-of-three. The file therefore calls
- * `test.describe.configure({ retries: 0 })` below, making CI behave the way
- * local already did — one reproduction fails the run.
- *
- * The exposure was never total, and the record should not imply it was.
- * A daily scheduled CI job already drives this same `test:e2e` task at
- * `--repeat-each=3 --retries=0`, and its own comment calls `--retries=0`
- * load-bearing for exactly this reason. (It is named in `precedent #20(e)`
- * rather than here: it lives in the monorepo's root workflow tree, which is not
- * part of this mirror, so the filename would not resolve for a reader who has
- * only the public repo.) Three unretried
- * attempts a day is arguably a stronger detector for a probabilistic abort than
- * the single PR-tier attempt this override creates. What the override actually
- * buys is PR-tier BLOCKING rather than next-day advisory, which matters because a
- * merged renderer-crash regression rides the beta cadence out to users before the
- * daily run fires.
- *
- * The opt-out is per-file on purpose. The suite-wide settings are load-bearing:
- * their own comment in `playwright.config.ts` records that turning
- * `failOnFlakyTests` on globally promoted WebSocket and CRDT-broadcast noise to
- * PR-red and cut the PR-tier green rate to roughly 22% on correct code. Those
- * retries absorb infrastructure flake, which is what they are for. A renderer
- * crash is not infrastructure flake, so this file — and only this file — treats
- * a single occurrence as fatal. The sibling `.ok-mode-hidden` pin does NOT need
- * the same treatment: its header records that it reproduces its timing
- * deterministically, so a regression there fails all three attempts anyway and
- * retries cannot mask it. Do not spread this policy on symmetry alone.
- *
- * WHAT THE OPT-OUT ALSO MAKES FATAL. The mechanism is per file, not per failure
- * mode, so it is not only the crash that stops being retried. `setupTallDoc`'s
- * seeding and provider sync, `stageTargetForClick`'s convergence bound, and the
- * lock-event settle waits in two of the three tests all become
- * single-occurrence-fatal too, and those are precisely the WebSocket and
- * CRDT-broadcast classes the retries were absorbing. Two more join them. The
- * file's `test.use({ trace })` is a WORKER-scoped option, so it partitions the
- * worker pool and this file can never land on an already-booted worker: it
- * always pays a fresh `workerServer` boot (Vite, Hocuspocus, a `mkdtemp`
- * contentDir and a warmup load), and that boot is now unretried as well. This
- * is the same partitioning the `workerServerEnv` files already accept, so it is
- * precedented rather than novel, but it was previously amortizable and is not
- * any more. And `pressAndProbe` resolves ANY renderer death to
- * `renderer-crashed`, so a host-pressure or OOM kill is indistinguishable here
- * from the abort being hunted and now fails the PR on first occurrence wearing
- * the hunted crash's face.
- *
- * That is the price, accepted knowingly: a crash reported green is a
- * worse failure for this file than a setup flake reported red, and three tests
- * over one document is a small surface to pay it on. If this file starts going
- * red on seeding or sync rather than on a hit-test abort, harden the setup —
- * do not restore the retries, which would re-hide the crash along with the noise.
- *
- * TRACE, AND WHAT A RED RUN ACTUALLY LEAVES. Zero retries makes the suite's
- * `trace: 'on-first-retry'` unreachable here, so the file sets
- * `retain-on-failure` instead. That is not a nicety on this pin: measured on
- * 1.59.1 by crashing a renderer with real page content loaded, a dead renderer
- * CANNOT be screenshotted. An identical failure with the renderer alive leaves
- * `test-failed-1.png`; kill the renderer first and the screenshot is simply
- * absent, while `trace.zip` and `video.webm` both survive. On the one failure
- * path this file exists to catch, trace is therefore the richest artifact that
- * still exists rather than a luxury on top of a screenshot.
- *
- * The churn arm pays for this and keeps it anyway. Tracing costs tests one and
- * two 13% and 18%, but takes the churn arm from 3.4s to 7.5s across three runs,
- * because it congests the main thread on purpose and snapshotting adds to that
- * congestion. Measured rather than assumed: with tracing on, all three still
- * pass and the churn arm's own precondition still holds, so the extra load makes
- * that arm slower without making it invalid. The DECLARATIVE option cannot be
- * scoped below file level: `trace` is worker-scoped, so `test.use({ trace })`
- * inside a `test.describe` is rejected outright ("forces a new worker"). That
- * leaves file-wide or nothing among the config-driven shapes. Playwright's
- * manual `context.tracing.start/stop` API is test-scoped and would allow per-arm
- * tracing, at the cost of hand-wiring output paths and losing the HTML report's
- * automatic trace linkage; it was judged not worth that for three tests, not
- * ruled impossible. File-wide wins because
- * the alternative gives up the only rich artifact that survives the crash.
- *
- * This narrows `precedent #20(e)`'s "every CI failure is debuggable from
- * artifacts alone" here only in that a crash leaves no screenshot, which is a
- * property of dead renderers rather than of this override. #20(e) records the
- * carve-out this file establishes.
+ * Renderer-survival pin for the `.ok-chunk-wrapper` (`content-visibility: auto`) display-lock
+ * site the sibling test leaves unpinned: a click whose hit-tested node has a paint-blocked
+ * ancestor kills the renderer. Per-test docName isolation per precedent #20(a).
*/
import { randomUUID } from 'node:crypto';
diff --git a/packages/app/tests/stress/editor-area-viewport-resize.e2e.ts b/packages/app/tests/stress/editor-area-viewport-resize.e2e.ts
index 3044769a1..7ed831e8c 100644
--- a/packages/app/tests/stress/editor-area-viewport-resize.e2e.ts
+++ b/packages/app/tests/stress/editor-area-viewport-resize.e2e.ts
@@ -1,20 +1,7 @@
/**
- * editor-area-viewport-resize.e2e.ts — Editor mount stability across viewport resize.
- *
- * Pins the invariant: the editor mount substrate (EditorActivityPool → ActivityEntry →
- * TiptapEditor + V2 mount-promise + portalTarget) MUST survive viewport-driven layout
- * transitions for the active doc. The hybrid render tree (precedent #18(b)) was
- * designed for flash-free doc-switch transitions; this test extends the contract to
- * the right doc-panel collapse/expand transition at the 1024px threshold.
- *
- * The right doc-panel is a `react-resizable-panels` Panel that is a STABLE SIBLING of
- * the editor in one `ResizablePanelGroup` (precedent #18(b)): crossing the threshold
- * collapses/expands the panel's flex size; it must never unmount the editor subtree.
- * The editor + doc-panel are NOT swapped between distinct React tree positions, so
- * the portal-target DOM identity is stable across any number of collapse cycles.
- *
- * Per CLAUDE.md STOP rule: each test creates its own unique doc via api.seedDocs —
- * no hardcoded `'test-doc'`.
+ * Editor mount stability across viewport resize: the right doc-panel is a stable sibling of the
+ * editor in one `ResizablePanelGroup` (precedent #18(b)), so crossing the 1024px threshold
+ * collapses the panel's flex size and must never unmount the editor subtree.
*/
import type { Page } from '@playwright/test';
diff --git a/packages/app/tests/stress/fixtures/handoff-mocks.ts b/packages/app/tests/stress/fixtures/handoff-mocks.ts
index 63600cce6..5d1fa7bb9 100644
--- a/packages/app/tests/stress/fixtures/handoff-mocks.ts
+++ b/packages/app/tests/stress/fixtures/handoff-mocks.ts
@@ -1,45 +1,7 @@
-/**
- * Playwright fixture helpers for the `handoff.e2e.ts` matrix.
- *
- * Goal: drive the Open-in-Agent dispatch flow across 8 cells
- * without dependencies on what Claude / Codex / Cursor is actually installed
- * on the CI runner, and without triggering real cross-app URL dispatch.
- *
- * Two host modes:
- * - `host: 'electron'` — installs a mock `window.okDesktop` bridge via
- * `page.addInitScript`. Every shell method is a capturing stub. The
- * initial probe + on-open refresh both consult `shell.detectProtocol`
- * which reads from the injected mock state.
- * - `host: 'web'` — leaves `window.okDesktop` undefined so the app falls
- * through to the web path. `GET /api/installed-agents` is intercepted
- * via `page.route` and served from the injected mock state.
- *
- * Anchor-click capture (both hosts):
- * Handoff URL dispatch on web host uses a short-lived `<a href=... click>`
- * pattern. Without interception, Chromium
- * would either navigate away (for `https://claude.ai/...`) or hit a
- * protocol-handler dialog (for `claude://`, `codex://`, `cursor://`). This
- * file patches `HTMLAnchorElement.prototype.click` to capture clicks on
- * anchors whose href matches a known handoff scheme / host, record the
- * URL into `window.__handoffMocks__.anchorClicks`, and swallow the click.
- * All other anchor clicks (sidebar nav, install-affordance `<button>`s in
- * tooltips when dispatched via Electron) fall through unchanged.
- *
- * Time control:
- * The install-detect coordinator throttles `refresh()` to once per 10s per
- * scheme. For the install-state-flip cell the test must advance past the
- * throttle window without stalling the run for 10s wall-time. The init
- * script patches `Date.now` only (not `setTimeout` / `setInterval`) so
- * WebSocket heartbeats + sonner toast lifecycles keep running on real
- * time while the handoff hook's lastProbedAt check sees future-time on
- * `advanceHandoffFakeTime(ms)`.
- */
-
import type { Page } from '@playwright/test';
import type { OkDesktopBridge } from '@/lib/desktop-bridge-types';
export interface InstallMap {
- /** Single `claude:` scheme covers both Claude Cowork + Claude rows. */
readonly claude: boolean;
readonly codex: boolean;
readonly cursor: boolean;
@@ -48,11 +10,7 @@ export interface InstallMap {
export interface HandoffMockConfig {
readonly host: 'electron' | 'web';
readonly install: InstallMap;
- /** Worker's baseURL — passed so the mock bridge's `collabUrl` / `apiOrigin`
- * point at the real Vite+Hocuspocus instance for this worker. */
readonly workerBaseURL: string;
- /** Worker's content dir — passed so the mock bridge's `projectPath`
- * matches the on-disk content dir and `useWorkspace()` resolves cleanly. */
readonly workerContentDir: string;
}
@@ -68,23 +26,7 @@ export interface CapturedHandoff {
readonly recordHandoffCalls: ReadonlyArray<Record<string, unknown>>;
}
-/**
- * Install the handoff mock harness onto the page.
- *
- * Call BEFORE `page.goto(...)` — `page.addInitScript` takes effect on the
- * next document load, and `page.route` must be installed before the
- * `/api/installed-agents` fetch fires (which happens on app mount when
- * `useInstalledAgents` boots).
- */
export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): Promise<void> {
- // Intercept `/api/handoff` for both Electron and Web hosts — the unified
- // dispatch endpoint POSTed by `dispatch.ts`. Tests must intercept before
- // it reaches the worker server, which runs on a CI host where Claude /
- // Codex / Cursor likely aren't installed (and we'd be racing OS-level
- // app launches). Returns 200 unconditionally so the renderer's
- // `dispatchHandoff` resolves successfully; tests assert on the captured
- // body via `mocks.handoffApiCalls` (populated by the window.fetch
- // wrapper in the init script).
await page.route('**/api/handoff', async (route) => {
await route.fulfill({
status: 200,
@@ -92,9 +34,6 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
body: JSON.stringify({}),
});
});
- // Web-host install-detect path: intercept the HTTP probe before it hits
- // the real server. Route handlers persist for the page's lifetime; the
- // later `updateWebInstallMap` helper re-registers on top.
if (cfg.host === 'web') {
await page.route('**/api/installed-agents', async (route) => {
await route.fulfill({
@@ -103,18 +42,6 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
body: JSON.stringify(cfg.install),
});
});
- // Web-host install gate: defense-in-depth no-op for `POST /api/install-skill`.
- // The install-state mock below should already short-circuit at Step 1 of
- // the gate ladder in `cowork-skill-install.ts`, so this route is unreachable
- // in steady state. It exists to keep `~/.ok/skill-state.yml` clean if a
- // future refactor changes the gate's short-circuit semantics — preventing the real
- // `buildAndOpenSkill` build that pollutes the runner's home directory and
- // re-introduces the install-flake class. Body shape mirrors the canonical
- // `skip-current` response `httpSkillInstaller` parses (for the
- // `skip-current` branch, `status` drives control flow; `outputPath` and
- // `handoffError` are absent on real responses, so any extras here are
- // inert — but a `built` or `installed` status would also need
- // `outputPath`).
await page.route('**/api/install-skill', async (route) => {
await route.fulfill({
status: 200,
@@ -128,21 +55,6 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
});
}
- // Cowork install-gate short-circuit. `GET /api/skill/install-state` is
- // host-agnostic — both web and Electron renderers call it from `runEnsure`
- // in `cowork-skill-install.ts`; only Step 3's installer differs by host
- // (HTTP POST on web, IPC bridge on Electron). Returning a snapshot whose
- // `targets['claude-cowork'].version` equals `currentVersion` makes the
- // gate's verdict deterministic (`{ kind: 'already-installed',
- // source: 'server' }`), so the `claude-cowork` install-gate branch in
- // `runHandoffDispatch` falls through past the install-gate branch to the
- // URL-dispatch path. Snapshot body mirrors the wire format
- // `readSkillInstallStateSnapshot` emits in `api-extension.ts` (the source
- // schema is `SkillStateSchema` in `skill-state/schema.ts`, declared as a
- // `z.looseObject`, so additive server changes won't break this mock).
- // Sentinel version `'0.0.0-test-fixture'` satisfies the
- // `SKILL_STATE_VERSION_RE` semver shape so the snapshot is structurally
- // valid for any future stricter parser.
await page.route('**/api/skill/install-state', async (route) => {
await route.fulfill({
status: 200,
@@ -161,13 +73,9 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
});
});
- // Init script: runs before ANY page script on every document load.
- // Plants the capture object + anchor-click interceptor + (Electron only)
- // the window.okDesktop bridge.
await page.addInitScript((args) => {
const { host, install, workerBaseURL, workerContentDir } = args as HandoffMockConfig;
- // ---- Capture scaffold ----
interface HandoffApiCall {
target: string;
url: string;
@@ -181,8 +89,6 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
recordHandoffCalls: Record<string, unknown>[];
install: { claude: boolean; codex: boolean; cursor: boolean };
fakeTimeOffset: number;
- /** Web-host only: set once `/api/installed-agents` fetch resolves so
- * tests can poll for the probe having landed. */
installedAgentsFetchResolved: boolean;
}
const mocks: HandoffMocksState = {
@@ -198,20 +104,11 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
// biome-ignore lint/suspicious/noExplicitAny: test-only global attachment.
(window as any).__handoffMocks__ = mocks;
- // ---- Fetch instrumentation for probe-settled detection (web host) ----
- // The install-detect coordinator's `probeViaFetch` strategy calls
- // `fetch('/api/installed-agents')`. Wrap window.fetch so we set a flag
- // when the response resolves — tests poll this instead of racing the
- // React state update. No-op for Electron cells (detectProtocol is the
- // probe strategy there, captured via detectProtocolCalls directly).
const originalFetch = window.fetch.bind(window);
const wrappedFetch = async (
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> => {
- // Capture `/api/handoff` POST body before forwarding so tests can
- // assert on the dispatched target / URL / workspacePath. Fail-soft:
- // if reading init.body throws, fall through unchanged.
try {
const url =
typeof input === 'string'
@@ -235,14 +132,11 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
: {}),
});
} catch {
- // Body wasn't JSON — record empty placeholder.
mocks.handoffApiCalls.push({ target: '', url: '' });
}
}
}
- } catch {
- // Defensive — never let instrumentation corrupt the real fetch.
- }
+ } catch {}
const res = await originalFetch(input, init);
try {
const url =
@@ -254,17 +148,11 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
if (url.includes('/api/installed-agents')) {
mocks.installedAgentsFetchResolved = true;
}
- } catch {
- // Defensive — never let instrumentation corrupt the real fetch.
- }
+ } catch {}
return res;
};
- // Cast through unknown because Bun's globals.d.ts augments `typeof fetch`
- // with a `fetch.preconnect` namespace member that the wrapper doesn't
- // implement. Standard lib.dom.d.ts does not declare `preconnect`.
window.fetch = wrappedFetch as unknown as typeof window.fetch;
- // ---- Anchor-click interceptor (both hosts) ----
const HANDOFF_SCHEMES = new Set(['claude:', 'codex:', 'cursor:']);
const HANDOFF_HOSTS = new Set(['claude.ai']);
const originalAnchorClick = HTMLAnchorElement.prototype.click;
@@ -275,22 +163,13 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
mocks.anchorClicks.push(this.href);
return;
}
- } catch {
- // Invalid URL — fall through to real click.
- }
+ } catch {}
return originalAnchorClick.call(this);
};
- // ---- Date.now patching for throttle bypass (install-state-flip cell) ----
- // ONLY patch Date.now — NOT setTimeout / setInterval — so real wall-clock
- // timers (WebSocket heartbeats, sonner lifecycles, React scheduler) keep
- // running. The install-detect coordinator reads `deps.now` (bound to
- // Date.now); patching here lets us advance its view of time without
- // stalling the test for 10 real seconds.
const realDateNow = Date.now.bind(Date);
Date.now = () => realDateNow() + mocks.fakeTimeOffset;
- // ---- Electron-host bridge injection ----
if (host === 'electron') {
const shellStub = {
openExternal: async (url: string): Promise<void> => {
@@ -306,9 +185,6 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
? { installed: true, displayName: `${scheme.replace(':', '')}-mock` }
: { installed: false };
},
- // No-op stub — the unified `/api/handoff` design routes Cursor
- // through the HTTP endpoint, not this IPC channel. Required by the
- // `OkDesktopBridge` contract until the IPC surface is retired.
spawnCursor: async (): Promise<{ ok: true }> => ({ ok: true }),
recordHandoff: async (line: Record<string, unknown>): Promise<void> => {
mocks.recordHandoffCalls.push(line);
@@ -321,33 +197,11 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
}),
showAssetMenu: async (): Promise<void> => {},
showItemInFolder: async (): Promise<void> => {},
- // No-op stub — sidebar Delete flow isn't exercised by the handoff
- // stress fixtures, but the `OkDesktopBridge` contract requires every
- // shell.* method to be present for `satisfies OkDesktopBridge` to
- // typecheck.
trashItem: async (): Promise<{ ok: true }> => ({ ok: true }),
};
- // Typed with `satisfies OkDesktopBridge` so any drift between the
- // canonical contract (`packages/core/src/desktop-bridge.ts`) and this
- // fixture fails `pnpm run typecheck` instead of going silent.
- // `tests/stress/fixtures` is in `packages/app/tsconfig.json` `include`
- // for this reason. Imported types erase at runtime, so the
- // `addInitScript` callback's stringification is unaffected.
- //
- // Coverage limit: TypeScript function subtyping accepts shape-
- // compatible parameters silently, so signature-shape drift on
- // existing methods (e.g. a new required field on a request param)
- // passes here. The canonical core contract and the dedicated preload
- // forwarding tests cover the declaration and transport boundaries.
const bridge = {
config: {
- // Hocuspocus is mounted at /collab by the Vite plugin (the upgrade
- // handler in `hocuspocus-plugin.ts` filters on
- // `req.url.startsWith('/collab')`). Passing just `ws://host:port`
- // without the path makes the WebSocket upgrade request hit Vite's
- // HMR handler instead of Hocuspocus, and the provider never reports
- // synced.
collabUrl: `${workerBaseURL.replace(/^http/, 'ws')}/collab`,
apiOrigin: workerBaseURL,
projectPath: workerContentDir,
@@ -375,9 +229,6 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
onServerRestarted: () => () => {},
onRecentRemovedMissing: () => () => {},
restartServer: async () => ({ ok: true as const }),
- // Theme bridge is invoked on first ConfigProvider render via
- // useThemeBridge — must not throw or the ConfigProvider subtree
- // unmounts before NavigationHandler can call pool.setActive(docName).
setThemeSource: async (): Promise<{ ok: true }> => ({ ok: true }),
setLanguagePreference: async (): Promise<{ ok: true }> => ({ ok: true }),
signalThemeApplied: (): void => {},
@@ -399,10 +250,6 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
project: {
listRecent: async () => [],
removeRecent: async () => {},
- // Tab-session-restore effect in DocumentContext reads
- // getSessionState on first render; setSessionState fires on tab
- // mutations. Both must resolve cleanly or the editor tree never
- // installs the __activeProvider getter the e2e helper polls.
getSessionState: async () => ({
updatedAt: null,
panes: [
@@ -504,13 +351,6 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
checkNow: async () => {},
dismissWhatsNew: async () => {},
},
- // installUpdateNoticesBridge() at main.tsx module-init invokes
- // bridge.state.query() (the result is consumed via .then(...) in
- // the installUpdateNoticesBridge body in update-notices-store.ts).
- // The throw happens at property-access time, not in the awaited
- // body — accessing `query` on an undefined `bridge.state` raises
- // TypeError synchronously, halting module-init before createRoot
- // runs.
state: {
query: async () => ({
channel: 'latest' as const,
@@ -582,14 +422,6 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
remoteAccess: {
probePort: async () => true,
},
- // installConsentListener + installOnboardingToastListener are
- // wired unconditionally by main.tsx (both guarded internally by
- // `if (!b.onboarding) return`), so these stubs run at the
- // subscription-install layer even in editor-mode boot. All
- // onboarding + localOp members below are stubbed to keep the
- // satisfies clause structurally complete — the selective-field
- // minimum would pass typecheck but defeat its purpose as a
- // contract backstop.
onboarding: {
onShow: () => () => {},
signalReady: () => {},
@@ -622,10 +454,6 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
share: {
validateLocalFolder: async () => ({ kind: 'not-git' as const }),
},
- // Sidebar context-menu surfaces — no-op stubs. Stress fixtures
- // don't exercise File-menu state-aware rebuilds or View-menu
- // tree-state push, but the `OkDesktopBridge` contract requires
- // these surfaces for `satisfies OkDesktopBridge` to typecheck.
editor: {
notifyActiveTargetChanged: (): void => {},
notifyViewMenuStateChanged: (): void => {},
@@ -669,15 +497,12 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
rewireClaudeMcp: async () => ({ claude: 'present' as const, mcp: 'wired' as const }),
},
menu: {
- // The renderer menubar only mounts off-darwin; fixture is darwin.
dispatch: async () => undefined,
},
platform: 'darwin' as const,
appVersion: 'test-0.0.0',
instanceLabel: null,
getPathForFile: () => null,
- // Crash annotations have no meaning in a fixture; the reporter only
- // needs the method to exist so it attaches its observer at all.
setDisplayLockCrashKey: () => undefined,
} satisfies OkDesktopBridge;
@@ -685,43 +510,14 @@ export async function installHandoffMocks(page: Page, cfg: HandoffMockConfig): P
(window as any).okDesktop = bridge;
}
- // ---- Cowork skill install-guard seed (offline fallback) ----
- // The Open-in-Agent dropdown's `claude-cowork` row routes through a lazy
- // install gate (`ensureCoworkSkillInstalled` in `cowork-skill-install.ts`)
- // on first click per skill version. The 3-step gate ladder is:
- // 1. `GET /api/skill/install-state` — server check.
- // 2. `localStorage` lookup of `ok:skill:cowork:installed:v<version>`.
- // 3. Real install: `POST /api/install-skill` (web) or
- // `okDesktop.skill.buildAndOpen()` IPC (Electron). On the Electron
- // bridge stub above, `buildAndOpen` returns `build-failed` — gate
- // then returns `install-failed` and `runHandoffDispatch` early-
- // returns with an error toast (no URL dispatch).
- //
- // Once the server-check Step 1 was introduced, the gate's lookup key for
- // Step 2 uses `snapshot.currentVersion` from the server response — which
- // on the real server is `@inkeep/open-knowledge-server`'s package.json
- // version (e.g. `0.4.0-beta.6`), NOT the `'unknown'` literal this seed
- // writes. The load-bearing short-circuit is now the
- // `/api/skill/install-state` route mock above (returns a snapshot whose
- // recorded `claude-cowork` version equals `currentVersion`, so the gate
- // resolves at Step 1 with `'already-installed', source: 'server'`).
- //
- // This localStorage seed is retained as the offline fallback (Step 2)
- // for environments where the server is unreachable — it preserves the
- // legacy offline-only contract and keeps the unit-test parity with
- // `useHandoffDispatch.test.ts`. The install gate itself is covered by
- // unit tests, not this matrix.
try {
// biome-ignore lint/suspicious/noExplicitAny: matches production resolution in cowork-skill-install.ts.
const ver = (window as any).okDesktop?.appVersion ?? 'unknown';
window.localStorage.setItem(`ok:skill:cowork:installed:v${ver}`, '1');
- } catch {
- // localStorage unavailable (sandboxed) — gate falls through harmlessly.
- }
+ } catch {}
}, cfg);
}
-/** Read all captured calls. */
export async function readCapturedHandoff(page: Page): Promise<CapturedHandoff> {
return await page.evaluate(() => {
// biome-ignore lint/suspicious/noExplicitAny: test-only global attachment.
@@ -742,12 +538,6 @@ export async function readCapturedHandoff(page: Page): Promise<CapturedHandoff>
});
}
-/**
- * Swap the Electron-host install map mid-test. After calling, the next
- * `shell.detectProtocol(scheme)` returns the new value. Pair with
- * `advanceHandoffFakeTime(11_000)` to bypass the 10s throttle so the
- * next `refresh()` actually probes.
- */
export async function updateElectronInstallMap(page: Page, install: InstallMap): Promise<void> {
await page.evaluate((next) => {
// biome-ignore lint/suspicious/noExplicitAny: test-only global attachment.
@@ -756,11 +546,6 @@ export async function updateElectronInstallMap(page: Page, install: InstallMap):
}, install);
}
-/**
- * Swap the web-host install response. Re-registers the page.route handler
- * so subsequent GET /api/installed-agents fetches see the new value.
- * Pair with `advanceHandoffFakeTime(11_000)` as above.
- */
export async function updateWebInstallMap(page: Page, install: InstallMap): Promise<void> {
await page.unroute('**/api/installed-agents');
await page.route('**/api/installed-agents', async (route) => {
@@ -772,11 +557,6 @@ export async function updateWebInstallMap(page: Page, install: InstallMap): Prom
});
}
-/**
- * Advance the page's `Date.now()` view by `ms` milliseconds. Only affects
- * `Date.now` (the install-detect coordinator's throttle check reads this).
- * Real `setTimeout` / `setInterval` fire on wall-clock time.
- */
export async function advanceHandoffFakeTime(page: Page, ms: number): Promise<void> {
await page.evaluate((delta) => {
// biome-ignore lint/suspicious/noExplicitAny: test-only global attachment.
diff --git a/packages/app/tests/stress/jsx-wildcard-convert.e2e.ts b/packages/app/tests/stress/jsx-wildcard-convert.e2e.ts
index 867496d56..76492f61f 100644
--- a/packages/app/tests/stress/jsx-wildcard-convert.e2e.ts
+++ b/packages/app/tests/stress/jsx-wildcard-convert.e2e.ts
@@ -1,38 +1,7 @@
/**
- * Playwright regression pin for the wildcard + render-error
- * auto-convert path in `JsxComponentView`.
- *
- * Bug class this guards against:
- * `JsxComponentView` registers an effect that schedules a
- * `requestAnimationFrame` to replace an unregistered `jsxComponent` with
- * a `rawMdxFallback` (Precedent #30 — "all user content visible and
- * editable; if a component render fails, the NodeView swaps to a nested
- * CM"). The effect uses a `convertedRef` one-shot guard. Flipping that
- * ref BEFORE the rAF fires is StrictMode-unsafe: the intentional
- * unmount-remount cycle's cleanup cancels the rAF, the ref stays flipped
- * across remount (refs persist by fiber identity), the remount's effect
- * early-returns, and no dispatch ever lands. Symptom: unregistered
- * components render stuck forever on the
- * "Unknown: `<ComponentName>` — opening source editor..." placeholder.
- * Production is unaffected (no StrictMode double-invoke); dev, CI, and
- * any future component-testing tier all hit the bug.
- *
- * This scenario exercises the path end-to-end in a real browser:
- * - Seed a doc containing an unregistered `<UnknownWidget>` MDX element.
- * - Open the doc; wait for sync.
- * - Poll until PM state has a `rawMdxFallback` whose reason names
- * "UnknownWidget" AND there is no residual `jsxComponent` with
- * componentName "UnknownWidget".
- *
- * Perturbation: reverting the post-dispatch `convertedRef.current = true`
- * flip — i.e., restoring the pre-dispatch flip — fails
- * this test deterministically. The poll times out because the remount's
- * effect early-returns and the conversion never lands.
- *
- * Intentionally NOT testing implementation details (convertedRef's value,
- * rAF scheduling, StrictMode-specific double-invoke behavior). The
- * assertion is on observable PM state — the node type the user sees and
- * any downstream code consumes.
+ * Playwright pin for `JsxComponentView`'s wildcard and render-error auto-convert into a
+ * `rawMdxFallback` (precedent #30, all user content visible and editable). Flipping the one-shot
+ * ref before the rAF fires is StrictMode-unsafe and leaves the placeholder stuck forever.
*/
import { randomUUID } from 'node:crypto';
diff --git a/packages/app/tests/stress/paste-fidelity.e2e.ts b/packages/app/tests/stress/paste-fidelity.e2e.ts
index 6b07a6b4d..a10f1bffb 100644
--- a/packages/app/tests/stress/paste-fidelity.e2e.ts
+++ b/packages/app/tests/stress/paste-fidelity.e2e.ts
@@ -409,10 +409,9 @@ test.describe('WYSIWYG FR-specific paste behavior', () => {
});
/**
- * Paste a payload at the Source editor's (CodeMirror) DOM. The chunked
- * Y.Text insertion path (`chunkedYTextInsert`) is invoked exclusively by
- * the Source dispatcher (per precedent #19), so
- * the frame-timing test must target `.cm-content`, not `.ProseMirror`.
+ * The chunked Y.Text insertion path (`chunkedYTextInsert`) is invoked exclusively by the Source
+ * dispatcher (per precedent #19), so the frame-timing test must target `.cm-content`, not
+ * `.ProseMirror`.
*/
async function pasteHtmlInSource(page: Page, html: string, plain: string) {
await page.evaluate(
diff --git a/packages/app/tests/stress/qa-canary-authoring-both-modes.e2e.ts b/packages/app/tests/stress/qa-canary-authoring-both-modes.e2e.ts
index d5063bc96..b0d390c8a 100644
--- a/packages/app/tests/stress/qa-canary-authoring-both-modes.e2e.ts
+++ b/packages/app/tests/stress/qa-canary-authoring-both-modes.e2e.ts
@@ -1,23 +1,6 @@
-/** QA canary — authoring nested <Steps> across BOTH editor modes, from scratch,
- * keystroke by keystroke through the transient-invalid states.
- *
- * As-built model: <Steps>/<Step> are unregistered (componentMap) -> they render
- * via the wildcard editable raw-source view even when VALID. There is no client
- * "freeze": server parseWithFallback never throws, so an invalid span renders as
- * rawMdxFallback (client cross-CRDT write paths are deleted, precedent #14).
- * Transient state = rawMdxFallback, NOT a freeze.
- *
- * Covers all three real typing surfaces: source CM, WYSIWYG ProseMirror (prose
- * around Steps), WYSIWYG wildcard CM (the Step itself), plus a mode-flip mid-build.
- * Includes a JITTER probe: typing in clean prose must not flash the Steps render.
- *
- * ORACLE NOTE: CM source-mode auto-indents JSX tags on Enter while authoring. The
- * indented shape is a stable, lossless serialize fixed point, and the bridge never
- * GLOBALLY re-indents. Assertions therefore check STRUCTURE + CONTENT INTEGRITY,
- * never flush-left tags, for authored-from-scratch content; SEEDED Steps guard the
- * OUTER container against the global re-indent write-back (a contended drain may
- * re-emit the INNER tags at the canonical nested indentation — a lossless fixed
- * point, not the corruption class; see the T2/T3 oracle notes).
+/**
+ * There is no client "freeze": server parseWithFallback never throws, so an invalid span renders as
+ * rawMdxFallback (client cross-CRDT write paths are deleted, precedent #14).
*/
import { randomUUID } from 'node:crypto';
diff --git a/packages/app/tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts b/packages/app/tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts
index a40c964c4..c58e4dfff 100644
--- a/packages/app/tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts
+++ b/packages/app/tests/stress/raw-mdx-fallback-onblur-upgrade.e2e.ts
@@ -1,39 +1,7 @@
/**
- * Layer C (Tier 2): on-blur upgrade of `rawMdxFallback` → parsed node when
- * the user fixes broken MDX in the nested CodeMirror.
- *
- * Context — prior art and scope:
- *
- * Surveyed editors (Obsidian Live Preview, SilverBullet,
- * codemirror-rich-markdoc, HedgeDoc, Typora, MDXEditor, Notion, BlockNote)
- * do not have a first-class parse-error-fallback → edit-source-live →
- * auto-upgrade-when-valid flow. Closest analog: Obsidian's S3
- * live-preview pattern uses a cursor-overlap guard — cursor inside
- * widget-region = reveal source; cursor outside = render widget. Our
- * architecture collapses Obsidian's "cursor exits widget" to "nested CM
- * loses focus" because the nested CM IS the source reveal.
- *
- * Trigger: CM `focusChanged` + `!view.hasFocus` (browser blur on the
- * nested CM). Handler reads the current CM source, runs it through the
- * same parse pipeline the outer editor uses, and if the result is a
- * single non-fallback block, dispatches a PM transaction replacing the
- * `rawMdxFallback` with the parsed node.
- *
- * Two tests:
- *
- * S21 — happy path upgrade. Seed broken tag (`<Foo>text</Bar>` →
- * rawMdxFallback at mount). Focus nested CM. Replace source with
- * valid MDX for a REGISTERED component (`<Callout …>`). Blur CM.
- * Assert: PM has a `jsxComponent` with componentName "Callout",
- * no residual `rawMdxFallback` at that position.
- *
- * S22 — still-invalid no-churn. Seed broken tag. Focus nested CM. Type
- * a character (still broken). Blur CM. Assert: PM still has
- * `rawMdxFallback` — the node is NOT replaced with another
- * rawMdxFallback (which would churn Y.XmlElement identity,
- * break y-prosemirror Item mapping, and cascade to observers per
- * Precedent #10). On-blur only commits when the re-parse
- * produces a genuinely better node.
+ * Assert: PM still has `rawMdxFallback` — the node is NOT replaced with another rawMdxFallback
+ * (which would churn Y.XmlElement identity, break y-prosemirror Item mapping, and cascade to
+ * observers per Precedent #10).
*/
import { randomUUID } from 'node:crypto';
diff --git a/packages/app/tests/visual/component-parity.e2e.ts b/packages/app/tests/visual/component-parity.e2e.ts
index abf957d89..3c116db2e 100644
--- a/packages/app/tests/visual/component-parity.e2e.ts
+++ b/packages/app/tests/visual/component-parity.e2e.ts
@@ -1,29 +1,7 @@
/**
- * Visual regression suite — 5-pack foundation parity.
- *
- * Captures screenshots of each 5-pack component rendered in the editor and
- * compares against golden baselines. Tolerance: ≤1% pixel delta (accommodates
- * anti-aliasing/subpixel). Covers {light, dark} themes and {selected, unselected}
- * states per the renamed 5-pack VR block set.
- *
- * Coverage:
- * VR01 — Callout across all 5 GFM types (× light/dark) + foldable variant
- * VR-IMAGE — Image with always-on zoom (no caption)
- * VR-VIDEO — Video with poster + HTML5 controls
- * VR-AUDIO — Audio with native chrome
- * VR-ACCORDION — Accordion expanded + collapsed + exclusive grouping (name attr)
- * VR17 — mixed 5-pack document
- * VR18 — wildcard unregistered component
- *
- *
- * Baseline management:
- * - packages/app/tests/visual/component-parity.e2e.ts-snapshots/ stores approved baselines
- * - First run creates baselines; subsequent runs diff
- * - Golden-file updates require explicit: pnpm --dir packages/app run test:visual:update
- * - Cannot silently regenerate in CI
- *
- * Isolation: per-worker fixture + per-test UUID docName — no hardcoded
- * 'test-doc' (precedent #20(a)).
+ * Visual regression suite for the 5-pack foundation, diffing each component against an approved
+ * baseline at a 1% pixel tolerance across light and dark themes and selected and unselected
+ * states. Per-worker fixture and per-test UUID docName, no hardcoded name (precedent #20(a)).
*/
import { randomUUID } from 'node:crypto';
diff --git a/packages/cli/scripts/build-config-schema.mjs b/packages/cli/scripts/build-config-schema.mjs
index 1cb74e756..286726bd0 100644
--- a/packages/cli/scripts/build-config-schema.mjs
+++ b/packages/cli/scripts/build-config-schema.mjs
@@ -1,49 +1,4 @@
#!/usr/bin/env node
-/**
- * Emit per-scope JSON Schemas from `ConfigSchema` for IDE intellisense.
- *
- * Schema versioning is **independent** of the npm package version. The
- * artifact directory is `dist/schemas/v<CONFIG_SCHEMA_MAJOR>/…`; the magic
- * comment URL pins to `@latest` of the package + the schema-major path. As
- * a result, additive changes (new optional fields, new enum values) reach
- * existing users automatically — their YAML's `$schema=…/v0/…` URL stays
- * valid, and unpkg's `@latest` redirect surfaces the newest schema. A
- * schema-major bump (v0 → v1) is reserved for breaking changes and emits
- * to a new directory; the old directory keeps shipping for legacy YAMLs.
- *
- * Files emitted (per major):
- * - `dist/schemas/v<N>/config.project.schema.json` — project-valid
- * fields (scope: 'project' or 'either')
- * - `dist/schemas/v<N>/config.user.schema.json` — user-valid fields
- * (scope: 'user' or 'either')
- * - `dist/schemas/v<N>/config.project-local.schema.json` — project-local
- * fields (scope: 'project-local' or 'either'); IDE autocomplete inside
- * `<projectDir>/.ok/local/config.yml` only surfaces these.
- *
- * Also emitted at the dist root (back-compat aliases for pre-versioning
- * magic comments still in the wild):
- * - `dist/config-schema.json` — full schema, every field
- * - `dist/config.project.schema.json` — same as v<current>/project
- * - `dist/config.user.schema.json` — same as v<current>/user
- * - `dist/config.project-local.schema.json` — same as v<current>/project-local
- *
- * `ok init`'s scaffolded project `config.yml` magic-comment points at the
- * versioned project schema; `writeConfigPatch`'s lazy first-write of
- * `~/.ok/global.yml` points at the versioned user schema.
- * Each file's autocomplete then surfaces only the fields that are valid
- * AT that scope — an `appearance.theme` typed in project YAML squiggles,
- * a `content.dir` typed in user YAML squiggles.
- *
- * `io: 'input'` (not `'output'`) is load-bearing: the IDE must show the user
- * what they TYPE (every defaulted field optional), not what the runtime
- * resolves (every defaulted field required). The CI test in
- * `src/config/json-schema-equivalence.test.ts` guards this contract.
- *
- * `metadata: fieldRegistry` flows the per-field `scope` / `agentSettable` /
- * `defaultScope` annotations into the JSON Schema as custom keys. JSON
- * Schema draft-07 ignores unknown keywords; the keys ride along for any
- * future consumer that wants to introspect them.
- */
import { mkdirSync, writeFileSync } from 'node:fs';
import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
@@ -63,29 +18,13 @@ const fullSchema = z.toJSONSchema(ConfigSchema, {
mkdirSync(distDir, { recursive: true });
mkdirSync(versionedDir, { recursive: true });
-/**
- * Recursively prune properties that don't apply at `targetScope`.
- *
- * - A leaf with no `scope` keyword → kept (nothing to filter).
- * - A leaf with `scope: 'either'` → kept everywhere.
- * - A leaf with `scope: 'user'` → kept only in the user schema.
- * - A leaf with `scope: 'project'` → kept only in the project schema.
- * - A leaf with `scope: 'project-local'` → kept only in the project-local schema.
- * - An object with `properties` is walked; if EVERY child property is
- * pruned, the parent object itself is pruned (no dangling empty
- * sections in the IDE autocomplete).
- *
- * Defaults are preserved as-is — JSON Schema's `default` keyword lets the
- * IDE show the runtime default when hovering, even though the field is
- * optional in the input view.
- */
function pruneByScope(node, targetScope) {
if (node === null || typeof node !== 'object') return node;
if (Array.isArray(node)) return node.map((item) => pruneByScope(item, targetScope));
const leafScope = node.scope;
if (leafScope !== undefined && leafScope !== 'either' && leafScope !== targetScope) {
- return undefined; // signals to caller to drop this property
+ return undefined;
}
const out = { ...node };
@@ -100,8 +39,6 @@ function pruneByScope(node, targetScope) {
}
}
if (kept === 0 && leafScope === undefined) {
- // No descendants survived; drop the object itself unless it has its
- // own `scope` registered (which we'd already have honored above).
return undefined;
}
out.properties = newProps;
@@ -122,16 +59,10 @@ const projectSchema = pruneByScope(fullSchema, 'project');
const userSchema = pruneByScope(fullSchema, 'user');
const projectLocalSchema = pruneByScope(fullSchema, 'project-local');
-// Versioned (canonical) — the URLs `ok init` and `writeConfigPatch`
-// scaffold point here. Bump CONFIG_SCHEMA_MAJOR + emit to a new dir
-// for breaking changes; keep emitting old majors forever.
writeSchema(resolve(versionedDir, 'config.project.schema.json'), projectSchema);
writeSchema(resolve(versionedDir, 'config.user.schema.json'), userSchema);
writeSchema(resolve(versionedDir, 'config.project-local.schema.json'), projectLocalSchema);
-// Back-compat aliases at dist root — pre-versioning magic comments
-// point here. Removing these would break existing `~/.ok/
-// config.yml` files that never re-pinned to a versioned URL.
writeSchema(resolve(distDir, 'config-schema.json'), fullSchema);
writeSchema(resolve(distDir, 'config.project.schema.json'), projectSchema);
writeSchema(resolve(distDir, 'config.user.schema.json'), userSchema);
diff --git a/packages/cli/src/commands/start.ts b/packages/cli/src/commands/start.ts
index 8c2eb71b0..73aa71c4c 100644
--- a/packages/cli/src/commands/start.ts
+++ b/packages/cli/src/commands/start.ts
@@ -880,22 +880,8 @@ interface ResolveServerReuseDeps {
}
/**
- * Spawn-or-reuse resolution: a second `ok start` that lost the server.lock
- * acquisition reads the live holder's advertisement and reports it instead of
- * failing. Returns the holder's browser-facing URL, or `null` when the lock
- * can't be resolved to a usable address (caller falls back to the error path).
- *
- * Polls through the pre-listen window (`port: 0` sentinel) so racing a
- * predecessor that is still binding reports its real address rather than
- * failing on the sentinel. URL preference order:
- *
- * 1. lock v2 `url` when the holder advertises the `ui` capability — the
- * canonical one-URL contract (the same record Desktop attaches through);
- * 2. the server's own `url`/port — API+MCP only (a `--only server` boot), but
- * still the right address.
- *
- * All time + IO deps injected (precedent #13b) so tests drive every branch
- * with a virtual clock and no filesystem.
+ * All time + IO deps injected (precedent #13b) so tests drive every branch with a virtual clock and
+ * no filesystem.
*/
export async function resolveServerReuse(
deps: ResolveServerReuseDeps,
diff --git a/packages/core/src/checkpoint-kinds.ts b/packages/core/src/checkpoint-kinds.ts
index 3b884c7f1..c422c462f 100644
--- a/packages/core/src/checkpoint-kinds.ts
+++ b/packages/core/src/checkpoint-kinds.ts
@@ -273,12 +273,8 @@ export function parseCheckpoint(body: string): ParsedCheckpoint | null {
}
/**
- * Format the `ok-checkpoint-v1:` body line for a given kind+metadata. Produces
- * exactly one line (no trailing newline). Consumers embed it inside a full
- * commit message body as a sibling to `ok-contributors:` lines.
- *
- * Exported so `saveInMemoryCheckpoint` in the server package can share this
- * serialization rule with the parser — see precedent #4 (shared computation).
+ * Exported so `saveInMemoryCheckpoint` in the server package can share this serialization rule with
+ * the parser — see precedent #4 (shared computation).
*/
export function formatCheckpointBodyLine(parsed: ParsedCheckpoint): string {
const payload: {
diff --git a/packages/core/src/extensions/code-mark-fidelity.ts b/packages/core/src/extensions/code-mark-fidelity.ts
index 109e41b28..eee2a2b52 100644
--- a/packages/core/src/extensions/code-mark-fidelity.ts
+++ b/packages/core/src/extensions/code-mark-fidelity.ts
@@ -1,23 +1,4 @@
-/**
- * Code mark override for source-text fidelity.
- *
- * Extends @tiptap/extension-code (preserving setCode/toggleCode/unsetCode
- * commands, Cmd+E shortcut, and input rules) and removes `excludes: '_'`
- * so the Code mark can coexist with other inline marks (emphasis, strong).
- *
- * Why:
- * The upstream Code mark declares `excludes: '_'` which prevents ANY other
- * mark from sharing a span with code. CommonMark explicitly allows
- * emphasis/strong to wrap inline-code spans (e.g. `*a \`*\`*`). With the
- * exclusion in place, mdast → PM drops the emphasis mark from the inlineCode
- * span; PM → mdast then can't recover the original coverage and emits
- * siblings instead of a wrapped structure, breaking idempotence.
- *
- * Schema widening per precedent #9 (add-only forever — widening is allowed,
- * narrowing is not). Editor render: italic/bold-within-inline-code now
- * possible. Visual rendering follows browser default `<em><code>` /
- * `<strong><code>` styling — no NodeView changes required for correctness.
- */
+/** Schema widening per precedent #9 (add-only forever — widening is allowed, narrowing is not). */
import Code from '@tiptap/extension-code';
diff --git a/packages/core/src/extensions/jsx-component.ts b/packages/core/src/extensions/jsx-component.ts
index f03cc9da8..b15a5186a 100644
--- a/packages/core/src/extensions/jsx-component.ts
+++ b/packages/core/src/extensions/jsx-component.ts
@@ -9,27 +9,9 @@ declare module '@tiptap/core' {
}
/**
- * jsxComponent — block-level PM node for MDX JSX flow elements.
- *
- * atom: false, content: 'block*', isolating: true, defining: true
- *
- * Children are recursively-walked mdast children from mdxJsxFlowElement.
- * Descriptor dispatch at render time determines the NodeView branch
- * (registered → live React; wildcard and render error both auto-convert to
- * the rawMdxFallback nested CodeMirror source editor — Precedent #28/#30).
- *
- * Attrs:
- * - componentName: the JSX tag name (e.g., 'Callout', 'Accordion')
- * - kind: 'element' | 'expression' — discriminates JSX elements from {expression} blocks
- * - attributes: preserved mdast MdxJsxAttribute[] for serialize reconstruct
- * - sourceRaw: byte-exact source from parse (pristine serialization path)
- * — for `kind:'expression'` the wrapped expression bytes, for `kind:'element'`
- * the full `<Component …>…</Component>` source used by the pristine path.
- * - sourceDirty: pattern flag — false = pristine (serialize via sourceRaw),
- * true = edited (serialize via reconstruction)
- * - props: structured props destructured from MdxJsxAttribute[] via descriptor.props
- *
- * See Precedent #9 (schema add-only), Precedent #10.
+ * Block-level PM node for MDX JSX flow elements. Descriptor dispatch at render time picks the
+ * NodeView branch: registered renders live React, wildcard and render errors auto-convert to the
+ * `rawMdxFallback` source editor (precedent #28 / #30). Attrs are add-only per precedent #9.
*/
export const JsxComponent = Node.create({
name: 'jsxComponent',
diff --git a/packages/core/src/extensions/jsx-inline.ts b/packages/core/src/extensions/jsx-inline.ts
index 923236a98..9047d6511 100644
--- a/packages/core/src/extensions/jsx-inline.ts
+++ b/packages/core/src/extensions/jsx-inline.ts
@@ -2,26 +2,8 @@ import { Node } from '@tiptap/core';
import { renderInlineObjectText } from './input-rule-text.ts';
/**
- * jsxInline — inline PM node for MDX inline JSX (`mdxJsxTextElement`).
- *
- * Two rendering paths sit behind one node type:
- * 1. Attrs-populated (registered inline descriptor) — `componentName` set,
- * `props` destructured. NodeView dispatches to the descriptor's React
- * component atomically (contentEditable={false}); source characters are
- * hidden. Paired bodies land as `props.children`. Analogous to
- * jsxComponent but at inline flow.
- * 2. Zero-attrs (legacy thin shape) — `componentName === ''` and the text
- * children carry raw source. WYSIWYG renders as visible source text
- * (source-text default for unregistered tags).
- *
- * `content: 'text*'` per Precedent #10 preserves Y.Item identity on
- * per-keystroke text mutation (thin-shape path uses children for the raw
- * JSX source).
- *
- * Attrs mirror jsxComponent's (componentName / kind / attributes / sourceRaw
- * / sourceDirty / props) so NodeViews and serialization handlers can share
- * utilities. `kind` is always `'element'` today; the field is present for
- * shape parity with jsxComponent (which carries `'element' | 'expression'`).
+ * `content: 'text*'` per Precedent #10 preserves Y.Item identity on per-keystroke text mutation
+ * (thin-shape path uses children for the raw JSX source).
*/
export const JsxInline = Node.create({
name: 'jsxInline',
diff --git a/packages/core/src/extensions/list-boundary-merge.ts b/packages/core/src/extensions/list-boundary-merge.ts
index ad9e81899..a762268cf 100644
--- a/packages/core/src/extensions/list-boundary-merge.ts
+++ b/packages/core/src/extensions/list-boundary-merge.ts
@@ -1,36 +1,7 @@
/**
- * Nested list-item boundary merges for Backspace/Delete.
- *
- * StarterKit's ListKeymap sub-extension drives GFM-correct Backspace/Delete
- * in lists (see shared.ts's `listKeymap` wiring), but two of its branches
- * misfire at NESTED item boundaries — schema-independently, by upstream
- * design (@tiptap/extension-list, keymap handleBackspace/handleDelete):
- *
- * - Backspace at the start of item B whose PREVIOUS sibling item A has a
- * nested sublist: the `previousListItemHasSubList` check skips
- * joinItemBackward and falls through to `liftListItem` — the fallthrough
- * meant for the FIRST item in a list — lifting B clean out into a bare
- * paragraph with no bullet/checkbox (issue #609's orphan rows).
- * - Delete at the end of a NESTED item when the next item sits SHALLOWER:
- * the `nextListIsHigher` branch runs `joinForward().joinBackward()`,
- * re-nesting the next item at the wrong depth and silently dropping its
- * `checked` attr (`- [ ] d` becomes ` - d`).
- *
- * This extension preempts EXACTLY those two configurations (all four key
- * bindings ListKeymap holds: Backspace/Delete and their Mod- variants) with
- * prosemirror-commands' joinTextblockBackward/joinTextblockForward, which
- * descend through container nodes to the adjacent textblocks and merge only
- * those — never re-parenting, never dropping the surviving item's attrs.
- * Every other configuration returns false so ListKeymap's good branches
- * (flat joins, first-item lift, undoInputRule, trailing-paragraph rejoin,
- * empty-nested-item removal) keep running unchanged.
- *
- * Registration order is load-bearing: this extension sits AFTER StarterKit
- * in sharedExtensions at the DEFAULT priority. At equal priority the
- * later-registered extension's key handler runs first, which is the whole
- * delivery mechanism — no priority escalation, so suggestion-layer plugins
- * (slash command, tag/wiki-link at the 200 band, precedent #48) keep their
- * Enter/Tab precedence untouched.
+ * At equal priority the later-registered extension's key handler runs first, which is the whole
+ * delivery mechanism — no priority escalation, so suggestion-layer plugins (slash command,
+ * tag/wiki-link at the 200 band, precedent #48) keep their Enter/Tab precedence untouched.
*/
import { Extension } from '@tiptap/core';
diff --git a/packages/core/src/extensions/underline-fidelity.ts b/packages/core/src/extensions/underline-fidelity.ts
index 48af5a0d7..47ee0edf6 100644
--- a/packages/core/src/extensions/underline-fidelity.ts
+++ b/packages/core/src/extensions/underline-fidelity.ts
@@ -1,31 +1,4 @@
-/**
- * Underline mark override for source-text fidelity.
- *
- * Extends @tiptap/extension-underline (preserving setUnderline/toggleUnderline/
- * unsetUnderline commands and the Mod-U shortcut) with a source-form attribute:
- *
- * - sourceForm: `'u'` or `'ins'` as authored. Markdown has no native
- * underline construct, so the construct-canonical emission IS raw inline
- * HTML. Two spellings are accepted on the way in — `<u>` (what Typora,
- * MarkText and Obsidian write, and what this mark renders as) and `<ins>`
- * (what Joplin and Logseq write, and the only one GitHub's sanitizer
- * keeps) — and each re-emits the spelling it arrived as, so an imported
- * file round-trips byte-identically instead of being rewritten under the
- * author.
- *
- * `Mod-U` and the bubble menu produce the default `'u'`.
- *
- * Registered in place of StarterKit's bundled Underline (disabled there), the
- * same way Bold/Italic/Strike/Code are replaced by their fidelity variants.
- * Upstream's `renderMarkdown` (`++text++`) is inert here: markdown
- * serialization runs through the unified pipeline
- * (packages/core/src/markdown/), never TipTap's own markdown layer.
- *
- * No `excludes` field: underline must share a span with strong / emphasis /
- * code, and the schema default (self-exclusion only) already allows that.
- * Narrowing it would violate precedent #9 the same way the Code widening
- * documents.
- */
+/** Narrowing it would violate precedent #9 the same way the Code widening documents. */
import Underline from '@tiptap/extension-underline';
diff --git a/packages/core/src/extensions/wiki-link-embed.test.ts b/packages/core/src/extensions/wiki-link-embed.test.ts
index cbd09af75..438bb5b8f 100644
--- a/packages/core/src/extensions/wiki-link-embed.test.ts
+++ b/packages/core/src/extensions/wiki-link-embed.test.ts
@@ -1,25 +1,7 @@
/**
- * WikiLinkEmbed TipTap Node — renderHTML / parseHTML coverage.
- *
- * The clipboard-round-trip is the load-bearing invariant: a user copies
- * the rendered embed from one doc (DOM `<img data-wiki-embed ...>` or
- * `<a data-wiki-embed ...>`) and pastes it into another. Without
- * parseHTML matching both tag shapes at `priority: 100`, standard Image
- * / Link extensions (priority 50) would claim the node first, the
- * `sourceForm='wikiembed'` marker would be lost, and the next save
- * would serialize as plain markdown `![](...)` / `[](...)` instead of
- * `![[...]]`.
- *
- * Tests also guard the schema-add-only invariant (precedent #9): if a
- * future change narrows the parseHTML matchers or drops an attr,
- * round-trip regresses silently for every existing embed in every
- * vault. A dedicated unit test fails loud.
- *
- * Approach: introspect the PM schema that getSchema(sharedExtensions)
- * builds. `nodeType.spec.toDOM` is the compiled renderHTML (returns a
- * DOMOutputSpec tuple); `nodeType.spec.parseDOM` is the compiled
- * parseHTML (array of tag-matcher rules with getAttrs). Avoids
- * requiring a DOM runtime (Bun's test env has no `window`).
+ * Tests also guard the schema-add-only invariant (precedent #9): if a future change narrows the
+ * parseHTML matchers or drops an attr, round-trip regresses silently for every existing embed in
+ * every vault.
*/
import { getSchema } from '@tiptap/core';
diff --git a/packages/core/src/handoff/claude-url.test.ts b/packages/core/src/handoff/claude-url.test.ts
index 2be4c036c..fd5418220 100644
--- a/packages/core/src/handoff/claude-url.test.ts
+++ b/packages/core/src/handoff/claude-url.test.ts
@@ -34,11 +34,11 @@ test('buildClaudeUrl single-encodes literal % in projectDir (cowork)', () => {
}),
);
expect(url).toContain('folder=%2FUsers%2Fwho%2FMy%20%25Project');
- // precedent #25 invariant: never threads file content / docPath bytes.
+ // precedent #60 invariant: never threads file content / docPath bytes.
expect(url).not.toContain('file=');
});
-test('buildClaudeUrl precedent #25: docPath bytes never leak into URL (em-dash, code)', () => {
+test('buildClaudeUrl precedent #60: docPath bytes never leak into URL (em-dash, code)', () => {
const url = buildClaudeUrl(
{ mode: 'code' },
payload({
@@ -51,7 +51,7 @@ test('buildClaudeUrl precedent #25: docPath bytes never leak into URL (em-dash,
expect(url).not.toContain('%E2%80%94');
});
-test('buildClaudeUrl precedent #25: docPath bytes never leak into URL (unicode, cowork)', () => {
+test('buildClaudeUrl precedent #60: docPath bytes never leak into URL (unicode, cowork)', () => {
const url = buildClaudeUrl(
{ mode: 'cowork' },
payload({ docPath: '/Users/who/proj/café-notes.md', prompt: 'simple prompt' }),
@@ -87,7 +87,7 @@ test('buildClaudeUrl single-encodes literal & in projectDir (cowork) — DC8.5',
expect(url.split('&').length - 1).toBe(1);
});
-test('buildClaudeUrl precedent #25: docPath bytes never leak into URL (# in docPath, code) — DC8.5', () => {
+test('buildClaudeUrl precedent #60: docPath bytes never leak into URL (# in docPath, code) — DC8.5', () => {
const url = buildClaudeUrl(
{ mode: 'code' },
payload({
@@ -143,7 +143,7 @@ test('buildClaudeUrl project-scoped (composeEmptySpacePrompt + empty docPath) em
expect(url).not.toContain('file=');
});
-test('INVARIANT: buildClaudeUrl threads prompt through ALL scopes; precedent #25 = no file=', () => {
+test('INVARIANT: buildClaudeUrl threads prompt through ALL scopes; precedent #60 = no file=', () => {
const cases: ReadonlyArray<{
projectDir: string;
docPath: string;
@@ -180,7 +180,7 @@ test('INVARIANT: buildClaudeUrl threads prompt through ALL scopes; precedent #25
{ mode },
{ target, projectDir: c.projectDir, docPath: c.docPath, prompt: c.prompt },
);
- // precedent #25 invariant — no native file-attach.
+ // precedent #60 invariant — no native file-attach.
expect(url).not.toContain('file=');
expect(url).toContain('q=');
expect(url).toContain('folder=');
diff --git a/packages/core/src/handoff/claude-url.ts b/packages/core/src/handoff/claude-url.ts
index fba841028..20ccadfb6 100644
--- a/packages/core/src/handoff/claude-url.ts
+++ b/packages/core/src/handoff/claude-url.ts
@@ -1,28 +1,9 @@
import type { HandoffPayload } from './types.ts';
/**
- * Build a `claude://cowork/new` or `claude://code/new` URL for the unified
- * Claude Desktop app (Cowork tab or Code/Epitaxy tab).
- *
- * Emits the prompt + folder shape when a prompt is present:
- *
- * claude://<mode>/new?q=<encoded prompt>&folder=<projectDir>
- *
- * The empty-prompt sub-branch is a defensive fallback that drops `q=` and
- * emits cwd-only:
- *
- * claude://<mode>/new?folder=<projectDir>
- *
- * **Prompt threading applies to ALL scopes** (file / folder / project) — the
- * dispatch hook composes the right scope-specific prompt (file directive,
- * folder directive, or project directive) and threads it through
- * `payload.prompt`; the builder doesn't branch on scope. The
- * precedent #25 invariant ("agent grounds via OK MCP, not native attach")
- * is preserved by virtue of the URL never carrying file content / `file=`
- * attach param — the prompt is a short directive only.
- *
- * `opts.mode` must agree with `payload.target` ('claude-cowork' → 'cowork',
- * 'claude-code' → 'code'); dispatch.ts enforces the pairing.
+ * The precedent #60 invariant ("agent grounds via OK MCP, not native attach") is preserved by
+ * virtue of the URL never carrying file content / `file=` attach param — the prompt is a short
+ * directive only.
*/
export function buildClaudeUrl(opts: { mode: 'cowork' | 'code' }, payload: HandoffPayload): string {
const folder = encodeURIComponent(payload.projectDir);
diff --git a/packages/core/src/handoff/codex-url.test.ts b/packages/core/src/handoff/codex-url.test.ts
index 08f381c00..f7675b66b 100644
--- a/packages/core/src/handoff/codex-url.test.ts
+++ b/packages/core/src/handoff/codex-url.test.ts
@@ -22,14 +22,14 @@ test('buildCodexUrl threads prompt for doc-scoped as prompt=<prompt>&path=<proje
test('buildCodexUrl single-encodes % in projectDir', () => {
const url = buildCodexUrl(payload({ projectDir: '/Users/who/My %Project' }));
expect(url).toContain('path=%2FUsers%2Fwho%2FMy%20%25Project');
- // precedent #25 invariant: no `file=` attach.
+ // precedent #60 invariant: no `file=` attach.
expect(url).not.toContain('file=');
});
-test('buildCodexUrl threads em-dash + unicode prompt safely (precedent #25: no file=)', () => {
+test('buildCodexUrl threads em-dash + unicode prompt safely (precedent #60: no file=)', () => {
const url = buildCodexUrl(payload({ prompt: 'Read café — notes about the feature' }));
expect(url).toContain('prompt=Read%20caf%C3%A9%20%E2%80%94%20notes%20about%20the%20feature');
- // precedent #25 invariant: no native file-attach.
+ // precedent #60 invariant: no native file-attach.
expect(url).not.toContain('file=');
});
@@ -40,7 +40,7 @@ test('buildCodexUrl single-encodes literal & in projectDir — DC8.5', () => {
expect(url.split('&').length - 1).toBe(1);
});
-test('buildCodexUrl precedent #25: docPath bytes never thread into URL', () => {
+test('buildCodexUrl precedent #60: docPath bytes never thread into URL', () => {
const url = buildCodexUrl(payload({ docPath: '/Users/who/proj/docs/SPECIFIC-FILE.md' }));
expect(url).not.toContain('SPECIFIC-FILE');
expect(url).not.toContain('file=');
@@ -64,7 +64,7 @@ test('buildCodexUrl project-scoped (composeEmptySpacePrompt) includes encoded pr
expect(url).toBe(`codex://new?prompt=${encodeURIComponent(prompt)}&path=%2FUsers%2Fwho%2Fproj`);
});
-test('INVARIANT: buildCodexUrl threads prompt through ALL scopes; precedent #25 = no file=', () => {
+test('INVARIANT: buildCodexUrl threads prompt through ALL scopes; precedent #60 = no file=', () => {
const cases: ReadonlyArray<{
projectDir: string;
docPath: string;
@@ -101,7 +101,7 @@ test('INVARIANT: buildCodexUrl threads prompt through ALL scopes; precedent #25
docPath: c.docPath,
prompt: c.prompt,
});
- // precedent #25 invariant — no native file-attach.
+ // precedent #60 invariant — no native file-attach.
expect(url).not.toContain('file=');
expect(url).toContain('prompt=');
expect(url).toContain('path=');
diff --git a/packages/core/src/handoff/codex-url.ts b/packages/core/src/handoff/codex-url.ts
index 008b6afcd..47c370034 100644
--- a/packages/core/src/handoff/codex-url.ts
+++ b/packages/core/src/handoff/codex-url.ts
@@ -1,24 +1,9 @@
import type { HandoffPayload } from './types.ts';
/**
- * Build a `codex://new?...` URL for OpenAI Codex Desktop.
- *
- * Emits the prompt + path shape when a prompt is present:
- *
- * codex://new?prompt=<encoded prompt>&path=<projectDir>
- *
- * The empty-prompt sub-branch is a defensive fallback that drops `prompt=`
- * and emits cwd-only:
- *
- * codex://new?path=<projectDir>
- *
- * **Prompt threading applies to ALL scopes** (file / folder / project) — the
- * dispatch hook composes the right scope-specific prompt and threads it
- * through `payload.prompt`; the builder doesn't branch on scope. The
- * precedent #25 invariant ("agent grounds via OK MCP, not native attach")
- * is preserved by virtue of the URL never carrying file content / a `file=`
- * attach param — the prompt is a short directive only. `docPath` is never
- * threaded — Codex's URL scheme has no atomic file param.
+ * The precedent #60 invariant ("agent grounds via OK MCP, not native attach") is preserved by
+ * virtue of the URL never carrying file content / a `file=` attach param — the prompt is a short
+ * directive only.
*/
export function buildCodexUrl(payload: HandoffPayload): string {
const path = encodeURIComponent(payload.projectDir);
diff --git a/packages/core/src/handoff/cursor-url.test.ts b/packages/core/src/handoff/cursor-url.test.ts
index c68f9bd15..489bc2755 100644
--- a/packages/core/src/handoff/cursor-url.test.ts
+++ b/packages/core/src/handoff/cursor-url.test.ts
@@ -22,7 +22,7 @@ test('buildCursorUrl threads double-encoded prompt for doc-scoped as text=<dbl-e
test('buildCursorUrl doc-scoped double-encodes prompt containing literal %', () => {
const url = buildCursorUrl(payload({ prompt: 'a%b' }));
expect(url).toContain('text=a%2525b');
- // precedent #25 invariant: no native file-attach.
+ // precedent #60 invariant: no native file-attach.
expect(url).not.toContain('file=');
});
@@ -109,7 +109,7 @@ test('buildCursorUrl project-scoped double-encodes adversarial prompt (round-tri
expect(decodeURIComponent(decodeURIComponent(text as string))).toBe(adversarialPrompt);
});
-test('INVARIANT: buildCursorUrl threads double-encoded prompt through ALL scopes; precedent #25 = no file=', () => {
+test('INVARIANT: buildCursorUrl threads double-encoded prompt through ALL scopes; precedent #60 = no file=', () => {
const cases: ReadonlyArray<{
projectDir: string;
docPath: string;
@@ -146,7 +146,7 @@ test('INVARIANT: buildCursorUrl threads double-encoded prompt through ALL scopes
docPath: c.docPath,
prompt: c.prompt,
});
- // precedent #25 invariant — no native file-attach.
+ // precedent #60 invariant — no native file-attach.
expect(url).not.toContain('file=');
expect(url).toContain('text=');
expect(url).toContain('workspace=');
diff --git a/packages/core/src/handoff/cursor-url.ts b/packages/core/src/handoff/cursor-url.ts
index e1813dab5..6e5d7a4f3 100644
--- a/packages/core/src/handoff/cursor-url.ts
+++ b/packages/core/src/handoff/cursor-url.ts
@@ -6,32 +6,9 @@ function basename(p: string): string {
}
/**
- * Build Cursor's step-2 prompt URL. Step 1 (`cursor <workspacePath>` spawn to
- * focus the workspace window) is owned by the `cli-binary` recipe in
- * `handoff-dispatch-api.ts`, which delegates to `spawn-cursor-api.ts`.
- *
- * Emits the prompt + workspace shape when a prompt is present:
- *
- * cursor://anysphere.cursor-deeplink/prompt?text=<double-enc prompt>&workspace=<single-enc-basename>&mode=agent
- *
- * The empty-prompt sub-branch is a defensive fallback that drops `text=`
- * and emits cwd-only:
- *
- * cursor://anysphere.cursor-deeplink/prompt?workspace=<single-enc-basename>&mode=agent
- *
- * `text=` is DOUBLE-encoded: Cursor's router does two decode passes with
- * error recovery on the second. Single-encoding silently corrupts prompts
- * containing substrings that look like valid URL escapes (`%41`, em-dash
- * bytes, pct-encoded URLs in quoted text) — this matches Linear's production
- * rule. `workspace=` is single-encoded basename (Cursor routes by
- * window-name, which is the basename, not the full path).
- *
- * **Prompt threading applies to ALL scopes** (file / folder / project) — the
- * dispatch hook composes the right scope-specific prompt and threads it
- * through `payload.prompt`; the builder doesn't branch on scope. The
- * precedent #25 invariant ("agent grounds via OK MCP, not native attach")
- * is preserved by virtue of the URL never carrying file content / a `file=`
- * attach param — the prompt is a short directive only.
+ * The precedent #60 invariant ("agent grounds via OK MCP, not native attach") is preserved by
+ * virtue of the URL never carrying file content / a `file=` attach param — the prompt is a short
+ * directive only.
*/
export function buildCursorUrl(payload: HandoffPayload): string {
const workspace = encodeURIComponent(basename(payload.projectDir));
diff --git a/packages/core/src/handoff/prompt-composer.ts b/packages/core/src/handoff/prompt-composer.ts
index 80eac8156..ecfe2fcd5 100644
--- a/packages/core/src/handoff/prompt-composer.ts
+++ b/packages/core/src/handoff/prompt-composer.ts
@@ -1,42 +1,6 @@
/**
- * Prompt composers for the native-handoff subsystem. Each produces the string
- * the per-target URL builders thread into the prompt query param
- * (`q=` / `prompt=` / `text=`).
- *
- * Three are **directive** composers — file, folder, and empty-space / project.
- * Each emits a short sentence naming a path (or none, for project scope) and
- * telling the agent to open the target in OpenKnowledge's web preview. They
- * never carry file content, so the precedent #25 invariant ("agent grounds
- * via OK MCP, not native attach") holds by virtue of the URL never carrying
- * `file=` attach data.
- *
- * `composeSelectionPrompt` is the fourth — the editor "Edit with AI"
- * affordance. It is not a bare directive: it carries the passage the user
- * selected, either inlined in a fenced block or, when the selection is too
- * large to fit the URL budget, referenced by a short locus anchor the agent
- * resolves by reading the doc via OK MCP. See its own JSDoc for the transport
- * contract.
- *
- * The dispatch hook (`useHandoffDispatch`) picks the composer per
- * `HandoffDispatchInput`.
- *
- * **`autoOpen` honors the user's `appearance.preview.autoOpen` preference.**
- * When `true` (default), the prompt includes a trailing "Open the OK editor in web view."
- * directive so the receiving agent opens the project's preview UI on first
- * turn. When `false`, the directive trailer is dropped so the receiving agent
- * does not contradict the user's "agent does not open my preview" preference.
- * The legacy " in web view" suffix is dropped in both modes — OpenKnowledge
- * is now distributed as both a desktop app and a web preview, so the prompt
- * stays surface-neutral.
- *
- * **Prompt-injection defense.** Filenames arrive from the filesystem and may
- * carry control characters, embedded newlines, or quote / backslash bytes a
- * downstream agent could interpret as instruction-terminator markers. Every
- * interpolated path is passed through `sanitizePathForPrompt` to strip
- * control bytes + zero-width / bidi tricks + backticks, so the agent sees the
- * path as a single literal token rather than as instruction text. Without
- * this, a file named `notes/innocent.md\n\nNew instructions: …` would inject
- * a fake instruction block into the agent's prompt.
+ * They never carry file content, so the precedent #60 invariant ("agent grounds via OK MCP, not
+ * native attach") holds by virtue of the URL never carrying `file=` attach data.
*/
import { shellSingleQuote } from './terminal-launch.ts';
import type { HandoffTarget } from './types.ts';
diff --git a/packages/core/src/handoff/types.ts b/packages/core/src/handoff/types.ts
index 638048880..cd5a64b3b 100644
--- a/packages/core/src/handoff/types.ts
+++ b/packages/core/src/handoff/types.ts
@@ -11,23 +11,9 @@ export type HandoffTarget =
| 'hermes';
/**
- * Data carried from the UI to the URL builder. Minimal by construction: only
- * path + prompt. The target agent grounds via the OpenKnowledge MCP server
- * (precedent #25 writer-ID taxonomy); the
- * URL never carries file content / a `file=` attach param — only a short
- * directive `prompt` and the project / folder path.
- *
- * The URL builders thread `prompt` (when non-empty) into the per-target
- * prompt query param (`q=` / `prompt=` / `text=`) regardless of scope. The
- * caller (`runHandoffDispatch`) composes the right scope-specific prompt —
- * file directive, folder directive, or project directive — and the builder
- * just encodes it. An empty `prompt` is a defensive fallback that drops the
- * query param.
- *
- * The renderer helpers `buildHandoffInput` (file scope),
- * `buildFolderHandoffInput` (folder scope), and `buildProjectScopedHandoffInput`
- * (project scope) wrap the sentinel construction so call sites never pass
- * `''` directly.
+ * The precedent #60 invariant ("agent grounds via OK MCP, not native attach") holds by construction:
+ * the payload carries only a short directive `prompt` and the project / folder path, never file
+ * content or a `file=` attach param.
*/
export interface HandoffPayload {
readonly target: HandoffTarget;
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index a5ff74960..1ef62e19b 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -594,7 +594,10 @@ export {
WikiLink,
type WikiLinkAttrs,
} from './extensions/wiki-link.ts';
-// schema-add-only per precedent #9, so the export commits to additive
+/**
+ * The re-exported attrs are schema-add-only per precedent #9, so this public import path
+ * commits to additive evolution only.
+ */
export {
WikiLinkEmbed,
type WikiLinkEmbedAttrs,
diff --git a/packages/core/src/markdown/fixtures/perf/generate.ts b/packages/core/src/markdown/fixtures/perf/generate.ts
index 8b1eb8519..c81ad5fa4 100644
--- a/packages/core/src/markdown/fixtures/perf/generate.ts
+++ b/packages/core/src/markdown/fixtures/perf/generate.ts
@@ -109,7 +109,7 @@ function paragraphBlock(rand: () => number): string {
}
function headingBlock(rand: () => number, index: number): string {
- const level = 1 + pickIndex(rand, 3); // h1-h3
+ const level = 1 + pickIndex(rand, 3);
const hashes = '#'.repeat(level);
return `${hashes} Section ${index}: ${words(rand, 3 + pickIndex(rand, 3))}`;
}
@@ -136,8 +136,8 @@ function codeBlock(rand: () => number): string {
}
function tableBlock(rand: () => number): string {
- const cols = 3 + pickIndex(rand, 2); // 3-4 cols
- const rows = 2 + pickIndex(rand, 4); // 2-5 rows
+ const cols = 3 + pickIndex(rand, 2);
+ const rows = 2 + pickIndex(rand, 4);
const header = Array.from({ length: cols }, (_, i) => `Col${i + 1}`);
const sep = Array.from({ length: cols }, () => '---');
const lines = [`| ${header.join(' | ')} |`, `| ${sep.join(' | ')} |`];
diff --git a/packages/core/src/registry/built-ins.ts b/packages/core/src/registry/built-ins.ts
index c0e418907..6d921815b 100644
--- a/packages/core/src/registry/built-ins.ts
+++ b/packages/core/src/registry/built-ins.ts
@@ -1,47 +1,3 @@
-/**
- * Built-ins manifest — canonical pack (Callout + Image + Video + Audio +
- * Accordion + Math + Mermaid + PDF + File + Tabs + Tab).
- *
- * KaTeX-lazy renderer for Math with γ-preserved source forms across
- * `<Math>`, `$$…$$`, ` ```math ` fence; mermaid-js renderer for
- * ` ```mermaid ` fences. The Mermaid canonical is named `MermaidFence`
- * (single `chart` prop, fence-only authoring); `Mermaid` is intentionally
- * NOT a registered descriptor name so legacy `<Mermaid />` JSX content
- * falls through to the wildcard `'*'` (raw-mdx editable source block).
- * The PDF canonical is a pdfjs-dist-backed multi-page canvas viewer with
- * its own toolbar.
- * `canonical-compat.test.ts` and `registry.test.ts` are the authoritative
- * count assertions and update with every canonical addition. The
- * compound-wrapper machinery is absent (`compound-wrappers.tsx` was deleted
- * and the precedent #29 compound-components bridge was retracted). Names that still appear in user content fall through to the
- * wildcard `'*'` descriptor (`hasChildren: true`, empty props) per
- * `createRegistry()` / `getOrWildcard()`.
- *
- * Per-component prop shapes (load-bearing):
- * - Image — 8 props (src, alt, width, height, caption, title, loading, zoom)
- * alongside the DIY `react-medium-image-zoom` renderer.
- * - Callout — 7 props (GFM 5-type enum + title/icon/color/collapsible/defaultOpen).
- * - Video — 11-prop shape (1 common + 10 advanced). HTML5 `<video>`
- * for file-served media; YouTube URLs dispatch via `parseYouTubeUrl`
- * to a `react-lite-youtube-embed` facade (thumbnail-then-iframe).
- * Timestamps ride inside the URL (`?t=…` folded to `?start=N`); no
- * dedicated `start` prop on the descriptor.
- * - Audio — 7 props (src/title/autoPlay/loop/muted/preload + children for
- * `<source>`/`<track>` passthrough); `hasChildren: true`.
- * - Accordion — 6 props (title required + defaultOpen + icon + description +
- * id + name + children). Standalone: no `<Accordions>` parent wrapper;
- * HTML5 `<details>`/`<summary>` substrate; cross-browser exclusive-accordion
- * grouping via HTML5 `<details name>`; no `variant` prop — Notion color-map
- * absorption path is preserved separately.
- *
- * ── Intent-of-ship ───────────────────────────────────────────────────────
- *
- * This manifest is the shipped default for the OK editor. The greenfield
- * directive forbids shipping empty-scaffolding registries; this
- * file is the authoritative source of truth. Downstream embedders can call
- * `createRegistry()` + `.set(...)` to add their own descriptors, but the
- * canonical pack here is the in-app baseline.
- */
import type { Nodes as MdastNodes } from 'mdast';
import {
ALLOWED_AUDIO_MIME_TYPES,
diff --git a/packages/core/src/registry/types.ts b/packages/core/src/registry/types.ts
index 59b973057..19aa9e590 100644
--- a/packages/core/src/registry/types.ts
+++ b/packages/core/src/registry/types.ts
@@ -11,22 +11,8 @@ export interface PropDefBase {
hideWhen?: (values: Record<string, unknown>) => boolean;
advanced?: boolean;
/**
- * Opt-in: when the prop value strictly equals the declared `defaultValue`,
- * omit the attribute on emit. The renderer applies the default at parse
- * time anyway (descriptor `translateProps` and React component-level
- * defaults), so the on-disk attribute is redundant.
- *
- * Distinct from `defaultValue`: `defaultValue` doubles as a UI initial-
- * state hint AND may carry semantic meaning (e.g., `<img alt="">` is
- * "decorative" — different from absent — even though defaultValue is `''`).
- * Set this flag only when the rendered behavior of `prop=default` and
- * `prop absent` is truly identical at the browser layer (e.g., HTML
- * `loading` defaults to `lazy`; HTML5 `<video controls>` defaults to
- * absent-controls = no controls but our descriptor flips that with
- * `defaultValue: true`).
- *
- * Strips redundant attrs on the dirty serialize path only — pristine
- * sourceRaw round-trips byte-identically (precedent #9 untouched).
+ * Strips redundant attrs on the dirty serialize path only — pristine sourceRaw round-trips
+ * byte-identically (precedent #9 untouched).
*/
omitOnDefault?: boolean;
}
diff --git a/packages/core/src/schema-invariant.test.ts b/packages/core/src/schema-invariant.test.ts
index 729fe642b..71bc7a76e 100644
--- a/packages/core/src/schema-invariant.test.ts
+++ b/packages/core/src/schema-invariant.test.ts
@@ -83,18 +83,7 @@ function loadSnapshot(): SchemaSnapshot | null {
return JSON.parse(readFileSync(SNAPSHOT_PATH, 'utf-8')) as SchemaSnapshot;
}
-/**
- * Explicit narrowings that have been authorized against precedent #9 with
- * linked spec evidence. Every entry names (a) the exact node-attribute
- * combination being narrowed and (b) the spec citation explaining why the
- * y-prosemirror schema-throw safety net is sufficient coverage. Adding a new
- * entry REQUIRES the companion spec section AND a live-fire regression test in
- * `packages/app/tests/integration/`.
- *
- * This is the NOT a loophole — it's a registry that surfaces every
- * authorized narrowing in one place so future audits can enumerate them
- * without re-reading specs.
- */
+/** Explicit narrowings that have been authorized against precedent #9 with linked spec evidence. */
interface AllowedNarrowing {
nodeType: string;
kind: 'content' | 'attr-removed';
diff --git a/packages/core/src/schemas/api/agent-write.ts b/packages/core/src/schemas/api/agent-write.ts
index 3a91cbc3e..b3a49bd37 100644
--- a/packages/core/src/schemas/api/agent-write.ts
+++ b/packages/core/src/schemas/api/agent-write.ts
@@ -1,14 +1,6 @@
/**
- * Cluster A: agent-write / -write-md / -patch / -undo
- *
- * Mutating handlers that write to Y.Docs through the agent attribution path
- * (precedent #24). `withValidation()` enforces these schemas at the wire
- * boundary; the handler receives an already-typed body. Body-shape failures
- * (schema rejection) emit `urn:ok:error:invalid-request` PRE-identity —
- * semantically OK because no Y.Doc mutation is attempted. Semantic failures
- * (reserved docname, target-not-found, stale-target, no-active-session) emit
- * POST-identity. The `attribution-sweep-coverage.test.ts` ordering check
- * enforces this distinction.
+ * Cluster A: agent-write / -write-md / -patch / -undo Mutating handlers that write to Y.Docs
+ * through the agent attribution path (precedent #24).
*/
import type { StandardSchemaV1 } from '@standard-schema/spec';
diff --git a/packages/core/src/schemas/cc1.ts b/packages/core/src/schemas/cc1.ts
index b5d162941..5f1797c26 100644
--- a/packages/core/src/schemas/cc1.ts
+++ b/packages/core/src/schemas/cc1.ts
@@ -26,11 +26,8 @@ export const DerivedViewChannelSchema = z.enum([
export type DerivedViewChannel = z.infer<typeof DerivedViewChannelSchema>;
/**
- * Union of every CC1 channel identifier — the five derived-view channels
- * plus the four broadcast-shape channels (`server-info`, `branch-switched`,
- * `disk-ack`, `config-validation-rejected`). Tightening from `string` to
- * this union narrows the per-channel watermark map (`metrics.cc1LastSeq`)
- * to bounded cardinality at compile time, mirroring the cardinality
+ * Tightening from `string` to this union narrows the per-channel watermark map
+ * (`metrics.cc1LastSeq`) to bounded cardinality at compile time, mirroring the cardinality
* discipline applied to `bridgeToleranceApplied` (precedent #38).
*/
export type CC1Channel =
diff --git a/packages/core/src/shadow-repo-layout.ts b/packages/core/src/shadow-repo-layout.ts
index 2f06d93a9..496248a3d 100644
--- a/packages/core/src/shadow-repo-layout.ts
+++ b/packages/core/src/shadow-repo-layout.ts
@@ -3,34 +3,7 @@ import { dirname, join, resolve, sep } from 'node:path';
import { fnv1aDigest } from './bridge/hash-util.ts';
import { discoverGitRepository } from './git-repository.ts';
-/**
- * Writer-ID taxonomy (precedent #25). Classified system writers are non-attributable
- * actions written under a fixed writer-id. Legacy values ('human-', 'upstream',
- * 'server') are classified 'unknown' so the allowlist sweep can
- * identify and GC them without confusing them with valid attributed refs.
- *
- * Full writer-ID table:
- * agent-<connectionId> → 'agent' (MCP session)
- * principal-<UUID> → 'principal' (browser tab)
- * git-author-<hash> → 'classified-git-author' (upstream commit author)
- * file-system → 'classified-file-system' (disk reconcile)
- * git-upstream → 'classified-git-upstream' (HEAD-move import boundary)
- * openknowledge-service → 'classified-openknowledge-service' (park / service)
- * ok-generator → 'classified-ok-generator' (OK-authored artifacts)
- * server, human-*, upstream → 'unknown' (legacy, swept on GC)
- *
- * `ok-generator` is distinct from `openknowledge-service` on purpose: the service
- * writer is the no-contributor fallback for housekeeping, while a generated
- * artifact is a deliberate authoring action that simply has no human behind it.
- * Folding the two would put generated content under the id this precedent
- * reserves for unattributable work.
- *
- * `git-author-<hash>` gives each distinct upstream commit author their own WIP
- * ref so the per-doc Timeline query (which diffs each ref's chain) attributes a
- * pulled change to the right author. The `<hash>` is `fnv1aDigest(email)` — one
- * ref per author, not per pull. Display name / real email travel on the commit's
- * `ok-actor` line, not in the id.
- */
+/** Writer-ID taxonomy (precedent #25). */
export type WriterClassification =
| 'agent'
| 'principal'
diff --git a/packages/core/src/skills-catalog/scope.ts b/packages/core/src/skills-catalog/scope.ts
index cf9e669ce..7176a8afc 100644
--- a/packages/core/src/skills-catalog/scope.ts
+++ b/packages/core/src/skills-catalog/scope.ts
@@ -1,24 +1,6 @@
/**
- * Detected-skill scope resolution — the project-locality boundary for the
- * cross-harness catalog (precedent #50).
- *
- * `enumerateInstalledSkills` is machine-global: it lists every skill installed
- * in every harness home, including Claude plugins installed *project-scoped for
- * a different project*. Surfacing those under the current project's PROJECT
- * header is a project-locality violation — a resource bound to project A must
- * not appear as project B's. These two pure helpers draw that boundary:
- *
- * - `catalogRawScopeToOkScope` maps a harness's raw scope string onto OK's
- * `project | global` enum (the client-side bucket for a detected row).
- * - `isDetectedSkillInProject` decides whether a detected skill belongs to the
- * open project at all — the server drops the ones that don't before the
- * client ever buckets them.
- * - `isSkillOutsideOpenProject` decides whether a skill that DOES belong is
- * nonetheless stored outside the open tree, where editing it in place would
- * write to a different checkout.
- *
- * Pure + browser-safe (no `node:*`) so both the client sidebar and the server
- * endpoint share one source of truth.
+ * Detected-skill scope resolution — the project-locality boundary for the cross-harness catalog
+ * (precedent #50).
*/
import type { SkillScope } from '../schemas/api/tags-search.ts';
diff --git a/packages/core/src/utils/apply-by-prefix-suffix.ts b/packages/core/src/utils/apply-by-prefix-suffix.ts
index 05d289fc5..d7b25e8e3 100644
--- a/packages/core/src/utils/apply-by-prefix-suffix.ts
+++ b/packages/core/src/utils/apply-by-prefix-suffix.ts
@@ -1,16 +1,8 @@
import type * as Y from 'yjs';
/**
- * Apply `newText` to `ytext` with minimal CRDT mutation: find matching prefix
- * and suffix, delete + insert only the differing middle region. Preserves
- * Y.Text Items in the prefix/suffix (and thus their transaction origins).
- *
- * Shared between client-side Observer A (Path B three-way merge result application)
- * and server-side agent-write path (applyAgentMarkdownWrite).
- * Same semantics, one implementation.
- *
- * @see PRECEDENTS.md precedent #9 (minimize CRDT mutation in sync bridges)
- * @see PRECEDENTS.md precedent #10 (XmlFragment-authoritative, Y.Text mirrors)
+ * Same semantics, one implementation. @see PRECEDENTS.md precedent #9 (minimize CRDT mutation in
+ * sync bridges) @see PRECEDENTS.md precedent #10 (XmlFragment-authoritative, Y.Text mirrors)
*/
export function applyByPrefixSuffix(ytext: Y.Text, currentText: string, newText: string): void {
if (currentText === newText) return;
diff --git a/packages/desktop/build/deb-postinst.sh b/packages/desktop/build/deb-postinst.sh
index 99acbc44b..bfa38244c 100644
--- a/packages/desktop/build/deb-postinst.sh
+++ b/packages/desktop/build/deb-postinst.sh
@@ -1,26 +1,10 @@
#!/bin/bash
-# after-install script, shared by the deb AND rpm targets (see the `rpm:` block
-# in electron-builder.yml for why one script serves both — every distro-
-# specific step below is already existence-guarded, so the Ubuntu-only halves
-# no-op on Fedora/RHEL rather than failing).
-#
-# electron-builder's FpmTarget passes custom scripts through the SAME macro
-# templating as its defaults — every dollar-brace sequence is treated as a
-# macro (unknown names throw at build time, comments included), so bash
-# variables here MUST use the brace-less $NAME form.
-#
-# The first half is a verbatim copy of app-builder-lib's
-# templates/linux/after-install.tpl (a custom afterInstall REPLACES the
-# default, it does not extend it): binary symlink via update-alternatives,
-# chrome-sandbox SUID fallback, mime/desktop database refresh, AppArmor
-# profile install (Ubuntu 24.04+ userns restriction). The OpenKnowledge
-# additions — /usr/bin/ok + /usr/bin/open-knowledge symlinks to the bundled
-# CLI wrapper (D10) — are at the bottom. Re-sync the copied half when
-# bumping electron-builder.
+# UPSTREAM([email protected]): FpmTarget runs this file through its macro
+# templater before packaging, so every dollar-brace sequence is a macro and an
+# unknown name throws at build time. Bash variables here use the $NAME form.
if type update-alternatives >/dev/null 2>&1; then
- # Remove previous link if it doesn't use update-alternatives
if [ -L '/usr/bin/${executable}' -a -e '/usr/bin/${executable}' -a "`readlink '/usr/bin/${executable}'`" != '/etc/alternatives/${executable}' ]; then
rm -f '/usr/bin/${executable}'
fi
@@ -29,9 +13,7 @@ else
ln -sf '/opt/${sanitizedProductName}/${executable}' '/usr/bin/${executable}'
fi
-# Check if user namespaces are supported by the kernel and working with a quick test:
if ! { [[ -L /proc/self/ns/user ]] && unshare --user true; }; then
- # Use SUID chrome-sandbox only on systems without user namespaces:
chmod 4755 '/opt/${sanitizedProductName}/chrome-sandbox' || true
else
chmod 0755 '/opt/${sanitizedProductName}/chrome-sandbox' || true
@@ -45,10 +27,6 @@ if hash update-desktop-database 2>/dev/null; then
update-desktop-database /usr/share/applications || true
fi
-# Install apparmor profile. (Ubuntu 24+)
-# First check if the version of AppArmor running on the device supports our profile.
-# This is in order to keep backwards compatibility with Ubuntu 22.04 which does not support abi/4.0.
-# In that case, we just skip installing the profile since the app runs fine without it on 22.04.
if apparmor_status --enabled > /dev/null 2>&1; then
APPARMOR_PROFILE_SOURCE='/opt/${sanitizedProductName}/resources/apparmor-profile'
APPARMOR_PROFILE_TARGET='/etc/apparmor.d/${executable}'
@@ -62,12 +40,6 @@ if apparmor_status --enabled > /dev/null 2>&1; then
fi
fi
-# --- OpenKnowledge additions below (keep the copied template above in sync) ---
-
-# CLI-on-PATH (D10): expose the bundled `ok` CLI system-wide. The wrapper
-# re-execs the app's Electron binary as a Node host (ELECTRON_RUN_AS_NODE=1),
-# so this is a symlink, not a copy — it tracks upgrades in place. Both bin
-# names ship, matching the npm package's `ok` + `open-knowledge` bins.
OK_WRAPPER='/opt/${sanitizedProductName}/resources/cli/bin/ok.sh'
if [ -f "$OK_WRAPPER" ]; then
chmod 0755 "$OK_WRAPPER" || true
diff --git a/packages/desktop/build/deb-postrm.sh b/packages/desktop/build/deb-postrm.sh
index 393f10103..147695444 100644
--- a/packages/desktop/build/deb-postrm.sh
+++ b/packages/desktop/build/deb-postrm.sh
@@ -1,30 +1,12 @@
#!/bin/bash
-# after-remove script, shared by the deb AND rpm targets (see the `rpm:` block
-# in electron-builder.yml for why one script serves both). The body below the
-# guard is a verbatim copy of app-builder-lib's
-# templates/linux/after-remove.tpl (a custom afterRemove REPLACES the
-# default) + removal of the OpenKnowledge /usr/bin CLI symlinks that
-# deb-postinst.sh created. Macro templating applies — bash variables must
-# use the brace-less $NAME form (see deb-postinst.sh).
-
-# Upgrade guard — the one place the two packagers genuinely disagree, and the
-# reason this is not a verbatim copy. On rpm, the NEW package's %post runs
-# BEFORE the old package's %postun, so an unguarded teardown deletes the
-# symlinks and the update-alternatives entry that the upgrade just installed,
-# leaving `ok` off PATH until the next reinstall. dpkg orders it the other way
-# round, so the deb only ever benefited from the guard cosmetically (no window
-# where /usr/bin/ok is missing) — but it must not regress, hence one guard
-# that reads both dialects:
-# rpm %postun: $1 is the count of instances left after the operation —
-# 0 on a real erase, >=1 on an upgrade.
-# deb postrm : $1 is the action word — "remove"/"purge" on a real removal,
-# "upgrade"/"failed-upgrade"/"abort-upgrade" mid-upgrade.
+# UPSTREAM([email protected]): rpm runs the new package's %post BEFORE the
+# old package's %postun, so an unguarded teardown deletes the symlinks the
+# upgrade just installed. $1 is an rpm instance count or a dpkg action word.
case "$1" in
upgrade | failed-upgrade | abort-upgrade | [1-9]*) exit 0 ;;
esac
-# Delete the link to the binary
if type update-alternatives >/dev/null 2>&1; then
update-alternatives --remove '${executable}' '/usr/bin/${executable}'
else
@@ -33,15 +15,10 @@ fi
APPARMOR_PROFILE_DEST='/etc/apparmor.d/${executable}'
-# Remove apparmor profile.
if [ -f "$APPARMOR_PROFILE_DEST" ]; then
rm -f "$APPARMOR_PROFILE_DEST"
fi
-# --- OpenKnowledge additions below (keep the copied template above in sync) ---
-
-# Remove the CLI symlinks only if they still point into this install —
-# a user-repointed /usr/bin/ok (e.g. npm-global install) is left alone.
for link in /usr/bin/ok /usr/bin/open-knowledge; do
if [ -L "$link" ]; then
target=$(readlink "$link")
diff --git a/packages/desktop/electron-builder.yml b/packages/desktop/electron-builder.yml
index 44390ce4d..345424f6e 100644
--- a/packages/desktop/electron-builder.yml
+++ b/packages/desktop/electron-builder.yml
@@ -607,7 +607,7 @@ rpm:
# the AppArmor block behind `apparmor_status --enabled`, which is simply
# absent outside the Ubuntu family. There are no dpkg-isms. The one thing
# they did NOT handle is rpm's upgrade ordering — the removal script grew a
- # guard for it; see the header of build/deb-postrm.sh.
+ # guard for it; see the UPSTREAM marker at the head of build/deb-postrm.sh.
afterInstall: build/deb-postinst.sh
afterRemove: build/deb-postrm.sh
# Our own list, not electron-builder's rpm default. The first eight entries
diff --git a/packages/desktop/resources/cli/bin/ok-linux.sh b/packages/desktop/resources/cli/bin/ok-linux.sh
index 5563edd22..540693d52 100755
--- a/packages/desktop/resources/cli/bin/ok-linux.sh
+++ b/packages/desktop/resources/cli/bin/ok-linux.sh
@@ -1,25 +1,5 @@
#!/usr/bin/env bash
-# Wrapper script shipped inside the OpenKnowledge Linux install at
-# <install-root>/resources/cli/bin/ok.sh (this file is renamed by the
-# electron-builder `linux.extraResources` rule). Re-uses the bundled
-# Electron runtime as a Node host via ELECTRON_RUN_AS_NODE=1 — no separate
-# Node install required. Linux sibling of the darwin ok.sh (which derives
-# its paths from the .app bundle shape); layout here is the flat
-# electron-builder Linux layout:
-#
-# <root>/openknowledge (Electron binary, linux.executableName)
-# <root>/resources/cli/bin/ok.sh (this wrapper)
-# <root>/resources/cli/dist/cli.mjs
-#
-# deb installs place <root> at /opt/OpenKnowledge and symlink
-# /usr/bin/ok -> this file (build/deb-postinst.sh). AppImage mounts are
-# ephemeral, so PATH install from an AppImage is declined by path-install
-# instead of pointing at a mount path that dies with the process.
-#
-# `set -e` deliberately omitted — matches ok.sh (the readlink loop handles
-# failures inline and the final exit must propagate the CLI's code).
-
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
DIR=$(dirname "$SOURCE")
@@ -28,23 +8,16 @@ while [ -h "$SOURCE" ]; do
done
BIN_DIR="$( cd -P "$( dirname "$SOURCE" )" >/dev/null 2>&1 && pwd )"
-# <root> = bin -> cli -> resources -> root
ROOT_DIR="$(cd -P "$BIN_DIR/../../.." >/dev/null 2>&1 && pwd)"
ELECTRON="$ROOT_DIR/openknowledge"
CLI="$BIN_DIR/../dist/cli.mjs"
if [ ! -f "$CLI" ] || [ ! -x "$ELECTRON" ]; then
- # Self-diagnose the uninstalled/moved lifecycle: MCP clients may hold this
- # wrapper path in their configs after the app is removed. Two-line stderr
- # (human-readable + machine-readable JSON) and exit 69 (EX_UNAVAILABLE),
- # mirroring ok.sh's ok-bundle-missing contract.
echo "OpenKnowledge has been removed. Reinstall the OpenKnowledge package." >&2
echo '{"error":"ok-bundle-missing","hint":"OpenKnowledge app appears to have been removed. Reinstall it, or remove OK entries from your MCP config and rerun ok init."}' >&2
exit 69
fi
-# Sanitize NODE_OPTIONS (VS Code pattern; mirrors ok.sh) — re-export under a
-# scoped name so the CLI can opt to honor them explicitly.
export OK_NODE_OPTIONS="$NODE_OPTIONS"
unset NODE_OPTIONS
diff --git a/packages/desktop/resources/cli/bin/ok.sh b/packages/desktop/resources/cli/bin/ok.sh
index 5501f8e1c..5557a0d78 100755
--- a/packages/desktop/resources/cli/bin/ok.sh
+++ b/packages/desktop/resources/cli/bin/ok.sh
@@ -1,19 +1,5 @@
#!/usr/bin/env bash
-# Wrapper script shipped inside the OpenKnowledge.app bundle. Re-uses the bundled Electron runtime as
-# a Node host via ELECTRON_RUN_AS_NODE=1 — no separate Node install
-# required on the user machine. Derived from VS Code's code.sh
-# (github.com/microsoft/vscode/blob/main/resources/darwin/bin/code.sh).
-#
-# See specs/2026-04-21-m6-cli-and-mcp-wiring/SPEC.md §6 (M6a).
-#
-# Note: `set -e` (errexit) is deliberately omitted. The `app_realpath`
-# while-loop handles readlink failures inline (by checking `[ -h "$SOURCE" ]`
-# before each iteration), and the final `exit $?` semantic requires a
-# non-zero exit to propagate from the exec'd CLI — `set -e` would short-
-# circuit both patterns. Matches VS Code's `code.sh` reference (same
-# omission, same rationale).
-
function app_realpath() {
SOURCE=$1
while [ -h "$SOURCE" ]; do
@@ -25,11 +11,6 @@ function app_realpath() {
echo "${SOURCE_DIR%%${SOURCE_DIR#*.app}}"
}
-# APP_BUNDLE_DIR test hook for AC2.12 fixtures — production never
-# sets this; the wrapper always derives APP_PATH from its own
-# realpath. Fixture tests set APP_BUNDLE_DIR to a path whose
-# Contents/Resources/cli/dist/cli.mjs does not exist to exercise
-# the self-diagnosing error branch below.
if [ -n "$APP_BUNDLE_DIR" ]; then
APP_PATH="$APP_BUNDLE_DIR"
else
@@ -37,12 +18,6 @@ else
fi
if [ -z "$APP_PATH" ]; then
- # Symlink resolution failed — install integrity broken (e.g., the wrapper
- # was copied outside the .app, or readlink chain runs into a foreign
- # target). Mirror the bundle-missing branch (Pass 0 Major #10): two-line
- # stderr (human-readable + machine-readable JSON) and exit 69 so MCP
- # clients can surface this distinctly from generic failures, and
- # operators have a structured signal in the diagnostic JSONL.
echo "OpenKnowledge CLI cannot find its app bundle. Reinstall from the OpenKnowledge DMG." >&2
echo "{\"error\":\"ok-wrapper-resolution-failed\",\"hint\":\"The ok.sh wrapper could not resolve its enclosing .app bundle. Reinstall OpenKnowledge from the DMG, or npm install -g @inkeep/open-knowledge for terminal access.\",\"source\":\"${BASH_SOURCE[0]}\"}" >&2
exit 69
@@ -52,37 +27,15 @@ CONTENTS="$APP_PATH/Contents"
ELECTRON="$CONTENTS/MacOS/OpenKnowledge"
CLI="$CONTENTS/Resources/cli/dist/cli.mjs"
-# Self-diagnose the drag-to-Trash lifecycle (D-M6-R6 / AC2.12): if
-# either the bundled CLI or the Electron binary is missing, the .app
-# has been deleted after MCP clients wrote the wrapper path into
-# their configs. Emit a two-line stderr — first line human-readable
-# for clients that surface stderr raw, second line machine-readable
-# JSON for clients that parse it — and exit 69 (EX_UNAVAILABLE) so
-# MCP clients surface the state distinctly from generic failures.
if [ ! -f "$CLI" ] || [ ! -x "$ELECTRON" ]; then
echo "OpenKnowledge has been removed. Reinstall from the OpenKnowledge DMG." >&2
echo '{"error":"ok-bundle-missing","hint":"OpenKnowledge app appears to have been removed. Reinstall from the DMG, or remove OK entries from your MCP config and rerun ok init."}' >&2
exit 69
fi
-# Dock-less helper redirect for the long-lived background servers. `ok mcp`
-# and `ok start` boot the collab server in-process as the ENTRY process —
-# unlike spawned children (redirected by self-spawn.ts /
-# resolve-detached-spawn-args.ts), nothing rewrites them to the LSUIElement
-# helper, so LaunchServices parks a generic "exec" Dock tile against the main
-# binary for the server's whole lifetime. Prefer the sibling helper bundle
-# (its Info.plist declares LSUIElement=true → no Dock tile) for these
-# subcommands when present; fall back to the main binary for older bundles and
-# npm-global installs that have no .app. The default `ok` (and every other
-# subcommand) keeps the main binary — it is a real foreground desktop app.
-#
-# The two literals below are a 5th encoding of the helper bundle dir +
-# executable basename and MUST stay in sync with HELPER_BUNDLE_NAME /
-# HELPER_EXECUTABLE_NAME in packages/core/src/helper-bundle.ts
-# (helper-bundle-name-agreement.test.ts pins the agreement). The executable
-# basename MUST remain "OpenKnowledge Helper": Electron's
-# ELECTRON_RUN_AS_NODE boot reads its own basename via _NSGetExecutablePath()
-# and SIGTRAPs on any other name.
+# UPSTREAM([email protected]): an ELECTRON_RUN_AS_NODE boot reads its own basename
+# via _NSGetExecutablePath() and SIGTRAPs on anything but "OpenKnowledge
+# Helper", so the executable literal below is fixed by Electron, not by us.
RUNTIME="$ELECTRON"
case "$1" in
mcp|start)
@@ -93,13 +46,6 @@ case "$1" in
;;
esac
-# Sanitize NODE_OPTIONS the user may have set for their own projects
-# — they would otherwise be inherited into the Electron-as-Node
-# process and can crash with "--require of ESM". Re-export under a
-# scoped name so the CLI can opt to honor them explicitly (VS Code
-# pattern). Quote the expansion so that multi-token values like
-# `NODE_OPTIONS='--require /tmp/x.js'` are captured verbatim instead
-# of being re-split on whitespace (Review Pass 0 Minor #15).
export OK_NODE_OPTIONS="$NODE_OPTIONS"
unset NODE_OPTIONS
diff --git a/packages/desktop/scripts/afterPack.mjs b/packages/desktop/scripts/afterPack.mjs
index f748bf5b0..b718bea4b 100644
--- a/packages/desktop/scripts/afterPack.mjs
+++ b/packages/desktop/scripts/afterPack.mjs
@@ -6,50 +6,9 @@ import { ensureNodePtySpawnHelperExecutable } from './ensure-node-pty-exec.mjs';
import { resolveElectronBinary } from './resolve-electron-binary.mjs';
import { targetFuses } from './target-fuses.mjs';
-/**
- * electron-builder `afterPack` hook — runs on the packed `.app` bundle before
- * code-signing. We flip the Electron fuses to harden the runtime: disable
- * NODE_OPTIONS env ingestion, require asar integrity validation, and only load
- * app code from asar. Cookie encryption is ON as a defense-in-depth hygiene
- * fuse. EnableNodeCliInspect is left ON because Playwright's `_electron.launch`
- * requires the inspect CLI arguments to attach.
- *
- * RunAsNode is ENABLED. The bundled `ok.sh` wrapper needs
- * `ELECTRON_RUN_AS_NODE=1` to work in packaged builds; VS Code + Atom
- * precedent. Full rationale + defense-in-depth argument at `./target-fuses.mjs`.
- *
- * Fuses are flipped BEFORE the Developer ID signature is applied — electron
- * ships with an ad-hoc Darwin signature that flipFuses would invalidate, so
- * we set `resetAdHocDarwinSignature: true` to keep the intermediate binary
- * in a valid ad-hoc-signed state until electron-builder re-signs with the
- * Developer ID cert.
- *
- * Post-sign verification of these same fuses lives in `afterSign.mjs`
- * ("Windows signtool has shipped silent fuse-clobber regressions; paranoid
- * verification is load-bearing"). Both hooks import the same `targetFuses`
- * map from `./target-fuses.mjs` — flip-time and verify-time cannot drift.
- */
-
export default async function afterPack(context) {
const { appOutDir, packager, electronPlatformName } = context;
- // Fuses flip on EVERY platform (D9). An off-darwin build without the flip
- // would ship with RunAsNode still at Electron's default — but also without
- // the NODE_OPTIONS/asar-integrity hardening, and any drift between
- // platforms here would surface as "works on mac, silently broken CLI on
- // win/linux". Only the darwin-specific steps below (helper bundle,
- // node-pty spawn-helper chmod) stay gated.
-
- // Universal builds: electron-builder packs arm64 and x64 into separate
- // `mac-universal-<arch>-temp` dirs, fires afterPack on each, then calls
- // @electron/universal.makeUniversalApp to merge them. That merge asserts
- // that all non-Mach-O files have identical SHAs across arches — and
- // flipping fuses perturbs `Contents/Frameworks/.../CodeSignature/
- // CodeResources` differently per arch, breaking the SHA-parity check.
- // The canonical fix is to only flip fuses on the MERGED universal app
- // (which has a fat Mach-O binary; @electron/fuses v2 handles that shape
- // correctly). Detect the final output dir by the absence of the `-temp`
- // suffix.
if (appOutDir.endsWith('-temp')) {
console.log(
`[afterPack] skipping per-arch temp "${appOutDir}" — fuses flip on the merged universal app`,
@@ -76,16 +35,10 @@ export default async function afterPack(context) {
try {
await flipFuses(electronBinary, {
version: FuseVersion.V1,
- // Darwin-only concern: electron ships with an ad-hoc signature that
- // the flip would invalidate. Harmless no-op elsewhere, but keep it
- // scoped so the intent is legible.
resetAdHocDarwinSignature: electronPlatformName === 'darwin',
...targetFuses,
});
} catch (err) {
- // Phase-annotated so a fuse-flip failure is distinguishable from a
- // post-sign verification failure in afterSign.mjs — the remediation
- // paths differ (rollback vs investigate re-sign pipeline).
throw new Error(
`[afterPack] fuse flip failed on ${electronBinary}: ${
err instanceof Error ? err.message : String(err)
@@ -96,12 +49,6 @@ export default async function afterPack(context) {
console.log('[afterPack] fuses flipped successfully; electron-builder will re-sign next');
- // Everything below is darwin-only: the LSUIElement helper bundle exists to
- // suppress the macOS Dock "exec" placeholder (no Dock/LaunchServices
- // concept on win/linux — resolve-detached-spawn-args.ts uses
- // parentExecPath directly there). The node-pty chmod is also mac-specific:
- // Linux prebuilds do not use a separate spawn-helper, while the Windows
- // package excludes node-pty.
if (electronPlatformName !== 'darwin') {
console.log(
`[afterPack] fuses done; skipping darwin-only helper-bundle + node-pty steps on "${electronPlatformName}"`,
@@ -109,32 +56,6 @@ export default async function afterPack(context) {
return;
}
- // Detached-server helper bundle: clone the Electron Helper stub binary
- // into our `OpenKnowledge Server.app/Contents/MacOS/` slot. electron-
- // builder's `extraFiles` (in electron-builder.yml) lands the Info.plist
- // alongside but cannot reference output-only artifacts, so the MacOS
- // binary itself is populated here. We source from Electron's own helper
- // stub because its rpath is `@executable_path/../../..` (3 ups, the
- // helper-bundle filesystem position) — sourcing from the parent's main
- // binary would give us a stub whose rpath is `@executable_path/../Frameworks`
- // (1 up) and dyld would fail at child launch. Note that electron-builder
- // renames `Electron Helper.app` → `<productName> Helper.app` during
- // packaging, so we source from the renamed path.
- //
- // The helper bundle's `Info.plist` declares `LSUIElement=true` so the
- // spawned detached server doesn't register a macOS Dock tile — without
- // it, LaunchServices treats the re-exec as a duplicate `.app` launch
- // and pins a stuck "exec" Dock placeholder for the child's lifetime.
- //
- // The cloned binary inside `OpenKnowledge Server.app` MUST be named
- // `<productName> Helper` (matching the canonical Electron generic-helper
- // basename). Electron's helper stub inspects its own `_NSGetExecutablePath()`
- // basename early in boot and SIGTRAPs silently (exit 133, empty stderr)
- // for any other name — including descriptive variants like "OpenKnowledge
- // Server" or invented suffixes like "Helper (Server)" not in Electron's
- // hardcoded {generic, Renderer, GPU, Plugin} type set. The bundle directory
- // name (`OpenKnowledge Server.app`) is free to be descriptive — only the
- // executable basename is load-bearing.
const electronHelperStub = join(
appOutDir,
`${appName}.app`,
@@ -164,10 +85,6 @@ export default async function afterPack(context) {
try {
mkdirSync(serverHelperMacOsDir, { recursive: true });
} catch (err) {
- // Phase-annotated to match the fuse-flip + clone error shapes above.
- // EACCES/ENOSPC/EROFS on the output dir all surface here — distinguish
- // from afterSign.mjs verify-time failures so the remediation path
- // (output-dir perms / disk space) is unambiguous.
throw new Error(
`[afterPack] failed to create MacOS dir for helper bundle at ${serverHelperMacOsDir}: ${
err instanceof Error ? err.message : String(err)
@@ -176,11 +93,6 @@ export default async function afterPack(context) {
);
}
}
- // Split into two phase-annotated blocks — copy vs chmod failures have
- // distinct remediation paths: copy fails on EACCES/ENOSPC/EIO at the
- // output dir (check space + perms on the build output); chmod fails on
- // EPERM (file ownership / SIP-style protection on the target). Keeping
- // them merged would lose the remediation breadcrumb.
try {
copyFileSync(electronHelperStub, serverHelperBinary);
} catch (err) {
@@ -202,13 +114,6 @@ export default async function afterPack(context) {
);
}
- // PkgInfo: every Electron helper bundle ships an 8-byte "APPL????" file
- // at `Contents/PkgInfo` (legacy Carbon type+creator code). Missing
- // PkgInfo isn't load-bearing for this binary's startup, but it diverges
- // from the bundle shape every other Electron helper carries and from
- // what LaunchServices expects of an `APPL` package. Add it here so the
- // Server.app bundle is structurally indistinguishable from its sibling
- // Helper bundles.
const serverHelperPkgInfo = join(serverHelperBundleDir, 'Contents', 'PkgInfo');
try {
writeFileSync(serverHelperPkgInfo, 'APPL????');
@@ -224,9 +129,6 @@ export default async function afterPack(context) {
`[afterPack] cloned Electron Helper stub into OpenKnowledge Server.app MacOS slot at ${serverHelperBinary}`,
);
- // node-pty's prebuilt spawn-helper ships 0644 (node-pty#850); the
- // `**/node-pty/prebuilds/**` asarUnpack rule lands it on disk but keeps that
- // mode, so make it executable before electron-builder re-signs.
const resourcesDir = join(appOutDir, `${appName}.app`, 'Contents', 'Resources');
const ptyHelpers = ensureNodePtySpawnHelperExecutable(resourcesDir);
console.log(`[afterPack] node-pty spawn-helper marked executable (${ptyHelpers.length} file(s))`);
diff --git a/packages/desktop/scripts/afterSign.mjs b/packages/desktop/scripts/afterSign.mjs
index 580e9b1f0..fb3a4297b 100644
--- a/packages/desktop/scripts/afterSign.mjs
+++ b/packages/desktop/scripts/afterSign.mjs
@@ -7,43 +7,6 @@ import { notarize } from '@electron/notarize';
import { resolveElectronBinary } from './resolve-electron-binary.mjs';
import { expectedFuseState, fuseStateName, targetFuses } from './target-fuses.mjs';
-/**
- * electron-builder `afterSign` hook — runs after the `.app` is code-signed
- * with the Developer ID cert, before the DMG is created.
- *
- * On darwin, after the .app is signed:
- * 1. Submit the `.app` to Apple's notary service (`@electron/notarize` calls
- * `xcrun notarytool`) — this also staples the ticket on success.
- * 2. Validate the stapled ticket via `xcrun stapler validate`.
- * 3. Read fuses via `@electron/fuses.getCurrentFuseWire` and assert every
- * fuse matches `targetFuses` (shared with `afterPack.mjs`).
- * paranoid post-sign verification is REQUIRED — Windows signtool has
- * shipped silent fuse-clobber regressions (electron-builder #9428), and
- * macOS codesign+notarize has no formal guarantee against the same class
- * of bug. Fuses confirmed at flip-time are not evidence they survive
- * signing; always re-read.
- *
- * Signing path is gated on env vars. Three credential states are distinguished:
- *
- * - **Zero credentials present** → log and return. Build continues as an
- * unsigned smoke. This is the procurement-in-progress state today.
- * - **Any field of a credential shape present but incomplete** → THROW with
- * the specific missing fields named. Partial credentials are always
- * operator error; silently skipping would ship an unsigned DMG from a
- * branch the operator intended to sign.
- * - **A complete credential shape present** → notarize + staple + verify.
- *
- * Supported shapes:
- * - APPLE_ID + APPLE_APP_SPECIFIC_PASSWORD + APPLE_TEAM_ID (password flow)
- * - APPLE_API_KEY + APPLE_API_KEY_ID [+ APPLE_API_ISSUER] (App Store Connect
- * API key). APPLE_API_ISSUER is required for **Team** keys and rejected
- * for **Individual** keys (401 Unauthorized). We follow
- * `@electron/notarize`'s `NotaryToolApiKeyCredentials` which types it as
- * optional — the operator decides based on which key class they're using.
- * - APPLE_KEYCHAIN_PROFILE [+ APPLE_KEYCHAIN] (`xcrun notarytool store-credentials`
- * profile; primarily a local-dev convenience)
- */
-
function collectMissing(required) {
return Object.entries(required)
.filter(([, value]) => !value)
@@ -62,13 +25,6 @@ function resolveNotarizeCredentials() {
APPLE_KEYCHAIN,
} = process.env;
- // APPLE_TEAM_ID is intentionally excluded from `hasAnyPassword`. It's not
- // exclusive to password-mode notarization — it's also used for the Keychain
- // ACL anchor and for codesign cert discovery, both of which an
- // Option B (API key) operator may legitimately want set. Treating
- // APPLE_TEAM_ID alone as a password-shape signal would force the operator
- // to choose between team-ID hygiene and using API-key notarization, since
- // having both would trip the multi-shape guard below.
const hasAnyPassword = Boolean(APPLE_ID || APPLE_APP_SPECIFIC_PASSWORD);
const hasAnyApiKey = Boolean(APPLE_API_KEY || APPLE_API_KEY_ID || APPLE_API_ISSUER);
const hasAnyKeychain = Boolean(APPLE_KEYCHAIN_PROFILE || APPLE_KEYCHAIN);
@@ -137,8 +93,6 @@ function resolveNotarizeCredentials() {
};
}
- // hasAnyKeychain — the only required field is APPLE_KEYCHAIN_PROFILE.
- // APPLE_KEYCHAIN alone (without a profile) is operator error.
if (!APPLE_KEYCHAIN_PROFILE) {
throw new Error(
`[afterSign] Partial Apple keychain credentials — missing: APPLE_KEYCHAIN_PROFILE. ` +
@@ -160,9 +114,6 @@ async function verifyFuses(electronBinary, expected) {
try {
wire = await getCurrentFuseWire(electronBinary);
} catch (err) {
- // Phase-annotated so a wire-read failure is distinguishable from a
- // value-mismatch failure — the former points at @electron/fuses or
- // the binary state, the latter points at the signing pipeline.
throw new Error(
`[afterSign] getCurrentFuseWire failed on ${electronBinary}: ${
err instanceof Error ? err.message : String(err)
@@ -200,21 +151,8 @@ export default async function afterSign(context) {
throw new Error(`[afterSign] packed Electron binary not found at ${electronBinary}`);
}
- // Always verify fuses, on EVERY platform (D9) — the paranoid post-flip
- // check runs regardless of whether we're about to notarize/sign. The
- // unsigned darwin path still has an ad-hoc re-sign (via `flipFuses`'
- // `resetAdHocDarwinSignature: true`) and electron-builder may still
- // invoke codesign with `identity=null` between afterPack and afterSign —
- // any of those steps could silently perturb fuse state. On Windows this
- // is the load-bearing guard the header warns about: signtool has shipped
- // silent fuse-clobber regressions (electron-builder #9428), so once Azure
- // Artifact Signing is wired the verify runs after the signature lands.
- // Verify-before-notarize means all paths share the same defense-in-depth
- // guarantee; verify-after-notarize would miss bugs on the unsigned path
- // where local developers exercise the pipeline most.
await verifyFuses(electronBinary, targetFuses);
- // Notarization (and its staple/validate follow-ups) is Apple-only.
if (electronPlatformName !== 'darwin') {
console.log(
`[afterSign] fuse verification done; no notarize step on platform "${electronPlatformName}"`,
@@ -247,11 +185,6 @@ export default async function afterSign(context) {
...credentials.creds,
});
} catch (err) {
- // Attach the credential kind so the operator's first debugging question
- // — "which credential shape was being used?" — is answered in the
- // exception itself, not inferred from secrets config. Structured log
- // transports (CloudWatch, Datadog) capture the Error object, not the
- // console.log preamble above.
throw new Error(
`[afterSign] notarize failed (credential kind: ${credentials.kind}): ${
err instanceof Error ? err.message : String(err)
@@ -262,11 +195,6 @@ export default async function afterSign(context) {
console.log('[afterSign] notarize + staple complete; validating stapled ticket');
try {
- // Capture stdout/stderr explicitly rather than `stdio: 'inherit'`.
- // `inherit` pipes child streams directly to the parent TTY at runtime
- // (visible in GHA logs), but `err.stdout` / `err.stderr` on the thrown
- // exception are `undefined` — the re-thrown Error loses the diagnostic
- // payload for any log scraper that only sees the exception object.
execFileSync('xcrun', ['stapler', 'validate', appPath], {
stdio: ['ignore', 'pipe', 'pipe'],
});
@@ -279,8 +207,6 @@ export default async function afterSign(context) {
err && typeof err === 'object' && 'stdout' in err && err.stdout
? err.stdout.toString().trim()
: '';
- // Echo the captured streams to the parent TTY for human-readable CI log
- // continuity before re-throwing the enriched Error.
if (stdout) console.error(`[afterSign] stapler stdout: ${stdout}`);
if (stderr) console.error(`[afterSign] stapler stderr: ${stderr}`);
throw new Error(
@@ -293,10 +219,6 @@ export default async function afterSign(context) {
);
}
- // Re-verify fuses AFTER notarize+staple. The pre-notarize verify above
- // catches fuse corruption from flipFuses / codesign (unsigned path);
- // this second verify catches any mutation from the notary-ticket staple
- // step — belt-and-suspenders.
await verifyFuses(electronBinary, targetFuses);
console.log('[afterSign] signed + notarized + stapled + fuse-verified successfully');
diff --git a/packages/desktop/scripts/assert-asar-complete.mjs b/packages/desktop/scripts/assert-asar-complete.mjs
index c02e3506c..cc3b452cc 100644
--- a/packages/desktop/scripts/assert-asar-complete.mjs
+++ b/packages/desktop/scripts/assert-asar-complete.mjs
@@ -1,47 +1,11 @@
#!/usr/bin/env node
-/**
- * Effect-level control: the packaged `app.asar` must actually carry the runtime
- * dependencies the main process imports.
- *
- * A packaged Electron app whose asar has no `node_modules` installs fine and
- * then dies on the first bare import, BEFORE `app.ready` — so there is no
- * window, no dialog, and no crash report. From the outside it is
- * indistinguishable from "nothing happened". Every other packaging control we
- * have (an executable exists, the smoke suite passes) stays green through it,
- * because the smoke suite drives the electron-vite `out/` build where the dev
- * `node_modules` are still on disk to resolve against.
- *
- * Reads the asar header directly rather than shelling out to the `asar` CLI:
- * the format is a 16-byte prefix whose last uint32 is the length of a JSON
- * directory listing, which is all we need and costs one read of the first few
- * hundred KB of a ~250 MB file.
- *
- * Usage: node assert-asar-complete.mjs <search-root> [label]
- * <search-root> directory to find app.asar under (e.g. dist-desktop)
- */
import { existsSync, readdirSync, statSync } from 'node:fs';
import { join } from 'node:path';
import { readAsarHeader } from './lib/asar-header.mjs';
-/**
- * Packages asserted present by name. `pino` is the one that actually broke —
- * `desktop-logger` imports it at module scope, so it is the first bare specifier
- * the main process resolves and thus the observed failure. The others are listed
- * so a partial collection (rather than a wholesale omission) still fails.
- * `node-pty` pins the terminal payload on every platform: the win files rules
- * once excluded it wholesale, and a regressed exclude would ship a
- * dead-on-arrival terminal while every other packaging control stays green.
- */
const REQUIRED_PACKAGES = ['pino', 'electron-updater', 'node-pty'];
-/**
- * EVERY asar under the root, not the first one found. A single `electron-builder
- * --win` run with `arch: [x64, arm64]` writes `win-unpacked/` AND
- * `win-arm64-unpacked/`, each with its own `app.asar`; checking only one would
- * let a broken second arch ship. (`--dir` builds the host arch alone, which is
- * why the PR-gate cells see exactly one.)
- */
function findAsars(root) {
if (!existsSync(root)) return [];
const found = [];
@@ -57,7 +21,6 @@ function findAsars(root) {
for (const entry of entries) {
const full = join(dir, entry.name);
if (entry.isFile() && entry.name === 'app.asar') found.push(full);
- // `*-unpacked/` trees mirror the asar's contents and would double the walk.
if (entry.isDirectory() && !entry.name.endsWith('.asar.unpacked')) stack.push(full);
}
}
diff --git a/packages/desktop/scripts/ensure-node-pty-exec.mjs b/packages/desktop/scripts/ensure-node-pty-exec.mjs
index c57f62250..c95e7479e 100644
--- a/packages/desktop/scripts/ensure-node-pty-exec.mjs
+++ b/packages/desktop/scripts/ensure-node-pty-exec.mjs
@@ -3,46 +3,12 @@ import { chmodSync, existsSync, readdirSync, statSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join } from 'node:path';
-/**
- * Make node-pty's prebuilt `spawn-helper` executable.
- *
- * node-pty ships prebuilt binaries under
- * `node-pty/prebuilds/<platform>-<arch>/{pty.node,spawn-helper}`, and the
- * prebuilt `spawn-helper` is mode 0644 — not executable (node-pty#850). Both
- * producers that lay it on disk preserve that non-executable mode — `pnpm install`
- * for the dev tree, electron-builder's asarUnpack for the packed app — so
- * `pty.fork()` dies at runtime with "posix_spawnp failed" and the in-app terminal
- * never spawns a shell.
- *
- * Two call sites re-enforce the executable bit, sharing one chmod primitive:
- * - PACKAGED (`ensureNodePtySpawnHelperExecutable`) — afterPack, against the
- * packed `Contents/Resources/app.asar.unpacked/.../prebuilds` tree, before
- * electron-builder re-signs (the Developer ID signature covers the +x bit).
- * - DEV / CI (`ensureNodePtySpawnHelperExecutableInNodeModules`) — the desktop
- * postinstall, against the real `node_modules/node-pty/prebuilds` tree, so
- * `pnpm run build:desktop` / `dev:electron` / smoke launches get a working
- * terminal without packaging.
- *
- * We ship arm64-only (mac.target), so the darwin-arm64 helper is load-bearing and
- * its absence is a hard error; any other prebuild dirs present get the same
- * treatment defensively.
- */
-
const SHIPPED_ARCH = 'darwin-arm64';
-/** The spawn-helper is a Darwin node-pty prebuild detail. */
export function shouldEnsureNodePtySpawnHelper(platform = process.platform) {
return platform === 'darwin';
}
-/**
- * chmod 0755 every `<arch>/spawn-helper` under a node-pty `prebuilds` directory.
- * Throws if the load-bearing SHIPPED_ARCH helper is absent.
- *
- * @param {string} prebuildsDir absolute path to a `node-pty/prebuilds` directory
- * @param {string} remediation context-specific hint appended to the missing-helper error
- * @returns {string[]} absolute paths of the spawn-helper files made executable
- */
function chmodSpawnHelpersUnderPrebuilds(prebuildsDir, remediation) {
const requiredHelper = join(prebuildsDir, SHIPPED_ARCH, 'spawn-helper');
if (!existsSync(requiredHelper)) {
@@ -63,18 +29,11 @@ function chmodSpawnHelpersUnderPrebuilds(prebuildsDir, remediation) {
return chmodded;
}
-/** Resolve the node-pty package directory the runtime actually loads. */
function resolveNodePtyDir() {
const require = createRequire(import.meta.url);
return dirname(require.resolve('node-pty/package.json'));
}
-/**
- * PACKAGED path (afterPack hook).
- *
- * @param {string} resourcesDir the packed app's `Contents/Resources` directory
- * @returns {string[]} absolute paths of the spawn-helper files made executable
- */
export function ensureNodePtySpawnHelperExecutable(resourcesDir) {
const prebuildsDir = join(
resourcesDir,
@@ -91,17 +50,6 @@ export function ensureNodePtySpawnHelperExecutable(resourcesDir) {
);
}
-/**
- * DEV / CI build+install path (desktop postinstall).
- *
- * `pnpm install` leaves the prebuilt helper non-executable, and the dev build
- * (`pnpm run build:desktop` / `dev:electron`, electron-vite, no afterPack) has no
- * step to fix it. Resolves the same node-pty the runtime loads; the `nodePtyDir`
- * parameter is for tests to point at a fixture.
- *
- * @param {string} [nodePtyDir] node-pty package dir; defaults to the resolved install
- * @returns {string[]} absolute paths of the spawn-helper files made executable
- */
export function ensureNodePtySpawnHelperExecutableInNodeModules(nodePtyDir = resolveNodePtyDir()) {
return chmodSpawnHelpersUnderPrebuilds(
join(nodePtyDir, 'prebuilds'),
@@ -115,16 +63,6 @@ export function ensureNodePtySpawnHelperExecutableInNodeModules(nodePtyDir = res
* @typedef {{ ok: true, chmodded: string[] } | { ok: false, error: Error }} SafeChmodResult
*/
-/**
- * Non-throwing wrapper around {@link ensureNodePtySpawnHelperExecutableInNodeModules}
- * for the desktop postinstall. The postinstall must NEVER fail `pnpm install` over a
- * pathological node-pty layout (a partially-broken install, an absent shipped-arch
- * prebuild) — that would gate the whole monorepo. This converts the throw into a
- * `{ ok: false, error }` result so the caller stays exit-0; the caller owns logging.
- *
- * @param {string} [nodePtyDir] node-pty package dir; defaults to the resolved install
- * @returns {SafeChmodResult}
- */
export function ensureNodePtySpawnHelperExecutableInNodeModulesSafe(nodePtyDir) {
try {
return { ok: true, chmodded: ensureNodePtySpawnHelperExecutableInNodeModules(nodePtyDir) };
diff --git a/packages/desktop/scripts/launch-instances.mjs b/packages/desktop/scripts/launch-instances.mjs
index a4fbb1391..f0a52a1e0 100644
--- a/packages/desktop/scripts/launch-instances.mjs
+++ b/packages/desktop/scripts/launch-instances.mjs
@@ -1,35 +1,4 @@
#!/usr/bin/env node
-/**
- * Launch one or more isolated OpenKnowledge desktop instances in parallel (macOS).
- *
- * A bare second launch of the app can't run: Electron keys its single-instance
- * lock on the `userData` directory (and Chromium storage + recents live there),
- * so the second process fails `requestSingleInstanceLock()` and quits. Giving
- * each instance its own `--user-data-dir` yields a distinct lock AND isolated
- * storage, so N instances coexist. This is the only mechanism that works for the
- * PACKAGED app — `OK_INSTANCE` (a sibling dev-only env knob) is gated to
- * `!app.isPackaged` and does not apply here.
- *
- * Each instance opens its named project by pre-seeding that instance's own
- * `state.json` `lastOpenedProject` — the cold-start restore opens it. (An
- * `openknowledge://` URL in argv only routes via the second-instance path, so it
- * is NOT honored by a fresh primary instance; pre-seeding is the per-instance
- * targetable path. The `state.json` shape mirrors `AppState` in
- * `src/main/state-store.ts` — keep in sync if that schema changes.)
- *
- * Launches are STAGGERED: each instance is given time to acquire its project's
- * `<contentDir>/.ok/local/server.lock` before the next starts. Booting two at
- * the same millisecond races and drops one project to the Navigator.
- *
- * Usage:
- * node scripts/launch-instances.mjs <name>=<projectPath> [<name>=<projectPath> ...]
- * bun run desktop:instances -- work=~/code/proj-a review=~/code/proj-b
- *
- * Flags / env:
- * --app <path> (or OK_DESKTOP_APP) path to the built .app
- * default: dist-desktop/mac-arm64/OpenKnowledge.app (run `bun run build:dir` first)
- * --user-data-root <dir> base dir for per-instance userData (default: ~/.ok/instances)
- */
import { execFileSync, spawn } from 'node:child_process';
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
@@ -75,7 +44,6 @@ function resolveAppPath(flagPath) {
if (!existsSync(abs)) throw new Error(`--app path not found: ${abs}`);
return abs;
}
- // Default: the unsigned local build output, relative to this package.
const pkgRoot = resolve(import.meta.dirname, '..');
const candidate = join(pkgRoot, 'dist-desktop', 'mac-arm64', 'OpenKnowledge.app');
if (!existsSync(candidate)) {
@@ -91,12 +59,9 @@ function resolveAppPath(flagPath) {
function ensureGitRepo(project) {
if (!existsSync(project)) mkdirSync(project, { recursive: true });
if (existsSync(join(project, '.git'))) return;
- // openProject falls back to the Navigator on a non-git folder; init so the
- // project actually opens.
execFileSync('git', ['-C', project, 'init', '-q']);
}
-// Mirrors the required AppState fields in src/main/state-store.ts (schemaVersion 1).
function emptyState() {
return {
recentProjects: [],
@@ -118,15 +83,11 @@ function emptyState() {
function seedState(userDataDir, project, name) {
mkdirSync(userDataDir, { recursive: true });
const statePath = join(userDataDir, 'state.json');
- // Merge into an existing state.json if present so we don't clobber fields this
- // script doesn't know about (forward-compatible with schema additions).
let state = emptyState();
if (existsSync(statePath)) {
try {
state = { ...state, ...JSON.parse(readFileSync(statePath, 'utf-8')) };
- } catch {
- // Corrupt — overwrite with a clean minimal doc.
- }
+ } catch {}
}
const now = new Date().toISOString();
const recents = Array.isArray(state.recentProjects) ? state.recentProjects : [];
@@ -138,8 +99,6 @@ function seedState(userDataDir, project, name) {
}
function launch(appPath, userDataDir) {
- // `open -n` starts a NEW, detached instance that survives this process;
- // `--args` passes the Chromium `--user-data-dir` switch to it.
const child = spawn('open', ['-n', appPath, '--args', `--user-data-dir=${userDataDir}`], {
detached: true,
stdio: 'ignore',
diff --git a/packages/desktop/scripts/lib/asar-header.mjs b/packages/desktop/scripts/lib/asar-header.mjs
index 1f95b5bd7..46665a41d 100644
--- a/packages/desktop/scripts/lib/asar-header.mjs
+++ b/packages/desktop/scripts/lib/asar-header.mjs
@@ -1,9 +1,7 @@
import { closeSync, openSync, readSync } from 'node:fs';
-/** Prevent a corrupt prefix from allocating an attacker-sized buffer. */
export const MAX_ASAR_HEADER_BYTES = 64 * 1024 * 1024;
-/** Read and parse the bounded JSON directory header from an Electron asar. */
export function readAsarHeader(asarPath) {
const fd = openSync(asarPath, 'r');
try {
diff --git a/packages/desktop/scripts/postinstall.mjs b/packages/desktop/scripts/postinstall.mjs
index 5538b4b75..5372028c3 100644
--- a/packages/desktop/scripts/postinstall.mjs
+++ b/packages/desktop/scripts/postinstall.mjs
@@ -1,34 +1,10 @@
#!/usr/bin/env node
-/**
- * Desktop postinstall — two install-producer fix-ups: (1) make node-pty's prebuilt
- * Darwin `spawn-helper` executable for the dev/CI build (the afterPack analog; runs
- * first on macOS), then (2) rebuild native modules (`@parcel/watcher`, etc.) against
- * the pinned Electron Node ABI so packaged + dev loads can `dlopen` the binaries.
- *
- * Agent-first default runs `electron-builder install-app-deps` on every
- * `pnpm install`. Non-desktop contributors opt out via `ELECTRON_SKIP_REBUILD=1` in
- * their shell profile — saves ~150MB of Electron headers on first install and a
- * few seconds on subsequent ones.
- *
- * Keeping this as a Node script (not a raw shell one-liner) so the skip-check
- * runs cross-platform (macOS / Linux / Windows) without shell-syntax surprises.
- */
import { spawn } from 'node:child_process';
import {
ensureNodePtySpawnHelperExecutableInNodeModulesSafe,
shouldEnsureNodePtySpawnHelper,
} from './ensure-node-pty-exec.mjs';
-// node-pty ships its prebuilt `spawn-helper` non-executable (node-pty#850) and
-// `pnpm install` preserves that mode, so the dev/CI build (`pnpm run build:desktop`
-// / `dev:electron`, electron-vite, no afterPack) launches with a terminal that
-// dies "posix_spawnp failed". The packaged `.app` fixes this in afterPack; this is
-// the dev/CI analog at the install producer that strips the bit. It runs FIRST and
-// on Darwin before the ELECTRON_SKIP_REBUILD / CI early-exits below because macOS
-// desktop-smoke is one of the affected environments and the +x bit is
-// independent of the electron-builder native rebuild those guards gate. The Safe
-// wrapper never throws so a pathological node-pty layout can't gate the whole
-// workspace's `pnpm install` (matching this script's install-app-deps stance below).
if (shouldEnsureNodePtySpawnHelper()) {
const spawnHelper = ensureNodePtySpawnHelperExecutableInNodeModulesSafe();
if (spawnHelper.ok) {
@@ -49,14 +25,6 @@ if (process.env.ELECTRON_SKIP_REBUILD === '1') {
process.exit(0);
}
-// GitHub Actions + most CI providers set `CI=true`. We also skip on CI
-// because Linux runners that don't exercise the desktop app can't
-// `install-app-deps` (electron's platform binary isn't guaranteed present,
-// and when it's missing electron-builder errors with "Cannot compute
-// electron version from installed node modules" — that cascades into every
-// downstream typecheck/test/lint job failing at `pnpm install`). Desktop
-// contributors running CI manually can set ELECTRON_SKIP_REBUILD=0 to
-// opt back in — the opt-out is for machines that don't need it.
if (process.env.CI && process.env.ELECTRON_SKIP_REBUILD !== '0') {
console.log(
'[desktop postinstall] CI detected — skipping electron-builder install-app-deps ' +
@@ -65,8 +33,6 @@ if (process.env.CI && process.env.ELECTRON_SKIP_REBUILD !== '0') {
process.exit(0);
}
-// Local desktop dev — run install-app-deps but soften failures to a warning.
-// A broken install shouldn't gate the whole workspace's `pnpm install`.
const child = spawn('electron-builder', ['install-app-deps'], {
stdio: 'inherit',
shell: true,
diff --git a/packages/desktop/scripts/prepare-platform-natives.mjs b/packages/desktop/scripts/prepare-platform-natives.mjs
index 75336a94c..232d3fc07 100644
--- a/packages/desktop/scripts/prepare-platform-natives.mjs
+++ b/packages/desktop/scripts/prepare-platform-natives.mjs
@@ -1,24 +1,4 @@
#!/usr/bin/env node
-/**
- * Force-install the @napi-rs/keyring prebuilt binary packages a Windows or
- * Linux desktop build needs before electron-builder runs.
- *
- * Sibling of `prepare-universal.mjs` (the darwin/universal variant — kept
- * separate so the shipping mac pipeline stays untouched). Same root cause:
- * `@napi-rs/keyring` publishes per-arch binaries as optionalDependencies
- * with `cpu`/`os` constraints, and pnpm installs only the host-matching one.
- * The `win.extraResources` / `linux.extraResources` rules in
- * electron-builder.yml copy BOTH arch packages (x64 + arm64) into
- * `cli/node_modules/`, so a single-arch host must fetch the missing ones
- * from the registry first or the copy rule fails the build.
- *
- * Pulls each missing tarball from registry.npmjs.org and extracts to
- * <repo-root>/node_modules/@napi-rs/keyring-<platform>-<arch>/, matching
- * the layout the package manager produces for the host package. Idempotent: skips when the
- * target dir already has a matching-version package.json.
- *
- * No-op on darwin (use `prepare-universal.mjs` there).
- */
import { execFileSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import { createWriteStream, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
@@ -45,10 +25,6 @@ const HERE = dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = resolve(HERE, '..', '..', '..');
const NAPI_DIR = join(REPO_ROOT, 'node_modules', '@napi-rs');
-// Resolve the target version from the installed wrapper package — it is a
-// plain dependency (no cpu/os constraint) and present on every platform,
-// unlike the host binary package prepare-universal keys off (its name
-// varies with libc on linux, e.g. -gnu vs -musl hosts).
const wrapperPkgJson = join(NAPI_DIR, 'keyring', 'package.json');
if (!existsSync(wrapperPkgJson)) {
console.error(
@@ -58,14 +34,6 @@ if (!existsSync(wrapperPkgJson)) {
}
const version = JSON.parse(readFileSync(wrapperPkgJson, 'utf8')).version;
-/**
- * Expected sha512 integrity for `<pkgName>@<version>` from pnpm-lock.yaml —
- * the registry fetch below deliberately bypasses the package manager (the
- * packages are cpu/os-gated so pnpm won't install them here), so the
- * lockfile's recorded integrity is re-checked by hand. Fail-closed: a
- * package missing from the lockfile means the fetch would be entirely
- * unpinned, which is exactly the supply-chain gap this check closes.
- */
function lockfileIntegrityFor(pkgName, pkgVersion) {
const lockfile = readFileSync(join(REPO_ROOT, 'pnpm-lock.yaml'), 'utf8');
const key = `${pkgName}@${pkgVersion}`;
@@ -128,12 +96,6 @@ for (const suffix of suffixes) {
}
mkdirSync(targetDir, { recursive: true });
- // Extract with bsdtar. On Windows a bare `tar` resolved from a Git-bash
- // PATH is GNU tar, which misreads the absolute `C:\...` tarball path as an
- // rsync-style `host:path` remote and dies with "Cannot connect to C:".
- // Windows 10+ ships bsdtar at System32\tar.exe, which handles drive-letter
- // paths natively — invoke it by absolute path rather than trusting PATH
- // resolution. Linux runners keep plain `tar`.
const tarBin =
process.platform === 'win32'
? join(process.env.SystemRoot || 'C:\\Windows', 'System32', 'tar.exe')
diff --git a/packages/desktop/scripts/prepare-universal.mjs b/packages/desktop/scripts/prepare-universal.mjs
index ee86ce3d5..c30deffde 100644
--- a/packages/desktop/scripts/prepare-universal.mjs
+++ b/packages/desktop/scripts/prepare-universal.mjs
@@ -1,22 +1,4 @@
#!/usr/bin/env node
-/**
- * Force-install @napi-rs/keyring darwin prebuilds for BOTH architectures
- * before electron-builder's universal-DMG merge runs.
- *
- * @napi-rs/keyring publishes per-arch native binaries as optionalDependencies
- * with `cpu`/`os` constraints. Bun (and npm/pnpm) skip optionalDependencies
- * whose cpu/os doesn't match the host. On an arm64 macOS runner only
- * @napi-rs/keyring-darwin-arm64 gets installed; the darwin-x64 binary is
- * missing, and electron-builder's @electron/universal lipo-merge step either
- * errors or hangs waiting for x64 inputs that don't exist.
- *
- * Pulls each missing tarball from registry.npmjs.org and extracts to
- * <repo-root>/node_modules/@napi-rs/keyring-darwin-<arch>/, matching the
- * layout bun produces for the host arch. Idempotent: skips when the target
- * dir already has a matching-version package.json.
- *
- * No-op on non-darwin hosts.
- */
import { execFileSync } from 'node:child_process';
import { createWriteStream, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
diff --git a/packages/desktop/scripts/resolve-electron-binary.mjs b/packages/desktop/scripts/resolve-electron-binary.mjs
index 2702a5050..d6061d1f6 100644
--- a/packages/desktop/scripts/resolve-electron-binary.mjs
+++ b/packages/desktop/scripts/resolve-electron-binary.mjs
@@ -1,18 +1,6 @@
#!/usr/bin/env node
import { join } from 'node:path';
-/**
- * Locate the packed Electron binary inside an electron-builder output dir,
- * per platform. Shared by `afterPack.mjs` (fuse flip) and `afterSign.mjs`
- * (fuse verify) so the two hooks can never disagree about which binary the
- * fuses live in.
- *
- * - darwin: `<out>/<Product>.app/Contents/MacOS/<Product>`
- * - win32: `<out>/<Product>.exe`
- * - linux: `<out>/<executableName>` (electron-builder lowercases the
- * sanitized product name unless `linux.executableName` overrides; the
- * LinuxPackager exposes the resolved value as `packager.executableName`).
- */
export function resolveElectronBinary(electronPlatformName, appOutDir, packager) {
const appName = packager.appInfo.productFilename;
switch (electronPlatformName) {
diff --git a/packages/desktop/scripts/smoke-linux-terminal-package.sh b/packages/desktop/scripts/smoke-linux-terminal-package.sh
index d74f479d1..d2b8a0cce 100755
--- a/packages/desktop/scripts/smoke-linux-terminal-package.sh
+++ b/packages/desktop/scripts/smoke-linux-terminal-package.sh
@@ -1,25 +1,6 @@
#!/usr/bin/env bash
set -euo pipefail
-# One-time pre-ship verification for packaged Linux terminals. Run both Fedora
-# rows on matching native hosts, then run one Debian 11 row to anchor the
-# Electron-inherited glibc generation documented for Linux:
-#
-# ./scripts/smoke-linux-terminal-package.sh \
-# --image fedora:41 --arch x86_64 --package dist-desktop/OpenKnowledge-x86_64.rpm
-# ./scripts/smoke-linux-terminal-package.sh \
-# --image fedora:41 --arch aarch64 --package dist-desktop/OpenKnowledge-aarch64.rpm
-# ./scripts/smoke-linux-terminal-package.sh \
-# --image debian:11 --arch x86_64 --package dist-desktop/OpenKnowledge-amd64.deb
-#
-# These are deliberate one-time package rows, not recurring CI. The recurring
-# rpm metadata guard remains electron-builder-linux-depends-parity.test.ts.
-#
-# Chromium first launches with its normal sandbox. In containers where user
-# namespaces prevent startup, OK_CONTAINER_SANDBOX=auto retries once with
-# --no-sandbox. Set OK_CONTAINER_SANDBOX=require to prohibit that fallback, or
-# OK_CONTAINER_SANDBOX=disable to use --no-sandbox immediately.
-
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd -P)
DRIVER_PATH="$SCRIPT_DIR/smoke-terminal-package-cdp.py"
diff --git a/packages/desktop/scripts/smoke-mock-update.mjs b/packages/desktop/scripts/smoke-mock-update.mjs
index f0a7b0af7..105ee8448 100644
--- a/packages/desktop/scripts/smoke-mock-update.mjs
+++ b/packages/desktop/scripts/smoke-mock-update.mjs
@@ -1,69 +1,4 @@
#!/usr/bin/env node
-/**
- * Dev-mode smoke harness for the auto-updater pipeline.
- *
- * Spins up a local HTTP server that serves a hand-crafted channel manifest
- * (`latest-mac.yml` or `beta-mac.yml`) + a matching fake `.zip` payload with
- * a valid sha512 hash. Exercises electron-updater's `GenericProvider`
- * download path end-to-end, short of the signature-verified Squirrel.Mac
- * swap (which only real signed DMGs can trigger).
- *
- * ## Usage
- *
- * **Standalone server mode (pure node/bun — this script's primary entry):**
- *
- * bun run --cwd packages/desktop smoke:mock-update
- * OK_UPDATER_MOCK_CHANNEL=beta bun run --cwd packages/desktop smoke:mock-update
- *
- * Prints a `[mock-updater] port=<N>` line on stdout, then serves two routes:
- *
- * GET /<channel>-mac.yml → hand-crafted YAML manifest
- * GET /open-knowledge-mock.zip → fake zip bytes matching yml's sha512
- *
- * Exits 0 after observing a successful GET of both routes, OR after 30s
- * timeout (exit 1). Set `MOCK_UPDATE_TIMEOUT_MS` to override the timeout.
- *
- * **Channel selection.** `OK_UPDATER_MOCK_CHANNEL` selects which channel
- * the harness simulates. Valid values: `latest` (default) or `beta`. Other
- * values fail fast with exit 2. Beta runs default the artifact version to
- * `0.4.0-beta.0`, embed `channel: beta` in the manifest body, and write the
- * dev-app-update.yml with the matching channel field — so a paired Electron
- * dev build configured with `autoUpdater.channel = 'beta'` can fetch the
- * beta manifest end-to-end.
- *
- * **Pair with an Electron dev build (the full round-trip):**
- *
- * 1. Terminal A: `bun run --cwd packages/desktop smoke:mock-update -- --keep-alive`
- * Note the port printed — the server keeps serving until Ctrl+C.
- * 2. Terminal B: `OK_UPDATER_FORCE_DEV=1 OK_UPDATER_FEED_URL=http://127.0.0.1:<N> bun run --filter=@inkeep/open-knowledge-desktop dev`
- * 3. Electron's main-process auto-updater hits the local server, downloads
- * the fake zip, and fires `update-downloaded`. Renderer Toast A renders
- * ("Update downloaded" + "Relaunch now") within 2-3 seconds of boot.
- *
- * Without `--keep-alive`, the script exits 0 after its built-in self-test
- * (CI mode — validates HTTP serving + sha512 without waiting for Electron).
- *
- * Uses GenericProvider + setFeedURL via forceDevUpdateConfig. Distinct from the
- * event-stub subclass approach exercised by `tests/integration/auto-updater.test.ts`.
- *
- * ## Why this script doesn't import electron-updater directly
- *
- * electron-updater's `autoUpdater` export is lazily constructed and its
- * platform-specific subclass (MacUpdater, NsisUpdater) requires
- * `require('electron').autoUpdater` at construction time — fails under plain
- * node/bun. The Tier-2 round-trip therefore splits into two processes: the
- * local HTTP server (this script, node/bun) and the Electron dev build
- * (normal `bun run dev --filter=@inkeep/open-knowledge-desktop`).
- *
- * ## Structured log shape
- *
- * [mock-updater] port=<N>
- * [mock-updater] event=start channel=<latest|beta> version=<V>
- * [mock-updater] event=served path=/<channel>-mac.yml status=200
- * [mock-updater] event=served path=/open-knowledge-mock.zip status=200 bytes=<len>
- * [mock-updater] event=manifest-and-zip-served — Electron dev build can verify update-downloaded
- * [mock-updater] event=shutdown reason=<timeout|signal|done>
- */
import { createHash, randomBytes } from 'node:crypto';
import { existsSync, unlinkSync, writeFileSync } from 'node:fs';
@@ -83,39 +18,15 @@ if (!SUPPORTED_CHANNELS.includes(/** @type {any} */ (RAW_CHANNEL))) {
/** @type {'latest' | 'beta'} */
const CHANNEL = /** @type {'latest' | 'beta'} */ (RAW_CHANNEL);
const MANIFEST_NAME = `${CHANNEL}-mac.yml`;
-// Default version per channel; either is overridable via MOCK_UPDATE_VERSION.
-// Beta default carries a real semver prerelease tag so the manifest looks
-// like a release a beta-channel client would actually fetch in the field.
const DEFAULT_VERSION = CHANNEL === 'beta' ? '0.4.0-beta.0' : '0.99.0-mock';
const VERSION = process.env.MOCK_UPDATE_VERSION ?? DEFAULT_VERSION;
const TIMEOUT_MS = Number.parseInt(process.env.MOCK_UPDATE_TIMEOUT_MS ?? '30000', 10);
-/**
- * `--keep-alive` skips the auto-shutdown after self-test and keeps serving
- * until the process is killed (Ctrl+C, SIGTERM). Used for the 2-terminal
- * manual Tier-2 flow where the Electron dev app needs the server to stay up.
- * When keep-alive is set, this script also writes `dev-app-update.yml` next
- * to `packages/desktop/package.json` with the chosen port — electron-updater
- * reads that file at `checkForUpdates()` time. Cleaned up on SIGINT/SIGTERM.
- */
const KEEP_ALIVE = process.argv.includes('--keep-alive');
const __dirname = dirname(fileURLToPath(import.meta.url));
const DESKTOP_ROOT = resolve(__dirname, '..');
const DEV_APP_UPDATE_YML = resolve(DESKTOP_ROOT, 'dev-app-update.yml');
-/**
- * Build a minimal valid .zip archive with a single text file. The zip format
- * has a precise local-file-header + central-directory layout; we emit the
- * smallest valid blob so electron-updater's download-verification + unpack
- * path can round-trip without native zip tooling.
- *
- * Structure:
- * - Local file header + compressed data for "payload.txt"
- * - Central directory entry pointing at the local header
- * - End-of-central-directory record
- *
- * Returns the full byte buffer.
- */
function buildMinimalZip() {
const filename = 'payload.txt';
const contents = Buffer.from(
@@ -123,7 +34,6 @@ function buildMinimalZip() {
'utf-8',
);
const compressed = deflateRawSync(contents);
- // Minimal CRC-32 implementation — zip requires this (crc of uncompressed bytes).
const crcTable = new Uint32Array(256);
for (let n = 0; n < 256; n++) {
let c = n;
@@ -140,71 +50,57 @@ function buildMinimalZip() {
const filenameBuf = Buffer.from(filename, 'utf-8');
- // Local file header (30 bytes + filename)
const localHeader = Buffer.alloc(30);
- localHeader.writeUInt32LE(0x04034b50, 0); // signature
- localHeader.writeUInt16LE(20, 4); // version needed
- localHeader.writeUInt16LE(0, 6); // flags
- localHeader.writeUInt16LE(8, 8); // method: deflate
- localHeader.writeUInt16LE(0, 10); // mtime
- localHeader.writeUInt16LE(0, 12); // mdate
+ localHeader.writeUInt32LE(0x04034b50, 0);
+ localHeader.writeUInt16LE(20, 4);
+ localHeader.writeUInt16LE(0, 6);
+ localHeader.writeUInt16LE(8, 8);
+ localHeader.writeUInt16LE(0, 10);
+ localHeader.writeUInt16LE(0, 12);
localHeader.writeUInt32LE(crc32, 14);
- localHeader.writeUInt32LE(compressed.length, 18); // compressed size
- localHeader.writeUInt32LE(contents.length, 22); // uncompressed size
- localHeader.writeUInt16LE(filenameBuf.length, 26); // filename length
- localHeader.writeUInt16LE(0, 28); // extra length
+ localHeader.writeUInt32LE(compressed.length, 18);
+ localHeader.writeUInt32LE(contents.length, 22);
+ localHeader.writeUInt16LE(filenameBuf.length, 26);
+ localHeader.writeUInt16LE(0, 28);
- // Central directory file header (46 bytes + filename)
const cdHeader = Buffer.alloc(46);
- cdHeader.writeUInt32LE(0x02014b50, 0); // signature
- cdHeader.writeUInt16LE(0x033f, 4); // version made by
- cdHeader.writeUInt16LE(20, 6); // version needed
- cdHeader.writeUInt16LE(0, 8); // flags
- cdHeader.writeUInt16LE(8, 10); // method
- cdHeader.writeUInt16LE(0, 12); // mtime
- cdHeader.writeUInt16LE(0, 14); // mdate
+ cdHeader.writeUInt32LE(0x02014b50, 0);
+ cdHeader.writeUInt16LE(0x033f, 4);
+ cdHeader.writeUInt16LE(20, 6);
+ cdHeader.writeUInt16LE(0, 8);
+ cdHeader.writeUInt16LE(8, 10);
+ cdHeader.writeUInt16LE(0, 12);
+ cdHeader.writeUInt16LE(0, 14);
cdHeader.writeUInt32LE(crc32, 16);
cdHeader.writeUInt32LE(compressed.length, 20);
cdHeader.writeUInt32LE(contents.length, 24);
- cdHeader.writeUInt16LE(filenameBuf.length, 28); // filename length
- cdHeader.writeUInt16LE(0, 30); // extra length
- cdHeader.writeUInt16LE(0, 32); // comment length
- cdHeader.writeUInt16LE(0, 34); // disk number
- cdHeader.writeUInt16LE(0, 36); // internal attrs
- cdHeader.writeUInt32LE(0, 38); // external attrs
- cdHeader.writeUInt32LE(0, 42); // local header offset
+ cdHeader.writeUInt16LE(filenameBuf.length, 28);
+ cdHeader.writeUInt16LE(0, 30);
+ cdHeader.writeUInt16LE(0, 32);
+ cdHeader.writeUInt16LE(0, 34);
+ cdHeader.writeUInt16LE(0, 36);
+ cdHeader.writeUInt32LE(0, 38);
+ cdHeader.writeUInt32LE(0, 42);
- // End of central directory (22 bytes)
const eocd = Buffer.alloc(22);
- eocd.writeUInt32LE(0x06054b50, 0); // signature
- eocd.writeUInt16LE(0, 4); // disk number
- eocd.writeUInt16LE(0, 6); // disk with cd
- eocd.writeUInt16LE(1, 8); // entries on this disk
- eocd.writeUInt16LE(1, 10); // total entries
+ eocd.writeUInt32LE(0x06054b50, 0);
+ eocd.writeUInt16LE(0, 4);
+ eocd.writeUInt16LE(0, 6);
+ eocd.writeUInt16LE(1, 8);
+ eocd.writeUInt16LE(1, 10);
const cdSize = cdHeader.length + filenameBuf.length;
const cdOffset = localHeader.length + filenameBuf.length + compressed.length;
eocd.writeUInt32LE(cdSize, 12);
eocd.writeUInt32LE(cdOffset, 16);
- eocd.writeUInt16LE(0, 20); // comment length
+ eocd.writeUInt16LE(0, 20);
return Buffer.concat([localHeader, filenameBuf, compressed, cdHeader, filenameBuf, eocd]);
}
-/**
- * Compute the sha512 hash of a buffer in the base64 format electron-updater
- * expects inside `latest-mac.yml`'s `sha512:` field.
- */
function sha512Base64(buf) {
return createHash('sha512').update(buf).digest('base64');
}
-/**
- * Hand-craft a channel manifest (`{channel}-mac.yml`) with a single `.zip`
- * entry. Matches the shape electron-updater's Provider emits — enough fields
- * for GenericProvider to parse and enqueue the download. The `channel` field
- * is omitted for `latest` (matches electron-builder's default-channel output)
- * and present for `beta` (so a beta-channel client can verify routing).
- */
function buildMacYml({ version, channel, zipName, zipBytes, releaseDate }) {
const sha = sha512Base64(zipBytes);
const lines = [
@@ -235,17 +131,11 @@ async function main() {
releaseDate: new Date().toISOString(),
});
- // Unique request-correlation id for log noise — helps distinguish runs when
- // the harness is looped by Playwright or CI.
const runId = randomBytes(4).toString('hex');
- /** Tracks which endpoints have been served so we know when "both served". */
const served = { manifest: false, zip: false };
const server = createServer((req, res) => {
- // electron-updater appends `?noCache=<random>` to every request to bypass
- // HTTP-layer caches. Strip the query string before route-matching so the
- // exact-path checks still work (and so log lines stay readable).
const rawUrl = req.url ?? '/';
const pathname = rawUrl.split('?', 1)[0] ?? rawUrl;
if (pathname === `/${MANIFEST_NAME}`) {
@@ -273,9 +163,6 @@ async function main() {
console.log(
'[mock-updater] event=manifest-and-zip-served — Electron dev build can verify update-downloaded',
);
- // Keep the server alive so repeat GETs during electron-updater retries
- // also succeed — but signal "primary goal reached" via stdout so any
- // orchestrator (Playwright, CI) can advance.
}
});
@@ -299,17 +186,12 @@ async function main() {
const port = await started;
- // Auto-shutdown after a successful smoke OR the configured timeout. Allows
- // tests + CI to invoke the script without hanging the pipeline.
let shutdownReason = 'timeout';
const timeoutHandle = setTimeout(() => {
console.log(`[mock-updater] event=shutdown reason=${shutdownReason} port=${port}`);
server.close(() => process.exit(shutdownReason === 'done' ? 0 : 1));
}, TIMEOUT_MS);
- // Quick self-test: fetch /latest-mac.yml + /<zipName> against our own
- // server. Proves the HTTP plumbing works end-to-end before we sit waiting
- // for the Electron side. No electron-updater dependency.
try {
const base = `http://127.0.0.1:${port}`;
const manifestResp = await fetch(`${base}/${MANIFEST_NAME}`);
@@ -329,20 +211,7 @@ async function main() {
if (computed !== expected) throw new Error(`sha512 mismatch: ${computed} vs ${expected}`);
console.log('[mock-updater] event=self-test-ok');
if (KEEP_ALIVE) {
- // Manual Tier-2 flow: keep serving until Ctrl+C so the Electron dev
- // app can hit us as many times as its periodic check fires. Clear the
- // self-test timeout so we don't auto-exit; SIGINT/SIGTERM handlers
- // below take over.
clearTimeout(timeoutHandle);
- // Write dev-app-update.yml so electron-updater's config-file
- // path (at app.getAppPath()) picks up our port. Without this, the
- // updater reads its default `publish: github` block and tries to hit
- // GitHub Releases. The dev app only needs OK_UPDATER_FORCE_DEV=1 —
- // the file itself routes traffic here.
- // For beta we set `channel: beta` so any client picking up this file
- // routes its GenericProvider to /beta-mac.yml. For latest we omit the
- // field — electron-updater's default channel is `latest`, so the
- // request goes to /latest-mac.yml without an explicit override.
const channelLine = CHANNEL === 'latest' ? '' : `channel: ${CHANNEL}\n`;
writeFileSync(
DEV_APP_UPDATE_YML,
@@ -366,10 +235,6 @@ async function main() {
server.close(() => process.exit(2));
}
- // Graceful signal handling so `Ctrl+C` exits 0 AND cleans up the dev-
- // app-update.yml we wrote at keep-alive start. Without cleanup, a
- // stale .yml pointing at a dead port poisons future `bun run dev`
- // sessions (first `checkForUpdates()` hangs until its internal timeout).
const handleSignal = (sig) => {
shutdownReason = `signal-${sig}`;
console.log(`[mock-updater] event=shutdown reason=${shutdownReason} port=${port}`);
diff --git a/packages/desktop/scripts/smoke-windows-terminal-package.mjs b/packages/desktop/scripts/smoke-windows-terminal-package.mjs
index 4f0f409c7..8e18eaa1f 100644
--- a/packages/desktop/scripts/smoke-windows-terminal-package.mjs
+++ b/packages/desktop/scripts/smoke-windows-terminal-package.mjs
@@ -78,9 +78,6 @@ export function runWindowsPackageTerminalSmoke({
const smokeRoot = mkdtempSync(join(tmpdir(), 'ok-packaged-win-pty-'));
const logPath = join(smokeRoot, 'openknowledge.log');
- // This headless ABI probe pins ComSpec/cmd for deterministic shell-family
- // coverage because discovery varies across Windows runners. The required
- // real-PTY harness separately covers the PowerShell structured-launch path.
const { projectDir, userDataDir } = seedWindowsPtySmokeProject(smokeRoot, shellPath);
const logFd = openSync(logPath, 'w');
let app = null;
@@ -116,9 +113,7 @@ export function runWindowsPackageTerminalSmoke({
}
try {
closeSync(logFd);
- } catch {
- // The failure path closes the descriptor before printing the log.
- }
+ } catch {}
try {
rmSync(smokeRoot, { recursive: true, force: true });
} catch (error) {
diff --git a/packages/desktop/scripts/stage-parcel-watcher.mjs b/packages/desktop/scripts/stage-parcel-watcher.mjs
index dd35b61ea..e90c44cd8 100644
--- a/packages/desktop/scripts/stage-parcel-watcher.mjs
+++ b/packages/desktop/scripts/stage-parcel-watcher.mjs
@@ -1,39 +1,4 @@
#!/usr/bin/env node
-/**
- * Stage @parcel/watcher + its runtime tree for the bundled CLI.
- *
- * The packaged app spawns `ok start` from `Resources/cli/`, whose ESM/CJS
- * resolver walks `cli/dist → cli → Resources → …` and NEVER reaches
- * `app.asar.unpacked/node_modules/` (the same resolver-scope wall the
- * @napi-rs/keyring + native-config copies already work around). So the app's
- * asarUnpack copy of @parcel/watcher is invisible to the CLI: at boot
- * `import('@parcel/watcher')` throws `Cannot find package`, the file watcher
- * degrades to chokidar, and external edits under content subfolders stop
- * reaching the server until a restart. inkeep/open-knowledge#760.
- *
- * Fix: give the CLI its own copy under `cli/node_modules/`. This script stages
- * that copy into `build/parcel-watcher-staging/node_modules/`; electron-builder
- * copies the staged tree via a single `extraResources` rule.
- *
- * Resolver-accurate on purpose. @parcel/watcher's wrapper.js `require()`s
- * picomatch/is-glob/is-extglob and index.js `require()`s detect-libc (linux)
- * plus the per-arch `@parcel/watcher-<platform>-<arch>` binary. Those runtime
- * deps are deliberately NOT flat-root-hoisted (`.npmrc`) — the tree carries
- * both picomatch v2 and v4, so a static `from: node_modules/picomatch` rule
- * could ship the wrong major. We resolve each dep the way Node's runtime
- * `require()` does, from @parcel/watcher's own package dir, so the staged
- * versions are exactly what the wrapper loads.
- *
- * Cross-arch: pnpm installs only the host-matching `@parcel/watcher-*` binary,
- * and we stage whatever binary packages are present. The mac DMG is arm64-only
- * (matches the arm64-only host), so its arm64 binary is always present and the
- * fix is complete there. Linux builds each arch on a runner of that arch, so
- * both debs get their matching binary. Windows still packages both arches from
- * one x64 host, so its arm64 installer stages only the x64 binary and falls
- * back to chokidar (now subfolder-correct, #760) — degraded, not broken.
- * Fetching the missing-arch parcel binaries the way
- * `prepare-platform-natives.mjs` does for keyring is a follow-up.
- */
import { cpSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
import { createRequire } from 'node:module';
import { dirname, join, resolve } from 'node:path';
@@ -44,16 +9,8 @@ const DESKTOP_ROOT = resolve(HERE, '..');
const REPO_ROOT = resolve(DESKTOP_ROOT, '..', '..');
const STAGING = join(DESKTOP_ROOT, 'build', 'parcel-watcher-staging', 'node_modules');
-/** Runtime JS deps @parcel/watcher `require()`s. node-addon-api is headers-only. */
const RUNTIME_DEPS = ['picomatch', 'is-glob', 'is-extglob', 'detect-libc'];
-/**
- * Candidate per-arch binary packages for OUR build targets — mac (arm64/x64),
- * win (x64/arm64), linux (x64/arm64). We stage whichever are present rather
- * than hardcoding one target. @parcel/watcher also publishes musl and 32-bit
- * `linux-arm` variants; those are intentionally omitted — Electron desktop
- * ships glibc-only and we build no 32-bit-arm artifact, so they'd never load.
- */
const PREBUILD_SUFFIXES = [
'darwin-arm64',
'darwin-x64',
@@ -65,7 +22,6 @@ const PREBUILD_SUFFIXES = [
const requireFromRepo = createRequire(join(REPO_ROOT, 'noop.js'));
-/** Resolve a package's dir the way Node's `require()` does (pnpm-isolation-safe). */
function resolvePkgDir(requireFrom, name) {
try {
return dirname(requireFrom.resolve(`${name}/package.json`));
@@ -82,15 +38,11 @@ if (!parcelDir) {
process.exit(1);
}
const parcelVersion = JSON.parse(readFileSync(join(parcelDir, 'package.json'), 'utf8')).version;
-// Resolve the wrapper's own deps from ITS package dir so we copy the exact
-// versions it loads (picomatch v4, not the v2 elsewhere in the tree).
const requireFromParcel = createRequire(join(parcelDir, 'package.json'));
-// Fresh staging tree each run — idempotent and never ships a stale version.
rmSync(dirname(STAGING), { recursive: true, force: true });
mkdirSync(STAGING, { recursive: true });
-/** Copy a resolved package dir into the staging tree, filtering to runtime files. */
function stagePackage(name, srcDir, { runtimeFilesOnly = false } = {}) {
const dest = join(STAGING, name);
mkdirSync(dirname(dest), { recursive: true });
@@ -99,10 +51,6 @@ function stagePackage(name, srcDir, { runtimeFilesOnly = false } = {}) {
dereference: true,
filter: (src) => {
if (!runtimeFilesOnly) return true;
- // Drop the C++ sources / gyp / prebuild scratch @parcel/watcher publishes
- // — dead weight in the app, none of it is loaded at runtime. cpSync hands
- // the filter native-separator paths, so split on both `/` and `\` or the
- // exclusion silently no-ops on Windows builds.
const rel = src.slice(srcDir.length + 1);
const top = rel.split(/[\\/]/)[0];
return top !== 'src' && top !== 'build' && top !== 'prebuilds' && top !== 'binding.gyp';
@@ -117,7 +65,6 @@ stagePackage('@parcel/watcher', parcelDir, { runtimeFilesOnly: true });
for (const dep of RUNTIME_DEPS) {
const dir = resolvePkgDir(requireFromParcel, dep);
if (!dir) {
- // detect-libc is only require()d on linux; the others are unconditional.
if (dep === 'detect-libc') {
console.log(`[stage-parcel-watcher] ${dep} not resolvable — skipping (linux-only dep)`);
continue;
diff --git a/packages/desktop/scripts/target-fuses.mjs b/packages/desktop/scripts/target-fuses.mjs
index af0bd40a8..6a4578fdc 100644
--- a/packages/desktop/scripts/target-fuses.mjs
+++ b/packages/desktop/scripts/target-fuses.mjs
@@ -1,54 +1,6 @@
#!/usr/bin/env node
import { FuseState, FuseV1Options } from '@electron/fuses';
-/**
- * Canonical fuse configuration. This is the single source of
- * truth for both `afterPack.mjs` (flip) and `afterSign.mjs` (verify).
- * Flip-time and verify-time must compare against the same map — any
- * drift means the paranoid post-sign check silently passes on values the
- * flip didn't actually set.
- *
- * Keys are `FuseV1Options` indices (numeric). Values are booleans (true =
- * enable, false = disable). The verifier maps boolean → `FuseState.ENABLE` /
- * `FuseState.DISABLE` via `expectedFuseState()` and then compares raw
- * FuseState values — never collapses to booleans. This is load-bearing
- * because `FuseState` has four values (DISABLE, ENABLE, REMOVED, INHERIT);
- * a boolean collapse maps REMOVED/INHERIT to `false` and silently accepts
- * fuses that should have been explicitly DISABLE.
- */
-// RunAsNode is ENABLED.
-//
-// The bundled `ok.sh` wrapper's `ELECTRON_RUN_AS_NODE=1 "$ELECTRON" "$CLI" …`
-// invocation requires this fuse to be enabled in packaged builds — with the
-// fuse disabled, Electron silently ignores the env var and launches the GUI
-// instead of executing the CLI. That would break the entire CLI-on-PATH
-// + first-launch MCP wiring path in the packaged `.app`. VS Code, Atom, and
-// the Electron-as-Node-host pattern all depend on RunAsNode
-// being enabled for the same reason.
-//
-// Defense-in-depth retained:
-// - `OnlyLoadAppFromAsar` + `EnableEmbeddedAsarIntegrityValidation` keep
-// the asar-loaded renderer + main scripts integrity-checked.
-// - `EnableNodeOptionsEnvironmentVariable` stays DISABLED so a hostile
-// `NODE_OPTIONS` in the user's shell can't inject `--require` into the
-// Electron-as-Node invocation. The wrapper also re-exports user-supplied
-// `NODE_OPTIONS` as `OK_NODE_OPTIONS` then unsets it, double-guarding.
-// - Post-sign `@electron/fuses read` verification (afterSign.mjs) still
-// diffs actual vs expected against this map — drift fails the release
-// pipeline.
-// - Bundle-modification attacks require admin write access to /Applications
-// (already a full-compromise scenario). Gatekeeper notarization ticket
-// validates on download (quarantine bit path); local tampering is out of
-// scope for the code-signing threat model.
-// EnableCookieEncryption is DISABLED. Audit found exactly one cookie in the
-// packaged Cookies SQLite store — shadcn's `sidebar_state=true|false`
-// open/closed flag set from a file:// page. file:// cookies have
-// `is_secure: 0` so Chromium's cookie-encryption path never engages on
-// them (it gates on is_secure: 1). The fuse-on path was a no-op for our
-// actual cookie traffic while triggering a Keychain prompt at every
-// first launch — defense-in-depth that defended nothing. Re-enable when
-// a feature actually stores a secret in a cookie (would coincide with
-// adding a webview to a third-party service).
export const targetFuses = {
[FuseV1Options.RunAsNode]: true,
[FuseV1Options.EnableCookieEncryption]: false,
@@ -58,10 +10,6 @@ export const targetFuses = {
[FuseV1Options.OnlyLoadAppFromAsar]: true,
};
-/**
- * Human-readable name for a `FuseState` value. Used in verifier error
- * messages so `expected ENABLE, got REMOVED` beats `expected 49, got 114`.
- */
export function fuseStateName(state) {
switch (state) {
case FuseState.DISABLE:
@@ -77,12 +25,6 @@ export function fuseStateName(state) {
}
}
-/**
- * Map the canonical boolean expectation to the `FuseState` the post-sign
- * verifier must see. `true` → `FuseState.ENABLE`, `false` → `FuseState.DISABLE`.
- * Any other observed state (REMOVED, INHERIT) is a mismatch — the signing
- * pipeline should not leave fuses in those states.
- */
export function expectedFuseState(expectedValue) {
return expectedValue ? FuseState.ENABLE : FuseState.DISABLE;
}
diff --git a/packages/desktop/src/main/index.ts b/packages/desktop/src/main/index.ts
index 846d2ab5e..07ac071e5 100644
--- a/packages/desktop/src/main/index.ts
+++ b/packages/desktop/src/main/index.ts
@@ -5536,10 +5536,10 @@ function installDockIcon(instanceLabel: string | null) {
if (process.platform !== 'darwin') return;
if (app.isPackaged) return;
/*
- * UPSTREAM(electron/electron#3391): macOS reads the Dock tile name from the
- * running bundle's Info.plist — Electron's own for an unpackaged app — and
- * `app.setName()` does not reach it. A badge is the only runtime way to put
- * an instance label on the Dock icon.
+ * UPSTREAM([email protected]): an unpackaged app runs out of Electron's own
+ * bundle, so macOS reads the Dock tile name from that Info.plist and
+ * `app.setName()` cannot reach it. A badge is the only runtime way to put an
+ * instance label on the Dock icon.
*/
if (instanceLabel) {
try {
diff --git a/packages/desktop/src/main/shell-allowlist.ts b/packages/desktop/src/main/shell-allowlist.ts
index 89ccd79e1..31a0d3b79 100644
--- a/packages/desktop/src/main/shell-allowlist.ts
+++ b/packages/desktop/src/main/shell-allowlist.ts
@@ -5,30 +5,23 @@ export const ALLOWED_SCHEMES: ReadonlySet<string> = new Set([
'openknowledge:',
/**
- * Claude Desktop unified app (Chat + Cowork + Code).
- * OK emits two shapes (single-encoded per `packages/core/src/handoff/claude-url.ts`):
- * claude://<mode>/new?folder=<enc> (doc-scoped: cwd-only, agent grounds via OK MCP per precedent #25)
- * claude://<mode>/new?q=<enc>&folder=<enc> (project-scoped: empty-state cards)
- * `<mode>` is `cowork` or `code`. No other paths.
+ * Claude Desktop unified app. OK emits `claude://<mode>/new?folder=<enc>` (doc-scoped) and
+ * `claude://<mode>/new?q=<enc>&folder=<enc>` (project-scoped), `<mode>` being `cowork` or `code`;
+ * the doc-scoped shape is cwd-only and the agent grounds via OK MCP (precedent #60).
*/
'claude:',
/**
- * OpenAI Codex Desktop.
* OK emits two shapes (single-encoded per `packages/core/src/handoff/codex-url.ts`):
- * codex://new?path=<enc> (doc-scoped: cwd-only, agent grounds via OK MCP per precedent #25)
- * codex://new?prompt=<enc>&path=<enc> (project-scoped: empty-state cards)
- * No other paths.
+ * codex://new?path=<enc> (doc-scoped: cwd-only, agent grounds via OK MCP per precedent #60)
+ * codex://new?prompt=<enc>&path=<enc> (project-scoped: empty-state cards) No other paths.
*/
'codex:',
/**
- * Cursor IDE.
- * OK emits two shapes (per `packages/core/src/handoff/cursor-url.ts`):
- * cursor://anysphere.cursor-deeplink/prompt?workspace=<enc>&mode=agent (doc-scoped: cwd-only, agent grounds via OK MCP per precedent #25)
- * cursor://anysphere.cursor-deeplink/prompt?text=<double-enc>&workspace=<enc>&mode=agent (project-scoped: empty-state cards)
- * `text=` is double-encoded per the two-pass-decode behavior.
- * No other paths.
+ * Cursor IDE. OK emits `cursor://anysphere.cursor-deeplink/prompt?workspace=<enc>&mode=agent`
+ * (doc-scoped, cwd-only, the agent grounds via OK MCP per precedent #60) and the same URL with a
+ * double-encoded `text=` for project-scoped cards. No other paths.
*/
'cursor:',
]);
diff --git a/packages/desktop/src/main/url-scheme.ts b/packages/desktop/src/main/url-scheme.ts
index 3efc67a41..fb7409f6b 100644
--- a/packages/desktop/src/main/url-scheme.ts
+++ b/packages/desktop/src/main/url-scheme.ts
@@ -1,43 +1,13 @@
/**
- * `openknowledge://` deep-link URL scheme — parser + runtime handler.
- *
- * Public surfaces in this module:
- * - Pure parsers — `parseOpenKnowledgeUrl` (`open` host, document deep
- * links), `parseShareUrl` (`share` host + `openknowledge.ai` universal
- * links), `parseScreenUrl` (`screen` host, named-screen deep links). No
- * Electron import at module top, so unit tests exercise them without a real
- * Electron runtime (precedent #4 — shared computation, per-surface render).
- * - `registerProtocolHandler(deps)` — wires `app.on('open-url', ...)` +
- * `app.on('second-instance', ...)`, scans `process.argv` for cold-start
- * CLI-launch delivery, and implements the VS Code queue-then-flush
- * pattern so macOS cold-start Apple Events that fire before `whenReady`
- * are never lost.
- *
- * **Caller contract:** `app.requestSingleInstanceLock()` MUST be acquired by
- * the caller BEFORE `registerProtocolHandler` runs. Without the lock, the
- * `second-instance` event cannot fire (Electron only dispatches it on the
- * primary when a secondary invocation relinquishes the lock), so the
- * documented "CLI launch with argv delivery" path is silently dead. The
- * current call site is `packages/desktop/src/main/index.ts`, gated on
- * `GOT_SINGLE_INSTANCE_LOCK`.
- *
- * Validation layers (URL shape: `openknowledge://open?project=<abs>&doc=<name>`):
- * 1. Reject null bytes anywhere in the raw input (`\x00`, `%00`).
- * 2. Protocol must be `openknowledge:`; host must be `open`.
- * 3. `project` + `doc` required; each URL-decoded before path checks.
- * 4. `project` must be absolute AND must not contain `..` segments after
- * `path.normalize()` — `path.resolve` would silently flatten `../../etc/x`
- * to `/etc/x`, so we reject ANY `..` segment in the decoded path.
- * 5. `doc` must be a relative in-project name — reject any `..` segment (so
- * `a/../b`, `../a`, and `..` all fail) and reject Windows `\` separators.
- * `/` IS allowed as a segment separator — nested docNames like
- * `notes/meeting-2026` are the common MCP producer shape (see
- * `packages/cli/src/mcp/tools/write-document.ts:31` + `preview-url.ts:183`),
- * and the renderer round-trips them cleanly via `encodeURIComponent(doc)`
- * + `docNameFromHash` (`packages/app/src/lib/doc-hash.ts:14`).
- *
- * URL shape is fixed by an upstream contract; this module is downstream of it —
- * changes must be made there, not here.
+ * `openknowledge://` deep-link scheme. The parsers keep no Electron import at module top, so unit
+ * tests exercise them without a real runtime (precedent #4, shared computation with per-surface
+ * rendering); `registerProtocolHandler` adds the cold-start queue-then-flush path.
+ */
+
+/**
+ * STOP: the caller must acquire `app.requestSingleInstanceLock()` before `registerProtocolHandler`
+ * runs. Without the lock Electron never dispatches `second-instance`, so the CLI-launch argv
+ * delivery path is silently dead. The call site is `packages/desktop/src/main/index.ts`.
*/
import { isAbsolute, resolve } from 'node:path';
diff --git a/packages/desktop/tests/integration/no-loosely-typed-webcontents-ipc.test.ts b/packages/desktop/tests/integration/no-loosely-typed-webcontents-ipc.test.ts
index b8cfa4a6c..1a713951d 100644
--- a/packages/desktop/tests/integration/no-loosely-typed-webcontents-ipc.test.ts
+++ b/packages/desktop/tests/integration/no-loosely-typed-webcontents-ipc.test.ts
@@ -1,22 +1,4 @@
-/**
- * IPC discipline enforcement — `no-loosely-typed-webcontents-ipc` oxlint rule.
- *
- * Rule: `lint-plugins/ok-rules/rules/no-loosely-typed-webcontents-ipc.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/no-loosely-typed-webcontents-ipc.fixture.tsx`
- *
- * Per precedent #42 (custom lint enforcement is oxlint JS-plugin rules) + precedent
- * #14 (IPC discipline). The fixture pairs 6 positive cases (one per banned
- * primitive) with 4 negative cases (adjacent methods on the same objects +
- * bare-function with the same name); the test asserts the rule fires
- * exactly 6 times.
- *
- * Exact equality (`toBe(6)`) catches drift in both directions:
- * - false-negative: a weakened pattern drops below 6 → fails
- * - false-positive: a widened pattern fires on a negative case → above 6 → fails
- *
- * Real input → public
- * interface (`oxlintFixtureArgs()` → `pnpm exec oxlint`) → observable outcome (diagnostic count).
- */
+/** The `no-loosely-typed-webcontents-ipc` oxlint rule fixture test, per precedent #42. */
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
diff --git a/packages/desktop/tests/integration/no-resolved-value-theme-source.test.ts b/packages/desktop/tests/integration/no-resolved-value-theme-source.test.ts
index 1be927944..b640ac6b8 100644
--- a/packages/desktop/tests/integration/no-resolved-value-theme-source.test.ts
+++ b/packages/desktop/tests/integration/no-resolved-value-theme-source.test.ts
@@ -1,26 +1,4 @@
-/**
- * 1-way theme contract — `no-resolved-value-theme-source` oxlint rule.
- *
- * Rule: `lint-plugins/ok-rules/rules/no-resolved-value-theme-source.mjs`
- * Fixture: `lint-plugins/ok-rules/__fixtures__/no-resolved-value-theme-source.fixture.tsx`
- *
- * Per precedent #42, oxlint rules are the canonical custom-enforcement
- * mechanism. This test mirrors the shape codified in precedent #42's
- * authoring template: shell out to `pnpm exec oxlint` on a fixture file
- * with deliberate violations + clean usage; assert exact diagnostic count.
- *
- * Exact-equality assertion (`toBe(3)`) catches BOTH directions of drift:
- * - false-negative: a weakened pattern that no longer fires on a positive
- * case → count drops below 3 → test fails
- * - false-positive: a widened pattern that fires on one of the fixture's
- * 4 negative cases → count rises above 3 → test fails
- *
- * The latter is the asymmetric-coverage property `toBeGreaterThanOrEqual`
- * lacks; it's why fixture design pairs positive cases with negative ones.
- *
- * Pattern C test: real input → public
- * interface (`oxlintFixtureArgs()` → `pnpm exec oxlint`) → observable outcome (diagnostic count).
- */
+/** The `no-resolved-value-theme-source` oxlint rule fixture test, per precedent #42. */
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
diff --git a/packages/desktop/tests/unit/packaged-report-path.test.mjs b/packages/desktop/tests/unit/packaged-report-path.test.mjs
index b0f166ef7..ae98d33a0 100644
--- a/packages/desktop/tests/unit/packaged-report-path.test.mjs
+++ b/packages/desktop/tests/unit/packaged-report-path.test.mjs
@@ -3,33 +3,12 @@ import { describe, expect, test } from 'vitest';
import { PACKAGED_REPORT } from '../../../../.github/scripts/smoke-packaged-dmg.mjs';
import { PACKAGED_JSON_REPORT_PATH } from '../../playwright.packaged.config.ts';
-/**
- * The release driver hardcodes the packaged report path; the config owns it.
- * Nothing in the type system relates the two, and the release workflow overlays
- * the driver while pinning the config to a tag, so they can move apart.
- *
- * The trap is specific: per-test ARTIFACTS go to `test-results-packaged/` while
- * the JSON report deliberately stays in `test-results/`, which makes "align the
- * driver with the artifact tree" a plausible and wrong edit.
- *
- * This lives in `packages/desktop/tests/unit/` because both values are real
- * here — the config is imported by `playwright-packaged-config.test.ts` in this
- * directory, and `verify-native-config-driver.test.mjs` beside it already
- * reaches a `.mjs` driver four levels up. Comparing values rather than reading
- * either as source keeps the guard blind to formatting: hoisting a literal into
- * a call, a template literal, or a type annotation changes no path and must not
- * fail this.
- */
describe('packaged report path', () => {
test('the release driver and the Playwright config name the same file', () => {
- // `join` yields the platform separator; the config declares POSIX.
expect(PACKAGED_REPORT.split(sep).join('/')).toBe(PACKAGED_JSON_REPORT_PATH);
});
test('and that file is the one the workflow reads', () => {
- // A coordinated rename of both sides would satisfy the equality above while
- // leaving the third copy — hardcoded in the desktop-smoke vacuity step —
- // pointing at a report nobody writes.
expect(PACKAGED_JSON_REPORT_PATH).toBe('test-results/desktop-smoke-packaged-results.json');
});
});
diff --git a/packages/desktop/tests/unit/verify-keyring-driver.test.mjs b/packages/desktop/tests/unit/verify-keyring-driver.test.mjs
index c5d05623d..3eb52b77b 100644
--- a/packages/desktop/tests/unit/verify-keyring-driver.test.mjs
+++ b/packages/desktop/tests/unit/verify-keyring-driver.test.mjs
@@ -65,11 +65,6 @@ describe('readSmokeResult', () => {
});
});
-/**
- * Build a fake child-process that exits synchronously with configured
- * exit code + stderr. The `spawn` deps-injection lets us drive the driver
- * without an actual Electron binary.
- */
function fakeSpawn({ exitCode = 0, stderr = '', delayMs = 0 } = {}) {
return () => {
const child = new EventEmitter();
@@ -132,7 +127,6 @@ describe('runDriver (full orchestration)', () => {
test('exit 2: timeout kills child + surfaces stderr tail', async () => {
const deps = fakeDeps({
spawn: fakeSpawn({ exitCode: null, delayMs: 10 }),
- // Short injected timeout
timeoutMs: 5,
});
const code = await runDriver(['node', 'script', '/tmp/app.app'], deps);
@@ -149,9 +143,6 @@ describe('runDriver (full orchestration)', () => {
const code = await runDriver(['node', 'script', '/tmp/app.app'], deps);
expect(code).toBe(3);
const errOut = deps.messages.stderr.join('');
- // Exit-3 stderr must name BOTH shapes collapsed into this branch —
- // "exited before the smoke finished" (pre-smoke crash) and "output write
- // failed" (smoke ran but writeSmokeResult threw).
expect(errOut).toContain('exited before the smoke finished');
expect(errOut).toContain('output write failed');
expect(errOut).toContain('dying early');
@@ -167,7 +158,6 @@ describe('runDriver (full orchestration)', () => {
test('cleanup runs on every exit path (rm called for outDir)', async () => {
const deps = fakeDeps();
await runDriver(['node', 'script', '/tmp/app.app'], deps);
- // outDir cleanup always runs
expect(deps.rm).toHaveBeenCalled();
});
@@ -207,11 +197,8 @@ describe('runDriver (full orchestration)', () => {
};
const deps = fakeDeps({ process: proc });
await runDriver(['node', 'script', '/tmp/app.app'], deps);
- // Both signals registered at run entry
expect(registered.map((r) => r.sig).sort()).toEqual(['SIGINT', 'SIGTERM']);
- // Both removed on finally — no listener-count leak across repeated runs
expect(removed.map((r) => r.sig).sort()).toEqual(['SIGINT', 'SIGTERM']);
- // Same handler refs registered + removed (correctness of cleanup)
for (const reg of registered) {
const match = removed.find((r) => r.sig === reg.sig && r.cb === reg.cb);
expect(match).toBeDefined();
@@ -231,18 +218,15 @@ describe('runDriver (full orchestration)', () => {
let runCommandCalls = 0;
const runCommand = vi.fn(async (cmd) => {
runCommandCalls += 1;
- // Simulate .dmg path so resolvedApp.cleanup has work to do (detach)
- if (cmd === 'hdiutil' && runCommandCalls === 1) return; // attach
- if (cmd === 'hdiutil' && runCommandCalls === 2) return; // detach (normal finally)
+ if (cmd === 'hdiutil' && runCommandCalls === 1) return;
+ if (cmd === 'hdiutil' && runCommandCalls === 2) return;
});
const rm = vi.fn(async () => {});
const deps = fakeDeps({
process: proc,
runCommand,
rm,
- // Inject a spawn that never exits so we can fire SIGINT before normal finally
spawn: () => {
- // Fire SIGINT synchronously after spawn "starts"
globalThis.setImmediate(() => sigintHandler?.());
return {
on: () => {},
@@ -251,24 +235,17 @@ describe('runDriver (full orchestration)', () => {
stdout: { on: () => {} },
};
},
- // Keep the run from timing out normally — test controls termination via SIGINT.
timeoutMs: 60_000,
});
- // Don't await — runDriver's promise will never resolve because we're
- // simulating signal-driven exit. Fire SIGINT via setImmediate above.
const runPromise = runDriver(['node', 'script', '/tmp/foo.dmg'], deps);
- // Let the event loop drain so the setImmediate + signal cleanup runs
await setImmediate();
await setImmediate();
await setImmediate();
expect(exits).toEqual([130]);
expect(rm).toHaveBeenCalled();
- // Cleanup message surfaced
expect(deps.messages.stderr.join('')).toContain('received SIGINT');
- // Prevent the dangling runPromise from causing an unhandled rejection —
- // we deliberately short-circuited runDriver before it could resolve.
runPromise.catch(() => {});
});
@@ -318,7 +295,7 @@ describe('runDriver (full orchestration)', () => {
spawn: () => {
globalThis.setImmediate(() => {
sigintHandler?.();
- sigintHandler?.(); // second fire — guarded by signalHandled
+ sigintHandler?.();
});
return {
on: () => {},
@@ -332,7 +309,7 @@ describe('runDriver (full orchestration)', () => {
const runPromise = runDriver(['node', 'script', '/tmp/app.app'], deps);
await setImmediate();
await setImmediate();
- expect(exits).toEqual([130]); // single exit despite two signal fires
+ expect(exits).toEqual([130]);
runPromise.catch(() => {});
});
});
diff --git a/packages/desktop/tests/unit/verify-native-config-driver.test.mjs b/packages/desktop/tests/unit/verify-native-config-driver.test.mjs
index 930ec3923..4e0c571cc 100644
--- a/packages/desktop/tests/unit/verify-native-config-driver.test.mjs
+++ b/packages/desktop/tests/unit/verify-native-config-driver.test.mjs
@@ -52,7 +52,6 @@ describe('resolveBundledNativeDirInDir', () => {
test('finds the loader when <dir> is itself the native dir', () => {
const existsSyncMock = vi.fn((p) => p === '/proj/native/index.js');
- // The first candidate '.' checks /proj/index.js (absent), then 'native'.
expect(resolveBundledNativeDirInDir('/proj', { existsSync: existsSyncMock })).toBe(
'/proj/native',
);
@@ -95,7 +94,7 @@ describe('loadAndRoundTrip', () => {
test('ok:false when a binding fn returns the wrong shape', () => {
const fakeBinding = {
parseTomlToJson: () => '{"probe":1}',
- upsertMcpServer: () => ({ changed: true }), // missing text
+ upsertMcpServer: () => ({ changed: true }),
resolveSymlinkWritePath: (p) => ({ writePath: p }),
};
const result = loadAndRoundTrip('/bundle/native', { requireModule: () => fakeBinding });
diff --git a/packages/native-config/scripts/build.mjs b/packages/native-config/scripts/build.mjs
index d6c3fd461..c24d71c88 100644
--- a/packages/native-config/scripts/build.mjs
+++ b/packages/native-config/scripts/build.mjs
@@ -19,9 +19,6 @@ export function resolveBuildArgs({ platform, arch, release }) {
const target = LINUX_GNU_TARGETS[arch];
if (target == null) throw new Error(`Unsupported Linux architecture: ${arch}`);
- // Linux package builds run on newer CI hosts than the distributions we
- // support. napi-rs's pinned cross toolchain keeps the addon's glibc floor
- // independent of the host runner.
args.push('--target', target, '--use-napi-cross');
return args;
}
diff --git a/packages/native-config/scripts/build.test.mjs b/packages/native-config/scripts/build.test.mjs
index 4daeee08b..f211c3d54 100644
--- a/packages/native-config/scripts/build.test.mjs
+++ b/packages/native-config/scripts/build.test.mjs
@@ -2,7 +2,6 @@ import assert from 'node:assert/strict';
import { describe, test } from 'node:test';
import { resolveBuildArgs } from './build.mjs';
-// This package has no Vitest dependency, so the plain-JS harness uses Node's built-in runner.
describe('resolveBuildArgs', () => {
test('uses the napi cross toolchain for Linux x64 release builds', () => {
assert.deepEqual(resolveBuildArgs({ platform: 'linux', arch: 'x64', release: true }), [
diff --git a/packages/server/src/acp/thread-manager.ts b/packages/server/src/acp/thread-manager.ts
index 68ba1179a..2d748eea7 100644
--- a/packages/server/src/acp/thread-manager.ts
+++ b/packages/server/src/acp/thread-manager.ts
@@ -1,23 +1,7 @@
/**
- * Server-hosted ACP threads — one spawned agent subprocess per thread,
- * bridged to browser/Electron clients over the `/collab/thread` WS.
- *
- * Responsibilities:
- * - Own the agent process lifecycle (spawn → initialize → session/new →
- * prompt turns → kill on close/shutdown/idle-reap).
- * - Implement the client side of ACP: session/update fan-out,
- * permission requests (policy-gated via `AcpPermissionStore`), and the
- * `fs/*` services — the attribution path that routes agent edits of
- * in-scope markdown through the CRDT write spine instead of raw disk.
- * - Retain a bounded per-thread event log so a reconnecting client can
- * replay from its last-seen seq (the WS-replay analog of the
- * "durable truth + live push" recovery contract).
- *
- * Write attribution: markdown writes reuse `AgentSessionManager` sessions
- * keyed by a per-thread `acp-<uuid>` agent id, so every edit lands under a
- * per-session frozen paired-write origin (precedent #24) and books to the
- * `agent-*` writer namespace (precedent #25) — write-flash, activity panel,
- * and per-session undo all work exactly as MCP agent writes do.
+ * Server-hosted ACP threads: one spawned agent subprocess per thread, bridged to clients over
+ * `/collab/thread`. Markdown writes reuse `AgentSessionManager` sessions keyed by `acp-<uuid>`, so
+ * each edit lands under a per-session frozen origin (precedent #24) in the `agent-*` namespace.
*/
import type { ChildProcess } from 'node:child_process';
diff --git a/packages/server/src/activity-log.ts b/packages/server/src/activity-log.ts
index c86cb92a6..45dad1d69 100644
--- a/packages/server/src/activity-log.ts
+++ b/packages/server/src/activity-log.ts
@@ -6,12 +6,7 @@ const RING_BUFFER_LIMIT = 50;
let _effectCounter = 0;
-/**
- * Typed origin for effect-capture writes to Y.Map('agent-effects') (precedent #1).
- * `paired: false` because this origin mutates only the agent-effects ring-buffer,
- * not the bridge-coupled Y.Text/Y.XmlFragment pair — server observers must NOT
- * short-circuit on this origin (isPairedWriteOrigin returns false).
- */
+/** Typed origin for effect-capture writes to Y.Map('agent-effects') (precedent #1). */
const EFFECT_CAPTURE_ORIGIN: LocalTransactionOrigin = Object.freeze({
source: 'local',
skipStoreHooks: true,
@@ -27,31 +22,9 @@ export interface EffectValue {
}
/**
- * Register a one-shot ytext observer that captures the delta of the agent's own
- * write transact into Y.Map('agent-effects'). Must be called BEFORE that
- * transact.
- *
- * The observer is ORIGIN-KEYED, not merely one-shot: it consumes only an event
- * whose `transaction.origin` is `writeOrigin` by identity (the same frozen
- * per-session object `Y.UndoManager` matches on, precedent #24). Origin-blind
- * arming is unsound because non-agent Y.Text writes legitimately land between
- * arming and the agent's transact — the pre-drain flush (`agentWritePreDrain`,
- * under `OBSERVER_SYNC_ORIGIN`) is exactly that, and consuming it would file the
- * USER's un-propagated keystroke as an agent effect while the agent's own write
- * produced no row at all.
- *
- * Returns a disposer the caller runs when the operation ends (a `finally` beside
- * the write). Arming is therefore scoped to the operation: a write that produces
- * no Y.Text delta at all (an empty append `composeAgentWrite` declines) leaves no
- * armed observer behind to consume a LATER same-session write's delta under this
- * call's stale key. Idempotent — the observer disarms itself on capture.
- *
- * @param ytext The Y.Text('source') instance to observe.
- * @param sessionId The agent's writer ID (e.g. 'agent-<connectionId>').
- * @param writeOrigin The transaction origin the agent's write will run under
- * (`session.origin`); matched by object identity.
- * @param colorSeed Color seed for UI rendering (defaults to sessionId).
- * @param agentType Agent type string for UI aggregation (e.g. 'claude', 'cursor').
+ * The observer is ORIGIN-KEYED, not merely one-shot: it consumes only an event whose
+ * `transaction.origin` is `writeOrigin` by identity (the same frozen per-session object
+ * `Y.UndoManager` matches on, precedent #24).
*/
export function captureEffect(
ytext: Y.Text,
diff --git a/packages/server/src/agent-id.ts b/packages/server/src/agent-id.ts
index d0d65f72d..ee6971791 100644
--- a/packages/server/src/agent-id.ts
+++ b/packages/server/src/agent-id.ts
@@ -17,18 +17,8 @@ export function toBroadcasterKey(rawAgentId: string): string {
}
/**
- * True iff the broadcaster-map key represents an agent whose state should
- * surface in the agent-presence / agent-focus UI.
- *
- * Form-write handlers attribute writes to `principal-<UUID>` (precedent #25
- * writer-ID taxonomy) — the local human editing their own properties is the
- * principal, not an agent. Routing those writes through the same broadcaster
- * call sites as MCP writes (the structural agent-presence test pins the
- * try/finally setPresence/touchMode shape, so handlers can't omit the calls)
- * would surface the user as their own agent: avatar in the editor chrome,
- * red agent-flash on the body text. Filter principal-prefixed ids at the
- * broadcaster boundary so handler shape stays valid AND non-agent writers
- * never reach the awareness fanout.
+ * Form-write handlers attribute writes to `principal-<UUID>` (precedent #25 writer-ID taxonomy) —
+ * the local human editing their own properties is the principal, not an agent.
*/
export function isPresenceEligibleAgentId(agentId: string): boolean {
return !agentId.startsWith('principal-');
diff --git a/packages/server/src/agent-sessions.ts b/packages/server/src/agent-sessions.ts
index fc959efe6..de398cef9 100644
--- a/packages/server/src/agent-sessions.ts
+++ b/packages/server/src/agent-sessions.ts
@@ -1,22 +1,4 @@
-/**
- * Agent session management — DirectConnection lifecycle.
- *
- * Each agent gets a persistent DirectConnection to the Hocuspocus server.
- * Sessions track awareness (presence bar shows agent).
- *
- * Each session creates its own frozen LocalTransactionOrigin at birth
- * (precedent #1). All agent write paths call
- * `session.dc.document.transact(fn, session.origin)` — never `dc.transact(fn)`
- * or the shared `AGENT_WRITE_ORIGIN` constant (STOP rule).
- *
- * getSession uses an in-flight promise dedup map so concurrent first-calls
- * share one pending openDirectConnection call and produce exactly one session.
- *
- * Each session creates a Y.UndoManager tracking [Y.Text, flashMap]
- * via session.origin. session.undoOrigin is the placeholder origin for the
- * applyAgentUndo path; captureTransaction excludes it from the UM stack
- * to prevent undo-of-undo cycles (defense-in-depth).
- */
+/** Each session creates its own frozen LocalTransactionOrigin at birth (precedent #1). */
import type { DirectConnection, Document, Hocuspocus } from '@hocuspocus/server';
import {
applyPatchToFm,
@@ -68,23 +50,9 @@ export interface AgentDirectConnection extends DirectConnection {
}
/**
- * Agent write origin — typed `PairedWriteOrigin` per precedent #1
- * extension; the typed marker carries the `paired: true` field that
- * `isPairedWriteOrigin` reads to gate paired-write transactions.
- *
- * LEGACY EXPORT — kept for unit tests that directly test observer behavior
- * against a paired-write origin. Production agent-write paths MUST use
- * `session.origin` (per-session frozen origin from getSession) instead of
- * this shared constant.
- *
- * `skipStoreHooks: false` — persistence SHOULD fire after agent writes so
- * content reaches disk through the normal debounce pipeline.
- *
- * `paired: true` — the caller atomically writes BOTH Y.XmlFragment and Y.Text
- * inside one `doc.transact(..., AGENT_WRITE_ORIGIN)` block (see
- * `applyAgentMarkdownWrite` below). The `satisfies PairedWriteOrigin`
- * annotation forces the literal to carry the marker; the compile-time gate
- * catches omissions before they reach runtime.
+ * Agent write origin — typed `PairedWriteOrigin` per precedent #1 extension; the typed marker
+ * carries the `paired: true` field that `isPairedWriteOrigin` reads to gate paired-write
+ * transactions.
*/
export const AGENT_WRITE_ORIGIN = {
source: 'local',
@@ -100,30 +68,9 @@ function docNameToFile(docName: string): string {
}
/**
- * Y.Text-is-truth agent write composition (precedent #38).
- *
- * Composes the agent's delta against the current Y.Text bytes (the source-of-
- * truth for user-intended source bytes), then routes through the sibling
- * primitive matching the caller's INTENT: `replaceRawBody` for `replace`
- * (atomic full overwrite — prior content discarded wholesale);
- * `composeAndWriteRawBody` for `append` / `prepend` / `patch` (DMP-incremental,
- * item-preserving — merging into surrounding content the caller keeps).
- * `patch` is the `edit` find/replace path: it hands a full recomposed
- * body but wants the minimal item-preserving delta, so it deliberately does
- * NOT take the atomic primitive (which would churn the whole doc per surgical
- * edit and widen the concurrent-edit residue surface to the whole document).
- * Y.Text receives the composed bytes verbatim (no
- * canonicalization); XmlFragment derives via `parse(body)` →
- * `updateYFragment` (structural diff preserves user-content Items at matching
- * positions); both writes are atomic inside the caller's outer transact.
- *
- * Atomicity boundary: caller MUST wrap this in
- * `session.dc.document.transact(fn, session.origin)`. The per-session frozen
- * origin (precedent #24) is what makes this work for `Y.UndoManager`
- * attribution + the paired-write origin guard in server-observers.
- *
- * @see PRECEDENTS.md precedent #11(a) (item-preserving cross-CRDT sync)
- * @see PRECEDENTS.md precedent #38 (Y.Text-is-truth contract)
+ * Y.Text-is-truth agent write composition (precedent #38): compose the delta against current
+ * Y.Text bytes, then route through the sibling primitive matching the caller's intent. The caller
+ * must wrap this in `session.dc.document.transact(fn, session.origin)` (precedent #24).
*/
export async function prepareAgentMarkdownParse(
document: Document,
@@ -370,59 +317,9 @@ function applyAgentMarkdownWriteInner(
}
/**
- * Y.Text-is-truth agent undo. The only sanctioned server-side undo write
- * surface — every other path is the deleted client-side cross-CRDT
- * anti-pattern.
- *
- * Calls session.um.undo() INSIDE an outer doc.transact(..., session.undoOrigin)
- * so Y.js merges the UM's internal transaction into the outer. The whole
- * operation fires under undoOrigin (paired: true) → Observer A/B short-circuit.
- *
- * After undo, Y.Text holds the user's intended post-undo bytes (precedent
- * #38). XmlFragment derives via `parseWithFallback(body)` →
- * `updateYFragment` so the structural diff preserves user-content Items at
- * matching positions. NO canonicalize-write-back step: re-serializing the
- * fragment and applying that to ytext would defeat the contract by
- * canonicalizing user-typed source-form bytes (e.g. `__foo__` → `**foo**`,
- * `:---:` table widths, ATX trailing hashes). Post-undo bridge invariant
- * divergence (if any) is detected by Observer B's watchdog.
- *
- * scope 'last': undo one UM stack item.
- * scope 'session': undo entire UM stack.
- * scope 'count': undo the `count` newest UM stack items (clamped to depth) —
- * the scoped "undo to edit N" range. `count` is required for this scope.
- *
- * Returns `true` when at least one UM frame was popped (i.e., the undo had
- * an observable effect), `false` when the stack was already empty. Callers
- * can surface this to the HTTP response so MCP clients know the no-op case.
- *
- * Contract — every requirement is load-bearing; do not relax without re-running
- * the bridge fuzzer + conversion-PBT suite that guards against the bug-A class:
- *
- * (1) Y.Text-is-truth composition (precedent #38). Y.UndoManager has
- * already mutated ytext to its desired post-undo state; XmlFragment
- * derives via parse(ytext). Do NOT re-canonicalize ytext from the
- * fragment — that defeats the contract.
- * (2) Fires under per-session `session.undoOrigin`, distinct from
- * `session.origin`. The UM is constructed with
- * `captureTransaction: tr => tr.origin !== session.undoOrigin` so
- * undo-of-undo never lands on the stack.
- * (3) No client-side cross-CRDT writes. Server-authoritative observer-
- * bridge is the only mirror path; client observers are baseline-only
- * (precedent #14).
- * (4) Single `doc.transact()` block — no defensive mutex. The atomicity
- * comes from the transact, not from extra serialization.
- * (5) Every change here ships with fuzzer + conversion-PBT coverage.
- *
- * Cross-deploy transition: undo-stack frames captured BEFORE the
- * Y.Text-is-truth migration contain canonical bytes (post-Phase-2
- * canonicalize-write-back). After deploy, undo through those frames
- * restores canonical bytes, while frames captured under contract restore
- * raw user bytes. Mixed-form undo across the boundary is acceptable
- * transition behavior — the UM stack is per-session and ephemeral.
- *
- * @see PRECEDENTS.md precedent #38 (Y.Text-is-truth contract)
- * @see PRECEDENTS.md precedent #14 (cross-CRDT sync is single-writer, server-side)
+ * Y.Text-is-truth agent undo, the only sanctioned server-side undo write surface: after
+ * `session.um.undo()` Y.Text holds the intended post-undo bytes and XmlFragment derives from them
+ * (precedent #38). There is no canonicalize-write-back step, which would defeat that contract.
*/
export function applyAgentUndo(
session: SessionRecord,
@@ -521,13 +418,7 @@ interface SessionRecord {
lastUsedAt: number;
}
-/**
- * Create a frozen per-session PairedWriteOrigin (precedent #24(b)).
- * Object-identity-unique per call; deep-frozen via Object.freeze on both
- * the context and the outer object. The returned object is the Y.UndoManager
- * trackedOrigins key for this session — a reconstructed object with the same
- * shape is NOT equivalent (Set-identity match, not structural equality).
- */
+/** Create a frozen per-session PairedWriteOrigin (precedent #24(b)). */
function createSessionOrigin(
sessionId: string,
agentType?: string,
@@ -660,18 +551,8 @@ export class AgentSessionManager {
}
/**
- * Get or create a per-agent SessionRecord (DirectConnection + per-session origin).
- *
- * Each new session creates a frozen LocalTransactionOrigin via
- * `createSessionOrigin`. The returned session.origin is object-identity-unique.
- *
- * Concurrent first-calls for the same (docName, agentId) share one
- * pending openDirectConnection promise — exactly one DirectConnection created.
- *
- * No per-doc awareness publishing: every Hocuspocus `Document` has a single
- * shared `Awareness` clientID, so per-doc writes stomp across N concurrent
- * agents. Presence is published on the `__system__` Y.Doc via
- * `AgentPresenceBroadcaster` instead (precedent #3).
+ * Presence is published on the `__system__` Y.Doc via `AgentPresenceBroadcaster` instead
+ * (precedent #3).
*/
async getSession(
docName: string,
diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.ts
index 5038a88a5..a0ee47c68 100644
--- a/packages/server/src/api-extension.ts
+++ b/packages/server/src/api-extension.ts
@@ -590,15 +590,8 @@ export const ROLLBACK_ORIGIN = {
} as const satisfies PairedWriteOrigin;
/**
- * Managed-rename origin — typed `PairedWriteOrigin`.
- *
- * Exported so the bridge-invariant watcher can enforce by identity (precedent #1)
- * and so server observers can resolve `context.paired` without importing the
- * object transitively.
- *
- * `paired: true` — the caller atomically writes BOTH XmlFragment (via
- * `updateYFragment`) and Y.Text (via `applyFastDiff`) inside one transact
- * block. `satisfies PairedWriteOrigin` is the compile-time gate.
+ * Exported so the bridge-invariant watcher can enforce by identity (precedent #1) and so server
+ * observers can resolve `context.paired` without importing the object transitively.
*/
export const MANAGED_RENAME_ORIGIN = {
source: 'local' as const,
@@ -1973,7 +1966,11 @@ export function createApiExtension(
};
}
- // (precedent #55): a doc the watcher would refuse to index must not slip into
+ /**
+ * Content-scope exclusion for a docName, mirroring the file-watcher's markdown admission
+ * gate: a doc the watcher would refuse to index must not slip into the admitted set by
+ * another door (precedent #55).
+ */
function isDocNameContentExcluded(docName: string): boolean {
if (!contentFilter) return false;
const relPath = docNameToRelativePath(docName);
@@ -2150,7 +2147,10 @@ export function createApiExtension(
};
}
- // Mirrors the watcher's admission gate (precedent #55): a content-scope-excluded
+ /**
+ * Mirrors the watcher's admission gate (precedent #55): a content-scope-excluded doc must
+ * NOT be registered, exactly as the watcher would skip it.
+ */
function registerWrittenDocInFileIndex(docName: string, content: string): void {
if (isDocNameContentExcluded(docName)) return;
mutateFileIndex?.({
@@ -3177,14 +3177,8 @@ export function createApiExtension(
}
/**
- * Canonical identity boundary (precedent #24) — every mutating POST handler calls this
- * before any Y.Doc mutation. Resolves request body → {agentId, agentName, colorSeed, clientName}.
- * The meta-test in attribution-sweep-coverage.test.ts asserts all handlers call this at entry.
- *
- * Body parsing + sanitization is shared with `extractActorIdentity` via
- * `parseAgentBodyFields` in `agent-id.ts`. This wrapper adds the write-handler
- * default — absent agentId becomes `'claude-1'` so attribution always lands on
- * a stable broadcaster key (matches `getSession()` for presence bar color).
+ * Canonical identity boundary (precedent #24) — every mutating POST handler calls this before any
+ * Y.Doc mutation.
*/
function extractAgentIdentity(body: Record<string, unknown>): {
rawAgentId: string | undefined;
@@ -3433,7 +3427,7 @@ export function createApiExtension(
if (rawDocName === null) return;
const docName = resolveAlias(rawDocName);
- // (precedent #24). Body-shape errors emitted by `withValidation` are
+ // Identity extraction precedes every semantic error emission below (precedent #24).
const { agentId, agentName, colorSeed, clientName, clientVersion, label } =
extractAgentIdentity(body);
@@ -4233,7 +4227,10 @@ export function createApiExtension(
}
if (result.nextFenced !== currentFenced) {
- // primitive (precedent #38, bridge-intake.ts) so paired-
+ /**
+ * Routed through the sanctioned `composeAndWriteRawBody` primitive
+ * (precedent #38) so paired-write semantics survive.
+ */
const needsFenceSeparator =
currentFenced === '' && currentBody !== '' && !currentBody.startsWith('\n');
const newFull = composeWithDerivedFrontmatter(
@@ -4496,7 +4493,11 @@ export function createApiExtension(
clientName,
);
session.dc.document.transact(() => {
- // precedent #38). Searching `serialize(fragment)` would compute
+ /**
+ * Read current authoritative state from Y.Text, the user's intended source-form bytes
+ * (Y.Text-is-truth, precedent #38); `serialize(fragment)` would compute offsets against
+ * canonical bytes instead.
+ */
const ytextSnapshot = session.dc.document.getText('source').toString();
const { frontmatter: currentFm, body: currentBody } = stripFrontmatter(ytextSnapshot);
const currentFull = prependFrontmatter(currentFm, currentBody);
@@ -5338,7 +5339,10 @@ export function createApiExtension(
return;
}
- // (precedent #38 — Y.Text-is-truth) which performs the full ytext
+ /**
+ * Rollback routes through the `replaceRawBody` sibling primitive (precedent #38,
+ * Y.Text-is-truth), which overwrites ytext first and derives the fragment after.
+ */
const rollbackEmbedResolver = options.resolveEmbed
? { resolveEmbed: options.resolveEmbed, sourcePath: docName }
: undefined;
@@ -6958,7 +6962,11 @@ export function createApiExtension(
if (checkSkillDocConflictGate(docName, 'skill-put', res)) return;
- // CRDT write (precedent #24 / #38): route the full SKILL.md through the
+ /**
+ * CRDT write (precedent #24 / #38): the full SKILL.md goes through the doc's
+ * `Y.Text('source')` via the sanctioned paired-write primitive under the per-session
+ * frozen origin.
+ */
const { agentId, agentName, colorSeed, clientName } = extractAgentIdentity(
body as unknown as Record<string, unknown>,
);
@@ -8082,7 +8090,10 @@ export function createApiExtension(
let created: boolean;
if (routedThroughContent) {
- // primitive (precedent #24 / #38), same branch as the SKILL.md body.
+ /**
+ * A project `.md` reference routes through the sanctioned paired-write primitive
+ * (precedent #24 / #38), the same branch as the SKILL.md body.
+ */
const refDocName = `${skillDirRel}/${rel.replace(/\.mdx?$/i, '')}`;
if (checkSkillDocConflictGate(refDocName, 'skill-file-put', res)) return;
created = !existsSync(resolve(skillDirAbs, rel));
@@ -8446,7 +8457,11 @@ export function createApiExtension(
): Promise<string | undefined> {
const shadow = shadowRef?.current;
if (!shadow || !writerId) return undefined;
- // (`refs/wip/<branch>/<writerId>`, precedent #25). `commitOkArtifactWrite` has
+ /**
+ * The shadow repo has no `HEAD`/`main`: writes land on per-writer WIP refs
+ * (`refs/wip/<branch>/<writerId>`, precedent #25), so capture the actor's WIP ref rather
+ * than `rev-parse HEAD`.
+ */
try {
const sg = shadowGit(shadow);
const readMine = async (): Promise<string | undefined> => {
diff --git a/packages/server/src/boot.ts b/packages/server/src/boot.ts
index e39b4730a..2225cced6 100644
--- a/packages/server/src/boot.ts
+++ b/packages/server/src/boot.ts
@@ -1,24 +1,3 @@
-/**
- * `bootServer` — HTTP + WebSocket wrapping layer around `createServer()`.
- *
- * Three consumers share this composed boot path:
- * 1. CLI `ok start` (via `bootStartServer` in packages/cli)
- * 2. Electron utility process (direct import — precedent #14-adjacent)
- * 3. Integration tests
- *
- * Before this extraction every consumer reimplemented HTTP + WS upgrade
- * + `listen()` + `updateServerLockPort` + idle-shutdown + composite destroy.
- * The extraction consolidates those ~150 LOC here so all three callers share
- * a single tested orchestrator.
- *
- * Opt-outs (Electron utility uses these):
- * - `idleShutdownMs: null` — disable idle-shutdown entirely
- * - `skipAutoInit: true` — skip the pre-createServer scaffold hook
- *
- * CLI-specific concerns (`initContent`, banner, signal handlers)
- * are NOT part of bootServer — the CLI wrapper layers them on top via
- * injected callbacks + post-return orchestration.
- */
import { existsSync, readdirSync, statSync } from 'node:fs';
import type { Server as HttpServer } from 'node:http';
import { homedir } from 'node:os';
diff --git a/packages/server/src/bridge-intake.test.ts b/packages/server/src/bridge-intake.test.ts
index 77069bb2f..eea247be6 100644
--- a/packages/server/src/bridge-intake.test.ts
+++ b/packages/server/src/bridge-intake.test.ts
@@ -1,32 +1,6 @@
/**
- * Unit tests for the three sibling write-side primitives in
- * `bridge-intake.ts` — the shared substrate of the Y.Text-is-truth
- * contract (precedent #38). Each primitive owns one paired-write
- * semantics and gets its own `describe` block here:
- *
- * - `composeAndWriteRawBody` — file-watcher + agent-write semantics
- * (parse → ytext-first applyFastDiff → fragment derive). Item-
- * preserving via character-level DMP.
- * - `replaceRawBody` — rollback semantics (parse → ytext-first FULL
- * OVERWRITE delete/insert → fragment derive). The non-incremental
- * replacement is the load-bearing signal to Y.UndoManager that this
- * is a rollback, not an edit; DMP-based diff would over-preserve
- * Items the user explicitly rolled back.
- * - `deriveFragmentFromYtext` — agent-undo semantics (NO ytext write;
- * UM.undo() has already mutated ytext to the post-undo state, this
- * primitive only re-derives the fragment).
- *
- * Properties exercised across the three blocks:
- * - Y.Text receives raw bytes verbatim (no canonicalization)
- * - XmlFragment derives from `parse(body)` via updateYFragment
- * - Both writes are atomic inside the caller's outer transact
- * - Write order is ytext-first then fragment
- * - Whitespace-meaningful bytes (leading/trailing newlines) survive
- * - Source-form delimiters (`__foo__` not `**foo**`) survive
- * - No primitive calls doc.transact() itself (caller-wrap is mandatory)
- * - The primitive distinguishing-features hold under regression
- * (replaceRawBody = full overwrite; deriveFragmentFromYtext = zero
- * ytext writes)
+ * Unit tests for the three sibling write-side primitives in `bridge-intake.ts` — the shared
+ * substrate of the Y.Text-is-truth contract (precedent #38).
*/
import { normalizeBridge, stripFrontmatter } from '@inkeep/open-knowledge-core';
diff --git a/packages/server/src/bridge-intake.ts b/packages/server/src/bridge-intake.ts
index 6585e9c4b..208dc38da 100644
--- a/packages/server/src/bridge-intake.ts
+++ b/packages/server/src/bridge-intake.ts
@@ -1,48 +1,7 @@
/**
- * Three sibling write-side primitives for the Y.Text-is-truth contract
- * (precedent #38). Each primitive owns one paired-write semantics — its
- * name is the contract.
- *
- * - `composeAndWriteRawBody` — file-watcher + agent-write: parse → ytext-
- * first `applyFastDiff` → fragment derive. Line-aligned diff preserves
- * unrelated whole-line Y.Text Items + their origins; changed lines land
- * as fresh contiguous runs (stale-anchor interleave safety).
- * - `replaceRawBody` — rollback: parse → ytext-first FULL OVERWRITE
- * (delete(0, len) + insert(0, raw)) → fragment derive. The non-
- * incremental replacement is the load-bearing signal to Y.UndoManager
- * that "this is a rollback, not an edit"; diff-based application would
- * over-preserve Items the user explicitly rolled back.
- * - `deriveFragmentFromYtext` — agent-undo: `Y.UndoManager.undo()` has
- * already mutated ytext to the post-undo state; this primitive ONLY
- * derives the fragment from `parse(ytext.toString())`. Writes zero
- * bytes to ytext.
- *
- * Atomicity boundary: NO primitive calls
- * `doc.transact()`. The caller wraps so:
- * 1. Both halves of the cross-CRDT write (XmlFragment + Y.Text) are atomic
- * from the perspective of any other observer.
- * 2. The per-session frozen origin object identity (precedent #24)
- * survives — Y.UndoManager's `trackedOrigins` Set membership and the
- * paired-write origin guard in server-observers both rely on object
- * identity, not structural equality. A nested `doc.transact()` here
- * would lose origin identity.
- *
- * Y.Text is the source-of-truth for user-intended source bytes.
- * Bytes that enter via these primitives land verbatim, modulo only the
- * equivalence classes enumerated in `normalizeBridge` — and even those are
- * TOLERATED at compare time, never WRITTEN at apply time.
- *
- * Write-order rationale (uniform across all three primitives that mutate
- * ytext): Y.Text receives bytes FIRST, then fragment derives. Yjs
- * transactions don't roll back on throw, so a partial failure mid-call
- * leaves whichever side wrote last in the new state and the other side
- * stale. Under the contract (Y.Text-is-truth), Y.Text is the source of
- * truth — if the ytext write succeeds and `updateYFragment` then throws,
- * ytext holds the correct user bytes and the next non-paired observer
- * dispatch re-derives fragment via `parse(ytext)`. Reversed order would
- * leave fragment correct and ytext stale — and Observer B Phase 1 on the
- * next non-paired ytext mutation would re-derive fragment from the STALE
- * ytext bytes, silently reverting the write.
+ * The three sibling write-side primitives for the Y.Text-is-truth contract (precedent #38):
+ * `composeAndWriteRawBody`, `replaceRawBody` and `deriveFragmentFromYtext`, each owning one
+ * paired-write semantics. No primitive calls `doc.transact()`; the caller wraps.
*/
import {
applyFastDiff,
@@ -128,25 +87,9 @@ function reportPairedDeriveLoss(
}
/**
- * Apply raw composed bytes to Y.Text via an incremental line-aligned diff and derive
- * XmlFragment via parse.
- *
- * MUST be called inside an outer `doc.transact(..., origin)` block
- * established by the caller (atomicity + per-session frozen origin object
- * identity per precedent #24).
- *
- * Bytes flow:
- * - `ytext` receives `rawContent` verbatim via `applyFastDiff`
- * (line-aligned diff, item-preserving for unchanged lines) — NO
- * canonicalization. Run
- * FIRST per the file-level write-order rationale.
- * - `xmlFragment` receives `parse(body-without-FM)` via
- * `updateYFragment` (item-preservation aware structural diff,
- * precedent #11(a)). Derived SECOND.
- *
- * @param document Y.Doc holding the doc's `default` XmlFragment and `source` Y.Text.
- * @param rawContent Full document bytes (frontmatter + body) to write to Y.Text verbatim.
- * @param embedResolver `![[file.ext]]` resolver context, or `false` to opt out for pre-composed-bytes callers.
+ * Applies raw composed bytes to Y.Text via an incremental line-aligned diff and derives
+ * XmlFragment via parse. Must run inside an outer `doc.transact(..., origin)` block for atomicity
+ * and the per-session frozen origin identity (precedent #24).
*/
export type ComposeWriteSurface =
| 'agent'
@@ -253,30 +196,8 @@ export function replaceRawBody(
}
/**
- * Derive XmlFragment from Y.Text — the agent-undo semantics.
- *
- * Pre-state contract: `Y.UndoManager.undo()` has already mutated ytext to
- * the post-undo bytes (those bytes ARE the user's intended post-undo
- * source form per Y.Text-is-truth, precedent #38). This primitive does
- * NOT mutate ytext; it ONLY parses ytext's current bytes and updates the
- * fragment so the structural diff preserves user-content Items at
- * matching positions.
- *
- * NO canonicalize-write-back step: re-serializing the fragment and
- * applying that back to ytext would canonicalize user-typed source-form
- * bytes (`__foo__` → `**foo**`, `:---:` widths, ATX trailing hashes,
- * setext underline length) and defeat the contract.
- *
- * MUST be called inside an outer `doc.transact(..., origin)` block
- * (typically `session.undoOrigin`).
- *
- * @param document Y.Doc holding the doc's `default` XmlFragment and `source` Y.Text.
- * @param embedResolver Optional `![[file.ext]]` resolver context.
- * @param detect Optional post-condition observer. When supplied, the pre-derive
- * fragment is serialized (the at-risk content) and, after the rebuild,
- * `detect.report` is invoked with the canonical before/after representations
- * so a caller can checkpoint + observe content the rebuild discarded. The
- * serialize cost is paid ONLY when a detector is wired.
+ * Pre-state contract: `Y.UndoManager.undo()` has already mutated ytext to the post-undo bytes
+ * (those bytes ARE the user's intended post-undo source form per Y.Text-is-truth, precedent #38).
*/
export function deriveFragmentFromYtext(
document: Y.Doc,
diff --git a/packages/server/src/bridge-no-wallclock.test.ts b/packages/server/src/bridge-no-wallclock.test.ts
index 45be24deb..3e9dd5fc8 100644
--- a/packages/server/src/bridge-no-wallclock.test.ts
+++ b/packages/server/src/bridge-no-wallclock.test.ts
@@ -1,29 +1,5 @@
/**
- * Precedent #13(b) enforcement — bridge observers are settlement-based,
- * never wall-clock debounce.
- *
- * Scans the two bridge observer source files at runtime:
- * - `packages/server/src/server-observers.ts` — server-authoritative
- * observer (`afterAllTransactions` settlement dispatch)
- * - `packages/app/src/editor/observers.ts` — client observer shell
- * (diagnostic parse validation)
- *
- * Forbidden patterns (any match fails CI):
- * - `setTimeout(` / `setInterval(` — wall-clock scheduling calls
- * - `sched.setTimeout(` / `sched.clearTimeout(` / `sched.setInterval(`
- * — historical Scheduler-DI call sites
- * - `new Scheduler(` / `: Scheduler` / `Scheduler<` — active Scheduler
- * type consumption (indicates debounce machinery)
- *
- * Comments and JSDoc referencing the retired machinery are allowed — the
- * forbidden regex targets call-site forms (parenthesis-after-identifier)
- * and type-annotation forms.
- *
- * Intentional omission: no allow-list file carve-outs inside this gate.
- * If a legitimate future reason emerges (e.g., a specific sanctioned
- * setTimeout for an escape-hatch retry), document it by narrowing the
- * scanned set or gating with a structured marker — don't silently
- * allow-list individual lines. Greenfield posture.
+ * Precedent #13(b) enforcement — bridge observers are settlement-based, never wall-clock debounce.
*/
import { readFileSync } from 'node:fs';
diff --git a/packages/server/src/bridge-quiescence.ts b/packages/server/src/bridge-quiescence.ts
index 03a612344..968e0dbb5 100644
--- a/packages/server/src/bridge-quiescence.ts
+++ b/packages/server/src/bridge-quiescence.ts
@@ -4,34 +4,12 @@ interface DocQuiescenceCounters {
lastUserTxGen: number;
settledGen: number;
/**
- * Wall-clock timestamp (ms since epoch) of the last user-origin transaction
- * — sourced from the per-tx `afterTransaction` hook. Surfaces as the
- * `wallClockMsSinceLastTransaction` telemetry attribute on the
- * `persistence-skip-non-quiescent` event so operators can correlate
- * deferral patterns with real-world user behavior.
- *
- * Lives here (not server-observers.ts) per precedent #13(b)'s spirit —
- * `Date.now()` calls flow through this module so the bridge observer
- * file stays clean of timer machinery.
+ * Lives here (not server-observers.ts) per precedent #13(b)'s spirit — `Date.now()` calls flow
+ * through this module so the bridge observer file stays clean of timer machinery.
*/
lastUserTxAtMs: number | null;
}
-/*
- * WARN: module-level state. Today this is correct because exactly one server
- * runs per `contentDir` per process (enforced by `server.lock`); the WeakMap
- * keys on Y.Doc *instance* identity so two doc instances with the same
- * docName naturally separate. If multi-server-per-process is ever adopted
- * (multi-vault desktop, cloud multi-tenant), `globalCounter` would still
- * increment correctly (it's just a monotonic ticker shared across all docs)
- * and the WeakMap-by-instance separation still holds, so this state remains
- * safe under that future. The watchdog's rate-limiter map at
- * `bridge-watchdog.ts:lastEmitMs` is the more concerning case — see the
- * matching WARN there. Compare with the closure-scoped `configLkgCache` in
- * `persistence.ts` (per-server-instance state for config docs) — different
- * scoping rationale: that cache keys by docName string, which would conflate
- * across servers without closure-scoping.
- */
const counters = new WeakMap<Y.Doc, DocQuiescenceCounters>();
let globalCounter = 0;
@@ -45,20 +23,9 @@ function getCounters(doc: Y.Doc): DocQuiescenceCounters {
}
/**
- * Match the structural shape of `OBSERVER_SYNC_ORIGIN` from
- * `server-observers.ts`. Importing the constant directly would create a
- * circular dependency (`server-observers.ts` calls
- * `attachQuiescenceTracker`); the structural check is intentional here per
- * precedent #1's same rationale (origin objects are LocalTransactionOrigin
- * shapes; structural match reaches remote-arriving observer-self transactions
- * too, even though those don't actually exist in practice — Yjs transaction
- * origin metadata is local to each Y.Doc instance and never serialized over
- * the wire (`Y.applyUpdate(ydoc, update, transactionOrigin)` takes the origin
- * as a separate argument on the receiving side, not from the update bytes),
- * so the server's origin object cannot reach a remote peer's transaction.
- * `skipStoreHooks: true` is unrelated — it controls whether Hocuspocus's
- * `onStoreDocument` / `afterStoreDocument` persistence hooks fire, not
- * whether Yjs broadcasts CRDT updates to peers).
+ * Matches the structural shape of `OBSERVER_SYNC_ORIGIN` rather than importing it, which would
+ * make `server-observers.ts` circular. Origin objects are `LocalTransactionOrigin` shapes and a
+ * structural match is the sanctioned form (precedent #1).
*/
function isObserverSelfOrigin(origin: unknown): boolean {
if (!origin || typeof origin !== 'object') return false;
diff --git a/packages/server/src/bridge-race-rig.test-helper.ts b/packages/server/src/bridge-race-rig.test-helper.ts
index 5b3cafc5e..960e2b0a3 100644
--- a/packages/server/src/bridge-race-rig.test-helper.ts
+++ b/packages/server/src/bridge-race-rig.test-helper.ts
@@ -1,33 +1,6 @@
/**
- * Deterministic bridge-race rig — one shared substrate that drives the REAL
- * `setupServerObservers` drain on a bare `Y.Doc`, so drain-race suites assert
- * against the production observer bridge (the `afterAllTransactions`
- * settlement dispatcher, both observer directions, all gates, the
- * map-driven-splice / Path-B merge write paths, and the real Observer B
- * `parseWithFallback → updateYFragment` re-derive) rather than a replica. It is
- * imported by sibling `*.test.ts` files; it is not itself a test.
- *
- * Why per-stimulus grouping. `onDispatch` fires once per drain from inside
- * `afterAllTransactions`, and a single outermost `doc.transact()` can produce
- * several drains: the observer sync writes are themselves nested transactions
- * whose own settlement dispatches fire (self-origin drains report 'none'). yjs
- * runs all of that synchronously before the outermost `transact` returns, so
- * the rig collects every drain's dispatch decision into one trace entry keyed
- * to the stimulus, and snapshots the settled Y.Text bytes once the stimulus
- * completes. A dual-CRDT stimulus therefore reads as e.g.
- * `dispatches: ['a','none','b']` with the post-drain bytes.
- *
- * Deterministic freshness. Observer A's re-derive freshness gate reads
- * `Date.now()` against the last external Y.Text change (a 2s quiescence window
- * that is not injectable). The rig fakes only `Date` (`vi.useFakeTimers({
- * toFake: ['Date'] })`, installed by the consuming test) and advances a
- * mutable clock past that window before each default stimulus, so whether a
- * drain runs freshness-safe or freshness-suppressed is scripted, not
- * wall-clock-dependent. Faking only Date keeps span timing and the settlement
- * dispatcher (which uses no wall clock, precedent #13(b)) untouched.
- *
- * The rig introduces no wall-clock scheduling of its own — it holds no timers
- * and reads the clock only through the faked `Date` the consumer installs.
+ * Faking only Date keeps span timing and the settlement dispatcher (which uses no wall clock,
+ * precedent #13(b)) untouched.
*/
import { type MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
diff --git a/packages/server/src/bridge-watchdog.ts b/packages/server/src/bridge-watchdog.ts
index 41c9c2108..f995d450b 100644
--- a/packages/server/src/bridge-watchdog.ts
+++ b/packages/server/src/bridge-watchdog.ts
@@ -1,43 +1,7 @@
/**
- * Server-side bridge invariant watchdog.
- *
- * Y.Text-is-truth contract assertion site: after Observer B Phase 1 derives
- * fragment from `parse(ytext)`, the watchdog asserts that the post-write
- * bridge invariant holds:
- *
- * normalizeBridge(ytext.toString())
- * === normalizeBridge(prependFrontmatter(fm, mdManager.serialize(fragment)))
- *
- * Outside the `normalizeBridge` tolerance set, the watchdog fires:
- * - dev (`NODE_ENV=test` or `OK_BRIDGE_THROW_ON_VIOLATION=1`):
- * throws `BridgeInvariantViolationError` so integration tests + fuzz
- * runs surface the regression loudly.
- * - prod: emits a structured `bridge-invariant-violation` console.warn
- * event (machine-readable JSON) + increments
- * `bridgeInvariantViolations`. Rate-limited per (site, doc) tuple so
- * a single buggy doc cannot drown the signal.
- *
- * Lives in its own module because precedent #13(b) bans wall-clock
- * SCHEDULING (`setTimeout`, `setInterval`) in `server-observers.ts` —
- * see `bridge-no-wallclock.test.ts` for the enforced gate's `FORBIDDEN`
- * regex array. The rate-limiter needs `Date.now()` for window comparison;
- * co-locating it here keeps timer machinery isolated even though the
- * precedent gate doesn't cover `Date.now()` directly (server-observers.ts
- * itself uses `new Date().toISOString()` for the timestamp field of its
- * own structured-log events).
- *
- * Telemetry payload is bounded-cardinality and content-redacted by default:
- * site, docName-or-null, the tolerance-class label (`'untracked'` for
- * unknown classes — the comparator stack tolerates known byte classes plus
- * the parse-equivalence fallback, so a violation past ALL of them is by
- * definition untracked), and FNV-1a digests of the
- * ytext + fragment snapshots for cross-event correlation. The truncated
- * unifiedDiff is included as `diff` ONLY when `OK_TELEMETRY_VERBOSE=1`
- * (mirrors the sibling `bridge-merge-content-loss` opt-in pattern). Full
- * snapshots travel only on the thrown error for dev triage; never logged.
- *
- * @see packages/core/src/bridge/normalize.ts (tolerance set)
- * @see packages/core/src/bridge/bridge-invariant.ts (error type)
+ * Lives in its own module because precedent #13(b) bans wall-clock SCHEDULING (`setTimeout`,
+ * `setInterval`) in `server-observers.ts` — see `bridge-no-wallclock.test.ts` for the enforced
+ * gate's `FORBIDDEN` regex array.
*/
import type { MarkdownManager } from '@inkeep/open-knowledge-core';
@@ -241,20 +205,9 @@ interface AssertBridgeInvariantOpts {
nowMs?: number;
suppressDevThrow?: boolean;
/**
- * Parse-equivalence fallback (`isParseEquivalentBridge`). When the inputs
- * diverge beyond every `normalizeBridge` byte class, canonicalize the
- * ytext body through the caller's own parse→serialize pipeline and accept
- * the pair when the canonical forms match — the fragment then IS
- * `parse(ytext)` (precedent #38), so a resting serializer canonicalization
- * (CommonMark lazy continuations: an unindented wrapped list line, a
- * paragraph glued under a list, a `> `-less blockquote continuation) is a
- * tolerated equivalence, not a violation. Reported through the
- * `bridge-tolerance-applied` channel as `parse-equivalence`.
- *
- * Callers MUST bind the same parse options the doc's fragment derivation
- * uses (embed resolution, source path) — a mismatched pipeline degrades
- * safely toward alerting, never masking. Omitting the callback preserves
- * the strict normalize-only behavior.
+ * Parse-equivalence fallback: when inputs diverge beyond every `normalizeBridge` byte class,
+ * canonicalize the ytext body through the caller's own parse-serialize pipeline and accept a
+ * match, since the fragment then IS `parse(ytext)` (precedent #38). Bind the doc's own options.
*/
canonicalizeBody?: (body: string) => string;
}
diff --git a/packages/server/src/config-edit-origin.ts b/packages/server/src/config-edit-origin.ts
index f59af04ab..44c344f6e 100644
--- a/packages/server/src/config-edit-origin.ts
+++ b/packages/server/src/config-edit-origin.ts
@@ -1,24 +1,8 @@
import type { LocalTransactionOrigin } from '@hocuspocus/server';
/**
- * Transaction origin for the persistence-hook config-doc revert path.
- *
- * Object reference per precedent #1 — identity-based matching in the
- * `onStoreDocument` config-doc branch's entry-gate (`if
- * (lastTransactionOrigin === CONFIG_VALIDATION_REVERT_ORIGIN) return`).
- *
- * `skipStoreHooks: true` is the primary defense against a revert →
- * validate → revert loop; the entry-gate is belt-and-suspenders. The
- * revert transaction body replaces Y.Text content with the in-memory
- * LKG cache; `skipStoreHooks` prevents Hocuspocus from firing
- * `onStoreDocument` for the revert itself, so the hook never re-validates
- * what is already known to be the last good state.
- *
- * NOT a paired-write origin — the markdown bridge is bypassed for config
- * docs in `server-observer-extension.ts`. No `paired: true` flag — adding
- * one would route this origin through `isPairedWriteOrigin`'s settlement-
- * handler short-circuit, which is wrong: the revert is a Y.Text-only
- * mutation with no XmlFragment counterpart.
+ * Object reference per precedent #1 — identity-based matching in the `onStoreDocument` config-doc
+ * branch's entry-gate (`if (lastTransactionOrigin === CONFIG_VALIDATION_REVERT_ORIGIN) return`).
*/
export const CONFIG_VALIDATION_REVERT_ORIGIN = {
source: 'local' as const,
diff --git a/packages/server/src/content-filter.ts b/packages/server/src/content-filter.ts
index e39e61c05..164275dc5 100644
--- a/packages/server/src/content-filter.ts
+++ b/packages/server/src/content-filter.ts
@@ -262,24 +262,9 @@ function isTemplateContentAncestorDir(relativePath: string): boolean {
}
/**
- * True for a FILE on the shareable `.ok` artifact allow-list:
- * - `.ok/config.yml` and `.ok/.gitignore`, project root only
- * - `.ok/schemas/<name>.json`, project root only, flat — `.json` matched
- * case-insensitively like the schema enumerator's filter
- * - `<folder>/.ok/templates/<name>.md` at any depth, root included
- * - `<folder>/.ok/frontmatter.yml` at any depth — root included, because
- * the project root's own folder metadata lives at `.ok/frontmatter.yml`
- *
- * Exported because the symlink guard's `.ok` write exemption must consult
- * THIS predicate on the resolved path (precedent #55: one predicate for
- * "is this in sync scope", never a parallel copy that can drift).
- *
- * The folder-scoped shapes inherit the templates family's skip-dir bound:
- * these predicates are consulted on flat full paths (head listings, raw
- * watcher events), not only via the top-down walk that prunes skip-dir roots
- * first, so a `frontmatter.yml` vendored under `node_modules/` — or inside
- * `.ok/worktrees/<wt>/…`, whose prefix contains the skip-dir `.ok` — must
- * not leak in.
+ * True for a FILE on the shareable `.ok` artifact allow-list. Exported because the symlink guard's
+ * `.ok` write exemption must consult THIS predicate on the resolved path: one predicate for
+ * whether a path is in sync scope, never a parallel copy that can drift (precedent #55).
*/
export function isShareableOkArtifact(relativePath: string): boolean {
const segments = relativePath.split('/');
@@ -385,21 +370,8 @@ function isSingleDocAncestorDir(relativeDir: string, singleDocRelPath: string):
}
/**
- * Gate that keeps a descendant project's content out of the enclosing
- * project's scope.
- *
- * A directory carrying `.ok/config.yml` is its own project root, so a server
- * anchored there owns those files. Indexing them from the enclosing project as
- * well gives one file on disk two owners that reconcile only through disk
- * writes. `isProjectRoot` is the marker check, and it is also what keeps a
- * nested `.ok/` holding folder rules (`frontmatter.yml`, `templates/`) but no
- * `config.yml` admitted — folder metadata is not a project.
- *
- * Consulted by both `isExcluded` and `isDirExcluded` so a walker pruning
- * directories and a caller classifying a single path agree (precedent #55).
- *
- * Inert in single-file scope: an ephemeral single-doc filter has no enclosing
- * project, and the one admitted doc must stay admitted wherever it lives.
+ * Consulted by both `isExcluded` and `isDirExcluded` so a walker pruning directories and a caller
+ * classifying a single path agree (precedent #55).
*/
function createDescendantProjectGate(
projectDir: string,
@@ -445,27 +417,8 @@ function createDescendantProjectGate(
const IGNORE_FILE_NAMES = ['.gitignore', '.okignore'] as const;
/**
- * Resolve the patterns `git add` would honor *beyond* the project's
- * `.gitignore` tree: the per-clone `<git-common-dir>/info/exclude` (where
- * `ensureOkExcludedFromGit` itself writes `.ok/`), and the user's
- * `core.excludesfile` — or, when that is unset, git's documented
- * `$XDG_CONFIG_HOME/git/ignore` fallback.
- *
- * Mirroring these into `ContentFilter` keeps the sync walker and `git add`
- * agreed on scope (precedent #55). Without it, the walker can gather a
- * file `.git/info/exclude` already disqualifies, and the next push-cycle
- * `git add -- <path>` errors with `addIgnoredFile`.
- *
- * Gated on the `git rev-parse --git-common-dir` probe succeeding: when
- * `projectDir` isn't a git repo, `git add` is never called and there's no
- * symmetry to maintain — both `.git/info/exclude` AND the global
- * excludesfile are skipped, so non-git OK vaults aren't silently filtered
- * by the user's host-wide git rules.
- *
- * Returns the combined pattern list, or [] when none are reachable
- * (non-git dirs, `git` missing from PATH, files unreadable). All failures
- * are silent — the rest of the filter pipeline (project `.gitignore` +
- * `.okignore`) continues to apply.
+ * Mirroring these into `ContentFilter` keeps the sync walker and `git add` agreed on scope
+ * (precedent #55).
*/
function loadGitExcludeSources(projectDir: string, bytesAcc: { value: number }): string[] {
const commonDir = readGitCommonDirSync(projectDir);
@@ -647,19 +600,9 @@ type ContentFilterOrdinaryReadOpts = ContentFilterCommonReadOpts & {
type ContentFilterSyncReadOpts = ContentFilterCommonReadOpts & {
bypassFilters?: never;
/**
- * Admit the shareable `.ok` artifact allow-list (`isShareableOkArtifact`)
- * so the sync engine can stage and deletion-track team-shareable OK state
- * — `isExcluded` / `isDirExcluded` only; `isPathIgnored` (the asset-serve
- * gate) keeps the absolute floor, so sync admission never makes these
- * paths HTTP-servable. Paths the unified ignore rules reject stay refused
- * even with the scope: the gather walk and `git add` must agree on every
- * path (precedent #55), and a local-only project's blanket `.ok/` exclude
- * covers exactly this set. Sync-engine staging + head-listing use only —
- * index, sidebar, watcher-event, and conflict-partition callers must not
- * pass it, so these artifacts never surface as documents and their merge
- * conflicts keep the non-content auto-resolve class. Independent of
- * `showOk`. The type contract prevents combining this capability with
- * `bypassFilters`.
+ * Paths the unified ignore rules reject stay refused even with the scope: the gather walk and
+ * `git add` must agree on every path (precedent #55), and a local-only project's blanket `.ok/`
+ * exclude covers exactly this set.
*/
syncScope: { pathBase: 'content' | 'project' };
};
@@ -1205,20 +1148,9 @@ function parseIgnorePatterns(content: string): string[] {
}
/**
- * Re-anchor one nested ignore-file pattern into project-root-relative form for
- * the single flattened `ignore` matcher, preserving gitignore depth semantics.
- *
- * gitignore scoping: a bare basename (no leading or embedded slash; an optional
- * trailing `/` doesn't count) matches at ANY depth below the ignore file's
- * directory, while a pattern with a leading or embedded slash is anchored to
- * that directory. A naive `${relPrefix}/${pattern}` always injects an embedded
- * slash, which the `ignore` library reads as root-anchored — silently
- * collapsing an any-depth rule to "this exact level only." That made nested
- * `.blob-storage/` match `<dir>/.blob-storage` but miss `<dir>/agents-api/.blob-storage`,
- * so the sync walker handed `git add` a path git rejects with `addIgnoredFile`
- * (the predicate-symmetry break precedent #55 guards against). Non-anchored
- * patterns therefore get a globstar segment (`relPrefix` + slash + `**` + slash)
- * so they keep matching at any depth.
+ * Re-anchors one nested ignore-file pattern into project-root-relative form while preserving
+ * gitignore depth semantics: a naive prefix join injects an embedded slash, collapsing an
+ * any-depth rule to one level and breaking the predicate symmetry precedent #55 guards.
*/
function prefixPattern(pattern: string, relPrefix: string): string {
const negated = pattern.startsWith('!');
diff --git a/packages/server/src/content/generate-index.ts b/packages/server/src/content/generate-index.ts
index c3676c661..38a1e5870 100644
--- a/packages/server/src/content/generate-index.ts
+++ b/packages/server/src/content/generate-index.ts
@@ -91,14 +91,8 @@ function relativeTo(directory: string, path: string): string {
}
/**
- * Link form: relative, `./`-prefixed, extension retained. Precedent #56 names
- * relative the recommended default, and the extension keeps the link working in
+ * Precedent #56 names relative the recommended default, and the extension keeps the link working in
* GitHub, Obsidian, and an editor that never loaded OK.
- *
- * Deliberately never a bare folder (`./concepts/`): `ClassifiedLinkTarget` has
- * no folder variant, so a trailing slash resolves to a *document* of that name
- * and a folder link reads as broken to our own link validator. A subdirectory
- * link therefore targets the child index document, not the folder.
*/
function toHref(relativePath: string): string {
const normalized = relativePath.replaceAll('\\', '/');
diff --git a/packages/server/src/contributor-tracker.test.ts b/packages/server/src/contributor-tracker.test.ts
index 5a67b4f1e..94a26ba85 100644
--- a/packages/server/src/contributor-tracker.test.ts
+++ b/packages/server/src/contributor-tracker.test.ts
@@ -55,7 +55,7 @@ describe('recordContributor', () => {
});
});
-describe('formatContributors / formatContributorsFrom', () => {
+describe('formatContributorsFrom', () => {
test('returns empty string when no contributors', () => {
expect(formatContributorsForTest()).toBe('');
});
diff --git a/packages/server/src/contributor-tracker.ts b/packages/server/src/contributor-tracker.ts
index c14355228..1ef2e483d 100644
--- a/packages/server/src/contributor-tracker.ts
+++ b/packages/server/src/contributor-tracker.ts
@@ -139,14 +139,6 @@ export function __formatContributorsForTests(): string {
return formatted;
}
-/**
- * @deprecated Use swapContributors() + formatContributorsFrom() + restoreContributors()
- * for the race-free drain pattern. Kept for backward compatibility.
- */
-export function formatContributors(): string {
- return formatContributorsFrom(pendingContributors);
-}
-
export function restoreContributorEntry(writerId: string, entry: ContributorEntry): void {
let live = pendingContributors.get(writerId);
if (!live) {
@@ -170,14 +162,6 @@ export function restoreContributorEntry(writerId: string, entry: ContributorEntr
}
}
-/**
- * @deprecated Use swapContributors() for atomic drain. Kept for backward compatibility.
- * Clear the pending contributors map.
- */
-export function clearContributors(): void {
- pendingContributors.clear();
-}
-
export function contributorCount(): number {
return pendingContributors.size;
}
diff --git a/packages/server/src/error-log-discipline.test.ts b/packages/server/src/error-log-discipline.test.ts
index 66264790b..f23881774 100644
--- a/packages/server/src/error-log-discipline.test.ts
+++ b/packages/server/src/error-log-discipline.test.ts
@@ -1,30 +1,3 @@
-/**
- * Source-scan STOP rule for error-log payload discipline: error/warn logger
- * calls pass the RAW error value under the `err` key — never a
- * string-coerced copy (`err.message`, `String(err)`, `(err as
- * Error).message`, `x instanceof Error ? x.message : String(x)`). The pino
- * serializers on both the server logger (`logger.ts`) and the desktop root
- * logger (`desktop-logger.ts`) capture name/message/stack from a raw Error;
- * a pre-coerced string discards the stack, which is the difference between
- * a correlatable JSONL bundle line and a dead-end one.
- *
- * Scope mirrors the Node-side logging surface: `packages/server/src`,
- * `packages/cli/src`, and `packages/desktop/src/main` (renderer is not
- * pino-backed). `console.*` receivers are exempt — the two sanctioned
- * console.warn styles (bracket-prefix; structured JSON) are their own
- * convention and stay out of this rule's reach.
- *
- * Escape hatch: suffix the offending line (or the call line) with
- * `// error-log-shape-ok: <why>` for a site where a string copy is the
- * point (e.g. capturing a message snapshot alongside the raw err), or add
- * a FILE_ALLOWLIST entry with a structural reason for a whole surface.
- *
- * The predicate is line-window based, so it has planted-positive +
- * adjacent-negative self-tests below (an absence-checker without a planted
- * positive is a vacuous no-op — same discipline as
- * console-discipline.test.ts).
- */
-
import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { basename, dirname, join, relative, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
diff --git a/packages/server/src/external-change-attribution.ts b/packages/server/src/external-change-attribution.ts
index 51fe38909..e53187ab1 100644
--- a/packages/server/src/external-change-attribution.ts
+++ b/packages/server/src/external-change-attribution.ts
@@ -1,24 +1,6 @@
/**
- * A short-lived claim that a disk change about to happen was made by a person.
- *
- * `applyExternalChange` attributes everything it ingests to `FILE_SYSTEM_WRITER`
- * — correct for its usual caller, the file watcher, which sees bytes appear and
- * cannot know why. But a merge-conflict resolution is a human decision the
- * server itself performed on the user's behalf: it writes the resolved content
- * to disk through git, and the watcher then ingests it like any other external
- * edit. The Timeline row lands as "File System", crediting nobody for what is
- * arguably the highest-stakes edit the product supports.
- *
- * A handler that is about to make such a write files a claim here first; the
- * ingest consumes it and attributes the row to that writer instead. The writer
- * id is an ordinary `principal-<UUID>` from the precedent #25 taxonomy — this
- * changes who a write is credited to, never what a writer id may look like.
- *
- * Deliberately weak by design. Claims are keyed by docName, single-use, and
- * expire; anything unmatched falls back to `FILE_SYSTEM_WRITER`. A lost race
- * therefore reproduces today's behaviour, while a stale claim can never
- * outlive its window and mis-credit a later unrelated edit. Wrong-but-silent
- * is the one outcome attribution must not have.
+ * The writer id is an ordinary `principal-<UUID>` from the precedent #25 taxonomy — this changes
+ * who a write is credited to, never what a writer id may look like.
*/
import { getLogger } from './logger.ts';
diff --git a/packages/server/src/external-change.ts b/packages/server/src/external-change.ts
index 8916be954..4f890b93b 100644
--- a/packages/server/src/external-change.ts
+++ b/packages/server/src/external-change.ts
@@ -39,35 +39,6 @@ import { FILE_SYSTEM_WRITER } from './shadow-repo.ts';
export { FILE_WATCHER_ORIGIN } from './disk-content-intake.ts';
-/**
- * Apply external file content to a live Y.Doc — the throwing core of the
- * disk→CRDT bridge. Both server-factory.ts (CLI) and the dev plugin delegate here.
- *
- * Under the Y.Text-is-truth contract (precedent #38):
- * 1. Looks up the live Y.Doc by docName (no-op if missing; system + config
- * docs short-circuit)
- * 2. Captures the prior FM region from `Y.Text('source')` for the
- * edit-surface telemetry counter (FM lives in the YAML region of
- * Y.Text — no Y.Map metadata cache)
- * 3. Routes through `composeAndWriteRawBody` inside
- * `document.transact(..., FILE_WATCHER_ORIGIN)`: Y.Text receives the
- * disk bytes verbatim via `applyFastDiff`; XmlFragment derives via
- * `parse(body) → updateYFragment` (the post-write watchdog asserts
- * the bridge invariant)
- * 4. Emits the FM-change telemetry counter when the captured FM
- * differs from the disk content's FM
- * 5. Records the file-system contributor and advances reconciledBase to
- * the raw disk bytes
- *
- * `FILE_WATCHER_ORIGIN` carries `context.paired: true` and
- * `skipStoreHooks: true` — the paired marker opts the bridge observers'
- * paired-write fast-paths in; skipStoreHooks prevents persistence feedback
- * loops.
- *
- * Throws on parse failure — callers choose their own error strategy.
- * `BridgeInvariantViolationError` re-throws past every soft-recovery layer
- * so dev/test surfaces regressions loudly.
- */
export function applyExternalChange(
durabilityState: DocumentDurabilityState,
hocuspocus: Hocuspocus,
diff --git a/packages/server/src/frontmatter-malformed-error.ts b/packages/server/src/frontmatter-malformed-error.ts
index 34fdb3cea..5431aae76 100644
--- a/packages/server/src/frontmatter-malformed-error.ts
+++ b/packages/server/src/frontmatter-malformed-error.ts
@@ -1,42 +1,6 @@
/**
- * Malformed-frontmatter write refusal: typed error + RFC 9457 envelope helper.
- *
- * Agent writes are byte-faithful (precedent #38, Y.Text-is-truth): the bytes
- * the agent submits land in `Y.Text('source')` verbatim. That's load-bearing
- * for source-form preservation, but it means a payload whose YAML region is
- * unparseable also lands on disk verbatim — the property panel then renders
- * the "Frontmatter YAML is malformed" banner and the file's own keys are
- * unrecoverable without a hand-edit. The most common shape: a
- * string value containing an unquoted YAML-significant character (`:`, `#`,
- * leading `-`), e.g. `title: The End of 3% Mortgages: Why ...`.
- *
- * The gate lives at `applyAgentMarkdownWriteInner` and fires when the agent's
- * write actually CHANGES the FM region (`finalFm !== existingFm`). Existing
- * docs that already carry malformed FM on disk continue to accept body-only
- * writes — the rejection is targeted at the introducer, not the inheritor.
- *
- * A second arm catches the same outcome by a different route: an append or
- * prepend inherits `existingFm` by construction, so it can never trip the
- * first arm, but it CAN place a `---`-fenced non-mapping span at byte 0 of a
- * document that has no frontmatter. The composed bytes then re-partition and
- * that span becomes the FM region — malformed frontmatter the agent never
- * asked for. Same envelope, but it carries its own `refusalClass`
- * (`byte-0-promotion`) and `hint`: nothing was parsed, so the YAML-quoting
- * advice would misdirect, and counting it as a parse error would blunt the
- * one signal the class label exists to give.
- *
- * Wire shape — slim RFC 9457 envelope at HTTP 400:
- *
- * {
- * "type": "urn:ok:error:frontmatter-malformed",
- * "title": "Frontmatter YAML is malformed.",
- * "status": 400,
- * "detail": "<parser message>. Common cause: a string value contains an
- * unquoted YAML-significant character (`:`, `#`, leading `-`).
- * Quote the value, e.g. `title: \"Foo: bar\"`.",
- * "file": "<.md path>",
- * "parseError": "<raw yaml@2 parser message>"
- * }
+ * Agent writes are byte-faithful (precedent #38, Y.Text-is-truth): the bytes the agent submits land
+ * in `Y.Text('source')` verbatim.
*/
import type { ServerResponse } from 'node:http';
diff --git a/packages/server/src/git-worktree-status.ts b/packages/server/src/git-worktree-status.ts
index cff7b4912..9415785e7 100644
--- a/packages/server/src/git-worktree-status.ts
+++ b/packages/server/src/git-worktree-status.ts
@@ -91,24 +91,8 @@ export async function readIncomingEntries(git: SimpleGit): Promise<GitWorktreeEn
}
/**
- * Read the working tree's status.
- *
- * `toOpenTarget` maps a project-relative path to where clicking it navigates,
- * or undefined when it navigates nowhere. Threaded in for the same reason as
- * `isSyncScoped`: the answer belongs to the server's live file index and
- * content filter, and a path this surface guessed at would render as a link
- * to a 404.
- *
- * `isSyncScoped` decides whether Open Knowledge would ever commit a given
- * project-relative path. It is threaded in rather than recomputed here so the
- * answer comes from the sync engine's own admission predicate — the same one
- * the staging walk consults (precedent #55). A UI that marked a path in-scope
- * that Push then skipped would be worse than showing nothing.
- *
- * Never throws: a repository that is unborn, mid-rebase, or not a git dir at
- * all yields an empty status rather than failing the popover. The engine's own
- * `sync-status` payload is what reports sync health; this surface is
- * supplementary detail.
+ * It is threaded in rather than recomputed here so the answer comes from the sync engine's own
+ * admission predicate — the same one the staging walk consults (precedent #55).
*/
export async function readWorktreeStatus(
projectDir: string,
diff --git a/packages/server/src/http/file-ops-routes.ts b/packages/server/src/http/file-ops-routes.ts
index f275fc71a..b07107f99 100644
--- a/packages/server/src/http/file-ops-routes.ts
+++ b/packages/server/src/http/file-ops-routes.ts
@@ -1463,8 +1463,10 @@ export function createFileOpsRoutes(deps: FileOpsRouteDeps): ApiRouteGroup {
}
const { parentDocName, placement } = validated.value;
- // attribution — mirrors precedent #24/#25 and lets operators trace
- // (precedent #24).
+ /**
+ * Identity extraction precedes every semantic error emission below (precedent #24/#25),
+ * so upload logs carry attribution operators can trace.
+ */
const { agentId, agentName } = extractAgentIdentity(
Object.fromEntries(new URL(req.url ?? '', 'http://localhost').searchParams.entries()),
);
diff --git a/packages/server/src/http/local-api-dispatch.ts b/packages/server/src/http/local-api-dispatch.ts
index 31a0701e1..00d4880bd 100644
--- a/packages/server/src/http/local-api-dispatch.ts
+++ b/packages/server/src/http/local-api-dispatch.ts
@@ -1,41 +1,6 @@
/**
- * In-process dispatch for MCP tool self-calls.
- *
- * The MCP tools mounted on the project server (`mcp-http.ts`) historically
- * reached server capabilities by issuing HTTP requests to their own listener
- * — a full TCP + HTTP-parse round trip to a handler living in the same
- * process. With the capability services extracted (`services/*`), the
- * handlers behind those endpoints are thin marshaling layers, so the
- * self-call can collapse to a function call: run the SAME handler against a
- * synthetic req/res pair and hand the captured wire body back to the tool.
- *
- * Byte parity is structural — the handler code that writes the HTTP
- * response writes the local response, and the tool-side normalization
- * (`normalizeResponse` in `mcp/tools/shared.ts`) consumes both transports
- * through one code path. Attribution parity is structural for the same
- * reason: identity rides the request body exactly as it does over HTTP
- * (precedent #24 — identity at entry).
- *
- * The dispatch deliberately does NOT run the `/api/*` admission pipeline
- * (`api-pipeline.ts`): request-id echo, CORS, and the loopback/workspace-Host
- * mutating gates defend the network listener. A same-process caller is
- * inside that trust boundary already — a self-call over HTTP always
- * originated from loopback and passed those gates vacuously.
- *
- * Skipping the pipeline also skips its telemetry triple: the HTTP SERVER
- * span, the `http.server.request.duration{http.route}` histogram sample,
- * and the `api.access` log line. Collapsed MCP traffic therefore leaves
- * the `/api/*`-keyed observability surfaces and shows up instead on the
- * MCP tool layer (`mcp/tool-telemetry.ts`: `mcp.tool.<name>` span +
- * `ok.mcp.tool.duration` histogram + per-tool error counting), which
- * already answers per-call latency and error rate for agent traffic.
- * Anything keyed on `http.route` for these endpoints sees browser/SDK
- * traffic only once this ships.
- *
- * Scope is allowlist-gated by the resolver the api extension supplies:
- * only endpoints whose handlers are thin over a capability service
- * (or an equally thin primitive like the derived-document-index reads)
- * resolve; everything else returns `null` and the tool falls back to HTTP.
+ * Attribution parity is structural for the same reason: identity rides the request body exactly as
+ * it does over HTTP (precedent #24 — identity at entry).
*/
import { EventEmitter } from 'node:events';
diff --git a/packages/server/src/http/request-validation.ts b/packages/server/src/http/request-validation.ts
index 0ad679221..534397fe3 100644
--- a/packages/server/src/http/request-validation.ts
+++ b/packages/server/src/http/request-validation.ts
@@ -1,24 +1,6 @@
/**
- * `withValidation()` middleware wrapper for HTTP request bodies.
- *
- * Structural enforcement that handlers can't be added without going through
- * Zod validation: at handler registration, wrap with
- * `withValidation(XyzRequestSchema, async (req, res, body) => { ... })`.
- * The handler receives an already-validated, typed `body`. Failure auto-
- * routes through `errorResponse(res, 400, 'urn:ok:error:invalid-request', ...)`
- * — the inner handler never sees a malformed body.
- *
- * Body-shape errors emitted by this wrapper happen BEFORE
- * `extractAgentIdentity` is called by the inner handler, which is
- * semantically OK: no Y.Doc mutation is attempted, so the response is
- * legitimately anonymous. Semantic errors (handler-internal logic) must be
- * post-identity (attributed). The `attribution-sweep-coverage.test.ts`
- * ordering check enforces the distinction on mutating
+ * The `attribution-sweep-coverage.test.ts` ordering check enforces the distinction on mutating
* handlers (precedent #24).
- *
- * Multipart binary parsing remains busboy's job (`POST /api/upload`); for
- * multipart handlers, call `validateBody(schema, parsedMetadata)` after
- * busboy assembles the metadata fields.
*/
import type { IncomingMessage, ServerResponse } from 'node:http';
diff --git a/packages/server/src/http/share-routes.ts b/packages/server/src/http/share-routes.ts
index 7d897b813..16df2b81f 100644
--- a/packages/server/src/http/share-routes.ts
+++ b/packages/server/src/http/share-routes.ts
@@ -289,7 +289,10 @@ export function createShareRoutes(deps: ShareRouteDeps): ApiRouteGroup {
);
return;
}
- // precedent #55 content-scope predicate symmetry. Kind-aware: an empty
+ /**
+ * Validate the path shape before it reaches git's `<ref>:<path>` ref-spec, mirroring the
+ * sibling share handlers (precedent #55 content-scope predicate symmetry).
+ */
if (!isValidBranchInfoPath(body.path, body.kind)) {
errorResponse(res, 400, 'urn:ok:error:invalid-request', 'path is missing or malformed.', {
handler: SHARE_TARGET_STATUS_HANDLER_TAG,
diff --git a/packages/server/src/http/sync-routes.ts b/packages/server/src/http/sync-routes.ts
index b92b30655..757855903 100644
--- a/packages/server/src/http/sync-routes.ts
+++ b/packages/server/src/http/sync-routes.ts
@@ -238,7 +238,10 @@ export function createSyncRoutes(deps: SyncRouteDeps): ApiRouteGroup {
return;
}
const { file, strategy, content } = body;
- // handlers (precedent #24); body `principalId` is ignored by contract,
+ /**
+ * `extractActorIdentity` is the mandated resolver for actor-attributed handlers
+ * (precedent #24); body `principalId` is ignored by contract.
+ */
const actor = extractActorIdentity(body as unknown as Record<string, unknown>, getPrincipal);
let claimedDocName: string | undefined;
if (projectDir && (actor.kind === 'agent' || actor.kind === 'principal')) {
diff --git a/packages/server/src/idle-shutdown.ts b/packages/server/src/idle-shutdown.ts
index d1dbc96df..8549a68a5 100644
--- a/packages/server/src/idle-shutdown.ts
+++ b/packages/server/src/idle-shutdown.ts
@@ -1,20 +1,7 @@
/**
- * Idle-shutdown primitive — WebSocket-client-count-only.
- *
- * Attaches an `upgrade` listener to the HTTP server and counts WebSocket
- * upgrade requests at `/collab`. When the counter hits zero for a configured
- * `thresholdMs`, `onShutdown` fires.
- *
- * Key property (precedent #14): DirectConnections
- * (CC1 broadcaster, AgentSessionManager) are invisible to this primitive —
- * they never transit an HTTP upgrade at `/collab`, so `getConnectionsCount()`
- * on the Hocuspocus instance is NOT consulted. Raw upgrade count is the sole
- * signal. This is the only correct way to idle-shutdown under a live
- * server whose CC1 DirectConnection is permanent.
- *
- * The scheduler is injectable per precedent #13b (implicit time
- * coupling is a test smell). Production defaults to `setTimeout`/`clearTimeout`
- * passthrough; tests inject a `ManualScheduler` for deterministic advance.
+ * Idle-shutdown primitive counting only WebSocket upgrades at `/collab`. DirectConnections are
+ * invisible to it by design (precedent #14), so `getConnectionsCount()` is never consulted; the
+ * scheduler is injectable per precedent #13(b).
*/
import type { Server as HttpServer, IncomingMessage } from 'node:http';
@@ -45,15 +32,9 @@ export interface CollabClientCounter {
}
/**
- * Count live `/collab` WebSocket upgrades on `httpServer`.
- *
- * The single counting implementation: idle-shutdown schedules off it, and the
- * server-info route discloses it so a caller about to terminate this process
- * can ask "is anything using it" rather than "who started it" (the latter is
- * unanswerable — the process title is rewritten at start). DirectConnections
- * (CC1 broadcaster, agent sessions) never transit an upgrade and are invisible
- * here, which is what keeps a permanently-connected internal consumer from
- * pinning the count above zero (precedent #14).
+ * DirectConnections (CC1 broadcaster, agent sessions) never transit an upgrade and are invisible
+ * here, which is what keeps a permanently-connected internal consumer from pinning the count above
+ * zero (precedent #14).
*/
export function attachCollabClientCounter(
httpServer: HttpServer,
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index 019aa1232..c905785ae 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -124,11 +124,7 @@ export {
} from './content-filter.ts';
export { safeContentPath } from './content-path.ts';
export {
- // oxlint-disable-next-line typescript/no-deprecated
- clearContributors,
contributorCount,
- // oxlint-disable-next-line typescript/no-deprecated
- formatContributors,
formatContributorsFrom,
recordContributor,
restoreContributors,
@@ -435,8 +431,6 @@ export {
type FileEntry,
formatPackRationale,
isKnownPackId,
- // oxlint-disable-next-line typescript/no-deprecated
- LOG_MD_TEMPLATE,
listStarterPacks,
type PackId,
planSeed,
@@ -447,12 +441,8 @@ export {
SeedRootDirError,
type SkipEntry,
STARTER_FOLDER_FRONTMATTER_FILENAME,
- // oxlint-disable-next-line typescript/no-deprecated
- STARTER_FOLDERS,
STARTER_PACK_IDS,
STARTER_PACKS,
- // oxlint-disable-next-line typescript/no-deprecated
- STARTER_TEMPLATES,
type StarterFolder,
type StarterPack,
type StarterPackEntryCounts,
diff --git a/packages/server/src/link-classification-uniformity.test.ts b/packages/server/src/link-classification-uniformity.test.ts
index 20ce371a5..3b838aabe 100644
--- a/packages/server/src/link-classification-uniformity.test.ts
+++ b/packages/server/src/link-classification-uniformity.test.ts
@@ -1,30 +1,6 @@
/**
- * Cross-plane link-classification uniformity.
- *
- * Every authored link occurrence must have exactly ONE canonical
- * classification — `{targetKind, resolvedTarget, status, reason,
- * resolutionMethod}` — computed once against the complete inventory
- * (documents AND files) over the complete form set (wiki, inline, reference,
- * html-img), and consumed verbatim by every reporting surface.
- *
- * Each classification plane already has its own unit tests and each one passes.
- * That is precisely the gap this file closes: the planes are only ever exercised
- * in isolation, so a disagreement between them is invisible until they are
- * COMPARED over the same document and the same inventory. `link-syntax.ts` cites
- * precedent #56 and is pinned by divergence tests for *recognition*; this is the
- * equivalent pin for *classification*.
- *
- * The two planes under comparison:
- *
- * - **A — document graph** (`backlink-index.ts`): feeds Links ▸ Outgoing and the
- * Problems rows that carry `linkTarget`.
- * - **B — local-target assessment** (`local-target-assessment.ts`): feeds
- * Links ▸ Local files and the Problems rows that carry `localTarget`.
- *
- * The inventory below is a boundary fake, not a mock of either plane: both
- * planes run their real production classifiers over it, and the assertions check
- * what those classifiers conclude. A fake reporting the wrong membership would
- * fail these tests rather than hide a bug.
+ * `link-syntax.ts` cites precedent #56 and is pinned by divergence tests for *recognition*; this is
+ * the equivalent pin for *classification*.
*/
import { describe, expect, test } from 'vitest';
diff --git a/packages/server/src/link-preview/guarded-fetch.ts b/packages/server/src/link-preview/guarded-fetch.ts
index 36b500195..7f7e7660e 100644
--- a/packages/server/src/link-preview/guarded-fetch.ts
+++ b/packages/server/src/link-preview/guarded-fetch.ts
@@ -42,10 +42,7 @@ export interface GuardedFetchFailure {
export type GuardedFetchResult = GuardedFetchSuccess | GuardedFetchFailure;
-/**
- * One resolved DNS record; mirrors the fields of a getaddrinfo lookup.
- * @lintignore Referenced by the exported HostResolver type; no direct importer.
- */
+/** @lintignore Referenced by the exported HostResolver type; no direct importer. */
export interface ResolvedAddress {
address: string;
family: 4 | 6;
diff --git a/packages/server/src/link-preview/request-gate.ts b/packages/server/src/link-preview/request-gate.ts
index 1e52c9810..ec3b46f06 100644
--- a/packages/server/src/link-preview/request-gate.ts
+++ b/packages/server/src/link-preview/request-gate.ts
@@ -1,7 +1,4 @@
-/**
- * Why a request was refused, so the caller can pick the right problem type.
- * @lintignore Referenced by the exported LinkPreviewGateVerdict type; no direct importer.
- */
+/** @lintignore Referenced by the exported LinkPreviewGateVerdict type; no direct importer. */
export type LinkPreviewGateRejection = 'origin' | 'content-type';
export type LinkPreviewGateVerdict = { ok: true } | { ok: false; reason: LinkPreviewGateRejection };
diff --git a/packages/server/src/link-syntax.ts b/packages/server/src/link-syntax.ts
index f860ad14e..9760ca186 100644
--- a/packages/server/src/link-syntax.ts
+++ b/packages/server/src/link-syntax.ts
@@ -1,26 +1,7 @@
/**
- * Single line-oriented grammar for the server's inline link recognizers:
- * `[[wiki links]]` / `![[wiki embeds]]` and `[markdown](links)` /
- * `![markdown](images)`. Consumers: `backlink-index.ts`,
- * `managed-rename-rewrite.ts`, `suggest-links.ts`, `asset-references.ts`.
- * Before consolidation each site owned a subtly different regex, so a link
- * could count for backlinks yet be missed by rename rewriting — the
- * divergence class the canonical link contract (precedent #56) exists to
- * prevent. Recognition is consolidated here; resolution stays in
- * `resolveInternalHref` / `classifyMarkdownHref` (core).
- *
- * Line-oriented: callers pre-split into lines, so the character classes
- * exclude `\n` defensively rather than relying on multiline flags.
- * cf. packages/core/src/extensions/wiki-link.ts WIKI_LINK_PATTERN — the
- * editor-side pattern (no `\n` exclusion, `^`-anchored) is a sibling grammar
- * that must stay observationally aligned with this one on shared inputs.
- *
- * Known deliberate residual: `server-observers.ts` `markdownBareText` strips
- * link syntax with a LOOSER regex (`/!?\[([^\]]*)\]\([^)]*\)/g`) that admits
- * whitespace in destinations and ignores titles/angle wrappers. That is a
- * reduction for carrier attribution, not link recognition — over-stripping
- * is acceptable there, under-stripping is not — so it intentionally does not
- * share this grammar. See the divergence pins in `link-syntax.test.ts`.
+ * Before consolidation each site owned a subtly different regex, so a link could count for
+ * backlinks yet be missed by rename rewriting — the divergence class the canonical link contract
+ * (precedent #56) exists to prevent.
*/
const WIKI_BODY_SOURCE = String.raw`\[\[([^\n#[\]|]+)(?:#([^\n[\]|]+))?(?:\|([^\n[\]]+))?\]\]`;
diff --git a/packages/server/src/managed-artifact-persistence.ts b/packages/server/src/managed-artifact-persistence.ts
index 429f40ed8..d83313c2a 100644
--- a/packages/server/src/managed-artifact-persistence.ts
+++ b/packages/server/src/managed-artifact-persistence.ts
@@ -1,29 +1,7 @@
/**
- * Persistence for managed-artifact docs — skills (`__skill__/<scope>/<name>`).
- * The CRDT amendment makes these first-class CRDT documents that persist to
- * `.ok/`. Templates are ordinary content docs now (`<folder>/.ok/templates/<name>`,
- * hydrated by the content persistence path); the retired `__template__/…`
- * synthetic name survives here only as a load/store tombstone so a stale client
- * name never seeds a second doc or writes a literal `__template__/…` file.
- *
- * Shape: a HYBRID of the two existing persistence branches.
- * - LOAD/STORE BODY mirrors the *document* branch (`persistence.ts`
- * onLoadDocument), NOT the Y.Text-only config branch — managed-artifact docs
- * are full XmlFragment+Y.Text docs (the observer bridge RUNS for them, so
- * WYSIWYG works). Load is a paired-write under `FILE_WATCHER_ORIGIN`.
- * - PATH RESOLUTION + atomic-write + file-lock + LKG + reconcile-on-concurrent
- * mirror the *config* branch (`config-persistence.ts`) — these are `.ok/`
- * files that a second OK window (or a hand/CLI edit) can race.
- *
- * Verbatim fidelity (precedent #38, Y.Text-is-truth): the store serializes the
- * body from `Y.Text('source')` — the raw source bytes — NEVER from the
- * XmlFragment (which would re-canonicalize the markdown that gets projected
- * verbatim into an agent's context). This is the single most load-bearing rule
- * in this module.
- *
- * Reconciled-base accessors are injected via ctx (not imported from
- * `persistence.ts`) to avoid a circular import — `persistence.ts` imports this
- * module for its third branch.
+ * Verbatim fidelity (precedent #38, Y.Text-is-truth): the store serializes the body from
+ * `Y.Text('source')` — the raw source bytes — NEVER from the XmlFragment (which would
+ * re-canonicalize the markdown that gets projected verbatim into an agent's context).
*/
import { existsSync, readdirSync, readFileSync } from 'node:fs';
@@ -315,14 +293,7 @@ async function backupExternalSkillOnce(
}
}
-/**
- * Persist a managed-artifact doc to disk. Serializes from `Y.Text('source')`
- * (verbatim — precedent #38). File-locked + atomic; reconciles instead of
- * clobbering when another writer changed the file since our LKG.
- *
- * Entry gate: a store whose last transaction was the load/reconcile import
- * (`FILE_WATCHER_ORIGIN`) is a no-op (don't write back what we just read).
- */
+/** Serializes from `Y.Text('source')` (verbatim — precedent #38). */
export async function storeManagedArtifactDoc(
document: Y.Doc,
documentName: string,
diff --git a/packages/server/src/managed-rename.test.ts b/packages/server/src/managed-rename.test.ts
index 6e6e600af..102b06122 100644
--- a/packages/server/src/managed-rename.test.ts
+++ b/packages/server/src/managed-rename.test.ts
@@ -1,23 +1,7 @@
/**
- * Unit tests for the MANAGED_RENAME_ORIGIN paired-write order property.
- *
- * `applyManagedRenameMapToLoadedDocument` in api-extension.ts writes both
- * Y.Text and Y.XmlFragment inside one `doc.transact(..., MANAGED_RENAME_ORIGIN)`
- * drain. Under the Y.Text-is-truth contract (precedent #38), Y.Text is the
- * source of truth — the write order MUST be ytext-first / fragment-second so
- * that a partial failure (second write throws after the first succeeds) leaves
- * ytext in the new state and Observer B Phase 1 re-derives fragment from
- * `parse(ytext)` on the next non-paired settlement.
- *
- * Reversed order (fragment-first / ytext-second) silently reverts the rename
- * if updateYFragment succeeds and applyFastDiff then throws: fragment holds
- * the new state but ytext is stale, and Observer B's next dispatch re-derives
- * fragment from the STALE ytext, undoing the rename without any visible error.
- *
- * This file mirrors the load-bearing properties already pinned for
- * `composeAndWriteRawBody` in bridge-intake.test.ts (write-order observation +
- * partial-failure recovery), specialized to the rename call site whose write
- * sequence is open-coded inside the api-extension closure.
+ * Pins the MANAGED_RENAME_ORIGIN paired-write order: under precedent #38 the write must be
+ * ytext-first and fragment-second, so a partial failure leaves ytext new and Observer B re-derives
+ * from it. Reversed, a throw after the fragment write silently reverts the rename.
*/
import { applyFastDiff, sharedExtensions, stripFrontmatter } from '@inkeep/open-knowledge-core';
diff --git a/packages/server/src/mcp/agent-identity.ts b/packages/server/src/mcp/agent-identity.ts
index 8c85b2fbf..b436a42fa 100644
--- a/packages/server/src/mcp/agent-identity.ts
+++ b/packages/server/src/mcp/agent-identity.ts
@@ -1,15 +1,6 @@
/**
- * Agent identity — captured from the MCP initialize handshake.
- *
- * Long-lived identity (who is this agent?) is derived from MCP `clientInfo`
- * and a server-generated `connectionId`. Per architectural precedent #8:
- * long-lived identity is separate from short-lived session concerns.
- *
- * `connectionId` is the per-session UUID and is the only stable disambiguator
- * when multiple clients report the same `clientInfo.name` (e.g. two Claude
- * Code instances connected to the same `ok start`). `clientInfo.name` is
- * mandatory in the MCP `InitializeRequestSchema`, so post-handshake every
- * session has a name.
+ * Per architectural precedent #8: long-lived identity is separate from short-lived session
+ * concerns.
*/
export interface AgentIdentity {
diff --git a/packages/server/src/mcp/tools/shared.ts b/packages/server/src/mcp/tools/shared.ts
index 051df3ba6..1943d3367 100644
--- a/packages/server/src/mcp/tools/shared.ts
+++ b/packages/server/src/mcp/tools/shared.ts
@@ -16,12 +16,7 @@ import { resolveWithinRoot } from './path-safety.ts';
export type ServerInstance = McpServer;
export type ConfigOrResolver = Config | ((cwd?: string) => Promise<Config>);
-/**
- * The agent-identity fields every mutating route accepts for attribution
- * (precedent #24/#25). Spread into a POST body: `{ ...agentIdentityFields(id) }`.
- * Returns an empty object when no identity is bound, so anonymous writes stay
- * anonymous. Single source for the four CRUD verbs + any future write tool.
- */
+/** The agent-identity fields every mutating route accepts for attribution (precedent #24/#25). */
export function agentIdentityFields(identity: AgentIdentity | undefined): Record<string, unknown> {
return identity
? {
@@ -296,21 +291,8 @@ export function normalizeDocName(
}
/**
- * Canonicalize a server response into the `{ ok: boolean, ...payload }` shape
- * MCP-tool consumers read against. The boundary canonicalizer pattern lets
- * tool handlers stay unaware of HTTP status semantics or the RFC 9457 wire
- * shape (precedent #38).
- *
- * Server contract:
- * - 2xx: flat success body, e.g. `{ renamed, rewrittenDocs, summary? }`
- * with `application/json`. No `ok` wrapper.
- * - 4xx/5xx: RFC 9457 `{ type, title, status, instance, detail?, ...extensions }`
- * with `application/problem+json`. Extensions (e.g. `colliding`) ride
- * alongside the canonical fields.
- *
- * Body extension members are spread onto the top level so consumers
- * automatically pick up new typed extensions (e.g. `colliding[]`) without a
- * per-tool change.
+ * The boundary canonicalizer pattern lets tool handlers stay unaware of HTTP status semantics or
+ * the RFC 9457 wire shape (precedent #38).
*/
function normalizeResponse(
res: { ok: boolean; status: number },
diff --git a/packages/server/src/mermaid-persistence.ts b/packages/server/src/mermaid-persistence.ts
index 56e5b9735..83a847ead 100644
--- a/packages/server/src/mermaid-persistence.ts
+++ b/packages/server/src/mermaid-persistence.ts
@@ -1,25 +1,6 @@
/**
- * Persistence for standalone Mermaid docs — `.mmd` / `.mermaid` files whose
- * docName RETAINS its extension (`assets/flow.mmd`). A FOURTH doc class.
- *
- * Shape: config-persistence's Y.Text-only body handling — the markdown observer
- * bridge is gated OFF for these (see `server-observer-extension.ts` /
- * `isMermaidDoc`), so the diagram source is stored VERBATIM. Routing the source
- * through the markdown pipeline (as `.md`/`.mdx` docs do) would re-canonicalize
- * it (blank-line normalization, escaping, fence promotion) and corrupt Mermaid
- * syntax. Verbatim fidelity (precedent #38, Y.Text-is-truth): the store
- * serializes from `Y.Text('source')` and never touches the XmlFragment.
- *
- * Unlike config docs (bounded `.ok/` set, schema-validated) these are arbitrary
- * user content files: no validation (any text is a valid `.mmd` — parse-failing
- * content still renders as source), and path resolution goes to the content dir.
- * A concurrent external writer (CLI / another editor) is caught by a
- * read-before-write reconcile; no file lock is taken (one server per contentDir
- * per `server.lock`, and Hocuspocus serializes `onStoreDocument` per doc).
- *
- * The path resolver is replicated here (rather than importing `safeContentPath`
- * from `persistence.ts`) to avoid a circular import — `persistence.ts` imports
- * this module for its dispatch branch.
+ * Verbatim fidelity (precedent #38, Y.Text-is-truth): the store serializes from `Y.Text('source')`
+ * and never touches the XmlFragment.
*/
import { existsSync, readFileSync } from 'node:fs';
@@ -92,14 +73,7 @@ export function loadMermaidDoc(
ctx.lkgCache.set(documentName, raw);
}
-/**
- * Persist a Mermaid doc to disk. Serializes from `Y.Text('source')` (verbatim —
- * precedent #38); atomic tmp+rename. Entry gate: a store whose last transaction
- * was the load/reconcile import (`MERMAID_SOURCE_ORIGIN`) is a no-op — belt-and-
- * suspenders alongside that origin's `skipStoreHooks: true`. Reconciles (imports
- * disk) instead of clobbering when an external writer changed the file since our
- * LKG.
- */
+/** Serializes from `Y.Text('source')` (verbatim — precedent #38); atomic tmp+rename. */
export async function storeMermaidDoc(
document: Y.Doc,
documentName: string,
diff --git a/packages/server/src/metrics.ts b/packages/server/src/metrics.ts
index 548b83f35..c10fe5155 100644
--- a/packages/server/src/metrics.ts
+++ b/packages/server/src/metrics.ts
@@ -66,14 +66,11 @@ export interface ReconciliationMetrics {
mapDrivenSpliceMemoHits: number;
mapDrivenSpliceMemoSkips: Partial<Record<MapDrivenSpliceMemoSkipReason, number>>;
observerAResidualMergeRuns: number;
- /** Count of Observer A duplication-gate recoveries — a substantive body
- * line materialized more times in the fragment than clean Y.Text justified,
- * provenance-confirmed as a server-vs-client CRDT double-materialization
- * (one copy minted by Observer B under the server's own clientID, another
- * by a foreign client), and re-derived from Y.Text before it could persist
- * (precedent #38, Y.Text-is-truth). Counter only, incremented once per
- * confirmed recovery; the rate-limited `bridge-split-brain-rederive`
- * console event under site `duplication-guard` carries the per-doc signal. */
+ /**
+ * Count of Observer A duplication-gate recoveries: a substantive body line materialized more times
+ * in the fragment than clean Y.Text justified, provenance-confirmed as a server-versus-client
+ * double-materialization and re-derived from Y.Text before it could persist (precedent #38).
+ */
observerADuplicationRederives: number;
observerADuplicationCheckpointCreated: number;
observerAApplyLoss: number;
@@ -94,19 +91,11 @@ export interface ReconciliationMetrics {
managedArtifactReconcileCheckpointCreated: number;
managedArtifactReconcileDeduped: number;
reDeriveBackstopTripped: number;
- /** Y.Text-is-truth contract (precedent #38) — count of Observer A
- * settlement checks that detected a drain settling split-brain (Y.Text
- * vs serialize(fragment) divergence beyond `normalizeBridge` tolerance)
- * and enqueued a same-drain Observer B re-derive, that escaped the
- * per-(site, doc) rate-limiter and emitted a structured
- * `bridge-split-brain-rederive` event. No organic input produces this
- * divergence at HEAD — producers were narrowed to dependency/plugin
- * drift — so this firing in production is itself the drift alert: a
- * new divergent fallback producer has appeared. Also the operator
- * signal for a doc stuck re-deriving its fragment on every edit (the
- * divergence is structural and persists by design; the re-derive cost
- * recurs per drain). Counter increments only on emit; the companion
- * suppressed counter preserves `actual_rate = fires + suppressed`. */
+ /**
+ * Count of Observer A settlement checks that detected a drain settling split-brain beyond
+ * `normalizeBridge` tolerance (precedent #38) and enqueued a same-drain Observer B re-derive.
+ * No organic input produces that divergence at HEAD, so a firing is itself the drift alert.
+ */
bridgeSplitBrainRederives: number;
bridgeSplitBrainRederivesSuppressed: number;
persistenceReconciliationFailures: number;
@@ -563,33 +552,8 @@ export function incrementAgentPresenceMutationError(): void {
}
/**
- * Classify a collab-socket error. Returns `true` if the error is a
- * known-safe kernel TCP-teardown signal (EPIPE or ECONNRESET) that should
- * be filtered out of logs per precedent #22. As a side effect, increments
- * the corresponding per-code metric counter so operators can see the rate
- * during incident triage.
- *
- * Returns `false` for any other error code — the caller surfaces those
- * via their normal logging path.
- *
- * Contract: callers MUST use this helper rather than re-implementing the
- * `code === 'EPIPE' || code === 'ECONNRESET'` check inline. Centralizing
- * the filter surface prevents future skew (e.g., if ETIMEDOUT or ECONNABORTED
- * become known-safe, the decision flips in one place).
- *
- * Usage shape:
- *
- * socket.on('error', (err: NodeJS.ErrnoException) => {
- * if (handleCollabSocketError(err)) return;
- * log.error({ err }, 'Upgrade socket error');
- * });
- *
- * ws.on('error', (err: NodeJS.ErrnoException) => {
- * if (!handleCollabSocketError(err)) {
- * log.error({ err }, 'WebSocket error');
- * }
- * ws.terminate();
- * });
+ * Returns `true` if the error is a known-safe kernel TCP-teardown signal (EPIPE or ECONNRESET) that
+ * should be filtered out of logs per precedent #23.
*/
export function handleCollabSocketError(err: NodeJS.ErrnoException): boolean {
if (err.code === 'EPIPE' || err.code === 'ECONNRESET') {
diff --git a/packages/server/src/normalize-write-sink-gate.test.ts b/packages/server/src/normalize-write-sink-gate.test.ts
index e10fa5527..daf8291fa 100644
--- a/packages/server/src/normalize-write-sink-gate.test.ts
+++ b/packages/server/src/normalize-write-sink-gate.test.ts
@@ -1,21 +1,7 @@
/**
- * `normalizeBridge` output must never drive a byte write.
- *
- * `normalizeBridge` collapses tolerance-class differences (trailing whitespace,
- * blank-line runs, escape forms) so two representations can be COMPARED for
- * bridge equality. Its output is a lossy canonical form — writing it back to
- * disk or into `Y.Text`/`Y.XmlFragment` would silently rewrite the user's
- * byte-sacred source (precedent #57). Every `normalizeBridge` caller today is
- * comparison-only; this gate keeps it that way by failing the build when a
- * `normalizeBridge` result flows (directly, or via a one-hop local const) into
- * a byte-write sink argument.
- *
- * Blindness residual: cross-function flow (a function that RETURNS
- * `normalizeBridge` output whose caller then writes it) is not statically
- * traced here — that needs whole-program type resolution. The compensating
- * controls are the manual audit that verified every caller comparison-only and
- * the per-write-path byte-sacred discipline (precedent #57). The realistic
- * regression — someone writing a freshly-normalized value — is caught.
+ * `normalizeBridge` output must never drive a byte write: its lossy canonical form would rewrite
+ * the user's byte-sacred source (precedent #57). This gate fails the build when a result flows,
+ * directly or via a one-hop local const, into a byte-write sink argument.
*/
import { readdirSync, readFileSync, statSync } from 'node:fs';
import { dirname, join } from 'node:path';
diff --git a/packages/server/src/observer-a-verbatim-fallback-respell.test.ts b/packages/server/src/observer-a-verbatim-fallback-respell.test.ts
index 4b62147e8..e44afad35 100644
--- a/packages/server/src/observer-a-verbatim-fallback-respell.test.ts
+++ b/packages/server/src/observer-a-verbatim-fallback-respell.test.ts
@@ -1,33 +1,6 @@
/**
- * Observer A must not rewrite authoritative `Y.Text` with a RE-SPELLED copy of
- * a block the user never edited.
- *
- * When a nested block inside a JSX container degrades to a verbatim-bytes
- * `rawMdxFallback` — the shape the editor holds whenever a `<Step>` inside
- * `<Steps>` stops parsing under it — the container goes onto the reconstruct
- * path. `mdast-util-mdx-jsx`'s `containerFlow` exempts only `mdxJsxFlowElement`
- * children from its depth indentation, so the fallback's raw bytes came back
- * indented two spaces per JSX level while its pristine siblings stayed
- * flush-left. Observer A treats that mixed spelling as the fragment's canonical
- * bytes and writes it over the authored source.
- *
- * The drain shape is what makes it reachable. On a quiet drain the respell is
- * swallowed: `normalizeBridge` tolerates both the container-boundary blanks and
- * the child indentation, so the in-sync gate certifies and nothing is written.
- * It escapes on a DUAL drain — a fragment change landing in the same
- * transaction as a source keystroke — where the real delta denies that gate and
- * the router rewrites the whole block. That is source-mode typing while the
- * hidden-but-mounted WYSIWYG mutates the fragment, so it is the everyday shape,
- * not a corner. The write is a whole-block multi-line delta, which is how a
- * burst still in flight ends up merged against a second spelling of the same
- * span.
- *
- * The assertion is on the settled `Y.Text` because that is the authoritative
- * source persisted to disk and converged to every peer (precedent #38).
- *
- * Deterministic by construction: no wall-clock race is staged, and `NODE_ENV`
- * is the packaged posture because the producer guard throws under a test
- * runtime and would abort the very write this test exists to observe.
+ * The assertion is on the settled `Y.Text` because that is the authoritative source persisted to
+ * disk and converged to every peer (precedent #38).
*/
import { sharedExtensions } from '@inkeep/open-knowledge-core';
diff --git a/packages/server/src/paired-write-enforcement.test.ts b/packages/server/src/paired-write-enforcement.test.ts
index c33035662..7d1ff7050 100644
--- a/packages/server/src/paired-write-enforcement.test.ts
+++ b/packages/server/src/paired-write-enforcement.test.ts
@@ -1,22 +1,4 @@
-/**
- * Structural enforcement of the paired-write contract (precedent #38).
- *
- * Walks every `<doc>.transact(fn, origin)` call site in `packages/server/src/`
- * via ts-morph and asserts that paired-write origins route through one of
- * the three sanctioned sibling primitives in `bridge-intake.ts`:
- * `composeAndWriteRawBody`, `replaceRawBody`, `deriveFragmentFromYtext`.
- *
- * Why structural, not textual: the STOP rule "paired-write origins must call
- * a sanctioned primitive" had only a sentence backing it. Past
- * iterations shipped ordering bugs past that sentence. This test fails the
- * build when a new transact site bypasses the primitive — no reviewer-
- * attention budget required.
- *
- * Allowlists are typed `Set<string>` literals colocated with the test (not
- * out-of-band). Adding a new entry forces explicit classification: any new
- * origin name that doesn't match one of the three buckets fails loudly with
- * a message naming the file:line and the unrecognized origin.
- */
+/** Structural enforcement of the paired-write contract (precedent #38). */
import { join, relative } from 'node:path';
import {
diff --git a/packages/server/src/paired-write-origin.test.ts b/packages/server/src/paired-write-origin.test.ts
index 9d806d13f..e2c9d189b 100644
--- a/packages/server/src/paired-write-origin.test.ts
+++ b/packages/server/src/paired-write-origin.test.ts
@@ -1,18 +1,5 @@
/**
- * Compile-time type assertions for `PairedWriteOrigin` (bridge-correctness
- * precedent #1 extension).
- *
- * Purpose: pin the four paired-write origins at the type level so the
- * regression class — "a paired-write origin written without `context.paired: true`
- * silently amplifies RGA-level content loss" — is impossible to reintroduce.
- * The authoring site's `as const satisfies PairedWriteOrigin` annotation forces
- * the literal to carry the marker; this file's `@ts-expect-error` tests prove
- * that omitting the marker or getting the paired flag wrong IS a compile
- * error, not just a runtime check the reviewer might miss.
- *
- * Runs as a regular unit file under `bunx tsc --noEmit` — Bun's test runner
- * executes the body as an empty test, and `turbo run typecheck` validates
- * the negative `@ts-expect-error` cases.
+ * Compile-time type assertions for `PairedWriteOrigin` (bridge-correctness precedent #1 extension).
*/
import { describe, test } from 'vitest';
diff --git a/packages/server/src/persistence.ts b/packages/server/src/persistence.ts
index 686a563d3..78f061a21 100644
--- a/packages/server/src/persistence.ts
+++ b/packages/server/src/persistence.ts
@@ -138,16 +138,9 @@ export class DocumentOpenSizeLimitError extends Error {
}
/**
- * Derive a WriterIdentity from a Hocuspocus transaction origin.
- *
- * Called from onStoreDocument to determine which writer triggered the store.
- * Handles the three origin shapes Hocuspocus surfaces:
- * - local + context.session_id → per-session agent writer
- * - local + context.origin → classified service writer
- * - connection + principalId → human-browser principal writer
- *
- * precedent #1 — origins are LocalTransactionOrigin object refs, not strings.
- * Exported for unit-testing the dispatch table without spinning up a server.
+ * Derives a `WriterIdentity` from a Hocuspocus transaction origin, handling the three origin
+ * shapes it surfaces. Origins are `LocalTransactionOrigin` object refs, not strings
+ * (precedent #1). Exported so the dispatch table is unit-testable without a server.
*/
export function resolveWriterFromOrigin(
origin: unknown,
@@ -687,31 +680,8 @@ export function createPersistenceExtension(options?: PersistenceOptions): Persis
}
/**
- * Re-derive XmlFragment from `parse(ytext.body)` after the persistence
- * sanity check detected divergence. Under the Y.Text-is-truth contract
- * (precedent #38) Y.Text holds the user's intended source-form bytes;
- * fragment must catch up so future edits start from a consistent base.
- *
- * Synchronous: parse + structural diff + transact all run before the
- * caller's next statement. The work is bounded by doc size (parseWithFallback
- * is O(N), updateYFragment is O(N)), and the caller (storeDocumentNow)
- * already accepts that cost — the alternative (microtask deferral) would
- * leave fragment stale until the microtask drains, opening a window where
- * another transaction could merge against the stale fragment.
- *
- * The reconciliation transacts under `OBSERVER_SYNC_ORIGIN`. Both
- * Observer A and Observer B self-skip on this origin (their callbacks
- * read `transaction.origin === OBSERVER_SYNC_ORIGIN` and `return`),
- * so this nested transact does NOT cascade through the dispatch
- * settlement — it's an Observer-B-style write of the fragment side.
- * The OBSERVER_SYNC_ORIGIN's `skipStoreHooks: true` also prevents this
- * helper from re-triggering `onStoreDocument`, avoiding a feedback loop.
- *
- * The reconciliation is best-effort: a `parseWithFallback` failure (already
- * returns paragraph fallback rather than throwing) means fragment will
- * have the fallback content, which still preserves Observer A's baseline
- * tracking. Any throw deeper down logs but does not propagate — the disk
- * write that triggered this reconciliation is what matters for durability.
+ * Under the Y.Text-is-truth contract (precedent #38) Y.Text holds the user's intended source-form
+ * bytes; fragment must catch up so future edits start from a consistent base.
*/
function canonicalizeForEphemeralBaseline(rawBytes: string, documentName: string): string | null {
try {
diff --git a/packages/server/src/rollback-write-order.test.ts b/packages/server/src/rollback-write-order.test.ts
index e4439a042..418df8585 100644
--- a/packages/server/src/rollback-write-order.test.ts
+++ b/packages/server/src/rollback-write-order.test.ts
@@ -1,25 +1,7 @@
/**
- * Unit tests for the ROLLBACK_ORIGIN paired-write order property.
- *
- * `handleRollback` in api-extension.ts writes both Y.Text and Y.XmlFragment
- * inside one `doc.transact(..., ROLLBACK_ORIGIN)` drain. Under the
- * Y.Text-is-truth contract (precedent #38), Y.Text is the source of truth —
- * the write order MUST be ytext-first / fragment-second so that a partial
- * failure (second write throws after the first succeeds) leaves ytext in the
- * new state and Observer B Phase 1 re-derives fragment from `parse(ytext)`
- * on the next non-paired settlement.
- *
- * Reversed order (fragment-first / ytext-second) silently reverts the
- * rollback if updateYFragment succeeds and the ytext delete/insert then
- * throws: fragment holds the new historical state but ytext is stale, and
- * Observer B's next dispatch re-derives fragment from the STALE ytext,
- * undoing the rollback without any visible error.
- *
- * This file mirrors the load-bearing properties already pinned for
- * `composeAndWriteRawBody` (`bridge-intake.ts`) and the
- * `MANAGED_RENAME_ORIGIN` write site (`managed-rename.test.ts`), specialized
- * to the rollback call site whose write sequence is open-coded inside the
- * api-extension closure.
+ * Pins the ROLLBACK_ORIGIN paired-write order: under precedent #38 the write must be ytext-first
+ * and fragment-second, so a partial failure leaves ytext new and Observer B re-derives from it.
+ * Reversed, a throw after the fragment write silently reverts the rollback with no error.
*/
import { sharedExtensions, stripFrontmatter } from '@inkeep/open-knowledge-core';
diff --git a/packages/server/src/seed/index.ts b/packages/server/src/seed/index.ts
index 271db363c..785ac0d7b 100644
--- a/packages/server/src/seed/index.ts
+++ b/packages/server/src/seed/index.ts
@@ -7,18 +7,12 @@ export {
coercePackId,
DEFAULT_PACK_ID,
isKnownPackId,
- // oxlint-disable-next-line typescript/no-deprecated
- LOG_MD_TEMPLATE,
listStarterPacks,
type PackId,
resolvePack,
STARTER_FOLDER_FRONTMATTER_FILENAME,
- // oxlint-disable-next-line typescript/no-deprecated
- STARTER_FOLDERS,
STARTER_PACK_IDS,
STARTER_PACKS,
- // oxlint-disable-next-line typescript/no-deprecated
- STARTER_TEMPLATES,
type StarterFolder,
type StarterPack,
type StarterPackEntryCounts,
diff --git a/packages/server/src/seed/starter.ts b/packages/server/src/seed/starter.ts
index c482c8ad8..0af2b45e7 100644
--- a/packages/server/src/seed/starter.ts
+++ b/packages/server/src/seed/starter.ts
@@ -1495,15 +1495,6 @@ function computePackEntryCounts(pack: StarterPack): StarterPackEntryCounts {
return { files, folders };
}
-/** @deprecated Use `STARTER_PACKS['knowledge-base'].folders` directly. */
-export const STARTER_FOLDERS: readonly StarterFolder[] = KNOWLEDGE_BASE_FOLDERS;
-
-/** @deprecated Use `STARTER_PACKS['knowledge-base'].templates` directly. */
-export const STARTER_TEMPLATES: Readonly<Record<string, string>> = KNOWLEDGE_BASE_TEMPLATES;
-
-/** @deprecated Use `STARTER_PACKS['knowledge-base'].rootFiles?.['log.md']` directly. */
-export const LOG_MD_TEMPLATE = KNOWLEDGE_BASE_LOG_MD;
-
export const STARTER_FOLDER_FRONTMATTER_FILENAME = 'frontmatter.yml';
export function buildStarterFolderFrontmatterYaml(folder: StarterFolder): string {
diff --git a/packages/server/src/server-factory.ts b/packages/server/src/server-factory.ts
index 2f2ccb15e..196350239 100644
--- a/packages/server/src/server-factory.ts
+++ b/packages/server/src/server-factory.ts
@@ -2070,7 +2070,6 @@ export function createServer(options: ServerOptions): ServerInstance {
const source = document.getText('source').toString();
if (!source.includes(needle)) continue;
try {
- // (precedent #24). Re-render uses the same FILE_WATCHER
document.transact(() => {
applyDiskContentToDoc(document, source, resolveEmbed, docName);
}, FILE_WATCHER_ORIGIN);
diff --git a/packages/server/src/server-observers-divergent-fallback.test.ts b/packages/server/src/server-observers-divergent-fallback.test.ts
index 6953ddb6c..7d1fb2588 100644
--- a/packages/server/src/server-observers-divergent-fallback.test.ts
+++ b/packages/server/src/server-observers-divergent-fallback.test.ts
@@ -1,46 +1,3 @@
-/**
- * Divergent rawMdxFallback source preservation.
- *
- * Contract under test: a degradation fallback whose PM content differs from
- * the Y.Text source region it stands for must NOT become authoritative for
- * that region. Concretely, at the server bridge boundary (the only path from
- * XmlFragment to Y.Text — client-side cross-CRDT write paths were deleted
- * under precedent #14):
- *
- * 1. Fragment-change drains driven by interaction inside the fallback
- * (the RawMdxFallbackCMView forwardUpdate channel) must not destroy the
- * region's source bytes in Y.Text — neither on a follow-up keystroke
- * nor on a later ordinary edit elsewhere in the doc, which may
- * come from a remote peer.
- * 2. Blur-upgrade of an empty divergent fallback (the tryParseUpgrade
- * channel) must not strip the broken-block chrome from the fragment
- * while Y.Text still holds the broken source.
- * 3. Bound: a divergent fallback at rest is safe — an edit elsewhere alone
- * must merge without touching the region (green guard).
- *
- * The fragment-write surface is treated as untrusted (CRDT peers — any
- * client version can write any fragment state), so the contract is pinned
- * here, where every enumerated site of the class routes through, rather
- * than inside the client NodeView.
- *
- * Divergence is fault-injected at the parseWithFallback seam: no organic
- * markdown input produces content-level divergence at HEAD (the
- * fix narrowed producers to dependency/plugin drift), so the proxy below
- * recreates the two degraded shapes real producers emit — the unknown-mdast
- * guard's unresolvedPosition arm (content '') and the blockUnknownHandler
- * sentinel arm ('«unknown:<type>»'). Downstream of that seam the components
- * (Observer A/B, three-way merge, serializer, y-prosemirror write path) are
- * real — but Observer B's re-derive parses through the SAME proxy, so each
- * re-derive re-injects the divergence shape. That models a structural
- * (permanent) divergence faithfully; it also means fragment-side chrome
- * assertions (findFallback) are satisfied by the proxy's re-injection,
- * and the Y.Text-intactness assertions are the load-bearing ones.
- *
- * Tests run under production bridge policy (NODE_ENV=production): the
- * NODE_ENV=test watchdog gates throw at doc load on the injected divergence,
- * which would mask the silent-destruction behavior these tests pin.
- */
-
import { MarkdownManager, sharedExtensions } from '@inkeep/open-knowledge-core';
import { getSchema } from '@tiptap/core';
import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';
diff --git a/packages/server/src/server-observers.lazy-continuation.test.ts b/packages/server/src/server-observers.lazy-continuation.test.ts
index c14530351..a5d266fd2 100644
--- a/packages/server/src/server-observers.lazy-continuation.test.ts
+++ b/packages/server/src/server-observers.lazy-continuation.test.ts
@@ -1,25 +1,7 @@
/**
- * Bridge health checks on CommonMark lazy-continuation docs.
- *
- * A doc whose source carries a lazy continuation (an unindented wrapped line
- * inside a list item, a paragraph glued to a list's last line, a blockquote
- * continuation without the `> ` prefix) parses identically to its canonical
- * form (CommonMark §5.2), but serializes differently — `serialize(parse(md))
- * !== md`, and the difference sits deliberately OUTSIDE the normalizeBridge
- * tolerance set (step 7f keeps list/blockquote continuations divergent so the
- * router's residual-merge keeps protecting the raw bytes; the step-7f
- * pins live next to normalizeBridge).
- *
- * The health checks layered on top of that router must NOT treat this
- * resting canonicalization as a broken bridge: the fragment IS
- * `parse(ytext)` (Y.Text-is-truth, precedent #38), so neither the
- * observer-b watchdog throw/warn nor the split-brain rederive may fire on
- * organic lazy-continuation input. Genuine fragment↔Y.Text divergence
- * (content one side lacks) must keep firing — pinned by the control test.
- *
- * Uses a synthetic Y.Doc (no Hocuspocus), production-order seeding
- * (paired-write intake first, observer attach second) — the same rig as
- * `server-observers.test.ts`.
+ * Bridge health checks on CommonMark lazy-continuation docs, whose resting canonicalization sits
+ * deliberately outside the `normalizeBridge` tolerance set. The fragment still IS `parse(ytext)`
+ * (precedent #38), so neither the watchdog nor the split-brain re-derive may fire on them.
*/
import {
diff --git a/packages/server/src/server-observers.test.ts b/packages/server/src/server-observers.test.ts
index fb8396d0e..e846a8888 100644
--- a/packages/server/src/server-observers.test.ts
+++ b/packages/server/src/server-observers.test.ts
@@ -1,21 +1,6 @@
/**
- * Unit tests for the server-authoritative observer bridge (server-observers.ts).
- *
- * Tests cover:
- * - Settlement-based dispatch on `afterAllTransactions` (precedent #13(b))
- * - Baseline-refresh semantics for Path A / Path B / paired-write / self-sync
- * - Path A vs Path B dispatch
- * - Origin-guard truth table
- * - No infinite loop on self-origin
- * - Agent paired-write early-exit
- * - Paired-write short-circuit symmetry across Observer A + Observer B
- * - Frontmatter sync (Observer B → Y.Map, Observer A reads Y.Map)
- * - Cleanup detaches observers and the settlement handler
- * - Observer B error-recovery branches
- *
- * Uses a synthetic Y.Doc (no Hocuspocus). Observer dispatch happens
- * synchronously after each `doc.transact()` drain via the new
- * `afterAllTransactions` settlement listener — tests assert post-transact
+ * Unit tests for the server-authoritative observer bridge over a synthetic Y.Doc. Dispatch is
+ * settlement-based on `afterAllTransactions` (precedent #13(b)), so tests assert post-transact
* state directly with no scheduler flushing.
*/
diff --git a/packages/server/src/server-observers.ts b/packages/server/src/server-observers.ts
index c1c2fe76d..846b9b1e4 100644
--- a/packages/server/src/server-observers.ts
+++ b/packages/server/src/server-observers.ts
@@ -1,25 +1,7 @@
/**
- * Server-authoritative observer bridge — single-writer cross-CRDT sync.
- *
- * Mirrors the client-side observer bridge's write-side logic on the server:
- * Observer A: XmlFragment → Y.Text (Path A: applyIncrementalDiff; Path B: mergeThreeWay + applyFastDiff)
- * Observer B: Y.Text → XmlFragment (via updateYFragment)
- *
- * Runs on the server's copy of the Y.Doc so concurrent client edits converge
- * through one writer instead of N. Client observer cross-CRDT write paths are
- * deleted (not gated) — see precedent #14.
- *
- * Dispatch model (precedent #13(b)): the
- * observers use `doc.on('afterAllTransactions', ...)` — per-drain, not
- * per-transaction, and not a wall-clock `setTimeout` debounce. One outermost
- * `doc.transact(...)` call = one drain = one settlement fire. Observer
- * callbacks set dirty flags; the settlement handler dispatches synchronous
- * sync work (A before B) and clears the flags.
- *
- * No typing-defer logic (server never types — that was client-specific UX).
- * No REMOTE_TREE_SYNC_GRACE_MS (origin guards replace the timing guard).
- * Fires on BOTH transaction.local=true (server-local) and local=false (remote).
- *
+ * Client observer cross-CRDT write paths are deleted (not gated) — see precedent #14. Dispatch
+ * model (precedent #13(b)): the observers use `doc.on('afterAllTransactions', ...)` — per-drain,
+ * not per-transaction, and not a wall-clock `setTimeout` debounce.
*/
import type { LocalTransactionOrigin } from '@hocuspocus/server';
@@ -119,16 +101,9 @@ const log = getLogger('server-observers');
const checkpointLog = getLogger('server-observers');
/**
- * Transaction origin for server observer cross-CRDT writes.
- *
- * Object reference per precedent #1 — identity-based matching in
- * Set.has / Y.UndoManager.trackedOrigins / attachBridgeInvariantWatcher
- * enforcing sets requires the exact object ref.
- *
- * skipStoreHooks: true — prevents observer → persistence → file-watcher →
- * observer feedback loop. Same pattern as
- * FILE_WATCHER_ORIGIN in external-change.ts. Verified by the
- * persistenceDiskWrites counter in `server-observer-feedback-loop.test.ts`.
+ * Transaction origin for server observer cross-CRDT writes: an object reference per precedent #1,
+ * because identity matching in `Set.has`, `trackedOrigins` and the bridge watcher's enforcing sets
+ * needs the exact ref. `skipStoreHooks` breaks the observer-persistence-watcher feedback loop.
*/
export const OBSERVER_SYNC_ORIGIN = {
source: 'local',
@@ -136,30 +111,7 @@ export const OBSERVER_SYNC_ORIGIN = {
context: { origin: 'observer-sync' },
} as const satisfies LocalTransactionOrigin;
-/**
- * Branded `LocalTransactionOrigin` for paired-write semantics — transactions
- * where the caller atomically writes BOTH Y.XmlFragment and Y.Text inside
- * one `doc.transact(..., ORIGIN)` block.
- *
- * Compile-time extension of precedent #1.
- * Origin literals opt in by asserting `satisfies
- * PairedWriteOrigin` at their definition site; that annotation forces the
- * literal to carry `context.paired: true` and prevents typos. See the
- * five paired origins in the repo — AGENT_WRITE_ORIGIN, FILE_WATCHER_ORIGIN,
- * ROLLBACK_ORIGIN, MANAGED_RENAME_ORIGIN, PARK_SNAPSHOT_ORIGIN
- * (server-factory.ts) — each satisfies this shape.
- *
- * Runtime remains structural (`context.paired === true`) so remote-arriving
- * transactions (where the origin object identity is reconstructed by Yjs)
- * still match; `satisfies PairedWriteOrigin` is the authoring-site gate,
- * not a runtime `instanceof` narrowing.
- *
- * Today's paired origin count: 5. When adding a 6th, the ONLY required
- * change is `satisfies PairedWriteOrigin` at the literal. No registry
- * update. No Observer A/B wiring. No `BRIDGE_ENFORCING_ORIGINS` change
- * (that set is unrelated — it enforces the bridge-invariant watcher's
- * post-transaction assertion, not paired-write short-circuit).
- */
+/** Compile-time extension of precedent #1. */
export type PairedWriteOrigin = LocalTransactionOrigin & {
readonly context: {
readonly origin: string;
@@ -167,27 +119,7 @@ export type PairedWriteOrigin = LocalTransactionOrigin & {
};
};
-/**
- * Semantic match (precedent #1 extension).
- *
- * When an observer callback sees a paired-write origin, it refreshes the
- * raw Y.Text witness synchronously from the post-write state and declines to
- * set its dirty flag — the settlement handler then has no work to dispatch
- * for this drain (the paired writer already made both CRDTs consistent).
- *
- * The structural runtime check covers both locally-written origins (where the
- * object identity is the one we exported) and remote-arriving transactions
- * (where Yjs may have reconstructed the origin from the wire payload). The
- * `PairedWriteOrigin` brand above is the authoring-site compile-time gate;
- * this predicate is the read-site runtime gate. Both together close the
- * loop the regression class left open.
- *
- * Fuzz reproduction: `STRESS_FUZZ_SEED=1776325179241 bun test
- * packages/app/tests/stress/bridge-convergence.fuzz.test.ts` produces an
- * "Oracle (e) content-set violation — missing 'M3-charlie hotel echo'" failure
- * whose proximate cause is a duplicated `M0-alpha echo` line that a later
- * agent-patch `indexOf('alpha')` locks onto instead of the intended target.
- */
+/** Semantic match (precedent #1 extension). */
export const isPairedWriteOrigin = (origin: unknown): origin is PairedWriteOrigin => {
if (origin == null || typeof origin !== 'object') return false;
const ctx = (origin as { context?: { paired?: boolean } }).context;
@@ -218,25 +150,12 @@ export class ProducerGuardViolationError extends Error {
const PRODUCER_GUARD_DANGER_TYPES = new Set(['jsxComponent', 'table', 'tableCell', 'tableHeader']);
/**
- * Consecutive derive-timing defers a document may accumulate before the guard
- * stops deferring and force-resolves the re-derive loudly. Drain-count based, so
- * it stays honest under the no-wall-clock rule (precedent #13(b)): the bound is
- * "how many re-derive drains have been withheld," never elapsed time. Same value
- * as the persistence layer's `QUIESCENCE_MAX_DEFER` — under sustained typing a
- * doc that keeps a keystroke un-propagated is the same shape both layers bound.
+ * Drain-count based, so it stays honest under the no-wall-clock rule (precedent #13(b)): the bound
+ * is "how many re-derive drains have been withheld," never elapsed time.
*/
const MAX_DERIVE_TIMING_DEFERS = 8;
-/**
- * Backstop cap for the Y.Text→XmlFragment re-derive loop (the loud
- * tripwire). A run of this many consecutive re-derive drains that never reaches
- * a raw-byte fixed point (the two representations keep diverging) freezes the
- * B-direction re-derive loop. Drain-count based (never wall-clock,
- * precedent #13(b)). Set well above the worst measured legitimate run — a single
- * byte-emitting round per settlement episode — so a legitimate flow can never
- * trip it; the residual it guards is the un-probed echo/normalize-UNEQUAL
- * corrective-loop domain, where a trip is a true positive.
- */
+/** Drain-count based (never wall-clock, precedent #13(b)). */
const MAX_REDERIVE_ROUNDS = 8;
const MERGE_BOUNDARY_SITE = 'merge-boundary';
@@ -395,12 +314,9 @@ export interface SetupServerObserversOpts {
}
/**
- * Split-brain settlement predicate (the precedent #38 comparison): true when
- * a drain is about to settle with Y.Text and the canonical fragment
- * serialization (`md`) diverged beyond `normalizeBridge` tolerance. The
- * byte-identity short-circuit skips the O(N) normalize passes on the common
- * in-sync case. Single-sourced so both Observer A detection sites (identity
- * gate + post-merge baseline check) apply the identical predicate.
+ * Split-brain settlement predicate (the precedent #38 comparison): true when a drain is about to
+ * settle with Y.Text and the canonical fragment serialization (`md`) diverged beyond
+ * `normalizeBridge` tolerance.
*/
function settlesSplitBrain(
settledText: string,
@@ -479,25 +395,7 @@ export function findRaceDuplicatedSpans(
return false;
}
-/**
- * Set up server-side bidirectional observers between Y.XmlFragment and Y.Text.
- *
- * Observer A (XmlFragment → Y.Text): mirrors client Observer A's write-side
- * logic — Path A (diffLines + content-comparison gate when Y.Text in sync
- * with baseline) and Path B (DMP three-way merge when Y.Text diverged).
- *
- * Observer B (Y.Text → XmlFragment): parses Y.Text markdown, applies to
- * XmlFragment via updateYFragment. Handles frontmatter sync (Y.Text ↔ Y.Map).
- *
- * Dispatch (precedent #13(b)): Observer callbacks only flag dirty state.
- * The `afterAllTransactions` listener runs Observer A's sync work first
- * (so any Y.Text write is visible to Observer B) and then Observer B's,
- * clearing the dirty flags afterwards. One outermost `doc.transact()` call
- * produces exactly one settlement dispatch.
- *
- * Returns a cleanup function that detaches the observers and the settlement
- * handler. The settlement handler holds no timers; cleanup is O(1).
- */
+/** Dispatch (precedent #13(b)): Observer callbacks only flag dirty state. */
export function setupServerObservers(opts: SetupServerObserversOpts): () => void {
const { doc, xmlFragment, ytext, mdManager, schema } = opts;
@@ -934,15 +832,7 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
};
/**
- * Record a COHERENT split-brain pair after an Observer A error recovery —
- * the recomputed canonical fragment form (`canonicalMd`) and the current
- * raw Y.Text diverge beyond `normalizeBridge` tolerance, but both are read
- * NOW from a consistent in-memory state, so they belong to one settlement
- * generation. Unlike the `''` sentinel, this pair is deliberately coherent:
- * the router must take the byte-preserving residual-merge (row 2) on the
- * next fragment-change drain rather than a wholesale Path A rewrite, which
- * is what protects the divergent source bytes. The same-drain Observer B
- * re-derive the caller enqueues then rebuilds the fragment from Y.Text
+ * The same-drain Observer B re-derive the caller enqueues then rebuilds the fragment from Y.Text
* (Y.Text-is-truth, precedent #38), so the split-brain state converges.
*/
const recordSplitBrainRecoveryBaselines = (canonicalMd: string): void => {
@@ -1029,18 +919,8 @@ export function setupServerObservers(opts: SetupServerObserversOpts): () => void
const guardCheckpointedPreLoss = new Map<string, string>();
/**
- * Report a producer-guard content-loss in the packaged posture: a rate-limited
- * structured event (bounded cardinality — doc.name + reason/degrade enums + a
- * construct locator, never raw content) plus a silent checkpoint of the
- * pre-loss source so the state stays user-recoverable. Never throws, never
- * corrective-writes (precedent #38): the drain still persists the bytes
- * as-computed. The guard is a second DETECTION site for the bridge-content-loss
- * class, not a second `BridgeMergeContentLossError` recovery — it uses its own
- * `producer-guard-loss` checkpoint kind and its own fire/suppressed counters.
- *
- * The log throttle and the checkpoint are independent: throttling the log must
- * not drop the recovery anchor, so the checkpoint always attempts (deduped on
- * the pre-loss source) even when the log is suppressed.
+ * Never throws, never corrective-writes (precedent #38): the drain still persists the bytes
+ * as-computed.
*/
const reportProducerGuardViolation = (
verdict: Extract<ReturnType<typeof comparePmStructural>, { equivalent: false }>,
diff --git a/packages/server/src/services/skill-install-ops.ts b/packages/server/src/services/skill-install-ops.ts
index ef03829ab..34f615f50 100644
--- a/packages/server/src/services/skill-install-ops.ts
+++ b/packages/server/src/services/skill-install-ops.ts
@@ -233,7 +233,6 @@ export function createSkillInstallOpsService(deps: SkillInstallOpsDeps): SkillIn
try {
const raw = readFileSync(skillMdPath, 'utf-8');
const { fenced, body: skillBody } = detectFmRegion(raw);
- // presence-exempt: no CRDT write, no agent identity
const renamed = applyPatchToFm(fenced, { name: toName });
if (renamed.ok) {
tracedWriteFileSync(skillMdPath, `${renamed.nextFenced}${skillBody}`);
diff --git a/packages/server/src/shadow-repo.ts b/packages/server/src/shadow-repo.ts
index 2ea79082d..52d4c432d 100644
--- a/packages/server/src/shadow-repo.ts
+++ b/packages/server/src/shadow-repo.ts
@@ -509,13 +509,8 @@ export const SERVICE_WRITER: WriterIdentity = {
};
/**
- * Artifacts OK authors itself — today the generated root `index.md`.
- *
- * Deliberately NOT `SERVICE_WRITER`: that one is the fallback for work with no
- * contributor behind it, and precedent #25 reserves it for exactly that. A
- * generated document is an authoring action with a real author; the author just
- * is not a person. Keeping them apart is what lets a reader tell "OK wrote this
- * file" from "OK flushed something nobody claimed".
+ * Deliberately NOT `SERVICE_WRITER`: that one is the fallback for work with no contributor behind
+ * it, and precedent #25 reserves it for exactly that.
*/
export const OK_GENERATOR_WRITER: WriterIdentity = {
id: OK_GENERATOR_WRITER_ID,
diff --git a/packages/server/src/spawn-cursor-api.ts b/packages/server/src/spawn-cursor-api.ts
index d8cd7178b..0c2f94e17 100644
--- a/packages/server/src/spawn-cursor-api.ts
+++ b/packages/server/src/spawn-cursor-api.ts
@@ -1,48 +1,7 @@
/**
- * POST /api/spawn-cursor — server-side `cursor <path>` spawn for the web host.
- *
- * Cursor's deep-link API has no single-call "open this folder" semantic; you
- * have to invoke the `cursor` CLI to spawn the workspace window, then fire
- * `cursor://anysphere.cursor-deeplink/prompt?...` to seed the prompt. Browsers
- * can't spawn processes, so the OK web UI defers step 1 to the server (which
- * runs on the user's machine via `open-knowledge start` and has filesystem +
- * `child_process` access).
- *
- * Sibling of:
- * - Electron IPC `ok:shell:spawn-cursor` in
- * `packages/desktop/src/main/ipc-handlers.ts` (electron host)
- * - GET `/api/installed-agents` in `./handoff-api.ts` (install detection)
- *
- * HTTP wire shape follows RFC 9457 (codebase precedent #39): 4xx/5xx errors
- * emit `application/problem+json` via `errorResponse(...)`; 200 success
- * emits empty `{}` via `successResponse(SpawnCursorSuccessSchema, ...)`.
- *
- * Note: after the `/api/handoff` unification, the OK renderer's Open-in-
- * Cursor dispatch goes through `packages/app/src/lib/handoff/dispatch.ts`
- * → `POST /api/handoff` (target: `cursor`), and the handoff dispatcher in
- * turn reuses the helpers in this file (`isPathWithinDir`,
- * `resolveCursorBinaryDefault`, `resolveCursorSpawnInvocation`). `/api/spawn-
- * cursor` remains for direct/legacy callers and as the install-state
- * sibling of `/api/installed-agents` — the wire shape contract above
- * still governs it. The Electron IPC layer (`ok:shell:spawn-cursor`)
- * keeps its typed `SpawnOutcome` contract via `createHandler` /
- * `createInvoker` — RFC 9457 is HTTP-only
- * by construction (it specifies media type `application/problem+json`).
- *
- * Security model — same shape as `/api/workspace`:
- * - Loopback-only (TCP peer + Host header gates) — endpoint is unreachable
- * over network.
- * - Path containment: the requested path must canonically resolve at or
- * under `contentDir`. A renderer compromise can't steer Cursor at
- * arbitrary filesystem locations (`~/.ssh`, `/etc`, …).
- * - Hardcoded `cursor` binary, argv-array (`shell: false`) — no shell
- * interpolation, no user-supplied executable.
- * - Detached + `stdio: 'ignore'` + `unref()` — OK does not parent Cursor's
- * process tree, so killing OK doesn't kill Cursor.
- *
- * Loopback gating is applied at the route registration layer in
- * `api-extension.ts`, not here, to match the convention for `/api/workspace`
- * and `/api/installed-agents`.
+ * `POST /api/spawn-cursor` runs the `cursor` CLI for the web host, which cannot spawn processes;
+ * the renderer then fires the deep link to seed the prompt. The wire shape follows RFC 9457 per
+ * precedent #39: errors emit `application/problem+json`, success emits an empty body.
*/
import { execFile } from 'node:child_process';
diff --git a/packages/server/src/sync-engine.ts b/packages/server/src/sync-engine.ts
index 5f45a0bfe..54a9447a6 100644
--- a/packages/server/src/sync-engine.ts
+++ b/packages/server/src/sync-engine.ts
@@ -218,14 +218,9 @@ interface MergePreparation {
}
/**
- * ContentFilter read-opts for the two staging-path consultations
- * (`gatherContentFilesSync`, `listHeadContentPaths`): admits the shareable
- * `.ok` artifact allow-list for staging and deletion tracking. Both paths
- * must consult the identical predicate — a HEAD path the head listing admits
- * but the gather walk refuses would be committed as a spurious deletion on
- * every push cycle (precedent #55). The conflict partition
- * (`isContentConflictPath` / `handleMergeConflict`) deliberately stays
- * unscoped so these artifacts keep the non-content auto-resolve class.
+ * ContentFilter read-opts for the two staging-path consultations, admitting the shareable `.ok`
+ * artifact allow-list. Both must consult the identical predicate (precedent #55): a HEAD path the
+ * listing admits but the gather walk refuses commits as a spurious deletion on every push.
*/
const CONTENT_SYNC_STAGING_SCOPE = { syncScope: { pathBase: 'content' } } as const;
const PROJECT_SYNC_STAGING_SCOPE = { syncScope: { pathBase: 'project' } } as const;
@@ -331,11 +326,9 @@ export class SyncEngine {
private contentFilter: ContentFilter;
private contentRoot: string;
/**
- * True when the project-root `.ok/` directory sits outside the contentDir
- * walk (content.dir configured as a subfolder). The push cycle then runs a
- * second enumeration rooted at the project root so shareable `.ok`
- * artifacts still stage and deletion-track; gather and head listing consult
- * this flag in lock-step (precedent #55).
+ * The push cycle then runs a second enumeration rooted at the project root so shareable `.ok`
+ * artifacts still stage and deletion-track; gather and head listing consult this flag in
+ * lock-step (precedent #55).
*/
private rootOkOutsideContentWalk: boolean;
private pullIntervalSeconds: number;
@@ -2726,27 +2719,8 @@ export class SyncEngine {
}
/**
- * Stage content files into the handle's index, dropping ignored-AND-untracked
- * paths first. Content scope is broader than git scope: the content filter
- * admits `<folder>/.ok/templates/*.md` regardless of ignore state so templates
- * stay visible in the editor, but a local-only-sharing project excludes `.ok/`
- * in `.git/info/exclude`, and naming such a path in `git add` fatals with
- * `addIgnoredFile`, wedging every push cycle. Precedent #55 (walker and
- * `git add` agree on scope) is enforced here rather than in content admission.
- *
- * Tracked files are exempt from ignore rules and must keep syncing, but
- * `git add` (Apple git 2.39.5) still refuses a named path under an ignored
- * directory even when tracked — so paths carrying a `.ok/` segment (the only
- * carve-out shape content admission holds above git scope) are added with
- * `-f`. Everything else keeps the plain fail-loud `add`: if the probe and the
- * add ever disagree (a future git version, a `.gitattributes` edge), an
- * unexpected refusable path surfaces as an error instead of being silently
- * force-added. On probe failure, stage unfiltered WITHOUT `-f` and let the
- * old error surface.
- *
- * Call only after the caller's `read-tree` seed: against an empty index a
- * tracked-but-ignored file reads as refusable and its HEAD entry would be
- * committed as a deletion. Returns the staged files for deletion-set pairing.
+ * Precedent #55 (walker and `git add` agree on scope) is enforced here rather than in content
+ * admission.
*/
private async stageContentFiles(
handle: GitHandle,
@@ -2863,14 +2837,9 @@ export class SyncEngine {
}
/**
- * Whether a project-relative path is inside the set this engine will commit.
- *
- * The staging walk, HEAD deletion tracking, and the working-tree status
- * surface must all answer this identically — a path one admits and another
- * refuses is precedent #55's failure mode (a HEAD path the gather walk
- * refuses gets committed as a spurious deletion every cycle). Public because
- * the status endpoint marks out-of-scope paths in the UI, and a second
- * predicate for that marking would be free to drift.
+ * The staging walk, HEAD deletion tracking, and the working-tree status surface must all answer
+ * this identically — a path one admits and another refuses is precedent #55's failure mode (a
+ * HEAD path the gather walk refuses gets committed as a spurious deletion every cycle).
*/
isSyncScopedPath(projRelPath: string): boolean {
const absPath = join(this.projectDir, projRelPath);
diff --git a/packages/server/src/timeline-query.ts b/packages/server/src/timeline-query.ts
index fe7712e0b..a3d3c8fc0 100644
--- a/packages/server/src/timeline-query.ts
+++ b/packages/server/src/timeline-query.ts
@@ -133,34 +133,9 @@ function matchesAuthor(entry: TimelineEntry, authors: string[]): boolean {
}
/**
- * Filter timeline entries to those where at least one writer's
- * `OkActorEntry.docs[]` or `previous_paths[].{from,to}` matches a docName in
- * the chain (cycle-bounded for predecessor steps; unbounded for current).
- *
- * The git-log pathspec filter (`git log -- <path>`) is a coarse pre-filter
- * that catches both real modifications AND topological noise:
- *
- * - Multi-writer fan-out: each writer's WIP ref is its own chain
- * (precedent #25). When writer B commits anything, `buildWipTree` builds
- * the tree from the entire `contentRoot` — so any file added by writer A
- * since writer B's last commit appears as ADDED in writer B's commit
- * even though the blob is identical. `git log -- <path>` returns those
- * commits as "modifications."
- *
- * - Backlink-rewrite side effects: when doc X is renamed, `applyRenameMap`
- * rewrites links in every backlink source. Those sources' blobs change.
- * `git log -- <source-path>` returns the rename commit even though the
- * source wasn't the rename target.
- *
- * `OkActorEntry.docs[]` carries the docs the writer EXPLICITLY targeted
- * (recordContributor docName + post-rename per-doc recordContributor). It
- * does NOT include incidental backlink-rewrite or topology-only changes.
- * `previous_paths[].{from,to}` carries the rename mapping. The intersection
- * with the chain is the correct "this commit really touched the doc" check.
- *
- * Cycle bound: predecessor steps reuse the same `predecessorAncestors` set
- * computed by `filterEntriesByChain` for checkpoint filtering. Current name
- * (chain[length-1]) is unbounded.
+ * The git-log pathspec filter (`git log -- <path>`) is a coarse pre-filter that catches both real
+ * modifications AND topological noise: - Multi-writer fan-out: each writer's WIP ref is its own
+ * chain (precedent #25).
*/
function filterEntriesByOkActorDocs(
entries: ParsedEntry[],
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index e9dd35ea2..f54f6fcfa 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -230,6 +230,9 @@ importers:
vitest:
specifier: ^4.1.0
+ yaml:
+ specifier: ^2.8.3
+ version: 2.9.0
docs:
dependencies:
diff --git a/scripts/check-husky-prepare-guard.sh b/scripts/check-husky-prepare-guard.sh
index 1cdb3db3a..1ef0465b5 100755
--- a/scripts/check-husky-prepare-guard.sh
+++ b/scripts/check-husky-prepare-guard.sh
@@ -1,25 +1,4 @@
#!/usr/bin/env bash
-#
-# Test: husky prepare guard distinguishes standalone OK clone from
-# agents-private monorepo context, and only invokes husky in the former.
-#
-# Background: OK's `prepare` script invokes `husky` to install git hooks.
-# In a standalone clone (inkeep/open-knowledge), `.git` lives at OK root
-# and husky writes core.hooksPath there — correct. Inside the
-# agents-private monorepo, OK has no own `.git`, so husky walks up,
-# finds the parent's `.git`, and writes core.hooksPath there with a path
-# pointing back at OK's `.husky/`. That clobbers the parent's intended
-# `.husky/` setup and makes `git push` from anywhere in agents-private
-# fire OK's hook (`pnpm run format && pnpm run lint && pnpm run check`)
-# instead of the parent's intended `pnpm check:monorepo-traps && pnpm check:pre-push`.
-#
-# The fix: a guard at the start of OK's prepare script that detects
-# the monorepo context and skips husky in that case. The discriminator
-# is whether `.git` exists relative to OK's cwd (it does in standalone
-# clones, it does not in the monorepo).
-#
-# This test invokes the guard script in two simulated environments and
-# asserts husky is invoked exactly when expected.
set -euo pipefail
@@ -39,9 +18,6 @@ fi
TEST_TMPDIR="$(mktemp -d)"
trap 'rm -rf "$TEST_TMPDIR"' EXIT
-# Stub `pnpm` so the guard's `pnpm exec husky` call is observable without
-# requiring a real husky binary. The stub records each invocation to
-# the file pointed to by $TEST_INVOCATION_LOG (set by each scenario).
STUB_DIR="$TEST_TMPDIR/stub-bin"
mkdir -p "$STUB_DIR"
cat > "$STUB_DIR/pnpm" <<'EOF'
@@ -56,7 +32,7 @@ FAILED=0
run_scenario() {
local label="$1"
local cwd="$2"
- local should_invoke="$3" # "yes" or "no"
+ local should_invoke="$3"
local log="$TEST_TMPDIR/$label.log"
: > "$log"
@@ -73,14 +49,9 @@ run_scenario() {
[ -s "$log" ] && { echo " stub log:"; sed 's/^/ /' "$log"; }
FAILED=$((FAILED + 1))
elif [ "$should_invoke" = "no" ] && [ "$rc" -ne 0 ]; then
- # Skip-husky case: guard must exit 0 cleanly. A non-zero exit means the
- # script crashed before/after the guard check — the empty invocation log
- # would otherwise pass this scenario as a false positive.
echo "FAIL: $label — script crashed (exit $rc) instead of exiting 0 cleanly"
FAILED=$((FAILED + 1))
elif [ "$should_invoke" = "yes" ] && [ "$rc" -ne 0 ]; then
- # Invoke-husky case: pnpm was called but the script still exited non-zero,
- # meaning something after pnpm crashed (e.g., chmod under set -euo pipefail).
echo "FAIL: $label — script crashed (exit $rc) despite invoking husky"
FAILED=$((FAILED + 1))
else
@@ -89,46 +60,32 @@ run_scenario() {
fi
}
-# Scenario A: standalone clone — `.git` is at the cwd
SCENARIO_A="$TEST_TMPDIR/standalone"
mkdir -p "$SCENARIO_A/.git" "$SCENARIO_A/.husky"
touch "$SCENARIO_A/.husky/pre-commit" "$SCENARIO_A/.husky/pre-push"
run_scenario "standalone-clone" "$SCENARIO_A" "yes"
-# Scenario B: standalone worktree — `.git` is a FILE pointing at the
-# real gitdir (created by `git worktree add`). Should still invoke.
SCENARIO_B="$TEST_TMPDIR/standalone-worktree"
mkdir -p "$SCENARIO_B/.husky"
echo "gitdir: /some/real/gitdir" > "$SCENARIO_B/.git"
touch "$SCENARIO_B/.husky/pre-commit" "$SCENARIO_B/.husky/pre-push"
run_scenario "standalone-worktree" "$SCENARIO_B" "yes"
-# Scenario C: monorepo — `.git` is in a parent dir, NOT at cwd
SCENARIO_C_PARENT="$TEST_TMPDIR/monorepo"
SCENARIO_C="$SCENARIO_C_PARENT/public/open-knowledge"
mkdir -p "$SCENARIO_C_PARENT/.git" "$SCENARIO_C/.husky"
touch "$SCENARIO_C/.husky/pre-commit" "$SCENARIO_C/.husky/pre-push"
run_scenario "monorepo-subdirectory" "$SCENARIO_C" "no"
-# Scenario D: standalone clone WITHOUT husky hooks (public mirror case).
-# `.husky/pre-commit` and `pre-push` aren't in the Copybara include list,
-# so a fresh public clone has `.git` but no hook files. Guard should skip
-# husky setup to avoid creating empty `_/` scaffolding.
SCENARIO_D="$TEST_TMPDIR/standalone-no-hooks"
mkdir -p "$SCENARIO_D/.git"
-# Deliberately do NOT create .husky/pre-commit or pre-push.
run_scenario "standalone-no-hooks" "$SCENARIO_D" "no"
-# Scenario E: standalone clone with only pre-commit (no pre-push).
-# Should still invoke husky — at least one hook exists.
SCENARIO_E="$TEST_TMPDIR/standalone-only-pre-commit"
mkdir -p "$SCENARIO_E/.git" "$SCENARIO_E/.husky"
touch "$SCENARIO_E/.husky/pre-commit"
run_scenario "standalone-only-pre-commit" "$SCENARIO_E" "yes"
-# Scenario F: standalone clone with only pre-push (no pre-commit).
-# Symmetric to E — exercises the other branch of the `! -f pre-commit
-# && ! -f pre-push` conjunction in husky-prepare.sh.
SCENARIO_F="$TEST_TMPDIR/standalone-only-pre-push"
mkdir -p "$SCENARIO_F/.git" "$SCENARIO_F/.husky"
touch "$SCENARIO_F/.husky/pre-push"
diff --git a/scripts/check-i18n-drift.sh b/scripts/check-i18n-drift.sh
index 8dfd03961..7fd6e9552 100755
--- a/scripts/check-i18n-drift.sh
+++ b/scripts/check-i18n-drift.sh
@@ -1,20 +1,4 @@
#!/usr/bin/env bash
-#
-# Run `lingui extract` (the canonical extractor wired via `pnpm run i18n` in
-# packages/app) and fail if the committed catalogs at
-# packages/app/src/locales/{en,pseudo}/messages.{po,json} do not match what the
-# extractor would produce against the current `<Trans>` / t`...` macros under
-# packages/app/src. Mirrors check-schema-snapshot-clean.sh so `pnpm check`
-# catches drift before push.
-#
-# Canonical source: packages/app/src/**/*.{ts,tsx} (per packages/app/lingui.config.ts).
-# Regenerate after adding strings:
-# cd packages/app && pnpm run i18n
-#
-# Lingui's CLI has no `--check` mode, so we run the real extract+compile+format
-# path and compare against the working tree via `git diff --quiet`. The catalog
-# files are content-stable for unchanged source, so a clean tree before this
-# script stays clean after a no-drift run.
set -euo pipefail
unset GIT_DIR GIT_WORK_TREE GIT_COMMON_DIR GIT_INDEX_FILE \
diff --git a/scripts/check-knip-clean.sh b/scripts/check-knip-clean.sh
index 5aec9832a..844973186 100755
--- a/scripts/check-knip-clean.sh
+++ b/scripts/check-knip-clean.sh
@@ -1,21 +1,4 @@
#!/usr/bin/env bash
-#
-# Run `pnpm run knip` and fail if it mutated the working tree.
-#
-# As of Phase B (#500), the `knip` script no longer passes
-# `--fix-type exports --fix-type types`, so knip should not modify
-# files in normal operation — it only reports findings and exits
-# non-zero on findings, which fails CI directly. This wrapper is
-# kept as a defensive guard against the `--fix-type` flag being
-# reintroduced in the future: auto-fixes in CI sandboxes never
-# reach main, but they DO produce code biome rejects (e.g. `export
-# { X } from 'foo'` → bare `;`, see PR #283), which then fails
-# the subsequent `pnpm run lint`.
-#
-# Compares `git diff` before/after, exits non-zero if knip added new
-# modifications. Developer WIP changes are preserved — only NEW
-# mutations from knip trigger the failure. Review with `git diff` and
-# either commit the cleanup or `git checkout --` to revert.
set -euo pipefail
diff --git a/scripts/check-no-major-changeset.sh b/scripts/check-no-major-changeset.sh
index 088f462c5..e3aac0ebc 100755
--- a/scripts/check-no-major-changeset.sh
+++ b/scripts/check-no-major-changeset.sh
@@ -1,13 +1,4 @@
#!/usr/bin/env bash
-#
-# Fail if any changeset declares a `major` bump. Open Knowledge is pre-1.0:
-# breaking changes ride as `minor`, and going to 1.0.0 is a deliberate team
-# decision — not something a single changeset should trigger. The release
-# math (scripts/compute-next-beta.mjs) would otherwise happily emit 1.0.0
-# from a stray `major` frontmatter. Mirrors check-i18n-drift.sh so
-# `pnpm run check` catches it before push.
-#
-# Canonical policy: .changeset/README.md.
set -euo pipefail
@@ -20,10 +11,6 @@ shopt -s nullglob
violations=()
for f in .changeset/*.md; do
[[ "$(basename "$f")" == "README.md" ]] && continue
- # Extract the YAML frontmatter (between the first two `---` fences) and look
- # for a `<pkg>: major` bump line. Mirrors the frontmatter parse in
- # scripts/compute-next-beta.mjs (`/:\s*(patch|minor|major)\s*$/`), so body
- # prose mentioning "major" can't false-positive.
fm="$(awk 'NR==1 && $0 !~ /^---/ {exit} /^---/{c++; next} c==1{print} c>=2{exit}' "$f")"
if grep -Eq ':[[:space:]]*major[[:space:]]*$' <<<"$fm"; then
violations+=("$f")
diff --git a/scripts/check-notices-clean.sh b/scripts/check-notices-clean.sh
index 3fcc78415..1f10bd256 100755
--- a/scripts/check-notices-clean.sh
+++ b/scripts/check-notices-clean.sh
@@ -1,12 +1,4 @@
#!/usr/bin/env bash
-#
-# Run the THIRD_PARTY_NOTICES.md generator in --check mode and fail if the
-# committed file does not match what the generator would produce against the
-# currently-installed `node_modules/`. Mirrors the `check-knip-clean.sh`
-# pattern so `bun run check` catches drift before push.
-#
-# Resolve the repo root from this script's location so callers from any cwd
-# (e.g. `packages/cli` invoking via `prepublishOnly`) hit the same generator.
set -euo pipefail
diff --git a/scripts/check-schema-snapshot-clean.sh b/scripts/check-schema-snapshot-clean.sh
index 29b2c6de1..59e1b527d 100755
--- a/scripts/check-schema-snapshot-clean.sh
+++ b/scripts/check-schema-snapshot-clean.sh
@@ -1,15 +1,4 @@
#!/usr/bin/env bash
-#
-# Run the audit-framework schema-snapshot generator in --check mode and fail
-# if the committed `packages/core/schema-snapshot.json` does not match what
-# the generator would produce against the currently-installed schema +
-# active mdast plugin chain. Mirrors the `check-knip-clean.sh` and
-# `check-notices-clean.sh` patterns so `pnpm run check` catches drift
-# before push.
-#
-# This snapshot is the canonical contract: drift here means downstream
-# tooling reads stale schema data. The gate is what keeps the committed
-# snapshot current.
set -euo pipefail
@@ -17,6 +6,4 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"
cd "$REPO_ROOT"
-# `pnpm exec` so tsx resolves from the workspace node_modules/.bin: a bare `tsx`
-# is not on PATH in a plain CI shell under pnpm (unlike bun's global shim).
pnpm exec tsx packages/core/scripts/dump-schema.ts --check
diff --git a/scripts/husky-prepare.sh b/scripts/husky-prepare.sh
index 13ae75daf..6bac4c17b 100755
--- a/scripts/husky-prepare.sh
+++ b/scripts/husky-prepare.sh
@@ -1,57 +1,12 @@
#!/usr/bin/env bash
-#
-# Conditional husky setup for Open Knowledge.
-#
-# Why this exists:
-# When OK is checked out as its own clone (inkeep/open-knowledge), `.git`
-# is at the OK root and husky correctly writes core.hooksPath to that
-# .git/config. Hooks fire from `<OK>/.husky/`. That's the design.
-#
-# When OK lives inside the agents-private monorepo, OK has no own `.git`
-# — the actual `.git` is at the parent root. Husky walks up and finds the
-# parent's `.git`, then writes a core.hooksPath that points back at
-# `<parent>/public/open-knowledge/.husky/` — clobbering whatever the
-# parent had configured. After that, every `git push` from anywhere in
-# agents-private fires OK's standalone-clone hook
-# (`pnpm run format && pnpm run lint && pnpm run check`) instead of the
-# parent's intended `pnpm check:monorepo-traps && pnpm check:pre-push`.
-# Developers then either install node_modules in every subtree or skip
-# hooks with `--no-verify` (forbidden by the repo's Git Safety Protocol).
-#
-# This guard skips husky entirely in the monorepo case so the parent's
-# own `.husky/` stays in charge of git hooks.
-#
-# When OK is cloned from the public mirror (inkeep/open-knowledge),
-# `.git` is at the OK root (standalone-clone shape) but the Copybara
-# manifest does NOT include `.husky/pre-commit` or `.husky/pre-push` in
-# the mirror output. A fresh public clone therefore has no hook files
-# for husky to register. Running `pnpm exec husky` would only create empty
-# `_/` scaffolding and the chmod would silently no-op, leaving cruft.
-# The second guard skips husky entirely in that case.
-#
-# Discriminators:
-# 1. Monorepo vs standalone: in a standalone clone `<OK>/.git` exists
-# (a directory for regular clones; a file pointing at the real gitdir
-# for `git worktree add` of the standalone clone). In the monorepo
-# `<OK>/.git` doesn't exist at all. `[ -e .git ]` is true in both
-# standalone shapes and false in the monorepo case.
-# 2. Public mirror vs internal standalone (when standalone): if neither
-# `.husky/pre-commit` nor `.husky/pre-push` exists on disk, husky has
-# nothing to register, so skip.
-#
-# Tested by: scripts/check-husky-prepare-guard.sh
set -euo pipefail
if [ ! -e .git ]; then
- # OK is checked out as a subdirectory of an enclosing repo (the
- # agents-private monorepo). Don't touch the parent's git config.
exit 0
fi
if [ ! -f .husky/pre-commit ] && [ ! -f .husky/pre-push ]; then
- # Fresh public-mirror clone — no hook files in the mirror output, so
- # husky has nothing to register. Skip to avoid empty scaffolding.
exit 0
fi
diff --git a/scripts/linux-repo/publish-linux-repo.sh b/scripts/linux-repo/publish-linux-repo.sh
index e85520d8a..c1c7d8ba4 100644
--- a/scripts/linux-repo/publish-linux-repo.sh
+++ b/scripts/linux-repo/publish-linux-repo.sh
@@ -1,34 +1,4 @@
#!/usr/bin/env bash
-# publish-linux-repo.sh — generate a signed apt + rpm repository tree from a
-# directory of built packages, ready to sync to the packages bucket.
-#
-# STATELESS BY DESIGN: the emitted metadata lists ONLY the packages present in
-# PACKAGES_DIR (one publish = the current version of one channel). The caller
-# syncs the output over the bucket's per-channel prefixes with --delete, so
-# the hosted repo is always "latest per channel" — no repo database, no state
-# to migrate, nothing to corrupt. Older versions remain downloadable from the
-# GitHub Release they shipped on; the repo's job is install + upgrade, not
-# archival.
-#
-# Layout emitted under OUT_DIR (mirrors the bucket layout):
-# apt/openknowledge.gpg binary keyring (signed-by=)
-# apt/key.asc same key, ASCII-armored
-# apt/dists/<channel>/InRelease clearsigned Release
-# apt/dists/<channel>/Release, Release.gpg detached-signature pair
-# apt/dists/<channel>/main/binary-{amd64,arm64}/Packages{,.gz}
-# apt/pool/<channel>/*.deb
-# rpm/key.asc
-# rpm/<channel>/{x86_64,aarch64}/*.rpm + repodata/ (repomd.xml.asc signed)
-#
-# Inputs (env):
-# PACKAGES_DIR directory containing the channel's .deb and .rpm files
-# CHANNEL stable | beta (becomes the apt suite + rpm subdir)
-# OUT_DIR output root (created; must not already contain a run)
-# GPG_KEY_ID key id / fingerprint of the imported signing key
-#
-# Requires: apt-ftparchive (apt-utils), createrepo_c, rpmsign (rpm), gpg.
-# The signing key must already be imported into the default keyring with no
-# passphrase (CI imports it from a secret; see the workflow).
set -euo pipefail
: "${PACKAGES_DIR:?set PACKAGES_DIR to the directory of .deb/.rpm files}"
@@ -47,18 +17,11 @@ if [ ${#DEBS[@]} -eq 0 ] && [ ${#RPMS[@]} -eq 0 ]; then
fi
echo "publishing channel=$CHANNEL: ${#DEBS[@]} deb(s), ${#RPMS[@]} rpm(s)"
-# ── apt ────────────────────────────────────────────────────────────────────
if [ ${#DEBS[@]} -gt 0 ]; then
APT="$OUT_DIR/apt"
POOL="$APT/pool/$CHANNEL"
DIST="$APT/dists/$CHANNEL"
mkdir -p "$POOL" "$DIST/main/binary-amd64" "$DIST/main/binary-arm64"
- # Rename into Debian's `name_version_arch.deb` convention on the way into
- # the pool: apt-ftparchive's `--arch` filter matches the FILENAME pattern
- # `*_<arch>.deb`, so electron-builder's `OpenKnowledge-arm64.deb` shape
- # silently lands in NO per-arch index (empty Packages, "Unable to locate
- # package" — caught in the VM rehearsal). Fields come from the deb's own
- # control, so the rename can't drift from the metadata.
for deb in "${DEBS[@]}"; do
pkg=$(dpkg-deb -f "$deb" Package)
ver=$(dpkg-deb -f "$deb" Version)
@@ -66,18 +29,11 @@ if [ ${#DEBS[@]} -gt 0 ]; then
cp "$deb" "$POOL/${pkg}_${ver}_${arch}.deb"
done
- # apt-ftparchive emits Filename: relative to the directory it scans from —
- # run from the apt root so entries read `pool/<channel>/...`, matching the
- # deb line's URL base.
(
cd "$APT"
for arch in amd64 arm64; do
apt-ftparchive --arch "$arch" packages "pool/$CHANNEL" \
> "dists/$CHANNEL/main/binary-$arch/Packages"
- # An empty index is structurally valid (signatures verify, URLs 200)
- # but users on that arch get "Unable to locate package" — exactly how
- # the filename-convention bug above first presented. Loud, not fatal:
- # a deliberately single-arch publish stays possible.
if [ ! -s "dists/$CHANNEL/main/binary-$arch/Packages" ]; then
echo "warning: Packages index for arch=$arch is EMPTY — no pool deb matched; expected only if this publish intentionally ships no $arch build" >&2
fi
@@ -93,23 +49,18 @@ if [ ${#DEBS[@]} -gt 0 ]; then
release "dists/$CHANNEL" > "dists/$CHANNEL/Release"
)
- # Both signature forms: InRelease (modern, single-fetch) + Release.gpg
- # (older apt). --batch/loopback because CI keys carry no passphrase.
gpg --batch --yes --pinentry-mode loopback --local-user "$GPG_KEY_ID" \
--clearsign -o "$DIST/InRelease" "$DIST/Release"
gpg --batch --yes --pinentry-mode loopback --local-user "$GPG_KEY_ID" \
--armor --detach-sign -o "$DIST/Release.gpg" "$DIST/Release"
- # signed-by= wants a binary keyring; the .asc is for humans + docs.
gpg --export "$GPG_KEY_ID" > "$APT/openknowledge.gpg"
gpg --armor --export "$GPG_KEY_ID" > "$APT/key.asc"
fi
-# ── rpm ────────────────────────────────────────────────────────────────────
if [ ${#RPMS[@]} -gt 0 ]; then
RPMROOT="$OUT_DIR/rpm"
mkdir -p "$RPMROOT"
- # rpmsign resolves its key through the rpm macro, not a CLI flag.
echo "%_gpg_name $GPG_KEY_ID" > "$HOME/.rpmmacros"
for rpm in "${RPMS[@]}"; do
@@ -122,14 +73,11 @@ if [ ${#RPMS[@]} -gt 0 ]; then
dest="$RPMROOT/$CHANNEL/$arch"
mkdir -p "$dest"
cp "$rpm" "$dest/"
- # Package-level signature — dnf's default gpgcheck=1 verifies THIS, not
- # just the repo metadata signature.
rpmsign --addsign "$dest/$base" >/dev/null
done
for dir in "$RPMROOT/$CHANNEL"/*/; do
createrepo_c --general-compress-type=gz "$dir" >/dev/null
- # repo_gpgcheck=1 verifies this detached signature over the metadata index.
gpg --batch --yes --pinentry-mode loopback --local-user "$GPG_KEY_ID" \
--armor --detach-sign -o "$dir/repodata/repomd.xml.asc" "$dir/repodata/repomd.xml"
done
diff --git a/test-support/bun-global-shim.test.ts b/test-support/bun-global-shim.test.ts
index 2c46fb0e8..eb922f6a0 100644
--- a/test-support/bun-global-shim.test.ts
+++ b/test-support/bun-global-shim.test.ts
@@ -62,11 +62,8 @@ describe('Bun global facade', () => {
writeFileSync(join(root, 'sub', 'nested.ts'), '');
const found = [...new bunFacade.Glob('**/*.ts').scanSync({ cwd: root })];
- // Visible files (including those in normal subdirs) are matched.
expect(found).toContain('visible.ts');
expect(found).toContain('sub/nested.ts');
- // Dotfiles and anything under a dot-directory are neither matched nor
- // descended into — matching real Bun.Glob's `dot: false` default.
expect(found).not.toContain('.hidden.ts');
expect(found).not.toContain('.git/inside.ts');
} finally {
@@ -79,10 +76,6 @@ describe('Bun global facade', () => {
});
test('Bun.resolveSync ignores the development condition (matches bun production resolution)', () => {
- // micromark ships a `./dev/` build under its `development` export condition.
- // The Vitest worker runs with `--conditions development`, so a naive
- // require.resolve would land in `dev/`; bun's Bun.resolveSync resolves to
- // the production entry. The facade must match bun.
const resolved = bunFacade.resolveSync('micromark', selfDir).replaceAll('\\', '/');
expect(resolved).toContain('/node_modules/micromark/');
expect(resolved).not.toContain('/micromark/dev/');
@@ -91,12 +84,9 @@ describe('Bun global facade', () => {
test('Bun.Transpiler compiles TypeScript and throws on a syntax error', () => {
const transpiler = new bunFacade.Transpiler({ loader: 'ts' });
const out = transpiler.transformSync('const x: number = 1;\n');
- // Type annotation erased.
expect(out).not.toContain(': number');
expect(out).toContain('const x');
expect(() => transpiler.transformSync('const = ;')).toThrow();
- // Enum lowering needs `transform` mode; on strip-only runtimes (Node 26)
- // the facade falls back and TS-only constructs throw instead of compiling.
let transformAvailable = true;
try {
stripTypeScriptTypes('0', { mode: 'transform' });
@@ -126,11 +116,6 @@ describe('Bun global facade', () => {
});
test('spawnSync surfaces a launch failure instead of reporting exit 0', () => {
- // Regression guard. `spawnSync` returns `{status: null, error: ENOENT}` when
- // the child cannot be launched; mapping that to `exitCode: 0` reported a
- // process that never ran as a clean success, and would let a test asserting
- // `exitCode === 0` pass against a command that never executed. Both shapes
- // below produce that state on every platform.
expect(() => bunFacade.spawnSync(['definitely-not-a-real-binary-xyz'])).toThrow();
expect(() =>
bunFacade.spawnSync({
@@ -141,8 +126,6 @@ describe('Bun global facade', () => {
});
test('a real non-zero exit still reports its code (not swallowed by the guard)', () => {
- // The complement of the guard above: a process that DID run and exited
- // non-zero must still surface its code rather than throwing.
const result = bunFacade.spawnSync([process.execPath, '-e', 'process.exit(78)']);
expect(result.exitCode).toBe(78);
expect(result.success).toBe(false);
@@ -150,9 +133,6 @@ describe('Bun global facade', () => {
});
describe('Bun.CryptoHasher', () => {
- // Published SHA-256 vector for the ASCII string "abc" — independent of the
- // node:crypto the facade wraps, so a wrong wiring (bad algorithm, dropped
- // data) fails against a real answer rather than tautologically agreeing.
const SHA256_ABC_HEX = 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad';
const SHA256_ABC_BASE64 = 'ungWv48Bz+pBQUDeXa4iI7ADYaOWF3qctBD/YfIAFa0=';
@@ -165,9 +145,7 @@ describe('Bun.CryptoHasher', () => {
test('.update() returns the hasher and accumulates across chained calls', () => {
const hasher = new bunFacade.CryptoHasher('sha256');
- // Chainable: update must return the same instance.
expect(hasher.update('a')).toBe(hasher);
- // Two separate updates of 'a' then 'bc' must digest identically to one 'abc'.
expect(hasher.update('bc').digest('hex')).toBe(SHA256_ABC_HEX);
});
});
diff --git a/test-support/bun-global-shim.ts b/test-support/bun-global-shim.ts
index 623d6ce4b..e074ab294 100644
--- a/test-support/bun-global-shim.ts
+++ b/test-support/bun-global-shim.ts
@@ -1,23 +1,3 @@
-/**
- * `Bun` global facade for running bun-flavored tests under stock Node.
- *
- * Importing this module (it is the shared vitest base config's setup file)
- * installs a `globalThis.Bun` covering the Bun runtime APIs the suites touch:
- * `file`, `write`, `sleep`, `which`, `spawnSync`, `Glob`, `TOML`, `gc`, plus
- * `resolveSync`, `CryptoHasher`, and `Transpiler`. Each maps to a Node
- * equivalent.
- *
- * `Bun.serve` and async `Bun.spawn` have NO facade here: their call sites are
- * rewritten to `node:http` / `node:child_process` per file during the owning
- * package's flip, because a faithful streaming facade would hide semantic
- * differences the rewrites need to make explicit.
- *
- * Two globals get installed, not one: the `Bun` facade and a `self` alias.
- * Dependents of the first are literal `Bun.` in test files, which a grep finds.
- * Dependents of the second are import-time reads of `self` in browser-targeting
- * modules (`scheduler-polyfill` is one), which no `Bun.` search surfaces. Both
- * have to be accounted for before this module can go away.
- */
import { spawnSync as nodeSpawnSync } from 'node:child_process';
import { createHash } from 'node:crypto';
import fs from 'node:fs';
@@ -26,19 +6,10 @@ import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { parse as parseToml, stringify as stringifyToml } from 'smol-toml';
-// ---- Bun.Glob (hand-rolled: no glob dependency) ----
-
-/** Escape a literal character for embedding in a RegExp source. */
function escapeRegexChar(c: string): string {
return /[.+^${}()|[\]\\]/.test(c) ? `\\${c}` : c;
}
-/**
- * Translate a glob body to a RegExp source fragment. `*` stays within a path
- * segment, `**` crosses segments, `?` is one non-separator char, `{a,b}` is
- * alternation (its branches may themselves contain globs), `[...]` is a char
- * class. Kept dependency-free so the shim adds no runtime beyond Node + Vitest.
- */
function translateGlob(glob: string): string {
const chars = [...glob];
let out = '';
@@ -125,8 +96,6 @@ class BunGlobFacade {
return results;
}
for (const entry of entries) {
- // Bun.Glob defaults to `dot: false`: a segment starting with `.`
- // (dot-dirs like `.git`/`.ok`, dotfiles) is never matched or descended.
if (entry.name.startsWith('.')) continue;
const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
@@ -148,8 +117,6 @@ class BunGlobFacade {
}
}
-// ---- Bun.file ----
-
function bunFile(target: string | URL) {
const filePath = target instanceof URL ? target.pathname : target;
return {
@@ -190,19 +157,12 @@ function bunFile(target: string | URL) {
};
}
-// ---- Bun.write ----
-
function destinationPath(destination: string | URL | { name: string }): string {
if (typeof destination === 'string') return destination;
if (destination instanceof URL) return fileURLToPath(destination);
return destination.name;
}
-/**
- * Minimal `Bun.write`: writes `input` to `destination`, creating parent
- * directories (Bun does this implicitly), and resolves to the byte count.
- * Covers the string / typed-array / ArrayBuffer inputs the suites pass.
- */
async function bunWrite(
destination: string | URL | { name: string },
input: string | ArrayBufferView | ArrayBuffer,
@@ -221,8 +181,6 @@ async function bunWrite(
return bytes.byteLength;
}
-// ---- Bun.sleep ----
-
function bunSleep(ms: number | Date): Promise<void> {
const delay = ms instanceof Date ? ms.getTime() - Date.now() : ms;
return new Promise((resolve) => {
@@ -230,8 +188,6 @@ function bunSleep(ms: number | Date): Promise<void> {
});
}
-// ---- Bun.which ----
-
function bunWhich(command: string, options?: { PATH?: string; cwd?: string }): string | null {
const searchPath = options?.PATH ?? process.env.PATH ?? '';
for (const dir of searchPath.split(path.delimiter)) {
@@ -241,14 +197,11 @@ function bunWhich(command: string, options?: { PATH?: string; cwd?: string }): s
fs.accessSync(candidate, fs.constants.X_OK);
return candidate;
} catch {
- /* not executable here — keep searching PATH */
}
}
return null;
}
-// ---- Bun.spawnSync (via node:child_process) ----
-
interface SpawnSyncOptions {
cwd?: string;
env?: Record<string, string | undefined>;
@@ -269,23 +222,6 @@ function bunSpawnSync(
});
const stdout = result.stdout ?? Buffer.alloc(0);
const stderr = result.stderr ?? Buffer.alloc(0);
- // FAIL LOUD when the process never ran.
- //
- // `spawnSync` reports `status: null` + a populated `error` when the child
- // could not be launched at all (ENOENT on the binary, a cwd that does not
- // exist, EACCES). The previous `result.status ?? 0` mapped that to exit code
- // ZERO — a process that never executed was reported as a clean success. Any
- // assertion of the form `expect(result.exitCode).toBe(N)` then failed with the
- // uninformative `expected +0 to be N`, and — far worse — a test asserting
- // `exitCode === 0` would have PASSED against a command that never ran.
- //
- // Real-Windows-verified: `spawnSync('node', [...], {cwd: '<missing>'})` returns
- // `{status: null, error: ENOENT}`, which is exactly how
- // `git-preflight-spawn.test.ts` came to report 0 instead of 78.
- //
- // Throwing (rather than inventing a sentinel code) is the honest mapping: a
- // launch failure is a harness bug every time, and the thrown error names the
- // real cause instead of leaving it to be inferred from a bogus exit code.
if (result.error) {
throw result.error;
}
@@ -297,8 +233,6 @@ function bunSpawnSync(
return {
stdout,
stderr,
- // Signal-killed processes legitimately have a null status; keep null rather
- // than coercing, so `toBe(0)` cannot pass for a killed process either.
exitCode: result.status,
signalCode: result.signal,
success: result.status === 0,
@@ -306,24 +240,8 @@ function bunSpawnSync(
};
}
-// ---- Bun.resolveSync ----
-
-/**
- * bun's `Bun.resolveSync` does not apply the `development` export condition,
- * but the Vitest worker runs with `--conditions development` in its execArgv,
- * so Node's `require.resolve` / `import.meta.resolve` would pick a package's
- * `development` target (e.g. micromark and mdast-util-from-markdown ship a
- * `./dev/` build under that condition). Production conditions match what bun
- * resolves to.
- */
const PRODUCTION_CONDITIONS = ['node', 'import', 'require', 'default'];
-/**
- * Walk an `exports` value (string, array, or conditions object) picking the
- * first branch that matches a production condition, in the object's own key
- * order — the same first-match semantics Node uses. Returns null when nothing
- * matches (e.g. a purely `development`-gated target under production).
- */
function selectExportsTarget(node: unknown, conditions: string[]): string | null {
if (typeof node === 'string') return node;
if (Array.isArray(node)) {
@@ -344,14 +262,6 @@ function selectExportsTarget(node: unknown, conditions: string[]): string | null
return null;
}
-/**
- * Codes where the CJS `require.resolve` legitimately fails but the module still
- * resolves via the ESM resolver — a package with an `import`-only exports map,
- * a directory import, an ESM target. Bun.resolveSync resolves these, so fall
- * back to `import.meta.resolve`. Any OTHER failure (a malformed package.json or
- * exports target) is a real error and surfaces rather than being papered over
- * by a fallback that could return a different resolution.
- */
const ESM_RESOLVER_FALLBACK_CODES = new Set([
'MODULE_NOT_FOUND',
'ERR_PACKAGE_PATH_NOT_EXPORTED',
@@ -372,7 +282,6 @@ function bunResolveSync(specifier: string, from: string): string {
return fileURLToPath(import.meta.resolve(specifier, pathToFileURL(fromFile).href));
}
};
- // Relative/absolute specifiers never touch an exports map.
if (specifier.startsWith('.') || specifier.startsWith('/')) return resolveAny();
const resolved = resolveAny().replaceAll('\\', '/');
@@ -409,8 +318,6 @@ function bunResolveSync(specifier: string, from: string): string {
return path.join(pkgRoot, target);
}
-// ---- Bun.CryptoHasher ----
-
class BunCryptoHasherFacade {
#hash: ReturnType<typeof createHash>;
constructor(algorithm: string) {
@@ -425,19 +332,6 @@ class BunCryptoHasherFacade {
}
}
-// ---- Bun.Transpiler ----
-
-/**
- * bun's `Transpiler` strips/compiles TypeScript to JavaScript and throws on a
- * syntax error. Node's `stripTypeScriptTypes` in `transform` mode is the
- * dependency-free equivalent: it compiles TS-only constructs (enums, parameter
- * properties) rather than only erasing annotations, and throws on invalid
- * syntax — the property the callers assert. Node 26 ships strip-only
- * (`transform` is rejected with ERR_INVALID_ARG_VALUE), so fall back to
- * `strip` there: annotations still erase and invalid syntax still throws;
- * only TS-only constructs — which no caller feeds in — throw instead of
- * compiling. Only the sync path the suites use is provided.
- */
function transpileTs(code: string): string {
try {
return stripTypeScriptTypes(code, { mode: 'transform' });
@@ -456,8 +350,6 @@ class BunTranspilerFacade {
}
}
-// ---- assembled facade ----
-
export const bunFacade = {
file: bunFile,
write: bunWrite,
@@ -474,17 +366,9 @@ export const bunFacade = {
Transpiler: BunTranspilerFacade,
};
-/**
- * Install the facade as `globalThis.Bun`, idempotently. A real `Bun` global
- * (should these ever run under bun again) wins; the `??=` never clobbers it.
- */
export function installBunGlobal(): void {
const g = globalThis as Record<string, unknown> & typeof globalThis;
g.Bun ??= bunFacade as unknown as typeof globalThis.Bun;
- // bun exposes the web `self` alias (=== globalThis) even in its non-DOM test
- // runtime; browser-targeting app modules read it at import time. Node's
- // node-env has no `self`, so provide the same alias. jsdom-env tiers already
- // define `self` (their window), which the `??=` preserves.
g.self ??= globalThis;
}
diff --git a/test-support/no-net-connect.test.ts b/test-support/no-net-connect.test.ts
index 48f0bfc74..5dc834ba1 100644
--- a/test-support/no-net-connect.test.ts
+++ b/test-support/no-net-connect.test.ts
@@ -6,8 +6,6 @@ import {
REFUSED_LOOPBACK_ORIGIN_ALT,
} from './refused-loopback.test-helper';
-// Port 1 is on the WHATWG fetch blocked-port list. It is named only here, as the
-// alternative the refused origin must NOT drift into.
const FETCH_BLOCKED_PORT_ORIGIN = 'http://127.0.0.1:1';
describe('isLoopbackHostname', () => {
@@ -36,11 +34,6 @@ describe('isLoopbackHostname', () => {
])('%s is not loopback', (host) => expect(isLoopbackHostname(host)).toBe(false));
});
-// Only the tests that trip the guard ON PURPOSE mute it, and each of them asserts
-// the `[no-net-connect]` line was emitted. Muting block-wide would swallow an
-// UNEXPECTED console.error from the tests that are meant to stay silent, and
-// muting without asserting would leave the log line -- the enforcement mechanism
-// behind the zero-lines invariant -- as the one thing here with no coverage.
async function blockedBy(run: () => Promise<unknown>): Promise<unknown> {
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
try {
diff --git a/test-support/no-net-connect.ts b/test-support/no-net-connect.ts
index 6cfe8b1e3..2f820f553 100644
--- a/test-support/no-net-connect.ts
+++ b/test-support/no-net-connect.ts
@@ -1,58 +1,7 @@
-/**
- * Hermetic-test guard: rejects `fetch` to anything that is not loopback.
- *
- * A unit test whose pass/fail depends on a socket to the outside world inherits
- * the resolver, the proxy, and a remote host's availability. This makes that class
- * refuse before it leaves the process, naming the test that made the request.
- *
- * Loopback stays reachable deliberately: suites here stand up real servers on
- * 127.0.0.1 and talk to them, which never leaves the machine. A CLOSED loopback
- * port is the sanctioned way to get a REAL transport error without inventing one
- * (see `refused-loopback.test-helper.ts`).
- *
- * A clean run emits ZERO `[no-net-connect]` lines; the guard's own suite mutes its
- * deliberate blocks to keep that literally true. A guard that fires routinely is a
- * broken alarm, so a line in CI output is a new reach to fix at its seam.
- *
- * WHAT THIS DOES NOT COVER, in rough order of how likely you are to hit it:
- * - A test that assigns over `globalThis.fetch`. The guard is then inert in that
- * file, for every host. This is the dominant idiom in this subtree, so the file
- * you are editing may well have it switched off. Prefer a
- * host-conditional pass-through to the captured real fetch, or a module-level
- * fake, over a blanket replacement.
- * - `node:http` / `node:https` directly. `packages/server/src/link-preview/
- * guarded-fetch.ts` is shipping product code that does exactly this.
- * - Raw `node:net` sockets, and jsdom's `XMLHttpRequest`.
- * - Spawned subprocesses, which own their own globals: the CLI e2e tier
- * (`packages/cli/vitest.e2e.config.ts`) tests a binary in another process.
- *
- * Prior art, and why this diverges: `msw` (`setupServer(...).listen({
- * onUnhandledRequest: 'error' })`) closes `node:http`, XHR and `fetch` in one
- * interceptor stack; `nock` and undici's `MockAgent` both offer
- * `disableNetConnect` / `enableNetConnect`, and `MockAgent` intercepts at the
- * dispatcher rather than by replacing a global. All three are request-mocking
- * frameworks; what is wanted here is a single allow-loopback-only policy on the one
- * surface this code fetches through, installed in every worker with no per-test
- * registration. Note also that none of them closes the first gap above: a
- * `globalThis.fetch` reassignment bypasses a dispatcher just as completely.
- *
- * There is deliberately no opt-out flag: an escape hatch would be re-openable by
- * the next test that finds the guard inconvenient.
- */
import { expect } from 'vitest';
const INSTALLED = Symbol.for('ok.test.noNetConnect.installed');
-// Deliberately matches `isLoopbackBindAddress` in packages/core
-// (src/config/resolve-server-config.ts): same hosts, same octet validation. The
-// wildcards `0.0.0.0` and `::` are NOT loopback -- core classifies them that way,
-// `loopback-bind-discipline.test.ts` treats binding them as a violation, and per
-// Winsock the all-zeros destination is not even routable on Windows. `.localhost`
-// is admitted on top of core's set: RFC 6761 reserves it to resolve to loopback,
-// and this predicate answers about fetch targets rather than bind addresses.
-// Both halves of that claim, the parity and the deliberate divergences, are
-// enforced by `packages/core/src/config/loopback-parity.test.ts`, which lives
-// beside `isLoopbackBindAddress` because that is where its dep graph already is.
const IPV4_OCTET = '(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)';
const LOOPBACK_V4_RE = new RegExp(`^127\\.${IPV4_OCTET}\\.${IPV4_OCTET}\\.${IPV4_OCTET}$`);
@@ -85,8 +34,6 @@ function resolveTarget(input: unknown): URL | null {
}
}
-// data:/blob:/file: carry no host and open no socket, so a hostname test would
-// refuse them for having an empty hostname rather than for going anywhere.
const SOCKETLESS_PROTOCOLS = new Set(['data:', 'blob:', 'file:']);
export class NetConnectBlockedError extends Error {
@@ -104,9 +51,6 @@ export class NetConnectBlockedError extends Error {
export function installNoNetConnect(): void {
const realFetch = globalThis.fetch;
if (typeof realFetch !== 'function') return;
- // The marker lives on the wrapper rather than on `globalThis`, so a test that
- // replaced `fetch` without restoring it cannot make a later install believe the
- // guard is present when it is not (precedent: `client-fetch.ts`).
if ((realFetch as { [INSTALLED]?: boolean })[INSTALLED] === true) return;
const guardedFetch = async function guardedFetch(
@@ -114,9 +58,6 @@ export function installNoNetConnect(): void {
init?: Parameters<typeof realFetch>[1],
): ReturnType<typeof realFetch> {
const target = resolveTarget(input);
- // An unresolvable target cannot reach the network either way: `fetch` rejects a
- // malformed or relative-without-base URL before opening a socket, so passing it
- // through surfaces its own error rather than masking it with the guard's.
if (
target !== null &&
!SOCKETLESS_PROTOCOLS.has(target.protocol) &&
@@ -124,9 +65,6 @@ export function installNoNetConnect(): void {
) {
const testName = expect.getState().currentTestName ?? '<outside a test>';
const blocked = new NetConnectBlockedError(target.hostname, testName);
- // A caller that swallows transport errors (every defensive upload path does)
- // would otherwise turn this into a silently-wrong assertion rather than a
- // legible failure, which is the exact invisibility this guard exists to end.
console.error(`[no-net-connect] ${blocked.message}`);
throw blocked;
}
diff --git a/test-support/refused-loopback.test-helper.ts b/test-support/refused-loopback.test-helper.ts
index f04e78018..19322a4a3 100644
--- a/test-support/refused-loopback.test-helper.ts
+++ b/test-support/refused-loopback.test-helper.ts
@@ -1,27 +1,3 @@
-/**
- * Loopback origins whose connections are always refused by the kernel.
- *
- * A client pointed here gets a REAL transport failure rather than a hand-built
- * `Error`: nothing listens, so `fetch` rejects with a genuine undici
- * `TypeError: fetch failed` wrapping `Error { code: 'ECONNREFUSED', syscall:
- * 'connect' }`, and it never leaves the machine.
- *
- * Two constraints fix the port numbers, both pinned by `no-net-connect.test.ts`:
- *
- * - Below every platform's ephemeral range (Linux 32768-60999, macOS and Windows
- * 49152-65535), so `listen(0)` can never hand one out. Bind-then-close returns
- * the port to that pool, leaving a window for a concurrent test to re-bind it
- * and turn the expected refusal into a connection.
- * - Not on the WHATWG fetch blocked-port list. Port 1 is, and fails quietly
- * rather than loudly: fetch rejects before any syscall with
- * `cause: Error('bad port')`, which carries no `code`, so an errno assertion
- * reads `undefined` instead of `ECONNREFUSED`.
- *
- * The ALT origin exists so a test can tell two hosts apart: a "names the host it
- * actually tried" assertion stops discriminating once both candidates collapse
- * onto one origin. Both origins are held to both constraints by the same
- * parametrized tests, so neither can rot into the other's shape.
- */
export const REFUSED_LOOPBACK_ORIGIN = 'http://127.0.0.1:4';
export const REFUSED_LOOPBACK_ORIGIN_ALT = 'http://127.0.0.1:5';
diff --git a/test-support/setup-files-contract.test.ts b/test-support/setup-files-contract.test.ts
index d2e43ebbe..527c3faeb 100644
--- a/test-support/setup-files-contract.test.ts
+++ b/test-support/setup-files-contract.test.ts
@@ -1,61 +1,3 @@
-/**
- * Pins the real invariant: every vitest project resolves a `setupFiles` array
- * that contains the hermetic-network guard.
- *
- * This used to match config SOURCE TEXT for a derived spread, which is how the
- * guard could go missing: a project that writes its own `test: { ... }`, or its
- * own `setupFiles:` key, replaces the base array rather than extending it, and
- * every test still passes. Five rewrites of that heuristic each closed one
- * spelling and admitted the next — comment text vouching for code, a base spread
- * short-circuiting the key, an inert optional group, a name mention standing in
- * for the value, and finally `[...base.test.setupFiles].filter(...)`, which reads
- * as a derived spread and drops whatever the filter removes. A regex over source
- * text is modelling JS array semantics in a character class; it cannot converge.
- *
- * So the configs are imported and their RESOLVED arrays inspected instead. No
- * spelling can defeat that: spread, pass-through, index, `.filter`, `.concat` and
- * anything else all collapse to the array the project actually runs with.
- *
- * The earlier objection to importing them — that `packages/app/vitest.config.ts`
- * needs `@vitejs/plugin-react`, which the OK root does not depend on — does not
- * hold. Bare specifiers resolve from the importer's directory, and pnpm's
- * isolated layout puts a declared devDep at `packages/app/node_modules`, so the
- * import resolves from here. Verified by importing it from outside the package.
- *
- * Two assertions, because either alone has a blind spot. Each project's resolved
- * array is compared against `okVitestBase.test.setupFiles`, which needs no
- * maintenance when the base gains a guard but is self-referential: delete an entry
- * from the base and both sides move together. So the base is ALSO checked against
- * a literal list, which exists purely to be the fixed point the derived comparison
- * lacks. That list, `KNOWN_TEST_PROJECTS` and `KNOWN_BUILD_CONFIGS` are the three
- * things here anyone has to maintain by hand, and they are not all the same shape.
- * The two config lists are EXACT, so a config appearing or disappearing both fail;
- * a floor would have let a vanishing project pass silently, which is the direction
- * that matters. `REQUIRED_BASE_SETUP_FILES` is deliberately a subset check, since
- * the base gaining a guard should not red this file. What it does catch is a
- * project installing only SOME of the base's entries, which is the per-project
- * comparison's job: picking a single entry out of the base array fails there.
- *
- * `findConfigs` enumerates every config the repo TRACKS, so a NEW project is
- * covered the moment its config lands, with no per-project opt-in to forget.
- * Only vitest projects are imported: a build config like
- * `packages/app/vite.config.ts` mutates `process.env` and touches the filesystem at
- * module scope, so importing it to learn it has no `test` block would pay a real
- * side effect for a null result. They are enumerated in `KNOWN_BUILD_CONFIGS`
- * instead, so a new one forces a decision rather than being classified by a
- * pattern that fails open on an indirected `test` key and closed on a comment
- * containing one. The vitest configs pay their own import cost deliberately,
- * which is the price of reading resolved arrays rather than parsing text.
- * `docs/vitest.real-source.config.mts` is the only function-form one, so it is the
- * only config whose factory this file CALLS; that call runs
- * `mdx(..., { outDir: '.source-vitest' })` against this cwd rather than the docs
- * runner's, and a `git status --porcelain` after a full run measured clean. Nothing
- * pins that: `.source-vitest/` is ignored only under `docs/`, so if an upstream
- * change ever moved emission to call time the artifact would surface here as an
- * untracked OK-root directory. Nothing automated reads that: the signal is a
- * `git status` before the next commit, and a git ignore rule at OK root would
- * delete it, so none is added.
- */
import { execFileSync } from 'node:child_process';
import { existsSync } from 'node:fs';
import { basename, join } from 'node:path';
@@ -66,14 +8,9 @@ import { okVitestBase } from './vitest.base';
const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url));
-// Both patterns admit a dotted prefix, because the repo uses that form
-// (`electron.vite.config.ts`). Start-anchoring them would hide a future
-// `electron.vitest.config.ts` from the sweep entirely.
const CONFIG_FILENAME = /(?:^|\.)vite(st)?[\w.-]*\.config\.m?[jt]s$/;
const TEST_CONFIG_FILENAME = /(?:^|\.)vitest[\w.-]*\.config\.m?[jt]s$/;
-// Every TRACKED config matching TEST_CONFIG_FILENAME, enumerated rather than
-// counted, so a project disappearing fails as loudly as one appearing.
const KNOWN_TEST_PROJECTS = [
'docs/vitest.config.ts',
'docs/vitest.real-source.config.mts',
@@ -92,44 +29,15 @@ const KNOWN_TEST_PROJECTS = [
'vitest.scripts.config.ts',
];
-// Every config matching CONFIG_FILENAME that is NOT a vitest project.
const KNOWN_BUILD_CONFIGS = [
'packages/app/vite.config.ts',
'packages/desktop/electron.vite.config.ts',
];
-// Named literally, NOT derived from the base. The per-project check compares
-// against `okVitestBase.test.setupFiles`, which is self-referential on its own:
-// delete an entry from the base and both sides move together, leaving the suite
-// green with that guard uninstalled everywhere. This is the anchor that catches it.
const REQUIRED_BASE_SETUP_FILES = ['bun-global-shim.ts', 'no-net-connect.ts'];
const isTestConfig = (relPath: string): boolean => TEST_CONFIG_FILENAME.test(basename(relPath));
-// TRACKED files, not a directory walk, and read through git rather than the
-// filesystem. A PR check tests the branch MERGED with its base, so the working tree
-// can lack a config the base has gained: `docs/vitest.real-source.config.mts`
-// landed on main while this branch was behind it, and a disk sweep saw 14 projects
-// here against CI's 15. `git ls-files` is the set the invariant is about, and it is
-// the same set on a runner and in a worktree at the same commit.
-//
-// `ls-files` reads the INDEX, so a config staged-then-deleted from the working
-// tree is still enumerated: a vitest one then fails on `import()` with a
-// module-not-found naming a path that looks fine, and a build config fails
-// nothing, because only vitest projects are imported. Neither is caught by the
-// exact enumerations, because the index still lists the name. Filtering the sweep
-// by `existsSync` would catch them there, but only by reintroducing the
-// index-vs-disk skew rejected above, and the vitest half would red with a message
-// telling the reader to edit `KNOWN_TEST_PROJECTS` when the fix is to restore the
-// file. So it is asserted separately instead, which puts a named sentence ahead of
-// the module-not-found.
-//
-// `gitCleanEnv()` because `execFileSync` inherits `process.env` and `cwd` does not
-// override an inherited GIT_DIR, so any caller that already has one would resolve
-// this `ls-files` against a different tree. The pre-push hook is NOT that caller —
-// it unsets the GIT_* family before any step runs — so this is prophylaxis against
-// a future caller, following `scripts/check-no-tracked-but-ignored.test.mjs`, not a
-// fix for a live path.
function findConfigs(): string[] {
return execFileSync(
'git',
diff --git a/test-support/share/frozen-v1-share-reader.test-helper.ts b/test-support/share/frozen-v1-share-reader.test-helper.ts
index 38ec0ec06..d99b8be04 100644
--- a/test-support/share/frozen-v1-share-reader.test-helper.ts
+++ b/test-support/share/frozen-v1-share-reader.test-helper.ts
@@ -5,10 +5,6 @@ export type FrozenV1TokenOutcome =
export type FrozenV1CustomOutcome = 'invalid' | 'ok-v1-url';
-/**
- * Release-baseline v1 decoder copied before v2 exists. It deliberately owns
- * its base64url and UTF-8 paths and must never import the production codec.
- */
export function frozenV1DecodeShareToken(encoded: string): FrozenV1TokenOutcome {
const cleaned = encoded.split(/[?#]/)[0];
if (cleaned.length === 0) return { kind: 'invalid' };
@@ -32,10 +28,6 @@ export function frozenV1DecodeShareToken(encoded: string): FrozenV1TokenOutcome
}
}
-/**
- * Release-baseline custom-scheme routing ignores unknown query parameters and
- * reads only the historical url field. Token-only input is therefore invalid.
- */
export function frozenV1CustomSchemeOutcome(input: string): FrozenV1CustomOutcome {
let parsed: URL;
try {
diff --git a/test-support/vitest.base.test.ts b/test-support/vitest.base.test.ts
index 1ca1041cc..bbf62903e 100644
--- a/test-support/vitest.base.test.ts
+++ b/test-support/vitest.base.test.ts
@@ -4,9 +4,6 @@ import { importMetaDirPlugin } from './vitest.base';
type TransformFn = (code: string) => { code: string } | null;
const transform = importMetaDirPlugin.transform as unknown as TransformFn;
-// Build the bun-only marker at runtime so its literal never appears in this
-// file's own source — otherwise the plugin (which transforms every file,
-// including this one) would rewrite the test inputs before the test runs.
const BUN_DIR = `import.meta.${'dir'}`;
describe('importMetaDirPlugin', () => {
@@ -16,19 +13,12 @@ describe('importMetaDirPlugin', () => {
});
test('does NOT rewrite to a URL pathname (Windows regression guard)', () => {
- // `new URL(".", import.meta.url).pathname` is a URL pathname, not a
- // filesystem path: on Windows it is `/C:/repo/pkg/src` — leading slash,
- // forward separators — which ENOENTs as a `spawnSync` cwd and corrupts any
- // `path` math built on it. Real-Windows-verified failure mode; see the
- // plugin's comment.
const result = transform(`const d = ${BUN_DIR};`);
expect(result?.code).not.toContain('new URL');
expect(result?.code).not.toContain('pathname');
});
test('leaves the native import.meta.dirname untouched', () => {
- // A greedy substring replace would corrupt `import.meta.dirname` into
- // `(...))name`; the transform must no-op when only the native form is present.
expect(transform('const d = import.meta.dirname;')).toBeNull();
});
diff --git a/test-support/vitest.base.ts b/test-support/vitest.base.ts
index 07121d3ca..678bc4d99 100644
--- a/test-support/vitest.base.ts
+++ b/test-support/vitest.base.ts
@@ -1,69 +1,19 @@
-/**
- * Shared Vitest base config for the Open Knowledge workspace.
- *
- * Per-package configs spread `okVitestBase` and add their own `test.include` /
- * `test.root`. Centralizing three load-bearing choices here keeps them from
- * drifting per package:
- *
- * - `resolve.conditions` / `ssr.resolve.conditions` pin the `development`
- * export condition EXPLICITLY. Vite's default condition follows NODE_ENV, so
- * `NODE_ENV=production` would silently resolve workspace deps to `dist/`
- * instead of `src/` — tests would then run against stale build output. The
- * SSR resolver is the operative one for inlined workspace symlinks; the
- * client-side `resolve.conditions` is set too for safety.
- * - `test.setupFiles` installs the `Bun` global facade and the hermetic-test
- * network guard (`no-net-connect.ts`) before any test runs.
- *
- * `import.meta.dir` (bun-only, no trailing slash) is rewritten at transform time
- * to the Node-equivalent directory expression. Node's own `import.meta.dirname`
- * is left untouched — it already resolves natively.
- */
import { availableParallelism } from 'node:os';
import { fileURLToPath } from 'node:url';
import { configDefaults, type Plugin, type ViteUserConfig } from 'vitest/config';
-// `pnpm check` fans every package's `test` script plus the app's dom/integration/
-// conversion/fidelity tiers through turbo at once — a dozen Vitest processes, each
-// with its own fork pool. On a workstation that oversubscribes every core and
-// starves the event loop of timing-sensitive suites (real CRDT servers, debounce/
-// convergence timers), which flake even though each tier is green in isolation.
-// Capping each pool's fork count lets the concurrent tiers share the box. CI runs
-// one tier per matrix job on a small runner, so the cap is a deliberate no-op
-// there (`CI` set, or few cores) — the per-tier matrix is the authoritative bar.
const cpuCount = availableParallelism();
const boundedMaxForks =
!process.env.CI && cpuCount >= 8 ? Math.max(1, Math.floor(cpuCount / 4)) : undefined;
-// Match `import.meta.dir` only when it is NOT the prefix of a longer property
-// (`import.meta.dirname` is native Node and must survive verbatim; a naive
-// substring replace would rewrite its `import.meta.dir` head and strand `name`).
const IMPORT_META_DIR = /import\.meta\.dir(?![\w$])/g;
export const importMetaDirPlugin: Plugin = {
name: 'ok-bun-import-meta-dir',
enforce: 'pre',
transform(code: string) {
- // Guard on the bare `import.meta` needle, not the full `.dir` form: this
- // module is self-hosting (a test that imports it runs it through this very
- // transform), and a `.dir`-literal guard would rewrite itself.
if (!code.includes('import.meta')) return null;
IMPORT_META_DIR.lastIndex = 0;
- // Rewrite to Node's NATIVE `import.meta.dirname`, not to a URL expression.
- //
- // The previous target — `new URL(".", import.meta.url).pathname.slice(0, -1)`
- // — is a URL PATHNAME, which is only accidentally a filesystem path, and only
- // on POSIX. On Windows it yields `/C:/repo/packages/server/src`: a leading
- // slash and forward separators. Passing that to `spawnSync({cwd})` fails
- // ENOENT, and any `path` operation against it silently produces nonsense.
- // Verified on a Windows 11 ARM64 VM: it is what made
- // `git-preflight-spawn.test.ts` report exit 0 instead of 78 (the subprocess
- // never launched).
- //
- // `import.meta.dirname` is native from Node 20.11 (this repo pins 24), is
- // already correct on every platform, and is exactly what the bun-only
- // `import.meta.dir` means. The regex deliberately does not match
- // `import.meta.dirname`, and `String.replace` never re-scans its own
- // output, so rewriting to that form cannot loop.
const out = code.replace(IMPORT_META_DIR, 'import.meta.dirname');
return out === code ? null : { code: out, map: null };
},
@@ -73,16 +23,6 @@ const bunGlobalShimPath = fileURLToPath(new URL('./bun-global-shim.ts', import.m
const noNetConnectPath = fileURLToPath(new URL('./no-net-connect.ts', import.meta.url));
-// A project's `setupFiles` must be the base array: either spread into a new one
-// (`[...okVitestBase.test.setupFiles, mine]`) or handed straight through. Not a
-// hand-listed array, not one entry picked out of the base, not a filtered copy —
-// each of those silently drops whichever guard the author left out, and the loss
-// is invisible because the tests still pass. The two paths above stay unexported
-// so the hand-rolled spelling is not reachable from outside this module, and
-// `setup-files-contract.test.ts` imports every vitest project's config and fails
-// any whose RESOLVED array omits an entry this base installs, so no spelling can
-// route around it.
-
export const okVitestBase = {
plugins: [importMetaDirPlugin],
resolve: {
@@ -98,17 +38,10 @@ export const okVitestBase = {
environment: 'node',
testTimeout: 30_000,
hookTimeout: 30_000,
- // The skills.sh install report honors the standard opt-out vars. Setting one
- // here means no test run — local or CI — can report an install it did not
- // make, and no suite depends on reaching a third-party host to pass. A test
- // that wants to exercise the reporter injects its own `fetchImpl` and
- // `env`, so this never hides the behavior under test.
env: { DO_NOT_TRACK: '1' },
setupFiles: [bunGlobalShimPath, noNetConnectPath],
include: ['**/*.test.ts?(x)'],
exclude: [...configDefaults.exclude, '**/*.spec.*', '**/*.e2e.*', '**/*.dom.test.ts?(x)'],
- // Vitest 4 flattened the pool sizing knobs to top-level `maxWorkers`/
- // `minWorkers` (the old `poolOptions.forks.maxForks` is a no-op here).
...(boundedMaxForks === undefined ? {} : { minWorkers: 1, maxWorkers: boundedMaxForks }),
},
} satisfies ViteUserConfig;