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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 59 additions & 59 deletions .agents/skills/verify-notification-barrier/SKILL.md

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions .agents/skills/verify-session-cancel/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ The code column cites functions and the line that each step depends on. `check.s
- The client sends each script in order. The agent can return from `Prompt` at any step, canceled or not.
- The connection is initialized: every script starts after `initialize` returned without an error. Before that, `handleWithExtensions` hands each message to `handleBeforeInitialize`, which drops a `session/cancel` and answers a prompt with -32600 before either reaches the agent, so no marker or cancel func exists yet. After it, the gate is one `a.openedAt.Load()` compared with the message's `messageArrival`, which reads only the handler's ctx, and the covered code runs as before. `handleWithExtensions` first waits on `a.ready`, which `NewAgentSideConnection` closes once `a.conn` is set, so a handler that runs before the constructor returns takes its next step (`PassBarrier`, `Register`, `RunCancel`) later, which the model's interleavings already include.
- Prompts and `session/cancel` requests are the requests in the model. Other requests in flight only keep markers longer.
- The model has fewer than `maxCancelMarkers` (1024) entries in `sessionCancelledAt` and `sessionNewest`, so `dropOldestAbove` never runs. A lost entry there loses only that peer's own cancel or prompt order, as the comment on `maxCancelMarkers` says. `TestAgentSideConnection_SessionCancelMarkersArePruned` and `TestAgentSideConnection_SessionNewestIsCapped` cover the caps.
- The model has fewer than 1024 entries (`maxCancelMarkers`) in `sessionCancelledAt` and `sessionNewest`, so `dropOldestAbove` never runs. A lost entry there loses only that peer's own cancel or prompt order, as the comment on `maxCancelMarkers` says. `TestAgentSideConnection_SessionCancelMarkersArePruned` and `TestAgentSideConnection_SessionNewestIsCapped` cover the caps.
- The three maps of `AgentSideConnection` key a session by `sessionKeyOf(id)`, the SHA-256 of its sessionId, so `sessionID` in `cancelPrompt` and `registerPrompt` is that digest. The model names sessions directly: it assumes that two sessionIds never share a digest. `TestAgentSideConnection_CancelMarkersKeepLongSessionIDsApart` covers two long ids that differ in their last byte.

Not covered, with what a user sees when it goes wrong:
Expand Down Expand Up @@ -169,5 +169,5 @@ A pass covers the model within these bounds, not the whole SDK.
- `agent_gen.go`: the `AgentMethodSessionCancel` and `AgentMethodSessionPrompt` cases (generated by `cmd/generate/internal/emit/dispatch.go`).
- `extensions.go`: `AgentSideConnection.handleWithExtensions`.
- `connection.go`: `NewConnection`, `notificationSeq`, `messageArrival`, `oldestInflightArrival`, `receive`, `handleResponse`, `processNotifications`, `handleInbound`, `SendRequest`, `SendRequestNoResult`, `sentRequest.wait`, `waitNotifications`, `waitInboundBarrier`, `startPeerWait`.
- Sync commit: the last commit that changed `fingerprint.txt`, which `git log -1 --format=%H -- .agents/skills/verify-session-cancel/fingerprint.txt` prints. The model was last confirmed to describe the covered code at that commit, and the line numbers in this file are at that commit.
- Sync commit: the last commit that changed `fingerprint.txt`, which `git log -1 --format=%H -- .agents/skills/verify-session-cancel/fingerprint.txt` prints. The model was last confirmed to describe the covered code at that commit.
- To see what changed since then: `git diff "$(git log -1 --format=%H -- .agents/skills/verify-session-cancel/fingerprint.txt)" -- agent.go agent_gen.go extensions.go connection.go`. `check.sh` exit 3 names the changed blocks.
9 changes: 9 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ jobs:
- name: Make tests
run: mise exec -- make test

# The module zip that the Go proxy serves leaves out every folder with a
# go.mod of its own; a test that reads one fails here.
- name: Test the module zip
run: mise exec -- make test-module-zip

# int is 32 bits on 386, so a value that fits on amd64 can overflow.
- name: Test as 32-bit code
run: mise exec -- make test-386

# Runs the ACP Test Compatibility Kit against the SDK's conformance agent
# and fails when a result drifts from .agents/skills/verify-tck/baseline.json.
tck:
Expand Down
23 changes: 20 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,17 @@ Core SDK code lives at the repo root (`agent.go`, `client.go`, `connection.go`,

- `go test ./...` exercises unit tests across packages.
- `go run ./example/agent` and `go run ./example/client` provide quick manual validation of agent/client behavior.
- `make test` runs `go vet` and `go test` for the SDK and `cmd/generate`, builds the examples, and runs the verification skills' offline unit tests: `acpwire` (verify-acp-go-sdk), `acpharness` (verify-real-harnesses), `methodcheck` and the roundtrip helpers of verify-schema-bump, and the conformance agent and `tckcheck` of verify-tck. CI runs `make check`, `make test` and `make tck`. The gates themselves run by hand from their skills, because they need the network, a model, npm, cargo or Java: G1, G2's data checks, the Rust probe and G7 (verify-schema-bump), G3 (verify-acp-go-sdk), G4 and G5 (verify-real-harnesses), G6 (verify-notification-barrier, verify-session-cancel).
- `make test` runs `go vet` and `go test` for the SDK and `cmd/generate`, builds the examples, and runs the verification skills' offline unit tests: `acpwire` (verify-acp-go-sdk), `acpharness` (verify-real-harnesses), `methodcheck` and the roundtrip helpers of verify-schema-bump, and the conformance agent and `tckcheck` of verify-tck. CI runs `make check`, `make test`, `make test-module-zip`, `make test-386` and `make tck`. The gates themselves run by hand from their skills, because they need the network, a model, npm, cargo or Java: G1, G2's data checks, the Rust probe and G7 (verify-schema-bump), G3 (verify-acp-go-sdk), G4 and G5 (verify-real-harnesses), G6 (verify-notification-barrier, verify-session-cancel).
- `make test-module-zip` runs `go vet` and `go test` in the module zip that the Go proxy would serve for the checkout (`scripts/test-module-zip`). That zip leaves out every folder with a go.mod of its own (`testdata/bench`, `cmd/generate`, `scripts/modzip`, the verify skills that are modules), so a test reading from one of them must go through `repoFiles` in `repo_files_test.go`. CI runs it after `make test`.
- `make test-386` runs `go vet` and `go test` for the SDK and `cmd/generate` with `GOARCH=386`, where `int` is 32 bits, so a wire value that fits `int` on amd64 and wraps on 32-bit fails. CI runs it.
- `make tck` runs the ACP Test Compatibility Kit, pinned in verify-tck's `runner/`, against the conformance agent and fails when a result drifts from `baseline.json`; after a change that moves a result, `make tck-update` rewrites the baseline and you write a reason for each requirement that does not pass. It needs uv, cgo with a C compiler (the agent is built with `-race`) and, on the first run, the network.
- `make fmt` runs `treefmt` so Go and Markdown stay formatted consistently.
- `make check` runs `treefmt --fail-on-change` plus the README guard used in CI.
- `make check` runs `scripts/check-code-citations` (no line numbers in the model-to-code tables of verify-notification-barrier and verify-session-cancel), `scripts/check-model-fingerprints` (the code those TLA+ models cover still matches their `fingerprint.txt`), then `treefmt`, and fails when formatting leaves a diff.
- `mise install` provisions the toolchain (Go, gopls, golangci-lint, treefmt, etc.); run it once after cloning.

## Coding Style & Naming Conventions

Target Go 1.21 idioms: tabs for indentation, short receiver names, and CamelCase for exported symbols (`AgentLoader`), lowerCamelCase for unexported helpers. Prefer table-driven tests and keep files focused on a single protocol concern. Run `make fmt` or `gofumpt -w .` to normalize spacing, imports, and composite literals before sending a change.
Target Go 1.21 idioms: tabs for indentation, short receiver names, and CamelCase for exported symbols (`AgentLoader`), lowerCamelCase for unexported helpers. Prefer table-driven tests and keep files focused on a single protocol concern. Run `make fmt` before sending a change: it runs `gofmt` (through `treefmt`), which `make check` enforces. Do not run `gofumpt -w .`: it rewrites files outside your change that the repo formats with `gofmt`, generated ones included.

## Testing Guidelines

Expand All @@ -29,3 +31,18 @@ Write commit subjects in the imperative mood (`Add request codec`, `Fix session
## Code Generation & Schema Updates

