small gleam coding and persistent agent daemon with a detachable cli and a canvas ui forked from okami.mom/albedo
albedo robot-docs testing.md
27 kB · 470 lines
Markdown
at main

Test execution #

test.sh is the pre-commit gate. With no arguments it selects Python end-to-end scenarios affected by the change and runs Go end-to-end tests for CLI changes. ./test.sh --full runs all end-to-end scenarios and the web check. Manual tests under test/manual are opt-in.

Run repository scripts from the repository root inside nix develop. Run the daemon's gleam test from apps/albedo, or use nix develop -c sh -c 'cd apps/albedo && gleam test' from the root.

The kernel state upgrade scenario can run the replacement daemon’s kernel on a second CPython minor. Set ALBEDO_TEST_UPGRADE_PYTHON to its absolute interpreter path, with the locked kernel dependencies installed, when running the scenario or the full gate. Without that setting the test exercises different and missing writer tags on the development shell’s interpreter.

Test tiers #

The test policy puts each check in the cheapest tier that can observe its defect. This table maps a tier to where it runs.

Tier What it checks Where it lives Gate suite
1. Pure logic One function, by example or property apps/albedo/test, each package's test/, Go _test.go, native/render gleam test, workspace packages, go test, the cargo test before the suites
2. State machines in process Operation sequences against a model the same places the same suites
3. Contracts across a boundary One language's encoder against another's decoder test/contract contracts
4. The real daemon Wiring only the assembled system has e2e, cli/test/e2e python e2e, go e2e

Fake daemons in Go #

A Go test that stands in for the daemon starts its fake with testwire.NewDaemon. Every exchange is checked against docs/openapi.yaml: the route, its query and required header parameters, the request body, the status, and the JSON, problem, or SSE response. A drift fails the test at cleanup. So a client request the daemon would refuse fails in the unit test, and a fixture cannot drift from what the daemon sends. Answer refusals with testwire.WriteProblem. The Go end-to-end suite checks its requests to the real daemon with the same checker through Checker.Transport.

Use a plain httptest server only for a fake that answers what no daemon sends on purpose, such as a malformed batch, an older protocol, or an extension route that the contract leaves to its declaration. Say so in a comment.

Seeds and budgets #

Every property library runs under one convention, through its own mechanism:

  • ALBEDO_PROPERTY_SEED unset runs the gate's fixed seed, so the gate tries the same cases on every run. random draws a fresh seed. An integer runs that seed.
  • ALBEDO_PROPERTY_CASES sets the cases per property. Unset, each property runs its own small gate budget.
  • A failure prints the seed with the shrunk counterexample, so the log alone reproduces it.
  • A check that a model's generator reached the interactions it is about is tuned to the gate's seed and budget. Enforce it only there; another seed that misses an event has found no defect. In Go, property.AtGate reports that run.

The libraries are the ones the project allows. Do not add another, and do not call one except through its wrapper. test/property_wrappers.py, run by test/quick.sh, refuses both. The test policy says when a test must be a property.

  • Gleam: albedo_property.run wraps qcheck.run and takes the property's gate budget. Add albedo_property and qcheck under a package's [dev_dependencies], then run test/packages.sh sync <name> to lock them. Its failure message starts with ALBEDO_PROPERTY_SEED=<n> ALBEDO_PROPERTY_CASES=<n>. A property or model that outlasts eunit's default limit returns albedo_property.within(seconds, body) from a function named ..._test_, rather than building eunit's timeout tuple itself. Draw operation histories for a model with albedo_property.sequence(choices, min, max), not qcheck.generic_list over qcheck.from_weighted_generators: qcheck chains each case's seed into the next, so a gate budget sees fewer histories and fewer operation values.
  • Python: import test/hypothesis_profiles.py before using Hypothesis. It loads the gate profile, derandomized with no example database, or the discovery profile, with its example database under $ALBEDO_TEST_TMP/hypothesis and never in the tree. Set a smaller gate budget with @settings(max_examples=hypothesis_profiles.cases(n)). Hypothesis is a test-only dependency group of the kernel project. The development shell's python3 has it, and the shipped kernel environment does not (python/package.nix).
  • Go: call property.Check in place of rapid.Check, and import it only from _test.go files. It maps the variables to rapid's -rapid.seed and -rapid.checks, which win when given, and turns off rapid's fail files. rapid prints the seed and the shrunk value.
  • Web: call check from web/scripts/property.mjs with a fast-check property and its gate budget, in place of fc.assert. It maps the variables to fast-check's seed and numRuns. fast-check is a development dependency of web/package.json and never reaches the build.
  • Rust: build a property's config with crate::property::config(gate_cases) from native/render/src/property.rs. It sets proptest's rng_seed and cases and turns off proptest-regressions files. It prints the seed, which cargo test shows only for a failing test.

Counterexamples #

