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
12 changes: 8 additions & 4 deletions .agents/scripts/instructions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { basename, dirname, join, relative, resolve } from 'node:path'
import { describe, expect, it } from 'vitest'
import { git } from './lib/git.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 @@ -149,10 +149,14 @@ it('names only test helpers that src/test-support/ or @todoist/cli-core/testing
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 supportDir = join(REPO_ROOT, 'src/test-support')
const local = readdirSync(supportDir).flatMap((file) =>
const helperFiles = TEST_HELPER_PATHS.flatMap((path) => {
const full = join(REPO_ROOT, path)
if (!lstatSync(full).isDirectory()) return [full]
return readdirSync(full).map((file) => join(full, file))
})
const local = helperFiles.flatMap((file) =>
[
...readFileSync(join(supportDir, file), 'utf8').matchAll(
...readFileSync(file, 'utf8').matchAll(
/^export (?:async )?(?:function|const|type) (\w+)/gm,
),
].map((match) => match[1]),
Expand Down
16 changes: 15 additions & 1 deletion .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,6 +141,20 @@ describe('verify covers CI', () => {
const step = (name: string) => VERIFY_STEPS.find((candidate) => candidate.name === name)
expect(step('tests')?.waitFor).toContain('build')
expect(step('skill-sync')?.waitFor).toContain('tests')
// package-contents.test.ts packs the package, dist/ included.
expect(step('tests:agents')?.waitFor).toEqual(expect.arrayContaining(['build', 'tests']))
})

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

Expand Down
32 changes: 32 additions & 0 deletions .agents/scripts/lib/steps.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { existsSync } from 'node:fs'
import { join } from 'node:path'
import { readJson } from './state.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 @@ -27,6 +28,36 @@ export const VERIFY_STEPS: Step[] = [
waitFor: ['tests'],
env: CI_ENV,
},
// The agent tooling's own tests, apart from the package's. They start once the package's tests
// have finished: package-contents.test.ts packs the package, dist/ included, which the build
// and src/index.integration.test.ts write, and two vitest pools side by side slow each other
// into timeouts.
{
name: 'tests:agents',
command: bin('vitest'),
args: ['run', '--config', 'vitest.agents.config.ts'],
env: CI_ENV,
waitFor: ['build', 'tests'],
// Everything those tests read: the tooling and its tests, the docs and skills
// instructions.test.ts checks (and the test helpers they name), the workflows and scripts
// steps.test.ts compares, the hook configs and Pi extension the tooling's tests run, and
// the dependencies and TypeScript config they run with.
onlyWhenChanged: [
'.agents/',
'vitest.agents.config.ts',
...AGENT_DOCS,
...TEST_HELPER_PATHS,
'.github/workflows/',
'package.json',
'package-lock.json',
'tsconfig.json',
'lefthook.yml',
'.claude/',
'.codex/',
'.cursor/',
'.pi/',
],
},
]

/**
Expand All @@ -40,6 +71,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'] },
{ run: 'npm run check:skill-sync', steps: ['skill-sync'] },
{
run: 'gh skill publish --dry-run',
Expand Down
4 changes: 2 additions & 2 deletions .agents/scripts/lib/test-repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export const REPO_ROOT = CHECKOUT_ROOT

/** Environment for a test process: no hook variables, no user git config, no CI exemption. */
export function isolatedEnv(overrides: Record<string, string | undefined> = {}): NodeJS.ProcessEnv {
// Clears the variables git exports to hooks. Left in place, a git command in a test would
// act on the real repository: `npm test` runs inside the pre-push hook.
// Clears the variables git exports to hooks. Left in place, a git command in a test run from
// inside a hook would act on the real repository.
const env = cleanGitEnv()
// DISABLE_AGENT_GUARD and LEFTHOOK=0 may be set by the person or agent running the tests; they
// would turn off what the tests check.
Expand Down
6 changes: 6 additions & 0 deletions .agents/scripts/lib/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,12 @@ export const CHECKED_WORKFLOWS = [
/** 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'])

/**
* The files and folders holding the test helpers the write-tests skill may name.
* instructions.test.ts reads their exports.
*/
export const TEST_HELPER_PATHS = ['src/test-support/']

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

Expand Down
66 changes: 66 additions & 0 deletions .agents/scripts/lib/verify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,72 @@ describe('a code change', () => {
expect(readVerified(repo.dir)).toBeUndefined()
})

describe('a step that runs only when what it reads changed', () => {
// Fails if it runs, so a pass shows it was skipped.
const tooling = (extra: Partial<Step> = {}): Step => ({
...fail('tests:agents'),
onlyWhenChanged: ['.agents/', 'vitest.agents.config.ts'],
...extra,
})

it('is skipped, and counts as passed, when nothing it reads changed', async () => {
expect(await verify([pass('lint'), tooling()])).toEqual({ ok: true, recorded: true })
expect(lines).toContain(
'- tests:agents skipped: nothing it reads changed since main; CI runs it on every pull request',
)
expect(lines.some((line) => line.includes('✗ tests:agents'))).toBe(false)
})

it('runs when a path it reads changed', async () => {
repo.write('vitest.agents.config.ts', 'export default {}\n')
repo.git(['add', '.'])
repo.git(['commit', '--quiet', '-m', 'config'])
repo.write('.agents/scripts/new.ts', 'export const n = 1\n')
expect(await verify([tooling({ args: ['-c', 'echo ok'] })])).toEqual({
ok: true,
recorded: true,
})
expect(lines.some((line) => line.startsWith('✓ tests:agents'))).toBe(true)
})

it('still runs the steps that wait for it or run after it', async () => {
const result = await verify([
tooling(),
pass('skill-sync', { waitFor: ['tests:agents'] }),
pass('report', { after: 'tests:agents' }),
])
expect(result).toEqual({ ok: true, recorded: true })
expect(lines.some((line) => line.startsWith('✓ skill-sync'))).toBe(true)
expect(lines.some((line) => line.startsWith('✓ report'))).toBe(true)
})

it('runs when nothing changed, since verify checks the tree anyway', async () => {
repo.git(['commit', '--quiet', '-am', 'change a'])
const head = repo.git(['rev-parse', 'HEAD']).stdout.trim()
const result = await verify([tooling({ args: ['-c', 'echo ok'] })], { base: head })
expect(result).toEqual({ ok: true, recorded: true })
expect(lines[0]).toBe('No changes since main; checking the tree anyway.')
expect(lines.some((line) => line.startsWith('✓ tests:agents'))).toBe(true)
})

// The agent docs may name the file that went, and a test checks every name they hold.
it.each([
['deleted', () => rmSync(join(repo.dir, 'src/a.ts'))],
['renamed', () => repo.git(['mv', 'src/a.ts', 'src/b.ts'])],
])('runs when a file was %s', async (_kind, change) => {
change()
const result = await verify([tooling({ args: ['-c', 'echo ok'] })])
expect(result).toEqual({ ok: true, recorded: true })
expect(lines.some((line) => line.startsWith('✓ tests:agents'))).toBe(true)
})

it('runs without a default branch to compare with', async () => {
const result = await verify([tooling({ args: ['-c', 'echo ok'] })], { base: null })
expect(result).toEqual({ ok: true, recorded: true })
expect(lines.some((line) => line.startsWith('✓ tests:agents'))).toBe(true)
})
})

it('fails when a command cannot start', async () => {
const result = await verify([{ name: 'lint', command: 'no-such-command-xyz', args: [] }])
expect(result.ok).toBe(false)
Expand Down
46 changes: 42 additions & 4 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 { forgetPassedPatch, recordPassedPatch } from './patches.ts'
Expand All @@ -23,6 +23,12 @@ export type Step = {
/** Starts only after these steps have finished, passed or not: they share files on disk. */
waitFor?: string[]
env?: Record<string, 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[]
}

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

if (base === undefined) {
const changes = base === undefined ? undefined : changedSince(root, base)
if (changes === undefined) {
out(`No ${baseName} branch found, so checking the whole tree.`)
} else {
const changes = changedSince(root, base)
const kinds = new Set(
changes.map((path) => (needsChecks(root, path) ? 'code' : classify(path))),
)
Expand Down Expand Up @@ -72,7 +78,12 @@ export async function runVerify(options: VerifyOptions): Promise<VerifyResult> {

const logDir = join(stateDir(root), 'logs')
mkdirSync(logDir, { recursive: true })
const passed = await runSteps(root, steps, logDir, out)
// With nothing changed, verify checks the tree anyway, so every step runs.
const stepsChanges =
changes === undefined || changes.length === 0
? undefined
: { paths: changes, since: baseName }
const passed = await runSteps(root, steps, logDir, out, stepsChanges)
if (!passed) return { ok: false, recorded: false }

const after = snapshot(root)
Expand All @@ -96,16 +107,43 @@ export async function runVerify(options: VerifyOptions): Promise<VerifyResult> {
return { ok: true, recorded: true }
}

/** The paths that differ from the base, and the base's name for messages. */
type Changes = { paths: string[]; since: string }

/**
* Whether a step reads one of the paths that changed. A deleted or renamed file counts for every
* step, since the agent docs may name it.
*/
function readsAChange(root: string, step: Step, paths: string[]): boolean {
const prefixes = step.onlyWhenChanged
if (prefixes === undefined) return true
return paths.some(
(path) =>
prefixes.some((prefix) => path.startsWith(prefix)) || !existsSync(join(root, path)),
)
}

async function runSteps(
root: string,
steps: Step[],
logDir: string,
out: (line: string) => void,
stepsChanges: Changes | undefined,
): 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
// Without a base to compare with, every step runs. A skipped step counts as passed, so the
// steps that wait for it or run after it still run.
if (stepsChanges !== undefined && !readsAChange(root, step, stepsChanges.paths)) {
out(
`- ${step.name} skipped: nothing it reads changed since ${stepsChanges.since}; 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 @@ -11,7 +11,7 @@
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"lib": ["es2023"],
"types": ["node", "vitest/globals"]
"types": ["node"]
},
"include": [".", "../../.pi/**/*"]
}
2 changes: 1 addition & 1 deletion .agents/skills/verify/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ The checks prove nothing broke. Now prove the change does what was asked, with t
| A command or flag added, renamed or removed | `SKILL_CONTENT` in `src/lib/skills/content.ts` updated and `npm run sync:skill` run; verify's skill-sync step checks the result. `node dist/index.js <command> --help` shows the change. |
| A real Todoist answer | `npm run build`, then `node dist/index.js <command>`, only on a test account. Check `node dist/index.js auth status` first. Ask before writes. |
| Terminal output (colours, spinners, a11y) | Run the command in a real terminal, with and without `--accessible`. Read it as a screen reader would: names first, ids after, no meaning carried by colour alone. |
| Agent tooling (`.agents/scripts`) | Its tests in throwaway repos, plus one real run of the hook or command. |
| Agent tooling (`.agents/scripts`) | Its tests in throwaway repos (`npm run test:agents`), plus one real run of the hook or command. |
| Docs only | Every path and command named exists (`ls`, `npm run`). |

Check the proof can fail: undo the change and see the test fail, or run the scenario that used to break. Done when you have seen it fail and then pass. A refactor is the exception: its proof is the pinned tests passing before and after (see `refactor`).
Expand Down
2 changes: 1 addition & 1 deletion .agents/skills/write-tests/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ description: Writes or changes tests in this repository to its quality bar, with
- Command tests mock the SDK client: `vi.mock('../../lib/api/core.js', () => ({ getApi: vi.fn() }))` at the top, `mockApi = setupApiMock()` in `beforeEach`, a program from `createTestProgram(registerXxxCommand)`, then `program.parseAsync(['node', 'td', ...])`. Capture output with `captureConsole()` or `captureStream()`. Read `src/commands/label/label.test.ts` for the shape.
- `src/index.integration.test.ts` builds the CLI and runs `dist/index.js`, for argv handling, global flags and JSON errors end to end.
- `vi.mock('chalk')` uses the manual mock in `src/__mocks__/chalk.ts`, which makes styling a passthrough so tests read plain text.
- Agent tooling tests live in `.agents/scripts/` and run copies of the tools in throwaway repos (`.agents/scripts/lib/test-repo.ts`).
- Agent tooling tests live in `.agents/scripts/` and run copies of the tools in throwaway repos (`.agents/scripts/lib/test-repo.ts`). `npm run test:agents` runs them; `npm test` does not.

## Helpers

Expand Down
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
Comment thread
scottlovegrove marked this conversation as resolved.
Resolved
3 changes: 2 additions & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@ npm run dev # watch mode (uses tsconfig.build.json)
npm run type-check # type check source + tests (tsconfig.json) and the agent tooling (.agents/scripts)
npm run check # lint + format check
npm run fix # auto-fix lint + format
npm test # run tests
npm test # run the package's tests (publishing runs these)
npm run test:agents # run the agent tooling's tests (.agents/scripts), for changes to the agent tooling
npm run verify # every check CI runs (lint, format, types, tests, build, skill sync)
```

Expand Down
15 changes: 11 additions & 4 deletions CODEBASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,8 @@ eslint/prettier) · semantic-release on merge to `main`.
├─ CLAUDE.md # Imports AGENTS.md for Claude Code; nothing else
├─ tsconfig.json # Includes src + tests (used by type-check, IDE)
├─ tsconfig.build.json # Excludes *.test.ts + test-support/ (used by build/dev)
├─ vitest.config.ts # Test runner config
├─ vitest.config.ts # Test runner config (the package's tests)
├─ vitest.agents.config.ts # Agent tooling tests (`npm run test:agents`)
├─ .oxlintrc.json / .oxfmtrc.json
├─ lefthook.yml # Git hooks (pre-commit, commit-msg, pre-push)
├─ docs/agents.md # How the agent tooling fits together
Expand Down Expand Up @@ -378,8 +379,12 @@ re-migrate a stale legacy slot.

## Testing

- **Runner:** vitest. `npm test` (one-shot), `npm run test:watch`. It also
runs the agent tooling's tests in `.agents/scripts/`.
- **Runner:** vitest. `npm test` (one-shot), `npm run test:watch`: the
package's tests only, which publishing runs (`prepublishOnly`). The agent
tooling's tests in `.agents/scripts/` run apart, through
`vitest.agents.config.ts` (`npm run test:agents`): in CI on every pull
request and every push to `main` and `next`, and in `npm run verify` when
something they read changed.
- **Location:** co-located `*.test.ts` next to the module under test.
- **Mocks:** `src/test-support/mock-api.ts` — `createMockApi()` returns
vitest-mocked versions of every SDK method. Use factories from
Expand Down Expand Up @@ -419,7 +424,9 @@ re-migrate a stale legacy slot.
`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`.
- **Release:** semantic-release on merge to `main` (`.github/workflows/release.yml`).
Commits must follow Conventional Commits — enforced by
`check-semantic-pull-request.yml`.
Expand Down
Loading
Loading