Schema bumps originate from `schema/version`. After editing it, run `make generate` to re-fetch upstream JSON and regenerate bindings. Commit the updated schemas, generated Go, and `schema/version` together so reviewers can track protocol changes. The top-level `version` file is the SDK's own semver: bump it only in a release PR (see `RELEASING.md`).

## Rules and what enforces them

Each rule came from a mistake that reached review at least twice. When a rule has a check, the check is the rule: fix what it reports. When nothing enforces a rule and the mistake happens again, add a check (or change the code so the mistake cannot be written) in the same change, and update this table. Drop a row once its mistake cannot happen.

| Rule | Enforced by |
| --- | --- |
| A test reads a file from a folder with its own `go.mod` (`testdata/bench`, `cmd/generate`, the verify skills that are modules) only through `repoFiles` (`repo_files_test.go`). | `make test-module-zip` in CI |
| A model-to-code table in a skill with a `fingerprint.txt` names the function and quotes the code, never a line number. | `scripts/check-code-citations` in `make check` |
| A change to code that a TLA+ model covers reruns that skill's `check.sh` and commits its `fingerprint.txt` in the same change. | `scripts/check-model-fingerprints` in `make check` recomputes each fingerprint and fails on a mismatch; nothing checks that TLC ran |
| A value from the wire or the schema that can exceed 2^31 is not held in `int`. | `make test-386` in CI, for values that a test reaches |
| A doc does not state a count of something on `main` that the next PR can change (types, methods, cases); count only what a tag fixes, or give the command that counts. | Nothing: judgment |
| Every sentence a change adds or keeps in a migration guide, README or doc comment is true for the code at the head, including each "before" clause against the old tag; every Go snippet compiles. | Nothing: a verifier reads each sentence |
| A new assertion fails on the defect it guards: break the code, watch the test fail, restore it. | Nothing: judgment |
| A fix covers every entry point and schema form that reaches the broken code, not only the one in the report. | Nothing: judgment |
2 changes: 1 addition & 1 deletion MIGRATION_v0.21.md
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ The rows come from the generated `Validate` methods of v0.20.0 and v0.21.0, foll

