Agent-readable wiki

Pierre Monorepo — First 30 Minutes

Fast orientation to the Pierre monorepo: the open-source home of @pierre/diffs (precision virtualized code diffs) and @pierre/trees (high-performance file trees), their shared tooling, documentation site, and strict contributor workflows.

Pages

  1. Start HereThe Pierre monorepo hosts two production-grade open source UI libraries — @pierre/diffs for pixel-perfect, virtualized code diffs and @pierre/trees for high-performance file trees — plus the documentation site that showcases them. This page gives the 30-minute orientation: what matters, entry points to open first, vocabulary, and recommended first files.
  2. Local Development & ToolingEverything you run in the first 10 minutes: Bun workspaces with catalog dependency rules (never pin versions in package.json), worktree-based parallel development via scripts/wt.ts + scripts/run-dev.sh for port isolation, mandatory root-level lint/format/tsc, AGENT=1 for readable test output, and the scripts that prevent zombie ports and inconsistent state.
  3. @pierre/diffs — Precision Diff EngineThe core of diffs.com: a Shiki-backed diff renderer with lazy language/theme resolution, UniversalRenderingManager + InteractionManager + ScrollSyncManager + ResizeManager, DiffHunksRenderer and FileRenderer, full virtualization (VirtualizedFileDiff), both React and web-component entry points, and extensive unit tests that assert exact DOM and scroll behavior without broad snapshots.
  4. @pierre/trees & Path Store — Virtualized TreesThe engine behind trees.software: prepared input + density presets, FileTree renderer, and the sophisticated @pierre/path-store (PathStore + createVisibleTreeProjection) that handles async directory loading, visible-row projection, mutations, and cleanup for massive trees (AOSP, Linux) while keeping O(n) behavior. Includes React and web-component surfaces plus Playwright E2E only for true browser-only invariants.
  5. Documentation Site & Live ExamplesThe Next.js app (apps/docs) that serves the public faces of diffs.com and trees.software: route groups for multiple brands, MDX-driven documentation, live component previews, a build pipeline that rebuilds the three published packages on every dev start, llms.txt generation, and E2E tests that exercise the real rendered output. Also contains the small Vite demo app.
  6. After 30 Minutes — Next Reads & TasksYou now understand the monorepo shape, the two libraries, the contributor contract (bun only, catalog, root lint+format, worktree cleanup), and the performance invariants (no nested loops, pre-calculate before iteration). This page lists the exact next files and commands: run a package test, study visible-tree-projection or UniversalRenderingManager, add a small feature, and the living glossary of Pierre terms (catalog:, PIERRE_PORT_OFFSET, prepareFileTreeInput, DiffHunksRenderer, oxfmt, AGENT=1, visible projection, worktree).

Complete Markdown

# Pierre Monorepo — First 30 Minutes

> Fast orientation to the Pierre monorepo: the open-source home of @pierre/diffs (precision virtualized code diffs) and @pierre/trees (high-performance file trees), their shared tooling, documentation site, and strict contributor workflows.

## Context Links

