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: tests sit in one describe each, diff's shared inputs in a fixtures folder, every decision and duplicate named
poteat936b92907ce1
diff --git a/mods/diff/tests/boot-probe.test.ts b/mods/diff/tests/boot-probe.test.tsindex 8fbedd94..3ddf822f 100644--- a/mods/diff/tests/boot-probe.test.ts+++ b/mods/diff/tests/boot-probe.test.ts@@ -1,58 +1,41 @@-import type {- CommandRunInput,- ProcessRunResult,- SessionStartInput,-} from 'claude-code'-import { clock, expect, test, tier } from 'claude-code/testing'+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')-const SESSION: SessionStartInput = {- surface: 'terminal',- isInteractive: true,- cwd: '/work',-}-const DIFF: CommandRunInput = {- command: 'diff',- args: '',- origin: { kind: 'composer' },-}-const NOT_A_REPOSITORY: ProcessRunResult = {- exitCode: 128,- stdout: '',- stderr: 'fatal: not a git repository',-}-const GIT_TIMEOUT_MS = 5000-const GIT_HUNG = `git aborted: still running after ${GIT_TIMEOUT_MS}ms`--test('/diff at boot joins the boot probe, then asks again', async ($, on) => {- const probes: (readonly string[])[] = []- on('session.start', ($, e) => ({ cwd: e.cwd }))- on('command.register', ($, e) => ({ value: { command: e.name } }))- on('process.run', async ($, e) => {- probes.push(e.argv)-- if (probes.length === 1) {- await clock.sleep(GIT_TIMEOUT_MS)-- return { deny: GIT_HUNG }- }-- return { value: NOT_A_REPOSITORY }- })+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(SESSION)- await clock.advance(0)- const ran = $.command.run(DIFF)- await clock.advance(0)+ 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)+ expect(probes, 'the boot probe, which /diff joined').toHaveLength(1)- await clock.advance(GIT_TIMEOUT_MS)- await booting+ await clock.advance(Limits.GIT_TIMEOUT_MS)+ await booting- expect(await ran).toEqual({- text: expect.stringContaining("isn't in a git repository"),+ expect(await ran).toEqual({+ text: expect.stringContaining("isn't in a git repository"),+ })+ expect(probes, 'then one more of its own').toHaveLength(2)})- 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.tsindex 57f79206..e058c24b 100644--- a/mods/diff/tests/command.test.ts+++ b/mods/diff/tests/command.test.ts@@ -1,88 +1,77 @@-import type {- CommandRunInput,- ProcessRunResult,- SessionStartInput,-} from 'claude-code'-import { expect, test, tier } from 'claude-code/testing'+import { describe, expect, test, tier } from 'claude-code/testing'-tier('builtin')+import Fixtures from './fixtures'-const SESSION: SessionStartInput = {- surface: 'terminal',- isInteractive: true,- cwd: '/work',-}-const DIFF: CommandRunInput = {- command: 'diff',- args: '',- origin: { kind: 'composer' },-}-const NOT_A_REPOSITORY: ProcessRunResult = {- exitCode: 128,- stdout: '',- stderr: 'fatal: not a git repository',-}const BUILTIN_HOLDS = '"/diff" refused: it is the built-in /diff'-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: NOT_A_REPOSITORY }))- on('ui.open', ($, e, next) => {- opened.push(e.id)- return next(e)- })+tier('builtin')- await $.session.start(SESSION)- const { text } = await $.command.run(DIFF)+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)- expect(text).toContain("isn't in a git repository")- expect(opened).toEqual([])-})+ return next(e)+ })-test('a git that never answers is not "no repository"', async ($, on) => {- on('session.start', ($, e) => ({ cwd: e.cwd }))- on('command.register', ($, e) => ({ value: { command: e.name } }))- on('process.run', () => ({- deny: 'git aborted: still running after 5000ms',- }))+ await $.session.start(Fixtures.SESSION)+ const { text } = await $.command.run(Fixtures.DIFF)- await $.session.start(SESSION)- const { text } = await $.command.run(DIFF)+ expect(text).toContain("isn't in a git repository")+ expect(opened).toEqual([])+ })- expect(text).toContain("git didn't answer")-})+ 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',+ }))-test('with the built-in holding /diff, the plugin 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)+ const { text } = await $.command.run(Fixtures.DIFF)++ expect(text).toContain("git didn't answer")})- await $.session.start(SESSION)+ 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)- expect(await $.command.run(DIFF)).toEqual({ text: 'the built-in /diff ran' })- expect(logged).toEqual([])-})+ return { value: undefined }+ })++ await $.session.start(Fixtures.SESSION)-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 }+ expect(await $.command.run(Fixtures.DIFF)).toEqual({+ text: 'the built-in /diff ran',+ })+ expect(logged).toEqual([])})- await $.session.start(SESSION)+ 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)- expect(logged).toEqual([- 'could not register /diff: diff: $.command.register: 32 commands are ' +- 'registered already; the diff panel is unavailable this session',- ])+ 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/diff.ts b/mods/diff/tests/fixtures/diff.tsnew file mode 100644index 00000000..51ccac22--- /dev/null+++ b/mods/diff/tests/fixtures/diff.ts@@ -0,0 +1,10 @@+import type { CommandRunInput } from 'claude-code'++/**+ * The command as the person types it, with no arguments.+ */+export const DIFF: CommandRunInput = {+ command: 'diff',+ args: '',+ origin: { kind: 'composer' },+}diff --git a/mods/diff/tests/fixtures/index.ts b/mods/diff/tests/fixtures/index.tsnew file mode 100644index 00000000..bd81c943--- /dev/null+++ b/mods/diff/tests/fixtures/index.ts@@ -0,0 +1,6 @@+export * from './diff.js'+export * from './not-a-repository.js'+export * from './session.js'+export * from './starts-session.js'++export * as default from '.'diff --git a/mods/diff/tests/fixtures/not-a-repository.ts b/mods/diff/tests/fixtures/not-a-repository.tsnew file mode 100644index 00000000..67ae31a8--- /dev/null+++ b/mods/diff/tests/fixtures/not-a-repository.ts@@ -0,0 +1,10 @@+import type { ProcessRunResult } from 'claude-code'++/**+ * How git fails in a directory outside any repository.+ */+export const NOT_A_REPOSITORY: ProcessRunResult = {+ exitCode: 128,+ stdout: '',+ stderr: 'fatal: not a git repository',+}diff --git a/mods/diff/tests/fixtures/session.ts b/mods/diff/tests/fixtures/session.tsnew file mode 100644index 00000000..c387d8e7--- /dev/null+++ b/mods/diff/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/diff/tests/fixtures/starts-session.ts b/mods/diff/tests/fixtures/starts-session.tsnew file mode 100644index 00000000..291dc0f5--- /dev/null+++ b/mods/diff/tests/fixtures/starts-session.ts@@ -0,0 +1,12 @@+import type { On } from 'claude-code'++/**+ * Answers what every /diff session asks first: its start, with its own+ * directory, and each command it registers, under the name asked for.+ *+ * @param on the test's `on`+ */+export function startsSession(on: On) {+ on('session.start', ($, e) => ({ cwd: e.cwd }))+ on('command.register', ($, e) => ({ value: { command: e.name } }))+}diff --git a/mods/diff/tests/pane.test.ts b/mods/diff/tests/pane.test.tsindex 168d041b..755cf373 100644--- a/mods/diff/tests/pane.test.ts+++ b/mods/diff/tests/pane.test.ts@@ -5,10 +5,10 @@ import type {ProcessRunResult,RenderElement,RenderInput,- SessionStartInput,} from 'claude-code'import {clock,+ describe,expect,memoryStore,test,@@ -16,18 +16,8 @@ import {tier,} from 'claude-code/testing'-tier('builtin')+import Fixtures from './fixtures'-const SESSION: SessionStartInput = {- surface: 'terminal',- isInteractive: true,- cwd: '/work',-}-const DIFF: CommandRunInput = {- command: 'diff',- args: '',- origin: { kind: 'composer' },-}const CLEAR: CommandRunInput = {command: 'clear',args: '',@@ -64,10 +54,9 @@ const HINT_DRAWN: RenderElement = {type: 'Text',children: ['? for shortcuts'],}-/**- * A repository at /work with one changed file, as git's output for each- * invocation whose command line holds the key.+ * 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',@@ -76,6 +65,13 @@ const REPOSITORY: Readonly<Record<string, string>> = {'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@@ -87,101 +83,114 @@ function gitIn(argv: readonly string[]): ProcessRunResult {return found? { exitCode: 0, stdout: found[1], stderr: '' }- : { exitCode: 128, stdout: '', stderr: 'fatal: not a git repository' }+ : Fixtures.NOT_A_REPOSITORY}/**- * A session in that repository: /diff registers, git answers, the store- * starts empty, the engine draws the prompt's hint, and what the plugin- * asks of the world (each git run, each pane opened or closed) is kept.+ * 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: Args<'ui.open'>[] = []- const closed: Args<'ui.close'>[] = []- on('session.start', ($, e) => ({ cwd: e.cwd }))- on('command.register', ($, e) => ({ value: { command: e.name } }))+ 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', ($, e) => {- opened.push(e)- return { value: undefined }- })- on('ui.close', ($, e) => {- closed.push(e)- return { value: undefined }- })+ 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, closed }+ return { runs, opened: opened.kept, closed: closed.kept }}-test('/diff opens the pane over the changes in the session', async ($, on) => {- const world = inRepository(on)+describe('pane', () => {+ test('/diff opens the pane over the session changes', async ($, on) => {+ const world = inRepository(on)- await $.session.start(SESSION)+ await $.session.start(Fixtures.SESSION)- expect(await $.command.run(DIFF)).toEqual({})- expect(world.opened.map(pane => pane.id)).toEqual(['diff'])+ expect(await $.command.run(Fixtures.DIFF)).toEqual({})+ expect(world.opened.map(pane => pane.id)).toEqual(['diff'])- await clock.advance(1000)- const drawn = textOf(await $.ui.render(PANE))+ await clock.advance(SETTLE_MS)+ const drawn = textOf(await $.ui.render(PANE))- expect(drawn).toContain('1 file changed')- expect(drawn).toContain('app.ts')-})--test('every git child is pinned to the repository and reads the C locale', async ($, on) => {- const world = inRepository(on)-- await $.session.start(SESSION)- await $.command.run(DIFF)- await clock.advance(1000)- 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' } })- }-})+ expect(drawn).toContain('1 file changed')+ expect(drawn).toContain('app.ts')+ })-test('the first edit Claude makes opens the pane on a wide terminal', async ($, on) => {- const world = inRepository(on)- on('tool.call', () => ({ result: 'edited' }))-- await $.session.start(SESSION)- await $.ui.render(HINT)- await $.tool.call({- tool: 'Edit',- file_path: '/work/app.ts',- old_string: '1',- new_string: '2',+ 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' } })+ }})- await clock.advance(1000)- expect(world.opened.map(pane => pane.id)).toEqual(['diff'])-})+ 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' }, () => ({}))+ test('/clear closes the pane it finds open', async ($, on) => {+ const world = inRepository(on)+ on('command.run', { command: 'clear' }, () => ({}))- await $.session.start(SESSION)- await $.command.run(DIFF)- await $.command.run(CLEAR)+ await $.session.start(Fixtures.SESSION)+ await $.command.run(Fixtures.DIFF)+ await $.command.run(CLEAR)- expect(world.closed.map(pane => pane.id)).toEqual(['diff'])+ expect(world.closed.map(pane => pane.id)).toEqual(['diff'])+ })})diff --git a/mods/sec-default/tests/sec-default.test.ts b/mods/sec-default/tests/sec-default.test.tsindex 0f56c5c3..1b5237c9 100644--- a/mods/sec-default/tests/sec-default.test.ts+++ b/mods/sec-default/tests/sec-default.test.ts@@ -6,8 +6,8 @@ import type {Settings,ToolInfo,} from 'claude-code'+import { describe, expect, test, tier } from 'claude-code/testing'import type { Plugin } from 'claude-code/testing'-import { expect, test, tier } from 'claude-code/testing'tier('prepend')@@ -24,7 +24,7 @@ const TOOLS_COMMAND: CommandRunInput = {const ALLOWLIST: Settings = { allowedMcpServers: [{ serverName: 'corp' }] }const NO_ALLOWLIST: Settings = { permissions: { allow: [] } }const MEMORY: PromptSectionInput = { name: 'memory', text: 'the org says hi' }-const TOOLS: ToolInfo[] = [+const TOOLS: readonly ToolInfo[] = [{name: 'mcp__corp__search',description: 'Searches the corp wiki.',@@ -53,6 +53,13 @@ const registering = (name: string, tier?: Plugin['tier']): Plugin => ({},})+/**+ * 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.@@ -63,7 +70,7 @@ function toolsRegistered(on: On) {on('tool.register', ($, e, next) => {registered.push(next.origin.plugin)- return { value: { tool: `mcp__plugin_${next.origin.plugin}__${e.name}` } }+ return registeredToolOf(next.origin.plugin, e.name)})return registered@@ -78,14 +85,16 @@ const relabeling: Plugin = {register(on) {on('tool.list', async ($, e, next) => {const listed = await next(e)+ const { value } = listed+ const isListed = value !== undefined- return listed.value === undefined- ? listed- : {- value: listed.value+ return isListed+ ? {+ value: value.filter(tool => !tool.name.startsWith('mcp__corp__')).map(tool => ({ ...tool, description: 'relabeled' })),}+ : listed})},}@@ -128,69 +137,71 @@ const signing: Plugin = {},}-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 skips the plugins the person installed, never the organization ones',- { plugins: [dropping, signing] },- async ($, on) => {- on('prompt.section', ($, e) => ({ text: e.text }))-- expect(await $.prompt.section(MEMORY)).toEqual({- text: 'the org says hi (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/telemetry.test.ts b/mods/telemetry/tests/telemetry.test.tsindex 958f8799..d385242e 100644--- a/mods/telemetry/tests/telemetry.test.ts+++ b/mods/telemetry/tests/telemetry.test.ts@@ -5,23 +5,25 @@ import type {On,SessionAuthorization,} from 'claude-code'+import { describe, expect, memoryEnv, test, tier } from 'claude-code/testing'import type { Plugin } from 'claude-code/testing'-import { expect, memoryEnv, test, tier } from 'claude-code/testing'import type { LogEntry } from '../hooks/telemetry-types'-tier('builtin')-const BEARER: SessionAuthorization = { handle: 'the-handle', kind: 'bearer' }const ACCEPTED: HttpResponse = { status: 200, ok: true, headers: {}, text: '' }-const SURVEY: LogEntry = {+/**+ * A survey answered, as a plugin logs it.+ */+const surveyAnswer = (): LogEntry => ({event: 'survey_answered',props: { answer: 2, seen: true },-}+})/**- * `/record <entry>`, which the recording plugin answers.+ * The command that has the recording plugin log an entry, typed as the+ * person would type it.*/const record = (entry: LogEntry): CommandRunInput => ({command: 'record',@@ -46,8 +48,20 @@ const recording: Plugin = {}/**- * A first-party session: its id and model, the credential it holds, and- * the ingest accepting each row, each post kept as it was made.+ * 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,@@ -66,124 +80,117 @@ function firstPartySession(return posts}-/**- * The batch a post to the ingest carries, as it was sent.- */-function batchOf(post: Args<'http.fetch'>): unknown {- return JSON.parse(String(post.init?.body))-}--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(SURVEY))).toEqual({- text: 'sent',- })- expect(posts).toHaveLength(1)-- const [post] = posts-- expect(post.init).toMatchObject({ method: 'POST', auth: 'the-handle' })- expect(batchOf(post)).toMatchObject({- events: [+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([{- event_data: {- event_name: 'tengu_plugin_survey_answered',- session_id: 'the-session',- model: 'the-model',- user_type: 'ant',- },+ 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({ ...SURVEY, 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(+ '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)-- expect(await $.command.run(record(SURVEY))).toEqual({- text: 'sent',- })- expect(posts).toEqual([])- },-)--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(SURVEY))-- 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(SURVEY))-- 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(SURVEY),- args: '{"event":"survey_answered","props":{"note":"hello world"}}',- })-- expect(text).toContain('props.note: free text is refused')- expect(posts).toEqual([])- },-)+ ],+ },+ ])+ },+ )++ 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([])+ },+ )+})