### Validate on values you build

- Every union, and each struct that has one of the checks above, now has a `Validate` method: 114 types more than in v0.20.0, such as `ContentChunk`, `McpServerAcpInline` and `PermissionOption`. A `oneOf` union's `Validate` requires exactly one variant set, and an `anyOf` union's one at least (`McpServer has no variant set`), so `Validate` on a zero union fails.
- Every union, and each struct that has one of the checks above, now has a `Validate` method, such as `ContentChunk`, `McpServerAcpInline` and `PermissionOption`, which had none in v0.20.0 (80 types had one there). A `oneOf` union's `Validate` requires exactly one variant set, and an `anyOf` union's one at least (`McpServer has no variant set`), so `Validate` on a zero union fails.
- `json.Marshal` of a zero union, such as `acp.ContentBlock{}`, fails with `ContentBlock has no variant set`. An `anyOf` union's `Validate` gives the same text. A `oneOf` union's `Validate` gives `ContentBlock must have exactly one variant set`, because it also rejects two variants set. v0.20.0 failed the marshal too: with encoding/json's `unexpected end of JSON input` for 26 unions, and with this same text for the other 5 (`CreateElicitationForm`, `CreateElicitationOther`, `CreateElicitationUrl`, `ElicitationFormMode` and `ElicitationUrlMode`). A send method, such as `SessionUpdate` with no update set, returns it inside its `-32602` error, and nothing is sent. A handler whose result holds a zero union, such as a `RequestPermission` that returns `RequestPermissionResponse{}`, makes the connection reply `-32603` with this text in `data.error`, so the peer reads `RequestPermissionOutcome has no variant set` where v0.20.0 sent `unexpected end of JSON input`.
- `SessionConfigOption.Validate` no longer rejects an empty `name`. The SDK never calls it on its own: the requests and notifications that it reads hold a `SessionConfigOption` only in a lenient member.
- The `Validate` of a response type checks the same rules. The SDK does not call it on a response that it receives.
Expand Down
18 changes: 18 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ fmt:
# place and let git confirm there's no net drift instead.
.PHONY: check
check:
scripts/check-code-citations
scripts/check-model-fingerprints
treefmt
git diff --exit-code

