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: each test file is named for the hooks/ subject it covers and holds one describe, shared inputs under tests/fixtures; memoryClock answers $.clock beneath the mod, and the diff pane's close button is pressed through $.ui.press

poteat59bb8853c1bd
diff --git a/mods/README.md b/mods/README.md
index bdee1f5c..43484208 100644
--- a/mods/README.md
+++ b/mods/README.md
@@ -30,33 +30,51 @@ the test registers with `on` sit beneath the mod, where the rest of the world
would be, and nothing is beneath them: a call they leave unanswered throws,
naming its event.
+A test file is named for what it covers under `hooks/` (`register.test.ts`
+beside `hooks/register.ts`, `git.test.ts` beside `hooks/git/`), and holds its
+imports, the tier the mod loads in, and one `describe` titled with that name;
+what several tests share sits under `tests/fixtures/`, one export a file.
+
```ts
-import { expect, test, tier } from 'claude-code/testing'
+import { describe, expect, memoryClock, test, tier } from 'claude-code/testing'
tier('builtin')
-test('outside a git repository /diff says so and opens nothing', async ($, on) => {
- const opened: string[] = []
- on('session.start', ($, e) => ({ cwd: e.cwd }))
- on('command.register', ($, e) => ({ value: { command: e.name } }))
- on('process.run', () => ({ value: { exitCode: 128, stdout: '', stderr: '' } }))
- on('ui.open', ($, e, next) => {
- opened.push(e.id)
- return next(e)
- })
+describe('register', () => {
+ test('outside a git repository /diff says so, opens nothing', async ($, on) => {
+ const opened: string[] = []
+ memoryClock(on)
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('command.register', ($, e) => ({ value: { command: e.name } }))
+ on('process.run', () => ({
+ value: { exitCode: 128, stdout: '', stderr: 'fatal: not a git repository' },
+ }))
+ on('ui.open', ($, e, next) => {
+ opened.push(e.id)
+ return next(e)
+ })
- await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })
- const { text } = await $.command.run({
- command: 'diff',
- args: '',
- origin: { kind: 'composer' },
- })
+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })
+ const { text } = await $.command.run({
+ command: 'diff',
+ args: '',
+ origin: { kind: 'composer' },
+ })
- expect(text).toContain("isn't in a git repository")
- expect(opened).toEqual([])
+ expect(text).toContain("isn't in a git repository")
+ expect(opened).toEqual([])
+ })
})
```
+The kit's helpers are plain functions over `on`, each answering one noun
+beneath the mod where the test calls it: `memoryEnv(on, variables)` for
+`$.env`, `memoryStore(on, entries)` for `$.store`, and `memoryClock(on)` for
+`$.clock`, whose `advance(ms)` resolves every wait the mod asked for
+(`$.clock.sleep`, `after`, `every`) as the clock crosses it. `textOf(tree)`
+reads a rendered tree's text, and `$.ui.press({ plugin, key })` presses a
+`Button` the test rendered, as a click in the terminal does.
+
`tsc -p mods/tsconfig.json` typechecks every mod's hooks and tests against
`types/`.
diff --git a/mods/diff/tests/boot-probe.test.ts b/mods/diff/tests/boot-probe.test.ts
deleted file mode 100644
index 3ddf822f..00000000
--- a/mods/diff/tests/boot-probe.test.ts
+++ /dev/null
@@ -1,41 +0,0 @@
-import { clock, describe, expect, test, tier } from 'claude-code/testing'
-
-import Limits from '../hooks/limits'
-import Fixtures from './fixtures'
-
-const GIT_HUNG = `git aborted: still running after ${Limits.GIT_TIMEOUT_MS}ms`
-
-tier('builtin')
-
-describe('boot-probe', () => {
- test('/diff at boot joins the boot probe, then asks again', async ($, on) => {
- const probes: (readonly string[])[] = []
- Fixtures.startsSession(on)
- on('process.run', async ($, e) => {
- probes.push(e.argv)
-
- if (probes.length === 1) {
- await clock.sleep(Limits.GIT_TIMEOUT_MS)
-
- return { deny: GIT_HUNG }
- }
-
- return { value: Fixtures.NOT_A_REPOSITORY }
- })
-
- const booting = $.session.start(Fixtures.SESSION)
- await clock.advance(0)
- const ran = $.command.run(Fixtures.DIFF)
- await clock.advance(0)
-
- expect(probes, 'the boot probe, which /diff joined').toHaveLength(1)
-
- await clock.advance(Limits.GIT_TIMEOUT_MS)
- await booting
-
- expect(await ran).toEqual({
- text: expect.stringContaining("isn't in a git repository"),
- })
- expect(probes, 'then one more of its own').toHaveLength(2)
- })
-})
diff --git a/mods/diff/tests/command.test.ts b/mods/diff/tests/command.test.ts
deleted file mode 100644
index e058c24b..00000000
--- a/mods/diff/tests/command.test.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { describe, expect, test, tier } from 'claude-code/testing'
-
-import Fixtures from './fixtures'
-
-const BUILTIN_HOLDS = '"/diff" refused: it is the built-in /diff'
-
-tier('builtin')
-
-describe('command', () => {
- test('outside a repository /diff says so, opens nothing', async ($, on) => {
- const opened: string[] = []
- Fixtures.startsSession(on)
- on('process.run', () => ({ value: Fixtures.NOT_A_REPOSITORY }))
- on('ui.open', ($, e, next) => {
- opened.push(e.id)
-
- return next(e)
- })
-
- await $.session.start(Fixtures.SESSION)
- const { text } = await $.command.run(Fixtures.DIFF)
-
- expect(text).toContain("isn't in a git repository")
- expect(opened).toEqual([])
- })
-
- test('a git that never answers is not "no repository"', async ($, on) => {
- Fixtures.startsSession(on)
- on('process.run', () => ({
- deny: 'git aborted: still running after 5000ms',
- }))
-
- await $.session.start(Fixtures.SESSION)
- const { text } = await $.command.run(Fixtures.DIFF)
-
- expect(text).toContain("git didn't answer")
- })
-
- test('when the built-in holds /diff, the mod stands down', async ($, on) => {
- const logged: string[] = []
- on('session.start', ($, e) => ({ cwd: e.cwd }))
- on('command.register', () => ({ deny: BUILTIN_HOLDS }))
- on('command.run', () => ({ text: 'the built-in /diff ran' }))
- on('ui.log', ($, e) => {
- logged.push(e.text)
-
- return { value: undefined }
- })
-
- await $.session.start(Fixtures.SESSION)
-
- expect(await $.command.run(Fixtures.DIFF)).toEqual({
- text: 'the built-in /diff ran',
- })
- expect(logged).toEqual([])
- })
-
- test('a refusal the built-in did not cause is said aloud', async ($, on) => {
- const logged: string[] = []
- on('session.start', ($, e) => ({ cwd: e.cwd }))
- on('command.register', () => ({
- deny: '32 commands are registered already',
- }))
- on('ui.log', ($, e) => {
- logged.push(e.text)
-
- return { value: undefined }
- })
-
- await $.session.start(Fixtures.SESSION)
-
- expect(logged).toEqual([
- 'could not register /diff: diff: $.command.register: 32 commands are ' +
- 'registered already; the diff panel is unavailable this session',
- ])
- })
-})
diff --git a/mods/diff/tests/fixtures/builtin-holds.ts b/mods/diff/tests/fixtures/builtin-holds.ts
new file mode 100644
index 00000000..58f081c8
--- /dev/null
+++ b/mods/diff/tests/fixtures/builtin-holds.ts
@@ -0,0 +1,4 @@
+/**
+ * How `$.command.register` refuses `/diff` while the built-in one is listed.
+ */
+export const BUILTIN_HOLDS = '"/diff" refused: it is the built-in /diff'
diff --git a/mods/diff/tests/fixtures/clear.ts b/mods/diff/tests/fixtures/clear.ts
new file mode 100644
index 00000000..20f8bd5f
--- /dev/null
+++ b/mods/diff/tests/fixtures/clear.ts
@@ -0,0 +1,10 @@
+import type { CommandRunInput } from 'claude-code'
+
+/**
+ * The command that starts the conversation over, as the person types it.
+ */
+export const CLEAR: CommandRunInput = {
+ command: 'clear',
+ args: '',
+ origin: { kind: 'composer' },
+}
diff --git a/mods/diff/tests/fixtures/git-hung.ts b/mods/diff/tests/fixtures/git-hung.ts
new file mode 100644
index 00000000..e2c27a59
--- /dev/null
+++ b/mods/diff/tests/fixtures/git-hung.ts
@@ -0,0 +1,7 @@
+import Limits from '../../hooks/limits'
+
+/**
+ * How `$.process.run` refuses a git that outran its timeout.
+ */
+export const GIT_HUNG =
+ 'git aborted: still running after ' + `${Limits.GIT_TIMEOUT_MS}ms`
diff --git a/mods/diff/tests/fixtures/git-in.ts b/mods/diff/tests/fixtures/git-in.ts
new file mode 100644
index 00000000..49e6ff7e
--- /dev/null
+++ b/mods/diff/tests/fixtures/git-in.ts
@@ -0,0 +1,20 @@
+import type { ProcessRunResult } from 'claude-code'
+
+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.
+ *
+ * @param argv the invocation, program first
+ * @returns git's exit code and output
+ */
+export function gitIn(argv: readonly string[]): ProcessRunResult {
+ const line = argv.join(' ')
+ const found = Object.entries(REPOSITORY).find(([key]) => line.includes(key))
+
+ return found
+ ? { exitCode: 0, stdout: found[1], stderr: '' }
+ : NOT_A_REPOSITORY
+}
diff --git a/mods/diff/tests/fixtures/hint-drawn.ts b/mods/diff/tests/fixtures/hint-drawn.ts
new file mode 100644
index 00000000..c9dd87da
--- /dev/null
+++ b/mods/diff/tests/fixtures/hint-drawn.ts
@@ -0,0 +1,9 @@
+import type { RenderElement } from 'claude-code'
+
+/**
+ * What the engine draws for the hint, standing in beneath the plugin.
+ */
+export const HINT_DRAWN: RenderElement = {
+ type: 'Text',
+ children: ['? for shortcuts'],
+}
diff --git a/mods/diff/tests/fixtures/hint.ts b/mods/diff/tests/fixtures/hint.ts
new file mode 100644
index 00000000..0948b81d
--- /dev/null
+++ b/mods/diff/tests/fixtures/hint.ts
@@ -0,0 +1,13 @@
+import type { RenderInput } from 'claude-code'
+
+/**
+ * The prompt's hint on a 160-column terminal: drawing it is how the plugin
+ * learns how wide the terminal is.
+ */
+export const HINT: RenderInput<'PromptHint'> = {
+ component: 'PromptHint',
+ surface: 'terminal',
+ requestId: 'hint',
+ viewport: { columns: 160, rows: 40 },
+ props: { isDraft: false, isWorking: false, hint: '' },
+}
diff --git a/mods/diff/tests/fixtures/in-repository.ts b/mods/diff/tests/fixtures/in-repository.ts
new file mode 100644
index 00000000..b5e78d1b
--- /dev/null
+++ b/mods/diff/tests/fixtures/in-repository.ts
@@ -0,0 +1,36 @@
+import type { Args, On } from 'claude-code'
+import { memoryStore } from 'claude-code/testing'
+
+import { gitIn } from './git-in.js'
+import { HINT_DRAWN } from './hint-drawn.js'
+import { keeping } from './keeping.js'
+import { startsSession } from './starts-session.js'
+
+/**
+ * A session in /work (REPOSITORY), keeping each git run and each pane
+ * opened or closed.
+ *
+ * The store starts empty, the clock at 0, and the engine draws the hint.
+ *
+ * @param on the test's `on`
+ * @returns the runs, the panes opened and closed, and the session's clock
+ */
+export function inRepository(on: On) {
+ const runs: Args<'process.run'>[] = []
+ const opened = keeping<Args<'ui.open'>>()
+ const closed = keeping<Args<'ui.close'>>()
+ const clock = startsSession(on)
+ on('process.run', ($, e) => {
+ runs.push(e)
+
+ return { value: gitIn(e.argv) }
+ })
+ on('ui.open', opened.hook)
+ on('ui.close', closed.hook)
+ on('ui.invalidate', () => ({ value: undefined }))
+ on('ui.render', { component: 'PromptHint' }, () => HINT_DRAWN)
+ on('session.messages', () => ({ value: [] }))
+ memoryStore(on)
+
+ return { runs, opened: opened.kept, closed: closed.kept, clock }
+}
diff --git a/mods/diff/tests/fixtures/index.ts b/mods/diff/tests/fixtures/index.ts
index bd81c943..f6ac63c1 100644
--- a/mods/diff/tests/fixtures/index.ts
+++ b/mods/diff/tests/fixtures/index.ts
@@ -1,6 +1,17 @@
+export * from './builtin-holds.js'
+export * from './clear.js'
export * from './diff.js'
+export * from './git-hung.js'
+export * from './git-in.js'
+export * from './hint.js'
+export * from './hint-drawn.js'
+export * from './in-repository.js'
+export * from './keeping.js'
export * from './not-a-repository.js'
+export * from './pane.js'
+export * from './repository.js'
export * from './session.js'
+export * from './settle-ms.js'
export * from './starts-session.js'
export * as default from '.'
diff --git a/mods/diff/tests/fixtures/keeping.ts b/mods/diff/tests/fixtures/keeping.ts
new file mode 100644
index 00000000..5d83ec88
--- /dev/null
+++ b/mods/diff/tests/fixtures/keeping.ts
@@ -0,0 +1,17 @@
+/**
+ * A hook that keeps each input it is asked with, and answers, beside what
+ * it kept.
+ *
+ * @returns the hook, and each input in the order it came
+ */
+export function keeping<E>() {
+ const kept: E[] = []
+
+ function hook(_engine: unknown, e: E) {
+ kept.push(e)
+
+ return { value: undefined }
+ }
+
+ return { hook, kept }
+}
diff --git a/mods/diff/tests/fixtures/pane.ts b/mods/diff/tests/fixtures/pane.ts
new file mode 100644
index 00000000..17f195bc
--- /dev/null
+++ b/mods/diff/tests/fixtures/pane.ts
@@ -0,0 +1,19 @@
+import type { RenderInput } from 'claude-code'
+
+/**
+ * The diff pane docked on a 160-column terminal, unfocused, 80 columns of
+ * body and 30 rows in view.
+ */
+export const PANE: RenderInput<'Pane'> = {
+ component: 'Pane',
+ surface: 'terminal',
+ requestId: 'diff',
+ viewport: { columns: 160, rows: 40 },
+ props: {
+ title: 'Diff',
+ isFocused: false,
+ bodyColumns: 80,
+ placement: 'dock',
+ scroll: { offset: 0, bodyRows: 30 },
+ },
+}
diff --git a/mods/diff/tests/fixtures/repository.ts b/mods/diff/tests/fixtures/repository.ts
new file mode 100644
index 00000000..bde9f86d
--- /dev/null
+++ b/mods/diff/tests/fixtures/repository.ts
@@ -0,0 +1,11 @@
+/**
+ * Git's output in /work, where one file changed, for each invocation whose
+ * command line holds the key.
+ */
+export const REPOSITORY: Readonly<Record<string, string>> = {
+ 'rev-parse --path-format=absolute': '/work\n/work/.git\n/work/.git\n',
+ 'HEAD --shortstat': ' 1 file changed, 1 insertion(+)',
+ 'HEAD --numstat': '1\t0\tapp.ts\0',
+ 'ls-files': '',
+ '-- app.ts': '@@ -1 +1 @@\n-const a = 1\n+const a = 2\n',
+}
diff --git a/mods/diff/tests/fixtures/settle-ms.ts b/mods/diff/tests/fixtures/settle-ms.ts
new file mode 100644
index 00000000..94a4bd99
--- /dev/null
+++ b/mods/diff/tests/fixtures/settle-ms.ts
@@ -0,0 +1,5 @@
+/**
+ * Longer than every wait the pane schedules before it fetches and draws
+ * (its open probe, refresh debounce and redraw), short of its HEAD poll.
+ */
+export const SETTLE_MS = 1000
diff --git a/mods/diff/tests/fixtures/starts-session.ts b/mods/diff/tests/fixtures/starts-session.ts
index 291dc0f5..f25ce47d 100644
--- a/mods/diff/tests/fixtures/starts-session.ts
+++ b/mods/diff/tests/fixtures/starts-session.ts
@@ -1,12 +1,17 @@
import type { On } from 'claude-code'
+import { memoryClock } from 'claude-code/testing'
+import type { MemoryClock } from 'claude-code/testing'
/**
* Answers what every /diff session asks first: its start, with its own
- * directory, and each command it registers, under the name asked for.
+ * directory, the time, and each command it registers, under its name.
*
* @param on the test's `on`
+ * @returns the clock the session reads, at 0 until the test moves it
*/
-export function startsSession(on: On) {
+export function startsSession(on: On): MemoryClock {
on('session.start', ($, e) => ({ cwd: e.cwd }))
on('command.register', ($, e) => ({ value: { command: e.name } }))
+
+ return memoryClock(on)
}
diff --git a/mods/diff/tests/git.test.ts b/mods/diff/tests/git.test.ts
new file mode 100644
index 00000000..43182849
--- /dev/null
+++ b/mods/diff/tests/git.test.ts
@@ -0,0 +1,29 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+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)
+
+ await $.session.start(Fixtures.SESSION)
+ await $.command.run(Fixtures.DIFF)
+ await world.clock.advance(Fixtures.SETTLE_MS)
+ const [discovery, ...pinned] = world.runs
+
+ expect(discovery?.argv).toContain('--show-toplevel')
+ expect(discovery?.init?.cwd).toBeUndefined()
+ expect(pinned.length).toBeGreaterThan(0)
+
+ for (const run of pinned) {
+ expect(run.argv.slice(0, 3)).toEqual([
+ 'git',
+ '--git-dir=/work/.git',
+ '--work-tree=/work',
+ ])
+ expect(run.init).toMatchObject({ cwd: '/work', env: { LC_ALL: 'C' } })
+ }
+ })
+})
diff --git a/mods/diff/tests/pane.test.ts b/mods/diff/tests/pane.test.ts
deleted file mode 100644
index 755cf373..00000000
--- a/mods/diff/tests/pane.test.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-import type {
- Args,
- CommandRunInput,
- On,
- ProcessRunResult,
- RenderElement,
- RenderInput,
-} from 'claude-code'
-import {
- clock,
- describe,
- expect,
- memoryStore,
- test,
- textOf,
- tier,
-} from 'claude-code/testing'
-
-import Fixtures from './fixtures'
-
-const CLEAR: CommandRunInput = {
- command: 'clear',
- args: '',
- origin: { kind: 'composer' },
-}
-const PANE: RenderInput<'Pane'> = {
- component: 'Pane',
- surface: 'terminal',
- requestId: 'diff',
- viewport: { columns: 160, rows: 40 },
- props: {
- title: 'Diff',
- isFocused: false,
- bodyColumns: 80,
- placement: 'dock',
- scroll: { offset: 0, bodyRows: 30 },
- },
-}
-/**
- * The prompt's hint on a 160-column terminal: drawing it is how the plugin
- * learns how wide the terminal is.
- */
-const HINT: RenderInput<'PromptHint'> = {
- component: 'PromptHint',
- surface: 'terminal',
- requestId: 'hint',
- viewport: { columns: 160, rows: 40 },
- props: { isDraft: false, isWorking: false, hint: '' },
-}
-/**
- * What the engine draws for the hint, standing in beneath the plugin.
- */
-const HINT_DRAWN: RenderElement = {
- type: 'Text',
- children: ['? for shortcuts'],
-}
-/**
- * Git's output in /work, where one file changed, for each invocation whose
- * command line holds the key.
- */
-const REPOSITORY: Readonly<Record<string, string>> = {
- 'rev-parse --path-format=absolute': '/work\n/work/.git\n/work/.git\n',
- 'HEAD --shortstat': ' 1 file changed, 1 insertion(+)',
- 'HEAD --numstat': '1\t0\tapp.ts\0',
- 'ls-files': '',
- '-- app.ts': '@@ -1 +1 @@\n-const a = 1\n+const a = 2\n',
-}
-/**
- * Longer than every wait the pane schedules before it fetches and draws
- * (its open probe, refresh debounce and redraw), short of its HEAD poll.
- */
-const SETTLE_MS = 1000
-
-tier('builtin')
-
-/**
- * What git answers in that repository; an invocation it does not know
- * fails as git does outside a repository.
- */
-function gitIn(argv: readonly string[]): ProcessRunResult {
- const line = argv.join(' ')
- const found = Object.entries(REPOSITORY).find(([key]) => line.includes(key))
-
- return found
- ? { exitCode: 0, stdout: found[1], stderr: '' }
- : Fixtures.NOT_A_REPOSITORY
-}
-
-/**
- * A hook that keeps each input it is asked with, and answers, beside what
- * it kept.
- *
- * @returns the hook, and each input in the order it came
- */
-function keeping<E>() {
- const kept: E[] = []
-
- function hook(_engine: unknown, e: E) {
- kept.push(e)
-
- return { value: undefined }
- }
-
- return { hook, kept }
-}
-
-/**
- * A session in that repository, keeping each git run and each pane opened
- * or closed; the store starts empty and the engine draws the hint.
- */
-function inRepository(on: On) {
- const runs: Args<'process.run'>[] = []
- const opened = keeping<Args<'ui.open'>>()
- const closed = keeping<Args<'ui.close'>>()
- Fixtures.startsSession(on)
- on('process.run', ($, e) => {
- runs.push(e)
-
- return { value: gitIn(e.argv) }
- })
- on('ui.open', opened.hook)
- on('ui.close', closed.hook)
- on('ui.invalidate', () => ({ value: undefined }))
- on('ui.render', { component: 'PromptHint' }, () => HINT_DRAWN)
- on('session.messages', () => ({ value: [] }))
- memoryStore(on)
-
- return { runs, opened: opened.kept, closed: closed.kept }
-}
-
-describe('pane', () => {
- test('/diff opens the pane over the session changes', async ($, on) => {
- const world = inRepository(on)
-
- await $.session.start(Fixtures.SESSION)
-
- expect(await $.command.run(Fixtures.DIFF)).toEqual({})
- expect(world.opened.map(pane => pane.id)).toEqual(['diff'])
-
- await clock.advance(SETTLE_MS)
- const drawn = textOf(await $.ui.render(PANE))
-
- expect(drawn).toContain('1 file changed')
- expect(drawn).toContain('app.ts')
- })
-
- test('each git child runs pinned to /work, in C locale', async ($, on) => {
- const world = inRepository(on)
-
- await $.session.start(Fixtures.SESSION)
- await $.command.run(Fixtures.DIFF)
- await clock.advance(SETTLE_MS)
- const [discovery, ...pinned] = world.runs
-
- expect(discovery?.argv).toContain('--show-toplevel')
- expect(discovery?.init?.cwd).toBeUndefined()
- expect(pinned.length).toBeGreaterThan(0)
-
- for (const run of pinned) {
- expect(run.argv.slice(0, 3)).toEqual([
- 'git',
- '--git-dir=/work/.git',
- '--work-tree=/work',
- ])
- expect(run.init).toMatchObject({ cwd: '/work', env: { LC_ALL: 'C' } })
- }
- })
-
- test('a wide terminal opens the pane at the first edit', async ($, on) => {
- const world = inRepository(on)
- on('tool.call', () => ({ result: 'edited' }))
-
- await $.session.start(Fixtures.SESSION)
- await $.ui.render(HINT)
- await $.tool.call({
- tool: 'Edit',
- file_path: '/work/app.ts',
- old_string: '1',
- new_string: '2',
- })
- await clock.advance(SETTLE_MS)
-
- expect(world.opened.map(pane => pane.id)).toEqual(['diff'])
- })
-
- test('/clear closes the pane it finds open', async ($, on) => {
- const world = inRepository(on)
- on('command.run', { command: 'clear' }, () => ({}))
-
- await $.session.start(Fixtures.SESSION)
- await $.command.run(Fixtures.DIFF)
- await $.command.run(CLEAR)
-
- expect(world.closed.map(pane => pane.id)).toEqual(['diff'])
- })
-})
diff --git a/mods/diff/tests/register.test.ts b/mods/diff/tests/register.test.ts
new file mode 100644
index 00000000..86f6d9a8
--- /dev/null
+++ b/mods/diff/tests/register.test.ts
@@ -0,0 +1,176 @@
+import {
+ describe,
+ expect,
+ memoryClock,
+ test,
+ textOf,
+ tier,
+} from 'claude-code/testing'
+
+import Limits from '../hooks/limits'
+import Fixtures from './fixtures'
+
+tier('builtin')
+
+describe('register', () => {
+ test('/diff at boot joins the boot probe, then asks again', async ($, on) => {
+ const probes: (readonly string[])[] = []
+ const clock = Fixtures.startsSession(on)
+ on('process.run', async ($, e) => {
+ probes.push(e.argv)
+
+ if (probes.length === 1) {
+ await clock.sleep(Limits.GIT_TIMEOUT_MS)
+
+ return { deny: Fixtures.GIT_HUNG }
+ }
+
+ return { value: Fixtures.NOT_A_REPOSITORY }
+ })
+
+ const booting = $.session.start(Fixtures.SESSION)
+ await clock.advance(0)
+ const ran = $.command.run(Fixtures.DIFF)
+ await clock.advance(0)
+
+ expect(probes, 'the boot probe, which /diff joined').toHaveLength(1)
+
+ await clock.advance(Limits.GIT_TIMEOUT_MS)
+ await booting
+
+ expect(await ran).toEqual({
+ text: expect.stringContaining("isn't in a git repository"),
+ })
+ expect(probes, 'then one more of its own').toHaveLength(2)
+ })
+
+ test('outside a repository /diff says so, opens nothing', async ($, on) => {
+ const opened: string[] = []
+ Fixtures.startsSession(on)
+ on('process.run', () => ({ value: Fixtures.NOT_A_REPOSITORY }))
+ on('ui.open', ($, e, next) => {
+ opened.push(e.id)
+
+ return next(e)
+ })
+
+ await $.session.start(Fixtures.SESSION)
+ const { text } = await $.command.run(Fixtures.DIFF)
+
+ expect(text).toContain("isn't in a git repository")
+ expect(opened).toEqual([])
+ })
+
+ test('a git that never answers is not "no repository"', async ($, on) => {
+ Fixtures.startsSession(on)
+ on('process.run', () => ({ deny: Fixtures.GIT_HUNG }))
+
+ await $.session.start(Fixtures.SESSION)
+ const { text } = await $.command.run(Fixtures.DIFF)
+
+ expect(text).toContain("git didn't answer")
+ })
+
+ test('when the built-in holds /diff, the mod stands down', async ($, on) => {
+ const logged: string[] = []
+ memoryClock(on)
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('command.register', () => ({ deny: Fixtures.BUILTIN_HOLDS }))
+ on('command.run', () => ({ text: 'the built-in /diff ran' }))
+ on('ui.log', ($, e) => {
+ logged.push(e.text)
+
+ return { value: undefined }
+ })
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(await $.command.run(Fixtures.DIFF)).toEqual({
+ text: 'the built-in /diff ran',
+ })
+ expect(logged).toEqual([])
+ })
+
+ test('a refusal the built-in did not cause is said aloud', async ($, on) => {
+ const logged: string[] = []
+ memoryClock(on)
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('command.register', () => ({
+ deny: '32 commands are registered already',
+ }))
+ on('ui.log', ($, e) => {
+ logged.push(e.text)
+
+ return { value: undefined }
+ })
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(logged).toEqual([
+ 'could not register /diff: diff: $.command.register: 32 commands are ' +
+ 'registered already; the diff panel is unavailable this session',
+ ])
+ })
+
+ test('/diff opens the pane over the session changes', async ($, on) => {
+ const world = Fixtures.inRepository(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(await $.command.run(Fixtures.DIFF)).toEqual({})
+ expect(world.opened.map(pane => pane.id)).toEqual(['diff'])
+
+ await world.clock.advance(Fixtures.SETTLE_MS)
+ const drawn = textOf(await $.ui.render(Fixtures.PANE))
+
+ expect(drawn).toContain('1 file changed')
+ expect(drawn).toContain('app.ts')
+ })
+
+ test('the close button closes the pane; /diff reopens it', async ($, on) => {
+ const world = Fixtures.inRepository(on)
+
+ await $.session.start(Fixtures.SESSION)
+ await $.command.run(Fixtures.DIFF)
+ await world.clock.advance(Fixtures.SETTLE_MS)
+ await $.ui.render(Fixtures.PANE)
+
+ expect(await $.ui.press({ plugin: 'diff', key: 'close' })).toEqual({
+ element: 'close',
+ })
+
+ await world.clock.advance(0)
+
+ expect(world.closed.map(pane => pane.id)).toEqual(['diff'])
+ expect(await $.command.run(Fixtures.DIFF)).toEqual({})
+ expect(world.opened.map(pane => pane.id)).toEqual(['diff', 'diff'])
+ })
+
+ test('a wide terminal opens the pane at the first edit', async ($, on) => {
+ const world = Fixtures.inRepository(on)
+ on('tool.call', () => ({ result: 'edited' }))
+
+ await $.session.start(Fixtures.SESSION)
+ await $.ui.render(Fixtures.HINT)
+ await $.tool.call({
+ tool: 'Edit',
+ file_path: '/work/app.ts',
+ old_string: '1',
+ new_string: '2',
+ })
+ await world.clock.advance(Fixtures.SETTLE_MS)
+
+ expect(world.opened.map(pane => pane.id)).toEqual(['diff'])
+ })
+
+ test('/clear closes the pane it finds open', async ($, on) => {
+ const world = Fixtures.inRepository(on)
+ on('command.run', { command: 'clear' }, () => ({}))
+
+ await $.session.start(Fixtures.SESSION)
+ await $.command.run(Fixtures.DIFF)
+ await $.command.run(Fixtures.CLEAR)
+
+ expect(world.closed.map(pane => pane.id)).toEqual(['diff'])
+ })
+})
diff --git a/mods/sec-default/tests/fixtures/allowlist.ts b/mods/sec-default/tests/fixtures/allowlist.ts
new file mode 100644
index 00000000..d3db029d
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/allowlist.ts
@@ -0,0 +1,8 @@
+import type { Settings } from 'claude-code'
+
+/**
+ * Managed settings holding an MCP allowlist: a tool policy in force.
+ */
+export const ALLOWLIST: Settings = {
+ allowedMcpServers: [{ serverName: 'corp' }],
+}
diff --git a/mods/sec-default/tests/fixtures/dropping.ts b/mods/sec-default/tests/fixtures/dropping.ts
new file mode 100644
index 00000000..023d7e9e
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/dropping.ts
@@ -0,0 +1,11 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that drops the memory section.
+ */
+export const dropping: Plugin = {
+ name: 'dropping',
+ register(on) {
+ on('prompt.section', () => ({ text: null }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/index.ts b/mods/sec-default/tests/fixtures/index.ts
new file mode 100644
index 00000000..e0e1615b
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/index.ts
@@ -0,0 +1,15 @@
+export * from './allowlist.js'
+export * from './dropping.js'
+export * from './listing.js'
+export * from './memory.js'
+export * from './no-allowlist.js'
+export * from './registered-tool-of.js'
+export * from './registering.js'
+export * from './relabeling.js'
+export * from './session.js'
+export * from './signing.js'
+export * from './tools.js'
+export * from './tools-command.js'
+export * from './tools-registered.js'
+
+export * as default from '.'
diff --git a/mods/sec-default/tests/fixtures/listing.ts b/mods/sec-default/tests/fixtures/listing.ts
new file mode 100644
index 00000000..4ce5dae1
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/listing.ts
@@ -0,0 +1,16 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin whose `/tools` answers the tool listing it reads, one
+ * `name: description` line per tool.
+ */
+export const listing: Plugin = {
+ name: 'listing',
+ register(on) {
+ on('command.run', { command: 'tools' }, async $ => ({
+ text: (await $.tool.list())
+ .map(tool => `${tool.name}: ${tool.description}`)
+ .join('\n'),
+ }))
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/memory.ts b/mods/sec-default/tests/fixtures/memory.ts
new file mode 100644
index 00000000..068c7e1d
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/memory.ts
@@ -0,0 +1,9 @@
+import type { PromptSectionInput } from 'claude-code'
+
+/**
+ * The system prompt's memory section, as the engine asks for it.
+ */
+export const MEMORY: PromptSectionInput = {
+ name: 'memory',
+ text: 'the org says hi',
+}
diff --git a/mods/sec-default/tests/fixtures/no-allowlist.ts b/mods/sec-default/tests/fixtures/no-allowlist.ts
new file mode 100644
index 00000000..84f67444
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/no-allowlist.ts
@@ -0,0 +1,6 @@
+import type { Settings } from 'claude-code'
+
+/**
+ * Managed settings with permissions but no MCP allowlist or denylist.
+ */
+export const NO_ALLOWLIST: Settings = { permissions: { allow: [] } }
diff --git a/mods/sec-default/tests/fixtures/registered-tool-of.ts b/mods/sec-default/tests/fixtures/registered-tool-of.ts
new file mode 100644
index 00000000..d6c22243
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/registered-tool-of.ts
@@ -0,0 +1,10 @@
+/**
+ * What registering a plugin's tool answers: the name it is called by.
+ *
+ * @param plugin the plugin that asked
+ * @param name the tool's own name
+ * @returns the `tool.register` result
+ */
+export const registeredToolOf = (plugin: string, name: string) => ({
+ value: { tool: `mcp__plugin_${plugin}__${name}` },
+})
diff --git a/mods/sec-default/tests/fixtures/registering.ts b/mods/sec-default/tests/fixtures/registering.ts
new file mode 100644
index 00000000..4d68de14
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/registering.ts
@@ -0,0 +1,25 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin that registers a tool when the session starts, in the tier
+ * given: the person's own by default.
+ *
+ * @param name the plugin's name
+ * @param tier the tier it loads in
+ * @returns the plugin
+ */
+export const registering = (name: string, tier?: Plugin['tier']): Plugin => ({
+ name,
+ tier,
+ register(on) {
+ on('session.start', async ($, e, next) => {
+ await $.tool.register({
+ name: 'greet',
+ description: 'Says hello.',
+ inputSchema: { type: 'object' },
+ })
+
+ return next(e)
+ })
+ },
+})
diff --git a/mods/sec-default/tests/fixtures/relabeling.ts b/mods/sec-default/tests/fixtures/relabeling.ts
new file mode 100644
index 00000000..ff5a9e8f
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/relabeling.ts
@@ -0,0 +1,24 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin the person installed that hides the organization's tools from
+ * the listing and relabels every other one.
+ */
+export const relabeling: Plugin = {
+ name: 'relabeling',
+ register(on) {
+ on('tool.list', async ($, e, next) => {
+ const listed = await next(e)
+ const { value } = listed
+ const isListed = value !== undefined
+
+ return isListed
+ ? {
+ value: value
+ .filter(tool => !tool.name.startsWith('mcp__corp__'))
+ .map(tool => ({ ...tool, description: 'relabeled' })),
+ }
+ : listed
+ })
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/session.ts b/mods/sec-default/tests/fixtures/session.ts
new file mode 100644
index 00000000..c387d8e7
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/session.ts
@@ -0,0 +1,10 @@
+import type { SessionStartInput } from 'claude-code'
+
+/**
+ * An interactive terminal session in /work.
+ */
+export const SESSION: SessionStartInput = {
+ surface: 'terminal',
+ isInteractive: true,
+ cwd: '/work',
+}
diff --git a/mods/sec-default/tests/fixtures/signing.ts b/mods/sec-default/tests/fixtures/signing.ts
new file mode 100644
index 00000000..68e1aac8
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/signing.ts
@@ -0,0 +1,14 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * The organization's own plugin, in its last tier, which signs the section.
+ */
+export const signing: Plugin = {
+ name: 'signing',
+ tier: 'append',
+ register(on) {
+ on('prompt.section', ($, e, next) =>
+ next({ ...e, text: `${e.text} (signed)` }),
+ )
+ },
+}
diff --git a/mods/sec-default/tests/fixtures/tools-command.ts b/mods/sec-default/tests/fixtures/tools-command.ts
new file mode 100644
index 00000000..2c213092
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tools-command.ts
@@ -0,0 +1,10 @@
+import type { CommandRunInput } from 'claude-code'
+
+/**
+ * `/tools` as the person types it: the listing plugin's command.
+ */
+export const TOOLS_COMMAND: CommandRunInput = {
+ command: 'tools',
+ args: '',
+ origin: { kind: 'composer' },
+}
diff --git a/mods/sec-default/tests/fixtures/tools-registered.ts b/mods/sec-default/tests/fixtures/tools-registered.ts
new file mode 100644
index 00000000..60030ac4
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tools-registered.ts
@@ -0,0 +1,22 @@
+import type { On } from 'claude-code'
+
+import { registeredToolOf } from './registered-tool-of.js'
+
+/**
+ * A session starting, where each tool a plugin asks for is registered and
+ * kept by the name of the plugin that asked.
+ *
+ * @param on the test's `on`
+ * @returns the plugins whose tools were registered, in order
+ */
+export function toolsRegistered(on: On) {
+ const registered: string[] = []
+ on('session.start', ($, e) => ({ cwd: e.cwd }))
+ on('tool.register', ($, e, next) => {
+ registered.push(next.origin.plugin)
+
+ return registeredToolOf(next.origin.plugin, e.name)
+ })
+
+ return registered
+}
diff --git a/mods/sec-default/tests/fixtures/tools.ts b/mods/sec-default/tests/fixtures/tools.ts
new file mode 100644
index 00000000..6ef775ca
--- /dev/null
+++ b/mods/sec-default/tests/fixtures/tools.ts
@@ -0,0 +1,13 @@
+import type { ToolInfo } from 'claude-code'
+
+/**
+ * The session's tools: one from the organization's MCP server, one built in.
+ */
+export const TOOLS: readonly ToolInfo[] = [
+ {
+ name: 'mcp__corp__search',
+ description: 'Searches the corp wiki.',
+ mcp: true,
+ },
+ { name: 'Bash', description: 'Runs a command.', mcp: false },
+]
diff --git a/mods/sec-default/tests/register.test.ts b/mods/sec-default/tests/register.test.ts
new file mode 100644
index 00000000..8d346844
--- /dev/null
+++ b/mods/sec-default/tests/register.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, test, tier } from 'claude-code/testing'
+
+import Fixtures from './fixtures'
+
+tier('prepend')
+
+describe('register', () => {
+ test(
+ 'under an MCP allowlist a plugin the person installed may not add a tool',
+ {
+ plugins: [
+ Fixtures.registering('mine'),
+ Fixtures.registering('bundled', 'builtin'),
+ ],
+ },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.ALLOWLIST }))
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['bundled'])
+ },
+ )
+
+ test(
+ 'with no allowlist, a plugin the person installed adds its tool',
+ { plugins: [Fixtures.registering('mine')] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.NO_ALLOWLIST }))
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual(['mine'])
+ },
+ )
+
+ test(
+ 'a policy that cannot be read counts as one in force',
+ { plugins: [Fixtures.registering('mine')] },
+ async ($, on) => {
+ on('settings.read', () => ({ deny: 'managed settings unreadable' }))
+ const registered = Fixtures.toolsRegistered(on)
+
+ await $.session.start(Fixtures.SESSION)
+
+ expect(registered).toEqual([])
+ },
+ )
+
+ test(
+ 'the organization tools are listed as its tiers listed them',
+ { plugins: [Fixtures.relabeling, Fixtures.listing] },
+ async ($, on) => {
+ on('settings.read', () => ({ value: Fixtures.ALLOWLIST }))
+ 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(
+ 'a prompt section passes over the plugins the person installed',
+ { plugins: [Fixtures.dropping, Fixtures.signing] },
+ async ($, on) => {
+ on('prompt.section', ($, e) => ({ text: e.text }))
+
+ expect(await $.prompt.section(Fixtures.MEMORY)).toEqual({
+ text: 'the org says hi (signed)',
+ })
+ },
+ )
+})
diff --git a/mods/sec-default/tests/sec-default.test.ts b/mods/sec-default/tests/sec-default.test.ts
deleted file mode 100644
index 1b5237c9..00000000
--- a/mods/sec-default/tests/sec-default.test.ts
+++ /dev/null
@@ -1,207 +0,0 @@
-import type {
- CommandRunInput,
- On,
- PromptSectionInput,
- SessionStartInput,
- Settings,
- ToolInfo,
-} from 'claude-code'
-import { describe, expect, test, tier } from 'claude-code/testing'
-import type { Plugin } from 'claude-code/testing'
-
-tier('prepend')
-
-const SESSION: SessionStartInput = {
- surface: 'terminal',
- isInteractive: true,
- cwd: '/work',
-}
-const TOOLS_COMMAND: CommandRunInput = {
- command: 'tools',
- args: '',
- origin: { kind: 'composer' },
-}
-const ALLOWLIST: Settings = { allowedMcpServers: [{ serverName: 'corp' }] }
-const NO_ALLOWLIST: Settings = { permissions: { allow: [] } }
-const MEMORY: PromptSectionInput = { name: 'memory', text: 'the org says hi' }
-const TOOLS: readonly ToolInfo[] = [
- {
- name: 'mcp__corp__search',
- description: 'Searches the corp wiki.',
- mcp: true,
- },
- { name: 'Bash', description: 'Runs a command.', mcp: false },
-]
-
-/**
- * A plugin that registers a tool when the session starts, in the tier
- * given: the person's own by default.
- */
-const registering = (name: string, tier?: Plugin['tier']): Plugin => ({
- name,
- tier,
- register(on) {
- on('session.start', async ($, e, next) => {
- await $.tool.register({
- name: 'greet',
- description: 'Says hello.',
- inputSchema: { type: 'object' },
- })
-
- return next(e)
- })
- },
-})
-
-/**
- * What registering a plugin's tool answers: the name it is called by.
- */
-const registeredToolOf = (plugin: string, name: string) => ({
- value: { tool: `mcp__plugin_${plugin}__${name}` },
-})
-
-/**
- * A session starting, where each tool a plugin asks for is registered and
- * kept by the name of the plugin that asked.
- */
-function toolsRegistered(on: On) {
- const registered: string[] = []
- on('session.start', ($, e) => ({ cwd: e.cwd }))
- on('tool.register', ($, e, next) => {
- registered.push(next.origin.plugin)
-
- return registeredToolOf(next.origin.plugin, e.name)
- })
-
- return registered
-}
-
-/**
- * A plugin the person installed that hides the organization's tools from
- * the listing and relabels every other one.
- */
-const relabeling: Plugin = {
- name: 'relabeling',
- register(on) {
- on('tool.list', async ($, e, next) => {
- const listed = await next(e)
- const { value } = listed
- const isListed = value !== undefined
-
- return isListed
- ? {
- value: value
- .filter(tool => !tool.name.startsWith('mcp__corp__'))
- .map(tool => ({ ...tool, description: 'relabeled' })),
- }
- : listed
- })
- },
-}
-
-/**
- * A plugin whose `/tools` answers the tool listing it reads, one
- * `name: description` line per tool.
- */
-const listing: Plugin = {
- name: 'listing',
- register(on) {
- on('command.run', { command: 'tools' }, async $ => ({
- text: (await $.tool.list())
- .map(tool => `${tool.name}: ${tool.description}`)
- .join('\n'),
- }))
- },
-}
-
-/**
- * A plugin the person installed that drops the memory section.
- */
-const dropping: Plugin = {
- name: 'dropping',
- register(on) {
- on('prompt.section', () => ({ text: null }))
- },
-}
-
-/**
- * The organization's own plugin, in its last tier, which signs the section.
- */
-const signing: Plugin = {
- name: 'signing',
- tier: 'append',
- register(on) {
- on('prompt.section', ($, e, next) =>
- next({ ...e, text: `${e.text} (signed)` }),
- )
- },
-}
-
-describe('sec-default', () => {
- test(
- 'under an MCP allowlist a plugin the person installed may not add a tool',
- { plugins: [registering('mine'), registering('bundled', 'builtin')] },
- async ($, on) => {
- on('settings.read', () => ({ value: ALLOWLIST }))
- const registered = toolsRegistered(on)
-
- await $.session.start(SESSION)
-
- expect(registered).toEqual(['bundled'])
- },
- )
-
- test(
- 'with no allowlist, a plugin the person installed adds its tool',
- { plugins: [registering('mine')] },
- async ($, on) => {
- on('settings.read', () => ({ value: NO_ALLOWLIST }))
- const registered = toolsRegistered(on)
-
- await $.session.start(SESSION)
-
- expect(registered).toEqual(['mine'])
- },
- )
-
- test(
- 'a policy that cannot be read counts as one in force',
- { plugins: [registering('mine')] },
- async ($, on) => {
- on('settings.read', () => ({ deny: 'managed settings unreadable' }))
- const registered = toolsRegistered(on)
-
- await $.session.start(SESSION)
-
- expect(registered).toEqual([])
- },
- )
-
- test(
- 'the organization tools are listed as its tiers listed them',
- { plugins: [relabeling, listing] },
- async ($, on) => {
- on('settings.read', () => ({ value: ALLOWLIST }))
- on('tool.list', () => ({ value: [...TOOLS] }))
-
- const { text } = await $.command.run(TOOLS_COMMAND)
-
- expect(text?.split('\n')).toEqual([
- 'mcp__corp__search: Searches the corp wiki.',
- 'Bash: relabeled',
- ])
- },
- )
-
- test(
- 'a prompt section passes over the plugins the person installed',
- { plugins: [dropping, signing] },
- async ($, on) => {
- on('prompt.section', ($, e) => ({ text: e.text }))
-
- expect(await $.prompt.section(MEMORY)).toEqual({
- text: 'the org says hi (signed)',
- })
- },
- )
-})
diff --git a/mods/telemetry/tests/fixtures/accepted.ts b/mods/telemetry/tests/fixtures/accepted.ts
new file mode 100644
index 00000000..14528e6d
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/accepted.ts
@@ -0,0 +1,11 @@
+import type { HttpResponse } from 'claude-code'
+
+/**
+ * The ingest's answer to a batch it took.
+ */
+export const ACCEPTED: HttpResponse = {
+ status: 200,
+ ok: true,
+ headers: {},
+ text: '',
+}
diff --git a/mods/telemetry/tests/fixtures/batch-of.ts b/mods/telemetry/tests/fixtures/batch-of.ts
new file mode 100644
index 00000000..8a3ebeda
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/batch-of.ts
@@ -0,0 +1,10 @@
+import type { Args } from 'claude-code'
+
+/**
+ * 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 =>
+ JSON.parse(String(post.init?.body))
diff --git a/mods/telemetry/tests/fixtures/bearer.ts b/mods/telemetry/tests/fixtures/bearer.ts
new file mode 100644
index 00000000..7c79d087
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/bearer.ts
@@ -0,0 +1,9 @@
+import type { SessionAuthorization } from 'claude-code'
+
+/**
+ * The credential a session signed in first party holds, by its handle.
+ */
+export const BEARER: SessionAuthorization = {
+ handle: 'the-handle',
+ kind: 'bearer',
+}
diff --git a/mods/telemetry/tests/fixtures/first-party-session.ts b/mods/telemetry/tests/fixtures/first-party-session.ts
new file mode 100644
index 00000000..997485dc
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/first-party-session.ts
@@ -0,0 +1,29 @@
+import type { Args, On, SessionAuthorization } from 'claude-code'
+
+import { ACCEPTED } from './accepted.js'
+import { BEARER } from './bearer.js'
+
+/**
+ * Answers what the telemetry plugin reads of a session signed in first
+ * party, and keeps each post the ingest accepts.
+ *
+ * @param on the test's `on`
+ * @param authorization the credential the session holds
+ * @returns each post, as it was made
+ */
+export function firstPartySession(
+ on: On,
+ authorization: SessionAuthorization = BEARER,
+) {
+ const posts: Args<'http.fetch'>[] = []
+ on('session.id', () => ({ value: 'the-session' }))
+ on('session.model', () => ({ value: 'the-model' }))
+ on('session.authorize', () => ({ value: authorization }))
+ on('http.fetch', ($, e) => {
+ posts.push(e)
+
+ return { value: ACCEPTED }
+ })
+
+ return posts
+}
diff --git a/mods/telemetry/tests/fixtures/index.ts b/mods/telemetry/tests/fixtures/index.ts
new file mode 100644
index 00000000..ffe2dec1
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/index.ts
@@ -0,0 +1,9 @@
+export * from './accepted.js'
+export * from './batch-of.js'
+export * from './bearer.js'
+export * from './first-party-session.js'
+export * from './record.js'
+export * from './recording.js'
+export * from './survey-answer.js'
+
+export * as default from '.'
diff --git a/mods/telemetry/tests/fixtures/record.ts b/mods/telemetry/tests/fixtures/record.ts
new file mode 100644
index 00000000..00e2a3ff
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/record.ts
@@ -0,0 +1,16 @@
+import type { CommandRunInput } from 'claude-code'
+
+import type { LogEntry } from '../../hooks/telemetry-types'
+
+/**
+ * The command that has the recording plugin log an entry, typed as the
+ * person would type it.
+ *
+ * @param entry what to log
+ * @returns `/record <entry>`
+ */
+export const record = (entry: LogEntry): CommandRunInput => ({
+ command: 'record',
+ args: JSON.stringify(entry),
+ origin: { kind: 'composer' },
+})
diff --git a/mods/telemetry/tests/fixtures/recording.ts b/mods/telemetry/tests/fixtures/recording.ts
new file mode 100644
index 00000000..ed6ec560
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/recording.ts
@@ -0,0 +1,17 @@
+import type { Plugin } from 'claude-code/testing'
+
+/**
+ * A plugin whose `/record <entry>` logs the entry through `$.telemetry`,
+ * answering "sent", or why the row was refused.
+ */
+export const recording: Plugin = {
+ name: 'recording',
+ register(on) {
+ on('command.run', { command: 'record' }, ($, e) =>
+ $.telemetry.log(JSON.parse(e.args)).then(
+ () => ({ text: 'sent' }),
+ (error: unknown) => ({ text: String(error) }),
+ ),
+ )
+ },
+}
diff --git a/mods/telemetry/tests/fixtures/survey-answer.ts b/mods/telemetry/tests/fixtures/survey-answer.ts
new file mode 100644
index 00000000..b3410093
--- /dev/null
+++ b/mods/telemetry/tests/fixtures/survey-answer.ts
@@ -0,0 +1,11 @@
+import type { LogEntry } from '../../hooks/telemetry-types'
+
+/**
+ * A survey answered, as a plugin logs it.
+ *
+ * @returns the entry, fresh each call
+ */
+export const surveyAnswer = (): LogEntry => ({
+ event: 'survey_answered',
+ props: { answer: 2, seen: true },
+})
diff --git a/mods/telemetry/tests/register.test.ts b/mods/telemetry/tests/register.test.ts
new file mode 100644
index 00000000..ba662aa1
--- /dev/null
+++ b/mods/telemetry/tests/register.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, memoryEnv, test, tier } from 'claude-code/testing'
+
+import Fixtures from './fixtures'
+
+tier('builtin')
+
+describe('register', () => {
+ test(
+ 'a $.telemetry.log call from a plugin posts one first-party row',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ memoryEnv(on, { USER_TYPE: 'ant' })
+ const posts = Fixtures.firstPartySession(on)
+
+ expect(
+ 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(Fixtures.batchOf)).toMatchObject([
+ {
+ events: [
+ {
+ event_data: {
+ event_name: 'tengu_plugin_survey_answered',
+ session_id: 'the-session',
+ model: 'the-model',
+ user_type: 'ant',
+ },
+ },
+ ],
+ },
+ ])
+ },
+ )
+
+ test(
+ 'a row already named tengu_ is sent under its own name',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ memoryEnv(on, {})
+ const posts = Fixtures.firstPartySession(on)
+
+ await $.command.run(
+ Fixtures.record({
+ ...Fixtures.surveyAnswer(),
+ event: 'tengu_repl_diff_panel_shown',
+ }),
+ )
+
+ expect(posts.map(Fixtures.batchOf)).toMatchObject([
+ {
+ events: [
+ {
+ event_data: {
+ event_name: 'tengu_repl_diff_panel_shown',
+ user_type: 'external',
+ },
+ },
+ ],
+ },
+ ])
+ },
+ )
+
+ test(
+ 'nothing is sent for a person who asked not to be tracked',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ memoryEnv(on, { DO_NOT_TRACK: '1' })
+ const posts = Fixtures.firstPartySession(on)
+ const { text } = await $.command.run(
+ Fixtures.record(Fixtures.surveyAnswer()),
+ )
+
+ expect({ text, posts }).toEqual({ text: 'sent', posts: [] })
+ },
+ )
+
+ test(
+ 'nothing is sent on a third-party provider',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ memoryEnv(on, { CLAUDE_CODE_USE_BEDROCK: '1' })
+ const posts = Fixtures.firstPartySession(on)
+
+ await $.command.run(Fixtures.record(Fixtures.surveyAnswer()))
+
+ expect(posts).toEqual([])
+ },
+ )
+
+ test(
+ 'a session with no first-party credential is refused, nothing sent',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ memoryEnv(on, {})
+ const posts = Fixtures.firstPartySession(on, null)
+ const { text } = await $.command.run(
+ Fixtures.record(Fixtures.surveyAnswer()),
+ )
+
+ expect(text).toEndWith(
+ '$.telemetry.log: this session has no first-party credential to ' +
+ 'authorize',
+ )
+ expect(posts).toEqual([])
+ },
+ )
+
+ test(
+ 'free text in a row is refused, nothing sent',
+ { plugins: [Fixtures.recording] },
+ async ($, on) => {
+ memoryEnv(on, {})
+ const posts = Fixtures.firstPartySession(on)
+ const { text } = await $.command.run({
+ ...Fixtures.record(Fixtures.surveyAnswer()),
+ args: '{"event":"survey_answered","props":{"note":"hello world"}}',
+ })
+
+ expect(text).toContain('props.note: free text is refused')
+ expect(posts).toEqual([])
+ },
+ )
+})
diff --git a/mods/telemetry/tests/telemetry.test.ts b/mods/telemetry/tests/telemetry.test.ts
deleted file mode 100644
index d385242e..00000000
--- a/mods/telemetry/tests/telemetry.test.ts
+++ /dev/null
@@ -1,196 +0,0 @@
-import type {
- Args,
- CommandRunInput,
- HttpResponse,
- On,
- SessionAuthorization,
-} from 'claude-code'
-import { describe, expect, memoryEnv, test, tier } from 'claude-code/testing'
-import type { Plugin } from 'claude-code/testing'
-
-import type { LogEntry } from '../hooks/telemetry-types'
-
-const BEARER: SessionAuthorization = { handle: 'the-handle', kind: 'bearer' }
-const ACCEPTED: HttpResponse = { status: 200, ok: true, headers: {}, text: '' }
-
-/**
- * A survey answered, as a plugin logs it.
- */
-const surveyAnswer = (): LogEntry => ({
- event: 'survey_answered',
- props: { answer: 2, seen: true },
-})
-
-/**
- * The command that has the recording plugin log an entry, typed as the
- * person would type it.
- */
-const record = (entry: LogEntry): CommandRunInput => ({
- command: 'record',
- args: JSON.stringify(entry),
- origin: { kind: 'composer' },
-})
-
-/**
- * A plugin whose `/record <entry>` logs the entry through `$.telemetry`,
- * answering "sent", or why the row was refused.
- */
-const recording: Plugin = {
- name: 'recording',
- register(on) {
- on('command.run', { command: 'record' }, ($, e) =>
- $.telemetry.log(JSON.parse(e.args)).then(
- () => ({ text: 'sent' }),
- (error: unknown) => ({ text: String(error) }),
- ),
- )
- },
-}
-
-/**
- * The batch a post to the ingest carries, as it was sent.
- */
-const batchOf = (post: Args<'http.fetch'>): unknown =>
- JSON.parse(String(post.init?.body))
-
-tier('builtin')
-
-/**
- * Answers what the telemetry plugin reads of a session signed in first
- * party, and keeps each post the ingest accepts.
- *
- * @param on the test's `on`
- * @param authorization the credential the session holds
- * @returns each post, as it was made
- */
-function firstPartySession(
- on: On,
- authorization: SessionAuthorization = BEARER,
-) {
- const posts: Args<'http.fetch'>[] = []
- on('session.id', () => ({ value: 'the-session' }))
- on('session.model', () => ({ value: 'the-model' }))
- on('session.authorize', () => ({ value: authorization }))
- on('http.fetch', ($, e) => {
- posts.push(e)
-
- return { value: ACCEPTED }
- })
-
- return posts
-}
-
-describe('telemetry', () => {
- test(
- 'a $.telemetry.log call from a plugin posts one first-party row',
- { plugins: [recording] },
- async ($, on) => {
- memoryEnv(on, { USER_TYPE: 'ant' })
- const posts = firstPartySession(on)
-
- expect(await $.command.run(record(surveyAnswer()))).toEqual({
- text: 'sent',
- })
- expect(posts.map(post => post.init)).toMatchObject([
- { method: 'POST', auth: 'the-handle' },
- ])
- expect(posts.map(batchOf)).toMatchObject([
- {
- events: [
- {
- event_data: {
- event_name: 'tengu_plugin_survey_answered',
- session_id: 'the-session',
- model: 'the-model',
- user_type: 'ant',
- },
- },
- ],
- },
- ])
- },
- )
-
- test(
- 'a row already named tengu_ is sent under its own name',
- { plugins: [recording] },
- async ($, on) => {
- memoryEnv(on, {})
- const posts = firstPartySession(on)
-
- await $.command.run(
- record({ ...surveyAnswer(), event: 'tengu_repl_diff_panel_shown' }),
- )
-
- expect(posts.map(batchOf)).toMatchObject([
- {
- events: [
- {
- event_data: {
- event_name: 'tengu_repl_diff_panel_shown',
- user_type: 'external',
- },
- },
- ],
- },
- ])
- },
- )
-
- test(
- 'nothing is sent for a person who asked not to be tracked',
- { plugins: [recording] },
- async ($, on) => {
- memoryEnv(on, { DO_NOT_TRACK: '1' })
- const posts = firstPartySession(on)
- const { text } = await $.command.run(record(surveyAnswer()))
-
- expect({ text, posts }).toEqual({ text: 'sent', posts: [] })
- },
- )
-
- test(
- 'nothing is sent on a third-party provider',
- { plugins: [recording] },
- async ($, on) => {
- memoryEnv(on, { CLAUDE_CODE_USE_BEDROCK: '1' })
- const posts = firstPartySession(on)
-
- await $.command.run(record(surveyAnswer()))
-
- expect(posts).toEqual([])
- },
- )
-
- test(
- 'a session with no first-party credential is refused, nothing sent',
- { plugins: [recording] },
- async ($, on) => {
- memoryEnv(on, {})
- const posts = firstPartySession(on, null)
- const { text } = await $.command.run(record(surveyAnswer()))
-
- expect(text).toEndWith(
- '$.telemetry.log: this session has no first-party credential to ' +
- 'authorize',
- )
- expect(posts).toEqual([])
- },
- )
-
- test(
- 'free text in a row is refused, nothing sent',
- { plugins: [recording] },
- async ($, on) => {
- memoryEnv(on, {})
- const posts = firstPartySession(on)
- const { text } = await $.command.run({
- ...record(surveyAnswer()),
- args: '{"event":"survey_answered","props":{"note":"hello world"}}',
- })
-
- expect(text).toContain('props.note: free text is refused')
- expect(posts).toEqual([])
- },
- )
-})