Skip to content

Latest commit

 

History

History
1278 lines (1163 loc) · 82.5 KB

testing.md

File metadata and controls

1278 lines (1163 loc) · 82.5 KB

Testing

For local cache and resource cleanup, follow worktree storage.

What CI checks, run locally from the repository root (the Levenshtein checks below run too):

go test -race -short -count=1 -timeout 20m ./...                  # the pull-request race suite
go test -race -count=1 -timeout 20m ./...                         # exhaustive fixtures: weekly and candidates
go vet ./...
golangci-lint run --disable=revive                       # v2.14.0; the blocking lint run
golangci-lint run --enable-only=revive --new-from-merge-base=origin/main   # doc comments, new code only
go run golang.org/x/tools/cmd/deadcode@v0.50.0 ./...     # only the exceptions listed in test.yml
GOBIN=/tmp/deadcode go install golang.org/x/tools/cmd/deadcode@v0.50.0   # the Linux pass needs a built binary:
GOOS=linux CGO_ENABLED=0 /tmp/deadcode/deadcode ./...    # also excepts credentials.errorForOSStatus
python3 scripts/test_release_signing.py
python3 scripts/test_release_assets.py
python3 scripts/test_release_candidate.py                 # synthetic release API, retry, and promotion fixtures
python3 scripts/test_install.py
python3 scripts/test_install_from_source.py
python3 scripts/test_purge_recipe.py                     # runs the bucket purge recipes in the docs
python3 scripts/test_ci_workflow.py                      # Extended keeps the validated systemd image
python3 -B scripts/test_ci_lane_verdict.py                # mandatory script and cross-target lanes
python3 scripts/test_ci_tiers.py                         # cadence, source proof and body evidence
python3 scripts/test_go_shards.py                         # discovery, coverage, verdict, and process cleanup
python3 -B scripts/test_generate_go_shard_hints.py         # matched artifact medians and pause envelopes
python3 -B scripts/test_go_cache_context.py               # cache identity and tracked source proof
python3 -B scripts/test_go_cache_steps.py                 # cache failure paths and PR-only wiring
python3 scripts/test_measure_hook.py                     # synthetic hook benchmark effect/cleanup checks
python3 -B scripts/test_muse_qualification.py             # offline Muse isolation/corpus and bounded synthetic loopback controls
./scripts/test_macos_smoke.sh                             # native macOS with cgo; the PR gate
VERSION=dev ./scripts/build-release.sh                   # the release build (CI runs it on a release tag)

CI's Test workflow runs the short race suite across eight Ubuntu trial workers for each pull request. Each worker discovers all packages and top-level tests, fuzz seeds and executable examples. Light packages remain whole; CLI, catalog, statshtml and state parents are assigned to disjoint bins and retain complete subtest trees. Timing hints only rank discovered units; new units are assigned and logged. The assigned native Git identity package runs first on a quiet worker because its observers have fixed 500 ms deadlines. The workers then overlap bounded ordinary-package and parent processes. The independent plain audit and each worker retain actual vet evidence bound to their source and compiler context. Each worker records its source, catalog, assignment and terminal coverage; the stable required linux-race verdict reconciles all eight artifacts and fails on any missing, failed or cancelled worker. All Linux Python gates run in independent script-static, script-install and script-purge jobs. Purge resolves the existing exact-source plan locally; static and installer fixtures start immediately. Each lane uses isolated HOME/XDG/temp directories. Purge discovers every complete unittest method and assigns sorted methods to two standard Linux workers. Each parent retains all runtime-generated cases; only its existing tier selection changes repeated resume boundaries. The aggregate checks both current-source catalogs, assignments, passing parent terminals and bound child streams, including the exact existing resume/cadence case union. Missing, duplicate or unexpected workers, parents or cases fail closed. The required linux-race verdict directly rejects missing, failed, skipped or cancelled script lanes and validates the complete current-source purge union. It also verifies the Linux/Go evidence, without a separate script aggregate job. The independent Linux/arm64 build+vet, Darwin/arm64 no-cgo vet and Linux release build+verification also run in separate standard Linux jobs behind the stable cross-build verdict. The existing deterministic planner runs locally in its consumers and selects focused representative regressions for sensitive PR changes. Its proof compares event base, actual head and tested merge, checks tracked bytes/types/modes, and includes both paths of renames and deletions. CLI, catalog, recovery, archive, presentation, platform and purge routes are explicit. CLI edits select CLI coverage; they do not select every other family. CI/configuration outside mapped product packages, shared helpers, unknown code and unavailable history require the complete unrestricted short shards already checked by the verdict, plus focused critical refusal/limit integration backstops. They do not duplicate the short suite. Every PR also builds all Darwin production packages with cgo and runs native smoke. Sensitive product changes additionally run explicitly named native short consent, source-authority and catalog refusal regressions. Scheduler protocol and CLI setup/uninstall/scheduler changes require the actual systemd integration on a disposable runner during a PR. Shared CLI dispatch, installation identity, status observation, setup journal and setup resource changes also retain this integration. The daily run retains the full real-manager suite.

The stable linux-full check records source-bound focused PR bodies (or an explicit empty selection) and exhaustive candidate bodies. PR reports retain compiled parent discovery, commands and actual terminals; omitted parents, forged source/plan/logs or weakened flags fail. Short bodies always mark scale restorations NOT RUN. Unknown inputs do not select exhaustive mutation, native scale or purge matrices. PR purge retains its representative refusal/recovery cases; expanded products run daily and exhaustive matrices weekly/candidates. The stable linux-race verdict requires extras, native smoke, unrestricted short shards and Python gates. Candidates run exhaustive full Linux race coverage, plain full-size performance assertions and vet. Full Linux and standalone native macOS tier coverage discovers every selected package and compiled Test/Fuzz/Example parent on the tested source. The CLI's parents are balanced into two partitions using advisory timing hints; new names receive the ordinary positive default. The full TestPickerQualificationRealCLIPhases parent runs in a separate third invocation: its 100k fixture and phase checks consumed 738 seconds on the macOS runner and exhausted an ordinary batch's cumulative package lifetime. The first Go invocation runs alone and retains ordinary package concurrency and excludes only names exclusive to the CLI that belong to later invocations. Names shared by another package always run in the first invocation. The two later CLI processes overlap through the existing bounded supervisor, with separate raw streams and process-private test fixtures. The canonical batch plan is [[0], [1, 2]]; the supervisor joins both processes on success, failure or cancellation. Fixture construction also reuses each session's immutable entry encoding and order keys within that construction. Every parent retains all descendants and fuzz seeds. This bounds cumulative CLI process work without changing any individual test's deadline.

Full artifacts retain raw package discovery, compiled listings, canonical commands, disjoint assignments and actual parent/child terminals. Execution and the required verdict check their complete union, restored full-size children, tracked source bytes/types/modes and exact source/event/plan. Missing bodies, unexpected packages, weakened flags, duplicate assignments and incomplete streams fail. Each invocation keeps race, count=1 and the 20-minute package timeout; discovery, all full invocations and the existing performance/systemd/fuzz obligations share the original supervisor and job budgets. These full partitions are separate from the representative PR short shards. A split is scheduling evidence, not permission to omit coverage. The PR short runner's shared 25-minute deadline includes discovery and tests; cancellation and failure stop and reap both test process groups. CLI listing invokes TestMain before execution, and both shards have independent TestMain initialization and temporary state. Hosted PR workers keep separate PR/worker-scoped build/module caches; sharding improves latency only if measured scheduling benefits outweigh that extra work. For local coverage validation on Linux, run one worker at a time:

for worker in 0 1 2 3; do
  python3 scripts/run_go_shard.py --workers 4 --shard "$worker" --output "/tmp/go-shard-$worker"
done

The checked-in timing hints are advisory integer milliseconds from successful paired artifact observations. scripts/go_shard_hint_sources.json pins the measured source, exact worker settings, sample IDs, hosted attribution and source limitations; scripts/generate_go_shard_hints.py validates the actual current runner's discovery, exhaustive coverage and body evidence before taking medians. Download and safely extract each named sample into its relative directory under an artifact root, then regenerate without executing Go:

python3 -B scripts/generate_go_shard_hints.py \
  --request scripts/go_shard_hint_sources.json \
  --artifacts-root /path/to/cache-integration-profiles \
  --output scripts/go_shard_hints.json

Imported evidence pins the measured source body catalog and its hash, so later scale catalog additions cannot rewrite a historical manifest. Current CI uses the current catalog. The generator rejects source/settings/catalog mixtures, failed or incomplete streams, reused samples and mismatched manifest body evidence. Reconciliation checks the request's pinned artifact source independently of the regenerating workflow's GITHUB_SHA. The request may provide fresh packages/cli discovery lists to drop stale names or give newly discovered names the positive 1000 ms fallback; omission uses actual sample discovery. Discovery in the live runner always remains authoritative. Artifact IDs and runtime-source equivalence require independent API/source verification; raw JSON alone cannot attest those caller-supplied provenance fields.

