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: 6 additions & 6 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,11 +149,11 @@ it('names only test helpers that the fixtures, global-args or @todoist/cli-core/
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 fixtures = join(REPO_ROOT, 'src/lib/__fixtures__')
const sources = [
...readdirSync(fixtures).map((file) => join(fixtures, file)),
join(REPO_ROOT, 'src/lib/global-args.ts'),
]
// A path ending in `/` is a folder of helper files.
const sources = TEST_HELPER_PATHS.flatMap((path) => {
const full = join(REPO_ROOT, path)
return path.endsWith('/') ? readdirSync(full).map((file) => join(full, file)) : [full]
})
const local = sources.flatMap((file) =>
[
...readFileSync(file, 'utf8').matchAll(
Expand Down
17 changes: 16 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 @@ -130,6 +130,21 @@ describe('verify covers CI', () => {
}
})

it('watches only paths that exist, so a rename cannot stop a step running locally', () => {
const missing = VERIFY_STEPS.flatMap((step) =>
(step.onlyWhenChanged ?? [])
// hook-wiring.test.ts checks .cursor/ holds no hooks file, so adding one runs the tests.
.filter((path) => path !== '.cursor/' && !existsSync(join(REPO_ROOT, path)))
.map((path) => `${step.name}: ${path}`),
)
expect(missing).toEqual([])
})

it('starts the agent tooling tests after the package tests, so their pools never compete', () => {
const agents = VERIFY_STEPS.find((step) => step.name === 'tests:agents')
expect(agents?.waitFor).toEqual(['tests'])
})

it('names only steps that exist', () => {
const names = VERIFY_STEPS.map((step) => step.name)
for (const entry of CI_EQUIVALENTS) {
Expand Down
31 changes: 31 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 @@ -16,6 +17,35 @@ export const VERIFY_STEPS: Step[] = [
{ name: 'types', command: bin('tsc'), args: ['--noEmit'] },
{ name: 'types:tools', command: bin('tsc'), args: ['--noEmit', '-p', '.agents/scripts'] },
{ name: 'tests', command: bin('vitest'), args: ['run'], env: CI_ENV },
{
name: 'tests:agents',
command: bin('vitest'),
args: ['run', '--config', 'vitest.agents.config.ts'],
env: CI_ENV,
// After the package tests, so two vitest pools don't share the CPU and slow each other into
// timeouts.
waitFor: ['tests'],
// Everything the tests in .agents/scripts read from the checkout.
onlyWhenChanged: [
'.agents/',
'vitest.agents.config.ts',
// Its scripts (instructions, steps) and what it packs (package-contents).
'package.json',
// The tools the tests run: lefthook, npm and @todoist/cli-core/testing.
'package-lock.json',
'.github/workflows/',
'lefthook.yml',
// The hook configs (hook-wiring) and the skill links (instructions).
'.claude/',
Comment thread
scottlovegrove marked this conversation as resolved.
Resolved
'.codex/',
'.pi/',
// hook-wiring.test.ts checks that no Cursor hooks file appears.
'.cursor/',
...AGENT_DOCS,
Comment thread
scottlovegrove marked this conversation as resolved.
Resolved
// The test helpers the write-tests skill names (instructions).
...TEST_HELPER_PATHS,
],
},
{ name: 'build', command: 'npm', args: ['run', '--silent', 'build'], env: CI_ENV },
{
name: 'skill-sync',
Expand All @@ -37,6 +67,7 @@ export const CI_EQUIVALENTS: { run: string; steps: string[]; why?: string }[] =
{ run: 'npm run lint: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
3 changes: 3 additions & 0 deletions .agents/scripts/lib/tree.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ 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'])

/** Where the test helpers the write-tests skill names live; instructions.test.ts reads them. */
export const TEST_HELPER_PATHS = ['src/lib/__fixtures__/', 'src/lib/global-args.ts']

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

Expand Down
52 changes: 52 additions & 0 deletions .agents/scripts/lib/verify.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -283,3 +283,55 @@ describe('what counts as a change', () => {
expect(lines[0]).toBe('No changes since main; checking the tree anyway.')
})
})

describe('a step that runs only when what it reads changed', () => {
const SKIPPED =
'- agents skipped: nothing it reads changed since main; CI runs it on every pull request'
// Fails if it runs, so a pass proves it was skipped.
const agents = { ...fail('agents'), onlyWhenChanged: ['.agents/', 'vitest.agents.config.ts'] }

it('is skipped, and says so, when nothing it reads changed', async () => {
repo.write('src/a.ts', 'export const a = 2\n')
expect(await verify([pass('lint'), agents])).toEqual({ ok: true, recorded: true })
expect(lines).toContain(SKIPPED)
})

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

it('counts as passed, so the steps that wait on or follow it still run', async () => {
repo.write('src/a.ts', 'export const a = 2\n')
const result = await verify([
agents,
pass('tests', { waitFor: ['agents'] }),
pass('report', { after: 'agents' }),
])
expect(result).toEqual({ ok: true, recorded: true })
expect(lines.some((line) => line.startsWith('✓ tests'))).toBe(true)
expect(lines.some((line) => line.startsWith('✓ report'))).toBe(true)
})

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

it.each([
['deleted', () => rmSync(join(repo.dir, 'README.md'))],
['renamed', () => repo.git(['mv', 'src/a.ts', 'src/b.ts'])],
])('runs when a file was %s, since the agent docs may name it', async (_kind, change) => {
change()
expect(await verify([pass('lint'), agents])).toEqual({ ok: false, recorded: false })
expect(lines.some((line) => line.startsWith('✗ agents (exit 3'))).toBe(true)
})

it('runs without a default branch, since there is nothing to compare with', async () => {
const result = await verify([agents], { base: null })
expect(result).toEqual({ ok: false, recorded: false })
expect(lines.some((line) => line.startsWith('✗ agents (exit 3'))).toBe(true)
})
})
36 changes: 32 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, resolveCommit } from './git.ts'
import { forgetPassedChanges, 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 All @@ -71,7 +77,7 @@ 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)
const passed = await runSteps(root, steps, logDir, out, { changes, baseName })
if (!passed) return { ok: false, recorded: false }

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

/** Whether a step has to run: always, unless it names what it reads and none of that changed. */
function needed(root: string, step: Step, changes: string[] | undefined): boolean {
const prefixes = step.onlyWhenChanged
// No base, or nothing changed: verify checks the whole tree, so every step runs.
if (prefixes === undefined || changes === undefined || changes.length === 0) return true
return changes.some(
(path) =>
// A deleted or renamed file may be one the agent docs name.
!existsSync(join(root, path)) || prefixes.some((prefix) => path.startsWith(prefix)),
)
}

async function runSteps(
root: string,
steps: Step[],
logDir: string,
out: (line: string) => void,
since: { changes: string[] | undefined; baseName: string },
): 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 (!needed(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 @@ -11,7 +11,7 @@
"allowImportingTsExtensions": true,
"erasableSyntaxOnly": true,
"lib": ["es2023"],
"types": ["node", "vitest/globals"]
"types": ["node"]
},
"include": [".", "../../.pi/**/*"]
}
5 changes: 5 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
name: Test

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

permissions:
Expand Down Expand Up @@ -33,3 +35,6 @@ jobs:

- name: Run tests
run: npm test

- name: Run agent tooling tests
Comment thread
scottlovegrove marked this conversation as resolved.
Resolved
run: npm run test:agents
7 changes: 4 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,13 @@ Reviewers, Doistbot included, apply these to every change:
```bash
npm run build # Compile TypeScript to dist/ (uses tsconfig.build.json, excludes tests)
npm run dev # Watch mode compilation (uses tsconfig.build.json, excludes tests)
npm test # Run all tests (vitest)
npm test # Run the package's tests (vitest); publishing runs these
npm run test:watch # Run tests in watch mode
npm run test:agents # Run the agent tooling's tests (.agents/scripts), for changes to the agent tooling
npm run type-check # Type check src + tests (tsconfig.json) and the agent tooling (.agents/scripts)
npm run lint # Fix lint issues (oxlint) + format (oxfmt)
npm run lint:check # Check lint + formatting (for CI)
npm run verify # Every check CI runs (lint, format, types, tests, build, skill sync)
npm run verify # Every check CI runs (lint, format, types, tests, build, skill sync, agent tooling tests)
```

The project uses two tsconfig files: `tsconfig.json` includes test files for type-checking, while `tsconfig.build.json` extends it and excludes colocated `*.test.ts` and `*.spec.ts` files (plus `src/__mocks__`) so test-only code is not compiled into `dist/`.
Expand Down Expand Up @@ -108,7 +109,7 @@ throw new CliError('ERROR_CODE', 'User-facing message', ['Optional hint'])

## Git hooks and agent tooling

- Lefthook refuses commits and pushes to `main`, runs oxlint, oxfmt and the type check on pre-commit, and the tests on pre-push. Work on a branch.
- Lefthook refuses commits and pushes to `main`, runs oxlint, oxfmt and the type check on pre-commit, and `npm test` (the package's tests only) on pre-push. The agent tooling's tests run in CI, and in `npm run verify` when something they read changed. Work on a branch.
- Your `git push` and `gh pr create` are stopped until `npm run verify` has passed on exactly the commit being pushed (Claude Code, Codex and Cursor hooks, and a Pi extension), or on the same changes before a rebase that only moved `main` under them. Verify, then commit exactly what it saw, or commit first and verify the clean tree. If something must be pushed unverified, ask the person you're working with to push it.
- Agent tooling lives in `.agents/scripts/`, never in `scripts/` (which ships in the npm package).
- How it all fits together: [`docs/agents.md`](docs/agents.md).
Expand Down
14 changes: 9 additions & 5 deletions CODEBASE.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,10 @@ come from `@todoist/cli-core`.
├─ tsconfig.json # Includes src + tests (type-check, IDE)
├─ tsconfig.build.json # Excludes *.test.ts/.spec.ts, __mocks__, __fixtures__
├─ vitest.config.ts # { globals, root: 'src', inlines @todoist/cli-core }
├─ vitest.agents.config.ts # The agent tooling's tests (.agents/scripts/)
├─ .oxlintrc.json / .oxfmtrc.json
├─ lefthook.yml # Git hooks: branch guard; pre-commit lint, format, types;
│ # pre-push tests
│ # pre-push npm test
├─ renovate.json # Dependency automation
└─ release.config.js # semantic-release config
```
Expand Down Expand Up @@ -264,9 +265,11 @@ see a per-command `--user`).

## Testing

- **Runner:** vitest. `npm test` (one-shot, including the agent tooling's tests
in `.agents/scripts/`), `npm run test:watch`. Single file:
`npx vitest run src/lib/refs.test.ts`.
- **Runner:** vitest. `npm test` (one-shot, the package's tests; `prepublishOnly`
runs it), `npm run test:watch`. Single file:
`npx vitest run src/lib/refs.test.ts`. The agent tooling's tests in
`.agents/scripts/` run apart, with `npm run test:agents`
(`vitest.agents.config.ts`); see `docs/agents.md`.
- **Location:** colocated `*.test.ts` next to the module under test.
- **Fixtures:** `src/lib/__fixtures__/accounts.ts` (`ACCOUNT_ALAN` /
`ACCOUNT_ELLIE`) — don't hand-build account objects. Manual npm-package mocks
Expand All @@ -291,7 +294,8 @@ see a per-command `--user`).
`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 verify when something they read changed). See `docs/agents.md`.
- **Release:** semantic-release on merge to `main`; Conventional Commits required
(enforced by `check-semantic-pull-request.yml`). `update-comms-sdk.yml` keeps
`@todoist/comms-sdk` current.
Expand Down
5 changes: 3 additions & 2 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@ After cloning the repository and installing dependencies with `npm install`, sev
- `npm run dev`: Runs in development mode
- `npm run lint`: Auto-fixes lint and formatting issues
- `npm run lint:check`: Validates code quality and formatting
- `npm test`: Runs all tests
- `npm test`: Runs the package's tests (publishing runs these)
- `npm run test:agents`: Runs the agent tooling's tests in `.agents/scripts/`, for changes to the agent tooling
- `npm run test:watch`: Runs tests in watch mode
- `npm run type-check`: Type checks without emitting
- `npm run verify`: Runs every check CI runs (lint, format, types, tests, build, skill sync) in about fifteen seconds
- `npm run verify`: Runs every check CI runs (lint, format, types, tests, build, skill sync, agent tooling tests) in about fifteen seconds

## Sending a Pull Request

Expand Down
Loading