[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M75KQ2EVSD79NGBXGAHCXP40":3,"skill-same:01M75KQ2EVSD79NGBXGAHCXP40":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":25,"commitSha":26,"skillDirectory":27,"forksCount":28,"repositoryHtmlUrl":29,"repositoryHomepageUrl":30,"ownerHtmlUrl":31,"ownerBlogUrl":32,"ownerDescription":6,"updatedAt":33,"install":34,"resources":47},"01M75KQ2EVSD79NGBXGAHCXP40","writing-tests",null,"Apply when writing tests, modifying test files, fixing test failures, debugging CI failures, adding test coverage, creating adversarial tests, or reviewing any file under tests\u002F. Also apply when implementing features or fixes that require corresponding test changes. Enforces bun:test framework rules, mock isolation, cross-platform compatibility (Linux, macOS, Windows), and CI pipeline awareness. Load this skill before touching any test file.","agisota\u002Fold-one","agisota","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F121413592?v=4","01M75B4BRNT67EC1NDRT8QZEP2","01M75B4BS7QR9VP580MSCPTS3X",3,"MIT","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fwriting-tests\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: writing-tests\ndescription: >\n  Apply when writing tests, modifying test files, fixing test failures, debugging CI failures,\n  adding test coverage, creating adversarial tests, or reviewing any file under tests\u002F.\n  Also apply when implementing features or fixes that require corresponding test changes.\n  Enforces bun:test framework rules, mock isolation, cross-platform compatibility (Linux,\n  macOS, Windows), and CI pipeline awareness. Load this skill before touching any test file.\neffort: medium\n---\n\n# Writing Tests for opencode-swarm\n\n## Framework: bun:test Only\n\nAll test files MUST import from `bun:test`:\n\n```typescript\nimport { describe, test, expect, beforeEach, afterEach } from 'bun:test';\n```\n\nBun provides a vitest compatibility layer (`vi.mock`, `vi.fn`, `vi.spyOn`) that works on Linux and macOS. However, `vi.mock()` has critical isolation bugs in Bun when multiple test directories run in the same process. Prefer `bun:test` native APIs:\n\n| vitest API | bun:test equivalent | Notes |\n|-----------|-------------------|-------|\n| `vi.fn()` | `mock(() => ...)` | Import `mock` from `bun:test` |\n| `vi.spyOn(obj, method)` | `spyOn(obj, method)` | Import `spyOn` from `bun:test` |\n| `vi.mock('module', factory)` | `mock.module('module', factory)` | Import `mock` from `bun:test` |\n| `vi.restoreAllMocks()` | `mock.restore()` | Call in `afterEach` |\n\n## Mock Isolation Rules\n\n**CRITICAL: Module-level mocks leak across test files within the same Bun process.**\n\nThe CI pipeline runs test directories in groups. All files in a group share one Bun process and one module cache. A `vi.mock()` or `mock.module()` call in file A replaces the module for file B if they run in the same group.\n\n### Rules\n\n1. **Never mock a module that another test file in the same CI group imports directly.** If `tests\u002Funit\u002Fcli\u002Frun-dispatch.test.ts` mocks `..\u002F..\u002Fsrc\u002Fcommands\u002Fagents.js`, then `tests\u002Funit\u002Fcommands\u002Fagents.test.ts` (in the same group) will get the mock instead of the real module.\n\n2. **If you must use module-level mocks, isolate the test in its own CI step** or use dependency injection instead of module replacement.\n\n3. **Never create circular mock imports.** This pattern deadlocks Bun:\n```typescript\n\u002F\u002F BROKEN — imports from the module it's about to mock\nimport { realFn } from '..\u002F..\u002Fsrc\u002Fmodule.js';\nvi.mock('..\u002F..\u002Fsrc\u002Fmodule.js', () => ({\n  realFn: (...args) => realFn(...args),  \u002F\u002F circular!\n  otherFn: vi.fn(),\n}));\n```\nInstead, inline the function logic or extract the real functions into a separate utility module.\n\n4. **Prefer constructor\u002Fparameter injection over module mocking.** The swarm's hook factories (`createScopeGuardHook`, `createDelegationLedgerHook`, etc.) accept injected dependencies — test them by passing mock callbacks, not by replacing modules.\n\n## CI Pipeline Structure\n\nThe CI runs on three platforms (ubuntu, macos, windows). Tests are split into sequential steps within each platform's job.\n\n**Per-file isolation:** Each test file runs in its own Bun process via `for f in dir\u002F*.test.ts; do bun --smol test \"$f\"; done`. This prevents module cache poisoning between files within the same step.\n\n**Cascade termination:** Each step uses `exit $failed` — the first failing step terminates the entire platform's job. This means failures in later steps are hidden until earlier steps pass. When fixing Windows issues, expect to peel back layers: fixing Step 4 may reveal a failure in Step 5 that was previously hidden.\n\n```\nStep 1: hooks - guardrails            (Linux\u002FmacOS only, skipped on Windows)\nStep 2: hooks - knowledge             (Linux\u002FmacOS only, skipped on Windows)\nStep 3: hooks - system-enhancer       (Linux\u002FmacOS only, skipped on Windows)\nStep 4: hooks - delegation + others   (Linux\u002FmacOS only, skipped on Windows)\nStep 5: commands + config             (all platforms)\nStep 6: cli                           (all platforms)\nStep 7: tools                         (all platforms)\nStep 8: services + build + quality + sast + sbom + scripts  (all platforms)\nStep 9: state + agents + knowledge + evidence + plan + misc (all platforms)\n```\n\nWhen writing a test, know which step your file will run in. Do not assume isolation from other files in the same step.\n\n**Job timeout: 15 minutes.** A single hanging test will kill the entire platform's test run.\n\n## File Placement\n\n### Convention\n\n| Test type | Location | When to use |\n|-----------|----------|-------------|\n| Unit tests for `src\u002Fhooks\u002F*.ts` | `tests\u002Funit\u002Fhooks\u002F` | Testing hook factories and hook behavior |\n| Unit tests for `src\u002Ftools\u002F*.ts` | `tests\u002Funit\u002Ftools\u002F` | Testing tool execute functions |\n| Unit tests for `src\u002Fcommands\u002F*.ts` | `tests\u002Funit\u002Fcommands\u002F` | Testing CLI command handlers |\n| Unit tests for `src\u002Fconfig\u002F*.ts` | `tests\u002Funit\u002Fconfig\u002F` | Testing schema validation, config loading |\n| Unit tests for `src\u002Fagents\u002F*.ts` | `tests\u002Funit\u002Fagents\u002F` | Testing agent prompt generation, factory logic |\n| Colocated tests | `src\u002F**\u002F*.test.ts` | Integration-style tests tightly coupled to the source module |\n| Integration tests | `tests\u002Fintegration\u002F` | Cross-module workflows, plugin initialization |\n| Security tests | `tests\u002Fsecurity\u002F` | Adversarial input handling, injection resistance |\n| Smoke tests | `tests\u002Fsmoke\u002F` | Built package validation |\n\n### Naming\n\n- Base test: `\u003Cmodule>.test.ts`\n- Adversarial variant: `\u003Cmodule>.adversarial.test.ts`\n\nOnly create an adversarial variant if it tests **distinct attack vectors** not covered by the base test. Do not duplicate base test assertions with different inputs — that's redundancy, not security coverage.\n\n### Regression tests (review-surfaced bugs)\n\nWhen fixing a bug surfaced by code review, swarm review, or post-merge audit, **always add a regression test** with the following shape so the test's purpose survives future cleanup:\n\n```typescript\ndescribe('\u003Cfeature> — regression: \u003Cone-line description> (F#)', () => {\n  it('\u003Cexact behavior the bug violated>', () => {\n    \u002F\u002F Previous code did \u003Cbad thing>: e.g. the regex `\u002F^\\.\\\u002F+\u002F` only stripped\n    \u002F\u002F a single leading `.\u002F`, so `.\u002F.\u002Futil.ts` survived as `.\u002Futil.ts`.\n    expect(normalizeGraphPath('.\u002F.\u002Futil.ts')).toBe('util.ts');\n  });\n});\n```\n\nRules:\n- The describe label includes the original finding ID (e.g. `F8`, `F9`, `F1.1`) so future readers can map back to the review.\n- The leading comment in the body explains the **prior buggy behavior** in concrete terms — what the code did before, not what it does now.\n- One regression test per finding. Do not pile unrelated assertions into a single regression block.\n\nExamples in-tree: `tests\u002Funit\u002Fgraph\u002Fgraph-query.test.ts` (`normalizeGraphPath — regression (F8)`, `getBlastRadius — regression: depthReached (F9)`), `tests\u002Funit\u002Fgraph\u002Fimport-extractor.test.ts` (`paren-preceded strings (F1)`, `member-expression require\u002Fimport (F1.1)`).\n\n## Test Quality Standards\n\n### DO\n\n- Test real behavior: call the actual function with real inputs, assert on real outputs.\n- Test error paths: what happens with `null`, `undefined`, empty string, oversized input?\n- Use temp directories (`fs.mkdtemp`) for file I\u002FO tests. Clean up in `afterEach`.\n- Assert on specific values, not just truthiness: `expect(result.status).toBe('pending')` not `expect(result).toBeTruthy()`.\n\n### DO NOT\n\n- **Do not test type definitions.** `expect(event.type === 'foo').toBe(true)` tests TypeScript, not your code.\n- **Do not test framework behavior.** \"Zod schema parses valid input\" tests Zod, not your schema.\n- **Do not test test utilities.** If it only exists to support other tests, it doesn't need its own test.\n- **Do not mock everything.** If every dependency is mocked, you're testing the mock setup. Prefer real dependencies for pure functions and only mock I\u002FO boundaries (filesystem, network, timers).\n- **Do not hardcode version numbers.** Version bumps are automated — a test asserting `version === '6.31.3'` breaks on every release.\n- **Do not use `sleep` or `setTimeout` for synchronization.** Use explicit signals, resolved promises, or `Bun.sleep()` with tight bounds.\n- **Do not spawn `cat \u002Fdev\u002Fzero`, `yes`, or other infinite-output commands.** Use `sleep 30` for \"blocking command\" tests.\n\n## Cross-Entry Invariants (config maps)\n\nWhen you modify any entry of a \"map of agents\u002Ftools\u002Froles\" in `src\u002Fconfig\u002Fconstants.ts` (`AGENT_TOOL_MAP`, `DEFAULT_MODELS`, `QA_AGENTS`, `PIPELINE_AGENTS`, etc.), there are tests that assert **parity across sibling entries**, not just shape of one entry.\n\nKnown parity assertions:\n\n| Test | Invariant |\n|---|---|\n| `tests\u002Funit\u002Fconfig\u002Fcritic-registration.test.ts:67` | `AGENT_TOOL_MAP.critic_sounding_board.length === AGENT_TOOL_MAP.critic.length` |\n| `tests\u002Funit\u002Fconfig\u002Fagent-tool-map.test.ts:26` | `AGENT_TOOL_MAP.architect.length` is strictly greater than every other agent's |\n| `tests\u002Funit\u002Fconfig\u002Fagent-tool-map.test.ts:34` | every subagent's tool list `\u003C= 20` entries |\n| `tests\u002Funit\u002Fconfig\u002Fconstants.test.ts:48` | `ALL_SUBAGENT_NAMES.length === 13` |\n| `tests\u002Funit\u002Fconfig\u002Fconstants.test.ts:137` | `Object.keys(DEFAULT_MODELS).length === 14` |\n\nWorkflow when adding a tool to a single agent:\n1. Add the entry.\n2. Run `bun --smol test tests\u002Funit\u002Fconfig --timeout 60000` **before pushing**.\n3. If a parity test fails, decide: mirror the change to sibling agents (most common — see this PR's `repo_map` mirrored to `critic_sounding_board` + `critic_drift_verifier`), or update the invariant test if the design intent has actually changed.\n4. To inspect runtime shape quickly: `bun -e \"import { AGENT_TOOL_MAP } from '.\u002Fsrc\u002Fconfig\u002Fconstants.ts'; for (const [k,v] of Object.entries(AGENT_TOOL_MAP)) console.log(k, v.length);\"`\n\nDo **not** push a constants change to CI without running the config test directory locally — these failures cascade through the per-OS unit jobs and waste minutes per push.\n\n## Cross-Platform Requirements\n\nAll tests must pass on Linux, macOS, and Windows unless explicitly gated.\n\n### Skipping tests on specific platforms\n\nUse the `skipIf` chaining pattern:\n```typescript\n\u002F\u002F Skip on Windows only\ntest.skipIf(process.platform === 'win32')('test name', async () => { ... });\n\n\u002F\u002F Skip on non-Linux (use when test relies on Linux-specific behavior)\ntest.skipIf(process.platform !== 'linux')('test name', async () => { ... });\n\n\u002F\u002F Skip entire describe block\ndescribe.skipIf(process.platform === 'win32')('group name', () => { ... });\n```\n\n### Temp directories and path handling\n- Use `path.join()` or `path.resolve()`, never string concatenation with `\u002F`.\n- Temp directories: use `os.tmpdir()`, never hardcoded `\u002Ftmp`.\n- **CRITICAL: Wrap `mkdtempSync` with `realpathSync` when using `process.chdir`:**\n  ```typescript\n  \u002F\u002F WRONG — on macOS, \u002Ftmp is a symlink to \u002Fprivate\u002Ftmp.\n  \u002F\u002F mkdtempSync returns \u002Ftmp\u002F... but process.cwd() resolves to \u002Fprivate\u002Ftmp\u002F...\n  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'test-'));\n  process.chdir(tempDir);\n  \u002F\u002F process.cwd() !== tempDir on macOS!\n\n  \u002F\u002F CORRECT — resolve symlinks first\n  const tempDir = fs.realpathSync(\n    fs.mkdtempSync(path.join(os.tmpdir(), 'test-')),\n  );\n  process.chdir(tempDir);\n  ```\n- File comparisons: normalize paths before comparing (`path.resolve(a) === path.resolve(b)`).\n\n### Permissions (`fs.chmodSync`)\n- `chmodSync` is a **no-op for directories** on Windows and unreliable for files.\n- Tests that rely on chmod to simulate permission errors should guard with platform checks:\n  ```typescript\n  if (process.platform !== 'win32') {\n    fs.chmodSync(filePath, 0o000);\n    \u002F\u002F ... test permission error behavior ...\n    fs.chmodSync(filePath, 0o644); \u002F\u002F restore\n  } else {\n    \u002F\u002F On Windows, skip or use a mock to throw EPERM\n  }\n  ```\n- If the test asserts that the tool handles permission errors **gracefully** (returns success despite write failure), the test may pass on Windows even without chmod — the write just succeeds. Verify this before adding guards.\n\n### Symlinks\n- `fs.symlinkSync` requires **administrator or developer mode** on Windows.\n- Use a runtime capability check:\n  ```typescript\n  let canCreateSymlinks = false;\n  try {\n    const testLink = path.join(tempDir, '.symlink-test');\n    fs.symlinkSync(tempDir, testLink);\n    fs.unlinkSync(testLink);\n    canCreateSymlinks = true;\n  } catch {}\n\n  test.skipIf(!canCreateSymlinks)('symlink test', async () => { ... });\n  ```\n\n### Process spawning\n- Use `.cmd` extension on Windows for npm\u002Fbun binaries: `process.platform === 'win32' ? 'bun.cmd' : 'bun'`.\n- Use array-form `spawn`\u002F`spawnSync`, never shell string commands.\n- **`npx` in empty temp dirs hangs on Windows.** If a test creates a temp directory with a `package.json` (for framework detection) and then calls a tool that spawns `npx vitest run` or similar, the spawn will hang until the test timeout fires. Skip these tests on non-Linux:\n  ```typescript\n  \u002F\u002F Flaky on macOS\u002FWindows: spawns vitest in temp dir without node_modules\n  test.skipIf(process.platform !== 'linux')(\n    'test that triggers process execution',\n    async () => { ... },\n    15000,\n  );\n  ```\n\n### Timestamps\n- Avoid comparing strings that embed `new Date().toISOString()`. Two sequential calls can span a millisecond boundary, especially on Windows CI. Strip or normalize volatile timestamps before comparison:\n  ```typescript\n  const stripTimestamp = (s: string) =>\n    s.replace(\u002FUpdated: \\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z\u002F, 'Updated: \u003CFROZEN>');\n  expect(stripTimestamp(output1)).toBe(stripTimestamp(output2));\n  ```\n\n## Running Tests\n\n```bash\n# Full suite (all platforms)\nbun test\n\n# Single file\nbun test tests\u002Funit\u002Fhooks\u002Fscope-guard.test.ts\n\n# Single directory\nbun --smol test tests\u002Funit\u002Fhooks --timeout 30000\n\n# CI-equivalent run (per-file isolation, matches actual CI behavior)\nfor f in tests\u002Funit\u002Ftools\u002F*.test.ts; do bun --smol test \"$f\" --timeout 120000; done\n\n# Quick directory run (faster but may have cross-file cache pollution)\nbun --smol test tests\u002Funit\u002Fcli --timeout 120000\nbun --smol test tests\u002Funit\u002Fcommands tests\u002Funit\u002Fconfig --timeout 120000\n```\n\nThe `--smol` flag reduces Bun's memory footprint. Use it when running large directories (50+ files).\n\nThe `--timeout 120000` flag sets per-test timeout to 120 seconds. Individual tests should complete in under 5 seconds. If a test needs more than 10 seconds, it's doing too much — split it or mock the slow dependency.\n\n**Note:** CI runs each file in its own Bun process (`for f in dir\u002F*.test.ts; do bun --smol test \"$f\"; done`). Running an entire directory at once (`bun --smol test tests\u002Funit\u002Ftools\u002F`) can mask cache-poisoning issues that only appear in CI. When debugging CI failures, test files individually.\n\n## Debugging CI failures\n\nWhen CI reports a `unit (ubuntu-latest|macos-latest|windows-latest)` failure:\n\n1. **Identify the actual failing test from the job log first.** Do not assume it's a pre-existing failure based on a local repro of a different test. Open the failing job's URL (`https:\u002F\u002Fgithub.com\u002F\u003Cowner>\u002F\u003Crepo>\u002Factions\u002Fruns\u002F\u003Crun-id>\u002Fjob\u002F\u003Cjob-id>`) and find the `\u003Cfile>:\u003Cline>` in the Bun output. WebFetch can scrape this if the `gh` CLI isn't available.\n2. **Reproduce that exact file locally** with the per-file CI command:\n   ```bash\n   bun --smol test tests\u002Funit\u002F\u003Cdir>\u002F\u003Cfile>.test.ts --timeout 30000\n   ```\n3. **Then check if the same failure reproduces on `main`.** If yes, document as pre-existing in the PR description and continue with your branch's work; do not silently inherit the failure.\n4. **For dist-check failures:** any change under `src\u002F` that the bundler picks up requires `bun run build` + commit of `dist\u002F` in the same PR. The job compares committed `dist\u002F` against a fresh build.\n5. **For matrix-OS-only failures:** check `process.platform` guards, `mkdtempSync` realpath wrapping, chmod guards, symlink capability checks, and `npx`-spawn skips (sections above).\n\n## Before Submitting\n\n1. Run the tests for your changed files: `bun test path\u002Fto\u002Fyour.test.ts`\n2. Run the full CI group your tests belong to (see pipeline structure above)\n3. Verify no `process.cwd()` usage — use the `directory` parameter from `createSwarmTool` or hook constructor\n4. Verify no hardcoded paths (`\u002Ftmp\u002F...`, `C:\\...`) — use `os.tmpdir()` + `path.join()`\n5. Verify mocks are restored in `afterEach` if using `spyOn` or `mock.module`\n6. Verify `mkdtempSync` is wrapped with `realpathSync` if you use `process.chdir` on the result\n7. Verify `chmodSync` calls are guarded with `process.platform !== 'win32'`\n8. Verify symlink creation is guarded or uses a `canCreateSymlinks` capability check\n9. Verify no `new Date().toISOString()` in equality assertions — strip volatile timestamps\n10. Verify tests that spawn `npx`\u002F`vitest`\u002F`jest` in temp dirs are skipped on non-Linux\n","# Writing Tests for opencode-swarm\n\n## Framework: bun:test Only\n\nAll test files MUST import from `bun:test`:\n\n```typescript\nimport { describe, test, expect, beforeEach, afterEach } from 'bun:test';\n```\n\nBun provides a vitest compatibility layer (`vi.mock`, `vi.fn`, `vi.spyOn`) that works on Linux and macOS. However, `vi.mock()` has critical isolation bugs in Bun when multiple test directories run in the same process. Prefer `bun:test` native APIs:\n\n| vitest API | bun:test equivalent | Notes |\n|-----------|-------------------|-------|\n| `vi.fn()` | `mock(() => ...)` | Import `mock` from `bun:test` |\n| `vi.spyOn(obj, method)` | `spyOn(obj, method)` | Import `spyOn` from `bun:test` |\n| `vi.mock('module', factory)` | `mock.module('module', factory)` | Import `mock` from `bun:test` |\n| `vi.restoreAllMocks()` | `mock.restore()` | Call in `afterEach` |\n\n## Mock Isolation Rules\n\n**CRITICAL: Module-level mocks leak across test files within the same Bun process.**\n\nThe CI pipeline runs test directories in groups. All files in a group share one Bun process and one module cache. A `vi.mock()` or `mock.module()` call in file A replaces the module for file B if they run in the same group.\n\n### Rules\n\n1. **Never mock a module that another test file in the same CI group imports directly.** If `tests\u002Funit\u002Fcli\u002Frun-dispatch.test.ts` mocks `..\u002F..\u002Fsrc\u002Fcommands\u002Fagents.js`, then `tests\u002Funit\u002Fcommands\u002Fagents.test.ts` (in the same group) will get the mock instead of the real module.\n\n2. **If you must use module-level mocks, isolate the test in its own CI step** or use dependency injection instead of module replacement.\n\n3. **Never create circular mock imports.** This pattern deadlocks Bun:\n```typescript\n\u002F\u002F BROKEN — imports from the module it's about to mock\nimport { realFn } from '..\u002F..\u002Fsrc\u002Fmodule.js';\nvi.mock('..\u002F..\u002Fsrc\u002Fmodule.js', () => ({\n  realFn: (...args) => realFn(...args),  \u002F\u002F circular!\n  otherFn: vi.fn(),\n}));\n```\nInstead, inline the function logic or extract the real functions into a separate utility module.\n\n4. **Prefer constructor\u002Fparameter injection over module mocking.** The swarm's hook factories (`createScopeGuardHook`, `createDelegationLedgerHook`, etc.) accept injected dependencies — test them by passing mock callbacks, not by replacing modules.\n\n## CI Pipeline Structure\n\nThe CI runs on three platforms (ubuntu, macos, windows). Tests are split into sequential steps within each platform's job.\n\n**Per-file isolation:** Each test file runs in its own Bun process via `for f in dir\u002F*.test.ts; do bun --smol test \"$f\"; done`. This prevents module cache poisoning between files within the same step.\n\n**Cascade termination:** Each step uses `exit $failed` — the first failing step terminates the entire platform's job. This means failures in later steps are hidden until earlier steps pass. When fixing Windows issues, expect to peel back layers: fixing Step 4 may reveal a failure in Step 5 that was previously hidden.\n\n```\nStep 1: hooks - guardrails            (Linux\u002FmacOS only, skipped on Windows)\nStep 2: hooks - knowledge             (Linux\u002FmacOS only, skipped on Windows)\nStep 3: hooks - system-enhancer       (Linux\u002FmacOS only, skipped on Windows)\nStep 4: hooks - delegation + others   (Linux\u002FmacOS only, skipped on Windows)\nStep 5: commands + config             (all platforms)\nStep 6: cli                           (all platforms)\nStep 7: tools                         (all platforms)\nStep 8: services + build + quality + sast + sbom + scripts  (all platforms)\nStep 9: state + agents + knowledge + evidence + plan + misc (all platforms)\n```\n\nWhen writing a test, know which step your file will run in. Do not assume isolation from other files in the same step.\n\n**Job timeout: 15 minutes.** A single hanging test will kill the entire platform's test run.\n\n## File Placement\n\n### Convention\n\n| Test type | Location | When to use |\n|-----------|----------|-------------|\n| Unit tests for `src\u002Fhooks\u002F*.ts` | `tests\u002Funit\u002Fhooks\u002F` | Testing hook factories and hook behavior |\n| Unit tests for `src\u002Ftools\u002F*.ts` | `tests\u002Funit\u002Ftools\u002F` | Testing tool execute functions |\n| Unit tests for `src\u002Fcommands\u002F*.ts` | `tests\u002Funit\u002Fcommands\u002F` | Testing CLI command handlers |\n| Unit tests for `src\u002Fconfig\u002F*.ts` | `tests\u002Funit\u002Fconfig\u002F` | Testing schema validation, config loading |\n| Unit tests for `src\u002Fagents\u002F*.ts` | `tests\u002Funit\u002Fagents\u002F` | Testing agent prompt generation, factory logic |\n| Colocated tests | `src\u002F**\u002F*.test.ts` | Integration-style tests tightly coupled to the source module |\n| Integration tests | `tests\u002Fintegration\u002F` | Cross-module workflows, plugin initialization |\n| Security tests | `tests\u002Fsecurity\u002F` | Adversarial input handling, injection resistance |\n| Smoke tests | `tests\u002Fsmoke\u002F` | Built package validation |\n\n### Naming\n\n- Base test: `\u003Cmodule>.test.ts`\n- Adversarial variant: `\u003Cmodule>.adversarial.test.ts`\n\nOnly create an adversarial variant if it tests **distinct attack vectors** not covered by the base test. Do not duplicate base test assertions with different inputs — that's redundancy, not security coverage.\n\n### Regression tests (review-surfaced bugs)\n\nWhen fixing a bug surfaced by code review, swarm review, or post-merge audit, **always add a regression test** with the following shape so the test's purpose survives future cleanup:\n\n```typescript\ndescribe('\u003Cfeature> — regression: \u003Cone-line description> (F#)', () => {\n  it('\u003Cexact behavior the bug violated>', () => {\n    \u002F\u002F Previous code did \u003Cbad thing>: e.g. the regex `\u002F^\\.\\\u002F+\u002F` only stripped\n    \u002F\u002F a single leading `.\u002F`, so `.\u002F.\u002Futil.ts` survived as `.\u002Futil.ts`.\n    expect(normalizeGraphPath('.\u002F.\u002Futil.ts')).toBe('util.ts');\n  });\n});\n```\n\nRules:\n- The describe label includes the original finding ID (e.g. `F8`, `F9`, `F1.1`) so future readers can map back to the review.\n- The leading comment in the body explains the **prior buggy behavior** in concrete terms — what the code did before, not what it does now.\n- One regression test per finding. Do not pile unrelated assertions into a single regression block.\n\nExamples in-tree: `tests\u002Funit\u002Fgraph\u002Fgraph-query.test.ts` (`normalizeGraphPath — regression (F8)`, `getBlastRadius — regression: depthReached (F9)`), `tests\u002Funit\u002Fgraph\u002Fimport-extractor.test.ts` (`paren-preceded strings (F1)`, `member-expression require\u002Fimport (F1.1)`).\n\n## Test Quality Standards\n\n### DO\n\n- Test real behavior: call the actual function with real inputs, assert on real outputs.\n- Test error paths: what happens with `null`, `undefined`, empty string, oversized input?\n- Use temp directories (`fs.mkdtemp`) for file I\u002FO tests. Clean up in `afterEach`.\n- Assert on specific values, not just truthiness: `expect(result.status).toBe('pending')` not `expect(result).toBeTruthy()`.\n\n### DO NOT\n\n- **Do not test type definitions.** `expect(event.type === 'foo').toBe(true)` tests TypeScript, not your code.\n- **Do not test framework behavior.** \"Zod schema parses valid input\" tests Zod, not your schema.\n- **Do not test test utilities.** If it only exists to support other tests, it doesn't need its own test.\n- **Do not mock everything.** If every dependency is mocked, you're testing the mock setup. Prefer real dependencies for pure functions and only mock I\u002FO boundaries (filesystem, network, timers).\n- **Do not hardcode version numbers.** Version bumps are automated — a test asserting `version === '6.31.3'` breaks on every release.\n- **Do not use `sleep` or `setTimeout` for synchronization.** Use explicit signals, resolved promises, or `Bun.sleep()` with tight bounds.\n- **Do not spawn `cat \u002Fdev\u002Fzero`, `yes`, or other infinite-output commands.** Use `sleep 30` for \"blocking command\" tests.\n\n## Cross-Entry Invariants (config maps)\n\nWhen you modify any entry of a \"map of agents\u002Ftools\u002Froles\" in `src\u002Fconfig\u002Fconstants.ts` (`AGENT_TOOL_MAP`, `DEFAULT_MODELS`, `QA_AGENTS`, `PIPELINE_AGENTS`, etc.), there are tests that assert **parity across sibling entries**, not just shape of one entry.\n\nKnown parity assertions:\n\n| Test | Invariant |\n|---|---|\n| `tests\u002Funit\u002Fconfig\u002Fcritic-registration.test.ts:67` | `AGENT_TOOL_MAP.critic_sounding_board.length === AGENT_TOOL_MAP.critic.length` |\n| `tests\u002Funit\u002Fconfig\u002Fagent-tool-map.test.ts:26` | `AGENT_TOOL_MAP.architect.length` is strictly greater than every other agent's |\n| `tests\u002Funit\u002Fconfig\u002Fagent-tool-map.test.ts:34` | every subagent's tool list `\u003C= 20` entries |\n| `tests\u002Funit\u002Fconfig\u002Fconstants.test.ts:48` | `ALL_SUBAGENT_NAMES.length === 13` |\n| `tests\u002Funit\u002Fconfig\u002Fconstants.test.ts:137` | `Object.keys(DEFAULT_MODELS).length === 14` |\n\nWorkflow when adding a tool to a single agent:\n1. Add the entry.\n2. Run `bun --smol test tests\u002Funit\u002Fconfig --timeout 60000` **before pushing**.\n3. If a parity test fails, decide: mirror the change to sibling agents (most common — see this PR's `repo_map` mirrored to `critic_sounding_board` + `critic_drift_verifier`), or update the invariant test if the design intent has actually changed.\n4. To inspect runtime shape quickly: `bun -e \"import { AGENT_TOOL_MAP } from '.\u002Fsrc\u002Fconfig\u002Fconstants.ts'; for (const [k,v] of Object.entries(AGENT_TOOL_MAP)) console.log(k, v.length);\"`\n\nDo **not** push a constants change to CI without running the config test directory locally — these failures cascade through the per-OS unit jobs and waste minutes per push.\n\n## Cross-Platform Requirements\n\nAll tests must pass on Linux, macOS, and Windows unless explicitly gated.\n\n### Skipping tests on specific platforms\n\nUse the `skipIf` chaining pattern:\n```typescript\n\u002F\u002F Skip on Windows only\ntest.skipIf(process.platform === 'win32')('test name', async () => { ... });\n\n\u002F\u002F Skip on non-Linux (use when test relies on Linux-specific behavior)\ntest.skipIf(process.platform !== 'linux')('test name', async () => { ... });\n\n\u002F\u002F Skip entire describe block\ndescribe.skipIf(process.platform === 'win32')('group name', () => { ... });\n```\n\n### Temp directories and path handling\n- Use `path.join()` or `path.resolve()`, never string concatenation with `\u002F`.\n- Temp directories: use `os.tmpdir()`, never hardcoded `\u002Ftmp`.\n- **CRITICAL: Wrap `mkdtempSync` with `realpathSync` when using `process.chdir`:**\n  ```typescript\n  \u002F\u002F WRONG — on macOS, \u002Ftmp is a symlink to \u002Fprivate\u002Ftmp.\n  \u002F\u002F mkdtempSync returns \u002Ftmp\u002F... but process.cwd() resolves to \u002Fprivate\u002Ftmp\u002F...\n  const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'test-'));\n  process.chdir(tempDir);\n  \u002F\u002F process.cwd() !== tempDir on macOS!\n\n  \u002F\u002F CORRECT — resolve symlinks first\n  const tempDir = fs.realpathSync(\n    fs.mkdtempSync(path.join(os.tmpdir(), 'test-')),\n  );\n  process.chdir(tempDir);\n  ```\n- File comparisons: normalize paths before comparing (`path.resolve(a) === path.resolve(b)`).\n\n### Permissions (`fs.chmodSync`)\n- `chmodSync` is a **no-op for directories** on Windows and unreliable for files.\n- Tests that rely on chmod to simulate permission errors should guard with platform checks:\n  ```typescript\n  if (process.platform !== 'win32') {\n    fs.chmodSync(filePath, 0o000);\n    \u002F\u002F ... test permission error behavior ...\n    fs.chmodSync(filePath, 0o644); \u002F\u002F restore\n  } else {\n    \u002F\u002F On Windows, skip or use a mock to throw EPERM\n  }\n  ```\n- If the test asserts that the tool handles permission errors **gracefully** (returns success despite write failure), the test may pass on Windows even without chmod — the write just succeeds. Verify this before adding guards.\n\n### Symlinks\n- `fs.symlinkSync` requires **administrator or developer mode** on Windows.\n- Use a runtime capability check:\n  ```typescript\n  let canCreateSymlinks = false;\n  try {\n    const testLink = path.join(tempDir, '.symlink-test');\n    fs.symlinkSync(tempDir, testLink);\n    fs.unlinkSync(testLink);\n    canCreateSymlinks = true;\n  } catch {}\n\n  test.skipIf(!canCreateSymlinks)('symlink test', async () => { ... });\n  ```\n\n### Process spawning\n- Use `.cmd` extension on Windows for npm\u002Fbun binaries: `process.platform === 'win32' ? 'bun.cmd' : 'bun'`.\n- Use array-form `spawn`\u002F`spawnSync`, never shell string commands.\n- **`npx` in empty temp dirs hangs on Windows.** If a test creates a temp directory with a `package.json` (for framework detection) and then calls a tool that spawns `npx vitest run` or similar, the spawn will hang until the test timeout fires. Skip these tests on non-Linux:\n  ```typescript\n  \u002F\u002F Flaky on macOS\u002FWindows: spawns vitest in temp dir without node_modules\n  test.skipIf(process.platform !== 'linux')(\n    'test that triggers process execution',\n    async () => { ... },\n    15000,\n  );\n  ```\n\n### Timestamps\n- Avoid comparing strings that embed `new Date().toISOString()`. Two sequential calls can span a millisecond boundary, especially on Windows CI. Strip or normalize volatile timestamps before comparison:\n  ```typescript\n  const stripTimestamp = (s: string) =>\n    s.replace(\u002FUpdated: \\d{4}-\\d{2}-\\d{2}T[\\d:.]+Z\u002F, 'Updated: \u003CFROZEN>');\n  expect(stripTimestamp(output1)).toBe(stripTimestamp(output2));\n  ```\n\n## Running Tests\n\n```bash\n# Full suite (all platforms)\nbun test\n\n# Single file\nbun test tests\u002Funit\u002Fhooks\u002Fscope-guard.test.ts\n\n# Single directory\nbun --smol test tests\u002Funit\u002Fhooks --timeout 30000\n\n# CI-equivalent run (per-file isolation, matches actual CI behavior)\nfor f in tests\u002Funit\u002Ftools\u002F*.test.ts; do bun --smol test \"$f\" --timeout 120000; done\n\n# Quick directory run (faster but may have cross-file cache pollution)\nbun --smol test tests\u002Funit\u002Fcli --timeout 120000\nbun --smol test tests\u002Funit\u002Fcommands tests\u002Funit\u002Fconfig --timeout 120000\n```\n\nThe `--smol` flag reduces Bun's memory footprint. Use it when running large directories (50+ files).\n\nThe `--timeout 120000` flag sets per-test timeout to 120 seconds. Individual tests should complete in under 5 seconds. If a test needs more than 10 seconds, it's doing too much — split it or mock the slow dependency.\n\n**Note:** CI runs each file in its own Bun process (`for f in dir\u002F*.test.ts; do bun --smol test \"$f\"; done`). Running an entire directory at once (`bun --smol test tests\u002Funit\u002Ftools\u002F`) can mask cache-poisoning issues that only appear in CI. When debugging CI failures, test files individually.\n\n## Debugging CI failures\n\nWhen CI reports a `unit (ubuntu-latest|macos-latest|windows-latest)` failure:\n\n1. **Identify the actual failing test from the job log first.** Do not assume it's a pre-existing failure based on a local repro of a different test. Open the failing job's URL (`https:\u002F\u002Fgithub.com\u002F\u003Cowner>\u002F\u003Crepo>\u002Factions\u002Fruns\u002F\u003Crun-id>\u002Fjob\u002F\u003Cjob-id>`) and find the `\u003Cfile>:\u003Cline>` in the Bun output. WebFetch can scrape this if the `gh` CLI isn't available.\n2. **Reproduce that exact file locally** with the per-file CI command:\n   ```bash\n   bun --smol test tests\u002Funit\u002F\u003Cdir>\u002F\u003Cfile>.test.ts --timeout 30000\n   ```\n3. **Then check if the same failure reproduces on `main`.** If yes, document as pre-existing in the PR description and continue with your branch's work; do not silently inherit the failure.\n4. **For dist-check failures:** any change under `src\u002F` that the bundler picks up requires `bun run build` + commit of `dist\u002F` in the same PR. The job compares committed `dist\u002F` against a fresh build.\n5. **For matrix-OS-only failures:** check `process.platform` guards, `mkdtempSync` realpath wrapping, chmod guards, symlink capability checks, and `npx`-spawn skips (sections above).\n\n## Before Submitting\n\n1. Run the tests for your changed files: `bun test path\u002Fto\u002Fyour.test.ts`\n2. Run the full CI group your tests belong to (see pipeline structure above)\n3. Verify no `process.cwd()` usage — use the `directory` parameter from `createSwarmTool` or hook constructor\n4. Verify no hardcoded paths (`\u002Ftmp\u002F...`, `C:\\...`) — use `os.tmpdir()` + `path.join()`\n5. Verify mocks are restored in `afterEach` if using `spyOn` or `mock.module`\n6. Verify `mkdtempSync` is wrapped with `realpathSync` if you use `process.chdir` on the result\n7. Verify `chmodSync` calls are guarded with `process.platform !== 'win32'`\n8. Verify symlink creation is guarded or uses a `canCreateSymlinks` capability check\n9. Verify no `new Date().toISOString()` in equality assertions — strip volatile timestamps\n10. Verify tests that spawn `npx`\u002F`vitest`\u002F`jest` in temp dirs are skipped on non-Linux\n",{"name":5,"effort":23,"description":24},"medium","Apply when writing tests, modifying test files, fixing test failures, debugging CI failures, adding test coverage, creating adversarial tests, or reviewing any file under tests\u002F. Also apply when implementing features or fixes that require corresponding test changes. Enforces bun:test framework rules, mock isolation, cross-platform compatibility (Linux, macOS, Windows), and CI pipeline awareness. Load this skill before touching any test file.\n","main","f37de8f681f0c0ca0e0ebab6e5fddf764ca7553d","skills\u002Fwriting-tests",1,"https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one","https:\u002F\u002Fagisota.github.io\u002Fold-one\u002F","https:\u002F\u002Fgithub.com\u002Fagisota","pzd.world","2026-07-04 22:32:06",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add agisota\u002Fold-one --skill writing-tests",{"tool":40,"command":41},"bunx","bunx skills add agisota\u002Fold-one --skill writing-tests",{"tool":43,"command":44},"pnpm","pnpm dlx skills add agisota\u002Fold-one --skill writing-tests","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fwriting-tests\u002FSKILL.md",true,[],[49,56,63,72,79,86],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M75KRGZWQWE9JDBS6RX42NWV","zoom-out","Tell the agent to zoom out and give broader context or a higher-level perspective. Use when you're unfamiliar with a section of code or need to understand how it fits into the bigger picture.","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fzoom-out\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":18},"01M75KRCZHKE0ZYAQFFYHS0YNP","zeroize-audit","Detects missing zeroization of sensitive data in source code and identifies zeroization removed by compiler optimizations, with assembly-level analysis, and control-flow verification. Use for auditing C\u002FC++\u002FRust code handling secrets, keys, passwords, or other sensitive data.","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fzeroize-audit\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":67,"licenseFileUrl":68,"sourceHtmlUrl":69,"categories":70,"keywords":71,"publishedAt":18},"01M75KR94KYQ30DTE1P9WNDAE0","yeet","Use only when the user explicitly asks to stage, commit, push, and open a GitHub pull request in one flow using the GitHub CLI (`gh`).","Apache-2.0","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fyeet\u002FLICENSE.txt","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fyeet\u002FSKILL.md",[],[],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":18},"01M75KR3H13YJ9QHMD49818FA1","yara-rule-authoring","Guides authoring of high-quality YARA-X detection rules for malware identification. Use when writing, reviewing, or optimizing YARA rules. Covers naming conventions, string selection, performance optimization, migration from legacy YARA, and false positive reduction. Triggers on: YARA, YARA-X, malware detection, threat hunting, IOC, signature, crx module, dex module.","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fyara-rule-authoring\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M75KQMPY8A4Y8XTDD2DT0M9T","x-twitter-growth","X\u002FTwitter growth engine for building audience, crafting viral content, and analyzing engagement. Use when the user wants to grow on X\u002FTwitter, write tweets or threads, analyze their X profile, research competitors on X, plan a posting strategy, or optimize engagement. Complements social-content (generic multi-platform) with X-specific depth: algorithm mechanics, thread engineering, reply strategy, profile optimization, and competitive intelligence via web search.","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fx-twitter-growth\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":18},"01M75KQHNZ0ANZNJGZY6M8MDAK","x-api","X\u002FTwitter API integration for posting tweets, threads, reading timelines, search, and analytics. Covers OAuth auth patterns, rate limits, and platform-native content posting. Use when the user wants to interact with X programmatically.","https:\u002F\u002Fgithub.com\u002Fagisota\u002Fold-one\u002Fblob\u002Fmain\u002Fskills\u002Fx-api\u002FSKILL.md",[],[]]