Commit each shrunk counterexample as a named example test beside the property, in the cheapest tier that fails on it. Do not commit a library's own failure store: Hypothesis's database, rapid's testdata/rapid fail files, or proptest's proptest-regressions. A later generator change may stop producing the case, and the named test still checks it.

Cross-language contracts #

test/contract/run.py checks each wire format that two languages share. The gate runs it as the contracts suite. Run python3 test/contract/run.py [contract ...] from the repository root inside nix develop.

Each side runs one peer process for the whole run, and generated cases cross in batches, one round trip per batch:

The two peers frame each JSON message with a 4-byte length. support.py describes the requests. Shrinking also runs against the live peer. The runner loads beams from test/beams.py. That module returns the gate's daemon snapshot when ALBEDO_TEST_DAEMON names one. Otherwise it builds the checkout through albedo-build first. Use it in any test that runs its own erl, so a test never loads beams older than the source.

The kernel_frames contract checks the kernel link. The daemon's frames come from wire.encode inside wire.envelope (wire.gleam). The kernel reads them as its link session does, with albedo_link.read_frame and albedo_protocol.parse_incoming. The kernel's packets come from albedo_link and are read by wire.decode and frame.read. The contract checks four things:

  • The kernel accepts every daemon frame and packet. Its re-encoding reads back as the same value.
  • The daemon reads every kernel frame type with its sequence, ack, kind, and binary payload. The frame's value survives the daemon's decode and encode.
  • A daemon frame with a required field missing or mistyped, an unknown type, a cut, or an oversized length is rejected by the kernel. The kernel does not crash on it.
  • No packet a kernel never writes crashes the daemon's reader. Such packets include truncation, wrong binary sizes, NaN, lone surrogates, deep nesting, and trailing bytes.

The similarity contract checks that similarity.at_least answers as difflib.SequenceMatcher(None, a, b).ratio() >= threshold does, autojunk included, at and on either side of each pair's ratio. Repetition detection depends on that ratio.

The openapi_encodings contract checks the daemon's wire encoders against docs/openapi.yaml. Its Gleam side, openapi_encodings.gleam, generates session events across their variants and sends each batch with the component schema it claims. The Python side hands the batch to one Go process, wirecheck, which validates with the same testwire.Contract the Go end-to-end suite uses for live responses. Extend its generators when an encoder gains a variant or a field.

The skill_mentions contract checks that the TUI and web composers offer skill completion exactly where the daemon reads a mention (mentions.gleam). Its Python side, skill_mentions_test.py, generates drafts of fences, indented code, inline code, escapes, and astral text that end in a typed mention. The Gleam peer answers which completed names the daemon reads, and one Go process (mentioncheck) and one node process (skill-mentions-check.mjs) answer where each composer offers completion, in runes and in UTF-16 units.

To add a contract, follow these steps:

  1. Give it a Gleam module under apps/albedo/test/albedo/contract/, with its properties and its ops, and list both in runner.gleam.
  2. Add a Python module test/contract/<name>.py with PYTHON_OPS and its strategies.
  3. Add a test/contract/<name>_test.py file for the Python-driven direction.

Do not name a Gleam contract module _test. gleam test would then start the peers inside its build lock.

Discovery runs #

test/discovery.sh runs the property suites with fresh seeds and a large budget until a time budget runs out: test/discovery.sh [seconds] [cases]. The defaults are one hour and 2000 cases per property. The suites are gleam test, the workspace packages, the contracts, the renderer, the web and Photon bridge properties, the Linux HEIC converter, the selected Python suites that import hypothesis_profiles, and the Go packages that import property. Each round sets one integer ALBEDO_PROPERTY_SEED for every suite. A failing suite's log stays under /tmp/albedo-discovery/<start>/ with a summary.txt that names its seed. The gate does not run it. Turn each confirmed failure into a named regression test and a fix.

Gate and resource limits #

test/quick.sh runs formatting, type, lint, generated-code, and Go vet checks before the suites. It also builds each workspace package with warnings as errors, and the gate runs each package's own tests as a suite. The gate builds a daemon snapshot and launches suites concurrently. Its end-to-end selection and web checks depend on the changed paths or --full. See test.sh for that selection and Gleam lint for lint profiles.

The snapcompact tests in gleam test render frames through albedo-render. The daemon looks for it in apps/albedo/priv/bin, then on PATH. The gate installs it with native/render/install.sh before its suites. When gleam test runs alone and finds no renderer, its entry point, apps/albedo/test/albedo_test.gleam, runs that script first. The script needs cargo from nix develop. Run it again after changing native/render, because gleam test does not rebuild a renderer that is already installed.

