diff --git a/.agents/agents/contract-reviewer.md b/.agents/agents/contract-reviewer.md new file mode 100644 index 000000000..fc0a4fd35 --- /dev/null +++ b/.agents/agents/contract-reviewer.md @@ -0,0 +1,6 @@ +--- +name: contract-reviewer +description: "Review an OCAP2 Web recording, authorization, HTTP, or playback contract independently." +--- + +Read the [repository guide](../../AGENTS.md) and [handoff instructions](../../docs/agent-workflows.md). Use the contract review skill on the specified diff. Follow the registered gate or writer through the UI, persisted artifact, or external consumer. Return severity, file and line, triggering input, concrete consequence, and remaining checks. Work read-only. Keep the assignment local and return it to the coordinator. diff --git a/.agents/agents/explorer.md b/.agents/agents/explorer.md new file mode 100644 index 000000000..f14f34108 --- /dev/null +++ b/.agents/agents/explorer.md @@ -0,0 +1,6 @@ +--- +name: explorer +description: "Trace one OCAP2 Web workflow and its source, history, consumers, and recovery evidence." +--- + +Read the [repository guide](../../AGENTS.md) and [handoff instructions](../../docs/agent-workflows.md). Trace the entry point, state and side effects to each affected consumer. Use the context recovery skill. Return the first relevant decision, current behavior, checks and any missing evidence with file and line references. Work read-only. Keep the assignment local and return it to the coordinator. diff --git a/.agents/agents/recovery-reviewer.md b/.agents/agents/recovery-reviewer.md new file mode 100644 index 000000000..d2d831d96 --- /dev/null +++ b/.agents/agents/recovery-reviewer.md @@ -0,0 +1,6 @@ +--- +name: recovery-reviewer +description: "Review OCAP2 Web retry, cancellation, concurrency, and restart behavior independently." +--- + +Read the [repository guide](../../AGENTS.md) and [handoff instructions](../../docs/agent-workflows.md). Trace ownership across handlers, queues, workers, database updates, and filesystem effects. Review retries, duplicate messages, incomplete writes, ack timing, and cleanup. Return concrete sequences and observed or unverified outcomes with file and line references. Work read-only. Keep the assignment local and return it to the coordinator. diff --git a/.agents/agents/worker.md b/.agents/agents/worker.md new file mode 100644 index 000000000..b7d4861a7 --- /dev/null +++ b/.agents/agents/worker.md @@ -0,0 +1,6 @@ +--- +name: worker +description: "Implement one scoped OCAP2 Web change in explicitly assigned files." +--- + +Read the [repository guide](../../AGENTS.md) and [handoff instructions](../../docs/agent-workflows.md). Edit only the files listed in the brief and preserve local changes. Run the assigned synthetic checks and return changed files, results, and integration needs. Report any edit needed outside your scope. Keep the assignment local and return it to the coordinator. diff --git a/.agents/skills/ocap-context-recovery/SKILL.md b/.agents/skills/ocap-context-recovery/SKILL.md new file mode 100644 index 000000000..861f7a71c --- /dev/null +++ b/.agents/skills/ocap-context-recovery/SKILL.md @@ -0,0 +1,14 @@ +--- +name: ocap-context-recovery +description: "Recover the reason for an OCAP2 Web compatibility rule, state transition, or operational guard from Git history, callers, contracts, and tests." +--- + +# ocap-context-recovery + +Read the [maintainer guide](../../../docs/maintainer-context.md) and the relevant workflow in [workflow evidence](../../../docs/context-evidence.md). Pin the checkout and identify the triggering input, output, and durable side effects. + +Search the integration history and the owning file with `git log --first-parent`, `--follow`, and `-S` or `-G` on the symbol or error. Read patches and relevant parents. Check the producer and all affected consumers, including existing SQLite rows, files on disk, or UI decoders as applicable. Look for when the rule entered, when it changed, and which version applies today. + +Use [Go source navigation](../../../docs/agent-workflows.md#go-source-navigation) to confirm Go callers when a symbol crosses packages or an interface. + +Return the historical reason, current observed behavior, consumers, check, and any inference. Keep new rationale with the owning code, contract, or runbook. Add an open evidence item with an owner and next action if the history or an acceptance check is missing. diff --git a/.agents/skills/ocap-contract-review/SKILL.md b/.agents/skills/ocap-contract-review/SKILL.md new file mode 100644 index 000000000..7cc2b45ed --- /dev/null +++ b/.agents/skills/ocap-contract-review/SKILL.md @@ -0,0 +1,14 @@ +--- +name: ocap-contract-review +description: "Review OCAP2 Web HTTP authorization, WebSocket ingestion, recording schemas, and playback or map consumers when a contract or failure path changes." +--- + +# ocap-contract-review + +Read the [review questions](../../../docs/maintainer-context.md#before-editing) and the affected [workflow evidence](../../../docs/context-evidence.md). Inspect the actual route or producer and the consuming UI, extension, or operator path. + +- For credentials, check the registered route, mode, prefix, role, and unauthorized result. Producer credentials, viewer JWTs, admin JWTs, and map event tokens have different entry points. +- For recordings, follow manifest and chunk formats, frame bounds, field presence, and the status and files visible to readers. When changing stream ownership or retries, trace old and replacement sessions through save, discard, cancellation, and restart. +- For maps, check job state and the tile/style paths against their consumers. If one operation succeeds and another fails, follow both projections into the UI and persisted state. + +Report concrete findings with the input, writer and reader locations, outcome, and the test that does or should exercise it. Mark actual provider or deployment verification separately. Use the [testkit](../../../docs/testkit.md) for applicable local cases. diff --git a/.agents/skills/ocap-local-verification/SKILL.md b/.agents/skills/ocap-local-verification/SKILL.md new file mode 100644 index 000000000..aa95c7ebc --- /dev/null +++ b/.agents/skills/ocap-local-verification/SKILL.md @@ -0,0 +1,15 @@ +--- +name: ocap-local-verification +description: "Select and run OCAP2 Web Go, SolidJS, schema, and agent-workflow checks for a local change, with CI and platform coverage in view." +--- + +# ocap-local-verification + +Start with the [contributor setup](../../../CONTRIBUTING.md), [CI workflows](../../../.github/workflows), and the [testkit cases](../../../docs/testkit.md#cases). + +- Test the affected Go package with a named case or `go test ./internal/ -run '^TestName$' -count=1`. For shared changes, run `go test ./...`. SQLite needs CGO and a working C compiler. Real map tool integration requires its native tools. +- For changes to stream ownership, timers, or goroutines, use the [stream race check](../../../docs/testkit.md#race-detector). Use the [Go concurrency testing guidance](../../../CONTRIBUTING.md#running-tests) to choose a fake clock or an integration harness. +- For UI changes, run `npm --prefix ui test` or pass selected files after `--`. From `ui/`, run `npx tsc --noEmit`, `npx eslint src/`, and `npm run build` as applicable. Build before checking the embedded SPA. +- For schema edits, regenerate bindings using the [contributor guide](../../../CONTRIBUTING.md#protobuf-schema-changes) and run `playback-delivery`. For agent guidance, run `go test ./internal/agentdocs` and `git diff --check`. + +Record exact commands, results, and skips. Use the [runbook](../../../docs/operational-verification.md) for checks that need a real browser, native tools, or deployed provider. diff --git a/.agents/skills/ocap-testkit/SKILL.md b/.agents/skills/ocap-testkit/SKILL.md new file mode 100644 index 000000000..76e04eea7 --- /dev/null +++ b/.agents/skills/ocap-testkit/SKILL.md @@ -0,0 +1,14 @@ +--- +name: ocap-testkit +description: "Run and maintain the OCAP2 Web testkit for isolated route, migration, stream, conversion, playback, map, and startup cases." +--- + +# ocap-testkit + +Read the [testkit runbook](../../../docs/testkit.md). List with `go run ./cmd/ocap-testkit list`. Run one or several cases with `go run ./cmd/ocap-testkit run ...`, or omit the names for the full catalog. Check the report and logs emitted by the command. + +For a stream concurrency change, run `go run ./cmd/ocap-testkit run -race stream-recovery` on a [supported toolchain](../../../docs/testkit.md#race-detector). + +Reuse a focused Go or Vitest check before adding a fixture. Use temporary files, synthetic recording bytes, or a fake provider on loopback. Keep a case independent of deployed services, real recordings, user settings, and credentials. Pin test selectors and bump the fixture version when changing case inputs or expected behavior. + +For a regression proof, make the smallest change that violates the contract in a disposable clone. Run the same case and inspect its failing assertion and downstream state. Retain the local report and record the mutation outside the tracked case catalog. diff --git a/.claude b/.claude new file mode 120000 index 000000000..c0ca46856 --- /dev/null +++ b/.claude @@ -0,0 +1 @@ +.agents \ No newline at end of file diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 93f741ef3..c93137e47 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -6,6 +6,10 @@ +## Contract and recovery + + + ## Checklist - [ ] `go test ./...` passes diff --git a/.gitignore b/.gitignore index fc746ac48..6773bbba4 100644 --- a/.gitignore +++ b/.gitignore @@ -3,7 +3,7 @@ .vscode # Local development -.claude/settings.local.json +/.agents/settings.local.json # Build artifacts /ocap-webserver @@ -29,6 +29,7 @@ cover.out coverage.out coverage.html ui/coverage/ +/testkit/runs/ # Frontend node_modules/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 000000000..da7c92415 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,22 @@ +# OCAP2 Web agent guide + +Start with [Contributing](CONTRIBUTING.md). Use [Maintainer context](docs/maintainer-context.md) to trace a contract, failure path, or guard and [Comment hygiene](docs/comment-hygiene.md) for comment changes. + +- Verify [HTTP authorization](internal/server/handler.go) through the registered mux under a non-root prefix. Viewer, admin, and producer routes use different credentials. Use the [streaming contract](docs/streaming-architecture.md) for ingestion, recording formats, and playback. Follow the [schema generation instructions](CONTRIBUTING.md#protobuf-schema-changes) for protobuf changes. +- Keep the UI's SolidJS, CSS module, and i18n conventions. Use the [operational runbook](docs/operational-verification.md) for startup, native map tooling, and Arsenal imports. +- Inspect the working tree before editing. Preserve local changes and use synthetic recordings, paths, identities, secrets, and provider responses for local checks. The [testkit](docs/testkit.md) is available without an application startup. +- Match [CI](.github/workflows) for Go tests and UI typecheck, lint, tests, and build when those surfaces change. Build the SPA before packaging the embedded binary. Keep tests close to the code they exercise. +- Always aim for 100% coverage in every test suite. Preserve existing coverage, test normal and failure paths deterministically, and check the coverage report for affected code. [Coverage commands](CONTRIBUTING.md#running-tests) + +## Agent workflows + +Use [roles and handoffs](docs/agent-workflows.md) for independent exploration, a disjoint implementation assignment, or a fresh review of a consequential change. The coordinator owns integration and final verification. + +Use [Go source navigation](docs/agent-workflows.md#go-source-navigation) for symbol-level caller evidence. + +| Skill | Use when | +| --- | --- | +| [ocap-context-recovery](.agents/skills/ocap-context-recovery/SKILL.md) | Recover why a constraint exists and how to verify it | +| [ocap-contract-review](.agents/skills/ocap-contract-review/SKILL.md) | Review a producer, consumer, or recovery boundary | +| [ocap-local-verification](.agents/skills/ocap-local-verification/SKILL.md) | Select and run checks for a change | +| [ocap-testkit](.agents/skills/ocap-testkit/SKILL.md) | Run or maintain the named local cases | diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 2cb86a587..000000000 --- a/CLAUDE.md +++ /dev/null @@ -1,107 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Project Overview - -OCAP2-Web is a Go-based web server for the Operation Capture And Playback system. It archives and replays Arma 3 military simulation missions, rendering unit positions, movements, and combat events on interactive Leaflet maps. - -## Build Commands - -```bash -# Build (Linux) -go build -o ocap-webserver ./cmd/ocap-webserver - -# Build (Windows) -go build -o ocap-webserver.exe ./cmd/ocap-webserver - -# Run tests -go test ./... - -# Run single test -go test -run TestName ./internal/server - -# Regenerate protobuf schemas -go generate ./pkg/schemas/... - -# Docker build -docker build -t ocap-webserver . -``` - -## Architecture - -### Backend (Go) - -Entry point: `cmd/ocap-webserver/main.go` initializes repositories and starts the Echo server. - -**Core packages in `internal/`:** -- `server/` - HTTP endpoints, repositories (operation, marker, ammo), configuration -- `storage/` - Storage engines (JSON, Protobuf) -- `conversion/` - Background format conversion worker - -**Public packages in `pkg/schemas/`:** -- `protobuf/` - Protocol Buffers schema (`ocap.proto`) and generated Go code - -Each schema package has a `generate.go` with `//go:generate` directives. Run `go generate ./pkg/schemas/...` after modifying `.proto` files. - -**API Endpoints (all under configurable `prefixURL`, default `/`):** -- `GET /api/healthcheck` - Health check (used by Docker HEALTHCHECK) -- `GET /api/v1/operations` - Query missions with filters -- `POST /api/v1/operations/add` - Upload mission (requires `secret`) -- `GET /api/v1/customize` - UI customization settings -- `GET /api/version` - Build info -- `GET /data/:name` - Stream mission data (gzipped JSON) -- `GET /file/:name` - Download mission as attachment -- `GET /images/markers/:name/:color` - Generate colored marker -- `GET /images/markers/magicons/:name` - Equipment icons -- `GET /images/maps/*` - Map tiles - -### Frontend (JavaScript) - -Static SPA in `static/` using Leaflet for map rendering. No build step required. - -**Key files in `static/scripts/`:** -- `ocap.js` - Main app, map init, playback engine -- `ocap.ui.js` - UI panels (unit list, events, timeline) -- `ocap.event.js` - Mission event handling -- `ocap.marker.js` - Unit/vehicle marker rendering -- `ocap.entity.js` - Base entity class -- `localizable.js` - i18n support - -### Data Storage - -- **SQLite database** - Mission metadata (default `data.db`, configure via `OCAP_DB`) -- **Mission files** - Gzipped JSON (default `data/`, configure via `OCAP_DATA`) -- **Map tiles** - Downloaded separately (default `maps/`, configure via `OCAP_MAPS`) -- **Assets** - `assets/markers/` and `assets/ammo/` contain mod-specific icons - -## Configuration - -Settings loaded via Viper with priority: environment variables → config files → defaults. - -**Config file:** `setting.json` -```json -{ - "listen": "127.0.0.1:5000", - "prefixURL": "/", - "secret": "same-secret", - "logger": true -} -``` - -**Environment variables** (prefix `OCAP_`): -- `OCAP_LISTEN`, `OCAP_SECRET`, `OCAP_PREFIXURL` -- `OCAP_DB`, `OCAP_DATA`, `OCAP_MAPS`, `OCAP_MARKERS`, `OCAP_AMMO`, `OCAP_STATIC`, `OCAP_TMP` -- `OCAP_TMP` redirects scratch space for map uploads/processing (and the gdal/tippecanoe subprocesses) by setting `TMPDIR`/`CPL_TMPDIR`. Unset = system temp. Set it to a path with space when `/tmp` is too small (e.g. Pelican). -- `OCAP_CUSTOMIZE_WEBSITEURL`, `OCAP_CUSTOMIZE_WEBSITELOGO` - -## Pelican Panel - -A Pelican egg (`egg-ocap2-web.json`) is provided for deploying in [Pelican Panel](https://pelican.dev/). The Docker image includes a dual-mode entrypoint (`docker/entrypoint.sh`) that detects Pelican/Wings via the `STARTUP` env var and processes variable substitution, falling back to direct execution for standalone Docker. - -## Key Implementation Details - -- Path traversal protection via `paramPath()` using `filepath.Clean()` validation -- Marker colors: predefined names (blufor, opfor, ind, civ, dead, hit) or hex codes -- Cache control: 7 days for assets, no-cache for HTML -- Build metadata injected via ldflags: `BuildCommit`, `BuildDate` diff --git a/CLAUDE.md b/CLAUDE.md new file mode 120000 index 000000000..47dc3e3d8 --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1 @@ +AGENTS.md \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 30a46ee87..ad8510922 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,10 +1,14 @@ # Contributing +- [Maintainer context](docs/maintainer-context.md) maps contracts, failure recovery, and review evidence. +- [Comment hygiene](docs/comment-hygiene.md) covers keeping rationale and directives where maintainers need them. +- [Agent workflows](docs/agent-workflows.md) and the [local testkit](docs/testkit.md) document scoped handoffs and reproducible checks. + ## Prerequisites | Tool | Version | Notes | |------|---------|-------| -| [Go](https://golang.org/dl/) | 1.26+ | Backend | +| [Go](https://golang.org/dl/) | See [go.mod](go.mod) | Backend, with a C compiler for SQLite | | [Node.js](https://nodejs.org/) | 24+ | Frontend build | | [protoc](https://grpc.io/docs/protoc-installation/) | 3+ | Only if editing `.proto` files | @@ -52,12 +56,14 @@ The frontend is embedded into the binary via `//go:embed`, so you only need to r ``` cmd/ ocap-webserver/ # Server entry point and CLI commands + ocap-testkit/ # Local testkit entry point internal/ server/ # HTTP handlers, repositories, configuration frontend/ # Embedded SPA (go:embed) conversion/ # Background format conversion worker storage/ # Storage engines (JSON, Protobuf) maptool/ # Map tile pipeline + testkit/ # Local testkit runner and case catalog pkg/schemas/ protobuf/ # Protobuf schema and generated code ui/ # SolidJS + Vite + TypeScript frontend source @@ -75,6 +81,17 @@ cd ui npm test ``` +Aim for 100% coverage in every test suite. Check the coverage report for the affected code and add deterministic tests for missing behavior, including errors. Report any remaining gaps when submitting the change. + +```bash +# From the repository root +go test -coverprofile=cover.out -coverpkg=./cmd/...,./internal/... ./... +go tool cover -func=cover.out +npm --prefix ui run test:coverage +``` + +Use [Go's `testing/synctest`](https://pkg.go.dev/testing/synctest) for timer and goroutine tests that stay in process. Wait for a competing goroutine to block with `synctest.Wait()` before checking an intermediate state. Keep real WebSocket and SQLite integration checks on the existing harnesses. Use the [testkit race option](docs/testkit.md#race-detector) when reviewing streaming or other concurrent Go changes. + ## Making Changes 1. Create a branch from `main` @@ -90,18 +107,15 @@ npm test ## Protobuf Schema Changes -If you modify `pkg/schemas/protobuf/v1/ocap.proto`: +The schemas in [pkg/schemas](pkg/schemas) are the source. Regenerate Go with `protoc` and `protoc-gen-go` on PATH: ```bash go generate ./pkg/schemas/... ``` -This regenerates the Go code. The frontend uses `ts-proto` — regenerate TypeScript types with: +Regenerate the affected TypeScript binding with the `ts-proto` version in its header. The decoders import [v1](ui/src/data/decoders/generated/ocap.pb.ts) or [v2](ui/src/data/decoders/generated/v2/ocap_v2.ts). Preserve the decoder-facing shapes and verify the generated diff and `playback-delivery` case. See the [open generation evidence](docs/context-evidence.md#open-evidence) for recovering the exact TypeScript options. -```bash -cd ui -npx protoc --ts_proto_out=./src/generated --ts_proto_opt=esModuleInterop=true ../pkg/schemas/protobuf/v1/ocap.proto -``` +Preserve field numbers, wire types, defaults, and field presence for stored recordings. Check the affected recording versions and every writer and decoder using the changed field. ## Docker Build diff --git a/cmd/ocap-testkit/main.go b/cmd/ocap-testkit/main.go new file mode 100644 index 000000000..6075085f1 --- /dev/null +++ b/cmd/ocap-testkit/main.go @@ -0,0 +1,17 @@ +package main + +import ( + "fmt" + "os" + + "github.com/OCAP2/web/internal/testkit" +) + +var osExit = os.Exit + +func main() { + if err := testkit.Run(os.Args[1:], os.Stdout, os.Stderr); err != nil { + fmt.Fprintln(os.Stderr, err) + osExit(1) + } +} diff --git a/cmd/ocap-testkit/main_test.go b/cmd/ocap-testkit/main_test.go new file mode 100644 index 000000000..3e1c6cef9 --- /dev/null +++ b/cmd/ocap-testkit/main_test.go @@ -0,0 +1,23 @@ +package main + +import ( + "os" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestMainPassesArgumentsAndReportsFailure(t *testing.T) { + args, exit := os.Args, osExit + t.Cleanup(func() { os.Args, osExit = args, exit }) + var codes []int + osExit = func(code int) { codes = append(codes, code) } + + os.Args = []string{"ocap-testkit", "list"} + main() + require.Empty(t, codes) + + os.Args = []string{"ocap-testkit", "unexpected"} + main() + require.Equal(t, []int{1}, codes) +} diff --git a/docs/agent-workflows.md b/docs/agent-workflows.md new file mode 100644 index 000000000..1788cd0b5 --- /dev/null +++ b/docs/agent-workflows.md @@ -0,0 +1,28 @@ +# Agent roles and handoffs + +Delegate when separate context or independent work improves the result. Use one role for each bounded question. Load the project role when available or give the child those instructions in its brief. + +| Role | Use for | Edit scope | Return | +| --- | --- | --- | --- | +| [`explorer`](../.agents/agents/explorer.md) | Trace a recording, stream, map, or release path | Read-only | Entry point, consumers, durable effects, source and history evidence, missing checks | +| [`worker`](../.agents/agents/worker.md) | Implement an agreed change | Files named in the assignment | Changed files, checks and outcomes, remaining integration | +| [`contract-reviewer`](../.agents/agents/contract-reviewer.md) | Review authentication, HTTP/wire shape, persisted formats, or UI consumers | Read-only | Findings with severity, file and line, triggering input, affected consumer and consequence | +| [`recovery-reviewer`](../.agents/agents/recovery-reviewer.md) | Review a retry, cancellation, concurrent writer, restart, or partial failure | Read-only | Failure sequence, ownership and durable outcome, source evidence and verification gap | + +Give the child the role and goal, repository and pinned revision, exact files or diff including untracked files, relevant rules, preserved constraints, authorized checks, and a stopping point. For review, provide the contract and inputs so the reviewer can trace the behavior independently. + +Assign workers disjoint files. Keep shared schemas, routes used by several workstreams, dependency files, and final wiring with the coordinator unless the whole boundary has one explicitly assigned owner. Resolve overlap with the coordinator before editing. Use local synthetic inputs and define writes narrowly. Subagents hand findings back to the coordinator, who checks them against source, integrates edits, runs the final checks, and reports remaining evidence. + +## Go source navigation + +Use `rg` to find the entry point, then use `go list` for package and build context and `go doc` for the API contract. When gopls is available, run `gopls definition file.go:line:column` and `gopls references -d file.go:line:column` at the identifier to trace Go callers. Use `gopls check file.go` for diagnostics before running the affected tests. Match the target build tags and CGO settings. For a route or a recording format, trace the web client and other producers separately because they cross the Go package boundary. [Go command](https://pkg.go.dev/cmd/go) · [gopls navigation](https://go.dev/gopls/features/navigation) · [gopls diagnostics](https://go.dev/gopls/features/diagnostics) + +An assistant with gopls MCP already configured can use the same Go workspace, navigation, and diagnostics tools. The optional `gopls mcp` command uses a headless session with saved files. An attached IDE session can also see unsaved buffers. [gopls MCP](https://go.dev/gopls/features/mcp) + +## Discovery and validation + +Use the root [AGENTS.md](../AGENTS.md) for shared guidance and [`.agents/`](../.agents) for skills and role briefs. Codex reads the root instructions and discovers the skills. When delegating in Codex, include the selected role in the brief. Antigravity discovers the roles in `.agents/agents/`. + +Claude Code uses two relative Git symlinks. `CLAUDE.md` resolves to `AGENTS.md`, and `.claude` resolves to `.agents`. On Windows, use a checkout with Git's `core.symlinks=true` and permission to create symbolic links. If a checkout materialized the links as text files, enable symlinks and restore those two paths from the index. + +Run `go test ./internal/agentdocs` and `git diff --check` when editing project guidance, roles, or skills. diff --git a/docs/comment-hygiene.md b/docs/comment-hygiene.md new file mode 100644 index 000000000..1707b995b --- /dev/null +++ b/docs/comment-hygiene.md @@ -0,0 +1,15 @@ +# Comment hygiene + +Keep the reason a future edit could miss. Preserve compiler and build directives such as `//go:embed`, `//go:generate`, and `//go:build`, generated-file notices, lint directives, public help and examples, and API or schema semantics. Check who consumes the text before editing it. When a workaround is temporary, name the compatibility condition that allows removal. + +- In Go, explain why the migration must finish reading candidate rows before touching disk or recording the schema version. The loop and `rows.Err()` already show how it works. See [operation.go](../internal/server/operation.go). +- In TypeScript, explain why a loader must distinguish an absent field from an explicit zero or false value. Assignments and types already show which fields are copied. Keep durable format rules in the [schema](../pkg/schemas) or [streaming contract](streaming-architecture.md). +- In workflow or shell files, retain dependencies such as job names used by downstream workflow triggers. Put operator recovery steps in the [runbook](operational-verification.md) and link to them where someone will need them. + +## On-demand audits + +Pin the revision and paths. Inventory Go comments with `go/parser` and `parser.ParseComments` and TypeScript comments and JSDoc with the TypeScript scanner/parser. Use a parser with comment support for configuration when available and record manual scope and limits otherwise. Keep generated code out of editorial cleanup unless its source also needs revision. + +For comment-only Go edits, compare parsed syntax or formatted ASTs with comments omitted. Check directives and other text consumers separately. Compare physical comment lines, documentation-comment lines, and total lines before and after within the same scope and counting rules. Record retained context, relevant tests or builds, generated/help output checks where applicable, and any open verification. Judge the edit by whether maintainers can still recover the intent and whether verification passes. + +See [Maintainer context](maintainer-context.md) for where decisions and open evidence belong. diff --git a/docs/context-evidence.md b/docs/context-evidence.md new file mode 100644 index 000000000..613ffa77c --- /dev/null +++ b/docs/context-evidence.md @@ -0,0 +1,42 @@ +# Workflow evidence + +Repository-wide audit at `dd840a704a5e2d8441a2e9a6817b399ba6564200` on `main`, with a clean Git working tree on 2026-11-29. The non-shallow clone contained the integration branch, local feature branches, remote-tracking refs and tags. Git described the baseline as `v2.1.1-187-gdd840a70`. The evidence applies to this source revision. Release and deployment acceptance appear under [open evidence](#open-evidence). + +The first trace was filename migration. An independent reader starting at [Contributing](../CONTRIBUTING.md) found the reason and checks in about two minutes by searching code and Git. The guide provided the broad test command and no direct route to the migration. After that trace, the audit examined the major workflows below and sampled the renderer, auxiliary CLI, and platform variants at their shared boundaries. + +## Constraints reviewed + +| Workflow and consumers | Historical reason and current constraint | Usable local check | +| --- | --- | --- | +| **1. SQLite filename migration and legacy upload.** The [startup path](../cmd/ocap-webserver/main.go) opens the [repository](../internal/server/operation.go). Upload and the [UI client](../ui/src/data/apiClient.ts) use the resulting recording names. | `e5098354` repaired persisted escaped names to align metadata, files and producer names. `e0e936e2` removed the scan guard and `336ccb40` restored it. Complete the scan before SQL writes and filesystem renames. Preserve literal plus signs and collision handling. `8852995b` added filename uniqueness so repeated uploads replace the recording consistently. | `filename-migration` and `legacy-upload`. | +| **2. Viewer and admin access, including recordings, mutations and producer auth.** [Route registration](../internal/server/handler.go), [auth middleware](../internal/server/handler_auth.go), and [UI API client](../ui/src/data/apiClient.ts). | `cff715bd` introduced admin and viewer roles. `1917fcac` restricted browser upload to administrators and retained the shared secret for producer uploads. `0c890c28` applied viewer access to both recording metadata and files, including playback bytes. Gated routes must preserve their own credential and role requirements under a configured prefix. | `route-access`. | +| **3. Steam identity and optional profile lookup.** The [callback](../internal/server/handler_auth.go) hands role and optional profile claims to the [UI auth flow](../ui/src/hooks/useAuth.tsx). | `264fbf80` moved human sign-in to OpenID and accounted for forwarded host in proxy deployments. `0c890c28` added viewer allowlist checks. A verified identity must pass the configured access check, with the admin bypass. Profile lookup failure leaves a valid sign-in usable. | `steam-boundary`. Live proxy and provider checks remain open. | +| **4. Stream ingest, reconnect, replay and discard.** Producer messages drive the [handler](../internal/server/handler_stream.go), [registry](../internal/server/stream_registry.go), [ingestion](../internal/ingestion), SQLite status and playback artifacts. | `b07d9a84` introduced live ingestion and a partial record on disconnect. `bc123d5a` added producer-scoped resume and segment replacement after a full resend. `e5a1bbe2` added discard and lost-ACK recovery. Repeated starts share a session. A complete replay may replace partial segments. Incomplete replays preserve them. End and discard ACKs reflect durable outcomes. See the [wire and recovery contract](streaming-architecture.md#recording-ingestion). | `stream-recovery`. Producer acceptance remains open. | +| **5. Conversion lifecycle and admin retry.** [Worker](../internal/conversion/worker.go), [admin retry](../internal/server/handler_admin.go), [convert CLI](../internal/convertcli/convert.go), and UI status. | `900027a5` introduced startup reset for interrupted conversion. `329510fb` reserved streaming status for live ingestion and `bc123d5a` separated stream recovery. Clean and retry interrupted conversion output while preserving stream-owned state. Admin retry targets failed rows and rejects a native v2 manifest because legacy conversion would overwrite it. | `conversion-recovery`. See [conversion flow](streaming-architecture.md#conversion-flow). | +| **6. Recording delivery and playback compatibility.** [Storage](../internal/storage), [schemas](../pkg/schemas), [asset serving](../internal/server/encoding.go), and [UI decoders](../ui/src/data/decoders). | `109f1a44` clarified inclusive v1 frame end to fix off-by-one playback. `b07d9a84` added streamed v2 and preserved v1 playback. `dcc1c805` moved richer player snapshots into optional sidecars and added negotiated compression. Preserve format-specific bounds, presence and sidecar fallback. The raw artifact is authoritative when a sidecar is missing, stale, or unacceptable to the client. | `playback-delivery`. See [playback flow](streaming-architecture.md#playback-flow) and [compression](../README.md#compression). | +| **7. Map import, job state, and asset fallback.** [Import handler](../internal/server/handler_maptool.go), [job manager](../internal/maptool/jobmanager.go), [scanner](../internal/maptool/scanner.go), [event subscriber](../ui/src/pages/map-manager/useMapToolEvents.ts) and [map config client](../ui/src/data/apiClient.ts). | `0fd6d24b` integrated web jobs, scoped upload cleanup and SSE. `793e9b16` persisted pipeline errors to surface incomplete imports after restart. `c10bbab6` sourced world identity from validated metadata so output and playback lookup match. `bf20eae1` changed world metadata cache behavior to keep imported maps visible. Local map data takes precedence before external PMTiles and raster sources. | `map-boundary`. See [map recovery](operational-verification.md#map-import-and-recovery). | +| **8. Startup, embedded SPA, deployment and packaging.** [Executable](../cmd/ocap-webserver/main.go), [embed](../internal/frontend/embed.go), [image](../Dockerfile), [entrypoint](../docker/entrypoint.sh), and [release workflow](../.github/workflows/build.yml). | `f4a4ef8d` embedded the SolidJS build for a self-contained browser experience. `2affa14a` used the panel-assigned port when its configured value did not interpolate. `67313a97` supplied full-image GDAL plugins, and `58a39f9b` introduced configurable HTTP timeouts. Keep the built SPA and runtime tools consistent with what the artifact promises. | `startup` and local UI and Go builds. See [startup and release](operational-verification.md#startup-and-release). | + +History used first-parent integration, owning-file history, blame, and patch searches on `migrateDecodeFilenames`, `rows.Err`, `cleanupInterrupted`, stream resume/discard, and the Vite embed, tool and provider boundaries. For the migration pilot, `git show e5098354 -- internal/server/operation.go`, `git show e0e936e2 -- internal/server/operation.go`, and `git show 336ccb40 -- internal/server/operation.go internal/server/operation_test.go` expose the introduction, regression, and fix. The history for the remaining constraints is identified in the table. The maintained environment and recovery guidance sits with the linked contracts and runbook. + +## Verification + +The four review questions identified the lost scan guard in `e0e936e2`. The SQL transaction began after a potentially incomplete scan, so normal migration tests could pass while a filesystem rename and a version write still occurred on this failure path. The adjacent transaction test seam in that patch delegates to the same `db.Begin()` operation in production. Review of the seam with the original guard in place found no change to the failure path. + +In a disposable checkout of the fix's parent `077edca5`, the regression test from `336ccb40` observed no error, a rename, and schema version 11 instead of 10. The current case passed. Removing only the scan guard in a disposable copy of the current code reproduced the same assertion failures. + +The migration comment edit added two physical comment lines to `operation.go` (91 to 93) and two total lines (922 to 924). Attached documentation stayed at 84 lines. Go parsed syntax matched with comments and positions omitted, and compiler directives matched. + +An independent reader followed [Contributing](../CONTRIBUTING.md) through both guides to the migration rationale, affected consumers, and exact test in about two minutes. They also verified that the new registered route fixture exercises its stated contract. The timing is approximate and unchanged from the first walkthrough. The current path adds direct links to the evidence and a named case. Eight high-impact workflow constraints have a current rationale and a usable local check. Renderer visuals, platform-specific packaging, provider acceptance, and upstream producer behavior are sampled or pending as described below. + +## Open evidence + +| Evidence needed | Owner | Next action | +| --- | --- | --- | +| Filesystem/SQLite reconciliation when a filename migration stops after a rename, or collides with a file on disk. SQL rollback and filesystem rename have different durability. | Storage maintainer | Reproduce interrupted multi-file repair with a copied legacy database and data tree. Decide and document how operators reconcile the result before changing retry semantics. | +| Native OpenID and forwarded scheme/host/prefix under a deployed proxy. The local verifier and profile response are simulated. | Auth maintainer | Run the [reverse-proxy smoke](operational-verification.md#startup-and-release) in a disposable deployment with a test identity. | +| Actual producer reconnect, resend and discard behavior across WebSocket and server restart. | Ingestion maintainer | Run the scenarios in [stream verification](streaming-architecture.md#verification) with a supported producer version and synthetic recording. | +| Full Linux map pipeline, retained job state and rendered map output. The local core-stage and restyling integration checks passed. Full pipeline and job-manager integration checks skipped for missing PMTiles and tippecanoe. | Map maintainer | Run the [full-image import and recovery smoke](operational-verification.md#map-import-and-recovery) with the packaged tools. | +| Exact TypeScript protobuf generation options. The committed headers identify the generator version and decoder paths. | Schema maintainer | Recover options from a known generation revision or reproduce both bindings in a disposable copy. Record deterministic commands after a generated diff and compatibility check. | +| Panel listener and timeouts, runtime image dependencies and release platforms. | Release maintainer | Run the [release smoke](operational-verification.md#startup-and-release) on the intended Linux image and panel, and on any changed target architecture. | +| Independent maintainer acceptance of recovered intent and open evidence ownership. | Repository maintainer | Walk the migration and route-access changes from [Contributing](../CONTRIBUTING.md), confirm who owns the remaining checks, and resolve the storage policy above. | diff --git a/docs/maintainer-context.md b/docs/maintainer-context.md new file mode 100644 index 000000000..345cc5ea8 --- /dev/null +++ b/docs/maintainer-context.md @@ -0,0 +1,22 @@ +# Maintainer context + +Contextual debt appears here when a route, fixture, or state transition shows what happens and the reason is hard to recover. A migration cleanup can pass normal startup tests yet let a failed row scan rename one recording and advance the database version. The [owning migration](../internal/server/operation.go) and `filename-migration` case preserve the reason and the failing input. + +## Before editing + +Start with the [workflow evidence](context-evidence.md), the [streaming and storage contract](streaming-architecture.md), and the [operational verification runbook](operational-verification.md). Follow the affected input to its consumers, including SQLite, recording directories, UI decoders, and operator-facing status. Use the [testkit](testkit.md) to run the named case or locate its existing tests. + +For changes to a contract, boundary, failure path, or guard, capture the intended change, affected consumers or versions, constraints that must survive, and planned check before editing. Review the diff against four questions. + +1. Does the rationale connect a recorded requirement or failure to the changed code? +2. Do the new dependencies and data flows fit the producer, consumer, and ownership boundaries? +3. Does a named check exercise the risk and observe the downstream state? +4. What happens on denied access, retries, partial success, cancellation, or restart where relevant? + +Give a fresh reviewer the scope and evidence when independent review would materially help. See [roles and handoffs](agent-workflows.md). + +## Update the reason with the change + +Keep local rationale next to code, format and API requirements in their contract, and recovery steps in the runbook. For a lasting cross-component compatibility decision, record the scope, decision, evidence, affected consumers, and verification with the owning contract and link it from the changed surface. For a deliberate replacement, update affected checks and operator guidance together and link the superseded decision. Follow [Comment hygiene](comment-hygiene.md) when editing or removing explanatory text. + +Record conflicting or missing evidence in [open evidence](context-evidence.md#open-evidence) with an owner and next action. Distinguish observed behavior from the reason it was originally chosen. A passing mock isolates a boundary. A deployed producer, provider, or proxy still needs its own acceptance evidence. diff --git a/docs/operational-verification.md b/docs/operational-verification.md new file mode 100644 index 000000000..1ecbd0fdd --- /dev/null +++ b/docs/operational-verification.md @@ -0,0 +1,25 @@ +# Operational verification + +## Startup and release + +Build the SPA before deploying a server binary. The embed package can compile without built assets so the Vite proxy can drive API-only development. `OCAP_STATIC` overrides the embed. The [Dockerfile](../Dockerfile) builds and embeds the SPA and the [release workflow](../.github/workflows/build.yml) builds target binaries and injects version metadata. The full image adds map tools and their runtime libraries. + +Use the [configuration and deployment guide](../README.md#configuration) for storage paths, proxy settings, and HTTP timeouts. For a release smoke on the intended platform, start with an isolated database, data directory and synthetic secret. Confirm the health and version endpoints, load the SPA and a hashed asset under the configured prefix, then stop the service. For a panel deployment, confirm the listener uses the assigned `SERVER_PORT` and the expected persistent paths. For reverse-proxied Steam sign-in, verify the external scheme, host and prefix through login and callback. Ensure a viewer can open a recording without acquiring admin access. + +## Map import and recovery + +See the [Map Manager deployment notes](../README.md#docker). Use `OCAP_TMP` when the system temp volume lacks space for map processing. It redirects scratch for the server and the GDAL and tippecanoe subprocesses. The HTTP handler owns the extracted upload until submission. On successful processing, [JobManager](../internal/maptool/jobmanager.go) removes job scratch and the explicitly assigned extraction directory. Failed jobs can leave scratch and incomplete output. The scanner reads `error.json` for incomplete outputs so the cause survives reload or restart. Inspect the job error, tools, and scratch space before re-uploading. Use the admin cancel action for an active job. Inspect its resulting state and paths before removing any retained files. + +Preserve the world name from the export metadata and the output layout read by the scanner and playback. MapLibre styles sort categories to keep rendering stable when input layers arrive in a different order. [Scanner](../internal/maptool/scanner.go) · [Styles](../internal/maptool/styles.go) + +In a disposable full-image instance, import a small synthetic export. Verify the job reaches completion via the event stream, the map is listed, and its styles and tiles load in the browser. Cancel an import and run one import with a missing input to check status, retained artifacts, and recovery. Confirm the first and updated job lists agree after reconnect. The local [map-boundary case](testkit.md#cases) exercises the Go and UI boundaries with synthetic input, without running GDAL, tippecanoe, or PMTiles. + +## Arsenal loadout import + +Use a sample loadout with a carried item, a loaded magazine, a binocular, and a modded assigned radio. In playback, open the player's Gear tab at the sample frame. Run the [playback-delivery case](testkit.md#cases) to check reconstruction and both output formats locally. + +1. Copy the vanilla export and import it with Ctrl+V in the editor or main-menu Virtual Arsenal. Use that environment because multiplayer clipboard access blocked this check in prior testing. +2. Copy the ACE export and import it in ACE Arsenal with the same mod set. Confirm the radio occupies the radio slot and the binocular occupies its dedicated slot. +3. Compare the imported loadout with the source Gear tab. Check the container item count, the loaded magazine, and that the radio is accepted as its base class. When editing an export format, import the previous and proposed outputs against the same loadout. + +The vanilla import format was established by in-game comparisons. Its header, spacing, magazine and assigned-item commands carry compatibility requirements. The exporter documents those details. [Arsenal exporter](../ui/src/pages/recording-playback/arsenalExport.ts) diff --git a/docs/streaming-architecture.md b/docs/streaming-architecture.md index 433d08be9..d9176d750 100644 --- a/docs/streaming-architecture.md +++ b/docs/streaming-architecture.md @@ -271,6 +271,14 @@ flowchart TD C14 --> E ``` +### Playback analysis and player detail + +- **Event factions follow the recorded frame.** Friendly-fire checks resolve sides for both the victim and the source at the hit or kill frame. A unit can change side during a recording, including during Zeus remote control. Older recordings or an unloaded chunk fall back to the unit's spawn side. Startup reads the manifest and first chunk. The event side index samples later chunks as playback or analysis loads them and retains the sampled sides after eviction. The reactive event reference version refreshes filters and scores as that evidence arrives. [Event side index](../ui/src/playback/eventSides.ts) · [Playback engine](../ui/src/playback/engine.ts) +- **Whole-mission analysis visits each chunk while it is held.** Use `visitAllFrames()` for work such as FPS diagnostics and occupancy totals. Fetching every chunk first would evict early frames from the bounded cache before analysis could read them. The traversal restores the playhead chunk when it finishes or a later chunk fails. [Playback engine](../ui/src/playback/engine.ts) +- **Player detail can arrive after playback starts.** Inline snapshots and per-player sidecars feed the same index. Each player and snapshot type has its own chain, and readers use the latest reconstructed payload at or before the requested frame. Active map transmissions request the radio data they need even if the viewer has never opened Comms or a profile. Requests share the playback engine's sidecar cache and discard results for a recording that has since been replaced. [Event manager](../ui/src/playback/eventManager.ts) · [Render bridge](../ui/src/pages/recording-playback/useRenderBridge.ts) + +Run `go run ./cmd/ocap-testkit run playback-delivery` for the local checks, including equivalent full JSON snapshots and compact protobuf snapshot sidecars. [Testkit](testkit.md#cases) + ## Conversion Flow ```mermaid diff --git a/docs/testkit.md b/docs/testkit.md new file mode 100644 index 000000000..4cf480c3d --- /dev/null +++ b/docs/testkit.md @@ -0,0 +1,48 @@ +# Local testkit + +Run these commands from the repository root with the Go version in [go.mod](../go.mod), CGO and a C compiler for SQLite. Install the Go module dependencies and run `npm ci --prefix ui` before using UI cases. Use the Node version in [UI CI](../.github/workflows/ui.yml). + +```sh +go run ./cmd/ocap-testkit list +go run ./cmd/ocap-testkit run filename-migration stream-recovery +go run ./cmd/ocap-testkit run +``` + +The runner uses cached dependencies, disables Go module and toolchain downloads in test subprocesses, and passes through toolchain settings from a small environment allowlist. It uses temporary data from the tests, fake providers and loopback servers. Set any custom Go cache paths or compiler settings in the invoking shell. The runner uses the checked-out code and test dependencies. Its proxy settings are a fallback for standard HTTP clients. The cases must use fake or loopback providers for isolation. + +On Windows, older MinGW distributions can fail to declare `GetTickCount64` when building SQLite. With TDM-GCC 9.2, the following process-local setting selects the Windows API level SQLite requires: + +```powershell +$env:CGO_CFLAGS='-O2 -g -D_WIN32_WINNT=0x0600' +go run ./cmd/ocap-testkit run +``` + +## Race detector + +Run the stream case with Go's race detector when changing ownership, retries, or background work. + +```sh +go run ./cmd/ocap-testkit run -race stream-recovery +``` + +Put `-race` immediately after `run`. It instruments Go steps in the selected cases and records the exact command in the report. UI steps run normally. Use a [supported compiler and platform](https://go.dev/doc/articles/race_detector#Requirements). Coverage and race detection measure different things. The detector reports races on paths exercised by the selected tests. [Go race detector](https://go.dev/doc/articles/race_detector#How_To_Use) + +## Cases + +| Case | Evidence | +| --- | --- | +| `filename-migration` | Repair and rerun, collisions, and no disk or database changes after an incomplete row scan | +| `legacy-upload` | Repeated filename replacement, failed reload leaves the prior recording available, and legacy raw JSON playback | +| `route-access` | Prefixed viewer route and admin mutation authorization through the mux, plus producer credential rejection | +| `steam-boundary` | Fake OpenID verifier and loopback profile API, denied allowlist access and provider errors | +| `stream-recovery` | Loopback reconnect, repeated starts, partial replacement, durable end, repeated discard, and fake-clock tests for reservation timeouts and a failed keepalive write | +| `conversion-recovery` | Temporary conversion artifacts, status failures and admin retry | +| `playback-delivery` | Synthetic artifact serving and decoding, lazy sidecar replay and Gear exports, event-time factions, and bounded chunk traversal | +| `map-boundary` | Synthetic ZIP and job lifecycle, authenticated SSE, stubbed CDN fallback | +| `startup` | Fake dependencies for startup, failure and shutdown wiring | + +Selectors and the fixture version are in [cases.go](../internal/testkit/cases.go). The runner executes every selected step and returns nonzero for failures. A missing or skipped named Go test fails the case. Logs and `report.json` are written to a new ignored directory under `testkit/runs/`. The report records HEAD, whether the checkout is dirty, testkit source hashes, toolchain, fixture version, commands and outcomes. + +## Changing cases + +Use the production entry point with synthetic inputs and assert the downstream effect. Preserve exact selectors, keep the fixture version current, and avoid capturing deployment data. Run the green case, then make the smallest change that violates the same contract in a disposable clone and verify the expected failing assertion. The filename migration regression is recorded in [workflow evidence](context-evidence.md#verification). See [operational verification](operational-verification.md) for acceptance in a real environment. diff --git a/internal/agentdocs/agentdocs_test.go b/internal/agentdocs/agentdocs_test.go new file mode 100644 index 000000000..51d8919b8 --- /dev/null +++ b/internal/agentdocs/agentdocs_test.go @@ -0,0 +1,142 @@ +package agentdocs + +import ( + "io/fs" + "net/url" + "os" + "path" + "path/filepath" + "regexp" + "runtime" + "strconv" + "strings" + "testing" + + "github.com/stretchr/testify/require" +) + +const root = "../.." + +func TestAgentAliases(t *testing.T) { + for _, alias := range []struct{ link, target string }{ + {".claude", ".agents"}, + {"CLAUDE.md", "AGENTS.md"}, + } { + t.Run(alias.link, func(t *testing.T) { + link := filepath.Join(root, alias.link) + info, err := os.Lstat(link) + require.NoError(t, err) + if runtime.GOOS == "windows" && info.Mode().IsRegular() { + // Git writes the target as a text file in checkouts with symlinks disabled. + data, err := os.ReadFile(link) + require.NoError(t, err) + require.Equal(t, alias.target, string(data)) + return + } + + target, err := os.Readlink(link) + require.NoError(t, err) + require.Equal(t, alias.target, filepath.ToSlash(target)) + _, err = os.Stat(link) + require.NoError(t, err) + }) + } +} + +var ( + nameLine = regexp.MustCompile("(?m)^name: ([a-z0-9]+(?:-[a-z0-9]+)*)$") + descLine = regexp.MustCompile("(?m)^description: (.+)$") + markdownLink = regexp.MustCompile(`\[[^\]\n]+\]\(([^()\s]+)\)`) + headingLine = regexp.MustCompile(`(?m)^#{1,6} +(.+)$`) + nonSlug = regexp.MustCompile(`[^\p{L}\p{N}_ -]`) +) + +func TestAgentWorkflowDocs(t *testing.T) { + repo := os.DirFS(root) + files := []string{ + "AGENTS.md", + "CONTRIBUTING.md", + "docs/agent-workflows.md", + "docs/comment-hygiene.md", + "docs/context-evidence.md", + "docs/maintainer-context.md", + "docs/operational-verification.md", + "docs/streaming-architecture.md", + "docs/testkit.md", + } + for _, pattern := range []string{".agents/agents/*.md", ".agents/skills/*/SKILL.md"} { + matches, err := fs.Glob(repo, pattern) + require.NoError(t, err) + require.NotEmpty(t, matches, pattern) + files = append(files, matches...) + } + + for _, file := range files { + t.Run(file, func(t *testing.T) { + body, err := fs.ReadFile(repo, file) + require.NoError(t, err) + text := strings.ReplaceAll(string(body), "\r\n", "\n") + if strings.HasPrefix(file, ".agents/") { + name := strings.TrimSuffix(path.Base(file), ".md") + if name == "SKILL" { + name = path.Base(path.Dir(file)) + } + checkMetadata(t, text, name) + } + for _, link := range markdownLink.FindAllStringSubmatch(text, -1) { + checkLink(t, repo, file, link[1]) + } + }) + } +} + +func checkMetadata(t *testing.T, text, name string) { + t.Helper() + header, ok := strings.CutPrefix(text, "---\n") + require.True(t, ok, "expected YAML frontmatter") + header, body, ok := strings.Cut(header, "\n---\n") + require.True(t, ok, "expected closing YAML frontmatter delimiter") + require.NotEmpty(t, strings.TrimSpace(body)) + names := nameLine.FindAllStringSubmatch(header, -1) + require.Len(t, names, 1, "expected a single lower-case name") + require.Equal(t, name, names[0][1]) + require.LessOrEqual(t, len(name), 64) + + descriptions := descLine.FindAllStringSubmatch(header, -1) + require.Len(t, descriptions, 1, "expected a single description") + description, err := strconv.Unquote(descriptions[0][1]) + require.NoError(t, err, "quote the description for YAML") + require.NotEmpty(t, strings.TrimSpace(description)) +} + +func checkLink(t *testing.T, repo fs.FS, file, link string) { + t.Helper() + target, err := url.Parse(link) + require.NoError(t, err, link) + if target.IsAbs() || target.Host != "" { + return + } + + dest := file + if target.Path != "" { + dest = path.Join(path.Dir(file), target.Path) + } + _, err = fs.Stat(repo, dest) + require.NoError(t, err, "local link %q", link) + if target.Fragment == "" || path.Ext(dest) != ".md" { + return + } + + body, err := fs.ReadFile(repo, dest) + require.NoError(t, err) + headings := headingLine.FindAllStringSubmatch(string(body), -1) + require.Condition(t, func() bool { + for _, heading := range headings { + slug := nonSlug.ReplaceAllString(strings.ToLower(strings.TrimSpace(heading[1])), "") + if strings.ReplaceAll(slug, " ", "-") == target.Fragment { + return true + } + } + return false + }, "missing heading for link %q", link) +} diff --git a/internal/maptool/CLAUDE.md b/internal/maptool/CLAUDE.md deleted file mode 100644 index 3f3bcc285..000000000 --- a/internal/maptool/CLAUDE.md +++ /dev/null @@ -1,56 +0,0 @@ -# internal/maptool - -Processes Arma 3 map data (grad_meh exports) into PMTiles + MapLibre styles for the OCAP2 web viewer. - -## Package Layout - -| File | Purpose | -|---|---| -| `pipeline.go` | `Pipeline` and `Job` structs, stage runner. `Job.SubDirs` controls output layout (tiles/, styles/ subdirs). | -| `jobmanager.go` | Queue-based job manager. `processJob` sets `SubDirs=true` for web uploads. Cleans up `filepath.Dir(job.InputPath)` on success. | -| `gradmeh.go` | `ValidateGradMehDir()`, `ReadGradMehMeta()`, `WorldNameFromDir()`. Validates meta.json + sat/ exist. | -| `satellite_gradmeh.go` | Reads grad_meh satellite PNGs, builds VRT, runs GDAL pipeline to satellite.pmtiles. | -| `vector_gradmeh.go` | Discovers GeoJSON layers from grad_meh export, processes into features.pmtiles via tippecanoe. | -| `styles.go` | All MapLibre style definitions. Generates standard/satellite/hybrid style documents. | -| `metadata.go` | Generates map.json and style JSON files as final pipeline stage. | -| `dem.go`, `dem_pipeline.go` | DEM/elevation grid handling. | -| `contour.go`, `contours_gdal.go` | Contour line generation (4-interval: 0.5m, 10m, 50m, 100m). | -| `hillshade.go`, `heightmap.go`, `colorrelief.go` | Terrain visualization layers. | -| `raster_tiles.go`, `tiles.go` | GDAL-based tile generation to PMTiles. | -| `scanner.go` | `ScanMaps()` for discovering installed maps in the maps directory. | -| `tools.go` | External tool detection (gdal, tippecanoe, etc.). | - -## styles.go — Key Design Decisions - -### Layer Render Order -`categoryRenderOrder` in `buildVectorFeatureLayers()` sorts layers to match Arma 3's engine paint order, bottom to top: - -sea → contours → forest → rocks → buildings → trail → track → road → main_road → runway → railway → powerline → bridges → vegetation → icons → labels - -This is critical because `VectorLayers` arrives in arbitrary directory-listing order from grad_meh. Without sorting, labels can end up below roads. - -### Layer Categories -`categorizeLayer()` maps layer names to categories. Roads return their own name (`trail`, `track`, etc.) for sub-ordering. `isLayerVisible()` still groups them under `vis.roads`. - -### Style Variants -Three variants share the same vector layers but differ in raster base: -- **standard**: color-relief + hillshade + hidden satellite toggle -- **satellite**: hillshade + satellite, no forest/sea-land fills -- **hybrid**: native hillshade from DEM + 60% satellite + all vector features - -### Label Readability -All label types need text halos. The halo styles: -- `namecity`, `namevillage`, `namecitycapital`: white text + black halo -- `hill`, `namemarine`, `namelocal`, `citycenter`: colored text + semi-transparent white halo `rgba(255,255,255,0.7)` - -### Runway Geometry -grad_meh exports runways as **polygons**, not lines. Style type must be `fill`, not `line`. - -### Known Layer Types -`knownLayerStyles` map covers: fills (sea, forest, rocks, house), roads (trail/track/road/main_road with outline+fill pairs), bridges (fill-extrusion), infrastructure (railway, runway, powerline), contours (legacy single-layer + 4-interval GDAL), object icons (20+ types), location labels (7 types), vegetation (4 types). - -## Integrated Map Manager (internal/server/handler_maptool.go) - -- Upload endpoint `POST /api/maps/import` accepts multipart ZIP, extracts with zip-slip protection, finds grad_meh dir (root or one level deep), submits to JobManager. -- Map Manager UI is part of the SolidJS frontend (`ui/src/pages/map-manager/`). -- ZIP extraction cleanup: JobManager's `processJob` calls `os.RemoveAll(filepath.Dir(job.InputPath))` which removes the per-upload extraction directory. diff --git a/internal/server/coverage_extra_test.go b/internal/server/coverage_extra_test.go index 3c7e3a3ed..5223a8dbc 100644 --- a/internal/server/coverage_extra_test.go +++ b/internal/server/coverage_extra_test.go @@ -777,7 +777,7 @@ func TestHandlerAndAuthAndMaptool_100(t *testing.T) { } func TestHandlerStream_100PercentCoverage(t *testing.T) { - // 1. PongHandler (66-67), Ping tick error (78-84), Double start (166), Resume while active (184), ackBatch (250) + // 1. Pong handling, ping writes, double start, resume while active, and ackBatch. h, mux, dir := newTestStreamHandlerWithRepo(t) h.setting.Streaming.PingInterval = 10 * time.Millisecond h.setting.Streaming.PingTimeout = 100 * time.Millisecond @@ -807,7 +807,7 @@ func TestHandlerStream_100PercentCoverage(t *testing.T) { st, _ := json.Marshal(core.SoldierState{SoldierID: 1, CaptureFrame: core.Frame(i)}) _ = c.WriteJSON(streaming.Envelope{Type: streaming.TypeSoldierState, Seq: uint64(i), Payload: st}) } - time.Sleep(25 * time.Millisecond) // let ping & ack tickers run + time.Sleep(25 * time.Millisecond) // let the ping ticker run // Second start_mission on active session -> hits 166-168 require.NoError(t, c.WriteJSON(streaming.Envelope{Type: streaming.TypeStartMission, Seq: 9999, Payload: startPayload})) _, _, _ = c.ReadMessage() diff --git a/internal/server/handler_stream.go b/internal/server/handler_stream.go index 09f67d80b..8ce19d94f 100644 --- a/internal/server/handler_stream.go +++ b/internal/server/handler_stream.go @@ -52,6 +52,22 @@ func (h *Handler) HandleStream(w http.ResponseWriter, r *http.Request) { // ack ticks, so its buffer is released promptly. const ackBatch = 500 +func sendStreamPings(done <-chan struct{}, interval time.Duration, ping func() error) { + ticker := time.NewTicker(interval) + defer ticker.Stop() + for { + select { + case <-ticker.C: + if err := ping(); err != nil { + slog.Warn("stream: failed to write ping", "error", err) + return + } + case <-done: + return + } + } +} + func (h *Handler) streamLoop(ws *websocket.Conn) { // Ping/pong keepalive pingInterval := h.setting.Streaming.PingInterval @@ -69,26 +85,12 @@ func (h *Handler) streamLoop(ws *websocket.Conn) { }) ws.SetReadDeadline(time.Now().Add(pingInterval + pingTimeout)) - // Ping ticker done := make(chan struct{}) - go func() { - ticker := time.NewTicker(pingInterval) - defer ticker.Stop() - for { - select { - case <-ticker.C: - mu.Lock() - err := ws.WriteControl(websocket.PingMessage, nil, time.Now().Add(pingTimeout)) - mu.Unlock() - if err != nil { - slog.Warn("stream: failed to write ping", "error", err) - return - } - case <-done: - return - } - } - }() + go sendStreamPings(done, pingInterval, func() error { + mu.Lock() + defer mu.Unlock() + return ws.WriteControl(websocket.PingMessage, nil, time.Now().Add(pingTimeout)) + }) defer close(done) conn := &streamConn{ws: ws, writeMu: &mu} diff --git a/internal/server/handler_stream_resume_test.go b/internal/server/handler_stream_resume_test.go index b568c5072..7f4b6797e 100644 --- a/internal/server/handler_stream_resume_test.go +++ b/internal/server/handler_stream_resume_test.go @@ -10,6 +10,7 @@ import ( "strings" "sync" "testing" + "testing/synctest" "time" "github.com/OCAP2/extension/v5/pkg/streaming" @@ -926,25 +927,43 @@ func TestStreamResume_ConcurrentRepeatedStartsShareOneSession(t *testing.T) { } func TestStreamRegistryReserveWaitsForConcurrentStart(t *testing.T) { - r := newStreamRegistry() - got, err := r.reserve("m", time.Second) - require.NoError(t, err) - require.Nil(t, got, "reserved") - - // A second start waits, and fails when the first never finishes. - _, err = r.reserve("m", 50*time.Millisecond) - require.ErrorIs(t, err, errReserveTimeout) - - // A failed first start frees the id for the next one. - r.settle("m", nil) - got, err = r.reserve("m", time.Second) - require.NoError(t, err) - require.Nil(t, got) + synctest.Test(t, func(t *testing.T) { + const wait = time.Second + r := newStreamRegistry() + got, err := r.reserve("m", wait) + require.NoError(t, err) + require.Nil(t, got, "reserved") + + start := time.Now() + _, err = r.reserve("m", wait) + require.ErrorIs(t, err, errReserveTimeout) + require.Equal(t, wait, time.Since(start), "a pending start waits for its deadline") + + r.settle("m", nil) + got, err = r.reserve("m", wait) + require.NoError(t, err) + require.Nil(t, got, "a failed start freed the reservation") + + type result struct { + session *streamSession + err error + } + done := make(chan result, 1) + go func() { + session, err := r.reserve("m", wait) + done <- result{session, err} + }() + synctest.Wait() + select { + case <-done: + t.Fatal("the competing start returned before the reservation settled") + default: + } - s := &streamSession{missionID: "m"} - done := make(chan *streamSession) - go func() { got, _ := r.reserve("m", time.Second); done <- got }() - time.Sleep(20 * time.Millisecond) - r.settle("m", s) - assert.Same(t, s, <-done, "the waiting start gets the session") + s := &streamSession{missionID: "m"} + r.settle("m", s) + completed := <-done + require.NoError(t, completed.err) + require.Same(t, s, completed.session, "the waiting start gets the session") + }) } diff --git a/internal/server/handler_stream_test.go b/internal/server/handler_stream_test.go index e5e69a3ef..bc8bcb821 100644 --- a/internal/server/handler_stream_test.go +++ b/internal/server/handler_stream_test.go @@ -3,6 +3,7 @@ package server import ( "context" "encoding/json" + "errors" "net/http" "net/http/httptest" "os" @@ -10,6 +11,7 @@ import ( "strings" "sync" "testing" + "testing/synctest" "time" "github.com/OCAP2/extension/v5/pkg/streaming" @@ -30,6 +32,24 @@ func TestStreamingSettingDefaults(t *testing.T) { assert.Equal(t, time.Duration(0), s.Streaming.PingTimeout) } +func TestSendStreamPings_StopsOnWriteError(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + const interval = 30 * time.Second + ctx, cancel := context.WithTimeout(t.Context(), 2*interval) + defer cancel() + + start := time.Now() + writes := 0 + sendStreamPings(ctx.Done(), interval, func() error { + writes++ + return errors.New("ping write failed") + }) + require.NoError(t, ctx.Err(), "the ping loop must stop on the write error") + require.Equal(t, 1, writes, "the ping loop must not retry a broken transport") + require.Equal(t, interval, time.Since(start), "the loop stopped at the failed ping") + }) +} + func TestHandleStream_InvalidStartMetadata(t *testing.T) { for _, payload := range []string{`null`, `{}`, `{"mission":null,"world":{}}`, `{"mission":{"MissionName":"Bad","CaptureDelay":0},"world":{"WorldName":"altis"}}`} { t.Run(payload, func(t *testing.T) { diff --git a/internal/server/operation.go b/internal/server/operation.go index 0a4216a93..cd5ba36c6 100644 --- a/internal/server/operation.go +++ b/internal/server/operation.go @@ -421,6 +421,8 @@ func (r *RepoOperation) migrateDecodeFilenames(version int) error { renames = append(renames, rename{id: id, oldName: oldName, newName: newName}) } rows.Close() + // Next can stop on an error after returning candidates. Require a complete + // scan before renaming files or recording the migration as applied. if err := rows.Err(); err != nil { return fmt.Errorf("v%d rows: %w", version, err) } diff --git a/internal/server/route_access_test.go b/internal/server/route_access_test.go new file mode 100644 index 000000000..460ae5439 --- /dev/null +++ b/internal/server/route_access_test.go @@ -0,0 +1,80 @@ +package server + +import ( + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "testing" + "time" + + "github.com/go-fuego/fuego" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestRecordingRouteAccess(t *testing.T) { + dir := t.TempDir() + dataDir := filepath.Join(dir, "data") + require.NoError(t, os.MkdirAll(dataDir, 0o755)) + + repo, err := NewRepoOperation(filepath.Join(dir, "operations.db")) + require.NoError(t, err) + t.Cleanup(func() { assert.NoError(t, repo.db.Close()) }) + + op := &Operation{ + WorldName: "altis", MissionName: "Synthetic recording", Filename: "synthetic", + Date: "2026-01-01", Tag: "coop", + } + require.NoError(t, repo.Store(t.Context(), op)) + recordingPath := filepath.Join(dataDir, "synthetic.json.gz") + writeTestGzippedJSON(t, recordingPath, map[string]string{"missionName": "Synthetic recording"}) + + require.NoError(t, os.MkdirAll(filepath.Join(dir, "markers"), 0o755)) + require.NoError(t, os.MkdirAll(filepath.Join(dir, "ammo"), 0o755)) + repoMarker, err := NewRepoMarker(filepath.Join(dir, "markers")) + require.NoError(t, err) + repoAmmo, err := NewRepoAmmo(filepath.Join(dir, "ammo")) + require.NoError(t, err) + + setting := Setting{ + PrefixURL: "/ocap", Secret: "synthetic-test-secret", Data: dataDir, + Auth: Auth{Mode: "password", SessionTTL: time.Hour}, + } + server := fuego.NewServer(fuego.WithoutStartupMessages(), fuego.WithoutAutoGroupTags(), fuego.WithSecurity(OpenAPISecuritySchemes)) + NewHandler(server, repo, repoMarker, repoAmmo, setting) + + jwt := NewJWTManager(setting.Secret, setting.Auth.SessionTTL) + viewerToken, err := jwt.Create("synthetic-viewer", WithRole("viewer")) + require.NoError(t, err) + dataRoute := "/ocap/data/synthetic.json.gz" + operationID := strconv.FormatInt(op.ID, 10) + for _, tc := range []struct { + name, method, path, token string + status int + }{ + {"anonymous cannot read", http.MethodGet, dataRoute, "", http.StatusUnauthorized}, + {"viewer can read", http.MethodGet, dataRoute, viewerToken, http.StatusOK}, + {"viewer cannot delete", http.MethodDelete, "/ocap/api/v1/operations/" + operationID, viewerToken, http.StatusUnauthorized}, + } { + t.Run(tc.name, func(t *testing.T) { + request := httptest.NewRequest(tc.method, tc.path, nil) + if tc.token != "" { + request.Header.Set("Authorization", "Bearer "+tc.token) + } + response := httptest.NewRecorder() + server.Mux.ServeHTTP(response, request) + assert.Equal(t, tc.status, response.Code) + if tc.status == http.StatusOK { + recording, err := os.ReadFile(recordingPath) + require.NoError(t, err) + assert.Equal(t, recording, response.Body.Bytes()) + } + }) + } + + _, err = repo.GetByID(t.Context(), operationID) + assert.NoError(t, err, "viewer request must preserve the recording row") + assert.FileExists(t, recordingPath, "viewer request must preserve the recording file") +} diff --git a/internal/testkit/cases.go b/internal/testkit/cases.go new file mode 100644 index 000000000..b02ed4374 --- /dev/null +++ b/internal/testkit/cases.go @@ -0,0 +1,70 @@ +package testkit + +// Bump this when case inputs or expected behavior change. +const fixtureVersion = "ocap-local-v4" + +type testStep struct { + target string + tests []string +} + +type testCase struct { + name, description string + steps []testStep +} + +// Keep the list explicit. Each Go selector is a top-level test and each UI +// selector is one test file with synthetic or stubbed inputs. +var cases = []testCase{ + {"filename-migration", "Legacy filename repair, rerun, and a failed candidate scan", []testStep{ + {"./internal/server", []string{"TestMigrationRerun", "TestMigrationV11DecodeFilenames", "TestMigrationV11_DBCollisionSkipped", "TestMigrationV11_FilesystemCollisionSkipped", "TestMigrateDecodeFilenames_IterationErrorLeavesVersionUnchanged"}}, + }}, + {"legacy-upload", "Recording replacement, failure without a row, and legacy playback", []testStep{ + {"./internal/server", []string{"TestIntegration_UploadSameFilenameReplaces", "TestIntegration_FailedReuploadPreservesExisting", "TestIntegration_UploadWriteFailureLeavesNoRow", "TestIntegration_ServeLegacyRawJSONAsGz"}}, + }}, + {"route-access", "Registered recording routes grant viewer reads and deny admin writes", []testStep{ + {"./internal/server", []string{"TestRecordingRouteAccess", "TestStoreOperation_WrongSecret", "TestHandleStream_WrongSecret"}}, + }}, + {"steam-boundary", "Verified identity, denied allowlist access, and optional profile failures", []testStep{ + {"./internal/server", []string{"TestSteamCallback_MissingNonce", "TestSteamCallback_VerifyError", "TestSteamCallback_AllowlistMode_DeniedUser", "TestSteamCallback_AllowlistMode_DBErrorRedirectsToSteamError", "TestSteamCallback_AllowlistMode_AdminBypass", "TestSteamCallback_SteamAPIError", "TestSteamCallback_WithSteamAPIKey"}}, + }}, + {"stream-recovery", "Reconnect, repeated starts, partial replay, durable end, and discard retry", []testStep{ + {"./internal/server", []string{ + "TestStreamResume_ReconnectContinuesSameRecording", + "TestStreamResume_ConcurrentRepeatedStartsShareOneSession", + "TestStreamResume_FullReplayReplacesPartialSegment", + "TestStreamResume_IncompleteReplayKeepsEarlierSegments", + "TestStreamResume_WebRestartMidMission", + "TestStreamResume_EndNotAcknowledgedBeforeSaveSucceeds", + "TestStreamDiscard_FailedRemovalIsRepeated", + "TestStreamDiscard_LostAckResolvedByResume", + "TestStreamRegistryReserveWaitsForConcurrentStart", + "TestSendStreamPings_StopsOnWriteError", + }}, + }}, + {"conversion-recovery", "Clean interrupted conversions without resetting stream-owned recordings", []testStep{ + {"./internal/conversion", []string{"TestWorker_CleanupInterrupted", "TestWorker_CleanupInterrupted_RetryFailed", "TestWorker_CleanupInterrupted_LeavesStreaming", "TestConvertOperation_UpdateStorageFormatError", "TestNativeV2SurvivesLegacyConversionAndStatsBackfill"}}, + {"./internal/server", []string{"TestRetryConversion", "TestRetryConversion_NotFailed", "TestHandlerAdmin_RetryV2AndDeleteLocked"}}, + }}, + {"playback-delivery", "Negotiated recording artifacts and UI compatibility with stored formats", []testStep{ + {"./internal/server", []string{"TestIntegration_ConversionAndStaticServing", "TestIntegration_PrecompressedArtifactServing"}}, + {"./internal/storage", []string{"TestWriteArtifact_RemovesStaleSidecarsWhenPayloadShrinks"}}, + {"ui", []string{ + "src/data/decoders/__tests__/streamingV2Compatibility.test.ts", + "src/data/decoders/__tests__/protobufDecoder.test.ts", + "src/data/__tests__/chunkManager.test.ts", + "src/pages/recording-playback/__tests__/snapshotReplay.integration.test.ts", + "src/pages/recording-playback/__tests__/convertedCombat.integration.test.ts", + "src/pages/recording-playback/__tests__/transmissionSidecars.integration.test.tsx", + "src/playback/__tests__/wholeMissionAnalysis.test.ts", + }}, + }}, + {"map-boundary", "Map import cleanup and failure state, event reconnect, and CDN fallback", []testStep{ + {"./internal/server", []string{"TestImportMapToolZip_NotZip", "TestMapToolEventStream_Unauthorized", "TestMapToolEventStream_QueryToken"}}, + {"./internal/maptool", []string{"TestExtractZip_ZipSlipRejected", "TestJobManager_SubmitWithCleanup", "TestJobManager_PipelineError_WritesErrorJSON"}}, + {"ui", []string{"src/data/__tests__/apiClient.test.ts", "src/pages/map-manager/__tests__/useMapToolEvents.test.ts"}}, + }}, + {"startup", "Config and dependency failures, plus startup and shutdown wiring with fakes", []testStep{ + {"./cmd/ocap-webserver", []string{"TestRunApp_EarlyErrors", "TestRunApp_FullPaths"}}, + }}, +} diff --git a/internal/testkit/runner.go b/internal/testkit/runner.go new file mode 100644 index 000000000..f0184395b --- /dev/null +++ b/internal/testkit/runner.go @@ -0,0 +1,264 @@ +package testkit + +import ( + "bytes" + "context" + "crypto/sha256" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "time" +) + +type runReport struct { + Revision string `json:"revision"` + Dirty bool `json:"dirty_worktree"` + FixtureVersion string `json:"fixture_version"` + TestkitSources map[string]string `json:"testkit_source_sha256"` + StartedAt time.Time `json:"started_at"` + Toolchain map[string]string `json:"toolchain"` + Cases []caseResult `json:"cases"` +} + +type caseResult struct { + Name string `json:"name"` + Status string `json:"status"` + Steps []stepResult `json:"steps"` +} + +type stepResult struct { + Directory string `json:"directory"` + Command []string `json:"command"` + Status string `json:"status"` + DurationMS int64 `json:"duration_ms"` + Log string `json:"log"` + Error string `json:"error,omitempty"` +} + +type commandRunner func(ctx context.Context, dir string, env []string, args []string) ([]byte, error) + +// Run executes the requested local test cases and writes progress to the given streams. +func Run(args []string, stdout, stderr io.Writer) error { + return run(args, stdout, stderr, executeCommand) +} + +func run(args []string, stdout, stderr io.Writer, execute commandRunner) error { + if len(args) == 1 && args[0] == "list" { + for _, c := range cases { + fmt.Fprintf(stdout, "%-21s %s\n", c.name, c.description) + } + return nil + } + if len(args) == 0 || args[0] != "run" { + return errors.New("usage: go run ./cmd/ocap-testkit list | run [-race] [case ...]") + } + names := args[1:] + race := len(names) > 0 && names[0] == "-race" + if race { + names = names[1:] + } + selected, err := selectCases(names) + if err != nil { + return err + } + sources := make(map[string]string) + for _, path := range []string{"cmd/ocap-testkit/main.go", "internal/testkit/runner.go", "internal/testkit/cases.go"} { + data, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("run from the repository root: %w", err) + } + sources[path] = fmt.Sprintf("%x", sha256.Sum256(data)) + } + env := testEnvironment() + revision, err := commandOutput(execute, env, "git", "rev-parse", "HEAD") + if err != nil { + return err + } + status, err := commandOutput(execute, env, "git", "status", "--porcelain", "--untracked-files=normal") + if err != nil { + return err + } + report := runReport{ + Revision: revision, Dirty: status != "", FixtureVersion: fixtureVersion, + StartedAt: time.Now().UTC(), Toolchain: map[string]string{}, TestkitSources: sources, + } + for _, tool := range [][]string{{"go", "version"}, {"go", "env", "-json", "CGO_ENABLED", "CC", "CGO_CFLAGS", "GOOS", "GOARCH"}, {"node", "--version"}} { + version, err := commandOutput(execute, env, tool...) + if err != nil { + version = err.Error() + } + report.Toolchain[strings.Join(tool, " ")] = version + } + compiler, err := commandOutput(execute, env, "go", "env", "CC") + if err == nil { + version, err := commandOutput(execute, env, compiler, "--version") + if err == nil { + report.Toolchain["C compiler"] = strings.SplitN(version, "\n", 2)[0] + } + } + runDir, err := makeRunDir(report.StartedAt) + if err != nil { + return err + } + failed := 0 + for _, c := range selected { + result := caseResult{Name: c.name, Status: "pass"} + for i, step := range c.steps { + log := fmt.Sprintf("%s-%d.log", c.name, i+1) + outcome := runStep(context.Background(), execute, step, env, filepath.Join(runDir, log), race) + result.Steps = append(result.Steps, outcome) + if outcome.Status == "fail" { + result.Status = "fail" + fmt.Fprintf(stderr, "%s: %s (%s)\n", c.name, outcome.Error, log) + } + } + fmt.Fprintf(stdout, "%s %s\n", result.Status, c.name) + if result.Status == "fail" { + failed++ + } + report.Cases = append(report.Cases, result) + } + path := filepath.Join(runDir, "report.json") + if err := writeReport(path, report); err != nil { + return err + } + fmt.Fprintln(stdout, path) + if failed > 0 { + return fmt.Errorf("%d of %d testkit cases failed", failed, len(selected)) + } + return nil +} + +const reportsDir = "testkit/runs" + +func makeRunDir(start time.Time) (string, error) { + if err := os.MkdirAll(reportsDir, 0o755); err != nil { + return "", err + } + return os.MkdirTemp(reportsDir, start.Format("20060102T150405Z-")) +} + +func writeReport(path string, report runReport) error { + file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err != nil { + return err + } + encoder := json.NewEncoder(file) + encoder.SetIndent("", " ") + return errors.Join(encoder.Encode(report), file.Close()) +} + +func selectCases(names []string) ([]testCase, error) { + if len(names) == 0 { + return cases, nil + } + selected := make([]testCase, 0, len(names)) + byName := make(map[string]testCase, len(cases)) + for _, c := range cases { + byName[c.name] = c + } + for _, name := range names { + c, exists := byName[name] + if !exists { + return nil, fmt.Errorf("unknown or repeated case %q (go run ./cmd/ocap-testkit list)", name) + } + selected = append(selected, c) + delete(byName, name) + } + return selected, nil +} + +func testEnvironment() []string { + var env []string + for _, key := range []string{ + "PATH", "PATHEXT", "SystemRoot", "WINDIR", "COMSPEC", "HOME", "USERPROFILE", "LOCALAPPDATA", "APPDATA", + "TEMP", "TMP", "TMPDIR", "GOCACHE", "GOMODCACHE", "GOPATH", "CC", "CXX", "CGO_CFLAGS", "CGO_CPPFLAGS", "CGO_CXXFLAGS", "CGO_LDFLAGS", + } { + if value, ok := os.LookupEnv(key); ok { + env = append(env, key+"="+value) + } + } + // Use installed dependencies and ignore per-user Go overrides. Standard + // HTTP clients keep loopback access for fixtures and fail on external URLs. + return append(env, "GOENV=off", "GOWORK=off", "GOTOOLCHAIN=local", "GOPROXY=off", "GOSUMDB=off", + "HTTP_PROXY=http://127.0.0.1:1", "HTTPS_PROXY=http://127.0.0.1:1", "NO_PROXY=localhost,127.0.0.1,::1", "CI=true") +} + +func commandOutput(execute commandRunner, env []string, args ...string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + output, err := execute(ctx, ".", env, args) + if err != nil { + return "", fmt.Errorf("%s: %w", strings.Join(args, " "), err) + } + return strings.TrimSpace(string(output)), nil +} + +func executeCommand(ctx context.Context, dir string, env []string, args []string) ([]byte, error) { + cmd := exec.CommandContext(ctx, args[0], args[1:]...) + cmd.Dir, cmd.Env, cmd.WaitDelay = dir, env, 2*time.Second + return cmd.CombinedOutput() +} + +func runStep(ctx context.Context, execute commandRunner, step testStep, env []string, logPath string, race bool) (result stepResult) { + start := time.Now() + result = stepResult{Directory: ".", Status: "fail", Log: filepath.Base(logPath)} + defer func() { result.DurationMS = time.Since(start).Milliseconds() }() + if step.target == "ui" { + result.Directory = "ui" + result.Command = append([]string{"node", "node_modules/vitest/vitest.mjs", "run", "--reporter=verbose"}, step.tests...) + for _, file := range step.tests { + if _, err := os.Stat(filepath.Join("ui", file)); err != nil { + result.Error = err.Error() + return result + } + } + } else { + pattern := "^(" + strings.Join(step.tests, "|") + ")$" + result.Command = []string{"go", "test"} + if race { + result.Command = append(result.Command, "-race") + } + result.Command = append(result.Command, "-mod=readonly", "-count=1", "-timeout=90s", "-json", "-run", pattern, step.target) + } + ctx, cancel := context.WithTimeout(ctx, 5*time.Minute) + defer cancel() + output, err := execute(ctx, result.Directory, env, result.Command) + if logErr := os.WriteFile(logPath, output, 0o600); logErr != nil { + result.Error = logErr.Error() + return result + } + if ctx.Err() != nil { + err = ctx.Err() + } + if err == nil && step.target != "ui" { + err = requireGoPasses(output, step.tests) + } + if err != nil { + result.Error = err.Error() + return result + } + result.Status = "pass" + return result +} + +func requireGoPasses(output []byte, tests []string) error { + passed := make(map[string]bool, len(tests)) + for line := range bytes.SplitSeq(output, []byte("\n")) { + var event struct{ Action, Test string } + if json.Unmarshal(line, &event) == nil && event.Action == "pass" { + passed[event.Test] = true + } + } + for _, test := range tests { + if !passed[test] { + return fmt.Errorf("missing passing result for %s", test) + } + } + return nil +} diff --git a/internal/testkit/runner_test.go b/internal/testkit/runner_test.go new file mode 100644 index 000000000..77e3f6ed3 --- /dev/null +++ b/internal/testkit/runner_test.go @@ -0,0 +1,229 @@ +package testkit + +import ( + "context" + "encoding/json" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestSelectCases(t *testing.T) { + all, err := selectCases(nil) + require.NoError(t, err) + require.Equal(t, cases, all) + + selected, err := selectCases([]string{"startup", "filename-migration"}) + require.NoError(t, err) + require.Len(t, selected, 2) + require.Equal(t, "startup", selected[0].name) + require.Equal(t, "filename-migration", selected[1].name) + + for _, names := range [][]string{{"unknown"}, {"startup", "startup"}} { + _, err := selectCases(names) + require.ErrorContains(t, err, "unknown or repeated case") + } +} + +func TestTestEnvironment(t *testing.T) { + t.Setenv("OCAP_SECRET", "synthetic-secret") + t.Setenv("GOPROXY", "https://proxy.example.invalid") + t.Setenv("GOFLAGS", "-mod=vendor") + t.Setenv("GOCACHE", t.TempDir()) + + env := testEnvironment() + require.Contains(t, env, "GOPROXY=off") + require.Contains(t, env, "GOWORK=off") + require.Contains(t, env, "GOCACHE="+os.Getenv("GOCACHE")) + require.NotContains(t, env, "OCAP_SECRET=synthetic-secret") + require.NotContains(t, env, "GOFLAGS=-mod=vendor") + require.NotContains(t, env, "GOPROXY=https://proxy.example.invalid") +} + +func TestRequireGoPasses(t *testing.T) { + output := []byte("compile notice\n" + + "{\"Action\":\"pass\",\"Package\":\"example.invalid/fixture\"}\n" + + "{\"Action\":\"pass\",\"Test\":\"TestPass\"}\n" + + "{\"Action\":\"skip\",\"Test\":\"TestSkip\"}\n") + require.NoError(t, requireGoPasses(output, []string{"TestPass"})) + require.ErrorContains(t, requireGoPasses(output, []string{"TestPass", "TestSkip"}), "TestSkip") + require.ErrorContains(t, requireGoPasses(output, []string{"TestMissing"}), "TestMissing") +} + +func TestRunValidatesArgumentsAndRoot(t *testing.T) { + t.Chdir(t.TempDir()) + require.NoError(t, Run([]string{"list"}, io.Discard, io.Discard)) + require.ErrorContains(t, Run(nil, io.Discard, io.Discard), "usage") + require.ErrorContains(t, Run([]string{"run", "unknown"}, io.Discard, io.Discard), "unknown or repeated case") + require.ErrorContains(t, Run([]string{"run"}, io.Discard, io.Discard), "run from the repository root") +} + +func setupRoot(t *testing.T) { + t.Helper() + t.Chdir(t.TempDir()) + writeFixture(t, "cmd/ocap-testkit/main.go", "package main\n") + writeFixture(t, "internal/testkit/runner.go", "package testkit\n") + writeFixture(t, "internal/testkit/cases.go", "package testkit\n") +} + +func writeFixture(t *testing.T, path, content string) { + t.Helper() + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + require.NoError(t, os.WriteFile(path, []byte(content), 0o600)) +} + +func useCases(t *testing.T, selected ...testCase) { + t.Helper() + old := cases + t.Cleanup(func() { cases = old }) + cases = selected +} + +func TestRunWritesReportForEverySelectedCase(t *testing.T) { + setupRoot(t) + writeFixture(t, "go.mod", "module example.invalid/testkit-fixture\n\ngo 1.23\n") + writeFixture(t, "fixture/fixture_test.go", "package fixture\n\nimport \"testing\"\n\nfunc TestReady(t *testing.T) {}\n") + + git := func(args ...string) { + t.Helper() + cmd := exec.Command("git", args...) + cmd.Env = testEnvironment() + out, err := cmd.CombinedOutput() + require.NoError(t, err, "%s", out) + } + git("init", "-q", "--template=") + git("-c", "user.name=Testkit Fixture", "-c", "user.email=fixture@example.invalid", + "-c", "core.hooksPath=.git/disabled-hooks", "commit", "-q", "--allow-empty", "--no-gpg-sign", "-m", "fixture") + + useCases(t, + testCase{"missing", "Missing Go selector", []testStep{{"./fixture", []string{"TestMissing"}}}}, + testCase{"ready", "Passing Go selector", []testStep{{"./fixture", []string{"TestReady"}}}}, + testCase{"missing-ui", "Missing UI input", []testStep{{"ui", []string{"missing.test.ts"}}}}, + ) + + require.ErrorContains(t, Run([]string{"run", "missing", "ready", "missing-ui"}, io.Discard, io.Discard), "2 of 3 testkit cases failed") + + runs, err := os.ReadDir("testkit/runs") + require.NoError(t, err) + require.Len(t, runs, 1) + runDir := filepath.Join("testkit/runs", runs[0].Name()) + data, err := os.ReadFile(filepath.Join(runDir, "report.json")) + require.NoError(t, err) + var report runReport + require.NoError(t, json.Unmarshal(data, &report)) + require.NotEmpty(t, report.Revision) + require.True(t, report.Dirty) + require.Equal(t, fixtureVersion, report.FixtureVersion) + require.Len(t, report.TestkitSources, 3) + require.Contains(t, report.Toolchain["go version"], "go version") + require.Len(t, report.Cases, 3) + + missing, ready, missingUI := report.Cases[0], report.Cases[1], report.Cases[2] + require.Equal(t, "fail", missing.Status) + require.Contains(t, missing.Steps[0].Error, "missing passing result for TestMissing") + require.Equal(t, "pass", ready.Status) + log, err := os.ReadFile(filepath.Join(runDir, ready.Steps[0].Log)) + require.NoError(t, err) + require.Contains(t, string(log), "\"Test\":\"TestReady\"") + require.Equal(t, "fail", missingUI.Status) + require.Equal(t, "ui", missingUI.Steps[0].Directory) + require.Contains(t, missingUI.Steps[0].Error, "missing.test.ts") +} + +func TestRunReportsRepositoryErrors(t *testing.T) { + setupRoot(t) + for _, failing := range []string{"rev-parse", "status"} { + t.Run(failing, func(t *testing.T) { + execute := func(_ context.Context, _ string, _ []string, args []string) ([]byte, error) { + if args[1] == failing { + return nil, errors.New("git unavailable") + } + return []byte("fixture-revision\n"), nil + } + require.ErrorContains(t, run([]string{"run"}, io.Discard, io.Discard, execute), "git "+failing) + }) + } + require.NoDirExists(t, reportsDir) +} + +func TestRunReportsOutputErrors(t *testing.T) { + t.Run("report root blocked", func(t *testing.T) { + setupRoot(t) + writeFixture(t, reportsDir, "occupied") + require.ErrorContains(t, run([]string{"run"}, io.Discard, io.Discard, successfulCommand), "runs") + }) + + t.Run("report file blocked", func(t *testing.T) { + setupRoot(t) + useCases(t, testCase{"fixture", "Report test", []testStep{{"./fixture", []string{"TestReady"}}}}) + execute := func(ctx context.Context, dir string, env, args []string) ([]byte, error) { + if args[1] == "test" { + runs, err := os.ReadDir(reportsDir) + require.NoError(t, err) + require.Len(t, runs, 1) + require.NoError(t, os.Mkdir(filepath.Join(reportsDir, runs[0].Name(), "report.json"), 0o755)) + } + return successfulCommand(ctx, dir, env, args) + } + require.ErrorContains(t, run([]string{"run"}, io.Discard, io.Discard, execute), "report.json") + }) +} + +func TestRunRecordsMixedCaseWithRaceDetector(t *testing.T) { + setupRoot(t) + writeFixture(t, "ui/fixture.test.ts", "// synthetic test") + useCases(t, testCase{"fixture", "Mixed report test", []testStep{ + {"./fixture", []string{"TestReady"}}, + {"ui", []string{"fixture.test.ts"}}, + }}) + execute := func(ctx context.Context, dir string, env, args []string) ([]byte, error) { + if args[0] == "node" && args[1] == "--version" { + return nil, errors.New("version unavailable") + } + if args[0] == "node" { + require.Equal(t, "ui", dir) + require.Equal(t, []string{"node", "node_modules/vitest/vitest.mjs", "run", "--reporter=verbose", "fixture.test.ts"}, args) + } + return successfulCommand(ctx, dir, env, args) + } + require.NoError(t, run([]string{"run", "-race", "fixture"}, io.Discard, io.Discard, execute)) + runs, err := os.ReadDir(reportsDir) + require.NoError(t, err) + require.Len(t, runs, 1) + data, err := os.ReadFile(filepath.Join(reportsDir, runs[0].Name(), "report.json")) + require.NoError(t, err) + var report runReport + require.NoError(t, json.Unmarshal(data, &report)) + require.Equal(t, "node --version: version unavailable", report.Toolchain["node --version"]) + require.Len(t, report.Cases, 1) + require.Equal(t, "pass", report.Cases[0].Status) + require.Len(t, report.Cases[0].Steps, 2) + require.Equal(t, []string{"go", "test", "-race", "-mod=readonly", "-count=1", "-timeout=90s", "-json", "-run", "^(TestReady)$", "./fixture"}, report.Cases[0].Steps[0].Command) + require.NotContains(t, report.Cases[0].Steps[1].Command, "-race") +} + +func successfulCommand(_ context.Context, _ string, _ []string, args []string) ([]byte, error) { + if args[1] == "test" { + return []byte("{\"Action\":\"pass\",\"Test\":\"TestReady\"}\n"), nil + } + return []byte("fixture-output\n"), nil +} + +func TestRunStepReportsLogAndCancellationErrors(t *testing.T) { + step := testStep{"./fixture", []string{"TestReady"}} + dir := t.TempDir() + cannotLog := runStep(t.Context(), successfulCommand, step, nil, dir, false) + require.Equal(t, "fail", cannotLog.Status) + require.NotEmpty(t, cannotLog.Error) + + ctx, cancel := context.WithCancel(t.Context()) + cancel() + canceled := runStep(ctx, successfulCommand, step, nil, filepath.Join(dir, "case.log"), false) + require.Equal(t, "fail", canceled.Status) + require.Equal(t, context.Canceled.Error(), canceled.Error) +} diff --git a/ui/src/data/__tests__/convertedRecording.integration.test.ts b/ui/src/data/__tests__/convertedRecording.integration.test.ts index 314ce0789..27393414f 100644 --- a/ui/src/data/__tests__/convertedRecording.integration.test.ts +++ b/ui/src/data/__tests__/convertedRecording.integration.test.ts @@ -1,20 +1,19 @@ /** - * End-to-end check that a recording converted by `python/convert_recording_gear.py` - * decodes and replays through the real UI code path: the JSON decoder, the event - * manager's diff reconstruction, gear categorisation, the display-name derivation - * and both Arsenal exports. + * Optional comparison for the historical gear migration. It decodes both + * recordings and compares the reconstructed snapshot chains, gear categories, + * display names, and both Arsenal exports. * * It also rebuilds the *original* recording's snapshot chains and compares them * against the converted ones, so a conversion that silently lost gear fails here * rather than in the browser. * - * Both files are large local artifacts, so the suite skips itself when they are - * not present. Point it somewhere else with OCAP_TEST_RECORDING / _V2. + * Set OCAP_TEST_RECORDING and OCAP_TEST_RECORDING_V3 to the original and + * converted local artifacts to run this corpus-specific comparison. + * The synthetic snapshot replay integration runs without these artifacts. */ import { beforeAll, describe, expect, it } from "vitest"; import { existsSync, readFileSync } from "node:fs"; import { gunzipSync } from "node:zlib"; -import { resolve } from "node:path"; import { JsonDecoder } from "../decoders/jsonDecoder"; import { applySnapshotDiff, isSnapshotDiff } from "../snapshotDiff"; @@ -38,13 +37,8 @@ import { exportVanillaArsenal, } from "../../pages/recording-playback/arsenalExport"; -const REPO = resolve(__dirname, "../../../../.."); -const ORIGINAL = - process.env.OCAP_TEST_RECORDING ?? - resolve(REPO, "No20Wonder20Conwoy_20260824_210930.json.gz"); -const CONVERTED = - process.env.OCAP_TEST_RECORDING_V3 ?? - resolve(REPO, "No20Wonder20Conwoy_20260824_210930.v3.json.gz"); +const ORIGINAL = process.env.OCAP_TEST_RECORDING ?? ""; +const CONVERTED = process.env.OCAP_TEST_RECORDING_V3 ?? ""; const SNAPSHOT_TYPES: PlayerSnapshotType[] = [ "inventorySnapshot", diff --git a/ui/src/pages/recording-playback/__tests__/snapshotReplay.integration.test.ts b/ui/src/pages/recording-playback/__tests__/snapshotReplay.integration.test.ts new file mode 100644 index 000000000..b471cabb7 --- /dev/null +++ b/ui/src/pages/recording-playback/__tests__/snapshotReplay.integration.test.ts @@ -0,0 +1,144 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { ApiClient } from "../../../data/apiClient"; +import { + Chunk, + EntityType, + Manifest, + PlayerSnapshotSeries, + Side, +} from "../../../data/decoders/generated/ocap.pb"; +import type { InventorySnapshot, Recording } from "../../../data/types"; +import { PlaybackEngine } from "../../../playback/engine"; +import { MarkerManager } from "../../../playback/markerManager"; +import { MockRenderer } from "../../../renderers/mockRenderer"; +import { exportAceArsenal, exportVanillaArsenal } from "../arsenalExport"; +import { categorizeGearItems, filledGearCategories } from "../gearCategories"; +import { loadRecording } from "../loadRecording"; + +const recording: Recording = { + id: "1", filename: "snapshot-replay", missionName: "Snapshot replay", + worldName: "altis", missionDuration: 3, date: "2026-01-01", +}; +const unitId = 7; +const unitName = "Synthetic player"; +const base: InventorySnapshot = { + unitId, load: 0.2, + uniform: { class: "", items: [] }, + vest: { class: "", items: [] }, + backpack: { + class: "B_AssaultPack_khk", + items: [ + { class: "FirstAidKit", cat: "medical", count: 1 }, + { class: "SmokeShell", cat: "grenades", count: 1 }, + ], + }, + headgear: { class: "" }, + goggles: { class: "" }, + weapons: [{ class: "Binocular", slot: "binocular", attachments: [] }], + magazines: [], + assignedItems: [{ class: "ItemMap" }, { class: "TFAR_anprc152_1" }, { class: "Binocular" }], +}; +const changed: InventorySnapshot = { + ...base, + backpack: { ...base.backpack, items: [{ class: "FirstAidKit", cat: "medical", count: 2 }] }, +}; +const bytes = (data: Uint8Array): ArrayBuffer => new Uint8Array(data).buffer; +const engines: PlaybackEngine[] = []; + +afterEach(() => { + for (const engine of engines.splice(0)) engine.dispose(); +}); + +async function open(api: Partial, format: Recording["storageFormat"]) { + const renderer = new MockRenderer(); + const engine = new PlaybackEngine(renderer); + engines.push(engine); + const world = { + worldName: recording.worldName, worldSize: 30720, minZoom: 0, maxZoom: 6, + }; + await loadRecording( + { getWorldConfig: async () => world, ...api } as ApiClient, + engine, new MarkerManager(renderer), { ...recording, storageFormat: format }, + ); + return engine; +} + +describe("player snapshots through recording replay", () => { + it("replays a lazy protobuf diff sidecar like the original full JSON snapshots", async () => { + const original = await open({ + getRecordingData: async () => bytes(new TextEncoder().encode(JSON.stringify({ + worldName: recording.worldName, missionName: recording.missionName, endFrame: 3, + entities: [{ + id: unitId, type: "unit", name: unitName, side: "WEST", startFrameNum: 0, + positions: Array.from({ length: 4 }, () => [[100, 200], 0, 1, 0, unitName, 1]), + }], + events: [ + [1, "inventorySnapshot", base], + [2, "inventorySnapshot", base], + [3, "inventorySnapshot", changed], + ], + }))), + }, "json"); + + const sidecar = PlayerSnapshotSeries.encode(PlayerSnapshotSeries.fromPartial({ + unitId, + events: [ + { frameNum: 1, type: "inventorySnapshot", message: JSON.stringify(base) }, + { frameNum: 3, type: "inventorySnapshot", message: JSON.stringify({ + unitId, + diffOf: 1, + set: { backpack: { items: { + $key: "class", put: [{ class: "FirstAidKit", count: 2 }], del: ["SmokeShell"], + } } }, + }) }, + ], + })).finish(); + const getPlayerSnapshots = vi.fn(async () => bytes(sidecar)); + const converted = await open({ + getManifest: async () => bytes(Manifest.encode(Manifest.fromPartial({ + version: 1, worldName: recording.worldName, missionName: recording.missionName, + endFrame: 3, chunkCount: 1, chunkSize: 4, captureDelayMs: 1000, + snapshotUnitIds: [unitId], + entities: [{ + id: unitId, type: EntityType.ENTITY_TYPE_UNIT, side: Side.SIDE_WEST, + name: unitName, startFrame: 0, endFrame: 3, isPlayer: true, + }], + })).finish()), + getChunk: async () => bytes(Chunk.encode(Chunk.fromPartial({ + frameCount: 4, + frames: Array.from({ length: 4 }, (_, frameNum) => ({ + frameNum, entities: [{ entityId: unitId, posX: 100, posY: 200, alive: 1 }], + })), + })).finish()), + getPlayerSnapshots, + }, "protobuf"); + + expect(getPlayerSnapshots).not.toHaveBeenCalled(); + await Promise.all([ + converted.ensurePlayerSnapshots(unitId), + converted.ensurePlayerSnapshots(unitId), + ]); + expect(getPlayerSnapshots).toHaveBeenCalledExactlyOnceWith(recording.filename, unitId); + + for (const [frame, expected] of [undefined, base, base, changed].entries()) { + const read = (engine: PlaybackEngine) => + engine.eventManager.getPlayerSnapshots(unitId, frame).get("inventorySnapshot")?.payload; + expect(read(original)).toEqual(expected); + expect(read(converted)).toEqual(expected); + } + + const gear = converted.eventManager.getPlayerSnapshots(unitId, 3).get("inventorySnapshot")?.payload as InventorySnapshot; + expect(filledGearCategories(categorizeGearItems(gear.backpack.items))).toEqual(["medical"]); + const vanilla = exportVanillaArsenal(gear); + expect(vanilla.split("\n")[0]).toBe('comment "Exported from OCAP";'); + expect(vanilla.split("\n")).not.toContain(""); + expect(vanilla).toContain('this linkItem "TFAR_anprc152";'); + expect(vanilla).toContain('this linkItem "Binocular";'); + expect(vanilla).not.toContain("SmokeShell"); + const [loadout, extended] = JSON.parse(exportAceArsenal(gear)); + expect(loadout[5]).toEqual(["B_AssaultPack_khk", [["FirstAidKit", 2]]]); + expect(loadout[8][0]).toBe("Binocular"); + expect(loadout[9]).toEqual(["ItemMap", "", "TFAR_anprc152", "", "", ""]); + expect(extended).toEqual([]); + }); +});