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

Change Albedo #

These project rules guide implementation changes. The linked feature pages describe current behavior and its limits.

Use Marmot for database access #

Define each query in a Marmot SQL source beside its owning feature. Use its generated operation directly. Put reusable execution behavior in the shared store or generator. Do not embed SQL in application code, handwrite query callers, or build per-feature query orchestration. Keep each extension's SQL, generated bindings, schema, and migrations in its own package.

Preserve the transaction or snapshot required by the operation. When generation cannot express a required operation, address the gap in the shared tooling and verify the database behavior. Track existing raw paths as unfinished migration work. See Generate typed queries.

Choose the owning layer #

Core modules under apps/albedo/src/albedo are grouped by subsystem. The repository map names their owners. Keep session coordination in session, transcript operations in history, and table operations and migrations in storage. runtime schedules preparation and kernel work, composition builds extension selections, and model_loop runs model/tool steps. http adapts those services to requests; lifecycle owns daemon boot, standby, and build identity. Workspace host services live in workspace. Tests under apps/albedo/test/albedo follow these owners. Integration tests that compose extracted extensions stay in the application's composition tests.

Add capabilities through typed plugins. Keep HTTP admission and wire encoding in daemon adapters, composition and kernel lifecycle in the runtime, and feature state with its owning extension. The interfaces are defined in extension.gleam.

Use the command's Context.state operations, typed SDK session operations, or supplied session callbacks to reach session behavior. Do not mutate a session's state from an extension. Resolve cross-extension dependencies from the applicable active selection, using host.Context or extension.Daemon rather than a captured installation registry. Declare each context capability the extension reads in its uses, and only those, as extension capabilities describes. See commands and extensions.

Add an actor when ordering, concurrency, or resource lifetime requires one. A plugin declaration alone does not require a process.

Write Gleam and keep values typed #

Write new code in Gleam, including process state, monitoring, actors, validation, and binary operations. Use gleam_erlang, gleam_otp, and the SDK helpers. Keep Erlang only for what Gleam cannot express, such as catching exceptions, opening ports, or an OTP call with no Gleam library, and keep that Erlang a thin binding with its reason in a comment. Keep policy and orchestration in Gleam. When a change touches an Erlang module, move what Gleam can express in the same change. Keep typed values through internal operations and encode JSON at the wire boundary. Do not encode an observation to JSON and parse it again to add fields. See command.StateOp.

Tests follow the same rule. Write a test, or a test support module, in Gleam, with @external bindings for the OTP calls it needs. Do not -include a generated Gleam record header in Erlang, and do not build or match a Gleam value as a positional tuple there. gleam build does not recompile an Erlang file when only the header it includes changes, so after a record change the test runs a stale module and fails with badrecord. A Gleam module that reads another process's mailbox coerces each message to its Gleam type and matches the constructor, so the compiler keeps it in step with the type.

Carry a refusal as a typed value from the place that decides it. Daemon operations return a Refusal variant, and refusal.failure is the only place that chooses its HTTP status, problem code and sentence. A storage or dependency failure that no caller treats specially travels as Unavailable. Do not branch on the text of an error, and do not build a Failure from a code string. Add a variant when a caller needs to tell the failure apart. The albedo_text_decisions lint refuses a search, a literal case arm, or a literal comparison on a value named like an error or a message. A module that decodes outside text once, such as a provider wire, is listed in the rule's edges with the reason.

Keep unfinished-output projection policy in active_output.gleam. Its spill store owns file operations. Do not reconstruct output by replaying events when a typed projection is available.

Keep reusable code in workspace packages #

Code with no dependency on albedo that other projects could use, such as a wire protocol, can live in a workspace package under packages/. A package never imports albedo. Keep albedo policy in the albedo module that calls it. Packages are layered: a package depends only on layers below its own, and nothing but albedo depends on an extension package. Run test/packages.sh check after changing a package or its gleam.toml, and re-lock a refused manifest with test/packages.sh sync, never by hand. Rebuild before attaching a CLI to test package changes. The build identity covers every runtime application.

Keep a package.nix beside every first-party gleam.toml. Call the shared mkGleamPackage helper and keep package overrides colocated. Discovery imports only that filename under apps, packages, extensions, and tools. Reuse the shared Hex build and production library graph. Never seed the package under test or include dependency tests in production library inputs. See workspace Nix builds.

