Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands.
TypeScript
Add mods: sec-default, diff and telemetry, the hooks-module plugins built into Claude Code
poteatd9c456d7dba7
diff --git a/mods/README.md b/mods/README.mdnew file mode 100644index 00000000..d2851034--- /dev/null+++ b/mods/README.md@@ -0,0 +1,24 @@+# Mods++A mod is a Claude Code plugin whose behaviour lives in a hooks module: one+`register(on, options)` entry that hooks the engine's events as functions+`($, e, next)`. These three ship inside Claude Code; this folder is their+source, published as it is built into the binary.++| Mod | What it does | Seated |+| --- | --- | --- |+| [`sec-default`](sec-default) | Keeps an organization's classic hooks, prompt content, managed settings and tool policy out of reach of the plugins a person installs; adds no policy of its own. | Outermost, on a machine with managed settings or for a Team or Enterprise organization, unless managed `prependPlugins` says otherwise |+| [`diff`](diff) | `/diff`: the session's uncommitted changes in a pane beside the transcript, file by file with their hunks, refreshed as Claude edits files and runs commands. | Built in |+| [`telemetry`](telemetry) | Adds `$.telemetry` (`log`, `mark`) in the `engine.create` fold so a plugin can record an event as a first-party analytics row; sends nothing wherever Claude Code's analytics are off. | Built in |++Each folder is a complete plugin: `.claude-plugin/plugin.json`, a+`hooks/hooks.json` naming the module, and TypeScript under `hooks/` typed+against the declarations `/plugin-types` writes (`import type … from+'claude-code'`). To read one running from source:++ claude --plugin-dir mods/diff++Early access: hooks modules load only where function hooks are enabled, and+the API these mods are written against may change between releases without+notice. They are not listed in this repository's marketplace; the copies that+matter are the ones already in your Claude Code.diff --git a/mods/diff/.claude-plugin/plugin.json b/mods/diff/.claude-plugin/plugin.jsonnew file mode 100644index 00000000..6ccd5832--- /dev/null+++ b/mods/diff/.claude-plugin/plugin.json@@ -0,0 +1,8 @@+{+ "name": "diff",+ "version": "0.1.0",+ "description": "The diff pane as a plugin: /diff opens the session's uncommitted changes beside the transcript, file by file with their hunks, refreshed as Claude edits and runs commands; the first edit opens it where the terminal is wide enough, and a file's ask button rides its hunks on the next prompt.",+ "author": {+ "name": "Anthropic"+ }+}diff --git a/mods/diff/README.md b/mods/diff/README.mdnew file mode 100644index 00000000..37b6e8d7--- /dev/null+++ b/mods/diff/README.md@@ -0,0 +1,54 @@+# diff++The diff pane as a plugin: `/diff` opens the session's uncommitted changes+beside the transcript, one row per changed file and the selected file's+hunks beneath, and closes it again. The pane refreshes as Claude edits,+runs shell commands and finishes turns, and while it is open it polls the+repository's HEAD so a commit or checkout made elsewhere shows too. The+first successful edit of a session opens the pane by itself where the+terminal is wide enough (144 columns when the person never chose, 110 when+they kept it open before; a person who closed it is left alone). A file's+ask button arms that file: its hunks ride the next prompt as context, once.++The pane compares the working tree against HEAD, split at the session's+start (the default), against HEAD plainly, or against the merge-base with+the default branch; the choice is kept per repository in the plugin's+store. A second picker shows one earlier turn's edits instead of the+working tree, read from the session's messages. Files that changed before+the session started, and noise (lockfiles, generated and test files), are+listed apart and folded until asked for. Outside a git repository `/diff`+says so and does nothing else.++`hooks/register.ts` is the module; everything under `hooks/` is its parts.++## What it hooks++| event | what the hook does |+| --- | --- |+| `session.start` | Binds the engine once, registers `/diff` (a session where another `/diff` is listed leaves the plugin idle), and pins the repository. |+| `ui.render` of `PromptHint` | Reads the terminal's width, which decides whether the first edit opens the pane. |+| `ui.render` of `Pane` | Draws the pane: header, the file list, the toggles, the base and source pickers, and the selected file's hunks. |+| `command.run` of `diff` | Opens or closes the pane and remembers the choice. |+| `command.run` of `clear`, `resume` | Closes the pane and forgets the session's state. |+| `tool.call` of `Edit`, `Write`, `NotebookEdit` | After the edit, refreshes an open pane; the session's first successful edit opens it. |+| `tool.call` of `Bash`, `PowerShell` | After the command, refreshes an open pane. |+| `turn.complete` | Refreshes an open pane. |+| `prompt.submit` | Adds the armed file's hunks to the prompt's context and disarms. |++## What it calls on `$`++`clock.after`, `clock.every`, `clock.now`, `clock.sleep`, `command.register`,+`fs.list`, `fs.read`, `fs.stat`, `process.run` (git, read-only), `session.messages`,+`store.get`, `store.set`, `telemetry.log`, `telemetry.mark`, `ui.close`,+`ui.invalidate`, `ui.log`, `ui.open`, `ui.resolve`, `ui.status`.++`$.telemetry` is the telemetry plugin's noun; where it is absent the rows+are dropped and nothing else changes.++## Try it++```sh+claude --plugin-dir /path/to/diff+```++then `/diff` inside a git repository with a modified file.diff --git a/mods/diff/hooks/array-of/array-of.ts b/mods/diff/hooks/array-of/array-of.tsnew file mode 100644index 00000000..f92993a4--- /dev/null+++ b/mods/diff/hooks/array-of/array-of.ts@@ -0,0 +1,9 @@+/**+ * A value a tool stored as the array it is, or an empty one when it is+ * anything else.+ *+ * @param value a field of a tool's input or result+ * @returns the array's items, unknown each+ */+export const arrayOf = (value: unknown): readonly unknown[] =>+ Array.isArray(value) ? value : []diff --git a/mods/diff/hooks/array-of/index.ts b/mods/diff/hooks/array-of/index.tsnew file mode 100644index 00000000..0ccf2dc5--- /dev/null+++ b/mods/diff/hooks/array-of/index.ts@@ -0,0 +1,3 @@+export * from './array-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/ask/armed-ask-of.ts b/mods/diff/hooks/ask/armed-ask-of.tsnew file mode 100644index 00000000..d0a64d84--- /dev/null+++ b/mods/diff/hooks/ask/armed-ask-of.ts@@ -0,0 +1,31 @@+import type Git from '../git'+import Limits from '../limits'+import type { ArmedAsk } from './armed-ask'++/**+ * A file's diff as the context block the next prompt carries when the+ * person presses ask.+ *+ * A line saying where it came from, then the hunks in unified form, cut at+ * MAX_LINES_PER_FILE lines.+ *+ * @param path the file's repository-relative path+ * @param hunks its hunks as the pane shows them+ * @returns the armed ask+ */+export function armedAskOf(path: string, hunks: readonly Git.Hunk[]): ArmedAsk {+ const body = hunks+ .flatMap(hunk => [+ `@@ -${hunk.oldStart} +${hunk.newStart} @@`,+ ...hunk.lines,+ ])+ .slice(0, Limits.MAX_LINES_PER_FILE)++ return {+ path,+ text:+ `The user attached the diff of ${path} from the diff pane to this ` ++ `prompt:\n${body.join('\n')}`,+ lines: body.length,+ }+}diff --git a/mods/diff/hooks/ask/armed-ask/armed-ask.ts b/mods/diff/hooks/ask/armed-ask/armed-ask.tsnew file mode 100644index 00000000..e760eb15--- /dev/null+++ b/mods/diff/hooks/ask/armed-ask/armed-ask.ts@@ -0,0 +1,9 @@+/**+ * The file the person asked about from the pane: its path and its diff as+ * text, held until the next prompt carries it as context.+ */+export type ArmedAsk = {+ path: string+ text: string+ lines: number+}diff --git a/mods/diff/hooks/ask/armed-ask/index.ts b/mods/diff/hooks/ask/armed-ask/index.tsnew file mode 100644index 00000000..c6efab89--- /dev/null+++ b/mods/diff/hooks/ask/armed-ask/index.ts@@ -0,0 +1,3 @@+export type * from './armed-ask.js'++export * as default from '.'diff --git a/mods/diff/hooks/ask/index.ts b/mods/diff/hooks/ask/index.tsnew file mode 100644index 00000000..f167fcca--- /dev/null+++ b/mods/diff/hooks/ask/index.ts@@ -0,0 +1,4 @@+export * from './armed-ask'+export * from './armed-ask-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/classify/base-name-of/base-name-of.ts b/mods/diff/hooks/classify/base-name-of/base-name-of.tsnew file mode 100644index 00000000..72a50391--- /dev/null+++ b/mods/diff/hooks/classify/base-name-of/base-name-of.ts@@ -0,0 +1,7 @@+/**+ * A `/`-separated path's last segment: the file's own name.+ *+ * @param path the repository-relative path+ * @returns the base name+ */+export const baseNameOf = (path: string) => path.split('/').at(-1) ?? pathdiff --git a/mods/diff/hooks/classify/base-name-of/index.ts b/mods/diff/hooks/classify/base-name-of/index.tsnew file mode 100644index 00000000..af27a138--- /dev/null+++ b/mods/diff/hooks/classify/base-name-of/index.ts@@ -0,0 +1,3 @@+export * from './base-name-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/classify/index.ts b/mods/diff/hooks/classify/index.tsnew file mode 100644index 00000000..b9a1d20c--- /dev/null+++ b/mods/diff/hooks/classify/index.ts@@ -0,0 +1,7 @@+export * from './base-name-of'+export * from './is-generated-file'+export * from './is-noise-file.js'+export * from './is-test-file'+export * from './rooted-path-of'++export * as default from '.'diff --git a/mods/diff/hooks/classify/is-generated-file/generated-directories/generated-directories.ts b/mods/diff/hooks/classify/is-generated-file/generated-directories/generated-directories.tsnew file mode 100644index 00000000..49e76281--- /dev/null+++ b/mods/diff/hooks/classify/is-generated-file/generated-directories/generated-directories.ts@@ -0,0 +1,28 @@+/**+ * Path segments of build output, vendored code, caches and snapshots, the+ * engine's excluded directories, matched against `/<path>`.+ */+export const GENERATED_DIRECTORIES = [+ '/dist/',+ '/build/',+ '/out/',+ '/output/',+ '/node_modules/',+ '/vendor/',+ '/vendored/',+ '/third_party/',+ '/third-party/',+ '/external/',+ '/.next/',+ '/.nuxt/',+ '/.svelte-kit/',+ '/coverage/',+ '/__pycache__/',+ '/.tox/',+ '/venv/',+ '/.venv/',+ '/target/release/',+ '/target/debug/',+ '.generated/',+ '/__snapshots__/',+] as constdiff --git a/mods/diff/hooks/classify/is-generated-file/generated-directories/index.ts b/mods/diff/hooks/classify/is-generated-file/generated-directories/index.tsnew file mode 100644index 00000000..13a8df21--- /dev/null+++ b/mods/diff/hooks/classify/is-generated-file/generated-directories/index.ts@@ -0,0 +1,3 @@+export * from './generated-directories.js'++export * as default from '.'diff --git a/mods/diff/hooks/classify/is-generated-file/generated-filename-patterns/generated-filename-patterns.ts b/mods/diff/hooks/classify/is-generated-file/generated-filename-patterns/generated-filename-patterns.tsnew file mode 100644index 00000000..f2d9fc81--- /dev/null+++ b/mods/diff/hooks/classify/is-generated-file/generated-filename-patterns/generated-filename-patterns.ts@@ -0,0 +1,21 @@+/**+ * File-name shapes of generated code, the engine's excluded file-name+ * patterns: minified, bundled, stubs, specs, snapshots.+ */+export const GENERATED_FILENAME_PATTERNS: readonly RegExp[] = Object.freeze([+ /\.min\.[a-z]+$/i,+ /-min\.[a-z]+$/i,+ /\.bundle\.[a-z]+$/i,+ /\.generated\.[a-z]+$/i,+ /\.gen\.[a-z]+$/i,+ /\.auto\.[a-z]+$/i,+ /_generated\.[a-z]+$/i,+ /_gen\.[a-z]+$/i,+ /\.pb\.(?:go|js|ts|py|rb)$/i,+ /_pb2?\.py$/i,+ /\.pb\.h$/i,+ /\.grpc\.[a-z]+$/i,+ /\.swagger\.[a-z]+$/i,+ /\.openapi\.[a-z]+$/i,+ /\.snap$/i,+])diff --git a/mods/diff/hooks/classify/is-generated-file/generated-filename-patterns/index.ts b/mods/diff/hooks/classify/is-generated-file/generated-filename-patterns/index.tsnew file mode 100644index 00000000..c01ca145--- /dev/null+++ b/mods/diff/hooks/classify/is-generated-file/generated-filename-patterns/index.ts@@ -0,0 +1,3 @@+export * from './generated-filename-patterns.js'++export * as default from '.'diff --git a/mods/diff/hooks/classify/is-generated-file/generated-filenames/generated-filenames.ts b/mods/diff/hooks/classify/is-generated-file/generated-filenames/generated-filenames.tsnew file mode 100644index 00000000..8b152a35--- /dev/null+++ b/mods/diff/hooks/classify/is-generated-file/generated-filenames/generated-filenames.ts@@ -0,0 +1,18 @@+/**+ * File names (lowercase) that are lockfiles or shrinkwraps, never hand+ * written, so their churn is noise in a diff.+ */+export const GENERATED_FILENAMES: ReadonlySet<string> = new Set([+ 'package-lock.json',+ 'yarn.lock',+ 'pnpm-lock.yaml',+ 'bun.lockb',+ 'bun.lock',+ 'composer.lock',+ 'gemfile.lock',+ 'cargo.lock',+ 'poetry.lock',+ 'pipfile.lock',+ 'shrinkwrap.json',+ 'npm-shrinkwrap.json',+])diff --git a/mods/diff/hooks/classify/is-generated-file/generated-filenames/index.ts b/mods/diff/hooks/classify/is-generated-file/generated-filenames/index.tsnew file mode 100644index 00000000..84bf2e29--- /dev/null+++ b/mods/diff/hooks/classify/is-generated-file/generated-filenames/index.ts@@ -0,0 +1,3 @@+export * from './generated-filenames.js'++export * as default from '.'diff --git a/mods/diff/hooks/classify/is-generated-file/generated-suffixes/generated-suffixes.ts b/mods/diff/hooks/classify/is-generated-file/generated-suffixes/generated-suffixes.tsnew file mode 100644index 00000000..7a530982--- /dev/null+++ b/mods/diff/hooks/classify/is-generated-file/generated-suffixes/generated-suffixes.ts@@ -0,0 +1,15 @@+/**+ * Extensions, simple and compound (lowercase), of minified, bundled or+ * generated output, the engine's excluded extensions.+ */+export const GENERATED_SUFFIXES = [+ '.lock',+ '.min.js',+ '.min.css',+ '.min.html',+ '.bundle.js',+ '.bundle.css',+ '.generated.ts',+ '.generated.js',+ '.d.ts',+] as constdiff --git a/mods/diff/hooks/classify/is-generated-file/generated-suffixes/index.ts b/mods/diff/hooks/classify/is-generated-file/generated-suffixes/index.tsnew file mode 100644index 00000000..c53be33e--- /dev/null+++ b/mods/diff/hooks/classify/is-generated-file/generated-suffixes/index.ts@@ -0,0 +1,3 @@+export * from './generated-suffixes.js'++export * as default from '.'diff --git a/mods/diff/hooks/classify/is-generated-file/index.ts b/mods/diff/hooks/classify/is-generated-file/index.tsnew file mode 100644index 00000000..13d01308--- /dev/null+++ b/mods/diff/hooks/classify/is-generated-file/index.ts@@ -0,0 +1,7 @@+export * from './generated-directories'+export * from './generated-filename-patterns'+export * from './generated-filenames'+export * from './generated-suffixes'+export * from './is-generated-file.js'++export * as default from '.'diff --git a/mods/diff/hooks/classify/is-generated-file/is-generated-file.ts b/mods/diff/hooks/classify/is-generated-file/is-generated-file.tsnew file mode 100644index 00000000..937d558f--- /dev/null+++ b/mods/diff/hooks/classify/is-generated-file/is-generated-file.ts@@ -0,0 +1,28 @@+import { baseNameOf } from '../base-name-of'+import { rootedPathOf } from '../rooted-path-of'+import { GENERATED_DIRECTORIES } from './generated-directories'+import { GENERATED_FILENAME_PATTERNS } from './generated-filename-patterns'+import { GENERATED_FILENAMES } from './generated-filenames'+import { GENERATED_SUFFIXES } from './generated-suffixes'++/**+ * Whether a repository-relative path names generated or vendored content,+ * by the Linguist-style rules the engine's own diff panel applies.+ *+ * @param path the file's path from the repository root, `/`-separated+ * @returns whether the diff pane counts it among the tests and generated files+ */+export function isGeneratedFile(path: string) {+ const name = baseNameOf(path).toLowerCase()+ const rooted = rootedPathOf(path)+ const hasGeneratedSuffix = GENERATED_SUFFIXES.some(suffix =>+ name.endsWith(suffix),+ )++ return (+ GENERATED_FILENAMES.has(name) ||+ hasGeneratedSuffix ||+ GENERATED_DIRECTORIES.some(directory => rooted.includes(directory)) ||+ GENERATED_FILENAME_PATTERNS.some(pattern => pattern.test(name))+ )+}diff --git a/mods/diff/hooks/classify/is-noise-file.ts b/mods/diff/hooks/classify/is-noise-file.tsnew file mode 100644index 00000000..3dfa1a55--- /dev/null+++ b/mods/diff/hooks/classify/is-noise-file.ts@@ -0,0 +1,12 @@+import { isGeneratedFile } from './is-generated-file'+import { isTestFile } from './is-test-file'++/**+ * Whether a changed file is hidden behind the pane's tests-and-generated+ * line until the person asks to see it.+ *+ * @param path the file's path from the repository root+ * @returns whether it is a test or a generated file+ */+export const isNoiseFile = (path: string) =>+ isTestFile(path) || isGeneratedFile(path)diff --git a/mods/diff/hooks/classify/is-test-file/index.ts b/mods/diff/hooks/classify/is-test-file/index.tsnew file mode 100644index 00000000..def0bac9--- /dev/null+++ b/mods/diff/hooks/classify/is-test-file/index.ts@@ -0,0 +1,5 @@+export * from './is-test-file.js'+export * from './test-directories'+export * from './test-filename-patterns'++export * as default from '.'diff --git a/mods/diff/hooks/classify/is-test-file/is-test-file.ts b/mods/diff/hooks/classify/is-test-file/is-test-file.tsnew file mode 100644index 00000000..2cb41a12--- /dev/null+++ b/mods/diff/hooks/classify/is-test-file/is-test-file.ts@@ -0,0 +1,21 @@+import { baseNameOf } from '../base-name-of'+import { rootedPathOf } from '../rooted-path-of'+import { TEST_DIRECTORIES } from './test-directories'+import { TEST_FILENAME_PATTERNS } from './test-filename-patterns'++/**+ * Whether a repository-relative path is a test, spec, fixture or snapshot,+ * by the same rules the engine's own diff panel applies.+ *+ * @param path the file's path from the repository root, `/`-separated+ * @returns whether the diff pane counts it among the tests and generated files+ */+export function isTestFile(path: string) {+ const name = baseNameOf(path)+ const rooted = rootedPathOf(path)++ return (+ TEST_DIRECTORIES.some(directory => rooted.includes(directory)) ||+ TEST_FILENAME_PATTERNS.some(pattern => pattern.test(name))+ )+}diff --git a/mods/diff/hooks/classify/is-test-file/test-directories/index.ts b/mods/diff/hooks/classify/is-test-file/test-directories/index.tsnew file mode 100644index 00000000..cecf4b11--- /dev/null+++ b/mods/diff/hooks/classify/is-test-file/test-directories/index.ts@@ -0,0 +1,3 @@+export * from './test-directories.js'++export * as default from '.'diff --git a/mods/diff/hooks/classify/is-test-file/test-directories/test-directories.ts b/mods/diff/hooks/classify/is-test-file/test-directories/test-directories.tsnew file mode 100644index 00000000..111c4e20--- /dev/null+++ b/mods/diff/hooks/classify/is-test-file/test-directories/test-directories.ts@@ -0,0 +1,16 @@+/**+ * Path segments of tests, specs, mocks and fixtures, the engine's test+ * directories, matched against `/<path>`.+ */+export const TEST_DIRECTORIES = [+ '/test/',+ '/tests/',+ '/spec/',+ '/specs/',+ '/__tests__/',+ '/__mocks__/',+ '/__snapshots__/',+ '/__fixtures__/',+ '/fixtures/',+ '/testdata/',+] as constdiff --git a/mods/diff/hooks/classify/is-test-file/test-filename-patterns/index.ts b/mods/diff/hooks/classify/is-test-file/test-filename-patterns/index.tsnew file mode 100644index 00000000..56f60e78--- /dev/null+++ b/mods/diff/hooks/classify/is-test-file/test-filename-patterns/index.ts@@ -0,0 +1,3 @@+export * from './test-filename-patterns.js'++export * as default from '.'diff --git a/mods/diff/hooks/classify/is-test-file/test-filename-patterns/test-filename-patterns.ts b/mods/diff/hooks/classify/is-test-file/test-filename-patterns/test-filename-patterns.tsnew file mode 100644index 00000000..6c472162--- /dev/null+++ b/mods/diff/hooks/classify/is-test-file/test-filename-patterns/test-filename-patterns.ts@@ -0,0 +1,11 @@+/**+ * File-name shapes of test files and snapshots, the engine's test file-name+ * patterns.+ */+export const TEST_FILENAME_PATTERNS: readonly RegExp[] = Object.freeze([+ /\.test\.[a-z]+$/i,+ /\.spec\.[a-z]+$/i,+ /_test\.[a-z]+$/i,+ /_spec\.[a-z]+$/i,+ /\.snap$/i,+])diff --git a/mods/diff/hooks/classify/rooted-path-of/index.ts b/mods/diff/hooks/classify/rooted-path-of/index.tsnew file mode 100644index 00000000..827b27f3--- /dev/null+++ b/mods/diff/hooks/classify/rooted-path-of/index.ts@@ -0,0 +1,3 @@+export * from './rooted-path-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/classify/rooted-path-of/rooted-path-of.ts b/mods/diff/hooks/classify/rooted-path-of/rooted-path-of.tsnew file mode 100644index 00000000..47411f45--- /dev/null+++ b/mods/diff/hooks/classify/rooted-path-of/rooted-path-of.ts@@ -0,0 +1,8 @@+/**+ * A path with exactly one leading `/`, so a directory pattern like `/test/`+ * matches at the start of a relative path too.+ *+ * @param path the repository-relative path+ * @returns the rooted path+ */+export const rootedPathOf = (path: string) => `/${path.replace(/^\/+/, '')}`diff --git a/mods/diff/hooks/command-spec/command-spec.ts b/mods/diff/hooks/command-spec/command-spec.tsnew file mode 100644index 00000000..9b4ea85a--- /dev/null+++ b/mods/diff/hooks/command-spec/command-spec.ts@@ -0,0 +1,10 @@+import Names from '../names'++/**+ * What `session.start` hands `$.command.register`: the one place the+ * `/diff` spec is built, where a later CommandSpec field joins.+ */+export const COMMAND_SPEC = {+ name: Names.COMMAND_NAME,+ description: Names.COMMAND_DESCRIPTION,+} as constdiff --git a/mods/diff/hooks/command-spec/index.ts b/mods/diff/hooks/command-spec/index.tsnew file mode 100644index 00000000..861ab9b1--- /dev/null+++ b/mods/diff/hooks/command-spec/index.ts@@ -0,0 +1,3 @@+export * from './command-spec.js'++export * as default from '.'diff --git a/mods/diff/hooks/count-of/count-of.ts b/mods/diff/hooks/count-of/count-of.tsnew file mode 100644index 00000000..989649ed--- /dev/null+++ b/mods/diff/hooks/count-of/count-of.ts@@ -0,0 +1,10 @@+/**+ * How many items of a list pass a test, without the intermediate array a+ * filter would build.+ *+ * @param items the list+ * @param passes the test+ * @returns the number of passing items+ */+export const countOf = <T>(items: readonly T[], passes: (item: T) => boolean) =>+ items.reduce((total, item) => total + (passes(item) ? 1 : 0), 0)diff --git a/mods/diff/hooks/count-of/index.ts b/mods/diff/hooks/count-of/index.tsnew file mode 100644index 00000000..6c6256c3--- /dev/null+++ b/mods/diff/hooks/count-of/index.ts@@ -0,0 +1,3 @@+export * from './count-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/entry-kinds-of/entry-kinds-of.ts b/mods/diff/hooks/entry-kinds-of/entry-kinds-of.tsnew file mode 100644index 00000000..3daad05b--- /dev/null+++ b/mods/diff/hooks/entry-kinds-of/entry-kinds-of.ts@@ -0,0 +1,17 @@+import type Git from '../git'+import type { Host } from '../host'++/**+ * A directory's entries by name with their own kinds, through the host's+ * listing (no link followed); null when it cannot be listed.+ *+ * @param engine the bound host+ * @returns the probe (GitDeps `entryKindsOf`)+ */+export const entryKindsOf =+ (engine: Host) =>+ (dir: string): Promise<ReadonlyMap<string, Git.EntryKind> | null> =>+ engine.listDir(dir).then(+ entries => new Map(entries.map(entry => [entry.name, entry.kind])),+ () => null,+ )diff --git a/mods/diff/hooks/entry-kinds-of/index.ts b/mods/diff/hooks/entry-kinds-of/index.tsnew file mode 100644index 00000000..97b3c174--- /dev/null+++ b/mods/diff/hooks/entry-kinds-of/index.ts@@ -0,0 +1,3 @@+export * from './entry-kinds-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/argv/diff-leading-args.ts b/mods/diff/hooks/git/argv/diff-leading-args.tsnew file mode 100644index 00000000..fe77659e--- /dev/null+++ b/mods/diff/hooks/git/argv/diff-leading-args.ts@@ -0,0 +1,20 @@+/**+ * The leading argv of every `git diff` the plugin runs: the config the+ * engine's own diff panel pins, `core.quotePath=false`, and raw-blob flags.+ *+ * Root-relative paths whatever `diff.relative` says, non-ASCII paths as+ * their own bytes, no optional locks, no child `git status` in a dirty+ * submodule, and no external diff or textconv driver even on a stats pass.+ */+export const DIFF_LEADING_ARGS = [+ '--no-optional-locks',+ '-c',+ 'diff.relative=false',+ '-c',+ 'core.quotePath=false',+ 'diff',+ '--no-ext-diff',+ '--no-textconv',+ '--ignore-submodules=dirty',+ '--submodule=short',+] as constdiff --git a/mods/diff/hooks/git/argv/git-child-env/git-child-env.ts b/mods/diff/hooks/git/argv/git-child-env/git-child-env.tsnew file mode 100644index 00000000..f362db6b--- /dev/null+++ b/mods/diff/hooks/git/argv/git-child-env/git-child-env.ts@@ -0,0 +1,8 @@+/**+ * The environment laid over every git child the plugin spawns: the C+ * locale, so `--shortstat` and git's messages parse the same everywhere.+ *+ * Nothing else is pinned, as for the built-in panel's own diff children:+ * a partial clone lazy-fetches as it would for `git diff` at the prompt.+ */+export const GIT_CHILD_ENV = { LC_ALL: 'C', LANGUAGE: '' } as constdiff --git a/mods/diff/hooks/git/argv/git-child-env/index.ts b/mods/diff/hooks/git/argv/git-child-env/index.tsnew file mode 100644index 00000000..07d69588--- /dev/null+++ b/mods/diff/hooks/git/argv/git-child-env/index.ts@@ -0,0 +1,3 @@+export * from './git-child-env.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/argv/index.ts b/mods/diff/hooks/git/argv/index.tsnew file mode 100644index 00000000..42515bf3--- /dev/null+++ b/mods/diff/hooks/git/argv/index.ts@@ -0,0 +1,6 @@+export * from './diff-leading-args.js'+export * from './git-child-env'+export * from './no-optional-locks.js'+export * from './pinned-lead-of'++export * as default from '.'diff --git a/mods/diff/hooks/git/argv/no-optional-locks.ts b/mods/diff/hooks/git/argv/no-optional-locks.tsnew file mode 100644index 00000000..7cc47104--- /dev/null+++ b/mods/diff/hooks/git/argv/no-optional-locks.ts@@ -0,0 +1,5 @@+/**+ * The flag every probe carries so a read never takes the index lock from a+ * git the person is running.+ */+export const NO_OPTIONAL_LOCKS = '--no-optional-locks'diff --git a/mods/diff/hooks/git/argv/pinned-lead-of/index.ts b/mods/diff/hooks/git/argv/pinned-lead-of/index.tsnew file mode 100644index 00000000..440afd54--- /dev/null+++ b/mods/diff/hooks/git/argv/pinned-lead-of/index.ts@@ -0,0 +1,3 @@+export * from './pinned-lead-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/argv/pinned-lead-of/pinned-lead-of.ts b/mods/diff/hooks/git/argv/pinned-lead-of/pinned-lead-of.tsnew file mode 100644index 00000000..c887e733--- /dev/null+++ b/mods/diff/hooks/git/argv/pinned-lead-of/pinned-lead-of.ts@@ -0,0 +1,18 @@+import type Types from '../../types'++/**+ * The argv that leads every git child once the repository is pinned: its+ * git directory and working tree named, as the built-in panel pins them.+ *+ * With `--git-dir` given git discovers nothing from its cwd, so a nested+ * repository the shell later moves into is never the one read.+ *+ * @param repository the session's pinned repository+ * @returns the leading argv+ */+export const pinnedLeadOf = (+ repository: Types.Repository,+): readonly string[] => [+ `--git-dir=${repository.gitDir}`,+ `--work-tree=${repository.toplevel}`,+]diff --git a/mods/diff/hooks/git/cut-hunks/cut-hunks.ts b/mods/diff/hooks/git/cut-hunks/cut-hunks.tsnew file mode 100644index 00000000..83545faa--- /dev/null+++ b/mods/diff/hooks/git/cut-hunks/cut-hunks.ts@@ -0,0 +1,30 @@+import Limits from '../../limits'+import type Types from '../types'++/**+ * Hunks with their lines cut at MAX_LINES_PER_FILE in all, in order, and+ * whether any line was dropped.+ *+ * The one bound on every body the pane draws or attaches, whether git+ * printed it or the transcript carried it.+ *+ * @param hunks the hunks as parsed or reported+ * @returns the cut hunks and whether the cut dropped lines+ */+export function cutHunks(+ hunks: readonly Types.Hunk[],+): Pick<Types.FileHunks, 'hunks' | 'isTruncated'> {+ let budget = Limits.MAX_LINES_PER_FILE+ let total = 0++ return {+ hunks: hunks.map(hunk => {+ const lines = hunk.lines.slice(0, budget)+ budget -= lines.length+ total += hunk.lines.length++ return { ...hunk, lines }+ }),+ isTruncated: total > Limits.MAX_LINES_PER_FILE,+ }+}diff --git a/mods/diff/hooks/git/cut-hunks/index.ts b/mods/diff/hooks/git/cut-hunks/index.tsnew file mode 100644index 00000000..25e0de49--- /dev/null+++ b/mods/diff/hooks/git/cut-hunks/index.ts@@ -0,0 +1,3 @@+export * from './cut-hunks.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/empty-file-hunks/empty-file-hunks.ts b/mods/diff/hooks/git/empty-file-hunks/empty-file-hunks.tsnew file mode 100644index 00000000..e368d272--- /dev/null+++ b/mods/diff/hooks/git/empty-file-hunks/empty-file-hunks.ts@@ -0,0 +1,11 @@+import type Types from '../types'++/**+ * A body with nothing to draw: an untracked or binary row's, or a staged+ * file's whose index body went stale on an unborn HEAD.+ */+export const EMPTY_FILE_HUNKS: Types.FileHunks = Object.freeze({+ hunks: [],+ isTruncated: false,+ isLarge: false,+})diff --git a/mods/diff/hooks/git/empty-file-hunks/index.ts b/mods/diff/hooks/git/empty-file-hunks/index.tsnew file mode 100644index 00000000..f702b354--- /dev/null+++ b/mods/diff/hooks/git/empty-file-hunks/index.ts@@ -0,0 +1,3 @@+export * from './empty-file-hunks.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/fetch-diff.ts b/mods/diff/hooks/git/fetch-diff.tsnew file mode 100644index 00000000..d36154ac--- /dev/null+++ b/mods/diff/hooks/git/fetch-diff.ts@@ -0,0 +1,33 @@+import Probes from './probes'+import Tiers from './tiers'+import type Types from './types'++/**+ * One fetch of the session's pinned repository, as the built-in panel+ * fetches; every git child names it so paths stay root-relative.+ *+ * Mid-merge, mid-rebase, mid-cherry-pick or mid-revert, or when git cannot+ * answer, it is unavailable and the caller keeps what it had.+ *+ * @param deps the host: pinned git, the repository, the file probes+ * @param mode what to compare against+ * @returns the outcome+ */+export async function fetchDiff(+ deps: Types.GitDeps,+ mode: Types.BaseMode,+): Promise<Types.FetchOutcome> {+ const isBusy = await Probes.isTransient(+ deps.entryKindsOf,+ deps.repository.gitDir,+ )++ if (isBusy) {+ return { kind: 'unavailable' }+ }++ const context = Tiers.fetchContextOf(deps, mode)+ const isBranch = mode === 'branch'++ return isBranch ? Tiers.branchTier(context) : Tiers.workingTreeTier(context)+}diff --git a/mods/diff/hooks/git/fetch-file-hunks.ts b/mods/diff/hooks/git/fetch-file-hunks.tsnew file mode 100644index 00000000..5ddc2b9e--- /dev/null+++ b/mods/diff/hooks/git/fetch-file-hunks.ts@@ -0,0 +1,41 @@+import Argv from './argv'+import { EMPTY_FILE_HUNKS } from './empty-file-hunks'+import GitParse from './parse'+import type Types from './types'++/**+ * One file's hunks against the base its row was read against, so body and+ * counts agree, by literal pathspec, as the built-in panel reads hunks.+ *+ * A rename passes both its paths so git pairs them; an untracked or binary+ * row, or on an unborn HEAD a file edited after staging, has no honest+ * body and answers no hunks.+ *+ * @param run runs git against the pinned repository+ * @param data the fetch the row belongs to+ * @param file the row+ * @returns the parsed body, or null when git failed+ */+export async function fetchFileHunks(+ run: Types.GitRun,+ data: Types.DiffData,+ file: Types.FileStat,+): Promise<Types.FileHunks | null> {+ const hasNoBody =+ file.isUntracked || file.isBinary || data.stalePaths.includes(file.path)++ if (hasNoBody) {+ return EMPTY_FILE_HUNKS+ }++ const { exitCode, stdout } = await run([+ '--literal-pathspecs',+ ...Argv.DIFF_LEADING_ARGS,+ data.baseRef,+ '--',+ ...(file.renamedFrom === null ? [] : [file.renamedFrom]),+ file.path,+ ])++ return exitCode === 0 ? GitParse.parseFileDiff(stdout) : null+}diff --git a/mods/diff/hooks/git/hunk-of/hunk-of.ts b/mods/diff/hooks/git/hunk-of/hunk-of.tsnew file mode 100644index 00000000..4aaed04f--- /dev/null+++ b/mods/diff/hooks/git/hunk-of/hunk-of.ts@@ -0,0 +1,17 @@+import type Types from '../types'++/**+ * One hunk from its header's captured starts and its body lines.+ *+ * @param starts the `old` and `new` groups of HUNK_HEADER, when it matched+ * @param lines the body lines after the header+ * @returns the hunk+ */+export const hunkOf = (+ starts: Record<string, string> | undefined,+ lines: readonly string[],+): Types.Hunk => ({+ oldStart: Number(starts?.old),+ newStart: Number(starts?.new),+ lines,+})diff --git a/mods/diff/hooks/git/hunk-of/index.ts b/mods/diff/hooks/git/hunk-of/index.tsnew file mode 100644index 00000000..9dc9d6d5--- /dev/null+++ b/mods/diff/hooks/git/hunk-of/index.ts@@ -0,0 +1,3 @@+export * from './hunk-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/index.ts b/mods/diff/hooks/git/index.tsnew file mode 100644index 00000000..2ce634a2--- /dev/null+++ b/mods/diff/hooks/git/index.ts@@ -0,0 +1,13 @@+export * from './argv'+export * from './cut-hunks'+export * from './empty-file-hunks'+export * from './fetch-diff.js'+export * from './fetch-file-hunks.js'+export * from './hunk-of'+export * from './large-file-hunks'+export * from './parse'+export * from './probes'+export * from './tiers'+export * from './types'++export * as default from '.'diff --git a/mods/diff/hooks/git/large-file-hunks/index.ts b/mods/diff/hooks/git/large-file-hunks/index.tsnew file mode 100644index 00000000..2a8706ba--- /dev/null+++ b/mods/diff/hooks/git/large-file-hunks/index.ts@@ -0,0 +1,3 @@+export * from './large-file-hunks.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/large-file-hunks/large-file-hunks.ts b/mods/diff/hooks/git/large-file-hunks/large-file-hunks.tsnew file mode 100644index 00000000..f5bca63b--- /dev/null+++ b/mods/diff/hooks/git/large-file-hunks/large-file-hunks.ts@@ -0,0 +1,11 @@+import type Types from '../types'++/**+ * The body of a file whose diff text passed MAX_DIFF_BYTES: no hunks, and+ * the pane says the file is too large.+ */+export const LARGE_FILE_HUNKS: Types.FileHunks = Object.freeze({+ hunks: [],+ isTruncated: false,+ isLarge: true,+})diff --git a/mods/diff/hooks/git/parse/hunk-header/hunk-header.ts b/mods/diff/hooks/git/parse/hunk-header/hunk-header.tsnew file mode 100644index 00000000..ecc79898--- /dev/null+++ b/mods/diff/hooks/git/parse/hunk-header/hunk-header.ts@@ -0,0 +1,5 @@+/**+ * A unified diff's hunk header, `@@ -old[,n] +new[,n] @@`, its two starts+ * captured as `old` and `new`.+ */+export const HUNK_HEADER = /^@@ -(?<old>\d+)(?:,\d+)? \+(?<new>\d+)(?:,\d+)? @@/diff --git a/mods/diff/hooks/git/parse/hunk-header/index.ts b/mods/diff/hooks/git/parse/hunk-header/index.tsnew file mode 100644index 00000000..25a979e2--- /dev/null+++ b/mods/diff/hooks/git/parse/hunk-header/index.ts@@ -0,0 +1,3 @@+export * from './hunk-header.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/parse/index.ts b/mods/diff/hooks/git/parse/index.tsnew file mode 100644index 00000000..b3f08909--- /dev/null+++ b/mods/diff/hooks/git/parse/index.ts@@ -0,0 +1,11 @@+export * from './hunk-header'+export * from './is-body-line'+export * from './is-whole-answer'+export * from './is-whole-listing'+export * from './parse-file-diff.js'+export * from './parse-numstat.js'+export * from './parse-shortstat.js'+export * from './rename-records'+export * from './shortstat-pattern'++export * as default from '.'diff --git a/mods/diff/hooks/git/parse/is-body-line/index.ts b/mods/diff/hooks/git/parse/is-body-line/index.tsnew file mode 100644index 00000000..deb69448--- /dev/null+++ b/mods/diff/hooks/git/parse/is-body-line/index.ts@@ -0,0 +1,3 @@+export * from './is-body-line.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/parse/is-body-line/is-body-line.ts b/mods/diff/hooks/git/parse/is-body-line/is-body-line.tsnew file mode 100644index 00000000..a0bc81fd--- /dev/null+++ b/mods/diff/hooks/git/parse/is-body-line/is-body-line.ts@@ -0,0 +1,9 @@+/**+ * Whether a line after a hunk header is a body line (added, removed or+ * context) rather than a note such as `\ No newline at end of file`.+ *+ * @param line one line of `git diff` output+ * @returns whether it starts with `+`, `-` or a space+ */+export const isBodyLine = (line: string) =>+ line.startsWith('+') || line.startsWith('-') || line.startsWith(' ')diff --git a/mods/diff/hooks/git/parse/is-whole-answer/index.ts b/mods/diff/hooks/git/parse/is-whole-answer/index.tsnew file mode 100644index 00000000..4a80f3e1--- /dev/null+++ b/mods/diff/hooks/git/parse/is-whole-answer/index.ts@@ -0,0 +1,3 @@+export * from './is-whole-answer.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/parse/is-whole-answer/is-whole-answer.ts b/mods/diff/hooks/git/parse/is-whole-answer/is-whole-answer.tsnew file mode 100644index 00000000..4c910cfa--- /dev/null+++ b/mods/diff/hooks/git/parse/is-whole-answer/is-whole-answer.ts@@ -0,0 +1,12 @@+import type Types from '../../types'+import { isWholeListing } from '../is-whole-listing'++/**+ * Whether a `-z` git child both succeeded and answered a whole listing,+ * so its stdout may be parsed (isWholeListing).+ *+ * @param result what the child left+ * @returns whether to parse it+ */+export const isWholeAnswer = (result: Types.RunResult) =>+ result.exitCode === 0 && isWholeListing(result.stdout)diff --git a/mods/diff/hooks/git/parse/is-whole-listing/index.ts b/mods/diff/hooks/git/parse/is-whole-listing/index.tsnew file mode 100644index 00000000..b4c9874a--- /dev/null+++ b/mods/diff/hooks/git/parse/is-whole-listing/index.ts@@ -0,0 +1,5 @@+export * from './is-under-utf8-ceiling'+export * from './is-whole-listing.js'+export * from './most-utf8-bytes'++export * as default from '.'diff --git a/mods/diff/hooks/git/parse/is-whole-listing/is-under-utf8-ceiling/index.ts b/mods/diff/hooks/git/parse/is-whole-listing/is-under-utf8-ceiling/index.tsnew file mode 100644index 00000000..5c3a0a07--- /dev/null+++ b/mods/diff/hooks/git/parse/is-whole-listing/is-under-utf8-ceiling/index.ts@@ -0,0 +1,3 @@+export * from './is-under-utf8-ceiling.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/parse/is-whole-listing/is-under-utf8-ceiling/is-under-utf8-ceiling.ts b/mods/diff/hooks/git/parse/is-whole-listing/is-under-utf8-ceiling/is-under-utf8-ceiling.tsnew file mode 100644index 00000000..c69d2712--- /dev/null+++ b/mods/diff/hooks/git/parse/is-whole-listing/is-under-utf8-ceiling/is-under-utf8-ceiling.ts@@ -0,0 +1,13 @@+import { MOST_UTF8_BYTES } from '../most-utf8-bytes'++/**+ * Whether the text's UTF-8 encoding stays under a byte count, encoding it+ * only when its length alone cannot already say so.+ *+ * @param text the text+ * @param ceiling the byte count it must stay under+ * @returns whether it is under+ */+export const isUnderUtf8Ceiling = (text: string, ceiling: number) =>+ text.length * MOST_UTF8_BYTES < ceiling ||+ new TextEncoder().encode(text).length < ceilingdiff --git a/mods/diff/hooks/git/parse/is-whole-listing/is-whole-listing.ts b/mods/diff/hooks/git/parse/is-whole-listing/is-whole-listing.tsnew file mode 100644index 00000000..7bb74607--- /dev/null+++ b/mods/diff/hooks/git/parse/is-whole-listing/is-whole-listing.ts@@ -0,0 +1,17 @@+import Limits from '../../../limits'+import { isUnderUtf8Ceiling } from './is-under-utf8-ceiling'+import { MOST_UTF8_BYTES } from './most-utf8-bytes'++/**+ * Whether a `-z` listing arrived whole: every record NUL-terminated and+ * the text short of the host's output cap, so no record was cut or lost.+ *+ * A cut inside a multi-byte character costs the decoded text up to+ * MOST_UTF8_BYTES, hence the margin under the cap.+ *+ * @param stdout the listing as `$.process.run` returned it+ * @returns whether it can be parsed as the whole answer+ */+export const isWholeListing = (stdout: string) =>+ (stdout === '' || stdout.endsWith('\0')) &&+ isUnderUtf8Ceiling(stdout, Limits.HOST_OUTPUT_CAP_BYTES - MOST_UTF8_BYTES)diff --git a/mods/diff/hooks/git/parse/is-whole-listing/most-utf8-bytes/index.ts b/mods/diff/hooks/git/parse/is-whole-listing/most-utf8-bytes/index.tsnew file mode 100644index 00000000..6cc4be64--- /dev/null+++ b/mods/diff/hooks/git/parse/is-whole-listing/most-utf8-bytes/index.ts@@ -0,0 +1,3 @@+export * from './most-utf8-bytes.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/parse/is-whole-listing/most-utf8-bytes/most-utf8-bytes.ts b/mods/diff/hooks/git/parse/is-whole-listing/most-utf8-bytes/most-utf8-bytes.tsnew file mode 100644index 00000000..99289178--- /dev/null+++ b/mods/diff/hooks/git/parse/is-whole-listing/most-utf8-bytes/most-utf8-bytes.ts@@ -0,0 +1,5 @@+/**+ * The most bytes one UTF-16 code unit takes in UTF-8, and so both the+ * bound on a text's encoded length and the most a cut character drops.+ */+export const MOST_UTF8_BYTES = 3diff --git a/mods/diff/hooks/git/parse/parse-file-diff.ts b/mods/diff/hooks/git/parse/parse-file-diff.tsnew file mode 100644index 00000000..21c6d35b--- /dev/null+++ b/mods/diff/hooks/git/parse/parse-file-diff.ts@@ -0,0 +1,40 @@+import Limits from '../../limits'+import { cutHunks } from '../cut-hunks'+import { hunkOf } from '../hunk-of'+import { LARGE_FILE_HUNKS } from '../large-file-hunks'+import type Types from '../types'+import { HUNK_HEADER } from './hunk-header'+import { isBodyLine } from './is-body-line'++/**+ * One file's unified `git diff` output as hunks, the body cut at+ * MAX_LINES_PER_FILE lines in all, as the built-in panel parses one file.+ *+ * Past MAX_DIFF_BYTES there are no hunks and `isLarge` is set; everything+ * before the first hunk header is the file's header.+ *+ * @param stdout the command's standard output for that one path+ * @returns the parsed body+ */+export function parseFileDiff(stdout: string): Types.FileHunks {+ if (stdout.length > Limits.MAX_DIFF_BYTES) {+ return LARGE_FILE_HUNKS+ }++ const rows = stdout.split('\n')+ const headerRows = rows.flatMap((row, at) =>+ HUNK_HEADER.test(row) ? [at] : [],+ )++ return {+ ...cutHunks(+ headerRows.map((at, ordinal) =>+ hunkOf(+ HUNK_HEADER.exec(rows[at] ?? '')?.groups,+ rows.slice(at + 1, headerRows[ordinal + 1]).filter(isBodyLine),+ ),+ ),+ ),+ isLarge: false,+ }+}diff --git a/mods/diff/hooks/git/parse/parse-numstat.ts b/mods/diff/hooks/git/parse/parse-numstat.tsnew file mode 100644index 00000000..65728d1e--- /dev/null+++ b/mods/diff/hooks/git/parse/parse-numstat.ts@@ -0,0 +1,62 @@+import type Types from '../types'+import { RENAME_RECORDS } from './rename-records'++/**+ * `git diff --numstat -z` output as totals over every row and the first+ * rows up to the cap; a binary file (`-` counts) is a 0/0 row marked binary.+ *+ * A record is `<added>\t<removed>\t<path>` ended by NUL, the path raw; a+ * rename is `<added>\t<removed>\t` then the old and the new path as the+ * next two records, kept as one row under the new path.+ *+ * @param stdout the command's standard output+ * @param maxFiles how many rows to keep+ * @returns the totals and the kept rows+ */+export function parseNumstat(+ stdout: string,+ maxFiles: number,+): Types.NumstatResult {+ const files: Types.FileStat[] = []+ const stats = { filesCount: 0, linesAdded: 0, linesRemoved: 0 }+ const records = stdout.split('\0')+ let at = 0++ while (at < records.length) {+ const [addedField, removedField, ...pathFields] = (records[at] ?? '').split(+ '\t',+ )+ const inline = pathFields.join('\t')+ const isRename = pathFields.length === 1 && inline === ''+ const renamedFrom = isRename ? (records[at + 1] ?? null) : null+ const path = isRename ? (records[at + 2] ?? '') : inline+ at += isRename ? RENAME_RECORDS : 1+ const isRow =+ addedField !== undefined && removedField !== undefined && path !== ''++ if (!isRow) {+ continue+ }++ const isBinary = addedField === '-' || removedField === '-'+ const added = isBinary ? 0 : Number(addedField) || 0+ const removed = isBinary ? 0 : Number(removedField) || 0+ stats.filesCount += 1+ stats.linesAdded += added+ stats.linesRemoved += removed++ if (files.length < maxFiles) {+ files.push({+ path,+ renamedFrom,+ added,+ removed,+ isBinary,+ isUntracked: false,+ isPreSession: false,+ })+ }+ }++ return { stats, files }+}diff --git a/mods/diff/hooks/git/parse/parse-shortstat.ts b/mods/diff/hooks/git/parse/parse-shortstat.tsnew file mode 100644index 00000000..ece5cae8--- /dev/null+++ b/mods/diff/hooks/git/parse/parse-shortstat.ts@@ -0,0 +1,23 @@+import type Types from '../types'+import { SHORTSTAT_PATTERN } from './shortstat-pattern'++/**+ * `git diff --shortstat` output as totals, or null when the line is not+ * git's summary line (empty output for an empty diff included).+ *+ * @param stdout the command's standard output+ * @returns the totals, or null+ */+export function parseShortstat(stdout: string): Types.DiffStats | null {+ const counts = SHORTSTAT_PATTERN.exec(stdout)?.groups++ if (!counts) {+ return null+ }++ return {+ filesCount: Number(counts.files),+ linesAdded: Number(counts.added ?? 0),+ linesRemoved: Number(counts.removed ?? 0),+ }+}diff --git a/mods/diff/hooks/git/parse/rename-records/index.ts b/mods/diff/hooks/git/parse/rename-records/index.tsnew file mode 100644index 00000000..f29fdeba--- /dev/null+++ b/mods/diff/hooks/git/parse/rename-records/index.ts@@ -0,0 +1,3 @@+export * from './rename-records.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/parse/rename-records/rename-records.ts b/mods/diff/hooks/git/parse/rename-records/rename-records.tsnew file mode 100644index 00000000..0322deab--- /dev/null+++ b/mods/diff/hooks/git/parse/rename-records/rename-records.ts@@ -0,0 +1,5 @@+/**+ * How many NUL records a rename takes in `--numstat -z` output: the counts+ * with an empty path, then the old path, then the new.+ */+export const RENAME_RECORDS = 3diff --git a/mods/diff/hooks/git/parse/shortstat-pattern/index.ts b/mods/diff/hooks/git/parse/shortstat-pattern/index.tsnew file mode 100644index 00000000..ce789a7a--- /dev/null+++ b/mods/diff/hooks/git/parse/shortstat-pattern/index.ts@@ -0,0 +1,3 @@+export * from './shortstat-pattern.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/parse/shortstat-pattern/shortstat-pattern.ts b/mods/diff/hooks/git/parse/shortstat-pattern/shortstat-pattern.tsnew file mode 100644index 00000000..ccd3fe3e--- /dev/null+++ b/mods/diff/hooks/git/parse/shortstat-pattern/shortstat-pattern.ts@@ -0,0 +1,11 @@+/**+ * `--shortstat`'s one line, ` 3 files changed, 10 insertions(+), 2+ * deletions(-)`, either tail optional; the counts captured by name.+ */+export const SHORTSTAT_PATTERN = new RegExp(+ [+ String.raw`(?<files>\d+) files? changed`,+ String.raw`(?:, (?<added>\d+) insertions?\(\+\))?`,+ String.raw`(?:, (?<removed>\d+) deletions?\(-\))?`,+ ].join(''),+)diff --git a/mods/diff/hooks/git/probes/branch-base-of/branch-base-of.ts b/mods/diff/hooks/git/probes/branch-base-of/branch-base-of.tsnew file mode 100644index 00000000..06dd410d--- /dev/null+++ b/mods/diff/hooks/git/probes/branch-base-of/branch-base-of.ts@@ -0,0 +1,72 @@+import Argv from '../../argv'+import type Types from '../../types'+import { currentBranchOf } from '../current-branch-of'+import { defaultBranchOf } from '../default-branch-of'+import { mergeBaseCandidatesOf } from '../merge-base-candidates-of'+import { missingBaseOf } from '../missing-base-of'++/**+ * What branch mode compares against, resolved as the built-in panel does:+ * the merge-base of HEAD and the default branch, HEAD itself, or none.+ *+ * `origin/<default>` wins unless the local ref's base descends from it; a+ * detached HEAD, a `-`-led default name or no common ancestor is `none`;+ * a failure that may pass (a ref still there, a failed rev-parse) `error`.+ *+ * @param run runs git+ * @returns the base+ */+export async function branchBaseOf(+ run: Types.GitRun,+): Promise<Types.BranchBase> {+ const [branch, defaultBranch] = await Promise.all([+ currentBranchOf(run),+ defaultBranchOf(run),+ ])+ const isUnrelated = branch === 'HEAD' || defaultBranch.startsWith('-')++ if (isUnrelated) {+ return { kind: 'none' }+ }++ if (branch === defaultBranch) {+ return { kind: 'head-is-base', baseBranch: defaultBranch }+ }++ const { candidates, hasNoCommonAncestor } = await mergeBaseCandidatesOf(+ run,+ defaultBranch,+ )+ const [first, second] = candidates++ if (first === undefined) {+ return hasNoCommonAncestor+ ? { kind: 'none' }+ : missingBaseOf(run, defaultBranch)+ }++ const isLocalBaseNewer =+ second !== undefined &&+ second !== first &&+ (+ await run([+ Argv.NO_OPTIONAL_LOCKS,+ 'merge-base',+ '--is-ancestor',+ first,+ second,+ ])+ ).exitCode === 0+ const mergeBase = isLocalBaseNewer ? second : first+ const head = await run([Argv.NO_OPTIONAL_LOCKS, 'rev-parse', 'HEAD'])++ if (head.exitCode !== 0) {+ return { kind: 'error', reason: 'head_rev_parse_failed' }+ }++ const isHeadTheBase = head.stdout.trim() === mergeBase++ return isHeadTheBase+ ? { kind: 'head-is-base', baseBranch: defaultBranch }+ : { kind: 'merge-base', mergeBase, baseBranch: defaultBranch }+}diff --git a/mods/diff/hooks/git/probes/branch-base-of/index.ts b/mods/diff/hooks/git/probes/branch-base-of/index.tsnew file mode 100644index 00000000..ababaf98--- /dev/null+++ b/mods/diff/hooks/git/probes/branch-base-of/index.ts@@ -0,0 +1,3 @@+export * from './branch-base-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/conventional-default-branches/conventional-default-branches.ts b/mods/diff/hooks/git/probes/conventional-default-branches/conventional-default-branches.tsnew file mode 100644index 00000000..1af3d267--- /dev/null+++ b/mods/diff/hooks/git/probes/conventional-default-branches/conventional-default-branches.ts@@ -0,0 +1,5 @@+/**+ * Tried in order as the default branch when `refs/remotes/origin/HEAD` names+ * none that resolves; past them the guess is `main`, as the engine's is.+ */+export const CONVENTIONAL_DEFAULT_BRANCHES = ['main', 'master'] as constdiff --git a/mods/diff/hooks/git/probes/conventional-default-branches/index.ts b/mods/diff/hooks/git/probes/conventional-default-branches/index.tsnew file mode 100644index 00000000..883c38a5--- /dev/null+++ b/mods/diff/hooks/git/probes/conventional-default-branches/index.ts@@ -0,0 +1,3 @@+export * from './conventional-default-branches.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/current-branch-of/current-branch-of.ts b/mods/diff/hooks/git/probes/current-branch-of/current-branch-of.tsnew file mode 100644index 00000000..db8b9f24--- /dev/null+++ b/mods/diff/hooks/git/probes/current-branch-of/current-branch-of.ts@@ -0,0 +1,20 @@+import Argv from '../../argv'+import type Types from '../../types'++/**+ * The checked-out branch's name, or `HEAD` when detached or unreadable.+ *+ * @param run runs git+ * @returns the branch name+ */+export async function currentBranchOf(run: Types.GitRun): Promise<string> {+ const { exitCode, stdout } = await run([+ Argv.NO_OPTIONAL_LOCKS,+ 'rev-parse',+ '--abbrev-ref',+ 'HEAD',+ ])+ const name = stdout.trim()++ return exitCode === 0 && name !== '' ? name : 'HEAD'+}diff --git a/mods/diff/hooks/git/probes/current-branch-of/index.ts b/mods/diff/hooks/git/probes/current-branch-of/index.tsnew file mode 100644index 00000000..cae908ba--- /dev/null+++ b/mods/diff/hooks/git/probes/current-branch-of/index.ts@@ -0,0 +1,3 @@+export * from './current-branch-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/datings-of/datings-of.ts b/mods/diff/hooks/git/probes/datings-of/datings-of.tsnew file mode 100644index 00000000..64011af1--- /dev/null+++ b/mods/diff/hooks/git/probes/datings-of/datings-of.ts@@ -0,0 +1,37 @@+import type Types from '../../types'+import { stampIfFile } from '../stamp-if-file'++/**+ * When each path was last modified against the session's start, dating a+ * path only when it is a real file under real directories at every level.+ *+ * Listings report an entry's own kind, so a symbolic link anywhere on the+ * path is never listed, descended or stat'ed: session work (the engine+ * lstats); a path the listing budget never reached is the caller's to place.+ *+ * @param probe the fetch's stamp probe over the working tree's top+ * @param sessionStartMs when the session began+ * @param paths repository-relative paths, `/`-separated as git prints them+ * @returns each path's Dating+ */+export async function datingsOf(+ probe: Types.StampProbe,+ sessionStartMs: number,+ paths: readonly string[],+): Promise<ReadonlyMap<string, Types.Dating>> {+ const stamps: readonly Types.Stamp[] = await Promise.all(+ paths.map(path => stampIfFile(probe, path)),+ )++ function datingOf(stamp: Types.Stamp): Types.Dating {+ if (stamp === 'over-budget') {+ return 'unlisted'+ }++ const isEarlier = (stamp ?? Number.POSITIVE_INFINITY) < sessionStartMs++ return isEarlier ? 'pre-session' : 'session'+ }++ return new Map(paths.map((path, at) => [path, datingOf(stamps[at] ?? null)]))+}diff --git a/mods/diff/hooks/git/probes/datings-of/index.ts b/mods/diff/hooks/git/probes/datings-of/index.tsnew file mode 100644index 00000000..370c3cfd--- /dev/null+++ b/mods/diff/hooks/git/probes/datings-of/index.ts@@ -0,0 +1,3 @@+export * from './datings-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/default-branch-of/default-branch-of.ts b/mods/diff/hooks/git/probes/default-branch-of/default-branch-of.tsnew file mode 100644index 00000000..4b1fff97--- /dev/null+++ b/mods/diff/hooks/git/probes/default-branch-of/default-branch-of.ts@@ -0,0 +1,45 @@+import Argv from '../../argv'+import type Types from '../../types'+import { CONVENTIONAL_DEFAULT_BRANCHES } from '../conventional-default-branches'++/**+ * The remote's default branch: what `origin/HEAD` names while that ref+ * resolves, else the first conventional name with a remote ref, else main.+ *+ * The engine's own default-branch confidence ladder, over `$.process.run`.+ *+ * @param run runs git+ * @returns the branch name, never empty+ */+export async function defaultBranchOf(run: Types.GitRun): Promise<string> {+ const hasRemoteRef = async (branch: string): Promise<boolean> =>+ (+ await run([+ Argv.NO_OPTIONAL_LOCKS,+ 'show-ref',+ '--verify',+ '--quiet',+ `refs/remotes/origin/${branch}`,+ ])+ ).exitCode === 0+ const symref = await run([+ Argv.NO_OPTIONAL_LOCKS,+ 'symbolic-ref',+ '--short',+ 'refs/remotes/origin/HEAD',+ ])+ const named =+ symref.exitCode === 0 ? symref.stdout.trim().replace(/^origin\//, '') : ''++ if (named !== '' && (await hasRemoteRef(named))) {+ return named+ }++ for (const candidate of CONVENTIONAL_DEFAULT_BRANCHES) {+ if (await hasRemoteRef(candidate)) {+ return candidate+ }+ }++ return 'main'+}diff --git a/mods/diff/hooks/git/probes/default-branch-of/index.ts b/mods/diff/hooks/git/probes/default-branch-of/index.tsnew file mode 100644index 00000000..bfb45edb--- /dev/null+++ b/mods/diff/hooks/git/probes/default-branch-of/index.ts@@ -0,0 +1,3 @@+export * from './default-branch-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/head-key-of/head-key-of.ts b/mods/diff/hooks/git/probes/head-key-of/head-key-of.tsnew file mode 100644index 00000000..ff381415--- /dev/null+++ b/mods/diff/hooks/git/probes/head-key-of/head-key-of.ts@@ -0,0 +1,64 @@+import Limits from '../../../limits'+import Argv from '../../argv'+import type Types from '../../types'+import { isSafeRefName } from '../is-safe-ref-name'+import { stampIfFile } from '../stamp-if-file'+import { stampProbeOf } from '../stamp-probe-of'++/**+ * A string that changes when HEAD moves: HEAD's text and the timestamps+ * of HEAD, its ref file and packed-refs, each a listed real file.+ *+ * A HEAD that is not a plain file, or a `ref:` outside the safe refname+ * grammar, is read through `git rev-parse` instead and nothing is stat'ed;+ * every directory above a stat'ed file was listed as a real directory.+ *+ * @param deps git, listings, timestamps, a file read+ * @param repository the repository's directories+ * @returns the key for this tick+ */+export async function headKeyOf(+ deps: Types.HeadKeyDeps,+ repository: Types.Repository,+): Promise<string> {+ const own = stampProbeOf(+ deps,+ repository.gitDir,+ Limits.MAX_LISTED_DIRECTORIES,+ )+ const isShared = repository.commonDir === repository.gitDir+ const common = isShared+ ? own+ : stampProbeOf(deps, repository.commonDir, Limits.MAX_LISTED_DIRECTORIES)++ async function viaGit() {+ const parsed = await deps.run([+ Argv.NO_OPTIONAL_LOCKS,+ 'rev-parse',+ '--verify',+ '--quiet',+ 'HEAD',+ ])++ return `rev:${parsed.exitCode === 0 ? parsed.stdout.trim() : ''}`+ }++ if ((await own.walk.kindOf('HEAD')) !== 'file') {+ return viaGit()+ }++ const head = await deps.readFile(`${repository.gitDir}/HEAD`).catch(() => '')+ const ref = head.startsWith('ref: ') ? head.slice('ref: '.length).trim() : ''+ const isSymbolic = ref !== ''++ const isUnsafeRef = isSymbolic && !isSafeRefName(ref)++ return isUnsafeRef+ ? viaGit()+ : [+ head,+ await stampIfFile(own, 'HEAD'),+ isSymbolic ? await stampIfFile(common, ref) : null,+ await stampIfFile(common, 'packed-refs'),+ ].join('|')+}diff --git a/mods/diff/hooks/git/probes/head-key-of/index.ts b/mods/diff/hooks/git/probes/head-key-of/index.tsnew file mode 100644index 00000000..52ac966e--- /dev/null+++ b/mods/diff/hooks/git/probes/head-key-of/index.ts@@ -0,0 +1,3 @@+export * from './head-key-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/index.ts b/mods/diff/hooks/git/probes/index.tsnew file mode 100644index 00000000..3e00acfa--- /dev/null+++ b/mods/diff/hooks/git/probes/index.ts@@ -0,0 +1,27 @@+export * from './branch-base-of'+export * from './conventional-default-branches'+export * from './current-branch-of'+export * from './datings-of'+export * from './default-branch-of'+export * from './head-key-of'+export * from './is-absolute-path'+export * from './is-safe-ref-name'+export * from './is-sha'+export * from './is-transient.js'+export * from './is-unborn-head.js'+export * from './kind-walk-of'+export * from './merge-base-candidates-of'+export * from './missing-base-of'+export * from './overlay-unstaged.js'+export * from './repository-lines'+export * from './repository-of'+export * from './stamp-if-file'+export * from './stamp-probe-of'+export * from './stats-of.js'+export * from './tag-pre-session.js'+export * from './transient-state-files'+export * from './unstaged-numstat.js'+export * from './untracked-files'+export * from './untracked-place'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/is-absolute-path/index.ts b/mods/diff/hooks/git/probes/is-absolute-path/index.tsnew file mode 100644index 00000000..d9cd599e--- /dev/null+++ b/mods/diff/hooks/git/probes/is-absolute-path/index.ts@@ -0,0 +1,3 @@+export * from './is-absolute-path.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/is-absolute-path/is-absolute-path.ts b/mods/diff/hooks/git/probes/is-absolute-path/is-absolute-path.tsnew file mode 100644index 00000000..de7e4363--- /dev/null+++ b/mods/diff/hooks/git/probes/is-absolute-path/is-absolute-path.ts@@ -0,0 +1,9 @@+/**+ * Whether a line `rev-parse --path-format=absolute` printed is an absolute+ * path (POSIX or drive-letter), and so neither relative nor an echoed flag.+ *+ * @param line one line of rev-parse output+ * @returns whether it names an absolute path+ */+export const isAbsolutePath = (line: string) =>+ line.startsWith('/') || /^[A-Za-z]:[\\/]/.test(line)diff --git a/mods/diff/hooks/git/probes/is-safe-ref-name/index.ts b/mods/diff/hooks/git/probes/is-safe-ref-name/index.tsnew file mode 100644index 00000000..be3dc8d9--- /dev/null+++ b/mods/diff/hooks/git/probes/is-safe-ref-name/index.ts@@ -0,0 +1,4 @@+export * from './is-safe-ref-name.js'+export * from './safe-ref-pattern'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/is-safe-ref-name/is-safe-ref-name.ts b/mods/diff/hooks/git/probes/is-safe-ref-name/is-safe-ref-name.tsnew file mode 100644index 00000000..708fc9da--- /dev/null+++ b/mods/diff/hooks/git/probes/is-safe-ref-name/is-safe-ref-name.ts@@ -0,0 +1,15 @@+import { SAFE_REF_PATTERN } from './safe-ref-pattern'++/**+ * Whether HEAD's `ref:` text names a ref the poll may stat: under `refs/`,+ * plain characters, no `..`, no component ending `.lock`.+ *+ * Git's refname rules, narrowed; anything else is read through git.+ *+ * @param ref the text after `ref: `+ * @returns whether the ref is safe to join under the common directory+ */+export const isSafeRefName = (ref: string) =>+ SAFE_REF_PATTERN.test(ref) &&+ !ref.includes('..') &&+ !ref.split('/').some(part => part.endsWith('.lock'))diff --git a/mods/diff/hooks/git/probes/is-safe-ref-name/safe-ref-pattern/index.ts b/mods/diff/hooks/git/probes/is-safe-ref-name/safe-ref-pattern/index.tsnew file mode 100644index 00000000..a9633570--- /dev/null+++ b/mods/diff/hooks/git/probes/is-safe-ref-name/safe-ref-pattern/index.ts@@ -0,0 +1,3 @@+export * from './safe-ref-pattern.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/is-safe-ref-name/safe-ref-pattern/safe-ref-pattern.ts b/mods/diff/hooks/git/probes/is-safe-ref-name/safe-ref-pattern/safe-ref-pattern.tsnew file mode 100644index 00000000..0137a3b1--- /dev/null+++ b/mods/diff/hooks/git/probes/is-safe-ref-name/safe-ref-pattern/safe-ref-pattern.ts@@ -0,0 +1,5 @@+/**+ * The refnames the HEAD poll will touch on disk: under `refs/`, of plain+ * name characters only, `/` between components.+ */+export const SAFE_REF_PATTERN = /^refs(?:\/[A-Za-z0-9_@+-][A-Za-z0-9._@+-]*)+$/diff --git a/mods/diff/hooks/git/probes/is-sha/index.ts b/mods/diff/hooks/git/probes/is-sha/index.tsnew file mode 100644index 00000000..0cbf1a6d--- /dev/null+++ b/mods/diff/hooks/git/probes/is-sha/index.ts@@ -0,0 +1,3 @@+export * from './is-sha.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/is-sha/is-sha.ts b/mods/diff/hooks/git/probes/is-sha/is-sha.tsnew file mode 100644index 00000000..773f3955--- /dev/null+++ b/mods/diff/hooks/git/probes/is-sha/is-sha.ts@@ -0,0 +1,9 @@+/**+ * Whether git printed an object name: 40 or 64 lowercase hex digits, the+ * only shape a merge-base may take before it reaches a `git diff` argv.+ *+ * @param text one trimmed line of git output+ * @returns whether it is a full object name+ */+export const isSha = (text: string) =>+ /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/.test(text)diff --git a/mods/diff/hooks/git/probes/is-transient.ts b/mods/diff/hooks/git/probes/is-transient.tsnew file mode 100644index 00000000..4fc7b437--- /dev/null+++ b/mods/diff/hooks/git/probes/is-transient.ts@@ -0,0 +1,22 @@+import type Types from '../types'+import { TRANSIENT_STATE_FILES } from './transient-state-files'++/**+ * Whether the repository is mid-merge, mid-rebase, mid-cherry-pick or+ * mid-revert, from one listing of the git directory.+ *+ * A state file counts only as a real file; a symbolic link by that name is+ * never touched.+ *+ * @param entryKindsOf the host's directory listing+ * @param gitDir the repository's own git directory, absolute+ * @returns whether any of TRANSIENT_STATE_FILES is present as a file+ */+export async function isTransient(+ entryKindsOf: Types.GitDeps['entryKindsOf'],+ gitDir: string,+): Promise<boolean> {+ const entries = await entryKindsOf(gitDir)++ return TRANSIENT_STATE_FILES.some(file => entries?.get(file) === 'file')+}diff --git a/mods/diff/hooks/git/probes/is-unborn-head.ts b/mods/diff/hooks/git/probes/is-unborn-head.tsnew file mode 100644index 00000000..098ce5fc--- /dev/null+++ b/mods/diff/hooks/git/probes/is-unborn-head.ts@@ -0,0 +1,24 @@+import Argv from '../argv'+import type Types from '../types'++/**+ * Whether HEAD is unborn (a repository before its first commit): only a+ * `rev-parse --verify HEAD` that ran and exited exactly 1 says so.+ *+ * A fatal repository error (128) or a killed probe proves nothing, as for+ * the built-in panel's no-commits probe.+ *+ * @param run runs git+ * @returns whether the probe exited 1+ */+export async function isUnbornHead(run: Types.GitRun): Promise<boolean> {+ const { exitCode } = await run([+ Argv.NO_OPTIONAL_LOCKS,+ 'rev-parse',+ '--verify',+ '--quiet',+ 'HEAD',+ ])++ return exitCode === 1+}diff --git a/mods/diff/hooks/git/probes/kind-walk-of/index.ts b/mods/diff/hooks/git/probes/kind-walk-of/index.tsnew file mode 100644index 00000000..bd5a1efb--- /dev/null+++ b/mods/diff/hooks/git/probes/kind-walk-of/index.ts@@ -0,0 +1,3 @@+export * from './kind-walk-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/kind-walk-of/kind-walk-of.ts b/mods/diff/hooks/git/probes/kind-walk-of/kind-walk-of.tsnew file mode 100644index 00000000..7e22c019--- /dev/null+++ b/mods/diff/hooks/git/probes/kind-walk-of/kind-walk-of.ts@@ -0,0 +1,70 @@+import type Types from '../../types'++/**+ * A KindWalk: each directory is listed once, only after its own entry+ * read as `dir` in its parent, and only while listings remain.+ *+ * Read from the root down, one listing a component: the depth is the+ * budget's, never the stack's. A symbolic link is never listed or descended+ * and what lies under it reads as null; the unlisted reads `over-budget`.+ *+ * @param entryKindsOf the host's directory listing+ * @param root the absolute directory the walk's paths are relative to+ * @param budget how many directories this walk may list+ * @returns the walk+ */+export function kindWalkOf(+ entryKindsOf: Types.GitDeps['entryKindsOf'],+ root: string,+ budget: number,+): Types.KindWalk {+ const listings = new Map<+ string,+ Promise<ReadonlyMap<string, Types.EntryKind> | null>+ >()++ function listingOf(directory: string) {+ const held = listings.get(directory)+ const isOverBudget = held === undefined && listings.size >= budget++ if (isOverBudget) {+ return 'over-budget'+ }++ const listed =+ held ?? entryKindsOf(directory === '' ? root : `${root}/${directory}`)+ listings.set(directory, listed)++ return listed+ }++ async function kindOf(path: string): Promise<Types.WalkKind> {+ const names = path === '' ? [] : path.split('/')+ let directory = ''++ for (const [depth, name] of names.entries()) {+ const listing = listingOf(directory)++ if (listing === 'over-budget') {+ return 'over-budget'+ }++ const kind = (await listing)?.get(name) ?? null+ const isLeaf = depth === names.length - 1++ if (isLeaf) {+ return kind+ }++ if (kind !== 'dir') {+ return null+ }++ directory = directory === '' ? name : `${directory}/${name}`+ }++ return 'dir'+ }++ return { kindOf }+}diff --git a/mods/diff/hooks/git/probes/merge-base-candidates-of/index.ts b/mods/diff/hooks/git/probes/merge-base-candidates-of/index.tsnew file mode 100644index 00000000..777dcb01--- /dev/null+++ b/mods/diff/hooks/git/probes/merge-base-candidates-of/index.ts@@ -0,0 +1,4 @@+export * from './merge-base-candidates'+export * from './merge-base-candidates-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/merge-base-candidates-of/merge-base-candidates-of.ts b/mods/diff/hooks/git/probes/merge-base-candidates-of/merge-base-candidates-of.tsnew file mode 100644index 00000000..fbbe2feb--- /dev/null+++ b/mods/diff/hooks/git/probes/merge-base-candidates-of/merge-base-candidates-of.ts@@ -0,0 +1,38 @@+import Argv from '../../argv'+import type Types from '../../types'+import { isSha } from '../is-sha'+import type { MergeBaseCandidates } from './merge-base-candidates'++/**+ * The merge-bases of HEAD with `origin/<default>` and with `<default>`, in+ * that order, each present only when git printed an object name.+ *+ * Also whether any call ran and exited 1: no common ancestor, a stable+ * state rather than a failure.+ *+ * @param run runs git+ * @param defaultBranch the default branch's name+ * @returns the candidate object names and the no-ancestor flag+ */+export async function mergeBaseCandidatesOf(+ run: Types.GitRun,+ defaultBranch: string,+): Promise<MergeBaseCandidates> {+ const results = [+ await run([+ Argv.NO_OPTIONAL_LOCKS,+ 'merge-base',+ 'HEAD',+ `origin/${defaultBranch}`,+ ]),+ await run([Argv.NO_OPTIONAL_LOCKS, 'merge-base', 'HEAD', defaultBranch]),+ ]++ return {+ candidates: results+ .filter(result => result.exitCode === 0)+ .map(result => result.stdout.trim())+ .filter(isSha),+ hasNoCommonAncestor: results.some(result => result.exitCode === 1),+ }+}diff --git a/mods/diff/hooks/git/probes/merge-base-candidates-of/merge-base-candidates/index.ts b/mods/diff/hooks/git/probes/merge-base-candidates-of/merge-base-candidates/index.tsnew file mode 100644index 00000000..7f1b58ab--- /dev/null+++ b/mods/diff/hooks/git/probes/merge-base-candidates-of/merge-base-candidates/index.ts@@ -0,0 +1,3 @@+export type * from './merge-base-candidates.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/merge-base-candidates-of/merge-base-candidates/merge-base-candidates.ts b/mods/diff/hooks/git/probes/merge-base-candidates-of/merge-base-candidates/merge-base-candidates.tsnew file mode 100644index 00000000..9ed1044e--- /dev/null+++ b/mods/diff/hooks/git/probes/merge-base-candidates-of/merge-base-candidates/merge-base-candidates.ts@@ -0,0 +1,8 @@+/**+ * What the two merge-base calls yielded: the object names printed, in+ * call order, and whether either ran to a no-common-ancestor exit.+ */+export type MergeBaseCandidates = {+ candidates: readonly string[]+ hasNoCommonAncestor: boolean+}diff --git a/mods/diff/hooks/git/probes/missing-base-of/index.ts b/mods/diff/hooks/git/probes/missing-base-of/index.tsnew file mode 100644index 00000000..9bb88e78--- /dev/null+++ b/mods/diff/hooks/git/probes/missing-base-of/index.ts@@ -0,0 +1,3 @@+export * from './missing-base-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/missing-base-of/missing-base-of.ts b/mods/diff/hooks/git/probes/missing-base-of/missing-base-of.tsnew file mode 100644index 00000000..fea8f2c1--- /dev/null+++ b/mods/diff/hooks/git/probes/missing-base-of/missing-base-of.ts@@ -0,0 +1,38 @@+import Argv from '../../argv'+import type Types from '../../types'++/**+ * The verdict for a merge-base that produced nothing: `none` when neither+ * ref of the default branch exists, else `error`.+ *+ * Only a probe that ran and exited non-zero is an authoritative miss; one+ * that answered 0 or never ran means the merge-base failure may pass.+ *+ * @param run runs git+ * @param defaultBranch the default branch's name+ * @returns `none` or `error`+ */+export async function missingBaseOf(+ run: Types.GitRun,+ defaultBranch: string,+): Promise<Types.BranchBase> {+ for (const ref of [+ `refs/remotes/origin/${defaultBranch}`,+ `refs/heads/${defaultBranch}`,+ ]) {+ const { exitCode } = await run([+ Argv.NO_OPTIONAL_LOCKS,+ 'show-ref',+ '--verify',+ '--quiet',+ ref,+ ])+ const isPresentOrUnknown = exitCode === 0 || exitCode === -1++ if (isPresentOrUnknown) {+ return { kind: 'error', reason: 'merge_base_failed' }+ }+ }++ return { kind: 'none' }+}diff --git a/mods/diff/hooks/git/probes/overlay-unstaged.ts b/mods/diff/hooks/git/probes/overlay-unstaged.tsnew file mode 100644index 00000000..53044117--- /dev/null+++ b/mods/diff/hooks/git/probes/overlay-unstaged.ts@@ -0,0 +1,41 @@+import type Types from '../types'++/**+ * The staged rows of an unborn HEAD with the working tree's unstaged edits+ * folded in, as the built-in panel overlays them.+ *+ * Against the empty tree every surviving line is an addition: a path in+ * both diffs shows added = staged + unstaged added − unstaged removed+ * (never below 0), removed stays 0, and the added total moves with it.+ *+ * @param staged `git diff --cached --numstat`, capped+ * @param unstaged plain `git diff --numstat`, uncapped+ * @returns the staged result with corrected rows and totals+ */+export function overlayUnstaged(+ staged: Types.NumstatResult,+ unstaged: Types.NumstatResult,+): Types.NumstatResult {+ const edits = new Map(unstaged.files.map(file => [file.path, file]))+ const files = staged.files.map(file => {+ const edit = edits.get(file.path)++ if (!edit) {+ return file+ }++ const isBinary = file.isBinary || edit.isBinary+ const added = isBinary+ ? 0+ : Math.max(0, file.added + edit.added - edit.removed)++ return { ...file, added, removed: 0, isBinary }+ })+ const linesAdded =+ staged.stats.linesAdded ++ files.reduce((sum, file) => sum + file.added, 0) -+ staged.files.reduce((sum, file) => sum + file.added, 0)+ const stats = { ...staged.stats, linesAdded }++ return { stats, files }+}diff --git a/mods/diff/hooks/git/probes/repository-lines/index.ts b/mods/diff/hooks/git/probes/repository-lines/index.tsnew file mode 100644index 00000000..47f95bf9--- /dev/null+++ b/mods/diff/hooks/git/probes/repository-lines/index.ts@@ -0,0 +1,3 @@+export * from './repository-lines.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/repository-lines/repository-lines.ts b/mods/diff/hooks/git/probes/repository-lines/repository-lines.tsnew file mode 100644index 00000000..15ee0548--- /dev/null+++ b/mods/diff/hooks/git/probes/repository-lines/repository-lines.ts@@ -0,0 +1,5 @@+/**+ * How many lines the repository probe's `rev-parse` answers when git+ * understood every option: top level, git directory, common directory.+ */+export const REPOSITORY_LINES = 3diff --git a/mods/diff/hooks/git/probes/repository-of/index.ts b/mods/diff/hooks/git/probes/repository-of/index.tsnew file mode 100644index 00000000..3a5a77e7--- /dev/null+++ b/mods/diff/hooks/git/probes/repository-of/index.ts@@ -0,0 +1,3 @@+export * from './repository-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/repository-of/repository-of.ts b/mods/diff/hooks/git/probes/repository-of/repository-of.tsnew file mode 100644index 00000000..a809ff6c--- /dev/null+++ b/mods/diff/hooks/git/probes/repository-of/repository-of.ts@@ -0,0 +1,36 @@+import Argv from '../../argv'+import type Types from '../../types'+import { isAbsolutePath } from '../is-absolute-path'+import { REPOSITORY_LINES } from '../repository-lines'++/**+ * The repository the session's directory is in, read with one `rev-parse`:+ * working tree top, git directory, common directory, all absolute.+ *+ * Exactly three absolute lines or nothing: a git too old for+ * `--path-format` echoes the flag as a line of its own, and such an answer+ * pins no repository rather than a wrong one.+ *+ * @param run runs git in the session's directory, nothing pinned yet+ * @returns the three absolute paths, or null outside a working tree+ */+export async function repositoryOf(+ run: Types.GitRun,+): Promise<Types.Repository | null> {+ const { exitCode, stdout } = await run([+ Argv.NO_OPTIONAL_LOCKS,+ 'rev-parse',+ '--path-format=absolute',+ '--show-toplevel',+ '--git-dir',+ '--git-common-dir',+ ])+ const lines = stdout.split('\n').filter(line => line !== '')+ const [toplevel = '', gitDir = '', commonDir = ''] = lines+ const isResolved =+ exitCode === 0 &&+ lines.length === REPOSITORY_LINES &&+ lines.every(isAbsolutePath)++ return isResolved ? { toplevel, gitDir, commonDir } : null+}diff --git a/mods/diff/hooks/git/probes/stamp-if-file/index.ts b/mods/diff/hooks/git/probes/stamp-if-file/index.tsnew file mode 100644index 00000000..35623ede--- /dev/null+++ b/mods/diff/hooks/git/probes/stamp-if-file/index.ts@@ -0,0 +1,3 @@+export * from './stamp-if-file.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/stamp-if-file/stamp-if-file.ts b/mods/diff/hooks/git/probes/stamp-if-file/stamp-if-file.tsnew file mode 100644index 00000000..9ad1c53b--- /dev/null+++ b/mods/diff/hooks/git/probes/stamp-if-file/stamp-if-file.ts@@ -0,0 +1,29 @@+import type Types from '../../types'++/**+ * A path's modification time when the walk shows it as a real entry of the+ * wanted kind under real directories; otherwise nothing is stat'ed.+ *+ * A path git printed with a trailing `/` (an untracked directory, a nested+ * repository) names a directory and is dated as one.+ *+ * @param probe the walk over the base directory and the timestamp probe+ * @param path the path relative to the walk's root+ * @returns the timestamp, `over-budget`, or null+ */+export async function stampIfFile(+ probe: Types.StampProbe,+ path: string,+): Promise<Types.Stamp> {+ const isDirectory = path.endsWith('/')+ const entry = isDirectory ? path.slice(0, -1) : path+ const kind = await probe.walk.kindOf(entry)+ const isUnlisted = kind === 'over-budget'+ const isWanted = kind === (isDirectory ? 'dir' : 'file')++ return isUnlisted+ ? 'over-budget'+ : isWanted+ ? probe.mtimeOf(`${probe.base}/${entry}`)+ : null+}diff --git a/mods/diff/hooks/git/probes/stamp-probe-of/index.ts b/mods/diff/hooks/git/probes/stamp-probe-of/index.tsnew file mode 100644index 00000000..15094899--- /dev/null+++ b/mods/diff/hooks/git/probes/stamp-probe-of/index.ts@@ -0,0 +1,3 @@+export * from './stamp-probe-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/stamp-probe-of/stamp-probe-of.ts b/mods/diff/hooks/git/probes/stamp-probe-of/stamp-probe-of.tsnew file mode 100644index 00000000..03cd0052--- /dev/null+++ b/mods/diff/hooks/git/probes/stamp-probe-of/stamp-probe-of.ts@@ -0,0 +1,21 @@+import type Types from '../../types'+import { kindWalkOf } from '../kind-walk-of'++/**+ * A StampProbe rooted at a directory: a fresh, bounded kind walk over it+ * and the host's timestamp probe.+ *+ * @param deps lists a directory, reads a timestamp+ * @param base the absolute directory the probe's paths are under+ * @param budget how many directories the walk may list+ * @returns the probe+ */+export const stampProbeOf = (+ deps: Pick<Types.GitDeps, 'entryKindsOf' | 'mtimeOf'>,+ base: string,+ budget: number,+): Types.StampProbe => ({+ walk: kindWalkOf(deps.entryKindsOf, base, budget),+ base,+ mtimeOf: deps.mtimeOf,+})diff --git a/mods/diff/hooks/git/probes/stats-of.ts b/mods/diff/hooks/git/probes/stats-of.tsnew file mode 100644index 00000000..4ec63068--- /dev/null+++ b/mods/diff/hooks/git/probes/stats-of.ts@@ -0,0 +1,42 @@+import Limits from '../../limits'+import Argv from '../argv'+import GitParse from '../parse'+import type Types from '../types'++/**+ * The rows and totals of `git diff <base>`, or null when git could not+ * say (as the built-in panel's stats fetch) or its listing arrived cut.+ *+ * A `--shortstat` probe runs first, so a diff past MAX_FILES_FOR_DETAILS+ * answers its totals with no rows and no `--numstat` buffering.+ *+ * @param context runs git+ * @param base the ref (or `--cached`) the working tree is compared with+ * @returns the parsed result, or null on a failed numstat+ */+export async function statsOf(+ context: Types.FetchContext,+ base: string,+): Promise<Types.NumstatResult | null> {+ const run = context.run++ const shortstat = await run([...Argv.DIFF_LEADING_ARGS, base, '--shortstat'])+ const totals =+ shortstat.exitCode === 0 ? GitParse.parseShortstat(shortstat.stdout) : null+ const isPastDetails =+ totals !== null && totals.filesCount > Limits.MAX_FILES_FOR_DETAILS++ if (isPastDetails) {+ return { stats: totals, files: [] }+ }++ const numstat = await run([+ ...Argv.DIFF_LEADING_ARGS,+ base,+ '--numstat',+ '-z',+ ])+ const isRead = GitParse.isWholeAnswer(numstat)++ return isRead ? GitParse.parseNumstat(numstat.stdout, Limits.MAX_FILES) : null+}diff --git a/mods/diff/hooks/git/probes/tag-pre-session.ts b/mods/diff/hooks/git/probes/tag-pre-session.tsnew file mode 100644index 00000000..baf39afb--- /dev/null+++ b/mods/diff/hooks/git/probes/tag-pre-session.ts@@ -0,0 +1,29 @@+import type Types from '../types'+import { datingsOf } from './datings-of'++/**+ * The tracked rows, `isPreSession` set on each whose file was modified+ * before the session began, by mtime alone as the built-in panel tags them.+ *+ * A file that cannot be dated (deleted this session, a symbolic link, past+ * the listing budget) stays session work, so nothing real is hidden.+ *+ * @param context the fetch: its stamp probe and the session's start+ * @param files the tracked rows+ * @returns the rows, tagged+ */+export async function tagPreSession(+ context: Pick<Types.FetchContext, 'deps' | 'stamps'>,+ files: readonly Types.FileStat[],+): Promise<readonly Types.FileStat[]> {+ const datings = await datingsOf(+ context.stamps,+ context.deps.sessionStartMs,+ files.map(file => file.path),+ )++ return files.map(file => ({+ ...file,+ isPreSession: datings.get(file.path) === 'pre-session',+ }))+}diff --git a/mods/diff/hooks/git/probes/transient-state-files/index.ts b/mods/diff/hooks/git/probes/transient-state-files/index.tsnew file mode 100644index 00000000..bbf7938f--- /dev/null+++ b/mods/diff/hooks/git/probes/transient-state-files/index.ts@@ -0,0 +1,3 @@+export * from './transient-state-files.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/transient-state-files/transient-state-files.ts b/mods/diff/hooks/git/probes/transient-state-files/transient-state-files.tsnew file mode 100644index 00000000..5e601f8c--- /dev/null+++ b/mods/diff/hooks/git/probes/transient-state-files/transient-state-files.ts@@ -0,0 +1,10 @@+/**+ * The git-directory files that mean a merge, rebase, cherry-pick or revert+ * is under way: the working tree then holds incoming changes, unread.+ */+export const TRANSIENT_STATE_FILES = [+ 'MERGE_HEAD',+ 'REBASE_HEAD',+ 'CHERRY_PICK_HEAD',+ 'REVERT_HEAD',+] as constdiff --git a/mods/diff/hooks/git/probes/unstaged-numstat.ts b/mods/diff/hooks/git/probes/unstaged-numstat.tsnew file mode 100644index 00000000..b2686def--- /dev/null+++ b/mods/diff/hooks/git/probes/unstaged-numstat.ts@@ -0,0 +1,23 @@+import Argv from '../argv'+import GitParse from '../parse'+import type Types from '../types'++/**+ * Plain `git diff --numstat` (index against working tree), the one diff+ * beside `--cached` that runs on an unborn HEAD; null on failure or a cut.+ *+ * Parsed uncapped, since its rows correct rows already kept.+ *+ * @param run runs git+ * @returns every row, or null when git failed+ */+export async function unstagedNumstat(+ run: Types.GitRun,+): Promise<Types.NumstatResult | null> {+ const numstat = await run([...Argv.DIFF_LEADING_ARGS, '--numstat', '-z'])+ const isRead = GitParse.isWholeAnswer(numstat)++ return isRead+ ? GitParse.parseNumstat(numstat.stdout, Number.POSITIVE_INFINITY)+ : null+}diff --git a/mods/diff/hooks/git/probes/untracked-files/index.ts b/mods/diff/hooks/git/probes/untracked-files/index.tsnew file mode 100644index 00000000..addc27ea--- /dev/null+++ b/mods/diff/hooks/git/probes/untracked-files/index.ts@@ -0,0 +1,3 @@+export * from './untracked-files.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/untracked-files/untracked-files.ts b/mods/diff/hooks/git/probes/untracked-files/untracked-files.tsnew file mode 100644index 00000000..3f8ca084--- /dev/null+++ b/mods/diff/hooks/git/probes/untracked-files/untracked-files.ts@@ -0,0 +1,73 @@+import Limits from '../../../limits'+import Argv from '../../argv'+import GitParse from '../../parse'+import type Types from '../../types'+import { datingsOf } from '../datings-of'+import type { UntrackedPlace } from '../untracked-place'++/**+ * The untracked, unignored files as 0/0 rows: the session's own first,+ * then, when the scope asks, the tagged pre-session ones, up to the slots.+ *+ * At most MAX_UNTRACKED_PROBES are dated; a file past that or past the+ * listing budget reads as pre-session, an undatable one as the session's+ * (the built-in panel's rule). A listing not given whole: no answer.+ *+ * @param context the fetch: its pinned git, stamp probe and session start+ * @param place the free row slots and the scope+ * @returns the rows to merge after the tracked ones, or null when the+ * `-z` listing failed, timed out or was cut+ */+export async function untrackedFiles(+ context: Pick<Types.FetchContext, 'run' | 'deps' | 'stamps'>,+ place: UntrackedPlace,+): Promise<readonly Types.FileStat[] | null> {+ if (place.slots <= 0) {+ return []+ }++ const listing = await context.run([+ Argv.NO_OPTIONAL_LOCKS,+ 'ls-files',+ '-z',+ '--others',+ '--exclude-standard',+ '--full-name',+ ])++ if (!GitParse.isWholeAnswer(listing)) {+ return null+ }++ const paths = listing.stdout.split('\0').filter(path => path !== '')+ const probedPaths = paths.slice(0, Limits.MAX_UNTRACKED_PROBES)+ const datings = await datingsOf(+ context.stamps,+ context.deps.sessionStartMs,+ probedPaths,+ )+ const probed = probedPaths.map(path => ({+ path,+ isPreSession: datings.get(path) !== 'session',+ }))+ const isWithPreSession = place.scope === 'with-pre-session'+ const earlier = isWithPreSession+ ? [+ ...probed.filter(file => file.isPreSession),+ ...paths+ .slice(Limits.MAX_UNTRACKED_PROBES)+ .map(path => ({ path, isPreSession: true })),+ ]+ : []+ const ordered = [...probed.filter(file => !file.isPreSession), ...earlier]++ return ordered.slice(0, place.slots).map(file => ({+ path: file.path,+ renamedFrom: null,+ added: 0,+ removed: 0,+ isBinary: false,+ isUntracked: true,+ isPreSession: file.isPreSession,+ }))+}diff --git a/mods/diff/hooks/git/probes/untracked-place/index.ts b/mods/diff/hooks/git/probes/untracked-place/index.tsnew file mode 100644index 00000000..1b89a40e--- /dev/null+++ b/mods/diff/hooks/git/probes/untracked-place/index.ts@@ -0,0 +1,3 @@+export type * from './untracked-place.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/probes/untracked-place/untracked-place.ts b/mods/diff/hooks/git/probes/untracked-place/untracked-place.tsnew file mode 100644index 00000000..a53586a5--- /dev/null+++ b/mods/diff/hooks/git/probes/untracked-place/untracked-place.ts@@ -0,0 +1,10 @@+import type Types from '../../types'++/**+ * How much untrackedFiles may keep: the row slots left under MAX_FILES, and+ * which files count.+ */+export type UntrackedPlace = {+ slots: number+ scope: Types.UntrackedScope+}diff --git a/mods/diff/hooks/git/tiers/branch-source-of/branch-source-of.ts b/mods/diff/hooks/git/tiers/branch-source-of/branch-source-of.tsnew file mode 100644index 00000000..8351edee--- /dev/null+++ b/mods/diff/hooks/git/tiers/branch-source-of/branch-source-of.ts@@ -0,0 +1,25 @@+import type Types from '../../types'++/**+ * What branch mode's diff compares, given its resolved base: the merge+ * base, HEAD under the default branch's label, or the plain working tree.+ *+ * @param base the resolved base+ * @returns the source the rows are labelled with+ */+export function branchSourceOf(+ base: Types.ResolvedBranchBase,+): Types.DiffSource {+ switch (base.kind) {+ case 'merge-base':+ return {+ kind: 'branch',+ baseBranch: base.baseBranch,+ baseRef: base.mergeBase,+ }+ case 'head-is-base':+ return { kind: 'branch', baseBranch: base.baseBranch, baseRef: 'HEAD' }+ case 'none':+ return { kind: 'working-tree' }+ }+}diff --git a/mods/diff/hooks/git/tiers/branch-source-of/index.ts b/mods/diff/hooks/git/tiers/branch-source-of/index.tsnew file mode 100644index 00000000..3e05a93f--- /dev/null+++ b/mods/diff/hooks/git/tiers/branch-source-of/index.ts@@ -0,0 +1,3 @@+export * from './branch-source-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/tiers/branch-tier.ts b/mods/diff/hooks/git/tiers/branch-tier.tsnew file mode 100644index 00000000..fed4adab--- /dev/null+++ b/mods/diff/hooks/git/tiers/branch-tier.ts@@ -0,0 +1,56 @@+import Probes from '../probes'+import type Types from '../types'+import { branchSourceOf } from './branch-source-of'+import { diffDataOf } from './diff-data-of'+import { unbornTier } from './unborn-tier'+import { withUntracked } from './with-untracked'++/**+ * Branch mode: everything that differs from the default branch, the merge+ * base against the working tree, pinned, as the built-in panel diffs it.+ *+ * With HEAD at the base the diff is HEAD's under the vs-<default> label;+ * with no base it is labelled a plain working-tree diff; a base that may+ * resolve next time answers unavailable so the last branch view stays.+ *+ * @param context the fetch+ * @returns the outcome+ */+export async function branchTier(+ context: Types.FetchContext,+): Promise<Types.FetchOutcome> {+ const { deps, run } = context+ const base = await Probes.branchBaseOf(run)+ deps.onBranchBase(base)++ if (base.kind === 'error') {+ return unbornTier(context)+ }++ const source = branchSourceOf(base)+ const baseRef = source.kind === 'branch' ? source.baseRef : 'HEAD'+ const diff = await Probes.statsOf(context, baseRef)+ const isTransientFailure = diff === null && base.kind === 'merge-base'++ if (isTransientFailure) {+ return { kind: 'unavailable' }+ }++ if (!diff) {+ return unbornTier(context)+ }++ return {+ kind: 'data',+ data: diffDataOf(+ context,+ await withUntracked(context, diff, 'session-only'),+ {+ source,+ baseRef,+ isUnborn: false,+ stalePaths: [],+ },+ ),+ }+}diff --git a/mods/diff/hooks/git/tiers/diff-data-of/diff-basis/diff-basis.ts b/mods/diff/hooks/git/tiers/diff-data-of/diff-basis/diff-basis.tsnew file mode 100644index 00000000..c3284f3a--- /dev/null+++ b/mods/diff/hooks/git/tiers/diff-data-of/diff-basis/diff-basis.ts@@ -0,0 +1,12 @@+import type Types from '../../../types'++/**+ * What a tier decided about its diff besides the rows: what it compares,+ * the ref the hunks read against, whether HEAD is unborn, stale bodies.+ */+export type DiffBasis = {+ source: Types.DiffSource+ baseRef: string+ isUnborn: boolean+ stalePaths: readonly string[]+}diff --git a/mods/diff/hooks/git/tiers/diff-data-of/diff-basis/index.ts b/mods/diff/hooks/git/tiers/diff-data-of/diff-basis/index.tsnew file mode 100644index 00000000..5311782e--- /dev/null+++ b/mods/diff/hooks/git/tiers/diff-data-of/diff-basis/index.ts@@ -0,0 +1,3 @@+export type * from './diff-basis.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/tiers/diff-data-of/diff-data-of.ts b/mods/diff/hooks/git/tiers/diff-data-of/diff-data-of.tsnew file mode 100644index 00000000..57f42d24--- /dev/null+++ b/mods/diff/hooks/git/tiers/diff-data-of/diff-data-of.ts@@ -0,0 +1,27 @@+import type Types from '../../types'+import type { DiffBasis } from './diff-basis'++/**+ * A settled fetch: the tier's merged rows and totals over the repository+ * and mode of the fetch, with the tier's basis.+ *+ * @param context the fetch+ * @param result the rows and totals, untracked files merged or withheld+ * @param basis what they compare and read against+ * @returns the data an outcome carries+ */+export const diffDataOf = (+ context: Types.FetchContext,+ result: Types.MergedResult,+ basis: DiffBasis,+): Types.DiffData => ({+ repository: context.repository,+ mode: context.mode,+ stats: result.stats,+ files: result.files,+ source: basis.source,+ baseRef: basis.baseRef,+ isUnborn: basis.isUnborn,+ stalePaths: basis.stalePaths,+ isUntrackedWithheld: result.isUntrackedWithheld,+})diff --git a/mods/diff/hooks/git/tiers/diff-data-of/index.ts b/mods/diff/hooks/git/tiers/diff-data-of/index.tsnew file mode 100644index 00000000..98736de9--- /dev/null+++ b/mods/diff/hooks/git/tiers/diff-data-of/index.ts@@ -0,0 +1,4 @@+export * from './diff-basis'+export * from './diff-data-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/tiers/fetch-context-of/fetch-context-of.ts b/mods/diff/hooks/git/tiers/fetch-context-of/fetch-context-of.tsnew file mode 100644index 00000000..74a85744--- /dev/null+++ b/mods/diff/hooks/git/tiers/fetch-context-of/fetch-context-of.ts@@ -0,0 +1,26 @@+import Limits from '../../../limits'+import Probes from '../../probes'+import type Types from '../../types'++/**+ * The context every tier of a fetch shares: the host's pinned git, the+ * repository, the mode, and one stamp probe over the working tree's top.+ *+ * @param deps the host+ * @param mode the comparison asked for+ * @returns the context+ */+export const fetchContextOf = (+ deps: Types.GitDeps,+ mode: Types.BaseMode,+): Types.FetchContext => ({+ deps,+ run: deps.run,+ repository: deps.repository,+ mode,+ stamps: Probes.stampProbeOf(+ deps,+ deps.repository.toplevel,+ Limits.MAX_LISTED_DIRECTORIES,+ ),+})diff --git a/mods/diff/hooks/git/tiers/fetch-context-of/index.ts b/mods/diff/hooks/git/tiers/fetch-context-of/index.tsnew file mode 100644index 00000000..868c2c29--- /dev/null+++ b/mods/diff/hooks/git/tiers/fetch-context-of/index.ts@@ -0,0 +1,3 @@+export * from './fetch-context-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/tiers/index.ts b/mods/diff/hooks/git/tiers/index.tsnew file mode 100644index 00000000..34d059b4--- /dev/null+++ b/mods/diff/hooks/git/tiers/index.ts@@ -0,0 +1,11 @@+export * from './branch-source-of'+export * from './branch-tier.js'+export * from './diff-data-of'+export * from './fetch-context-of'+export * from './is-past-details'+export * from './unborn-tier'+export * from './with-untracked'+export * from './working-tree-basis'+export * from './working-tree-tier.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/tiers/is-past-details/index.ts b/mods/diff/hooks/git/tiers/is-past-details/index.tsnew file mode 100644index 00000000..61d9811a--- /dev/null+++ b/mods/diff/hooks/git/tiers/is-past-details/index.ts@@ -0,0 +1,3 @@+export * from './is-past-details.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/tiers/is-past-details/is-past-details.ts b/mods/diff/hooks/git/tiers/is-past-details/is-past-details.tsnew file mode 100644index 00000000..7181ab49--- /dev/null+++ b/mods/diff/hooks/git/tiers/is-past-details/is-past-details.ts@@ -0,0 +1,12 @@+import Limits from '../../../limits'+import type Types from '../../types'++/**+ * Whether a diff has more files than get per-file rows: past+ * MAX_FILES_FOR_DETAILS only its totals are kept.+ *+ * @param result the parsed diff+ * @returns whether rows, hunks and the untracked probe are skipped+ */+export const isPastDetails = (result: Types.NumstatResult) =>+ result.stats.filesCount > Limits.MAX_FILES_FOR_DETAILSdiff --git a/mods/diff/hooks/git/tiers/unborn-tier/empty-numstat/empty-numstat.ts b/mods/diff/hooks/git/tiers/unborn-tier/empty-numstat/empty-numstat.tsnew file mode 100644index 00000000..c31260e1--- /dev/null+++ b/mods/diff/hooks/git/tiers/unborn-tier/empty-numstat/empty-numstat.ts@@ -0,0 +1,10 @@+import type Types from '../../../types'++/**+ * No rows and zero totals: what an unborn HEAD shows when even+ * `git diff --cached` could not be read.+ */+export const EMPTY_NUMSTAT: Types.NumstatResult = Object.freeze({+ stats: Object.freeze({ filesCount: 0, linesAdded: 0, linesRemoved: 0 }),+ files: Object.freeze([]),+})diff --git a/mods/diff/hooks/git/tiers/unborn-tier/empty-numstat/index.ts b/mods/diff/hooks/git/tiers/unborn-tier/empty-numstat/index.tsnew file mode 100644index 00000000..b14b1cca--- /dev/null+++ b/mods/diff/hooks/git/tiers/unborn-tier/empty-numstat/index.ts@@ -0,0 +1,3 @@+export * from './empty-numstat.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/tiers/unborn-tier/index.ts b/mods/diff/hooks/git/tiers/unborn-tier/index.tsnew file mode 100644index 00000000..6b3a769a--- /dev/null+++ b/mods/diff/hooks/git/tiers/unborn-tier/index.ts@@ -0,0 +1,4 @@+export * from './empty-numstat'+export * from './unborn-tier.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/tiers/unborn-tier/unborn-tier.ts b/mods/diff/hooks/git/tiers/unborn-tier/unborn-tier.tsnew file mode 100644index 00000000..db1695f8--- /dev/null+++ b/mods/diff/hooks/git/tiers/unborn-tier/unborn-tier.ts@@ -0,0 +1,57 @@+import Probes from '../../probes'+import type Types from '../../types'+import { diffDataOf } from '../diff-data-of'+import { withUntracked } from '../with-untracked'+import { EMPTY_NUMSTAT } from './empty-numstat'++/**+ * The one permanent cause of a failed vs-HEAD diff, told apart from the+ * passing ones: an unborn HEAD, as the built-in panel tells it apart.+ *+ * Its rows are the staged files with unstaged edits folded in, then the+ * session's untracked files; hunks read against `--cached`, a file edited+ * after staging has no honest body; a withheld `--numstat`: no data.+ *+ * @param context the fetch+ * @returns data marked unborn, or unavailable+ */+export async function unbornTier(+ context: Types.FetchContext,+): Promise<Types.FetchOutcome> {+ const { run } = context++ if (!(await Probes.isUnbornHead(run))) {+ return { kind: 'unavailable' }+ }++ const staged = await Probes.statsOf(context, '--cached')++ if (!staged) {+ return { kind: 'unavailable' }+ }++ const isOverlaid = staged.files.length > 0+ const unstaged = isOverlaid+ ? await Probes.unstagedNumstat(run)+ : EMPTY_NUMSTAT++ if (!unstaged) {+ return { kind: 'unavailable' }+ }++ const merged = await withUntracked(+ context,+ Probes.overlayUnstaged(staged, unstaged),+ 'session-only',+ )++ return {+ kind: 'data',+ data: diffDataOf(context, merged, {+ source: { kind: 'working-tree' },+ baseRef: '--cached',+ isUnborn: true,+ stalePaths: unstaged.files.map(file => file.path),+ }),+ }+}diff --git a/mods/diff/hooks/git/tiers/with-untracked/index.ts b/mods/diff/hooks/git/tiers/with-untracked/index.tsnew file mode 100644index 00000000..d2e9aa54--- /dev/null+++ b/mods/diff/hooks/git/tiers/with-untracked/index.ts@@ -0,0 +1,4 @@+export * from './merged-result-of'+export * from './with-untracked.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/tiers/with-untracked/merged-result-of/index.ts b/mods/diff/hooks/git/tiers/with-untracked/merged-result-of/index.tsnew file mode 100644index 00000000..e719f73b--- /dev/null+++ b/mods/diff/hooks/git/tiers/with-untracked/merged-result-of/index.ts@@ -0,0 +1,3 @@+export * from './merged-result-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/tiers/with-untracked/merged-result-of/merged-result-of.ts b/mods/diff/hooks/git/tiers/with-untracked/merged-result-of/merged-result-of.tsnew file mode 100644index 00000000..7224db9f--- /dev/null+++ b/mods/diff/hooks/git/tiers/with-untracked/merged-result-of/merged-result-of.ts@@ -0,0 +1,13 @@+import type Types from '../../../types'++/**+ * A tier's rows stamped with whether the untracked listing was withheld.+ *+ * @param result the rows and totals, untracked files merged in or not+ * @param mark whether git did not give the listing whole+ * @returns the merged result+ */+export const mergedResultOf = (+ result: Types.NumstatResult,+ mark: Pick<Types.MergedResult, 'isUntrackedWithheld'>,+): Types.MergedResult => ({ ...result, ...mark })diff --git a/mods/diff/hooks/git/tiers/with-untracked/with-untracked.ts b/mods/diff/hooks/git/tiers/with-untracked/with-untracked.tsnew file mode 100644index 00000000..3618c7cc--- /dev/null+++ b/mods/diff/hooks/git/tiers/with-untracked/with-untracked.ts@@ -0,0 +1,47 @@+import Limits from '../../../limits'+import Probes from '../../probes'+import type Types from '../../types'+import { isPastDetails } from '../is-past-details'+import { mergedResultOf } from './merged-result-of'++/**+ * A tier's rows with the untracked files merged after them, as the built-in+ * panel merges the session's untracked files.+ *+ * A path a numstat row already holds keeps that row and counts once. Past+ * MAX_FILES_FOR_DETAILS nothing is listed; a listing git withheld leaves+ * the tracked rows as they are and says so, as the built-in degrades.+ *+ * @param context the fetch+ * @param result the tier's tracked rows and totals+ * @param scope which untracked files count+ * @returns the merged rows and totals, and whether the listing was withheld+ */+export async function withUntracked(+ context: Types.FetchContext,+ result: Types.NumstatResult,+ scope: Types.UntrackedScope,+): Promise<Types.MergedResult> {+ if (isPastDetails(result)) {+ return mergedResultOf(result, { isUntrackedWithheld: false })+ }++ const tracked = new Set(result.files.map(file => file.path))+ const untracked = await Probes.untrackedFiles(context, {+ slots: Limits.MAX_FILES - result.files.length,+ scope,+ })++ if (!untracked) {+ return mergedResultOf(result, { isUntrackedWithheld: true })+ }++ const fresh = untracked.filter(file => !tracked.has(file.path))+ const filesCount = result.stats.filesCount + fresh.length+ const stats = { ...result.stats, filesCount }++ return mergedResultOf(+ { stats, files: [...result.files, ...fresh] },+ { isUntrackedWithheld: false },+ )+}diff --git a/mods/diff/hooks/git/tiers/working-tree-basis/index.ts b/mods/diff/hooks/git/tiers/working-tree-basis/index.tsnew file mode 100644index 00000000..dffa72a5--- /dev/null+++ b/mods/diff/hooks/git/tiers/working-tree-basis/index.ts@@ -0,0 +1,3 @@+export * from './working-tree-basis.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/tiers/working-tree-basis/working-tree-basis.ts b/mods/diff/hooks/git/tiers/working-tree-basis/working-tree-basis.tsnew file mode 100644index 00000000..558ffa0a--- /dev/null+++ b/mods/diff/hooks/git/tiers/working-tree-basis/working-tree-basis.ts@@ -0,0 +1,12 @@+import type DiffDataOf from '../diff-data-of'++/**+ * The basis of a plain working-tree diff: against HEAD, commits present,+ * every body current.+ */+export const WORKING_TREE_BASIS: DiffDataOf.DiffBasis = Object.freeze({+ source: Object.freeze({ kind: 'working-tree' }),+ baseRef: 'HEAD',+ isUnborn: false,+ stalePaths: Object.freeze([]),+})diff --git a/mods/diff/hooks/git/tiers/working-tree-tier.ts b/mods/diff/hooks/git/tiers/working-tree-tier.tsnew file mode 100644index 00000000..ad7280b7--- /dev/null+++ b/mods/diff/hooks/git/tiers/working-tree-tier.ts@@ -0,0 +1,43 @@+import Probes from '../probes'+import type Types from '../types'+import { diffDataOf } from './diff-data-of'+import { unbornTier } from './unborn-tier'+import { withUntracked } from './with-untracked'+import { WORKING_TREE_BASIS } from './working-tree-basis'++/**+ * Session and uncommitted mode: the working tree against HEAD, the built-in+ * panel's working-tree tier.+ *+ * Session mode tags the rows that predate the session and keeps+ * pre-session untracked files as tagged rows; uncommitted keeps the+ * session's untracked files and answers even when empty.+ *+ * @param context the fetch+ * @returns the outcome+ */+export async function workingTreeTier(+ context: Types.FetchContext,+): Promise<Types.FetchOutcome> {+ const workingTree = await Probes.statsOf(context, 'HEAD')++ if (!workingTree) {+ return unbornTier(context)+ }++ const isSession = context.mode === 'session'+ const files = isSession+ ? await Probes.tagPreSession(context, workingTree.files)+ : workingTree.files+ const data = diffDataOf(+ context,+ await withUntracked(+ context,+ { stats: workingTree.stats, files },+ isSession ? 'with-pre-session' : 'session-only',+ ),+ WORKING_TREE_BASIS,+ )++ return { kind: 'data', data }+}diff --git a/mods/diff/hooks/git/types/base-mode/base-mode.ts b/mods/diff/hooks/git/types/base-mode/base-mode.tsnew file mode 100644index 00000000..8d955e58--- /dev/null+++ b/mods/diff/hooks/git/types/base-mode/base-mode.ts@@ -0,0 +1,5 @@+/**+ * What the diff compares the working tree against: HEAD partitioned by the+ * session's start, HEAD plainly, or the merge-base with the default branch.+ */+export type BaseMode = 'session' | 'uncommitted' | 'branch'diff --git a/mods/diff/hooks/git/types/base-mode/index.ts b/mods/diff/hooks/git/types/base-mode/index.tsnew file mode 100644index 00000000..d67c2450--- /dev/null+++ b/mods/diff/hooks/git/types/base-mode/index.ts@@ -0,0 +1,3 @@+export type * from './base-mode.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/branch-base/branch-base.ts b/mods/diff/hooks/git/types/branch-base/branch-base.tsnew file mode 100644index 00000000..21ce582a--- /dev/null+++ b/mods/diff/hooks/git/types/branch-base/branch-base.ts@@ -0,0 +1,9 @@+import type { ResolvedBranchBase } from '../resolved-branch-base'++/**+ * What branch mode diffs against, as the built-in panel names it: a+ * resolved base, or a failure that may pass on the next fetch.+ */+export type BranchBase =+ | ResolvedBranchBase+ | { kind: 'error'; reason: 'merge_base_failed' | 'head_rev_parse_failed' }diff --git a/mods/diff/hooks/git/types/branch-base/index.ts b/mods/diff/hooks/git/types/branch-base/index.tsnew file mode 100644index 00000000..0b338343--- /dev/null+++ b/mods/diff/hooks/git/types/branch-base/index.ts@@ -0,0 +1,3 @@+export type * from './branch-base.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/dating/dating.ts b/mods/diff/hooks/git/types/dating/dating.tsnew file mode 100644index 00000000..4cbc87fc--- /dev/null+++ b/mods/diff/hooks/git/types/dating/dating.ts@@ -0,0 +1,7 @@+/**+ * When a path was last written, against the session: before it began,+ * since, or never reached because the listing budget was spent.+ *+ * An undatable path (deleted, a symbolic link) reads as `session`.+ */+export type Dating = 'pre-session' | 'session' | 'unlisted'diff --git a/mods/diff/hooks/git/types/dating/index.ts b/mods/diff/hooks/git/types/dating/index.tsnew file mode 100644index 00000000..57b5af7f--- /dev/null+++ b/mods/diff/hooks/git/types/dating/index.ts@@ -0,0 +1,3 @@+export type * from './dating.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/diff-data/diff-data.ts b/mods/diff/hooks/git/types/diff-data/diff-data.tsnew file mode 100644index 00000000..c04d438d--- /dev/null+++ b/mods/diff/hooks/git/types/diff-data/diff-data.ts@@ -0,0 +1,25 @@+import type { BaseMode } from '../base-mode'+import type { DiffSource } from '../diff-source'+import type { DiffStats } from '../diff-stats'+import type { FileStat } from '../file-stat'+import type { Repository } from '../repository'++/**+ * One settled fetch: the rows, the totals, what they compare, and what a+ * file's hunks must be read against so both agree.+ *+ * `isUnborn`: a repository before its first commit (rows are the staged+ * and new files, `baseRef` is `--cached`); `stalePaths`: files whose staged+ * body is behind the working tree; `isUntrackedWithheld`: MergedResult's.+ */+export type DiffData = {+ repository: Repository+ mode: BaseMode+ stats: DiffStats+ files: readonly FileStat[]+ source: DiffSource+ isUnborn: boolean+ baseRef: string+ stalePaths: readonly string[]+ isUntrackedWithheld: boolean+}diff --git a/mods/diff/hooks/git/types/diff-data/index.ts b/mods/diff/hooks/git/types/diff-data/index.tsnew file mode 100644index 00000000..9933d529--- /dev/null+++ b/mods/diff/hooks/git/types/diff-data/index.ts@@ -0,0 +1,3 @@+export type * from './diff-data.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/diff-source/diff-source.ts b/mods/diff/hooks/git/types/diff-source/diff-source.tsnew file mode 100644index 00000000..d9c59d77--- /dev/null+++ b/mods/diff/hooks/git/types/diff-source/diff-source.ts@@ -0,0 +1,7 @@+/**+ * What a fetched diff compares: the working tree against HEAD, or against+ * the merge-base with the default branch (`baseRef` the ref git was handed).+ */+export type DiffSource =+ | { kind: 'working-tree' }+ | { kind: 'branch'; baseBranch: string; baseRef: string }diff --git a/mods/diff/hooks/git/types/diff-source/index.ts b/mods/diff/hooks/git/types/diff-source/index.tsnew file mode 100644index 00000000..e2bcaba6--- /dev/null+++ b/mods/diff/hooks/git/types/diff-source/index.ts@@ -0,0 +1,3 @@+export type * from './diff-source.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/diff-stats/diff-stats.ts b/mods/diff/hooks/git/types/diff-stats/diff-stats.tsnew file mode 100644index 00000000..85f948a9--- /dev/null+++ b/mods/diff/hooks/git/types/diff-stats/diff-stats.ts@@ -0,0 +1,8 @@+/**+ * A diff's totals as `--numstat` or `--shortstat` count them.+ */+export type DiffStats = {+ filesCount: number+ linesAdded: number+ linesRemoved: number+}diff --git a/mods/diff/hooks/git/types/diff-stats/index.ts b/mods/diff/hooks/git/types/diff-stats/index.tsnew file mode 100644index 00000000..47582ad2--- /dev/null+++ b/mods/diff/hooks/git/types/diff-stats/index.ts@@ -0,0 +1,3 @@+export type * from './diff-stats.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/entry-kind/entry-kind.ts b/mods/diff/hooks/git/types/entry-kind/entry-kind.tsnew file mode 100644index 00000000..40b5011c--- /dev/null+++ b/mods/diff/hooks/git/types/entry-kind/entry-kind.ts@@ -0,0 +1,7 @@+import type { FsEntry } from 'claude-code'++/**+ * A directory entry's own kind as `$.fs.list` reports it, no link+ * followed: `file`, `dir`, or `other` (a symbolic link is `other`).+ */+export type EntryKind = FsEntry['kind']diff --git a/mods/diff/hooks/git/types/entry-kind/index.ts b/mods/diff/hooks/git/types/entry-kind/index.tsnew file mode 100644index 00000000..dbbbe547--- /dev/null+++ b/mods/diff/hooks/git/types/entry-kind/index.ts@@ -0,0 +1,3 @@+export type * from './entry-kind.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/fetch-context.ts b/mods/diff/hooks/git/types/fetch-context.tsnew file mode 100644index 00000000..2af21da7--- /dev/null+++ b/mods/diff/hooks/git/types/fetch-context.ts@@ -0,0 +1,20 @@+import type { BaseMode } from './base-mode'+import type { GitDeps } from './git-deps'+import type { GitRun } from './git-run'+import type { Repository } from './repository'+import type { StampProbe } from './stamp-probe'++/**+ * What every tier of one fetch shares: the host, its pinned git, the+ * repository, the mode asked for, and one stamp probe over the tree.+ *+ * One probe, so tracked and untracked dating draw on the same listings+ * and one budget.+ */+export type FetchContext = {+ deps: GitDeps+ run: GitRun+ repository: Repository+ mode: BaseMode+ stamps: StampProbe+}diff --git a/mods/diff/hooks/git/types/fetch-outcome.ts b/mods/diff/hooks/git/types/fetch-outcome.tsnew file mode 100644index 00000000..b06d48ee--- /dev/null+++ b/mods/diff/hooks/git/types/fetch-outcome.ts@@ -0,0 +1,10 @@+import type { DiffData } from './diff-data'++/**+ * How one fetch ended: outside any repository, unreadable for now (a lock, a+ * timeout, a rebase under way: the last good diff stays), or data.+ */+export type FetchOutcome =+ | { kind: 'no-repository' }+ | { kind: 'unavailable' }+ | { kind: 'data'; data: DiffData }diff --git a/mods/diff/hooks/git/types/file-hunks.ts b/mods/diff/hooks/git/types/file-hunks.tsnew file mode 100644index 00000000..3ec06959--- /dev/null+++ b/mods/diff/hooks/git/types/file-hunks.ts@@ -0,0 +1,11 @@+import type { Hunk } from './hunk'++/**+ * One file's parsed diff body: its hunks, cut at MAX_LINES_PER_FILE+ * (`isTruncated`), or none at all past MAX_DIFF_BYTES (`isLarge`).+ */+export type FileHunks = {+ hunks: readonly Hunk[]+ isTruncated: boolean+ isLarge: boolean+}diff --git a/mods/diff/hooks/git/types/file-stat/file-stat.ts b/mods/diff/hooks/git/types/file-stat/file-stat.tsnew file mode 100644index 00000000..dbeeabb1--- /dev/null+++ b/mods/diff/hooks/git/types/file-stat/file-stat.ts@@ -0,0 +1,17 @@+/**+ * One changed file's row: its repository-relative path, its line counts,+ * and what kind of change it is.+ *+ * `isPreSession` is set in session mode alone, when the file's timestamp+ * predates the session's start (an untracked file too); `renamedFrom` is+ * the old path of a rename git detected, else null.+ */+export type FileStat = {+ path: string+ renamedFrom: string | null+ added: number+ removed: number+ isBinary: boolean+ isUntracked: boolean+ isPreSession: boolean+}diff --git a/mods/diff/hooks/git/types/file-stat/index.ts b/mods/diff/hooks/git/types/file-stat/index.tsnew file mode 100644index 00000000..15a8b3a3--- /dev/null+++ b/mods/diff/hooks/git/types/file-stat/index.ts@@ -0,0 +1,3 @@+export type * from './file-stat.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/git-deps/git-deps.ts b/mods/diff/hooks/git/types/git-deps/git-deps.tsnew file mode 100644index 00000000..930c8705--- /dev/null+++ b/mods/diff/hooks/git/types/git-deps/git-deps.ts@@ -0,0 +1,39 @@+import type { BranchBase } from '../branch-base'+import type { EntryKind } from '../entry-kind'+import type { GitRun } from '../git-run'+import type { Repository } from '../repository'++/**+ * What the fetch reaches the host through: pinned git, the repository, a+ * directory listing, a timestamp probe, the start, a branch-base listener.+ */+export type GitDeps = {+ /**+ * Runs git against `repository`; never rejects (GitRun).+ */+ run: GitRun++ /**+ * Where the session started, resolved once and pinned on every child.+ */+ repository: Repository++ /**+ * A path's modification time in epoch milliseconds, or null when it+ * cannot be read. Called only on a path a listing showed as a file.+ */+ mtimeOf: (path: string) => Promise<number | null>++ /**+ * A directory's entries by name with their own kinds (no link followed),+ * or null when it cannot be listed.+ */+ entryKindsOf: (dir: string) => Promise<ReadonlyMap<string, EntryKind> | null>++ sessionStartMs: number++ /**+ * Told each time branch mode resolves its base, for telemetry.+ */+ onBranchBase: (base: BranchBase) => void+}diff --git a/mods/diff/hooks/git/types/git-deps/index.ts b/mods/diff/hooks/git/types/git-deps/index.tsnew file mode 100644index 00000000..200b088d--- /dev/null+++ b/mods/diff/hooks/git/types/git-deps/index.ts@@ -0,0 +1,3 @@+export type * from './git-deps.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/git-run/git-run.ts b/mods/diff/hooks/git/types/git-run/git-run.tsnew file mode 100644index 00000000..8cca9e86--- /dev/null+++ b/mods/diff/hooks/git/types/git-run/git-run.ts@@ -0,0 +1,7 @@+import type { RunResult } from '../run-result'++/**+ * Runs git with `argv` (no `git` in it) against the session's pinned+ * repository and never rejects: a failure is a RunResult of exit code -1.+ */+export type GitRun = (argv: readonly string[]) => Promise<RunResult>diff --git a/mods/diff/hooks/git/types/git-run/index.ts b/mods/diff/hooks/git/types/git-run/index.tsnew file mode 100644index 00000000..50d96509--- /dev/null+++ b/mods/diff/hooks/git/types/git-run/index.ts@@ -0,0 +1,3 @@+export type * from './git-run.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/head-key-deps/head-key-deps.ts b/mods/diff/hooks/git/types/head-key-deps/head-key-deps.tsnew file mode 100644index 00000000..4d6b6d7a--- /dev/null+++ b/mods/diff/hooks/git/types/head-key-deps/head-key-deps.ts@@ -0,0 +1,12 @@+import type { GitDeps } from '../git-deps'++/**+ * What reading the HEAD key takes: git for the fallback, listings and+ * timestamps for the files, and a file read for HEAD's text.+ */+export type HeadKeyDeps = Pick<GitDeps, 'run' | 'mtimeOf' | 'entryKindsOf'> & {+ /**+ * A file's text; rejects when it cannot be read.+ */+ readFile: (path: string) => Promise<string>+}diff --git a/mods/diff/hooks/git/types/head-key-deps/index.ts b/mods/diff/hooks/git/types/head-key-deps/index.tsnew file mode 100644index 00000000..9dfd2ee3--- /dev/null+++ b/mods/diff/hooks/git/types/head-key-deps/index.ts@@ -0,0 +1,3 @@+export type * from './head-key-deps.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/hunk/hunk.ts b/mods/diff/hooks/git/types/hunk/hunk.tsnew file mode 100644index 00000000..1f4faff9--- /dev/null+++ b/mods/diff/hooks/git/types/hunk/hunk.ts@@ -0,0 +1,9 @@+/**+ * One hunk of a unified diff: where it starts on each side and its lines,+ * each still carrying its `+`, `-` or space marker.+ */+export type Hunk = {+ oldStart: number+ newStart: number+ lines: readonly string[]+}diff --git a/mods/diff/hooks/git/types/hunk/index.ts b/mods/diff/hooks/git/types/hunk/index.tsnew file mode 100644index 00000000..bd22de7f--- /dev/null+++ b/mods/diff/hooks/git/types/hunk/index.ts@@ -0,0 +1,3 @@+export type * from './hunk.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/index.ts b/mods/diff/hooks/git/types/index.tsnew file mode 100644index 00000000..834946c4--- /dev/null+++ b/mods/diff/hooks/git/types/index.ts@@ -0,0 +1,26 @@+export * from './base-mode'+export * from './branch-base'+export * from './dating'+export * from './diff-data'+export * from './diff-source'+export * from './diff-stats'+export * from './entry-kind'+export type * from './fetch-context.js'+export type * from './fetch-outcome.js'+export type * from './file-hunks.js'+export * from './file-stat'+export * from './git-deps'+export * from './git-run'+export * from './head-key-deps'+export * from './hunk'+export * from './kind-walk'+export * from './merged-result'+export * from './repository'+export * from './resolved-branch-base'+export * from './run-result'+export * from './stamp'+export * from './stamp-probe'+export type * from './untracked-scope.js'+export * from './walk-kind'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/kind-walk/index.ts b/mods/diff/hooks/git/types/kind-walk/index.tsnew file mode 100644index 00000000..cb3fe9f0--- /dev/null+++ b/mods/diff/hooks/git/types/kind-walk/index.ts@@ -0,0 +1,3 @@+export type * from './kind-walk.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/kind-walk/kind-walk.ts b/mods/diff/hooks/git/types/kind-walk/kind-walk.tsnew file mode 100644index 00000000..a809d446--- /dev/null+++ b/mods/diff/hooks/git/types/kind-walk/kind-walk.ts@@ -0,0 +1,13 @@+import type { WalkKind } from '../walk-kind'++/**+ * Entry kinds under one root, every ancestor checked: a path's kind is+ * answered only when each directory above it is itself a real directory.+ */+export type KindWalk = {+ /**+ * Answers the entry's kind at a root-relative `/` path (`''`: the root);+ * see WalkKind for the two ways it cannot say.+ */+ kindOf: (path: string) => Promise<WalkKind>+}diff --git a/mods/diff/hooks/git/types/merged-result/index.ts b/mods/diff/hooks/git/types/merged-result/index.tsnew file mode 100644index 00000000..0d4a85da--- /dev/null+++ b/mods/diff/hooks/git/types/merged-result/index.ts@@ -0,0 +1,4 @@+export type * from './merged-result.js'+export * from './numstat-result'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/merged-result/merged-result.ts b/mods/diff/hooks/git/types/merged-result/merged-result.tsnew file mode 100644index 00000000..5ce44495--- /dev/null+++ b/mods/diff/hooks/git/types/merged-result/merged-result.ts@@ -0,0 +1,10 @@+import type { NumstatResult } from './numstat-result'++/**+ * A tier's rows once the untracked files were merged in, and whether git+ * withheld their listing (failed, timed out, cut).+ *+ * Withheld: the rows are the tracked ones alone, as the built-in degrades,+ * and the pane says so.+ */+export type MergedResult = NumstatResult & { isUntrackedWithheld: boolean }diff --git a/mods/diff/hooks/git/types/merged-result/numstat-result/index.ts b/mods/diff/hooks/git/types/merged-result/numstat-result/index.tsnew file mode 100644index 00000000..8c5af981--- /dev/null+++ b/mods/diff/hooks/git/types/merged-result/numstat-result/index.ts@@ -0,0 +1,3 @@+export type * from './numstat-result.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/merged-result/numstat-result/numstat-result.ts b/mods/diff/hooks/git/types/merged-result/numstat-result/numstat-result.tsnew file mode 100644index 00000000..c7d1b692--- /dev/null+++ b/mods/diff/hooks/git/types/merged-result/numstat-result/numstat-result.ts@@ -0,0 +1,11 @@+import type { DiffStats } from '../../diff-stats'+import type { FileStat } from '../../file-stat'++/**+ * A parsed `--numstat`: the totals over every row, and the first MAX_FILES+ * rows.+ */+export type NumstatResult = {+ stats: DiffStats+ files: readonly FileStat[]+}diff --git a/mods/diff/hooks/git/types/repository/index.ts b/mods/diff/hooks/git/types/repository/index.tsnew file mode 100644index 00000000..8b45030b--- /dev/null+++ b/mods/diff/hooks/git/types/repository/index.ts@@ -0,0 +1,3 @@+export type * from './repository.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/repository/repository.ts b/mods/diff/hooks/git/types/repository/repository.tsnew file mode 100644index 00000000..a30bc890--- /dev/null+++ b/mods/diff/hooks/git/types/repository/repository.ts@@ -0,0 +1,9 @@+/**+ * Where the session's repository lives: its working tree's top, its own git+ * directory (a linked worktree's), and the common directory holding refs.+ */+export type Repository = {+ toplevel: string+ gitDir: string+ commonDir: string+}diff --git a/mods/diff/hooks/git/types/resolved-branch-base/index.ts b/mods/diff/hooks/git/types/resolved-branch-base/index.tsnew file mode 100644index 00000000..529169e9--- /dev/null+++ b/mods/diff/hooks/git/types/resolved-branch-base/index.ts@@ -0,0 +1,3 @@+export type * from './resolved-branch-base.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/resolved-branch-base/resolved-branch-base.ts b/mods/diff/hooks/git/types/resolved-branch-base/resolved-branch-base.tsnew file mode 100644index 00000000..21e30f59--- /dev/null+++ b/mods/diff/hooks/git/types/resolved-branch-base/resolved-branch-base.ts@@ -0,0 +1,8 @@+/**+ * What branch mode diffs against once it resolved: the merge-base with the+ * default branch, HEAD itself when it is that base, or nothing defensible.+ */+export type ResolvedBranchBase =+ | { kind: 'merge-base'; mergeBase: string; baseBranch: string }+ | { kind: 'head-is-base'; baseBranch: string }+ | { kind: 'none' }diff --git a/mods/diff/hooks/git/types/run-result/index.ts b/mods/diff/hooks/git/types/run-result/index.tsnew file mode 100644index 00000000..b003dbca--- /dev/null+++ b/mods/diff/hooks/git/types/run-result/index.ts@@ -0,0 +1,3 @@+export type * from './run-result.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/run-result/run-result.ts b/mods/diff/hooks/git/types/run-result/run-result.tsnew file mode 100644index 00000000..b5889925--- /dev/null+++ b/mods/diff/hooks/git/types/run-result/run-result.ts@@ -0,0 +1,9 @@+/**+ * What one git child left: its exit code and both output streams; a child+ * that never ran or was killed reads as exit code -1 with no output.+ */+export type RunResult = {+ exitCode: number+ stdout: string+ stderr: string+}diff --git a/mods/diff/hooks/git/types/stamp-probe/index.ts b/mods/diff/hooks/git/types/stamp-probe/index.tsnew file mode 100644index 00000000..4c29c50f--- /dev/null+++ b/mods/diff/hooks/git/types/stamp-probe/index.ts@@ -0,0 +1,3 @@+export type * from './stamp-probe.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/stamp-probe/stamp-probe.ts b/mods/diff/hooks/git/types/stamp-probe/stamp-probe.tsnew file mode 100644index 00000000..6373fe06--- /dev/null+++ b/mods/diff/hooks/git/types/stamp-probe/stamp-probe.ts@@ -0,0 +1,12 @@+import type { GitDeps } from '../git-deps'+import type { KindWalk } from '../kind-walk'++/**+ * What stamping a file behind a kind walk takes: the walk, the absolute+ * base its paths are under, and the timestamp probe.+ */+export type StampProbe = {+ walk: KindWalk+ base: string+ mtimeOf: GitDeps['mtimeOf']+}diff --git a/mods/diff/hooks/git/types/stamp/index.ts b/mods/diff/hooks/git/types/stamp/index.tsnew file mode 100644index 00000000..2f851597--- /dev/null+++ b/mods/diff/hooks/git/types/stamp/index.ts@@ -0,0 +1,3 @@+export type * from './stamp.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/stamp/stamp.ts b/mods/diff/hooks/git/types/stamp/stamp.tsnew file mode 100644index 00000000..6c110e5b--- /dev/null+++ b/mods/diff/hooks/git/types/stamp/stamp.ts@@ -0,0 +1,7 @@+/**+ * A file's date behind a kind walk: its modification time; null when it is+ * no real file under real directories or cannot be read.+ *+ * `over-budget` when the walk's listings ran out before reaching it.+ */+export type Stamp = number | 'over-budget' | nulldiff --git a/mods/diff/hooks/git/types/untracked-scope.ts b/mods/diff/hooks/git/types/untracked-scope.tsnew file mode 100644index 00000000..795ebd2f--- /dev/null+++ b/mods/diff/hooks/git/types/untracked-scope.ts@@ -0,0 +1,5 @@+/**+ * Which untracked files a fetch keeps: the session's own, or those and the+ * ones that predate it, tagged (session mode).+ */+export type UntrackedScope = 'session-only' | 'with-pre-session'diff --git a/mods/diff/hooks/git/types/walk-kind/index.ts b/mods/diff/hooks/git/types/walk-kind/index.tsnew file mode 100644index 00000000..a210ca32--- /dev/null+++ b/mods/diff/hooks/git/types/walk-kind/index.ts@@ -0,0 +1,3 @@+export type * from './walk-kind.js'++export * as default from '.'diff --git a/mods/diff/hooks/git/types/walk-kind/walk-kind.ts b/mods/diff/hooks/git/types/walk-kind/walk-kind.tsnew file mode 100644index 00000000..21f4fb74--- /dev/null+++ b/mods/diff/hooks/git/types/walk-kind/walk-kind.ts@@ -0,0 +1,9 @@+import type { EntryKind } from '../entry-kind'++/**+ * What a kind walk answers for a path: the entry's own kind; null when it+ * is absent, an ancestor is no real directory, or a listing failed.+ *+ * `over-budget` when the walk had spent its listings before reaching it.+ */+export type WalkKind = EntryKind | 'over-budget' | nulldiff --git a/mods/diff/hooks/hooks.json b/mods/diff/hooks/hooks.jsonnew file mode 100644index 00000000..42164197--- /dev/null+++ b/mods/diff/hooks/hooks.json@@ -0,0 +1,4 @@+{+ "description": "The diff pane: /diff and its Pane drawing, a refresh on Claude's edits, shell commands and finished turns, the pane's opening on the first edit, and the ask that rides a file's hunks on the next prompt",+ "modules": ["./register.ts"]+}diff --git a/mods/diff/hooks/host/host.ts b/mods/diff/hooks/host/host.tsnew file mode 100644index 00000000..be5ed36e--- /dev/null+++ b/mods/diff/hooks/host/host.ts@@ -0,0 +1,116 @@+import type {+ CommandSpec,+ EngineInterface,+ FsEntry,+ FsStat,+ PaneCloseArgs,+ PaneOpenArgs,+ ProcessRunInit,+ ProcessRunResult,+ SessionMessage,+ TimerCall,+} from 'claude-code'++/**+ * The engine as `session.start` bound it from its `$`, each member spelled+ * `$.noun.event(...)` there; used by every later hook, timer and press.+ */+export type Host = {+ /**+ * `$.clock.now`.+ */+ now: () => number++ /**+ * `$.clock.after`.+ */+ after: TimerCall++ /**+ * `$.clock.every`.+ */+ every: TimerCall++ /**+ * `$.clock.sleep`, no signal.+ */+ sleep: (ms: number) => Promise<void>++ /**+ * `$.process.run`.+ */+ run: (+ argv: readonly string[],+ init: ProcessRunInit,+ ) => Promise<ProcessRunResult>++ /**+ * `$.fs.stat`.+ */+ stat: (path: string) => Promise<FsStat>++ /**+ * `$.fs.list`: a directory's entries by kind, links never followed.+ */+ listDir: (path: string) => Promise<FsEntry[]>++ /**+ * `$.fs.read`.+ */+ readFile: (path: string) => Promise<string>++ /**+ * Reads the plugin's store (`$.store.get`).+ */+ storeGet: (key: string) => Promise<unknown>++ /**+ * Writes the plugin's store (`$.store.set`).+ */+ storeSet: (key: string, value: unknown) => Promise<void>++ /**+ * `$.session.messages`.+ */+ messages: () => Promise<SessionMessage[]>++ /**+ * `$.ui.invalidate("ui.render")`: every pane instance draws again.+ */+ invalidate: () => void++ /**+ * `$.ui.status`: the plugin's line under the prompt.+ */+ status: (text: string | undefined) => void++ /**+ * One debug line under the plugin's name (`$.ui.log`).+ */+ uiLog: (text: string) => void++ /**+ * `$.ui.open`.+ */+ openPane: (pane: PaneOpenArgs) => Promise<void>++ /**+ * `$.ui.close`.+ */+ closePane: (pane: PaneCloseArgs) => Promise<void>++ /**+ * `$.command.register`; rejects while another `/diff` is listed.+ */+ registerCommand: (spec: CommandSpec) => Promise<unknown>++ /**+ * `$.telemetry.mark`; rejects where the telemetry built-in is absent.+ */+ mark: EngineInterface['telemetry']['mark']++ /**+ * `$.telemetry.log`; rejects where the telemetry built-in is absent.+ */+ log: EngineInterface['telemetry']['log']+}diff --git a/mods/diff/hooks/host/index.ts b/mods/diff/hooks/host/index.tsnew file mode 100644index 00000000..5abe18a8--- /dev/null+++ b/mods/diff/hooks/host/index.ts@@ -0,0 +1,3 @@+export type * from './host.js'++export * as default from '.'diff --git a/mods/diff/hooks/index.ts b/mods/diff/hooks/index.tsnew file mode 100644index 00000000..b9627cab--- /dev/null+++ b/mods/diff/hooks/index.ts@@ -0,0 +1,25 @@+export * from './array-of'+export * from './ask'+export * from './classify'+export * from './command-spec'+export * from './count-of'+export * from './entry-kinds-of'+export * from './git'+export * from './host'+export * from './is-on-pane-surface'+export * from './is-record'+export * from './limits'+export * from './message-of'+export * from './mtime-of'+export * from './names'+export * from './pane-state'+export * from './pane-toggle'+export * from './record'+export * from './register.js'+export * from './todos'+export * from './tools'+export * from './turns'+export * from './views'+export * from './word-diff'++export * as default from '.'diff --git a/mods/diff/hooks/is-on-pane-surface/index.ts b/mods/diff/hooks/is-on-pane-surface/index.tsnew file mode 100644index 00000000..f9fce2e7--- /dev/null+++ b/mods/diff/hooks/is-on-pane-surface/index.ts@@ -0,0 +1,3 @@+export * from './is-on-pane-surface.js'++export * as default from '.'diff --git a/mods/diff/hooks/is-on-pane-surface/is-on-pane-surface.ts b/mods/diff/hooks/is-on-pane-surface/is-on-pane-surface.tsnew file mode 100644index 00000000..63025caf--- /dev/null+++ b/mods/diff/hooks/is-on-pane-surface/is-on-pane-surface.ts@@ -0,0 +1,12 @@+import type { RenderSurface } from 'claude-code'++/**+ * Whether a render event comes from a surface that draws the pane: every+ * one but the mobile app, which has no Select and is not terminal-wide.+ *+ * @param e the render event, or anything naming its surface+ * @returns false on `mobile`, true otherwise, narrowing `e` to the rest+ */+export const isOnPaneSurface = <E extends Record<'surface', RenderSurface>>(+ e: E,+): e is Exclude<E, Record<'surface', 'mobile'>> => e.surface !== 'mobile'diff --git a/mods/diff/hooks/is-record/index.ts b/mods/diff/hooks/is-record/index.tsnew file mode 100644index 00000000..b3255fa1--- /dev/null+++ b/mods/diff/hooks/is-record/index.ts@@ -0,0 +1,3 @@+export * from './is-record.js'++export * as default from '.'diff --git a/mods/diff/hooks/is-record/is-record.ts b/mods/diff/hooks/is-record/is-record.tsnew file mode 100644index 00000000..aebdb34e--- /dev/null+++ b/mods/diff/hooks/is-record/is-record.ts@@ -0,0 +1,8 @@+/**+ * Whether a value is a plain object that can be read field by field.+ *+ * @param value anything a tool result may be+ * @returns whether it is a non-null, non-array object+ */+export const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value)diff --git a/mods/diff/hooks/limits/columns/auto-open-min-columns.ts b/mods/diff/hooks/limits/columns/auto-open-min-columns.tsnew file mode 100644index 00000000..edc53890--- /dev/null+++ b/mods/diff/hooks/limits/columns/auto-open-min-columns.ts@@ -0,0 +1,5 @@+/**+ * The terminal width from which the first edit opens the pane when the person+ * never said whether they want it (the built-in sidebar's own 144).+ */+export const AUTO_OPEN_MIN_COLUMNS = 144diff --git a/mods/diff/hooks/limits/columns/index.ts b/mods/diff/hooks/limits/columns/index.tsnew file mode 100644index 00000000..e98ed0fd--- /dev/null+++ b/mods/diff/hooks/limits/columns/index.ts@@ -0,0 +1,5 @@+export * from './auto-open-min-columns.js'+export * from './open-min-columns.js'+export * from './widest-bucket-columns.js'++export * as default from '.'diff --git a/mods/diff/hooks/limits/columns/open-min-columns.ts b/mods/diff/hooks/limits/columns/open-min-columns.tsnew file mode 100644index 00000000..c34a84a1--- /dev/null+++ b/mods/diff/hooks/limits/columns/open-min-columns.ts@@ -0,0 +1,5 @@+/**+ * The terminal width from which the first edit opens the pane when the person+ * kept it open before (the built-in sidebar's own minimum).+ */+export const OPEN_MIN_COLUMNS = 110diff --git a/mods/diff/hooks/limits/columns/widest-bucket-columns.ts b/mods/diff/hooks/limits/columns/widest-bucket-columns.tsnew file mode 100644index 00000000..cb4d6686--- /dev/null+++ b/mods/diff/hooks/limits/columns/widest-bucket-columns.ts@@ -0,0 +1,4 @@+/**+ * The terminal width from which `diff_pane_shown` reports `200_plus`.+ */+export const WIDEST_BUCKET_COLUMNS = 200diff --git a/mods/diff/hooks/limits/index.ts b/mods/diff/hooks/limits/index.tsnew file mode 100644index 00000000..87c57389--- /dev/null+++ b/mods/diff/hooks/limits/index.ts@@ -0,0 +1,5 @@+export * from './columns'+export * from './sizes'+export * from './timing'++export * as default from '.'diff --git a/mods/diff/hooks/limits/sizes/host-output-cap-bytes.ts b/mods/diff/hooks/limits/sizes/host-output-cap-bytes.tsnew file mode 100644index 00000000..08128af0--- /dev/null+++ b/mods/diff/hooks/limits/sizes/host-output-cap-bytes.ts@@ -0,0 +1,5 @@+/**+ * The most of a child's stdout `$.process.run` hands back, in bytes+ * (process-host OUTPUT_LIMIT); a listing that long was cut, silently.+ */+export const HOST_OUTPUT_CAP_BYTES = 4 * 1024 * 1024diff --git a/mods/diff/hooks/limits/sizes/index.ts b/mods/diff/hooks/limits/sizes/index.tsnew file mode 100644index 00000000..a184760a--- /dev/null+++ b/mods/diff/hooks/limits/sizes/index.ts@@ -0,0 +1,9 @@+export * from './host-output-cap-bytes.js'+export * from './max-diff-bytes.js'+export * from './max-files.js'+export * from './max-files-for-details.js'+export * from './max-lines-per-file.js'+export * from './max-listed-directories.js'+export * from './max-untracked-probes.js'++export * as default from '.'diff --git a/mods/diff/hooks/limits/sizes/max-diff-bytes.ts b/mods/diff/hooks/limits/sizes/max-diff-bytes.tsnew file mode 100644index 00000000..18be71ce--- /dev/null+++ b/mods/diff/hooks/limits/sizes/max-diff-bytes.ts@@ -0,0 +1,5 @@+/**+ * A file whose unified diff text is longer than this is a "large file": its+ * hunks are not parsed (the built-in panel's size cap).+ */+export const MAX_DIFF_BYTES = 1_000_000diff --git a/mods/diff/hooks/limits/sizes/max-files-for-details.ts b/mods/diff/hooks/limits/sizes/max-files-for-details.tsnew file mode 100644index 00000000..7d37404f--- /dev/null+++ b/mods/diff/hooks/limits/sizes/max-files-for-details.ts@@ -0,0 +1,5 @@+/**+ * Past this many changed files the shortstat totals alone are kept: no+ * per-file rows, no hunks, no untracked probe (the built-in panel's cap).+ */+export const MAX_FILES_FOR_DETAILS = 500diff --git a/mods/diff/hooks/limits/sizes/max-files.ts b/mods/diff/hooks/limits/sizes/max-files.tsnew file mode 100644index 00000000..b1490c5c--- /dev/null+++ b/mods/diff/hooks/limits/sizes/max-files.ts@@ -0,0 +1,5 @@+/**+ * How many per-file rows a diff keeps (the built-in panel's cap); the rest+ * are counted as "not shown".+ */+export const MAX_FILES = 50diff --git a/mods/diff/hooks/limits/sizes/max-lines-per-file.ts b/mods/diff/hooks/limits/sizes/max-lines-per-file.tsnew file mode 100644index 00000000..0b953d43--- /dev/null+++ b/mods/diff/hooks/limits/sizes/max-lines-per-file.ts@@ -0,0 +1,5 @@+/**+ * How many diff lines of one file are kept before the body is cut and the+ * file reads as truncated (GitHub's auto-load limit, as the built-in's).+ */+export const MAX_LINES_PER_FILE = 400diff --git a/mods/diff/hooks/limits/sizes/max-listed-directories.ts b/mods/diff/hooks/limits/sizes/max-listed-directories.tsnew file mode 100644index 00000000..4c3646a1--- /dev/null+++ b/mods/diff/hooks/limits/sizes/max-listed-directories.ts@@ -0,0 +1,9 @@+/**+ * How many directories one fetch may list while dating its files; past it+ * an untracked file reads as pre-session, a tracked one as session work.+ *+ * A walk lists only the distinct ancestors of the paths it dates (MAX_FILES+ * tracked, MAX_UNTRACKED_PROBES untracked), so the budget in effect is the+ * dated set's own directory count; this caps a pathological spread.+ */+export const MAX_LISTED_DIRECTORIES = 512diff --git a/mods/diff/hooks/limits/sizes/max-untracked-probes.ts b/mods/diff/hooks/limits/sizes/max-untracked-probes.tsnew file mode 100644index 00000000..8c35009e--- /dev/null+++ b/mods/diff/hooks/limits/sizes/max-untracked-probes.ts@@ -0,0 +1,5 @@+/**+ * How many untracked paths get a timestamp probe per fetch; the rest read as+ * pre-session, since only MAX_FILES rows could ever show.+ */+export const MAX_UNTRACKED_PROBES = 500diff --git a/mods/diff/hooks/limits/timing/git-timeout-ms.ts b/mods/diff/hooks/limits/timing/git-timeout-ms.tsnew file mode 100644index 00000000..e7824e48--- /dev/null+++ b/mods/diff/hooks/limits/timing/git-timeout-ms.ts@@ -0,0 +1,5 @@+/**+ * How long one git child may run before the fetch gives up on it and keeps+ * the last good diff (the built-in panel's own timeout).+ */+export const GIT_TIMEOUT_MS = 5000diff --git a/mods/diff/hooks/limits/timing/head-poll-ms.ts b/mods/diff/hooks/limits/timing/head-poll-ms.tsnew file mode 100644index 00000000..6d49c4ed--- /dev/null+++ b/mods/diff/hooks/limits/timing/head-poll-ms.ts@@ -0,0 +1,5 @@+/**+ * How often `.git/HEAD` and the checked-out ref are probed for a checkout or+ * commit made outside the session.+ */+export const HEAD_POLL_MS = 2000diff --git a/mods/diff/hooks/limits/timing/index.ts b/mods/diff/hooks/limits/timing/index.tsnew file mode 100644index 00000000..07008be6--- /dev/null+++ b/mods/diff/hooks/limits/timing/index.ts@@ -0,0 +1,7 @@+export * from './git-timeout-ms.js'+export * from './head-poll-ms.js'+export * from './open-probe-ms.js'+export * from './redraw-coalesce-ms.js'+export * from './refresh-debounce-ms.js'++export * as default from '.'diff --git a/mods/diff/hooks/limits/timing/open-probe-ms.ts b/mods/diff/hooks/limits/timing/open-probe-ms.tsnew file mode 100644index 00000000..b25647da--- /dev/null+++ b/mods/diff/hooks/limits/timing/open-probe-ms.ts@@ -0,0 +1,5 @@+/**+ * How long `/diff` waits for the pane to draw after an invalidate before it+ * takes the pane as closed by the person and opens it again.+ */+export const OPEN_PROBE_MS = 120diff --git a/mods/diff/hooks/limits/timing/redraw-coalesce-ms.ts b/mods/diff/hooks/limits/timing/redraw-coalesce-ms.tsnew file mode 100644index 00000000..fa467952--- /dev/null+++ b/mods/diff/hooks/limits/timing/redraw-coalesce-ms.ts@@ -0,0 +1,5 @@+/**+ * How long state changes gather before one `$.ui.invalidate`, keeping the+ * pane under the engine's ten redraws a second.+ */+export const REDRAW_COALESCE_MS = 100diff --git a/mods/diff/hooks/limits/timing/refresh-debounce-ms.ts b/mods/diff/hooks/limits/timing/refresh-debounce-ms.tsnew file mode 100644index 00000000..38332e9c--- /dev/null+++ b/mods/diff/hooks/limits/timing/refresh-debounce-ms.ts@@ -0,0 +1,5 @@+/**+ * The trailing-edge wait between a trigger (an edit, a shell command, a turn+ * step) and the refetch it causes, so a burst of edits fetches once.+ */+export const REFRESH_DEBOUNCE_MS = 150diff --git a/mods/diff/hooks/message-of/index.ts b/mods/diff/hooks/message-of/index.tsnew file mode 100644index 00000000..1de1dae4--- /dev/null+++ b/mods/diff/hooks/message-of/index.ts@@ -0,0 +1,3 @@+export * from './message-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/message-of/message-of.ts b/mods/diff/hooks/message-of/message-of.tsnew file mode 100644index 00000000..1967d034--- /dev/null+++ b/mods/diff/hooks/message-of/message-of.ts@@ -0,0 +1,9 @@+/**+ * A thrown or rejected value as the words it carries: an Error's message,+ * anything else as a string.+ *+ * @param error what was caught+ * @returns the message+ */+export const messageOf = (error: unknown) =>+ error instanceof Error ? error.message : String(error)diff --git a/mods/diff/hooks/mtime-of/index.ts b/mods/diff/hooks/mtime-of/index.tsnew file mode 100644index 00000000..6298941e--- /dev/null+++ b/mods/diff/hooks/mtime-of/index.ts@@ -0,0 +1,3 @@+export * from './mtime-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/mtime-of/mtime-of.ts b/mods/diff/hooks/mtime-of/mtime-of.tsnew file mode 100644index 00000000..80e175fb--- /dev/null+++ b/mods/diff/hooks/mtime-of/mtime-of.ts@@ -0,0 +1,16 @@+import type { Host } from '../host'++/**+ * A path's modification time through the host, or null when the path+ * cannot be read (GitDeps `mtimeOf`).+ *+ * @param engine the bound host+ * @returns the probe+ */+export const mtimeOf =+ (engine: Host) =>+ (path: string): Promise<number | null> =>+ engine.stat(path).then(+ stat => stat.mtimeMs,+ () => null,+ )diff --git a/mods/diff/hooks/names/command-description.ts b/mods/diff/hooks/names/command-description.tsnew file mode 100644index 00000000..780af852--- /dev/null+++ b/mods/diff/hooks/names/command-description.ts@@ -0,0 +1,6 @@+/**+ * What the typeahead and `/help` show for `/diff` (the built-in's fullscreen+ * wording: the pane is the panel's successor).+ */+export const COMMAND_DESCRIPTION =+ 'Toggle the diff panel showing uncommitted changes'diff --git a/mods/diff/hooks/names/command-name.ts b/mods/diff/hooks/names/command-name.tsnew file mode 100644index 00000000..5d9143f8--- /dev/null+++ b/mods/diff/hooks/names/command-name.ts@@ -0,0 +1,4 @@+/**+ * The slash command the plugin serves once the built-in `/diff` stands down.+ */+export const COMMAND_NAME = 'diff'diff --git a/mods/diff/hooks/names/focused-pane/focused-pane.ts b/mods/diff/hooks/names/focused-pane/focused-pane.tsnew file mode 100644index 00000000..32f8533c--- /dev/null+++ b/mods/diff/hooks/names/focused-pane/focused-pane.ts@@ -0,0 +1,9 @@+import type { PaneOpenArgs } from 'claude-code'++/**+ * The part of `$.ui.open`'s argument that asks the surface for the+ * person's keyboard: what `/diff` adds and the first-edit open leaves out.+ */+export const FOCUSED_PANE: Pick<PaneOpenArgs, 'focus'> = Object.freeze({+ focus: true,+})diff --git a/mods/diff/hooks/names/focused-pane/index.ts b/mods/diff/hooks/names/focused-pane/index.tsnew file mode 100644index 00000000..d5e82936--- /dev/null+++ b/mods/diff/hooks/names/focused-pane/index.ts@@ -0,0 +1,3 @@+export * from './focused-pane.js'++export * as default from '.'diff --git a/mods/diff/hooks/names/index.ts b/mods/diff/hooks/names/index.tsnew file mode 100644index 00000000..bcf08ba9--- /dev/null+++ b/mods/diff/hooks/names/index.ts@@ -0,0 +1,9 @@+export * from './command-description.js'+export * from './command-name.js'+export * from './focused-pane'+export * from './keys'+export * from './pane-id.js'+export * from './pane-title.js'+export * from './texts'++export * as default from '.'diff --git a/mods/diff/hooks/names/keys/base-store-key-of.ts b/mods/diff/hooks/names/keys/base-store-key-of.tsnew file mode 100644index 00000000..7896b6d1--- /dev/null+++ b/mods/diff/hooks/names/keys/base-store-key-of.ts@@ -0,0 +1,8 @@+/**+ * The `$.store` key of a working tree's chosen comparison base, one per+ * `--show-toplevel` so a linked worktree keeps its own.+ *+ * @param toplevel the working tree's top-level path+ * @returns the key+ */+export const baseStoreKeyOf = (toplevel: string) => `base:${toplevel}`diff --git a/mods/diff/hooks/names/keys/index.ts b/mods/diff/hooks/names/keys/index.tsnew file mode 100644index 00000000..754b99ce--- /dev/null+++ b/mods/diff/hooks/names/keys/index.ts@@ -0,0 +1,4 @@+export * from './base-store-key-of.js'+export * from './store-open-key.js'++export * as default from '.'diff --git a/mods/diff/hooks/names/keys/store-open-key.ts b/mods/diff/hooks/names/keys/store-open-key.tsnew file mode 100644index 00000000..be9f3fd6--- /dev/null+++ b/mods/diff/hooks/names/keys/store-open-key.ts@@ -0,0 +1,5 @@+/**+ * The `$.store` key holding whether the person keeps the pane open (`/diff`+ * writes it; the first edit reads it): the built-in's `diffSidebarOpen`.+ */+export const STORE_OPEN_KEY = 'open'diff --git a/mods/diff/hooks/names/pane-id.ts b/mods/diff/hooks/names/pane-id.tsnew file mode 100644index 00000000..a3a550ed--- /dev/null+++ b/mods/diff/hooks/names/pane-id.ts@@ -0,0 +1,4 @@+/**+ * The one pane the plugin opens; its `requestId` at `ui.render`.+ */+export const PANE_ID = 'diff'diff --git a/mods/diff/hooks/names/pane-title.ts b/mods/diff/hooks/names/pane-title.tsnew file mode 100644index 00000000..0f586fa8--- /dev/null+++ b/mods/diff/hooks/names/pane-title.ts@@ -0,0 +1,4 @@+/**+ * The pane header's text.+ */+export const PANE_TITLE = 'Diff'diff --git a/mods/diff/hooks/names/texts/builtin-holds-pattern.ts b/mods/diff/hooks/names/texts/builtin-holds-pattern.tsnew file mode 100644index 00000000..afc27dc9--- /dev/null+++ b/mods/diff/hooks/names/texts/builtin-holds-pattern.ts@@ -0,0 +1,5 @@+/**+ * The one `$.command.register` refusal meaning the built-in `/diff` serves+ * this session, as the engine words it: the plugin stands down silently.+ */+export const BUILTIN_HOLDS_PATTERN = /refused: it is the built-in \//diff --git a/mods/diff/hooks/names/texts/index.ts b/mods/diff/hooks/names/texts/index.tsnew file mode 100644index 00000000..4c64e5d4--- /dev/null+++ b/mods/diff/hooks/names/texts/index.ts@@ -0,0 +1,6 @@+export * from './builtin-holds-pattern.js'+export * from './not-in-repository-text.js'+export * from './register-failed-text-of.js'+export * from './untracked-withheld-text.js'++export * as default from '.'diff --git a/mods/diff/hooks/names/texts/not-in-repository-text.ts b/mods/diff/hooks/names/texts/not-in-repository-text.tsnew file mode 100644index 00000000..b9d8bdfe--- /dev/null+++ b/mods/diff/hooks/names/texts/not-in-repository-text.ts@@ -0,0 +1,6 @@+/**+ * `/diff`'s answer outside a git repository, worded as the built-in words it.+ */+export const NOT_IN_REPOSITORY_TEXT =+ 'The diff panel shows git changes — the current directory isn’t in a ' ++ 'git repository'diff --git a/mods/diff/hooks/names/texts/register-failed-text-of.ts b/mods/diff/hooks/names/texts/register-failed-text-of.tsnew file mode 100644index 00000000..11ba7ea7--- /dev/null+++ b/mods/diff/hooks/names/texts/register-failed-text-of.ts@@ -0,0 +1,10 @@+/**+ * The transcript line when `/diff` could not be registered for a reason+ * other than the built-in holding it: the person learns the pane is off.+ *+ * @param reason the refusal's message+ * @returns the line+ */+export const registerFailedTextOf = (reason: string) =>+ `could not register /diff: ${reason}; the diff panel is unavailable this ` ++ `session`diff --git a/mods/diff/hooks/names/texts/untracked-withheld-text.ts b/mods/diff/hooks/names/texts/untracked-withheld-text.tsnew file mode 100644index 00000000..2db14124--- /dev/null+++ b/mods/diff/hooks/names/texts/untracked-withheld-text.ts@@ -0,0 +1,6 @@+/**+ * The pane's word for a fetch whose untracked listing git did not give+ * whole: the tracked rows stand, the new files are not counted.+ */+export const UNTRACKED_WITHHELD_TEXT =+ 'Untracked files unavailable (git could not list them); not counted'diff --git a/mods/diff/hooks/pane-state/after-fetch/after-fetch.ts b/mods/diff/hooks/pane-state/after-fetch/after-fetch.tsnew file mode 100644index 00000000..8e5380d9--- /dev/null+++ b/mods/diff/hooks/pane-state/after-fetch/after-fetch.ts@@ -0,0 +1,29 @@+import Todos from '../../todos'+import Turns from '../../turns'+import type { PaneModel } from '../pane-model'+import type { Fetched } from './fetched'++/**+ * The model once a refresh has settled: the outcome's data (kept as it was+ * when the fetch was unavailable), the transcript's turns and todos.+ *+ * @param model the model before the refresh+ * @param fetched what the refresh read+ * @returns the settled model+ */+export function afterFetch(model: PaneModel, fetched: Fetched): PaneModel {+ const { outcome, messages } = fetched+ const isData = outcome.kind === 'data'+ const isKept = outcome.kind === 'unavailable'+ const data = isData ? outcome.data : isKept ? model.data : null++ return {+ ...model,+ isLoading: false,+ hasSettled: true,+ isOutsideRepository: outcome.kind === 'no-repository',+ data,+ turns: Turns.turnDiffsOf(messages),+ todos: Todos.todoProgressOf(messages),+ }+}diff --git a/mods/diff/hooks/pane-state/after-fetch/fetched/fetched.ts b/mods/diff/hooks/pane-state/after-fetch/fetched/fetched.tsnew file mode 100644index 00000000..c93b77cd--- /dev/null+++ b/mods/diff/hooks/pane-state/after-fetch/fetched/fetched.ts@@ -0,0 +1,11 @@+import type { SessionMessage } from 'claude-code'++import type Git from '../../../git'++/**+ * What one refresh read: how the diff fetch ended and the transcript rows.+ */+export type Fetched = {+ outcome: Git.FetchOutcome+ messages: readonly SessionMessage[]+}diff --git a/mods/diff/hooks/pane-state/after-fetch/fetched/index.ts b/mods/diff/hooks/pane-state/after-fetch/fetched/index.tsnew file mode 100644index 00000000..7262baa1--- /dev/null+++ b/mods/diff/hooks/pane-state/after-fetch/fetched/index.ts@@ -0,0 +1,3 @@+export type * from './fetched.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/after-fetch/index.ts b/mods/diff/hooks/pane-state/after-fetch/index.tsnew file mode 100644index 00000000..227de9d3--- /dev/null+++ b/mods/diff/hooks/pane-state/after-fetch/index.ts@@ -0,0 +1,4 @@+export * from './after-fetch.js'+export * from './fetched'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/after-new-session/after-new-session.ts b/mods/diff/hooks/pane-state/after-new-session/after-new-session.tsnew file mode 100644index 00000000..3769c1c0--- /dev/null+++ b/mods/diff/hooks/pane-state/after-new-session/after-new-session.ts@@ -0,0 +1,14 @@+import type { PaneModel } from '../pane-model'+import { NEW_SESSION_FIELDS } from './new-session-fields'++/**+ * The model after `/clear` or `/resume`: the fetch kept, every pick and+ * the transcript's turns dropped.+ *+ * @param model the model before the switch+ * @returns the reset model+ */+export const afterNewSession = (model: PaneModel): PaneModel => ({+ ...model,+ ...NEW_SESSION_FIELDS,+})diff --git a/mods/diff/hooks/pane-state/after-new-session/index.ts b/mods/diff/hooks/pane-state/after-new-session/index.tsnew file mode 100644index 00000000..04346ab5--- /dev/null+++ b/mods/diff/hooks/pane-state/after-new-session/index.ts@@ -0,0 +1,4 @@+export * from './after-new-session.js'+export * from './new-session-fields'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/after-new-session/new-session-fields/index.ts b/mods/diff/hooks/pane-state/after-new-session/new-session-fields/index.tsnew file mode 100644index 00000000..e57f39c8--- /dev/null+++ b/mods/diff/hooks/pane-state/after-new-session/new-session-fields/index.ts@@ -0,0 +1,3 @@+export * from './new-session-fields.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/after-new-session/new-session-fields/new-session-fields.ts b/mods/diff/hooks/pane-state/after-new-session/new-session-fields/new-session-fields.tsnew file mode 100644index 00000000..6895ebe7--- /dev/null+++ b/mods/diff/hooks/pane-state/after-new-session/new-session-fields/new-session-fields.ts@@ -0,0 +1,11 @@+/**+ * What `/clear` and `/resume` reset: the pick, the source, the turns and+ * the body; the fetch itself stays.+ */+export const NEW_SESSION_FIELDS = Object.freeze({+ selectedPath: null,+ source: Object.freeze({ kind: 'current' }),+ turns: Object.freeze([]),+ body: null,+ bodyState: 'idle',+} as const)diff --git a/mods/diff/hooks/pane-state/base-label-of.ts b/mods/diff/hooks/pane-state/base-label-of.tsnew file mode 100644index 00000000..4bd42d02--- /dev/null+++ b/mods/diff/hooks/pane-state/base-label-of.ts@@ -0,0 +1,43 @@+import type Git from '../git'+import { modeLabelOf } from './mode-label-of'++/**+ * The dim line under the header naming what the diff compares against+ * (ReplDiffSidebar diffBaseLabel), or null for none.+ *+ * Hidden in settled session mode and before any fetch; the requested mode+ * with an ellipsis while its fetch is pending; on an unborn HEAD with+ * rows, what the rows are instead.+ *+ * @param requested the mode the person picked+ * @param data the last good fetch+ * @param filesCount the header's session file count+ * @returns the line, or null+ */+export function baseLabelOf(+ requested: Git.BaseMode,+ data: Git.DiffData | null,+ filesCount: number,+): string | null {+ if (!data) {+ return null+ }++ if (data.isUnborn) {+ const hasRows = filesCount > 0++ return hasRows ? 'no commits yet — showing staged and new files' : null+ }++ const isPending = requested !== data.mode+ const isSettledSession = !isPending && requested === 'session'++ if (isSettledSession) {+ return null+ }++ const phase = isPending ? 'pending' : 'settled'+ const label = modeLabelOf(requested, data.source, phase)++ return isPending ? `${label}…` : label+}diff --git a/mods/diff/hooks/pane-state/base-mode-of/base-mode-of.ts b/mods/diff/hooks/pane-state/base-mode-of/base-mode-of.tsnew file mode 100644index 00000000..de11c94a--- /dev/null+++ b/mods/diff/hooks/pane-state/base-mode-of/base-mode-of.ts@@ -0,0 +1,14 @@+import type Git from '../../git'++/**+ * A stored or picked value as a base mode, or null when it names none.+ *+ * @param value what `$.store.get` returned or a Select carried+ * @returns the mode, or null+ */+export function baseModeOf(value: unknown): Git.BaseMode | null {+ const isMode =+ value === 'session' || value === 'uncommitted' || value === 'branch'++ return isMode ? value : null+}diff --git a/mods/diff/hooks/pane-state/base-mode-of/index.ts b/mods/diff/hooks/pane-state/base-mode-of/index.tsnew file mode 100644index 00000000..3479978c--- /dev/null+++ b/mods/diff/hooks/pane-state/base-mode-of/index.ts@@ -0,0 +1,3 @@+export * from './base-mode-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/body-state/body-state.ts b/mods/diff/hooks/pane-state/body-state/body-state.tsnew file mode 100644index 00000000..7224e104--- /dev/null+++ b/mods/diff/hooks/pane-state/body-state/body-state.ts@@ -0,0 +1,5 @@+/**+ * Where the selected file's body stands: nothing selected, being read, git+ * could not read it, or in hand.+ */+export type BodyState = 'idle' | 'loading' | 'failed' | 'ready'diff --git a/mods/diff/hooks/pane-state/body-state/index.ts b/mods/diff/hooks/pane-state/body-state/index.tsnew file mode 100644index 00000000..a56b3a84--- /dev/null+++ b/mods/diff/hooks/pane-state/body-state/index.ts@@ -0,0 +1,3 @@+export type * from './body-state.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/empty-state-of.ts b/mods/diff/hooks/pane-state/empty-state-of.tsnew file mode 100644index 00000000..65ab7b13--- /dev/null+++ b/mods/diff/hooks/pane-state/empty-state-of.ts@@ -0,0 +1,64 @@+import type Git from '../git'+import Names from '../names'+import type { EmptyState } from './empty-state'++/**+ * The headline that replaces the count when nothing is listed, worded as+ * ReplDiffSidebar words it, keyed on the mode the data was FETCHED in.+ *+ * Null while there are files to count. No data after a settled fetch is+ * "Diff unavailable"; no tracked rows while the untracked listing was+ * withheld claims nothing about new files.+ *+ * @param data the last good fetch, or null when none ever settled+ * @param filesCount the header's session file count+ * @returns the empty state, or null+ */+export function emptyStateOf(+ data: Git.DiffData | null,+ filesCount: number,+): EmptyState | null {+ if (!data) {+ return {+ headline: 'Diff unavailable',+ hint: "Couldn't read the git diff — it will retry on the next change",+ }+ }++ if (filesCount > 0) {+ return null+ }++ if (data.isUntrackedWithheld) {+ return {+ headline: 'No tracked changes',+ hint: Names.UNTRACKED_WITHHELD_TEXT,+ }+ }++ if (data.isUnborn) {+ return {+ headline: 'No commits yet',+ hint: "Nothing to diff against until the repo's first commit",+ }+ }++ switch (data.mode) {+ case 'uncommitted':+ return { headline: 'No uncommitted changes', hint: null }+ case 'branch':+ if (data.source.kind === 'branch') {+ return {+ headline: `No changes vs ${data.source.baseBranch}`,+ hint: null,+ }+ }++ return {+ headline: 'No changes vs HEAD',+ hint: 'No base branch to compare against — showing changes vs HEAD',+ }+ case 'session':+ return { headline: 'No changes this session', hint: null }+ }+}diff --git a/mods/diff/hooks/pane-state/empty-state/empty-state.ts b/mods/diff/hooks/pane-state/empty-state/empty-state.tsnew file mode 100644index 00000000..1ae9e9d2--- /dev/null+++ b/mods/diff/hooks/pane-state/empty-state/empty-state.ts@@ -0,0 +1,8 @@+/**+ * What the header says instead of a count when there is nothing to list,+ * and the body's hint under it when the hint adds something.+ */+export type EmptyState = {+ headline: string+ hint: string | null+}diff --git a/mods/diff/hooks/pane-state/empty-state/index.ts b/mods/diff/hooks/pane-state/empty-state/index.tsnew file mode 100644index 00000000..6a00dc2d--- /dev/null+++ b/mods/diff/hooks/pane-state/empty-state/index.ts@@ -0,0 +1,3 @@+export type * from './empty-state.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/header-totals-of.ts b/mods/diff/hooks/pane-state/header-totals-of.tsnew file mode 100644index 00000000..615c4dc4--- /dev/null+++ b/mods/diff/hooks/pane-state/header-totals-of.ts@@ -0,0 +1,32 @@+import type Git from '../git'+import type { HeaderTotals } from './header-totals'+import type { Partition } from './partition'++/**+ * The header's counts (ReplDiffSidebar): the fetched totals less the+ * pre-session rows, and how many session files fell past the row cap.+ *+ * Files past the cap were never dated, so they always count and always+ * show as `notShown`: an edit that sorts after fifty older ones stays seen.+ *+ * @param data the fetch+ * @param partition its rows, grouped+ * @returns the counts and how many session files are past the cap+ */+export function headerTotalsOf(+ data: Git.DiffData,+ partition: Partition,+): HeaderTotals {+ const { stats, files } = data+ const before = partition.preSession+ const filesCount = stats.filesCount - before.length++ return {+ filesCount,+ linesAdded:+ stats.linesAdded - before.reduce((sum, file) => sum + file.added, 0),+ linesRemoved:+ stats.linesRemoved - before.reduce((sum, file) => sum + file.removed, 0),+ notShown: Math.max(0, filesCount - (files.length - before.length)),+ }+}diff --git a/mods/diff/hooks/pane-state/header-totals/header-totals.ts b/mods/diff/hooks/pane-state/header-totals/header-totals.tsnew file mode 100644index 00000000..7bbb1409--- /dev/null+++ b/mods/diff/hooks/pane-state/header-totals/header-totals.ts@@ -0,0 +1,10 @@+/**+ * The header's counts: the fetched totals less the pre-session rows, and+ * how many session files fell past the row cap ("not shown").+ */+export type HeaderTotals = {+ filesCount: number+ linesAdded: number+ linesRemoved: number+ notShown: number+}diff --git a/mods/diff/hooks/pane-state/header-totals/index.ts b/mods/diff/hooks/pane-state/header-totals/index.tsnew file mode 100644index 00000000..3b4702ca--- /dev/null+++ b/mods/diff/hooks/pane-state/header-totals/index.ts@@ -0,0 +1,3 @@+export type * from './header-totals.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/index.ts b/mods/diff/hooks/pane-state/index.tsnew file mode 100644index 00000000..8a952ba9--- /dev/null+++ b/mods/diff/hooks/pane-state/index.ts@@ -0,0 +1,22 @@+export * from './after-fetch'+export * from './after-new-session'+export * from './base-label-of.js'+export * from './base-mode-of'+export * from './body-state'+export * from './empty-state'+export * from './empty-state-of.js'+export * from './header-totals'+export * from './header-totals-of.js'+export * from './initial-model'+export * from './listed-of.js'+export * from './mode-label-of'+export * from './pane-model'+export * from './partition'+export * from './partition-of.js'+export * from './picked-turn-of'+export * from './selection-of'+export * from './source'+export * from './turn-totals-of'+export * from './zero-totals'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/initial-model/index.ts b/mods/diff/hooks/pane-state/initial-model/index.tsnew file mode 100644index 00000000..912d01fa--- /dev/null+++ b/mods/diff/hooks/pane-state/initial-model/index.ts@@ -0,0 +1,3 @@+export * from './initial-model.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/initial-model/initial-model.ts b/mods/diff/hooks/pane-state/initial-model/initial-model.tsnew file mode 100644index 00000000..73e1982b--- /dev/null+++ b/mods/diff/hooks/pane-state/initial-model/initial-model.ts@@ -0,0 +1,23 @@+import type { PaneModel } from '../pane-model'++/**+ * The pane before anything happened: session mode, nothing fetched,+ * nothing picked, the current source.+ */+export const INITIAL_MODEL: PaneModel = Object.freeze({+ isLoading: false,+ hasSettled: false,+ isOutsideRepository: false,+ data: null,+ requestedMode: 'session',+ selectedPath: null,+ isNoiseShown: false,+ isPreSessionShown: false,+ source: Object.freeze({ kind: 'current' }),+ turns: Object.freeze([]),+ body: null,+ bodyState: 'idle',+ todos: Object.freeze({ done: 0, total: 0 }),+ armedPath: null,+ isFocused: false,+})diff --git a/mods/diff/hooks/pane-state/listed-of.ts b/mods/diff/hooks/pane-state/listed-of.tsnew file mode 100644index 00000000..4aa75dda--- /dev/null+++ b/mods/diff/hooks/pane-state/listed-of.ts@@ -0,0 +1,21 @@+import type Git from '../git'+import type { Partition } from './partition'++/**+ * The rows a person can pick from right now: the session's shown rows,+ * then the pre-session rows while that section is open.+ *+ * @param partition the fetch's rows, grouped+ * @param preSession whether the pre-session section is open+ * @returns the pickable rows in drawing order+ */+export function listedOf(+ partition: Partition,+ preSession: 'shown' | 'hidden',+): readonly Git.FileStat[] {+ const isOpen = preSession === 'shown'++ return isOpen+ ? [...partition.shown, ...partition.preSession]+ : partition.shown+}diff --git a/mods/diff/hooks/pane-state/mode-label-of/index.ts b/mods/diff/hooks/pane-state/mode-label-of/index.tsnew file mode 100644index 00000000..04fb5c40--- /dev/null+++ b/mods/diff/hooks/pane-state/mode-label-of/index.ts@@ -0,0 +1,3 @@+export * from './mode-label-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/mode-label-of/mode-label-of.ts b/mods/diff/hooks/pane-state/mode-label-of/mode-label-of.tsnew file mode 100644index 00000000..92479e83--- /dev/null+++ b/mods/diff/hooks/pane-state/mode-label-of/mode-label-of.ts@@ -0,0 +1,29 @@+import type Git from '../../git'++/**+ * A requested mode's name for the base line; branch mode names its base+ * branch from the data, or says what stands in while none is known.+ *+ * @param requested the mode the person picked+ * @param source what the data on screen compares+ * @param phase `pending` while the requested mode's fetch has not landed+ * @returns the label without its pending ellipsis+ */+export function modeLabelOf(+ requested: Git.BaseMode,+ source: Git.DiffSource,+ phase: 'pending' | 'settled',+) {+ switch (requested) {+ case 'session':+ return 'this session'+ case 'uncommitted':+ return 'uncommitted (vs HEAD)'+ case 'branch':+ if (source.kind === 'branch') {+ return `branch vs ${source.baseBranch}`+ }++ return phase === 'pending' ? 'branch diff' : 'vs HEAD (no base branch)'+ }+}diff --git a/mods/diff/hooks/pane-state/pane-model/index.ts b/mods/diff/hooks/pane-state/pane-model/index.tsnew file mode 100644index 00000000..41959688--- /dev/null+++ b/mods/diff/hooks/pane-state/pane-model/index.ts@@ -0,0 +1,3 @@+export type * from './pane-model.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/pane-model/pane-model.ts b/mods/diff/hooks/pane-state/pane-model/pane-model.tsnew file mode 100644index 00000000..e72e23dc--- /dev/null+++ b/mods/diff/hooks/pane-state/pane-model/pane-model.ts@@ -0,0 +1,27 @@+import type Git from '../../git'+import type Todos from '../../todos'+import type Turns from '../../turns'+import type { BodyState } from '../body-state'+import type { Source } from '../source'++/**+ * Everything one drawing of the pane reads: the last good fetch, what the+ * person picked, the selected file's body, the transcript's turns and todos.+ */+export type PaneModel = {+ isLoading: boolean+ hasSettled: boolean+ isOutsideRepository: boolean+ data: Git.DiffData | null+ requestedMode: Git.BaseMode+ selectedPath: string | null+ isNoiseShown: boolean+ isPreSessionShown: boolean+ source: Source+ turns: readonly Turns.TurnDiff[]+ body: Git.FileHunks | null+ bodyState: BodyState+ todos: Todos.TodoProgress+ armedPath: string | null+ isFocused: boolean+}diff --git a/mods/diff/hooks/pane-state/partition-of.ts b/mods/diff/hooks/pane-state/partition-of.tsnew file mode 100644index 00000000..d2a5ed83--- /dev/null+++ b/mods/diff/hooks/pane-state/partition-of.ts@@ -0,0 +1,28 @@+import Classify from '../classify'+import type Git from '../git'+import type { Partition } from './partition'++/**+ * A fetch's rows split the way ReplDiffSidebar splits them: pre-session+ * rows apart, tests and generated files counted and hidden unless shown.+ *+ * No read-deny bucket: the pane feeds nothing to the model on its own.+ *+ * @param files the fetched rows+ * @param noise `shown` keeps tests and generated files in the list+ * @returns the groups+ */+export function partitionOf(+ files: readonly Git.FileStat[],+ noise: 'shown' | 'hidden',+): Partition {+ const preSession = files.filter(file => file.isPreSession)+ const session = files.filter(file => !file.isPreSession)+ const quiet = session.filter(file => !Classify.isNoiseFile(file.path))++ return {+ shown: noise === 'shown' ? session : quiet,+ preSession,+ noiseCount: session.length - quiet.length,+ }+}diff --git a/mods/diff/hooks/pane-state/partition/index.ts b/mods/diff/hooks/pane-state/partition/index.tsnew file mode 100644index 00000000..993d49fe--- /dev/null+++ b/mods/diff/hooks/pane-state/partition/index.ts@@ -0,0 +1,3 @@+export type * from './partition.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/partition/partition.ts b/mods/diff/hooks/pane-state/partition/partition.tsnew file mode 100644index 00000000..befaaee5--- /dev/null+++ b/mods/diff/hooks/pane-state/partition/partition.ts@@ -0,0 +1,11 @@+import type Git from '../../git'++/**+ * A fetch's rows as the pane groups them: the session's own that are+ * listed, how many tests and generated files there are, the pre-session.+ */+export type Partition = {+ shown: readonly Git.FileStat[]+ preSession: readonly Git.FileStat[]+ noiseCount: number+}diff --git a/mods/diff/hooks/pane-state/picked-turn-of/index.ts b/mods/diff/hooks/pane-state/picked-turn-of/index.tsnew file mode 100644index 00000000..02451531--- /dev/null+++ b/mods/diff/hooks/pane-state/picked-turn-of/index.ts@@ -0,0 +1,3 @@+export * from './picked-turn-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/picked-turn-of/picked-turn-of.ts b/mods/diff/hooks/pane-state/picked-turn-of/picked-turn-of.tsnew file mode 100644index 00000000..b83f5271--- /dev/null+++ b/mods/diff/hooks/pane-state/picked-turn-of/picked-turn-of.ts@@ -0,0 +1,16 @@+import type Turns from '../../turns'+import type { PaneModel } from '../pane-model'++/**+ * The turn the pane's source names while the transcript still holds it;+ * undefined for the current source or a turn a rewind dropped.+ *+ * @param model the pane's state+ * @returns the picked turn, or undefined+ */+export function pickedTurnOf(model: PaneModel): Turns.TurnDiff | undefined {+ const { source } = model+ const wanted = source.kind === 'turn' ? source.index : null++ return model.turns.find(candidate => candidate.index === wanted)+}diff --git a/mods/diff/hooks/pane-state/selection-of/index.ts b/mods/diff/hooks/pane-state/selection-of/index.tsnew file mode 100644index 00000000..17269d9f--- /dev/null+++ b/mods/diff/hooks/pane-state/selection-of/index.ts@@ -0,0 +1,3 @@+export * from './selection-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/selection-of/selection-of.ts b/mods/diff/hooks/pane-state/selection-of/selection-of.tsnew file mode 100644index 00000000..9d47d05c--- /dev/null+++ b/mods/diff/hooks/pane-state/selection-of/selection-of.ts@@ -0,0 +1,16 @@+import type Git from '../../git'++/**+ * The file whose body the pane shows: the one the person picked while it is+ * still listed, else the first listed one, else none.+ *+ * @param listed the rows on screen, in order (session rows, then the+ * pre-session rows while that section is open)+ * @param selectedPath the person's pick, or null+ * @returns the selected row, or null for an empty list+ */+export const selectionOf = (+ listed: readonly Git.FileStat[],+ selectedPath: string | null,+): Git.FileStat | null =>+ listed.find(file => file.path === selectedPath) ?? listed[0] ?? nulldiff --git a/mods/diff/hooks/pane-state/source/index.ts b/mods/diff/hooks/pane-state/source/index.tsnew file mode 100644index 00000000..f1b0da3a--- /dev/null+++ b/mods/diff/hooks/pane-state/source/index.ts@@ -0,0 +1,3 @@+export type * from './source.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/source/source.ts b/mods/diff/hooks/pane-state/source/source.tsnew file mode 100644index 00000000..e5621a26--- /dev/null+++ b/mods/diff/hooks/pane-state/source/source.ts@@ -0,0 +1,4 @@+/**+ * What the pane lists: the repository's diff now, or one past turn's edits.+ */+export type Source = { kind: 'current' } | { kind: 'turn'; index: number }diff --git a/mods/diff/hooks/pane-state/turn-totals-of/index.ts b/mods/diff/hooks/pane-state/turn-totals-of/index.tsnew file mode 100644index 00000000..e33459e0--- /dev/null+++ b/mods/diff/hooks/pane-state/turn-totals-of/index.ts@@ -0,0 +1,3 @@+export * from './turn-totals-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/turn-totals-of/turn-totals-of.ts b/mods/diff/hooks/pane-state/turn-totals-of/turn-totals-of.tsnew file mode 100644index 00000000..ea49e80a--- /dev/null+++ b/mods/diff/hooks/pane-state/turn-totals-of/turn-totals-of.ts@@ -0,0 +1,16 @@+import type Turns from '../../turns'+import type { HeaderTotals } from '../header-totals'++/**+ * A turn's header counts: its files and their summed lines; nothing falls+ * past a cap.+ *+ * @param turn the turn+ * @returns the counts+ */+export const turnTotalsOf = (turn: Turns.TurnDiff): HeaderTotals => ({+ filesCount: turn.files.length,+ linesAdded: turn.files.reduce((sum, file) => sum + file.added, 0),+ linesRemoved: turn.files.reduce((sum, file) => sum + file.removed, 0),+ notShown: 0,+})diff --git a/mods/diff/hooks/pane-state/zero-totals/index.ts b/mods/diff/hooks/pane-state/zero-totals/index.tsnew file mode 100644index 00000000..59d381c3--- /dev/null+++ b/mods/diff/hooks/pane-state/zero-totals/index.ts@@ -0,0 +1,3 @@+export * from './zero-totals.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-state/zero-totals/zero-totals.ts b/mods/diff/hooks/pane-state/zero-totals/zero-totals.tsnew file mode 100644index 00000000..9c372e1a--- /dev/null+++ b/mods/diff/hooks/pane-state/zero-totals/zero-totals.ts@@ -0,0 +1,12 @@+import type { HeaderTotals } from '../header-totals'++/**+ * The header's counts when no fetch has settled into data: nothing+ * changed, nothing past the cap.+ */+export const ZERO_TOTALS: HeaderTotals = Object.freeze({+ filesCount: 0,+ linesAdded: 0,+ linesRemoved: 0,+ notShown: 0,+})diff --git a/mods/diff/hooks/pane-toggle/index.ts b/mods/diff/hooks/pane-toggle/index.tsnew file mode 100644index 00000000..3730c793--- /dev/null+++ b/mods/diff/hooks/pane-toggle/index.ts@@ -0,0 +1,4 @@+export * from './pane-belief'+export * from './pane-toggle-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-toggle/pane-belief/index.ts b/mods/diff/hooks/pane-toggle/pane-belief/index.tsnew file mode 100644index 00000000..921fcf30--- /dev/null+++ b/mods/diff/hooks/pane-toggle/pane-belief/index.ts@@ -0,0 +1,3 @@+export type * from './pane-belief.js'++export * as default from '.'diff --git a/mods/diff/hooks/pane-toggle/pane-belief/pane-belief.ts b/mods/diff/hooks/pane-toggle/pane-belief/pane-belief.tsnew file mode 100644index 00000000..80c4475e--- /dev/null+++ b/mods/diff/hooks/pane-toggle/pane-belief/pane-belief.ts@@ -0,0 +1,8 @@+/**+ * What the plugin knows of its pane when `/diff` runs: whether it opened+ * it and never closed it, and whether it drew when a redraw was asked.+ */+export type PaneBelief = {+ isBelievedOpen: boolean+ wasDrawnWhenProbed: boolean+}diff --git a/mods/diff/hooks/pane-toggle/pane-toggle-of.ts b/mods/diff/hooks/pane-toggle/pane-toggle-of.tsnew file mode 100644index 00000000..24eca7a0--- /dev/null+++ b/mods/diff/hooks/pane-toggle/pane-toggle-of.ts@@ -0,0 +1,14 @@+import type { PaneBelief } from './pane-belief'++/**+ * What `/diff` does, the one place its toggle is decided: close only when+ * the plugin opened the pane and it still draws; otherwise open, focused.+ *+ * The person's `[x]` raises nothing a plugin sees, so a pane believed+ * open is probed with a redraw first.+ *+ * @param pane the plugin's belief and the probe's answer+ * @returns `close` or `open`+ */+export const paneToggleOf = (pane: PaneBelief): 'open' | 'close' =>+ pane.isBelievedOpen && pane.wasDrawnWhenProbed ? 'close' : 'open'diff --git a/mods/diff/hooks/record/features/features.ts b/mods/diff/hooks/record/features/features.tsnew file mode 100644index 00000000..a667977e--- /dev/null+++ b/mods/diff/hooks/record/features/features.ts@@ -0,0 +1,13 @@+/**+ * The feature names the plugin marks, kept as the built-in panel's so the+ * feature surface keeps one series across the swap.+ *+ * `read` per fetch round, `tabSwitch` per open or close, `baseSwitch` per+ * base pick, `baseResolve` once a session.+ */+export const FEATURES = {+ read: 'repl_diff_read',+ tabSwitch: 'repl_tab_switch',+ baseSwitch: 'repl_diff_base_switch',+ baseResolve: 'diff_base_resolve',+} as constdiff --git a/mods/diff/hooks/record/features/index.ts b/mods/diff/hooks/record/features/index.tsnew file mode 100644index 00000000..672d470c--- /dev/null+++ b/mods/diff/hooks/record/features/index.ts@@ -0,0 +1,3 @@+export * from './features.js'++export * as default from '.'diff --git a/mods/diff/hooks/record/index.ts b/mods/diff/hooks/record/index.tsnew file mode 100644index 00000000..6a541ec8--- /dev/null+++ b/mods/diff/hooks/record/index.ts@@ -0,0 +1,10 @@+export * from './features'+export * from './mark-outcome'+export * from './recorder'+export * from './recorder-of.js'+export * from './safely'+export * from './shown-triggers'+export * from './width-bucket-of'+export * from './width-buckets'++export * as default from '.'diff --git a/mods/diff/hooks/record/mark-outcome/index.ts b/mods/diff/hooks/record/mark-outcome/index.tsnew file mode 100644index 00000000..d6e18091--- /dev/null+++ b/mods/diff/hooks/record/mark-outcome/index.ts@@ -0,0 +1,3 @@+export type * from './mark-outcome.js'++export * as default from '.'diff --git a/mods/diff/hooks/record/mark-outcome/mark-outcome.ts b/mods/diff/hooks/record/mark-outcome/mark-outcome.tsnew file mode 100644index 00000000..697c5393--- /dev/null+++ b/mods/diff/hooks/record/mark-outcome/mark-outcome.ts@@ -0,0 +1,5 @@+/**+ * How a marked feature went: fine, or degraded for a reason (the pane never+ * marks `bad`: a failed fetch keeps the last good diff on screen).+ */+export type MarkOutcome = { kind: 'ok' } | { kind: 'sad'; reason: string }diff --git a/mods/diff/hooks/record/recorder-of.ts b/mods/diff/hooks/record/recorder-of.tsnew file mode 100644index 00000000..015661f6--- /dev/null+++ b/mods/diff/hooks/record/recorder-of.ts@@ -0,0 +1,28 @@+import type { Host } from '../host'+import type { Recorder } from './recorder'+import { safely } from './safely'+import { SHOWN_TRIGGERS } from './shown-triggers'+import { WIDTH_BUCKETS } from './width-buckets'++/**+ * The plugin's Recorder over the host: each row goes through the telemetry+ * built-in's `$.telemetry`; a missing noun or a refused row is dropped.+ *+ * @param host the engine as session.start bound it+ * @returns the recorder+ */+export const recorderOf = (host: Host): Recorder => ({+ mark: (feature, outcome) => safely(() => host.mark({ feature, ...outcome })),+ shown: (trigger, bucket) =>+ safely(() =>+ host.log({+ event: 'diff_pane_shown',+ props: {+ trigger: { value: trigger, of: SHOWN_TRIGGERS },+ width_bucket: { value: bucket, of: WIDTH_BUCKETS },+ },+ }),+ ),+ asked: lines =>+ safely(() => host.log({ event: 'diff_ask_attach', props: { lines } })),+})diff --git a/mods/diff/hooks/record/recorder/index.ts b/mods/diff/hooks/record/recorder/index.tsnew file mode 100644index 00000000..ffa2cf74--- /dev/null+++ b/mods/diff/hooks/record/recorder/index.ts@@ -0,0 +1,3 @@+export type * from './recorder.js'++export * as default from '.'diff --git a/mods/diff/hooks/record/recorder/recorder.ts b/mods/diff/hooks/record/recorder/recorder.tsnew file mode 100644index 00000000..899d0b99--- /dev/null+++ b/mods/diff/hooks/record/recorder/recorder.ts@@ -0,0 +1,27 @@+import type { MarkOutcome } from '../mark-outcome'+import type { SHOWN_TRIGGERS } from '../shown-triggers'+import type { WIDTH_BUCKETS } from '../width-buckets'++/**+ * The plugin's telemetry as its hooks call it; every method swallows a+ * missing `$.telemetry` and a refused row, so recording never disturbs.+ */+export type Recorder = {+ /**+ * One `tengu_feature_<kind>` row.+ */+ mark: (feature: string, outcome: MarkOutcome) => void++ /**+ * `tengu_plugin_diff_pane_shown`, once a session.+ */+ shown: (+ trigger: (typeof SHOWN_TRIGGERS)[number],+ bucket: (typeof WIDTH_BUCKETS)[number],+ ) => void++ /**+ * `tengu_plugin_diff_ask_attach`: a file's diff rode the next prompt.+ */+ asked: (lines: number) => void+}diff --git a/mods/diff/hooks/record/safely/index.ts b/mods/diff/hooks/record/safely/index.tsnew file mode 100644index 00000000..002c90f9--- /dev/null+++ b/mods/diff/hooks/record/safely/index.ts@@ -0,0 +1,3 @@+export * from './safely.js'++export * as default from '.'diff --git a/mods/diff/hooks/record/safely/safely.ts b/mods/diff/hooks/record/safely/safely.tsnew file mode 100644index 00000000..8bda37a7--- /dev/null+++ b/mods/diff/hooks/record/safely/safely.ts@@ -0,0 +1,11 @@+/**+ * Sends one telemetry row and forgets it: a missing `$.telemetry` (no+ * telemetry built-in) throws synchronously, a refused row rejects; both drop.+ *+ * @param send posts the row+ */+export function safely(send: () => Promise<void>) {+ try {+ void send().catch(() => undefined)+ } catch {}+}diff --git a/mods/diff/hooks/record/shown-triggers/index.ts b/mods/diff/hooks/record/shown-triggers/index.tsnew file mode 100644index 00000000..0c963ba6--- /dev/null+++ b/mods/diff/hooks/record/shown-triggers/index.ts@@ -0,0 +1,3 @@+export * from './shown-triggers.js'++export * as default from '.'diff --git a/mods/diff/hooks/record/shown-triggers/shown-triggers.ts b/mods/diff/hooks/record/shown-triggers/shown-triggers.tsnew file mode 100644index 00000000..fdb1a80e--- /dev/null+++ b/mods/diff/hooks/record/shown-triggers/shown-triggers.ts@@ -0,0 +1,5 @@+/**+ * What opened the pane the first time it showed this session: Claude's+ * first edit, or the person's `/diff`.+ */+export const SHOWN_TRIGGERS = ['auto_open', 'manual'] as constdiff --git a/mods/diff/hooks/record/width-bucket-of/index.ts b/mods/diff/hooks/record/width-bucket-of/index.tsnew file mode 100644index 00000000..9127054c--- /dev/null+++ b/mods/diff/hooks/record/width-bucket-of/index.ts@@ -0,0 +1,3 @@+export * from './width-bucket-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/record/width-bucket-of/width-bucket-of.ts b/mods/diff/hooks/record/width-bucket-of/width-bucket-of.tsnew file mode 100644index 00000000..d98208e3--- /dev/null+++ b/mods/diff/hooks/record/width-bucket-of/width-bucket-of.ts@@ -0,0 +1,21 @@+import Limits from '../../limits'+import { WIDTH_BUCKETS } from '../width-buckets'++/**+ * The bucket a terminal width falls in, the built-in panel's own buckets.+ *+ * @param columns the terminal's width, or null when no render told it yet+ * @returns one of WIDTH_BUCKETS+ */+export function widthBucketOf(+ columns: number | null,+): (typeof WIDTH_BUCKETS)[number] {+ const [narrow, medium, wide, widest] = WIDTH_BUCKETS+ const width = columns ?? 0++ const isNarrow = width < Limits.OPEN_MIN_COLUMNS+ const isMedium = width < Limits.AUTO_OPEN_MIN_COLUMNS+ const isWide = width < Limits.WIDEST_BUCKET_COLUMNS++ return isNarrow ? narrow : isMedium ? medium : isWide ? wide : widest+}diff --git a/mods/diff/hooks/record/width-buckets/index.ts b/mods/diff/hooks/record/width-buckets/index.tsnew file mode 100644index 00000000..14a139cd--- /dev/null+++ b/mods/diff/hooks/record/width-buckets/index.ts@@ -0,0 +1,3 @@+export * from './width-buckets.js'++export * as default from '.'diff --git a/mods/diff/hooks/record/width-buckets/width-buckets.ts b/mods/diff/hooks/record/width-buckets/width-buckets.tsnew file mode 100644index 00000000..a979845b--- /dev/null+++ b/mods/diff/hooks/record/width-buckets/width-buckets.ts@@ -0,0 +1,10 @@+/**+ * The terminal-width buckets `diff_pane_shown` reports, the built-in's+ * `tengu_repl_diff_panel_shown` buckets.+ */+export const WIDTH_BUCKETS = [+ 'under_110',+ '110_to_143',+ '144_to_199',+ '200_plus',+] as constdiff --git a/mods/diff/hooks/register.ts b/mods/diff/hooks/register.tsnew file mode 100644index 00000000..3cbacb70--- /dev/null+++ b/mods/diff/hooks/register.ts@@ -0,0 +1,575 @@+import type { On, ResultOf, SessionMessage, Timer } from 'claude-code'++import Ask from './ask'+import { COMMAND_SPEC } from './command-spec'+import { entryKindsOf } from './entry-kinds-of'+import Git from './git'+import type { Host } from './host'+import { isOnPaneSurface } from './is-on-pane-surface'+import Limits from './limits'+import { messageOf } from './message-of'+import { mtimeOf } from './mtime-of'+import Names from './names'+import PaneState from './pane-state'+import PaneToggle from './pane-toggle'+import Record from './record'+import Tools from './tools'+import Views from './views'++/**+ * Registers the diff pane: `/diff` once the built-in stands down, the+ * pane's drawing and refresh, its opening on Claude's first edit, the ask.+ *+ * `session.start` binds the engine once, registers the command (refused+ * because the built-in holds it, the plugin does nothing) and pins the+ * repository (probed again on `/diff` and first edit until found).+ *+ * @param on the engine's registrar+ */+export function register(on: On) {+ let host: Host | null = null+ let repository: Git.Repository | null = null+ let sessionStartMs = 0+ let isPaneOpen = false+ let hasAutoOpened = false+ let columns: number | null = null+ let hasShownOnce = false+ let wasDrawnSinceProbe = false+ let armed: Ask.ArmedAsk | null = null+ let isRefreshing = false+ let isRefreshQueued = false+ let generation = 0+ let bodyKey: string | null = null+ const polled = { gitDir: '', headKey: '' }+ let model: PaneState.PaneModel = PaneState.INITIAL_MODEL+ const timers = new Map<'refresh' | 'redraw' | 'poll', Timer>()+ const loggedBaseKinds = new Set<'ok' | 'sad'>()++ const gitOf =+ (engine: Host, pinned: Git.Repository | null): Git.GitRun =>+ async argv => {+ try {+ return await engine.run(+ ['git', ...(pinned ? Git.pinnedLeadOf(pinned) : []), ...argv],+ {+ timeoutMs: Limits.GIT_TIMEOUT_MS,+ env: Git.GIT_CHILD_ENV,+ ...(pinned && { cwd: pinned.toplevel }),+ },+ )+ } catch {+ return { exitCode: -1, stdout: '', stderr: '' }+ }+ }++ async function pinRepository(engine: Host): Promise<void> {+ if (repository) {+ return+ }++ const probed = await Git.repositoryOf(gitOf(engine, null))+ repository ??= probed++ if (!probed || repository !== probed) {+ return+ }++ const mode = PaneState.baseModeOf(+ await engine+ .storeGet(Names.baseStoreKeyOf(probed.toplevel))+ .catch(() => undefined),+ )++ if (mode) {+ model = { ...model, requestedMode: mode }+ }+ }++ const depsOf = (engine: Host, pinned: Git.Repository): Git.GitDeps => ({+ run: gitOf(engine, pinned),+ repository: pinned,+ mtimeOf: mtimeOf(engine),+ entryKindsOf: entryKindsOf(engine),+ sessionStartMs,+ onBranchBase: base => {+ const isError = base.kind === 'error'+ const outcome: Record.MarkOutcome = isError+ ? { kind: 'sad', reason: base.reason }+ : { kind: 'ok' }++ if (!loggedBaseKinds.has(outcome.kind)) {+ loggedBaseKinds.add(outcome.kind)+ Record.recorderOf(engine).mark(Record.FEATURES.baseResolve, outcome)+ }+ },+ })++ function redraw(engine: Host) {+ if (timers.has('redraw')) {+ return+ }++ timers.set(+ 'redraw',+ engine.after(Limits.REDRAW_COALESCE_MS, () => {+ timers.delete('redraw')+ engine.invalidate()+ }),+ )+ }++ const selectedOf = (): Git.FileStat | null =>+ PaneState.selectionOf(+ PaneState.listedOf(+ PaneState.partitionOf(+ model.data?.files ?? [],+ model.isNoiseShown ? 'shown' : 'hidden',+ ),+ model.isPreSessionShown ? 'shown' : 'hidden',+ ),+ model.selectedPath,+ )++ async function loadBody(engine: Host): Promise<void> {+ const { data } = model+ const selected = selectedOf()++ if (!data || !selected || !repository) {+ bodyKey = null+ model = { ...model, body: null, bodyState: 'idle' }++ return+ }++ const key = `${generation}|${data.baseRef}|${selected.path}`++ if (key === bodyKey) {+ return+ }++ bodyKey = key+ model = { ...model, body: null, bodyState: 'loading' }+ redraw(engine)+ const body = await Git.fetchFileHunks(+ gitOf(engine, repository),+ data,+ selected,+ )++ if (bodyKey !== key) {+ return+ }++ model = { ...model, body, bodyState: body ? 'ready' : 'failed' }+ redraw(engine)+ }++ function startPoll(engine: Host, polledRepository: Git.Repository) {+ const readHeadKey = () =>+ Git.headKeyOf(+ {+ run: gitOf(engine, polledRepository),+ mtimeOf: mtimeOf(engine),+ entryKindsOf: entryKindsOf(engine),+ readFile: path => engine.readFile(path),+ },+ polledRepository,+ ).catch(() => '')++ if (polled.gitDir === polledRepository.gitDir) {+ return+ }++ timers.get('poll')?.cancel()+ polled.gitDir = polledRepository.gitDir+ polled.headKey = ''+ timers.set(+ 'poll',+ engine.every(Limits.HEAD_POLL_MS, () => {+ if (!isPaneOpen) {+ return+ }++ void readHeadKey().then(key => {+ const hasMoved = polled.headKey !== '' && key !== polled.headKey+ polled.headKey = key++ if (hasMoved) {+ scheduleRefresh(engine)+ }+ })+ }),+ )+ }++ async function refresh(engine: Host): Promise<void> {+ if (isRefreshing) {+ isRefreshQueued = true++ return+ }++ isRefreshing = true+ const record = Record.recorderOf(engine)+ const fetched = (): Promise<Git.FetchOutcome> =>+ repository+ ? Git.fetchDiff(depsOf(engine, repository), model.requestedMode)+ : Promise.resolve({ kind: 'no-repository' })++ try {+ model = { ...model, isLoading: model.data === null }+ const [outcome, messages] = await Promise.all([+ fetched(),+ engine.messages().catch((): SessionMessage[] => []),+ ])+ model = PaneState.afterFetch(model, { outcome, messages })++ switch (outcome.kind) {+ case 'no-repository':+ break+ case 'unavailable':+ record.mark(Record.FEATURES.read, {+ kind: 'sad',+ reason: 'git_diff_failed',+ })+ break+ case 'data':+ record.mark(Record.FEATURES.read, { kind: 'ok' })+ generation += 1+ startPoll(engine, outcome.data.repository)+ break+ }++ await loadBody(engine)+ } finally {+ isRefreshing = false+ redraw(engine)++ if (isRefreshQueued) {+ isRefreshQueued = false+ scheduleRefresh(engine)+ }+ }+ }++ function scheduleRefresh(engine: Host): void {+ timers.get('refresh')?.cancel()+ timers.set(+ 'refresh',+ engine.after(Limits.REFRESH_DEBOUNCE_MS, () => {+ timers.delete('refresh')+ void refresh(engine)+ }),+ )+ }++ async function openPane(+ engine: Host,+ trigger: (typeof Record.SHOWN_TRIGGERS)[number],+ ): Promise<void> {+ const pane = { id: Names.PANE_ID, title: Names.PANE_TITLE }+ const isManual = trigger === 'manual'+ await engine.openPane(isManual ? { ...pane, ...Names.FOCUSED_PANE } : pane)+ isPaneOpen = true+ const record = Record.recorderOf(engine)+ record.mark(Record.FEATURES.tabSwitch, { kind: 'ok' })++ if (!hasShownOnce) {+ hasShownOnce = true+ record.shown(trigger, Record.widthBucketOf(columns))+ }++ void refresh(engine)+ }++ async function closePane(engine: Host): Promise<void> {+ await engine.closePane({ id: Names.PANE_ID })+ isPaneOpen = false+ Record.recorderOf(engine).mark(Record.FEATURES.tabSwitch, { kind: 'ok' })+ }++ async function wasDrawnWhenProbed(engine: Host): Promise<boolean> {+ wasDrawnSinceProbe = false+ engine.invalidate()+ await engine.sleep(Limits.OPEN_PROBE_MS)++ return wasDrawnSinceProbe+ }++ async function openOnFirstEdit(engine: Host): Promise<void> {+ const isTaken = () => isPaneOpen || hasAutoOpened++ if (isTaken()) {+ return+ }++ const preference = await engine.storeGet(Names.STORE_OPEN_KEY)+ await pinRepository(engine)+ const isKeptOpen = preference === true+ const floor = isKeptOpen+ ? Limits.OPEN_MIN_COLUMNS+ : Limits.AUTO_OPEN_MIN_COLUMNS+ const isEligible =+ preference !== false &&+ columns !== null &&+ columns >= floor &&+ repository !== null++ if (!isEligible || isTaken()) {+ return+ }++ hasAutoOpened = true+ await openPane(engine, 'auto_open')+ }++ function disarm(engine: Host) {+ armed = null+ model = { ...model, armedPath: null }+ engine.status(undefined)+ }++ const actionsOf = (engine: Host): Views.PaneActions => ({+ selectFile: path => {+ model = { ...model, selectedPath: path }+ void loadBody(engine)+ redraw(engine)+ },+ toggleNoise: () => {+ model = { ...model, isNoiseShown: !model.isNoiseShown }+ void loadBody(engine)+ redraw(engine)+ },+ togglePreSession: () => {+ model = { ...model, isPreSessionShown: !model.isPreSessionShown }+ void loadBody(engine)+ redraw(engine)+ },+ chooseBase: value => {+ const mode = PaneState.baseModeOf(value)++ if (!mode || mode === model.requestedMode) {+ return+ }++ bodyKey = null+ model = { ...model, requestedMode: mode, body: null, bodyState: 'idle' }+ Record.recorderOf(engine).mark(Record.FEATURES.baseSwitch, {+ kind: 'ok',+ })+ const toplevel = model.data?.repository.toplevel++ if (toplevel !== undefined) {+ void engine+ .storeSet(Names.baseStoreKeyOf(toplevel), mode)+ .catch(() => undefined)+ }++ void refresh(engine)+ redraw(engine)+ },+ chooseSource: value => {+ const index = Number(value)+ const isTurn = value !== 'current' && Number.isInteger(index)+ const source: PaneState.Source = isTurn+ ? { kind: 'turn', index }+ : { kind: 'current' }+ model = { ...model, source, selectedPath: null }+ void loadBody(engine)+ redraw(engine)+ },+ toggleAsk: path => {+ if (armed?.path === path) {+ disarm(engine)+ redraw(engine)++ return+ }++ arm(engine, path)+ },+ })++ function arm(engine: Host, path: string) {+ armed = Ask.armedAskOf(+ path,+ PaneState.pickedTurnOf(model)?.files.find(file => file.path === path)+ ?.hunks ??+ model.body?.hunks ??+ [],+ )+ model = { ...model, armedPath: path }+ engine.status(+ `${Views.sanitizeName(path)} rides your next prompt (press ` ++ `asked ✓ to drop it)`,+ )+ redraw(engine)+ }++ async function bind(engine: Host): Promise<void> {+ sessionStartMs = engine.now()++ try {+ await engine.registerCommand(COMMAND_SPEC)+ host = engine+ } catch (error) {+ const reason = messageOf(error)++ if (!Names.BUILTIN_HOLDS_PATTERN.test(reason)) {+ engine.uiLog(Names.registerFailedTextOf(Views.sanitizeName(reason)))+ }++ return+ }++ await pinRepository(engine)+ }++ on('session.start', async ($, e, next) => {+ await bind({+ now: () => $.clock.now(),+ after: (ms, fn) => $.clock.after(ms, fn),+ every: (ms, fn) => $.clock.every(ms, fn),+ sleep: ms => $.clock.sleep(ms),+ run: (argv, init) => $.process.run(argv, init),+ stat: path => $.fs.stat(path),+ listDir: path => $.fs.list(path),+ readFile: path => $.fs.read(path),+ storeGet: key => $.store.get(key),+ storeSet: (key, value) => $.store.set(key, value),+ messages: () => $.session.messages(),+ invalidate: () => $.ui.invalidate('ui.render'),+ status: text => $.ui.status(text),+ uiLog: text => $.ui.log(text),+ openPane: pane => $.ui.open(pane),+ closePane: pane => $.ui.close(pane),+ registerCommand: spec => $.command.register(spec),+ mark: entry => $.telemetry.mark(entry),+ log: entry => $.telemetry.log(entry),+ })++ return next(e)+ })++ on('ui.render', { component: 'PromptHint' }, ($, e, next) => {+ if (isOnPaneSurface(e)) {+ columns = e.viewport?.columns ?? columns+ }++ return next(e)+ })++ on('ui.render', { component: 'Pane' }, async ($, e, next) => {+ if (e.requestId !== Names.PANE_ID || !host || !isOnPaneSurface(e)) {+ return next(e)+ }++ const { Box, Text, Button, Select } = await $.ui.resolve(e)+ wasDrawnSinceProbe = true+ columns = e.viewport?.columns ?? columns+ model = { ...model, isFocused: e.props.focused }++ return Views.paneView(+ {+ ui: { Box, Text, Button, Select },+ actions: actionsOf(host),+ columns: e.props.bodyColumns,+ },+ model,+ )+ })++ on('command.run', { command: Names.COMMAND_NAME }, async ($, e, next) => {+ if (!host) {+ return next(e)+ }++ await pinRepository(host)++ if (!repository) {+ return { text: Names.NOT_IN_REPOSITORY_TEXT }+ }++ const isOpening =+ PaneToggle.paneToggleOf({+ isBelievedOpen: isPaneOpen,+ wasDrawnWhenProbed: isPaneOpen && (await wasDrawnWhenProbed(host)),+ }) === 'open'+ await (isOpening ? openPane(host, 'manual') : closePane(host))+ await host.storeSet(Names.STORE_OPEN_KEY, isOpening).catch(() => undefined)++ return {}+ })++ on('command.run', { command: ['clear', 'resume'] }, async ($, e, next) => {+ const result = await next(e)++ if (host) {+ if (isPaneOpen) {+ await closePane(host).catch(() => undefined)+ }++ hasAutoOpened = false+ bodyKey = null+ disarm(host)+ model = PaneState.afterNewSession(model)+ }++ return result+ })++ on('tool.call', { tool: [...Tools.EDITING_TOOLS] }, async ($, e, next) => {+ let result: ResultOf['tool.call'] | undefined++ try {+ result = await next(e)++ return result+ } finally {+ if (host) {+ if (isPaneOpen) {+ scheduleRefresh(host)+ }++ const isEditDone = result !== undefined && !('deny' in result)++ if (isEditDone) {+ void openOnFirstEdit(host).catch(() => undefined)+ }+ }+ }+ })++ on('tool.call', { tool: [...Tools.SHELL_TOOLS] }, async ($, e, next) => {+ try {+ return await next(e)+ } finally {+ if (host && isPaneOpen) {+ scheduleRefresh(host)+ }+ }+ })++ on('turn.complete', ($, e, next) => {+ if (host && isPaneOpen) {+ scheduleRefresh(host)+ }++ return next(e)+ })++ on('prompt.submit', async ($, e, next) => {+ const result = await next(e)+ const asked = armed++ if (!host || !asked || result.drop !== undefined) {+ return result+ }++ disarm(host)+ redraw(host)+ Record.recorderOf(host).asked(asked.lines)++ return { ...result, context: [...(result.context ?? []), asked.text] }+ })+}diff --git a/mods/diff/hooks/telemetry-noun.d.ts b/mods/diff/hooks/telemetry-noun.d.tsnew file mode 100644index 00000000..60d5a4f9--- /dev/null+++ b/mods/diff/hooks/telemetry-noun.d.ts@@ -0,0 +1,56 @@+/**+ * The `$.telemetry` noun as this plugin calls it, declared for a build of+ * this folder on its own; no module imports it.+ *+ * The telemetry plugin adds the noun in the engine.create fold on internal+ * builds and nowhere else: where no plugin provides it the calls throw and+ * record/ drops the row. The engine's repository leaves this file out.+ *+ * @entry+ */+declare module 'claude-code' {+ /**+ * How one use of a feature went: as hoped, degraded, or failed outright.+ */+ type DiffTelemetryMarkKind = 'ok' | 'sad' | 'bad'++ /**+ * A string property: the value and the list it is chosen from.+ */+ type DiffTelemetryChoice = { value: string; of: readonly string[] }++ /**+ * One property value a row may carry.+ */+ type DiffTelemetryProp = number | boolean | DiffTelemetryChoice++ /**+ * What `$.telemetry.log` takes: the event's name after the prefix, and+ * its properties by snake_case key.+ */+ type DiffTelemetryLogEntry = {+ event: string+ props?: Readonly<Record<string, DiffTelemetryProp>>+ }++ /**+ * What `$.telemetry.mark` takes: the feature, how it went, and why when+ * not ok.+ */+ type DiffTelemetryMarkEntry = {+ feature: string+ kind: DiffTelemetryMarkKind+ reason?: string+ }++ interface EngineInterface {+ /**+ * A plugin's analytics, one first-party row per call; present only+ * where the telemetry plugin is seated.+ */+ telemetry: {+ log: (entry: DiffTelemetryLogEntry) => Promise<void>+ mark: (entry: DiffTelemetryMarkEntry) => Promise<void>+ }+ }+}diff --git a/mods/diff/hooks/todos/index.ts b/mods/diff/hooks/todos/index.tsnew file mode 100644index 00000000..0ce645da--- /dev/null+++ b/mods/diff/hooks/todos/index.ts@@ -0,0 +1,4 @@+export * from './todo-progress'+export * from './todo-progress-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/todos/todo-progress-of.ts b/mods/diff/hooks/todos/todo-progress-of.tsnew file mode 100644index 00000000..2b38c936--- /dev/null+++ b/mods/diff/hooks/todos/todo-progress-of.ts@@ -0,0 +1,32 @@+import type { SessionMessage } from 'claude-code'++import { arrayOf } from '../array-of'+import { countOf } from '../count-of'+import { isRecord } from '../is-record'+import Tools from '../tools'+import type { TodoProgress } from './todo-progress'++/**+ * The todo list as the latest TodoWrite call left it, counted: the pane's+ * progress bar (ReplDiffSidebar's, read from the transcript instead).+ *+ * No call yet reads as an empty list.+ *+ * @param messages the transcript rows, oldest first+ * @returns completed over total+ */+export function todoProgressOf(+ messages: readonly SessionMessage[],+): TodoProgress {+ const latest = messages+ .flatMap(message => message.toolUses)+ .findLast(use => use.name === Tools.TODO_TOOL)+ const statuses = arrayOf(latest?.input.todos).map(todo =>+ isRecord(todo) ? todo.status : null,+ )++ return {+ done: countOf(statuses, status => status === 'completed'),+ total: statuses.length,+ }+}diff --git a/mods/diff/hooks/todos/todo-progress/index.ts b/mods/diff/hooks/todos/todo-progress/index.tsnew file mode 100644index 00000000..0ab3b873--- /dev/null+++ b/mods/diff/hooks/todos/todo-progress/index.ts@@ -0,0 +1,3 @@+export type * from './todo-progress.js'++export * as default from '.'diff --git a/mods/diff/hooks/todos/todo-progress/todo-progress.ts b/mods/diff/hooks/todos/todo-progress/todo-progress.tsnew file mode 100644index 00000000..b053fa2c--- /dev/null+++ b/mods/diff/hooks/todos/todo-progress/todo-progress.ts@@ -0,0 +1,7 @@+/**+ * How far the session's todo list has come: completed items over all.+ */+export type TodoProgress = {+ done: number+ total: number+}diff --git a/mods/diff/hooks/tools/editing-tools.ts b/mods/diff/hooks/tools/editing-tools.tsnew file mode 100644index 00000000..dec3dfc7--- /dev/null+++ b/mods/diff/hooks/tools/editing-tools.ts@@ -0,0 +1,5 @@+/**+ * The tools whose success means Claude changed a file: the pane's open+ * trigger and a refresh (fileHistory's `track` ops in the built-in).+ */+export const EDITING_TOOLS = ['Edit', 'Write', 'NotebookEdit'] as constdiff --git a/mods/diff/hooks/tools/index.ts b/mods/diff/hooks/tools/index.tsnew file mode 100644index 00000000..3083c37a--- /dev/null+++ b/mods/diff/hooks/tools/index.ts@@ -0,0 +1,5 @@+export * from './editing-tools.js'+export * from './shell-tools.js'+export * from './todo-tool.js'++export * as default from '.'diff --git a/mods/diff/hooks/tools/shell-tools.ts b/mods/diff/hooks/tools/shell-tools.tsnew file mode 100644index 00000000..c7dd5f02--- /dev/null+++ b/mods/diff/hooks/tools/shell-tools.ts@@ -0,0 +1,5 @@+/**+ * The tools whose completion may have changed the working tree without an+ * edit record: a refresh trigger, never an open trigger.+ */+export const SHELL_TOOLS = ['Bash', 'PowerShell'] as constdiff --git a/mods/diff/hooks/tools/todo-tool.ts b/mods/diff/hooks/tools/todo-tool.tsnew file mode 100644index 00000000..6e8e4039--- /dev/null+++ b/mods/diff/hooks/tools/todo-tool.ts@@ -0,0 +1,4 @@+/**+ * The tool whose latest input carries the session's todo list.+ */+export const TODO_TOOL = 'TodoWrite'diff --git a/mods/diff/hooks/turns/index.ts b/mods/diff/hooks/turns/index.tsnew file mode 100644index 00000000..c2fb4509--- /dev/null+++ b/mods/diff/hooks/turns/index.ts@@ -0,0 +1,5 @@+export * from './turn-diffs-of.js'+export * from './turn-of'+export * from './types'++export * as default from '.'diff --git a/mods/diff/hooks/turns/turn-diffs-of.ts b/mods/diff/hooks/turns/turn-diffs-of.tsnew file mode 100644index 00000000..cb93e120--- /dev/null+++ b/mods/diff/hooks/turns/turn-diffs-of.ts@@ -0,0 +1,29 @@+import type { SessionMessage } from 'claude-code'++import TurnOf from './turn-of'+import type Types from './types'++/**+ * The transcript's turns that edited files, newest first, each numbered by+ * its place among all prompts, read over `$.session.messages()`.+ *+ * Recomputed whole from the rows given, so a rewind that shrinks the+ * transcript simply yields fewer turns.+ *+ * @param messages the transcript rows, oldest first+ * @returns the turns with edits, newest first+ */+export function turnDiffsOf(+ messages: readonly SessionMessage[],+): Types.TurnDiff[] {+ const starts = messages.flatMap((message, at) =>+ TurnOf.isPromptRow(message) ? [at] : [],+ )++ return starts+ .map((start, ordinal) =>+ TurnOf.turnOf(messages.slice(start, starts[ordinal + 1]), ordinal + 1),+ )+ .filter(turn => turn.files.length > 0)+ .toReversed()+}diff --git a/mods/diff/hooks/turns/turn-of/file-edit-of/file-edit-of.ts b/mods/diff/hooks/turns/turn-of/file-edit-of/file-edit-of.tsnew file mode 100644index 00000000..2a68d229--- /dev/null+++ b/mods/diff/hooks/turns/turn-of/file-edit-of/file-edit-of.ts@@ -0,0 +1,53 @@+import { countOf } from '../../../count-of'+import { isRecord } from '../../../is-record'+import type Types from '../../types'+import { hunksOf } from './hunks-of'++/**+ * One Edit or Write result as the file it changed, told as the built-in+ * turn view tells an edit result; null for any other result.+ *+ * A `filePath` with a non-empty `structuredPatch`, or a `create` with its+ * `content`, which becomes one all-`+` hunk.+ *+ * @param result what the transcript stored for the tool call+ * @returns the file's edit, or null+ */+export function fileEditOf(result: unknown): Types.TurnFile | null {+ if (!isRecord(result) || typeof result.filePath !== 'string') {+ return null+ }++ const hunks = hunksOf(result.structuredPatch)+ const isNewFile = result.type === 'create'++ if (hunks.length > 0) {+ const lines = hunks.flatMap(hunk => hunk.lines)++ return {+ path: result.filePath,+ hunks,+ added: countOf(lines, line => line.startsWith('+')),+ removed: countOf(lines, line => line.startsWith('-')),+ isNewFile,+ isTruncated: false,+ }+ }++ if (!isNewFile || typeof result.content !== 'string') {+ return null+ }++ const created = result.content.split('\n')++ return {+ path: result.filePath,+ hunks: [+ { oldStart: 0, newStart: 1, lines: created.map(line => `+${line}`) },+ ],+ added: created.length,+ removed: 0,+ isNewFile: true,+ isTruncated: false,+ }+}diff --git a/mods/diff/hooks/turns/turn-of/file-edit-of/hunks-of/hunks-of.ts b/mods/diff/hooks/turns/turn-of/file-edit-of/hunks-of/hunks-of.tsnew file mode 100644index 00000000..de9975f5--- /dev/null+++ b/mods/diff/hooks/turns/turn-of/file-edit-of/hunks-of/hunks-of.ts@@ -0,0 +1,33 @@+import { arrayOf } from '../../../../array-of'+import type Git from '../../../../git'+import { isRecord } from '../../../../is-record'++/**+ * A tool result's `structuredPatch` as hunks, keeping only entries shaped+ * like one (numeric starts, string lines).+ *+ * @param patch the result's `structuredPatch` field+ * @returns the well-formed hunks; empty when the field is not an array+ */+export const hunksOf = (patch: unknown): Git.Hunk[] =>+ arrayOf(patch)+ .filter(isRecord)+ .flatMap(hunk => {+ const { oldStart, newStart, lines } = hunk+ const isHunk =+ typeof oldStart === 'number' &&+ typeof newStart === 'number' &&+ Array.isArray(lines)++ return isHunk+ ? [+ {+ oldStart,+ newStart,+ lines: arrayOf(lines).filter(+ (line): line is string => typeof line === 'string',+ ),+ },+ ]+ : []+ })diff --git a/mods/diff/hooks/turns/turn-of/file-edit-of/hunks-of/index.ts b/mods/diff/hooks/turns/turn-of/file-edit-of/hunks-of/index.tsnew file mode 100644index 00000000..a106cc06--- /dev/null+++ b/mods/diff/hooks/turns/turn-of/file-edit-of/hunks-of/index.ts@@ -0,0 +1,3 @@+export * from './hunks-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/turns/turn-of/file-edit-of/index.ts b/mods/diff/hooks/turns/turn-of/file-edit-of/index.tsnew file mode 100644index 00000000..b03ef904--- /dev/null+++ b/mods/diff/hooks/turns/turn-of/file-edit-of/index.ts@@ -0,0 +1,4 @@+export * from './file-edit-of.js'+export * from './hunks-of'++export * as default from '.'diff --git a/mods/diff/hooks/turns/turn-of/index.ts b/mods/diff/hooks/turns/turn-of/index.tsnew file mode 100644index 00000000..33f8048a--- /dev/null+++ b/mods/diff/hooks/turns/turn-of/index.ts@@ -0,0 +1,6 @@+export * from './file-edit-of'+export * from './is-prompt-row'+export * from './preview-chars'+export * from './turn-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/turns/turn-of/is-prompt-row/index.ts b/mods/diff/hooks/turns/turn-of/is-prompt-row/index.tsnew file mode 100644index 00000000..486694e9--- /dev/null+++ b/mods/diff/hooks/turns/turn-of/is-prompt-row/index.ts@@ -0,0 +1,3 @@+export * from './is-prompt-row.js'++export * as default from '.'diff --git a/mods/diff/hooks/turns/turn-of/is-prompt-row/is-prompt-row.ts b/mods/diff/hooks/turns/turn-of/is-prompt-row/is-prompt-row.tsnew file mode 100644index 00000000..14155f7e--- /dev/null+++ b/mods/diff/hooks/turns/turn-of/is-prompt-row/is-prompt-row.ts@@ -0,0 +1,13 @@+import type { SessionMessage } from 'claude-code'++/**+ * Whether a transcript row starts a turn: a user message that carries text+ * and no tool results (`$.session.messages()` already leaves out meta rows).+ *+ * @param message one row of the transcript+ * @returns whether it is a typed prompt+ */+export const isPromptRow = (message: SessionMessage) =>+ message.role === 'user' &&+ (message.toolResults === undefined || message.toolResults.length === 0) &&+ message.text !== ''diff --git a/mods/diff/hooks/turns/turn-of/preview-chars/index.ts b/mods/diff/hooks/turns/turn-of/preview-chars/index.tsnew file mode 100644index 00000000..114ed80b--- /dev/null+++ b/mods/diff/hooks/turns/turn-of/preview-chars/index.ts@@ -0,0 +1,3 @@+export * from './preview-chars.js'++export * as default from '.'diff --git a/mods/diff/hooks/turns/turn-of/preview-chars/preview-chars.ts b/mods/diff/hooks/turns/turn-of/preview-chars/preview-chars.tsnew file mode 100644index 00000000..883d6038--- /dev/null+++ b/mods/diff/hooks/turns/turn-of/preview-chars/preview-chars.ts@@ -0,0 +1,5 @@+/**+ * How many characters of a turn's prompt its source label keeps, as the+ * built-in turn view does: 30, an ellipsis standing for the rest.+ */+export const PREVIEW_CHARS = 30diff --git a/mods/diff/hooks/turns/turn-of/turn-of.ts b/mods/diff/hooks/turns/turn-of/turn-of.tsnew file mode 100644index 00000000..f10c704b--- /dev/null+++ b/mods/diff/hooks/turns/turn-of/turn-of.ts@@ -0,0 +1,57 @@+import type { SessionMessage } from 'claude-code'++import Git from '../../git'+import type Types from '../types'+import { fileEditOf } from './file-edit-of'+import { PREVIEW_CHARS } from './preview-chars'++/**+ * One turn's rows (its prompt first) as the files its tool calls edited,+ * as the built-in turn view reads them.+ *+ * A file edited twice keeps both calls' hunks (cut at MAX_LINES_PER_FILE+ * in all) and the summed counts, and one created then edited stays new.+ *+ * @param rows the prompt row through the last row before the next prompt+ * @param index the turn's number, from 1+ * @returns the turn; `files` empty when nothing was edited+ */+export function turnOf(+ rows: readonly SessionMessage[],+ index: number,+): Types.TurnDiff {+ const text = rows[0]?.text ?? ''+ const isShort = [...text].length <= PREVIEW_CHARS+ const preview = isShort+ ? text+ : `${[...text].slice(0, PREVIEW_CHARS - 1).join('')}…`+ const edits = rows+ .flatMap(row => (row.role === 'assistant' ? row.toolUses : []))+ .map(use => fileEditOf(use.result))+ .filter((edit): edit is Types.TurnFile => edit !== null)+ const byPath = new Map<string, Types.TurnFile>()++ for (const edit of edits) {+ const earlier = byPath.get(edit.path)+ byPath.set(+ edit.path,+ earlier+ ? {+ path: edit.path,+ hunks: [...earlier.hunks, ...edit.hunks],+ added: earlier.added + edit.added,+ removed: earlier.removed + edit.removed,+ isNewFile: earlier.isNewFile || edit.isNewFile,+ isTruncated: false,+ }+ : edit,+ )+ }++ const files = [...byPath.values()].map(file => ({+ ...file,+ ...Git.cutHunks(file.hunks),+ }))++ return { index, preview, files }+}diff --git a/mods/diff/hooks/turns/types/index.ts b/mods/diff/hooks/turns/types/index.tsnew file mode 100644index 00000000..3c5ba82b--- /dev/null+++ b/mods/diff/hooks/turns/types/index.ts@@ -0,0 +1,4 @@+export type * from './turn-diff.js'+export * from './turn-file'++export * as default from '.'diff --git a/mods/diff/hooks/turns/types/turn-diff.ts b/mods/diff/hooks/turns/types/turn-diff.tsnew file mode 100644index 00000000..ac0bd7b6--- /dev/null+++ b/mods/diff/hooks/turns/types/turn-diff.ts@@ -0,0 +1,11 @@+import type { TurnFile } from './turn-file'++/**+ * The file edits of one turn: a prompt the person typed through the tool+ * results that followed it, numbered from 1 in transcript order.+ */+export type TurnDiff = {+ index: number+ preview: string+ files: readonly TurnFile[]+}diff --git a/mods/diff/hooks/turns/types/turn-file/index.ts b/mods/diff/hooks/turns/types/turn-file/index.tsnew file mode 100644index 00000000..abb92a49--- /dev/null+++ b/mods/diff/hooks/turns/types/turn-file/index.ts@@ -0,0 +1,3 @@+export type * from './turn-file.js'++export * as default from '.'diff --git a/mods/diff/hooks/turns/types/turn-file/turn-file.ts b/mods/diff/hooks/turns/types/turn-file/turn-file.tsnew file mode 100644index 00000000..3d1154b3--- /dev/null+++ b/mods/diff/hooks/turns/types/turn-file/turn-file.ts@@ -0,0 +1,18 @@+import type Git from '../../../git'++/**+ * One file as a turn's edits left it: its hunks (cut at the pane's line+ * cap), the counts over every line, and whether the turn created it.+ */+export type TurnFile = {+ path: string+ hunks: readonly Git.Hunk[]+ added: number+ removed: number+ isNewFile: boolean++ /**+ * Whether the hunks were cut at MAX_LINES_PER_FILE lines.+ */+ isTruncated: boolean+}diff --git a/mods/diff/hooks/views/current-pane/current-pane.tsx b/mods/diff/hooks/views/current-pane/current-pane.tsxnew file mode 100644index 00000000..39d8aa63--- /dev/null+++ b/mods/diff/hooks/views/current-pane/current-pane.tsx@@ -0,0 +1,124 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import type Git from '../../git'+import Names from '../../names'+import PaneState from '../../pane-state'+import Detail from '../detail'+import type { Kit } from '../kit'+import Layout from '../layout'+import Sections from '../sections'+import { fileRowOf } from './file-row-of'+import { listBodyOf } from './list-body-of'++/**+ * The pane over the repository's diff now (ReplDiffSidebarBody, one file's+ * body at a time): header, base line, todo bar, pickers, rows, detail.+ *+ * The tests-and-generated toggle sits above the rows; the elision count, the+ * withheld-untracked note, the pre-session line and rows below them; the+ * selected file last.+ *+ * @param kit the elements, the handlers, the width+ * @param model the pane's state+ * @returns the pane's tree+ */+export function currentPane(+ kit: Kit,+ model: PaneState.PaneModel,+): RenderElement {+ const { Box } = kit.ui+ const { data } = model++ if (model.isOutsideRepository) {+ return <Box>{Sections.dimNote(kit, Names.NOT_IN_REPOSITORY_TEXT)}</Box>+ }++ if (!data && !model.hasSettled) {+ return <Box>{Sections.dimNote(kit, 'Loading diff…')}</Box>+ }++ const noise = model.isNoiseShown ? 'shown' : 'hidden'+ const preSession = model.isPreSessionShown ? 'shown' : 'hidden'+ const partition = PaneState.partitionOf(data?.files ?? [], noise)+ const totals = data+ ? PaneState.headerTotalsOf(data, partition)+ : PaneState.ZERO_TOTALS+ const empty = PaneState.emptyStateOf(data, totals.filesCount)+ const baseLabel = PaneState.baseLabelOf(+ model.requestedMode,+ data,+ totals.filesCount,+ )+ const selected = PaneState.selectionOf(+ PaneState.listedOf(partition, preSession),+ model.selectedPath,+ )+ const rowOf = (file: Git.FileStat): RenderElement =>+ Sections.fileRow(kit, fileRowOf(file, selected?.path ?? null), () =>+ kit.actions.selectFile(file.path),+ )+ const noteOf = (text: string | null): RenderElement | null =>+ text === null ? null : Sections.dimNote(kit, Layout.sanitizeName(text))+ const noiseFace = model.isNoiseShown ? 'hide' : 'show'+ const noiseCount = Layout.plural(partition.noiseCount, 'test')+ const hasNoise = partition.noiseCount > 0+ const noiseToggle = hasNoise+ ? Sections.toggleRow(kit, 'noise', {+ label: `${noiseCount}/generated (${noiseFace})`,+ onPress: kit.actions.toggleNoise,+ })+ : null+ const earlierFace = model.isPreSessionShown ? 'hide' : 'show'+ const earlierCount = Layout.plural(partition.preSession.length, 'file')+ const hasEarlier = partition.preSession.length > 0+ const earlierToggle = hasEarlier+ ? Sections.toggleRow(kit, 'presession', {+ label: `+${earlierCount} edited before this session (${earlierFace})`,+ onPress: kit.actions.togglePreSession,+ })+ : null+ const earlierRows = model.isPreSessionShown ? partition.preSession : []+ const isUntrackedNoted = data?.isUntrackedWithheld === true && !empty+ const listed = listBodyOf(kit, { data, partition, totals, empty })+ const detail = selected+ ? [+ Sections.divider(kit),+ Detail.detailView(+ kit,+ {+ path: selected.path,+ renamedFrom: selected.renamedFrom,+ isUntracked: selected.isUntracked,+ isBinary: selected.isBinary,+ body: model.body,+ bodyState: model.bodyState,+ isArmed: model.armedPath === selected.path,+ },+ () => kit.actions.toggleAsk(selected.path),+ ),+ ]+ : []++ return (+ <Box flexDirection="column">+ {Sections.present([+ Sections.headerView(kit, empty?.headline ?? null, totals),+ noteOf(baseLabel),+ Sections.todoBar(kit, model.todos),+ Sections.controlsView(kit, model),+ noiseToggle,+ ...listed.map(line =>+ typeof line === 'string' ? noteOf(line) : rowOf(line),+ ),+ noteOf(totals.notShown > 0 ? `${totals.notShown} not shown` : null),+ noteOf(isUntrackedNoted ? Names.UNTRACKED_WITHHELD_TEXT : null),+ earlierToggle,+ ...earlierRows.map(rowOf),+ ...detail,+ ])}+ </Box>+ )+}diff --git a/mods/diff/hooks/views/current-pane/file-row-of/file-row-of.ts b/mods/diff/hooks/views/current-pane/file-row-of/file-row-of.tsnew file mode 100644index 00000000..eae8c3e9--- /dev/null+++ b/mods/diff/hooks/views/current-pane/file-row-of/file-row-of.ts@@ -0,0 +1,33 @@+import type Git from '../../../git'+import Sections from '../../sections'++/**+ * A fetched row as the list draws it: its counts, or a note in their+ * place (`untracked`, `Binary file`, `renamed`), and selection.+ *+ * @param file the row+ * @param selectedPath the selected file's path, or null+ * @returns the row model+ */+export function fileRowOf(+ file: Git.FileStat,+ selectedPath: string | null,+): Sections.FileRowModel {+ const isRenamed = file.renamedFrom !== null+ const note = file.isUntracked+ ? 'untracked'+ : file.isBinary+ ? 'Binary file'+ : isRenamed+ ? 'renamed'+ : null++ return {+ key: Sections.fileKeyOf(file.path),+ path: file.path,+ added: file.added,+ removed: file.removed,+ note,+ isSelected: file.path === selectedPath,+ }+}diff --git a/mods/diff/hooks/views/current-pane/file-row-of/index.ts b/mods/diff/hooks/views/current-pane/file-row-of/index.tsnew file mode 100644index 00000000..9184800e--- /dev/null+++ b/mods/diff/hooks/views/current-pane/file-row-of/index.ts@@ -0,0 +1,3 @@+export * from './file-row-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/current-pane/index.ts b/mods/diff/hooks/views/current-pane/index.tsnew file mode 100644index 00000000..f802aa62--- /dev/null+++ b/mods/diff/hooks/views/current-pane/index.ts@@ -0,0 +1,5 @@+export * from './current-pane.jsx'+export * from './file-row-of'+export * from './list-body-of'++export * as default from '.'diff --git a/mods/diff/hooks/views/current-pane/list-body-of/index.ts b/mods/diff/hooks/views/current-pane/list-body-of/index.tsnew file mode 100644index 00000000..96fa17f5--- /dev/null+++ b/mods/diff/hooks/views/current-pane/list-body-of/index.ts@@ -0,0 +1,4 @@+export * from './list-body-of.js'+export * from './list-place'++export * as default from '.'diff --git a/mods/diff/hooks/views/current-pane/list-body-of/list-body-of.ts b/mods/diff/hooks/views/current-pane/list-body-of/list-body-of.tsnew file mode 100644index 00000000..9b688d0c--- /dev/null+++ b/mods/diff/hooks/views/current-pane/list-body-of/list-body-of.ts@@ -0,0 +1,46 @@+import type Git from '../../../git'+import type { Kit } from '../../kit'+import type { ListPlace } from './list-place'++/**+ * The list's body as ReplDiffSidebarBody decides it: the empty state's+ * hint, the too-many state, the only-noise state, or the session's rows.+ *+ * Strings are dim lines; rows are files to draw.+ *+ * @param _kit unused; keeps the part's shape+ * @param place the fetch, its groups, the counts, the empty state+ * @returns the lines and rows, in order+ */+export function listBodyOf(+ _kit: Kit,+ place: ListPlace,+): readonly (string | Git.FileStat)[] {+ const { data, partition, totals, empty } = place++ const hint = empty?.hint ?? null++ if (empty) {+ return hint === null ? [] : [hint]+ }++ const isTooMany =+ data !== null && data.files.length === 0 && totals.filesCount > 0++ if (isTooMany) {+ return [+ 'Too many changed files to show diff',+ 'Per-file diff is skipped above 500 files',+ ]+ }++ const isOnlyNoise = partition.shown.length === 0 && partition.noiseCount > 0++ return isOnlyNoise+ ? [+ 'Only tests and generated files changed',+ 'Tests and generated files are hidden · click "show" above to view ' ++ 'them',+ ]+ : partition.shown+}diff --git a/mods/diff/hooks/views/current-pane/list-body-of/list-place/index.ts b/mods/diff/hooks/views/current-pane/list-body-of/list-place/index.tsnew file mode 100644index 00000000..fc5d4cf1--- /dev/null+++ b/mods/diff/hooks/views/current-pane/list-body-of/list-place/index.ts@@ -0,0 +1,3 @@+export type * from './list-place.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/current-pane/list-body-of/list-place/list-place.ts b/mods/diff/hooks/views/current-pane/list-body-of/list-place/list-place.tsnew file mode 100644index 00000000..e517bde2--- /dev/null+++ b/mods/diff/hooks/views/current-pane/list-body-of/list-place/list-place.ts@@ -0,0 +1,13 @@+import type Git from '../../../../git'+import type PaneState from '../../../../pane-state'++/**+ * What decides the list's body: the fetch, its grouped rows, the header's+ * counts, and the empty state when there is one.+ */+export type ListPlace = {+ data: Git.DiffData | null+ partition: PaneState.Partition+ totals: PaneState.HeaderTotals+ empty: PaneState.EmptyState | null+}diff --git a/mods/diff/hooks/views/detail/backgrounds/backgrounds.ts b/mods/diff/hooks/views/detail/backgrounds/backgrounds.tsnew file mode 100644index 00000000..78cc8069--- /dev/null+++ b/mods/diff/hooks/views/detail/backgrounds/backgrounds.ts@@ -0,0 +1,11 @@+import type Types from '../types'++/**+ * The theme key behind a run of each kind: the diff's added and removed+ * bands, the plain background behind context.+ */+export const BACKGROUNDS: Readonly<Record<Types.LineKind, string>> = {+ added: 'diffAdded',+ removed: 'diffRemoved',+ context: 'background',+}diff --git a/mods/diff/hooks/views/detail/backgrounds/index.ts b/mods/diff/hooks/views/detail/backgrounds/index.tsnew file mode 100644index 00000000..cd6017e9--- /dev/null+++ b/mods/diff/hooks/views/detail/backgrounds/index.ts@@ -0,0 +1,3 @@+export * from './backgrounds.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/detail-model/detail-model.ts b/mods/diff/hooks/views/detail/detail-model/detail-model.tsnew file mode 100644index 00000000..bd0e9993--- /dev/null+++ b/mods/diff/hooks/views/detail/detail-model/detail-model.ts@@ -0,0 +1,16 @@+import type Git from '../../../git'+import type PaneState from '../../../pane-state'++/**+ * The selected file as its body draws it: the path, what kind of row it is,+ * its hunks once read, and whether it is armed for the next prompt.+ */+export type DetailModel = {+ path: string+ renamedFrom: string | null+ isUntracked: boolean+ isBinary: boolean+ body: Git.FileHunks | null+ bodyState: PaneState.BodyState+ isArmed: boolean+}diff --git a/mods/diff/hooks/views/detail/detail-model/index.ts b/mods/diff/hooks/views/detail/detail-model/index.tsnew file mode 100644index 00000000..b0404f71--- /dev/null+++ b/mods/diff/hooks/views/detail/detail-model/index.ts@@ -0,0 +1,3 @@+export type * from './detail-model.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/detail-view.tsx b/mods/diff/hooks/views/detail/detail-view.tsxnew file mode 100644index 00000000..45e96373--- /dev/null+++ b/mods/diff/hooks/views/detail/detail-view.tsx@@ -0,0 +1,92 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import type { Kit } from '../kit'+import Layout from '../layout'+import type { DetailModel } from './detail-model'+import { gutterCellsOf } from './gutter-cells-of'+import { hunkBody } from './hunk-body'+import { linesOf } from './lines-of'+import { MARKER_CELLS } from './marker-cells'+import { maxRowsOf } from './max-rows-of'+import { placeholderOf } from './placeholder-of'+import { rowsOf } from './rows-of'++/**+ * The selected file under the list: its bold path and asides (renamed+ * from, untracked, truncated) cut to the width, the ask Button, the body.+ *+ * The body is a placeholder or the hunks (cut to the rows the body's char+ * and node budgets hold, maxRowsOf), then the footer; the gutter fits the+ * largest number.+ *+ * @param kit the elements and the width+ * @param detail the selected file+ * @param onToggleAsk arms or disarms the file for the next prompt+ * @returns the detail element+ */+export function detailView(+ kit: Kit,+ detail: DetailModel,+ onToggleAsk: () => void,+): RenderElement {+ const { Box, Text, Button } = kit.ui+ const placeholder = placeholderOf(detail)+ const hunks = placeholder ? [] : (detail.body?.hunks ?? [])+ const lines = linesOf(hunks)+ const gutterCells = gutterCellsOf(lines)+ const contentCells = Math.max(1, kit.columns - gutterCells - MARKER_CELLS)+ const rows = placeholder ? [] : rowsOf(lines, contentCells)+ const cells = { gutterCells, contentCells }+ const maxRows = maxRowsOf(rows, cells)+ const isTruncated = detail.body?.isTruncated === true || rows.length > maxRows+ const nameOf = (path: string) =>+ Layout.truncateStart(Layout.sanitizeName(path), kit.columns)+ const renamedFrom =+ detail.renamedFrom === null ? null : nameOf(detail.renamedFrom)+ const asides = [+ renamedFrom === null ? null : `renamed from ${renamedFrom}`,+ detail.isUntracked ? 'untracked' : null,+ isTruncated ? 'truncated' : null,+ ].filter(word => word !== null)+ const aside = asides.length === 0 ? '' : ` (${asides.join(', ')})`+ const notes = (placeholder ?? []).map(line => (+ <Text dimColor italic wrap="wrap">+ {line}+ </Text>+ ))+ const body = placeholder+ ? notes+ : [hunkBody(kit.ui, rows.slice(0, maxRows), cells)]+ const ask = placeholder+ ? []+ : [+ <Button key="ask" onPress={onToggleAsk}>+ {detail.isArmed ? 'asked ✓' : 'ask'}+ </Button>,+ ]+ const footer = isTruncated+ ? [+ <Text dimColor italic>+ … diff truncated (exceeded 400 line limit)+ </Text>,+ ]+ : []++ const header = (+ <Box flexDirection="row">+ {[+ <Text bold wrap="truncate-start">+ {nameOf(detail.path)}+ </Text>,+ <Text dimColor>{aside}</Text>,+ <Box flexGrow={1} />,+ ...ask,+ ]}+ </Box>+ )++ return <Box flexDirection="column">{[header, ...body, ...footer]}</Box>+}diff --git a/mods/diff/hooks/views/detail/gutter-cells-of/gutter-cells-of.ts b/mods/diff/hooks/views/detail/gutter-cells-of/gutter-cells-of.tsnew file mode 100644index 00000000..098be16a--- /dev/null+++ b/mods/diff/hooks/views/detail/gutter-cells-of/gutter-cells-of.ts@@ -0,0 +1,12 @@+import type Types from '../types'++/**+ * How wide the line-number gutter is for these lines: the longest number's+ * digits and one leading cell (StructuredDiff's digits + 1).+ *+ * @param lines the numbered lines+ * @returns the gutter's width in cells+ */+export const gutterCellsOf = (lines: readonly Types.DiffLine[]) =>+ String(lines.reduce((most, line) => Math.max(most, line.lineNumber), 0))+ .length + 1diff --git a/mods/diff/hooks/views/detail/gutter-cells-of/index.ts b/mods/diff/hooks/views/detail/gutter-cells-of/index.tsnew file mode 100644index 00000000..4730ab40--- /dev/null+++ b/mods/diff/hooks/views/detail/gutter-cells-of/index.ts@@ -0,0 +1,3 @@+export * from './gutter-cells-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/hunk-body/body-cells/body-cells.ts b/mods/diff/hooks/views/detail/hunk-body/body-cells/body-cells.tsnew file mode 100644index 00000000..423b840a--- /dev/null+++ b/mods/diff/hooks/views/detail/hunk-body/body-cells/body-cells.ts@@ -0,0 +1,8 @@+/**+ * The two widths a body is drawn in: the gutter's and the content's, the+ * marker cells between them.+ */+export type BodyCells = {+ gutterCells: number+ contentCells: number+}diff --git a/mods/diff/hooks/views/detail/hunk-body/body-cells/index.ts b/mods/diff/hooks/views/detail/hunk-body/body-cells/index.tsnew file mode 100644index 00000000..21daa6d4--- /dev/null+++ b/mods/diff/hooks/views/detail/hunk-body/body-cells/index.ts@@ -0,0 +1,3 @@+export type * from './body-cells.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/hunk-body/hunk-body.tsx b/mods/diff/hooks/views/detail/hunk-body/hunk-body.tsxnew file mode 100644index 00000000..ffe2f9a8--- /dev/null+++ b/mods/diff/hooks/views/detail/hunk-body/hunk-body.tsx@@ -0,0 +1,114 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement, RenderNode } from 'claude-code'++import type Kit from '../../kit'+import Layout from '../../layout'+import { BACKGROUNDS } from '../backgrounds'+import { MARKER_CELLS } from '../marker-cells'+import { MAX_RUN_CHARS } from '../max-run-chars'+import { runsOf } from '../runs-of'+import type Types from '../types'+import { WORD_BACKGROUNDS } from '../word-backgrounds'+import type { BodyCells } from './body-cells'++/**+ * A file's rows drawn as StructuredDiff's fallback draws them, in few+ * nodes: one dim gutter Text beside a column of one Text per run.+ *+ * Added and removed runs sit on their theme bands, changed words on the+ * word bands, every row is padded to the band's width less its text's+ * chargedWidth; a run's text and the gutter split at MAX_RUN_CHARS a string.+ *+ * @param ui the surface's elements+ * @param rows the laid-out rows (rowsOf), each exactly one terminal row+ * @param cells the gutter's and the content's widths+ * @returns the body element+ */+export function hunkBody(+ ui: Kit.Ui,+ rows: readonly Types.Row[],+ cells: BodyCells,+): RenderElement {+ const { Box, Text } = ui+ const bandCells = MARKER_CELLS + cells.contentCells++ function gutterChildren(): string[] {+ const children: string[] = []+ let pending = ''++ rows.forEach((row, at) => {+ const label = row.gutter.padStart(cells.gutterCells)+ const text = `${at === 0 ? '' : '\n'}${label}`++ if (pending.length + text.length > MAX_RUN_CHARS) {+ children.push(pending)+ pending = ''+ }++ pending += text+ })++ return pending === '' ? children : [...children, pending]+ }++ function runChildren(run: Types.Run): RenderNode[] {+ const children: RenderNode[] = []+ let pending = ''++ function flush() {+ if (pending !== '') {+ children.push(pending)+ pending = ''+ }+ }++ function plain(text: string) {+ if (pending.length + text.length > MAX_RUN_CHARS) {+ flush()+ }++ pending += text+ }++ function marked(text: string) {+ flush()+ children.push(+ <Text backgroundColor={WORD_BACKGROUNDS[run.kind]}>{text}</Text>,+ )+ }++ run.rows.forEach((row, at) => {+ const used = row.segments.reduce(+ (sum, segment) => sum + Layout.chargedWidth(segment.text),+ MARKER_CELLS,+ )+ plain(`${at === 0 ? '' : '\n'} ${row.marker} `)++ for (const segment of row.segments) {+ ;(segment.isChanged ? marked : plain)(segment.text)+ }++ plain(' '.repeat(Math.max(0, bandCells - used)))+ })+ flush()++ return children+ }++ return (+ <Box flexDirection="row">+ <Text dimColor wrap="truncate-end">+ {gutterChildren()}+ </Text>+ <Box flexDirection="column" flexShrink={0} width={bandCells}>+ {runsOf(rows).map(run => (+ <Text backgroundColor={BACKGROUNDS[run.kind]} wrap="truncate-end">+ {runChildren(run)}+ </Text>+ ))}+ </Box>+ </Box>+ )+}diff --git a/mods/diff/hooks/views/detail/hunk-body/index.ts b/mods/diff/hooks/views/detail/hunk-body/index.tsnew file mode 100644index 00000000..937d5ed1--- /dev/null+++ b/mods/diff/hooks/views/detail/hunk-body/index.ts@@ -0,0 +1,4 @@+export * from './body-cells'+export * from './hunk-body.jsx'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/index.ts b/mods/diff/hooks/views/detail/index.tsnew file mode 100644index 00000000..9283fae6--- /dev/null+++ b/mods/diff/hooks/views/detail/index.ts@@ -0,0 +1,18 @@+export * from './backgrounds'+export * from './detail-model'+export * from './detail-view.jsx'+export * from './gutter-cells-of'+export * from './hunk-body'+export * from './lines-of'+export * from './marker-cells'+export * from './max-body-chars'+export * from './max-body-nodes'+export * from './max-rows-of'+export * from './max-run-chars'+export * from './placeholder-of'+export * from './rows-of'+export * from './runs-of'+export * from './types'+export * from './word-backgrounds'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/lines-of/index.ts b/mods/diff/hooks/views/detail/lines-of/index.tsnew file mode 100644index 00000000..8a09a14e--- /dev/null+++ b/mods/diff/hooks/views/detail/lines-of/index.ts@@ -0,0 +1,3 @@+export * from './lines-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/lines-of/lines-of.ts b/mods/diff/hooks/views/detail/lines-of/lines-of.tsnew file mode 100644index 00000000..445a6393--- /dev/null+++ b/mods/diff/hooks/views/detail/lines-of/lines-of.ts@@ -0,0 +1,74 @@+import type Git from '../../../git'+import Layout from '../../layout'+import type Types from '../types'++/**+ * A file's hunks as numbered lines, hunk after hunk: context and added+ * lines count the new file's lines, removed ones the old file's.+ *+ * Each run of removed lines is paired index by index with the added run+ * right after it, for the word diff, as the engine's fallback diff pairs.+ *+ * @param hunks the parsed hunks+ * @returns the lines in drawing order+ */+export function linesOf(hunks: readonly Git.Hunk[]): Types.DiffLine[] {+ const lines: Types.DiffLine[] = []++ for (const hunk of hunks) {+ let oldNumber = hunk.oldStart+ let newNumber = hunk.newStart+ let removedRun: Types.DiffLine[] = []+ let pairing = 0++ for (const raw of hunk.lines) {+ const text = Layout.sanitizeLine(raw.slice(1))+ const kind: Types.LineKind = raw.startsWith('+')+ ? 'added'+ : raw.startsWith('-')+ ? 'removed'+ : 'context'++ if (kind === 'removed') {+ const isNewRun = pairing > 0++ if (isNewRun) {+ removedRun = []+ pairing = 0+ }++ const line = { kind, lineNumber: oldNumber, text, pairedText: null }+ removedRun.push(line)+ lines.push(line)+ oldNumber += 1+ continue+ }++ if (kind === 'added') {+ const partner = removedRun[pairing]++ if (partner) {+ partner.pairedText = text+ pairing += 1+ }++ lines.push({+ kind,+ lineNumber: newNumber,+ text,+ pairedText: partner ? partner.text : null,+ })+ newNumber += 1+ continue+ }++ removedRun = []+ pairing = 0+ lines.push({ kind, lineNumber: newNumber, text, pairedText: null })+ oldNumber += 1+ newNumber += 1+ }+ }++ return lines+}diff --git a/mods/diff/hooks/views/detail/marker-cells/index.ts b/mods/diff/hooks/views/detail/marker-cells/index.tsnew file mode 100644index 00000000..18692c83--- /dev/null+++ b/mods/diff/hooks/views/detail/marker-cells/index.ts@@ -0,0 +1,3 @@+export * from './marker-cells.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/marker-cells/marker-cells.ts b/mods/diff/hooks/views/detail/marker-cells/marker-cells.tsnew file mode 100644index 00000000..bc096888--- /dev/null+++ b/mods/diff/hooks/views/detail/marker-cells/marker-cells.ts@@ -0,0 +1,5 @@+/**+ * The cells between the gutter and a row's content: a space, the `+`, `-`+ * or space marker, and a space.+ */+export const MARKER_CELLS = 3diff --git a/mods/diff/hooks/views/detail/max-body-chars/index.ts b/mods/diff/hooks/views/detail/max-body-chars/index.tsnew file mode 100644index 00000000..56056883--- /dev/null+++ b/mods/diff/hooks/views/detail/max-body-chars/index.ts@@ -0,0 +1,3 @@+export * from './max-body-chars.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/max-body-chars/max-body-chars.ts b/mods/diff/hooks/views/detail/max-body-chars/max-body-chars.tsnew file mode 100644index 00000000..e2e294c8--- /dev/null+++ b/mods/diff/hooks/views/detail/max-body-chars/max-body-chars.ts@@ -0,0 +1,5 @@+/**+ * The most characters a file's drawn body holds in all, padding included:+ * under the host's whole-tree cap (100 000) with room for the pane's rest.+ */+export const MAX_BODY_CHARS = 80_000diff --git a/mods/diff/hooks/views/detail/max-body-nodes/index.ts b/mods/diff/hooks/views/detail/max-body-nodes/index.tsnew file mode 100644index 00000000..b81bd725--- /dev/null+++ b/mods/diff/hooks/views/detail/max-body-nodes/index.ts@@ -0,0 +1,3 @@+export * from './max-body-nodes.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/max-body-nodes/max-body-nodes.ts b/mods/diff/hooks/views/detail/max-body-nodes/max-body-nodes.tsnew file mode 100644index 00000000..10f58af5--- /dev/null+++ b/mods/diff/hooks/views/detail/max-body-nodes/max-body-nodes.ts@@ -0,0 +1,5 @@+/**+ * The most nodes a file's drawn body holds, strings included: under the+ * host's whole-tree cap (2 000) with room for the list and the pane's rest.+ */+export const MAX_BODY_NODES = 1_200diff --git a/mods/diff/hooks/views/detail/max-rows-of/frame-nodes/frame-nodes.ts b/mods/diff/hooks/views/detail/max-rows-of/frame-nodes/frame-nodes.tsnew file mode 100644index 00000000..4a54c58e--- /dev/null+++ b/mods/diff/hooks/views/detail/max-rows-of/frame-nodes/frame-nodes.ts@@ -0,0 +1,5 @@+/**+ * The nodes the body costs before any row: its row Box, the gutter Text+ * beside it, and the column Box that holds the runs.+ */+export const FRAME_NODES = 3diff --git a/mods/diff/hooks/views/detail/max-rows-of/frame-nodes/index.ts b/mods/diff/hooks/views/detail/max-rows-of/frame-nodes/index.tsnew file mode 100644index 00000000..d163b7f8--- /dev/null+++ b/mods/diff/hooks/views/detail/max-rows-of/frame-nodes/index.ts@@ -0,0 +1,3 @@+export * from './frame-nodes.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/max-rows-of/highlight-nodes/highlight-nodes.ts b/mods/diff/hooks/views/detail/max-rows-of/highlight-nodes/highlight-nodes.tsnew file mode 100644index 00000000..cf55ca56--- /dev/null+++ b/mods/diff/hooks/views/detail/max-rows-of/highlight-nodes/highlight-nodes.ts@@ -0,0 +1,5 @@+/**+ * The nodes one word highlight costs inside a run: the highlighted Text,+ * its string, and the string the run resumes with.+ */+export const HIGHLIGHT_NODES = 3diff --git a/mods/diff/hooks/views/detail/max-rows-of/highlight-nodes/index.ts b/mods/diff/hooks/views/detail/max-rows-of/highlight-nodes/index.tsnew file mode 100644index 00000000..9c8766a9--- /dev/null+++ b/mods/diff/hooks/views/detail/max-rows-of/highlight-nodes/index.ts@@ -0,0 +1,3 @@+export * from './highlight-nodes.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/max-rows-of/index.ts b/mods/diff/hooks/views/detail/max-rows-of/index.tsnew file mode 100644index 00000000..64112310--- /dev/null+++ b/mods/diff/hooks/views/detail/max-rows-of/index.ts@@ -0,0 +1,6 @@+export * from './frame-nodes'+export * from './highlight-nodes'+export * from './max-rows-of.js'+export * from './run-nodes'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/max-rows-of/max-rows-of.ts b/mods/diff/hooks/views/detail/max-rows-of/max-rows-of.tsnew file mode 100644index 00000000..a7cd3210--- /dev/null+++ b/mods/diff/hooks/views/detail/max-rows-of/max-rows-of.ts@@ -0,0 +1,59 @@+import Layout from '../../layout'+import type { BodyCells } from '../hunk-body/body-cells'+import { MARKER_CELLS } from '../marker-cells'+import { MAX_BODY_CHARS } from '../max-body-chars'+import { MAX_BODY_NODES } from '../max-body-nodes'+import { MAX_RUN_CHARS } from '../max-run-chars'+import type Types from '../types'+import { FRAME_NODES } from './frame-nodes'+import { HIGHLIGHT_NODES } from './highlight-nodes'+import { RUN_NODES } from './run-nodes'++/**+ * How many of these rows the body may draw under MAX_BODY_CHARS and+ * MAX_BODY_NODES, counted as the host counts what hunkBody draws.+ *+ * A row costs its gutter, marker, segments and padding in UTF-16 units (an+ * astral letter costs two); a change of kind opens a run (a Text and its+ * string), a highlight is three nodes, the gutter and long runs split.+ *+ * @param rows the laid-out rows, in order+ * @param cells the gutter's and the content's widths+ * @returns the count of leading rows whose drawn tree fits both budgets+ */+export function maxRowsOf(rows: readonly Types.Row[], cells: BodyCells) {+ let chars = 0+ let nodes = FRAME_NODES+ let kept = 0+ let kind: Types.LineKind | undefined++ for (const row of rows) {+ let units = 0+ let charged = 0+ let highlights = 0++ for (const segment of row.segments) {+ units += segment.text.length+ charged += Layout.chargedWidth(segment.text)+ highlights += segment.isChanged ? 1 : 0+ }++ chars +=+ cells.gutterCells ++ 2 ++ MARKER_CELLS ++ units ++ Math.max(0, cells.contentCells - charged)+ nodes += (row.kind === kind ? 0 : RUN_NODES) + highlights * HIGHLIGHT_NODES+ kind = row.kind+ const splits = Math.ceil((2 * chars) / MAX_RUN_CHARS)++ if (chars > MAX_BODY_CHARS || nodes + splits > MAX_BODY_NODES) {+ return kept+ }++ kept += 1+ }++ return kept+}diff --git a/mods/diff/hooks/views/detail/max-rows-of/run-nodes/index.ts b/mods/diff/hooks/views/detail/max-rows-of/run-nodes/index.tsnew file mode 100644index 00000000..75348395--- /dev/null+++ b/mods/diff/hooks/views/detail/max-rows-of/run-nodes/index.ts@@ -0,0 +1,3 @@+export * from './run-nodes.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/max-rows-of/run-nodes/run-nodes.ts b/mods/diff/hooks/views/detail/max-rows-of/run-nodes/run-nodes.tsnew file mode 100644index 00000000..46f77a05--- /dev/null+++ b/mods/diff/hooks/views/detail/max-rows-of/run-nodes/run-nodes.ts@@ -0,0 +1,4 @@+/**+ * The nodes a change of line kind opens: a Text and its string.+ */+export const RUN_NODES = 2diff --git a/mods/diff/hooks/views/detail/max-run-chars/index.ts b/mods/diff/hooks/views/detail/max-run-chars/index.tsnew file mode 100644index 00000000..f6fd9b0b--- /dev/null+++ b/mods/diff/hooks/views/detail/max-run-chars/index.ts@@ -0,0 +1,3 @@+export * from './max-run-chars.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/max-run-chars/max-run-chars.ts b/mods/diff/hooks/views/detail/max-run-chars/max-run-chars.tsnew file mode 100644index 00000000..a77d43e1--- /dev/null+++ b/mods/diff/hooks/views/detail/max-run-chars/max-run-chars.ts@@ -0,0 +1,5 @@+/**+ * The most characters one Text string of a run holds: under the host's+ * per-string cap (10 000), which a hooks module cannot import.+ */+export const MAX_RUN_CHARS = 8_000diff --git a/mods/diff/hooks/views/detail/placeholder-of/index.ts b/mods/diff/hooks/views/detail/placeholder-of/index.tsnew file mode 100644index 00000000..36afd40d--- /dev/null+++ b/mods/diff/hooks/views/detail/placeholder-of/index.ts@@ -0,0 +1,4 @@+export * from './placeholder-of.js'+export * from './safe-pathspec-pattern'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/placeholder-of/placeholder-of.ts b/mods/diff/hooks/views/detail/placeholder-of/placeholder-of.tsnew file mode 100644index 00000000..d3d6f6b2--- /dev/null+++ b/mods/diff/hooks/views/detail/placeholder-of/placeholder-of.ts@@ -0,0 +1,48 @@+import type { DetailModel } from '../detail-model'+import { SAFE_PATHSPEC_PATTERN } from './safe-pathspec-pattern'++/**+ * The dim italic lines drawn instead of hunks (DiffDetailView's wording),+ * or null when the hunks draw.+ *+ * Untracked (the pasteable `git add` line only for a name of letters,+ * digits and `._/@+-`, any other told to stage without one), binary,+ * loading, unreadable, large, or empty.+ *+ * @param detail the selected file+ * @returns the lines, or null+ */+export function placeholderOf(detail: DetailModel): readonly string[] | null {+ if (detail.isUntracked) {+ const isPasteable = SAFE_PATHSPEC_PATTERN.test(detail.path)++ return [+ 'New file not yet staged.',+ isPasteable+ ? `Run \`git add ':/${detail.path}'\` to see line counts.`+ : 'Stage it with git add to see line counts.',+ ]+ }++ if (detail.isBinary) {+ return ['Binary file - cannot display diff']+ }++ if (detail.bodyState === 'idle' || detail.bodyState === 'loading') {+ return ['Loading diff…']+ }++ if (detail.bodyState === 'failed' || !detail.body) {+ return ['Diff unavailable']+ }++ const { isLarge, hunks } = detail.body+ const isEmpty = hunks.length === 0+ const note = isLarge+ ? 'Large file - diff exceeds 1 MB limit'+ : isEmpty+ ? 'No diff content'+ : null++ return note ? [note] : null+}diff --git a/mods/diff/hooks/views/detail/placeholder-of/safe-pathspec-pattern/index.ts b/mods/diff/hooks/views/detail/placeholder-of/safe-pathspec-pattern/index.tsnew file mode 100644index 00000000..90d3e07f--- /dev/null+++ b/mods/diff/hooks/views/detail/placeholder-of/safe-pathspec-pattern/index.ts@@ -0,0 +1,3 @@+export * from './safe-pathspec-pattern.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/placeholder-of/safe-pathspec-pattern/safe-pathspec-pattern.ts b/mods/diff/hooks/views/detail/placeholder-of/safe-pathspec-pattern/safe-pathspec-pattern.tsnew file mode 100644index 00000000..3f936e93--- /dev/null+++ b/mods/diff/hooks/views/detail/placeholder-of/safe-pathspec-pattern/safe-pathspec-pattern.ts@@ -0,0 +1,7 @@+/**+ * A file name safe to paste inside `git add ':/…'` in any shell (POSIX,+ * PowerShell, cmd): letters and digits of any script and `._/@+-` only.+ *+ * No quote of any kind, no separator and no substitution can ride in it.+ */+export const SAFE_PATHSPEC_PATTERN = /^[\p{L}\p{N}._/@+-]+$/udiff --git a/mods/diff/hooks/views/detail/rows-of/index.ts b/mods/diff/hooks/views/detail/rows-of/index.tsnew file mode 100644index 00000000..04f748c7--- /dev/null+++ b/mods/diff/hooks/views/detail/rows-of/index.ts@@ -0,0 +1,5 @@+export * from './max-highlights'+export * from './rows-of.js'+export * from './segments-of'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/rows-of/max-highlights/index.ts b/mods/diff/hooks/views/detail/rows-of/max-highlights/index.tsnew file mode 100644index 00000000..6e25c387--- /dev/null+++ b/mods/diff/hooks/views/detail/rows-of/max-highlights/index.ts@@ -0,0 +1,3 @@+export * from './max-highlights.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/rows-of/max-highlights/max-highlights.ts b/mods/diff/hooks/views/detail/rows-of/max-highlights/max-highlights.tsnew file mode 100644index 00000000..accf1ccc--- /dev/null+++ b/mods/diff/hooks/views/detail/rows-of/max-highlights/max-highlights.ts@@ -0,0 +1,5 @@+/**+ * How many word-diff highlights one body may draw; past it lines draw plain,+ * keeping the tree under its node cap (each highlight is two nodes).+ */+export const MAX_HIGHLIGHTS = 300diff --git a/mods/diff/hooks/views/detail/rows-of/rows-of.ts b/mods/diff/hooks/views/detail/rows-of/rows-of.tsnew file mode 100644index 00000000..36e44dfe--- /dev/null+++ b/mods/diff/hooks/views/detail/rows-of/rows-of.ts@@ -0,0 +1,48 @@+import { countOf } from '../../../count-of'+import Layout from '../../layout'+import type Types from '../types'+import { MAX_HIGHLIGHTS } from './max-highlights'+import { segmentsOf } from './segments-of'++/**+ * Numbered lines laid into terminal rows: a long line wraps onto+ * continuation rows with an empty gutter.+ *+ * Word highlights stop once MAX_HIGHLIGHTS are spent, keeping the tree+ * under its node cap.+ *+ * @param lines the numbered lines+ * @param cells the content's room per row after gutter and marker, one at+ * least+ * @returns the rows in drawing order+ */+export function rowsOf(+ lines: readonly Types.DiffLine[],+ cells: number,+): Types.Row[] {+ const rows: Types.Row[] = []+ let highlights = 0++ for (const line of lines) {+ const marked = segmentsOf(line)+ const wanted = countOf(marked, segment => segment.isChanged)+ const isAffordable = highlights + wanted <= MAX_HIGHLIGHTS+ highlights += isAffordable ? wanted : 0+ const segments = isAffordable+ ? marked+ : [{ text: line.text, isChanged: false }]+ const marker =+ line.kind === 'added' ? '+' : line.kind === 'removed' ? '-' : ' '++ Layout.wrapSegments(segments, cells).forEach((wrapped, at) => {+ rows.push({+ kind: line.kind,+ gutter: at === 0 ? String(line.lineNumber) : '',+ marker: at === 0 ? marker : ' ',+ segments: wrapped,+ })+ })+ }++ return rows+}diff --git a/mods/diff/hooks/views/detail/rows-of/segments-of/index.ts b/mods/diff/hooks/views/detail/rows-of/segments-of/index.tsnew file mode 100644index 00000000..1bbbdb86--- /dev/null+++ b/mods/diff/hooks/views/detail/rows-of/segments-of/index.ts@@ -0,0 +1,3 @@+export * from './segments-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/rows-of/segments-of/segments-of.ts b/mods/diff/hooks/views/detail/rows-of/segments-of/segments-of.tsnew file mode 100644index 00000000..d38c2829--- /dev/null+++ b/mods/diff/hooks/views/detail/rows-of/segments-of/segments-of.ts@@ -0,0 +1,32 @@+import { wordDiff } from '../../../../word-diff'+import type Layout from '../../../layout'+import type Types from '../../types'++/**+ * A line's content as segments: one plain segment, or, for a paired line+ * whose word diff holds, its own side's parts with the changed ones marked.+ *+ * @param line the numbered line+ * @returns the segments in order+ */+export function segmentsOf(line: Types.DiffLine): Layout.Segment[] {+ const plain = [{ text: line.text, isChanged: false }]++ if (line.pairedText === null || line.kind === 'context') {+ return plain+ }++ const isRemoved = line.kind === 'removed'+ const parts = isRemoved+ ? wordDiff(line.text, line.pairedText)+ : wordDiff(line.pairedText, line.text)+ const ownSide = isRemoved ? 'removed' : 'added'++ if (!parts) {+ return plain+ }++ return parts+ .filter(part => part.kind === 'same' || part.kind === ownSide)+ .map(part => ({ text: part.text, isChanged: part.kind === ownSide }))+}diff --git a/mods/diff/hooks/views/detail/runs-of/index.ts b/mods/diff/hooks/views/detail/runs-of/index.tsnew file mode 100644index 00000000..baee7840--- /dev/null+++ b/mods/diff/hooks/views/detail/runs-of/index.ts@@ -0,0 +1,3 @@+export * from './runs-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/runs-of/runs-of.ts b/mods/diff/hooks/views/detail/runs-of/runs-of.tsnew file mode 100644index 00000000..c7539814--- /dev/null+++ b/mods/diff/hooks/views/detail/runs-of/runs-of.ts@@ -0,0 +1,23 @@+import type Types from '../types'++/**+ * Rows grouped into runs of one kind, in order.+ *+ * @param rows the laid-out rows+ * @returns the runs+ */+export function runsOf(rows: readonly Types.Row[]): Types.Run[] {+ const runs: Types.Run[] = []+ let start = 0++ rows.forEach((row, at) => {+ const isRunEnd = rows[at + 1]?.kind !== row.kind++ if (isRunEnd) {+ runs.push({ kind: row.kind, rows: rows.slice(start, at + 1) })+ start = at + 1+ }+ })++ return runs+}diff --git a/mods/diff/hooks/views/detail/types/diff-line/diff-line.ts b/mods/diff/hooks/views/detail/types/diff-line/diff-line.tsnew file mode 100644index 00000000..7a692663--- /dev/null+++ b/mods/diff/hooks/views/detail/types/diff-line/diff-line.ts@@ -0,0 +1,15 @@+import type { LineKind } from '../line-kind'++/**+ * One hunk line ready to lay out: its side, its gutter's line number, its+ * sanitized text, and the paired line's text for a word diff, if any.+ *+ * The number is the new file's for context and added lines, the old+ * file's for removed ones; a removed line pairs with its added counterpart.+ */+export type DiffLine = {+ kind: LineKind+ lineNumber: number+ text: string+ pairedText: string | null+}diff --git a/mods/diff/hooks/views/detail/types/diff-line/index.ts b/mods/diff/hooks/views/detail/types/diff-line/index.tsnew file mode 100644index 00000000..74685334--- /dev/null+++ b/mods/diff/hooks/views/detail/types/diff-line/index.ts@@ -0,0 +1,3 @@+export type * from './diff-line.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/types/index.ts b/mods/diff/hooks/views/detail/types/index.tsnew file mode 100644index 00000000..0bf55f05--- /dev/null+++ b/mods/diff/hooks/views/detail/types/index.ts@@ -0,0 +1,6 @@+export * from './diff-line'+export * from './line-kind'+export * from './row'+export type * from './run.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/types/line-kind/index.ts b/mods/diff/hooks/views/detail/types/line-kind/index.tsnew file mode 100644index 00000000..9b1925af--- /dev/null+++ b/mods/diff/hooks/views/detail/types/line-kind/index.ts@@ -0,0 +1,3 @@+export type * from './line-kind.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/types/line-kind/line-kind.ts b/mods/diff/hooks/views/detail/types/line-kind/line-kind.tsnew file mode 100644index 00000000..cc378105--- /dev/null+++ b/mods/diff/hooks/views/detail/types/line-kind/line-kind.ts@@ -0,0 +1,4 @@+/**+ * Which side of the diff a line is on, read from its marker.+ */+export type LineKind = 'context' | 'added' | 'removed'diff --git a/mods/diff/hooks/views/detail/types/row/index.ts b/mods/diff/hooks/views/detail/types/row/index.tsnew file mode 100644index 00000000..41a5adfa--- /dev/null+++ b/mods/diff/hooks/views/detail/types/row/index.ts@@ -0,0 +1,3 @@+export type * from './row.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/types/row/row.ts b/mods/diff/hooks/views/detail/types/row/row.tsnew file mode 100644index 00000000..4893b9ca--- /dev/null+++ b/mods/diff/hooks/views/detail/types/row/row.ts@@ -0,0 +1,13 @@+import type Layout from '../../../layout'+import type { LineKind } from '../line-kind'++/**+ * One terminal row of a file's body: the gutter's text (the line number,+ * or nothing on a continuation), the marker, and the content's segments.+ */+export type Row = {+ kind: LineKind+ gutter: string+ marker: string+ segments: readonly Layout.Segment[]+}diff --git a/mods/diff/hooks/views/detail/types/run.ts b/mods/diff/hooks/views/detail/types/run.tsnew file mode 100644index 00000000..65faf3b4--- /dev/null+++ b/mods/diff/hooks/views/detail/types/run.ts@@ -0,0 +1,11 @@+import type { LineKind } from './line-kind'+import type { Row } from './row'++/**+ * Consecutive rows of one kind, drawn as one Text so a long file stays far+ * under the tree's node cap.+ */+export type Run = {+ kind: LineKind+ rows: readonly Row[]+}diff --git a/mods/diff/hooks/views/detail/word-backgrounds/index.ts b/mods/diff/hooks/views/detail/word-backgrounds/index.tsnew file mode 100644index 00000000..4c966806--- /dev/null+++ b/mods/diff/hooks/views/detail/word-backgrounds/index.ts@@ -0,0 +1,3 @@+export * from './word-backgrounds.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/detail/word-backgrounds/word-backgrounds.ts b/mods/diff/hooks/views/detail/word-backgrounds/word-backgrounds.tsnew file mode 100644index 00000000..01a8bd2b--- /dev/null+++ b/mods/diff/hooks/views/detail/word-backgrounds/word-backgrounds.ts@@ -0,0 +1,11 @@+import type Types from '../types'++/**+ * The theme key behind a changed word of each kind (a context line never+ * carries one).+ */+export const WORD_BACKGROUNDS: Readonly<Record<Types.LineKind, string>> = {+ added: 'diffAddedWord',+ removed: 'diffRemovedWord',+ context: 'background',+}diff --git a/mods/diff/hooks/views/index.ts b/mods/diff/hooks/views/index.tsnew file mode 100644index 00000000..a69d8e87--- /dev/null+++ b/mods/diff/hooks/views/index.ts@@ -0,0 +1,10 @@+export * from './current-pane'+export * from './detail'+export * from './kit'+export * from './layout'+export * from './pane-actions'+export * from './pane-view.jsx'+export * from './sections'+export * from './turn-pane'++export * as default from '.'diff --git a/mods/diff/hooks/views/kit/index.ts b/mods/diff/hooks/views/kit/index.tsnew file mode 100644index 00000000..ae1cb795--- /dev/null+++ b/mods/diff/hooks/views/kit/index.ts@@ -0,0 +1,4 @@+export type * from './kit.js'+export * from './ui'++export * as default from '.'diff --git a/mods/diff/hooks/views/kit/kit.ts b/mods/diff/hooks/views/kit/kit.tsnew file mode 100644index 00000000..5950d26d--- /dev/null+++ b/mods/diff/hooks/views/kit/kit.ts@@ -0,0 +1,12 @@+import type { PaneActions } from '../pane-actions'+import type { Ui } from './ui'++/**+ * What every part of one drawing is handed: the surface's elements, the+ * controls' handlers, and the body's width (`props.bodyColumns`).+ */+export type Kit = {+ ui: Ui+ actions: PaneActions+ columns: number+}diff --git a/mods/diff/hooks/views/kit/ui/index.ts b/mods/diff/hooks/views/kit/ui/index.tsnew file mode 100644index 00000000..9d8eb46e--- /dev/null+++ b/mods/diff/hooks/views/kit/ui/index.ts@@ -0,0 +1,3 @@+export type * from './ui.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/kit/ui/ui.ts b/mods/diff/hooks/views/kit/ui/ui.tsnew file mode 100644index 00000000..b1fe9342--- /dev/null+++ b/mods/diff/hooks/views/kit/ui/ui.ts@@ -0,0 +1,13 @@+import type { ElementTable } from 'claude-code'++/**+ * The element constructors the pane draws with, destructured from the+ * table `$.ui.resolve(e)` hands the render hook.+ *+ * The terminal and the desktop carry all four; the mobile app has no+ * Select, so the pane never draws there.+ */+export type Ui = Pick<+ ElementTable<'terminal' | 'desktop'>,+ 'Box' | 'Text' | 'Button' | 'Select'+>diff --git a/mods/diff/hooks/views/layout/cell-width/cell-width.ts b/mods/diff/hooks/views/layout/cell-width/cell-width.tsnew file mode 100644index 00000000..f9b5f8c4--- /dev/null+++ b/mods/diff/hooks/views/layout/cell-width/cell-width.ts@@ -0,0 +1,29 @@+import { FIRST_WIDE_POINT } from './first-wide-point'+import { WIDE_RANGES } from './wide-ranges'+import { ZERO_WIDTH_RANGES } from './zero-width-ranges'++/**+ * How many terminal cells a sanitized line takes: one per code point, two+ * for a wide one, none for a combining or zero-width one.+ *+ * Everything below FIRST_WIDE_POINT, the common case in a diff, never+ * reaches the tables.+ *+ * @param text a line with no tabs or control characters+ * @returns its width in cells+ */+export function cellWidth(text: string) {+ let width = 0++ for (const character of text) {+ const point = character.codePointAt(0) ?? 0+ const holds = ([low, high]: readonly [number, number]) =>+ point >= low && point <= high+ const isNarrow = point < FIRST_WIDE_POINT+ const isZero = !isNarrow && ZERO_WIDTH_RANGES.some(holds)+ const isWide = !isNarrow && !isZero && WIDE_RANGES.some(holds)+ width += isZero ? 0 : isWide ? 2 : 1+ }++ return width+}diff --git a/mods/diff/hooks/views/layout/cell-width/first-wide-point/first-wide-point.ts b/mods/diff/hooks/views/layout/cell-width/first-wide-point/first-wide-point.tsnew file mode 100644index 00000000..243bdb51--- /dev/null+++ b/mods/diff/hooks/views/layout/cell-width/first-wide-point/first-wide-point.ts@@ -0,0 +1,5 @@+/**+ * The lowest code point any width table holds; everything below it is one+ * cell wide without a table lookup.+ */+export const FIRST_WIDE_POINT = 0x0300diff --git a/mods/diff/hooks/views/layout/cell-width/first-wide-point/index.ts b/mods/diff/hooks/views/layout/cell-width/first-wide-point/index.tsnew file mode 100644index 00000000..bf9cfd8f--- /dev/null+++ b/mods/diff/hooks/views/layout/cell-width/first-wide-point/index.ts@@ -0,0 +1,3 @@+export * from './first-wide-point.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/cell-width/index.ts b/mods/diff/hooks/views/layout/cell-width/index.tsnew file mode 100644index 00000000..1b3ef08c--- /dev/null+++ b/mods/diff/hooks/views/layout/cell-width/index.ts@@ -0,0 +1,6 @@+export * from './cell-width.js'+export * from './first-wide-point'+export * from './wide-ranges'+export * from './zero-width-ranges'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/cell-width/wide-ranges/index.ts b/mods/diff/hooks/views/layout/cell-width/wide-ranges/index.tsnew file mode 100644index 00000000..ec1884b0--- /dev/null+++ b/mods/diff/hooks/views/layout/cell-width/wide-ranges/index.ts@@ -0,0 +1,3 @@+export * from './wide-ranges.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/cell-width/wide-ranges/wide-ranges.ts b/mods/diff/hooks/views/layout/cell-width/wide-ranges/wide-ranges.tsnew file mode 100644index 00000000..609dba3f--- /dev/null+++ b/mods/diff/hooks/views/layout/cell-width/wide-ranges/wide-ranges.ts@@ -0,0 +1,20 @@+/**+ * Code point ranges a terminal draws two cells wide (Hangul Jamo, CJK,+ * fullwidth forms, emoji); an approximation of the engine's string width.+ */+export const WIDE_RANGES: readonly (readonly [number, number])[] = [+ [0x1100, 0x115f],+ [0x2e80, 0x303e],+ [0x3041, 0x33ff],+ [0x3400, 0x4dbf],+ [0x4e00, 0x9fff],+ [0xa000, 0xa4cf],+ [0xac00, 0xd7a3],+ [0xf900, 0xfaff],+ [0xfe30, 0xfe4f],+ [0xff00, 0xff60],+ [0xffe0, 0xffe6],+ [0x1f300, 0x1f64f],+ [0x1f900, 0x1f9ff],+ [0x20000, 0x3fffd],+]diff --git a/mods/diff/hooks/views/layout/cell-width/zero-width-ranges/index.ts b/mods/diff/hooks/views/layout/cell-width/zero-width-ranges/index.tsnew file mode 100644index 00000000..7b57e96c--- /dev/null+++ b/mods/diff/hooks/views/layout/cell-width/zero-width-ranges/index.ts@@ -0,0 +1,3 @@+export * from './zero-width-ranges.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/cell-width/zero-width-ranges/zero-width-ranges.ts b/mods/diff/hooks/views/layout/cell-width/zero-width-ranges/zero-width-ranges.tsnew file mode 100644index 00000000..349d28d5--- /dev/null+++ b/mods/diff/hooks/views/layout/cell-width/zero-width-ranges/zero-width-ranges.ts@@ -0,0 +1,10 @@+/**+ * Code point ranges that take no cell: combining marks, zero-width spaces+ * and joiners, variation selectors.+ */+export const ZERO_WIDTH_RANGES: readonly (readonly [number, number])[] = [+ [0x0300, 0x036f],+ [0x200b, 0x200f],+ [0xfe00, 0xfe0f],+ [0x20d0, 0x20ff],+]diff --git a/mods/diff/hooks/views/layout/charged-width/charged-width.ts b/mods/diff/hooks/views/layout/charged-width/charged-width.tsnew file mode 100644index 00000000..3354a840--- /dev/null+++ b/mods/diff/hooks/views/layout/charged-width/charged-width.ts@@ -0,0 +1,22 @@+import { cellWidth } from '../cell-width'++/**+ * The cells a sanitized text is charged when laid into rows and padded:+ * cellWidth, but a code point drawing in no cell is still charged one.+ *+ * The slicer and the band padding both count by this, so a row never+ * emits more code points than the cells it was given, combining marks or+ * not.+ *+ * @param text a line or segment with no tabs or control characters+ * @returns its charge in cells, at least one per code point+ */+export function chargedWidth(text: string) {+ let charged = 0++ for (const character of text) {+ charged += Math.max(1, cellWidth(character))+ }++ return charged+}diff --git a/mods/diff/hooks/views/layout/charged-width/index.ts b/mods/diff/hooks/views/layout/charged-width/index.tsnew file mode 100644index 00000000..bbb7075b--- /dev/null+++ b/mods/diff/hooks/views/layout/charged-width/index.ts@@ -0,0 +1,3 @@+export * from './charged-width.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/index.ts b/mods/diff/hooks/views/layout/index.tsnew file mode 100644index 00000000..20264812--- /dev/null+++ b/mods/diff/hooks/views/layout/index.ts@@ -0,0 +1,12 @@+export * from './cell-width'+export * from './charged-width'+export * from './plural'+export * from './sanitize-line'+export * from './sanitize-name'+export * from './segment'+export * from './slice-cells'+export * from './tab-width'+export * from './truncate-start'+export * from './wrap-segments'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/plural/index.ts b/mods/diff/hooks/views/layout/plural/index.tsnew file mode 100644index 00000000..c3ed00c1--- /dev/null+++ b/mods/diff/hooks/views/layout/plural/index.ts@@ -0,0 +1,3 @@+export * from './plural.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/plural/plural.ts b/mods/diff/hooks/views/layout/plural/plural.tsnew file mode 100644index 00000000..71a8ac46--- /dev/null+++ b/mods/diff/hooks/views/layout/plural/plural.ts@@ -0,0 +1,10 @@+/**+ * `1 file`, `2 files`: the count, a space, and the noun with an `s` unless+ * the count is one.+ *+ * @param count how many+ * @param noun the singular noun+ * @returns the phrase+ */+export const plural = (count: number, noun: string) =>+ count === 1 ? `1 ${noun}` : `${count} ${noun}s`diff --git a/mods/diff/hooks/views/layout/sanitize-line/index.ts b/mods/diff/hooks/views/layout/sanitize-line/index.tsnew file mode 100644index 00000000..da8f4c56--- /dev/null+++ b/mods/diff/hooks/views/layout/sanitize-line/index.ts@@ -0,0 +1,3 @@+export * from './sanitize-line.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/sanitize-line/sanitize-line.ts b/mods/diff/hooks/views/layout/sanitize-line/sanitize-line.tsnew file mode 100644index 00000000..d1bf798c--- /dev/null+++ b/mods/diff/hooks/views/layout/sanitize-line/sanitize-line.ts@@ -0,0 +1,17 @@+import { TAB_WIDTH } from '../tab-width'++/**+ * A diff line made safe to measure and draw: tabs become spaces, and every+ * control, format and default-ignorable character is dropped.+ *+ * The render tree refuses control characters; the rest (bidi overrides,+ * zero-width spaces and joiners, variation selectors, the soft hyphen)+ * draw as nothing, so nothing invisible can reorder, hide or pad a line.+ *+ * @param text one line of file content+ * @returns the drawable line+ */+export const sanitizeLine = (text: string) =>+ text+ .replaceAll('\t', ' '.repeat(TAB_WIDTH))+ .replace(/[\p{Cc}\p{Cf}\p{Default_Ignorable_Code_Point}]/gu, '')diff --git a/mods/diff/hooks/views/layout/sanitize-name/index.ts b/mods/diff/hooks/views/layout/sanitize-name/index.tsnew file mode 100644index 00000000..fce8ca0c--- /dev/null+++ b/mods/diff/hooks/views/layout/sanitize-name/index.ts@@ -0,0 +1,3 @@+export * from './sanitize-name.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/sanitize-name/sanitize-name.ts b/mods/diff/hooks/views/layout/sanitize-name/sanitize-name.tsnew file mode 100644index 00000000..4a973092--- /dev/null+++ b/mods/diff/hooks/views/layout/sanitize-name/sanitize-name.ts@@ -0,0 +1,13 @@+import { sanitizeLine } from '../sanitize-line'++/**+ * A path, preview or message made safe to draw as a name: sanitizeLine's+ * rule, which already drops every control, format and invisible character.+ *+ * Kept as its own word so a name's rule can tighten without touching the+ * diff body's.+ *+ * @param text the name as git, the transcript or an error gave it+ * @returns the drawable name+ */+export const sanitizeName = (text: string) => sanitizeLine(text)diff --git a/mods/diff/hooks/views/layout/segment/index.ts b/mods/diff/hooks/views/layout/segment/index.tsnew file mode 100644index 00000000..7702d779--- /dev/null+++ b/mods/diff/hooks/views/layout/segment/index.ts@@ -0,0 +1,3 @@+export type * from './segment.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/segment/segment.ts b/mods/diff/hooks/views/layout/segment/segment.tsnew file mode 100644index 00000000..1799cbe0--- /dev/null+++ b/mods/diff/hooks/views/layout/segment/segment.ts@@ -0,0 +1,8 @@+/**+ * One stretch of a drawn diff row: its text and whether the word diff+ * marks it as changed.+ */+export type Segment = {+ text: string+ isChanged: boolean+}diff --git a/mods/diff/hooks/views/layout/slice-cells/cells-split/cells-split.ts b/mods/diff/hooks/views/layout/slice-cells/cells-split/cells-split.tsnew file mode 100644index 00000000..7055d7ee--- /dev/null+++ b/mods/diff/hooks/views/layout/slice-cells/cells-split/cells-split.ts@@ -0,0 +1,9 @@+/**+ * A line cut at a cell budget: the head that fits, the budget it spent+ * (a code point that draws in no cell still spends one), and the tail.+ */+export type CellsSplit = {+ head: string+ spent: number+ tail: string+}diff --git a/mods/diff/hooks/views/layout/slice-cells/cells-split/index.ts b/mods/diff/hooks/views/layout/slice-cells/cells-split/index.tsnew file mode 100644index 00000000..b4ada917--- /dev/null+++ b/mods/diff/hooks/views/layout/slice-cells/cells-split/index.ts@@ -0,0 +1,3 @@+export type * from './cells-split.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/slice-cells/index.ts b/mods/diff/hooks/views/layout/slice-cells/index.tsnew file mode 100644index 00000000..110bebcb--- /dev/null+++ b/mods/diff/hooks/views/layout/slice-cells/index.ts@@ -0,0 +1,4 @@+export * from './cells-split'+export * from './slice-cells.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/slice-cells/slice-cells.ts b/mods/diff/hooks/views/layout/slice-cells/slice-cells.tsnew file mode 100644index 00000000..859d01fc--- /dev/null+++ b/mods/diff/hooks/views/layout/slice-cells/slice-cells.ts@@ -0,0 +1,37 @@+import { chargedWidth } from '../charged-width'+import type { CellsSplit } from './cells-split'++/**+ * The longest head of a line that fits a cell budget, cut between code+ * points, and what is left after it.+ *+ * The budget is spent by chargedWidth, at least one cell a code point, so+ * a head never holds more code points than cells: a line of ten thousand+ * combining marks still wraps.+ *+ * @param text a sanitized line+ * @param cells the room, at least one cell+ * @returns the head that fits, the budget it spent, and the remaining tail+ */+export function sliceCells(text: string, cells: number): CellsSplit {+ let spent = 0+ let taken = 0+ const characters = [...text]++ for (const character of characters) {+ const next = spent + chargedWidth(character)++ if (next > cells && taken > 0) {+ break+ }++ spent = next+ taken += 1+ }++ return {+ head: characters.slice(0, taken).join(''),+ spent,+ tail: characters.slice(taken).join(''),+ }+}diff --git a/mods/diff/hooks/views/layout/tab-width/index.ts b/mods/diff/hooks/views/layout/tab-width/index.tsnew file mode 100644index 00000000..a5c8786b--- /dev/null+++ b/mods/diff/hooks/views/layout/tab-width/index.ts@@ -0,0 +1,3 @@+export * from './tab-width.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/tab-width/tab-width.ts b/mods/diff/hooks/views/layout/tab-width/tab-width.tsnew file mode 100644index 00000000..b271b2ab--- /dev/null+++ b/mods/diff/hooks/views/layout/tab-width/tab-width.ts@@ -0,0 +1,5 @@+/**+ * The spaces a tab in a diff line becomes before the line is measured and+ * wrapped.+ */+export const TAB_WIDTH = 4diff --git a/mods/diff/hooks/views/layout/truncate-start/index.ts b/mods/diff/hooks/views/layout/truncate-start/index.tsnew file mode 100644index 00000000..615b34a7--- /dev/null+++ b/mods/diff/hooks/views/layout/truncate-start/index.ts@@ -0,0 +1,3 @@+export * from './truncate-start.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/truncate-start/truncate-start.ts b/mods/diff/hooks/views/layout/truncate-start/truncate-start.tsnew file mode 100644index 00000000..3cf30e0e--- /dev/null+++ b/mods/diff/hooks/views/layout/truncate-start/truncate-start.ts@@ -0,0 +1,34 @@+import { chargedWidth } from '../charged-width'++/**+ * A path cut from its start to fit, an ellipsis standing for what went, so+ * the file name survives, as the engine truncates a path from its start.+ *+ * It counts by chargedWidth, a cell at least per code point, so a name+ * padded with combining marks is cut like any other and never passes the+ * room whole.+ *+ * @param text the path+ * @param cells the room+ * @returns the path, or `…` and its tail+ */+export function truncateStart(text: string, cells: number) {+ if (chargedWidth(text) <= cells) {+ return text+ }++ const characters = [...text]+ let kept = ''++ for (let at = characters.length - 1; at >= 0; at--) {+ const candidate = `${characters[at]}${kept}`++ if (chargedWidth(candidate) + 1 > cells) {+ break+ }++ kept = candidate+ }++ return `…${kept}`+}diff --git a/mods/diff/hooks/views/layout/wrap-segments/index.ts b/mods/diff/hooks/views/layout/wrap-segments/index.tsnew file mode 100644index 00000000..15c13b85--- /dev/null+++ b/mods/diff/hooks/views/layout/wrap-segments/index.ts@@ -0,0 +1,3 @@+export * from './wrap-segments.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/layout/wrap-segments/wrap-segments.ts b/mods/diff/hooks/views/layout/wrap-segments/wrap-segments.tsnew file mode 100644index 00000000..2d60129f--- /dev/null+++ b/mods/diff/hooks/views/layout/wrap-segments/wrap-segments.ts@@ -0,0 +1,43 @@+import type { Segment } from '../segment'+import { sliceCells } from '../slice-cells'++/**+ * A line's segments laid into rows of at most a cell budget, a segment+ * split where a row fills, so each row draws as exactly one terminal row.+ *+ * A row holds no more code points than cells (sliceCells' spending), and+ * a continuation can sit under an empty gutter.+ *+ * @param segments the line's segments in order+ * @param cells the room per row, at least one cell+ * @returns the rows; one empty row for an empty line+ */+export function wrapSegments(+ segments: readonly Segment[],+ cells: number,+): Segment[][] {+ const rows: Segment[][] = []+ let row: Segment[] = []+ let used = 0++ for (const segment of segments) {+ let rest = segment.text++ while (rest !== '') {+ const split = sliceCells(rest, Math.max(1, cells - used))+ row.push({ text: split.head, isChanged: segment.isChanged })+ used += split.spent+ rest = split.tail++ if (rest !== '' || used >= cells) {+ rows.push(row)+ row = []+ used = 0+ }+ }+ }++ const isRowPending = row.length > 0 || rows.length === 0++ return isRowPending ? [...rows, row] : rows+}diff --git a/mods/diff/hooks/views/pane-actions/index.ts b/mods/diff/hooks/views/pane-actions/index.tsnew file mode 100644index 00000000..c76c6da7--- /dev/null+++ b/mods/diff/hooks/views/pane-actions/index.ts@@ -0,0 +1,3 @@+export type * from './pane-actions.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/pane-actions/pane-actions.ts b/mods/diff/hooks/views/pane-actions/pane-actions.tsnew file mode 100644index 00000000..a66c943d--- /dev/null+++ b/mods/diff/hooks/views/pane-actions/pane-actions.ts@@ -0,0 +1,36 @@+/**+ * What the pane's Buttons and Selects do, each closing over the plugin's+ * state in its register function.+ */+export type PaneActions = {+ /**+ * Shows this file's body under the list.+ */+ selectFile: (path: string) => void++ /**+ * Shows or hides the tests and generated files.+ */+ toggleNoise: () => void++ /**+ * Opens or closes the pre-session section.+ */+ togglePreSession: () => void++ /**+ * Picks the comparison base by its Select value; an unknown value is+ * ignored.+ */+ chooseBase: (value: string) => void++ /**+ * Picks the source by its Select value: `current` or a turn's number.+ */+ chooseSource: (value: string) => void++ /**+ * Arms this file's diff for the next prompt, or disarms it.+ */+ toggleAsk: (path: string) => void+}diff --git a/mods/diff/hooks/views/pane-view.tsx b/mods/diff/hooks/views/pane-view.tsxnew file mode 100644index 00000000..813d44f3--- /dev/null+++ b/mods/diff/hooks/views/pane-view.tsx@@ -0,0 +1,24 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import PaneState from '../pane-state'+import { currentPane } from './current-pane'+import type { Kit } from './kit'+import { turnPane } from './turn-pane'++/**+ * The diff pane's body for one `ui.render`: the repository's diff now, or+ * the picked turn's edits while that turn still exists (a rewind drops it).+ *+ * @param kit the elements, the handlers, the width+ * @param model the pane's state+ * @returns the tree+ */+export function paneView(kit: Kit, model: PaneState.PaneModel): RenderElement {+ const turn = PaneState.pickedTurnOf(model)+ const isCurrent = turn === undefined++ return isCurrent ? currentPane(kit, model) : turnPane(kit, model, turn)+}diff --git a/mods/diff/hooks/views/sections/controls-view.tsx b/mods/diff/hooks/views/sections/controls-view.tsxnew file mode 100644index 00000000..41db64a7--- /dev/null+++ b/mods/diff/hooks/views/sections/controls-view.tsx@@ -0,0 +1,65 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import type PaneState from '../../pane-state'+import type { Kit } from '../kit'+import { present } from './present'++/**+ * The pickers under the header: the source (`Current`, then `T<n>` per+ * turn with edits, newest first) and, for the current source, the base.+ *+ * The source picker draws only when a turn exists, as DiffDialog hides its+ * tabs; the base picker is the built-in's ctrl+x b cycle as a Select.+ *+ * @param kit the elements and the handlers+ * @param model what is picked now and the turns to pick from+ * @returns the row, or null when neither picker applies+ */+export function controlsView(+ kit: Kit,+ model: Pick<PaneState.PaneModel, 'source' | 'requestedMode' | 'turns'>,+): RenderElement | null {+ const { Box, Select } = kit.ui+ const { source, turns } = model+ const hasTurns = turns.length > 0+ const sourcePicker = hasTurns ? (+ <Select+ key="source"+ label="source"+ options={[+ { value: 'current', label: 'Current' },+ ...turns.map(turn => ({+ value: String(turn.index),+ label: `T${turn.index}`,+ })),+ ]}+ value={source.kind === 'current' ? 'current' : String(source.index)}+ onSelect={value => kit.actions.chooseSource(value)}+ />+ ) : null+ const isCurrent = source.kind === 'current'+ const basePicker = isCurrent ? (+ <Select+ key="base"+ label="base"+ options={[+ { value: 'session', label: 'this session' },+ { value: 'uncommitted', label: 'uncommitted (vs HEAD)' },+ { value: 'branch', label: 'branch' },+ ]}+ value={model.requestedMode}+ onSelect={value => kit.actions.chooseBase(value)}+ />+ ) : null+ const pickers = present([sourcePicker, basePicker])+ const row = (+ <Box flexDirection="row" gap={2}>+ {pickers}+ </Box>+ )++ return pickers.length === 0 ? null : row+}diff --git a/mods/diff/hooks/views/sections/diff-stat/diff-stat.tsx b/mods/diff/hooks/views/sections/diff-stat/diff-stat.tsxnew file mode 100644index 00000000..423927e9--- /dev/null+++ b/mods/diff/hooks/views/sections/diff-stat/diff-stat.tsx@@ -0,0 +1,32 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import type { Kit } from '../../kit'++/**+ * `+N -M` in the diff's word colours, a side left out at zero and nothing+ * at all at 0/0 (design-system DiffStat).+ *+ * @param kit the drawing's kit; its elements draw the counts+ * @param added lines added+ * @param removed lines removed+ * @returns the inline element+ */+export function diffStat(+ kit: Kit,+ added: number,+ removed: number,+): RenderElement {+ const { Text } = kit.ui+ const hasBoth = added > 0 && removed > 0++ return (+ <Text>+ {added > 0 ? <Text color="diffAddedWord">{`+${added}`}</Text> : ''}+ {hasBoth ? ' ' : ''}+ {removed > 0 ? <Text color="diffRemovedWord">{`-${removed}`}</Text> : ''}+ </Text>+ )+}diff --git a/mods/diff/hooks/views/sections/diff-stat/index.ts b/mods/diff/hooks/views/sections/diff-stat/index.tsnew file mode 100644index 00000000..afaeb9c5--- /dev/null+++ b/mods/diff/hooks/views/sections/diff-stat/index.ts@@ -0,0 +1,3 @@+export * from './diff-stat.jsx'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/dim-note/dim-note.tsx b/mods/diff/hooks/views/sections/dim-note/dim-note.tsxnew file mode 100644index 00000000..0994309d--- /dev/null+++ b/mods/diff/hooks/views/sections/dim-note/dim-note.tsx@@ -0,0 +1,23 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import type { Kit } from '../../kit'++/**+ * One dim line of the pane: a hint, an elision count, a base label.+ *+ * @param kit the drawing's kit; its elements draw the line+ * @param text the line+ * @returns the element+ */+export function dimNote(kit: Kit, text: string): RenderElement {+ const { Text } = kit.ui++ return (+ <Text dimColor wrap="truncate-end">+ {text}+ </Text>+ )+}diff --git a/mods/diff/hooks/views/sections/dim-note/index.ts b/mods/diff/hooks/views/sections/dim-note/index.tsnew file mode 100644index 00000000..7adf3e29--- /dev/null+++ b/mods/diff/hooks/views/sections/dim-note/index.ts@@ -0,0 +1,3 @@+export * from './dim-note.jsx'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/divider.tsx b/mods/diff/hooks/views/sections/divider.tsxnew file mode 100644index 00000000..22ee9ec4--- /dev/null+++ b/mods/diff/hooks/views/sections/divider.tsx@@ -0,0 +1,22 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import type { Kit } from '../kit'++/**+ * A dim rule across the body, between the list and the selected file.+ *+ * @param kit the elements and the width+ * @returns the rule+ */+export function divider(kit: Kit): RenderElement {+ const { Text } = kit.ui++ return (+ <Text dimColor wrap="truncate-end">+ {'─'.repeat(Math.max(1, kit.columns))}+ </Text>+ )+}diff --git a/mods/diff/hooks/views/sections/file-key-of/file-key-of.ts b/mods/diff/hooks/views/sections/file-key-of/file-key-of.tsnew file mode 100644index 00000000..0f73ee18--- /dev/null+++ b/mods/diff/hooks/views/sections/file-key-of/file-key-of.ts@@ -0,0 +1,9 @@+import Layout from '../../layout'++/**+ * A file row's Button address: the path made printable, under `file:`.+ *+ * @param path the file's path as git or the transcript gave it+ * @returns the key+ */+export const fileKeyOf = (path: string) => `file:${Layout.sanitizeName(path)}`diff --git a/mods/diff/hooks/views/sections/file-key-of/index.ts b/mods/diff/hooks/views/sections/file-key-of/index.tsnew file mode 100644index 00000000..c7db4eb4--- /dev/null+++ b/mods/diff/hooks/views/sections/file-key-of/index.ts@@ -0,0 +1,3 @@+export * from './file-key-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/file-row-model/file-row-model.ts b/mods/diff/hooks/views/sections/file-row-model/file-row-model.tsnew file mode 100644index 00000000..541f1a1d--- /dev/null+++ b/mods/diff/hooks/views/sections/file-row-model/file-row-model.ts@@ -0,0 +1,12 @@+/**+ * One listed file as its row draws it: the Button's address, the path, the+ * counts or a dim note in their place, and whether its body shows.+ */+export type FileRowModel = {+ key: string+ path: string+ added: number+ removed: number+ note: string | null+ isSelected: boolean+}diff --git a/mods/diff/hooks/views/sections/file-row-model/index.ts b/mods/diff/hooks/views/sections/file-row-model/index.tsnew file mode 100644index 00000000..9bac45ba--- /dev/null+++ b/mods/diff/hooks/views/sections/file-row-model/index.ts@@ -0,0 +1,3 @@+export type * from './file-row-model.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/file-row/file-row.tsx b/mods/diff/hooks/views/sections/file-row/file-row.tsxnew file mode 100644index 00000000..488b1854--- /dev/null+++ b/mods/diff/hooks/views/sections/file-row/file-row.tsx@@ -0,0 +1,49 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import type { Kit } from '../../kit'+import Layout from '../../layout'+import { diffStat } from '../diff-stat'+import type { FileRowModel } from '../file-row-model'+import { POINTER } from '../pointer'+import { STAT_CELLS } from '../stat-cells'++/**+ * One file of the list (ReplDiffSidebar FileSummaryRow): a plain Button+ * with the start-truncated path, its counts or note at the right.+ *+ * The pointer marks the selected one.+ *+ * @param kit the elements, the handlers, the width+ * @param row the file+ * @param onPress selects the file+ * @returns the row element+ */+export function fileRow(+ kit: Kit,+ row: FileRowModel,+ onPress: () => void,+): RenderElement {+ const { Box, Text, Button } = kit.ui+ const room = Math.max(kit.columns - STAT_CELLS, STAT_CELLS)+ const mark = row.isSelected ? POINTER : ' '+ const note = (+ <Text dimColor italic>+ {row.note ?? ''}+ </Text>+ )+ const hasNote = row.note !== null+ const tail = hasNote ? note : diffStat(kit, row.added, row.removed)++ return (+ <Box flexDirection="row">+ <Button key={row.key} plain onPress={onPress}>+ {`${mark} ${Layout.truncateStart(Layout.sanitizeName(row.path), room)}`}+ </Button>+ <Box flexGrow={1} />+ {tail}+ </Box>+ )+}diff --git a/mods/diff/hooks/views/sections/file-row/index.ts b/mods/diff/hooks/views/sections/file-row/index.tsnew file mode 100644index 00000000..2e7f25d4--- /dev/null+++ b/mods/diff/hooks/views/sections/file-row/index.ts@@ -0,0 +1,3 @@+export * from './file-row.jsx'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/header-view.tsx b/mods/diff/hooks/views/sections/header-view.tsxnew file mode 100644index 00000000..b69bf9f5--- /dev/null+++ b/mods/diff/hooks/views/sections/header-view.tsx@@ -0,0 +1,43 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import type PaneState from '../../pane-state'+import type { Kit } from '../kit'+import Layout from '../layout'+import { diffStat } from './diff-stat'++/**+ * The pane's first line: `N files changed +A -R`, or the empty headline in+ * its place when there is nothing to count (ReplDiffSidebar's header).+ *+ * The headline may name a branch the repository chose, so it is drawn as+ * a name: no control or format character survives.+ *+ * @param kit the drawing's kit; its elements draw the line+ * @param headline the empty headline, or null to draw the counts+ * @param totals the header's counts+ * @returns the line+ */+export function headerView(+ kit: Kit,+ headline: string | null,+ totals: PaneState.HeaderTotals,+): RenderElement {+ const { Text } = kit.ui+ const empty = (+ <Text dimColor wrap="truncate-end">+ {Layout.sanitizeName(headline ?? '')}+ </Text>+ )+ const counts = (+ <Text wrap="truncate-end">+ <Text bold>{Layout.plural(totals.filesCount, 'file')}</Text>+ {' changed '}+ {diffStat(kit, totals.linesAdded, totals.linesRemoved)}+ </Text>+ )++ return headline === null ? counts : empty+}diff --git a/mods/diff/hooks/views/sections/index.ts b/mods/diff/hooks/views/sections/index.tsnew file mode 100644index 00000000..fd97560d--- /dev/null+++ b/mods/diff/hooks/views/sections/index.ts@@ -0,0 +1,18 @@+export * from './controls-view.jsx'+export * from './diff-stat'+export * from './dim-note'+export * from './divider.jsx'+export * from './file-key-of'+export * from './file-row'+export * from './file-row-model'+export * from './header-view.jsx'+export * from './pointer'+export * from './present'+export * from './pressable'+export * from './stat-cells'+export * from './todo-bar.jsx'+export * from './todo-bar-cells'+export * from './todo-bar-reserve'+export * from './toggle-row.jsx'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/pointer/index.ts b/mods/diff/hooks/views/sections/pointer/index.tsnew file mode 100644index 00000000..eb89af57--- /dev/null+++ b/mods/diff/hooks/views/sections/pointer/index.ts@@ -0,0 +1,3 @@+export * from './pointer.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/pointer/pointer.ts b/mods/diff/hooks/views/sections/pointer/pointer.tsnew file mode 100644index 00000000..d0e13e25--- /dev/null+++ b/mods/diff/hooks/views/sections/pointer/pointer.ts@@ -0,0 +1,4 @@+/**+ * Drawn before the selected file's row (DiffFileList's pointer).+ */+export const POINTER = '❯'diff --git a/mods/diff/hooks/views/sections/present/index.ts b/mods/diff/hooks/views/sections/present/index.tsnew file mode 100644index 00000000..ae76f18f--- /dev/null+++ b/mods/diff/hooks/views/sections/present/index.ts@@ -0,0 +1,3 @@+export * from './present.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/present/present.ts b/mods/diff/hooks/views/sections/present/present.tsnew file mode 100644index 00000000..04f8a099--- /dev/null+++ b/mods/diff/hooks/views/sections/present/present.ts@@ -0,0 +1,13 @@+import type { RenderElement } from 'claude-code'++/**+ * The children that are there: nulls dropped, so a part may answer null for+ * "nothing to draw" and the parent lists it all the same.+ *+ * @param children elements or nulls+ * @returns the elements+ */+export const present = (+ children: readonly (RenderElement | null)[],+): RenderElement[] =>+ children.filter((child): child is RenderElement => child !== null)diff --git a/mods/diff/hooks/views/sections/pressable/index.ts b/mods/diff/hooks/views/sections/pressable/index.tsnew file mode 100644index 00000000..8d5fc84f--- /dev/null+++ b/mods/diff/hooks/views/sections/pressable/index.ts@@ -0,0 +1,3 @@+export type * from './pressable.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/pressable/pressable.ts b/mods/diff/hooks/views/sections/pressable/pressable.tsnew file mode 100644index 00000000..3585854f--- /dev/null+++ b/mods/diff/hooks/views/sections/pressable/pressable.ts@@ -0,0 +1,11 @@+/**+ * A plain Button's face and what pressing it does.+ */+export type Pressable = {+ label: string++ /**+ * Runs on a click or Enter.+ */+ onPress: () => void+}diff --git a/mods/diff/hooks/views/sections/stat-cells/index.ts b/mods/diff/hooks/views/sections/stat-cells/index.tsnew file mode 100644index 00000000..66c29aea--- /dev/null+++ b/mods/diff/hooks/views/sections/stat-cells/index.ts@@ -0,0 +1,3 @@+export * from './stat-cells.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/stat-cells/stat-cells.ts b/mods/diff/hooks/views/sections/stat-cells/stat-cells.tsnew file mode 100644index 00000000..133ba8a4--- /dev/null+++ b/mods/diff/hooks/views/sections/stat-cells/stat-cells.ts@@ -0,0 +1,5 @@+/**+ * The cells a file row keeps for its `+N -M` (ReplDiffSidebar's 12) and the+ * selection pointer before the path.+ */+export const STAT_CELLS = 14diff --git a/mods/diff/hooks/views/sections/todo-bar-cells/index.ts b/mods/diff/hooks/views/sections/todo-bar-cells/index.tsnew file mode 100644index 00000000..8570d75b--- /dev/null+++ b/mods/diff/hooks/views/sections/todo-bar-cells/index.ts@@ -0,0 +1,3 @@+export * from './todo-bar-cells.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/todo-bar-cells/todo-bar-cells.ts b/mods/diff/hooks/views/sections/todo-bar-cells/todo-bar-cells.tsnew file mode 100644index 00000000..364678a5--- /dev/null+++ b/mods/diff/hooks/views/sections/todo-bar-cells/todo-bar-cells.ts@@ -0,0 +1,4 @@+/**+ * The widest the todo progress bar draws (ReplDiffSidebar's 20).+ */+export const TODO_BAR_CELLS = 20diff --git a/mods/diff/hooks/views/sections/todo-bar-reserve/index.ts b/mods/diff/hooks/views/sections/todo-bar-reserve/index.tsnew file mode 100644index 00000000..e914070d--- /dev/null+++ b/mods/diff/hooks/views/sections/todo-bar-reserve/index.ts@@ -0,0 +1,3 @@+export * from './todo-bar-reserve.js'++export * as default from '.'diff --git a/mods/diff/hooks/views/sections/todo-bar-reserve/todo-bar-reserve.ts b/mods/diff/hooks/views/sections/todo-bar-reserve/todo-bar-reserve.tsnew file mode 100644index 00000000..24b17085--- /dev/null+++ b/mods/diff/hooks/views/sections/todo-bar-reserve/todo-bar-reserve.ts@@ -0,0 +1,4 @@+/**+ * The cells kept beside the todo bar for its `done/total` count.+ */+export const TODO_BAR_RESERVE = 12diff --git a/mods/diff/hooks/views/sections/todo-bar.tsx b/mods/diff/hooks/views/sections/todo-bar.tsxnew file mode 100644index 00000000..a1101a14--- /dev/null+++ b/mods/diff/hooks/views/sections/todo-bar.tsx@@ -0,0 +1,43 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import type Todos from '../../todos'+import type { Kit } from '../kit'+import { TODO_BAR_CELLS } from './todo-bar-cells'+import { TODO_BAR_RESERVE } from './todo-bar-reserve'++/**+ * The session's todo progress as a bar and `done/total`, drawn only while+ * a todo list exists (ReplDiffSidebar's ProgressBar row).+ *+ * @param kit the elements and the width+ * @param todos completed over total+ * @returns the row, or null without todos+ */+export function todoBar(+ kit: Kit,+ todos: Todos.TodoProgress,+): RenderElement | null {+ if (todos.total === 0) {+ return null+ }++ const { Box, Text } = kit.ui+ const cells = Math.max(+ 1,+ Math.min(TODO_BAR_CELLS, kit.columns - TODO_BAR_RESERVE),+ )+ const filled = Math.round((todos.done / todos.total) * cells)++ return (+ <Box flexDirection="row" gap={1} marginTop={1}>+ <Text>+ <Text color="success">{'█'.repeat(filled)}</Text>+ <Text color="inactive">{'░'.repeat(Math.max(0, cells - filled))}</Text>+ </Text>+ <Text dimColor>{`${todos.done}/${todos.total}`}</Text>+ </Box>+ )+}diff --git a/mods/diff/hooks/views/sections/toggle-row.tsx b/mods/diff/hooks/views/sections/toggle-row.tsxnew file mode 100644index 00000000..9d911161--- /dev/null+++ b/mods/diff/hooks/views/sections/toggle-row.tsx@@ -0,0 +1,32 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import type { Kit } from '../kit'+import type { Pressable } from './pressable'++/**+ * A clickable line that shows or hides a group (ReplDiffSidebar's+ * NoiseFilterToggle and pre-session header), as a plain Button.+ *+ * @param kit the drawing's kit; its elements draw the row+ * @param key the Button's address+ * @param pressable the line's text, `(show)` or `(hide)` in it, and its press+ * @returns the row+ */+export function toggleRow(+ kit: Kit,+ key: string,+ pressable: Pressable,+): RenderElement {+ const { Box, Button } = kit.ui++ return (+ <Box flexDirection="row">+ <Button key={key} plain onPress={pressable.onPress}>+ {pressable.label}+ </Button>+ </Box>+ )+}diff --git a/mods/diff/hooks/views/turn-pane/index.ts b/mods/diff/hooks/views/turn-pane/index.tsnew file mode 100644index 00000000..76fb5d2b--- /dev/null+++ b/mods/diff/hooks/views/turn-pane/index.ts@@ -0,0 +1,3 @@+export * from './turn-pane.jsx'++export * as default from '.'diff --git a/mods/diff/hooks/views/turn-pane/turn-pane.tsx b/mods/diff/hooks/views/turn-pane/turn-pane.tsxnew file mode 100644index 00000000..e8eb38b5--- /dev/null+++ b/mods/diff/hooks/views/turn-pane/turn-pane.tsx@@ -0,0 +1,83 @@+/* @jsxRuntime classic */+/* @jsx h */+/* @jsxFrag Fragment */+import type { RenderElement } from 'claude-code'++import PaneState from '../../pane-state'+import type Turns from '../../turns'+import Detail from '../detail'+import type { Kit } from '../kit'+import Layout from '../layout'+import Sections from '../sections'++/**+ * The pane over one past turn's edits (DiffDialog's T<n> tab): the turn's+ * counts, its prompt's opening words, the pickers, its files, one body.+ *+ * @param kit the elements, the handlers, the width+ * @param model the pane's state+ * @param turn the turn picked+ * @returns the pane's tree+ */+export function turnPane(+ kit: Kit,+ model: PaneState.PaneModel,+ turn: Turns.TurnDiff,+): RenderElement {+ const { Box } = kit.ui+ const selected =+ turn.files.find(file => file.path === model.selectedPath) ??+ turn.files[0] ??+ null+ const rows = turn.files.map(file =>+ Sections.fileRow(+ kit,+ {+ key: Sections.fileKeyOf(file.path),+ path: file.path,+ added: file.added,+ removed: file.removed,+ note: null,+ isSelected: file.path === selected?.path,+ },+ () => kit.actions.selectFile(file.path),+ ),+ )+ const detail = selected+ ? [+ Sections.divider(kit),+ Detail.detailView(+ kit,+ {+ path: selected.path,+ renamedFrom: null,+ isUntracked: false,+ isBinary: false,+ body: {+ hunks: selected.hunks,+ isTruncated: selected.isTruncated,+ isLarge: false,+ },+ bodyState: 'ready',+ isArmed: model.armedPath === selected.path,+ },+ () => kit.actions.toggleAsk(selected.path),+ ),+ ]+ : []++ return (+ <Box flexDirection="column">+ {Sections.present([+ Sections.headerView(kit, null, PaneState.turnTotalsOf(turn)),+ Sections.dimNote(+ kit,+ `Turn ${turn.index} "${Layout.sanitizeName(turn.preview)}"`,+ ),+ Sections.controlsView(kit, model),+ ...rows,+ ...detail,+ ])}+ </Box>+ )+}diff --git a/mods/diff/hooks/word-diff/change-threshold/change-threshold.ts b/mods/diff/hooks/word-diff/change-threshold/change-threshold.tsnew file mode 100644index 00000000..02a48ae7--- /dev/null+++ b/mods/diff/hooks/word-diff/change-threshold/change-threshold.ts@@ -0,0 +1,5 @@+/**+ * Past this share of changed characters a line pair reads as rewritten, not+ * edited, and gets no word highlights (the engine's fallback diff rule).+ */+export const CHANGE_THRESHOLD = 0.4diff --git a/mods/diff/hooks/word-diff/change-threshold/index.ts b/mods/diff/hooks/word-diff/change-threshold/index.tsnew file mode 100644index 00000000..82132d14--- /dev/null+++ b/mods/diff/hooks/word-diff/change-threshold/index.ts@@ -0,0 +1,3 @@+export * from './change-threshold.js'++export * as default from '.'diff --git a/mods/diff/hooks/word-diff/diff-parts/diff-parts.ts b/mods/diff/hooks/word-diff/diff-parts/diff-parts.tsnew file mode 100644index 00000000..72a07e0b--- /dev/null+++ b/mods/diff/hooks/word-diff/diff-parts/diff-parts.ts@@ -0,0 +1,76 @@+import { MAX_LCS_CELLS } from '../max-lcs-cells'+import type { WordPart } from '../word-part'++/**+ * The parts of a longest-common-subsequence diff of two token lists, in+ * order, adjacent parts of one kind merged.+ *+ * Null when the table would pass MAX_LCS_CELLS.+ *+ * @param before the removed line's tokens+ * @param after the added line's tokens+ * @returns the parts, or null for lines too long to compare+ */+export function diffParts(+ before: readonly string[],+ after: readonly string[],+): WordPart[] | null {+ const columns = after.length + 1++ if ((before.length + 1) * columns > MAX_LCS_CELLS) {+ return null+ }++ const lengths = new Uint32Array((before.length + 1) * columns)+ const at = (i: number, j: number) => lengths[i * columns + j] ?? 0++ for (let i = before.length - 1; i >= 0; i--) {+ for (let j = after.length - 1; j >= 0; j--) {+ const isMatch = before[i] === after[j]+ lengths[i * columns + j] = isMatch+ ? at(i + 1, j + 1) + 1+ : Math.max(at(i + 1, j), at(i, j + 1))+ }+ }++ const parts: WordPart[] = []++ function emit(text: string, kind: WordPart['kind']) {+ const last = parts.at(-1)++ if (last?.kind === kind) {+ last.text += text++ return+ }++ parts.push({ text, kind })+ }++ let i = 0+ let j = 0++ while (i < before.length || j < after.length) {+ const old = before[i]+ const fresh = after[j]+ const isSame = old !== undefined && old === fresh+ const isRemoved =+ !isSame &&+ old !== undefined &&+ (fresh === undefined || at(i + 1, j) >= at(i, j + 1))++ if (isSame) {+ emit(old, 'same')+ i += 1+ j += 1+ } else if (isRemoved) {+ emit(old, 'removed')+ i += 1+ } else if (fresh !== undefined) {+ emit(fresh, 'added')+ j += 1+ }+ }++ return parts+}diff --git a/mods/diff/hooks/word-diff/diff-parts/index.ts b/mods/diff/hooks/word-diff/diff-parts/index.tsnew file mode 100644index 00000000..8be9cfce--- /dev/null+++ b/mods/diff/hooks/word-diff/diff-parts/index.ts@@ -0,0 +1,3 @@+export * from './diff-parts.js'++export * as default from '.'diff --git a/mods/diff/hooks/word-diff/index.ts b/mods/diff/hooks/word-diff/index.tsnew file mode 100644index 00000000..b6e603f7--- /dev/null+++ b/mods/diff/hooks/word-diff/index.ts@@ -0,0 +1,8 @@+export * from './change-threshold'+export * from './diff-parts'+export * from './max-lcs-cells'+export * from './tokens-of'+export * from './word-diff.js'+export * from './word-part'++export * as default from '.'diff --git a/mods/diff/hooks/word-diff/max-lcs-cells/index.ts b/mods/diff/hooks/word-diff/max-lcs-cells/index.tsnew file mode 100644index 00000000..68ceabec--- /dev/null+++ b/mods/diff/hooks/word-diff/max-lcs-cells/index.ts@@ -0,0 +1,3 @@+export * from './max-lcs-cells.js'++export * as default from '.'diff --git a/mods/diff/hooks/word-diff/max-lcs-cells/max-lcs-cells.ts b/mods/diff/hooks/word-diff/max-lcs-cells/max-lcs-cells.tsnew file mode 100644index 00000000..6dca6759--- /dev/null+++ b/mods/diff/hooks/word-diff/max-lcs-cells/max-lcs-cells.ts@@ -0,0 +1,5 @@+/**+ * The largest token-count product a word diff will fill a table for; two+ * longer lines are shown without word highlights.+ */+export const MAX_LCS_CELLS = 250_000diff --git a/mods/diff/hooks/word-diff/tokens-of/index.ts b/mods/diff/hooks/word-diff/tokens-of/index.tsnew file mode 100644index 00000000..e1b0b5d7--- /dev/null+++ b/mods/diff/hooks/word-diff/tokens-of/index.ts@@ -0,0 +1,3 @@+export * from './tokens-of.js'++export * as default from '.'diff --git a/mods/diff/hooks/word-diff/tokens-of/tokens-of.ts b/mods/diff/hooks/word-diff/tokens-of/tokens-of.tsnew file mode 100644index 00000000..528807f2--- /dev/null+++ b/mods/diff/hooks/word-diff/tokens-of/tokens-of.ts@@ -0,0 +1,9 @@+/**+ * A line as the tokens a word diff compares: runs of word characters, runs+ * of whitespace (kept, as diffWordsWithSpace does), other characters alone.+ *+ * @param text one line without its diff marker+ * @returns the tokens, which join back to `text`+ */+export const tokensOf = (text: string): string[] =>+ text.match(/\w+|\s+|[^\w\s]/gu) ?? []diff --git a/mods/diff/hooks/word-diff/word-diff.ts b/mods/diff/hooks/word-diff/word-diff.tsnew file mode 100644index 00000000..ea7b2ca2--- /dev/null+++ b/mods/diff/hooks/word-diff/word-diff.ts@@ -0,0 +1,30 @@+import { CHANGE_THRESHOLD } from './change-threshold'+import { diffParts } from './diff-parts'+import { tokensOf } from './tokens-of'+import type { WordPart } from './word-part'++/**+ * The word-level diff of a removed line and the added line paired with it,+ * or null when the pair reads as a rewrite or is too long to compare.+ *+ * A rewrite changed more than CHANGE_THRESHOLD of its characters; the+ * caller then draws both lines plain (the engine's fallback diff rule).+ *+ * @param removed the removed line's text, marker dropped+ * @param added the added line's text, marker dropped+ * @returns the parts in order, or null+ */+export function wordDiff(removed: string, added: string): WordPart[] | null {+ const parts = diffParts(tokensOf(removed), tokensOf(added))++ if (!parts) {+ return null+ }++ const total = removed.length + added.length+ const changed = parts+ .filter(part => part.kind !== 'same')+ .reduce((sum, part) => sum + part.text.length, 0)++ return total > 0 && changed / total > CHANGE_THRESHOLD ? null : parts+}diff --git a/mods/diff/hooks/word-diff/word-part/index.ts b/mods/diff/hooks/word-diff/word-part/index.tsnew file mode 100644index 00000000..e7a36dbd--- /dev/null+++ b/mods/diff/hooks/word-diff/word-part/index.ts@@ -0,0 +1,3 @@+export type * from './word-part.js'++export * as default from '.'diff --git a/mods/diff/hooks/word-diff/word-part/word-part.ts b/mods/diff/hooks/word-diff/word-part/word-part.tsnew file mode 100644index 00000000..b7417ae8--- /dev/null+++ b/mods/diff/hooks/word-diff/word-part/word-part.ts@@ -0,0 +1,8 @@+/**+ * One run of a word-level diff between a removed line and the added line+ * that replaced it: text both share, or text on one side only.+ */+export type WordPart = {+ text: string+ kind: 'same' | 'added' | 'removed'+}diff --git a/mods/sec-default/.claude-plugin/plugin.json b/mods/sec-default/.claude-plugin/plugin.jsonnew file mode 100644index 00000000..86aea45a--- /dev/null+++ b/mods/sec-default/.claude-plugin/plugin.json@@ -0,0 +1,8 @@+{+ "name": "sec-default",+ "version": "0.1.0",+ "description": "Security default for organizations: seated outermost, it keeps the organization's classic hooks, prompt content, settings and tool policy out of reach of the plugins a person installs, and adds no policy of its own.",+ "author": {+ "name": "Anthropic"+ }+}diff --git a/mods/sec-default/README.md b/mods/sec-default/README.mdnew file mode 100644index 00000000..7152f7e9--- /dev/null+++ b/mods/sec-default/README.md@@ -0,0 +1,55 @@+# sec-default++The security default for organizations. Function hooks give every plugin a+say on every event, in chain order, and the plugins a person installs sit+in the user tier, beneath the organization's prepend tier and above its+append tier. Some of what an organization sets today (its classic hooks,+its managed CLAUDE.md and rules, its settings, its MCP allowlist) was never+within a person's reach before function hooks; seated outermost, this+plugin keeps exactly those out of the user tier's reach and adds no policy+of its own. Everything else passes through untouched.++It has three moves and nothing else: continue past the user tier+(`next.to(e, "append")`), refuse a user-tier caller by name (`{ deny }`+when `next.origin.tier` is `user`), or pass (`next(e)`). A subject's+provenance is the event's pinned `e.provider`; policy is read through+`$.settings.read({ source: "policy" })`, one read serving a burst; both+fail closed, so an unreadable policy counts as a policy in force.++`hooks/register.ts` is the module; `hooks/policy/` reads the managed+settings it decides by.++## The rows++| event | from the outermost seat |+| --- | --- |+| `classic.*` | Continue past the user tier: the organization's settings hooks see the engine's input and their answer stands. |+| `prompt.section`, `prompt.context`, `skill.prompt`, `attribution.text` | Continue past the user tier: managed CLAUDE.md, rules and policy skills reach the model as written. A person's plugins keep `prompt.submit` and its additive context. |+| `settings.read` | Continue past the user tier: no user hook rewrites what any caller reads as settings, this plugin's own policy reads included. |+| `tool.describe`, `command.describe`, `agent.offer`, `agent.spawn` | When the subject's pinned `e.provider.tier` is `prepend` or `append` (a policy-installed plugin, the managed folder, a policy MCP server), continue past the user tier; a subject provided by `user`, `builtin` or `core` passes. |+| `tool.register` | A caller in `prepend` or `append` continues past the user tier. A `user`-tier caller is refused by name while managed settings hold `allowedMcpServers` (set at all, empty included); otherwise it passes. |+| `tool.list` | The tools of the organization's managed MCP servers are listed as the organization's tiers listed them; every other tool as the user tier left it. With no policy to read, or a refusal from either listing, the organization's listing stands whole. |+| everything else | Passes: `prompt.submit`, `turn.*`, `tool.call`, `tool.check`, `command.run`, `command.register`, `session.*`, `ui.*`, `fs.*`, `http.fetch`, `process.run`, `store.*`, `clock.*`, `model.*`, `mcp.call`, `audio.*`, `agent.list`, `engine.create`. |++## What it hooks++`classic.*`, `prompt.section`, `prompt.context`, `skill.prompt`,+`attribution.text`, `settings.read`, `tool.describe`, `command.describe`,+`agent.offer`, `agent.spawn`, `tool.register`, `tool.list`.++## What it calls on `$`++`settings.read`. It continues to the `append` tier with `next.to`, which+only a plugin in a managed tier may do.++## Where it is seated++The CLI seats it first in the prepend tier wherever hooks modules load on a+machine with managed settings or for a Team or Enterprise organization,+unless managed settings define `prependPlugins`: then that list is the+whole prepend tier, and the organization names `sec-default@builtin` in it+at the position it wants, e.g. `"prependPlugins": ["acme-guard@acme-tools",+"sec-default@builtin"]`, or leaves it out. It is a plugin folder like any+other, but its one move that matters, `next.to`, is refused outside a+managed tier, so loading it with `--plugin-dir` seats a plugin that can+only pass.diff --git a/mods/sec-default/hooks/hooks.json b/mods/sec-default/hooks/hooks.jsonnew file mode 100644index 00000000..0342a30c--- /dev/null+++ b/mods/sec-default/hooks/hooks.json@@ -0,0 +1,4 @@+{+ "description": "Security default: from the outermost seat, continues past the user tier on the organization's classic hooks, prompt content, settings and subjects, refuses a user-tier tool.register under an MCP allowlist, and restores the organization's tools in tool.list",+ "modules": ["./register.ts"]+}diff --git a/mods/sec-default/hooks/index.ts b/mods/sec-default/hooks/index.tsnew file mode 100644index 00000000..f9dd0b52--- /dev/null+++ b/mods/sec-default/hooks/index.ts@@ -0,0 +1,6 @@+export * from './past-users'+export * from './policy'+export * from './register.js'+export * from './tool-register-refusal'++export * as default from '.'diff --git a/mods/sec-default/hooks/past-users/index.ts b/mods/sec-default/hooks/past-users/index.tsnew file mode 100644index 00000000..b6ee2675--- /dev/null+++ b/mods/sec-default/hooks/past-users/index.ts@@ -0,0 +1,5 @@+export * from './past-users.js'+export * from './provided'+export * from './user-reachable-tiers'++export * as default from '.'diff --git a/mods/sec-default/hooks/past-users/past-users.ts b/mods/sec-default/hooks/past-users/past-users.tsnew file mode 100644index 00000000..410a7378--- /dev/null+++ b/mods/sec-default/hooks/past-users/past-users.ts@@ -0,0 +1,23 @@+import type Provided from './provided'+import { USER_REACHABLE_TIERS } from './user-reachable-tiers'++/**+ * What the `tool.describe`, `command.describe`, `agent.offer` and+ * `agent.spawn` hooks do: an organization's subject continues past users.+ *+ * The subject is the organization's unless its pinned `e.provider.tier` is+ * `user`, `builtin` or `core`: a policy-installed plugin (`prepend`,+ * `append`), the managed folder, a policy MCP server, or no provider at all.+ *+ * @param e the event's input with its pinned `provider`+ * @param next the hook's own continuation, handed whole+ * @returns the result from append inward, or from every tier+ */+export function pastUsers<E extends Provided.Provided, R>(+ e: E,+ next: Provided.ProvidedNext<E, R>,+): Promise<R> {+ const isUsers = USER_REACHABLE_TIERS.includes(e.provider?.tier)++ return isUsers ? next(e) : next.to(e, 'append')+}diff --git a/mods/sec-default/hooks/past-users/provided/index.ts b/mods/sec-default/hooks/past-users/provided/index.tsnew file mode 100644index 00000000..afb8511e--- /dev/null+++ b/mods/sec-default/hooks/past-users/provided/index.ts@@ -0,0 +1,4 @@+export type * from './provided.js'+export type * from './provided-next.js'++export * as default from '.'diff --git a/mods/sec-default/hooks/past-users/provided/provided-next.ts b/mods/sec-default/hooks/past-users/provided/provided-next.tsnew file mode 100644index 00000000..c7507ac7--- /dev/null+++ b/mods/sec-default/hooks/past-users/provided/provided-next.ts@@ -0,0 +1,14 @@+import type { TargetTier } from 'claude-code'++/**+ * What the shared hook needs of `next` on those events: the call, and the+ * continuation past the user tier.+ */+export type ProvidedNext<E, R> = {+ (e: E): Promise<R>++ /**+ * Continues the dispatch at `tier`, the links between skipped (Next's).+ */+ readonly to: (e: E, tier: TargetTier) => Promise<R>+}diff --git a/mods/sec-default/hooks/past-users/provided/provided.ts b/mods/sec-default/hooks/past-users/provided/provided.tsnew file mode 100644index 00000000..22cb19d6--- /dev/null+++ b/mods/sec-default/hooks/past-users/provided/provided.ts@@ -0,0 +1,9 @@+/**+ * An event input that carries who provides its subject (`tool.describe`,+ * `command.describe`, `agent.offer`, `agent.spawn`), read for its tier.+ *+ * Typed loosely on purpose: a missing or odd provider fails closed.+ */+export type Provided = {+ readonly provider?: { readonly tier?: unknown } | null+}diff --git a/mods/sec-default/hooks/past-users/user-reachable-tiers/index.ts b/mods/sec-default/hooks/past-users/user-reachable-tiers/index.tsnew file mode 100644index 00000000..4cc4ca68--- /dev/null+++ b/mods/sec-default/hooks/past-users/user-reachable-tiers/index.ts@@ -0,0 +1,3 @@+export * from './user-reachable-tiers.js'++export * as default from '.'diff --git a/mods/sec-default/hooks/past-users/user-reachable-tiers/user-reachable-tiers.ts b/mods/sec-default/hooks/past-users/user-reachable-tiers/user-reachable-tiers.tsnew file mode 100644index 00000000..10c3da2e--- /dev/null+++ b/mods/sec-default/hooks/past-users/user-reachable-tiers/user-reachable-tiers.ts@@ -0,0 +1,11 @@+/**+ * The provider tiers whose subject the user tier may still rewrite: a+ * person's plugin, a bundled one, the engine.+ *+ * Any other provider, or none, is the organization's (fail closed).+ */+export const USER_REACHABLE_TIERS: readonly unknown[] = Object.freeze([+ 'user',+ 'builtin',+ 'core',+])diff --git a/mods/sec-default/hooks/policy/create-policy-memo/create-policy-memo.ts b/mods/sec-default/hooks/policy/create-policy-memo/create-policy-memo.tsnew file mode 100644index 00000000..f5c0529e--- /dev/null+++ b/mods/sec-default/hooks/policy/create-policy-memo/create-policy-memo.ts@@ -0,0 +1,28 @@+import type { Settings } from 'claude-code'++/**+ * A reader of managed policy that serves one read to every caller inside a+ * window after it, rejections included (a failed read still fails closed).+ *+ * @param ttlMs how long a read is served after it starts+ * @param now the clock, for a test+ * @returns `(read) => policy`: `read` runs when nothing fresh is held+ */+export function createPolicyMemo(+ ttlMs: number,+ now: () => number = Date.now,+): (read: () => Promise<Settings>) => Promise<Settings> {+ let heldAt = Number.NEGATIVE_INFINITY+ let held: Promise<Settings> | undefined++ return read => {+ const isStale = held === undefined || now() - heldAt > ttlMs++ if (isStale) {+ heldAt = now()+ held = read()+ }++ return held ?? read()+ }+}diff --git a/mods/sec-default/hooks/policy/create-policy-memo/index.ts b/mods/sec-default/hooks/policy/create-policy-memo/index.tsnew file mode 100644index 00000000..725bbbf5--- /dev/null+++ b/mods/sec-default/hooks/policy/create-policy-memo/index.ts@@ -0,0 +1,3 @@+export * from './create-policy-memo.js'++export * as default from '.'diff --git a/mods/sec-default/hooks/policy/decided-by-policy.ts b/mods/sec-default/hooks/policy/decided-by-policy.tsnew file mode 100644index 00000000..abb01c56--- /dev/null+++ b/mods/sec-default/hooks/policy/decided-by-policy.ts@@ -0,0 +1,15 @@+import type { Settings } from 'claude-code'++/**+ * A yes/no read off managed policy that fails closed: true (protect) when+ * the read rejects or deciding throws.+ *+ * @param policy the memoized policy read (createPolicyMemo over the hook's+ * `$.settings.read({ source: "policy" })`)+ * @param decide the answer once the policy is read+ * @returns what decide answers, else true+ */+export const decidedByPolicy = (+ policy: Promise<Settings>,+ decide: (policy: Settings) => boolean,+): Promise<boolean> => policy.then(decide).catch(() => true)diff --git a/mods/sec-default/hooks/policy/has-mcp-allowlist.ts b/mods/sec-default/hooks/policy/has-mcp-allowlist.tsnew file mode 100644index 00000000..03e7b44a--- /dev/null+++ b/mods/sec-default/hooks/policy/has-mcp-allowlist.ts@@ -0,0 +1,11 @@+import type { Settings } from 'claude-code'++/**+ * Whether managed policy holds an MCP allowlist (allowedMcpServers set at+ * all, empty included): the organization decides which servers add tools.+ *+ * @param policy the managed settings, as `$.settings.read` answers them+ * @returns true when allowedMcpServers is in force+ */+export const hasMcpAllowlist = (policy: Settings) =>+ Array.isArray(policy.allowedMcpServers)diff --git a/mods/sec-default/hooks/policy/index.ts b/mods/sec-default/hooks/policy/index.tsnew file mode 100644index 00000000..f101494d--- /dev/null+++ b/mods/sec-default/hooks/policy/index.ts@@ -0,0 +1,8 @@+export * from './create-policy-memo'+export * from './decided-by-policy.js'+export * from './has-mcp-allowlist.js'+export * from './managed-tools-restored'+export * from './policy-memo-ms.js'+export * from './source.js'++export * as default from '.'diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/index.ts b/mods/sec-default/hooks/policy/managed-tools-restored/index.tsnew file mode 100644index 00000000..3a59b3b0--- /dev/null+++ b/mods/sec-default/hooks/policy/managed-tools-restored/index.ts@@ -0,0 +1,4 @@+export * from './is-org-tool'+export * from './managed-tools-restored.js'++export * as default from '.'diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/index.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/index.tsnew file mode 100644index 00000000..92b1cef6--- /dev/null+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/index.ts@@ -0,0 +1,4 @@+export * from './is-org-tool.js'+export * from './org-server-names'++export * as default from '.'diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-org-tool.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-org-tool.tsnew file mode 100644index 00000000..65e46726--- /dev/null+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/is-org-tool.ts@@ -0,0 +1,14 @@+import type { Settings } from 'claude-code'++import { orgServerNames } from './org-server-names'++/**+ * Whether a tool is one of a managed MCP server's: `mcp__<server>__...` for+ * a server the policy's allowlist names.+ *+ * @param policy the managed settings, as `$.settings.read` answers them+ * @param tool the tool's name as the model calls it+ * @returns true for a managed server's tool+ */+export const isOrgTool = (policy: Settings, tool: string) =>+ orgServerNames(policy).some(server => tool.startsWith(`mcp__${server}__`))diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-server-names/index.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-server-names/index.tsnew file mode 100644index 00000000..fbda5ec4--- /dev/null+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-server-names/index.ts@@ -0,0 +1,3 @@+export * from './org-server-names.js'++export * as default from '.'diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-server-names/org-server-names.ts b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-server-names/org-server-names.tsnew file mode 100644index 00000000..03a7b600--- /dev/null+++ b/mods/sec-default/hooks/policy/managed-tools-restored/is-org-tool/org-server-names/org-server-names.ts@@ -0,0 +1,29 @@+import type { Settings } from 'claude-code'++/**+ * The MCP servers managed policy names, as their tools are prefixed+ * (`mcp__<name>__`): allowlist entries with a serverName, and its own.+ *+ * Its own are the servers it delivers (managedMcpServers keys), which need+ * no allowedMcpServers entry.+ *+ * @param policy the managed settings, as `$.settings.read` answers them+ * @returns one name per named or delivered server; none without either+ */+export function orgServerNames(policy: Settings): string[] {+ const allowlist = policy.allowedMcpServers+ const delivered = policy.managedMcpServers+ const isMap = typeof delivered === 'object' && !Array.isArray(delivered)++ return [+ ...(Array.isArray(allowlist) ? allowlist : []).flatMap((entry: unknown) => {+ const isEntry =+ typeof entry === 'object' && entry !== null && 'serverName' in entry+ const name = isEntry ? entry.serverName : undefined+ const isNamed = typeof name === 'string' && name !== ''++ return isNamed ? [name] : []+ }),+ ...Object.keys(isMap ? (delivered ?? {}) : {}),+ ]+}diff --git a/mods/sec-default/hooks/policy/managed-tools-restored/managed-tools-restored.ts b/mods/sec-default/hooks/policy/managed-tools-restored/managed-tools-restored.tsnew file mode 100644index 00000000..9e838a45--- /dev/null+++ b/mods/sec-default/hooks/policy/managed-tools-restored/managed-tools-restored.ts@@ -0,0 +1,33 @@+import type { Settings, ToolInfo, ValueOrDeny } from 'claude-code'++import { isOrgTool } from './is-org-tool'++/**+ * A `tool.list` answer with the managed servers' tools as the organization's+ * tiers listed them, and every other tool as the user tier left it.+ *+ * A refusal from either listing, or no policy to read, leaves the+ * organization's listing standing whole (fail closed).+ *+ * @param policy the managed settings, or undefined when the read failed+ * @param real the listing past the user tier (`next.to(e, "append")`)+ * @param seen the listing through every tier (`next(e)`)+ * @returns the merged answer+ */+export function managedToolsRestored(+ policy: Settings | undefined,+ real: ValueOrDeny<ToolInfo[]>,+ seen: ValueOrDeny<ToolInfo[]>,+): ValueOrDeny<ToolInfo[]> {+ const isWhole =+ policy === undefined || real.value === undefined || seen.value === undefined++ return isWhole+ ? real+ : {+ value: [+ ...real.value.filter(tool => isOrgTool(policy, tool.name)),+ ...seen.value.filter(tool => !isOrgTool(policy, tool.name)),+ ],+ }+}diff --git a/mods/sec-default/hooks/policy/policy-memo-ms.ts b/mods/sec-default/hooks/policy/policy-memo-ms.tsnew file mode 100644index 00000000..812f07cd--- /dev/null+++ b/mods/sec-default/hooks/policy/policy-memo-ms.ts@@ -0,0 +1,7 @@+/**+ * How long one policy read serves the decisions after it: a burst of+ * `$.tool.list` and `$.tool.register` calls reads once.+ *+ * A settings change waits this long to be seen.+ */+export const POLICY_MEMO_MS = 500diff --git a/mods/sec-default/hooks/policy/source.ts b/mods/sec-default/hooks/policy/source.tsnew file mode 100644index 00000000..3bbe12f1--- /dev/null+++ b/mods/sec-default/hooks/policy/source.ts@@ -0,0 +1,4 @@+/**+ * What `$.settings.read` is asked for: the managed (policy) source alone.+ */+export const SOURCE = { source: 'policy' } as constdiff --git a/mods/sec-default/hooks/register.ts b/mods/sec-default/hooks/register.tsnew file mode 100644index 00000000..06e04174--- /dev/null+++ b/mods/sec-default/hooks/register.ts@@ -0,0 +1,61 @@+import type { On } from 'claude-code'++import { pastUsers } from './past-users'+import Policy from './policy'+import { TOOL_REGISTER_REFUSAL } from './tool-register-refusal'++/**+ * The built-in's hooks, seated outermost: each keeps one control an+ * organization has today out of reach of the plugins a person installs.+ *+ * Three moves: continue past the user tier (`next.to(e, "append")`), refuse+ * a user-tier caller by name, or pass. Provenance is the event's pinned+ * `provider`; policy is `$.settings.read`, memoized per burst; fail closed.+ *+ * @param on the engine's registrar+ */+export function register(on: On) {+ const readPolicy = Policy.createPolicyMemo(Policy.POLICY_MEMO_MS)++ on('classic.*', ($, e, next) => next.to(e, 'append'))++ on('prompt.section', ($, e, next) => next.to(e, 'append'))+ on('prompt.context', ($, e, next) => next.to(e, 'append'))+ on('skill.prompt', ($, e, next) => next.to(e, 'append'))+ on('attribution.text', ($, e, next) => next.to(e, 'append'))++ on('settings.read', ($, e, next) => next.to(e, 'append'))++ on('tool.describe', ($, e, next) => pastUsers(e, next))+ on('command.describe', ($, e, next) => pastUsers(e, next))+ on('agent.offer', ($, e, next) => pastUsers(e, next))+ on('agent.spawn', ($, e, next) => pastUsers(e, next))++ on('tool.register', async ($, e, next) => {+ const isOrgs =+ next.origin.tier === 'prepend' || next.origin.tier === 'append'++ if (isOrgs) {+ return next.to(e, 'append')+ }++ const isRefused =+ next.origin.tier === 'user' &&+ (await Policy.decidedByPolicy(+ readPolicy(() => $.settings.read(Policy.SOURCE)),+ Policy.hasMcpAllowlist,+ ))++ return isRefused ? { deny: TOOL_REGISTER_REFUSAL } : next(e)+ })++ on('tool.list', async ($, e, next) =>+ Policy.managedToolsRestored(+ await readPolicy(() => $.settings.read(Policy.SOURCE)).catch(+ () => undefined,+ ),+ await next.to(e, 'append'),+ await next(e),+ ),+ )+}diff --git a/mods/sec-default/hooks/tool-register-refusal/index.ts b/mods/sec-default/hooks/tool-register-refusal/index.tsnew file mode 100644index 00000000..16d8322b--- /dev/null+++ b/mods/sec-default/hooks/tool-register-refusal/index.ts@@ -0,0 +1,3 @@+export * from './tool-register-refusal.js'++export * as default from '.'diff --git a/mods/sec-default/hooks/tool-register-refusal/tool-register-refusal.ts b/mods/sec-default/hooks/tool-register-refusal/tool-register-refusal.tsnew file mode 100644index 00000000..79b3e259--- /dev/null+++ b/mods/sec-default/hooks/tool-register-refusal/tool-register-refusal.ts@@ -0,0 +1,6 @@+/**+ * Why a plugin outside policy may not add a tool while the organization's+ * MCP allowlist is in force: the setting, then the rule.+ */+export const TOOL_REGISTER_REFUSAL =+ 'allowedMcpServers (managed): plugins outside policy may not add tools'diff --git a/mods/telemetry/.claude-plugin/plugin.json b/mods/telemetry/.claude-plugin/plugin.jsonnew file mode 100644index 00000000..e53b7f60--- /dev/null+++ b/mods/telemetry/.claude-plugin/plugin.json@@ -0,0 +1,8 @@+{+ "name": "telemetry",+ "version": "0.1.0",+ "description": "Plugin analytics: adds $.telemetry in the engine.create fold, so a plugin logs an event or marks a feature's use as one first-party row per call, sent with the session's own credential.",+ "author": {+ "name": "Anthropic"+ }+}diff --git a/mods/telemetry/README.md b/mods/telemetry/README.mdnew file mode 100644index 00000000..98302a64--- /dev/null+++ b/mods/telemetry/README.md@@ -0,0 +1,49 @@+# telemetry++Plugin analytics as a plugin: one `engine.create` step adds `$.telemetry`+to the engine interface every plugin above it is handed, built over the+`$.session` and `$.http` nouns beneath. `$.telemetry.log({ event, props })`+sends one event as one first-party row, `tengu_plugin_<event>`;+`$.telemetry.mark({ feature, kind, reason? })` marks one use of a feature as+the CLI's own feature events do, `tengu_feature_<kind>` with a+`feature_name`. Each call is one POST to the event-logging ingest with the+session's own credential (`$.session.authorize()`, resolved once and held),+one attempt, nothing batched; a session with no first-party credential, or+an ingest that refuses, rejects the caller's promise.++It sends nothing wherever the CLI's own analytics are off: under+`DISABLE_TELEMETRY`, `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC` or+`DO_NOT_TRACK`, on a third-party provider (Bedrock, Vertex, Foundry and+kin, unless the host manages the provider), on a deployment with its own+OAuth URL, and under test; each read through `$.env` once a session. The+row's `user_type` is `ant` when `USER_TYPE` says so, else `external`.++Nothing free-form reaches a row. An event name and every property key is a+snake_case token; a value is a finite number, a boolean, or a Choice (a+string named together with the list it is chosen from); `mark` takes `ok`,+`sad` or `bad`, with a `reason` required on the last two and refused on the+first. An entry that breaks a rule is refused before anything is sent.++`hooks/register.ts` is the module; `hooks/telemetry-types/` is the noun's+type as a caller sees it.++## What it hooks++`engine.create`: `{ ...await next(e), telemetry }`, so the noun is added and+nothing beneath is replaced.++## What it calls on `$`++`session.authorize`, `session.id`, `session.model`, `http.fetch`, `env.get`+(the switches above and `USER_TYPE`, by literal name), each on the+interface the fold handed it.++## Where it runs++This plugin is seated by the CLI itself, on internal builds whose own+analytics are on, and nowhere else: `session.authorize` exists only there,+and the rows it writes join tables only the CLI's own events reach. It is+not meant to be installed or loaded with `--plugin-dir`; the folder has a+manifest so it reads like every other plugin, not so it can stand alone. A+plugin that calls `$.telemetry` where this one is absent finds no such noun+and should treat that as "no analytics here".diff --git a/mods/telemetry/hooks/entries/batch-of.ts b/mods/telemetry/hooks/entries/batch-of.tsnew file mode 100644index 00000000..a8a1c919--- /dev/null+++ b/mods/telemetry/hooks/entries/batch-of.ts@@ -0,0 +1,34 @@+import type { Fields } from './fields'+import type { RowSession } from './row-session'++/**+ * The first-party event batch for one entry, shaped as the CLI's own+ * event exporter shapes its batches.+ *+ * The ClaudeCodeInternalEvent JSON, one event per batch; the properties ride+ * as base64 JSON in `additional_metadata`, the field the exporter uses;+ * `user_type` is what the environment's USER_TYPE says of the build.+ *+ * @param fields the entry as checked+ * @param session the session's id and model, and the build's user type+ * @returns the batch's JSON text, ready to send to the exporter+ */+export function batchOf(fields: Fields, session: RowSession) {+ const metadata = JSON.stringify(fields.props)++ return JSON.stringify({+ events: [+ {+ event_type: 'ClaudeCodeInternalEvent',+ event_data: {+ event_name: fields.name,+ client_timestamp: new Date().toISOString(),+ session_id: session.sessionId,+ model: session.model,+ user_type: session.userType,+ additional_metadata: btoa(metadata),+ },+ },+ ],+ })+}diff --git a/mods/telemetry/hooks/entries/checked-fields.ts b/mods/telemetry/hooks/entries/checked-fields.tsnew file mode 100644index 00000000..de14c7e6--- /dev/null+++ b/mods/telemetry/hooks/entries/checked-fields.ts@@ -0,0 +1,51 @@+import { checkedValue } from './checked-value'+import type { Fields } from './fields'+import { fieldsOf } from './fields-of'+import { isRecord } from './is-record'+import { PROP_LIMIT } from './prop-limit'+import { refusal } from './refusal'+import { TOKEN } from './token'++/**+ * The row's fields from one entry, or a refusal naming the first thing+ * wrong: the entry's shape, the event, then each property in turn.+ *+ * Nothing is sent from an entry refused here: the row reaches the ingest as+ * written, so this check is the gate between the argument and the wire.+ *+ * @param entry the event's name and properties as the caller passed them+ * @returns the entry's checked event name and properties, as `Fields`+ */+export function checkedFields(entry: unknown): Fields {+ if (!isRecord(entry)) {+ throw refusal('takes one entry, { event, props? }')+ }++ const { event, props = {} } = entry++ if (typeof event !== 'string' || !TOKEN.test(event)) {+ throw refusal('takes an event name, a snake_case token')+ }++ if (!isRecord(props)) {+ throw refusal('props: an object of properties by key')+ }++ const entries = Object.entries(props)++ if (entries.length > PROP_LIMIT) {+ throw refusal(`props: at most ${PROP_LIMIT} properties`)+ }++ const checked: Record<string, string | number | boolean> = {}++ for (const [key, value] of entries) {+ if (!TOKEN.test(key)) {+ throw refusal('props: every key is a snake_case token')+ }++ checked[key] = checkedValue(key, value)+ }++ return fieldsOf(event, checked)+}diff --git a/mods/telemetry/hooks/entries/checked-mark.ts b/mods/telemetry/hooks/entries/checked-mark.tsnew file mode 100644index 00000000..d570666f--- /dev/null+++ b/mods/telemetry/hooks/entries/checked-mark.ts@@ -0,0 +1,46 @@+import type { Fields } from './fields'+import { isMarkKind } from './is-mark-kind'+import { isRecord } from './is-record'+import { markFieldsOf } from './mark-fields-of'+import { refusal } from './refusal'+import { TOKEN } from './token'++/**+ * The row's fields from one mark, or a refusal naming the first thing+ * wrong: the entry's shape, the feature, the kind, then the reason.+ *+ * @param entry the feature, kind and reason as the caller passed them+ * @returns the mark's row fields once the entry passes every check+ */+export function checkedMark(entry: unknown): Fields {+ if (!isRecord(entry)) {+ throw refusal('takes one entry, { feature, kind, reason? }', 'mark')+ }++ const { feature, kind, reason } = entry++ if (typeof feature !== 'string' || !TOKEN.test(feature)) {+ throw refusal('takes a feature name, a snake_case token', 'mark')+ }++ if (!isMarkKind(kind)) {+ throw refusal("kind: 'ok', 'sad' or 'bad'", 'mark')+ }++ if (kind === 'ok') {+ if (reason !== undefined) {+ throw refusal('reason: an ok mark carries none', 'mark')+ }++ return markFieldsOf(kind, feature)+ }++ if (typeof reason !== 'string' || !TOKEN.test(reason)) {+ throw refusal(+ `reason: a ${kind} mark names why, a snake_case token`,+ 'mark',+ )+ }++ return markFieldsOf(kind, feature, reason)+}diff --git a/mods/telemetry/hooks/entries/checked-value/checked-value.ts b/mods/telemetry/hooks/entries/checked-value/checked-value.tsnew file mode 100644index 00000000..6b3da4a8--- /dev/null+++ b/mods/telemetry/hooks/entries/checked-value/checked-value.ts@@ -0,0 +1,65 @@+import { CHOICES_LIMIT } from '../choices-limit'+import { isRecord } from '../is-record'+import { refusal } from '../refusal'+import { TOKEN } from '../token'++/**+ * One property's value as it goes into the metadata: a finite number, a+ * boolean, or a Choice's value chosen from its token list.+ *+ * A bare string is refused: free text never reaches the row.+ *+ * @param key the property's key, named in a refusal+ * @param value what the caller passed under it+ * @returns the value as stored: the boolean or finite number unchanged, or the+ * chosen member when value is a Choice+ */+export function checkedValue(+ key: string,+ value: unknown,+): string | number | boolean {+ if (typeof value === 'boolean') {+ return value+ }++ if (typeof value === 'number') {+ if (Number.isFinite(value)) {+ return value+ }++ throw refusal(`props.${key}: a number is finite`)+ }++ if (typeof value === 'string') {+ throw refusal(+ `props.${key}: free text is refused; a string is a Choice, ` ++ `{ value, of: [...] }`,+ )+ }++ if (!isRecord(value) || !Array.isArray(value.of)) {+ throw refusal(+ `props.${key}: a value is a finite number, a boolean, or a Choice, ` ++ `{ value, of: [...] }`,+ )+ }++ const members = value.of+ const chosen = value.value+ const isTokenList =+ members.length > 0 &&+ members.length <= CHOICES_LIMIT &&+ members.every(member => typeof member === 'string' && TOKEN.test(member))++ if (!isTokenList) {+ throw refusal(+ `props.${key}.of: a list of 1 to ${CHOICES_LIMIT} ` + `snake_case tokens`,+ )+ }++ if (typeof chosen !== 'string' || !members.includes(chosen)) {+ throw refusal(`props.${key}.value: one of the members of \`of\``)+ }++ return chosen+}diff --git a/mods/telemetry/hooks/entries/checked-value/index.ts b/mods/telemetry/hooks/entries/checked-value/index.tsnew file mode 100644index 00000000..319b97e7--- /dev/null+++ b/mods/telemetry/hooks/entries/checked-value/index.ts@@ -0,0 +1,3 @@+export * from './checked-value.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/choices-limit/choices-limit.ts b/mods/telemetry/hooks/entries/choices-limit/choices-limit.tsnew file mode 100644index 00000000..d6071e88--- /dev/null+++ b/mods/telemetry/hooks/entries/choices-limit/choices-limit.ts@@ -0,0 +1,4 @@+/**+ * The most members a Choice's list may have.+ */+export const CHOICES_LIMIT = 32diff --git a/mods/telemetry/hooks/entries/choices-limit/index.ts b/mods/telemetry/hooks/entries/choices-limit/index.tsnew file mode 100644index 00000000..f83ac2b4--- /dev/null+++ b/mods/telemetry/hooks/entries/choices-limit/index.ts@@ -0,0 +1,3 @@+export * from './choices-limit.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/event-prefix/event-prefix.ts b/mods/telemetry/hooks/entries/event-prefix/event-prefix.tsnew file mode 100644index 00000000..d01c20ab--- /dev/null+++ b/mods/telemetry/hooks/entries/event-prefix/event-prefix.ts@@ -0,0 +1,5 @@+/**+ * What every event's name starts with: the plugin-event convention. The+ * calling built-in's own name is already in the event it passes.+ */+export const EVENT_PREFIX = 'tengu_plugin_'diff --git a/mods/telemetry/hooks/entries/event-prefix/index.ts b/mods/telemetry/hooks/entries/event-prefix/index.tsnew file mode 100644index 00000000..d1f98baf--- /dev/null+++ b/mods/telemetry/hooks/entries/event-prefix/index.ts@@ -0,0 +1,3 @@+export * from './event-prefix.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/feature-prefix/feature-prefix.ts b/mods/telemetry/hooks/entries/feature-prefix/feature-prefix.tsnew file mode 100644index 00000000..6171f6be--- /dev/null+++ b/mods/telemetry/hooks/entries/feature-prefix/feature-prefix.ts@@ -0,0 +1,7 @@+/**+ * What every feature mark's event name starts with; the kind follows.+ *+ * The CLI's own feature events are named so, which puts a plugin's marks in+ * the same table as every other feature's.+ */+export const FEATURE_PREFIX = 'tengu_feature_'diff --git a/mods/telemetry/hooks/entries/feature-prefix/index.ts b/mods/telemetry/hooks/entries/feature-prefix/index.tsnew file mode 100644index 00000000..57ab8343--- /dev/null+++ b/mods/telemetry/hooks/entries/feature-prefix/index.ts@@ -0,0 +1,3 @@+export * from './feature-prefix.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/fields-of/fields-of.ts b/mods/telemetry/hooks/entries/fields-of/fields-of.tsnew file mode 100644index 00000000..60a76303--- /dev/null+++ b/mods/telemetry/hooks/entries/fields-of/fields-of.ts@@ -0,0 +1,14 @@+import { EVENT_PREFIX } from '../event-prefix'+import type { Fields } from '../fields'++/**+ * One checked entry as its fields, the event under its prefix.+ *+ * @param event the event's name as the caller spelled it+ * @param props the properties as checked+ * @returns the entry's fields, the event name prefixed and the props attached+ */+export const fieldsOf = (event: string, props: Fields['props']): Fields => ({+ name: EVENT_PREFIX + event,+ props,+})diff --git a/mods/telemetry/hooks/entries/fields-of/index.ts b/mods/telemetry/hooks/entries/fields-of/index.tsnew file mode 100644index 00000000..266ba297--- /dev/null+++ b/mods/telemetry/hooks/entries/fields-of/index.ts@@ -0,0 +1,3 @@+export * from './fields-of.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/fields/fields.ts b/mods/telemetry/hooks/entries/fields/fields.tsnew file mode 100644index 00000000..0b3b8192--- /dev/null+++ b/mods/telemetry/hooks/entries/fields/fields.ts@@ -0,0 +1,8 @@+/**+ * One entry after the check: the event's full name and the properties as+ * they go into the row's metadata.+ */+export type Fields = {+ name: string+ props: Readonly<Record<string, string | number | boolean>>+}diff --git a/mods/telemetry/hooks/entries/fields/index.ts b/mods/telemetry/hooks/entries/fields/index.tsnew file mode 100644index 00000000..f650daef--- /dev/null+++ b/mods/telemetry/hooks/entries/fields/index.ts@@ -0,0 +1,3 @@+export type * from './fields.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/index.ts b/mods/telemetry/hooks/entries/index.tsnew file mode 100644index 00000000..e7348482--- /dev/null+++ b/mods/telemetry/hooks/entries/index.ts@@ -0,0 +1,20 @@+export * from './batch-of.js'+export * from './checked-fields.js'+export * from './checked-mark.js'+export * from './checked-value'+export * from './choices-limit'+export * from './event-prefix'+export * from './feature-prefix'+export * from './fields'+export * from './fields-of'+export * from './ingest-url.js'+export * from './is-mark-kind'+export * from './is-record'+export * from './mark-fields-of'+export * from './mark-kinds'+export * from './prop-limit'+export * from './refusal'+export * from './row-session'+export * from './token'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/ingest-url.ts b/mods/telemetry/hooks/entries/ingest-url.tsnew file mode 100644index 00000000..718da90a--- /dev/null+++ b/mods/telemetry/hooks/entries/ingest-url.ts@@ -0,0 +1,9 @@+/**+ * The first-party event-logging ingest: the same address the CLI's own+ * event exporter posts its batches to.+ *+ * No `$` reads the session's API base, so the production host is spelled+ * here; a session on another base logs nothing, which the authorize gate+ * already makes so.+ */+export const INGEST_URL = 'https://api.anthropic.com/api/event_logging/v2/batch'diff --git a/mods/telemetry/hooks/entries/is-mark-kind/index.ts b/mods/telemetry/hooks/entries/is-mark-kind/index.tsnew file mode 100644index 00000000..f096be79--- /dev/null+++ b/mods/telemetry/hooks/entries/is-mark-kind/index.ts@@ -0,0 +1,3 @@+export * from './is-mark-kind.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/is-mark-kind/is-mark-kind.ts b/mods/telemetry/hooks/entries/is-mark-kind/is-mark-kind.tsnew file mode 100644index 00000000..75b971eb--- /dev/null+++ b/mods/telemetry/hooks/entries/is-mark-kind/is-mark-kind.ts@@ -0,0 +1,11 @@+import type TelemetryTypes from '../../telemetry-types'+import { MARK_KINDS } from '../mark-kinds'++/**+ * Whether the value names one of the three mark kinds.+ *+ * @param value what the caller passed as `kind`+ * @returns whether value names one of the three mark kinds+ */+export const isMarkKind = (value: unknown): value is TelemetryTypes.MarkKind =>+ MARK_KINDS.some(kind => kind === value)diff --git a/mods/telemetry/hooks/entries/is-record/index.ts b/mods/telemetry/hooks/entries/is-record/index.tsnew file mode 100644index 00000000..b3255fa1--- /dev/null+++ b/mods/telemetry/hooks/entries/is-record/index.ts@@ -0,0 +1,3 @@+export * from './is-record.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/is-record/is-record.ts b/mods/telemetry/hooks/entries/is-record/is-record.tsnew file mode 100644index 00000000..db0f7cdb--- /dev/null+++ b/mods/telemetry/hooks/entries/is-record/is-record.ts@@ -0,0 +1,8 @@+/**+ * Whether the value is a plain object (not null, not an array).+ *+ * @param value what the caller passed+ * @returns whether the value is a plain object, not null and not an array+ */+export const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null && !Array.isArray(value)diff --git a/mods/telemetry/hooks/entries/mark-fields-of/index.ts b/mods/telemetry/hooks/entries/mark-fields-of/index.tsnew file mode 100644index 00000000..4b210cd4--- /dev/null+++ b/mods/telemetry/hooks/entries/mark-fields-of/index.ts@@ -0,0 +1,3 @@+export * from './mark-fields-of.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/mark-fields-of/mark-fields-of.ts b/mods/telemetry/hooks/entries/mark-fields-of/mark-fields-of.tsnew file mode 100644index 00000000..81d38919--- /dev/null+++ b/mods/telemetry/hooks/entries/mark-fields-of/mark-fields-of.ts@@ -0,0 +1,24 @@+import type TelemetryTypes from '../../telemetry-types'+import { FEATURE_PREFIX } from '../feature-prefix'+import type { Fields } from '../fields'++/**+ * One checked mark as its fields: the CLI's own feature event,+ * `tengu_feature_<kind>` with `feature_name`, and `error_code` when given.+ *+ * @param kind how the feature went+ * @param feature the feature marked+ * @param reason why, on a sad or bad mark; absent on ok+ * @returns the event's name and props, ready to log+ */+export const markFieldsOf = (+ kind: TelemetryTypes.MarkKind,+ feature: string,+ reason?: string,+): Fields => ({+ name: FEATURE_PREFIX + kind,+ props:+ reason === undefined+ ? { feature_name: feature }+ : { feature_name: feature, error_code: reason },+})diff --git a/mods/telemetry/hooks/entries/mark-kinds/index.ts b/mods/telemetry/hooks/entries/mark-kinds/index.tsnew file mode 100644index 00000000..81be6cf7--- /dev/null+++ b/mods/telemetry/hooks/entries/mark-kinds/index.ts@@ -0,0 +1,3 @@+export * from './mark-kinds.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/mark-kinds/mark-kinds.ts b/mods/telemetry/hooks/entries/mark-kinds/mark-kinds.tsnew file mode 100644index 00000000..9c33eb3e--- /dev/null+++ b/mods/telemetry/hooks/entries/mark-kinds/mark-kinds.ts@@ -0,0 +1,10 @@+import type TelemetryTypes from '../../telemetry-types'++/**+ * The three kinds a mark may be, in the order the feature events name them.+ */+export const MARK_KINDS: readonly TelemetryTypes.MarkKind[] = [+ 'ok',+ 'sad',+ 'bad',+]diff --git a/mods/telemetry/hooks/entries/prop-limit/index.ts b/mods/telemetry/hooks/entries/prop-limit/index.tsnew file mode 100644index 00000000..7b49b376--- /dev/null+++ b/mods/telemetry/hooks/entries/prop-limit/index.ts@@ -0,0 +1,3 @@+export * from './prop-limit.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/prop-limit/prop-limit.ts b/mods/telemetry/hooks/entries/prop-limit/prop-limit.tsnew file mode 100644index 00000000..b00144da--- /dev/null+++ b/mods/telemetry/hooks/entries/prop-limit/prop-limit.ts@@ -0,0 +1,4 @@+/**+ * The most properties one entry may carry.+ */+export const PROP_LIMIT = 16diff --git a/mods/telemetry/hooks/entries/refusal/index.ts b/mods/telemetry/hooks/entries/refusal/index.tsnew file mode 100644index 00000000..a3405db2--- /dev/null+++ b/mods/telemetry/hooks/entries/refusal/index.ts@@ -0,0 +1,3 @@+export * from './refusal.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/refusal/refusal.ts b/mods/telemetry/hooks/entries/refusal/refusal.tsnew file mode 100644index 00000000..59c9888f--- /dev/null+++ b/mods/telemetry/hooks/entries/refusal/refusal.ts@@ -0,0 +1,17 @@+import type TelemetryTypes from '../../telemetry-types'++/**+ * The error a refused entry rejects with, naming the method and what was wrong.+ *+ * The text carries a key that passed TOKEN or a status code, nothing the caller+ * wrote as free text.+ *+ * @param what the refusal, as the caller reads it+ * @param method the method refusing+ * @returns the error to reject the call with, naming the method and what was+ * wrong+ */+export const refusal = (+ what: string,+ method: TelemetryTypes.Method = 'log',+): Error => new Error(`$.telemetry.${method}: ${what}`)diff --git a/mods/telemetry/hooks/entries/row-session/index.ts b/mods/telemetry/hooks/entries/row-session/index.tsnew file mode 100644index 00000000..32704bf4--- /dev/null+++ b/mods/telemetry/hooks/entries/row-session/index.ts@@ -0,0 +1,3 @@+export type * from './row-session.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/row-session/row-session.ts b/mods/telemetry/hooks/entries/row-session/row-session.tsnew file mode 100644index 00000000..f7065c28--- /dev/null+++ b/mods/telemetry/hooks/entries/row-session/row-session.ts@@ -0,0 +1,9 @@+/**+ * What one row says of the session that sent it: its id, its model, and+ * the build's user type (`ant` or `external`) as the environment names it.+ */+export type RowSession = {+ sessionId: string+ model: string+ userType: string+}diff --git a/mods/telemetry/hooks/entries/token/index.ts b/mods/telemetry/hooks/entries/token/index.tsnew file mode 100644index 00000000..79e7863d--- /dev/null+++ b/mods/telemetry/hooks/entries/token/index.ts@@ -0,0 +1,3 @@+export * from './token.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/entries/token/token.ts b/mods/telemetry/hooks/entries/token/token.tsnew file mode 100644index 00000000..a37c3ea3--- /dev/null+++ b/mods/telemetry/hooks/entries/token/token.ts@@ -0,0 +1,5 @@+/**+ * The shape of an event name, a property key and a Choice member: a+ * snake_case token of at most 64 characters, starting with a letter.+ */+export const TOKEN = /^[a-z][a-z0-9_]{0,63}$/diff --git a/mods/telemetry/hooks/environment/environment.ts b/mods/telemetry/hooks/environment/environment.tsnew file mode 100644index 00000000..a5a858d0--- /dev/null+++ b/mods/telemetry/hooks/environment/environment.ts@@ -0,0 +1,22 @@+/**+ * What the plugin reads of the environment, once a session: the+ * build's user type and every switch that turns the CLI's analytics off.+ *+ * Each field is the variable's value as `$.env.get` answers it, undefined+ * when unset; analytics-off/ decides what they mean together.+ */+export type Environment = {+ readonly userType: string | undefined+ readonly nodeEnv: string | undefined+ readonly disableTelemetry: string | undefined+ readonly disableNonessentialTraffic: string | undefined+ readonly doNotTrack: string | undefined+ readonly customOauthUrl: string | undefined+ readonly providerManagedByHost: string | undefined+ readonly useBedrock: string | undefined+ readonly useVertex: string | undefined+ readonly useFoundry: string | undefined+ readonly useAnthropicAws: string | undefined+ readonly useAnthropicGoogleCloud: string | undefined+ readonly useMantle: string | undefined+}diff --git a/mods/telemetry/hooks/environment/index.ts b/mods/telemetry/hooks/environment/index.tsnew file mode 100644index 00000000..e9d00dca--- /dev/null+++ b/mods/telemetry/hooks/environment/index.ts@@ -0,0 +1,3 @@+export type * from './environment.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/hooks.json b/mods/telemetry/hooks/hooks.jsonnew file mode 100644index 00000000..dd92650e--- /dev/null+++ b/mods/telemetry/hooks/hooks.json@@ -0,0 +1,4 @@+{+ "description": "Plugin analytics: an engine.create step adds $.telemetry (log, mark) over $.session, $.http and $.env beneath; sends nothing wherever the CLI's analytics are off",+ "modules": ["./register.ts"]+}diff --git a/mods/telemetry/hooks/index.ts b/mods/telemetry/hooks/index.tsnew file mode 100644index 00000000..23563c78--- /dev/null+++ b/mods/telemetry/hooks/index.ts@@ -0,0 +1,9 @@+export * from './entries'+export * from './environment'+export * from './is-analytics-off'+export * from './register.js'+export * from './telemetry-deps'+export * from './telemetry-of'+export * from './telemetry-types'++export * as default from '.'diff --git a/mods/telemetry/hooks/is-analytics-off/index.ts b/mods/telemetry/hooks/is-analytics-off/index.tsnew file mode 100644index 00000000..29119fff--- /dev/null+++ b/mods/telemetry/hooks/is-analytics-off/index.ts@@ -0,0 +1,5 @@+export * from './is-analytics-off.js'+export * from './is-env-set'+export * from './is-env-truthy'++export * as default from '.'diff --git a/mods/telemetry/hooks/is-analytics-off/is-analytics-off.ts b/mods/telemetry/hooks/is-analytics-off/is-analytics-off.tsnew file mode 100644index 00000000..26190548--- /dev/null+++ b/mods/telemetry/hooks/is-analytics-off/is-analytics-off.ts@@ -0,0 +1,35 @@+import type { Environment } from '../environment'+import { isEnvSet } from './is-env-set'+import { isEnvTruthy } from './is-env-truthy'++/**+ * Whether the CLI's own analytics would be off here, read off the+ * environment alone: then the plugin sends nothing either.+ *+ * Off under test, when DISABLE_TELEMETRY or the nonessential-traffic switch+ * is set at all or DO_NOT_TRACK is on, on a third-party provider the host+ * does not manage, and on a deployment with its own OAuth URL.+ *+ * @param environment the variables as read once for the session+ * @returns true when no row may be sent+ */+export function isAnalyticsOff(environment: Environment) {+ const isTest = environment.nodeEnv === 'test'+ const isPrivate =+ isEnvSet(environment.disableTelemetry) ||+ isEnvSet(environment.disableNonessentialTraffic) ||+ isEnvTruthy(environment.doNotTrack)+ const isThirdParty =+ !isEnvTruthy(environment.providerManagedByHost) &&+ [+ environment.useBedrock,+ environment.useVertex,+ environment.useFoundry,+ environment.useAnthropicAws,+ environment.useAnthropicGoogleCloud,+ environment.useMantle,+ ].some(isEnvTruthy)+ const isCustomDeployment = isEnvSet(environment.customOauthUrl?.trim())++ return isTest || isPrivate || isThirdParty || isCustomDeployment+}diff --git a/mods/telemetry/hooks/is-analytics-off/is-env-set/index.ts b/mods/telemetry/hooks/is-analytics-off/is-env-set/index.tsnew file mode 100644index 00000000..863fe804--- /dev/null+++ b/mods/telemetry/hooks/is-analytics-off/is-env-set/index.ts@@ -0,0 +1,3 @@+export * from './is-env-set.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/is-analytics-off/is-env-set/is-env-set.ts b/mods/telemetry/hooks/is-analytics-off/is-env-set/is-env-set.tsnew file mode 100644index 00000000..4cce201c--- /dev/null+++ b/mods/telemetry/hooks/is-analytics-off/is-env-set/is-env-set.ts@@ -0,0 +1,9 @@+/**+ * Whether a variable is set to anything at all, as the CLI's privacy level+ * reads DISABLE_TELEMETRY: any non-empty value counts, `0` included.+ *+ * @param value the variable as the environment holds it+ * @returns true for a non-empty value+ */+export const isEnvSet = (value: string | undefined) =>+ value !== undefined && value !== ''diff --git a/mods/telemetry/hooks/is-analytics-off/is-env-truthy/index.ts b/mods/telemetry/hooks/is-analytics-off/is-env-truthy/index.tsnew file mode 100644index 00000000..e96e568e--- /dev/null+++ b/mods/telemetry/hooks/is-analytics-off/is-env-truthy/index.ts@@ -0,0 +1,3 @@+export * from './is-env-truthy.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/is-analytics-off/is-env-truthy/is-env-truthy.ts b/mods/telemetry/hooks/is-analytics-off/is-env-truthy/is-env-truthy.tsnew file mode 100644index 00000000..540f7ab0--- /dev/null+++ b/mods/telemetry/hooks/is-analytics-off/is-env-truthy/is-env-truthy.ts@@ -0,0 +1,9 @@+/**+ * Whether a variable reads as on, as the CLI reads its boolean switches:+ * `1`, `true`, `yes` or `on`, in any case, spaces around it ignored.+ *+ * @param value the variable as the environment holds it+ * @returns true for one of the four spellings+ */+export const isEnvTruthy = (value: string | undefined) =>+ ['1', 'true', 'yes', 'on'].includes((value ?? '').trim().toLowerCase())diff --git a/mods/telemetry/hooks/register.ts b/mods/telemetry/hooks/register.tsnew file mode 100644index 00000000..c7e257bd--- /dev/null+++ b/mods/telemetry/hooks/register.ts@@ -0,0 +1,51 @@+import type { On } from 'claude-code'++import { telemetryOf } from './telemetry-of'++/**+ * Registers the plugin's one hook: its engine.create step adds+ * `$.telemetry` over the nouns beneath, the plugin's own `$` as core built.+ *+ * `log` runs after the fold, reaching `$.session` and `$.http` through the+ * nouns beneath; each is one call on them.+ *+ * @param on the engine's registrar+ */+export function register(on: On) {+ on('engine.create', async ($, e, next) => {+ const beneath = await next(e)++ return {+ ...beneath,+ telemetry: telemetryOf({+ authorize: () => beneath.session.authorize(),+ id: () => beneath.session.id(),+ model: () => beneath.session.model(),+ environment: async () => ({+ userType: await beneath.env.get('USER_TYPE'),+ nodeEnv: await beneath.env.get('NODE_ENV'),+ disableTelemetry: await beneath.env.get('DISABLE_TELEMETRY'),+ disableNonessentialTraffic: await beneath.env.get(+ 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC',+ ),+ doNotTrack: await beneath.env.get('DO_NOT_TRACK'),+ customOauthUrl: await beneath.env.get('CLAUDE_CODE_CUSTOM_OAUTH_URL'),+ providerManagedByHost: await beneath.env.get(+ 'CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST',+ ),+ useBedrock: await beneath.env.get('CLAUDE_CODE_USE_BEDROCK'),+ useVertex: await beneath.env.get('CLAUDE_CODE_USE_VERTEX'),+ useFoundry: await beneath.env.get('CLAUDE_CODE_USE_FOUNDRY'),+ useAnthropicAws: await beneath.env.get(+ 'CLAUDE_CODE_USE_ANTHROPIC_AWS',+ ),+ useAnthropicGoogleCloud: await beneath.env.get(+ 'CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD',+ ),+ useMantle: await beneath.env.get('CLAUDE_CODE_USE_MANTLE'),+ }),+ fetch: (url, init) => beneath.http.fetch(url, init),+ }),+ }+ })+}diff --git a/mods/telemetry/hooks/telemetry-deps/index.ts b/mods/telemetry/hooks/telemetry-deps/index.tsnew file mode 100644index 00000000..ba5ab0c8--- /dev/null+++ b/mods/telemetry/hooks/telemetry-deps/index.ts@@ -0,0 +1,3 @@+export type * from './telemetry-deps.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/telemetry-deps/telemetry-deps.ts b/mods/telemetry/hooks/telemetry-deps/telemetry-deps.tsnew file mode 100644index 00000000..ffb09c18--- /dev/null+++ b/mods/telemetry/hooks/telemetry-deps/telemetry-deps.ts@@ -0,0 +1,35 @@+import type { HttpInit, HttpResponse, SessionAuthorization } from 'claude-code'++import type { Environment } from '../environment'++/**+ * What `telemetryOf` reaches on the nouns beneath: the session's authorize+ * and reads, and one fetch. Each is a call on the plugin's own `$`.+ */+export type TelemetryDeps = {+ /**+ * Resolves the session's held credential, or null.+ */+ authorize: () => Promise<SessionAuthorization>++ /**+ * The session's id, for the row.+ */+ id: () => Promise<string>++ /**+ * The session's model, for the row.+ */+ model: () => Promise<string>++ /**+ * Reads what the row and the off switch need of the environment:+ * the build's user type, and every variable that turns analytics off.+ */+ environment: () => Promise<Environment>++ /**+ * Posts the batch to the ingest with the credential handle.+ */+ fetch: (url: string, init: HttpInit) => Promise<HttpResponse>+}diff --git a/mods/telemetry/hooks/telemetry-of/index.ts b/mods/telemetry/hooks/telemetry-of/index.tsnew file mode 100644index 00000000..0facc6fa--- /dev/null+++ b/mods/telemetry/hooks/telemetry-of/index.ts@@ -0,0 +1,3 @@+export * from './telemetry-of.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/telemetry-of/telemetry-of.ts b/mods/telemetry/hooks/telemetry-of/telemetry-of.tsnew file mode 100644index 00000000..fb68eba7--- /dev/null+++ b/mods/telemetry/hooks/telemetry-of/telemetry-of.ts@@ -0,0 +1,80 @@+import Entries from '../entries'+import { isAnalyticsOff } from '../is-analytics-off'+import type { TelemetryDeps } from '../telemetry-deps'+import type TelemetryTypes from '../telemetry-types'++/**+ * Builds `$.telemetry`: `log` and `mark` check the entry, authorize once, build+ * the first-party row and POST it to the ingest.+ *+ * One POST per call, none batched, one attempt; a session with no credential to+ * authorize, or an ingest that refuses, rejects the caller's promise. A failed+ * authorize or environment read is not memoized, so a later call retries it.+ *+ * @param deps the calls on the nouns beneath+ * @returns the `$.telemetry` interface, `log` and `mark`, each authorizing once+ * (memoized) before it posts+ */+export function telemetryOf(deps: TelemetryDeps): TelemetryTypes.Telemetry {+ let held: ReturnType<TelemetryDeps['authorize']> | undefined+ let read: ReturnType<TelemetryDeps['environment']> | undefined++ async function post(+ fields: Entries.Fields,+ method: TelemetryTypes.Method,+ ): Promise<void> {+ read ??= deps.environment().catch((error: unknown) => {+ read = undefined++ throw error+ })+ const environment = await read++ if (isAnalyticsOff(environment)) {+ return+ }++ if (!held) {+ held = deps.authorize().catch((error: unknown) => {+ held = undefined++ throw error+ })+ }++ const auth = await held++ if (!auth) {+ held = undefined++ throw Entries.refusal(+ 'this session has no first-party credential to authorize',+ method,+ )+ }++ const body = Entries.batchOf(fields, {+ sessionId: await deps.id(),+ model: await deps.model(),+ userType: environment.userType === 'ant' ? 'ant' : 'external',+ })+ const response = await deps.fetch(Entries.INGEST_URL, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'x-service-name': 'claude-code',+ },+ auth: auth.handle,+ body,+ })++ if (!response.ok) {+ throw Entries.refusal(`the ingest answered ${response.status}`, method)+ }+ }++ return {+ log: async entry => post(Entries.checkedFields(entry), 'log'),+ mark: async entry => post(Entries.checkedMark(entry), 'mark'),+ }+}diff --git a/mods/telemetry/hooks/telemetry-types/choice/choice.ts b/mods/telemetry/hooks/telemetry-types/choice/choice.tsnew file mode 100644index 00000000..42ebec36--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/choice/choice.ts@@ -0,0 +1,8 @@+/**+ * A string property: the value and the list it is chosen from, declared+ * beside it, so no free text reaches the row.+ *+ * Every member of `of` is a snake_case token, at most CHOICES_LIMIT of+ * them; `value` is one of them.+ */+export type Choice = { value: string; of: readonly string[] }diff --git a/mods/telemetry/hooks/telemetry-types/choice/index.ts b/mods/telemetry/hooks/telemetry-types/choice/index.tsnew file mode 100644index 00000000..4d2a25a9--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/choice/index.ts@@ -0,0 +1,3 @@+export type * from './choice.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/telemetry-types/index.ts b/mods/telemetry/hooks/telemetry-types/index.tsnew file mode 100644index 00000000..b234be35--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/index.ts@@ -0,0 +1,9 @@+export * from './choice'+export * from './log-entry'+export * from './mark-entry'+export * from './mark-kind'+export type * from './method.js'+export * from './prop'+export type * from './telemetry.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/telemetry-types/log-entry/index.ts b/mods/telemetry/hooks/telemetry-types/log-entry/index.tsnew file mode 100644index 00000000..7a12ce6b--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/log-entry/index.ts@@ -0,0 +1,3 @@+export type * from './log-entry.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/telemetry-types/log-entry/log-entry.ts b/mods/telemetry/hooks/telemetry-types/log-entry/log-entry.tsnew file mode 100644index 00000000..63836b0f--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/log-entry/log-entry.ts@@ -0,0 +1,10 @@+import type { Prop } from '../prop'++/**+ * What `$.telemetry.log` takes: the event's name after the prefix, and its+ * properties by snake_case key.+ */+export type LogEntry = {+ event: string+ props?: Readonly<Record<string, Prop>>+}diff --git a/mods/telemetry/hooks/telemetry-types/mark-entry/index.ts b/mods/telemetry/hooks/telemetry-types/mark-entry/index.tsnew file mode 100644index 00000000..795de000--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/mark-entry/index.ts@@ -0,0 +1,3 @@+export type * from './mark-entry.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/telemetry-types/mark-entry/mark-entry.ts b/mods/telemetry/hooks/telemetry-types/mark-entry/mark-entry.tsnew file mode 100644index 00000000..101e12b1--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/mark-entry/mark-entry.ts@@ -0,0 +1,11 @@+import type { MarkKind } from '../mark-kind'++/**+ * What `$.telemetry.mark` takes: the feature, how it went, and why when not+ * ok.+ */+export type MarkEntry = {+ feature: string+ kind: MarkKind+ reason?: string+}diff --git a/mods/telemetry/hooks/telemetry-types/mark-kind/index.ts b/mods/telemetry/hooks/telemetry-types/mark-kind/index.tsnew file mode 100644index 00000000..6a653767--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/mark-kind/index.ts@@ -0,0 +1,3 @@+export type * from './mark-kind.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/telemetry-types/mark-kind/mark-kind.ts b/mods/telemetry/hooks/telemetry-types/mark-kind/mark-kind.tsnew file mode 100644index 00000000..8b71ffae--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/mark-kind/mark-kind.ts@@ -0,0 +1,8 @@+/**+ * How a feature went, as the CLI's own feature events count it.+ *+ * `ok`: used, the person got what they asked. `sad`: degraded, a fallback+ * or a partial, the person still got something. `bad`: failed, the person+ * got nothing.+ */+export type MarkKind = 'ok' | 'sad' | 'bad'diff --git a/mods/telemetry/hooks/telemetry-types/method.ts b/mods/telemetry/hooks/telemetry-types/method.tsnew file mode 100644index 00000000..a9c2b77d--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/method.ts@@ -0,0 +1,4 @@+/**+ * The two methods of `$.telemetry`, named in a refusal.+ */+export type Method = 'log' | 'mark'diff --git a/mods/telemetry/hooks/telemetry-types/prop/index.ts b/mods/telemetry/hooks/telemetry-types/prop/index.tsnew file mode 100644index 00000000..bdcedd03--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/prop/index.ts@@ -0,0 +1,3 @@+export type * from './prop.js'++export * as default from '.'diff --git a/mods/telemetry/hooks/telemetry-types/prop/prop.ts b/mods/telemetry/hooks/telemetry-types/prop/prop.tsnew file mode 100644index 00000000..acc0e237--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/prop/prop.ts@@ -0,0 +1,7 @@+import type { Choice } from '../choice'++/**+ * A property's value: a finite number, a boolean, or a Choice; never free+ * text.+ */+export type Prop = number | boolean | Choicediff --git a/mods/telemetry/hooks/telemetry-types/telemetry.ts b/mods/telemetry/hooks/telemetry-types/telemetry.tsnew file mode 100644index 00000000..f04920d0--- /dev/null+++ b/mods/telemetry/hooks/telemetry-types/telemetry.ts@@ -0,0 +1,51 @@+import type { LogEntry } from './log-entry'+import type { MarkEntry } from './mark-entry'++/**+ * A plugin's analytics, sent one event at a time through `$.telemetry`.+ *+ * Internal builds alone: the telemetry built-in adds the noun in the+ * engine.create fold, so a plugin on an external build, or one where the+ * built-in is off, finds no `$.telemetry`.+ */+export type Telemetry = {+ /**+ * Sends one event, `tengu_plugin_<event>`, as one first-party row;+ * resolves once the ingest accepted it.+ *+ * The noun cannot see its caller, so the calling built-in names itself in+ * `event` and this adds the prefix. A value is a finite number, a boolean+ * or a Choice; free text is refused. One input, as every op on `$` takes.+ *+ * @param entry the event's name after the prefix, a snake_case token, and+ * its properties by snake_case key+ * @example+ * await $.telemetry.log({+ * event: "suggest_learning_survey_answered",+ * props: {+ * answer: 2,+ * page: { value: "ready", of: ["ready", "later"] },+ * },+ * })+ */+ log: (entry: LogEntry) => Promise<void>++ /**+ * Marks one use of a feature as the CLI's own feature events do, one+ * `tengu_feature_<kind>` row; resolves once the ingest accepted it.+ *+ * The row carries `feature_name`, and `error_code` on a sad or bad one; it+ * joins the product-wide feature surface (queried by `feature_name`), so+ * no plugin prefix. `reason` is required on sad and bad, refused on ok.+ *+ * @param entry the feature, how it went, and why when not ok+ * @example+ * await $.telemetry.mark({ feature: "learn_page", kind: "ok" })+ * await $.telemetry.mark({+ * feature: "learn_page",+ * kind: "sad",+ * reason: "blocked",+ * })+ */+ mark: (entry: MarkEntry) => Promise<void>+}