Ordinary weights are median package-terminal elapsed seconds, rounded half-up to positive milliseconds (minimum 1). CLI weights recursively account logical body cost: subtract each direct child's synchronous run-to-pause (parallel) or run-to-terminal (sequential) interval from the parent's elapsed value, then add each child's accounted cost. This avoids charging parallel cohort queueing and counting sequential children twice, while including parallel descendant bodies. Slash-containing child names use observed active enclosing lifecycles rather than inventing a parent for each selector component. Nanosecond RFC3339 clocks and complete run/pause/cont/terminal lifecycles are validated. Skipped bodies retain their actual elapsed cost and remain skips in coverage evidence. These costs rank logical work; they are not elapsed-time or CPU forecasts. Predicted bin loads are logged separately from measured worker phase durations. Git invocation and worker0 vet costs stay separate from weights; the assigned Git package stays isolated on whichever worker receives it.

The current hints use the complete eight-worker schema 4 observation from successful normal Test run38816393618 and paired Levenshtein38816394218, at tested merge 39c550ebd40bf68e62e8a2cf4e58fd69b3c954dc. Artifact IDs, archive digests, exact settings, raw-file hashes and immutable measured catalog bytes are pinned. Fetch that exact commit before regeneration. The importer resolves its Git tree and regular catalog blob independently, checks the requested catalog bytes, and verifies the separate named plain audit body and package PASS against that tree. Each sample supplies an explicit audit_directory; audit report and raw stream hashes are included. This import path does not change the live verdict's current tracked-source/event guard or permit old schemas in live CI.

The owned builtin package already skips the relocated race audit, so its elapsed cost is used directly, without another subtraction. Local shards without ownership add the verified same-source plain audit body cost only as ranking advice. All eight caches reported a previous source prefix, rather than exact hits or empty-cache cold controls. Parent lifecycle sums include parallel descendant waits and process fixture effects; they rank work, not elapsed or CPU forecasts. The same-workload balance comparison and exact source limitations are recorded in CI timing. The PR source-audit job also executes complete native Linux/amd64 plain go vet ./... sequentially after the actual named audit body. Its separate vet receipt pins canonical command, successful exit, raw-log hash, source before and after, and the existing exact Go1.27.3/compiler/runtime context. Worker0 omits its trailing vet only under explicit --plain-vet-owned; all workers record matching ownership/context and the required reconciliation demands the same-source actual-vet receipt. Default local/standalone shards still run vet, with no change to daily, full or native vet behavior. Owned scheduling excludes the historical fixed-vet offset rather than charging the moved work twice. Historical unowned observations remain valid and require no new receipt. The live owned-vet protocol is plain-vet-compatible-v1: cross-job identity excludes only the incidental runner image.ImageVersion release label, while retaining ImageOS, OS-release, exact Go/compiler/tool hashes and every flag. The full raw context and image label remain in the receipt, and per-job pre/post checks and compilation-cache keys retain the complete image identity. This allows compatible Ubuntu image rollouts across matrix jobs. Missing live identity schemas cannot downgrade the gate. Schema-less owned receipts use full digests only through the independently source-bound historical importer; older unowned samples retain their original contract.

Raw object-stream parsing uses the same offset decoder for live execution and historical imports, retaining concatenated objects, whitespace and malformed stream rejection without repeatedly copying large remaining log tails.

Four workers remain a hosted trial. Current whole-job latency and allocation must justify retaining them; no five-minute target or wall-time saving is claimed from these logical rankings. The generic partition helper accepts1..16 bins for shared native scheduling; representative PR topology/cache ownership accepts only two/four and the full-race default stays two.

Every PR runs the exact whole-source architecture/type audit in a separate required plain job, with count=1, package concurrency1 and its existing inner go list-export concurrency1. Assertions are unchanged. The job retains actual named run/PASS, package PASS, command and tracked source proof. Representative shards skip only that short race body under explicit --plain-audit-owned; raw artifacts mark the race body NOT RUN and retain its skip reason. Required shard reconciliation fails without the independently passing plain audit evidence. Local short tests without this ownership still run the audit. Daily Linux coverage executes the same actual plain audit before owned short race coverage. Weekly/candidate non-short Linux and Darwin coverage execute the original body; only the redundant candidate PR audit job intentionally skips. This is a static architecture/type audit; relocation does not substitute compilation for a test body or change its source/permission assertions.

Hosted comparisons must record whole-job latency and rounded runner allocation, including scripts, verdict and native verification, against both the original spend and the new single-worker fixture baseline. A local warm serial run proves coverage rather than two-runner cold latency. On macOS it builds all production packages with cgo and runs the focused Keychain, launchd, terminal, and CLI smoke suite above in short mode. macOS golangci-lint also runs on each pull request: the first pass blocks, and revive's doc-comment rule checks only code the pull request adds or changes. All jobs use Go 1.27.3 exactly (go.mod's toolchain line). A new push to a pull request cancels that pull request's older Test and Levenshtein runs.

Short mode scales large rendering, statistics, collector, and codec fixtures while retaining race checks and logical assertions. It deliberately omits real 32 MiB import admission/rejection and oversized journal encoding/refilter integration, and scales fixtures that exceed the former 128 MiB source cap. Default non-short tests remain exhaustive, and the Python purge runner defaults to --tier full. Weekly and exact-commit candidate runs restore full scale and matrices. Daily runs additionally restore the full catalog list50 /128+/512, same-root warm SQL /128+/512, actual CLI1100/1050 pagination and physical million-record related-history limit. Confirmed backfill runs its actual mixed 3/17-session import, publication and readback cases in short mode; daily, weekly and exact-commit candidate runs also restore the unchanged 513-session case. A short pass records the full 513-session body as NOT RUN. Under the race detector its durable-quota rescans exceed the 20-minute package timeout, so the race build skips that child with the exact plain_children reason and the restored tiers (Linux and the macOS obligations job) run it in one plain plain-restoration invocation whose pass the tier gate requires. The sparse staged-import traversal test runs all three actual consumers over 5,000 physical session directories in short mode; daily, weekly and exact-commit candidate runs restore the unchanged 50,000-directory body. Short evidence marks that full body as NOT RUN. These content-free directory fixtures do not qualify full native-session throughput. The combined durable census keeps 129 supported published peers and every save/readback, accounting, late-unknown and cancellation assertion in short mode over 257 physical entries. Its named 65,537-entry boundary is NOT RUN in short mode and restored daily, weekly and for exact-commit candidates. The small cached-prefix history test pins aggregate refusal/release/retry; it does not prove million-record physical streaming. Metadata 16384, retained warm sources 2000 and physical/indexed five-sweep 1100*2 bodies restore weekly. The picker catalog first-page bounds use 128/512 records on PRs and restore 10000/100000 records weekly/candidates. CLI first/Older page qualification retains 1400 records to preserve over 100 eligible rows after synthetic membership filters, and explicitly restores its 10000/100000-record matrices weekly/candidates. The exact names and existing 32 MiB import/encoded-text/refilter restorations are in scripts/ci_tiers.json. Scaled-capacity state tests and smaller import recovery still run on every PR. Unknown tests run in the ordinary unrestricted short suite by default; the tier catalog does not filter them out. Statistics/property/geometry and all 28 privacy field combinations retain their existing PR coverage.

Artifacts retain actual pass/skip identities, including skipped children and reasons. A scaled representative pass records its full scale as NOT RUN; a discovered skipped name is not a body pass. Selected daily full bodies must exist in dynamic discovery, pass without skipped children, and include required /512 or /1100 descendants. Ordinary unrestricted package execution uses actual terminals without another cold all-package listing. A previous scheduled or PR merge-ref run cannot replace validation of the final release candidate SHA. Dedicated real-manager verification permits only the existing TestRealUserManagerConformance/UnreadableAndAbsentDefinitions skip with its exact reason: a real manager cannot be put in a loaded state over damaged unit files. The fake-manager conformance suite covers that case. Artifacts retain the actual SKIP and reason; other skips and missing selected manager bodies fail.

The Git identity compatibility job runs three serial isolated native Git versions on one runner: pinned upstream Git 2.30.2 and 2.39.2, and the runner's current Git. It logs exact executable versions and verifies the pinned cases. Upstream 2.30.2 tests older command semantics; it does not establish acceptance of a Debian-patched Git package. Older distribution package acceptance is recorded separately.