The SDK is the package albedo_sdk, and its modules are albedo_sdk/* (current packages). A module moved out of albedo's src/ with its name kept leaves a stale beam in albedo's build directory. The daemon launchers rebuild it, but a bare gleam run or gleam test loads it, so run gleam clean once after pulling such a move (how albedo consumes a package).

Reuse runtime helpers #

For extension imports and native bindings, follow the SDK import contract. Keep shared extension helpers in the SDK, packages/albedo_sdk, and call their Gleam APIs.

Use albedo_clock for timestamps and deadlines. Use system time for durable timestamps and monotonic time for elapsed durations. Request an explicit native time unit. Keep a scaled test timer and the deadline it checks consistent.

Use albedo_bytes/scalars for scalar-bounded previews and names. Do not allocate a codepoint list for the entire input just to truncate a prefix. Scalar limits and grapheme limits serve different purposes.

Take a token estimate from size. The albedo_token_estimates lint refuses a length divided by 3 or 4, and an estimate_* function, anywhere else.

Use shared for long-lived immutable values shared across processes. Release a handle at the end of its owner's lifetime. Do not turn changing provider caches into repeatedly replaced compound persistent terms. Use albedo_process/memo for changing per-key caches with expiry. Capture compact arguments in stored callbacks rather than the whole actor state. session_namespace.watch_kernel demonstrates that pattern.

A process that waits after handling large binaries keeps them referenced until its next collection, and a waiting process does not collect. Call albedo_process.collect_over where such a process goes idle. The SQLite reader pool does so after each read, and sdk/worker.receive before each wait.

Do not rebuild a value from a turn's whole history on every request: result_view.request_entries hands back the tool output views it rendered, and the model loop passes them to the next request. The context scenario in the performance harness measures what a turn costs per megabyte of request.

Use albedo_process/actor_call.try_call for finite monitored waits. A timeout does not cancel accepted work. Keep inner waits within their callers' deadlines so the inner failure can be returned. Use a lifetime protocol when the caller must wait for a definite outcome or owner death.

Use albedo_process/within.run for work that is not an actor call and whose time a slow disk, a hung mount, or a held lock can stretch. It runs the work on a helper and kills the helper at the deadline, which frees any lock it held; the system call it was blocked in still returns on its own. A daemon route that clients use to find a live daemon must not wait unboundedly on such work. GET /server leaves out the quota readings and the dismissed-notice filter when they take longer than a second and a half, and still fails at once on a real error. The workspace routes refuse a local folder read after thirty seconds.

Preserve extension lifecycle boundaries #

Do not make core depend on extension internals. Core and SDK modules reach extension behavior through plugin contracts in the active composition. The kernel runtime under albedo/kernel is core-owned, and the skills catalog under albedo_sdk/skills/ is SDK-owned. Extensions import only the parts the SDK import contract allows.

Keep discovery read-only. A catalog read must not boot Python, allocate managed resources, execute commands, or contact providers. runtime/catalog.gleam owns discovery, and runtime/preparation.gleam owns preparation work.

Distinguish installed extensions, saved selection, and loaded composition. Use installation for schema and deletion ownership, and the loaded composition for session capabilities. Do not leave callable contributions from a failed bundle. See extensions.

Give each allocated resource a cleanup owner. Use the owned preparation contract when a resource must survive handoff. A resource must establish its lifecycle monitors before reporting readiness, and adoption must finish before publication. Make close callbacks idempotent. sdk/worker.gleam and composition.adopt implement these contracts. Legacy managed callbacks do not acquire them automatically.

Keep kernel replacement in the runtime. When a caller owns a live session, use runtime.apply_change or apply_desired and reconcile the surviving session from either result. Do not add a separate snapshot-and-replace sequence in an HTTP handler. Preserve saved intent on apply failure. A database rollback cannot restore a process that has already stopped.

Before changing reload behavior, identify the selection each handler uses, the owner that closes each resource, and the state retained after failure.

Keep actor handlers responsive #

Keep lifecycle waits and slow work outside session actors. Command handlers must run outside the actor whose state operations they call. A handler that waits on its own actor deadlocks. See commands and session.gleam.

Use store.reading or snapshot for pure observations. Keep mutations and read-modify-write work on the writer through query. Use query_then when an actor must remain responsive while a write commits. Publish the result after commit, not after enqueueing.

Keep SDK mail insertion and stored-image writes on the connection supplied by the feature transaction. Notify clients after that transaction commits.

Inside a snapshot, use the supplied connection for related reads. Do not write, retain the connection, or call Store-level APIs from the callback. Do not wait for capture-reader admission inside the session actor. The separate capture connection exists to avoid that ordering problem.

Reserve runtime producer storage before sending payloads or creating completion relays. Use the public runtime entrypoints instead of sending request messages directly. Keep a request's reservation through deferred work and shared waiters, and tag completion with the applicable generation. Requester withdrawal must remove its waiter without cancelling another requester's shared work.

Count runtime workers from monitored tickets, not session ownership maps. Keep cleanup capacity separate from public preparation and observation. Reserve cleanup bookkeeping before resource allocation. A stale generation still consumes computation capacity until its worker settles; an unconfirmed cleanup retains its resource callback and cleanup credit afterward. Preserve the runtime's failed-stop fencing and result acknowledgment protocol. See the runtime admission contract.

Register stop_before_close for resources that read the store on their own schedule. The stop callback runs on the writer and must not call the store. Keep resource shutdown within the store's lifecycle. See store.gleam.

store.close returns once every connection of the store is closed, so the next open or the startup check finds the database's files final. Close a SQLite connection you open yourself with albedo_sqlite.close, from the process that ran its queries. A process that runs queries on a connection another process owns, such as a session actor running a capture on a lent reader, calls albedo_sqlite.release before it hands the connection back, since the owner's close collects only the owner's garbage. Do not use sqlight.close. It leaves a connection open while a statement waits for the garbage collector. If that is the database's last connection, its close removes the -shm and -wal files later, while other code may be reading them. Collecting garbage just before sqlight.close does not fix this: the VM runs the finalizers a collection queues on a scheduler, after the close may have started.

For schema changes, preserve the foreign-key indexing rule. Unindexed child lookups can make deletion block the writer.

Keep the constructor names, field order and arity of every type stored as an external term, and load the modules that name its constructors before a safe decode. See persisted terms.

Decide whether each migration is additive or breaking, and declare it. Prefer an additive change. A breaking migration makes every older build refuse the home, so users can roll back only by restoring a backup. Never rename a recorded migration or drop its name. See downgrades.

Preserve client conventions #

Use lowercase for settings titles, navigation, controls, and status labels. Preserve the spelling of service names, acronyms, and user-entered values. Give the same destination the same name in the web and terminal clients. Name the service once on its row, such as Honcho. Use a separate action, such as sign in, on the button or keyboard hint.

For terminal screens, follow Add or change a terminal screen. Reuse the shared layout, filtering, confirmation, and request-generation contracts. Check the result visually using the repository's UI review instructions.

Preserve provider and retry boundaries #

Keep ModelProviderPlugin, ModelContext, and Upstream as the provider boundary. Shared request and replay types belong in the albedo_model package, and the shared OpenAI-compatible wire in albedo_openai. Provider identity, signing, file handling, and body repair remain provider-owned. Reuse shared codecs and transport where they fit.

Keep credential recovery separate from request encoding. Preserve the error variants, cancellation behavior, usage, and account attribution used by recovery. Do not add another broad retry loop around the existing model-loop and transport retries. See authentication and provider requests.

After an interrupted or uncertain operation, inspect its receipt or effects before retrying. A missing answer does not establish that the operation did nothing. Keep operation identity across retries where the admission contract requires it.

Handle uploaded files #

Treat client-side attachment checks as convenience. The daemon validates names, encoding, counts, and sizes again and decides admission. Build storage paths from daemon-owned identity, such as the session, input ID, and content hash. Do not use the uploaded filename as a path component.

Record attachment metadata in the submission that owns the message. Do not infer that a message had an attachment from text that looks like a label. Do not resend changed attachments under an old input ID. A transcript can outlive the saved bytes, so do not promise that a file named in history is still readable. See saved pastes and uploads and the web client's attachment rules.

Test the observable change #

Put each check in the cheapest tier that can observe the defect, as the test policy describes. Plant the defect a test claims to catch and confirm it fails. Fix a product bug a test finds rather than weakening the test. Use the shared real-daemon harness for wiring that exists only in the assembled system. Do not copy daemon startup plumbing into a test. Keep upgrade scenarios while their old formats remain supported. See testing and migrations.

Write tests of logic as property or model tests through the project's property wrappers, as the property frameworks rule describes. Keep hand-picked examples for named regressions. Do not add tests that only restate constants, copy, or record plumbing. Keep live-provider experiments under test/manual.

Run the relevant checks before submitting a change. Keep generated audit and benchmark reports under /tmp. Retain a measurement in documentation only with its fixture, revision, environment, command, and result artifact. See Gleam checks and performance checks.