Expand All @@ -91,6 +93,22 @@ test: $(GO_FILES)
# The TCK run itself is make tck.
cd .agents/skills/verify-tck && GOFLAGS=$(GOFLAGS) GOCACHE=$(GOCACHE) go vet ./...
cd .agents/skills/verify-tck && GOFLAGS=$(GOFLAGS) GOCACHE=$(GOCACHE) go test ./...
cd scripts/modzip && GOFLAGS=$(GOFLAGS) GOCACHE=$(GOCACHE) go vet ./...

# Run the SDK and generator tests as 32-bit code, where int holds only 32 bits:
# a value that fits int on amd64 overflows or wraps here (#118, #138, #160).
.PHONY: test-386
test-386:
GOARCH=386 GOFLAGS=$(GOFLAGS) GOCACHE=$(GOCACHE) go vet ./...
GOARCH=386 GOFLAGS=$(GOFLAGS) GOCACHE=$(GOCACHE) go test ./...
cd cmd/generate && GOARCH=386 GOFLAGS=$(GOFLAGS) GOCACHE=$(GOCACHE) go vet ./...
cd cmd/generate && GOARCH=386 GOFLAGS=$(GOFLAGS) GOCACHE=$(GOCACHE) go test ./...

# Run the tests in the module zip that the Go proxy would serve, where every
# folder with a go.mod of its own is missing (scripts/test-module-zip).
.PHONY: test-module-zip
test-module-zip:
GOCACHE=$(GOCACHE) scripts/test-module-zip