test/resources.py calculates concurrency limits from CPU and available memory. It reserves one quarter of memory and gives half of the rest to end-to-end lanes. A lane is one test on the shared daemon, two exclusive daemons, and one Go scenario. E2E_LANE_MEMORY is what one lane adds to the gate's peak, and the plan rejects a host where one lane does not fit. End-to-end lanes follow the host's processor count because they mostly wait on daemons. Gleam modules and builds follow the cgroup's CPU quota, since many Gleam tests wait a fixed time for an event and miss it when far more modules run than the quota can schedule. ALBEDO_TEST_*_JOBS variables can override the calculated limits. These limits control concurrency, not process memory allocations.

Measure the gate before changing a cost in the plan:

  1. Set every ALBEDO_TEST_*_JOBS variable to the plan under test, such as CI's test plan: line with a different lane count.
  2. Put TMPDIR and ALBEDO_TEST_TMP under /dev/shm, as CI does.
  3. Run each suite of ./test.sh --full in its own cgroup, for example through systemd-run --user --scope, and sample each cgroup's memory.current.
  4. Compare the gate's peak at two or more lane counts.

A cgroup counts the detached daemons and the tmpfs scratch that a sum of the suite's process tree misses. Gleam lint runs in test/quick.sh before the suites start, so its peak does not add to theirs. See Gleam lint memory.

The suites start together, so the gate's peak memory is what they all hold at that moment. CI's workflow puts TMPDIR and ALBEDO_TEST_TMP under /dev/shm, so scratch files use the same memory. Do not let a test start background work that it does not check. For example, dev-proxy.test.mjs loads only the server options from vite.config.ts. With the config's plugins, Vite pre-bundles the client's dependencies when its server starts, and CI's fresh node_modules has no cache for that work.

A test signals only processes it can show are its own: a pid it started, or a command line that names its own scratch directory. Suites run side by side, and other gates may share the machine, so a pattern such as pkill -f albedo_transfer_relay ends other tests' work mid-call. The move scenarios drop their relays with drop_relays in _transfer_support.py, which matches the loopback host's home.

Stalls in daemon logs #

A test that times out on a loaded machine needs evidence of where the time went. Every daemon starts the stall monitor in stalls.gleam, which logs stall: lines beside the store's warnings for a slow commit (store: committing ... took N ms) and a slow query (store: one query held the store N ms):

  • A long garbage collection or a long schedule names the process, by its label where it has one.
  • A busy port or busy distribution port names the port.
  • the monitor woke N ms late means nothing in the VM ran for that long, because the host did not schedule it (an oversubscribed runner, a suspended process, swapping) or the VM's schedulers were all busy.

A slow store line next to a late wake waited on the host. One without any stall: line is the query or the disk. Each window logs at most ten lines and then counts what it left out. Read the failing test's daemon log before changing a deadline.

The shared home in gleam test #

albedo_test_runner runs test modules in parallel in one VM, and albedo_test_home gives them all one ALBEDO_HOME, with a HOME inside it. Every module reads that home's saved settings. A composition preparation that keys a session's saved settings refuses when they change under it, by design (see preparation and kernels), and its waiters get "composition inputs changed" with no kernel booted. A module that saved settings there would fail other modules' preparations at random.

So no module may write settings in the shared home. A module that saves settings gives itself a private home: pass a temporary directory as the home argument, as configuration_test and turn_harness do, or run in a disposable VM with its own ALBEDO_HOME, as settings_update_test does for code that reads only the environment. Do not change ALBEDO_HOME or HOME in the shared VM.

When the run ends, albedo_test_home looks for the settings documents (config.json, extensions.json, capabilities.json, creds.json, settings-revisions.json, hooks.json, and the .settings-recovery record) in the shared home, and for .albedo, .agents, AGENTS.md, and CLAUDE.md in its HOME. The run fails and names any it finds, even when every test passed, so a writer is caught on the first run rather than by a rare timing. Do not retry a refused preparation to hide the race.

Expected reports in gleam test #

Some tests provoke failure paths on purpose, and the daemon code they drive logs those failures. A passing run prints these lines, each from the named test:

  • listener was killed, listener did not start: port taken, and giving the listener up come from a_bounded_listener_stops_after_its_failed_restarts_test in listener_test. listener was killed also comes from a_killed_listener_comes_back_on_its_port_test_ there, with the crash reports of the mist tree it kills.

  • kernel_cleanup_failed with plugin cleanup did not finish within 1.5 s comes from hard_timeout_requires_explicit_reset_test in runtime_test. Its cell holds the kernel's event loop, so plugin cleanup cannot start.

  • owner_lost with kernel ownership cleanup was not confirmed comes from tests that end a kernel's owner: owner_loss_* in owner_supervision_test and runtime_killed_with_a_queued_reload_result_retires_the_kernel_test in runtime_ownership_test. Only the owner can forget the kernel's record. The last test also prints reload for a stopped runtime: with either that reason or kernel lost before its processes could be supervised, depending on whether the driver handles the stop or the owner's death first.

  • spare warmup outcome is unknown comes from an_unknown_spare_allocation_retains_budget_without_blocking_stop_test, and kernel cleanup late-cleanup: unconfirmed from late_cleanup_success_keeps_another_generations_failure_and_retry_test, both in runtime_ownership_test.

  • kernel_unresponsive and kernel_wedged for the kernel model come from the unresponsive-kernel scenarios in driver_model_test, which end a stand-in sleep process on purpose.

  • notes: scripted failure comes from notes_follow_what_each_compaction_evicted_test in notes_test, whose summarizer fails some rewrites on purpose.