- [Agent index](https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/llms.txt)
- [Human interactive wiki](https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845)
- [GitHub repository](https://github.com/pierrecomputer/pierre)

## Repository Metadata

- Repository: pierrecomputer/pierre

- Generated: 2026-05-21T01:19:41.873Z
- Updated: 2026-05-21T21:33:31.171Z
- Runtime: Grok CLI
- Format: First 30 Minutes
- Pages: 6

## Page Index

- 01. [Start Here](https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/01-start-here.md) - The Pierre monorepo hosts two production-grade open source UI libraries — @pierre/diffs for pixel-perfect, virtualized code diffs and @pierre/trees for high-performance file trees — plus the documentation site that showcases them. This page gives the 30-minute orientation: what matters, entry points to open first, vocabulary, and recommended first files.
- 02. [Local Development & Tooling](https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/02-local-development-tooling.md) - Everything you run in the first 10 minutes: Bun workspaces with catalog dependency rules (never pin versions in package.json), worktree-based parallel development via scripts/wt.ts + scripts/run-dev.sh for port isolation, mandatory root-level lint/format/tsc, AGENT=1 for readable test output, and the scripts that prevent zombie ports and inconsistent state.
- 03. [@pierre/diffs — Precision Diff Engine](https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/03-pierre-diffs-precision-diff-engine.md) - The core of diffs.com: a Shiki-backed diff renderer with lazy language/theme resolution, UniversalRenderingManager + InteractionManager + ScrollSyncManager + ResizeManager, DiffHunksRenderer and FileRenderer, full virtualization (VirtualizedFileDiff), both React and web-component entry points, and extensive unit tests that assert exact DOM and scroll behavior without broad snapshots.
- 04. [@pierre/trees & Path Store — Virtualized Trees](https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/04-pierre-trees-path-store-virtualized-trees.md) - The engine behind trees.software: prepared input + density presets, FileTree renderer, and the sophisticated @pierre/path-store (PathStore + createVisibleTreeProjection) that handles async directory loading, visible-row projection, mutations, and cleanup for massive trees (AOSP, Linux) while keeping O(n) behavior. Includes React and web-component surfaces plus Playwright E2E only for true browser-only invariants.
- 05. [Documentation Site & Live Examples](https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/05-documentation-site-live-examples.md) - The Next.js app (apps/docs) that serves the public faces of diffs.com and trees.software: route groups for multiple brands, MDX-driven documentation, live component previews, a build pipeline that rebuilds the three published packages on every dev start, llms.txt generation, and E2E tests that exercise the real rendered output. Also contains the small Vite demo app.
- 06. [After 30 Minutes — Next Reads & Tasks](https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/06-after-30-minutes-next-reads-tasks.md) - You now understand the monorepo shape, the two libraries, the contributor contract (bun only, catalog, root lint+format, worktree cleanup), and the performance invariants (no nested loops, pre-calculate before iteration). This page lists the exact next files and commands: run a package test, study visible-tree-projection or UniversalRenderingManager, add a small feature, and the living glossary of Pierre terms (catalog:, PIERRE_PORT_OFFSET, prepareFileTreeInput, DiffHunksRenderer, oxfmt, AGENT=1, visible projection, worktree).

## Source File Index

- `AGENTS.md`
- `apps/demo/src/main.ts`
- `apps/docs/app/(trees)/docs/Guides/GetStartedWithReact/content.mdx`
- `apps/docs/app/layout.tsx`
- `apps/docs/app/page.tsx`
- `apps/docs/lib/mdx.tsx`
- `apps/docs/package.json`
- `apps/docs/scripts/generate-llms-txt.ts`
- `bunfig.toml`
- `CLAUDE.md`
- `package.json`
- `packages/diffs/package.json`
- `packages/diffs/scripts/benchmarkParseMergeConflictDiffFromFile.ts`
- `packages/diffs/src/highlighter/shared_highlighter.ts`
- `packages/diffs/src/index.ts`
- `packages/diffs/src/managers/UniversalRenderingManager.ts`
- `packages/diffs/src/react/CodeView.tsx`
- `packages/diffs/src/renderers/DiffHunksRenderer.ts`
- `packages/diffs/test/CodeView.diffIndicators.test.ts`
- `packages/diffs/test/FileRenderer.test.ts`
- `packages/path-store/scripts/benchmark.ts`
- `packages/path-store/src/index.ts`
- `packages/path-store/src/store.ts`
- `packages/path-store/src/visible-tree-projection.ts`
- `packages/tree-test-data/index.js`
- `packages/trees/package.json`
- `packages/trees/src/index.ts`
- `packages/trees/src/model/virtualization.ts`
- `packages/trees/src/render/FileTree.ts`
- `packages/trees/test/rename-file-tree-paths.test.ts`
- `packages/trees/TESTING.md`
- `README`
- `scripts/run-dev.sh`
- `scripts/ws.ts`
- `scripts/wt.ts`
- `tsconfig.json`
- `tsconfig.options.json`

---

## 01. Start Here

> The Pierre monorepo hosts two production-grade open source UI libraries — @pierre/diffs for pixel-perfect, virtualized code diffs and @pierre/trees for high-performance file trees — plus the documentation site that showcases them. This page gives the 30-minute orientation: what matters, entry points to open first, vocabulary, and recommended first files.

- Page Markdown: https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/01-start-here.md
- Generated: 2026-05-21T01:16:50.330Z

### Source Files

- `README`
- `package.json`
- `AGENTS.md`
- `apps/docs/package.json`
- `scripts/wt.ts`

<details>
<summary>Relevant source files</summary>
The following files were used as context for generating this wiki page:
- [README](README)
- [package.json](package.json)
- [AGENTS.md](AGENTS.md)
- [apps/docs/package.json](apps/docs/package.json)
- [scripts/wt.ts](scripts/wt.ts)
- [packages/diffs/package.json](packages/diffs/package.json)
- [packages/diffs/README.md](packages/diffs/README.md)
- [packages/diffs/src/index.ts](packages/diffs/src/index.ts)
- [packages/diffs/src/components/Virtualizer.ts](packages/diffs/src/components/Virtualizer.ts)
- [packages/trees/package.json](packages/trees/package.json)
- [packages/trees/README.md](packages/trees/README.md)
- [tsconfig.json](tsconfig.json)
- [apps/docs/lib/product-config.ts](apps/docs/lib/product-config.ts)
</details>

# Start Here

This page orients anyone opening the `pierrecomputer/pierre` repository for the first time. In under 30 minutes you will know what the monorepo contains, which two published UI libraries are the reason it exists, how to run its code, and which files reward reading first. Everything else—internal packages, scripts, and the docs site—exists to support those two libraries and the documentation that showcases them.

The repository is a Bun-based TypeScript monorepo that ships `@pierre/diffs` (a Shiki-powered library for rendering code files and diffs) and `@pierre/trees` (a path-first, shadow-DOM file tree component). A single Next.js application in `apps/docs` serves the public documentation sites for both libraries plus an internal “diffshub” variant. Strict monorepo rules (catalog dependencies, root-only lint/format, worktree port isolation, project references) keep the published packages small and consistent.

## The Two Published Libraries

### @pierre/diffs
A production diff and code-file rendering library. It accepts raw patches, two versions of a file, or arbitrary text, then produces split or unified views with syntax highlighting, inline annotations, line selection, and accept/reject UI. Rendering is virtualized for large files; theming reuses Shiki themes (including CSS variable themes) and automatically follows light/dark.

Public entry points (from package.json):
- `@pierre/diffs` – core components and highlighter APIs
- `@pierre/diffs/react` – React wrappers
- `@pierre/diffs/ssr` – server-side rendering helpers
- `@pierre/diffs/worker` – off-main-thread diff computation

Key source modules include `VirtualizedFileDiff`, `Virtualizer`, `FileDiff`, `CodeView`, and the Shiki language/theme resolvers. The package depends on `diff`, `shiki`, and the internal `@pierre/theme` package.

Sources: [packages/diffs/package.json:20-50](), [packages/diffs/README.md:1-35](), [packages/diffs/src/index.ts:1-45](), [packages/diffs/src/components/Virtualizer.ts:1-15]()

### @pierre/trees
A high-performance file tree that stores all public state by canonical path strings rather than numeric IDs. The implementation lives in one place and is exposed through four entry points so the same model works in vanilla JS, React, SSR, and web components. The tree renders inside a shadow root, supports search, git status badges, custom icons, keyboard navigation, and context menus. Large trees use a prepared-input path that avoids re-sorting on every render.

Public entry points:
- `@pierre/trees` – `FileTree` model class and `prepare*Input` helpers
- `@pierre/trees/react` – `useFileTree`, `FileTree` component, selection/search hooks
- `@pierre/trees/ssr` – `preloadFileTree` for declarative shadow DOM
- `@pierre/trees/web-components` – side-effect registration

The tree depends on the internal `@pierre/path-store` workspace package for its efficient model. The package ships extensive benchmarks and Playwright E2E tests that specifically cover sticky-header drift and scroll performance.

Sources: [packages/trees/package.json:1-70](), [packages/trees/README.md:1-60]()

## Documentation and Demo Sites

`apps/docs` is a Next.js 16 application that builds the three published packages (`diffs`, `trees`, `truncate`) on every dev and prod build. It then serves three distinct sites from the same binary, switched by the `NEXT_PUBLIC_SITE` environment variable:

- `diffs` → diffs.com (or local :3690)
- `trees` → trees.software (or local :3691)
- `diffshub` → internal hub (or local :3692)

The site uses route groups `(diffs)`, `(trees)`, and `(diffshub)` plus a shared component library and MDX documentation. `apps/demo` exists for quick local Vite-based experiments (primarily path-store and tree visuals).

Sources: [apps/docs/package.json:5-35](), [apps/docs/lib/product-config.ts:1-30](), [apps/docs/app/layout.tsx:1-30]()

## Monorepo Layout and Entry Points

```
.
├── packages/
│   ├── diffs/          # published @pierre/diffs (tsdown → dist/)
│   ├── trees/          # published @pierre/trees (depends on path-store)
│   ├── truncate/       # small published utility, used by docs
│   ├── path-store/     # internal model for trees + benchmarks
│   └── ...
├── apps/
│   ├── docs/           # Next.js multi-site docs (builds the libs first)
│   └── demo/           # Vite playground
├── scripts/
│   ├── wt.ts           # worktree + port-offset manager
│   ├── ws.ts           # workspace script runner (“bun ws <pkg> <task>”)
│   └── run-dev.sh      # port-cleaner used by all dev scripts
├── package.json        # catalog + root scripts only
└── tsconfig.json       # project references to every package/app
```

All TypeScript projects answer to `bun run tsc`. The root `tsconfig.json` wires project references so editor and `tsgo` type-checking stay fast and accurate.

Sources: [tsconfig.json:1-15](), [package.json:3-20]()

## Development Workflow (AGENTS.md Rules)

You must follow these conventions; they are enforced by CI and by every maintainer.

- **Always use Bun.** Never `npm`, `pnpm`, or `npx` inside the repo.
- **Catalog dependencies only.** Add a version once in the root `package.json` under `workspaces.catalog`, then reference it as `"foo": "catalog:"` in any package. Never run `bun add` inside a package directory.
- **Lint and format from the root only.** `bun run lint`, `bun run format`, `bun run lint:css`. After any code change you are not done until these pass plus the relevant `bun run tsc`.
- **AGENT=1 for tests.** `export AGENT=1` before `bun test` so Bun’s runner emits AI-friendly output.
- **No O(n²) loops.** Calculate expensive values once before the loop; scan backwards when you only need the last interesting index.
- **Helper comments.** Every non-trivial function gets a one-sentence plain-English comment above its declaration explaining what data it transforms and why it exists.
- **Worktrees for parallel work.** `bun run wt new <slug>` creates an isolated checkout at `~/pierre/pierre-worktrees/<slug>` with its own port offset. All dev servers (3690/3691/4174/9222 etc.) are shifted so multiple agents or branches never collide. Always run `bun run wt clean` before you finish.

Sources: [AGENTS.md:1-30](), [AGENTS.md:80-120](), [scripts/wt.ts:1-60]()

## Most Useful Root Scripts

| Command                  | Purpose                                      |
|--------------------------|----------------------------------------------|
| `bun run wt new <slug>`  | Create isolated worktree + port offset       |
| `bun run wt clean`       | Kill stale processes on all managed ports    |
| `bun run lint && bun run format` | Required after any edit               |
| `bun run tsc`            | Type-check every package (uses tsgo)         |
| `bun ws <pkg> <task>`    | Run a script inside one workspace package    |
| `bun run docs:build`     | Build docs + all three published libs        |
| `bun run icons:sprite`   | Regenerate SVG sprite used by diffs          |

Sources: [package.json:60-85]()

## Recommended First 30-Minute Reading Order

1. [packages/diffs/README.md](packages/diffs/README.md) and [packages/trees/README.md](packages/trees/README.md) – the public contract and examples.
2. The `exports` block of each package’s `package.json` – exactly what consumers can import.
3. [AGENTS.md](AGENTS.md) (first 60 lines) – the non-negotiable rules.
4. [apps/docs/lib/product-config.ts](apps/docs/lib/product-config.ts) – how the same Next.js app becomes three different sites.
5. One source file from each library, e.g. `packages/diffs/src/components/Virtualizer.ts` and the `FileTree` constructor in trees, to see the performance focus in practice.
6. [scripts/wt.ts](scripts/wt.ts) header comments – why the worktree/port system exists.

After those six files you will understand the product, the constraints, and the exact commands you will type every day.

## Quick Vocabulary

- **catalog:** – Bun workspace dependency indirection defined once at the root.
- **preparedInput** – Trees optimization: pre-sort and pre-build the tree model once, then hand the result to `FileTree`.
- **Virtualizer / VirtualizedFileDiff** – Diffs windowing layer that only renders the visible scroll window.
- **port offset** – Integer added to every well-known port when you are inside a worktree so 3690, 9222, etc. never conflict.
- **tsgo** – The fast native TypeScript checker used by most `tsc` scripts.
- **shadow root** – Trees renders its DOM inside an open shadow root for style encapsulation.
- **ws / wt** – The two custom Bun scripts (`scripts/ws.ts`, `scripts/wt.ts`) that replace `npm --workspace` and `git worktree` ergonomics.

## Summary

The repository’s only public deliverables are two small, well-tested, Apache-2.0 UI libraries plus the documentation that proves they work. Everything else—worktree tooling, catalog discipline, root-only quality gates, and the multi-site docs build—is infrastructure that keeps those two packages reliable and pleasant to maintain. Read the two READMEs, the AGENTS rules, and the package.json exports blocks first; you will then know exactly where to look for any subsequent question.

Sources: [packages/trees/README.md:1-25](), [AGENTS.md:10-45](), [package.json:60-80]()

---

## 02. Local Development & Tooling

> Everything you run in the first 10 minutes: Bun workspaces with catalog dependency rules (never pin versions in package.json), worktree-based parallel development via scripts/wt.ts + scripts/run-dev.sh for port isolation, mandatory root-level lint/format/tsc, AGENT=1 for readable test output, and the scripts that prevent zombie ports and inconsistent state.

- Page Markdown: https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/02-local-development-tooling.md
- Generated: 2026-05-21T01:16:44.091Z

### Source Files

- `AGENTS.md`
- `package.json`
- `scripts/wt.ts`
- `scripts/ws.ts`
- `scripts/run-dev.sh`
- `tsconfig.json`
- `tsconfig.options.json`
- `bunfig.toml`

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [AGENTS.md](AGENTS.md)
- [package.json](package.json)
- [scripts/wt.ts](scripts/wt.ts)
- [scripts/ws.ts](scripts/ws.ts)
- [scripts/run-dev.sh](scripts/run-dev.sh)
- [tsconfig.json](tsconfig.json)
- [tsconfig.options.json](tsconfig.options.json)
- [bunfig.toml](bunfig.toml)
- [apps/docs/package.json](apps/docs/package.json)
- [packages/diffs/package.json](packages/diffs/package.json)
- [packages/trees/test/file-tree-profile-cli.test.ts](packages/trees/test/file-tree-profile-cli.test.ts)

</details>

# Local Development & Tooling

This page covers the commands and conventions you need in the first 10–30 minutes after cloning the pierre monorepo. It focuses on the Bun-based workspace setup, the catalog dependency rules that keep versions consistent, the worktree system for parallel development, port isolation to prevent conflicts, the scripts that clean up zombie processes, and the root-level quality gates that every change must pass.

The monorepo uses Bun exclusively for running commands, installing packages, and executing TypeScript without a separate build step. All local development flows through a small set of root scripts and two purpose-built helpers in `scripts/`.

## First Session Setup

Export the agent flag at the start of every terminal session. This tells Bun's test runner to produce plain, non-interactive output that is easy for humans and tools to read.

```bash
export AGENT=1
```

Run everything from the repository root. The root `package.json` defines the catalog and the convenience scripts; individual packages delegate to it via the workspace runner.

Sources: [AGENTS.md:5-10](), [package.json:100-119]()

## Dependency Management with Bun Catalog

The root `package.json` declares every shared dependency inside `workspaces.catalog`. Packages never contain hard-coded version numbers for catalog entries.

```json
// root package.json
"workspaces": {
  "packages": ["packages/*", "apps/*"],
  "catalog": {
    "react": "19.2.3",
    "typescript": "5.9.2",
    ...
  }
}
```

To add or update a dependency:

1. Add the exact version to the `catalog` object in the root `package.json`.
2. Reference it from any package with the string `"catalog:"`.

Never run `bun add <pkg>` inside a package directory; that writes a version pin directly into that package's `package.json` and breaks the single-source-of-truth rule. Published packages (`diffs`, etc.) may carry a few `^` ranges for end-user flexibility, but the catalog still supplies the development versions.

Bun's `bunfig.toml` adds a seven-day minimum release age for most packages (with explicit excludes for internal and `@types/*` packages) to reduce surprise upgrades.

Sources: [package.json:4-97](), [AGENTS.md:19-32](), [bunfig.toml:1-10](), [packages/diffs/package.json:64-70]()

## Workspace Script Runner (`bun ws`)

Typing `bun run` repeatedly inside each package is tedious. The `bun ws` command (implemented in `scripts/ws.ts`) lets you address any package by short name or path and forwards the requested script plus arguments.

```bash
bun ws diffs test
bun ws apps/docs build
bun ws '*' tsc          # every workspace that has a tsc script
bun ws 'packages/*' dev
```

`ws.ts` walks upward from the current directory, stops at the first `.git` marker (so it never leaks out of a worktree), loads any `.env.worktree` it finds, and injects those variables plus a correctly ordered `PATH` before spawning the target script. It also handles graceful shutdown, TTY restoration, and descendant process tracking so that Ctrl-C behaves reliably even when the child spawns further grandchildren.

Root-level commands such as `lint`, `format`, and `tsc` are thin wrappers around `ws`:

```json
"tsc": "bun run ws \"*\" tsc",
"lint": "oxlint --type-aware --tsconfig tsconfig.oxlint.json .",
```

Sources: [package.json:101-103](), [scripts/ws.ts:18-34](), [scripts/ws.ts:282-293](), [AGENTS.md:192-204]()

## Parallel Development with Git Worktrees

`bun run wt` (implemented in `scripts/wt.ts`) creates isolated git worktrees so you can have several independent checkouts running at once without branch-switching or stashing.

```bash
bun run wt new my-feature
bun run wt rm my-feature
bun run wt clean my-feature   # or --all
bun run wt ps                 # shows every worktree + live ports
bun run wt list
```

Each managed worktree is created under `~/pierre/pierre-worktrees/<slug>/` and receives a deterministic port offset (10, 20, 30, …) stored in `.env.worktree`:

```
PIERRE_WORKTREE_SLUG=my-feature
PIERRE_PORT_OFFSET=10
```

The main clone has offset 0 and keeps the historical default ports. `wt new` also runs `bun install` inside the new tree and prints the resulting port map.

`wt clean` (and `wt rm`) walk the process table with `lsof`, send SIGTERM, wait briefly, then SIGKILL any survivors on the ports that belong to that worktree (or all managed worktrees). This is the required cleanup step before an agent finishes its turn.

Sources: [scripts/wt.ts:30-40](), [scripts/wt.ts:143-166](), [scripts/wt.ts:257-282](), [scripts/wt.ts:442-469](), [AGENTS.md:38-68]()

## Port Isolation and Zombie Prevention

Dev servers and E2E fixtures bind fixed ports. Worktree offsets guarantee that no two live worktrees ever fight for the same port:

| Service     | Base port (offset 0) | Example with offset 10 |
|-------------|----------------------|------------------------|
| docs diffs  | 3690                 | 3700                   |
| docs trees  | 3691                 | 3701                   |
| docs E2E    | 4174                 | 4184                   |
| trees E2E   | 4173                 | 4183                   |
| chrome dev  | 9222                 | 9232                   |

Inside `apps/docs/package.json` the dev scripts compute the concrete port and then invoke the guard script:

```json
"diffs:dev": "export NEXT_PUBLIC_SITE=diffs PORT=$((${PIERRE_PORT_OFFSET:-0} + 3690)) && bash ../../scripts/run-dev.sh \"$PORT\" -- bun run _dev",
```

`scripts/run-dev.sh` does exactly one thing before `exec`ing the real command:

1. `lsof -ti :$PORT -sTCP:LISTEN` → SIGTERM any listeners.
2. Brief sleep.
3. SIGKILL any that remain.
4. `exec "$@"`

The same pattern appears in E2E server scripts and the Chrome remote-debug helper. Because the offset is injected by both `ws.ts` and the `.env.worktree` loader, even direct invocations outside the normal `bun ws` chain still receive the correct port.

Sources: [scripts/run-dev.sh:19-44](), [apps/docs/package.json:12-14](), [scripts/wt.ts:434-439](), [scripts/load-worktree-env.mjs:1-17]()

## Linting, Formatting, Type Checking

All three quality gates are run from the repository root after any code change:

```bash
bun run lint          # oxlint (type-aware via tsconfig.oxlint.json)
bun run lint:fix
bun run format        # oxfmt
bun run format:check
bun run tsc           # runs every package's tsc script via ws
```

`tsconfig.json` uses project references so that `tsc` (and the Go-based `tsgo` used by many packages) can type-check incrementally. Shared strict settings live in `tsconfig.options.json`.

The lint-staged configuration in the root `package.json` runs the same fixers on pre-commit.

Sources: [package.json:108-113](), [tsconfig.json:1-30](), [tsconfig.options.json:1-35](), [AGENTS.md:70-107]()

## Testing

Run tests from inside the package directory:

```bash
cd packages/diffs && bun test
cd packages/trees && bun test
```

With `AGENT=1` in the environment, Bun's test runner emits plain, line-oriented output instead of the interactive TTY UI. Several test suites also set the variable explicitly when spawning CLI child processes so that their `--help` and error output remain deterministic for assertions.

Sources: [AGENTS.md:5-10](), [packages/trees/test/file-tree-profile-cli.test.ts:11-15](), [AGENTS.md:226-241]()

## Command Cheat Sheet

| Task                        | Command                                      |
|-----------------------------|----------------------------------------------|
| Install / update deps       | `bun install` (from root)                    |
| Run a package script        | `bun ws <pkg> <script> [args...]`            |
| Create parallel checkout    | `bun run wt new <slug>`                      |
| Clean ports for one tree    | `bun run wt clean <slug>`                    |
| Clean all managed ports     | `bun run wt clean --all`                     |
| Lint / format / typecheck   | `bun run lint && bun run format && bun run tsc` |
| Run tests in a package      | `cd packages/<name> && bun test`             |
| Start a docs dev server     | `bun ws docs diffs:dev` (or trees:dev)       |

## Summary

The tooling exists to make the first ten minutes productive and the next ten hours free of port collisions, stale processes, and version drift. Always start with `export AGENT=1`, use the catalog for every new dependency, create worktrees with `wt new`, kill their ports with `wt clean` when you are finished, and run the three root quality commands after every edit. The implementation details live in the scripts and configuration files cited above; reading `AGENTS.md` and the top of `scripts/wt.ts` gives you the complete mental model.

Sources: [AGENTS.md:1-70](), [scripts/wt.ts:1-25]()

---

## 03. @pierre/diffs — Precision Diff Engine

> The core of diffs.com: a Shiki-backed diff renderer with lazy language/theme resolution, UniversalRenderingManager + InteractionManager + ScrollSyncManager + ResizeManager, DiffHunksRenderer and FileRenderer, full virtualization (VirtualizedFileDiff), both React and web-component entry points, and extensive unit tests that assert exact DOM and scroll behavior without broad snapshots.

- Page Markdown: https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/03-pierre-diffs-precision-diff-engine.md
- Generated: 2026-05-21T01:17:27.744Z

### Source Files

- `packages/diffs/package.json`
- `packages/diffs/src/index.ts`
- `packages/diffs/src/managers/UniversalRenderingManager.ts`
- `packages/diffs/src/renderers/DiffHunksRenderer.ts`
- `packages/diffs/src/highlighter/shared_highlighter.ts`
- `packages/diffs/src/react/CodeView.tsx`
- `packages/diffs/test/CodeView.diffIndicators.test.ts`
- `packages/diffs/test/FileRenderer.test.ts`

<details>
<summary>Relevant source files</summary>

The following files were used as context for generating this wiki page:

- [packages/diffs/package.json](packages/diffs/package.json)
- [packages/diffs/README.md](packages/diffs/README.md)
- [packages/diffs/src/index.ts](packages/diffs/src/index.ts)
- [packages/diffs/src/managers/UniversalRenderingManager.ts](packages/diffs/src/managers/UniversalRenderingManager.ts)
- [packages/diffs/src/managers/InteractionManager.ts](packages/diffs/src/managers/InteractionManager.ts)
- [packages/diffs/src/managers/ScrollSyncManager.ts](packages/diffs/src/managers/ScrollSyncManager.ts)
- [packages/diffs/src/managers/ResizeManager.ts](packages/diffs/src/managers/ResizeManager.ts)
- [packages/diffs/src/renderers/DiffHunksRenderer.ts](packages/diffs/src/renderers/DiffHunksRenderer.ts)
- [packages/diffs/src/renderers/FileRenderer.ts](packages/diffs/src/renderers/FileRenderer.ts)
- [packages/diffs/src/highlighter/shared_highlighter.ts](packages/diffs/src/highlighter/shared_highlighter.ts)
- [packages/diffs/src/components/CodeView.ts](packages/diffs/src/components/CodeView.ts)
- [packages/diffs/src/components/VirtualizedFileDiff.ts](packages/diffs/src/components/VirtualizedFileDiff.ts)
- [packages/diffs/src/components/web-components.ts](packages/diffs/src/components/web-components.ts)
- [packages/diffs/src/react/CodeView.tsx](packages/diffs/src/react/CodeView.tsx)
- [packages/diffs/src/react/index.ts](packages/diffs/src/react/index.ts)
- [packages/diffs/test/CodeView.diffIndicators.test.ts](packages/diffs/test/CodeView.diffIndicators.test.ts)
- [packages/diffs/test/FileRenderer.test.ts](packages/diffs/test/FileRenderer.test.ts)

</details>

# @pierre/diffs — Precision Diff Engine

`@pierre/diffs` is the core rendering engine behind diffs.com. It is a Shiki-backed library that produces exact, syntax-highlighted diff and file views with split/unified layouts, hunk expansion, line annotations, selection, smooth scrolling, and full virtualization. The package exports both React components and an imperative DOM API, plus SSR helpers and an optional Web Worker path for large inputs. Every major behavior—scroll anchoring, indicator toggles, column measurements—is covered by narrow, assertion-heavy tests that avoid broad snapshots.

The design keeps renderers pure (they emit HAST only) while four focused managers own DOM events, measurements, and cross-view coordination. Lazy language/theme resolution and a render queue keep first-paint fast and bundle size small.

## Package Shape and Entry Points

```json
// packages/diffs/package.json:1-55
{
  "name": "@pierre/diffs",
  "exports": {
    ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
    "./react": "...",
    "./ssr": "...",
    "./worker": "..."
  },
  "sideEffects": ["dist/components/web-components.js"]
}
```

`src/index.ts` re-exports the imperative core (`CodeView`, `VirtualizedFileDiff`, `DiffHunksRenderer`, managers, highlighter utilities) plus the Shiki `codeToHtml` and `createCSSVariablesTheme` helpers. The React surface lives under `./react`; SSR and worker entry points are separate to keep the main bundle lean.

Sources: [packages/diffs/package.json:30-55](), [packages/diffs/src/index.ts:6-112]()

## Rendering Pipeline

User items (a diff or a file) flow through this sequence:

1. `CodeView` (or `Virtualizer`) owns the scroll viewport and a list of `VirtualizedFileDiff` / `VirtualizedFile` instances.
2. Each virtualized item extends `FileDiff` / `File` and owns a `DiffHunksRenderer` or `FileRenderer`.
3. `hydrate()` seeds a render cache and may start a worker task or async highlighter load.
4. `renderDiff(range)` or `renderCodeAST(range)` returns a `HunksRenderResult` / `FileRenderResult` containing HAST arrays, pre node, theme CSS, row counts, and buffer sizes.
5. The virtualizer materializes only the visible window plus overscroll into pooled DOM elements.
6. The four managers attach listeners, measure columns/annotations, and keep split panes in sync.

When the highlighter or language is not yet ready, the renderer emits plain-text HAST first and schedules a follow-up highlight pass that later updates the cache and triggers a targeted re-render via the `onRenderUpdate` callback.

Sources: [packages/diffs/src/components/CodeView.ts:445-524](), [packages/diffs/src/components/VirtualizedFileDiff.ts:61-100](), [packages/diffs/src/renderers/DiffHunksRenderer.ts:395-573]()

## The Four Managers

| Manager                    | Responsibility                                                                 | Key Mechanism                          |
|----------------------------|--------------------------------------------------------------------------------|----------------------------------------|
| UniversalRenderingManager  | Global RAF batching queue for all view updates                                 | `queueRender` / `dequeueRender` set    |
| InteractionManager         | Pointer handling, hover, line/token selection, gutter utilities                | Per-<pre> listeners + slot elements    |
| ScrollSyncManager          | Keep deletions and additions columns in sync in split view                     | Passive scroll listeners + timeout guard |
| ResizeManager              | Measure line-number gutters, content columns, annotation heights               | Shared ResizeObserver, batched per-view updates |

`UniversalRenderingManager` is deliberately tiny (one rAF drain loop) so that many independent virtualized items do not each schedule their own frames.

```ts
// packages/diffs/src/managers/UniversalRenderingManager.ts:7-9
export function queueRender(callback: Callback): void {
  callbacks.add(callback);
  frameId ??= requestAnimationFrame(render);
}
```

Sources: [packages/diffs/src/managers/UniversalRenderingManager.ts:1-37](), [packages/diffs/src/managers/InteractionManager.ts:227-276](), [packages/diffs/src/managers/ScrollSyncManager.ts:27-85](), [packages/diffs/src/managers/ResizeManager.ts:18-60]()

## DiffHunksRenderer and FileRenderer

Both renderer classes follow an identical lifecycle:

- Constructor accepts options, an optional `onRenderUpdate` hook, and an optional `WorkerPoolManager`.
- `setLineAnnotations`, `expandHunk`, `setOptions` mutate internal state and invalidate caches only when necessary.
- `renderDiff` / `renderCodeAST` consult the cache, the worker result, or the current highlighter and return a complete render result (HAST + metrics + CSS).
- Protected hooks (`getUnifiedInjectedRowsForLine`, `getSplitInjectedRowsForLine`) let subclasses inject extra rows (annotations, accept/reject controls) without subclassing the entire AST builder.
- `cleanUp` / `recycle` release worker tasks and cached highlighter references.

The renderers never touch real DOM; they only produce HAST via `renderDiffWithHighlighter` / `renderFileWithHighlighter` and the small set of `create*Element` utilities.

Sources: [packages/diffs/src/renderers/DiffHunksRenderer.ts:202-573](), [packages/diffs/src/renderers/FileRenderer.ts:88-100]()

## Lazy Language and Theme Resolution

`shared_highlighter.ts` owns a module-level singleton. `getSharedHighlighter({ themes, langs, preferredHighlighter })` creates the Shiki instance once (JS regex engine by default) and then:

- For every requested language/theme, either reuses an already-resolved registration or queues a dynamic import.
- Awaits the loaders, attaches the results, and returns the ready instance.
- Four Pierre themes are pre-registered via `registerCustomTheme`.

Renderers call `getHighlighterIfLoaded()` for the synchronous fast path and fall back to plain text + an async `initializeHighlighter()` call when needed. This keeps initial JS small and only pays for languages that are actually rendered.

Sources: [packages/diffs/src/highlighter/shared_highlighter.ts:36-89](), [packages/diffs/src/highlighter/shared_highlighter.ts:116-149]()

## Virtualization and Scroll

`VirtualizedFileDiff` (and its file counterpart) add:

- A sparse height map and checkpoint array so deep scrolls do not re-walk the entire diff from line 0.
- `renderRange` + `expandedHunks` control exactly which subset the renderer materializes.
- `top` / `height` + visibility flags let the `Virtualizer` (IntersectionObserver + scroll listener) decide which items receive real DOM nodes.
- Pending scroll targets remain active across layout shifts caused by annotations or line wrapping; the next rAF recomputes the exact destination.

`CodeView` owns the scroll container, element pool, sticky header logic, and the smooth-scroll animation state machine.

Sources: [packages/diffs/src/components/VirtualizedFileDiff.ts:69-100](), [packages/diffs/src/components/CodeView.ts:478-510]()

## React versus Imperative / Web Component Usage

- **React** (`./react`): `CodeView`, `FileDiff`, `MultiFileDiff`, `PatchDiff`, `Virtualizer`. They create the imperative instances internally, forward refs, and use portals for custom header/annotation content. `WorkerPoolContext` lets many views share one worker pool.
- **Imperative**: `new CodeView(options)`, `.setup(container)`, `.setItems(...)`, `.render(true)`, `.scrollTo(...)`. This is the surface used by the web-component SSR path and by any non-React host.
- **Web Components**: A side-effect module registers `<diffs-container>` (a shadow host that adopts the library stylesheet). SSR output places prerendered HTML inside a declarative shadow root under this tag; client hydration reuses the same DOM.

Sources: [packages/diffs/src/react/CodeView.tsx:138-232](), [packages/diffs/src/components/web-components.ts:7-38](), [packages/diffs/src/react/index.ts:4-20]()

## Testing Approach

Tests run in JSDOM with mocked `requestAnimationFrame`, `ResizeObserver`, and `IntersectionObserver`. They exercise the imperative API directly and make precise assertions on attributes (`data-indicators`), scroll positions, node counts, and selection state.

`CodeView.diffIndicators.test.ts` is representative: it sets `diffIndicators`, waits for the `<pre>` to appear, asserts the attribute, changes the option, re-renders, and asserts the new attribute value—without any structural snapshot.

Snapshot tests are intentionally narrow (AST shapes from `FileRenderer`, parser outputs) while behavioral tests (scroll anchoring, range scroll, element pooling, pointer events) stay assertion-based. This protects the invariants that annotation layers and review UIs depend on.

Sources: [packages/diffs/test/CodeView.diffIndicators.test.ts:174-225](), [packages/diffs/test/FileRenderer.test.ts:11-17]()

## Summary

`@pierre/diffs` achieves precise, scalable diff rendering by keeping a clean separation between pure HAST production (renderers + lazy Shiki) and DOM lifecycle (virtualizer + four managers). The checkpointed layout, render-range pruning, and RAF queue let the engine handle files that would defeat simpler “render everything” approaches while still exposing an imperative handle for exact scroll and selection control. The test suite’s focus on narrow, repeatable DOM and scroll assertions gives consumers confidence that the surface they build on will not shift under them.

Sources: [packages/diffs/src/renderers/DiffHunksRenderer.ts:455-573]()

---

## 04. @pierre/trees & Path Store — Virtualized Trees

> The engine behind trees.software: prepared input + density presets, FileTree renderer, and the sophisticated @pierre/path-store (PathStore + createVisibleTreeProjection) that handles async directory loading, visible-row projection, mutations, and cleanup for massive trees (AOSP, Linux) while keeping O(n) behavior. Includes React and web-component surfaces plus Playwright E2E only for true browser-only invariants.

- Page Markdown: https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/04-pierre-trees-path-store-virtualized-trees.md
- Generated: 2026-05-21T01:19:41.871Z

### Source Files

- `packages/trees/package.json`
- `packages/trees/src/index.ts`
- `packages/trees/src/render/FileTree.ts`
- `packages/trees/src/model/virtualization.ts`
- `packages/path-store/src/index.ts`
- `packages/path-store/src/visible-tree-projection.ts`
- `packages/path-store/src/store.ts`
- `packages/tree-test-data/index.js`
- `packages/trees/test/rename-file-tree-paths.test.ts`

<details>
<summary>Relevant source files</summary>
The following files were used as context for generating this wiki page:
- [packages/trees/package.json](packages/trees/package.json)
- [packages/trees/src/index.ts](packages/trees/src/index.ts)
- [packages/trees/src/render/FileTree.ts](packages/trees/src/render/FileTree.ts)
- [packages/trees/src/model/virtualization.ts](packages/trees/src/model/virtualization.ts)
- [packages/trees/src/preparedInput.ts](packages/trees/src/preparedInput.ts)
- [packages/trees/src/model/FileTreeController.ts](packages/trees/src/model/FileTreeController.ts)
- [packages/path-store/src/index.ts](packages/path-store/src/index.ts)
- [packages/path-store/src/visible-tree-projection.ts](packages/path-store/src/visible-tree-projection.ts)
- [packages/path-store/src/store.ts](packages/path-store/src/store.ts)
- [packages/path-store/src/projection.ts](packages/path-store/src/projection.ts)
- [packages/path-store/package.json](packages/path-store/package.json)
- [packages/tree-test-data/index.js](packages/tree-test-data/index.js)
</details>

# @pierre/trees & Path Store — Virtualized Trees

The `@pierre/trees` and `@pierre/path-store` packages together power the high-performance file tree used by trees.software. They deliver a complete virtualized tree solution that ingests prepared path lists, applies density presets, renders rows via the `FileTree` component (and its React/web-component surfaces), and delegates the hard work of visible-row management, async directory loading, mutations, and cleanup to `PathStore` plus `createVisibleTreeProjection`.

The design targets massive trees—Linux kernel snapshots, AOSP-scale repositories, and 10× replicas—while preserving predictable O(n) behavior through single-pass DFS walks, typed-array bookkeeping, presorted fast paths, and chunked child-index sums. Unit and integration tests cover the model; Playwright E2E tests exist only for browser-only invariants such as sticky-scroll drift and shadow-DOM style isolation.

## Prepared Input and Density Presets

Callers avoid repeated parsing by supplying either raw paths or a precomputed `FileTreePreparedInput` (or `PathStorePreparedInput`). Two helpers exist:

```ts
// packages/trees/src/preparedInput.ts:15-30
export function prepareFileTreeInput(paths, options)
export function preparePresortedFileTreeInput(paths)
```

`preparePresortedFileTreeInput` marks input as already in canonical order, letting both the store and renderer skip sorting and duplicate detection. The store constructor detects this shape and takes the presorted fast path, including a specialized reverse post-order count walk that never re-visits the builder's work.

Density is expressed with presets or a numeric factor:

```ts
// packages/trees/src/model/density.ts:10-17
export const FILE_TREE_DENSITY_PRESETS = {
  compact: { itemHeight: 24, factor: 0.8 },
  default: { itemHeight: 30, factor: 1 },
  relaxed: { itemHeight: 36, factor: 1.2 },
};
```

`resolveFileTreeDensity` (and the exported `FILE_TREE_DEFAULT_ITEM_HEIGHT`) feed the virtualization layer so row height, overscan, and sticky-window math stay consistent between SSR and client hydration.

Sources: [packages/trees/src/preparedInput.ts:15-30](), [packages/trees/package.json:52-70]()

## FileTree Renderer and Virtualization Model

`FileTree` (the primary class) and its React counterpart accept `paths`, `preparedInput`, density, `initialExpansion`, `stickyFolders`, `overscan`, and a rich set of composition, drag-and-drop, search, and renaming options. Internally it owns a `FileTreeController` that wraps a `PathStore` instance and maintains a cached visible projection for focus, selection, and ARIA attributes.

The core virtualization primitives live in one small module:

```ts
// packages/trees/src/model/virtualization.ts:34-54
export function computeVisibleRange({ itemCount, itemHeight, scrollTop, viewportHeight })
export function computeWindowRange(metrics, currentRange)
export function computeStickyWindowLayout(...)
```

`computeWindowRange` expands the visible range by `overscan` (default 10) only when the current window does not already cover the viewport. `computeStickyWindowLayout` produces the CSS offsets and random inset that keep folder headers visually stable during fast scrolling without snapping to a grid.

The controller subscribes to store events and calls `#rebuildVisibleProjection`, which requests either a bounded slice (`INITIAL_PROJECTION_ROW_LIMIT`) or the full projection data depending on whether the caller needs the complete ARIA parent/posInSet/setSize tables.

Sources: [packages/trees/src/model/virtualization.ts:34-94](), [packages/trees/src/model/FileTreeController.ts:1947-1979]()

## Path Store — The Engine

`@pierre/path-store` is the private but fully public-API core (re-exported via trees). Its surface is intentionally small:

- `PathStore` (constructor + `add`/`remove`/`move`/`batch`)
- `getVisibleCount`, `getVisibleSlice(start, end)`, `getVisibleRowContext(index)`
- `getVisibleTreeProjection()`, `getVisibleTreeProjectionData(maxRows?)`
- `getVisibleIndex(path)`, `getPathInfo(path)`
- Async directory loading: `beginChildLoad`, `completeChildLoad`, `failChildLoad`, `markDirectoryUnloaded`
- `cleanup(options)`

Construction is heavily instrumented for benchmarks and chooses among several fast paths:

- presorted prepared input
- explicit “all directories open” initialization that skips the generic recompute walk
- detection of “every directory is already expanded” so visible counts can be written in one reverse-order pass

```ts
// packages/path-store/src/store.ts:234-341
export class PathStore {
  public constructor(options: PathStoreConstructorOptions = {})
  // chooses initializeOpenVisibleCounts or recomputeCountsRecursive
  // ...
}
```

The same class exposes the three child-load lifecycle methods that power on-demand expansion for trees too large to materialize entirely up front.

Sources: [packages/path-store/src/store.ts:234-341](), [packages/path-store/src/store.ts:604-786]()

## Visible Tree Projection

`createVisibleTreeProjection` (and the internal `buildVisibleTreeProjectionDataDFS`) turn a list of visible rows into the metadata React and web-component renderers need for `aria-posinset`/`aria-setsize` and parent-chain computation.

Implementation highlights:

- Uses `Int32Array` tables (`parentRowIndex`, `childCount`, `lastRowAtDepth`) instead of per-path Maps.
- Grows depth capacity by doubling; never allocates a row object per visible item when only the compact `PathStoreVisibleTreeProjectionData` form is requested.
- The `visibleIndexByPath` Map is built lazily on first access.
- Single DFS preorder walk over the visible subtree (bounded by `maxRows`) keeps cost linear in the number of rows actually rendered.

```ts
// packages/path-store/src/visible-tree-projection.ts:19-94
export function createVisibleTreeProjection(
  rows: readonly Pick<PathStoreVisibleRow, 'depth' | 'path'>[]
): PathStoreVisibleTreeProjection
```

The projection is deliberately decoupled from the store’s internal node IDs so that consumers can derive stable ARIA values without retaining the full canonical tree.

Sources: [packages/path-store/src/visible-tree-projection.ts:19-94](), [packages/path-store/src/projection.ts:740-790]()

## Async Directory Loading, Mutations, and Cleanup

Directories that are not yet expanded start with `loadState: 'unloaded'`. The host application calls:

1. `beginChildLoad(path)` → receives a `{ nodeId, attemptId }` token
2. performs its own I/O (network, FS, etc.)
3. `completeChildLoad(attempt)` or `failChildLoad(attempt, message)`

The store emits the corresponding `beginChildLoad` / `completeChildLoad` events, updates visible counts, and the controller rebuilds only the affected projection slice. `markDirectoryUnloaded` lets the host drop an entire subtree while preserving the placeholder row.

Mutations (`add`, `remove`, `move`, `batch`) record the visible count before and after, then emit a single coalesced event. The controller’s `#applyMutationState` walks the event to keep renaming state, focus, and search results consistent.

Cleanup (`cleanup({ mode: 'aggressive' | 'stable' })`) removes unreachable nodes and shrinks internal tables. It refuses to run while any directory load is in flight.

Sources: [packages/path-store/src/store.ts:823-849]()

## Rendering Surfaces

| Surface | Entry | Notes |
|---------|-------|-------|
| React | `export * from './react'` | `FileTree`, `useFileTree`, `useFileTreeSelection`, `useFileTreeSearch`, selector hooks |
| Web Components | `export * from './web-components'` | declarative shadow DOM, slot composition, custom element registration |
| SSR | `serializeFileTreeSsrPayload`, `preloadFileTree` | produces `outerStart` + `shadowHtml` + `outerEnd`; hydration re-uses the same controller |
| Vanilla / SSR consumers | `FileTree` class + `renderFileTreeRoot` | no React required |

All surfaces ultimately delegate to the identical `FileTreeController` + `PathStore` core, guaranteeing identical visible-row math and event ordering.

Sources: [packages/trees/src/index.ts:36-46](), [packages/trees/src/render/FileTree.ts:173-200]()

## Test Data and Massive-Tree Workloads

`@pierre/tree-test-data` supplies canonical Linux-kernel and Pierre-snapshot fixtures plus reproducible 5× and 10× replicas. Workloads expose both the raw file list and a presorted variant so benchmarks exercise the exact fast path used in production.

```js
// packages/tree-test-data/index.js:231-246
'linux-5x':  ... 5× replica
'linux-10x': ... 10× replica
```

Benchmarks in both packages (and the dedicated `benchmark:visible-tree-projection` script) measure cold-ingest, visible-slice, projection construction, and sticky-scroll window math against these data sets.

Sources: [packages/tree-test-data/index.js:180-246]()

## Testing Strategy

- Unit/integration tests (`bun test`) live beside each package and cover the model exhaustively (ingest, mutations, projection, async loading, cleanup, search, renaming).
- Playwright E2E is intentionally narrow and gated behind `@diagnostic` or explicit sticky-drift/style-isolation suites; the contract is that true browser-only behavior (layout, scroll anchoring, shadow-DOM isolation) is the only thing that justifies a real browser.

Sources: [packages/trees/package.json:61-65](), packages/trees/test/e2e/ (structure verified via listing)

## Summary

`@pierre/trees` + `@pierre/path-store` give you a drop-in virtualized tree that stays fast from a few dozen nodes to multi-million-node repositories by combining prepared-input fast paths, density-driven virtualization, a linear-cost visible projection, async child loading, and explicit cleanup. Start with the package `index.ts` files, then read `FileTreeController` and the store constructor to see how the layers compose. Every performance-sensitive path has been measured against the Linux-scale fixtures in `tree-test-data`.

Sources: [packages/path-store/src/store.ts:234-341](), [packages/trees/src/render/FileTree.ts:837-850]()

---

## 05. Documentation Site & Live Examples

> The Next.js app (apps/docs) that serves the public faces of diffs.com and trees.software: route groups for multiple brands, MDX-driven documentation, live component previews, a build pipeline that rebuilds the three published packages on every dev start, llms.txt generation, and E2E tests that exercise the real rendered output. Also contains the small Vite demo app.

- Page Markdown: https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/05-documentation-site-live-examples.md
- Generated: 2026-05-21T01:17:06.816Z

### Source Files

- `apps/docs/package.json`
- `apps/docs/app/layout.tsx`
- `apps/docs/app/page.tsx`
- `apps/docs/scripts/generate-llms-txt.ts`
- `apps/docs/lib/mdx.tsx`
- `apps/docs/app/(trees)/docs/Guides/GetStartedWithReact/content.mdx`
- `apps/demo/src/main.ts`

<details>
<summary>Relevant source files</summary>
The following files were used as context for generating this wiki page:

- [apps/docs/package.json](apps/docs/package.json)
- [apps/docs/app/layout.tsx](apps/docs/app/layout.tsx)
- [apps/docs/app/page.tsx](apps/docs/app/page.tsx)
- [apps/docs/scripts/generate-llms-txt.ts](apps/docs/scripts/generate-llms-txt.ts)
- [apps/docs/lib/mdx.tsx](apps/docs/lib/mdx.tsx)
- [apps/docs/app/(trees)/docs/Guides/GetStartedWithReact/content.mdx](apps/docs/app/(trees)/docs/Guides/GetStartedWithReact/content.mdx)
- [apps/demo/src/main.ts](apps/demo/src/main.ts)
- [apps/docs/lib/product-config.ts](apps/docs/lib/product-config.ts)
- [apps/docs/next.config.mjs](apps/docs/next.config.mjs)
- [apps/docs/components/docs/DocsCodeExample.tsx](apps/docs/components/docs/DocsCodeExample.tsx)
- [apps/docs/components/docs/DocsLayout.tsx](apps/docs/components/docs/DocsLayout.tsx)
- [apps/docs/test/e2e/playwright.config.ts](apps/docs/test/e2e/playwright.config.ts)
- [apps/docs/app/(trees)/_docs/DocsPage.tsx](apps/docs/app/(trees)/_docs/DocsPage.tsx)
- [apps/docs/app/docs/page.tsx](apps/docs/app/docs/page.tsx)
- [apps/docs/app/(trees)/docs/Guides/GetStartedWithReact/constants.ts](apps/docs/app/(trees)/docs/Guides/GetStartedWithReact/constants.ts)
- [apps/docs/components/docs/DocsSidebar.tsx](apps/docs/components/docs/DocsSidebar.tsx)
</details>

# Documentation Site & Live Examples

The `apps/docs` Next.js application is the public delivery layer for the three Pierre product sites: diffs.com, trees.software, and the diffshub.com microsite. It uses build-time environment selection (`NEXT_PUBLIC_SITE`) and Next.js route groups to serve completely separate branded experiences from a single codebase while sharing documentation infrastructure, component libraries, and the published packages themselves.

Documentation is authored in MDX, rendered server-side, and enhanced with live, interactive previews of the actual `@pierre/diffs` and `@pierre/trees` components. A dedicated build step ensures the three published packages are always rebuilt from source before the docs server starts. The same pipeline also emits `llms.txt` and `llms-full.txt` files for AI consumption. End-to-end Playwright tests run against the fully built production output.

A small companion Vite application (`apps/demo`) demonstrates the packages in a minimal vanilla + React context outside the docs site.

## Multi-Brand Routing Architecture

Route groups under `app/(diffs)`, `app/(trees)`, and `app/(diffshub)` isolate brand-specific pages, layouts, and assets. The root `app/page.tsx` and `app/docs/page.tsx` act as static dispatchers:

```tsx
// apps/docs/app/page.tsx:10-13
const SITE = process.env.NEXT_PUBLIC_SITE;
const Page = SITE === 'trees' ? TreesHome : SITE === 'diffshub' ? DiffshubHome : DiffsHome;
export default Page;
```

`app/layout.tsx` reads the same variable to select per-site metadata, favicons, Open Graph images, viewport behavior, and theme bootstrap. Worktree-aware title prefixes are injected for parallel development.

Redirects in `next.config.mjs` keep legacy paths working while pointing cross-product traffic to the correct domain.

**Sources:** [apps/docs/app/page.tsx:1-14](), [apps/docs/app/layout.tsx:45-140](), [apps/docs/app/docs/page.tsx:1-20](), [apps/docs/next.config.mjs:60-95]()

## MDX-Driven Documentation Content

Each documentation section lives in a folder containing `content.mdx` and an optional `constants.ts`. The `renderMDX` and `renderMDXWithPreloadedFiles` helpers in `lib/mdx.tsx` compile the MDX at request time inside React Server Components.

```tsx
// apps/docs/lib/mdx.tsx:45-70
export async function renderMDX({ filePath, scope = {} }: RenderMDXOptions) {
  const fullPath = join(process.cwd(), 'app', filePath);
  const source = await readFile(fullPath, 'utf-8');
  const { content } = await compileMDX({ source, components: defaultComponents, ... });
  return content;
}
```

Remark and rehype plugins add GitHub-flavored markdown, table-of-contents slugging, and `[toc-ignore]` support. Custom components (`Notice`, `DocsCodeExample`, tab switchers, live `<MultiFileDiff>` instances, etc.) are registered once and available in every MDX file.

Trees documentation contains 18 sections; diffs documentation contains 14 sections. Both are organized under `Guides/` and `Reference/` with consistent front-matter-free heading extraction used for navigation and llms.txt anchors.

**Sources:** [apps/docs/lib/mdx.tsx:1-95](), [apps/docs/app/(trees)/docs/Guides/GetStartedWithReact/content.mdx:1-70](), [apps/docs/app/(trees)/_docs/DocsPage.tsx:20-80]()

## Live Component Previews

The `DocsCodeExample` component renders real instances of the published packages directly inside the documentation:

```tsx
// apps/docs/components/docs/DocsCodeExample.tsx:20-35
export function DocsCodeExample<LAnnotation = undefined>(props: DocsCodeExampleProps<LAnnotation>) {
  return (
    <File {...rest} className="..." renderHeaderMetadata={(file) => (...)} />
  );
}
```

Authors export `PreloadFileOptions` objects (or tree equivalents) from a sibling `constants.ts`. `renderMDXWithPreloadedFiles` calls `preloadFile` (from `@pierre/diffs/ssr`) in parallel at build/render time and injects the results into MDX scope so the live component receives pre-highlighted, production-grade data.

This pattern guarantees that every code sample shown to readers is also a working, interactive demo of the exact code the reader will copy.

**Sources:** [apps/docs/components/docs/DocsCodeExample.tsx:1-45](), [apps/docs/app/(trees)/docs/Guides/GetStartedWithReact/constants.ts:1-30](), [apps/docs/lib/mdx.tsx:75-95]()

## Package Rebuild Pipeline

The docs `package.json` scripts guarantee fresh builds of the workspace packages on every developer start:

```json
// apps/docs/package.json:6-20
"build:deps": "bun run build:deps:diffs && bun run build:deps:truncate && bun run build:deps:tree",
"build:deps:diffs": "output=$(cd ../../packages/diffs && bun run build 2>&1) ...",
"_dev": "bun run build:deps && bun concurrently \"bun run dev:deps:diffs\" ... \"bun run dev:next\" ..."
```

`diffs:dev`, `trees:dev`, and `diffshub:dev` each set `NEXT_PUBLIC_SITE` and a port offset, then invoke the shared `_dev` target. The same `build:deps` step runs before `next build`, before E2E tests, and before the Vite demo. This eliminates the class of "stale package" bugs that would otherwise appear when editing the core libraries while viewing their documentation.

**Sources:** [apps/docs/package.json:1-45](), [apps/demo/package.json:8-15]()

## llms.txt Generation

`scripts/generate-llms-txt.ts` runs as part of the production build. It:

1. Reads every `content.mdx` for the active product (`diffs` or `trees`).
2. Strips JSX and converts `<Notice>` elements to blockquotes.
3. Auto-discovers code examples from exported constants in sibling `constants.ts` files.
4. Assembles a compact `llms.txt` (section index) and a full `llms-full.txt` (entire prose + examples).

Output always lands at `public/llms.txt` and `public/llms-full.txt` so the files are served at the root of whichever domain the current build targets. Diffshub builds skip generation cleanly.

**Sources:** [apps/docs/scripts/generate-llms-txt.ts:140-200](), [apps/docs/scripts/generate-llms-txt.ts:260-320](), [apps/docs/package.json:8]()

## E2E Tests That Exercise Real Rendered Output

Playwright configuration (`test/e2e/playwright.config.ts`) starts the production server (`bun run start`) after a full `build:deps && build:next`. Tests run in a real browser against the exact HTML, CSS, and JavaScript that end users receive. Current coverage focuses on high-risk interactive surfaces (context menus, drag-and-drop, item customization) inside the trees development playground.

The web server command and port-offset handling mirror the worktree-aware dev scripts, so tests remain stable across parallel worktrees.

**Sources:** [apps/docs/test/e2e/playwright.config.ts:1-45](), [apps/docs/package.json:30-35]()

## The Small Vite Demo App

`apps/demo` is a minimal Vite + React application that consumes `@pierre/diffs` (and transitively the other packages) directly. Its `main.ts` wires up `File`, `FileDiff`, `VirtualizedFileDiff`, `FileStream`, worker pools, and annotation renderers with the same patterns used in the docs examples and the diffshub microsite.

It serves as both a manual testing surface for the packages and a living reference for consumers who prefer a non-Next.js environment. Like the docs app, it runs `build:deps` before Vite starts.

**Sources:** [apps/demo/src/main.ts:1-50](), [apps/demo/package.json:1-25](), [apps/demo/vite.config.ts]()

## Summary

`apps/docs` is not a passive documentation host. It is an active integration surface that forces the published packages to stay buildable, renders them live inside their own reference material, emits AI-friendly text artifacts, and validates the final output with browser tests. The combination of route-group isolation, MDX + preload scope, the `build:deps` contract, and the `DocsCodeExample` pattern gives contributors a single place to author, demonstrate, and ship changes across all public Pierre products.

**Sources:** [apps/docs/package.json:6-45](), [apps/docs/lib/mdx.tsx:75-95](), [apps/docs/scripts/generate-llms-txt.ts:1-50]()

---

## 06. After 30 Minutes — Next Reads & Tasks

> You now understand the monorepo shape, the two libraries, the contributor contract (bun only, catalog, root lint+format, worktree cleanup), and the performance invariants (no nested loops, pre-calculate before iteration). This page lists the exact next files and commands: run a package test, study visible-tree-projection or UniversalRenderingManager, add a small feature, and the living glossary of Pierre terms (catalog:, PIERRE_PORT_OFFSET, prepareFileTreeInput, DiffHunksRenderer, oxfmt, AGENT=1, visible projection, worktree).

- Page Markdown: https://grok-wiki.com/public/wiki/pierrecomputer-pierre-fac2c554b845/pages/06-after-30-minutes-next-reads-tasks.md
- Generated: 2026-05-21T01:16:57.092Z

### Source Files

- `AGENTS.md`
- `packages/diffs/src/managers/UniversalRenderingManager.ts`
- `packages/path-store/src/visible-tree-projection.ts`
- `packages/trees/TESTING.md`
- `packages/diffs/scripts/benchmarkParseMergeConflictDiffFromFile.ts`
- `packages/path-store/scripts/benchmark.ts`
- `CLAUDE.md`

<details>
<summary>Relevant source files</summary>
The following files were used as context for generating this wiki page:
- [AGENTS.md](AGENTS.md)
- [CLAUDE.md](CLAUDE.md)
- [packages/diffs/src/managers/UniversalRenderingManager.ts](packages/diffs/src/managers/UniversalRenderingManager.ts)
- [packages/path-store/src/visible-tree-projection.ts](packages/path-store/src/visible-tree-projection.ts)
- [packages/trees/test/TESTING.md](packages/trees/test/TESTING.md)
- [packages/diffs/scripts/benchmarkParseMergeConflictDiffFromFile.ts](packages/diffs/scripts/benchmarkParseMergeConflictDiffFromFile.ts)
- [packages/path-store/scripts/benchmark.ts](packages/path-store/scripts/benchmark.ts)
- [package.json](package.json)
- [packages/trees/src/preparedInput.ts](packages/trees/src/preparedInput.ts)
- [packages/diffs/src/renderers/DiffHunksRenderer.ts](packages/diffs/src/renderers/DiffHunksRenderer.ts)
- [scripts/wt.ts](scripts/wt.ts)
- [packages/diffs/src/index.ts](packages/diffs/src/index.ts)
- [packages/trees/src/index.ts](packages/trees/src/index.ts)
- [packages/path-store/src/index.ts](packages/path-store/src/index.ts)
</details>

# After 30 Minutes — Next Reads & Tasks

After your first 30 minutes in the pierrecomputer/pierre monorepo, you have seen the high-level shape: a Bun-based TypeScript monorepo with two primary libraries (`diffs` for rich diff rendering and `trees`/`path-store` for high-performance file tree state and UI), plus supporting packages (`truncate`, `storage-elements`, test data). You have internalized the contributor contract from the agent instructions and the performance culture that keeps hot paths fast.

This page gives you the exact next files, commands, and a living glossary so you can move from orientation to useful work without violating invariants (bun-only, catalog dependencies, root-only lint/format, worktree cleanup, no nested loops).

## The Two Libraries at a Glance

- **diffs** (`packages/diffs`): Renders diffs as virtualized HAST trees with syntax highlighting (Shiki), hunk expansion, annotations, and split/unified views. Key export: `DiffHunksRenderer`.
- **trees + path-store** (`packages/trees`, `packages/path-store`): `PathStore` + `prepareFileTreeInput` feed a virtualized file tree; `createVisibleTreeProjection` builds ARIA-aware sibling metadata using typed arrays instead of maps.

Everything else (apps, scripts, test fixtures) exists to exercise these two libraries under realistic Git-scale loads.

Sources: [packages/diffs/src/index.ts:1-50](), [packages/trees/src/index.ts:1-30](), [packages/path-store/src/index.ts:1-30]()

## Recommended Next Reads (Study These Immediately)

### 1. `packages/path-store/src/visible-tree-projection.ts`
The clearest example of the performance contract in action. It builds a preorder projection of visible rows using `Int32Array` for parent indices, child counts, and last-row-at-depth tracking, then lazily materializes the `visibleIndexByPath` map only when needed.

```ts
// Calculate once upfront, typed arrays, no per-iteration Maps
const parentRowIndex = new Int32Array(rowCount);
// ...
lastRowAtDepth = ensureDepthCapacity(lastRowAtDepth, depth);
```

Read the whole 115-line file. Then look at its callers in `projection.ts` and the benchmark in `packages/path-store/scripts/benchmarkVisibleTreeProjection.ts`.

Sources: [packages/path-store/src/visible-tree-projection.ts:19-115](), [packages/path-store/src/visible-tree-projection.ts:27-43]()

### 2. `packages/diffs/src/managers/UniversalRenderingManager.ts`
A tiny (37-line) rAF batching utility with a self-deprecating TODO. It is the shared render scheduler used by diff components to coalesce updates. Even though small, it demonstrates the "universal" rendering concerns that cross the virtualized components.

Sources: [packages/diffs/src/managers/UniversalRenderingManager.ts:1-37]()

### 3. The benchmark scripts
- `packages/diffs/scripts/benchmarkParseMergeConflictDiffFromFile.ts` (340 lines) — shows how the diffs team measures parse + render cost across `maxContextLines` cases.
- `packages/path-store/scripts/benchmark.ts` (thousands of lines of workloads) — the canonical place to see what "fast for real Git repos" means.

Running or reading these tells you where the team actually spends profiling time.

Sources: [packages/diffs/scripts/benchmarkParseMergeConflictDiffFromFile.ts:29-60]()

### 4. Test strategy documents
- [packages/trees/test/TESTING.md](packages/trees/test/TESTING.md) (and the matching section in AGENTS.md) — explicit rules: unit first, Playwright only for computed styles / shadow DOM / CSS custom properties, no broad snapshots.

Sources: [packages/trees/test/TESTING.md:1-46](), [AGENTS.md:206-258]()

## Run a Real Package Test (Do This Now)

```bash
export AGENT=1
# From repo root (preferred)
bun ws diffs test
# Or inside the package
cd packages/diffs && bun test
```

For the tree package (includes E2E):
```bash
bun ws trees test
bun ws trees test:e2e   # builds dist, installs Chromium if needed, runs Playwright
```

Always run from the package directory or via `bun ws` when the task is package-scoped. After any code change you must also run (from root):
```bash
bun run format
bun run lint
bun run tsc   # or the package's bun run tsc
```

Sources: [AGENTS.md:8-10](), [AGENTS.md:226-241](), [packages/trees/test/TESTING.md:36-39]()

## Add a Small Feature — Minimal Contract-Compliant Path

1. Pick a leaf: a new option on `DiffHunksRenderer`, a tiny helper in `path-store`, or a missing icon preset in `trees`.
2. Implement the helper with a one-line comment above it explaining what data it transforms and why (see AGENTS readability rules).
3. Add or extend a unit test (never a broad snapshot).
4. From the package dir: `bun test`.
5. From repo root: `bun run format && bun run lint && bun run tsc`.
6. If you touched anything that starts a dev server or browser fixture, run `bun run wt clean` (or `bun run wt clean <slug>`) before you finish.
7. If you added a dependency: first edit root `package.json` `workspaces.catalog`, then reference it as `"catalog:"` in the package `package.json`. Never `bun add` inside a package.

Sources: [AGENTS.md:131-188](), [AGENTS.md:62-68]()

## Living Glossary of Pierre Terms

| Term                    | Meaning & Where It Lives                                                                 | Why It Matters |
|-------------------------|------------------------------------------------------------------------------------------|--------------|
| `catalog:`              | Dependency reference in every sub `package.json` (root `workspaces.catalog` holds the real version). Never put a version number in a package's own file. | Eliminates drift across 8+ packages. |
| `PIERRE_PORT_OFFSET`    | Integer written by `scripts/wt.ts` into each worktree's `.env.worktree`; read by `ws.ts`, Playwright config, and dev scripts. | Prevents port collisions when multiple agents run dev servers or Chrome debuggers in parallel worktrees. |
| `prepareFileTreeInput`  | `packages/trees/src/preparedInput.ts:15` — thin wrapper around `PathStore.prepareInput` that returns an opaque `FileTreePreparedInput` token. | Guarantees the expensive normalization/sort work has already happened before the tree component sees the data. |
| `DiffHunksRenderer`     | `packages/diffs/src/renderers/DiffHunksRenderer.ts` (exported from `diffs/index.ts`). Class that turns hunk data into themed HAST rows for virtualized rendering. | The single place that knows split vs unified, annotation injection, and Shiki tokenization. |
| `oxfmt`                 | Root formatter invoked via `bun run format` / `bun run format:check`. | One canonical style for the whole monorepo; must be run from root after every edit. |
| `AGENT=1`               | Environment variable that makes Bun's test runner emit AI-friendly, non-interactive output. | Required at the top of any terminal session before `bun test`. |
| Visible projection      | `createVisibleTreeProjection` in `path-store/src/visible-tree-projection.ts`. Returns `{ rows, getParentIndex, visibleIndexByPath }` built with `Int32Array`s and a lazy Map. | Powers ARIA sibling calculations and expansion state without O(n) path reparsing on every render. |
| Worktree                | Git worktree managed by `bun run wt new <slug>` (creates `~/pierre/pierre-worktrees/<slug>/` + offset). Scripts: `wt rm`, `wt clean`, `wt ps`. | The official way to run multiple isolated dev environments; agents must clean up ports on exit. |

Sources: [package.json:workspaces.catalog](), [scripts/wt.ts:164-373](), [packages/trees/src/preparedInput.ts:15-32](), [packages/diffs/src/renderers/DiffHunksRenderer.ts:1-30](), [AGENTS.md:5-10](), [AGENTS.md:38-68](), [packages/path-store/src/visible-tree-projection.ts:19-50]()

## Quick Command Cheat Sheet

```bash
export AGENT=1
bun run lint && bun run format          # after any edit (from root)
bun ws <pkg> test                       # diffs, trees, truncate, ...
bun ws trees test:e2e                   # Playwright only when jsdom is insufficient
bun run wt clean                        # before you log off or switch worktrees
bun run tsc                             # typecheck everything via project references
```

## Closing Summary

The monorepo's power comes from ruthless consistency: one package manager, one linter/formatter invocation point, one dependency catalog, typed-array projections instead of nested loops, and an explicit cleanup contract for parallel work. Read the two projection and renderer files, run one package's test suite under `AGENT=1`, and you will be ready to make a contract-compliant contribution on your next turn.

Sources: [AGENTS.md:145-188]()

---