# Run the ACP Test Compatibility Kit (acp-tck) against the conformance agent
# and fail when the results drift from the baseline (see
Expand Down
29 changes: 4 additions & 25 deletions inbound_bench_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,10 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"log/slog"
"os"
"path/filepath"
"reflect"
"regexp"
"sort"
Expand All @@ -30,21 +27,16 @@ import (

// inboundCorpusGlobs name the recorded traffic: the fixtures of the Claude and
// Codex adapters and the verify-acp-go-sdk journeys in testdata/bench, and the
// transcripts that verify-schema-bump's G2 gate round-trips. testdata/bench
// and .agents/skills/verify-schema-bump are modules of their own, so the
// module zip that the Go proxy serves has neither (it keeps the rest of
// .agents), and a test that needs the corpus skips there. Where either folder
// exists, every glob must match, so a lost source fails loudly.
// transcripts that verify-schema-bump's G2 gate round-trips. Both folders are
// modules of their own, which the module zip leaves out, so loadInboundCorpus
// reads them through repoFiles.
var inboundCorpusGlobs = []string{
"testdata/bench/claude-agent-acp/*.jsonl",
"testdata/bench/codex-acp/*.jsonl",
"testdata/bench/g3/*.jsonl",
".agents/skills/verify-schema-bump/roundtrip/testdata/transcripts/*.jsonl",
}

// inboundCorpusRoots are the corpus folders that the module zip leaves out.
var inboundCorpusRoots = []string{"testdata/bench", ".agents/skills/verify-schema-bump"}

// An inboundMessage is one message of the corpus, as the side that receives
// it reads it.
type inboundMessage struct {
Expand All @@ -62,21 +54,8 @@ type inboundMessage struct {
func loadInboundCorpus(tb testing.TB) []inboundMessage {
tb.Helper()
var paths []string
zip := true
for _, root := range inboundCorpusRoots {
if _, err := os.Stat(root); !errors.Is(err, fs.ErrNotExist) {
zip = false
}
}
if zip {
tb.Skip("no corpus: this is the module zip, which leaves out testdata/bench and .agents/skills/verify-schema-bump")
}
for _, g := range inboundCorpusGlobs {
matches, err := filepath.Glob(g)
if err != nil || len(matches) == 0 {
tb.Fatalf("no corpus files match %s: %v", g, err)
}
paths = append(paths, matches...)
paths = append(paths, repoFiles(tb, g)...)
}
sort.Strings(paths)
var corpus []inboundMessage
Expand Down
67 changes: 67 additions & 0 deletions repo_files_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package acp

import (
"errors"
"io/fs"
"os"
"path/filepath"
"sort"
"testing"
)

// repoFiles returns the files that match pattern, a filepath.Glob pattern
// relative to the repository root. Use it for any file a test reads from a
// folder that holds a go.mod of its own (testdata/bench, cmd/generate and the
// verify skills under .agents/skills): the module zip that the Go proxy serves
// leaves such folders out, so `go test github.com/coder/acp-go-sdk/...` in a
// consumer's module cache has none of those files. In the module zip,
// repoFiles skips the test. In a checkout, it fails the test when nothing
// matches, so a lost fixture fails loudly. make test-module-zip runs the tests
// in a real module zip.
func repoFiles(tb testing.TB, pattern string) []string {
tb.Helper()
matches, err := filepath.Glob(pattern)
if err != nil {
tb.Fatalf("glob %s: %v", pattern, err)
}
if len(matches) > 0 {
sort.Strings(matches)
return matches
}
if inModuleZip(tb) {
tb.Skipf("no %s: this is the module zip, which leaves out every folder with a go.mod of its own", pattern)
}
tb.Fatalf("no files match %s", pattern)
return nil
}

// inModuleZip reports whether the tests run in the module zip: a checkout
// holds go.mod files below the root (cmd/generate, testdata/bench, ...), and
// the module zip holds none.
func inModuleZip(tb testing.TB) bool {
tb.Helper()
nested := errors.New("nested go.mod")
err := filepath.WalkDir(".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() || path == "." {
return nil
}
switch d.Name() {
case ".git", ".gocache":
return filepath.SkipDir
}
if _, err := os.Stat(filepath.Join(path, "go.mod")); err == nil {
return nested
}
return nil
})
if errors.Is(err, nested) {
return false
}
if err != nil {
tb.Fatalf("look for a nested go.mod: %v", err)
}
return true
}
38 changes: 38 additions & 0 deletions scripts/check-code-citations
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Fail when a skill that maps a model onto the code (a skill folder with a
# fingerprint.txt, such as verify-notification-barrier) cites the code by line
# number. Every edit to connection.go moved those numbers: nine PRs had to
# rewrite 31 to 55 rows of the barrier's table, and stale rows still slipped
# through review. Name the function and quote the code instead, as
# verify-session-cancel/SKILL.md does; check.sh finds each line by its text.
#
# scripts/check-code-citations [SKILL.md ...]
#
# make check runs it over every such skill.
set -euo pipefail

cd "$(dirname "$0")/.."
if [ $# -eq 0 ]; then
set --
for fp in .agents/skills/*/fingerprint.txt; do
set -- "$@" "$(dirname "$fp")/SKILL.md"
done
fi

# A backquoted name, then a line or a range: "`receive`, 617-686:" or
# "`sentRequest.wait` 1047,". A ", 670:" or "(1002)" of bare numbers. A
# "line 29", "at 1292" or "connection.go:812".
num='[0-9]{2,5}(-[0-9]{2,5})?'
pattern="\`[A-Za-z_][A-Za-z0-9_.]*\`,? $num([:,);]| and| where)|, $num: |\\($num(, $num)*\\)|\\blines? [0-9]+\\b|\\bat [0-9]{3,5}\\b|\\.go:[0-9]+"

status=0
for f in "$@"; do
if grep -nE "$pattern" "$f" >/dev/null; then
grep -nE -o "$pattern" "$f" | sed "s|^|$f:|" >&2
status=1
fi
done
if [ "$status" -ne 0 ]; then
echo "check-code-citations: cite the code by function name and quoted code, not by line number (see verify-session-cancel/SKILL.md)." >&2
fi
exit "$status"
Loading