Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .agents/scripts/instructions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { describe, expect, it } from 'vitest'
import { git } from './lib/git.ts'
import { readJson } from './lib/state.ts'
import { REPO_ROOT } from './lib/test-repo.ts'
import { AGENT_DOCS } from './lib/tree.ts'
import { AGENT_DOCS, TEST_HELPER_PATHS } from './lib/tree.ts'

const SKILLS_DIR = join(REPO_ROOT, '.agents/skills')
const skills = readdirSync(SKILLS_DIR).filter((name) => !name.startsWith('.'))
Expand Down Expand Up @@ -144,7 +144,7 @@ it('names only test helpers that src/test-support/ or src/testing/ export', asyn
const skill = readFileSync(join(SKILLS_DIR, 'write-tests/SKILL.md'), 'utf8')
const section = skill.split('## Helpers')[1]?.split('\n## ')[0] ?? ''
const named = [...section.matchAll(/`(\w+)`/g)].map((match) => match[1] ?? '')
const modules = ['src/test-support', 'src/testing'].flatMap((dir) =>
const modules = TEST_HELPER_PATHS.flatMap((dir) =>
readdirSync(join(REPO_ROOT, dir))
.filter((file) => file.endsWith('.ts') && !file.endsWith('.test.ts'))
.map((file) => join(REPO_ROOT, dir, file)),
Expand Down
22 changes: 20 additions & 2 deletions .agents/scripts/lib/steps.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'
import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { basename, join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
Expand Down Expand Up @@ -141,7 +141,7 @@ describe('verify covers CI', () => {
})

it('runs the build and the tests with CI=true, as GitHub Actions does', () => {
for (const name of ['build', 'tests']) {
for (const name of ['build', 'tests', 'tests:agents']) {
const step = VERIFY_STEPS.find((candidate) => candidate.name === name)
expect(step?.env, name).toEqual({ CI: 'true' })
}
Expand All @@ -153,6 +153,24 @@ describe('verify covers CI', () => {
expect(env).toEqual({ PATH: '/bin' })
})

it('runs the agent tooling tests with their own config, after the package tests', () => {
const step = VERIFY_STEPS.find((candidate) => candidate.name === 'tests:agents')
expect(step?.args).toEqual(['run', '--config', 'vitest.agents.config.ts'])
expect(step?.onlyWhenChanged).toContain('vitest.agents.config.ts')
expect(step?.waitFor).toEqual(['tests'])
})

it('runs the agent tooling tests only for paths that exist', () => {
const step = VERIFY_STEPS.find((candidate) => candidate.name === 'tests:agents')
const paths = step?.onlyWhenChanged ?? []
expect(paths.length).toBeGreaterThan(0)
// hook-wiring.test.ts checks .cursor/ holds no hooks file, so adding one runs the tests.
const missing = paths.filter(
(path) => path !== '.cursor/' && !existsSync(join(REPO_ROOT, path)),
)
expect(missing).toEqual([])
})

it('starts the tests only once the build has written dist/', () => {
const tests = VERIFY_STEPS.find((candidate) => candidate.name === 'tests')
expect(tests?.waitFor).toContain('build')
Expand Down
28 changes: 28 additions & 0 deletions .agents/scripts/lib/steps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { existsSync } from 'node:fs'
import { join } from 'node:path'
import { readJson } from './state.ts'
import { listSome } from './text.ts'
import { AGENT_DOCS, TEST_HELPER_PATHS } from './tree.ts'
import type { Step } from './verify.ts'

const bin = (tool: string) => `node_modules/.bin/${tool}`
Expand All @@ -26,6 +27,32 @@ export const VERIFY_STEPS: Step[] = [
env: CI_ENV,
waitFor: ['build'],
},
// The agent tooling's tests, for changes to the tooling and to what it reads: its own files and
// config, the hook configs, the agent docs and the test helpers they name, the workflows and
// package.json scripts verify mirrors, and the lefthook the hook tests install from the lockfile.
// They start once the package's tests have finished: run side by side, the two vitest pools
// slow each other down enough for the hook tests to time out.
{
name: 'tests:agents',
command: bin('vitest'),
args: ['run', '--config', 'vitest.agents.config.ts'],
env: CI_ENV,
waitFor: ['tests'],
onlyWhenChanged: [
'.agents/',
'vitest.agents.config.ts',
...AGENT_DOCS,
'.claude/',
'.codex/',
// hook-wiring.test.ts checks that no Cursor hooks file appears.
'.cursor/',
'lefthook.yml',
'.github/workflows/',
'package.json',
'package-lock.json',
...TEST_HELPER_PATHS,
],
},
]

/**
Expand All @@ -39,6 +66,7 @@ export const CI_EQUIVALENTS: { run: string; steps: string[]; why?: string }[] =
{ run: 'npm run check', steps: ['lint', 'format'] },
{ run: 'npm run build', steps: ['build'] },
{ run: 'npm test', steps: ['tests'] },
{ run: 'npm run test:agents', steps: ['tests:agents'] },
]

/**
Expand Down
3 changes: 3 additions & 0 deletions .agents/scripts/lib/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ export const CHECKED_WORKFLOWS = ['.github/workflows/lint.yml', '.github/workflo
/** Agent instructions outside .agents/. instructions.test.ts checks every reference in them. */
export const AGENT_DOCS = new Set(['AGENTS.md', 'CODEBASE.md', 'docs/agents.md'])

/** Where the test helpers the write-tests skill names live. instructions.test.ts imports them. */
export const TEST_HELPER_PATHS = ['src/test-support/', 'src/testing/']

/** The kind of file, as far as local checks are concerned. */
export type FileKind = 'docs' | 'unchecked' | 'code'

Expand Down
66 changes: 65 additions & 1 deletion .agents/scripts/lib/verify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,11 @@ const pass = (name: string, extra: Partial<Step> = {}): Step => ({
args: ['-c', `echo ${name} ok`],
...extra,
})
const fail = (name: string): Step => ({
const fail = (name: string, extra: Partial<Step> = {}): Step => ({
name,
command: 'sh',
args: ['-c', 'i=1; while [ $i -le 40 ]; do echo "line $i"; i=$((i + 1)); done; exit 3'],
...extra,
})

const verify = (steps: Step[], options: { base?: string | null } = {}) =>
Expand Down Expand Up @@ -167,6 +168,69 @@ describe('a code change', () => {
})
})

describe('a step that runs only when what it reads changed', () => {
const tools = (extra: Partial<Step> = {}) =>
fail('tools', { onlyWhenChanged: ['.agents/', 'tools.config.ts'], ...extra })

it('is skipped, and counts as passed, when nothing it reads changed', async () => {
repo.write('src/a.ts', 'export const a = 2\n')
expect(await verify([pass('lint'), tools()])).toEqual({ ok: true, recorded: true })
expect(lines).toContain(
'- tools skipped: nothing it reads changed since main; CI runs it on every pull request',
)
expect(lines.some((line) => line.startsWith('✗ tools'))).toBe(false)
})

it('runs when a path it reads changed', async () => {
repo.write('src/a.ts', 'export const a = 2\n')
repo.write('.agents/scripts/tool.ts', 'export const tool = 1\n')
expect(await verify([pass('lint'), tools()])).toEqual({ ok: false, recorded: false })
expect(lines.some((line) => line.startsWith('✗ tools (exit 3'))).toBe(true)
})

it('runs when a file it reads by name changed', async () => {
repo.write('tools.config.ts', 'export default {}\n')
expect(await verify([tools()])).toEqual({ ok: false, recorded: false })
expect(lines.some((line) => line.startsWith('✗ tools (exit 3'))).toBe(true)
})

it('still runs the steps that wait for it or run after it', async () => {
repo.write('src/a.ts', 'export const a = 2\n')
const steps = [
tools(),
pass('after-tools', { after: 'tools' }),
pass('waits-for-tools', { waitFor: ['tools'] }),
]
expect(await verify(steps)).toEqual({ ok: true, recorded: true })
expect(lines.some((line) => line.startsWith('✓ after-tools'))).toBe(true)
expect(lines.some((line) => line.startsWith('✓ waits-for-tools'))).toBe(true)
})

it('runs when nothing changed, since verify then checks the whole tree', async () => {
expect(await verify([tools()])).toEqual({ ok: false, recorded: false })
expect(lines[0]).toBe('No changes since main; checking the tree anyway.')
expect(lines.some((line) => line.startsWith('✗ tools (exit 3'))).toBe(true)
})

it('runs when a file was deleted, since the agent docs may name it', async () => {
rmSync(join(repo.dir, 'src/a.ts'))
expect(await verify([tools()])).toEqual({ ok: false, recorded: false })
expect(lines.some((line) => line.startsWith('✗ tools (exit 3'))).toBe(true)
})

it('runs when a file was renamed, since the agent docs may name the old path', async () => {
repo.git(['mv', 'src/a.ts', 'src/renamed.ts'])
expect(await verify([tools()])).toEqual({ ok: false, recorded: false })
expect(lines.some((line) => line.startsWith('✗ tools (exit 3'))).toBe(true)
})

it('runs without a default branch, when there is nothing to compare with', async () => {
repo.write('src/a.ts', 'export const a = 2\n')
expect(await verify([tools()], { base: null })).toEqual({ ok: false, recorded: false })
expect(lines.some((line) => line.startsWith('✗ tools (exit 3'))).toBe(true)
})
})

describe('what counts as a change', () => {
it('sees an untracked file as a change', async () => {
repo.write('src/new.ts', 'new\n')
Expand Down
34 changes: 31 additions & 3 deletions .agents/scripts/lib/verify.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { spawn } from 'node:child_process'
import { createWriteStream, mkdirSync, readFileSync } from 'node:fs'
import { createWriteStream, existsSync, mkdirSync, readFileSync } from 'node:fs'
import { join, relative } from 'node:path'
import { cleanGitEnv, git } from './git.ts'
import { clearVerified, readVerified, safeName, stateDir, writeVerified } from './state.ts'
Expand All @@ -20,6 +20,12 @@ export type Step = {
after?: string
/** Starts only after these steps have finished, passed or not: they share files on disk. */
waitFor?: string[]
/**
* Runs only when a path changed since the base starts with one of these, or a file was deleted
* or renamed (the agent docs may name it). With nothing changed it runs, as every step does. CI
* runs the step on every pull request regardless.
*/
onlyWhenChanged?: string[]
env?: Record<string, string>
}

Expand All @@ -39,10 +45,12 @@ const LOG_TAIL_LINES = 30
export async function runVerify(options: VerifyOptions): Promise<VerifyResult> {
const { root, steps, base, baseName = 'main', out = console.log } = options

// Undefined without a base: with nothing to compare against, every step runs.
let changes: string[] | undefined
if (base === undefined) {
out(`No ${baseName} branch found, so checking the whole tree.`)
} else {
const changes = changedSince(root, base)
changes = changedSince(root, base)
const kinds = new Set(
changes.map((path) => (needsChecks(root, path) ? 'code' : classify(path))),
)
Expand Down Expand Up @@ -76,7 +84,7 @@ export async function runVerify(options: VerifyOptions): Promise<VerifyResult> {
clearVerified(root)
const before = snapshot(root)

const passed = await runSteps(root, steps, logDirFor(root), out)
const passed = await runSteps(root, steps, { changes, baseName }, logDirFor(root), out)
if (!passed) return { ok: false, recorded: false }

const after = snapshot(root)
Expand All @@ -103,16 +111,36 @@ function logDirFor(root: string): string {
return dir
}

/** Whether a step with `onlyWhenChanged` has nothing to read in these changes. */
function nothingToRead(root: string, step: Step, changes: string[] | undefined): boolean {
const prefixes = step.onlyWhenChanged
// With nothing changed, verify checks the whole tree, so every step runs.
if (!prefixes || changes === undefined || changes.length === 0) return false
// A path gone from disk was deleted or renamed, and the agent docs may name it.
if (changes.some((path) => !existsSync(join(root, path)))) return false
return !changes.some((path) => prefixes.some((prefix) => path.startsWith(prefix)))
}

async function runSteps(
root: string,
steps: Step[],
since: { changes: string[] | undefined; baseName: string },
logDir: string,
out: (line: string) => void,
): Promise<boolean> {
const results = new Map<string, Promise<boolean>>()
const start = (step: Step): Promise<boolean> => {
const existing = results.get(step.name)
if (existing) return existing
// A skipped step counts as passed, so the steps after it still run.
if (nothingToRead(root, step, since.changes)) {
out(
`- ${step.name} skipped: nothing it reads changed since ${since.baseName}; CI runs it on every pull request`,
)
const skipped = Promise.resolve(true)
results.set(step.name, skipped)
return skipped
}
const find = (name: string) => {
const found = steps.find((s) => s.name === name)
if (!found) throw new Error(`step ${step.name} runs after unknown ${name}`)
Expand Down
2 changes: 1 addition & 1 deletion .agents/scripts/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"lib": ["es2023"],
"types": ["node", "vitest/globals"]
"types": ["node"]
},
"include": ["."]
}
5 changes: 5 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ name: Tests

on:
pull_request:
push:
branches: [main, next]

permissions:
contents: read
Expand Down Expand Up @@ -32,3 +34,6 @@ jobs:

- name: Run tests
run: npm test

- name: Run agent tooling tests
run: npm run test:agents
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ npm run dev # watch mode
npm run type-check # tsc --noEmit for src/ and the agent tooling (.agents/scripts)
npm run check # oxlint + oxfmt --check
npm run fix # oxlint --fix + oxfmt
npm test # vitest run
npm test # vitest run: the package's own tests, which publishing runs
npm run test:agents # the agent tooling's tests (.agents/scripts), for changes to the tooling
npm run verify # every check CI runs (lint, format, types, build, tests)
```

Expand Down
16 changes: 11 additions & 5 deletions CODEBASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,10 @@ that needs them (`commander`, `marked`, `marked-terminal-renderer`,
├─ README.md # Public API docs ("What's in it" table + usage)
├─ tsconfig.json # Includes src + tests (type-check, IDE)
├─ tsconfig.build.json # Excludes *.test.ts + test-support/ + __mocks__/ (build/dev)
├─ vitest.config.ts # { globals, root: 'src', include: ['**/*.test.ts'] }
├─ vitest.config.ts # { globals, root: 'src', include: ['**/*.test.ts'] } (npm test)
├─ vitest.agents.config.ts # .agents/scripts tests (npm run test:agents)
├─ lefthook.yml # Git hooks: branch guard; pre-commit lint, format, types;
│ # pre-push tests
│ # pre-push npm test
└─ release.config.js # semantic-release config
```

Expand Down Expand Up @@ -226,8 +227,11 @@ helpers, not suites.

## Testing

- **Runner:** vitest. `npm test` (one-shot, including the agent tooling's tests in
`.agents/scripts/`), `npm run test:watch`.
- **Runner:** vitest. `npm test` (one-shot: the package's own tests, which
publishing runs), `npm run test:watch`.
`npm run test:agents` runs the agent tooling's tests in `.agents/scripts/`;
CI runs them on every pull request and every push to `main` and `next`, and
`npm run verify` when something they read changed.
- **Location:** colocated `*.test.ts` next to the module under test.
- **Account suites:** import fixtures + `buildTokenStore` / `buildSingleEntryStore`
from `testing/accounts.js` and the spy/scaffold helpers from
Expand Down Expand Up @@ -262,7 +266,9 @@ helpers, not suites.
`prepare` script. `pre-commit` refuses commits on `main`, then lints and
formats staged files and runs the type check; `commit-msg` repeats the
branch rule for empty commits; `pre-push` refuses pushes to `main`, then
runs the tests. See `docs/agents.md`.
runs `npm test`, the package's tests only (the agent tooling's tests run in
CI, and in `npm run verify` when something they read changed). See
`docs/agents.md`.

## Conventions (quick)

Expand Down
5 changes: 3 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@
npm install
```

This installs dependencies and registers lefthook git hooks through the `prepare` script: commits and pushes to `main` are refused, pre-commit lints, formats and type-checks, pre-push runs the tests.
This installs dependencies and registers lefthook git hooks through the `prepare` script: commits and pushes to `main` are refused, pre-commit lints, formats and type-checks, pre-push runs `npm test`, the package's tests only. The agent tooling's tests run in CI, and in `npm run verify` when something they read changed.

## Scripts

- `npm run build` — compile TypeScript to `dist/`
- `npm run dev` — watch-mode build
- `npm test` — run vitest
- `npm test`: run the package's tests, which publishing also runs
- `npm run test:agents`: run the agent tooling's tests (`.agents/scripts`), for changes to the tooling
- `npm run type-check` — typecheck without emit
- `npm run check` — oxlint + oxfmt --check
- `npm run fix` — oxlint --fix + oxfmt
Expand Down
Loading
Loading