A run-owned release-candidate/** branch push runs the same Test jobs and Levenshtein verify against the pushed commit, plus Extended macos-full, fuzz, and real-systemd. This provides an automatic final integration campaign when manual dispatch is unavailable. Extended skips its duplicate Linux suite on these branches because Test runs full non-short Linux race coverage and plain full-size performance assertions. Extended supplies full non-short macOS race coverage and plain full-size performance assertions. Extended full Darwin coverage uses a compiled native CGO/race catalog at the exact source SHA, followed by three independent macos-14 hosts. Whole ordinary packages and disjoint CLI parent trees share a deterministic weighted assignment; fuzz seeds and executable examples are discovered from the compiled test mains. Each host bounds Go package concurrency to one and test concurrency/CPU to two, with private temporary/build state. The macos-full check retains its stable name and reconciles all three workers, source/context/catalog identity, raw package and body terminals, and every named full restoration child. A separate native job compiles and runs plain performance bodies plus the pinned published writer once. The four-package plain command retains archive as an explicit compilation/test-main scope with required package PASS; its catalog has no performance-regex bodies. The collector, nativecodec and capture scopes require all five intended compiled parents and actual body PASS. Missing parents, missing packages or an unexpected performance match in the compilation-only scope fail validation; archive is never counted as a plain performance body. Daily remains smoke plus expanded short native integration and published writer. Full qualification fixture construction reuses canonical entry bytes across ordering memberships and counts their leaf framing without serializing nested payloads again just for the byte budget. Final node encoding and the 128 KiB limits remain unchanged; a bounded reference encoder pins node bytes, hashes and topology. Full 10k/100k qualification sizes and CLI phase assertions still run in the full native catalog.

scripts/native_full_hints.json contains advisory costs imported from the successful historical Darwin full artifact at 11ccad84, with source/settings, archive and raw-file fingerprints. Regeneration resolves its regular Git source blobs and derives the canonical historical schedule from only the pure scheduling definitions, with an explicit reviewed partition-helper compatibility pair and exact selector semantics. Current scheduling changes cannot rewrite old evidence; unreviewed helper contracts fail closed. It reuses the logical-duration helper from scripts/generate_go_shard_hints.py; it does not use Linux short costs. One older serial run cannot predict current worker elapsed time. Unknown/changed restoration CLI trees receive a positive unmeasured one-second weight; unknown/changed ordinary packages receive one second per compiled parent (minimum one). Other costs remain historical advice even when dependencies or CPU bounds change. Qualification and rebalancing require the current candidate's three-worker timings. Ordinary PR checks do not run this Extended full matrix. Full scheduled jobs can take longer than the four-to-five-minute PR goal.

Test, Levenshtein and Extended disable setup-go's shared module/build cache for every trigger; only the PR representative workers have explicit restore/save actions. Candidate validation cannot restore executable build state from another run. Go still verifies downloaded modules against go.sum; fresh runners may take longer while downloading and compiling dependencies. Concurrency groups keep each candidate branch separate from other runs. Candidate pushes cannot start the tag-only signing workflow or the manual promotion workflow. Record the exact pushed SHA and all three run URLs; missing, skipped, queued, timed-out, or failed required jobs leave readiness pending. Push a fresh candidate ref at the final main commit after merges if merge commits or squash changed the previously tested SHA. These campaigns do not establish live provider, app, architecture, or signed-installer acceptance; see releasing.

The Extended workflow uses separate daily 17 8 * * 1-6 and weekly 17 8 * * 0 cron events, avoiding a duplicate daily campaign on Sunday. Daily runs all Linux representative race bodies plus the seven named full restorations, native Darwin platform smoke, expanded native config/catalog/capture/source-I/O integration and the pinned published writer, actual systemd scheduler/setup/timer/uninstall, five seconds of mutations on every discovered fuzz target and expanded purge cases. Daily Linux short race bodies use the full tier's compiled CLI split with -short, because one short CLI process reached the 20-minute package timeout; all its invocations overlap in one batch to fit the daily job's 50-minute limit and must record every assigned parent. Extended Linux exports GOMEMLIMIT=3GiB for every event; native macOS workers run with --seconds 3000 so their receipt uploads inside the 60-minute job. Weekly runs complete default Linux and Darwin race suites, plain full-size performance assertions, exhaustive purge products and 30 seconds per fuzz target. Security advisory/workflow audits remain fresh daily in Levenshtein, including the separate release-compiler vulnerability scanner.

Candidate pushes and manual all always select full coverage regardless of the calendar. Candidates supply Linux full coverage in Test, so Extended avoids running Linux twice; it supplies Darwin, fuzz and real systemd. Manual per-suite choices run that suite full. Separate scheduled/manual concurrency groups cannot be cancelled by a newer main push. Missing/failed/cancelled bodies or artifacts leave validation incomplete. The workflows retain source SHA, tier, commands, actual terminals and selected/not-run identities in artifacts. No dependency, compiled-test, result or advisory caches change with these tiers. The separate PR cache policy below does not apply to these full/scheduled jobs.

PR dependency and compilation caches

Only the two linux-short PR workers restore Go modules and compiled artifacts with explicit pinned actions/cache/restore and /save actions. Setup-go's integrated cache stays disabled. Both workers need the full CLI race testmain; their ordinary packages differ and worker 0 also runs vet. Each worker therefore owns a separate cache and save key; neither races the other worker's save. The only cached paths are controlled runner-temp pr-go-build and pr-go-modules directories. Catalogs, manifests, tier/body evidence, test results and security advisories are never stored as verification evidence in a cache. Actual discovery and execution use -count=1 regardless of cache outcome, and the required verdict always reconciles freshly generated artifacts.

Keys include actual Go 1.27.3 driver/build/vet tool bytes, native OS/architecture/CGO/flags, C/C++ compiler binary/version identities, runner image/version and OS metadata, both module files' bytes, PR number, worker and source tree. A single narrow restore prefix may reuse older source from the same PR/worker/dependency/build context; Go's input-derived compilation keys rebuild changed code. Context or dependency changes have no broad fallback. Missing/unsafe context fails explicitly. Actual event base/head/tested merge ancestry and tracked bytes/types/modes are checked before restore, after module verification and after successful execution, including index-hidden edits. Module download and go mod verify run on hits and misses. Source/checksum/discovery/test failures remain failures and cannot save. A missing or transport-failed restore clears only the owned cache directories, then runs normal compilation/tests; save service failures warn after actual worker success.

PR merge scope is never promoted to main/base/release caches. Saves additionally require a successful same-repository PR; forks still verify and execute but do not create caches under this conservative policy. A cache contains no secrets or private artifacts. Compiler input hashes and module verification are useful rebuild/corruption checks, not proof of adversarial restored-state integrity. Candidate, manual/full, scheduled, native and security verification paths stay fresh; a cached green PR cannot replace fresh exact-candidate evidence.

Adoption requires frozen-source uncached/cold/warm hosted measurement, including hash/source/compiler metadata, module verification, restore/save/upload/post steps, real verdict latency and each job's rounded allocation. No warm-speedup or 4–6-minute guarantee follows from enabling this attachment. Initial PR/fork misses, duplicated module/full-CLI cache volume, immutable keys, image changes, quota/eviction and restore/verify/save overhead limit useful reuse. Native caches need their own measured case. Dedicated measurement adapters may share the pure key/context primitives with an isolated namespace and truthful dispatch source; the production entrypoint remains PR-only. Never spoof event/SHA or broaden full/candidate paths to measure this policy.

Purge --tier pr retains every test method, bash/zsh where available and every privacy, wrong-prefix, ownership, preflight, corruption, pause, partial-deletion, crash and recovery failure class. It reduces only the repeated fresh-shell resume product to first/last boundaries in the ordinary prefix for every mode; other prefix protection and uncertain capsule refusal cases still run. Daily expands that product to all prefixes and first/middle/last boundaries. Weekly, candidate and no-option direct invocations keep every original combination, including the tenth all-prefix boundary for an empty prefix. Its evidence records omitted case tuples as NOT RUN, not passes. CI requires jq, bash and zsh rather than accepting an empty shell list or missing-tool skips.

Large integration-only regressions may be detected up to 24 hours later; exhaustive scale regressions up to 7 days later. Conservative relevant PR backstops and full exact-source candidates reduce that risk. Feedback and allocated compute still need measurement on final settings; fixture durations cannot be added as savings.

The Keychain code needs cgo and Xcode's command line tools on macOS; elsewhere a stub is built. The real-systemd job runs the Linux scheduler against a real systemd user manager on Ubuntu (see below). The separate Extended job is a backstop; sensitive PRs also require its real manager bodies through the Test tier plan. go test ./... also checks the docs: internal/doclinks fails on a broken relative link or #anchor in any Markdown file, TestDocsQuoteOnlyRealCommandsAndFlags on an agent-archive COMMAND --flag quoted in the README, the docs, or an issue template that the CLI does not accept, and TestCLIReferenceIsCurrent on a stale CLI reference.

Performance tests check what a pass costs on every run (published-state decodes and local writes, counted, not timed). Their wall-clock targets run only at full size in a plain build, which CI runs weekly, on candidate pushes, and in manually dispatched full OS suites:

AGENT_ARCHIVE_PERF=1 go test -v -p 1 -count=1 -run 'StayFast|FiveMegabyte|TestCursorOverlappingHooksRegisterOnce' ./internal/collector ./internal/archive ./internal/agents/nativecodec ./internal/capture

A test of a timeout or budget doesn't time the whole call: -race on a loaded runner stretches the file writes around the wait by seconds. It checks the deadline a stub sees against clock readings taken in the stub (TestOriginURLGivesGitAtMostTheTimeout), or runs the code in a testing/synctest bubble, whose clock moves only while every goroutine in it is blocked (TestHookRegistersOnTimeWhenTheRepoKeyLookupHangs).

Levenshtein checks

The verify job (levenshtein.yml) runs the shared checks from wangjohn/levenshtein at the commit that workflow pins, on Linux: Go lint (staticcheck, HTTP-body and SQL-close rules, and more) and vet, go.mod hygiene, govulncheck, actionlint, and zizmor for the workflows. levenshtein.json picks the checks. The full lint selection includes bodyclose and sqlclosecheck; separate go-http and go-sql checks would repeat those analyses. Keep those rules in the full lint selection when updating the pin.

CI runs the pinned tools natively with Go from Levenshtein's .go-version, Linux amd64 build settings, and cgo enabled. scripts/stage_native_verify.py copies the tracked inputs selected by the pinned planner into a fresh temporary root, preserving relative paths and excluding private files and symlinks. This keeps unrelated packages such as scripts/acceptance/cloudflare outside the analysis, just as the container does. Native tools still have normal host filesystem access; staging is not a container sandbox. The checked-in configuration keeps Dagger for local runs. Pushes and manual runs retain all six checks; nightly audits retain the main run and rerun_checks: true. Only PR events may select the guarded Go-only run described below. The CI adapter fails before execution if future community rules, environment settings, checks or target/run policy cannot be preserved by the native route. Verified trusted compilation/module seeds may be restored; check results and XDG state stay fresh, and vulnerability checks continue querying current advisory data.

The additional native-release-vulnerabilities job runs on the same workflow events, alongside the existing verifier. It installs the product Go 1.27.3 compiler from go.mod and refuses a different native compiler or shared verifier pin. Its helper stages the tracked archive inputs into a new private directory and generates a temporary native-only vulnerability run; it leaves the repository's six-check Dagger configuration and PR selection unchanged. The pinned scanner queries advisory data on every execution. This additional check identity is not added to branch protections by this change. Passing Python preparation controls or compiling the helper does not establish a native scan pass; record the exact candidate and successful scanner result.

For PRs, the staging helper can omit actionlint and zizmor when the event base, actual PR head, and tested merge prove that workflow inputs are unchanged. The four Go checks still run in full. Changes anywhere under .github or scripts, to levenshtein.json, or to relevant root tool/configuration files run the complete checks. Missing history, unexpected ancestry, dirty source, symlinks, or an unsupported configuration also retain the complete run. The required verify job remains present, and its summary identifies workflow checks as NOT RUN when scoped, with the compared commits. Main, nightly, manual, release-candidate and direct local verification keep all six checks.

The cold comparison used identical deduplicated source and pinned checks on fresh ubuntu-24.04 workers. Native preparation plus verification took 178 seconds versus 268 seconds for Dagger, with a repeat at 182 versus 335 seconds; deliberately failing Go/workflow probes reported identical diagnostics. These are verification timings, not a promise about total PR feedback. Check durations overlap, and Dagger client CPU omits engine work; the shorter same-class runner duration is the compute-cost comparison.

Run the same thing from a sibling checkout of Levenshtein at the pinned commit (it needs Docker):

../levenshtein/verify pre-merge --source .

The Go lint is the check most changes trip, and it runs natively in seconds. Build its binary once from the pinned commit, then lint as the container does, with Linux build tags and the checks list from Levenshtein's runner/toolchain.json:

pin=$(sed -n 's/^ *ref: \([0-9a-f]\{40\}\)$/\1/p' .github/workflows/levenshtein.yml)
git -C ../levenshtein worktree add /tmp/levenshtein-pin "$pin"
(cd /tmp/levenshtein-pin/runner/lint && go build -o /tmp/levenshtein-lint ./cmd/levenshtein-lint)
GOOS=linux CGO_ENABLED=0 /tmp/levenshtein-lint \
  -checks 'all,-ST1000,-ST1003,-ST1016,-ST1020,-ST1021,-ST1022,-gocognit' ./...

It prints nothing when clean. Because it lints Linux build tags, the darwin-only Keychain and launchd files are covered by the macOS golangci-lint job instead. Two things it enforces that surprise people: a //lint:ignore nilerr directive never works (restructure the code instead), and terminal output goes through internal/terminal rather than _, _ = fmt.Fprintf.

Never test against your real machine

Tests and hand-run experiments must not touch your real home directory, your apps' real hook files, the real LaunchAgent or systemd user units, your Keychain, Cursor's real database, or a real bucket. The live collector on your machine is com.agent-archive.collector (launchd) or agent-archive-collector.timer (systemd).

In Go tests, everything goes through injection:

  • internal/cli tests build an Env (see testEnv in cli_test.go) with a temporary data directory, temporary user and account homes, a fixed clock, no environment variables, and an in-memory bucket. Its scheduler (Env.Scheduler, a fakeScheduler that answers every job "missing" and fails the test on a load or stop), Keychain, and executable fields fail the test unless the test sets them; setupTestEnv gives it a scheduler that loads and stops jobs like launchd. To drive the real launchd code, set Env.Scheduler to nil and replace runLaunchctl with stubLaunchctl.

  • Isolation in internal/cli fails closed. Its TestMain points $HOME at a temporary folder, unsets AGENT_ARCHIVE_HOME, CLAUDE_CONFIG_DIR, CODEX_HOME and the AWS configuration variables, and replaces the real launchctl and Keychain with stand-ins that stop the test (see isolation_test.go). A test that leaves an Env field unset can therefore never reach your real apps, launchd, or Keychain.

  • internal/capture (the hook runtime) takes its data directory as an argument and does not import anything that runs launchctl, opens the Keychain, or uses the network (TestCaptureImportBoundary), so it has no stand-ins for them. Its tests may not either: TestCaptureTestsCannotReachTheMac fails a test file that imports os/exec or the network, or uses internal/credentials for anything but a config's storage settings. Its TestMain gives its tests a temporary HOME, unsets the same variables, and keeps $TMPDIR in a folder of the run's own (internal/testutil/isolation). Its tests call capture.HandleEvent directly; tests that go through a command (_hook, status, sync, setup) stay in internal/cli.

  • internal/setupjournal (setup's journal, rollback and recovery) reaches a scheduler only through the Backends it is passed, which resolve the backend name each journal records, so its tests pass a launchdSim (a launchd's ownership rules: a label loaded from another plist is never stopped, and bootstrap and bootout can fail) or a schedulertest.Model (a second backend, to see each job driven through the backend that made it) and cannot reach launchctl; its TestMain isolates the process as internal/capture's does. Tests that run setup itself stay in internal/cli.

  • internal/scheduler/launchd (the macOS adapter) runs launchctl only through the scheduler.Runner it is given, so its tests pass a recording Runner and cannot reach launchd. It passes schedulertest.RunConformance, the suite every scheduler adapter must (the state matrix, refusing to stop what another installation owns with typed errors, an idempotent unload, loads and unloads that a cancelled context does not stop, Plan's purity and recorded output, the Plan to Inspect and refresh round trips, no credential in a definition, Installed listing the installation's own job first and its earlier jobs after), over a fake launchctl that prints the recordings in internal/cli/testdata/scheduler/launchctl-print; the schedulertest.Model, a scheduler with a vocabulary of its own, passes it too, and is what code written against the port can be tested over. internal/scheduler/host owns the real Runner; its tests run a stand-in launchctl script found on a temporary PATH. TestOnlyListedPackagesRunPrograms fails when a package outside a listed set imports os/exec, and TestOnlyHostImportsAdapters when one but host imports an adapter; depguard says the same in .golangci.yml.

  • internal/scheduler/systemd (the Linux adapter) is tested the same way: a recording or fake Runner and no systemctl. It passes schedulertest.RunConformance for systemd 239, 245, 252 and 255 over a fake systemctl that answers show from the fixtures in internal/scheduler/systemd/testdata/systemctl (captured from real user managers in disposable containers; the README there says how), and the state map is pinned over the same fixtures. internal/cli's Linux tests drive the real commands over it with fakeUserManager, a user manager that keeps each job's state, answers show and enables a timer only when its unit files are where the manager searches.

  • The same adapter also runs against a real systemd user manager, which no fake can vouch for: TestRealUserManagerConformance (the conformance suite, with states put in and read back by systemctl itself) in internal/scheduler/systemd and TestRealSystemdSetupRunsTheTimerAndUninstallStopsIt (the real setup, the manager's timer starting the job's program, the real uninstall) in internal/cli, with TestRealSystemdUninstallSkippingTheSchedulerPrintsACommandThatStopsTheJob (uninstall --skip-scheduler with the manager out of reach, then the command it prints, which must stop the timer the manager still runs after the unit files are gone). They skip unless AGENT_ARCHIVE_REAL_SYSTEMD=1, because they change the running user's manager (units named agent-archive-collector* in ~/.config/systemd/user, and the user's hook and skill files for the smoke); they refuse a machine that already has such units. Extended CI runs them daily or on demand in the real-systemd job on ubuntu-24.04 (a virtual machine with systemd: it enables lingering for the runner user, sets XDG_RUNTIME_DIR and DBUS_SESSION_BUS_ADDRESS, and waits up to two and a half minutes for the timer's first run). That job is a daily or manually requested check, pinned to the image it was validated on rather than ubuntu-latest, whose move to a new image would change the systemd version and defaults. Bump the pin deliberately, re-validating on the new image with scripts/acceptance/linux first. Keep the job's name real-systemd for consistent backstop results (scripts/test_ci_workflow.py fails on a rename or an unpinned image). A failure in it is a real finding about the adapter. To run it yourself, never on your own machine or login, use a disposable Linux container with systemd as PID 1 (Docker on macOS runs it in a Linux VM) and a non-root user (or run scripts/acceptance/linux/host.sh, which does all of this and more; see the Linux live acceptance run):

    docker run -d --name aa-systemd --privileged --cgroupns=host \
      -v /sys/fs/cgroup:/sys/fs/cgroup:rw --tmpfs /run --tmpfs /run/lock \
      IMAGE /sbin/init   # Ubuntu 24.04 with systemd, dbus-user-session, sudo and Go
    # as a user with sudo, in a checkout of the repository inside it:
    sudo loginctl enable-linger "$USER"     # starts the user's manager
    export XDG_RUNTIME_DIR=/run/user/$(id -u) DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus
    AGENT_ARCHIVE_REAL_SYSTEMD=1 go test -count=1 -v -run 'TestReal' ./internal/scheduler/systemd ./internal/cli
    docker rm -f aa-systemd                 # when done
  • internal/stats (the statistics engine) is a pure function of the metadata, time, time zone and price table it is passed, so its tests build synthetic archive.Metadata and need no isolation. TestStatsImportBoundary and TestStatsReadsNoClockOrEnvironment keep it that way: it imports only archive's types and reads no clock, file or environment. Its default prices are internal/stats/prices.json, dated and versioned; update the file (and its as_of and version) from the pages in its sources when list prices change. Read each model's own page as well as the pricing table (the two can differ), and re-check any price the notes call promotional on its end date: the table does not expire by itself.

  • internal/statshtml (the stats --html page) is a pure function of the stats.Stats it is passed, so its tests compute stats from synthetic metadata and need no isolation. Every page a test renders goes through checkPage: strict XML parsing, an allowlist of elements, no script, event handler, link or other request, unique ids, and a stylesheet that fetches nothing. TestHostileTextIsInertInEveryField sets every text field of the stats, in turn, to names built to break out of markup; TestSpoiledNumbersNeverBreakTheGeometry does the same with numbers (NaN, infinities, extremes); TestOnlyTheseStatsTextsReachThePage pins which stats texts may reach the page at all (a new one is a privacy decision); and TestPaletteContrast checks the colors' WCAG contrast in both themes from the stylesheet itself. TestStatsPageAgreesWithTheTerminalAndJSON (in internal/cli, which may import both) runs the screen, --json and --html over the same archives and compares every table, card and sentence, because the two lay their numbers out separately (they share internal/statsfmt, whose one table pins every formatter, and whose TestFormattersImportBoundary keeps it pure). The page goldens are in internal/statshtml/testdata/ (go test ./internal/statshtml -update); look at a changed page in a browser, light and dark and at phone width, before accepting a diff.

  • internal/credentials fails closed too: its TestMain replaces every Keychain call KeychainStore makes with one that stops the test, so a test can reach the real login Keychain only through the opt-in TestKeychainRoundTrip (AGENT_ARCHIVE_KEYCHAIN_ROUND_TRIP=1). The file store and the environment store (what OpenDefault picks off macOS) have no build tag, so their tests run on macOS and Ubuntu alike; they write only under t.TempDir(), take the platform, the folder, the environment and the Keychain constructor as arguments, and never open a real Keychain. In internal/cli, credentialOS is platform.Darwin in every test (the fake store stands for the Keychain, so its wording is pinned on every runner); a test of the other platform's wording calls useCredentialOS and must not be parallel.

  • The operating system is a value (platform.OS), read once by platform.Current and passed everywhere else, so a test answers for macOS, Linux or an unknown system on any host: Env.OS in internal/cli, Environment.OS in internal/backfill, OpenOptions.OS in internal/credentials, platform.NewLocations for where each system keeps Cursor's data. Tests pin a platform explicitly (testEnv models a Mac) and never branch on runtime.GOOS except to say what the real system must answer; TestOnlyPlatformReadsRuntimeGOOS fails a production file that reads runtime.GOOS itself. An unknown system fails closed (no Cursor location, no credential store) and each caller's choice is pinned by a test.

  • The mount table the Linux network-home check reads (/proc/self/mountinfo) is Env.MountTable in internal/cli, and the package's isolation replaces its default with one that reads nothing, so no test sees the machine's own mounts: a test of a network home passes a table (mountTableWith), and an unreadable one stops nothing. local.FilesystemProbe takes the same table and its own symlink resolver.

  • internal/backfill and internal/cli point Cursor database copies at a per-run temporary folder (cursorstore.SnapshotTempDirForTesting, set in their TestMain). The real root is a choice of platform.Locations over values (macOS: the per-user temporary directory; Linux: under $XDG_CACHE_HOME or the account's ~/.cache), and cursorstore's tests make it in a temporary directory through preparedSnapshotRoot(root, cacheDir), so no test touches a real cache directory. The isolation helpers unset XDG_CACHE_HOME with XDG_CONFIG_HOME.

  • Storage tests use storagetest.NewMemoryStore() (internal/storage/storagetest, test code only: depguard keeps it out of production code, as it does state/statetest).

Running the binary by hand in a sandbox

scratch=$(mktemp -d)
mkdir -p "$scratch/home" "$scratch/stub"
cat > "$scratch/stub/launchctl" <<'EOF'
#!/bin/sh
# Stand-in for launchctl: no job is ever loaded, and nothing reaches launchd.
echo "stub launchctl $*" >&2
if [ "$1" = print ]; then
  echo "Could not find service \"$2\" in domain for port" >&2
  exit 113
fi
exit 0
EOF
chmod +x "$scratch/stub/launchctl"

export AGENT_ARCHIVE_HOME="$scratch/data"   # a data directory of its own
export HOME="$scratch/home"                 # app configs and LaunchAgents live here
export PATH="$scratch/stub:$PATH"           # agent-archive runs `launchctl` from PATH
# Variables that would point setup back at your real configuration:
unset CLAUDE_CONFIG_DIR CODEX_HOME AWS_CONFIG_FILE AWS_SHARED_CREDENTIALS_FILE XDG_CONFIG_HOME
  • AGENT_ARCHIVE_HOME gives the sandbox its own data directory and its own launchd label; a sandboxed HOME keeps setup away from your real app configs. Neither stops a completed setup from loading its job into your real launchd, which is what the launchctl stub is for. The stub answers print as launchd does for a job that isn't loaded ("Could not find service", exit 113); a stub that just exits 0 there leaves the job's state unknown, and setup refuses to continue. Without the stub, cancel setup at "Start archiving?".
  • CLAUDE_CONFIG_DIR and CODEX_HOME would send setup's hooks to your real app configuration even with a sandboxed HOME; the AWS_* file variables would use your real AWS profiles. Unset them.
  • Choose S3 (a local MinIO, below) in a sandbox, not R2: R2 secrets are saved in your real login Keychain, which a sandboxed HOME doesn't change.
  • Setup needs a terminal; script -q /dev/null agent-archive setup supplies one when you drive it from a script.
  • For storage, run a local S3-compatible server (MinIO works) and point an AWS profile in the sandbox's ~/.aws/config at it with endpoint_url = http://127.0.0.1:9000.
  • To exercise the pipeline without setup, write config.json by hand (see configuration) and feed agent-archive _hook --harness <app> a JSON payload on stdin with a copied transcript path, then run agent-archive sync. Never register a real transcript path.
  • scripts/measure-hook.py BINARY measures hook latency in its own temporary directory; it installs nothing.
  • On Linux a stub systemctl is not enough. setup asks systemctl --version and systemctl --user show ... and refuses to go on when it cannot get a real answer, and a sandboxed HOME does not stop it from enabling a timer in your real user manager. Run the binary by hand only in a disposable Linux container with systemd as PID 1 (the recipe under the real-systemd bullet above, or the Linux live acceptance run, which builds one and drives the whole product in it), never in your own login.

The hidden commands _hook (what app hooks run) and _collect (what the LaunchAgent runs) are not part of the user interface and may change.

The Linux live acceptance run

The Linux adapter's unit tests run against fakes and the real-systemd CI job runs two real-manager tests; neither runs the product the way a person does. scripts/acceptance/linux/host.sh does: the real setup, hooks, timer, collector, status, setup --refresh and uninstall, over a real systemd 255 user manager, with a MinIO standing in for the bucket. Run it before a change to the Linux scheduler, setup's rollback, uninstall, the collector's environment or the Cursor snapshot root merges, and before any claim that Linux works is published.

scripts/acceptance/linux/host.sh            # the whole run
scripts/acceptance/linux/host.sh --dry-run  # what it would create; no Docker needed

It needs only Docker (colima or Docker Desktop on a Mac; with a Linux Docker the privileged machine shares your own kernel, so use a VM there) and Go to cross-build (BUILD_IN_DOCKER=1 builds in a golang container instead). It builds linux binaries of your working tree, starts a privileged Ubuntu 24.04 container with systemd as PID 1 and a MinIO container on a network of their own, runs guest.sh in the machine as root, prints each check as PASS or FAIL, and removes everything it made (named aa-accept-<random>-*; it removes nothing else, such as a MinIO of your own) whether it passes, fails or is interrupted. Nothing runs on your Mac but Docker's client and the Go build, nothing of your home, Keychain or buckets is involved, the only credentials are a MinIO user and password made up for the run, and every transcript is synthetic (the repository's fixture, and a Cursor database the script writes). It takes about three minutes (150 to 170 seconds measured) with Docker's caches warm, most of it waiting for systemd timers (the collector's first run is a minute after boot). It is not in CI: a privileged container is not something CI should be asked for. python3 scripts/test_linux_acceptance.py is in CI and checks the scripts without Docker (shellcheck, --dry-run, and with a fake docker that cleanup removes only the run's own names, on success, failure and interruption).

What it covers, by section of guest.sh (the README beside the scripts lists each check):

  • Setup and the timer: setup --yes to S3 from a shell with XDG variables; the unit files' content and mode, the recorded PATH and XDG environment, append: logging, the enable link, the timer running the collector in the manager, config.json's backend and host_id.
  • Capture: a synthetic Claude Code session through the hook command setup installed, published by the timer's collector (not sync) and read back with list and show; a hand-made Cursor database written the way a running Cursor leaves it, with a chat older than setup's 7-day import, imported by backfill through a copy under $XDG_CACHE_HOME/agent-archive/cursor-snapshots (mode, CACHEDIR.TAG, the copy removed, nothing under /tmp or the default cache).
  • status: the XDG-drift warnings, and the machine-ID clone warning (quiet on the original; after /etc/machine-id changes it warns in status --issues, --json and setup, and setup keeps the recorded host_id; a machine ID bind-mounted over /etc/machine-id is not read, so it stays quiet).
  • setup --refresh after the binary moved, and uninstall.
  • The enable link on every path that removes a job: uninstall; uninstall --skip-scheduler with a reachable manager and with no user bus (the unit files go, no dangling link is left, the manager keeps the timer until the printed stop command is run, and that command stops it); and a setup whose start fails after systemctl enable made the link (a systemctl wrapper in the user's PATH enables without starting, then fails): the rollback leaves no files, no link and no running timer.
  • The real-manager Go tests (AGENT_ARCHIVE_REAL_SYSTEMD=1) as a second lingering user, and cursorstore's snapshot tests on a real Linux account.
  • On the container's own disk, status reports no network filesystem and config.json records no allow_network_home opt-in. A real network home remains untested live.

What it does not cover: the real Cursor application, cursor-agent and the Cursor database layout on Linux (the database is hand-made after macOS's and VS Code's layout, so a real Cursor's Linux paths and its hook approval are unverified); the real Claude Code and Codex apps (only hand-written Claude Code hook payloads are exercised); any distribution other than Ubuntu 24.04 or systemd other than 255 (the fixtures cover 239, 245, 252 and 255 for the adapter's parsing, but only 255 has run live); a manager without lingering over a real logout (the no-user-bus session is simulated by unsetting the bus variables); real R2 or AWS (MinIO stands in); WSL; Linux running as the machine's only user session with a desktop; and anything about upgrades from an earlier release.

Recorded runs (record each run that follows a change to what it covers: date, commit, systemd, architecture, result):

  • 2026-09-30, the tree of the pull request that added the run (on top of 5c's enable-link and clone-warning change), Ubuntu 24.04.5 LTS, systemd 255 (255.4-1ubuntu8.17), linux/arm64 (Docker in a colima VM on an Apple silicon Mac): 88 passed, 0 failed, 150 seconds. The run found nothing wrong with the product. At that point amd64 had not been run.
  • 2026-09-30, the same pull request after review (the Go test binaries must report each named test passed, a root-only cursorstore test added), same machine: 89 passed, 0 failed, 160 seconds. A deliberately broken build (the enable link left out of uninstall's paths, and the clone warning turned off) failed 8 checks, in sections 6, 9, 11 and 12.
  • 2026-10-01, the network-home guard's pull request after review (section 2 also checks that status sees no network filesystem and config.json records no allow_network_home on the container's own disk), same machine: 91 passed, 0 failed, 103 seconds. A home on a real network filesystem is not run live (the container cannot fake an NFS mount's type); the unit tests cover it with injected mount tables.
  • 2026-10-01, clean commit 61d068b785a6d554bad8400ae8ab69023e355dad, Ubuntu 24.04.5 LTS, systemd 255 (255.4-1ubuntu8.17), linux/amd64 (Docker in the x86-64 Colima levenshtein VM on macOS): 91 passed, 0 failed, exit 0, 341 seconds including guest image preparation. This establishes live harness coverage on amd64 as well as arm64. The first attempt stopped before any checks because Quay returned 401 for the default MinIO image; Docker Hub images were also unavailable and official binary downloads returned 410. The successful retry used MINIO_IMAGE and MC_IMAGE with temporary Alpine 3.24 images built from official source pins: github.com/minio/minio@v0.0.0-20260212201848-7aac2a2c5b7c and github.com/minio/mc@v0.0.0-20251106162529-77f82e18b540, cross-built with Go 1.27.1, GOOS=linux GOARCH=amd64 CGO_ENABLED=0. Product code and checks were unchanged; the run's resources and temporary MinIO images were removed. Local evidence (not committed): /private/tmp/agent-archive-linux-acceptance-20261001-61d068b-retry.log and /private/tmp/agent-archive-linux-acceptance-20261001-61d068b-summary.txt.
  • 2026-10-20, v0.2.2 product (8764d745) with the harness updated for the product's changes since 2026-10-01 (compact config.json, the status overview with warnings under --issues and app rows under --verbose, the new list layout, and setup's 7-day import, which now took the Cursor chat before backfill could), Ubuntu 24.04.5 LTS, systemd 255 (255.4-1ubuntu8.18), linux/arm64 (Docker in the colima levenshtein VM): 93 passed, 0 failed, 167 seconds. Before the update the same product failed 12 checks, all of them the harness's; none was a product defect. The compact config.json had also made section 6's kept-host_id check pass on an empty match; it now checks the ID was read (one of the two new checks; the other names the project list shows).

When a check fails, read it from the top (later sections build on earlier ones), and diagnose before changing a check: a failure is a finding about the product until shown to be the harness's. KEEP=1 leaves the machine for a look; the README says how to get a shell as the user whose manager is running.

Fixtures and goldens

  • Adapter fixtures are in internal/archive/testdata/ as <app>-<shape>.jsonl with synthetic content only. filter-golden.json pins the SHA-256 of what each fixture filters to; Cursor database chats (internal/archive/testdata/cursor-composer/), handoff output (testdata/handoff/), eval export records (internal/archive/testdata/eval-export/, each line validated against its schema), the stats screens end to end at 60, 80 and 120 columns and without a terminal (internal/cli/testdata/stats/), every stats page (overview, detail, projects, models, agents) at 60, 80 and 120 columns with and without color from hand-built numbers, plus a previous period, Cursor alone, saturated sums, hostile names and ASCII (internal/cli/testdata/stats/pages/; a colored golden writes each escape character as \e), backfill plans (internal/cli/testdata/backfill/, internal/backfill/testdata/) and the CLI reference have goldens of their own.

  • One flag rewrites every golden file:

    go test ./... -update                  # or one package: go test ./internal/archive -update
    git diff                               # review every changed line

    Review the diff line by line: a change to the archive's goldens is a privacy change (see versions). The flag is defined once, in internal/testutil/golden (golden.Check, golden.Update), which every package with tests imports, so no package rejects it (TestEveryTestedPackageKnowsUpdate). A new golden test uses golden.Check; a package with tests but no goldens imports the package blank.

  • Screen goldens (internal/cli/testdata/screens/, TestScreens in internal/cli/screens_test.go) record what setup and status print, whole, for the screens users meet most: a first run with and without apps, the recent-projects list, the resume and reconfigure menus, a failed storage check, the review, the next steps, and status when ready and when it needs attention. Each is recorded twice: NAME.txt as a pipe or NO_COLOR shows it, and NAME.color.txt as a color terminal does, with each escape character written \e. Setup's answers are echoed after their prompts, and the paths (home /Users/alex) and the clock (2026-09-25 12:00 UTC) are fixed. A change to what setup or status prints rewrites them, so review the diff as the change's screenshots:

    go test ./internal/cli -run Screens -update
    git diff internal/cli/testdata/screens

    A new screen is one more entry in screens: its answers, its exit code, and an arrange function that prepares the machine through the fixture.

  • A bug fix comes with a test that fails without the fix. Check by reverting the fix.

Where tests live

  • A test sits next to the production file it covers: tests of status.go go in status_test.go, or in status_<aspect>_test.go when one aspect has enough tests to be worth its own file (status_gaps_test.go, setup_transaction_recovery_test.go). Package-wide test helpers (testEnv, fixtures used by many files) live in cli_test.go or the package's testonly_test.go; TestMain lives in main_test.go.

  • Name files and tests by the behavior they pin (TestUndoKeepsAProjectAnotherImportStillNeeds), never by the review, round, or pull request that found the bug: no review_fixes_test.go, second_review_test.go, or cli_correctness_test.go.

  • Record where a regression came from in the test's doc comment instead:

    // A resumed chat keeps the project it started in.
    //
    // Regression: 2026-09 review H-21.
    func TestResumeKeepsItsProject(t *testing.T) {
  • Moving tests between files is a pure move: keep each test's body unchanged, and check that go test -list '.*' ./... prints the same names before and after.

Parallel tests

Tests call t.Parallel() unless they cannot share the process: a test that assigns a package variable (stubLaunchctl, collectSoftDeadline, hookDiagnosticsWait), calls t.Setenv or os.Chdir, reads a process-wide counter (state.PublishedStateLoads), removes this process's Cursor snapshots or checks what a sweep of the shared snapshot folder did, orders goroutines with real sleeps, or needs work to finish within a production time bound that a busy parallel run can exceed (a hook's lock wait, a version command's output deadline) stays sequential, with a comment saying why when it is not obvious. Go runs every sequential test before it releases the parallel ones, so a package variable a sequential test changes and restores is never seen by a parallel test. Test seams that vary per test belong in Env (observeFlags, backfillCheckpoint, exitOnSignal), not in package variables. Subtests that each build their own fixture call t.Parallel() too.

Check a change for order dependence and races with go test -race -count=3 -shuffle=on ./internal/cli, and for timing under load with go test -race -cpu 1,4,18 -shuffle=on ./internal/cli. internal/cli's TestMain puts $TMPDIR (so every t.TempDir) in a folder of the run's own under /tmp: local.CanonicalPath lists each parent of a path, and macOS's per-user temporary folder can hold thousands of entries. (The product calls it only from setup, status and uninstall, on paths under your home folder, never from a hook or a collector pass.)

Live acceptance: guided R2 creation

Guided R2 creation (internal/cloudflare, internal/cli/setup_r2_create.go) is tested against a fake Cloudflare (internal/cloudflare/cloudflaretest). Its request and response shapes come from Cloudflare's API reference, read on 2026-09-29, and the fake cannot confirm the points the documentation leaves open. A partial real-account provider run on 2026-10-05 is recorded below. The maintainer approved general availability on 2026-10-05 after additional acceptance testing. Guided creation and machine pairing/key management now need no experimental environment switches. The checklist below tracks remaining provider coverage; approval does not turn unrecorded cases into passes. Use a scratch Cloudflare account (never one with real archives), and the sandbox recipe below, so nothing touches your real Mac; create the bootstrap token with exactly the two permissions setup prints, then run agent-archive setup and choose "Cloudflare R2", then "Continue". Record the result of each item in the open-source acceptance record.

The 2026-10-05 provider evidence records a run on macOS arm64 using two new private scratch buckets, three bucket-scoped keys and synthetic objects. All keys and buckets were deleted. Lowercase-hex SHA-256 derivation, storage probe/write/read/list/delete, access outside the archive prefix, denial on the second bucket, canonical immutable names/policies with no expiry, bounded inventory and independent revocation passed. Revocation denial was observed after about 4.24 seconds in this one run; this does not establish an immediate-cutoff guarantee. Activation was measured after three sequential creations, so exact mint-to-activation latency is still unknown. An already-deleted token returned HTTP 404, code 1003; this observation does not justify treating every 404 as confirmed absence.

The sole failed check exposed a classifier mismatch: management REST returned HTTP 409 with code 10004 for the duplicate bucket. The classifier and fake now recognize that response, while retaining code 10073 from the Workers/S3 error reference. The original failed evidence is preserved. The provider rerun passed every required runner check, including collision classification, and confirmed cleanup of all three keys and both buckets. Actual guided-setup collision/retry acceptance is still required.

Build and run the isolated provider runner from a human terminal:

go build -o /private/tmp/agent-archive-cloudflare-acceptance ./scripts/acceptance/cloudflare
/private/tmp/agent-archive-cloudflare-acceptance --output /private/tmp/aa-cloudflare-acceptance-next.json

It prompts for the account ID and a hidden management token, uses no real archive configuration, Keychain or scheduler, journals only sanitized evidence with mode 0600, and cleans up only resources created by that run. Interrupted runs exit unsuccessfully. Evidence-write failures stop acceptance work but do not stop the remaining cleanup attempts, and are reported as failures. It does not exercise the CLI pairing transaction. Exact management-token permissions have not yet been confirmed by the operator, so account/domain reads with precisely the advertised two permissions remain open. The unchecked items below remain coverage gaps; a partial provider observation does not close a whole item.

  • Secret encoding (blocker). The derived key (cloudflare.DeriveS3Credentials: Access Key ID = the token's id, Secret Access Key = lowercase hex SHA-256 of its value) passes the storage check (probe, write, read, list, delete). Cloudflare's docs say only "SHA-256 hash". If the check fails there, try the other encodings (base64, raw bytes) in that one function; it is the only place to change.
  • Key activation delay. How long after the token is created the key is accepted. Setup makes up to r2VerifyAttempts checks, r2VerifyPause apart; tune them to what you see.
  • GET /accounts with only the two permissions. Whether it lists the account (else setup asks for the account ID, which is the fallback).
  • Public-access reads. Whether GET .../domains/managed and GET .../domains/custom work with only Workers R2 Storage Write (else setup says "couldn't check"; adjust its wording if a Read permission is needed), and that result.enabled and result.domains[] are the fields read, and that a bucket with no custom domains answers with an empty domains list and not without the field (setup treats a missing enabled or domains, like any success without a result, as unreadable, never as "off" or "none"). Turn r2.dev on for a scratch bucket and confirm the warning and the "What now?" menu (Enter revokes the key and returns to the storage question; "Check again" sees the dashboard change).
  • Token expiry. A token created without expires_on has no expiry in the dashboard.
  • Token revoke. DELETE /accounts/{account}/tokens/{id} with the bootstrap token revokes the key. Exercise the failure path (for example a scratch build with a wrong derivation): the key is revoked, and nothing is stored.
  • Delete-token 404. What DELETE /accounts/{account}/tokens/{id} returns for a token that is already gone or was never created (setup says "Cloudflare says that token doesn't exist" and tells the person to check the dashboard, since the meaning is unconfirmed), and that a second delete of the same ID behaves the same.
  • Prefix scoping unavailable. The runtime token reaches the whole bucket, and only it: it cannot read or list another bucket, create a bucket, or set a lifecycle rule. The docs describe bucket-level scope only; setup treats prefix scoping as unavailable.
  • Bucket name collision. The 2026-10-05 management REST run returned HTTP 409, code 10004. cloudflare.Error.AlreadyExists now accepts that response and the documented Workers/S3 code 10073, each only with 409. The provider rerun passed; confirm guided setup retry with a new name.
  • Jurisdictions. For each of eu, us, and fedramp (the ones setup offers): a bucket created with the jurisdiction, and its token resource string ..._<jurisdiction>_<bucket>, pass the storage check at <account>.<jurisdiction>.r2.cloudflarestorage.com, and the saved endpoint works after setup finishes. fedramp-high is documented only for the create header, so setup does not offer it; add it only once its resource string and endpoint are confirmed.
  • Non-administrator member. Token creation by a member who lacks a permission is refused with a 403 that the message covers.
  • Permission group listing. The lookup by name returns the bucket-item-write group with is_selectable, the paging parameter is accepted (or ignored harmlessly), and the name filter matches the exact name (setup also compares names itself, so a fuzzy filter is harmless, an over-strict one is not).
  • R2 not enabled. On an account where R2 is not enabled (or needs a payment method), what bucket creation returns. Setup maps a 403 to "needs Workers R2 Storage Write" and adds a hint to enable R2; confirm the status and message, and give that case its own text if it is not a 403.
  • Public-access response shape. GET .../domains/managed returns result.enabled (Cloudflare's reference page for it was unavailable when this was written; the shape comes from its summary).
  • Rate limits. A 429 carries Retry-After in whole seconds, as the client reads it.
  • Orphan token name. The name printed before creation is the name the dashboard shows for the token.
  • No leftovers. After a run, search the sandbox (data directory, hook files, LaunchAgent plist, setup-draft.json) for the bootstrap token; it appears nowhere. The automated search (TestGuidedR2NeverPersistsTheBootstrapToken) covers the fake only.

Terminal tests

What a real terminal does (echo, key mode, Ctrl-C, Ctrl-Z, a resize, a hangup) is tested under a pseudo-terminal: a Python script (python3, or the test skips) opens one, starts this test binary as a child in it, types, and checks the terminal's modes and the output. Run such a script with runPTYScript (internal/cli/pty_harness_test.go):

  • The script owns its deadlines (60 seconds overall, 30 for each step) and says what it was waiting for when one passes; match what it waits for to offsets in the output, never to sleeps.
  • runPTYScript is the backstop, 90 seconds and never later than 30 seconds before the test binary's own -timeout, so a stuck harness fails its test with a message instead of ending the package in a timeout panic. It stops the script with SIGTERM, which raises an exception in the script so its finally stops the child, and kills it only after ten seconds more. A script killed outright leaves its child running with nobody to stop it.
  • Budget for a slow start. On macOS, /usr/bin/python3 is Xcode's, and with the fresh HOME that TestMain gives each run it compiles its library into ~/Library/Caches first: a few seconds before the script's first line, more on a loaded machine.

Fuzzing

Redaction, parsing, hook-file editing and the hook itself have fuzz targets (go test -list Fuzz ./...). In internal/archive:

Target Input Properties
FuzzRedactSensitive any string redacting twice changes nothing; valid UTF-8 stays valid
FuzzRedactCredentialTemplates a secret in each credential shape the secret never survives
FuzzSanitizeValueIdempotent any string the whole string sanitizer (JSON inside strings, instruction blocks, redaction, the cap) is idempotent
FuzzFilterJSONL any JSONL, with each adapter (Claude Code, Codex, Cursor) no panic; only FilterErrors; retained records are JSON objects that refilter unchanged; the handoff renders with no control character; every token count in the metadata is from 0 to 2^53, and the per-model counts add up to the session's unless one saturated
FuzzFilterJSONLDropsSecrets a secret in typed input, credential-named arguments, and JSON strings, per adapter the secret never survives
FuzzSubagentMeta any .meta.json bytes beside a subagent transcript no failure; at most one subagent-meta record, first, holding only a bounded string of valid UTF-8; the transcript's own records unchanged; the output refilters unchanged
FuzzSubagentMetaDropsSecrets a secret in a description, among filler so the cap can fall in or beside it the secret never survives
FuzzCursorText any Cursor text transcript refiltering is a no-op; no hidden section is retained; the handoff finds no more prompts than the filter kept
FuzzCursorComposer a Cursor database chat and one message row no panic; retained records are JSON objects; the handoff renders cleanly
FuzzDecodeSource any byte stream, gzip or not no panic; the streaming and whole-bundle readers agree
FuzzLineMatchesCoverWholeString any text running each credential pattern line by line, only on lines with its needles, finds everything matching the whole string finds
FuzzGatedRedactionMatchesWhole any text the redaction as it runs (line by line, gated by needles and separators) equals the same redaction run ungated over the whole string
FuzzNormalizeRemoteURL any remote URL or other string no panic; repository keys have the documented shape, and normalized URLs have no edge slash, control character, or .git suffix
FuzzURLUserinfoMatchesReference any text up to 4096 bytes the linear URL userinfo scanner agrees with the reference implementation

In internal/hooks:

Target Input Properties
FuzzMergeRemove any hook file Merge accepts, per harness merging twice changes nothing; Remove takes out exactly what Merge added
FuzzCommandDataHome any data directory the hook command reads back the directory it was built with

In internal/scheduler/launchd:

Target Input Properties
FuzzLaunchAgentRoundTrip an executable, a data directory, a label, and one environment variable the three plist readers give back what LaunchAgent wrote (the program, the environment with AGENT_ARCHIVE_HOME, the data directory), up to XML's own rewriting of characters it cannot spell
FuzzLaunchAgentReaders any bytes the readers never panic, and the data directory is what the environment says

In internal/scheduler/systemd:

Target Input Properties
FuzzRenderServiceRoundTrip an executable, a data directory, and one environment variable the unit reader gives back exactly what renderService wrote (the program, the environment with AGENT_ARCHIVE_HOME), whatever %, $, quotes, backslashes and spaces the values hold, and every line of the unit is a setting the renderer writes, so a value cannot inject one
FuzzReadService any bytes the reader never panics, and a unit it accepts has a program and an environment

In internal/cli:

Target Input Properties
FuzzHookPayload an app name and up to eight hook payloads, run in turn against a fresh data directory set up for all three apps every run exits 0 without a panic, and nothing outside the data directory (the project folder, HOME) changes

In internal/termlaunch:

Target Input Properties
FuzzShellQuote any shell argument without NUL /bin/sh reads the quoted argument back unchanged

Their seeds come from the fixtures in testdata/ and from testdata/fuzz/<target>/, and plain go test runs them on every pull request. The fuzz job in Extended CI mutates every discovered target (at least the 24 currently known) for five seconds daily and 30 seconds weekly, on candidates or on demand. Full campaigns have a 45-minute job limit around the tier runner's 40-minute deadline, leaving room for setup and artifact upload; daily jobs retain their 30-minute limit. For a change to redaction or parsing, run the affected targets for a couple of minutes each, with fast minimization so a failure is reported promptly:

go test ./internal/archive -run '^$' -fuzz '^FuzzFilterJSONL$' -fuzztime 2m -fuzzminimizetime 2s

A failing input is written to testdata/fuzz/<target>/; keep it there as a seed once it is fixed.

Published writer refusal

bash scripts/test_published_writer.sh runs an opt-in native macOS acceptance check against the checksum-pinned public v0.1.1 Darwin binary. It uses disposable HOME and data roots, stripped environment, and scheduler/Keychain stubs. A legacy scalar config is the successful control; protected config must fail the old integer decoder and remain byte-identical. Extended macOS runs this check.

Non-live machine pairing regression coverage

Run combined source, recipient and third-operator fake acceptance together with scope, delivery, token-source and progress regressions:

go test -race ./internal/cli -run 'TestMachine(TwoHome|Remote)FakeAcceptance|TestPairingStandalone|TestPairingClipboardUnavailable|TestManagementTokenFailure|TestCommittedPairingHousekeeping|TestRetired|TestDirectDiscovery|TestRevocationProgressUses|TestPairingMissingApp' -count=1

These use temporary homes, private synthetic operator bindings, memory object and credential stores, and a loopback fake Cloudflare provider. Source issuer labels, rename-safe third-machine IDs, re-pairing history, unused versus delivered spares, issuer compromise and per-key partial deletion/retry are combined command flows. The existing issuance/revocation suites additionally exercise lock contention, interrupted reservations, uncertain delivery and cancelled execution budgets; bounded discovery/listing suites cover partial reads, shared deadlines, caps and worker limits. Fake results do not establish live token permissions, account inventory visibility, absence semantics, propagation or macOS/Linux timings. First-run pairing and guided creation are generally available by maintainer approval. Record separate live and platform acceptance results for the final release candidate; fake tests do not establish that evidence.