# Contributing to OpenCode Swarm > **This file is the authoritative reference for any automated agent (LLM, Copilot, CI bot) or human contributor submitting a PR to this repository. Read it fully before making any commit.** > > **Required reading before code changes:** > 1. [`AGENTS.md`](./AGENTS.md) — root engineering contract (12 non-negotiable invariants). > 2. [`docs/engineering-invariants.md`](./docs/engineering-invariants.md) — long-form rationale and historical failure map (skim, deep-dive on touched invariants). > 3. This file (`contributing.md`) — release-please workflow and CI pipeline. > 4. The `writing-tests` skill — for any test changes (`.opencode/skills/writing-tests/SKILL.md` or `.claude/skills/writing-tests/SKILL.md`). > 5. The `commit-pr` skill — before committing or opening a PR (`.claude/skills/commit-pr/SKILL.md`). It enforces the invariant audit gate. > > When this file conflicts with `AGENTS.md`, `AGENTS.md` wins. --- ## Filing issues — issues are executable contracts Issues in this repository are not prose requests: they are **executable contracts**. A well-formed issue can be frozen into acceptance checks, proven RED at the base commit, and proven GREEN at the head of its PR, with independent reviewer and critic gates in between. Every criterion that can be executable must be bound to a check — a criterion with a fake or missing binding is miswritten. Criteria that genuinely cannot be executable take the NON-EXECUTABLE path below instead. This section defines the contract; the tracer workflow consumes this shape. Existing issues filed before this contract are grandfathered; it governs new issues. **Where this sits in the field.** The acceptance-criteria grammar below is [EARS](https://alistairmavin.com/ears/) (Easy Approach to Requirements Syntax — Mavin/Rolls-Royce, 2009; used across aerospace and heavyweight systems engineering). The overall shape — specification before plan, plan before tasks, human gates around implementation — is the same family as [GitHub Spec Kit](https://github.com/github/spec-kit)'s constitution → specify → plan → tasks → implement → converge. Our differentiator: the specification lives in the tracker (the issue itself), and acceptance is **proven executably** (frozen checks run RED at base, GREEN at head) rather than by implementation review alone. The one-AC-one-check rule is classical requirements traceability: every requirement gets exactly one chosen verification method. ### Two issue types 1. **Standalone issues** (feature, bug, investigation): the required core below, no title convention beyond a clear outcome-oriented statement. 2. **Workstream program issues**: when a program spans multiple PRs, give each issue one accountable PR slot and use the title ``[Workstream ] PR of : `` — workstreams are parallel-capable tracks, PRs within a workstream are sequential, and related issues may share a reviewable PR when the maintainer authorizes it. Each body carries a `## Sequence` section naming the full chain (`#A -> #B -> ...`) and its depends-on/blocks relationships. The umbrella tracker/epic issue (workstream table, closure ledger, maintainer-gated items, checklist) is repo-specific; see the repo notes at the end of this file. ### Issue triage with ZaxbyGraph Include the affected area, observed impact, target branch, and any real prerequisites in the issue body. Link related issues, findings, and pull requests. Issue authors can leave the tagging to their authorized coding harness. Before selecting work, refresh the existing ZaxbyGraph cache incrementally. Use the repository's configured queue query when it has one. Otherwise use `zaxbygraph triage` with the repository's open issues and PRs. Check the live issue comments for active claims and inspect open PRs for overlaps. Prioritize demonstrated impact and work that unblocks other issues. If a required tool fails or returns inconsistent results, report the failure and pause the affected workflow. Apply the label families the repository already uses. Record the issue type, severity for impact, scheduling priority, relevant areas and platforms, and target branch or workstream where applicable. Keep one severity and one priority when those label families exist. Record unavailable label metadata in the issue body or claim comment. Where a managed queue is configured, give each lead one active stage. Keep leads with unresolved decisions, missing acceptance evidence, or open prerequisites held. Related issues and duplicates should not compete for dispatch. Use native GitHub **Blocked by** links for genuine prerequisites and explain why each must land first. If a prerequisite closes without delivery, keep its successors held until the dependency is replaced or shown to be unnecessary. After changing dispatch labels or blockers, refresh the same graph and verify the updated issue. If the repository has a managed queue, also verify that the issue appears at the expected stage or is excluded while held. Recheck live comments and assignees immediately before claiming. Claim each issue you take on by posting a comment with the harness session ID and intended scope. Skip issues another session already owns. When the maintainer authorizes a shared PR, claim each included issue and keep separate acceptance evidence for each. Share a PR only when the combined change is reviewable. ### Body anatomy (required core) Every verifiable issue has, in this order: 1. **Provenance preamble** (italic, first line): where the issue was generated from (audit run, session, plan), the exact commit every claim was re-checked against (full SHA), the one-issue-one-PR statement, and a disclaimer for any referenced local artifacts that are not in this repository. 2. `## Summary` — what will be true after this PR that is not true today. Outcome-framed, not task-framed. 3. `## Problem (claims to verify)` or `## Current state (evidence)` — numbered claims, each carrying: - a file:line reference, as a permalink anchored to the full SHA named in the preamble; - a code excerpt for load-bearing lines (the lines a fix will touch or a check will read); - an **epistemic label** — `VERIFIED` (re-checked at the anchor commit; say how) or `INFERENCE` (motivating but unproven) — so the implementer knows which premises still need proving; - a **prior-art reconciliation** note when a claim overlaps existing implementations (name them and state which one this PR extends rather than duplicates); - corrections discovered during review are **preserved inline** (`CORRECTED during review: ...`), never silently rewritten — the issue is a living record of what was claimed and what was verified. 4. `## Scope` — `In:` and `Out:` (out-of-scope items reference their owning issue when they have one). 5. `## Acceptance criteria` — the contract (next subsection). Non-negotiable. 6. `## Sequence` — programs only (above). ### The acceptance-criteria contract Each criterion is a checkbox line in **EARS grammar**: ``` - [ ] ACn: WHEN , THE SYSTEM SHALL ``` - Sequential from `AC1`, nothing between the id and the colon, each AC appears exactly once. One AC binds to exactly **one** frozen check — never share a check across ACs. - EARS patterns, in order of preference for this repo: **event-driven** (`WHEN , THE SYSTEM SHALL ` — the default), **ubiquitous** (`THE SYSTEM SHALL ` — always-true properties; the natural shape for PRESERVING criteria), **unwanted-behavior** (`IF , THEN THE SYSTEM SHALL ` — error paths), **state-driven** (`WHILE , THE SYSTEM SHALL `), **optional-feature** (`WHERE , THE SYSTEM SHALL `). - The response must be **observable** — a test can assert it. "The system shall be more robust" is not a response. Each AC carries exactly five sub-bullets: ``` - [ ] AC1: WHEN , THE SYSTEM SHALL . - class: DISCRIMINATING | NEW-SURFACE | PRESERVING - argv: - expect: - files: - why: ``` | class | meaning | base leg | head leg | |---|---|---|---| | `DISCRIMINATING` | the defect exists today | **RED** (the failure signature) | GREEN | | `NEW-SURFACE` | the fix creates a surface that cannot exist at base (new spec, new tool) | deterministic **absence** signature — the runner's literal no-matches output (e.g. vitest's `No test files found`, bun's `The following filters did not match any test files:`) | GREEN | | `PRESERVING` | a regression floor | GREEN | GREEN | Honest-class rules: - Do not label an AC `DISCRIMINATING` unless it is genuinely red at the anchor commit — run the check mentally (or for real) against base before claiming it. - A `NEW-SURFACE` AC must fail at base with a **deterministic** absence signature, never an environmental error (missing runtime, network). If the driver cannot exist at base, the driver itself prints a sentinel line and exits nonzero. - `PRESERVING` criteria are regression floors: they must be green at base and stay green at head. A PRESERVING check that regresses at head is a fix bug, not a check bug. - **No vacuous checks.** An AC shaped "do X and observe failure" that cannot fail on the primary dev/test runtime is a false contract — route the probe through a context where it can genuinely fail, or reshape the AC. **NON-EXECUTABLE criteria.** Some criteria have no meaningful executable check — docs-only changes, host-only behavior (GUI/TUI surfaces a check cannot drive), maintainer product decisions, unavailable external services. For those, write `class: NON-EXECUTABLE()` with the closed reason enum `DOCS_ONLY | HOST_ONLY | PRODUCT_DECISION | EXTERNAL_SERVICE_UNAVAILABLE`, replace `argv`/`expect` with **named substitute evidence** (a review artifact, a decision recorded on the issue, a captured external state), and get plan-critic approval for the substitution — never force an artificial executable check; that is the vacuous shape the rule above forbids. - `argv` is one command, runnable from the repository root, POSIX-safe, deterministic (use the repo's test-runner flags for hermetic runs — see repo notes). `expect` describes what the **base** leg shows; the head leg's pass condition lives in the check's own exit logic. ### Published acceptance commands The published `argv:` is the command the trace must prove at both revisions. When it cannot witness the fix, disclose the affected criterion, both commands, and their observed outcomes before asking the maintainer to correct the published criterion. ### Evidence rules - Every claim is anchored: permalinks embed the full SHA; before filing, re-verify each claim at that commit and say so in the preamble. - Quotes and excerpts must exist verbatim in the cited file at the cited lines — grep each one before filing (a fabricated quote propagates into every downstream ledger). - When line numbers matter, confirm the cited file is unchanged between the anchor commit and filing (or re-anchor). - Label every non-trivial claim `VERIFIED` or `INFERENCE`. ### Extended-section menu (recommended for design-heavy and program issues) The core is the required minimum. For issues whose fix has real design surface, add any of these (they **inform**, the ACs **bind** — if a Design section and an AC disagree, the AC wins and the Design section gets corrected): `## Why (evidence)` · `## Current behaviour` · `## Dependencies` (`Depends on:` / `Gated on:` / `Blocks:`) · `## Design` (numbered, with exact signatures) · `## Files to change` · `## Tests` (named spec files) · `## Fixtures to add` · `## Local verification recipe` (commands) · `## Release rules` · `## Definition of done` ### Filing checklist (self-review before Create) - [ ] Preamble names the source, the anchor SHA, and re-verification - [ ] Every claim has a full-SHA permalink; every quote greps clean at that SHA; VERIFIED/INFERENCE labeled - [ ] Scope has both In and Out - [ ] ACs sequential, each exactly five sub-bullets, one-AC-one-check - [ ] Classes honest (DISCRIMINATING genuinely red at base; NEW-SURFACE deterministic absence; PRESERVING green-both-ends) - [ ] No vacuous checks; argv runnable from repo root; expect describes the base leg - [ ] Program issues: title `[Workstream ] PR n of m`, Sequence section, and one accountable PR slot per issue - [ ] Any NON-EXECUTABLE criterion carries a closed-enum reason and named substitute evidence (not a forced check) - [ ] Follow-up issues: passed the necessity gate below, collated into at most two issues per source PR (more needs the maintainer's go-ahead, Priority items excepted), titled `Follow-up from PR #N: ` ### Filing follow-up issues This section covers work found during a PR review or a PR-feedback round that the PR does not fix. Agents and contributors handle it the same way. Issue-tracer closeouts keep their own full-resolution contract (the issue-tracer skill's `references/full-resolution-contract.md`): a separable concern there is fixed or filed with the user's acknowledgment, and this section does not waive any of its clauses. Collation and the title convention below still apply to issues filed from a trace. Anything the PR introduced is fixed in the PR, not routed here; a small pre-existing item inside the PR's files and scope is fixed only with the maintainer's go-ahead. Nothing is silently dropped. Equally, not every leftover becomes an issue: most review findings are never acted on, and filing all of them turns review noise into backlog noise. **1. Give every unfixed item exactly one disposition.** | Disposition | When | |---|---| | `ABSORB` | An open issue already covers it. Comment on that issue with the new evidence instead of opening a new one. | | `FILE` | It passes the necessity gate (step 2) and is Priority, or the maintainer approved it. | | `RECORD` | It fails gate 1 or gate 2, or the maintainer declined it. Add a row to the PR body's "Considered, not filed" table (inside `## Summary`) with: the item, the reason, which gate test failed, and a re-evaluation trigger. This is a complete closure. | | `ASK` | It needs a product or maintainer decision, it fails only gate 3, or it is an Improvement item awaiting approval. Ask before filing anything; a decline makes it `RECORD` (quote it); an approval makes a gate-3 or Improvement item `FILE`, lands a gate-4 fix in the PR, and sends an unverified item back to investigation. | `ASK` takes precedence over fixing in the PR when the fix itself needs a product or compatibility decision. `ABSORB` takes precedence over `RECORD` when an open issue already covers the item. **2. Apply the necessity gate.** `FILE` only when all four hold, or when the maintainer approves an `ASK` proposal. Failing gate 1 or 2 is `RECORD`, except that an unverified item claiming a wedge, fail-open gate, security, or data-loss consequence is `ASK`. Failing only gate 3 makes the item an Improvement proposal (`ASK`). Failing gate 4 means `ABSORB` (already tracked) or `ASK` to fix it in the PR (fixable here), never `RECORD` without the maintainer's decline. A wedge, fail-open gate, security, or data-loss consequence satisfies gate 3. 1. **Verified.** An executed probe or an exact `path:line` source trace proves it on the current head. An `INFERENCE` is never filed. 2. **Consequential.** There is a concrete, reachable trigger with a correctness, safety or security, data-loss, or workflow-blocking consequence. Coverage gaps, docs, wording, and "could harden" items fail unless they hide a real defect. 3. **Material.** It is on a hot path, invalidates a gate or contract, or blocks planned work. 4. **Untracked and not fixable here.** No open issue covers it, and it cannot be fixed in the PR without leaving the PR's files or scope. **3. Collate the survivors.** - All `FILE` items from one PR go into one issue titled `Follow-up from PR #: `, in the executable-contract format above, with at least one acceptance criterion per item, each bound to its own check. - Split into a second issue only when the items genuinely need separate PRs. A HIGH-severity item (fail-open gate, security, data loss) may stand alone. - More than two follow-up issues from one PR needs the maintainer's go-ahead before filing (Priority items excepted). A standalone HIGH item counts toward the two. Priority items over the budget are still filed, and the overflow is reported. **4. Respect the two tiers.** - **Priority** items (a wedge, fail-open gate, security, or data loss) are filed after the closeout review, once the push is published. - **Improvement** items that pass the gate are proposed as a list in the final response to the maintainer and filed only once the maintainer approves. - Findings about how the review or feedback round was conducted, such as an incomplete ledger or a missed disposition, are `RECORD` unless they block a workflow. This never covers defects in any code, skill text, or gate, changed by the PR or not: PR-introduced ones are fixed in the PR, and a fail-open gate is Priority. **5. Keep the record true.** A disposition is planned before the closeout review and executed after the push. The published record states it only after it is true on the live artifact: the issue is filed, the comment is posted, or the table row is in the PR body. The swarm-pr-feedback ledger form of this rule is the swarm-pr-feedback skill's `references/followup-dispositions.md`. ### Repo notes (opencode-swarm) - **argv conventions for this repo**: checks run with `bun` (`bun --smol test --timeout 30000`, per-file where mock conflicts exist — see the test rules below). New test files must use `canonicalMkdtemp`/`createSafeTestDir` for temp dirs (FR-011: a raw `os.tmpdir()` in a new test fails CI), stay under the 500-line test-file cap (FR-006), and follow `.opencode/skills/writing-tests`. - **Tracker convention**: program tracker issues are titled `[Epic] ...`; workstream letters are allocated per program. - The PR side of the contract (title format, invariant audit, release fragment) is the rest of this file. - A `NEW-SURFACE` argv naming a spec that does not exist at base fails with bun's literal `The following filters did not match any test files:` (or `Test filter "./..." had no matches` for the path form) — that is the deterministic absence signature; write it in `expect` verbatim. --- ## Managed issue dispatch For the managed replacement backlog, use the configured polling edition and apply `dispatch:lead` to the issue that owns the implementation contract. Set one `queue:*` stage. Use `hold` for missing evidence, prerequisites, or decisions, `investigate` for bounded diagnosis, `qualify` for acceptance verification, `implement` after the evidence is accepted, and `active-pr` once a PR owns the work. Record the stable contract key, PR slot, and prerequisite contract keys in a single `dispatch-v1` marker. For an independent slot, set `needs` to `"|"` and `count` to `0`. For a dependent slot, list the distinct prerequisite keys between pipes and record their count. Use matching native GitHub blocker links and preserve the source issue links and finding IDs in the body. After syncing ZaxbyGraph, check that eligible leads appear once at the expected stage and held leads are excluded. ## End-to-end PR workflow This is the complete sequence for getting code from your branch to an npm release. Every step matters — skipping one breaks the pipeline downstream. ### 1. Set up your branch ```bash git checkout main && git pull origin main git checkout -b / # e.g. feat/add-retry-backoff bun install --frozen-lockfile ``` > **`dist/` is generated, not committed** (#1047). The plugin entry (`package.json#main` > → `dist/index.js`) only exists after a build. `bun install` builds it automatically via > the `prepare` script, so a fresh clone is runnable. If you load the plugin from this > checkout and pull source changes **without** re-running `bun install`, refresh the bundle > with `bun run build` (or `bun run dev`, which builds then launches OpenCode) before the > plugin will load. The build is cross-platform (bun + tsc, no OS-specific steps). ### 2. Make your changes - Write code, tests, and docs - Follow the commit message format below for every commit - Follow the test rules in `.opencode/skills/writing-tests/SKILL.md` (bun:test only, mock isolation, cross-platform paths) - If you change behavior guarded by existing tests, **update those tests in the same PR** ### 3. Write a pending release-note fragment **Every PR with a user-visible change MUST add a unique fragment at `docs/releases/pending/.md`.** Do NOT compute the next version, do NOT create `docs/releases/vX.Y.Z.md`, and do NOT write to a shared `unreleased.md` — release-please picks the version and the release workflow aggregates pending fragments at release time. See the "Release notes" section below for what each fragment should contain. ### 4. Run all checks locally ```bash # Tier 1 — quality (must pass before anything else) bun run typecheck bunx biome ci . # Tier 2 — unit tests (all platforms in CI; run locally on yours) # For directories with mock conflicts, use per-file loops: for f in tests/unit/tools/*.test.ts; do bun --smol test "$f" --timeout 30000; done # CI also isolates hook files per file because several hooks share mutable mocks: for f in src/hooks/*.test.ts tests/unit/hooks/*.test.ts; do bun --smol test "$f" --timeout 30000; done # For directories without known mock conflicts, batch is fine: bun --smol test tests/unit/cli tests/unit/commands tests/unit/config --timeout 120000 # Tier 3 — integration tests bun test tests/integration ./test --timeout 120000 # Tier 4 — security and adversarial tests bun test tests/security --timeout 120000 bun test tests/adversarial --timeout 120000 # Tier 5 — build + smoke (smoke tests require a successful build first) bun run build bun test tests/smoke --timeout 120000 ``` ### Canonical repository-validation command (issue #2675) The CI-equivalent entry point is the shared, bounded repository-validation authority. It runs every supported surface in inventory order and persists a schema-versioned report under `.swarm/`: ```bash # Complete repository matrix bun run validate:repo -- --mode full --diff-base origin/main # Changed-work matrix; no discovered work reports no_op, not passed bun run validate:repo -- --mode diff --diff-base origin/main ``` In diff mode, selection is based on committed branch changes in `...HEAD`; unstaged and untracked work is excluded. The complete inventory is: `quality`, `unit`, `integration`, `security`, `coverage`, `memory-recall-regression`, `package-check`, `smoke`, `php-validation`, and `rust-sandbox-runner`. Each report has `schemaVersion: 1`, runtime metadata (`bunVersion`, `platform`, `arch`), the exact array-form command and cwd for each item, the `origin/main` diff base, per-item terminal status, bounded output, timing, signal, and cleanup outcome. Terminal statuses are `passed`, `failed`, `crashed`, `timed_out`, `missing`, `skipped`, and `output_truncated` (a child whose run completed with no timeout and no crash — tree cleanup succeeded, no signal, known exit code — but whose bounded stdout/stderr reader missed its deadline; the terminal evidence was only partially observed, so the row counts as failed (#3664)); a run containing an unresolved crash, timeout, missing item, or skip is `incomplete` rather than a complete pass. Run-level statuses are `passed`, `failed`, `incomplete`, and `no_op`, with `no_op` reserved for an empty diff selection. Use repeatable `--surface ` or comma-separated `--surfaces ` for a deliberate subset; omitting both runs the full ten-surface matrix. An unavailable required runtime produces a `skipped` item with a reason and an `incomplete` run (nonzero exit), including in full-matrix mode; missing tools must not be reported as a pass. Validation bounds are fixed by default at 120000 ms for each test process, 180000 ms per item, 900000 ms for the whole run, and 65536 bytes per output channel after redaction. Test argv uses the keepalive preload `scripts/ci/bun-32056-keepalive.ts`, and file paths remain individual argv tokens so quoted or spaced paths are reproduced exactly. The historical `659/3,389` count is an unconfirmed historical count: the raw per-item output and provenance were not retained, so that figure cannot be used as current reproducible evidence. New validation reports retain the bounded raw evidence needed to distinguish pass, failure, crash, timeout, missing, and skip. Fix any failures before proceeding. If a test failure is pre-existing and unrelated to your changes, note it in the PR description but do not skip the other tiers. ### 5. Push and open a PR ```bash git push -u origin gh pr create --title "(): " --body "$(cat <<'EOF' ## Summary <1-3 bullet points explaining what and why> ## Test plan - [ ] EOF )" --base main ``` The PR title is preserved in the merge commit and is what release-please reads. It must follow the conventional commit format exactly (see below). The `pr-standards` CI check enforces this. ### 6. Wait for CI All checks must be green before merging. See the "CI checks" section below for the full list. ### 7. Merge the PR `main` requires a GitHub merge queue (repository ruleset, `merge_method: MERGE`) — once required checks and review are green, add the PR to the merge queue rather than merging directly; GitHub re-validates and merges it as a two-parent merge commit, not a squash. The PR title is preserved as the merge commit's body (GitHub's default merge-commit template: `Merge pull request #N from ` subject, PR title as body), which is what release-please reads — do not assume a squash-commit history when working with `git log`. ### 8. What happens automatically after merge 1. `release-please` runs and creates (or updates) a release PR (e.g. `chore(main): release 6.41.0`) 2. The `update-pr-notes` job prepends your `docs/releases/` file to the release PR body (preserving release-please markers — see "How releases work" below) 3. When someone merges the release PR, release-please creates a git tag + GitHub Release, and the `publish-npm` job publishes to npm automatically **Do not manually create tags, releases, or run `npm publish`.** The pipeline handles everything. --- ## How releases work This repository uses [release-please](https://github.com/googleapis/release-please) (`release-type: node`) to automate versioning, changelog generation, and npm publishing. The entire release pipeline is driven **exclusively by commit messages and PR titles**. There is no manual versioning step. When a PR is merged to `main`: 1. `release-please` reads every commit message merged since the last release tag 2. It determines the next semver version bump based on conventional commit types 3. It creates or updates a "release PR" that bumps `package.json`, updates `CHANGELOG.md`, and updates `.release-please-manifest.json` 4. When that release PR is merged, it creates a git tag + GitHub Release and publishes to npm **If your commit messages are malformed, release-please will either ignore your changes in the changelog or produce the wrong version bump.** There is no recovery path other than a follow-up fix commit. ### Critical: release-please PR body markers release-please identifies its own PRs by parsing markers in the PR body (the `:robot: I have created a release` header and structured changelog). **Never replace the entire body of a release PR.** The `update-pr-notes` CI job aggregates pending release-note fragments from every PR referenced in the release-please PR body and inserts the combined content inside a stable `` … `` marker block — release-please's own markers must remain intact below it. Same flow runs against the GitHub Release body after a tag is cut via `update-release-notes`. The implementation is `scripts/release-notes-fragments.mjs`. ### What release-please manages automatically — do not touch manually - `package.json` → `version` field - `CHANGELOG.md` - `.release-please-manifest.json` If you manually edit any of these files in a PR, release-please will conflict with itself on the next run. Leave them alone. --- ## Commit message format (Conventional Commits) Every commit **and every PR title** must follow this format exactly: ``` (): ``` - The description must be lowercase and not end with a period - The type must be one of the allowed types below - Scope is optional but encouraged for clarity ### Allowed types and their semver effect | Type | Changelog section | Version bump | |---|---|---| | `feat` | Features | **minor** (e.g. 6.30.1 → 6.31.0) | | `fix` | Bug Fixes | **patch** (e.g. 6.30.1 → 6.30.2) | | `perf` | Performance Improvements | **patch** | | `revert` | Reverts | **patch** | | `docs` | Documentation | none (not included in changelog) | | `chore` | — | none (not included in changelog) | | `refactor` | — | none (not included in changelog) | | `test` | — | none (not included in changelog) | | `ci` | — | none (not included in changelog) | | `build` | — | none (not included in changelog) | > **Note:** Types that produce "none" version bump (`docs`, `chore`, `refactor`, `test`, `ci`, `build`) will not trigger a release on their own. If your PR only contains these types, release-please will not create a release PR until a bump-producing commit (`feat`, `fix`, `perf`, `revert`) is merged. ### Breaking changes → major bump To trigger a **major** version bump (e.g. 6.30.1 → 7.0.0), add a footer to the commit body: ``` feat: redesign swarm orchestration API BREAKING CHANGE: SwarmConfig.agents field renamed to SwarmConfig.workers ``` Or append `!` to the type: ``` feat!: redesign swarm orchestration API ``` ### Valid examples ``` feat(architect): add retry backoff to SME delegation fix(circuit-breaker): prevent race condition on concurrent invocations perf(plan-sync): reduce lock contention in worker handoff docs: update getting-started guide for bun 1.2 chore: bump @opencode-ai/sdk to 1.1.54 test(gate): add adversarial coverage for evidence summary init ci: add tiered test pipeline and PR quality checks refactor(swarm): extract phase orchestration into dedicated module ``` ### Invalid examples (will be rejected by `pr-standards` CI check) ``` WIP fix stuff Update README feat: Add new feature. ← trailing period Feat: new feature ← uppercase type feature: new thing ← not an allowed type ``` --- ## PR title requirement The PR title is used by release-please as the merge commit message (see "Merge the PR" above — `main` uses a required merge queue, not a squash merge). **It must follow the same conventional commit format as individual commits.** The `pr-standards` CI check will block merging if the title is invalid. Choose the type that matches the **primary change** in the PR: - New capability → `feat` - Bug fix or correctness fix → `fix` - Mixed feat + fix → use `feat` (minor bump subsumes patch) --- ## What CI checks must pass before merging The protected `main` ruleset currently requires the exact contexts recorded in the [machine-readable required-check contract](scripts/required-check-contract.json) and its [fresh external evidence](docs/ci/required-check-evidence.json). That contract is the live required set; it is not a claim that every workflow job or matrix cell runs on every pull request. | Live required context(s) | What it validates | |---|---| | `quality` | TypeScript compiles (`tsc --noEmit`), Biome lint + format clean | | `unit (ubuntu-latest, 1)` through `unit (ubuntu-latest, 4)` | Required Ubuntu unit-test shards | | `unit-passed` | Aggregate of the `unit` matrix (additional platform cells are event- or path-scoped) | | `security` | Security and adversarial tests pass | | `package-check` | Package metadata and publishable artifact checks pass | | `integration` (Ubuntu) | Integration tests pass (circuit breakers, gate workflows, state machines) | | `smoke (ubuntu-latest)`, `smoke (macos-latest)`, `smoke (windows-latest)` | Package builds successfully and smoke tests pass on each required platform | | `php-validation` | PHP language/build fixtures and validation tests pass | | `rust-sandbox-runner` | Rust sandbox runner builds and validates | | `check-title` and `pr-standards` | PR title and standards checks pass | | `coverage` (merge queue only) | Code coverage ≥ 65.00% over the merged union of the 6-way `coverage-shard` matrix (issue #2341; fail-closed if any shard report is missing) | The `unit` and `smoke` rows expand into event- and path-scoped matrix cells; `coverage` is merge-group scoped. `release-owner-guard` is a dependency helper for the required `quality` context, not a standalone required context. `check-duplicates` is a non-required helper. The local `drift` workflow now declares `pull_request`, `push` to `main`, and `merge_group: checks_requested`, but `drift` remains an intended context until the live ruleset is promoted; the checker reports that pre-promotion divergence as a visible nonblocking notice. See [required-check contract details](docs/ci-required-check-contract.md). Every user-visible PR (`src/`, `package.json`, workflows, shipped skills) still adds a `docs/releases/pending/.md` fragment — release-please aggregates fragments into the release notes, so a missing fragment means the PR ships with no notes. Escape hatch: `FRAGMENT_CHECK_ENFORCE=0` (soft-warn) applies to the CI quality gate only — the PR Standards fragment gate has no soft-warn path, so a workflow/skills/`docs/configuration.md` PR missing a fragment is blocked regardless. Release-please branches are exempt. The hatch soft-warns BOTH fragment violations and git infrastructure failures (unusable repository root, base-branch probe failures, merge-base/diff failures and timeouts — issue #3283); CI never sets it, so the required `quality` context fails closed whenever the gate cannot determine the diff instead of silently passing. **Do not ask for a merge if any check is red.** Fix the issue first. The `quality` job also runs `bun run check:mock-cleanup` which enforces: - All `mock.module` calls have proper cleanup (`afterEach(mock.restore())` or file-scoped `mockClear`/`mockReset`) - All `mock.module('node:*', ...)` calls spread real exports (e.g., `...realFs`) to prevent test pollution The same job runs `bun run check:invariants` Check 4 (issue #1666): the `scripts/mock-allowlist.txt` allowlist is closed against unapproved growth. Adding a new `mock.module` target requires a matching standalone marker line `# APPROVED-NEW: ` in `scripts/mock-allowlist.txt` (preserved across regen by `scripts/generate-mock-allowlist.sh`). `MOCK_ALLOWLIST_ENFORCE=0` soft-warns for a deliberate growth PR. Prefer the `_internals` DI seam for new code — the allowlist is legacy debt, not a bypass. Before pushing, run `bun run check:pre-push`. This cross-platform package entrypoint hard-enforces repository drift and then validates retention-registry citations; it is the local equivalent of those two CI authorities. --- ## Test rules ### Test framework All tests use `bun:test`. Do not use Jest, Vitest, or any other framework. See `.opencode/skills/writing-tests/SKILL.md` for the full guide including mock isolation rules and cross-platform requirements. ### Test directory map | Directory | Purpose | |---|---| | `tests/unit/` | Pure logic tests, no I/O, fast (<5s total) | | `tests/integration/` | Multi-component tests, orchestration flows, state machine transitions | | `tests/smoke/` | Post-build packaging verification — does the built artifact actually work? | | `tests/security/` | Adversarial inputs, injection attempts, CI security invariants | | `tests/adversarial/` | Extended adversarial scenarios for swarm-specific attack surfaces | | `tests/architect/` | Architect agent behavior and identity tests | | `test/` | Top-level standalone tests (adversarial plan write, reviewer tiers, agent tagging) | ### Test file size limits - **Maximum 500 lines per test file** (FR-006 SC-006.1), enforced by `scripts/check-test-file-cap.ts` as a diff-scoped ratchet (new over-cap files and grown over-cap files fail CI; pre-existing violators are non-blocking). Escape hatch: `TEST_CAP_ENFORCE=0` soft-warns. The config-consumption ratchet (`scripts/check-config-consumption.ts`, issue #2904) has the same escape hatch: `CONFIG_CONSUMPTION_ENFORCE=0` soft-warns for a deliberate declaration-growth PR. Verify locally on any platform — Windows PowerShell included — with `bun run check:test-file-cap` (fetch `origin/main` first; the check is diff-scoped and reads committed changes). - `delegation-gate.test.ts` was the monolith — 2835 lines split into 45 focused files, each under 500 lines - When a test file exceeds 500 lines, split it by behavior/feature into focused files - SME tests (FR-008) use parameterization to keep files lean while maximizing coverage - FR-010/011/012 hook tests (Phase 4) use shared fixture files (e.g., `curator-test-fixtures.ts`) to consolidate common setup and avoid duplication across focused test files ### Checkout-drift guard Every `bun test` process loads `tests/preload/prod-store-tripwire.ts`, which snapshots the repository root and its `.swarm/` before any test file loads and compares them once all tests have finished. Tests must write only into temp directories (`canonicalMkdtemp`, `createSafeTestDir`) or a `ToolContext` with an explicit directory, never into the checkout: - a new, removed or changed top-level entry (including creating `.swarm/`) fails the run; - a change inside an existing `.swarm/` fails the run too, in CI and locally; - `SWARM_TEST_CHECKOUT_DRIFT=enforce|warn|off` sets both checks to one mode. If you run tests in a checkout where a live opencode-swarm session is writing `.swarm/` state, set `SWARM_TEST_CHECKOUT_DRIFT=warn` so its writes print a `CHECKOUT DRIFT` warning instead of failing your run. `warn` downgrades both checks, so it also stops failing on new top-level entries. The value is matched case-insensitively after trimming, and anything else (including an empty or misspelled value) is treated as `enforce`; - a part that cannot be checked (an unreadable root or `.swarm/` directory, a `.swarm/` with more than 20,000 entries) is reported as a warning; - writes inside an existing top-level directory such as `src/` or `tests/` are not detected: only top-level names, top-level files and `.swarm/` are compared. - the comparison runs 25 ms after the last test, so an un-awaited write a test started still lands in time to be caught; a write that waits on a timer, or takes longer, is not. The helper is `tests/helpers/checkout-drift.ts`; its wiring is pinned by `tests/helpers/checkout-drift-wiring.test.ts`. ### When you change behavior, update the tests If your code change alters the behavior of an existing function (new error messages, stricter validation, changed defaults), **find and update every test that asserts the old behavior.** Do not leave tests failing for a follow-up PR. Common examples: - Adding `.strict()` to a Zod schema → tests asserting unknown fields are accepted must flip to rejected - Adding `.int()` validation → tests asserting floats are accepted must flip to rejected - Changing error handling from silent skip to structured error → tests asserting no output must assert the error - Adding a new default field to a config schema → tests using `toEqual({...})` on config objects must include the new field ### Opt-in tool maps Some tools are gated behind feature flags and use **opt-in tool maps** (e.g., `MEMORY_AGENT_TOOL_MAP` when `memory.enabled === true`, `EXTERNAL_SKILL_AGENT_TOOL_MAP` when `external_skills.curation_enabled === true`, `EPIC_AGENT_TOOL_MAP` — architect-only `epic_next_wave` / `epic_phase_review` — when `epic.mode.enabled === true`). These tools must still be fully registered (export, `TOOL_NAMES`, `tool-metadata`, manifest entry), but are merged into agent configs conditionally at build time. See AGENTS.md invariant #11 (Tool registration + agent-map coherence) for the complete checklist. ### Adding adversarial tests Adversarial tests live in `tests/adversarial/` and verify security boundaries (FR-003 subprocess injection, FR-004 guardrail bypass, FR-005 evidence spoofing). Use the `_internals` DI seam pattern rather than `mock.module` to avoid cross-file mock leakage: ```typescript // in tests/adversarial/evidence-spoofing.test.ts import { _internals } from '../../src/hooks/knowledge-migrator'; const real = _internals.writeSentinel; afterEach(() => { _internals.writeSentinel = real; }); test('evidence spoofing is blocked', () => { _internals.writeSentinel = mock(...) as typeof real; // assertions }); ``` For validating evidence integrity, use `src/evidence/manager.ts:_internals.validateEvidence` which is exposed for DI testing. --- ## Release notes (mandatory — no exceptions) **Every PR with a user-visible change MUST add a pending fragment at `docs/releases/pending/.md`.** This is not optional. This is not conditional on "user-facing changes" being polished. If your PR is merged without it, release-please publishes a generic changelog with no explanation of what changed or how to migrate. > **Do NOT** calculate the next version, create `docs/releases/vX.Y.Z.md`, or write to a shared `unreleased.md`. release-please picks the version. The release workflow (`scripts/release-notes-fragments.mjs`) gathers every pending fragment from every PR included in the release-please release PR and inserts the combined content into a stable marker block in the release PR / GitHub Release body. Each PR owning its own unique file is what makes the previous merge-conflict hotspot go away. ### Where to put the fragment - Path: `docs/releases/pending/.md` - Slug: short, kebab-case, descriptive of THIS change. Examples: - `docs/releases/pending/guardrails-transient-node-errors.md` - `docs/releases/pending/spec-drift-self-ack-guardrail.md` - `docs/releases/pending/phase-complete-durable-gate-proof.md` - Pick a slug nobody else is likely to pick. Concurrent PRs each adding a *different* file produce zero merge conflicts. ### What to include The fragment is freeform markdown. Cover: - **What changed** — summarize the changes grouped by theme - **Why** — the motivation (bug report, feature request, hardening) - **Migration steps** — if any API, config, or behavior changed - **Breaking changes** — if any (should be rare) - **Known caveats** — anything users should watch out for Do not prefix the heading with a version (`# v7.21.4`) — release-please owns the version. A descriptive `# ` is the canonical header. See `docs/releases/v6.35.0.md` for the prose style; ignore the version prefix in that historical file. ### What still happens automatically After your PR merges, release-please opens or updates its release PR. CI runs `scripts/release-notes-fragments.mjs update-pr` to aggregate every pending fragment referenced by that release PR and inject it inside the ` … ` marker block (preserving release-please's own body markers). When the release PR merges and a tag is cut, `update-release` mirrors the same aggregation into the GitHub Release body. A fragment's leading YAML frontmatter block (`---`-fenced, mapping-shaped) is treated as authoring metadata: it is stripped from the rendered release notes, while the provenance oracle keeps comparing the raw fragment bytes and accepts both the raw and the rendered published forms. The tag job then prepares an exact-tag cleanup plan. It proves the remote peeled tag, local peeled tag, and checkout HEAD are the same commit, binds the full GitHub Release body and each consumed fragment's SHA-256, and passes that plan to a fresh `main` checkout. The apply step runs with `GH_TOKEN`/`GITHUB_REPOSITORY` step env (any step invoking a gh-dependent fragment-script mode must carry them — enforced by `tests/unit/scripts/ci/release-fragments-gh-auth-shape-2898.test.ts`), is dry-run first, and writes `docs/releases/v.md` plus `docs/releases/manifests/v.json`; it deletes only a current pending file whose raw bytes still equal the tagged bytes. Changed, renamed, missing, ambiguous, unsafe, and unconsumed files are retained and reported. Repository changes are proposed on a deterministic cleanup PR—never pushed to `main`. Re-running the same tag is a no-op. Safety limits cap one fragment at 256 KiB, one release at 1,000 candidate PRs and 5,000 fragment entries, historical content matching at 64 MiB total, and recursive directory enumeration at 5,000 pending entries or 1,000 manifests; excess input fails closed before unbounded reads or collection. For an old release whose PR linkage can no longer be resolved, an exact unique match against the published marker block may recover tagged fragments in source order. Its manifest records `prNumber: null` plus that order; the immutable tag commit, raw-byte hashes, and complete release body remain the authoritative provenance. For historical reconstruction, first write an immutable oldest-to-newest tag list as `{ "schemaVersion": 1, "tags": ["v1.0.0", "v1.1.0"] }` in `.release-fragment-cleanup/tags.json`. Run `prepare-historical-batch --tags-file .release-fragment-cleanup/tags.json > .release-fragment-cleanup/batch.json`; stdout is the reusable JSON batch while diagnostics go to stderr. Process only the returned tags, and resume with its non-null `nextCursor`. The cursor includes a SHA-256 binding to the complete ordered tag list, so deletion, insertion, or reordering between batches fails closed instead of skipping work. Each batch is capped at 25 tags, the input is hard-capped at 1,000 tags, and invalid or oversized input fails visibly rather than truncating. For each returned tag, check out that exact tag oldest-to-newest and run `prepare-cleanup --tag --out .release-fragment-cleanup/plan.json --apply`. For every returned tag in every batch, including the batch whose `nextCursor` is null, also pass `--historical-batch .release-fragment-cleanup/batch.json`. The immutable plan records the digest-bound ordered tag snapshot, exact slice, and continuation. Both `prepare-cleanup` and `apply-cleanup` — the dry-run first, then the explicit `--apply` form — validate an exact-tag proof that requires the checkout HEAD to be the tag commit, so run them AT the tag checkout (a detached worktree per batch; early historical tags predate the cleanup feature, so overlay the current script without staging it, `git restore .` before each tag-to-tag move, and restore `docs/releases/manifests/historical-replay-state.json` before every tag except the first of the whole ordered list). Cleanup-plan paths are restricted to one JSON file directly under `.release-fragment-cleanup/`. Existing matching history is preserved; any conflict fails closed. The resulting `docs/releases` changes (history, manifests, replay state, and deletion of exactly the manifest-referenced pending fragments whose bytes still hash-match) are then committed from a current main checkout as the batch PR. Commit each bounded batch as a cleanup PR. Each non-final tag writes a version-controlled replay-state artifact so required retention CI can verify that bounded work remains. That authorization expires after seven days, reruns preserve its original deadline, and an expiry beyond that fixed window is rejected, so an abandoned/interrupted replay fails retention CI instead of suppressing the limit indefinitely. The last tag of the final batch removes that state and fails closed before mutation unless its projected pending count satisfies the limit. The final batch has `nextCursor: null`, and its last tag must satisfy `verify-retention`. The drift workflow runs `verify-retention` to reject byte-identical consumed fragments and to enforce the pending-fragment count limit, reporting the 14-day add rate and projected days-to-limit (with a `::warning::` under 30 days). Every release run ends in a `release-health-summary` job that reports the release-please, update-release-notes, and cleanup-release-fragments conclusions and emits an `::error::` annotation (plus a job failure) if `update-release-notes` did not succeed — a failed producer cannot strand a release silently behind a skipped cleanup — or if the cleanup job did not complete. --- ## SHA pinning for GitHub Actions If you add or modify a workflow file in `.github/workflows/`, every `uses:` reference to a third-party action must be pinned to a full 40-character commit SHA with the version as a comment. This is a hard requirement enforced by the security tests. ```yaml # Correct - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1 # Wrong — will fail security tests - uses: actions/checkout@v4 - uses: actions/checkout@main ``` To find the SHA for a given tag, run: ```bash gh api repos/{owner}/{repo}/git/ref/tags/{tag} --jq '.object.sha' ``` --- ## Common mistakes that break the release pipeline | Mistake | Consequence | Prevention | |---|---|---| | Replacing release PR body | release-please can't parse its own PR → no tag, no release, no npm publish | Never `gh pr edit --body-file` on a release PR; use prepend only | | Editing `package.json` version | Merge conflict with release-please on next run | Let release-please manage version fields | | Editing `CHANGELOG.md` | Merge conflict with release-please on next run | Let release-please manage the changelog | | Editing `.release-please-manifest.json` | release-please version tracking breaks | Let release-please manage the manifest | | Using only `docs`/`chore`/`test`/`ci` commit types | No version bump triggered, release PR is never created | Include at least one `feat` or `fix` commit if you want a release | | Creating tags or releases manually | `publish-npm` job doesn't trigger (gated on release-please output) | Let the pipeline create tags and releases | | Missing `docs/releases/pending/.md` | GitHub Release has no useful description | Always add a unique pending fragment for your PR | | Creating `docs/releases/v{VERSION}.md` in a feature/fix PR | Version prediction collides with release-please; merge conflict hotspot | Use `docs/releases/pending/.md` instead — release-please owns the version | | Writing to a shared `docs/releases/unreleased.md` | Same merge-conflict hotspot, just relocated | Use a unique slug under `docs/releases/pending/` per PR | --- ## Summary checklist for any PR - [ ] [`AGENTS.md`](./AGENTS.md) read; touched invariants identified - [ ] PR body includes an `## Invariant audit` section in the format from `AGENTS.md` (when relevant invariants are touched) - [ ] OpenCode `test_runner` was NOT used with `scope: 'all'` or broad `'graph'` / `'impact'` scope to validate this repo (use shell commands instead) - [ ] If invariants 1, 2, or 3 (plugin init / runtime portability / subprocesses) are touched: ran `bun run build`, `node scripts/repro-704.mjs`, and `node --input-type=module -e "await import('./dist/index.js'); console.log('dist import OK')"` cleanly - [ ] Branch created from latest `main` - [ ] Every commit message follows `(): ` format - [ ] PR title follows the same format and matches the primary change - [ ] No manual edits to `package.json` version, `CHANGELOG.md`, or `.release-please-manifest.json` - [ ] `docs/releases/pending/.md` exists with release notes (do NOT create `docs/releases/vX.Y.Z.md`) - [ ] New tests are in the correct `tests/` subdirectory - [ ] Tests updated for any changed behavior (defaults, validation, error messages) - [ ] If adding/modifying a workflow, all `uses:` references are SHA-pinned - [ ] All CI checks pass locally or remotely as appropriate (`typecheck`, `biome ci`, `unit`, `integration`, `security`, `package-check`, `php-validation`, `rust-sandbox-runner`, `smoke`) - [ ] PR description includes a summary and test plan