This list covers the listener, kernel lifecycle and notes reports. When one of them comes from a different test, or a new one appears, find the test that printed it before treating it as expected.

Fixture teardown #

e2e/harness.py owns test daemons and fixtures. peer_daemon(name, prepare=None) starts a separate daemon for a test. finish_test cleans up peers and registered resources. Use the shared harness for daemon scenarios. See storage migrations for upgrade coverage.

A test daemon stops when the suite that started it exits, through ALBEDO_PARENT_PID. A daemon that a scenario installs as a service drops that variable, so the scenario's own cleanup must stop it. When the gate ends, test/reap-daemons.sh waits for detached kernels to finish their grace period, then stops any process still running from the gate's snapshot and fails the gate, naming each process's ALBEDO_HOME. Fix the scenario that owns that home. Run the script on the scratch root to clear processes left by an interrupted run. That also stops the daemons of a gate still running in another checkout.

Mixed-version moves #

move_versions_test.py runs this checkout's daemon beside an older reference daemon. Both run as peer daemons. Moves are real ones, over the loopback ssh that move_test.py uses. Each source session has a transcript, kernel cells, a memory note, a work item, a vent, a delivered webhook letter, a schedule, and a workspace link.

  • A move from the reference to this daemon is the supported path. The scenario finishes the checklist, then checks the carried data and runs a cell and a turn on the target.
  • A move from this daemon to the reference must be refused cleanly. The scenario adds a column to sessions first, so the refusal does not depend on how far the pin lags. The reference predates POST /transfers/check, so the preflight must still offer the move. The move must then fail at staging with transfer_target_older and the reference's detail, leaving no receipt or staging directory there. The scenario then checks for no session on the reference, and a source session that keeps its schedule and takes input. move_test.py covers the check against a target of this build.

The rules these scenarios check are in moves between versions.

test/reference-daemon.sh pins the reference commit in REFERENCE. Albedo has no release tags, so the pin is a commit on main. The script extracts it with git archive, builds it with that commit's own test/snapshot-daemon.sh and its CLI, and prints the directory. It fetches the commit first when a shallow clone lacks it. Builds are cached under ALBEDO_REFERENCE_CACHE, which defaults to ~/.cache/albedo-reference, one directory per commit. A cold build took 37 s on a developer machine with warm Hex and Go module caches. A cached run returns at once. CI keeps the directory in its albedo-reference cache, keyed by the script, so ./test.sh --full builds it once per pin.

Bump the pin when a commit that users run lands, such as one deployed to another host, or when the reference falls back past a transfer protocol change.

  1. Set REFERENCE to the full commit hash.
  2. Run nix develop -c python3 e2e/run.py move_versions_test.py downgrade_test.py.
  3. Report a failure of the supported move as an incompatibility between the two builds. Do not loosen an assertion to make it pass.

reference_support.py builds the reference on first use. Its run_reference points a test daemon's next boot at the reference daemon and CLI. downgrade_test.py uses it to restart a home this checkout upgraded on the reference build, and checks that the reference reads a session this checkout wrote. A rollback across a breaking migration is not supported, so bump the pin past each new breaking migration. See downgrades.

areas.toml selects the file for changes to transfer code, adapters, migrations, and the core tables in conversation.gleam and mail.gleam. A schema change in another owner reaches it only through ./test.sh --full. Run it directly after adding a column or table that a transfer carries.

Antigravity upstream #

Antigravity sends to one fixed Google route, which no loopback fake can stand in for. antigravity_upstream_test drives the real adapter in process instead, through resolve_with: a scripted send records each exchange the encoder produced and answers it with Cloud Code Assist frames, which the real stream reducer reads, or with a failure status and body. The test checks the route, identity headers, request counter, signed tool replay, the one portable resend after a refused cross-effort replay, title requests, limit marks, and suspension. The daemon's transcript persistence and restart replay are generic, and the provider protocol scenarios cover them. Fixture signatures check preservation, not Google's cryptographic validation. OAuth, Google TLS, live quotas and acceptance of genuine signatures need live checks under test/manual.

Manual web review #

Use the UI review kit for seeded browser reviews, scenario helpers, evidence capture, and private-resource cleanup. These manual checks are separate from the automated gate.