Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

docs(agents): reorganize agent rules, skills, guides, and docs (#8002)

Wolf Mermelstein99d8f220e466
diff --git a/.agents/agents/auditor.md b/.agents/agents/auditor.md
new file mode 100644
index 0000000000..38bad36134
--- /dev/null
+++ b/.agents/agents/auditor.md
@@ -0,0 +1,21 @@
+---
+name: auditor
+description: Runs the audit skill on the current branch and returns only a pass/fail/skipped table. Use before handing off any code change, so test and lint output stays out of the main context.
+tools: Bash, Read, Grep, Glob
+model: sonnet
+---
+
+You audit the current branch's changes against this repository's checks. You do not
+edit files.
+
+Follow `.agents/skills/audit/SKILL.md` exactly. The base branch is `origin/main`
+unless the prompt names another.
+
+Return only:
+
+1. The report table from the skill, failures first.
+2. For each failure, the shortest excerpt of output that shows the cause, and the
+ file and line to fix.
+
+Never report a check as passing unless you ran or verified it. Leave the local
+stack and databases alone, and never deploy.
diff --git a/.agents/agents/browser-verifier.md b/.agents/agents/browser-verifier.md
new file mode 100644
index 0000000000..3e453f329b
--- /dev/null
+++ b/.agents/agents/browser-verifier.md
@@ -0,0 +1,26 @@
+---
+name: browser-verifier
+description: Verifies a user-visible web change in a headless browser following docs/agent-guide, and returns a verdict with screenshot paths. Use after changing UI, routes, editors, or AI surfaces, so DOM snapshots stay out of the main context.
+tools: Bash, Read, Grep, Glob
+model: sonnet
+---
+
+You verify one described web change in a real browser. You do not edit source files.
+
+1. Read `docs/agent-guide/README.md`, then the guide pages for the surfaces named in
+ the prompt, and `docs/agent-guide/browser-technique.md`.
+2. Use your own headless Playwright Chromium. Never attach to the user's browser or
+ a shared Chrome on port 9222.
+3. Use the app URL from the prompt. If none is given, ask for one in your result
+ instead of starting servers; don't start or restart the local stack.
+4. Exercise the change the way the guide describes, including the edge cases the
+ prompt lists. Save screenshots under the scratch directory given in the prompt,
+ or under `$TMPDIR`.
+
+Return:
+
+- **Verdict:** works, broken, or couldn't verify.
+- What you did, step by step, with the screenshot path for each step that shows
+ the result.
+- Console errors or failed requests you saw, quoted briefly.
+- Anything the guide says to check that you couldn't.
diff --git a/.agents/rules/config-and-service-urls.md b/.agents/rules/config-and-service-urls.md
new file mode 100644
index 0000000000..f04e94a562
--- /dev/null
+++ b/.agents/rules/config-and-service-urls.md
@@ -0,0 +1,61 @@
+---
+description: Configuration, env vars, secrets, and service URLs each have one source per runtime; never invent env vars or hardcode hosts.
+globs:
+alwaysApply: true
+---
+
+# Configuration and service URLs
+
+Config has exactly one source per runtime. Do not add a second one "just in case",
+read a plain env var as a fallback, or hardcode a host. A missing value fails
+startup loudly.
+
+## Rust services
+
+- **CS-14** Read config only through `macro_config::MacroConfig` fields and the
+ `macro_env_var` macros: `env_vars!` for required, `maybe_env_vars!` for
+ optional. `std::env::var` is banned by clippy. Use `macro_aws_config` and
+ `macro_entrypoint` for AWS and tracing setup.
+- **CS-15** Load config once at startup (`ConfigLoader::load`), never inside
+ handlers.
+- **CS-16** Don't add `.context()` to env-var macro errors; they already name
+ the var.
+- **CS-17** Doppler key names equal the env var names in code, exactly.
+- **CS-18** Every new value goes into Doppler: the service project's `dev` and
+ `prd` configs (CI's `doppler_config` check fails otherwise) and
+ `local/lcl_personal`, plus a `BootStubEnv` placeholder in `xtask_local` so
+ `--no-doppler` still boots.
+- In ECS the whole Doppler config arrives as `APP_SECRETS_JSON`, and
+ `MacroConfig` reads **only** that JSON when it is present. A Pulumi container
+ `environment:` entry is invisible to `MacroConfig`; a value that comes from
+ infra must be written into Doppler (see `infra/stacks/preview-gateway`).
+
+## Service URLs
+
+- Service-to-service URLs are typed in `crates/macro_service_urls`
+ (`service_url!` with `local`/`dev`/`prod`), chosen by `ENVIRONMENT`. Call
+ `XServiceUrl::new()`. Never declare a `FOO_SERVICE_URL` env var or match on
+ `Environment` to build a URL. Queue names follow the same pattern in
+ `crates/macro_queues`.
+- The only override is `OVERRIDE_<SNAKE_NAME>`, read from the process
+ environment, not from Doppler. Local in-network overrides live in
+ `xtask_local`'s `local_env.rs`; `local` defaults are host ports and do not
+ work inside Docker.
+- The URL table is hand-copied. A new or changed service URL updates every copy:
+ `macro_service_urls`, `infra/packages/shared/src/service_urls.ts`,
+ `apps/web/src/lib/core/constant/servers.ts`, `packages/sdk/src/config.ts`, and
+ any `wrangler` `[env.*.vars]` that call it.
+
+## Other runtimes
+
+- **Web app:** service hosts come from `SERVER_HOSTS` in `servers.ts`; app
+ origin from `getWebOrigin`. Feature switches use `defineFlag` (see the
+ `feature-flags` skill), not raw `VITE_ENABLE_*` reads. Declare new
+ `VITE_*` vars in `src/vite-env.d.ts`.
+- **Cloudflare workers:** non-secret config goes in every `[env.*.vars]` block
+ of `wrangler.toml`/`.jsonc` (named envs don't inherit) and
+ `wrangler.docker.toml`; secrets via `wrangler secret put`; type them in the
+ worker's env module.
+
+Details: [new service guide](../../docs/guides/new-service.md),
+[infrastructure guide](../../docs/development/infrastructure.md).
diff --git a/.agents/rules/infra/github-workflows.md b/.agents/rules/infra/github-workflows.md
new file mode 100644
index 0000000000..f193df4e8e
--- /dev/null
+++ b/.agents/rules/infra/github-workflows.md
@@ -0,0 +1,24 @@
+---
+description: "GitHub Actions workflows are written in Rust with the xtask_workflows generator, never as hand-written YAML."
+paths:
+ - ".github/workflows/**"
+ - "tooling/xtask/crates/xtask_workflows/**"
+globs: ".github/workflows/**,tooling/xtask/crates/xtask_workflows/**"
+alwaysApply: false
+---
+
+# Write workflows in Rust with `cargo x workflows`
+
+Workflow YAML is generated from Rust so jobs share typed runners, secrets, and
+steps; hand-edited YAML drifts and fails CI's `cargo x workflows --check`.
+
+- A new workflow is a module in `tooling/xtask/crates/xtask_workflows/src/workflows/`
+ registered in `WORKFLOWS` (`workflows.rs`). Reuse `runners`, `vars`, and
+ `steps` instead of inlining labels, env, or step definitions.
+- Change a generated workflow (header `DO NOT EDIT`) by editing its source module,
+ then run `cargo x workflows` and commit the regenerated YAML with it.
+- A few older workflows are still hand-written YAML. When you change one
+ substantially, port it to the generator instead of editing the YAML.
+
+Check: `cargo x workflows --check` passes and no new `.github/workflows/*.yml`
+lacks the generated header.
diff --git a/.agents/rules/infra/pulumi.md b/.agents/rules/infra/pulumi.md
new file mode 100644
index 0000000000..98bf71b890
--- /dev/null
+++ b/.agents/rules/infra/pulumi.md
@@ -0,0 +1,34 @@
+---
+description: Pulumi changes follow the current ECS/gateway/Doppler pattern, and agents never deploy.
+paths:
+ - "infra/**"
+ - ".github/services-config.json"
+ - "**/wrangler.toml"
+ - "**/wrangler.jsonc"
+globs: infra/**,.github/services-config.json,**/wrangler.toml,**/wrangler.jsonc
+alwaysApply: false
+---
+
+# Pulumi and deploys
+
+Read the [infrastructure guide](../../../docs/development/infrastructure.md)
+before changing a stack.
+
+- Never run `pulumi up`/`destroy`, `wrangler deploy`/`secret put`, or dispatch a
+ deploy workflow unless the user asked for that deploy in this conversation.
+ `pulumi preview` is fine.
+- Copy the current pattern (`calendar-service`, `lexical-service`): gateway
+ `ServiceTargetGroup` with a unique `GATEWAY_PRIORITIES` entry,
+ `DopplerEcsEnvironment`, `EcrImage`, Fargate with the circuit breaker. Not
+ per-service ALBs, raw `aws.sqs.Queue`, or `createServiceRole`.
+- `MacroConfig` sees only `APP_SECRETS_JSON` in ECS: values infra produces go
+ into Doppler, not container `environment:`.
+- Secrets live in the service's Doppler project, nowhere else. Don't create
+ Secrets Manager secrets by hand or reference them from Pulumi config; that is
+ the old pattern. Never put a resolved `secretString` in an env var.
+- Generated files (`.github/kafka-cluster-topics.json`, workspace closures) are
+ regenerated with `cargo x`, never hand-edited.
+- New queues or buckets also go in `xtask_local`'s `resources.rs`.
+
+Check: `bun run --cwd infra check` and Biome pass; a new stack is listed in
+`services-config.json` or deliberately manual.
diff --git a/.agents/rules/observability.md b/.agents/rules/observability.md
new file mode 100644
index 0000000000..d3f095ec38
--- /dev/null
+++ b/.agents/rules/observability.md
@@ -0,0 +1,59 @@
+---
+description: "Changes to a flow carry the instrumentation to debug it: one correlated trace across services, spans at boundaries, timing, and searchable IDs."
+alwaysApply: true
+---
+
+# Observability
+
+Every new or changed flow must be debuggable from its trace alone: one trace from
+the user's action through every service it touches, with the timing and IDs needed
+to answer "what happened to this request and where did the time go". Reviewers
+treat missing instrumentation on a new flow as a defect, like a missing test.
+New flows and hot paths are instrumented in the same change, frontend and
+backend. The document open lifecycle (`doc.open`) and agent editing
+(`edit.session`) are the reference examples; the `instrumentation` skill walks
+through them and the per-runtime APIs.
+
+## Correlate across hops
+
+- Propagate W3C trace context on every hop. Inbound HTTP adopts `traceparent`
+ through `macro_tower_layers`; outbound Rust HTTP calls `inject_trace_headers`;
+ Kafka publishes carry trace headers via `kafka_util`; agent and ACP messages
+ use `genai_telemetry::propagation`. A new transport (queue message, websocket
+ frame, worker call) needs inject on send and extract on receive. If a hop
+ can't carry context, record the upstream trace id as a span field.
+- Web and Cloudflare Workers use the `@macro-inc/observability` `Telemetry`
+ facade (`Telemetry.span`, `Telemetry.clientSpan`); don't import OpenTelemetry
+ directly and don't add a second telemetry path.
+
+## Spans at boundaries
+
+- Span the places a trace would otherwise go dark: queue and Kafka consumers,
+ cross-service client calls, background jobs, and multi-step business
+ operations. Don't span trivial helpers; HTTP handlers already get spans from
+ `macro_tower_layers`.
+- Name spans for the operation (`calendar.sync_account`), not the function.
+- Record the IDs you will search by (entity, user, team, session, document) and
+ sizes/counts as fields. Skip bulky or sensitive arguments; never record
+ prompts, message content, tokens, secrets, or personal data (email, username,
+ IP); use opaque ids.
+- Async work that outlives the request (spawned tasks, queued jobs) links to or
+ parents on the span that started it, so the flow stays one trace.
+
+## Timing
+
+- Separate the phases a reader would ask about: queueing vs. execution, network
+ vs. processing, each external call. Long operations get child spans per phase,
+ not one opaque span.
+- Record outcome on the span (error status, retry count, cache hit/miss), so
+ slow and failed paths can be filtered without logs.
+
+## Logs
+
+- Logs are events inside spans with structured fields, not a parallel narrative:
+ one `warn!` with fields beats several formatted `debug!`s. Rust specifics are
+ CS-22 in [`rust/code.md`](rust/code.md); GenAI spans follow CS-55.
+
+Check: run the changed flow locally and find its trace in Tempo (see the
+`live-debug` skill): it is one connected trace across services, phases show their
+durations, and the span is findable by the entity ID.
diff --git a/.agents/rules/rust/architecture.md b/.agents/rules/rust/architecture.md
new file mode 100644
index 0000000000..e61f7e107d
--- /dev/null
+++ b/.agents/rules/rust/architecture.md
@@ -0,0 +1,40 @@
+---
+description: "Boundaries between crates and layers, and how handlers and APIs are shaped."
+paths:
+ - "crates/**/*.rs"
+ - "services/**/*.rs"
+ - "tooling/**/*.rs"
+globs: "crates/**/*.rs,services/**/*.rs,tooling/**/*.rs"
+alwaysApply: false
+---
+
+# Rust architecture and API design
+
+Boundaries between crates and layers in the Rust backend.
+
+- **CS-23** Do not grow `macro_db_client` — new domain logic gets a new crate;
+ the catch-all crates must shrink, not accumulate.
+- **CS-25** `mod.rs` declares submodules; it doesn't host logic — prefer the
+ `foo.rs` + `foo/` file-and-directory style for modules with logic. Enforced by
+ ast-grep `rust-mod-rs-declarations-only`, error.
+- **CS-27** Shared domain tables are only touched by their owning crate — e.g.
+ `entity_access` mutations go through `entity_access`/`entity_access_db_utils`,
+ never raw SQL elsewhere.
+- **CS-30** Axum handlers take shared services via `State`, not `Extension`.
+ Enforced by ast-grep `rust-no-axum-extension-param`, warning.
+- **CS-31** Attach cross-cutting services to the owning domain service, not ad
+ hoc at the router/handler layer — e.g. `EntityAccessManagementService` hangs
+ off the email/document service itself, the way the documents crate does.
+- **CS-51** Domain modules reference no infrastructure or transport: no AWS
+ SDKs, redis, reqwest, opensearch, kafka, axum, or http types under
+ `src/domain/**` — wrap clients in outbound adapters behind ports; response
+ mapping lives in inbound. Enforced by ast-grep `rust-no-infra-in-domain`
+ warning, `rust-no-transport-in-domain` error.
+- **CS-52** Dependencies point inward: `src/domain/**` never imports
+ `crate::inbound`/`crate::outbound`, and `src/outbound/**` never imports
+ `crate::inbound` — define a port in domain and implement it in the adapter.
+ Enforced by ast-grep `rust-domain-no-adapter-imports` warning,
+ `rust-outbound-no-inbound-imports` error.
+- **CS-53** Inbound adapters run no database queries — handlers, tools, and
+ listeners call a domain service backed by an outbound repository, never sqlx
+ directly. Enforced by ast-grep `rust-no-sqlx-in-inbound`, warning.
diff --git a/.agents/rules/rust/code.md b/.agents/rules/rust/code.md
new file mode 100644
index 0000000000..8c259e14be
--- /dev/null
+++ b/.agents/rules/rust/code.md
@@ -0,0 +1,80 @@
+---
+description: "Type design, idioms, errors and observability, performance, and tests."
+paths:
+ - "crates/**/*.rs"
+ - "services/**/*.rs"
+ - "tooling/**/*.rs"
+globs: "crates/**/*.rs,services/**/*.rs,tooling/**/*.rs"
+alwaysApply: false
+---
+
+# Rust code
+
+Type design, idioms, errors and observability, performance, and tests.
+
+- **CS-10** Newtype your identifiers and tokens — wrap raw `String`
+ ids/tokens/model-ids in a validated newtype that checks shape at construction.
+- **CS-11** A closed set of string values is an enum, not a `String` — impl
+ `Display`/`FromStr` as needed.
+- **CS-12** Optional means `Option<T>` — don't rely on sentinel values or
+ convention to express absence.
+- **CS-13** Model tri-state data (not-loaded / missing / present) as one flat
+ enum, not nested `Option`s or ad-hoc flags.
+- **CS-19** Give third-party errors their own variant — don't collapse e.g. a
+ `jsonwebtoken` failure into a generic internal error.
+- **CS-20** Depending on a rate-limited external provider requires a fallback
+ (fallback model, retry story, or documented degradation).
+- **CS-21** Wire usage metering on every invocation path — MCP-triggered tool
+ calls count too, not just the primary path.
+- **CS-22** When adding `#[tracing::instrument]`, include `err` on `Result`
+ functions and omit it on other return types. Never set `level = "info"` on the
+ attribute. Log errors as structured fields (`tracing::error!(error=?e,
+ "msg")`); prefer `.inspect_err` over `if let Err(e)` for logging.
+- **CS-40** Repeated literals become named consts.
+- **CS-41** Don't use `#[allow(...)]` — use `#[expect(..., reason = "...")]` on
+ the narrowest item it applies to; `allow` silently rots when the lint stops
+ firing, `expect` warns.
+- **CS-42** Don't re-state trait bounds already implied by a supertrait.
+- **CS-43** Use the smallest type that makes invalid states unrepresentable: a
+ counter that can't go negative is unsigned, one that can't plausibly pass 255
+ is a `u8`.
+- **CS-44** Large inline strings belong in files — use `include_str!`.
+- **CS-45** CLI binaries use `clap`, not hand-rolled arg parsing.
+- **CS-46** Use `rootcause` for error handling in new code — it's preferred over
+ `anyhow` these days. In code that's still on anyhow, prefer `bail!` for early
+ error returns.
+- **CS-47** Keep latency-critical services thin: push bytes directly instead of
+ round-tripping through presigned URLs or extra services; dispatch non-blocking
+ background work with `wait_until`.
+- **CS-48** Don't do per-message work on hot websocket paths — accumulate and
+ flush on a timer/alarm.
+- **CS-49** Tests live in a sibling `test.rs`, not inline `#[cfg(test)]` blocks
+ in the implementation file. See the [Rust
+ guide](../../../docs/development/rust.md#test-the-affected-packages).
+- **CS-50** Update affected tests for db-crate changes. Refresh SQLx metadata
+ when queries/schema change or required cache data is missing, not for
+ unrelated Rust-only edits. Run affected tests with `SQLX_OFFLINE` unset. See
+ the [database guide](../../../docs/development/database.md).
+- **CS-54** New library crates (not service binaries) put
+ `#![deny(missing_docs)]` in `lib.rs` and document all public items. Do not
+ mark documentation code blocks `ignore` to skip doctests unless explicitly
+ directed.
+- **CS-55** AI spans follow the OpenTelemetry GenAI conventions (`gen_ai.*`, see
+ `crates/genai_telemetry`). Agent sessions of every harness are traced in one
+ place: the session actor projects each session's ACP frames onto
+ `invoke_agent` / `execute_tool` spans
+ (`crates/agent_session/src/domain/session/telemetry.rs`), so do not add GenAI
+ spans to a harness runtime — `agent_inmem` runs its agent loop with
+ `with_genai_telemetry(false)` for that reason. Outside sessions (chat in
+ `document_cognition_service`), the agent loop and
+ `ai_toolset::ToolSet::try_tool_call` emit and enrich the `invoke_agent` /
+ `chat` / `execute_tool` spans; do not open tool spans in tools or toolsets,
+ and never record prompts, tool arguments or tool results as span fields or
+ logs — they are content, recorded on the spans under the
+ `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` policy and a size budget.
+- **CS-68** Don't mark types `#[non_exhaustive]` by default. Exhaustive matches
+ are how a new variant reaches every place that must handle it; reserve the
+ attribute for types published outside the workspace.
+- **CS-69** Derive serde, schema, and other traits on the type itself. Don't
+ keep parallel copies (a `wire.rs` mirror of domain types) just to carry
+ derives; add a separate type only when the wire shape genuinely differs.
diff --git a/.agents/rules/rust/db.md b/.agents/rules/rust/db.md
new file mode 100644
index 0000000000..f095dd5314
--- /dev/null
+++ b/.agents/rules/rust/db.md
@@ -0,0 +1,41 @@
+---
+description: "Rust database rules: ids, keys, migrations, and SQLx."
+paths:
+ - "**/outbound/**"
+ - "crates/*_db_client/**"
+ - "crates/*db_utils/**"
+ - "**/migrations/**"
+ - "**/*.sql"
+globs: "**/outbound/**,crates/*_db_client/**,crates/*db_utils/**,**/migrations/**,**/*.sql"
+alwaysApply: false
+---
+
+# Database and migrations
+
+Rust database rules: ids, keys, migrations, and SQLx.
+
+- **CS-01** Generate ids as UUIDv7 in application code — never
+ `gen_random_uuid()` (UUIDv4); v7 ids sort by creation time.
+- **CS-02** Make seed/backfill inserts and anything that can race idempotent
+ with an `ON CONFLICT` handler.
+- **CS-03** Prefer natural/composite keys over surrogate ids when the table is
+ queried/sorted by those columns anyway, and key REST routes on the natural id.
+- **CS-04** Name user columns `user_id` — not `owner_user_id` or other variants;
+ follow existing tables.
+- **CS-05** New tables need a deliberate cascade/cleanup story, not whatever the
+ default happens to be.
+- **CS-06** Don't add redundant indexes — a column already covered as the
+ leading part of the primary key does not need its own index.
+- **CS-07** Don't store columns that are implicit in context (e.g. a scoping id
+ already fixed per durable object / per tenant).
+- **CS-08** Use `sqlx::query!` / `query_as!` (compile-time checked) by default;
+ the non-macro form is only for queries that genuinely cannot be statically
+ known. Enforced by clippy `disallowed-methods`; see the [database
+ guide](../../../docs/development/database.md).
+- **CS-09** The `.sqlx` cache lives at the workspace root — run `nix develop
+ --command just prepare_db` from the repository root; never commit a `.sqlx`
+ directory inside an individual crate. See the [database
+ guide](../../../docs/development/database.md).
+- **CS-70** Migrations survive a rolling deploy: new `NOT NULL` columns get a
+ default, and changes to large tables set `lock_timeout` and use `NOT VALID` +
+ `VALIDATE` or `CREATE INDEX CONCURRENTLY` instead of a full rewrite.
diff --git a/.agents/rules/rust/guardrails.md b/.agents/rules/rust/guardrails.md
new file mode 100644
index 0000000000..d6dc77f27b
--- /dev/null
+++ b/.agents/rules/rust/guardrails.md
@@ -0,0 +1,27 @@
+---
+description: "Backend guardrails: how to run Rust tests, migrations, the SQLx cache, and crate boundaries."
+paths:
+ - "crates/**"
+ - "services/**"
+ - "tooling/**"
+globs: "crates/**,services/**,tooling/**"
+alwaysApply: false
+---
+
+# Backend guardrails
+
+- Run Rust tests from the repository root with `cargo test -p <package>` and
+ **leave `SQLX_OFFLINE` unset**. Offline mode is for checks, builds, and lints,
+ not tests.
+- Generate migrations with `sqlx migrate add`; never invent timestamped
+ filenames. Never hand-edit `.sqlx/query-*.json`. Prepare the workspace cache
+ from the root inside Nix with `just prepare_db` ([database
+ guide](../../../docs/development/database.md)).
+- Never generate `.sqlx` metadata for test queries: no `--tests` on prepare.
+ Tests compile against the live database, so they don't need the cache.
+- Across domain crates, depend on the owning domain service or port; only a
+ composition root may construct that crate's outbound adapters. Never import
+ another crate's `outbound` module from an outbound adapter.
+- Read the [Rust development guide](../../../docs/development/rust.md) before
+ building or testing, and the hexagonal architecture skill before changing
+ inbound, domain, or outbound code.
diff --git a/.agents/rules/rust/libraries.md b/.agents/rules/rust/libraries.md
new file mode 100644
index 0000000000..75fc7b4e26
--- /dev/null
+++ b/.agents/rules/rust/libraries.md
@@ -0,0 +1,65 @@
+---
+description: "Use the workspace's standard Rust crates and their house idioms instead of hand-rolling or adding alternatives."
+paths:
+ - "crates/**/*.rs"
+ - "services/**/*.rs"
+ - "tooling/**/*.rs"
+ - "**/Cargo.toml"
+globs: "crates/**/*.rs,services/**/*.rs,tooling/**/*.rs,**/Cargo.toml"
+alwaysApply: false
+---
+
+# Rust libraries
+
+Reach for these before writing a helper or adding a dependency. Infrastructure
+crates (`macro_config`, `macro_entrypoint`, `macro_service_urls`, `kafka_util`,
+`sqs_worker`, `macro_cors`, `macro_tower_layers`, `macro_auth`,
+`macro_authorization`) are covered by the config and observability rules; use
+them instead of their generic equivalents.
+
+- **CS-56** Error types: `thiserror` enums for every public error (domain and
+ adapters), with caller-meaningful variants plus `Internal(rootcause::Report)`.
+ Ports expose `type Err: std::error::Error + Send + Sync + 'static`; services
+ map adapter errors with `rootcause::Report::new(e).into_dynamic()`. Binaries
+ return `Result<(), rootcause::Report>`. Never add `anyhow` to a crate that
+ doesn't use it (CS-46). Model: `crates/user_api_key`.
+- **CS-57** No `Box<dyn Error>`, `Result<_, String>`, or `.unwrap()` /
+ `.expect()` outside tests and startup invariants; an `expect` states the
+ invariant it relies on.
+- **CS-58** Parse structured text with `nom` (and `logos` for tokenizing a real
+ grammar, as `crates/database_sql` does), not hand-rolled `split_once` /
+ `strip_prefix` / index scanners.
+- **CS-59** Enum string forms (CS-11) use `strum` derives (`EnumString`,
+ `Display`, `AsRefStr`, `IntoStaticStr`, `EnumIter`) with `serialize_all`
+ matching serde's `rename_all`, imported from `strum`, not `strum_macros`.
+ Serde: API DTOs are `camelCase`; new enums are internally tagged (`tag =
+ "..."`); `untagged` only for backward-compatible input. HTTP schemas are
+ `utoipa::ToSchema`; AI-tool schemas are `schemars::JsonSchema`.
+- **CS-60** Async traits are native: `fn x(&self) -> impl Future<Output = ...> +
+ Send`. Use `#[async_trait]` only when the trait must be object-safe (`Arc<dyn
+ Port>`), and say so in a comment.
+- **CS-61** Concurrency uses tokio: `mpsc` / `oneshot` / `watch` / `broadcast` /
+ `Notify`. `std::sync::Mutex` when no `.await` happens under the guard,
+ `tokio::sync::Mutex` only across awaits. Every spawned background loop takes a
+ `CancellationToken` and is tracked by a `TaskTracker`.
+- **CS-62** Outbound HTTP: build one `reqwest::Client` with a timeout in the
+ adapter's constructor and keep it; take the base URL from
+ `macro_service_urls`; call `macro_tower_layers::inject_trace_headers` on every
+ request. Never `Client::new()` per call or `.unwrap()` the builder.
+- **CS-63** Time is `chrono` (`DateTime<Utc>`); `time` only where a dependency's
+ API requires it. New ids are `Uuid::now_v7()` or a newtype's `generate()`
+ (CS-01, CS-10), never `new_v4`.
+- **CS-64** Statics use `std::sync::LazyLock` / `OnceLock`; literal regexes use
+ `lazy_regex::regex!`, others a `LazyLock<Regex>`. Never add `lazy_static` or
+ `once_cell`, and never compile a regex per call.
+- **CS-65** Domain-service tests use hand-written fakes implementing the port;
+ `mockall` only for narrow interaction assertions. DB tests use
+ `#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]`; HTTP doubles use
+ `wiremock`; transcript and replay output uses `insta`.
+- **CS-66** Never wait for a condition by polling: no `yield_now` or `sleep`
+ loops. Signal with `oneshot`, `Notify`, `watch`, `Barrier`, or a channel, and
+ use `#[tokio::test(start_paused = true)]` for time.
+- **CS-67** Dependencies come from root `[workspace.dependencies]` as `x = {
+ workspace = true }`; after any `Cargo.toml` change run `just hakari` and
+ commit `crates/workspace-hack`. Check the workspace list before adding a
+ crate, and don't add one that duplicates an existing choice.
diff --git a/.agents/rules/rust/security.md b/.agents/rules/rust/security.md
new file mode 100644
index 0000000000..c8553d637d
--- /dev/null
+++ b/.agents/rules/rust/security.md
@@ -0,0 +1,29 @@
+---
+description: "Authorization and permission checks in backend code."
+paths:
+ - "crates/**/*.rs"
+ - "services/**/*.rs"
+ - "tooling/**/*.rs"
+globs: "crates/**/*.rs,services/**/*.rs,tooling/**/*.rs"
+alwaysApply: false
+---
+
+# Rust security and permissions
+
+Authorization and permission checks in backend code.
+
+- **CS-36** Permission grants are stateless HTTP endpoints, not channel messages
+ — in-memory channel flows don't survive reconnects.
+- **CS-37** Mint narrowly-scoped tokens instead of forwarding the user's full
+ JWT downstream — least privilege by construction.
+- **CS-38** Tool responses must be valid members of the message chain — include
+ `tool_call_id` and required chain metadata.
+- **CS-39** Pin third-party GitHub Actions to a commit SHA, not a movable tag.
+- **CS-72** Store user or third-party secrets (API keys, OAuth refresh tokens)
+ only as AWS KMS ciphertext, following `crates/cursor_api_key` (direct KMS) or
+ `crates/microsoft_oauth_grant_db_utils` (envelope: encrypted data key, KMS
+ key id, encryption version). Bind the encryption context to the owner so a
+ copied row won't decrypt. Hold the plaintext in a type that redacts `Debug`
+ and zeroizes on drop, use it immediately (e.g. as a request header), and never
+ log or cache it. Deleting the row doesn't revoke the secret upstream; say so
+ in any disconnect UI.
diff --git a/.agents/rules/sdk.md b/.agents/rules/sdk.md
new file mode 100644
index 0000000000..99455cc514
--- /dev/null
+++ b/.agents/rules/sdk.md
@@ -0,0 +1,26 @@
+---
+description: "The TypeScript SDK exposes entity handles, never raw ids: methods take and return entity objects, and a missing noun gets a new entity class."
+paths:
+ - "packages/sdk/src/**"
+globs: "packages/sdk/src/**"
+alwaysApply: false
+---
+
+# SDK methods take and return entities, not ids
+
+Ids are correlation data, not parameters; a `string` id argument lets callers
+pass the wrong kind of id and scatters operations away from the thing they act on.
+
+- A public method never takes a raw id. It takes the entity handle and reads `.id`
+ internally: `task.addComment(...)`, not `tasks.addComment(taskId, ...)`.
+- A public method never returns a raw id; it returns a handle.
+- If the id names a noun with no entity class yet, create the entity (class plus
+ namespace under `src/entities/<noun>/`, registered in `src/macro.ts`) in the
+ same change. Sub-resources too: a listing returns handles, and mutations are
+ methods on them (`entry.edit(...)`, `entry.remove()`).
+- The only id-taking entry point is `static byId(client, id)`, which mints a handle.
+
+Details and conventions: the `add-sdk-endpoint` skill.
+
+Check: no exported SDK method has a parameter or return type that is a bare id
+string, apart from `byId`.
diff --git a/.agents/rules/web/architecture.md b/.agents/rules/web/architecture.md
new file mode 100644
index 0000000000..cf9e209b01
--- /dev/null
+++ b/.agents/rules/web/architecture.md
@@ -0,0 +1,86 @@
+---
+description: "Module layout, layering, and TypeScript conventions."
+paths:
+ - "apps/web/**"
+ - "packages/**"
+globs: "apps/web/**,packages/**"
+alwaysApply: false
+---
+
+# Frontend architecture and TypeScript
+
+Module layout, layering, and TypeScript conventions.
+
+- **FE-16** Keep modules single-purpose: feature-specific logic out of generic
+ util files, generic/collaboration logic decoupled from feature specifics,
+ styling out of core business logic.
+- **FE-17** Reuse existing shared utilities and primitives before hand-rolling
+ (`removeNodeAndRestoreSelection`, Kobalte components) — re-implementations
+ reintroduce bugs that were already fixed.
+- **FE-18** Within a package, use relative imports — don't route through the
+ package's own barrel file; it adds indirection and invites circular
+ dependencies.
+- **FE-19** Trust `match` narrowing — an exhaustive `ts-pattern` match already
+ narrows the type inside each closure; a manual `Extract<>` alias is redundant.
+- **FE-20** Exhaustive branching uses `match` from `ts-pattern`.
+- **FE-21** No `any` — proper types or `unknown` + type guards.
+- **FE-31** Never cast a string to `ItemType` — parse it with `stringToItemType`
+ from `@service-storage/client`, the one owner of entity-type spellings (email
+ threads alone are stored as `email`, `thread`, and `email_thread`). Enforced
+ by ast-grep `ts-no-item-type-cast` + `tsx-no-item-type-cast`, CI error.
+- **FE-33** New features and feature restructures use the [layered feature
+ architecture](../../../docs/architecture/frontend-features.md), with
+ `features/activity` as the reference. Use `core/` for pure feature types and
+ functions, `queries/` for wire adapters and query factories, `primitives/` for
+ reactive state/actions without JSX, `components/` for presentation from props,
+ and `views/` for use-case composition. `context/` holds feature-owned
+ capability contracts and the provider/consumer, without production imports or
+ fallback. An app-facing entry point constructs real adapters and supplies the
+ provider; missing provider setup fails clearly. Meaningful reactive decisions
+ depend on narrow feature sources, not concrete query adapters or raw clients.
+ Adapters implement those contracts using existing query/cache infrastructure;
+ Solid accessors and ownership remain part of the reactive foundation. Per-host
+ behavior belongs in callback props, and flags gate mounting outside the
+ capability contract. Primitives and adapters depend on feature-owned
+ contracts; views depend on primitives and components, and core stays
+ independent. Components may import context display types only. Keep data
+ availability in source adapters and presentation decisions in primitives;
+ avoid interfaces with no independent behavior to protect. Controllers receive
+ only their named capabilities; production environments and presentation wiring
+ stay in views. Reuse query/mutation infrastructure rather than adding a
+ generic async wrapper. Keep request failures distinct from errors after a
+ successful write, and require promises when callers depend on completion. Use
+ view-state unions when the use case has distinct states; small helpers can
+ return accessors. Test feature behavior through injected capabilities, with
+ shared helpers in `tests/`. Use fake sources for primitive unit tests and fake
+ clients for adapter tests, retaining integration coverage of both. Activity
+ still has combined context/production wiring, raw-client injection, and
+ UI/import-side-effect stubs; these are documented migration gaps. The detailed
+ document covers layer responsibilities, narrow reference exceptions, adoption,
+ and review. Register adopting feature paths in both language variants of every
+ feature rule. Enforced by ast-grep `ts-/tsx-feature-core-pure`,
+ `ts-/tsx-feature-components-presentational`, `ts-/tsx-feature-data-no-ui`,
+ `ts-/tsx-feature-layers-use-context`, warning; currently scoped to activity.
+ Separate production composition and source-contract inversion still require
+ explicit review; the existing rules do not enforce them.
+- **FE-34** Treat the legacy block state system as adapter-boundary code, not
+ state management for new or refactored surfaces. Do not add new `useBlock*`,
+ `createBlock*`, block-scoped signal/store/memo/resource, or block permission
+ dependencies. An existing block adapter may read legacy state once and
+ translate it into a feature-owned context or explicit props; descendants and
+ reusable components receive identity, permissions, state, and lifecycle owners
+ through those contracts and must remain mountable without `<Block>`. Never add
+ a `<Block>` wrapper merely to satisfy a missing dependency. If shared code
+ needs an owner or other host capability, expose it through the owning surface
+ context instead of borrowing `BlockContext`.
+
+## TypeScript
+
+- For exhaustive matching use `match(...).exhaustive()` from `ts-pattern`, never
+ a hand-written `switch`.
+- **FE-47** Blocks are a legacy integration pattern we live with, not an
+ architecture to build on. Keep `definition.ts` to registration and lazy
+ loading, and the `<name>-block.tsx` adapter to translating block state once;
+ put all behavior in the feature layers so it mounts without a block. Don't
+ add block-level abstractions, and prefer moving logic out of a block over
+ extending it.
diff --git a/.agents/rules/web/data.md b/.agents/rules/web/data.md
new file mode 100644
index 0000000000..a0d304192a
--- /dev/null
+++ b/.agents/rules/web/data.md
@@ -0,0 +1,81 @@
+---
+description: "Queries, caching, and where data is fetched."
+paths:
+ - "apps/web/**"
+ - "packages/**"
+globs: "apps/web/**,packages/**"
+alwaysApply: false
+---
+
+# Frontend data fetching
+
+Queries, caching, and where data is fetched.
+
+- **FE-01** Never call a service client outside the `queries` package — UI code
+ calling an endpoint directly is usually re-fetching data an existing query
+ already caches. Enforced by ast-grep `ts-no-service-client-outside-queries` +
+ `tsx-no-service-client-outside-queries`, warning.
+- **FE-02** Every query module has a `keys.ts` structured like the existing
+ ones.
+- **FE-03** Conditional fetching uses a debounced signal passed to TanStack
+ Query's `enabled`, not a custom resource.
+- **FE-04** Pre-populating data means exposing a cache-seeding method on the
+ query, not an ad hoc manual cache.
+- **FE-05** Data-dependent UI that must not suspend uses `queryReadyGate`.
+- **FE-06** Extend `QUERY_FILTERS_BASE` instead of re-deriving filter exclusions
+ per query, and prefer explicit include lists — exclude lists silently break
+ when a new entity type is added.
+- **FE-07** Don't hardcode backend-owned config in the frontend (e.g. system bot
+ config) — fetch it dynamically or generate types from the backend source of
+ truth.
+- **FE-29** Every new query call site (`useQuery`/`useInfiniteQuery` or a hook
+ from `src/lib/queries/**`) needs a deliberate `Suspense` boundary: reading
+ `query.data` suspends to the *nearest ancestor* boundary. When reviewing, walk
+ up the component tree from the call site and determine which boundary would
+ catch it. If none exists below the app root, or the nearest one is far outside
+ the component's own UI scope (e.g. the route-level boundary in
+ `apps/web/src/routes/Root.tsx`, whose fallback blanks unrelated UI), flag it
+ and ask which boundary is intended.
+
+## Query callback lifetimes
+
+Query options can remain cached after their UI unmounts, including for disabled
+queries. Callbacks created inside hooks can retain component accessors, Solid
+owners, and detached DOM through shared closure environments—even when a callback
+only references a locally resolved ID. This does not mean every closure captures
+every local variable.
+
+- Create cached callbacks in module-scope query factories accepting resolved
+ IDs, flags, and plain data. Resolve reactive inputs inside the `useQuery` /
+ `useInfiniteQuery` options accessor, e.g. `useQuery(() =>
+ itemQueryOptions(id()))`, so inputs still update reactively.
+- Keep pure selectors and polling policies at module scope, or inside those
+ factories. Check **all** retained callbacks: `queryFn`, `select`,
+ `refetchInterval`, pagination, placeholder callbacks, and functions in `meta`.
+- Do not pass component accessors, props getters, or query proxies into the
+ factory. For reactive selection, pass plain snapshots of the needed values
+ (such as channel names or a resolved document ID). Naming a function or
+ copying an ID inside the hook does not isolate its closure from the hook.
+- Use `keepPreviousData` from `@tanstack/solid-query` instead of an inline
+ `placeholderData: (p) => p`.
+- The same rule applies to callers of wrapper hooks such as
+ `useSoupAstItemsQuery` and `createGroupedSoupQueries`: `meta.itemFilter` /
+ `meta.insertFilter` passed from a component or view context are cached too, so
+ build them with a module-scope factory over plain snapshots (see
+ [drive-data-source](../../../apps/web/src/features/drive-view/queries/drive-data-source.ts)).
+- Query hooks in `src/lib/urql-solid` are exempt: their observers are created
+ per mount and destroyed on cleanup, so nothing outlives the component.
+
+Examples: [session query factory](../../../apps/web/src/lib/queries/agent-session/session.ts) and
+[search query factories](../../../apps/web/src/lib/queries/soup/search.ts).
+- **FE-48** Keep cached data on screen through refetch errors: gate on
+ `isPending`, never `isSuccess` / `isError`. Every query view handles pending,
+ error, empty, and nothing-selected separately.
+- **FE-49** Refetches and optimistic updates never wipe local state (drafts,
+ anchors, selections), and a refetch started before a mutation can't overwrite
+ its result. Optimistic rollback state lives in `onMutate`; temporary ids are
+ never openable.
+- **FE-50** Scope invalidation to what changed, but update every reader of it.
+ Query keys hold exactly the fetch inputs.
+- **FE-51** State moved into the URL round-trips every field. Removed or renamed
+ routes and route ids get redirects, and saved split layouts keep working.
diff --git a/.agents/rules/web/lexical-nodes.md b/.agents/rules/web/lexical-nodes.md
new file mode 100644
index 0000000000..ffec3b0651
--- /dev/null
+++ b/.agents/rules/web/lexical-nodes.md
@@ -0,0 +1,35 @@
+---
+description: "Lexical nodes bump the version counter on breaking changes and render at their final height on first paint."
+paths:
+ - "packages/lexical-core/nodes/**"
+ - "apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/**"
+ - "apps/web/src/lib/core/component/LexicalMarkdown/version.ts"
+globs: "packages/lexical-core/nodes/**,apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/**,apps/web/src/lib/core/component/LexicalMarkdown/version.ts"
+alwaysApply: false
+---
+
+# Lexical nodes
+
+## Bump the version counter
+
+When you create a Lexical node or make a breaking change to one, increment the
+counter in `apps/web/src/lib/core/component/LexicalMarkdown/version.ts` with a short
+note on what changed.
+
+## Keep decorators at a stable height
+
+Any decorator node can appear in a channel message. Channels are a virtualized
+list anchored to the bottom, so a message that grows after it mounts pushes
+every row and the channel visibly jumps.
+
+- Render the decorator at its final size on first paint. Reserve the box before
+ data arrives: known width/height or `aspect-ratio` for media, a fixed-height
+ placeholder for anything fetched.
+- A loading state and its loaded state must be the same height.
+ `MediaLoadingPlaceholder` and `LazyDecorator`'s `placeholder` slot are the
+ existing ways to do this.
+- Do not fetch or resolve something after mount that adds rows, previews, or
+ expanded content unless its space is already reserved.
+
+Check: open a channel with the node in an older message, reload, and confirm the
+scroll position does not move while the node loads.
diff --git a/.agents/rules/web/libraries.md b/.agents/rules/web/libraries.md
new file mode 100644
index 0000000000..fae8b6d49a
--- /dev/null
+++ b/.agents/rules/web/libraries.md
@@ -0,0 +1,64 @@
+---
+description: "Use the web app's standard libraries and house helpers: ts-pattern, neverthrow, TanStack Query, solid-primitives, Kobalte wrappers, and friends."
+paths:
+ - "apps/web/**"
+ - "packages/**"
+globs: "apps/web/**,packages/**"
+alwaysApply: false
+---
+
+# Web libraries
+
+Reach for these before writing a helper or adding a dependency. `packages/sdk`
+throws `MacroApiError` instead of returning `Result`, and the Bun/Worker services
+under `services/` throw and validate with zod; elsewhere in `apps/web` and
+`packages/` these rules apply.
+
+- **FE-35** Branch on unions and literal sets with ts-pattern:
+ `match(x).with(...).exhaustive()`. `.otherwise` only for open domains
+ (arbitrary strings, error codes). Never hand-write `switch` on a discriminant;
+ a `switch` over `event.key` in a keyboard handler is fine.
+- **FE-36** Fallible operations return neverthrow `Result` / `ResultAsync`. New
+ feature code types errors as `{ kind:... }` unions matched with ts-pattern;
+ transport code keeps `ResultError<Code>[]`. Guard with `if (r.isErr())
+ return...`, then use `.value`; chain with `andThen` / `mapErr`. Enter from
+ throwing code with `ResultAsync.fromPromise` / `fromThrowable` (or
+ `catchToResult` for legacy `ResultError`). Never wrap a `Result`-returning
+ call in try/catch; `_unsafeUnwrap` is test-only.
+- **FE-37** Cross into TanStack Query with `throwOnErr` (`@core/util/result`) in
+ `queryFn` and `mutationFn`. Never `throw` a raw error or `new Error(...)` from
+ an `isErr()` branch: `ThrownResultError` carries the codes the client's retry
+ and auth policy read.
+- **FE-38** Server state is TanStack Query: `queryOptions` factories at module
+ scope, called as `useQuery(() => xQueryOptions(id()))`; keys come from the
+ module's `keys.ts` built with `createQueryKeys`, never inline arrays;
+ optimistic mutations use `onMutate` (cancel, snapshot, patch, return context).
+ GraphQL reads go through `src/lib/urql-solid` / `createLiveQuery`.
+- **FE-39** Check `@solid-primitives/*` before writing a reactive utility, and
+ declare the package you import in `package.json`. Debounce and throttle
+ through `@core/util/debounce` (`debouncedDependent` for a debounced signal);
+ no hand-rolled `clearTimeout`/`setTimeout` pairs, no lodash.
+- **FE-40** Use the `@ui/components/*` wrapper when one exists (Dialog, Tooltip,
+ Select, Tabs, HoverCard,...) instead of importing `@kobalte/core` directly.
+ Merge classes with `cn` (`@ui/utils/classname`), never `twMerge` or `clsx`.
+- **FE-41** HTTP goes through the service clients (`safeFetch`,
+ `fetchWithToken`, `fetchWithAuth`); raw `fetch` only for presigned or blob
+ URLs.
+- **FE-42** zod (v4) validates at boundaries only: route and search params,
+ persisted state, service responses, worker request bodies.
+- **FE-43** Ids: `uuid` `v7` for server-persisted entities (`v5` for
+ deterministic ones), `crypto.randomUUID()` for ephemeral or optimistic ids,
+ `nanoid` only for Lexical and canvas node keys. Never `Math.random()` ids,
+ `uuid` `v4`, or `short-uuid`.
+- **FE-44** Dates: `date-fns` (and `@date-fns/tz`) for arithmetic and the house
+ `@core/util/date` / `@core/util/time` helpers; `Intl.DateTimeFormat` for
+ locale display. No dayjs, luxon, moment, or Temporal.
+- **FE-45** Virtualized lists use `virtua`, not `@tanstack/solid-virtual`.
+ Persisted UI state uses `makePersistedState` (`src/lib/persistence`) with a
+ zod schema, not raw `localStorage` calls.
+- **FE-46** Reuse the house helpers instead of re-implementing them: `deepEqual`
+ (`@core/util/compareUtils`), `structuredClone` for copies, and
+ `@tanstack/pacer` (`AsyncBatcher`, `Queuer`) for request coalescing. `effect`
+ stays inside `lib/graphql-cache/worker/**` and `lib/queries/soup/backfill.ts`
+ and is never mixed with neverthrow in one module. Don't add lodash, immer,
+ axios, ky, or another validator.
diff --git a/.agents/rules/web/mobile.md b/.agents/rules/web/mobile.md
new file mode 100644
index 0000000000..59dc0a55d7
--- /dev/null
+++ b/.agents/rules/web/mobile.md
@@ -0,0 +1,104 @@
+---
+description: "Mobile UI uses the shared touch helpers, chrome, and sheets."
+paths:
+ - "apps/web/src/**/*.tsx"
+ - "apps/web/src/**/*.css"
+ - "apps/web/src/lib/core/mobile/**"
+globs: "apps/web/src/**/*.tsx,apps/web/src/**/*.css,apps/web/src/lib/core/mobile/**"
+alwaysApply: false
+---
+
+# Build mobile UI with the shared touch helpers
+
+The web app is also the iOS and Android apps. Mobile bugs come from hover-only
+UI, taps that drop the keyboard, content under chrome or safe areas, and
+WebKit quirks that Chrome emulation never shows.
+
+Before building mobile UI, open the app at phone width and study how existing
+surfaces solve the same problem (sheets, the dock, header islands, list rows),
+read their code, and follow that pattern rather than inventing a new one.
+
+## Detection and input
+
+- `isTouchDevice()` / `touch:` decide input (no hover); `isMobile()` /
+ `mobile:` decide phone layout (touch and under 640px). Hide a desktop
+ control and show its touch replacement with the same one, or tablets get
+ neither. Native checks (`isPlatform` in `@core/util/platform`) are for
+ native bridges, not layout.
+- Gate hover and press styles with `not-touch:`; iOS leaves hover stuck.
+- No action lives only behind hover. `HoverCard` renders nothing on touch,
+ so give it a tap path that opens a sheet, as `UserCardTrigger` does.
+- Keep `@ui` Button's touch sizing (no `noTouchResize` without cause); rows
+ are 44px on touch (`touch:min-h-[44px]`).
+- Long-press goes through the `touchHandler` directive. A touch drag scrolls:
+ selecting or dragging starts only after a long press, and horizontal
+ swipes ignore the left edge (iOS back swipe).
+- Primary nav fires `hapticImpact('light')` on pointer down and acts on
+ click, so a held or cancelled touch does nothing. `glass` and `island`
+ controls get press animation from `installGlassPress`; add none.
+
+## Sheets, menus, and dialogs
+
+- Use `@ui` `Dialog` and `ConfirmDialog`; they become drawers on phones.
+ Build other sheets from `MobileDrawer` (`components/app/mobile`), never raw
+ `@corvu/drawer`, with content in `MobileDrawer.ScrollBody` and height from
+ `maxHeight` / `targetHeight`, never hand-set.
+- Phone drawers have a handle and no X; drag, backdrop, or Escape dismiss,
+ and focus returns to the opener. No submenus at phone width: drill in
+ place with a back row.
+- Overlays are Kobalte or corvu layers or handle Escape: Android Back sends
+ Escape to the top layer. Own back stacks use `useAndroidBackNavigation`.
+
+## Keyboard and focus
+
+- Focus inputs on user intent only, never on mount. On touch, Enter in a
+ composer inserts a newline; the send button submits.
+- UI over an editor must not take focus: cancel `pointerdown` and
+ `mousedown` on its root (`keepEditorFocus` in `TouchSelectionToolbar`) or
+ use `usePreserveFocusOnButtonTaps`; mark sibling regions
+ `data-keep-keyboard`. Dismiss with `useTouchOutsideToDismissKeyboard`.
+- Size against the keyboard with `var(--dvh,1dvh)` and
+ `var(--virtual-keyboard-height,0px)`, fallback included (Android leaves it
+ unset); in JS read `virtualKeyboardVisible()`. Sheets with inputs call
+ `scrollToFocusedInput` from `onFocusIn`.
+- Never remount a focused editor (keys on content ids, Suspense around it).
+ Collapsed inputs match the focused height (`CollapsedInput`), and hidden
+ controls use `hidden`, not `opacity-0`, so neighbors don't jump.
+
+## Layout and chrome
+
+- Content scrolls under the floating chrome: pad the scroller with
+ `mobile:pt-(--mobile-content-inset-top)` and
+ `mobile:pb-(--mobile-content-inset-bottom)`, never a spacer.
+- Safe areas come from the `--safe-*` CSS variables (e.g.
+ `bottom-[var(--safe-bottom,0px)]`); `getSafeAreaInset` only when JS needs
+ the number. Never measure insets yourself.
+- Wrap split-header contributions in `HeaderIsland` (the touch header
+ ignores taps outside islands). Bottom chrome goes through `FloatRegion` or
+ `FloatRegionOrInline` with `px-(--mobile-chrome-gutter)` and
+ `pointer-events-auto`. Style it with `island` / `glass`, size it with the
+ px `--mobile-chrome-*` tokens (not rem), and pass Button a `depth`.
+- Phones show one pane: open in place or as a front pane, never a new
+ split. Desktop-only layouts fall back (board to list) and update the URL.
+- Suspense wraps content, never the router or chrome, with `ContentLoading`
+ as the fallback; otherwise phones go blank.
+- Keep content and actions the same as desktop and change presentation.
+ Drop a feature on phones only when it is desk work (API keys).
+
+## Platform pitfalls
+
+- Construct Web Workers on first use, never at module load: eager module
+ workers deadlock iOS WKWebView. Open links with `openExternalUrl`.
+- Virtual rows reserve media size up front (resizes during iOS momentum
+ scroll jump the list; see `ThreadList`); virtual lists use
+ `overscroll-none`.
+
+## Verify
+
+- Check at 390px with touch emulation (width alone doesn't set `touch:`) and
+ a tablet (touch at desktop width). Check keyboard, safe areas, and native
+ menus in the iOS Simulator and tap/focus bugs on a physical iPhone
+ (`apps/web/AGENTS.md`); Android per `docs/development/android.md`.
+
+Check: no hover-only actions, the helpers above are used, and the change was
+seen at phone width with touch emulation.
diff --git a/.agents/rules/web/solid.md b/.agents/rules/web/solid.md
new file mode 100644
index 0000000000..970f975ac0
--- /dev/null
+++ b/.agents/rules/web/solid.md
@@ -0,0 +1,67 @@
+---
+description: "State ownership, reactivity, and async error handling."
+paths:
+ - "apps/web/**"
+ - "packages/**"
+globs: "apps/web/**,packages/**"
+alwaysApply: false
+---
+
+# Solid reactivity and async
+
+State ownership, reactivity, and async error handling.
+
+- **FE-08** No ad-hoc global state modules — shared state for a subtree lives in
+ a Context scoped to a clear ownership boundary.
+- **FE-09** Derive, don't sync — an effect that only copies one signal into
+ another similarly-shaped signal should be a derived signal at the appropriate
+ level.
+- **FE-10** `createEffect` is for external/imperative systems only (DOM APIs,
+ third-party libs, navigation events) — never for deriving state; use `on()` to
+ make dependencies explicit when an effect is warranted. Prefer wrapping the
+ setter over `createEffect(() => { if (signal()) sideEffect() })` when setting
+ a value should also clear related UI, blur a control, or scroll.
+- **FE-11** Check `solid-primitives` before writing a custom reactive utility.
+- **FE-12** `async`/`await`, not `.then()`/`.catch()` chains; fallible calls
+ return `Result` (FE-36) rather than being wrapped in `try`/`catch`. Enforced
+ by oxlint `promise/prefer-await-to-then` — `bun run lint:oxlint` from the
+ repository root.
+- **FE-13** Extract multi-step async coordination into named helper functions,
+ and make intentionally-unawaited promises explicit — no bare floating
+ promises.
+- **FE-14** Keep neverthrow `Result`/`ResultAsync` intact end-to-end — use the
+ existing helpers (`ResultAsync`, `throwOnErr` in `queryFn`, `catchToResult`)
+ instead of ad hoc `Promise <-> Result` conversions.
+- **FE-15** Guard once, at the top — missing/invalid state gets an early return
+ at the start of the function or hook, not a repeated check in every branch or
+ a silent fall-through.
+
+## Solid patterns
+
+- Avoid createEffect. Legitimate uses: syncing with external/imperative systems
+ (DOM APIs, third-party libs). If you're using it to derive state or trigger
+ updates, use a derived signal or wrap the setter instead.
+- Prefer wrapping the setter over `createEffect(() => { if (signal())
+ sideEffect() })`. When setting focus/selection should also clear another stop,
+ blur a control, or scroll, put that work in the setter (or a named helper the
+ setter calls) so the action is explicit at the call site — not a distant
+ effect watching the signal.
+- Use createMemo only when you need referential stability or the derivation is
+ expensive. Cheap derivations (() => a() + b()) don't need it regardless of
+ subscriber count.
+- Before rolling your own reactive utility, check solid-primitives first.
+- Never read a solid-query `query.data` unguarded from a component body or an
+ eager `createMemo`. `data` is a resource read: while the query is pending it
+ suspends the caller's nearest `<Suspense>`, which detaches and re-attaches
+ that whole subtree — a blank flash, lost scroll position, remounted editors.
+ Gate the read on status (`query.isSuccess ? query.data : fallback`, or
+ `queryReadyGate` from `src/lib/queries/gate.ts`); an `isLoading` check is not
+ enough, because a disabled or paused query is pending without loading and its
+ data read still suspends. Every other field is a plain store read and is safe.
+ Remember `createMemo` runs immediately, so a guard inside a `<Show>`/`<Match>`
+ further down does not save you. This has blanked the calendar grid twice — see
+ `focusTarget` in `src/features/block-calendar/CalendarBlockAdapter.tsx` and
+ `useSystemSkillsQuery`.
+- **FE-52** Read reactive values (feature flags, `isEditable()`, the current
+ user) inside a reactive scope, never as a snapshot at mount. A flag that is
+ still loading is not "off".
diff --git a/.agents/rules/web/startup-bundle.md b/.agents/rules/web/startup-bundle.md
new file mode 100644
index 0000000000..9363b9fcb1
--- /dev/null
+++ b/.agents/rules/web/startup-bundle.md
@@ -0,0 +1,33 @@
+---
+description: "Keep the web startup bundle small: views, blocks, and modals load lazily."
+paths:
+ - "apps/web/src/**"
+ - "apps/web/index.html"
+globs: "apps/web/src/**,apps/web/index.html"
+alwaysApply: false
+---
+
+# Startup bundle
+
+- Everything statically reachable from `src/index.tsx` downloads and runs before
+ the first screen. Views, block components, and modals load through `lazy()` /
+ `lazyNamed` (`@core/util/lazyNamed`) inside a `<Suspense>`; never statically
+ import one into a shared hub (`Root`, `Layout`, `AppProviders`,
+ `componentRegistry`, `app-router-view`, `routes/shells.tsx`, block
+ `definition.ts`, Lexical `init.ts`).
+- Each top-level route picks its shell in `app-router-view.tsx`
+ (`routes/shells.tsx`): `authRoute` pages and booking links render without app
+ chrome, and `appRoute` renders `AppShell` — the app's providers
+ (`AppProviders`), chrome (`AppChrome` in `Layout.tsx`), and the split layout.
+ Put state only the app's views use in `AppProviders`, not `Root`; `Root` keeps
+ what every page or a call needs.
+- `index.html` paints a boot shell before any JS runs: the saved theme's
+ background, the rail column, and the desktop app's content card — no app
+ content. The first shell to mount dismisses it (`dismissBootShell`). Keep its
+ rail width and desktop inset in step with `SidebarRail` and `SplitLayout`.
+- Production web builds register `public/sw.js`: it serves the cached
+ `index.html` and content-hashed assets from Cache Storage and moves tabs to
+ newer builds. Set localStorage `macro:sw` to `off` to bypass it while
+ debugging.
+- The build fails if any emitted file exceeds CloudFront's 10 MB compression
+ limit; split it rather than raising the limit.
diff --git a/.agents/rules/web/ui-primitives.md b/.agents/rules/web/ui-primitives.md
new file mode 100644
index 0000000000..828e5038a7
--- /dev/null
+++ b/.agents/rules/web/ui-primitives.md
@@ -0,0 +1,28 @@
+---
+description: "Shared UI primitives keep Kobalte semantics, semantic tokens, a gallery page, and tests."
+paths:
+ - "apps/web/src/components/ui/**"
+globs: "apps/web/src/components/ui/**"
+alwaysApply: false
+---
+
+# UI primitives
+
+Applies to `apps/web/src/components/ui`, including ports from shadcn-solid.
+
+- Use the upstream structure and behavior as a starting point, then reshape
+ exports to match the local slot-based, compound-component API.
+- Replace upstream palette, surface, border, and status classes with the
+ existing semantic tokens; inputs normally use `bg-input`, `border-edge-muted`,
+ `text-ink`, and `text-ink-placeholder`.
+- Preserve Kobalte semantics, state attributes, and polymorphic prop types. Keep
+ accessibility relationships inside the primitive instead of recreating them at
+ call sites.
+- Add a co-located `*.docs.tsx` gallery page and focused `*.test.tsx` coverage
+ for every ported component.
+- Keep `Input` a thin native control. Use `InputGroup` for icons, clear actions,
+ inline Buttons, and shared ButtonGroup framing instead of adding composition
+ props to `Input`.
+- In `InputGroup`, keep the input as the single control and place surrounding
+ content in `Addon` slots. Use `align` for visual placement so accessible DOM
+ order stays independent of layout.
diff --git a/.agents/rules/web/ui.md b/.agents/rules/web/ui.md
new file mode 100644
index 0000000000..20a280ee85
--- /dev/null
+++ b/.agents/rules/web/ui.md
@@ -0,0 +1,71 @@
+---
+description: "Components, styling, and interaction conventions."
+paths:
+ - "**/*.tsx"
+globs: "**/*.tsx"
+alwaysApply: false
+---
+
+# UI conventions
+
+Components, styling, and interaction conventions.
+
+- **FE-22** Pending or permission-gated actions render as a dimmed version of
+ the real UI with inline accept/reject controls — not a generic placeholder
+ icon.
+- **FE-23** Disclosure carets rotate 180° to point down when expanded, matching
+ Discussion, SplitFileMenu, CollapsibleMessage, etc.
+- **FE-24** Truncated/collapsed controls get a tooltip (matching the app's
+ tooltip pattern) so the lost label stays discoverable.
+- **FE-25** Semantic color tokens, not raw Tailwind palette classes — the
+ default palette is disabled via `--color-*: initial` in
+ `apps/web/src/index.css`, so classes like `text-red-500` silently render
+ nothing. Enforced by ast-grep `tsx-no-raw-tailwind-palette`, CI error.
+- **FE-26** Prefer composition over configurability; keep reusable components
+ small and free of queries/complex state.
+- **FE-27** Don't add `cursor-pointer` to clickable elements. Enforced by
+ ast-grep `tsx-no-cursor-pointer`, warning.
+- **FE-28** Dialogs rely on Kobalte's default autofocus: make the intended
+ target the first tabbable element and preserve focus ownership for
+ restoration. Override `onOpenAutoFocus` only for a proven lifecycle
+ requirement, and verify `document.activeElement` after both opening and
+ reopening in the live app.
+- **FE-30** Never hoist Tailwind class strings into named constants (`const
+ DAY_CELL_CLASS = '...'`) — shared markup+styling is a component; a class
+ string can't carry structure, props, or behavior. Extract a component, or
+ inline the literal at its single use; styling variants are component props,
+ not exported strings. Enforced by ast-grep `tsx-no-class-string-consts`,
+ warning.
+- **FE-32** Prefer styling in the component (Tailwind on the markup). Reserve
+ `@utility` in `apps/web/src/index.css` for styles widely shared across many
+ components — not one-off or two-callsite layouts.
+
+## Components
+
+- Prefer composition over configurability. Follow slot-based patterns (see
+ src/features/channel, src/features/entity, or Kobalte).
+- Keep reusable components small, atomic, and decoupled from queries/complex
+ state. Push data-fetching and mutations up to use-case-specific composed
+ components.
+- Context should be scoped to a component subtree — Message.Content consuming a
+ MessageContext is fine because the ownership boundary is clear.
+- Composed primitives must not depend on use-case-specific context — a
+ RecipientsSelector should never require an EmailComposeContext.
+- New features and feature restructures use the layered layout in
+ [docs/architecture/frontend-features.md](../../../docs/architecture/frontend-features.md),
+ summarized by FE-33 (`core / queries / primitives / components / views` plus
+ an injected `context/`). Keep production wiring in an app-facing entry point
+ and give reactive logic narrow feature-owned contracts.
+ `src/features/activity` illustrates the layers but still has documented
+ composition and contract migration gaps.
+- **FE-53** Use the shared components in `apps/web/src/components/ui` (`@ui`)
+ whenever one fits; browse them at `/app/component/ui`. Don't build a one-off
+ button, dialog, menu, or input. A missing primitive is added there, with a
+ `*.docs.tsx` page and tests, not inside a feature.
+- **FE-54** Decide mobile behavior deliberately. Unless the change makes it
+ obvious, ask the user how a UI change should look and behave on mobile, then
+ follow [`mobile.md`](mobile.md).
+- **FE-55** UI tests drive real interactions (click, type, keyboard, focus)
+ through `@solidjs/testing-library` and assert what the user sees or can do.
+ No tests that only render and check classes, snapshot markup, or mock the
+ component under test; cover full flows with browser tests.
diff --git a/.claude/skills/add-sdk-endpoint/SKILL.md b/.agents/skills/add-sdk-endpoint/SKILL.md
similarity index 88%
rename from .claude/skills/add-sdk-endpoint/SKILL.md
rename to .agents/skills/add-sdk-endpoint/SKILL.md
index 214e3544ec..b230e482fd 100644
--- a/.claude/skills/add-sdk-endpoint/SKILL.md
+++ b/.agents/skills/add-sdk-endpoint/SKILL.md
@@ -41,12 +41,9 @@ To skip: add the method name, alphabetically, to `<camelService>Excluded` in
- create/list/search/lookup → the namespace
- new noun → new `src/entities/<noun>/` pair, registered in `src/macro.ts`
- cross-entity capability → a base in `src/entities/entity.ts`
-3. **Never take or return a raw id.** Wherever the generated endpoint takes an id,
- the SDK takes the entity handle and reads `.id` off it internally; wherever it
- returns an id, the SDK returns a handle. If the id refers to a noun that has no
- entity class yet, build that entity (and its namespace) as part of this change —
- do not fall back to a `string` parameter. The one exception is a `static byId`,
- which is how handles are minted in the first place.
+3. **Never take or return a raw id** (the [SDK rule](../../rules/sdk.md)). Take
+ the entity handle and return handles; if the noun has no entity class yet,
+ build it in this change rather than accepting a `string`.
4. **Match the conventions:**
- `static byId(client, id)`; detail via `Lazy` + `protected fetch()`, exposed with
`this.field(...)` / `this.mappedField(...)`
diff --git a/.claude/skills/add-tour/SKILL.md b/.agents/skills/add-tour/SKILL.md
similarity index 99%
rename from .claude/skills/add-tour/SKILL.md
rename to .agents/skills/add-tour/SKILL.md
index ebf8f292a4..8ec9f0dc37 100644
--- a/.claude/skills/add-tour/SKILL.md
+++ b/.agents/skills/add-tour/SKILL.md
@@ -156,5 +156,5 @@ list):
the tour reopens on every mount. Walk
every step, including one that waits on an entry, once with the sidebar
open and once collapsed.
-- Update `docs/AGENT_GUIDE/view-tours.md` when a view gains a tour or its steps
+- Update `docs/agent-guide/view-tours.md` when a view gains a tour or its steps
change.
diff --git a/.agents/skills/audit/SKILL.md b/.agents/skills/audit/SKILL.md
new file mode 100644
index 0000000000..d0ac2e4b50
--- /dev/null
+++ b/.agents/skills/audit/SKILL.md
@@ -0,0 +1,62 @@
+---
+name: audit
+description: Post-change checks before handing off. Works out which checks apply from the files changed (directory AGENTS.md Checks sections and matching .agents/rules), runs or verifies each, and reports pass/fail/skipped. Use before saying work is done, before pushing, or when asked to audit or verify a change.
+---
+
+# Audit
+
+Delegate to the `auditor` subagent when it is available, passing the base branch
+(default `origin/main`), so command output stays out of your context. Otherwise
+follow these steps yourself.
+
+## 1. Changed files
+
+```sh
+base=$(git merge-base HEAD origin/main)
+{ git diff --name-only "$base"; git ls-files --others --exclude-standard; } | sort -u
+```
+
+## 2. Collect the checks
+
+For every changed file:
+
+- **Directory guides.** Each `AGENTS.md` from the file's directory up to the repo
+ root: take its `## Checks` section, and the root guide's "Before handing off".
+- **Rules.** Each file in `.agents/rules/` whose `paths:` globs match the file, plus
+ rules with no `paths:`. Every bullet is a requirement to verify against the diff;
+ a `Check:` line is a step to run.
+- **Area defaults**, when no guide gives a more specific command:
+
+| Changed | Check |
+| --- | --- |
+| Any | `just check` |
+| Rust in a package | `cargo test -p <package>` (SQLX_OFFLINE unset), `cargo fmt --all -- --check`, `just clippy` |
+| `sqlx::query!` or migrations | `.sqlx/` regenerated and committed; migration works with the code already deployed |
+| `Cargo.toml` | `cargo x deps --check` |
+| `apps/web` | `bun run check` and `bun run test` for the touched features, in `apps/web` |
+| User-visible web behavior | Exercised in a browser; `docs/agent-guide` updated if routes, editors, AI surfaces, or composer changed |
+| `infra/` | `bun run --cwd infra check`; no deploy was run |
+| New or changed flow, cross-service call, queue, or background job | Instrumented per the observability rule; trace verified connected in Tempo, or listed as not verified |
+| Any behavior, API, name, or workflow change | Every doc that mentions it is updated: touched directories' `AGENTS.md`, `docs/guides/`, `docs/architecture/`, agent guide, READMEs, rules, skills (grep the changed names) |
+| Config, env vars, service URLs | Every copy and Doppler step in the config rule is done or listed as a follow-up |
+
+Deduplicate. Run one command per package, not per file.
+
+## 3. Run and verify
+
+Run each command. For rule bullets that no command covers, read the relevant diff
+hunks and judge. Don't stop at the first failure; finish the list.
+
+## 4. Report
+
+One table, failures first:
+
+| Result | Check | Source | Evidence |
+| --- | --- | --- | --- |
+| fail | `cargo test -p calendar_service` | area default | 2 failed: `sync::tests::…` |
+| pass | Decorator reserves its height | `web/lexical-nodes.md` | `Foo.tsx:40` sets `aspect-ratio` |
+| skipped | Browser check | root guide | No browser in this environment |
+
+A check is `pass` only if it ran or was verified in this audit. Explain every
+`skipped`. Then list fixes for each failure; do not claim the work is done while
+anything fails.
diff --git a/.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md b/.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md
index 8c5cd5c40f..7d7ebb8e8f 100644
--- a/.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md
+++ b/.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md
@@ -1,6 +1,6 @@
---
name: cloud-storage-hexagonal-architecture
-description: Enforce hexagonal architecture in the Rust backend. Use before modifying crates or Rust services, especially inbound axum/tool/listener adapters, domain services/ports, outbound adapters, authorization, permissions, database access, or external clients.
+description: Enforce hexagonal architecture in the Rust backend. Use before modifying crates/ or Rust services, especially inbound axum/tool/listener adapters, domain services/ports, outbound adapters, authorization, permissions, database access, or external clients.
---
# Cloud Storage Hexagonal Architecture Guard
@@ -190,7 +190,7 @@ If a step has no answer, stop and design that boundary before writing code.
## Review checklist
-For every diff under `crates/**` or `services/**`, reject or refactor if any of these are true:
+For every Rust backend diff, reject or refactor if any of these are true:
- `src/domain/**` imports `axum`, `http::StatusCode`, `IntoResponse`, `Json`, `Router`, `Request`, `HeaderMap`, SQLx pools/queries, AWS SDK clients, Redis clients, reqwest clients, `crate::inbound`, or `crate::outbound`.
- `src/inbound/**` contains SQLx queries, transaction handling, repository calls, AWS/Redis/OpenSearch/reqwest calls, or direct calls to outbound implementations.
diff --git a/.agents/skills/database-core/SKILL.md b/.agents/skills/database-core/SKILL.md
index 726a9cbb77..900577f0f6 100644
--- a/.agents/skills/database-core/SKILL.md
+++ b/.agents/skills/database-core/SKILL.md
@@ -40,7 +40,7 @@ Rust type names stay singular.
The Macro database app, CRM pipelines, and other consumers are hosts of the same
editor. A host supplies an authorized API and its capabilities; it should not
reimplement database editing, pagination, option creation, or refresh behavior.
-Follow the [frontend architecture](../../../docs/FRONTEND_FEATURE_ARCHITECTURE.md).
+Follow the [frontend architecture](../../../docs/architecture/frontend-features.md).
### Target ownership
@@ -125,5 +125,5 @@ wire host discovery/read/write tools explicitly without bypassing its permission
Read the [storage boundary](../../../crates/databases/README.md#storage-and-app-entities)
and [domain ports](../../../crates/databases/src/domain/ports.rs) before wiring a
-consumer. Follow the [database guide](../../../docs/DATABASE_DEVELOPMENT.md) for
+consumer. Follow the [database guide](../../../docs/development/database.md) for
schema and migration work.
diff --git a/.agents/skills/debug-service/SKILL.md b/.agents/skills/debug-service/SKILL.md
index fcbbbdfb6d..f56c50752d 100644
--- a/.agents/skills/debug-service/SKILL.md
+++ b/.agents/skills/debug-service/SKILL.md
@@ -1,6 +1,6 @@
---
name: debug-service
-description: Debug local Rust services in this repository by starting the crate's binary with debug logging, tailing service logs, and using those logs to answer runtime questions. Use when Codex needs to investigate service startup, runtime behavior, errors, or logs for a Rust binary in a crate.
+description: Debug local Rust services in this repository by starting the crate's binary with debug logging, tailing service logs, and using those logs to answer runtime questions. Use when investigating service startup, runtime behavior, errors, or logs for a Rust binary in a crate.
---
# Debug Service
diff --git a/.agents/skills/dependabot/skill.md b/.agents/skills/dependabot/SKILL.md
similarity index 100%
rename from .agents/skills/dependabot/skill.md
rename to .agents/skills/dependabot/SKILL.md
diff --git a/.claude/skills/define-feature-flag/SKILL.md b/.agents/skills/feature-flags/SKILL.md
similarity index 50%
rename from .claude/skills/define-feature-flag/SKILL.md
rename to .agents/skills/feature-flags/SKILL.md
index 295feab299..5b6434e828 100644
--- a/.claude/skills/define-feature-flag/SKILL.md
+++ b/.agents/skills/feature-flags/SKILL.md
@@ -1,12 +1,12 @@
---
-name: define-feature-flag
-description: Define a frontend feature flag with `defineFlag` and wire its readers. Use when adding, suggesting, or changing a feature flag, PostHog flag, `ENABLE_*` env flag, `useFeatureFlag`, `isFeatureEnabled`, or `ShowFeatureFlag`.
+name: feature-flags
+description: Add, read, or remove a feature flag in the web app (`defineFlag`, PostHog, `ENABLE_*` env flags, `useFeatureFlag`, `isFeatureEnabled`, `ShowFeatureFlag`) or the Rust backend (`crates/feature_flags`, config switches). Use when gating, rolling out, or killing a feature, or when asked to "flag it".
---
-# Define a frontend feature flag
+# Feature flags
-Frontend only. Registry: `apps/web/src/lib/core/constant/featureFlags.ts`.
-There is no shared backend flag system.
+Web registry: `apps/web/src/lib/core/constant/featureFlags.ts`. Backend: see
+section 5. A flag is never an authorization check.
## 1. Remote or env-only?
@@ -55,8 +55,10 @@ export const ENABLE_BAR = defineFlag({
}).enabled;
```
-Do not create the PostHog flag. Ask which project / environment it should live
-in and wait.
+The PostHog MCP (in the repo's MCP config) can look up existing flags and
+their rollout. Don't create or change a PostHog flag without asking which
+project and rollout the user wants, and never change a production rollout
+without explicit permission.
## 3. Read it
@@ -73,6 +75,42 @@ requires calendar UI), not on the flag object.
`useFeatureFlag` / `ShowFeatureFlag` take a `RemoteFlag`. Passing an env-only
flag is a type error.
+## 4. Get the rollout right
+
+These are the mistakes past flagged launches had to fix:
+
+- **Loading is not off.** Until PostHog answers, `isFeatureEnabled` returns
+ `false` and `useFeatureFlag` returns `{ loading: true }`. A cold deep link
+ must wait for `loading` to clear rather than fall back to the off path (see
+ `block-database`'s `load`), or the page flashes or degrades.
+- **Read reactively** (FE-52): call `isFeatureEnabled` / `useFeatureFlag` inside
+ a reactive scope, never snapshot it at mount or module load.
+- **Gate every entry point**: routes, deep links, previews, copy-link,
+ notifications, command menu, mobile surfaces, and agent/MCP tools that
+ expose the feature, not just the main button.
+- **Off keeps today's behavior.** A flagged change must leave the off path
+ exactly as it was.
+- **Keep the kill switch.** A remote flag that defaults on (`default: true`)
+ can no longer be turned off from PostHog; use `undefined` so PostHog stays in
+ control.
+
+## 5. Backend
+
+- **Per-user remote flags** use `crates/feature_flags` (read its `README.md`):
+ construct `PostHogFeatureFlags` once at the composition root, load one
+ `FlagSnapshot` per authenticated user id, and read it synchronously. A failed
+ load returns `Err`; the caller decides the fallback, explicitly. The crate has
+ no callers yet, so the first one also wires the adapter and its config.
+- **Deployment switches** (on for an environment, not per user) are
+ `MacroConfig` bools with a default, configured in Doppler (see the config
+ rule), not PostHog.
+- Keep the backend and web flag keys identical when both gate one feature.
+
+## 6. Remove it
+
+When a flag is fully rolled out, delete the `defineFlag`, every reader, and the
+off path in the same change, and say which PostHog flag can be archived.
+
## Don't
- Migrate existing FLAG / OVERRIDE / string `useFeatureFlag` call sites unless
diff --git a/.agents/skills/git/SKILL.md b/.agents/skills/git/SKILL.md
new file mode 100644
index 0000000000..fffcd2d467
--- /dev/null
+++ b/.agents/skills/git/SKILL.md
@@ -0,0 +1,94 @@
+---
+name: git
+description: Commit, branch, push, and open or update pull requests in this repository. Use before writing a commit message or PR title/body, pushing, stacking PRs, or when asked to "commit", "open a PR", or "push".
+---
+
+# Git and pull requests
+
+Commit as you go on a feature branch, one logical change per commit, without
+asking. Never commit to `main`. Push or open a PR only when the user asks.
+
+## Branches
+
+`<user>/<topic>` in kebab-case, for example `wolf/agent-rules`. One concern per
+branch. For dependent work, stack branches and open one PR per layer, each based on
+the branch below it.
+
+## Commits and PR titles
+
+[Conventional Commits](https://www.conventionalcommits.org): `type(scope): summary`.
+The PR title follows the same form; squash merges use it as the commit on `main`.
+
+- **type:** `feat`, `fix`, `perf`, `refactor`, `docs`, `test`, `ci`, `build`,
+ `chore`. A breaking change adds `!` (`feat!:`) and says what breaks in the body.
+- **scope:** the feature or crate a reader would recognise, lowercase:
+ `channels`, `crm`, `auth`, `mcp`, `sync-service`. Omit it when the change is
+ genuinely repo-wide.
+- **summary:** what changes for the user or caller, imperative, lowercase start,
+ no trailing period, about 72 characters at most.
+ `fix(channels): open conversations without loading their read history`, not
+ `fix: update channel loading logic`.
+- **body:** why the change was needed and anything a reviewer can't see in the
+ diff. Wrap at 72 columns.
+
+## Before pushing
+
+Run what applies to the files you changed, and fix failures before pushing:
+
+```sh
+just check # format, lint, code rules on changed files
+cargo fmt --all -- --check # any Rust change
+cargo x deps --check # Cargo.toml or crate added/removed
+cargo x workflows --check # workflow generators changed
+cargo x kafka-topics --check # macro_event_topics changed
+```
+
+GitHub Actions workflows are generated from Rust: edit
+`tooling/xtask/crates/xtask_workflows`, never the YAML (see the
+[workflows rule](../../rules/infra/github-workflows.md)).
+
+Run the `audit` skill before handing off; it covers tests and area checks.
+
+## PR description
+
+Write for a reviewer who hasn't seen the conversation. Use these sections, in
+order, and drop any that would be empty:
+
+```markdown
+## Why
+
+The problem or goal, with the evidence: the bug and how it shows up, numbers
+measured, the user request. Link issues.
+
+## How it works
+
+A short high-level explanation of the approach, plus an ASCII diagram of the
+flow, data shape, or before/after when one helps (cross-service flows, state
+machines, pipelines). Drop it for small or mechanical changes.
+
+## What
+
+- One bullet per meaningful change, in reading order. Name files or modules
+ when it helps navigation. Call out decisions and alternatives rejected.
+
+## Follow-ups
+
+- Work deliberately left out, with the reason.
+```
+
+No test plan or testing section in PR descriptions or commit messages: CI shows
+the checks, and what you ran goes in your report to the user. Attach proof for
+user-visible changes: screenshots or a recording (see the `record-proof` skill
+when it is available).
+
+## Handing off a PR
+
+Open PRs ready for review, not as drafts; if one was created as a draft, mark it
+ready. A PR whose checks are failing or still running is not done: watch CI and fix
+failures before handing off.
+
+## Updating a PR
+
+Push follow-up commits rather than force-pushing over review history, unless the
+user asks for a rebase. When the scope changes, update the title and the What
+section to match.
diff --git a/.agents/skills/instrumentation/SKILL.md b/.agents/skills/instrumentation/SKILL.md
new file mode 100644
index 0000000000..e500229aee
--- /dev/null
+++ b/.agents/skills/instrumentation/SKILL.md
@@ -0,0 +1,94 @@
+---
+name: instrumentation
+description: >-
+ Add OpenTelemetry tracing to a new flow or hot path, frontend or backend.
+ Use when building a user-facing flow, a cross-service call, a queue or
+ background job, or code on a latency-sensitive path; when adding spans,
+ span attributes, or trace propagation; or when a trace in Tempo/Datadog is
+ missing, disconnected, or opaque.
+---
+
+# Instrumentation
+
+New flows and hot paths ship instrumented, in the same change. The standard is
+the [observability rule](../../rules/observability.md): one connected trace from
+the user's action through every service, with phases timed and the entity id on
+the spans. This skill is how to meet it.
+
+## Pick the shape first
+
+Before writing code, sketch the trace you want to read during an incident:
+
+```text
+doc.open (browser, root, document.id)
+├─ doc.load
+│ └─ doc.load.context (HTTP → DSS, traceparent header)
+├─ doc.seed / doc.sync.catchup
+└─ sync-service connect (WebSocket, traceparent query param)
+```
+
+One root span per user action, one child per phase a reader would ask about
+(network, queue wait, processing, each external call), and the id you'd search
+by on the root.
+
+## Frontend and Cloudflare Workers
+
+Use the `@macro-inc/observability` facade (`packages/observability`); never
+import OpenTelemetry directly.
+
+- `Telemetry.span(name, fn)` for a phase; `span.span(name, fn)` for a child.
+ `Telemetry.clientSpan(name)` for an outbound call, then
+ `span.injectTraceHeaders(headers)`.
+- `span.setAttr(key, value)` for ids and counts; `span.error(message)` on
+ failure; manual spans must `end()` on every path.
+- A flow that spans components or outlives one call keeps its root span in a
+ registry keyed by entity id and resumes it later (see the document example).
+- Transports without headers carry `span.traceparent()` another way, such as a
+ WebSocket query parameter.
+- Workers wrap their handler with `instrument()` and `createWorkerTraceConfig`
+ from `@macro-inc/observability/worker`, which adopts the incoming
+ `traceparent`.
+
+## Rust services
+
+- HTTP handlers already get spans from `macro_tower_layers`; outbound HTTP calls
+ `macro_tower_layers::inject_trace_headers`.
+- `#[tracing::instrument(skip_all, fields(document_id = %id), err)]` on domain
+ operations and outbound adapters (CS-22: `err` only on `Result`, no
+ `level = "info"`).
+- Kafka: `kafka_util` injects trace headers on publish; consumers open
+ `kafka_util::consumer_span` and call `record_span_error` on failure.
+- Agent/ACP messages: `genai_telemetry::propagation::inject` / `set_parent`
+ carry context in `_meta`; GenAI spans follow CS-55.
+- Spawned tasks take the span with them (`.instrument(span)`) or link to it.
+
+## Worked examples
+
+**Document open lifecycle (web → DSS → sync-service).**
+`apps/web/src/features/block-md/definition.ts` starts or resumes `doc.open`
+(`document.id`, `doc.type`) and times `doc.load` → `doc.load.context`.
+`apps/web/src/features/block-md/observability.ts` keeps open document spans by
+id so the launcher's `doc.create`, the collab provider, and the sync client all
+attach to one trace. `packages/collaboration/src/collab/telemetry.ts` stamps
+`document.id` and `session.id` on `doc.seed`, `doc.sync.catchup`, and
+`edit.apply`. The sync WebSocket carries `traceparent` as a query parameter,
+which sync-service reads with `worker_rs_otel::traceparent_from_request`.
+
+**Agent editing (web or Rust → ai-editing-worker → sync-service).**
+The web client (`apps/web/src/lib/service-clients/ai-editing-worker/client.ts`)
+opens `http POST /edit` under the document's span; Rust callers
+(`crates/documents/src/outbound/editing_worker_client.rs`) inject headers from
+an instrumented method. The worker
+(`services/ai-editing-worker/src/endpoints/edit.ts`) roots an `edit.session`
+with outcome fields (`edit.mode`, `edit.ops_total`, `edit.blocked`,
+`edit.aborted`), then a child per phase: `edit.sync_init`, `edit.hydrate`,
+`edit.interpret`, `edit.supervise.turn`, `edit.dispatch`, `edit.run_code`,
+`edit.flush`. On the agent side, `crates/agent_session/src/domain/session/telemetry.rs`
+emits `invoke_agent` and `execute_tool` and propagates into the ACP agent.
+
+## Verify
+
+Run the flow on the local stack and find its trace (see the `live-debug`
+skill): one trace from browser to the last service, each phase visible with its
+duration, findable by the entity id, and failures marked as errors. Report the
+trace as verified or say it wasn't.
diff --git a/.agents/skills/live-debug b/.agents/skills/live-debug
deleted file mode 120000
index ba58e5e29a..0000000000
--- a/.agents/skills/live-debug
+++ /dev/null
@@ -1 +0,0 @@
-../../.claude/skills/live-debug
\ No newline at end of file
diff --git a/.claude/skills/live-debug/SKILL.md b/.agents/skills/live-debug/SKILL.md
similarity index 86%
rename from .claude/skills/live-debug/SKILL.md
rename to .agents/skills/live-debug/SKILL.md
index 75f5096ec3..34a8d97305 100644
--- a/.claude/skills/live-debug/SKILL.md
+++ b/.agents/skills/live-debug/SKILL.md
@@ -129,7 +129,7 @@ and the Rust handler share one trace ID.
The condensed version is below; the full field-tested guide (routes, every
surface, keyboard model, crash recovery, trace correlation from a network
-request's `traceparent`) is `docs/AGENT_GUIDE/`.
+request's `traceparent`) is `docs/agent-guide/`.
- Unauthenticated users land on `/app/welcome`: "Continue with email" → fill
the email input → "Continue". Locally this may log in with no code prompt;
@@ -154,22 +154,9 @@ request's `traceparent`) is `docs/AGENT_GUIDE/`.
## Write tracing code that is debuggable
-Follow CLAUDE.md's tracing rules (`err` on `Result`-returning `#[instrument]`,
-never `level = "info"`, `tracing::error!(error=?e, "msg")`, prefer
-`.inspect_err`). Beyond those:
-
-- Instrument boundaries, not plumbing: HTTP handlers get spans from
- `macro_tower_layers`; add `#[tracing::instrument]` to queue consumers,
- cross-service client calls, and multi-step business operations — the places
- a trace would otherwise go dark.
-- Skip bulky args (`#[instrument(skip(payload), fields(document_id = %id))]`)
- and record the IDs you will actually search by: entity IDs, user IDs,
- counts. A span you can't find by ID is a span you can't use.
-- Record late-known values with `tracing::Span::current().record(...)` rather
- than emitting a second event.
-- Events inside a span inherit its trace: one `tracing::warn!` with fields
- beats three unstructured `debug!`s. Fields, not format strings —
- `warn!(attempts, "retrying")`, not `warn!("retrying attempt {attempts}")`.
-- Verify your instrumentation live: run the code path, then confirm the span
- shows up in Tempo with the fields you expect. Unverified instrumentation is
- the usual reason "the trace was empty" during a real incident.
+How to add spans is the `instrumentation` skill; the conventions are the
+always-on [observability rule](../../rules/observability.md) and CS-22 in
+[`rust/code.md`](../../rules/rust/code.md). Use the queries above to verify new
+instrumentation live: run the code path and confirm the span shows up in Tempo,
+connected to its parent trace, with the fields you expect. Unverified
+instrumentation is the usual reason "the trace was empty" during an incident.
diff --git a/.agents/skills/local-preview/SKILL.md b/.agents/skills/local-preview/SKILL.md
new file mode 100644
index 0000000000..172dc5b9fc
--- /dev/null
+++ b/.agents/skills/local-preview/SKILL.md
@@ -0,0 +1,87 @@
+---
+name: local-preview
+description: Start a local preview of the app for the user and share an HTTPS link to it. Use when asked for a local preview, to "run it", "spin it up", "show me", or for a link to try a change on this machine (not Cursor Cloud; that is the run-app skill).
+---
+
+# Local preview
+
+Two ways to preview, from [running locally](../../../docs/development/running-locally.md).
+Pick one, start it, and hand the user an HTTPS hostname link.
+
+| Preview | Runs | Use when |
+| --- | --- | --- |
+| **Web app only** | Vite in `apps/web` against hosted `*-dev` services | The change is frontend-only (`apps/web`, `packages/`) |
+| **Full stack** | Docker infra, local Rust services, Caddy proxy, frontend | The change touches `crates/`, `services/`, migrations, or needs private data |
+
+## 1. Choose
+
+- Look at the changed files (`git diff --name-only $(git merge-base HEAD origin/main)`
+ plus uncommitted ones). Only frontend paths: web app. Only backend paths, or
+ both: full stack (it includes the frontend).
+- If it isn't obvious (no changes yet, or the user wants to try something
+ unrelated to the diff), ask the user: "web app only, or the full local stack?"
+ Mention the trade: the web app starts in a minute against shared dev data; the
+ stack takes several minutes and runs everything locally.
+
+## 2. Start it
+
+**Web app only**
+
+1. Pick a free port; never assume 3000 is yours:
+ `lsof -nP -iTCP:<port> -sTCP:LISTEN -t`. Reuse a running Vite only if its cwd
+ (`lsof -p <pid> | awk '$4=="cwd"'`) is this worktree.
+2. From `apps/web`, inside the Nix shell, run `PORT=<port> bun run dev` in the
+ background. The first run may build wasm for a few minutes.
+3. Wait for Vite to print `App: https://<hostname>:<port>/app/`.
+
+**Full stack**
+
+1. Use a named instance per worktree so you never collide with another session:
+ `--instance <worktree-name>`. Never stop, reset, or destroy an instance you
+ didn't start.
+2. Prefer headless for an agent: `just stack up --instance <name>` (add
+ `--no-doppler` if Doppler isn't authenticated). It serves a static build of
+ the frontend; after frontend edits run `just stack update --frontend
+ --instance <name>`, after Rust edits `just stack update --instance <name>`.
+ If the user wants live reload, run `just run_local --instance <name>`
+ attached in a terminal they can see instead.
+3. Read the proxy port from `just stack status --json --instance <name>`, and
+ build the link from `hostname`, even if a URL is printed with `localhost`.
+4. Offer seed data: `just seed-scenario --instance <name> apply --file
+ seed/scenarios/team-perms.json` prints persona login links.
+
+If startup fails, run `just doctor-local --instance <name>`; for running-stack
+problems use the `live-debug` skill. Don't wipe volumes to recover.
+
+## 3. Share the link
+
+Always share the HTTPS URL on the machine's hostname, never `localhost`, an IP
+address, or plain HTTP:
+
+- Web app: `https://<hostname>:<port>/app/`
+- Full stack: `https://<hostname>:<proxy-port>/app/`
+
+The certificate is issued from the repo's development CA for the output of
+`hostname` (plus `localhost` and loopback); an IP address isn't in it, so an IP
+link fails TLS. Tell the user, once:
+
+- Trust `infra/local/certs/ca.pem` on the viewing machine (see
+ `infra/local/certs/README.md`).
+- The viewer must resolve the hostname and reach the port (same network or
+ tailnet).
+- Sign in with an email code on that hostname. On the web-app preview it is a
+ real email to a dev account; on the stack the code lands in Mailpit, served
+ at `https://<hostname>:<proxy-port>/mailpit/` by a headless stack (with
+ attached `run_local`, use the Mailpit URL it prints).
+
+Public links: only if the user explicitly asks to share outside their network.
+Then the stack needs `just run_local --instance <name> --with-cf-tunnel`, which
+prints a `https://….trycloudflare.com/app/` URL. Say first that it publishes a
+passwordless-login stack to the internet.
+
+## 4. Report
+
+One short message: which preview and why, the HTTPS link, how to sign in, how to
+stop it (`q` in an attached `run_local`, `just stop_local --instance <name>` for
+headless, or the background Vite process), and anything that failed or was
+skipped.
diff --git a/.agents/skills/new-service/SKILL.md b/.agents/skills/new-service/SKILL.md
new file mode 100644
index 0000000000..9b3c13095b
--- /dev/null
+++ b/.agents/skills/new-service/SKILL.md
@@ -0,0 +1,19 @@
+---
+name: new-service
+description: Create and register a new deployable service (Rust ECS service, worker, Kafka consumer, or Cloudflare Worker). Use when adding a directory under services/, a new Pulumi stack, or wiring an existing binary for deployment.
+---
+
+# New service
+
+Follow [docs/guides/new-service.md](../../../docs/guides/new-service.md)
+section by section. It is the checklist; this skill makes sure none of it is skipped.
+
+1. Pick the model to copy from the guide's table and say which one.
+2. Make a task list with one item per guide section that applies (crate, deploy
+ inventory, infrastructure, config and secrets, service discovery, local stack,
+ API clients, Kafka topics). Mark sections that don't apply, with the reason.
+3. Work through the list. For each section, re-read it in the guide before
+ editing; the pitfalls are inline.
+4. Run the guide's "Verify locally" commands and report each result.
+5. Do not deploy, create Doppler values, or remove `bootstrap_pending`. List
+ those as follow-ups for the user, with the exact steps from "After merge".
diff --git a/.claude/skills/run-app/SKILL.md b/.agents/skills/run-app/SKILL.md
similarity index 100%
rename from .claude/skills/run-app/SKILL.md
rename to .agents/skills/run-app/SKILL.md
diff --git a/.pi/skills/rust-validation/SKILL.md b/.agents/skills/rust-validation/SKILL.md
similarity index 100%
rename from .pi/skills/rust-validation/SKILL.md
rename to .agents/skills/rust-validation/SKILL.md
diff --git a/.pi/skills/sqlx-migration/SKILL.md b/.agents/skills/sqlx-migration/SKILL.md
similarity index 100%
rename from .pi/skills/sqlx-migration/SKILL.md
rename to .agents/skills/sqlx-migration/SKILL.md
diff --git a/.pi/skills/sqlx-query-validator/SKILL.md b/.agents/skills/sqlx-query-validator/SKILL.md
similarity index 100%
rename from .pi/skills/sqlx-query-validator/SKILL.md
rename to .agents/skills/sqlx-query-validator/SKILL.md
diff --git a/.agents/skills/upgrade-model/SKILL.md b/.agents/skills/upgrade-model/SKILL.md
index 195ab7ed9f..8a2a6b2b55 100644
--- a/.agents/skills/upgrade-model/SKILL.md
+++ b/.agents/skills/upgrade-model/SKILL.md
@@ -10,7 +10,7 @@ Upgrades the AI model used in the chat app. There are two model slots:
- **fast** (Enter): default/fallback model (first entry in `CHAT_MODELS`)
- **good** (Cmd+Enter): smart mode model (second entry in `CHAT_MODELS`)
-The user must specify which slot to upgrade and the new model name (e.g. `Codex-opus-4-6`).
+The user must specify which slot to upgrade and the new model name (e.g. `claude-opus-4-6`).
## Steps
@@ -18,14 +18,14 @@ The user must specify which slot to upgrade and the new model name (e.g. `Codex-
Ask the user (if not already provided):
- Which slot: `fast` or `good`?
-- What is the new model name? (e.g. `Codex-opus-4-6`)
+- What is the new model name? (e.g. `claude-opus-4-6`)
Derive from the model name:
-- `SERDE_NAME`: the kebab-case model ID sent over the wire (e.g. `Codex-opus-4-6`)
+- `SERDE_NAME`: the kebab-case model ID sent over the wire (e.g. `claude-opus-4-6`)
- `ENUM_VARIANT`: PascalCase variant name (e.g. `Claude46Opus`)
- `CONST_NAME`: SCREAMING_SNAKE constant name (e.g. `CLAUDE_46_OPUS`)
-- `CONST_VALUE`: display string used by the frontend/provider (e.g. `Codex-4.6-opus`)
-- `PRETTY_NAME`: human-readable name (e.g. `Codex Opus 4.6`)
+- `CONST_VALUE`: display string used by the frontend/provider (e.g. `claude-4.6-opus`)
+- `PRETTY_NAME`: human-readable name (e.g. `Claude Opus 4.6`)
### 2. Add model to AI crate (if it doesn't already exist)
diff --git a/.agents/templates/AGENTS.md b/.agents/templates/AGENTS.md
new file mode 100644
index 0000000000..226107ab46
--- /dev/null
+++ b/.agents/templates/AGENTS.md
@@ -0,0 +1,58 @@
+# <crate or directory name>
+
+Status: legacy — do not extend; use `<replacement>` | migrating to `<target>`
+
+## What it is
+
+<Which product feature this belongs to (Calendar, CRM, agent sessions, ...) and
+what this crate does for it, in one to three sentences.>
+
+## How it works
+
+<Optional. The main flow in a few lines: what comes in, the key steps, what
+comes out. Omit when "Start here" already makes it obvious.>
+
+## Start here
+
+- `src/<file>`: <why to read it first>
+
+## Scope
+
+- Owns: <responsibilities>
+- Not here: <neighbouring responsibility> → `crates/<owner>`
+
+## Boundaries
+
+- Depends on: <ports, domain crates>
+- Used by: <callers that matter>
+
+## Recipes
+
+- Add a <thing>: `<file>` → `<file>` → `<file>`
+
+## Checks
+
+- `cargo test -p <package>`
+- If <condition>: `<command>`
+
+## Gotchas
+
+- <non-obvious invariant an agent would get wrong; link a rule instead of restating it>
+
+## Related
+
+- Rules: `.agents/rules/<file>` · Skills: `<skill>` · Docs: `docs/<file>`
+
+<!--
+Writing rules:
+- Under ~50 lines; up to ~70 only for very large crates. Every line is something an agent would otherwise get wrong or
+ spend time rediscovering.
+- Nothing a file listing, the code, or a crate-level doc comment already says.
+- Delete empty sections instead of filling them.
+- Status: omit the line for active crates; include it only for legacy or migrating ones.
+- Boundaries is for shared libraries and domain crates. For a leaf service, put its
+ callers in Scope and drop the section. "Used by" names the callers that matter,
+ not every dependent.
+- Don't restate rules from .agents/rules; link them.
+- A sibling CLAUDE.md is a symlink to this file: `ln -s AGENTS.md CLAUDE.md`.
+-->
diff --git a/.agents/templates/rule.md b/.agents/templates/rule.md
new file mode 100644
index 0000000000..255cbfd4f2
--- /dev/null
+++ b/.agents/templates/rule.md
@@ -0,0 +1,19 @@
+---
+description: "<One sentence: the rule, stated as the outcome.>"
+paths:
+ - "<glob where an agent editing these files needs this rule>"
+globs: "<same globs, comma-separated, for Cursor>"
+alwaysApply: false
+---
+
+<!-- Quote description and globs: a leading `*` or a `: ` breaks YAML.
+ Omit paths and set alwaysApply: true only for rules every session needs. -->
+
+# <Rule as an imperative title>
+
+<Why: the failure this prevents, in one or two sentences.>
+
+- <What to do. Name the existing helper or pattern to reuse.>
+- <What not to do.>
+
+Check: <How to verify compliance, for the audit skill.>
diff --git a/.claude/agents b/.claude/agents
new file mode 120000
index 0000000000..4c8a5fc93d
--- /dev/null
+++ b/.claude/agents
@@ -0,0 +1 @@
+../.agents/agents
\ No newline at end of file
diff --git a/.claude/rules b/.claude/rules
new file mode 120000
index 0000000000..2d5c9a97a7
--- /dev/null
+++ b/.claude/rules
@@ -0,0 +1 @@
+../.agents/rules
\ No newline at end of file
diff --git a/.claude/skills b/.claude/skills
new file mode 120000
index 0000000000..2b7a412b8f
--- /dev/null
+++ b/.claude/skills
@@ -0,0 +1 @@
+../.agents/skills
\ No newline at end of file
diff --git a/.claude/skills/cloud-storage-hexagonal-architecture/SKILL.md b/.claude/skills/cloud-storage-hexagonal-architecture/SKILL.md
deleted file mode 100644
index 7d7ebb8e8f..0000000000
--- a/.claude/skills/cloud-storage-hexagonal-architecture/SKILL.md
+++ /dev/null
@@ -1,232 +0,0 @@
----
-name: cloud-storage-hexagonal-architecture
-description: Enforce hexagonal architecture in the Rust backend. Use before modifying crates/ or Rust services, especially inbound axum/tool/listener adapters, domain services/ports, outbound adapters, authorization, permissions, database access, or external clients.
----
-
-# Cloud Storage Hexagonal Architecture Guard
-
-Use this skill whenever you add, change, or review Rust code under `crates/**` or `services/**` that touches a crate with `src/domain`, `src/inbound`, or `src/outbound`.
-
-This repository follows the ports-and-adapters / hexagonal style described in _Master Hexagonal Architecture in Rust_ and the `howtocodeit/hexarch` `3-simple-service` branch: domain models + ports + services are the center; inbound and outbound adapters are replaceable shells around that center.
-
-## Non-negotiable dependency rule
-
-Dependencies point inward:
-
-```text
-inbound adapters ──► domain ports/models/services ◄── outbound adapters
-composition root ──► inbound + domain service + outbound implementations
-```
-
-- `domain/` must not depend on `inbound/`, `outbound/`, `axum`, HTTP response types, SQLx pools/queries, AWS SDKs, Redis, reqwest, environment variables, or transport DTOs.
-- `inbound/` may depend on domain ports/models/services. It must not own business decisions or persistence/external-service implementation details.
-- `outbound/` implements domain ports for databases, S3, HTTP clients, queues, metrics, etc. It must not own use-case policy.
-- Wiring concrete adapters into services belongs in the composition root / builder, not inside domain logic or handlers.
-
-## Layer responsibilities
-
-### Domain (`src/domain/**`)
-
-Put the following here:
-
-- Domain models, value objects, command/request types, response types, and domain errors.
-- Service/use-case traits exposed to inbound adapters.
-- Concrete domain service implementations that orchestrate a use case.
-- Port traits for required capabilities: repositories, authorizers, notifiers, event publishers, clocks, ID generators, metrics, external domain services.
-- Business invariants, state transitions, authorization policy, ownership checks, permission-level checks, tenant/team/workspace policy, filtering rules, and side-effect orchestration.
-
-### Inbound adapters (`src/inbound/**`)
-
-Axum handlers, AI tools, Kafka/listener handlers, lambda handlers, and CLI entrypoints are adapters. Keep them thin:
-
-- Extract authentication/identity from transport (`MacroAuthorizationExtractor`, `OptionalMacroAuthorizationExtractor`, JWT, signed internal header, request context).
-- Parse path/query/body/header data and perform transport/syntax validation.
-- Convert transport DTOs into domain request/command types.
-- Call exactly the appropriate domain service/port method.
-- Convert domain success/errors into transport responses/status codes/tool output.
-
-Inbound adapters must not:
-
-- Decide whether a user may access/edit/delete/share/list an entity.
-- Call `entity_access`, `roles_and_permissions`, repositories, SQLx, S3, Redis, SQS, reqwest, or other outbound implementations to make a use-case decision.
-- Branch on `AccessLevel`, role, owner/admin/member, tenant/team membership, project membership, subscription tier, feature entitlement, entity state, or ownership for business policy.
-- Filter returned entities by permissions or hide fields based on authz rules.
-- Start transactions or compose multiple persistence/external calls as the core use case.
-
-### Outbound adapters (`src/outbound/**`)
-
-Put implementation details here:
-
-- SQLx queries and transaction mechanics.
-- AWS/Redis/OpenSearch/HTTP client calls.
-- Mapping external errors to domain errors as required by a port contract.
-- Implementing repository/authorizer/client/notifier ports.
-
-Outbound adapters must not:
-
-- Import `crate::inbound::*`, axum extractors/responses, or transport DTOs.
-- Invent business policy beyond faithfully implementing the domain port contract.
-- Decide use-case flow; return facts/capabilities/results for the domain service to decide.
-
-## Authorization and `EntityAccessReceipt` rule
-
-Authentication can happen at the edge. Entity access checks should cross the boundary as a typed capability: `EntityAccessReceipt<T>`.
-
-`EntityAccessReceipt<T>` means the entity access layer has verified the caller has at least permission `T` for the entity. Inbound adapters may obtain this receipt through the standard access extractors or by calling the entity access service specifically to mint a receipt. After that, ordinary handlers/tools/listeners must pass the receipt inward instead of re-checking or branching on authorization.
-
-Allowed in inbound:
-
-- Reject missing/invalid credentials (`401` / unauthenticated).
-- Extract `actor`, `request_context`, `user_id`, service identity, internal principal, or a typed `EntityAccessReceipt<T>`.
-- Use standard access extractors or `generate_entity_access_receipt::<RequiredLevel>(...)` to mint a receipt.
-- Pass the receipt and parsed request data into the domain service call.
-- Convert domain/access errors into transport responses.
-
-Forbidden in ordinary inbound handlers/tools/listeners:
-
-- `if user_id != owner_id { ... }`
-- `if access_level < Edit { ... }`
-- `entity_access_service.get_access_level(...)` or `can_edit(...)` followed by allow/deny branching.
-- Role/team/tenant/project permission checks.
-- Inspecting `receipt.entity_permission()` to decide use-case business policy.
-- Direct repository/persistence calls for the protected action.
-
-Correct pattern:
-
-1. Pick the minimum required permission type for the use case, e.g. `ViewAccessLevel`, `EditAccessLevel`, or `OwnerAccessLevel`.
-2. In inbound, obtain `EntityAccessReceipt<RequiredLevel>` using the existing entity access boundary.
-3. Pass that receipt to the domain service method.
-4. In the domain service, perform use-case-specific policy that is not captured by the minimum receipt type, e.g. owner-only share changes inside an edit operation.
-5. Return a domain error such as `Unauthorized`, `Forbidden`, or a typed policy error.
-6. Let inbound map that domain/access error to HTTP/tool/listener semantics.
-7. Unit-test allow and deny cases at the domain service level with fake receipts/ports.
-
-## Bad vs good
-
-Bad: the handler branches on permissions and performs the protected action itself.
-
-```rust
-pub async fn edit_document_handler(
- State(state): State<DocumentRouterState>,
- Json(args): Json<EditDocumentServiceArgs>,
-) -> Result<Json<EditDocumentResponse>, DocumentError> {
- let access_level = state
- .entity_access
- .get_access_level(current_user(), &args.document_id, EntityType::Document)
- .await?
- .ok_or(DocumentError::Unauthorized)?;
-
- if access_level < AccessLevel::Edit {
- return Err(DocumentError::Unauthorized);
- }
-
- if args.share_permission.is_some() && access_level != AccessLevel::Owner {
- return Err(DocumentError::Unauthorized);
- }
-
- state.document_repo.update_document(args).await?;
- Ok(Json(EditDocumentResponse::success()))
-}
-```
-
-Good: inbound obtains a typed receipt and forwards it; the domain service owns policy and orchestration.
-
-```rust
-pub async fn edit_document_handler<T: DocumentService, Svc: EntityAccessService>(
- access: DocumentAccessExtractor<EditAccessLevel, Svc>,
- State(state): State<DocumentRouterState<T, Svc>>,
- document_context: LoadedDocumentBasic,
- project: ProjectBodyAccessLevelExtractor<EditAccessLevel, EditDocumentServiceArgs, Svc>,
-) -> Result<Json<EditDocumentResponse>, DocumentError> {
- state
- .service
- .edit_document(
- access.entity_access_receipt,
- document_context.into_inner(),
- project.into_inner(),
- )
- .await?;
-
- Ok(Json(EditDocumentResponse::success()))
-}
-```
-
-```rust
-async fn edit_document(
- &self,
- receipt: EntityAccessReceipt<EditAccessLevel>,
- document_context: DocumentBasic,
- args: EditDocumentServiceArgs,
-) -> Result<(), DocumentError> {
- if let EntityPermission::AccessLevel { access_level } = receipt.entity_permission() {
- if args.project_id.is_some() && *access_level != AccessLevel::Owner {
- return Err(DocumentError::Unauthorized);
- }
-
- if args.share_permission.is_some() && *access_level != AccessLevel::Owner {
- return Err(DocumentError::Unauthorized);
- }
- }
-
- let document_id = receipt.entity().entity_id.clone();
- self.repo
- .edit_document_metadata(document_id, document_context, args)
- .await
-}
-```
-
-## Pre-write checklist
-
-Before editing code, classify each touched file:
-
-1. Is it `domain`, `inbound`, `outbound`, or composition/wiring?
-2. What use case is being added or changed?
-3. What domain command/model/error represents it?
-4. Which domain service method should inbound call?
-5. Which outbound capabilities are needed, and are they behind domain port traits?
-6. What authorization/policy decisions are needed, and where will domain service tests cover them?
-
-If a step has no answer, stop and design that boundary before writing code.
-
-## Review checklist
-
-For every Rust backend diff, reject or refactor if any of these are true:
-
-- `src/domain/**` imports `axum`, `http::StatusCode`, `IntoResponse`, `Json`, `Router`, `Request`, `HeaderMap`, SQLx pools/queries, AWS SDK clients, Redis clients, reqwest clients, `crate::inbound`, or `crate::outbound`.
-- `src/inbound/**` contains SQLx queries, transaction handling, repository calls, AWS/Redis/OpenSearch/reqwest calls, or direct calls to outbound implementations.
-- Ordinary `src/inbound/**` handlers/tools/listeners contain authorization decisions (`AccessLevel`, role checks, owner checks, team/project membership checks, `can_*`, `authorize_*`, `ensure_*permission*`) instead of forwarding a typed `EntityAccessReceipt<T>` or identity to a service. Dedicated access extractors whose job is to mint receipts are the exception.
-- Handlers return domain-specific decisions not produced by a domain service.
-- Outbound code imports inbound/transport DTOs or axum types.
-- A domain service depends on concrete adapters rather than port traits/generic bounds/trait objects.
-- Tests only cover HTTP status mapping and do not cover service-level allow/deny/business-rule cases.
-
-## Useful inspection commands
-
-Set `CRATE` to the crate you are touching, for example `CRATE=crates/documents`.
-
-```bash
-# Domain must not know transport or concrete infrastructure.
-rg -n "use (axum|http::StatusCode)|IntoResponse|Json<|Router|HeaderMap|Request<|sqlx::|PgPool|aws_sdk|redis::|reqwest|crate::inbound|crate::outbound" "$CRATE/src/domain" --glob '*.rs'
-
-# Inbound authz/policy hits require inspection. Receipt-minting extractors are allowed;
-# ordinary handlers should forward EntityAccessReceipt<T> instead of branching.
-rg -n "entity_access|EntityAccessReceipt|roles_and_permissions|AccessLevel|RoleId|owner|admin|member|tenant|team|project|permission|authorize|authz|can_|ensure_.*permission|Forbidden|Unauthorized" "$CRATE/src/inbound" --glob '*.rs'
-
-# Inbound should not do persistence or infrastructure work.
-rg -n "sqlx::|query!|query_as!|PgPool|Transaction|aws_sdk|redis::|opensearch|reqwest|S3|Sqs|Dynamo" "$CRATE/src/inbound" --glob '*.rs'
-
-# Outbound must not depend on inbound transport.
-rg -n "crate::inbound|axum|IntoResponse|Json<|Router|StatusCode" "$CRATE/src/outbound" --glob '*.rs'
-```
-
-`rg` hits are not automatically failures, but every hit must be explained by layer responsibilities. When in doubt, move policy inward.
-
-## If you find an existing violation
-
-- Do not add more logic to the violating adapter.
-- If the task touches that use case, prefer moving the policy/orchestration into the domain service as part of the change.
-- If a full refactor is large or risky, stop and ask the user before making sweeping changes. Offer the smallest compliant plan that prevents new violations.
-
-## Final response requirement
-
-When you use this skill, explicitly state that the hexagonal boundary was checked and summarize where authz/business policy lives after your change.
diff --git a/.claude/skills/collab-surface-core b/.claude/skills/collab-surface-core
deleted file mode 120000
index 7d646ac1fd..0000000000
--- a/.claude/skills/collab-surface-core
+++ /dev/null
@@ -1 +0,0 @@
-../../.agents/skills/collab-surface-core
\ No newline at end of file
diff --git a/.claude/skills/create-ai-tool/SKILL.md b/.claude/skills/create-ai-tool/SKILL.md
deleted file mode 100644
index 43e81e8b5a..0000000000
--- a/.claude/skills/create-ai-tool/SKILL.md
+++ /dev/null
@@ -1,130 +0,0 @@
----
-name: create-ai-tool
-description: Build a new AI tool end-to-end — Rust implementation, toolset wiring, infra, schema generation, and frontend UI.
----
-
-# Create AI Tool
-
-This skill walks through building a new AI tool from scratch. Before writing any code, read the design guide at `crates/ai_toolset/TOOL_DESIGN.md` and the framework docs/examples in `crates/ai_toolset/src/lib.rs`.
-
-**IMPORTANT:** Never modify the `crates/ai_toolset/` crate. It is the framework — you build tools that use it.
-
-## Step 1: Write the tool
-
-Decide which domain crate the tool belongs in. Tools live at `crates/<crate>/src/inbound/toolset/`.
-
-Study an existing tool for patterns:
-- `crates/documents/src/inbound/toolset/` — tools: `read_content.rs`, `read_metadata.rs`, `create_document.rs`
-- `crates/email/src/inbound/toolset/` — tools: `send_email.rs`, `get_thread.rs`, `update_thread_labels.rs`
-- `crates/soup/src/inbound/toolset/` — tool: `list_entities.rs`
-- `crates/call/src/inbound/toolset/` — call-related tools
-
-Each tool is a struct that derives `JsonSchema` and `Deserialize`, with `#[schemars(title = "...", description = "...")]` on the struct and `#[schemars(description = "...")]` on each field. The struct implements `AsyncTool<Context>` from the `ai_toolset` crate.
-
-Create a new file for your tool (e.g. `my_tool.rs`), add it as a `mod` in the toolset's `mod.rs`, and wire it into the toolset's `AsyncToolSet::new().add_tool::<...>()` chain.
-
-## Step 2: Create the tool context
-
-If your tool needs dependencies (DB connections, service clients) that aren't already in an existing context, define a new context struct in the toolset's `mod.rs`. See `crates/documents/src/inbound/toolset/mod.rs` for the `DocumentToolContext` pattern.
-
-The context must be `Clone` and derivable from the parent `ToolServiceContext` via `FromRef`.
-
-If the tool's dependencies are already available in an existing context (e.g. it only needs `Arc<ToolScribe>`), you can use that context directly — no new struct needed.
-
-## Step 3: Add the toolset to `all_tools` in the ai_tools crate
-
-Edit `crates/ai_tools/src/lib.rs`:
-- Import your toolset function and context type
-- Add `.add_tool::<YourTool, YourContext>()` or `.add_subtoolset::<YourToolContext>(your_toolset())` to the `all_tools()` function
-
-## Step 4: Add the context to ToolServiceContext
-
-Edit `crates/ai_tools/src/tool_context.rs`:
-- Add any new type aliases for your service implementations (follow the `Tool*` naming pattern)
-- Add your tool context field to the `ToolServiceContext` struct
-- Implement `FromRef<ToolServiceContext>` for your context if needed (or derive it — the struct uses `#[derive(FromRef)]`)
-
-## Step 5: Wire up env vars and service construction
-
-Edit `crates/ai_tools/src/build_context.rs`:
-- Add any new env vars to the `env_var!` or `maybe_env_var!` blocks
-- Construct your service/context in `build_tool_service_context_from_env`
-- Add it to the returned `ToolServiceContext`
-
-## Step 6: Update infra (if new env vars or AWS resources are needed)
-
-Edit `infra/packages/shared/src/ai_tools.ts`:
-- Add new env vars to the `envVars` array in `getAiToolsInfra()`
-- Add any new secret ARNs, queue ARNs, or bucket ARNs to the respective arrays
-- Add any new Pulumi stack references needed to resolve the values
-
-## Step 7: Rust checks
-
-Run from the repository root:
-```bash
-cargo fmt
-cargo clippy -p ai_tools
-cargo test -p <your_domain_crate>
-```
-
-Fix any warnings or errors before proceeding.
-
-## Step 8: Generate frontend types
-
-Run from `apps/web/`:
-```bash
-bun gen-tools
-```
-
-This builds `crates/ai_tools/src/bin/gen_tool_schemas.rs`, generates `crates/ai_tools/schemas/tools.json`, and transpiles the schemas into TypeScript at `apps/web/src/lib/service-clients/service-cognition/generated/tools/`.
-
-## Step 9: Check what frontend UI is needed
-
-Run from `apps/web/`:
-```bash
-bun check
-```
-
-This runs `tsc --noEmit` and will report type errors — specifically, the `toolHandlers` map in `apps/web/src/lib/core/component/AI/component/tool/handler.tsx` will be missing your new tool name. The errors tell you exactly what to implement.
-
-## Step 10: Read existing tool UI for patterns
-
-The tool UI components live at `apps/web/src/lib/core/component/AI/component/tool/`. Study existing renderers:
-- `Search.tsx` — search results rendering
-- `ReadContent.tsx` / `ReadMetadata.tsx` — document tool UI
-- `SendEmail.tsx` — email tool UI
-- `ListEntities.tsx` — list display
-- `Properties.tsx` — property get/set tools
-- `ListCallRecords.tsx` / `ReadCallRecord.tsx` — call tools
-- `BaseTool.tsx` — shared base component
-
-Each tool needs a handler object implementing `ToolHandler` (from `ToolRenderer.tsx`) with at minimum a `render` component. Use `createToolRenderer` to create it.
-
-## Step 11: Write the tool UI
-
-1. Create a new component file at `apps/web/src/lib/core/component/AI/component/tool/YourTool.tsx`
-2. Export a handler using `createToolRenderer`
-3. Register it in `apps/web/src/lib/core/component/AI/component/tool/handler.tsx`:
- - Import your handler
- - Add it to the `toolHandlers` map with the key matching your tool's schema title
-
-Every tool renderer must show results. Use the expandable dropdown pattern from `Search.tsx` / `ListEntities.tsx`:
-
-- Use `BaseTool` (from `BaseTool.tsx`) as the wrapper. It accepts a `response` prop for expandable content.
-- Create `const [isExpanded, setIsExpanded] = createSignal(false)` to track open/closed state.
-- Access the response via `ctx.response?.data` (typed from the generated schema).
-- Show a status summary (e.g. hit count, "No Results") on the right side of the tool row.
-- Render a `CaretRight` toggle button (`@icon/regular/caret-right.svg?component-solid`) that rotates 90deg when expanded.
-- Pass the expanded content into `BaseTool`'s `response` prop, gated on `isExpanded()`.
-
-For tools that return text/string results (not entity lists), render the response string in a `<pre>` or similar block inside the `response` prop. The key point: the response data must always be surfaced in the UI via the dropdown — never silently swallowed.
-
-## Step 12: Frontend checks
-
-Run from `apps/web/`:
-```bash
-bun format
-bun check
-```
-
-Fix any remaining type or formatting errors.
diff --git a/.claude/skills/database-core b/.claude/skills/database-core
deleted file mode 120000
index 2c6783b3a7..0000000000
--- a/.claude/skills/database-core
+++ /dev/null
@@ -1 +0,0 @@
-../../.agents/skills/database-core
\ No newline at end of file
diff --git a/.claude/skills/debug-service/SKILL.md b/.claude/skills/debug-service/SKILL.md
deleted file mode 100644
index c22213386e..0000000000
--- a/.claude/skills/debug-service/SKILL.md
+++ /dev/null
@@ -1,10 +0,0 @@
-You are going to help me interactively debug the rust binary
-that's in this crate.
-
-Use this command to start the service with debug logging
-
-RUST_LOG=<name_of_bin>=debug,info
- just run > /tmp/<name_of_bin>.log 2>&1 & tail -f /tmp/<name_of_bin>.log
-
-Use the log tail to answer questions as appropriate
-
diff --git a/.claude/skills/dependabot/skill.md b/.claude/skills/dependabot/skill.md
deleted file mode 100644
index 81753a3eca..0000000000
--- a/.claude/skills/dependabot/skill.md
+++ /dev/null
@@ -1,78 +0,0 @@
----
-name: dependabot
-description: Find all open Dependabot alerts for this repo and create a plan to resolve them using the appropriate package manager overrides (pnpm, bun, npm, cargo).
-allowed-tools: Bash, Read, Edit, Glob, Grep, Agent
----
-
-# Dependabot Alert Resolution
-
-## Step 1: Fetch all open alerts
-
-```bash
-REPO=$(gh repo view --json nameWithOwner -q .nameWithOwner)
-gh api "repos/${REPO}/dependabot/alerts" \
- --jq '.[] | select(.state == "open") | {
- number,
- dependency: .dependency.package.name,
- ecosystem: .dependency.package.ecosystem,
- manifest: .dependency.manifest_path,
- vulnerable_range: .security_vulnerability.vulnerable_version_range,
- patched_version: .security_vulnerability.first_patched_version.identifier,
- severity: .security_vulnerability.severity,
- summary: .security_advisory.summary
- }'
-```
-
-## Step 2: Group alerts by manifest/lockfile
-
-Group the alerts by their `manifest` field (e.g. `bun.lock`, `Cargo.lock`, `packages/loro-mirror/pnpm-lock.yaml`). This determines which override mechanism to use.
-
-## Step 3: Determine override strategy per manifest
-
-For each manifest/lockfile, determine the correct override mechanism:
-
-| Lockfile | Override mechanism |
-|----------|-------------------|
-| `bun.lock` / `bun.lockb` | `"overrides"` in the nearest `package.json` |
-| `pnpm-lock.yaml` | `"pnpm": { "overrides": { ... } }` in the workspace root `package.json` |
-| `package-lock.json` | `"overrides"` in the nearest `package.json` |
-| `yarn.lock` | `"resolutions"` in the nearest `package.json` |
-| `Cargo.lock` | `cargo update -p <package>` or workspace `[patch.crates-io]` in `Cargo.toml` |
-
-Read each target `package.json` or `Cargo.toml` to check for existing overrides before adding new ones.
-
-## Step 4: Present the plan
-
-Present a table of all alerts grouped by manifest, showing:
-- Alert numbers
-- Package name
-- Current version (from lockfile)
-- Patched version
-- Severity
-- Override mechanism to use
-
-Ask the user to confirm before making changes.
-
-## Step 5: Apply fixes
-
-For each group:
-
-### npm/bun/pnpm overrides
-- Add override entries to the appropriate `package.json`
-- Reinstall: `bun install` / `pnpm install` / `npm install`
-- Verify: check the lockfile or `<pm> ls` for the patched version
-
-### Cargo
-- Try `cargo update -p <package>` first
-- If that doesn't reach the patched version, also try `cargo update -p <parent-package>` (the package that depends on the vulnerable one, found via `cargo tree -i <package>`)
-- Verify with `cargo tree -i <package>` and checking `Cargo.lock`
-
-## Step 6: Verify
-
-After all changes, confirm patched versions are in place and no new audit issues were introduced.
-
-## Notes
-
-- Some alerts may be false positives (e.g. `undici-types` triggering `undici` alerts). Flag these to the user.
-- Prefer minimal version bumps (e.g. `>=6.14.0` not `^8.0.0`) to reduce breakage risk.
-- If a `cargo update` only bumps to a version below the patch, escalate the parent dependency.
diff --git a/.claude/skills/dump-schema/SKILL.md b/.claude/skills/dump-schema/SKILL.md
deleted file mode 100644
index 0527826955..0000000000
--- a/.claude/skills/dump-schema/SKILL.md
+++ /dev/null
@@ -1,35 +0,0 @@
----
-name: dump-schema
-description: Dump clean Postgres schema to a file and copy path to clipboard.
-allowed-tools: Bash
----
-
-# Dump Schema
-
-Dump a clean PostgreSQL schema (no comments, no ownership, no privileges) from the local dev database.
-
-## Parameters
-
-Ask the user (if not provided):
-- **output_file** – absolute path for the `.sql` file (default: prompt user)
-
-Use this database URL unless the user specifies otherwise:
-```
-postgres://user:password@localhost:5432/macrodb
-```
-
-## Steps
-
-1. Run `pg_dump` with schema-only flags, pipe through cleanup, write to file:
-
-```bash
-pg_dump --schema-only --no-owner --no-privileges --no-comments --no-publications --no-subscriptions --no-security-labels --no-tablespaces "$DB_URL" | sed '/^--/d' | sed '/^SET /d' | sed '/^SELECT pg_catalog/d' | sed '/^$/N;/^\n$/d' > "$OUTPUT_FILE"
-```
-
-2. Copy the output path to the clipboard:
-
-```bash
-echo -n "$OUTPUT_FILE" | pbcopy
-```
-
-3. Report: `Schema dumped to <path> (path copied to clipboard)`
diff --git a/.claude/skills/qc/SKILL.md b/.claude/skills/qc/SKILL.md
deleted file mode 100644
index f0a3dcb14d..0000000000
--- a/.claude/skills/qc/SKILL.md
+++ /dev/null
@@ -1,110 +0,0 @@
----
-name: qc
-description: Quality gate. 5 parallel agents review changes. All must pass.
-allowed-tools: Task, Bash, Read, Grep, Glob
----
-
-# QC Gate
-
-## Setup
-```bash
-DIFF=$(git diff main)
-FILES=$(git diff main --name-only)
-TASK="{task description or 'general changes'}"
-```
-
-Read 1-2 unmodified files from same directories for pattern context.
-
-## Agents
-
-Spawn all 5 in parallel. All output raw JSON only, no markdown.
-
-### 1: Code Review (sonnet)
-```
-DIFF: ${DIFF}
-
-- Descriptive naming?
-- Errors caught with useful messages?
-- No hardcoded values, commented code, debug statements?
-- No TODO without ticket ref?
-- No obvious bugs?
-- No useless comments?
-
-{"pass": bool, "issues": [...]}
-```
-
-### 2: Simplification (sonnet)
-```
-DIFF: ${DIFF}
-
-- Is this overcomplicated? Can I solve the same problem in a simpler manner?
-- Can I reduce indirection?
-- Can I reduce surface area?
-- Premature abstraction? Premature Optimization? YAGNI violations?
-- Dead code?
-- Three similar lines > one abstraction
-
-{"pass": bool, "issues": [...]}
-```
-
-### 3: Consistency (sonnet)
-```
-DIFF: ${DIFF}
-PATTERNS: ${PATTERN_FILES}
-
-- Matches existing codebase patterns?
-- Proper types, no any, no unsafe casts?
-- Idiomatic error handling?
-- Changes internally consistent?
-- Is logic isolated and composable?
-- Are there existing tests if neccesary?
-
-{"pass": bool, "issues": [...]}
-```
-
-### 4: Robustness (sonnet)
-```
-TASK: ${TASK}
-DIFF: ${DIFF}
-
-- Actually solves the problem?
-- Edge cases: empty, null, zero, negative, boundaries, concurrency?
-- Regression risk: changed signatures, shared state, removed exports?
-- Maintains API contracts?
-
-{"pass": bool, "issues": [...]}
-```
-
-### 5: Scope (haiku)
-```
-TASK: ${TASK}
-FILES: ${FILES}
-DIFF: ${DIFF}
-
-- Solved the problem or just the symptom?
-- Changes unrelated to task?
-- Unnecessary refactoring?
-
-{"pass": bool, "issues": [...]}
-```
-
-## Results
-
-| Check | Verdict | Issues |
-|-------|---------|--------|
-| Code Review | ✓/✗ | ... |
-| Simplification | ✓/✗ | ... |
-| Consistency | ✓/✗ | ... |
-| Robustness | ✓/✗ | ... |
-| Scope | ✓/✗ | ... |
-
-**ALL PASS:** Ready to commit.
-
-**ANY FAIL:** List issues, fix them, run `/qc` again.
-
-**Same issue 3x:** Escalate to user.
-
-## Notes
-
-- Invalid JSON? Retry once. Still broken? Mark fail.
-- Large diffs (>500 lines): run simplification file-by-file.
diff --git a/.claude/skills/upgrade-model/SKILL.md b/.claude/skills/upgrade-model/SKILL.md
deleted file mode 100644
index 8a2a6b2b55..0000000000
--- a/.claude/skills/upgrade-model/SKILL.md
+++ /dev/null
@@ -1,136 +0,0 @@
----
-name: upgrade-model
-description: Upgrade an AI chat model (fast or good) across backend and frontend.
-allowed-tools: Bash, Read, Write, Edit, Grep, Glob
----
-
-# Upgrade Chat Model
-
-Upgrades the AI model used in the chat app. There are two model slots:
-- **fast** (Enter): default/fallback model (first entry in `CHAT_MODELS`)
-- **good** (Cmd+Enter): smart mode model (second entry in `CHAT_MODELS`)
-
-The user must specify which slot to upgrade and the new model name (e.g. `claude-opus-4-6`).
-
-## Steps
-
-### 1. Determine the change
-
-Ask the user (if not already provided):
-- Which slot: `fast` or `good`?
-- What is the new model name? (e.g. `claude-opus-4-6`)
-
-Derive from the model name:
-- `SERDE_NAME`: the kebab-case model ID sent over the wire (e.g. `claude-opus-4-6`)
-- `ENUM_VARIANT`: PascalCase variant name (e.g. `Claude46Opus`)
-- `CONST_NAME`: SCREAMING_SNAKE constant name (e.g. `CLAUDE_46_OPUS`)
-- `CONST_VALUE`: display string used by the frontend/provider (e.g. `claude-4.6-opus`)
-- `PRETTY_NAME`: human-readable name (e.g. `Claude Opus 4.6`)
-
-### 2. Add model to AI crate (if it doesn't already exist)
-
-File: `crates/agent/src/model/predefined_model.rs`
-
-Check if the enum variant already exists. If not, add all of the following:
-
-1. **Enum variant** in `pub enum Model` (under the Anthropic section):
- ```rust
- #[serde(rename = "{SERDE_NAME}")]
- #[strum(serialize = "{SERDE_NAME}")]
- {ENUM_VARIANT},
- ```
-
-2. **String constant** in `pub mod constants::models`:
- ```rust
- pub const {CONST_NAME}: &str = "{CONST_VALUE}";
- ```
-
-3. **Match arm** in `to_provider_model_string()`:
- ```rust
- Model::{ENUM_VARIANT} => (ANTHROPIC, {CONST_NAME}),
- ```
-
-4. **Match arm** in `from_model_str()`:
- ```rust
- {CONST_NAME} => Model::{ENUM_VARIANT},
- ```
-
-File: `crates/agent/src/model/predefined_model.rs`
-
-5. **Metadata** in `fn metadata()`:
- ```rust
- Model::{ENUM_VARIANT} => ModelMetadata {
- context_window: 200_000,
- },
- ```
- Use the correct context window for the model. Anthropic models are typically 200,000.
-
-6. **Provider** in `fn provider()`:
- ```rust
- Model::{ENUM_VARIANT} => Provider::Anthropic,
- ```
-
-### 3. Update DCS constants
-
-File: `services/document_cognition_service/src/core/model.rs`
-
-- If upgrading the **fast** slot: change the first entry in `CHAT_MODELS` and update `FALLBACK_MODEL`.
-- If upgrading the **good** slot: change the second entry in `CHAT_MODELS`.
-
-### 4. Update DCS chat message handler
-
-File: `services/document_cognition_service/src/api/ws/chat_message/mod.rs`
-
-Search for the old model variant being used in the model selection logic (e.g. `Model::Claude45Opus`). Update it to the new variant.
-
-### 5. Verify Rust compiles
-
-```bash
-cargo check -p agent -p document_cognition_service
-```
-
-Fix any compilation errors before proceeding.
-
-### 6. Generate frontend types
-
-Run from `apps/web/`:
-```bash
-cd apps/web && bun install && bun run gen-api
-```
-
-This builds all Rust OpenAPI and models binaries from local code, generates `openapi.json`, runs orval for TypeScript types, and generates `model.ts` from the local models binary. All generated files will reflect your local Rust changes.
-
-### 7. Run `bun check` to find frontend usages
-
-```bash
-cd apps/web && bun check
-```
-
-This will report TypeScript errors everywhere the old model string is used. Fix each one. Common locations:
-
-- `apps/web/src/lib/core/component/AI/constant/model.ts` — `MODEL_PRETTYNAME`, `MODEL_PROVIDER_ICON`, `SMART_MODE_MODEL` / `DEFAULT_MODEL`
-- `apps/web/src/lib/core/component/AI/component/input/useChatInput.tsx` — hardcoded model references
-- `apps/web/src/lib/core/component/AI/signal/pendingSend.test.ts` — test data
-
-Replace old model strings and update display names.
-
-### 8. Format and verify
-
-```bash
-cd apps/web && bun format && bun check
-```
-
-The only errors remaining should be **pre-existing** ones unrelated to models (e.g. `three`, `@aws-crypto/sha256-js` type issues). All model-related errors must be resolved.
-
-Finally, run the CI check:
-```bash
-cd apps/web && bun run gen-api -- --check
-```
-
-This must pass.
-
-## Notes
-
-- We only support Anthropic models for chat. Other providers exist in the AI crate but are not used for the chat feature.
-- The `ExhaustiveMap` type in `constant/model.ts` requires an entry for every model in the `Model` type, so missing entries will cause type errors.
-- The `SMART_MODE_MODEL` constant is the "good" model, `DEFAULT_MODEL` is the "fast" model.
diff --git a/.coderabbit.yaml b/.coderabbit.yaml
index fad2b259f9..a158941727 100644
--- a/.coderabbit.yaml
+++ b/.coderabbit.yaml
@@ -51,7 +51,7 @@ reviews:
Rust review guidelines (from project conventions):
- New crates must have `#![deny(missing_docs)]` in `lib.rs`.
- Only look for and report semantic bugs that the typesystem will not catch. This includes incomplete integration, incorrect environment variables, or any other logic error that will compile as valid rust.
- - Cross-check database usage changes against migrations in the same PR. Migrations deploy BEFORE services: flag any migration that breaks pre-PR service code, even if the new Rust code compiles. In particular, dropping a column/table in the same PR that removes its usage is unsafe; usage removal must be fully deployed first (see docs/DATABASE_DEVELOPMENT.md, "Safe database schema changes").
+ - Cross-check database usage changes against migrations in the same PR. Migrations deploy BEFORE services: flag any migration that breaks pre-PR service code, even if the new Rust code compiles. In particular, dropping a column/table in the same PR that removes its usage is unsafe; usage removal must be fully deployed first (see docs/development/database.md, "Safe database schema changes").
- path: "crates/**/*_db_client/**"
instructions: |
@@ -72,7 +72,7 @@ reviews:
- Avoid deprecated SolidJS APIs: `blockSignals`, `blockMemos`, `blockResources`, etc.
- Primitive UI components should be pure and prefer composition over complex global state/context.
- If a Lexical Node is created or modified with breaking changes, the lexical version counter must be incremented (`apps/web/src/lib/core/component/LexicalMarkdown/version.ts`).
- - New or moved query call sites must have a deliberate Suspense boundary — walk up the tree from the call site and check which boundary would catch it (see FE-29 in docs/STYLE_GUIDE.md).
+ - New or moved query call sites must have a deliberate Suspense boundary — walk up the tree from the call site and check which boundary would catch it (see FE-29 in .agents/rules/web/data.md).
- path: "infra/**/*.ts"
instructions: |
@@ -86,7 +86,7 @@ reviews:
SQL review guidelines:
- Explicitly check migration/service compatibility across the entire PR. Database migrations deploy BEFORE service changes, so migrations must work with currently deployed (pre-PR) code, not just the updated code.
- Flag as a deployment-safety bug any column/table drop in the same PR that removes its service usage. Require usage removal first, confirmation that it is fully deployed to all consumers, then a separate cleanup PR; merging the usage-removal PR is not sufficient.
- - Also flag column/table renames, incompatible type changes, and new constraints or required columns that break existing reads/writes. Require staged, backward-compatible changes as described in docs/DATABASE_DEVELOPMENT.md ("Safe database schema changes"). Do not flag combined schema/service PRs solely for combining changes when the migration remains compatible with deployed code.
+ - Also flag column/table renames, incompatible type changes, and new constraints or required columns that break existing reads/writes. Require staged, backward-compatible changes as described in docs/development/database.md ("Safe database schema changes"). Do not flag combined schema/service PRs solely for combining changes when the migration remains compatible with deployed code.
- Verify migrations are idempotent where possible (use IF NOT EXISTS, etc.).
- Check index strategy — composite indexes should match common query patterns.
- Confirm camelCased column names are handled correctly in Rust SQLx queries.
@@ -250,8 +250,8 @@ knowledge_base:
filePatterns:
- "**/CLAUDE.md"
- "**/AGENTS.md"
- - "docs/STYLE_GUIDE.md"
- - "docs/DATABASE_DEVELOPMENT.md"
+ - ".agents/rules/**/*.md"
+ - "docs/development/database.md"
- "**/.cursor/rules/*.mdc"
- "**/.cursor/commands/*.md"
diff --git a/.cursor/mcp.json b/.cursor/mcp.json
index 5dde156e6c..b7466c4525 100644
--- a/.cursor/mcp.json
+++ b/.cursor/mcp.json
@@ -23,6 +23,9 @@
"-t",
"stdio"
]
+ },
+ "posthog": {
+ "url": "https://mcp.posthog.com/mcp"
}
}
}
diff --git a/.cursor/rules b/.cursor/rules
new file mode 120000
index 0000000000..2d5c9a97a7
--- /dev/null
+++ b/.cursor/rules
@@ -0,0 +1 @@
+../.agents/rules
\ No newline at end of file
diff --git a/.github/workflows/publish-android-play.yml b/.github/workflows/publish-android-play.yml
index 9a2b71dad6..0c96ba4eaf 100644
--- a/.github/workflows/publish-android-play.yml
+++ b/.github/workflows/publish-android-play.yml
@@ -61,7 +61,7 @@ jobs:
run: |
set -euo pipefail
if [[ -z "$WIF_PROVIDER" || -z "$PLAY_ACCOUNT" ]]; then
- echo "Configure the Google Play repository variables; see docs/ANDROID_DEVELOPMENT.md" >&2
+ echo "Configure the Google Play repository variables; see docs/development/android.md" >&2
exit 1
fi
- name: Download verified release bundle
@@ -139,7 +139,7 @@ jobs:
exit 1
fi
if [[ -z "$WIF_PROVIDER" || -z "$PLAY_ACCOUNT" ]]; then
- echo "Configure the Google Play repository variables; see docs/ANDROID_DEVELOPMENT.md" >&2
+ echo "Configure the Google Play repository variables; see docs/development/android.md" >&2
exit 1
fi
- name: Authenticate to Google Play
diff --git a/.mcp.json b/.mcp.json
index bfb923c02f..777d1669da 100644
--- a/.mcp.json
+++ b/.mcp.json
@@ -26,6 +26,10 @@
},
"macro": {
"url": "https://mcp-server.macro.com/mcp"
+ },
+ "posthog": {
+ "type": "http",
+ "url": "https://mcp.posthog.com/mcp"
}
}
}
diff --git a/.pi/agents/db-checker.md b/.pi/agents/db-checker.md
index 4f179b93d1..67813f0c3f 100644
--- a/.pi/agents/db-checker.md
+++ b/.pi/agents/db-checker.md
@@ -13,7 +13,7 @@ Your job is to validate database migrations and SQL queries, including Rust SQLx
Before doing any review, load and follow the project skill:
```text
-.pi/skills/sqlx-query-validator/SKILL.md
+.agents/skills/sqlx-query-validator/SKILL.md
```
That skill is the source of truth for:
diff --git a/.pi/skills b/.pi/skills
new file mode 120000
index 0000000000..2b7a412b8f
--- /dev/null
+++ b/.pi/skills
@@ -0,0 +1 @@
+../.agents/skills
\ No newline at end of file
diff --git a/.pi/skills/live-debug b/.pi/skills/live-debug
deleted file mode 120000
index ba58e5e29a..0000000000
--- a/.pi/skills/live-debug
+++ /dev/null
@@ -1 +0,0 @@
-../../.claude/skills/live-debug
\ No newline at end of file
diff --git a/CLAUDE.md b/CLAUDE.md
index 9f35e6dd11..269d072067 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -6,11 +6,16 @@ This file is the shared entry point: `AGENTS.md` symlinks to `CLAUDE.md`. Edit
## Start here
-1. Identify the affected app, service, or crate using the map below.
-2. Read any applicable directory-level `AGENTS.md` / `CLAUDE.md` before editing.
+Unless the user says otherwise, before writing any code:
+
+1. Read [CODING.md](CODING.md).
+2. Find the affected app, service, or crate in the map below and read its
+ `AGENTS.md`.
3. Read the task-relevant guides below, not every linked document.
-4. Follow [the style guide](docs/STYLE_GUIDE.md) for the language you change.
- Prefer its current rules over patterns in older code.
+4. Explore the code you will change and its callers until you know how it works.
+
+Rules in `.agents/rules/` load when you touch matching files. Prefer them over
+patterns in older code.
## Repository map
@@ -23,7 +28,21 @@ This file is the shared entry point: `AGENTS.md` symlinks to `CLAUDE.md`. Edit
| `crates/macro_db_client/migrations/` | MacroDB PostgreSQL migrations. |
| `infra/` | Deployment definitions and local infrastructure. |
| `tooling/` | Development tools, scripts, and imported `just` recipes. |
-| `docs/AGENT_GUIDE/` | How browser agents operate the app, not how to develop the repository. |
+| `docs/` | Development guides, architecture, designs, runbooks, and the browser agent guide; see [the index](docs/README.md). |
+
+## Where agent guidance lives
+
+| Path | Contents |
+| --- | --- |
+| `CODING.md` | Coding rules for every language; read before writing code. |
+| `AGENTS.md` in a directory | Scope, map, checks, and gotchas for that subtree; a sibling `CLAUDE.md` symlinks to it. |
+| `.agents/skills/` | Task workflows. `.claude/skills` and `.pi/skills` symlink here. |
+| `.agents/rules/` | Path-scoped conventions, loaded when you touch matching files. `.claude/rules` and `.cursor/rules` symlink here. |
+| `.agents/agents/` | Subagents (`auditor`, `browser-verifier`). `.claude/agents` symlinks here. |
+| `.agents/templates/` | Templates for new rules and `AGENTS.md` files. |
+| `rules/ast-grep/` | Mechanically enforced code rules, run by `just check`. |
+
+Real files live in `.agents/`; tool-specific directories only symlink to it.
## Read when relevant
@@ -31,40 +50,58 @@ This file is the shared entry point: `AGENTS.md` symlinks to `CLAUDE.md`. Edit
| --- | --- |
| Reusing database storage or separating it from an app entity | [Database core skill](.agents/skills/database-core/SKILL.md) |
| Adding collaborative markdown to a feature | [Collab surface core skill](.agents/skills/collab-surface-core/SKILL.md) |
-| Rust code, builds, or tests | [Rust development](docs/RUST_DEVELOPMENT.md) |
-| SQLx queries, migrations, DB tests, or cache errors | [Database development](docs/DATABASE_DEVELOPMENT.md) |
+| Adding a flow or hot path, or tracing one | `instrumentation` skill |
+| Rust code, builds, or tests | [Rust development](docs/development/rust.md) |
+| SQLx queries, migrations, DB tests, or cache errors | [Database development](docs/development/database.md) |
| Web frontend | [Web agent guide](apps/web/AGENTS.md) |
| Email body rendering or snapshots | [Standalone renderer](packages/email-renderer/README.md) |
-| Running the frontend or backend on a local machine | [Running locally](docs/RUNNING_LOCALLY.md) |
-| Working inside Cursor Cloud | [Cursor Cloud](docs/CURSOR_CLOUD.md) |
-| Driving the app through a browser | [App agent guide](docs/AGENT_GUIDE/README.md) |
+| Running the frontend or backend on a local machine | [Running locally](docs/development/running-locally.md) |
+| Giving the user a local preview link | `local-preview` skill |
+| Working inside Cursor Cloud | [Cursor Cloud](docs/development/cursor-cloud.md) |
+| Driving the app through a browser | [App agent guide](docs/agent-guide/README.md) |
+| Adding or changing SDK methods | [SDK rule](.agents/rules/sdk.md), `add-sdk-endpoint` skill |
| SDK version bumps and npm publishing | [SDK release guide](packages/sdk/RELEASING.md), [release-sdk skill](.agents/skills/release-sdk/SKILL.md) |
-| Deployment | [Infrastructure guide](infra/README.md) |
-
-## Essential guardrails
-
-- Run Rust tests from the repository root with `cargo test -p <package>` and
- **leave `SQLX_OFFLINE` unset**. Offline mode is for checks/builds/lints, not tests.
-- Generate migrations with `sqlx migrate add`; never invent timestamped filenames.
- Never hand-edit `.sqlx/query-*.json`. Prepare the workspace cache from the root
- inside Nix; see the database guide for the workflow and test-query flags.
-- Do not reset databases or wipe stack volumes to troubleshoot without explicit
- approval. Database and Cloud guides distinguish rebuilds from destructive resets.
-- On a local machine, frontend-only work uses `apps/web` against the dev backend;
- it does not need a local Rust stack. `.cursor/*.sh` scripts are **Cursor Cloud
- only**, not local-machine setup commands. Treat hosted dev data as real data.
-- Load Rust configuration through `macro_env_var` / `macro_config`, never
- `std::env::var` or hand-rolled wrappers. Register new env vars in Doppler; never
- paste secrets into chat or commit them.
-- Across domain crates, depend on the owning domain service or port; only a
- composition root may construct that crate's outbound adapters. Never import
- another crate's `outbound` module from an outbound adapter.
-- Use `\cd` instead of `cd` to bypass repository shell aliases.
+| Adding a service, worker, or Pulumi stack | [New service guide](docs/guides/new-service.md) |
+| Infrastructure, Pulumi, or deploys | [Infrastructure guide](docs/development/infrastructure.md) |
+
+## Rules
+
+**Working with the user**
+
+- Do only what was asked. Questions get answers, not code changes.
+- Commit as you go, in small logical commits on a feature branch, without
+ asking. Never commit to `main`. Push or open a PR only when asked.
+- Flag real risks; once the user decides, act on it.
+- Disagree when they're wrong. No flattery.
+- Answer simple questions directly.
+- For UI work, ask how it should behave on mobile unless that's obvious.
+- Be brief. No justification essays, no time estimates.
+
+**Environment**
+
+- Never touch production (data, services, consoles, secrets) without explicit
+ permission.
+- Never deploy (`pulumi up`, `wrangler deploy`, workflow dispatch) without
+ explicit permission for that deploy.
+- Never reset databases or wipe stack volumes without approval.
+- Never paste or commit secrets.
+- Never `git stash`; it's shared across sessions.
+- Memory is context, not authority; verify against code.
+- Treat hosted dev data as real. `.cursor/*.sh` is Cursor Cloud only.
+- Use `\cd` instead of `cd`.
## Before handing off
-- Always use Conventional Commit syntax for PR titles: `type(scope): description`
- (scope optional), for example `fix(onboarding): preserve team inputs`.
+- Commits, branches, and PRs follow the `git` skill: Conventional Commit titles
+ such as `fix(onboarding): preserve team inputs`, and Why / What bodies with no test plan.
+- Run the `audit` skill (via the `auditor` subagent) before saying work is done.
+- Update every doc your change makes stale, in the same change: the `AGENTS.md`
+ of each directory you touched, `docs/guides/`, `docs/architecture/`, the
+ agent guide, READMEs, rules, and skills. Search for the names you changed.
+- A new crate, service, or package gets an `AGENTS.md` from the
+ [template](.agents/templates/AGENTS.md); one you change keeps its `AGENTS.md`
+ current. Add the sibling symlink (`ln -s AGENTS.md CLAUDE.md`) so Claude Code
+ reads it too.
- Open pull requests ready for review. If one is created as a draft, mark it
ready for review before handing off.
- Get CI passing before handing off. A pull request whose checks are failing
@@ -76,12 +113,35 @@ This file is the shared entry point: `AGENTS.md` symlinks to `CLAUDE.md`. Edit
the workspace Rust type check. These checks do not replace tests.
- Exercise user-visible changes in a browser. If routes, creation flows, editors,
AI surfaces, or composer behavior change, update the corresponding
- [app agent guide](docs/AGENT_GUIDE/README.md) in the same change.
+ [app agent guide](docs/agent-guide/README.md) in the same change.
- Report what you tested and any checks blocked by the environment.
-## Keeping these instructions useful
+## Keeping guidance current
+
+Update the docs in the same change whenever:
+
+- the user gives feedback that applies beyond the current task,
+- you and the user settle on a new convention or reverse an old one,
+- you find a doc, rule, or guide that is wrong or stale.
+
+Put it in exactly one place, the narrowest that fits:
+
+| Kind of guidance | Goes in |
+| --- | --- |
+| How to behave with the user, or a cross-cutting guardrail | This file, **Rules** |
+| A coding rule for every language | `CODING.md` |
+| A convention for certain paths (Rust, web, DB, infra) | `.agents/rules/<area>/`, from the [rule template](.agents/templates/rule.md) |
+| Something checkable by a tool | An ast-grep rule in `rules/ast-grep/` or a lint, instead of prose |
+| Navigation, recipes, or gotchas for one directory | That directory's `AGENTS.md`, from the [template](.agents/templates/AGENTS.md) |
+| A repeatable multi-step task | A skill in `.agents/skills/` |
+| An end-to-end walkthrough of a change | `docs/guides/` |
+| How a system works | `docs/architecture/` |
+
+How:
-Keep this file short: shared guardrails and links with explicit reading triggers.
-Put workflows in the relevant guide, coding rules in `docs/STYLE_GUIDE.md`, and
-subtree-specific instructions near their code. Do not append implementation
-journals, duplicate command lists, or environment-specific runbooks here.
+- Edit the existing entry before adding a new one; delete what the change makes
+ wrong. Never leave two versions of the same rule.
+- Write the rule as one imperative line, with the reason only when it isn't
+ obvious. ID-bearing rules take the next free number.
+- Keep this file short: rules and links, no journals, command lists, or runbooks.
+- Tell the user which doc you changed and how, in one line.
diff --git a/CODING.md b/CODING.md
new file mode 100644
index 0000000000..6d022e1928
--- /dev/null
+++ b/CODING.md
@@ -0,0 +1,79 @@
+# Coding rules
+
+Read this before writing code in this repository, then read what applies to
+the area you're changing:
+
+| Writing | Also read |
+| --- | --- |
+| Rust | [Hexagonal architecture skill](.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md), [Rust guide](docs/development/rust.md) |
+| SQL, migrations, SQLx | [Database guide](docs/development/database.md) |
+| Web frontend | [Web agent guide](apps/web/AGENTS.md), [frontend feature architecture](docs/architecture/frontend-features.md) |
+| Infrastructure | [Infrastructure guide](docs/development/infrastructure.md) |
+| A new service, entity, block, or other multi-place change | The matching [guide](docs/guides/README.md) |
+
+Path-scoped rules in `.agents/rules/` load automatically when you touch matching
+files; the [style guide](docs/development/style-guide.md) indexes them.
+
+## Code
+
+- Simplest correct change. Fewer lines; deleting is good.
+- Fix compiler errors at the cause. No casts, `any`, `unwrap`, or allows to silence them.
+- No speculative optimization.
+- Extend existing features; no parallel paths or fallbacks.
+- Generate types from their source of truth; don't hand-write wire types.
+- No macros or helpers just to save a few lines.
+- Use native APIs and existing libraries. No polyfills, no homemade crypto.
+- Keep types and traits small.
+- Name things for what they are. No jargon or slang.
+- Compatibility only at deployed boundaries (migrations, persisted formats).
+
+## Correctness
+
+- Anything a caller can retry, cancel, or redeliver is safe to repeat: no double
+ effects, no stuck state.
+- Clear or drain state only after the step that can fail succeeds. Multi-step
+ creates and deletes leave no orphans, and projections can't resurrect a
+ deleted row.
+- When an async result arrives, check it still applies (same account, selection,
+ version) before writing it. When racing async sources, flush the loser's
+ buffered state before teardown.
+- One bad item never fails a batch or stalls a consumer partition.
+- A new gate (permission, archived state, caller type, feature flag) applies at
+ every entry point and sibling handler. New routes copy their sibling's access
+ check.
+- When behavior changes, update every doc that mentions it in the same change.
+
+## Tests
+
+- Every bug fix adds a regression test that fails before the fix and passes
+ after.
+- Test behavior, not names or derive round-trips.
+- Explicit literals, no tiny helpers.
+- No `sleep`, `yield_now`, or polling; use real sync primitives.
+- No testing plans; run tests and report results.
+
+## Organization
+
+- **CS-24** Keep source files under ~1000 lines; split before a reviewer has to
+ ask.
+- **CS-26** Reuse before reimplementing. If the logic plausibly exists (service
+ clients, permission checks, OAuth utilities, the `agent` crate), find it and
+ reuse or extract it instead of writing a second copy.
+- **CS-71** Reuse only what was built for the same purpose. Don't repurpose a
+ table, column, type, endpoint, or component for an unrelated feature because
+ its shape fits; confirm what it's for (its owner, callers, and docs) first,
+ and create a new one when the meaning differs.
+- **CS-28** Don't extract single-use code into shared crates or packages
+ prematurely. Dependencies point from specific to general, never the reverse.
+- **CS-29** Group proliferating root files (e.g. Dockerfiles) into a dedicated
+ folder.
+- **CS-32** New API and Soup models mirror the shape of their existing
+ counterpart: omit fields derivable from a nested field, keep lazily loaded
+ collections lazy, and include only fields relevant to the new context.
+- **CS-33** Interface methods every implementor must consciously decide get no
+ default implementation (e.g. schema version). Defaults are for genuine
+ defaults, not escape hatches.
+- **CS-34** When mapping is the point of a generic abstraction, design it to map
+ `T -> U`, not just `T -> T`.
+- **CS-35** Sibling endpoints on a resource share one DTO shape; migrate them
+ together rather than changing one in isolation.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index f84e3d0ddd..b450773562 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -46,13 +46,13 @@ No generated boilerplate, no exhaustive file-by-file change lists.
You do not need the local stack if you only change the frontend.
-If you only change the frontend, run the [frontend against hosted services](docs/RUNNING_LOCALLY.md#run-the-frontend-against-hosted-services).
+If you only change the frontend, run the [frontend against hosted services](docs/development/running-locally.md#run-the-frontend-against-hosted-services).
-If you change a backend service, the database, or behavior that must stay on your machine, [run the local stack](docs/RUNNING_LOCALLY.md#run-the-local-stack).
+If you change a backend service, the database, or behavior that must stay on your machine, [run the local stack](docs/development/running-locally.md#run-the-local-stack).
## Before you push
-- Follow the [style guide](docs/STYLE_GUIDE.md).
+- Follow the [style guide](docs/development/style-guide.md).
- Format and lint: `cargo fmt` and `just clippy` for Rust changes.
- Run the tests for the crates you touched: `cargo test -p <crate>`.
- If you changed SQL queries or migrations, run `just prepare_db` from the
diff --git a/README.md b/README.md
index d9bc85d14e..9d8cd478ce 100644
--- a/README.md
+++ b/README.md
@@ -201,7 +201,7 @@ Deeper reading: [key concepts](https://docs.macro.com/concepts/blocks) covers bl
# Running it locally
-To run the frontend against hosted services, or to run the local stack, follow [Running locally](docs/RUNNING_LOCALLY.md).
+To run the frontend against hosted services, or to run the local stack, follow [Running locally](docs/development/running-locally.md).
To contribute, see [CONTRIBUTING.md](CONTRIBUTING.md).
@@ -223,7 +223,7 @@ macro/
└── tooling/ repo scripts and code generators
```
-Services follow a hexagonal layout: inbound adapters, a domain core with ports, outbound adapters. [`docs/STYLE_GUIDE.md`](docs/STYLE_GUIDE.md) has the conventions and [`CONTRIBUTING.md`](CONTRIBUTING.md) covers the PR process.
+Services follow a hexagonal layout: inbound adapters, a domain core with ports, outbound adapters. [`docs/development/style-guide.md`](docs/development/style-guide.md) has the conventions and [`CONTRIBUTING.md`](CONTRIBUTING.md) covers the PR process.
<br />
diff --git a/apps/docs/.claude/skills b/apps/docs/.claude/skills
new file mode 120000
index 0000000000..2b7a412b8f
--- /dev/null
+++ b/apps/docs/.claude/skills
@@ -0,0 +1 @@
+../.agents/skills
\ No newline at end of file
diff --git a/apps/docs/AGENTS.md b/apps/docs/AGENTS.md
index ae9bea37d8..198cf68fd9 100644
--- a/apps/docs/AGENTS.md
+++ b/apps/docs/AGENTS.md
@@ -3,9 +3,15 @@
# Documentation project instructions
+## What it is
+
+The customer-facing documentation site for Macro, served at docs.macro.com
+and built on [Mintlify](https://mintlify.com). It covers the hosted
+product for end users, plus the MCP tool reference pages AI surfaces
+expose.
+
## About this project
-- This is the documentation site for [Macro](https://macro.com), served at docs.macro.com, built on [Mintlify](https://mintlify.com)
- Pages are MDX files with YAML frontmatter
- Configuration lives in `docs.json`
- Run `mint dev` to preview locally
diff --git a/apps/docs/CLAUDE.md b/apps/docs/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/apps/docs/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/apps/web/.oxlintrc.json b/apps/web/.oxlintrc.json
index 0716a42162..0226d70617 100644
--- a/apps/web/.oxlintrc.json
+++ b/apps/web/.oxlintrc.json
@@ -1,6 +1,6 @@
{
// oxlint runs ALONGSIDE Biome, scoped to rules Biome cannot express.
- // Enforces FE-12 (and eventually FE-13) from docs/STYLE_GUIDE.md.
+ // Enforces FE-12 (and eventually FE-13) from docs/development/style-guide.md.
//
// Run: bun run lint:oxlint (from the repository root), or `bunx oxlint` from apps/web.
//
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index a234995591..b1b0a42e82 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -35,7 +35,7 @@ nix develop --command just run_local --instance <name>
- `--instance <name>` gives an isolated Compose project, volumes, and a deterministic per-name port window, so it never clashes with another worktree's stack. `just status_local --instance <name>` prints the endpoints without starting anything; `just stop_local --instance <name>` stops it (volumes kept) and `just destroy_local --instance <name>` removes it.
- First bring-up is slow (zigbuild of every service plus the agent-harness sandbox image); later runs reuse the caches. While attached, press `r` to rebuild changed Rust services in place and `q` to stop cleanly.
- No accounts are pre-created: passwordless login registers any email on demand, and the one-time code lands in the instance's Mailpit (endpoint in `just status_local`). `just seed-scenario apply --file seed/scenarios/team-perms.json` seeds multi-user team fixtures with printed login links.
-- Full details, Doppler vs no-Doppler modes, and port-conflict debugging: `docs/RUNNING_LOCALLY.md`.
+- Full details, Doppler vs no-Doppler modes, and port-conflict debugging: `docs/development/running-locally.md`.
- First run in a fresh worktree spends a few minutes on `just ensure-cache-wasm` / `just ensure-agent-fold-wasm` before Vite serves.
- That tab is pointed at **real dev data**. Treat creates, edits, and deletes as real, and discard drafts you open.
@@ -69,84 +69,14 @@ Then trigger the interaction and read `window.__inst.log`. `'1,2,3' → '' → '
- Reactive GraphQL reads use `createLiveQuery` for a document and
`useSoupAstItemsQuery` (backed by `createSoupLiveQuery`) for Soup lists; see
[choosing a reactive read](docs/graphql-normalized-cache-plan.md#choosing-a-reactive-read).
-- When adding or changing a feature flag, follow the `define-feature-flag` skill.
+- When adding or changing a feature flag, follow the `feature-flags` skill.
- When adding or changing a view's feature tour, follow the `add-tour` skill.
-### Startup bundle
-- Everything statically reachable from `src/index.tsx` downloads and runs before the first screen. Views, block components, and modals load through `lazy()` / `lazyNamed` (`@core/util/lazyNamed`) inside a `<Suspense>`; never statically import one into a shared hub (`Root`, `Layout`, `AppProviders`, `componentRegistry`, `app-router-view`, `routes/shells.tsx`, block `definition.ts`, Lexical `init.ts`).
-- Each top-level route picks its shell in `app-router-view.tsx` (`routes/shells.tsx`): `authRoute` pages and booking links render without app chrome, and `appRoute` renders `AppShell` — the app's providers (`AppProviders`), chrome (`AppChrome` in `Layout.tsx`), and the split layout. Put state only the app's views use in `AppProviders`, not `Root`; `Root` keeps what every page or a call needs.
-- `index.html` paints a boot shell before any JS runs: the saved theme's background, the rail column, and the desktop app's content card — no app content. The first shell to mount dismisses it (`dismissBootShell`). Keep its rail width and desktop inset in step with `SidebarRail` and `SplitLayout`.
-- Production web builds register `public/sw.js`: it serves the cached `index.html` and content-hashed assets from Cache Storage and moves tabs to newer builds. Set localStorage `macro:sw` to `off` to bypass it while debugging.
-- The build fails if any emitted file exceeds CloudFront's 10 MB compression limit; split it rather than raising the limit.
-
-### Query callback lifetimes
-
-Query options can remain cached after their UI unmounts, including for disabled
-queries. Callbacks created inside hooks can retain component accessors, Solid
-owners, and detached DOM through shared closure environments—even when a callback
-only references a locally resolved ID. This does not mean every closure captures
-every local variable.
-
-- Create cached callbacks in module-scope query factories accepting resolved IDs,
- flags, and plain data. Resolve reactive inputs inside the `useQuery` /
- `useInfiniteQuery` options accessor, e.g. `useQuery(() => itemQueryOptions(id()))`,
- so inputs still update reactively.
-- Keep pure selectors and polling policies at module scope, or inside those
- factories. Check **all** retained callbacks: `queryFn`, `select`,
- `refetchInterval`, pagination, placeholder callbacks, and functions in `meta`.
-- Do not pass component accessors, props getters, or query proxies into the
- factory. For reactive selection, pass plain snapshots of the needed values
- (such as channel names or a resolved document ID). Naming a function or copying
- an ID inside the hook does not isolate its closure from the hook.
-- Use `keepPreviousData` from `@tanstack/solid-query` instead of an inline
- `placeholderData: (p) => p`.
-- The same rule applies to callers of wrapper hooks such as `useSoupAstItemsQuery`
- and `createGroupedSoupQueries`: `meta.itemFilter` / `meta.insertFilter` passed
- from a component or view context are cached too, so build them with a
- module-scope factory over plain snapshots (see
- [drive-data-source](src/features/drive-view/queries/drive-data-source.ts)).
-- Query hooks in `src/lib/urql-solid` are exempt: their observers are created per
- mount and destroyed on cleanup, so nothing outlives the component.
-
-Examples: [session query factory](src/lib/queries/agent-session/session.ts) and
-[search query factories](src/lib/queries/soup/search.ts).
-
-### SolidJs
-- Avoid createEffect. Legitimate uses: syncing with external/imperative systems (DOM APIs, third-party libs). If you're using it to derive state or trigger updates, use a derived signal or wrap the setter instead.
-- Prefer wrapping the setter over `createEffect(() => { if (signal()) sideEffect() })`. When setting focus/selection should also clear another stop, blur a control, or scroll, put that work in the setter (or a named helper the setter calls) so the action is explicit at the call site — not a distant effect watching the signal.
-- Use createMemo only when you need referential stability or the derivation is expensive. Cheap derivations (() => a() + b()) don't need it regardless of subscriber count.
-- Before rolling your own reactive utility, check solid-primitives first.
-- Never read a solid-query `query.data` unguarded from a component body or an eager `createMemo`. `data` is a resource read: while the query is pending it suspends the caller's nearest `<Suspense>`, which detaches and re-attaches that whole subtree — a blank flash, lost scroll position, remounted editors. Gate the read on status (`query.isSuccess ? query.data : fallback`, or `queryReadyGate` from `src/lib/queries/gate.ts`); an `isLoading` check is not enough, because a disabled or paused query is pending without loading and its data read still suspends. Every other field is a plain store read and is safe. Remember `createMemo` runs immediately, so a guard inside a `<Show>`/`<Match>` further down does not save you. This has blanked the calendar grid twice — see `focusTarget` in `src/features/block-calendar/CalendarBlockAdapter.tsx` and `useSystemSkillsQuery`.
-
-## UI / Components
-- Prefer composition over configurability. Follow slot-based patterns (see src/features/channel, src/features/entity, or Kobalte).
-- Keep reusable components small, atomic, and decoupled from queries/complex state. Push data-fetching and mutations up to use-case-specific composed components.
-- Context should be scoped to a component subtree — Message.Content consuming a MessageContext is fine because the ownership boundary is clear.
-- Composed primitives must not depend on use-case-specific context — a RecipientsSelector should never require an EmailComposeContext.
-- New features and feature restructures use the layered layout in [docs/FRONTEND_FEATURE_ARCHITECTURE.md](../../docs/FRONTEND_FEATURE_ARCHITECTURE.md), summarized by FE-33 (`core / queries / primitives / components / views` plus an injected `context/`). Keep production wiring in an app-facing entry point and give reactive logic narrow feature-owned contracts. `src/features/activity` illustrates the layers but still has documented composition and contract migration gaps.
-
-### Porting shadcn-solid primitives
-- Use the upstream structure and behavior as a starting point, then reshape exports to match the local slot-based, compound-component API.
-- Replace upstream palette, surface, border, and status classes with the existing semantic tokens; inputs normally use `bg-input`, `border-edge-muted`, `text-ink`, and `text-ink-placeholder`.
-- Preserve Kobalte semantics, state attributes, and polymorphic prop types. Keep accessibility relationships inside the primitive instead of recreating them at call sites.
-- Add a co-located `*.docs.tsx` gallery page and focused `*.test.tsx` coverage for every ported component.
-- Keep `Input` a thin native control. Use `InputGroup` for icons, clear actions, inline Buttons, and shared ButtonGroup framing instead of adding composition props to `Input`.
-- In `InputGroup`, keep the input as the single control and place surrounding content in `Addon` slots. Use `align` for visual placement so accessible DOM order stays independent of layout.
-
-## Styling
-- Use semantic color tokens, not raw Tailwind color classes.
-- Do not add cursor-pointer to clickable elements.
-- Prefer styling in the component (Tailwind classes on the markup) so styling lives next to structure. Reserve `@utility` in `index.css` for styles that are widely shared across many components — not one-off or two-component layouts.
-
-## TS
-- For exhaustive switch statements use `match` from `ts-pattern`.
-
-### Misc
-- If you create a Lexical Node or make breaking changes to a Lexical Node, you must increment the lexical version counter (in src/lib/core/component/LexicalMarkdown/version.ts) along with a brief note about changes.
-- Do not add dependencies on the legacy block state system. Read it only at an
- existing block-adapter boundary, then pass identity, permissions, state, and
- lifecycle through feature context or explicit props; see FE-34 in
- `docs/STYLE_GUIDE.md`.
+## Rules
+
+Conventions for this app live in `.agents/rules/web/` and load when you touch
+matching files: data fetching, Solid reactivity, architecture, UI, UI primitives,
+the startup bundle, and Lexical nodes.
### Good Reference
- https://github.com/solidjs-community/solid-primitives
diff --git a/apps/web/docs/graphql-cache-testing.md b/apps/web/docs/graphql-cache-testing.md
index d2de4e5983..72bf10fe46 100644
--- a/apps/web/docs/graphql-cache-testing.md
+++ b/apps/web/docs/graphql-cache-testing.md
@@ -111,7 +111,7 @@ Before treating the entire query surface as covered, also require:
- Existing schema projection, identity isolation, cursor retention, worker
lifecycle, and mutation recipe tests to pass.
- Browser checks of optimistic edits and rollback across tabs, with delayed
- mutation and refetch responses; see [task verification](../../../docs/AGENT_GUIDE/tasks.md).
+ mutation and refetch responses; see [task verification](../../../docs/agent-guide/tasks.md).
- Storage failure and worker takeover tests against the actual storage adapters.
- Longer rotating-seed runs and permanent regressions for every discovered bug.
diff --git a/apps/web/docs/local-predicate-pagination-plan.md b/apps/web/docs/local-predicate-pagination-plan.md
index 63f16d6ce1..1958d5e380 100644
--- a/apps/web/docs/local-predicate-pagination-plan.md
+++ b/apps/web/docs/local-predicate-pagination-plan.md
@@ -6,8 +6,7 @@ The `soup-mail-v1` ALL/INBOX slice now uses exclusive keyset pages bound to a
query fingerprint, engine generation and cache revision. Pages cover complete
cached Mail projections, not proof of whole-mailbox coverage. This is separate
from the all-or-network proposal below; other Soup partitions continue to use
-server-baseline reconciliation. See `docs/AGENT_GUIDE/surfaces.md` at the repository
-root for the shipped scope and remaining filters.
+server-baseline reconciliation. See `docs/agent-guide/email.md` (Cached Mail filtering) for the shipped scope and remaining filters.
The implementation now reconciles loaded server-page membership with bounded local
candidates, retaining unknown baseline rows and removing confirmed non-matches/deletions.
diff --git a/apps/web/justfile b/apps/web/justfile
index 8cca5b1c1e..1790c50e74 100644
--- a/apps/web/justfile
+++ b/apps/web/justfile
@@ -82,7 +82,7 @@ local-services:
@sed -n "s/.*'\([a-z][-a-z]*\)':.*/\1/p" src/lib/core/constant/servers.ts | sort -u
# Run the app with local services (defaults to ALL)
-# This assumes you have followed the docs/RUNNING_LOCALLY.md instructions
+# This assumes you have followed the docs/development/running-locally.md instructions
servers := 'ALL'
port := '3000'
diff --git a/apps/web/scripts/android-firebase.ts b/apps/web/scripts/android-firebase.ts
index 48e3c9c091..6d69f9e573 100644
--- a/apps/web/scripts/android-firebase.ts
+++ b/apps/web/scripts/android-firebase.ts
@@ -77,7 +77,7 @@ export function fetchAndroidFirebase(pin: (typeof pins)['dev']) {
).trim();
} catch {
throw new Error(
- `Unable to fetch Android Firebase config from Doppler ${pin.project}/${pin.config}. Install the Doppler CLI and authenticate with access to this config (CI: DOPPLER_TOKEN), or pass --firebase-config. See docs/ANDROID_DEVELOPMENT.md.`
+ `Unable to fetch Android Firebase config from Doppler ${pin.project}/${pin.config}. Install the Doppler CLI and authenticate with access to this config (CI: DOPPLER_TOKEN), or pass --firebase-config. See docs/development/android.md.`
);
}
if (createHash('sha256').update(contents).digest('hex') !== pin.sha256)
diff --git a/apps/web/scripts/android-release.test.ts b/apps/web/scripts/android-release.test.ts
index cc6787f4fb..4d61dc154b 100644
--- a/apps/web/scripts/android-release.test.ts
+++ b/apps/web/scripts/android-release.test.ts
@@ -202,7 +202,7 @@ describe('Android signing provisioning', () => {
throw new Error('secret-password');
});
await expect(ensureAndroidSigning(directory, properties)).rejects.toThrow(
- 'Unable to fetch Android signing credentials. Install the Doppler CLI and authenticate with read access to android-release/prd (CI: DOPPLER_TOKEN). See docs/ANDROID_DEVELOPMENT.md.'
+ 'Unable to fetch Android signing credentials. Install the Doppler CLI and authenticate with read access to android-release/prd (CI: DOPPLER_TOKEN). See docs/development/android.md.'
);
await expect(stat(directory)).rejects.toMatchObject({ code: 'ENOENT' });
await expect(stat(properties)).rejects.toMatchObject({ code: 'ENOENT' });
diff --git a/apps/web/scripts/android-release.ts b/apps/web/scripts/android-release.ts
index 01d09d09af..e6d5ce33d9 100644
--- a/apps/web/scripts/android-release.ts
+++ b/apps/web/scripts/android-release.ts
@@ -154,7 +154,7 @@ function fetchSigning() {
);
} catch {
throw new Error(
- 'Unable to fetch Android signing credentials. Install the Doppler CLI and authenticate with read access to android-release/prd (CI: DOPPLER_TOKEN). See docs/ANDROID_DEVELOPMENT.md.'
+ 'Unable to fetch Android signing credentials. Install the Doppler CLI and authenticate with read access to android-release/prd (CI: DOPPLER_TOKEN). See docs/development/android.md.'
);
}
}
@@ -167,7 +167,7 @@ export async function ensureAndroidSigning(
if (existsSync(propertiesPath)) return;
if (lstatSync(propertiesPath, { throwIfNoEntry: false })) {
throw new Error(
- 'Android keystore.properties is a broken symlink. Restore its signing files; see docs/ANDROID_DEVELOPMENT.md.'
+ 'Android keystore.properties is a broken symlink. Restore its signing files; see docs/development/android.md.'
);
}
@@ -178,7 +178,7 @@ export async function ensureAndroidSigning(
!existsSync(join(directory, 'upload-keystore.jks'))
) {
throw new Error(
- `Android signing directory ${directory} is incomplete. Restore its signing files or provision signing manually; see docs/ANDROID_DEVELOPMENT.md.`
+ `Android signing directory ${directory} is incomplete. Restore its signing files or provision signing manually; see docs/development/android.md.`
);
}
await symlink(resolve(properties), propertiesPath);
diff --git a/apps/web/src/components/ui/components/FileTree.docs.tsx b/apps/web/src/components/ui/components/FileTree.docs.tsx
index 719c4977fe..540d05b1a3 100644
--- a/apps/web/src/components/ui/components/FileTree.docs.tsx
+++ b/apps/web/src/components/ui/components/FileTree.docs.tsx
@@ -21,7 +21,7 @@ const REPOSITORY: ExampleFile[] = [
owner: 'backend',
},
{ path: 'crates/macro_inbox/Cargo.toml', bytes: 700, owner: 'backend' },
- { path: 'docs/STYLE_GUIDE.md', bytes: 15_000 },
+ { path: 'docs/development/style-guide.md', bytes: 15_000 },
{ path: 'justfile', bytes: 2600 },
{ path: 'README.md', bytes: 3100 },
];
diff --git a/apps/web/src/features/block-canvas/README.md b/apps/web/src/features/block-canvas/README.md
index 21afe7eaaa..3357b4f5d6 100644
--- a/apps/web/src/features/block-canvas/README.md
+++ b/apps/web/src/features/block-canvas/README.md
@@ -26,7 +26,7 @@ Saves are debounced and serialized; failures keep edits dirty. Save state is not
shown in the canvas UI.
SyncService integration and collaboration remain a follow-up. This change keeps
-the existing whole-file save behavior. See [Graphics and Canvas parity](../../../../../docs/GRAPHICS_PARITY.md)
+the existing whole-file save behavior. See [Graphics and Canvas parity](../../../../../docs/design/graphics-parity.md)
for the remaining editor and collaboration work.
## Controls
diff --git a/apps/web/src/features/slack-import/core/export.ts b/apps/web/src/features/slack-import/core/export.ts
index e79a24a52b..768bc9968c 100644
--- a/apps/web/src/features/slack-import/core/export.ts
+++ b/apps/web/src/features/slack-import/core/export.ts
@@ -1,6 +1,6 @@
import { z } from 'zod';
-/** Browser-owned subset of the effective limits in SLACK_ARCHIVE_IMPORT_CONTRACT.md. */
+/** Browser-owned subset of the effective limits in docs/runbooks/slack-archive-import-contract.md. */
export type ArchiveLimits = {
jsonBytes: number;
selectedBytes: number;
diff --git a/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts b/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts
index bc05825817..7fb480d9d1 100644
--- a/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts
+++ b/apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts
@@ -14,14 +14,14 @@ val keystorePropertiesFile = rootProject.file("keystore.properties")
// Defer signing failures until release work is requested so debug builds remain usable.
val releaseSigningProperties = runCatching {
if (!keystorePropertiesFile.isFile) {
- throw GradleException("Release builds require keystore.properties; see docs/ANDROID_DEVELOPMENT.md")
+ throw GradleException("Release builds require keystore.properties; see docs/development/android.md")
}
val properties = Properties().apply {
keystorePropertiesFile.inputStream().use { load(it) }
}
for (name in listOf("keyAlias", "keyPassword", "storePassword", "storeFile")) {
if (properties.getProperty(name).isNullOrBlank()) {
- throw GradleException("Missing $name in keystore.properties; see docs/ANDROID_DEVELOPMENT.md")
+ throw GradleException("Missing $name in keystore.properties; see docs/development/android.md")
}
}
if (!rootProject.file(properties.getProperty("storeFile")).isFile) {
@@ -35,7 +35,7 @@ if (firebaseConfigured) {
}
gradle.taskGraph.whenReady {
if (!firebaseConfigured && allTasks.any { it.name.contains("Release") }) {
- throw GradleException("Release builds require app/google-services.json for com.macro.workspace.mobile; see docs/ANDROID_DEVELOPMENT.md")
+ throw GradleException("Release builds require app/google-services.json for com.macro.workspace.mobile; see docs/development/android.md")
}
if (allTasks.any { it.name.contains("Release") }) {
releaseSigningProperties.getOrThrow()
diff --git a/crates/activity/AGENTS.md b/crates/activity/AGENTS.md
new file mode 100644
index 0000000000..d7266188de
--- /dev/null
+++ b/crates/activity/AGENTS.md
@@ -0,0 +1,53 @@
+# activity
+
+## What it is
+
+Shared infrastructure behind activity feeds, entity timelines, and
+attribution sorts across the product (Soup, Documents, Forms, Databases,
+Initiative, and more): one durable `activity_events` row per "a principal
+did something to an entity." Domain crates decide what counts as activity
+in their own domain; this crate owns the vocabulary, storage, and
+distribution.
+
+## Start here
+
+- `src/domain/models.rs`: `Action`, `Activity`, and the `DomainActivity`
+ contract every domain crate implements.
+- `src/domain/service.rs` + `src/domain/ports.rs`: the ingest/query service
+ and the ports it depends on.
+- `src/outbound/pg_activity_repo.rs`: the single `activity_events` table.
+- `src/inbound/kafka_consumer.rs` + `src/outbound/activity_topic_consumer.rs`:
+ generic Kafka consumer wired to per-domain event mappings.
+
+## Scope
+
+- Owns: the `Action` vocabulary, the `Activity`/`ActivityRecord` row shape,
+ feeds/timeline/overview queries, and realtime distribution of new activity.
+- Not here: deciding what counts as activity in a given domain — each domain
+ crate depends on this with `default-features = false` (models only) and
+ implements its own event → `DomainActivity` mapping; the hosting service
+ declares consumed topics and dispatches.
+
+## Boundaries
+
+- Depends on: `macro_event_broker`, `macro_event_topics`, `channel_sender`,
+ `model-entity`, `model_owner`.
+- Used by: most domain crates with activity surfaces (`documents`, `forms`,
+ `databases`, `initiative`, `messages`, `channels`, `soup`, `call`, `chat`,
+ `work_feed`, `projects`, `github`, `email`, `properties`) and `ai_tools`.
+
+## Recipes
+
+- Add a new activity source in a domain: implement `DomainActivity` for the
+ domain's event type → map it in the domain crate's own consumer → register
+ the topic in the hosting service's composition root.
+- Add a feed/timeline query: `src/domain/timeline.rs` or
+ `src/domain/overview.rs` → `src/domain/ports.rs` → `src/outbound/pg_activity_repo.rs`.
+
+## Checks
+
+- `cargo test -p activity` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/activity/CLAUDE.md b/crates/activity/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/activity/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/agent/AGENTS.md b/crates/agent/AGENTS.md
new file mode 100644
index 0000000000..ca63cb1f3c
--- /dev/null
+++ b/crates/agent/AGENTS.md
@@ -0,0 +1,57 @@
+# agent
+
+## What it is
+
+Part of AI: the model-agnostic turn runner every AI surface in the product
+builds on — agent sessions, document AI, and background AI features all
+run a turn through this crate's loop, with a shared model/speed vocabulary
+and usage metering.
+
+## Start here
+
+- `src/agent_loop.rs`: `AgentLoop`/`Session` — runs a turn, dispatches tool
+ calls, loops until a final response.
+- `src/model/`: provider adapters (`anthropic.rs`, `openai.rs`, `gemini.rs`)
+ behind `model/router.rs`, plus `predefined_model.rs`/`speed.rs` (the
+ product-facing model/speed vocabulary) and `metering.rs` (usage recording
+ hook into `ai_usage`).
+- `src/stream.rs`: `StreamPart`/`ChatCompletionStream`, the wire shape
+ callers consume.
+- `src/completion.rs`: one-shot, non-looping completions (no tools).
+- `src/structured_output.rs`: prompted JSON generation for schema-conforming
+ output, used where providers don't support native structured output.
+
+## Scope
+
+- Owns: the turn loop, provider routing/model selection, streaming parts,
+ and metering integration.
+- Not here: tool definitions and schemas → `ai_toolset`, `ai_tools`; usage
+ pricing/billing → `ai_usage`, `ai_billing`.
+
+## Boundaries
+
+- Depends on: `ai_usage` (metering), `ai_toolset` (tool adapter trait),
+ `attachment`, `genai_telemetry`, `prompt`, `rig-core`/`rig-agent`.
+- Used by: `agent_inmem`, `ai_tools`, `ai_projections` (`agent` feature),
+ and most AI-surface crates that run a turn (directly or via `ai_tools`).
+
+## Recipes
+
+- Add a model: `src/model/predefined_model.rs` (enum variant) →
+ `src/model/router.rs` (dispatch) → provider adapter in `src/model/` →
+ pricing in `ai_usage`.
+- Add a stream part / tool-call shape change: `src/stream.rs` → `src/convert.rs`
+ (rig message conversion) → `src/accumulator.rs` (accumulation across chunks).
+
+## Checks
+
+- `cargo test -p agent` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `rig-core`/`rig-agent` are pinned exact versions (not workspace deps);
+ bump both together and check `test-utils` feature compatibility.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md` · Skill: `upgrade-model`
diff --git a/crates/agent/CLAUDE.md b/crates/agent/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/agent/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/agent_changes/AGENTS.md b/crates/agent_changes/AGENTS.md
new file mode 100644
index 0000000000..7ab639855e
--- /dev/null
+++ b/crates/agent_changes/AGENTS.md
@@ -0,0 +1,45 @@
+# agent_changes
+
+## What it is
+
+Part of agent sessions: after each turn, reviews the GitHub pull request
+linked to a coding-agent session and captures per-file diff facts, the
+patch, and a summary, so the harness and its UI can show what changed
+without re-reading the repo.
+
+## Start here
+
+- `src/domain/service.rs`: capture flow — reads the PR through a port,
+ derives file facts, stores the patch (S3) and summary (Postgres).
+- `src/domain/ports.rs`: `PullRequestReader` and the storage ports the
+ service depends on.
+- `src/inbound/`: HTTP handlers taking session access receipts.
+- `src/outbound/`: S3 patch storage, Postgres summary storage, GitHub token
+ adapter.
+
+## Scope
+
+- Owns: deriving and storing a session's PR change summary and patch.
+- Not here: whether the caller may see the session or repo — checked by the
+ owning GitHub token service before this crate is reached.
+
+## Boundaries
+
+- Depends on: `agent_session`, `agent_fold`, `entity_access`, `git_patch`,
+ `github_pull_requests`, `teams`.
+- Used by: `agent_harness_service` (full), `document_storage_service`
+ (`outbound` only, for the capture-after-turn path).
+
+## Recipes
+
+- Add a derived file fact: `src/domain/service.rs` (derivation) →
+ `src/domain/model.rs` (shape) → Postgres summary schema in
+ `src/outbound/` migrations.
+
+## Checks
+
+- `cargo test -p agent_changes` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/agent_changes/CLAUDE.md b/crates/agent_changes/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/agent_changes/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/agent_egress/AGENTS.md b/crates/agent_egress/AGENTS.md
new file mode 100644
index 0000000000..f9c064910c
--- /dev/null
+++ b/crates/agent_egress/AGENTS.md
@@ -0,0 +1,52 @@
+# agent_egress
+
+## What it is
+
+Part of agent sessions: the security boundary for sandboxed coding agents.
+A sandbox running model-authored code holds only a short-lived session
+token; this crate resolves that token to the right upstream credential (an
+MCP app, a custom server, or a GitHub installation token) on each request.
+
+## Start here
+
+- `src/lib.rs` doc comment: the full request flow (session token → grant →
+ credential port → forward).
+- `src/domain/service.rs`: `EgressServiceImpl` — steps 2 and 3 (token → grant,
+ grant → credential).
+- `src/domain/ports.rs`: `SessionAuthority`, `McpCredentials`, `GithubTokens`,
+ `Forwarder`.
+- `src/outbound/mcp_credentials.rs` / `macro_mcp.rs` / `custom_mcp.rs` /
+ `github_tokens.rs`: the credential resolvers.
+- `src/inbound/axum_router.rs`: the HTTP entry point the sandbox calls.
+
+## Scope
+
+- Owns: resolving a session token to a scoped upstream credential and
+ deciding whether a request is allowed; never names a destination itself.
+- Not here: byte-shovelling the forwarded request — `src/outbound/forwarder.rs`
+ is a thin port deliberately kept separate so the decision logic is testable
+ without a socket.
+
+## Boundaries
+
+- Depends on: `agent_session` (session/owner lookup), `agent_runtime_protocol`.
+- Used by: `agent_harness_service`, `preview_gateway`.
+
+## Recipes
+
+- Add a new upstream credential type: `src/domain/ports.rs` (new port) →
+ `src/outbound/` (adapter) → `src/domain/service.rs` (dispatch) →
+ `src/domain/approval.rs` if it needs owner approval.
+
+## Checks
+
+- `cargo test -p agent_egress` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Never let the sandbox see an upstream credential directly; every egress
+ path must go through a port here, not a bypass in the harness.
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md`, `.agents/rules/rust/architecture.md`
diff --git a/crates/agent_egress/CLAUDE.md b/crates/agent_egress/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/agent_egress/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/agent_harness/AGENTS.md b/crates/agent_harness/AGENTS.md
new file mode 100644
index 0000000000..f370abeefc
--- /dev/null
+++ b/crates/agent_harness/AGENTS.md
@@ -0,0 +1,50 @@
+# agent_harness
+
+## What it is
+
+Part of agent sessions: orchestrates sandboxed coding-agent sessions end to
+end — provisioning containers, speaking to each coding-agent runtime
+(Claude, Codex), routing triggers to a session, and relaying ACP traffic
+between the sandbox and the rest of the product.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/ports.rs`: the harness service and
+ the ports every runtime/container provider implements.
+- `src/domain/claude.rs` / `src/domain/codex.rs`: per-runtime session setup.
+- `src/outbound/sidecar.rs` + `sidecar_pump.rs`: the container sidecar
+ transport that speaks `agent_runtime_protocol`.
+- `src/outbound/containers.rs` / `managed_containers.rs`: container
+ provisioning.
+- `src/domain/trigger_router.rs`: routes an incoming trigger to a session.
+- `src/inbound/kafka.rs`: trigger ingestion.
+
+## Scope
+
+- Owns: session lifecycle orchestration, container provisioning, runtime
+ selection, MCP/tool-approval wiring for sandboxed sessions.
+- Not here: session state/persistence → `agent_session`; credential
+ stamping for sandbox egress → `agent_egress`; the ACP wire protocol →
+ `agent_runtime_protocol`.
+
+## Boundaries
+
+- Depends on: `agent_session`, `agent_egress`, `agent_runtime_protocol`,
+ `agent_trigger`, `ai_billing`.
+- Used by: `agent_harness_service` (its sole host).
+
+## Recipes
+
+- Add a new runtime: `src/domain/<runtime>.rs` (session setup) →
+ `src/outbound/<runtime>.rs` (adapter) → `src/domain/service.rs` (dispatch)
+ → `src/inbound/capability_discovery.rs` if it needs discovery.
+- Add a trigger source: `crates/agent_trigger` (context) →
+ `src/domain/trigger_router.rs` → `src/inbound/kafka.rs`.
+
+## Checks
+
+- `cargo test -p agent_harness` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/security.md`
diff --git a/crates/agent_harness/CLAUDE.md b/crates/agent_harness/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/agent_harness/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/agent_inmem/AGENTS.md b/crates/agent_inmem/AGENTS.md
new file mode 100644
index 0000000000..6c1594c800
--- /dev/null
+++ b/crates/agent_inmem/AGENTS.md
@@ -0,0 +1,49 @@
+# agent_inmem
+
+## What it is
+
+Part of agent sessions: the lightweight alternative to `agent_harness`'s
+sandboxed containers — serves the agent side of ACP in-process, running
+the same agentic loop behind the same ACP contract, so a session starts in
+milliseconds instead of waiting on container provisioning.
+
+## Start here
+
+- `src/rig_engine.rs`: `RigTurnEngine` — the production composition root,
+ runs one turn over `agent::AgentLoop` and the Macro toolset.
+- `src/domain/engine.rs`: `TurnEngine` port — the seam `rig_engine` fills.
+- `src/outbound/manager.rs`: `InMemAgentManager` — provisions per-session
+ agent tasks, implements the container-manager port the harness expects.
+- `src/domain/session.rs` / `src/domain/replay.rs`: in-process session state
+ and log replay on reconnect.
+- `src/domain/admission.rs` + `src/outbound/approval_gate.rs`: usage/plan
+ admission and tool-approval gating for in-memory sessions.
+
+## Scope
+
+- Owns: running the agentic loop in-process behind the same ACP contract as
+ the sandboxed harness, so session log/fold/UI code is runtime-agnostic.
+- Not here: sandboxed container sessions → `agent_harness`; the ACP wire
+ shapes themselves → `agent_runtime_protocol`.
+
+## Boundaries
+
+- Depends on: `agent` (the turn loop), `ai_toolset`, `agent_egress`
+ (`egress_mcp.rs`), `ai_billing`, `ai_usage`.
+- Used by: `agent_harness_service` (its sole host, alongside
+ `agent_harness` for sandboxed sessions).
+
+## Recipes
+
+- Add compaction/summarization behavior: `src/domain/engine.rs` →
+ `src/rig_engine.rs`.
+- Add a new tool gate or admission check: `src/domain/tool_gate.rs` /
+ `src/domain/admission.rs` → `src/outbound/approval_gate.rs`.
+
+## Checks
+
+- `cargo test -p agent_inmem` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/agent_inmem/CLAUDE.md b/crates/agent_inmem/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/agent_inmem/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/agent_preview/AGENTS.md b/crates/agent_preview/AGENTS.md
new file mode 100644
index 0000000000..afd9de17c1
--- /dev/null
+++ b/crates/agent_preview/AGENTS.md
@@ -0,0 +1,46 @@
+# agent_preview
+
+## What it is
+
+Part of agent sessions: lets an agent session's dev server be viewed live
+by other people. Leases an entity-authorized preview and proxies
+HTTP/WebSocket traffic (including Vite HMR) to viewers over a tunnel built
+on stock OpenSSH reverse forwarding.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/ports.rs`: lease/authorization
+ policy, independent of HTTP and SSH.
+- `src/inbound/ssh.rs`: accepts the sandbox's reverse SSH tunnel.
+- `src/inbound/http.rs`: serves the proxied preview to viewers.
+- `src/outbound/ssh_tunnel.rs`: the SSH transport implementation.
+- `src/inbound/toolset.rs`: the AI tool surface (`SharePreview`).
+
+## Scope
+
+- Owns: leasing a preview to an entity, authorizing viewers, and proxying
+ HTTP/WebSocket traffic (including Vite HMR) over the tunnel.
+- Not here: credential stamping on the sandbox side → `agent_egress`.
+
+## Boundaries
+
+- Depends on: `agent_egress` (shares the sandbox's egress credential path).
+- Used by: `preview_gateway` (its sole host).
+
+## Recipes
+
+- Add a preview policy: `src/domain/service.rs` → `src/domain/ids.rs` if a
+ new id shape is needed → `src/inbound/control.rs` for the control API.
+
+## Checks
+
+- `cargo test -p agent_preview` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Vite's module fan-out must be queued, not refused as `text/plain`, or HMR
+ breaks silently (see git history on `src/inbound/http.rs`).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/security.md`
diff --git a/crates/agent_preview/CLAUDE.md b/crates/agent_preview/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/agent_preview/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/agent_runtime_protocol/AGENTS.md b/crates/agent_runtime_protocol/AGENTS.md
new file mode 100644
index 0000000000..9b4bd25cae
--- /dev/null
+++ b/crates/agent_runtime_protocol/AGENTS.md
@@ -0,0 +1,50 @@
+# agent_runtime_protocol
+
+## What it is
+
+Part of agent sessions: the outer wire protocol every coding-agent
+transport (sandboxed containers, in-process, and the Cursor/Codex/Claude
+cloud-agent adapters) speaks — carries Agent Client Protocol (ACP) payloads
+plus runtime control messages without interpreting the wrapped ACP
+payloads.
+
+## Start here
+
+- `src/domain/connection.rs`: role-oriented connections (host vs. runtime
+ side of the wire).
+- `src/domain/turn.rs` / `src/domain/action.rs`: turn and action framing.
+- `src/domain/tool_approval.rs`: the approval message shapes used by owner
+ approval flows.
+- `src/domain/ports.rs`: the transport-agnostic wire port.
+- `src/outbound/websocket.rs`: the WebSocket transport adapter (behind the
+ `transport` feature).
+- `src/testing/wire_conformance.rs`: shared conformance tests for any new
+ transport.
+
+## Scope
+
+- Owns: the protocol schema and the role-oriented wire port; nothing about
+ how a session is provisioned or stored.
+- Not here: session lifecycle/state → `agent_session`; container/runtime
+ orchestration → `agent_harness`, `agent_inmem`.
+
+## Boundaries
+
+- Depends on: nothing crate-specific (foundational protocol crate).
+- Used by: `agent_session`, `agent_session_realtime`, `agent_harness`,
+ `agent_egress`, `agent_inmem`, `webhook`, `complete_graph`, and the
+ Cursor/Codex/Claude cloud-agent adapter crates.
+
+## Recipes
+
+- Add a new message type: `src/domain/` (schema) → `src/testing/wire_conformance.rs`
+ (conformance test) → `src/bin/export_types.rs` if the frontend needs the
+ generated type.
+
+## Checks
+
+- `cargo test -p agent_runtime_protocol` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/agent_runtime_protocol/CLAUDE.md b/crates/agent_runtime_protocol/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/agent_runtime_protocol/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/agent_session/AGENTS.md b/crates/agent_session/AGENTS.md
new file mode 100644
index 0000000000..e6f4610d0d
--- /dev/null
+++ b/crates/agent_session/AGENTS.md
@@ -0,0 +1,59 @@
+# agent_session
+
+## What it is
+
+Part of agent sessions: the coding-agent session entity itself — lifecycle,
+control, sharing, and the Postgres/HTTP surface every agent-harness
+consumer talks to.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/ports.rs`: the session service and
+ its ports — the widest surface in the crate.
+- `src/domain/lifecycle.rs`: create/resume/stop state machine.
+- `src/domain/model.rs`: the `AgentSession` entity shape.
+- `src/domain/turn_state.rs` + `src/domain/control.rs`: per-turn state and
+ the control-plane commands (used by held tool-call approvals).
+- `src/inbound/axum_router.rs`: the HTTP surface.
+- `src/outbound/postgres.rs`: the session repository.
+- `src/outbound/broker_lifecycle_publisher.rs` /
+ `broker_log_realtime.rs`: Kafka publication of lifecycle and log events.
+
+## Scope
+
+- Owns: session identity, lifecycle, sharing/audience, credentials, pull
+ request links, and the Postgres/HTTP/Kafka adapters for all of that.
+- Not here: container provisioning and runtime wiring → `agent_harness`,
+ `agent_inmem`; PR diff capture → `agent_changes`; the ACP wire format →
+ `agent_runtime_protocol`.
+
+## Boundaries
+
+- Depends on: `agent_runtime_protocol`, `agent_fold` (indirectly via
+ callers), `teams`, `macro_authorization`.
+- Used by: `agent_harness`, `agent_inmem`, `agent_egress`, `agent_trigger`,
+ `agent_changes`, `agent_session_realtime`, `ai_tools` (coding-agent
+ toolset), `complete_graph`, `webhook`, `search_service`, `soup_realtime`,
+ and the cloud-agent crates (`cursor_cloud_agents`, `codex_cloud_agents`).
+
+## Recipes
+
+- Add a session field: `src/domain/model.rs` → `src/outbound/postgres.rs`
+ (migration + query) → `src/inbound/axum_router.rs` (DTO) if exposed over
+ HTTP.
+- Add a lifecycle transition: `src/domain/lifecycle.rs` → `src/domain/service.rs`
+ → `src/outbound/broker_lifecycle_publisher.rs` if it should publish.
+
+## Checks
+
+- `cargo test -p agent_session` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- The row's fenced log writer and the Cursor projection both lock the
+ session row `FOR UPDATE`; never add a second `NOWAIT` locker without
+ checking both paths (see git history on `src/domain/control.rs`).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/agent_session/CLAUDE.md b/crates/agent_session/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/agent_session/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/agent_session_realtime/AGENTS.md b/crates/agent_session_realtime/AGENTS.md
new file mode 100644
index 0000000000..0f18caedde
--- /dev/null
+++ b/crates/agent_session_realtime/AGENTS.md
@@ -0,0 +1,35 @@
+# agent_session_realtime
+
+## What it is
+
+Part of agent sessions: fans out newly appended agent session log frames,
+from Kafka to whoever is subscribed over GraphQL, so an open session view
+updates live.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/ports.rs`: the fan-out service —
+ hands each consumed run of frames to its session's subscribers.
+- `src/outbound/log_topic_consumer.rs`: the Kafka consumer for
+ `macro.agent_session_log` (behind the `consumer` feature).
+
+## Scope
+
+- Owns: fanning out already-published log frames to live subscribers. No
+ composition root and no background tasks start here — the host owns that.
+- Not here: writing session log frames → `agent_session`; the GraphQL
+ subscription resolver itself → `complete_graph`.
+
+## Boundaries
+
+- Depends on: `agent_session` (log frame shape).
+- Used by: `complete_graph` (the GraphQL `agentSessionLogAppended`
+ subscription, its sole consumer).
+
+## Checks
+
+- `cargo test -p agent_session_realtime` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/observability.md`
diff --git a/crates/agent_session_realtime/CLAUDE.md b/crates/agent_session_realtime/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/agent_session_realtime/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/agent_trigger/AGENTS.md b/crates/agent_trigger/AGENTS.md
new file mode 100644
index 0000000000..217a5f6546
--- /dev/null
+++ b/crates/agent_trigger/AGENTS.md
@@ -0,0 +1,55 @@
+# agent_trigger
+
+## What it is
+
+Part of agent sessions: decides whether a posted channel message, task
+assignment, or project assignment should start an agent session, and
+assembles the prompt context (thread history, people, discussion) for the
+session that results.
+
+## Start here
+
+- `src/domain/service.rs`: orchestration for evaluating one posted message
+ — mention detection, admission, and dispatch.
+- `src/domain/sources.rs`: the trigger sources (explicit mention, implicit
+ reply, task/project assignment).
+- `src/domain/context.rs`: structured context assembled for the agent
+ prompt (thread history, people, discussion).
+- `src/domain/task_assignment.rs` / `src/domain/project_assignment.rs`:
+ non-message trigger paths.
+- `src/outbound/fast_model_judge.rs`: the Haiku-class implicit-trigger
+ classifier.
+
+## Scope
+
+- Owns: trigger detection/admission and prompt-context assembly for all
+ trigger sources.
+- Not here: running the agent session once triggered → `agent_harness`;
+ session state → `agent_session`.
+
+## Boundaries
+
+- Depends on: `agent_session`, `ai_billing` (admission, `admission`
+ feature), `messages`, `bots`.
+- Used by: `agent_trigger_service` (its primary host) and `agent_harness`
+ (routes triggers it receives via `agent_harness`'s `trigger_router`).
+
+## Recipes
+
+- Add a trigger source: `src/domain/sources.rs` → `src/domain/service.rs`
+ (admission + dispatch) → `src/domain/context.rs` if it needs new context.
+- Change implicit-reply detection: `src/outbound/fast_model_judge.rs` →
+ `src/outbound/lexical_explicit_reply_extractor.rs`.
+
+## Checks
+
+- `cargo test -p agent_trigger` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- A new trigger variant must also be taught to `crates/webhook` ingestion
+ and the SSE fan-out, or it will be silently dropped end to end.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/agent_trigger/CLAUDE.md b/crates/agent_trigger/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/agent_trigger/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/ai_billing/AGENTS.md b/crates/ai_billing/AGENTS.md
new file mode 100644
index 0000000000..9a92f00271
--- /dev/null
+++ b/crates/ai_billing/AGENTS.md
@@ -0,0 +1,55 @@
+# ai_billing
+
+## What it is
+
+Part of billing: meters and charges for AI usage across the product — plan
+allowances, prepaid credits, and post-paid overage for AI usage, priced at
+provider cost (plus markup for overage).
+
+## Start here
+
+- `src/lib.rs` doc comment: the pricing model (free/premium/max allowances,
+ overage markup) and the cost-cents vs. customer-cents unit split — read
+ before touching any number.
+- `src/domain/pricing.rs` + `src/config.rs`: `AiPricing`, built once at
+ startup from mandatory Doppler values.
+- `src/domain/admission.rs`: `AiAdmissionService` — the pre-call gate
+ (`ai_trigger`, etc. depend on this).
+- `src/domain/ledger.rs` + `src/domain/sweep.rs`: the credit/overage ledger
+ and the settlement sweep.
+- `src/outbound/stripe_gateway.rs`: the only place Stripe is called.
+
+## Scope
+
+- Owns: pricing, admission (can this call happen), and settling charges.
+- Not here: per-call token/cost tracking → `ai_usage` (this crate reads it
+ via `pg_usage_reader.rs`, never recomputes it).
+
+## Boundaries
+
+- Depends on: `ai_usage` (usage reader port).
+- Used by: `agent_harness_service`, `document_cognition_service`,
+ `agent_trigger_service`, `document_storage_service`,
+ `authentication_service`, `mcp_service`, `scheduled_action`, `ai_tools`,
+ `agent_session`, `agent_trigger`, `agent_inmem`, `channel_bots`, `memory`,
+ `documents`, `anthropic`, `import`.
+
+## Recipes
+
+- Change a pricing number: Doppler (never hardcode) → `src/config.rs` →
+ `src/domain/pricing.rs`.
+- Add an admission check: `src/domain/admission.rs` → `src/inbound/admission.rs`.
+
+## Checks
+
+- `cargo test -p ai_billing` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Usage is cost cents; credits/charges/caps/packs are customer cents — only
+ `AiPricing`'s conversions cross that boundary; never multiply/compare the
+ two directly.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md`
diff --git a/crates/ai_billing/CLAUDE.md b/crates/ai_billing/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/ai_billing/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/ai_engine/AGENTS.md b/crates/ai_engine/AGENTS.md
new file mode 100644
index 0000000000..280b6224cb
--- /dev/null
+++ b/crates/ai_engine/AGENTS.md
@@ -0,0 +1,53 @@
+# ai_engine
+
+## What it is
+
+Part of Documents: the engine behind the web app's Illustrator editor — a
+from-scratch Illustrator (`.ai`) implementation that reads Illustrator's
+PDF-based files, builds an editable model, renders it, edits with undo,
+collaborates, and saves files Illustrator and any PDF reader open. Runs
+natively and as WebAssembly.
+
+## Start here
+
+- `README.md`: the format background and the full module map — read this
+ first, it documents every module's role.
+- `src/model.rs`: artboards, layers, groups, paths, text, images.
+- `src/build.rs` + `src/interp.rs`: PDF content stream → model.
+- `src/edit.rs` + `src/collab.rs`: operations/undo and shared editing.
+- `src/save.rs`: writing the model back out as a PDF-based `.ai`.
+- `src/wasm.rs`: the wasm-bindgen shell (wasm32 only).
+
+## Scope
+
+- Owns: the entire `.ai`/PDF read-edit-render-save pipeline. Third-party
+ code is limited to small single-purpose libraries (`tiny-skia`,
+ `miniz_oxide`, `png`, `zune-jpeg`, `skrifa`); text layout shares
+ `fig_engine`'s font registry rather than duplicating it.
+- Not here: the web editor UI and worker wiring →
+ `apps/web/src/lib/core/ai-engine`.
+
+## Boundaries
+
+- Depends on: `fig_engine` (fonts, boolean ops, image decoding, JPEG
+ encoding).
+- Used by: `documents`, `search_processing_service` (native, for indexing),
+ the web app's Illustrator editor worker (wasm).
+
+## Recipes
+
+- Add support for a PDF feature: `src/pdf/` (parse) → `src/interp.rs`
+ (interpret) → `src/build.rs` (model it) → `src/render.rs` (draw it) →
+ `src/save.rs` (round-trip it).
+- Add an edit operation: `src/edit/nodes.rs` / `src/edit/shapes.rs` →
+ `src/edit/tree.rs` (undo/redo) → `src/collab.rs` if shared.
+
+## Checks
+
+- `cargo test -p ai_engine` (`SQLX_OFFLINE` unset not relevant; no DB).
+- The `ai_render` CLI (`cli` feature) round-trips and fidelity-scores
+ against reference renders — use it after parser/render changes.
+
+## Related
+
+- Docs: `crates/ai_engine/README.md`
diff --git a/crates/ai_engine/CLAUDE.md b/crates/ai_engine/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/ai_engine/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/ai_projections/AGENTS.md b/crates/ai_projections/AGENTS.md
new file mode 100644
index 0000000000..427f3bac9c
--- /dev/null
+++ b/crates/ai_projections/AGENTS.md
@@ -0,0 +1,47 @@
+# ai_projections
+
+## What it is
+
+Part of AI: materialized, cached AI-generated views of a user's data (for
+example a dashboard widget), keyed by a frontend-defined id and
+regenerated on demand or when cold.
+
+## Start here
+
+- `src/lib.rs` doc comment: the full lifecycle — upsert-and-read on
+ `POST /ai-projections`, async vs. `await: true` materialization,
+ `prompt_hash` versioning, push via connection gateway.
+- `src/domain/ai_projection_service.rs`: the upsert/read/invalidate logic.
+- `src/domain/projection_generator.rs`: the generation port.
+- `src/outbound/agent_generator.rs`: the agent-backed generator (behind the
+ `agent` feature) — two-phase when `output_schema` is set (tool-enabled
+ agent gathers context, then a structured completion distills it).
+- `src/worker.rs`: the SQS-polling worker that drains `ai_projection_queue`.
+
+## Scope
+
+- Owns: projection definitions, per-user cached instances, generation
+ orchestration (inline or queued), and push notification on completion.
+- Not here: the agent turn loop itself → `agent`; tool definitions →
+ `ai_tools`/`ai_toolset`.
+
+## Boundaries
+
+- Depends on: `models_ai_projection`, and (behind `agent`) `ai_tools`,
+ `ai_toolset`, `agent`, `ai_usage`.
+- Used by: `document_cognition_service` (inbound/outbound/agent) and
+ `ai_projections_refresh_handler` (the scheduled refresh lambda).
+
+## Recipes
+
+- Add a projection type: define its prompt/schema at the frontend-defined
+ id → `src/domain/model.rs` if a new output shape → `src/outbound/agent_generator.rs`
+ if it needs the two-phase schema path.
+
+## Checks
+
+- `cargo test -p ai_projections` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/ai_projections/CLAUDE.md b/crates/ai_projections/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/ai_projections/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/ai_tools/AGENTS.md b/crates/ai_tools/AGENTS.md
new file mode 100644
index 0000000000..278137c0d2
--- /dev/null
+++ b/crates/ai_tools/AGENTS.md
@@ -0,0 +1,56 @@
+# ai_tools
+
+## What it is
+
+Part of AI: assembles every domain crate's AI tool implementations into
+the one `AsyncToolCollection` every AI surface (chat, agent sessions, MCP)
+calls through, plus the cross-cutting tools (search, subagents, deferred
+execution, display) that don't belong to a single domain.
+
+## Start here
+
+- `src/lib.rs`: the composition point — imports each domain crate's
+ `inbound::toolset` module and builds the combined `AsyncToolCollection`
+ and frontend schema set.
+- `src/subagent.rs`: dispatches `snippet_specs` to parallel subagents.
+- `src/search.rs` / `src/search_tools.rs`: cross-entity search tools.
+- `src/deferred.rs`: tools whose result arrives after the turn (long-running
+ work).
+- `src/tool_context.rs` + `src/tool_context/`: per-tool context extraction.
+- `src/bin/gen_tool_schemas.rs`, `src/bin/gen_ai_request_schemas.rs`:
+ schema-generation binaries the frontend consumes.
+
+## Scope
+
+- Owns: assembling the toolset and the handful of tools with no single
+ domain owner (search, subagent, deferred, self-knowledge, display).
+- Not here: a domain's own tools — those live in that domain crate's
+ `inbound::toolset` (e.g. `forms`, `activity`, `agent_session`) and are
+ only wired in here.
+
+## Boundaries
+
+- Depends on: nearly every domain crate with tools (`forms`, `activity`,
+ `agent_session`, `anthropic`, `initiative`, `collab_surface`, `favorites`,
+ `routines`, `ai_billing`, `ai_usage`, `ai_toolset`, `agent`), plus
+ `bot_id`, `attachment`, `static_file`.
+- Used by: `document_storage_service`, `document_cognition_service`,
+ `agent_harness_service`, `mcp_service`.
+
+## Recipes
+
+- Add a tool to an existing domain: implement it in that domain crate's
+ `inbound::toolset` → it's picked up automatically via `src/lib.rs`'s
+ existing import — no change needed here unless it's cross-domain.
+- Add a cross-domain tool: new module in `src/` → register in
+ `src/lib.rs`'s toolset assembly → regenerate schemas (see Checks).
+
+## Checks
+
+- `cargo test -p ai_tools` (`SQLX_OFFLINE` unset).
+- After adding/changing a tool: `cargo run -p ai_tools --bin gen_tool_schemas`
+ and `--bin gen_ai_request_schemas` to refresh generated frontend schemas.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md` · Skill: `create-ai-tool`
diff --git a/crates/ai_tools/CLAUDE.md b/crates/ai_tools/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/ai_tools/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/ai_toolset/AGENTS.md b/crates/ai_toolset/AGENTS.md
new file mode 100644
index 0000000000..9a3b005e24
--- /dev/null
+++ b/crates/ai_toolset/AGENTS.md
@@ -0,0 +1,57 @@
+# ai_toolset
+
+## What it is
+
+Part of AI: the framework underneath every AI tool in the product — the
+`AsyncTool` trait, JSON schema generation via `schemars`, per-tool context
+extraction, and toolset collection/dispatch that `ai_tools` assembles
+domain crates' tools with.
+
+Do not change this crate without reading `TOOL_DESIGN.md` first; it is
+deliberately stable and widely depended on.
+
+## Start here
+
+- `src/lib.rs` doc comment: a worked multi-context toolset example — read
+ it before defining a new tool.
+- `src/tool.rs`: `AsyncTool`, `ToolAnnotated`, `ToolResult`.
+- `src/toolset/traits.rs` + `src/toolset/types.rs`: `AsyncToolCollection`
+ and how tools from different contexts combine.
+- `src/schema/generate.rs` + `src/schema/frontend_typegen.rs`: schema
+ generation for both the model-facing JSON schema and frontend TS types.
+- `src/annotations.rs`: required MCP tool annotations (every tool must set
+ these).
+- `src/context.rs`: `RequestContext`/`ServiceContext` and the `FromRef`
+ extraction pattern.
+
+## Scope
+
+- Owns: the tool trait, schema generation, and collection mechanics.
+- Not here: any actual tool implementation — those live in domain crates
+ and are assembled in `ai_tools`.
+
+## Boundaries
+
+- Depends on: `schemars`, `axum` (for `FromRef`-based context extraction).
+- Used by: nearly every domain crate that defines tools (`forms`,
+ `activity`, `agent_session`, `anthropic`, `databases`, `mcp_toolset`,
+ `crm`, `routines`, and many more) plus `ai_tools` itself and `agent`.
+
+## Recipes
+
+- Define a new tool: implement `AsyncTool` in the owning domain crate →
+ add required annotations (`src/annotations.rs`) → wire it into that
+ crate's `inbound::toolset` module → picked up by `ai_tools`.
+
+## Checks
+
+- `cargo test -p ai_toolset` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Every tool must declare MCP annotations; a tool without them fails to
+ compile/register (see `src/annotations.rs`).
+
+## Related
+
+- Docs: `crates/ai_toolset/TOOL_DESIGN.md` · Skill: `create-ai-tool`
diff --git a/crates/ai_toolset/CLAUDE.md b/crates/ai_toolset/CLAUDE.md
deleted file mode 100644
index fc238d541f..0000000000
--- a/crates/ai_toolset/CLAUDE.md
+++ /dev/null
@@ -1,3 +0,0 @@
-You are not allowed to _EVER_ change this crate.
-
-Guidelines for writing toolsets are in TOOL_DESIGN.md
diff --git a/crates/ai_toolset/CLAUDE.md b/crates/ai_toolset/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/ai_toolset/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/ai_usage/AGENTS.md b/crates/ai_usage/AGENTS.md
new file mode 100644
index 0000000000..572f8a62c4
--- /dev/null
+++ b/crates/ai_usage/AGENTS.md
@@ -0,0 +1,57 @@
+# ai_usage
+
+## What it is
+
+Part of billing: a robust log of AI usage with cost computed from model id
+and token counts (or audio duration), feeding `ai_billing`'s admission and
+ledger decisions, plus a flexible admin query API.
+
+## Start here
+
+- `src/lib.rs` doc comment: the layering (`domain`/`outbound`/`inbound`)
+ and the split between best-effort analytics tracking and the awaited,
+ fail-closed `FinancialUsage` capability for billable traffic.
+- `src/domain/financial.rs` + `src/domain/financial_service.rs`: immutable
+ provider cost evidence and exact customer-money calculation.
+- `src/domain/tracking.rs`: `UsageTracking` — the always-recorded log, used
+ for analytics regardless of billing status.
+- `src/domain/counting.rs`: `is_billable_feature` and the
+ `NON_BILLABLE_AI_FEATURES` allowlist.
+- `src/outbound/pg_usage_repo.rs`, `pg_tracking_repo.rs`,
+ `pg_financial_usage_repo.rs`: the Postgres adapters.
+
+## Scope
+
+- Owns: pricing a model invocation and logging usage/cost.
+- Not here: plan allowances, credits, and settlement → `ai_billing` (reads
+ this crate's financial usage, never recomputes cost itself).
+
+## Boundaries
+
+- Depends on: none notable outside the workspace-hack set.
+- Used by: `agent`, `agent_session`, `agent_harness`, `agent_trigger`,
+ `ai_billing`, `ai_tools`, `ai_projections`, `anthropic`, `call`,
+ `documents`, `import`, `image_generation`, `memory`, `channel_bots`,
+ `agent_inmem`, `dictation`, `task_dedup`, `jev`.
+
+## Recipes
+
+- Price a new model: `src/domain/financial.rs` (rate entry) →
+ `src/config.rs` (if a new Doppler-sourced rate) → test in
+ `src/config/test.rs`.
+- Mark a feature non-billable: `src/domain/counting.rs`'s
+ `NON_BILLABLE_AI_FEATURES`.
+
+## Checks
+
+- `cargo test -p ai_usage` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `UsageRecorder` (analytics) is best-effort and never fails the
+ originating call; `FinancialUsage` (billable) is awaited and fail-closed
+ — don't conflate the two when adding a new recording path.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md`
diff --git a/crates/ai_usage/CLAUDE.md b/crates/ai_usage/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/ai_usage/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/anthropic/AGENTS.md b/crates/anthropic/AGENTS.md
new file mode 100644
index 0000000000..fd8bbbc262
--- /dev/null
+++ b/crates/anthropic/AGENTS.md
@@ -0,0 +1,49 @@
+# anthropic
+
+## What it is
+
+Part of AI: the SDK client for the Anthropic Messages API that the rest of
+the product's AI surfaces (via `agent`) build requests against, plus an
+OpenAI-compatible request/response mapping layer and Anthropic's own
+server-side tools (web search, web fetch, bash/text-editor code
+execution).
+
+## Start here
+
+- `src/client.rs` + `src/client/chat.rs`: the Anthropic Messages API client and streaming.
+- `src/openai/mod.rs`: request/response mapping to the OpenAI `v1/chat/completions` shape
+ (feature `openai`) — the standard the `ai` crate builds requests against.
+- `src/toolset.rs` + `src/toolset/*.rs`: server-side tool implementations (feature `toolset`).
+- `src/types/mod.rs`: wire types for the Messages API.
+
+## Scope
+
+- Owns: the Anthropic API client, its OpenAI-shaped adapter, and Anthropic's
+ built-in tools (web search/fetch, code execution).
+- Not here: model selection, pricing, usage/billing policy, or the provider-agnostic
+ chat abstraction → `crates/agent`, `crates/ai_billing`, `crates/ai_usage`.
+
+## Boundaries
+
+- Depends on: `macro_env_var`, optionally `async-openai` (`openai` feature),
+ `ai_billing`/`ai_toolset`/`ai_usage` (`toolset` feature).
+- Used by: `crates/ai_tools`.
+
+## Recipes
+
+- Add/change a server tool: `src/toolset/<tool>.rs` → register in `src/toolset.rs`.
+- Map a new Anthropic response field into the OpenAI shape: `src/types/mod.rs` →
+ `src/openai/stream_response.rs` / `src/openai/stream_extension.rs`.
+
+## Checks
+
+- `cargo test -p anthropic` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `WebSearch` must tolerate a `pause_turn` stop reason and keep accumulating results
+ across turns rather than returning only the last turn's hits (#7421).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/anthropic/CLAUDE.md b/crates/anthropic/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/anthropic/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/attachment/.claude/skills/WRITE_ATTACHMENT_SERVICE/SKILL.md b/crates/attachment/.agents/skills/WRITE_ATTACHMENT_SERVICE/SKILL.md
similarity index 100%
rename from crates/attachment/.claude/skills/WRITE_ATTACHMENT_SERVICE/SKILL.md
rename to crates/attachment/.agents/skills/WRITE_ATTACHMENT_SERVICE/SKILL.md
diff --git a/crates/attachment/.claude/skills b/crates/attachment/.claude/skills
new file mode 120000
index 0000000000..2b7a412b8f
--- /dev/null
+++ b/crates/attachment/.claude/skills
@@ -0,0 +1 @@
+../.agents/skills
\ No newline at end of file
diff --git a/crates/attachment/AGENTS.md b/crates/attachment/AGENTS.md
new file mode 100644
index 0000000000..835707a99b
--- /dev/null
+++ b/crates/attachment/AGENTS.md
@@ -0,0 +1,55 @@
+# attachment
+
+## What it is
+
+Part of AI: the shared contract for turning a reference to any entity (a
+document, a channel message, a calendar event) into AI-consumable content,
+so AI tools and attachments behave the same way across every domain. No
+dependency on any domain crate.
+
+## Start here
+
+- `src/lib.rs`: the `AttachmentService` and `Attachable` traits.
+- `src/models.rs`: `AttachmentContent`, `AttachmentPart`, `AttachmentReference`,
+ `Attachments`, `FormattedParts`.
+- `src/fmt.rs`: XML formatting (`XmlTag`, `ClosedXmlTag`, `Indent`) used by `Attachable` impls.
+- `src/provider.rs`: `AttachmentProvider` router (feature `provider`), dispatching
+ `AttachmentReference` variants to per-domain services.
+
+## Scope
+
+- Owns: the `AttachmentService`/`Attachable` trait contracts and shared formatting
+ types used to turn entities into AI context.
+- Not here: resolving a specific entity type — each domain crate implements
+ `AttachmentService` in its own `inbound/attachment/` module (e.g. `crates/chat`,
+ `crates/channels`, `crates/documents`, `crates/email`).
+
+## Boundaries
+
+- Depends on: `macro_user_id`, `model-entity`, `non_empty`.
+- Used by: `channels`, `email`, `ai_tools`, `agent`, `agent_inmem`, `static_file`,
+ `chat`, `documents`, `image_generation` — each implementing `AttachmentService`.
+
+## Recipes
+
+- Add a new attachable entity type: implement `AttachmentService` in the owning
+ domain crate's `inbound/attachment/` module → add the `AttachmentReference`
+ variant in `src/models.rs` → wire it into `src/provider.rs` (if used behind the
+ router) → implement `Attachable` for the new content type in `src/attachable.rs`.
+
+## Checks
+
+- `cargo test -p attachment` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `AttachmentContent.content` is `NonEmpty<Vec<AttachmentPart>>` — never insert a
+ placeholder to satisfy the non-empty constraint; return `AttachmentError::NoContent`
+ if resolution produces zero parts.
+- Individual resolution failures surface as `ResolutionError` entries in the
+ `Attachments` batch; they never fail the whole batch.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md` · Skill: `WRITE_ATTACHMENT_SERVICE`
+ (`.claude/skills/` here) for implementing a new domain's `AttachmentService`.
diff --git a/crates/attachment/CLAUDE.md b/crates/attachment/CLAUDE.md
deleted file mode 100644
index 5c5807ca2c..0000000000
--- a/crates/attachment/CLAUDE.md
+++ /dev/null
@@ -1,29 +0,0 @@
-# attachment
-
-Shared crate that defines the `AttachmentService` trait and supporting types for resolving entity references into AI-consumable content.
-
-## Architecture
-
-This crate has two roles:
-
-1. **Trait definition** — `AttachmentService` and `Attachable` in `lib.rs`
-2. **Provider router** — `AttachmentProvider` (behind the `provider` feature) dispatches `AttachmentReference` variants to per-domain `AttachmentService` implementations
-
-Domain crates (documents, chat, email, comms) each implement `AttachmentService` in their own `inbound/attachment/` module. This crate does not depend on any domain crate.
-
-## Module map
-
-- `lib.rs` — `AttachmentService` trait, `Attachable` trait
-- `models.rs` — `AttachmentContent`, `AttachmentPart`, `AttachmentReference`, `AttachmentError`, `Attachments`, `FormattedParts`, `TextOrImage`
-- `fmt.rs` — XML formatting utilities (`XmlTag`, `ClosedXmlTag`, `Indent`) used by `Attachable` impls and by domain crates directly
-- `attachable.rs` — `Attachable` impls for all model types; converts the attachment tree into `FormattedParts`
-- `macros.rs` — `non_empty_collection!` macro for newtype wrappers around `NonEmpty<Vec<T>>`
-- `provider.rs` — `AttachmentProvider` router (feature-gated behind `provider`)
-
-## Key rules
-
-- `AttachmentContent.content` is `NonEmpty<Vec<AttachmentPart>>`. Never insert empty or placeholder strings to satisfy the non-empty constraint. If resolution produces zero parts, return `AttachmentError::NoContent`.
-- Use `AttachmentReference` variants to identify the source entity. The `Attachable` impl for `AttachmentContent` calls `reference.as_attributes()` to produce XML tags via `fmt::XmlTag`.
-- Use `AttachmentPart::Child` with the appropriate `AttachmentReference` for sub-attachments (e.g. inline images within a markdown document). This flows through the `Attachable` formatting system.
-- Use `fmt::XmlTag` / `fmt::ClosedXmlTag` for structured text formatting within attachment services (e.g. wrapping chat messages, channel messages).
-- Individual resolution failures surface as `ResolutionError` entries in the `Attachments` batch — they never fail the entire batch.
diff --git a/crates/attachment/CLAUDE.md b/crates/attachment/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/attachment/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/authentication_service_client/AGENTS.md b/crates/authentication_service_client/AGENTS.md
new file mode 100644
index 0000000000..d767f53f11
--- /dev/null
+++ b/crates/authentication_service_client/AGENTS.md
@@ -0,0 +1,44 @@
+# authentication_service_client
+
+## What it is
+
+Part of shared infrastructure: the typed Rust client other services use to
+call `authentication_service`'s internal API (users, Google access tokens,
+AI billing hooks, inbox-grant management), one module per endpoint group.
+
+## Start here
+
+- `src/lib.rs`: `AuthServiceClient` (base URL + internal-auth header) and the
+ `INTERNAL_AUTH_HEADER_KEY` every endpoint call authenticates with.
+- `src/users.rs`, `src/google_access_token.rs`, `src/ai_billing.rs`,
+ `src/unlink.rs`, `src/relocate_inbox_grant.rs`, `src/delete_inbox_grant_user.rs`:
+ one file per endpoint group, each adding methods to `AuthServiceClient`.
+- `src/error.rs`: shared client error type.
+
+## Scope
+
+- Owns: typed request/response methods for calling `authentication_service`'s
+ internal API.
+- Not here: `authentication_service`'s own HTTP routes or domain logic — this
+ crate only calls them.
+
+## Boundaries
+
+- Depends on: `model` (shared types), `reqwest`.
+- Used by: `email`, `google_token`, `ai_billing`, and other services that need
+ internal user/auth operations from `authentication_service`.
+
+## Recipes
+
+- Add a new endpoint call: add a method in the matching `src/<group>.rs` file
+ (or a new file + `pub mod` in `src/lib.rs` for a new group) → match the
+ request/response shape against the route in `authentication_service`'s inbound
+ router.
+
+## Checks
+
+- `cargo test -p authentication_service_client` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md`, `.agents/rules/rust/architecture.md`
diff --git a/crates/authentication_service_client/CLAUDE.md b/crates/authentication_service_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/authentication_service_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/bots/AGENTS.md b/crates/bots/AGENTS.md
new file mode 100644
index 0000000000..75dea975d0
--- /dev/null
+++ b/crates/bots/AGENTS.md
@@ -0,0 +1,49 @@
+# bots
+
+## What it is
+
+Part of agent sessions: owns the bot entity itself — models, persistence,
+ownership (user or team), and HTTP/AI-tool adapters, plus lifecycle events
+for bot mutations that channel bots, agent triggers, and memory build on.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/models.rs`: bot CRUD policy and model.
+- `src/domain/events.rs`: `bot.created`/`bot.updated`/`bot.deleted` events published
+ to the `macro.bots` Kafka topic (see `README.md` for the wire schema).
+- `src/inbound/axum_router.rs`, `src/inbound/channel_webhook_router.rs`,
+ `src/inbound/toolset.rs`: HTTP, channel-webhook, and AI-tool adapters.
+- `src/outbound/pg_bots_repo.rs`: Postgres repository (feature `outbound`).
+
+## Scope
+
+- Owns: bot CRUD, ownership (user or team), and bot lifecycle events.
+- Not here: agent sessions, channel message triggers, or trigger detection →
+ `crates/agent_session`, `crates/channel_bots`.
+
+## Boundaries
+
+- Depends on: `channels` (inbound, optional), `entity_access`, `entity_registry`,
+ `messages`, `macro_event_broker`/`macro_event_topics`, `macro_authorization`.
+- Used by: `memory`, `ai_tools`, `agent_trigger`, `complete_graph`, `agent_session`.
+
+## Recipes
+
+- Add a bot field or mutation: `src/domain/models.rs` → `src/domain/service.rs`
+ → `src/outbound/pg_bots_repo.rs` → `src/inbound/axum_router.rs` → emit/update
+ the matching event in `src/domain/events.rs` if it changes mutable state.
+- Add an AI tool over bots: `src/inbound/toolset.rs` (feature `ai_tools`).
+
+## Checks
+
+- `cargo test -p bots` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Kafka events key on the bot's bare UUID (no `bot|` prefix); `bot.updated`
+ metadata describes the requested PATCH, not a full snapshot — an omitted
+ field serializes as `null` (see `README.md`).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/observability.md`
diff --git a/crates/bots/CLAUDE.md b/crates/bots/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/bots/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/cal/AGENTS.md b/crates/cal/AGENTS.md
new file mode 100644
index 0000000000..abab352805
--- /dev/null
+++ b/crates/cal/AGENTS.md
@@ -0,0 +1,46 @@
+# cal
+
+## What it is
+
+Part of Calendar: receives cal.com booking-event webhooks and fires
+analytics events in response. Macro's own calendar/booking domain lives in
+`calendar_events`/`calendar_scheduling`; no other consumers of this crate
+in the workspace yet.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/models.rs`: webhook event parsing and policy.
+- `src/inbound/cal_webhook_router.rs`: HTTP router validating and dispatching
+ cal.com webhook signatures (feature `axum`).
+- `src/outbound/analytics_client.rs`: analytics sink adapter (feature `outbound`).
+
+## Scope
+
+- Owns: cal.com webhook signature verification and the booking→analytics-event
+ mapping.
+- Not here: Macro's own calendar/booking domain → `crates/calendar_events`,
+ `crates/calendar_scheduling`.
+
+## Boundaries
+
+- Depends on: `analytics_client` (feature `outbound`), `axum`/`utoipa`/`model-error-response`
+ (feature `axum`).
+- Used by: `services/document_storage_service`, its composition root.
+
+## Recipes
+
+- Handle a new cal.com event type: `src/domain/models.rs` (event variant) →
+ `src/domain/service.rs` → `src/inbound/cal_webhook_router.rs`.
+
+## Checks
+
+- `cargo test -p cal` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Webhook signature verification uses HMAC-SHA256 (`hmac`/`sha2`) over the raw
+ body; don't re-serialize the payload before verifying.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/cal/CLAUDE.md b/crates/cal/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/cal/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/calendar_events/AGENTS.md b/crates/calendar_events/AGENTS.md
new file mode 100644
index 0000000000..c218a7bb42
--- /dev/null
+++ b/crates/calendar_events/AGENTS.md
@@ -0,0 +1,60 @@
+# calendar_events
+
+## What it is
+
+Part of Calendar: owns the stable `CalendarEvent` entity — parsing from
+external sources (Google Calendar, email invitations), mutation, reminder
+dispatch, team availability, and Google/Postgres persistence.
+
+## Start here
+
+- `src/domain/models.rs` + `src/domain/events.rs`: the `CalendarEvent` entity and
+ recurrence-occurrence projections.
+- `src/domain/mutations.rs`, `src/domain/invitations.rs`, `src/domain/meeting_links.rs`:
+ write paths — mutations, email invitations, and Macro-call meeting links.
+- `src/domain/team_availability.rs` + `src/domain/team.rs`: team sharing/availability.
+- `src/outbound/google.rs`, `src/outbound/pg.rs`: Google Calendar and Postgres adapters.
+- `src/inbound/dispatch_worker.rs` + `src/outbound/sqs_dispatch_queue.rs`: reminder
+ dispatch queue (feature `dispatch`/`dispatch-sqs`).
+
+## Scope
+
+- Owns: the `CalendarEvent` entity, its Google/email/Postgres sources, recurrence
+ occurrences, reminder dispatch, and team calendar sharing/availability.
+- Not here: booking links, scheduling pages, and host/attendee booking policy →
+ `crates/calendar_scheduling`; the calendar service's HTTP composition root →
+ `services/calendar_service`.
+
+## Boundaries
+
+- Depends on: `call` (feature `call-meetings`, meeting links), `macro_user_id`,
+ `notification` (feature `notify`), `model_notifications`, `aws-sdk-sqs`
+ (feature `dispatch-sqs`).
+- Used by: `email`, `ai_tools`, `channel_bots`, `graphql_calendar`, `complete_graph`,
+ `calendar_scheduling`.
+
+## Recipes
+
+- Add a mutation: `src/domain/mutations.rs` → `src/outbound/pg.rs` (or
+ `src/outbound/calendar_service_mutations.rs` for the HTTP client adapter) →
+ `src/inbound/mutation_router.rs` / `src/inbound/toolset.rs`.
+- Add a reminder type: `src/domain/reminder_dispatch.rs` → `src/inbound/dispatch_worker.rs`
+ → `src/outbound/notification_notifier.rs`.
+- Change team availability: `src/domain/team_availability.rs` → `src/outbound/pg_team.rs`
+ → `src/inbound/team_router.rs` / `src/inbound/team_toolset.rs`.
+
+## Checks
+
+- `cargo test -p calendar_events` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `CalendarEvent` is the stable Macro entity; external calendars and email
+ invitations are sources feeding it, and recurrence instances are queryable
+ occurrence projections, not separate events — don't model them as new entities.
+- Imported point (non-recurring) events must survive sync and cache round-trips
+ unchanged (#7762) — a regression here silently drops user events.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/calendar_events/CLAUDE.md b/crates/calendar_events/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/calendar_events/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/calendar_scheduling/AGENTS.md b/crates/calendar_scheduling/AGENTS.md
new file mode 100644
index 0000000000..c11398cbdb
--- /dev/null
+++ b/crates/calendar_scheduling/AGENTS.md
@@ -0,0 +1,59 @@
+# calendar_scheduling
+
+## What it is
+
+Part of Calendar: personal and Macro-team booking pages — event types,
+availability, collective/round-robin hosts, booking limits, and the booking
+lifecycle. See `README.md` for the full product model and the required
+MacroDB migrations.
+
+## Start here
+
+- `README.md`: integration requirements, booking semantics, and web entry points
+ (`/app/book/:profile/:slug?`, `/app/booking/:id#token`) — read before changing behavior.
+- `src/domain/service.rs`: authorization and booking policy (the crate's core).
+- `src/domain/booking_links.rs` + `src/domain/booking_link_models.rs`: event-type
+ and booking-link models.
+- `src/domain/availability.rs`: weekly schedules, date overrides, and conflict
+ resolution across connected calendars.
+- `src/outbound/postgres.rs`: storage (feature `postgres`).
+- `src/outbound/macro_services.rs`, `src/outbound/meeting_links.rs`: calendar/team
+ domain ports and Macro-call meeting links (feature `calendar`).
+
+## Scope
+
+- Owns: booking links, event types, availability computation, and the booking/
+ cancellation/reschedule lifecycle.
+- Not here: the underlying `CalendarEvent` entity, sync, or team sharing →
+ `crates/calendar_events`.
+
+## Boundaries
+
+- Depends on: `calendar_events`, `teams`, `email_validator`; optionally `call`
+ via `calendar_events` (meeting links).
+- Used by: `forms`, `ai_tools`.
+
+## Recipes
+
+- Add a booking policy rule: `src/domain/service.rs` → `src/domain/booking_links.rs`
+ → `src/outbound/postgres.rs` → `src/inbound/router.rs` / `src/inbound/toolset.rs`.
+- Change availability computation: `src/domain/availability.rs` → its callers in
+ `src/domain/service.rs`.
+
+## Checks
+
+- `cargo test -p calendar_scheduling` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Booking range queries are half-open and capped at 733 days and 5,000 records;
+ insights must treat a failed query as an error, never as an empty dataset.
+- Existing bookings keep their original event/schedule snapshot after the
+ booking link is edited or removed — don't resolve bookings through the live
+ link config.
+- Reschedule counts only increase after a successful move; old records default
+ to zero rather than reconstructing unknown history.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/calendar_scheduling/CLAUDE.md b/crates/calendar_scheduling/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/calendar_scheduling/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/calendar_scheduling/README.md b/crates/calendar_scheduling/README.md
index 65bdc139fa..c944474bd7 100644
--- a/crates/calendar_scheduling/README.md
+++ b/crates/calendar_scheduling/README.md
@@ -72,7 +72,7 @@ New approval-only configurations and bookings are disabled until standalone host
notifications exist. Existing pending records remain manageable. Confirmed meetings receive
provider calendar invitations. Shared PostgreSQL budgets cap public availability and booking
requests per profile; all booking changes use a monotonic revision to prevent stale edits.
-See `docs/CALENDAR_SCHEDULING_V1.md` for rollout, rollback and monitoring queries.
+See `docs/design/calendar-scheduling-v1.md` for rollout, rollback and monitoring queries.
It does not deploy the backend or apply migrations to shared databases.
## AI booking-link workflows
diff --git a/crates/call/AGENTS.md b/crates/call/AGENTS.md
new file mode 100644
index 0000000000..2946d4edbc
--- /dev/null
+++ b/crates/call/AGENTS.md
@@ -0,0 +1,57 @@
+# call
+
+## What it is
+
+Part of Calls: Macro's video/audio call management (hexagonal), using
+LiveKit as the RTC backend — call lifecycle, LiveKit rooms, recordings, and
+in-call chat.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/models.rs`: call lifecycle policy.
+- `src/domain/meetings.rs`: scheduled-meeting ↔ call association (used by
+ `calendar_events`/`calendar_scheduling` meeting links).
+- `src/inbound/axum_router.rs`, `src/inbound/stale_call_sweeper.rs`: HTTP routes
+ and the sweeper that ends abandoned calls.
+- `src/outbound/livekit_rtc_client.rs`: LiveKit adapter.
+- `src/outbound/pg_call_repo.rs`, `src/outbound/pg_voice_repo.rs`: Postgres.
+- `src/outbound/ai_call_summarizer.rs`, `src/outbound/s3_recording_storage.rs`:
+ call recording/summarization.
+
+## Scope
+
+- Owns: call creation/ringing/join lifecycle, LiveKit room management, call
+ recordings, and persistent in-call chat.
+- Not here: channel messages and threads outside calls → `crates/channels`;
+ calendar meeting scheduling → `crates/calendar_events`, `crates/calendar_scheduling`.
+
+## Boundaries
+
+- Depends on: `channels` (feature `outbound`), `agent`/`ai_usage` (call summarization),
+ `entity_access_db_utils`, `livekit-api`/`livekit-protocol`.
+- Used by: `memory`, `ai_tools`, `models_soup`, `agent_trigger`, `crm`, `soup`,
+ `calendar_events` (meeting links).
+
+## Recipes
+
+- Add a call event/activity: `src/domain/activity.rs` → `src/domain/events.rs`
+ → `src/outbound/pg_call_repo.rs`.
+- Change ringing/decline behavior: `src/domain/service.rs` → `src/inbound/axum_router.rs`.
+- Add an AI tool over calls: `src/inbound/toolset.rs` (feature `ai_tools`).
+
+## Checks
+
+- `cargo test -p call` (`SQLX_OFFLINE` unset).
+- `just -f crates/call/justfile check` for an all-features compile check.
+
+## Gotchas
+
+- Declining a call on one device must stop ringing on every other device — this
+ regressed once (#7092); route the decline through the shared call state, not
+ a per-device signal.
+- The team-memory helper only compiles with the `ports` feature (#7912) — don't
+ reintroduce an unconditional dependency on it.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/call/CLAUDE.md b/crates/call/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/call/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/channel_bots/AGENTS.md b/crates/channel_bots/AGENTS.md
new file mode 100644
index 0000000000..80e3f8a8c1
--- /dev/null
+++ b/crates/channel_bots/AGENTS.md
@@ -0,0 +1,52 @@
+# channel_bots
+
+## What it is
+
+Part of Chat and Documents: built-in agents for document comments and
+channel messages. Reads committed posts from the common message boundary,
+decides whether to trigger, authorizes, and delivers a reply.
+
+## Start here
+
+- `src/domain/trigger_detector.rs`: decides whether an incoming message should
+ trigger a bot response (mentions, quote-replies, implicit triggers).
+- `src/domain/service.rs` + `src/domain/models.rs`: trigger policy and bot turn model.
+- `src/outbound/fast_model_trigger_classifier.rs`: Haiku-based implicit-trigger
+ classifier used when there's no explicit mention.
+- `src/outbound/agent_loop_responder.rs`: drives the agent loop to produce a reply.
+- `src/outbound/lexical_comment_marks.rs`: comment-mark delivery for document bots.
+- `src/inbound/bot_trigger_router.rs`: wires channel/document message events in.
+
+## Scope
+
+- Owns: deciding when a built-in agent responds to a channel message or document
+ comment, and delivering that response back through the same message boundary.
+- Not here: bot CRUD/ownership → `crates/bots`; the message store itself →
+ `crates/channels`, `crates/messages`.
+
+## Boundaries
+
+- Depends on: `bots`, `channels`, `calendar_events` (time zones), `lexical_client`,
+ `messages`, `prompt`, `ai_tools`/`ai_toolset`, `ai_usage`/`ai_billing`.
+- Used by: `services/document_storage_service`, its composition root.
+
+## Recipes
+
+- Change what triggers a bot reply: `src/domain/trigger_detector.rs` →
+ `src/outbound/fast_model_trigger_classifier.rs` (implicit triggers only).
+- Change how a reply is delivered: `src/outbound/agent_loop_responder.rs` →
+ `src/outbound/conversation.rs` → `src/outbound/lexical_comment_marks.rs`
+ (document comments only).
+
+## Checks
+
+- `cargo test -p channel_bots` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Implicit (non-mention) triggers go through the fast-model classifier, not the
+ main agent model — keep that path cheap; it runs on every message.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/channel_bots/CLAUDE.md b/crates/channel_bots/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/channel_bots/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/channel_labels/AGENTS.md b/crates/channel_labels/AGENTS.md
new file mode 100644
index 0000000000..251586565d
--- /dev/null
+++ b/crates/channel_labels/AGENTS.md
@@ -0,0 +1,46 @@
+# channel_labels
+
+## What it is
+
+Part of Chat: shared or private named groups of chat channels shown in the
+Chat sidebar, following the standard hexagonal crate layout.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/models.rs`: label CRUD, smart-tag
+ matching, and ordering policy — read the module doc comment in `src/lib.rs`
+ first for the sharing/visibility rules.
+- `src/outbound/pg_channel_labels_repo.rs`: Postgres repository.
+- `src/inbound/axum_router.rs`: HTTP routes.
+
+## Scope
+
+- Owns: manual and smart channel labels, their team-wide ordering, and per-member
+ channel visibility within a label.
+- Not here: the channels/messages themselves → `crates/channels`.
+
+## Boundaries
+
+- Depends on: `entity_access` (ports), `macro_authorization` (feature `inbound`), `cowlike`.
+- Used by: `services/document_storage_service`, its composition root.
+
+## Recipes
+
+- Add a label field or smart-tag rule: `src/domain/models.rs` → `src/domain/service.rs`
+ → `src/outbound/pg_channel_labels_repo.rs` → `src/inbound/axum_router.rs`.
+
+## Checks
+
+- `cargo test -p channel_labels` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Every team member sees the same labels in the same order; only per-member
+ channel *visibility inside* a label differs — don't make label ordering
+ per-user.
+- Labels are restricted to team channels (#6801) — don't extend them to
+ non-team channels without revisiting that fix.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/channel_labels/CLAUDE.md b/crates/channel_labels/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/channel_labels/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/channels/AGENTS.md b/crates/channels/AGENTS.md
new file mode 100644
index 0000000000..47965517f2
--- /dev/null
+++ b/crates/channels/AGENTS.md
@@ -0,0 +1,58 @@
+# channels
+
+## What it is
+
+Part of Chat: paginated channel messages — threads, reactions, attachments,
+DMs, and the shared message store other domains discuss things on.
+
+## Start here
+
+- `src/domain/service.rs`, `src/domain/models.rs`: channel/message CRUD and policy.
+- `src/domain/message_delivery.rs`, `src/domain/broker_events.rs`: realtime
+ fan-out of new messages to connection gateway.
+- `src/domain/dm.rs`, `src/domain/teammate_dms.rs`: direct-message channels.
+- `src/domain/reference_sharing.rs`: sharing an external item (PDF, doc, CRM
+ record) into a channel.
+- `src/inbound/attachment.rs`: the `AttachmentService` impl for channel messages.
+- `src/inbound/toolset.rs`: AI tools over channels (feature `ai_tools`).
+- `src/outbound/pg_channels_repo.rs`, `src/outbound/connection_gateway_realtime.rs`:
+ storage and realtime delivery adapters.
+
+## Scope
+
+- Owns: channels, channel messages, threads, reactions, DMs, and message-level
+ attachment/reference sharing.
+- Not here: channel labels → `crates/channel_labels`; calls/video →
+ `crates/call`; built-in agent triggers → `crates/channel_bots`.
+
+## Boundaries
+
+- Depends on: `entity_access`, `macro_authorization`, `attachment` (feature
+ `attachment`), `model-entity`.
+- Used by: widely — `bots`, `call`, `teams`, `webhook`, `soup`/`soup_realtime`,
+ `agent_harness`, `agent_trigger`, `coding_agent_worker`, `comms_db_client`,
+ `graphql_channel`, `search_service`, `name_search`, `ai_tools`, `memory`.
+ Check callers before changing a public service method's signature.
+
+## Recipes
+
+- Add a message field or mutation: `src/domain/models.rs` → `src/domain/service.rs`
+ → `src/outbound/pg_channels_repo.rs` → `src/inbound/axum_router.rs`.
+- Change realtime delivery: `src/domain/message_delivery.rs` →
+ `src/outbound/connection_gateway_realtime.rs`.
+- Add a channel-message AI tool: `src/inbound/toolset.rs` (feature `ai_tools`).
+
+## Checks
+
+- `cargo test -p channels` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- DM invitation emails must stay distinguishable from channel invites (#7964) —
+ don't collapse the two email templates.
+- Legacy document/CRM/channel message paths were removed (#6732); don't
+ reintroduce a parallel message path outside this crate's domain service.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/channels/CLAUDE.md b/crates/channels/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/channels/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/chat/AGENTS.md b/crates/chat/AGENTS.md
new file mode 100644
index 0000000000..52091fab01
--- /dev/null
+++ b/crates/chat/AGENTS.md
@@ -0,0 +1,53 @@
+# chat
+
+## What it is
+
+Part of AI chat: chats and chat messages, persistence, HTTP/toolset
+adapters, and lifecycle events. See `README.md` for the Kafka event schema.
+
+## Start here
+
+- `src/domain.rs`: `ChatService`/`MessageService` — chat and message CRUD,
+ copy, revert-delete, and project bookkeeping.
+- `src/domain/events.rs`: `chat.*`/`chat.message_*` events published to
+ `macro.chats` (schema in `README.md`).
+- `src/inbound/attachment.rs`: the `AttachmentService` impl for chat messages.
+- `src/inbound/toolset.rs`: AI tools over chats (feature `ai_tools`).
+- `src/outbound/postgres.rs`: storage (feature `outbound`).
+- `PLAN.md`: in-progress plan for user-level resolved attachments — check its
+ "What's Broken" section before assuming it's finished.
+
+## Scope
+
+- Owns: the `Chat`/`ChatMessage` tables, chat sharing/ownership, and message
+ send/store/delete.
+- Not here: channel messages → `crates/channels`; model selection and provider
+ calls → `crates/agent`.
+
+## Boundaries
+
+- Depends on: `attachment` (feature `attachment`), `entity_access_db_utils`,
+ `share_permission_db_utils`, `macro_uuid`.
+- Used by: `ai_tools`, `agent_inmem`, `soup_realtime`.
+
+## Recipes
+
+- Add a chat/message field or mutation: `src/domain.rs` → `src/outbound/postgres.rs`
+ → `src/inbound/mod.rs` (router) → emit/update the matching event in
+ `src/domain/events.rs`.
+
+## Checks
+
+- `cargo test -p chat` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Kafka events key on the chat's bare UUID (no `chat|` prefix); `chat.updated`
+ metadata describes the requested PATCH — an omitted field serializes as
+ `null`, and `project_id: ""` means "removed from its project" (see `README.md`).
+- Sharing a chat with a team is gated through `SharePermission.team_share_*` and
+ only the persisted owner may set `teamShareAccessLevel`.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/observability.md`
diff --git a/crates/chat/CLAUDE.md b/crates/chat/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/chat/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/claude_cloud_agents/AGENTS.md b/crates/claude_cloud_agents/AGENTS.md
new file mode 100644
index 0000000000..383cee2e1a
--- /dev/null
+++ b/crates/claude_cloud_agents/AGENTS.md
@@ -0,0 +1,51 @@
+# claude_cloud_agents
+
+## What it is
+
+Part of agent sessions: a demo-only Claude Code cloud provider that runs
+agent sessions against Anthropic's hosted Claude Code using user
+subscription OAuth, via the Agent Client Protocol.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/ports.rs`: provider-independent session
+ behavior and the ports a cloud agent provider must implement.
+- `src/domain/auth.rs` + `src/outbound/oauth.rs`: owner-bound interactive OAuth flow.
+- `src/inbound/acp.rs`: Agent Client Protocol adapter driving sessions.
+- `src/domain/translate.rs`: translating between ACP and the hosted Claude API shape.
+- `src/outbound/credentials.rs` + `src/outbound/postgres.rs`: credential storage.
+- `examples/smoke.rs`: a runnable end-to-end smoke test of the flow.
+
+## Scope
+
+- Owns: the demo Claude Cloud provider — auth, MCP gateway access, and
+ ACP session translation for hosted Claude Code.
+- Not here: other agent providers or the provider-agnostic harness →
+ `crates/agent_harness`.
+
+## Boundaries
+
+- Depends on: `agent-client-protocol`, `agent_runtime_protocol`, `cursor_api_key`,
+ `macro_authorization` (feature `axum`).
+- Used by: `agent_harness`.
+
+## Recipes
+
+- Add a session capability: `src/domain/ports.rs` → `src/domain/service.rs` →
+ `src/inbound/acp.rs` → `src/domain/translate.rs` if the wire shape changes.
+
+## Checks
+
+- `cargo test -p claude_cloud_agents` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Model discovery goes through the models API, not a hardcoded Fable/Claude
+ list (#6595) — don't reintroduce a hardcoded model set.
+- The MCP gateway and hosted browser sign-in need explicit allowances in the
+ cloud environment; don't assume the same network access as local agents
+ (#6550, #6529).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/claude_cloud_agents/CLAUDE.md b/crates/claude_cloud_agents/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/claude_cloud_agents/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/client/cache-core/AGENTS.md b/crates/client/cache-core/AGENTS.md
new file mode 100644
index 0000000000..2a1370648b
--- /dev/null
+++ b/crates/client/cache-core/AGENTS.md
@@ -0,0 +1,65 @@
+# cache-core
+
+## What it is
+
+Part of the web client's shared infrastructure: the normalized GraphQL
+cache engine — pure, native-tested core shared by every storage backend and
+host (web, Tauri). Design doc:
+`apps/web/docs/graphql-normalized-cache-plan.md`.
+
+## How it works
+
+GraphQL responses are normalized into keyed records (`normalize.rs`);
+watched queries and the optimistic mutation queue read/write those records
+through the predicate/projection IR; results are denormalized back into
+GraphQL response shape for callers. A concrete `Storage` impl (e.g.
+`cache-turso`) persists the records.
+
+## Start here
+
+- `src/engine.rs`: the `CacheEngine` — the crate's entry point, owns queued
+ mutations, watched queries, and optimistic resolution.
+- `src/normalize.rs` / `src/denormalize.rs`: GraphQL response ↔ normalized record
+ transforms.
+- `src/store.rs`: the `Storage` trait every backend (e.g. `cache-turso`) implements.
+- `src/predicate.rs` + `src/record_selection.rs`: the predicate/projection IR
+ used to select which cached records satisfy a query.
+- `src/queue.rs`: the optimistic mutation queue.
+- `tests/`: the primary spec for engine behavior — one file per concern
+ (optimistic updates, calendar range, search, subscriptions, fuzz).
+
+## Scope
+
+- Owns: normalization, denormalization, optimistic mutation resolution, watched
+ queries, and the storage-agnostic predicate/projection IR.
+- Not here: a concrete storage backend → `crates/client/cache-turso`; the wasm
+ host shell → `crates/client/cache-wasm`; Soup-specific projection policy →
+ `soup_filter_cache_adapter`, `soup_filter_projection`.
+
+## Boundaries
+
+- Depends on: `apollo-compiler`/`apollo-parser` (GraphQL parsing), `predicate-index`,
+ `maybe_send`.
+- Used by: `cache-turso`, `cache-wasm`.
+
+## Recipes
+
+- Add a new mutation's optimistic resolver: `src/engine.rs` (resolver registration)
+ → a new `tests/<name>_optimistic.rs` first (see the existing `*_optimistic.rs` tests).
+- Change what a query can select: `src/predicate.rs` → `src/record_selection.rs`
+ → `src/query_inspection.rs`.
+
+## Checks
+
+- `cargo test -p cache-core` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Opaque JSON scalars must preserve floating-point values on reparse — `serde_json`
+ is pulled in with the `float_roundtrip` feature; don't drop it.
+- Patches structural query changes in place instead of resending full results
+ (#7825); a new query shape change needs a patch path, not just a resend.
+
+## Related
+
+- Docs: `apps/web/docs/graphql-normalized-cache-plan.md`
diff --git a/crates/client/cache-core/CLAUDE.md b/crates/client/cache-core/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/client/cache-core/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/client/cache-turso/AGENTS.md b/crates/client/cache-turso/AGENTS.md
new file mode 100644
index 0000000000..a7f4a0b398
--- /dev/null
+++ b/crates/client/cache-turso/AGENTS.md
@@ -0,0 +1,50 @@
+# cache-turso
+
+## What it is
+
+Part of the web client's shared infrastructure: the production Turso
+(SQLite-compatible, embedded) storage adapter for `cache-core`'s normalized
+GraphQL cache — native for tests/Tauri, OPFS-backed on wasm32.
+
+## Start here
+
+- `src/storage.rs`: `TursoStorage` — implements `cache_core::store::Storage`
+ with the frozen compound-key schema and strict-head mutation leasing.
+- `src/driver.rs`: Turso connection/transaction handling.
+- `src/key.rs`: the compound key schema (frozen — see Gotchas).
+- `src/error.rs`: `TursoStorageError` / `PhysicalResetReason`.
+- `tests/storage_conformance.rs`, `tests/shared_conformance.rs`: the shared
+ conformance suite every storage backend must pass.
+
+## Scope
+
+- Owns: translating `cache-core`'s `Storage` trait onto a real Turso database,
+ on both native (tests) and wasm32 (browser, via `turso-opfs`).
+- Not here: the cache engine logic itself → `crates/client/cache-core`; the
+ wasm-bindgen host shell → `crates/client/cache-wasm`.
+
+## Boundaries
+
+- Depends on: `cache-core`, `turso_core`, `turso-opfs` (wasm32 target only).
+- Used by: `cache-wasm`.
+
+## Recipes
+
+- Add a storage operation: implement it in `src/storage.rs` → add a case to
+ `tests/storage_conformance.rs` (native) and the `tests/web.rs` wasm suite.
+
+## Checks
+
+- `cargo test -p cache-turso` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `#![forbid(unsafe_code)]` and `#![deny(missing_docs)]` — this crate is held to
+ a stricter bar than most because it's the single physical-disk commit point.
+- The compound-key schema and payload encoding are frozen; an incompatible or
+ uncertain on-disk state is classified for physical reset, never silently
+ migrated, copied, or redirected to a fallback backend.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/client/cache-turso/CLAUDE.md b/crates/client/cache-turso/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/client/cache-turso/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/client/cache-wasm/AGENTS.md b/crates/client/cache-wasm/AGENTS.md
new file mode 100644
index 0000000000..474ff05179
--- /dev/null
+++ b/crates/client/cache-wasm/AGENTS.md
@@ -0,0 +1,56 @@
+# cache-wasm
+
+## What it is
+
+Part of the web client's shared infrastructure: the browser-only
+wasm-bindgen shell exposing `cache-core` + `cache-turso` + `turso-opfs` as a
+`CacheEngine` JS class to the web worker glue in
+`apps/web/src/lib/graphql-cache/`.
+
+## Start here
+
+- `src/shell.rs`: the `CacheEngine` wasm-bindgen class — translates JS calls
+ into `cache-core` engine calls behind an async mutex.
+- `src/query_telemetry.rs`: slow-query callback exposed to JS.
+- `apps/web/src/lib/graphql-cache/`: the JS/TS worker that owns this engine.
+
+## Scope
+
+- Owns: the wasm boundary — operation-id interning (`"{clientId}:{urqlKey}"` →
+ internal `u64`), Promise-based method signatures, and composing `soup-filter-cache-adapter`
+ at the browser composition edge.
+- Not here: cache engine logic → `crates/client/cache-core`; Soup-specific
+ projection policy → `soup_filter_cache_adapter`, `soup_filter_projection`
+ (composed here, not reimplemented); OPFS storage → `crates/client/cache-turso`,
+ `crates/client/turso-opfs`.
+
+## Boundaries
+
+- Depends on: `cache-core` (all targets), `cache-turso`/`turso-opfs`/
+ `soup-filter-cache-adapter` (wasm32 target only).
+- Used by: `apps/web` only, through the generated wasm-bindgen glue — no other
+ Rust crate depends on this one.
+
+## Recipes
+
+- Expose a new engine capability to JS: implement it in `cache-core` first →
+ add the wasm-bindgen method in `src/shell.rs` → update the TS caller in
+ `apps/web/src/lib/graphql-cache/`.
+
+## Checks
+
+- Off-wasm: `cargo test -p cache-wasm` compiles the empty non-wasm shell only.
+- Real coverage is wasm32: `cargo test --target wasm32-unknown-unknown -p cache-wasm`
+ (see `crates/client/turso-opfs/README.md` for the `wasm-bindgen-test` pattern
+ this crate also follows).
+
+## Gotchas
+
+- The engine is guarded by an async mutex so overlapping JS calls serialize
+ instead of causing reentrancy — don't bypass it with a second entry point.
+- Compiles to an empty shell off-wasm specifically so plain `cargo test` across
+ the workspace stays green; don't make the non-wasm cfg path do real work.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/client/cache-wasm/CLAUDE.md b/crates/client/cache-wasm/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/client/cache-wasm/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/client/turso-opfs/AGENTS.md b/crates/client/turso-opfs/AGENTS.md
new file mode 100644
index 0000000000..feb8a5a045
--- /dev/null
+++ b/crates/client/turso-opfs/AGENTS.md
@@ -0,0 +1,59 @@
+# turso-opfs
+
+## What it is
+
+Part of the web client's shared infrastructure: a browser-only Turso
+`Clock`/`IO`/`File` adapter over a DedicatedWorker's Origin Private File
+System, backing `cache-turso`'s storage for the normalized GraphQL cache.
+Production code is wasm32-only; the lifecycle state machine also compiles
+natively for its unit tests. See `README.md` for the full ownership/recovery
+contract and the multi-target verification commands.
+
+## Start here
+
+- `README.md`: the ownership/recovery boundary — read before touching
+ `OpfsOwner`, `OpfsSession`, or close/reset paths.
+- `src/browser.rs` (wasm32 only): `OpfsOwner`, `OpfsSession`, `ConnectedOpfsSession`,
+ close/reset state types.
+- `src/state.rs`, `src/write_batch.rs`: target-independent lifecycle machine,
+ compiled natively for unit tests.
+
+## Scope
+
+- Owns: the exclusive Web Lock + main/WAL file pair for one canonical database
+ identity, and the typed open/connect/close/reset state machine around it.
+- Not here: the Turso storage adapter that uses this → `crates/client/cache-turso`;
+ cross-worker termination/restart orchestration (a coordinator responsibility,
+ not tested here — see README "Repeatable verification").
+
+## Boundaries
+
+- Depends on: `turso_core` (feature `fs`, `uuid`), `wasm-bindgen`/`web-sys` (wasm32 only).
+- Used by: `cache-turso`, `cache-wasm` (wasm32 target only).
+
+## Recipes
+
+- Change the open/close state machine: `src/state.rs` (native-testable) →
+ `src/browser.rs` (wasm wiring) → the `#[wasm_bindgen_test]` suite (README
+ "Repeatable verification").
+
+## Checks
+
+- `cargo test -p turso-opfs` (native lifecycle tests; `SQLX_OFFLINE` unset).
+- `cargo check --target wasm32-unknown-unknown -p turso-opfs --all-targets`
+ and the `#[wasm_bindgen_test]` suite — see `README.md` for the full command list.
+
+## Gotchas
+
+- `#![forbid(unsafe_code)]` and `#![deny(missing_docs)]`.
+- Never call `Connection::close` directly — `ConnectedOpfsSession::try_close()`
+ exclusively owns and proves that transition.
+- `OpfsOwner::acquire` derives both the lock name and main/WAL paths from one
+ canonical identity; there's no independent path input that could alias the
+ same files to a different lock.
+- Local tests prove physical lock contention but not real cross-worker
+ termination — don't read passing tests here as proof of that.
+
+## Related
+
+- Docs: `README.md`
diff --git a/crates/client/turso-opfs/CLAUDE.md b/crates/client/turso-opfs/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/client/turso-opfs/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/codex_cloud_agents/AGENTS.md b/crates/codex_cloud_agents/AGENTS.md
new file mode 100644
index 0000000000..c5c9556fe3
--- /dev/null
+++ b/crates/codex_cloud_agents/AGENTS.md
@@ -0,0 +1,58 @@
+# codex_cloud_agents
+
+## What it is
+
+Part of agent sessions: Codex cloud transport and ACP conversations —
+OAuth/credentials, the OpenAI cloud-task HTTP client, and the ACP adapter
+used by both the `codex-acp` binary and `codex_connection`'s hosted
+sessions.
+
+## Start here
+
+- `src/domain.rs` + `src/domain/cloud.rs`, `src/domain/journal.rs`: provider-
+ independent vocabulary (`Launch`, `TurnId`, `CloudId`) and the journal port.
+- `src/domain/acp_session.rs`: the ACP session service tying a prompt to a
+ cloud turn.
+- `src/outbound/openai.rs` + `src/outbound/openai/tasks.rs`: the OpenAI cloud-
+ task HTTP client and its streaming adapter.
+- `src/inbound/acp.rs`: ACP protocol adapter (citations, session updates).
+- `src/main.rs` / `src/bin/codex_acp.rs`: two composition roots — a direct-
+ OAuth probe CLI and the stdio ACP binary for Zed.
+
+## Scope
+
+- Owns: Codex cloud OAuth/credentials for the standalone probe, the OpenAI
+ cloud-task client, ACP translation, and (behind the `postgres` feature) a
+ Postgres-backed session journal.
+- Not here: owner-bound connection storage and KMS encryption for hosted
+ sessions → `crates/codex_connection`.
+
+## Boundaries
+
+- Depends on: `agent_runtime_protocol`, `agent-client-protocol`.
+- Used by: `codex_connection`, `agent_harness`, `authentication_service`,
+ `agent_harness_service`.
+
+## Recipes
+
+- Add an OpenAI cloud-task endpoint: `src/outbound/openai/tasks.rs` →
+ `src/outbound/openai/tasks/stream.rs` (if streamed) → `src/domain/cloud.rs`
+ (if it changes the domain vocabulary).
+- Change ACP translation (citations, message shaping): `src/inbound/acp.rs` →
+ `src/inbound/acp/citations.rs` → its `test.rs`/snapshots.
+
+## Checks
+
+- `cargo test -p codex_cloud_agents` (`SQLX_OFFLINE` unset).
+- With Postgres journal: `cargo test -p codex_cloud_agents --features postgres`.
+
+## Gotchas
+
+- `#![deny(missing_docs)]`: every public item needs a doc comment.
+- `postgres_journal` only compiles under the `postgres` feature, which pulls
+ in `agent_session` and `sqlx` — don't add a plain `sqlx` dependency outside
+ that feature gate.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/codex_cloud_agents/CLAUDE.md b/crates/codex_cloud_agents/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/codex_cloud_agents/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/codex_connection/AGENTS.md b/crates/codex_connection/AGENTS.md
new file mode 100644
index 0000000000..743ab245c8
--- /dev/null
+++ b/crates/codex_connection/AGENTS.md
@@ -0,0 +1,50 @@
+# codex_connection
+
+## What it is
+
+Part of agent sessions: owner-bound Codex OAuth connections — durable
+device login and encrypted credential storage/rotation for hosted Codex
+sessions.
+
+## Start here
+
+- `src/domain.rs` + `src/domain/service.rs`: connection lifecycle policy
+ (`ConnectionError`, `ConnectionServiceImpl`) independent of HTTP/Postgres/KMS.
+- `src/outbound/postgres.rs`: owner transaction locking and encrypted state
+ persistence.
+- `src/outbound/cipher.rs`: AWS KMS envelope encryption for OAuth payloads.
+
+## Scope
+
+- Owns: per-owner Codex connection state, login-attempt tracking, and the
+ encrypted-at-rest persistence of that state.
+- Not here: the OpenAI cloud-task client and ACP session itself →
+ `crates/codex_cloud_agents` (this crate depends on it for `CloudId`,
+ `Credentials`, `Environment`, `Secret`).
+
+## Boundaries
+
+- Depends on: `codex_cloud_agents` (domain types), `macro_user_id`.
+- Used by: `agent_harness`, `authentication_service`, `agent_harness_service`.
+
+## Recipes
+
+- Add a connection-lifecycle rule (e.g. a new error case or transition):
+ `src/domain.rs` → `src/domain/service.rs` → its `test.rs`.
+- Change persisted connection state: `src/outbound/postgres.rs` →
+ `src/outbound/postgres/test.rs` (uses `macro_db_migrator` as a dev-dependency).
+
+## Checks
+
+- `cargo test -p codex_connection` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `ConnectionError` variants intentionally never carry credentials or
+ provider response bodies — don't add an error case that does.
+- `#![deny(missing_docs)]` applies to every public item.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`,
+ `.agents/rules/rust/security.md`
diff --git a/crates/codex_connection/CLAUDE.md b/crates/codex_connection/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/codex_connection/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/coding_agent_worker/AGENTS.md b/crates/coding_agent_worker/AGENTS.md
new file mode 100644
index 0000000000..c0a8c4b7b9
--- /dev/null
+++ b/crates/coding_agent_worker/AGENTS.md
@@ -0,0 +1,62 @@
+# coding_agent_worker
+
+## What it is
+
+Part of agent sessions: `macrod`, the agent harness daemon operators run on
+their own machine — serves a registered harness's agent sessions, bridges
+the local ACP process (Claude Code, Codex, ...), and drives native
+[herdr](https://herdr.dev) sessions, all inside one terminal control panel.
+
+## Start here
+
+- `src/main.rs`: module list and the composition root's CLI entrypoint.
+- `src/config.rs`: `macrod.toml` — the daemon's one input (see
+ `config.example.toml`, `default.macrod.toml`).
+- `src/daemon.rs` + `src/runtime.rs`: the serving core — persistent harness
+ service connection, ACP process bridge, start/stop/restart on re-pair.
+- `src/trigger.rs` + `src/dispatch.rs`: agent-trigger broker events → session
+ create/dial/prompt against the live harness service.
+- `src/tui.rs` (`src/tui/`): the control panel itself (registration, agents,
+ sessions, config form, logs).
+- `src/herdr.rs` (`src/herdr/`): native herdr pane integration — only compiled
+ `#[cfg(unix)]`.
+- `README.md`: native Herdr session behavior (repositories, reconnect, model
+ switching, MCP) — read before changing anything under `src/herdr/`.
+
+## Scope
+
+- Owns: the `macrod` binary end to end — config, pairing, the harness bridge,
+ trigger dispatch, native herdr session control, and the TUI.
+- Not here: the trigger event vocabulary (`agent_trigger`), the fold/transcript
+ logic for a given provider (`claude_fold`, `codex_fold`), or the harness
+ service itself (`services/agent_harness_service`).
+
+## Recipes
+
+- Add a config field: `src/config.rs` → `config.example.toml` →
+ `default.macrod.toml` → the TUI config form (`src/tui/config_form/`).
+- Handle a new trigger kind: `src/trigger.rs` → `src/dispatch.rs` → its tests.
+- Add/change a native herdr control (command, model picker): `src/herdr/controls/`
+ → `README.md` (native controls section) → `src/herdr/acp_agent/`.
+
+## Checks
+
+- `cargo test -p coding_agent_worker` (`SQLX_OFFLINE` unset).
+- `just run` (from this directory) to run the daemon against `macrod.toml` at
+ the repo root.
+- `just build-static` to build and smoke-test the release `macrod` the way
+ the tag workflow does (needs the Nix devshell: cargo-zigbuild, zig, cmake).
+
+## Gotchas
+
+- `src/herdr.rs` and its submodule are Unix-only (`#[cfg(unix)]`); don't add
+ Windows-breaking code there without a cfg gate.
+- macrod never pulls into the operator's working branch — new herdr worktrees
+ start from a fresh fetch of `origin/main` (see README.md).
+- Switching native agents clears the previous agent's model/extra-args but
+ keeps storage and focus preferences (README.md, "Setup").
+
+## Related
+
+- `README.md` in this directory is the native herdr behavior contract —
+ update it alongside `src/herdr/` changes.
diff --git a/crates/coding_agent_worker/CLAUDE.md b/crates/coding_agent_worker/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/coding_agent_worker/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/collab_surface/AGENTS.md b/crates/collab_surface/AGENTS.md
new file mode 100644
index 0000000000..42085dc318
--- /dev/null
+++ b/crates/collab_surface/AGENTS.md
@@ -0,0 +1,66 @@
+# collab_surface
+
+## What it is
+
+Part of Documents (and other features that embed collaborative markdown):
+stable ids for arbitrary collaborative markdown surfaces, each backed by
+its own Loro CRDT session in sync-service, independent of the `Document`
+table.
+
+## Start here
+
+- `src/lib.rs`: module doc — the hexagonal layout and why a surface has no
+ owner (authorization derives from the parent entity).
+- `src/domain/ports.rs`: `CollabSurfaceRepo` (outbound) and the service traits
+ consumers depend on.
+- `src/domain/models.rs`: `SurfaceOwnership`/parent policy — read before adding
+ a new parent type.
+- `src/domain/service.rs`: `CollabSurfaceService` / `OwnedSurfaceService` logic
+ (ensure, retire, connection tokens).
+
+## Scope
+
+- Owns: the `collab_surfaces` table (id, parent, lifecycle state, soft
+ deletion), surface ensure/retire, and minting sync-service connection tokens.
+- Not here: markdown content itself (sync-service/Loro is the source of
+ truth), and parent-entity authorization (the owning feature decides access,
+ this crate only derives tokens from it).
+
+## Boundaries
+
+- Depends on (by feature): `entity_access` (ports), `macro_authorization`
+ (inbound), `lexical_client` + `sync_service_client` (outbound init),
+ `macro_db_client` (postgres).
+- Used by: `forms`, `ai_tools`, `initiative_description`,
+ `document_storage_service` — each wires its own domain port over
+ `OwnedSurfaceService` or calls `CollabSurfaceService` directly for
+ public-API-managed surfaces.
+
+## Recipes
+
+- Add a new parent type: `src/domain/models.rs` (`SurfaceOwnership`/parent
+ policy) → `src/domain/service.rs` → the consuming feature's domain port (see
+ `crates/initiative_description/src/lib.rs` for the pattern).
+- Wire a new feature onto an existing surface kind: the feature's domain port
+ → `OwnedSurfaceService` methods (`ensure_owned_surface`,
+ `owned_surface_markdown`, `retire_surface`) → its cleanup path for
+ retirement.
+
+## Checks
+
+- `cargo test -p collab_surface` (`SQLX_OFFLINE` unset; exercises
+ `src/outbound/pg_collab_surface_repo/test.rs` against MacroDB).
+
+## Gotchas
+
+- Surface ids are application-generated UUIDv7 and name the sync-service
+ session; never recycle one, even after retirement.
+- Retirement blocks new connection tokens but does not reclaim the
+ sync-service session — it's a one-way lifecycle step.
+- The parent reference is polymorphic with no FK cascade; wiring retirement
+ into the parent feature's own cleanup is the caller's responsibility.
+
+## Related
+
+- Skill: `.agents/skills/collab-surface-core/SKILL.md` · Rules:
+ `.agents/rules/rust/architecture.md`, `.agents/rules/rust/security.md`
diff --git a/crates/collab_surface/CLAUDE.md b/crates/collab_surface/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/collab_surface/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/comms_db_client/AGENTS.md b/crates/comms_db_client/AGENTS.md
new file mode 100644
index 0000000000..355648cfa3
--- /dev/null
+++ b/crates/comms_db_client/AGENTS.md
@@ -0,0 +1,53 @@
+# comms_db_client
+
+## What it is
+
+Part of Chat's shared infrastructure: the query layer for channel messages,
+participants, mentions, activity, and attachment references — the shared
+tables behind channel/document conversations.
+
+## Start here
+
+- `src/lib.rs`: module list — one module per table area (`messages`,
+ `channels`, `participants`, `entity_mentions`, `activity`, `attachments`).
+- `src/model.rs`: the shared row types (`Message`, etc.) returned by queries.
+- `src/messages/create_message.rs`: a representative `sqlx::query!` call site.
+
+## Scope
+
+- Owns: `sqlx::query!` call sites over `comms_messages` and related tables.
+- Not here: the table schema itself, or any other MacroDB table → both live in
+ `crates/macro_db_client/migrations`; comms_db_client only queries them.
+- Not here: comms domain logic, authorization, or HTTP — those live in the
+ callers listed below, not a dedicated comms service.
+
+## Boundaries
+
+- Depends on: `channels` (message event types), `model` (shared models).
+- Used by: `documents`, `search_service`, and services that read/write
+ channel messages (`document_storage_service`, `authentication_service`,
+ `search_processing_service`), plus `tooling/seed_cli`.
+
+## Recipes
+
+- Add a query against an existing table: the matching `src/<area>/<verb>.rs`
+ file → its sibling `test.rs` → `nix develop --command just prepare_db` from
+ the repository root if `.sqlx` cache metadata is missing.
+- Add a new table area: new `src/<area>.rs` module → `pub mod <area>;` in
+ `src/lib.rs` → add the corresponding migration in
+ `crates/macro_db_client/migrations` first (schema lives there, not here).
+
+## Checks
+
+- `cargo test -p comms_db_client` (`SQLX_OFFLINE` unset; requires local
+ MacroDB — `just run_dbs -d` then `sqlx database setup`, per `README.md`).
+
+## Gotchas
+
+- This crate has no `migrations/` of its own — `comms_messages` and related
+ tables are defined in `crates/macro_db_client/migrations`; keep query
+ columns in sync with that schema, not the other way around.
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md` · Docs: `docs/development/database.md`
diff --git a/crates/comms_db_client/CLAUDE.md b/crates/comms_db_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/comms_db_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/complete_graph/AGENTS.md b/crates/complete_graph/AGENTS.md
index 04665619bd..4c43d84fab 100644
--- a/crates/complete_graph/AGENTS.md
+++ b/crates/complete_graph/AGENTS.md
@@ -1,14 +1,16 @@
# complete_graph — schema conventions
-This crate composes the domain GraphQL adapter crates (`graphql_soup`,
-`graphql_properties`, `graphql_notification`, `graphql_email`,
-`graphql_entity_mutation`, with shared plumbing in `graphql_common`) into the
-complete GraphQL schema consumed by the client's
-**normalized cache** (`crates/client`, design doc:
+## What it is
+
+Part of the web client's shared infrastructure: this crate composes the
+domain GraphQL adapter crates (`graphql_soup`, `graphql_properties`,
+`graphql_notification`, `graphql_email`, `graphql_entity_mutation`, with
+shared plumbing in `graphql_common`) into the complete GraphQL schema
+consumed by the client's **normalized cache** (`crates/client`, design doc:
`apps/web/docs/graphql-normalized-cache-plan.md`). The conventions below are
-load-bearing for cache correctness and API consistency. The
-cache's build validates *shapes* but cannot validate *semantics* — that's
-what schema review is for.
+load-bearing for cache correctness and API consistency. The cache's build
+validates *shapes* but cannot validate *semantics* — that's what schema
+review is for.
## 1. `id` is a reserved, semantic field name (presence-of-id convention)
@@ -101,6 +103,6 @@ cargo run -p complete_graph --bin graphql_schema -- static_assets/schema.graphql
```
The exported `static_assets/schema.graphql` feeds both the client codegen
-(`apps/web && bun gen-graphql`) and the cache metadata codegen (hashing it —
-any change rotates all persisted client caches, which rebuild from the
-network automatically).
+(`apps/web && bun gen-graphql`) and the cache metadata codegen. Additive changes
+keep persisted client caches; a change that makes stored records unsafe needs a
+bump of `CACHE_SCHEMA_COMPATIBILITY_EPOCH` in `crates/client/cache-core/src/codec.rs`.
diff --git a/crates/complete_graph/CLAUDE.md b/crates/complete_graph/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/complete_graph/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/connection/AGENTS.md b/crates/connection/AGENTS.md
new file mode 100644
index 0000000000..5cc88dc66c
--- /dev/null
+++ b/crates/connection/AGENTS.md
@@ -0,0 +1,46 @@
+# connection
+
+## What it is
+
+Part of shared infrastructure: a domain port over the connection gateway,
+sending realtime invalidation events and arbitrary channel messages to
+users, independent of the HTTP client.
+
+## Start here
+
+- `src/lib.rs`: hexagonal layout — domain + outbound only, no inbound.
+- `src/domain/ports.rs`: `ConnectionGateway` (outbound trait) and
+ `ConnectionService` (the port callers depend on).
+- `src/domain/service.rs`: the service implementation adapting a
+ `ConnectionGateway` to `ConnectionService`.
+- `src/outbound/connection_gateway_client.rs`: the `ConnectionGateway` adapter
+ over `connection_gateway_client`.
+
+## Scope
+
+- Owns: the `ConnectionService` port (invalidation events, channel messages)
+ and its adapter onto `connection_gateway_client`.
+- Not here: the HTTP transport and request shapes to the gateway →
+ `crates/connection_gateway_client`.
+
+## Boundaries
+
+- Depends on: `entity_access` (ports), `connection_gateway_client` +
+ `model-entity` (outbound feature).
+- Used by: `call`, `documents`, `ai_tools`, `document_storage_service` — a
+ composition root constructs the outbound adapter; domain crates depend on
+ `ConnectionService`/`ConnectionGateway`, never the client directly.
+
+## Recipes
+
+- Add a new message kind: `src/domain/models.rs` (event/message type) →
+ `src/domain/ports.rs` → `src/domain/service.rs` →
+ `src/outbound/connection_gateway_client.rs`.
+
+## Checks
+
+- `cargo test -p connection` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/connection/CLAUDE.md b/crates/connection/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/connection/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/connection_gateway_client/AGENTS.md b/crates/connection_gateway_client/AGENTS.md
new file mode 100644
index 0000000000..b4659d38b9
--- /dev/null
+++ b/crates/connection_gateway_client/AGENTS.md
@@ -0,0 +1,49 @@
+# connection_gateway_client
+
+## What it is
+
+Part of shared infrastructure: the HTTP client for
+`services/connection_gateway`, pushing best-effort realtime messages
+(invalidation events, channel messages, feature-specific refreshes) to
+connected users.
+
+## Start here
+
+- `src/client.rs`: `ConnectionGatewayClient`, `REQUEST_TIMEOUT` (15s — read its
+ doc comment before changing; delivery is best-effort, callers don't wait
+ indefinitely), and the generic `send_message`/batch methods.
+- `src/client/calendar.rs`, `src/client/email.rs`: thin per-feature wrappers
+ over the generic send methods (e.g. `refresh_calendar`, `refresh_email`).
+- `connection_gateway_models` (sibling crate): the wire types
+ (`SendMessageBody`, `BatchSendMessageBody`, `MessageReceipt`, ...).
+
+## Scope
+
+- Owns: the reqwest-based client to the connection gateway and its
+ feature-specific convenience methods.
+- Not here: the gateway service itself → `services/connection_gateway`; a
+ domain port wrapping this client → `crates/connection`.
+
+## Boundaries
+
+- Depends on: `connection_gateway_models`, `model-entity`,
+ `macro_tower_layers` (trace header injection).
+- Used by: most services and several domain crates (`connection`, `channels`,
+ `messages`, `forms`, `databases`, `ai_tools`, `slack_integration`, ...) —
+ widely shared; check callers before changing a method signature.
+
+## Recipes
+
+- Add a feature-specific refresh/notification: a new file under
+ `src/client/<feature>.rs` with an `impl ConnectionGatewayClient` block
+ calling `self.send_message(...)`, declared in `src/client.rs`'s `mod` list.
+- Add a new generic send shape: `connection_gateway_models` (wire type) →
+ `src/client.rs`.
+
+## Checks
+
+- `cargo test -p connection_gateway_client` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/observability.md`
diff --git a/crates/connection_gateway_client/CLAUDE.md b/crates/connection_gateway_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/connection_gateway_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/contacts/AGENTS.md b/crates/contacts/AGENTS.md
new file mode 100644
index 0000000000..0651776e38
--- /dev/null
+++ b/crates/contacts/AGENTS.md
@@ -0,0 +1,49 @@
+# contacts
+
+## What it is
+
+Part of Contacts: a hexagonal service tracking who each user knows, built
+from message/call activity and explicit relationships, exposed over HTTP
+and kept in sync via the connection gateway.
+
+## Start here
+
+- `src/domain/service.rs`: the contacts use cases (`domain::service`).
+- `src/domain/ports.rs`: the traits `inbound`/`outbound` implement.
+- `src/inbound/http.rs`: HTTP handlers, router, DTOs, swagger.
+- `src/inbound/worker.rs`: SQS worker that ingests contact-affecting events.
+- `src/outbound/repository.rs`: Postgres adapter; `src/outbound/gateway.rs`
+ notifies the connection gateway of graph changes.
+
+## Scope
+
+- Owns: the contact graph (who a user has an explicit or inferred
+ relationship with) and its HTTP/queue surface.
+- Not here: CRM companies/contacts (external organizations) → `crates/crm`;
+ connection-level presence/relay → `crates/connection_gateway_client`.
+
+## Boundaries
+
+- Depends on: `macro_authorization` (axum feature), `rate_limit`, `sqs_worker`,
+ `macro_user_id`.
+- Used by: `contacts_service` (composition root), `teams` (backfill on team
+ join), `channels`, `ai_tools`, `databases_sql`; also linked into
+ `document_storage_service`, `authentication_service`, `email_service`,
+ `agent_harness_service`.
+
+## Recipes
+
+- Add an HTTP endpoint: `src/domain/ports.rs` (port method) →
+ `src/domain/service.rs` → `src/inbound/http.rs` (handler + router + swagger).
+- Change what triggers a contact update: `src/inbound/worker.rs` (SQS message
+ parsing) → `src/domain/service.rs`.
+- Add a repository query: `src/outbound/repository.rs` → its `test.rs`.
+
+## Checks
+
+- `cargo test -p contacts` (`SQLX_OFFLINE` unset; the `outbound`/`default`
+ features need a local MacroDB — see `.agents/rules/rust/guardrails.md`).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/security.md`
diff --git a/crates/contacts/CLAUDE.md b/crates/contacts/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/contacts/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/crm/AGENTS.md b/crates/crm/AGENTS.md
new file mode 100644
index 0000000000..8b4dc78b80
--- /dev/null
+++ b/crates/crm/AGENTS.md
@@ -0,0 +1,63 @@
+# crm
+
+## What it is
+
+Part of CRM (Sales): a hexagonal crate for companies, contacts, and
+pipelines (including the legacy-CRM → Sales migration), plus the AI
+tools/HTTP/GraphQL surfaces over them.
+
+## Start here
+
+- `src/domain/service.rs`, `src/domain/pipelines.rs`: core use cases.
+- `src/domain/pipeline_workflows/`: pipeline entry/field/record ops built on
+ the shared `databases` engine (Sales pipelines are a `databases` consumer).
+- `src/inbound/axum_router.rs` (+ `axum_router/*.rs`): HTTP handlers.
+- `src/inbound/toolset.rs` (+ `toolset/*.rs`): AI tool definitions.
+- `src/outbound/companies_repo.rs`: the Postgres adapter for companies/contacts.
+- `SALES_BACKFILL.md`: how the legacy-CRM-to-Sales migration behaves.
+
+## Scope
+
+- Owns: CRM company/contact records, pipelines, and their HTTP/AI-tool/search
+ surfaces for a team.
+- Not here: the contact *graph* (who a user knows) → `crates/contacts`;
+ shared database storage/positions → `crates/databases`.
+
+## Boundaries
+
+- Cargo features gate what's pulled in: `lookup` and `search` are read-only,
+ sqlx-only slices for other domains to depend on without pulling in
+ `reqwest`/`axum`; pick the narrowest feature for a new caller.
+- Depends on: `entity_access` (ports-and-adapters base), `databases` (ports),
+ `filter_ast`, `item_filters`, `macro_authorization`, `properties`.
+- Used by: `email`, `memory`, `ai_tools`, `soup`/`models_soup`, `graphql_crm`,
+ `search_service`, `complete_graph`; composition roots include
+ `document_storage_service`, `agent_harness_service`, `mcp_service`,
+ `email_service`, `agent_trigger_service`, `scheduled_action`.
+
+## Recipes
+
+- Add an HTTP route: `src/domain/service.rs` (or a domain submodule) →
+ `src/inbound/axum_router/<name>.rs` → `src/inbound/axum_router.rs` (mount it).
+- Add an AI tool: `src/inbound/toolset/<name>.rs` → `src/inbound/toolset.rs`
+ (register it) → its `test.rs`.
+- Change pipeline behavior: `src/domain/pipelines.rs` or
+ `src/domain/pipeline_workflows/*.rs` → `src/outbound/pipelines.rs` →
+ matching test under `src/domain/pipeline_workflows/*/test.rs`.
+
+## Checks
+
+- `cargo test -p crm` (`SQLX_OFFLINE` unset; needs a local MacroDB — see
+ `.agents/rules/rust/guardrails.md`). After query/migration changes, run
+ `nix develop --command just prepare_db` from the repository root.
+
+## Gotchas
+
+- The Sales migration (`SALES_BACKFILL.md`) is forward-only and additive —
+ its down migration refuses to erase completion or user edits; never revert
+ it to undo a bad migration, only the application code that reads it.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md` ·
+ Skill: `database-core`
diff --git a/crates/crm/CLAUDE.md b/crates/crm/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/crm/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/cursor_api_key/AGENTS.md b/crates/cursor_api_key/AGENTS.md
new file mode 100644
index 0000000000..b6d7ec45c8
--- /dev/null
+++ b/crates/cursor_api_key/AGENTS.md
@@ -0,0 +1,36 @@
+# cursor_api_key
+
+## What it is
+
+Part of agent sessions: a user's Cursor API key — KMS encryption (`cipher`)
+and row storage (`store`) for the per-user secret `@cursor` sessions run
+on. See the crate-level doc comment in `src/lib.rs` for the full threat
+model.
+
+## Boundaries
+
+- Depends on: AWS KMS (via `aws-sdk-kms`).
+- Used by: `claude_cloud_agents`, `agent_harness`, `authentication_service`,
+ `agent_harness_service`.
+
+## Recipes
+
+- Change how a key is encrypted/decrypted: `src/cipher.rs` → its `test.rs`.
+- Change how the ciphertext row is read or written: `src/store.rs` → its
+ `test.rs` (uses `macro_db_migrator` as a dev-dependency).
+
+## Checks
+
+- `cargo test -p cursor_api_key` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `cipher::CursorApiKey` redacts its `Debug` and zeroizes on drop; a decrypted
+ key must become an HTTP header and be dropped, never held for a session's
+ lifetime (see `src/lib.rs` threat model).
+- Deleting a row does not revoke anything at Cursor — any "disconnect" surface
+ must say so explicitly.
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md`, `.agents/rules/rust/db.md`
diff --git a/crates/cursor_api_key/CLAUDE.md b/crates/cursor_api_key/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/cursor_api_key/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/cursor_cloud_agents/AGENTS.md b/crates/cursor_cloud_agents/AGENTS.md
new file mode 100644
index 0000000000..44427d5a80
--- /dev/null
+++ b/crates/cursor_cloud_agents/AGENTS.md
@@ -0,0 +1,68 @@
+# cursor_cloud_agents
+
+## What it is
+
+Part of agent sessions: an ACP agent backed by Cursor cloud agents — one
+ACP session is one Cursor *agent*, one `session/prompt` is one Cursor
+*run*, and the run's SSE stream is translated into ACP `session/update`
+notifications as it arrives.
+
+## Start here
+
+- `src/lib.rs`: the hexagonal layout (`domain`/`api`/`inbound`/`outbound`) —
+ read this doc comment first, it's the map.
+- `src/domain/translate.rs`: the Cursor→ACP event translation state machine
+ (`TranslateMachine`), mirroring `agent_fold`'s `FoldMachine`.
+- `src/domain/service.rs`: ties a prompt to a run.
+- `src/api.rs` (`src/api/`): the Cursor cloud REST + SSE client.
+- `src/inbound/acp.rs`: newline-delimited JSON-RPC ACP adapter (stdio or
+ in-process duplex pipe).
+- `src/outbound/postgres_journal.rs`: the hosted session journal (Postgres);
+ `src/outbound/memory_journal.rs` for standalone/tests.
+- `REPLAY.md`: the native journal, recovery, and migration-rollout contract —
+ read before touching `domain/journal.rs` or `outbound/postgres_journal.rs`.
+
+## Scope
+
+- Owns: the Cursor REST/SSE client, the Cursor event→ACP translation, the ACP
+ JSON-RPC adapter, and (behind the default `postgres` feature) the hosted
+ session journal.
+- Not here: the per-user Cursor API key and its encryption →
+ `crates/cursor_api_key`.
+
+## Boundaries
+
+- Depends on: `cursor_api_key` (indirectly, via callers), `agent_session`
+ (`postgres` feature), `agent_runtime_protocol`, `static_file_service_client`.
+- Used by: `agent_harness`, `authentication_service`, `agent_harness_service`.
+
+## Recipes
+
+- Handle a new Cursor SSE event kind: `src/domain/event.rs` →
+ `src/domain/translate.rs` → add a fixture under `fixtures/` → the snapshot
+ tests in `src/replay/test.rs` / `src/inbound/acp/test.rs`.
+- Add a Cursor REST call: `src/api.rs` → its submodule under `src/api/` →
+ the matching `domain::ports` trait.
+- Change journal recovery/replay behavior: read `REPLAY.md` first, then
+ `src/domain/journal.rs` → `src/outbound/postgres_journal.rs` → `src/replay.rs`.
+
+## Checks
+
+- `cargo test -p cursor_cloud_agents` (`SQLX_OFFLINE` unset; default features
+ include `postgres`).
+- `cargo test -p cursor_cloud_agents --no-default-features` for the in-memory
+ path only.
+
+## Gotchas
+
+- `REPLAY.md`'s migration-rollout section documents a one-time consolidation
+ of four old migrations into `20260906060601_cursor_session_replay`; don't
+ reset or DOWN-migrate a database that already has journal history without
+ reading it first.
+- `#![deny(missing_docs)]` applies to every public item.
+- Translation is a pure state machine fed one event at a time — keep new
+ logic in `domain/translate.rs`, not in `api.rs` or `inbound/acp.rs`.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/cursor_cloud_agents/CLAUDE.md b/crates/cursor_cloud_agents/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/cursor_cloud_agents/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/database_sql/AGENTS.md b/crates/database_sql/AGENTS.md
new file mode 100644
index 0000000000..5d6ca5c49a
--- /dev/null
+++ b/crates/database_sql/AGENTS.md
@@ -0,0 +1,60 @@
+# database_sql
+
+## What it is
+
+Part of the Databases feature: the SQL subset agents and the console use to
+read and write Macro databases. A pure parse → resolve → split → engine →
+fold pipeline, compiled natively and to `wasm32` (the browser's SQL editor
+uses the wasm build directly).
+
+## Start here
+
+- `src/lib.rs`: the pipeline diagram and the public re-exports — read this
+ before any other file.
+- `src/parse.rs` / `src/resolve.rs` / `src/split.rs` / `src/engine.rs` /
+ `src/fold.rs`: the pipeline stages, in order; each has a sibling `test.rs`.
+- `examples/repl.rs`: an interactive console against a live stack; `examples/gql.rs`
+ shows the GraphQL queries `split` emits.
+- `fixtures/transcripts/*.json`: one request/response fixture per SQL feature,
+ used by the engine tests.
+
+## Scope
+
+- Owns: the SQL grammar, catalog binding, GraphQL-query splitting, and the row
+ fold — i.e. the engine itself, with no knowledge of Postgres, Soup, or HTTP.
+- Not here: the domain service that stores tables/rows and exposes the ops API
+ → `crates/databases`; the agent-facing adapter that runs this engine over
+ that service and Soup → `crates/databases_sql`.
+
+## Boundaries
+
+- Depends on: `filter_ast`, `item_filters` (predicate ASTs shared with other
+ filtering code), `models_databases` (wire types).
+- Used by: `crates/databases` and `crates/databases_sql` natively; the web
+ app's database SQL console via the `wasm` module (crate-type `cdylib`).
+
+## Recipes
+
+- Add a SQL feature (new clause/function): `src/parse/ast.rs` + grammar in
+ `src/parse/parser.rs` → `src/resolve.rs` (bind against the catalog) →
+ `src/split.rs` (emit the GraphQL query) → `src/fold.rs` (shape rows) → add a
+ fixture under `fixtures/transcripts/`.
+- Regenerate the TypeScript wire types: `cargo run -p database_sql --features
+ cli --bin database_sql_types` (never hand-edit the generated output).
+
+## Checks
+
+- `cargo test -p database_sql`.
+- `cargo check -p database_sql --target wasm32-unknown-unknown` after touching
+ anything outside `src/wasm.rs`, since the crate must keep compiling there.
+
+## Gotchas
+
+- Keep the crate free of native-only dependencies (no `tokio`, no `sqlx`) —
+ it must compile to `wasm32`; native-only tooling goes behind the `cli` feature.
+- The grammar is the contract: a statement this crate rejects must never reach
+ `databases`' ops API some other way.
+
+## Related
+
+- Skill: `database-core` · Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/database_sql/CLAUDE.md b/crates/database_sql/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/database_sql/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/databases/AGENTS.md b/crates/databases/AGENTS.md
new file mode 100644
index 0000000000..74f1cc01ca
--- /dev/null
+++ b/crates/databases/AGENTS.md
@@ -0,0 +1,62 @@
+# databases
+
+## What it is
+
+The core of the Databases feature (also underlies CRM and Forms storage):
+tables of typed rows whose cells are entity properties, behind a hexagonal
+service with Axum, agent-tool and Postgres adapters.
+
+## Start here
+
+- `README.md`: the op/result contract (`POST /databases/{id}/ops`), the
+ `databases`/`database_entities` storage-vs-app-entity split, and a review map
+ of every module.
+- `src/domain/service.rs` + `src/domain/ports.rs`: orchestration and the ports
+ adapters implement.
+- `src/domain/models.rs`: `Database`, `DatabaseStorage`, typed ops/results.
+
+## Scope
+
+- Owns: database/table/column/row/view/saved-query persistence, the typed ops
+ batch API, sharing, provisioning, and the `database_entities` app-entity layer.
+- Not here: the SQL grammar agents and the console compile → `crates/database_sql`
+ (pure parse/resolve/fold engine, also runs in wasm); the agent-facing SQL
+ adapter that runs that engine over this crate's ops and Soup →
+ `crates/databases_sql`.
+
+## Boundaries
+
+- Depends on: `entity_access` (permission scoping), `properties` (cell values),
+ `macro_event_broker`/`macro_event_topics` (change notifications),
+ `connection_gateway_client` (liveness), `entity_mutation` (rename/trash/restore).
+- Used by: `databases_sql` (agent SQL), `crm` and `forms` (own storage via
+ `DatabaseStorage`, no `database_entities` row), `ai_tools`, `complete_graph`,
+ `graphql_crm`. The document storage service mounts `src/inbound/axum_router.rs`.
+
+## Recipes
+
+- Add a new op kind: `models_databases` (op/result shape) → `src/domain/service/ops/`
+ (per README's review map) → `src/outbound/pg_databases_repo.rs` → add a row to
+ the README's op/result tables.
+- Add a Postgres-backed read/write path for a new host (like CRM/forms): use
+ `DatabaseStorage::create_storage`/`apply_storage_writes` via the `postgres`
+ feature; do not add a `database_entities` row unless the host needs Soup
+ discovery, sharing, and trash semantics.
+
+## Checks
+
+- `cargo test -p databases --features postgres,inbound,ai_tools,gateway,entity_mutation`
+ (`SQLX_OFFLINE` unset; needs a migrated local MacroDB).
+
+## Gotchas
+
+- `databases` (core storage) and `database_entities` (app identity: name,
+ owner, trash) are separate tables by design; a host can use one without the
+ other (see README "Storage and app entities").
+- Column type changes must convert every value or refuse with the misfit count;
+ never silently drop data outside an explicit delete.
+
+## Related
+
+- Skill: `database-core` · Rules: `.agents/rules/rust/db.md`,
+ `.agents/rules/rust/architecture.md`
diff --git a/crates/databases/CLAUDE.md b/crates/databases/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/databases/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/databases_sql/AGENTS.md b/crates/databases_sql/AGENTS.md
new file mode 100644
index 0000000000..b2b8fbbe3f
--- /dev/null
+++ b/crates/databases_sql/AGENTS.md
@@ -0,0 +1,60 @@
+# databases_sql
+
+## What it is
+
+Part of the Databases feature: runs the `database_sql` engine over Macro
+databases for agents, as the agent-tool counterpart to the browser's direct
+`database_sql` wasm usage. Reads go through Soup and contacts, writes go
+through `databases`' typed ops.
+
+## Start here
+
+- `src/lib.rs`: module list and public re-exports (`DatabasesSql`, `SqlRequest`,
+ `SqlOutcome`).
+- `src/service.rs`: the entry point — runs a parsed statement's engine
+ `Request`s against `row_source`/`ops_sink` and returns a `SqlOutcome`.
+- `src/row_source.rs` / `src/ops_sink.rs`: the two adapters that plug this
+ crate's Soup/contacts/databases access into the `database_sql` engine's
+ generic `RowSource`/write traits.
+- `src/toolset.rs` + `src/toolset/*.md`: the `QueryDatabase` and
+ `SaveDatabaseQuery` agent tools; the `.md` files are the tool descriptions
+ sent to the model.
+- `src/view_only.rs`: a read-only variant of access, used where writes must be
+ refused.
+
+## Scope
+
+- Owns: binding the `database_sql` engine to live Macro data for agents, and
+ the two SQL agent tools.
+- Not here: the SQL grammar/engine itself → `crates/database_sql`; table/row
+ persistence and the ops API → `crates/databases`.
+
+## Boundaries
+
+- Depends on: `database_sql` (engine), `databases` (ops/storage, `ports` only),
+ `soup`, `contacts`, `entity_access` (all `ports`-only — this crate is an
+ adapter, not a composition root).
+- Used by: `crates/ai_tools` (wires the `ai_tools` feature's `QueryDatabase`/
+ `SaveDatabaseQuery` into the agent toolset).
+
+## Recipes
+
+- Change what a SQL read/write can see or do: `src/row_source.rs` or
+ `src/ops_sink.rs` → `src/service.rs`.
+- Edit a tool's behavior or its description: `src/toolset/query_database.rs` /
+ `query_database_writes.md` or `src/toolset/save_database_query.rs` →
+ `src/toolset/sql_guide.md` if the shared SQL guidance text changes.
+
+## Checks
+
+- `cargo test -p databases_sql --features ai_tools`.
+
+## Gotchas
+
+- This crate only depends on `ports` features of its domain crates — it must
+ not import `databases`' or `soup`'s `outbound` adapters directly; the
+ composition root supplies those.
+
+## Related
+
+- Skill: `database-core` · Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/databases_sql/CLAUDE.md b/crates/databases_sql/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/databases_sql/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/dictation/AGENTS.md b/crates/dictation/AGENTS.md
new file mode 100644
index 0000000000..9026953a9d
--- /dev/null
+++ b/crates/dictation/AGENTS.md
@@ -0,0 +1,44 @@
+# dictation
+
+## What it is
+
+Backs voice dictation in document and chat composers: private, transient
+audio transcription that validates a recording, transcribes it via Whisper,
+and returns text — nothing is stored.
+
+## Start here
+
+- `src/domain/service.rs`: the transcription use case (`DictationServiceImpl`).
+- `src/domain/models.rs`: `Recording`/`Transcript` value objects and limits
+ (`MAX_AUDIO_BYTES`, `MAX_AUDIO_DURATION`).
+- `src/domain/ports.rs`: `TranscriptionProvider` / `RecordingInspector` traits.
+- `src/outbound/whisper.rs`: the OpenAI Whisper adapter.
+- `src/inbound/axum_router.rs`: the authenticated, rate-limited HTTP endpoint.
+
+## Scope
+
+- Owns: recording validation, format/duration limits, and the HTTP endpoint
+ used by `document_storage_service`'s composers.
+- Not here: AI usage accounting (`ai_usage`, a dependency) or any persisted
+ transcript storage — this crate does not persist audio or text.
+
+## Boundaries
+
+- Depends on: `ai_usage`, `macro_authorization` + `rate_limit` (inbound
+ feature), `async-openai` + `opus-pure`/`symphonia` (outbound feature).
+- Used by: `document_storage_service`.
+
+## Recipes
+
+- Swap or tune the transcription provider: `src/outbound/whisper.rs` →
+ `src/domain/ports.rs` (if the port signature changes) → its `test.rs`.
+- Change validation limits: `src/domain/models.rs` → `src/domain/service.rs`.
+
+## Checks
+
+- `cargo test -p dictation --features inbound,outbound` (no database; pure
+ unit/HTTP tests with `wiremock`).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/dictation/CLAUDE.md b/crates/dictation/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/dictation/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/document_storage_service_client/AGENTS.md b/crates/document_storage_service_client/AGENTS.md
new file mode 100644
index 0000000000..8021f2bc7d
--- /dev/null
+++ b/crates/document_storage_service_client/AGENTS.md
@@ -0,0 +1,54 @@
+# document_storage_service_client
+
+## What it is
+
+Shared infrastructure for the Documents feature (and the other entities DSS
+hosts): a Rust HTTP client for `document_storage_service` (DSS) covering
+documents, projects, threads, notifications, and uploads.
+
+## Start here
+
+- `src/lib.rs`: `DocumentStorageServiceClient`, built with two `reqwest`
+ clients (see Gotchas).
+- `src/error.rs`: `DssClientError`, the shared error type most methods return.
+- `src/document.rs`, `src/project.rs`, `src/thread.rs`, `src/notification.rs`,
+ `src/upload.rs`, `src/delete.rs`: one module per DSS resource, each adding
+ methods via `impl DocumentStorageServiceClient`.
+
+## Scope
+
+- Owns: typed request/response wrapping for DSS's HTTP API.
+- Not here: DSS's own domain logic → `services/document_storage_service`;
+ the request/response types themselves → `crates/model`.
+
+## Boundaries
+
+- Depends on: `model`, `model_owner`, `models_bulk_upload`,
+ `models_permissions`, `shared_entity_registry`.
+- Used by: `crates/agent_trigger` and most services that call DSS directly
+ (`document_cognition_service`, `authentication_service`,
+ `agent_trigger_service`, `search_upload_handler`,
+ `upload_extractor_lambda_handler`, `agent_harness_service`,
+ `email_service`).
+
+## Recipes
+
+- Add an endpoint: add a method in the matching resource module (or a new
+ one) using `self.client` (internal auth) or `self.external_request` (JWT) →
+ add request/response types to `crates/model` if new → map the response to
+ `DssClientError` on failure.
+
+## Checks
+
+- `cargo test -p document_storage_service_client` (`SQLX_OFFLINE` unset; no
+ database needed).
+
+## Gotchas
+
+- Two `reqwest::Client`s: `client` carries the internal auth header for
+ service-to-service calls; `external_client` (via `external_request`) sends
+ a caller's JWT instead — don't mix them up.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/document_storage_service_client/CLAUDE.md b/crates/document_storage_service_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/document_storage_service_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/documents/AGENTS.md b/crates/documents/AGENTS.md
new file mode 100644
index 0000000000..06bbce6058
--- /dev/null
+++ b/crates/documents/AGENTS.md
@@ -0,0 +1,71 @@
+# documents
+
+## What it is
+
+The core of the Documents feature: document CRUD, content storage, AI
+editing/tools, and file-type-specific services (spreadsheets, presentations,
+word docs, Illustrator/Photoshop files).
+
+## Start here
+
+- `src/lib.rs`: the hexagonal layout (`domain`/`inbound`/`outbound`) and which
+ Cargo features gate each module.
+- `src/domain/service.rs` + `src/domain/ports.rs`: orchestration and the ports
+ adapters implement.
+- `src/domain/content.rs`: document content storage model (markdown vs legacy
+ Office formats, S3 locations).
+- `src/inbound/toolset.rs`: one submodule per AI document tool (`create_document`,
+ `edit_document`, `word_document`, `spreadsheet`, `presentation`, ...).
+- `src/inbound/axum_router.rs`: the HTTP surface.
+
+## Scope
+
+- Owns: document lifecycle (create/rename/purge/upgrade), content storage and
+ markdown backfill, comments, AI-editing tools, and file-type domain services
+ (spreadsheet, presentation, word, illustrator, photoshop).
+- Not here: realtime collaborative sync of document content → sync-service;
+ the lexical markdown node/editor implementation → `packages/lexical-core`.
+
+## Boundaries
+
+- Depends on (feature-gated): `entity_access`/`entity_registry` (permissions),
+ `ai_engine`/`ai_toolset`/`ai_billing`/`ai_usage` (AI tools), `pptx_engine`/
+ `psd_engine` (file formats), `lexical_client` (sync-service calls),
+ `comms_db_client` (create/purge adapters), `macro_db_client` (purge/backfill).
+- Used by: `ai_tools`, `agent_harness`, `webhook`, `soup_realtime`, `memory`,
+ `projects`, `skills`, `github` — this crate's service and toolset are widely
+ reused; check callers before changing a port signature.
+
+## Recipes
+
+- Add an AI document tool: new module under `src/inbound/toolset/` → wire it
+ into `src/inbound/toolset.rs` → register it where `ai_tools`/`crates/ai_tools`
+ assembles the toolset.
+- Add a document route: `src/domain/service.rs` (new domain method) →
+ `src/inbound/axum_router.rs` → `src/domain/ports.rs` if it needs a new
+ outbound capability.
+- Change content storage/markdown lifecycle: `src/domain/content.rs` →
+ `src/outbound/s3_markdown_source.rs` / `src/outbound/markdown_init.rs` →
+ `src/bin/backfill_markdown_content_location.rs` if existing documents need
+ migrating (run via `just backfill_markdown_content_location_dev` from this
+ crate's `justfile`).
+
+## Checks
+
+- `cargo test -p documents --all-features` (`SQLX_OFFLINE` unset; needs a
+ migrated local MacroDB for `outbound`/`document_create_adapters` tests).
+- `just -f crates/documents/justfile check` for an all-features `cargo check`.
+
+## Gotchas
+
+- Features compose non-trivially (`inbound` pulls in `axum` and
+ `document_create_adapters`; `ai_tools` pulls in `outbound` and `ports`) —
+ check `Cargo.toml`'s `[features]` block before assuming a module compiles
+ standalone.
+- The markdown backfill binary defaults to dry-run; the `_apply`/prod `just`
+ recipes require a typed confirmation before writing.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md` ·
+ Skill: `collab-surface-core`
diff --git a/crates/documents/CLAUDE.md b/crates/documents/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/documents/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/docx_engine/AGENTS.md b/crates/docx_engine/AGENTS.md
new file mode 100644
index 0000000000..1fff573016
--- /dev/null
+++ b/crates/docx_engine/AGENTS.md
@@ -0,0 +1,55 @@
+# docx_engine
+
+## What it is
+
+Powers Word-document editing within the Documents feature: a from-scratch
+`.docx` engine — parse, lay out, render, edit, save. Runs natively (tests,
+the corpus CLI) and as WebAssembly in the web app's DOCX editor worker.
+
+## Start here
+
+- `README.md`: design (attributed-string paragraphs, block tree, the
+ collaborative shape), the full directory map, current fidelity numbers,
+ and known gaps — read this before the source.
+- `src/document.rs`: the package, body story, headers/footers/notes.
+- `src/edit.rs` + `src/edit/txn.rs`: `Session::apply`, the edit-operation
+ transaction model.
+- `src/collab.rs`: the document as Loro containers; `src/wasm.rs`: the
+ wasm-bindgen API the browser worker calls.
+
+## Scope
+
+- Owns: everything Word-specific — model, layout, render, edit, collab, wasm
+ bridge.
+- Not here: the shared Office foundation (ZIP/OPC, DrawingML, fonts,
+ rasterizer) → `crates/pptx_engine`.
+
+## Boundaries
+
+- Depends on: `pptx_engine` (default-features disabled).
+- Used by: `services/convert_service` natively; the web app's DOCX editor
+ worker (`apps/web/src/lib/core/docx-engine`) via the wasm build.
+
+## Recipes
+
+- Add an edit operation: `src/edit.rs` (`EditOp` variant) → the matching
+ `src/edit/<area>.rs` → `src/edit/test.rs`.
+- Rebuild the wasm bundle after a native change: `just build-docx-engine-wasm`
+ from `apps/web` (or `just ensure-docx-engine-wasm` to rebuild only if stale).
+
+## Checks
+
+- `cargo test -p docx_engine`.
+- Fidelity scoring against reference renders: `cargo run -p docx_engine
+ --bin docx_corpus --features cli` (see `tests/corpus/README.md`).
+
+## Gotchas
+
+- `#![deny(missing_docs)]`: every public item needs a doc comment.
+- Content the engine doesn't interpret is kept as opaque XML and written back
+ unchanged — don't drop unknown attributes or children while editing a block.
+
+## Related
+
+- Docs: `README.md` (this crate) · `apps/web/AGENTS.md` for the browser
+ editor side.
diff --git a/crates/docx_engine/CLAUDE.md b/crates/docx_engine/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/docx_engine/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/email/AGENTS.md b/crates/email/AGENTS.md
new file mode 100644
index 0000000000..c30a94d260
--- /dev/null
+++ b/crates/email/AGENTS.md
@@ -0,0 +1,61 @@
+# email
+
+## What it is
+
+The core of the Email feature: threads/messages orchestration, scheduling
+and reminders/followups, calendar-invitation extraction, and the AI email
+tools — hexagonal, heavily feature-gated.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/ports.rs`: the domain service and the
+ traits its adapters implement.
+- `src/inbound/axum.rs`: HTTP routes (feature `axum`); `src/inbound/toolset.rs`:
+ the AI email tools (feature `ai_tools`).
+- `src/outbound/email_pg_repo.rs`, `src/outbound/invitation_pg.rs`: Postgres
+ adapters (feature `outbound`); `src/outbound/email_service_http.rs`: calls
+ into `email_service`; `src/outbound/s3_draft_attachment_storage.rs`: staged
+ draft attachments (feature `s3`).
+
+## Scope
+
+- Owns: email/thread domain logic, scheduled delivery, reminders/followups,
+ calendar invitation extraction and resolution.
+- Not here: raw provider API calls → `email_api_client`; HTML
+ parsing/sanitization → `email_utils`; SQLx queries over email tables →
+ `email_db_client`.
+
+## Boundaries
+
+- Depends on: `entity_access`, `entity_access_management`, `email_utils`,
+ `crm`, `frecency`, `item_filters`, `lexical_client`, `macro_event_broker`,
+ `calendar_events` (optional, feature `calendar_invitations`).
+- Used by: many crates and services, including `ai_tools`, `graphql_email`,
+ `teams`, `databases_sql`, `work_feed`, `calendar_service`, `email_service`,
+ `email_scheduled_handler`, `search_processing_service`.
+
+## Recipes
+
+- Add a route: `src/inbound/axum.rs` → `src/domain/service.rs` →
+ the relevant `src/outbound/*.rs` adapter.
+- Add an AI tool: `src/inbound/toolset.rs` → `src/domain/service.rs`.
+- Add a feature-gated adapter: add the optional dependency and a feature in
+ `Cargo.toml` → `src/outbound/<name>.rs` → declare it in `src/outbound.rs`.
+
+## Checks
+
+- `cargo test -p email --all-features` (`SQLX_OFFLINE` unset; the `outbound`
+ feature's tests need a local MacroDB — `just setup_macrodb`).
+
+## Gotchas
+
+- The feature matrix (`ports`/`inbound`/`outbound`/`http_client`/`s3`/
+ `gmail_token`/`ai_tools`/`attachment`/`calendar_invitations`/`axum`) gates
+ most modules; check `Cargo.toml`'s `[features]` block for which one a new
+ dependency belongs under before wiring it in.
+- `domain/ports.rs` defines the traits adapters implement — call through the
+ domain service, never an outbound adapter directly from another crate.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/email/CLAUDE.md b/crates/email/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/email/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/email_api_client/AGENTS.md b/crates/email_api_client/AGENTS.md
new file mode 100644
index 0000000000..7d3fafb8ef
--- /dev/null
+++ b/crates/email_api_client/AGENTS.md
@@ -0,0 +1,52 @@
+# email_api_client
+
+## What it is
+
+Part of the Email feature: provider-neutral contracts and models for email
+provider integrations (sync, send, tokens, rate limits), plus the Gmail
+outbound adapter.
+
+## Start here
+
+- `src/domain/service.rs`: `EmailApiClientServiceImpl<R, T, L>` — the
+ orchestration layer, generic over a repository, token source, and rate
+ limiter port; submodules `attachments`/`blocklist`/`contacts`/`labels`/
+ `messages`/`send`/`subscription`/`sync` hold one capability each.
+- `src/domain/ports.rs`: `ProviderRateLimiter`, `ProviderTokenSource`, and the
+ repository trait adapters implement.
+- `src/outbound/gmail.rs`: the Gmail adapter (feature `outbound-gmail`).
+
+## Scope
+
+- Owns: the provider-neutral vocabulary (`Message`, `Contact`, `SyncCursor`,
+ `SendRequest`, token/rate-limit errors) and orchestration over it.
+- Not here: Macro's own email domain (threads, scheduling) → `crates/email`;
+ SQLx storage → `email_db_client`.
+
+## Boundaries
+
+- Depends on: `email_utils`, `models_email`, `gmail_client` (feature
+ `outbound-gmail`).
+- Used by: `services/email_service`.
+
+## Recipes
+
+- Add a provider capability: a trait method on `src/domain/ports.rs` → a
+ submodule under `src/domain/service.rs` → implement it in
+ `src/outbound/gmail.rs` → tests alongside in `src/domain/service/test.rs`
+ / `test_support.rs`.
+
+## Checks
+
+- `cargo test -p email_api_client --features outbound-gmail`.
+
+## Gotchas
+
+- `#![deny(missing_docs)]`.
+- The service is generic over `<R, T, L>` (repository, token source, rate
+ limiter) — add a new dependency as a port + generic bound, not a concrete
+ field.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/email_api_client/CLAUDE.md b/crates/email_api_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/email_api_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/email_db_client/AGENTS.md b/crates/email_db_client/AGENTS.md
new file mode 100644
index 0000000000..905cdb21fb
--- /dev/null
+++ b/crates/email_db_client/AGENTS.md
@@ -0,0 +1,51 @@
+# email_db_client
+
+## What it is
+
+Part of the Email feature: the SQLx query crate for MacroDB's email tables —
+messages, threads, contacts, labels, links, attachments, sync tokens, CRM
+cleanup, and backfill.
+
+## Start here
+
+- `src/lib.rs`: the module list, one per table/feature area, mirroring
+ `macro_db_client`'s layout.
+- `src/parse/`: service↔DB type conversion (`db_to_service.rs`,
+ `service_to_db.rs`) and column-length limits (`column_limits.rs`).
+- `README.md`: local test-database setup.
+
+## Scope
+
+- Owns: the `sqlx::query!` call sites for email tables.
+- Not here: email domain/business logic → `crates/email`; provider API calls
+ → `email_api_client`. The schema lives in `crates/macro_db_client/migrations/`
+ (shared MacroDB), not here.
+
+## Boundaries
+
+- Depends on: `models_email`, `models_pagination`, `email_utils`.
+- Used by: `crates/email`, `crates/search_service`, `services/calendar_service`,
+ `services/authentication_service`, `services/search_processing_service`,
+ `services/email_service`.
+
+## Recipes
+
+- Add a query to an existing table: the module in `src/<area>/` (e.g.
+ `src/messages/get.rs`) → its `mod.rs` → a fixture under `fixtures/*.sql` if
+ the test needs seed data.
+- Add a column or table: see `crates/macro_db_client/AGENTS.md` (this crate
+ only owns queries, not migrations).
+
+## Checks
+
+- `cargo test -p email_db_client` (`SQLX_OFFLINE` unset; requires local
+ MacroDB — `just setup_macrodb`).
+
+## Gotchas
+
+- Quote and alias camelCase columns to Rust field names; check
+ `crates/macro_db_client/migrations/` for real column spelling, don't guess.
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md` · Docs: `docs/development/database.md`
diff --git a/crates/email_db_client/CLAUDE.md b/crates/email_db_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/email_db_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/email_service_client/AGENTS.md b/crates/email_service_client/AGENTS.md
new file mode 100644
index 0000000000..38c7a79100
--- /dev/null
+++ b/crates/email_service_client/AGENTS.md
@@ -0,0 +1,49 @@
+# email_service_client
+
+## What it is
+
+Part of the Email feature: a Rust HTTP client for `email_service` —
+message/thread lookups by id, thread owner lookup, and an external
+(JWT-authenticated) preview endpoint.
+
+## Start here
+
+- `src/lib.rs`: `EmailServiceClient` (internal auth header, one `reqwest`
+ client).
+- `src/external.rs`: `EmailServiceClientExternal`, the JWT-authenticated
+ counterpart used for external/preview calls.
+- `src/get_message_by_id.rs`, `src/get_messages_by_thread_id.rs`,
+ `src/get_message_senders.rs`, `src/get_thread_owner.rs`: one module per
+ endpoint.
+
+## Scope
+
+- Owns: typed request/response wrapping for `email_service`'s HTTP API.
+- Not here: `email_service`'s own domain logic → `crates/email`.
+
+## Boundaries
+
+- Depends on: `email` (features `axum`, `inbound`), `model`, `models_email`.
+- Used by: `crates/memory`, `crates/ai_tools`, `services/document_cognition_service`,
+ `services/mcp_service`.
+
+## Recipes
+
+- Add an endpoint: new module with `impl EmailServiceClient` (internal auth)
+ or `impl EmailServiceClientExternal` (JWT) → wire response types from
+ `email`/`models_email`.
+
+## Checks
+
+- `cargo test -p email_service_client` (`SQLX_OFFLINE` unset; no database
+ needed).
+
+## Gotchas
+
+- Two client types, not two modes of one struct: `EmailServiceClient` is for
+ internal service-to-service calls, `EmailServiceClientExternal` is for
+ calls authenticated with a caller's JWT — pick the one matching the caller.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/email_service_client/CLAUDE.md b/crates/email_service_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/email_service_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/email_utils/AGENTS.md b/crates/email_utils/AGENTS.md
new file mode 100644
index 0000000000..83eb3d08ef
--- /dev/null
+++ b/crates/email_utils/AGENTS.md
@@ -0,0 +1,50 @@
+# email_utils
+
+## What it is
+
+Part of the Email feature: shared email text handling — HTML sanitization,
+reply-quote stripping, body parsing, contact name normalization, and
+sender/generic-address checks.
+
+## Start here
+
+- `src/sanitizer.rs`: `sanitize_email_html`, `sanitize_authored_html`,
+ `sanitize_html_fragment` — every HTML body that reaches
+ `body_html_sanitized` must pass through one of these.
+- `src/body_replyless.rs` + `src/body_replyless/`: strips quoted reply chains
+ from HTML and plaintext bodies.
+- `src/body_parsed.rs`: the parsed-body representation used across callers.
+
+## Scope
+
+- Owns: provider-neutral email text transforms with no I/O.
+- Not here: provider API calls → `email_api_client`; DB storage →
+ `email_db_client`; domain logic → `crates/email`.
+
+## Boundaries
+
+- Depends on: `ammonia`, `scraper` (no Macro crates).
+- Used by: `crates/email`, `crates/email_db_client`, `crates/email_api_client`,
+ `crates/graphql_email`, `crates/google_token`, `crates/models_email`,
+ `services/calendar_service`, `services/email_service`.
+
+## Recipes
+
+- Add a sanitizer rule: `src/sanitizer.rs` (ammonia allowlist/`Builder`) →
+ `src/sanitizer/test.rs`.
+- Add a reply-stripping heuristic: `src/body_replyless/html_parser.rs` or
+ `plaintext_parser.rs` → `src/body_replyless/test.rs`.
+
+## Checks
+
+- `cargo test -p email_utils`.
+
+## Gotchas
+
+- Sanitization is security-sensitive (XSS via email HTML): any allowlist
+ change needs a test proving the previously-dangerous input is now stripped,
+ not just that benign input survives.
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md`
diff --git a/crates/email_utils/CLAUDE.md b/crates/email_utils/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/email_utils/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/entity_access/AGENTS.md b/crates/entity_access/AGENTS.md
new file mode 100644
index 0000000000..62e241a53e
--- /dev/null
+++ b/crates/entity_access/AGENTS.md
@@ -0,0 +1,62 @@
+# entity_access
+
+## What it is
+
+Shared infrastructure used across nearly every feature: entity access
+control for cloud storage, checking a user's or bot's access level to any
+entity (documents, chats, projects, and more). One of the most widely
+depended-on crates in the backend.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/ports.rs`: `EntityAccessService` and
+ the `AccessRepository` trait it's built on — one `get_<entity>_access`
+ method per entity kind.
+- `src/domain/models.rs`: `AccessLevel`, `RequiredPermission`,
+ `EntityAccessReceipt` — the typed receipt proving a checked access level.
+- `src/inbound/axum_extractors.rs`: Axum extractors that resolve a receipt
+ from the request (feature `inbound`).
+- `src/outbound/pg_access_repo.rs`: the Postgres adapter (feature `outbound`).
+- `src/bin/explain_access.rs`: CLI to explain why a user has (or lacks)
+ access to an entity (feature `explain_binary`).
+
+## Scope
+
+- Owns: read-side access-level checks and their `EntityAccessReceipt` proof
+ type.
+- Not here: writing/propagating access grants (project moves, sharing
+ updates) → `crates/entity_access_management`; the raw `entity_access` table
+ queries → `crates/entity_access_db_utils`.
+
+## Boundaries
+
+- Depends on: `model-entity`, `model_owner`, `models_entity_access_management`,
+ `models_permissions`, `macro_user_id`, `bot_id`.
+- Used by: nearly every domain crate that authorizes a request (`documents`,
+ `chat`, `projects`, `crm`, `forms`, `databases`, `channels`, `agent_session`,
+ `graphql_*` crates, and most services) — a signature change here ripples
+ widely; check callers first.
+
+## Recipes
+
+- Add an entity kind's access check: `src/domain/ports.rs`
+ (`AccessRepository` method) → `src/domain/service.rs` → `src/outbound/pg_access_repo.rs`.
+- Debug a specific grant: `cargo run -p entity_access --bin explain_access
+ --features explain_binary`.
+
+## Checks
+
+- `cargo test -p entity_access` (`SQLX_OFFLINE` unset; requires local
+ MacroDB — `just setup_macrodb`).
+
+## Gotchas
+
+- `#![deny(missing_docs)]`.
+- `EntityAccessReceipt<R: RequiredPermission>` is the only proof a caller
+ checked access at the right level; domain code downstream (e.g.
+ `entity_mutation`) takes a receipt, not a raw boolean/level.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/security.md`
+ · Skill: `cloud-storage-hexagonal-architecture`
diff --git a/crates/entity_access/CLAUDE.md b/crates/entity_access/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/entity_access/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/entity_access_db_utils/AGENTS.md b/crates/entity_access_db_utils/AGENTS.md
new file mode 100644
index 0000000000..7d7ba2d274
--- /dev/null
+++ b/crates/entity_access_db_utils/AGENTS.md
@@ -0,0 +1,53 @@
+# entity_access_db_utils
+
+## What it is
+
+Shared infrastructure backing entity access across every feature:
+transactional helpers for the shared `entity_access` table — insert grant
+rows, and the channel-share/team-share/source-grant query helpers built on
+top of it.
+
+## Start here
+
+- `src/lib.rs`: `insert_entity_access_row`, `OwnerGrantSource` — the base
+ insert other helpers build on.
+- `src/source_grants.rs`: `delete_source_grants` and friends, grouped by
+ `EntityAccessSourceType`.
+- `src/channel_share.rs`, `src/team_share.rs`: grant helpers scoped to a
+ channel or team source.
+
+## Scope
+
+- Owns: writes to the `entity_access` table.
+- Not here: read-side access-level checks → `crates/entity_access`; the
+ owner-grant policy that decides *which* grants to write on creation →
+ `crates/entity_access_management`.
+
+## Boundaries
+
+- Depends on: `macro_user_id`, `model-entity`, `model_owner`,
+ `models_entity_access_management`, `models_permissions`.
+- Used by: `crates/entity_access_management`, `crates/entity_registry/entity_registry_db_utils`,
+ and most domain crates that grant access as part of a write
+ (`channels`, `projects`, `teams`, `crm`, `call`, `chat`, `documents`,
+ `macro_db_client`, `services/scheduled_action`).
+
+## Recipes
+
+- Add a grant helper: `src/source_grants.rs` (or a new `src/<source>.rs`) →
+ export from `src/lib.rs` → a fixture under `fixtures/*.sql` if the test
+ needs seed rows.
+
+## Checks
+
+- `cargo test -p entity_access_db_utils` (`SQLX_OFFLINE` unset; requires
+ local MacroDB — `just setup_macrodb`).
+
+## Gotchas
+
+- Helpers never commit; every function takes `&mut Transaction<'_, Postgres>`
+ and the caller commits once alongside its own row writes.
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md`, `.agents/rules/rust/architecture.md`
diff --git a/crates/entity_access_db_utils/CLAUDE.md b/crates/entity_access_db_utils/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/entity_access_db_utils/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/entity_access_management/AGENTS.md b/crates/entity_access_management/AGENTS.md
new file mode 100644
index 0000000000..ef770842c8
--- /dev/null
+++ b/crates/entity_access_management/AGENTS.md
@@ -0,0 +1,44 @@
+# entity_access_management
+
+## What it is
+
+Shared infrastructure backing entity access, mainly for the Projects
+feature: manages `entity_access` row updates triggered by entity lifecycle
+events — adding/removing an entity from a project, and moving a project.
+
+## Start here
+
+- `src/domain/ports.rs`: `EntityAccessManagementRepository` (add/remove from
+ project, move project) and `EntityAccessManagementService`.
+- `src/domain/service.rs`: the service implementation.
+- `src/outbound/pg_repo.rs`: the Postgres adapter (feature `outbound`,
+ default-on).
+
+## Scope
+
+- Owns: propagating project-membership changes into `entity_access` rows.
+- Not here: checking access levels → `crates/entity_access`; the raw insert/
+ delete helpers it calls → `crates/entity_access_db_utils`.
+
+## Boundaries
+
+- Depends on: `macro_user_id`, `model-entity`, `models_entity_access_management`,
+ `models_permissions`, `entity_access_db_utils` (feature `outbound`).
+- Used by: `crates/email`, `crates/projects`, `crates/chat`, `crates/documents`,
+ `crates/macro_db_client`, `services/document_storage_service`,
+ `services/email_service`.
+
+## Recipes
+
+- Add a lifecycle event: `src/domain/ports.rs` (repository method) →
+ `src/domain/service.rs` → `src/outbound/pg_repo.rs` → a fixture under
+ `fixtures/*.sql`.
+
+## Checks
+
+- `cargo test -p entity_access_management` (`SQLX_OFFLINE` unset; requires
+ local MacroDB — `just setup_macrodb`).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/entity_access_management/CLAUDE.md b/crates/entity_access_management/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/entity_access_management/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/entity_mutation/AGENTS.md b/crates/entity_mutation/AGENTS.md
new file mode 100644
index 0000000000..5283a3b400
--- /dev/null
+++ b/crates/entity_mutation/AGENTS.md
@@ -0,0 +1,49 @@
+# entity_mutation
+
+## What it is
+
+Shared infrastructure used across every entity-owning feature: the
+canonical mutation vocabulary (`rename`, `move`, `trash`, `restore`,
+`duplicate`, `permanently delete`, `update share policy`) that each entity
+domain crate implements, so a composition-layer router can dispatch to any
+entity kind generically.
+
+## Start here
+
+- `src/capability.rs`: the per-capability traits (`RenameEntity`,
+ `MoveEntity`, `TrashEntity`, `RestoreEntity`, `DuplicateEntity`,
+ `DeleteEntityPermanently`, `UpdateEntitySharePolicy`) — implemented by each
+ entity domain crate, not by anything here.
+- `src/models.rs`: shared request/effect/error types
+ (`EntityMutationEffect`, `EntityMutationErrorCode`).
+- `src/ports.rs`: `EntityMutationService`, the router-facing port.
+
+## Scope
+
+- Owns: the shared mutation vocabulary and effect types.
+- Not here: any entity kind's actual rename/move/trash logic (lives in that
+ entity's own domain crate, e.g. `crates/documents`, `crates/chat`); the
+ router dispatching to them → the DSS entity mutation service.
+
+## Boundaries
+
+- Depends on: `entity_access` (for `EntityAccessReceipt`/`RequiredPermission`),
+ `model-entity`, `models_permissions`.
+- Used by: `crates/channels`, `crates/email`, `crates/forms`, `crates/databases`,
+ `crates/projects`, `crates/call`, `crates/chat`, `crates/documents`,
+ `crates/graphql_entity_mutation`, `crates/graphql_favorite`,
+ `services/document_storage_service`.
+
+## Recipes
+
+- Add a capability: a trait in `src/capability.rs` (with an associated
+ `Receipt: RequiredPermission`) → export it from `src/lib.rs` → implement it
+ in each entity domain crate that supports it.
+
+## Checks
+
+- `cargo test -p entity_mutation`.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/entity_mutation/CLAUDE.md b/crates/entity_mutation/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/entity_mutation/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/entity_registry/entity_registry/AGENTS.md b/crates/entity_registry/entity_registry/AGENTS.md
new file mode 100644
index 0000000000..285602ac5a
--- /dev/null
+++ b/crates/entity_registry/entity_registry/AGENTS.md
@@ -0,0 +1,54 @@
+# entity_registry
+
+## What it is
+
+Shared infrastructure used across every owned-entity feature: the owning
+crate for the `entity` table, recording one owner per in-scope resource,
+plus the owner-grant policy for what access that owner implies.
+
+## Start here
+
+- `src/lib.rs`: crate-level doc comment explains the split with
+ `entity_registry_db_utils` and `shared_entity_registry` — read it first.
+- `src/domain/service.rs` + `src/domain/ports.rs`: `EntityRegistryService` /
+ `EntityRegistryRepository` (reads).
+- `src/domain/owner_grant_policy.rs`: `OwnerGrantPolicy` — which access
+ grants a given owner type implies.
+- `src/domain/creation_principal.rs`: resolving who gets recorded as creator
+ vs. owner (bots vs. users).
+- `src/outbound/pg_entity_registry_repo.rs`: the Postgres adapter (feature
+ `postgres`).
+
+## Scope
+
+- Owns: reads of the `entity` table and the owner-grant policy.
+- Not here: effective access (who can view/edit) → `crates/entity_access`;
+ transactional writes → `crates/entity_registry/entity_registry_db_utils`;
+ shared types (`NewEntityRecord`, `Owner`, errors) →
+ `crates/entity_registry/shared_entity_registry`.
+
+## Boundaries
+
+- Depends on: `shared_entity_registry`, `model-entity`, `model_owner`,
+ `macro_authorization` (feature `axum`), `bot_id`.
+- Used by: `crates/memory`, `crates/ai_tools`, `crates/projects`,
+ `crates/agent_harness`, `crates/teams`, `crates/agent_session`,
+ `crates/chat`, `crates/documents`, `crates/bots`,
+ `crates/document_storage_service_client`, and most services that create
+ owned entities.
+
+## Recipes
+
+- Add an ownable entity type: `shared_entity_registry` (`RegisteredEntityType`)
+ → `src/domain/owner_grant_policy.rs` (grants for the new type) →
+ `entity_registry_db_utils` (callers register rows there).
+
+## Checks
+
+- `cargo test -p entity_registry` (`SQLX_OFFLINE` unset; requires local
+ MacroDB — `just setup_macrodb`).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md` · Crate:
+ `crates/entity_registry/entity_registry_db_utils`
diff --git a/crates/entity_registry/entity_registry/CLAUDE.md b/crates/entity_registry/entity_registry/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/entity_registry/entity_registry/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/entity_registry/entity_registry_db_utils/AGENTS.md b/crates/entity_registry/entity_registry_db_utils/AGENTS.md
new file mode 100644
index 0000000000..248690f001
--- /dev/null
+++ b/crates/entity_registry/entity_registry_db_utils/AGENTS.md
@@ -0,0 +1,56 @@
+# entity_registry_db_utils
+
+## What it is
+
+Shared infrastructure used across every owned-entity feature: transactional
+writes to the `entity` table, for callers to run inside their own
+resource-row transaction.
+
+## Start here
+
+- `src/lib.rs`: `insert_entity`, `mark_deleted`, `clear_deleted`,
+ `touch_updated`, `delete_entity` — plain, non-committing helpers.
+- `src/owned.rs`: `OwnedEntityRegistrar` — registers an entity row and
+ applies `entity_registry`'s `OwnerGrantPolicy` grants atomically (via a
+ savepoint), for owned-entity creation flows.
+
+## Scope
+
+- Owns: `entity` table writes.
+- Not here: reads → `crates/entity_registry/entity_registry`
+ (`EntityRegistryService`); the grant policy itself →
+ `entity_registry::OwnerGrantPolicy`; the actual access-grant rows →
+ `crates/entity_access_db_utils`.
+
+## Boundaries
+
+- Depends on: `entity_registry`, `entity_access_db_utils`, `model_owner`,
+ `shared_entity_registry`.
+- Used by: `crates/ai_tools`, `crates/memory`, `crates/projects`,
+ `crates/agent_session`, `crates/chat`, `crates/documents`,
+ `crates/macro_db_client`, and services that create owned entities
+ (`document_storage_service`, `agent_harness_service`, `scheduled_action`).
+
+## Recipes
+
+- Register a new owned entity type end to end: construct `NewEntityRecord`
+ (via `entity_registry::NewEntityRecord::try_new`) → call
+ `OwnedEntityRegistrar::register_owned_entity` inside your own transaction
+ → commit once.
+
+## Checks
+
+- `cargo test -p entity_registry_db_utils` (`SQLX_OFFLINE` unset; requires
+ local MacroDB — `just setup_macrodb`).
+
+## Gotchas
+
+- `insert_entity` is idempotent (`ON CONFLICT (id) DO NOTHING`); helpers
+ never commit the caller's transaction.
+- `register_owned_entity` is not an ownership-transfer API — conflicting
+ owners/types fail rather than re-granting to a different principal.
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md` · Crate:
+ `crates/entity_registry/entity_registry`
diff --git a/crates/entity_registry/entity_registry_db_utils/CLAUDE.md b/crates/entity_registry/entity_registry_db_utils/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/entity_registry/entity_registry_db_utils/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/favorites/AGENTS.md b/crates/favorites/AGENTS.md
new file mode 100644
index 0000000000..c4574fa228
--- /dev/null
+++ b/crates/favorites/AGENTS.md
@@ -0,0 +1,43 @@
+# favorites
+
+## What it is
+
+Backs favoriting/pinning across Macro surfaces (sidebar, Home/Soup):
+user- and team-scoped ordered collections of entities, following the
+hexagonal architecture pattern.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/mutation_service.rs`: the service and
+ its mutation (reorder/add/remove) logic.
+- `src/domain/ports.rs`: the repository port, implemented in `outbound`.
+- `src/inbound/axum_router.rs`, `src/inbound/toolset.rs`: HTTP router and AI
+ toolset adapter.
+- `src/outbound/pg_favorites_repo.rs`: the Postgres adapter.
+
+## Scope
+
+- Owns: favoriting/ordering for any entity type, behind `ports`, `inbound`,
+ `outbound`, `ai_tools` feature flags.
+- Not here: the GraphQL favorites surface → `crates/graphql_favorite`.
+
+## Boundaries
+
+- Depends on: `entity_access` (ports), `macro_authorization` (inbound),
+ `model-entity`, `cowlike`.
+- Used by: `graphql_favorite`, `ai_tools`, `complete_graph`, `soup`,
+ `document_storage_service`, `authentication_service`.
+
+## Recipes
+
+- Add a favoritable entity type: `src/domain/models.rs` → `src/domain/service.rs`
+ → `src/outbound/pg_favorites_repo.rs` → caller's feature wiring.
+- Add an AI tool action: `src/inbound/toolset.rs` → `src/domain/mutation_service.rs`.
+
+## Checks
+
+- `cargo test -p favorites --all-features` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/favorites/CLAUDE.md b/crates/favorites/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/favorites/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/feature_flags/AGENTS.md b/crates/feature_flags/AGENTS.md
new file mode 100644
index 0000000000..f8f6858b4f
--- /dev/null
+++ b/crates/feature_flags/AGENTS.md
@@ -0,0 +1,39 @@
+# feature_flags
+
+## What it is
+
+Shared infrastructure for cross-feature rollout gating: async flag loading
+for the authenticated Macro user, where one load returns a stable
+`FlagSnapshot`, read synchronously after.
+
+## Start here
+
+- `README.md`: the contract (load semantics, PostHog request/response rules,
+ error behavior) — read this before `src/`, which is also the crate doc.
+- `src/outbound/posthog.rs`: the real adapter.
+- `src/outbound/fake.rs`: the in-memory adapter for tests.
+
+## Scope
+
+- Owns: the `FeatureFlags` port, `FlagSnapshot`/`FlagValue`, and the PostHog
+ and fake adapters.
+- Not here: which flag name gates which feature — that lives at the call site.
+
+## Boundaries
+
+- Depends on: `macro_user_id`.
+- Used by: nothing yet (landed in #7985); a composition root wires an adapter
+ in before any caller depends on this crate.
+
+## Recipes
+
+- Add an outbound adapter: `src/domain.rs` (port) → `src/outbound/<name>.rs`
+ → `src/outbound.rs`.
+
+## Checks
+
+- `cargo test -p feature_flags`.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/feature_flags/CLAUDE.md b/crates/feature_flags/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/feature_flags/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/fig_engine/AGENTS.md b/crates/fig_engine/AGENTS.md
new file mode 100644
index 0000000000..7450df7c9d
--- /dev/null
+++ b/crates/fig_engine/AGENTS.md
@@ -0,0 +1,51 @@
+# fig_engine
+
+## What it is
+
+Backs the Design feature's `.fig` file viewer/editor: a from-scratch Figma
+file engine that decodes, expands instances, renders, inspects, edits, and
+saves `.fig` files, built both as native Rust and as wasm for the web viewer.
+
+## Start here
+
+- `README.md`: read this first — the file format, the module map ("Design"
+ section), editing/saving, collab, and the `fig_render` CLI are all explained
+ there in depth; this file only adds what the README doesn't.
+- `src/lib.rs`: the module list matches the README's "Design" table exactly.
+- `src/testing.rs`: the from-scratch kiwi encoder and test schema every test
+ builds files with — there is no third-party `.fig` data in the repo.
+
+## Scope
+
+- Owns: everything under `src/` — decode, scene, render, edit, export, save,
+ collab, library, prototypes.
+- Not here: the web app's viewer/editor UI and worker wiring →
+ `apps/web/src/lib/core/fig-engine`.
+
+## Recipes
+
+- Add an edit operation: `src/edit.rs` (`Op` variant) → the relevant
+ `src/edit/<area>.rs` → `src/save.rs` if it touches new fields →
+ `fig_render roundtrip` to check save fidelity.
+- Add an export format: `src/export.rs` → new `src/export/<format>.rs`.
+- Change decoded model fields: `src/model.rs` / `src/model/<area>.rs` →
+ `src/decode/<area>.rs` → `src/save.rs` (fields not modeled must survive a
+ save byte-for-byte).
+
+## Checks
+
+- `cargo test -p fig_engine`.
+- After a decode/edit/save change: `cargo run -p fig_engine --features cli
+ --release --bin fig_render -- roundtrip FILE.fig…` against local `.fig`
+ files (not committed — third-party).
+- Wasm build: `just build-fig-engine-wasm` from `apps/web`.
+
+## Gotchas
+
+- Regenerate committed fixtures after a model change:
+ `cargo test -p fig_engine --lib write_showcase_fixture -- --ignored` and
+ `write_prototype_fixture -- --ignored`; a test fails when they're stale.
+
+## Related
+
+- Docs: `README.md` (this crate's primary guide — read before editing)
diff --git a/crates/fig_engine/CLAUDE.md b/crates/fig_engine/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/fig_engine/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/folds/agent_fold/AGENTS.md b/crates/folds/agent_fold/AGENTS.md
new file mode 100644
index 0000000000..de184ebc4a
--- /dev/null
+++ b/crates/folds/agent_fold/AGENTS.md
@@ -0,0 +1,71 @@
+# agent_fold
+
+## What it is
+
+Core to the agent sessions feature: collapses an agent session's raw ACP/ARP
+protocol log into the renderable message vocabulary every caller (harness,
+web, exports) reads sessions through. Builds native (`rlib`) and as wasm
+(`cdylib`) for the browser.
+
+## How it works
+
+Raw log frames (`domain/log.rs`) go in; `domain/fold.rs` folds them, handling
+lifecycle and speculative state, and always succeeds (unaccounted frames are
+logged, not errored); `domain/model.rs` renderable messages come out, exposed
+to the browser via `inbound/wasm`.
+
+## Start here
+
+- `src/domain/fold.rs`: the fold itself — read its module doc first; it's
+ total by design (see "Why this cannot fail") and never errors on read.
+- `src/domain/model.rs`: the renderable vocabulary (`FoldedMessage`,
+ `ToolStatus`, …) folds produce.
+- `src/domain/log.rs`: the raw log vocabulary folds consume.
+- `src/domain/ports.rs`: `FoldedMessageRepo`, the driving port services call
+ directly — there is no HTTP adapter; only the browser gets `inbound/wasm`.
+- `src/testing/fixtures.rs` + `fixtures/`: hand-shaped and sanitized real
+ recordings shared by this crate's and downstream tests.
+
+## Scope
+
+- Owns: the fold, its model/log vocabularies, lifecycle and speculation
+ folding, and the wasm/wire adapters that carry the model to the browser.
+- Not here: per-harness quirks (Claude/Codex-specific normalization) →
+ `crates/folds/claude_fold`, `crates/folds/codex_fold`.
+
+## Boundaries
+
+- Depends on: `agent_runtime_protocol` (schema only, `default-features =
+ false` — no transport, which is what makes wasm possible).
+- Used by: `agent_harness_service`, `agent_session`, `agent_harness`,
+ `coding_agent_worker`, `lexical_client`, `agent_changes`, `webhook`, and both
+ harness-specific fold crates. Widely shared — check callers before changing
+ `domain/model.rs` or `domain/ports.rs`.
+
+## Recipes
+
+- Add a new message/event kind: `src/domain/log.rs` (raw shape) →
+ `src/domain/fold.rs` (fold logic) → `src/domain/model.rs` (renderable type)
+ → `src/inbound/wire.rs` if the browser needs it → `cargo run -p agent_fold
+ --bin export_types` to regenerate the TypeScript contract.
+- Debug a fold against a recorded session: `cargo run -p agent_fold --bin
+ fold_jsonl -- <path>.jsonl`.
+
+## Checks
+
+- `cargo test -p agent_fold`.
+- After changing `inbound/wire.rs` or exported `domain/model.rs` types:
+ `cargo run -p agent_fold --bin export_types` and commit the regenerated
+ TypeScript.
+
+## Gotchas
+
+- A frame the fold can't account for is logged at `WARN` via `FoldError`, not
+ returned as an error — `fold` must stay total (see `domain/fold.rs` docs).
+- `scripts/sanitize_recording.py` strips real-session fixtures before they
+ land under `fixtures/real/`; never commit an unsanitized recording.
+
+## Related
+
+- Skill: none dedicated; see `services/agent_harness_service` for how the
+ fold is composed into the harness.
diff --git a/crates/folds/agent_fold/CLAUDE.md b/crates/folds/agent_fold/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/folds/agent_fold/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/foreign_entity/AGENTS.md b/crates/foreign_entity/AGENTS.md
new file mode 100644
index 0000000000..c0fb0bf5b7
--- /dev/null
+++ b/crates/foreign_entity/AGENTS.md
@@ -0,0 +1,44 @@
+# foreign_entity
+
+## What it is
+
+Shared infrastructure used across many product features (GitHub PRs, Soup,
+documents, memory, AI tools): generic CRUD storage for records sourced from a
+third-party system, following the hexagonal architecture pattern.
+
+## Start here
+
+- `src/domain/models.rs`: `ForeignEntity`, `SourceId`, and the create/patch
+ shapes.
+- `src/domain/ports.rs` + `src/domain/service.rs`: the service and its
+ listing/query port.
+- `src/outbound/pg_foreign_entity_repo.rs`: the Postgres adapter.
+
+## Scope
+
+- Owns: the generic foreign-entity row (source id, owning entity, payload)
+ and its listing/filter query.
+- Not here: what a specific foreign entity's payload means (e.g. pull request
+ fields) → `crates/github_pull_requests`, which stores its typed columns on
+ top of this crate's rows.
+
+## Boundaries
+
+- Depends on: `entity_access` (ports), `item_filters`, `models_pagination`.
+- Used by: `github_pull_requests`, `github`, `soup`, `documents`, `memory`,
+ `ai_tools`, `document_storage_service`, `document_cognition_service`,
+ `authentication_service`, `mcp_service`.
+
+## Recipes
+
+- Add a new foreign entity source: the owning domain crate stores its typed
+ columns through `src/domain/ports.rs` → `src/outbound/pg_foreign_entity_repo.rs`
+ (shared query/listing logic lives here, not per-source).
+
+## Checks
+
+- `cargo test -p foreign_entity --all-features` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/foreign_entity/CLAUDE.md b/crates/foreign_entity/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/foreign_entity/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/forms/AGENTS.md b/crates/forms/AGENTS.md
new file mode 100644
index 0000000000..5e46cbd9dd
--- /dev/null
+++ b/crates/forms/AGENTS.md
@@ -0,0 +1,49 @@
+# forms
+
+## What it is
+
+Backs the Forms feature: questionnaires that are views of a database table.
+This crate owns form presentation, collaborative authoring, sharing, and the
+response ledger; answers land as rows of the table through the `databases`
+service.
+
+## Start here
+
+- `src/domain/service.rs`: the service — submodules are the use cases
+ (`answers`, `create`, `drafts`, `layout`, `lifecycle`, `sharing`, `submit`);
+ all authorization policy beyond receipt minting lives here.
+- `src/domain/authoring.rs`: deterministic authoring workflows and the layout
+ edit model — Loro owns live draft content, `src/domain/drafts.rs` is the
+ validated relational projection the repository stores.
+- `src/wiring.rs`: the one Postgres assembly every host builds from.
+- `src/inbound/axum_router.rs` / `src/inbound/toolset.rs`: HTTP router and AI
+ authoring tools.
+
+## Scope
+
+- Owns: form layout, authoring, sharing/audience, drafts, and submission
+ ledger. Answer storage itself is the referenced database table.
+- Not here: generic database row/column storage → `crates/databases`; the
+ Loro document mechanics → `crates/collab_surface`.
+
+## Boundaries
+
+- Depends on: `databases` (ports), `collab_surface` (outbound, ports),
+ `entity_access`, `models_forms`, `models_databases`, `macro_event_broker`.
+- Used by: `document_storage_service`, `ai_tools`.
+
+## Recipes
+
+- Add a layout field: `src/domain/authoring/models.rs` → `src/domain/authoring/edit.rs`
+ → `src/domain/authoring/validate.rs` → `src/outbound/collaborative_layout.rs`.
+- Add an AI authoring tool: `src/inbound/toolset.rs` → `src/domain/authoring/workflow.rs`.
+- Add a submission rule: `src/domain/service.rs` (`submit`/`answers` modules)
+ → `src/outbound/pg_forms_repo.rs`.
+
+## Checks
+
+- `cargo test -p forms --all-features` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Skills: `collab-surface-core`, `database-core` · Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/forms/CLAUDE.md b/crates/forms/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/forms/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/frecency/AGENTS.md b/crates/frecency/AGENTS.md
new file mode 100644
index 0000000000..638ef033b8
--- /dev/null
+++ b/crates/frecency/AGENTS.md
@@ -0,0 +1,43 @@
+# frecency
+
+## What it is
+
+Shared infrastructure for Search/Soup ranking and other item lists (used by
+soup, ai_tools, memory, channels, email, scheduled actions): frecency
+(frequency + recency) scoring, following the hexagonal architecture pattern.
+
+## Start here
+
+- `src/domain/models.rs`: the score model and decay parameters.
+- `src/domain/services.rs`: the scoring/ranking logic.
+- `src/outbound/postgres.rs`: the SQL-side scoring adapter (recursive CTEs via
+ the `recursion` crate).
+- `src/inbound/polling_aggregator.rs`: the polling path that aggregates and
+ persists scores.
+
+## Scope
+
+- Owns: frecency computation and its Postgres persistence/query adapter.
+- Not here: what gets ranked or how it's displayed — callers combine this
+ with their own entity filters.
+
+## Boundaries
+
+- Depends on: `filter_ast`, `item_filters`, `model-entity`.
+- Used by: `soup`, `ai_tools`, `memory`, `channels`, `email`,
+ `document_storage_service`, `connection_gateway`, `document_cognition_service`,
+ `scheduled_action`, `mcp_service`, `email_service`.
+
+## Recipes
+
+- Add a new signal to the score: `src/domain/models.rs` → `src/domain/services.rs`
+ → `src/outbound/postgres.rs`.
+
+## Checks
+
+- `cargo test -p frecency --all-features` (`SQLX_OFFLINE` unset).
+- `just integration_test` (DynamoDB-backed cases, from this directory).
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md`
diff --git a/crates/frecency/CLAUDE.md b/crates/frecency/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/frecency/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/fusionauth/AGENTS.md b/crates/fusionauth/AGENTS.md
new file mode 100644
index 0000000000..83986e88b1
--- /dev/null
+++ b/crates/fusionauth/AGENTS.md
@@ -0,0 +1,45 @@
+# fusionauth
+
+## What it is
+
+Backs the Authentication feature: a FusionAuth API client for
+OAuth/identity-provider login, user management, JWTs, and
+passwordless/password flows against the FusionAuth HTTP API.
+
+## Start here
+
+- `src/lib.rs`: `AuthedClient`/unauthenticated client and the crate-wide
+ `Result` alias — every module is a thin set of request builders over these.
+- `src/identity_provider.rs`: link/login/lookup/search/unlink for third-party
+ identity providers (Google, Microsoft, Apple).
+- `src/jwt.rs`, `src/oauth.rs`, `src/passwordless.rs`, `src/password.rs`: the
+ token and login flows.
+- `src/user.rs`: create/delete/get/register/verify.
+
+## Scope
+
+- Owns: typed request/response shapes and calls for FusionAuth's REST API.
+- Not here: Macro's own session/cookie handling or route wiring → the calling
+ service (`authentication_service`).
+
+## Boundaries
+
+- Depends on: nothing Macro-specific beyond `workspace-hack`; this is a plain
+ HTTP client crate.
+- Used by: `authentication_service`, `mcp_auth_proxy`, `mcp_service`,
+ `tooling/seed_cli`, `github` (for linking).
+
+## Recipes
+
+- Add a new FusionAuth endpoint: new `src/<area>.rs` (or a function in an
+ existing one) → `pub mod` it in `src/lib.rs` → `wiremock`-backed test next
+ to it (see `src/user/test.rs` for the pattern).
+
+## Checks
+
+- `cargo test -p fusionauth`.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md` (FusionAuth base URL/keys
+ are config, not hardcoded)
diff --git a/crates/fusionauth/CLAUDE.md b/crates/fusionauth/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/fusionauth/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/genai_telemetry/AGENTS.md b/crates/genai_telemetry/AGENTS.md
new file mode 100644
index 0000000000..a290c85235
--- /dev/null
+++ b/crates/genai_telemetry/AGENTS.md
@@ -0,0 +1,40 @@
+# genai_telemetry
+
+## What it is
+
+Supports the agent sessions feature's observability: adds `gen_ai.*`
+content/tool-definition attributes that Datadog LLM Observability needs on
+top of the structural spans `rig` already emits, shared by the AI toolset and
+agent loop.
+
+## Start here
+
+- `src/lib.rs`: read the crate doc first — it explains exactly what this adds
+ (content, tool definitions, session id) and why (`tracing` can't add fields
+ to spans another crate opened).
+- `src/content.rs`: `ContentPolicy`/`Limits` — whether/how much content capture
+ is allowed, and the bounding that keeps a 12-turn conversation from
+ re-sending itself on every span.
+- `src/span.rs`: `GenAiSpanExt`, the attribute setters that write to an
+ already-open span.
+- `src/messages.rs`: builders for the semconv JSON message/tool-definition shapes.
+
+## Scope
+
+- Owns: `gen_ai.*` attribute names/values, content bounding, and the setters
+ that attach them to spans opened elsewhere.
+- Not here: the spans themselves (`invoke_agent`, `chat`, `execute_tool`) —
+ those come from `rig`.
+
+## Boundaries
+
+- Depends on: `macro_env_var` (reads `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT`).
+- Used by: `agent`, `agent_inmem`, `agent_session`, `ai_toolset`.
+
+## Checks
+
+- `cargo test -p genai_telemetry`.
+
+## Related
+
+- Rules: `.agents/rules/observability.md`
diff --git a/crates/genai_telemetry/CLAUDE.md b/crates/genai_telemetry/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/genai_telemetry/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/git_patch/AGENTS.md b/crates/git_patch/AGENTS.md
new file mode 100644
index 0000000000..88a066bc4e
--- /dev/null
+++ b/crates/git_patch/AGENTS.md
@@ -0,0 +1,42 @@
+# git_patch
+
+## What it is
+
+Shared infrastructure for the agent sessions and GitHub integration features:
+parses git-style unified diffs into per-file facts, cuts them to a size
+budget, and builds the changeset-summary types both agent session changes
+and GitHub pull request changes read through, so a client sees the same
+status/line counts whichever produced the patch.
+
+## Start here
+
+- `src/patch.rs`: `parse_git_patch`, `budget_patch`, and the byte-budget
+ constants (`MAX_PATCH_BYTES`, `MAX_FILE_PATCH_BYTES`).
+- `src/model.rs`: `ChangedFile`, `FileChangeKind`, `ChangesetRange`, `GitRef`.
+- `src/wire.rs`: the wire/schema (`utoipa`, behind the `schema` feature) shape
+ for the summary a client decodes.
+
+## Scope
+
+- Owns: diff parsing and budgeting, and the changeset summary wire types.
+- Not here: where the diff comes from (git CLI, GitHub API) or what stores it
+ → `crates/github_pull_requests`, `crates/agent_changes`.
+
+## Boundaries
+
+- Depends on: nothing Macro-specific.
+- Used by: `github_pull_requests`, `agent_changes`.
+
+## Checks
+
+- `cargo test -p git_patch`.
+
+## Gotchas
+
+- `budget_patch` truncates per-file and overall — a parser change that
+ reorders when budgeting runs can silently change what a client sees as
+ "truncated" vs. complete.
+
+## Related
+
+- Rules: `.agents/rules/rust/code.md`
diff --git a/crates/git_patch/CLAUDE.md b/crates/git_patch/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/git_patch/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/github/AGENTS.md b/crates/github/AGENTS.md
new file mode 100644
index 0000000000..aef522e827
--- /dev/null
+++ b/crates/github/AGENTS.md
@@ -0,0 +1,60 @@
+# github
+
+## What it is
+
+Backs the GitHub integration used by agent sessions and document storage:
+GitHub account linking, the GitHub App install/webhook sync, and the OAuth
+link flow, following the hexagonal architecture pattern.
+
+## Start here
+
+- `src/domain/models.rs`: re-exports pull request domain types from
+ `github_pull_requests` alongside this crate's own link/installation/sync
+ models — most "GitHub" domain types actually live in that crate.
+- `src/inbound/github_sync_router.rs`: GitHub App install redirect, OAuth
+ callback, and the webhook handler.
+- `src/inbound/pull_request_index_router.rs`: the HTTP surface for indexed PRs.
+- `src/outbound/github_sync_client.rs`, `src/outbound/github_auth_client.rs`:
+ GitHub's own REST/App API clients.
+- `src/outbound/pg_github_repo.rs`, `src/outbound/pg_github_sync_repo.rs`: the
+ Postgres adapters for links and sync state.
+
+## Scope
+
+- Owns: account linking (`link` feature), the App installation/webhook sync
+ (`sync` feature), and the Axum router/webhook verification for both.
+- Not here: the pull request model, merge rules, and PR listing/service →
+ `crates/github_pull_requests`, which this crate re-exports and calls into.
+
+## Boundaries
+
+- Depends on: `github_pull_requests` (ports/schema), `foreign_entity`,
+ `documents`, `fusionauth`, `connection_gateway_client`, `macro_service_urls`,
+ `notification`/`model_notifications`.
+- Used by: `agent_harness_service`, `agent_harness`, `agent_egress`,
+ `document_storage_service`, `authentication_service`.
+
+## Recipes
+
+- Add a webhook event: `src/inbound/github_sync_router.rs` (dispatch) →
+ `src/domain/models.rs` (sync model) → `src/outbound/pg_github_sync_repo.rs`.
+- Add a new GitHub API call: `src/outbound/github_sync_client.rs` or
+ `github_auth_client.rs` → the domain service that needs it.
+
+## Checks
+
+- `cargo test -p github --all-features` (`SQLX_OFFLINE` unset).
+- `just check` (from this directory) runs `cargo check --all-features`.
+
+## Gotchas
+
+- Webhook signature verification uses `hmac`/`subtle` for constant-time
+ comparison — don't swap in a plain `==` when touching
+ `github_sync_router.rs`.
+- `GithubError::Forbidden`, `SetupUserNotLinked`, and `RepositoryUnavailable`
+ all map to the same 403 deliberately — don't let a response distinguish
+ "app not installed" from "installed somewhere you have no claim to".
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/security.md`
diff --git a/crates/github/CLAUDE.md b/crates/github/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/github/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/github_pull_requests/AGENTS.md b/crates/github_pull_requests/AGENTS.md
new file mode 100644
index 0000000000..630404e5b5
--- /dev/null
+++ b/crates/github_pull_requests/AGENTS.md
@@ -0,0 +1,49 @@
+# github_pull_requests
+
+## What it is
+
+Backs the GitHub integration's pull request surface (agent session
+changesets and PR review): the PR model, stored as `foreign_entity` records,
+the rules for merging refreshed GitHub data, and the service that writes and
+lists visible PRs.
+
+## Start here
+
+- `src/domain/service.rs`: submodules `index` (write/list/refresh) and
+ `changes` (`GithubPullRequestChangesServiceImpl` — the diff/changeset path
+ agent sessions use).
+- `src/domain/models.rs`: the PR model and merge rules for refreshed data.
+- `src/broker.rs`: event broker wiring for PR update events.
+- `src/outbound/pg_github_pull_request_repo.rs`: the typed-column Postgres
+ adapter over `foreign_entity`'s generic storage.
+- `src/outbound/s3_patch_store.rs`: diff/patch storage in S3 (`s3` feature).
+
+## Scope
+
+- Owns: the PR domain model, merge-on-refresh semantics, PR listing/filtering,
+ and the changeset/diff path.
+- Not here: GitHub App auth, webhook receipt, and account linking →
+ `crates/github`, which depends on this crate, not the reverse.
+
+## Boundaries
+
+- Depends on: `foreign_entity` (ports/outbound), `git_patch` (diff parsing/schema).
+- Used by: `github` (re-exports this crate's models), `soup`, `soup_realtime`,
+ `agent_changes`, `ai_tools`, `memory`, `document_storage_service`,
+ `document_cognition_service`, `authentication_service`, `mcp_service`,
+ `agent_harness_service`.
+
+## Recipes
+
+- Add a typed PR column: `src/domain/models.rs` → `src/outbound/pg_github_pull_request_repo.rs`
+ → the merge rule in `src/domain/models.rs` that decides how it's refreshed.
+- Add a changeset/diff capability: `src/domain/service.rs` (`changes` module)
+ → `src/outbound/s3_patch_store.rs` → `git_patch` if the diff shape changes.
+
+## Checks
+
+- `cargo test -p github_pull_requests --all-features` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/github_pull_requests/CLAUDE.md b/crates/github_pull_requests/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/github_pull_requests/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/gmail_client/AGENTS.md b/crates/gmail_client/AGENTS.md
new file mode 100644
index 0000000000..6edc3a93b9
--- /dev/null
+++ b/crates/gmail_client/AGENTS.md
@@ -0,0 +1,48 @@
+# gmail_client
+
+## What it is
+
+Backs the Email feature's Gmail sync: a thin Gmail API client, `GmailClient`,
+wrapping per-area modules (messages, threads, labels, filters, history,
+contacts, watch) behind a single public facade; most modules are
+`pub(crate)`.
+
+## Start here
+
+- `src/lib.rs`: `GmailClient`, its constructors (`new` vs. `new_with_urls` for
+ injectable endpoints in tests), and `sanitize_error_body` — every error body
+ is redacted (emails) and length-capped before it can reach logs.
+- `src/auth.rs`: Google JWT verification for push notifications.
+- `src/watch.rs`: Gmail push notification (`users.watch`) setup.
+- `src/test.rs` + each module's own `test.rs`: `wiremock`-backed HTTP tests,
+ one server per test via `new_with_urls`.
+
+## Scope
+
+- Owns: typed request/response calls against the Gmail REST API.
+- Not here: Macro's email domain model or sync orchestration →
+ `models_email` (the wire types this crate returns), `email_service`.
+
+## Boundaries
+
+- Depends on: `models_email` (response/request types).
+- Used by: `email_service`, `email_api_client`.
+
+## Recipes
+
+- Add a new Gmail endpoint: new or existing `src/<area>.rs` function →
+ `pub(crate) mod` it in `src/lib.rs` → re-export only what callers need →
+ `wiremock` test in `src/<area>/test.rs`.
+
+## Checks
+
+- `cargo test -p gmail_client`.
+
+## Gotchas
+
+- Any new error path should go through `sanitize_error_body` (or an
+ equivalent) before logging — Gmail error bodies can contain email addresses.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md`
diff --git a/crates/gmail_client/CLAUDE.md b/crates/gmail_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/gmail_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_activity/AGENTS.md b/crates/graphql_activity/AGENTS.md
new file mode 100644
index 0000000000..4df2b63af8
--- /dev/null
+++ b/crates/graphql_activity/AGENTS.md
@@ -0,0 +1,44 @@
+# graphql_activity
+
+## What it is
+
+Backs the Activity feed feature across the app: a GraphQL adapter exposing
+three read surfaces over the `activity_events` log — the viewer's feed, a
+trailing-year overview, a per-entity `activity` edge (batched via
+DataLoader) — plus database/form timelines and a realtime subscription.
+
+## Start here
+
+- `src/lib.rs`: read the crate doc — it lists exactly which resolver answers
+ which surface and why entities carry only `entityType`/`entityId`
+ references (clients resolve names from their Soup cache).
+- `src/loaders.rs`: `EntityActivityLoader` — the batched per-entity edge;
+ touch this when activity needs to appear on a new Soup entity type.
+- `src/feed.rs` / `src/overview.rs`: the viewer feed and yearly aggregate.
+- `src/timeline.rs`: by-id, access-checked timelines for databases/forms
+ (not Soup items, so not loader-batched).
+- `src/subscriptions.rs`: the realtime `activityUpdates` subscription.
+
+## Scope
+
+- Owns: GraphQL objects/resolvers over activity; not the event log itself →
+ `crates/activity`.
+
+## Boundaries
+
+- Depends on: `activity` (realtime feature), `entity_access`, `graphql_common`.
+- Used by: `complete_graph`.
+
+## Recipes
+
+- Add activity to a new Soup entity: `src/loaders.rs` (reader) →
+ `crate::activity` port implementation for that entity → wire the edge on
+ the entity's GraphQL object in `complete_graph`.
+
+## Checks
+
+- `cargo test -p graphql_activity`.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/graphql_activity/CLAUDE.md b/crates/graphql_activity/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_activity/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_calendar/AGENTS.md b/crates/graphql_calendar/AGENTS.md
new file mode 100644
index 0000000000..68692d335d
--- /dev/null
+++ b/crates/graphql_calendar/AGENTS.md
@@ -0,0 +1,43 @@
+# graphql_calendar
+
+## What it is
+
+Backs the Calendar feature: the GraphQL inbound adapter exposing typed
+calendar/event/occurrence objects, reads, mutations, and the authenticated
+user's calendar query root.
+
+## Start here
+
+- `src/objects.rs`: the typed GraphQL objects (event time variants, attendee,
+ reminders, out-of-office, sync status) — the richest part of the schema.
+- `src/reads.rs` + `src/user_query.rs`: `CalendarGraphqlContext` and the
+ user-facing query fields (occurrence ranges, changes/watermarks).
+- `src/mutation.rs` + `src/inputs.rs`: typed mutation inputs/payloads with
+ explicit error codes (see `bad_input`/`unavailable` in `src/lib.rs`).
+- `src/writes.rs`: `CalendarGraphqlMutationContext`.
+
+## Scope
+
+- Owns: the GraphQL shape over calendar data.
+- Not here: calendar domain logic and Google Calendar sync →
+ `crates/calendar_events`, `crates/calendar_scheduling`.
+
+## Boundaries
+
+- Depends on: `calendar_events`, `graphql_common`.
+- Used by: `complete_graph`, `document_storage_service`.
+
+## Recipes
+
+- Add a mutation: `src/inputs.rs` (input type) → `src/mutation.rs` (field +
+ typed error codes) → `src/writes.rs` (context plumbing) → `calendar_events`
+ if the domain operation doesn't exist yet.
+- Add a read field: `src/objects.rs` → `src/reads.rs` / `src/user_query.rs`.
+
+## Checks
+
+- `cargo test -p graphql_calendar`.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/graphql_calendar/CLAUDE.md b/crates/graphql_calendar/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_calendar/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_common/AGENTS.md b/crates/graphql_common/AGENTS.md
new file mode 100644
index 0000000000..381fa52a10
--- /dev/null
+++ b/crates/graphql_common/AGENTS.md
@@ -0,0 +1,49 @@
+# graphql_common
+
+## What it is
+
+Shared infrastructure for every product feature's GraphQL adapter crate:
+request-scoped extractor context, filter-input conversion, and cross-domain
+schema types (entity type, owner type, property filters).
+
+## Start here
+
+- `src/request_context.rs` + `src/extract.rs`: `GraphqlRequestParts`, the
+ per-request context every resolver pulls from, and its Axum extraction.
+- `src/authorization.rs`: `require_authenticated_user` /
+ `require_authorized_user` — the two checks resolvers call before touching data.
+- `src/filter_input.rs`: `IntoFilterExpr`, `parse_id`/`parse_uuid`/`parse_macro_user_id`
+ — shared GraphQL-input-to-domain-type conversions.
+- `src/entity_type.rs`, `src/owner_type.rs`, `src/property_filter.rs`: schema
+ types reused across domain crates so two adapters don't define incompatible
+ GraphQL shapes for the same concept.
+
+## Scope
+
+- Owns: cross-domain GraphQL conventions — context, auth checks, filter/limit
+ input parsing, shared entity/owner/property types.
+- Not here: any one domain's resolvers or objects → `crates/graphql_<domain>`.
+
+## Boundaries
+
+- Depends on: `macro_authorization` (axum), `filter_ast`, `item_filters`,
+ `model-entity`, `model_owner`, `models_properties`.
+- Used by: every `graphql_*` domain adapter crate (favorite, initiative,
+ calendar, email, notification, soup_filter_input, entity_mutation,
+ properties, crm, soup, channel, work_feed, activity) and `complete_graph`
+ (the schema that composes them all).
+
+## Recipes
+
+- Add a shared filter/input type: `src/property_filter.rs` or
+ `src/filter_input.rs` → used from the domain crate's input types.
+- Change the request context: `src/request_context.rs` → `src/extract.rs` →
+ every domain crate that reads a new field from it.
+
+## Checks
+
+- `cargo test -p graphql_common`.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/security.md`
diff --git a/crates/graphql_common/CLAUDE.md b/crates/graphql_common/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_common/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_crm/AGENTS.md b/crates/graphql_crm/AGENTS.md
new file mode 100644
index 0000000000..ee3a1ce2e3
--- /dev/null
+++ b/crates/graphql_crm/AGENTS.md
@@ -0,0 +1,41 @@
+# graphql_crm
+
+## What it is
+
+Backs the CRM feature: the typed GraphQL inbound adapter for CRM pipeline
+records (rows that reference a company or contact), composed onto their Soup
+entities.
+
+## Start here
+
+- `src/objects.rs`: `GraphqlCrmPipeline`/`GraphqlCrmPipelineEntry` and related
+ typed objects.
+- `src/loaders.rs`: `PipelineEntriesLoader` — batches pipeline entries by
+ record (company/contact) across a query.
+- `src/context.rs`: `CrmGraphqlContext` and the object-safe `CrmPipelineApi`
+ forwarding trait over `crm::domain::pipelines::PipelineService`.
+
+## Scope
+
+- Owns: the GraphQL shape over CRM pipeline entries.
+- Not here: pipeline domain logic and storage → `crates/crm` (built on
+ `crates/databases`).
+
+## Boundaries
+
+- Depends on: `crm` (ports), `databases` (ports), `entity_access` (ports),
+ `graphql_common`, `graphql_properties`.
+- Used by: `complete_graph`, `document_storage_service`.
+
+## Recipes
+
+- Add a pipeline field: `crm::domain::pipelines` (domain) → `src/objects.rs`
+ → `src/loaders.rs` if it needs batched loading → `src/context.rs`.
+
+## Checks
+
+- `cargo test -p graphql_crm`.
+
+## Related
+
+- Skill: `database-core` · Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/graphql_crm/CLAUDE.md b/crates/graphql_crm/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_crm/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_email/AGENTS.md b/crates/graphql_email/AGENTS.md
new file mode 100644
index 0000000000..fd108b787b
--- /dev/null
+++ b/crates/graphql_email/AGENTS.md
@@ -0,0 +1,45 @@
+# graphql_email
+
+## What it is
+
+Backs the Email feature: the GraphQL inbound adapter exposing message object
+types, the `EmailThread` edge resolvers, and draft mutations.
+
+## Start here
+
+- `src/objects.rs`: `GraphqlSoupEmailMessage`, `GraphqlMailPreviewMessage`, and
+ the loaders that fetch message bodies vs. previews.
+- `src/mutation.rs`: `GraphqlEmailMutation` (save/delete draft, mark seen/unread,
+ update label).
+- `src/loaders.rs`: DataLoader batching for thread metadata, mail projection,
+ and content, keyed by thread/message id.
+- `src/user_query.rs` / `src/user_objects.rs`: viewer-scoped email settings
+ (labels, links, sync status) separate from message content.
+
+## Scope
+
+- Owns: GraphQL types and resolvers for email messages, threads, drafts, and
+ viewer email settings.
+- Not here: email sync, sending, and storage — `crates/email`; thread
+ membership in Soup → `crates/graphql_soup`.
+
+## Boundaries
+
+- Depends on: `email` (ports only), `email_utils`, `entity_access`,
+ `graphql_common`.
+- Used by: `complete_graph` (schema composition), `graphql_soup` (email edge).
+
+## Recipes
+
+- Add a field to a message/thread type: `src/objects.rs` → its loader in
+ `src/loaders.rs` if the field needs a new fetch.
+- Add a draft mutation: `src/mutation.rs` → `EmailMutationService` port (in
+ `email`) → the service implementation that backs it.
+
+## Checks
+
+- `cargo test -p graphql_email` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/graphql_email/CLAUDE.md b/crates/graphql_email/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_email/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_favorite/AGENTS.md b/crates/graphql_favorite/AGENTS.md
new file mode 100644
index 0000000000..60d3b2a972
--- /dev/null
+++ b/crates/graphql_favorite/AGENTS.md
@@ -0,0 +1,41 @@
+# graphql_favorite
+
+## What it is
+
+Backs the Favorites feature (Soup sidebar pinning): the GraphQL inbound
+adapter exposing ordered favorite objects, user-scoped queries/mutations, and
+the DataLoader-backed current-viewer favorite edge.
+
+## Start here
+
+- `src/objects.rs`: `GraphqlFavorite`.
+- `src/queries.rs`: `resolve_favorites`, `FavoritesFilterInput`.
+- `src/mutations.rs`: `FavoriteMutationRoot`, `ReorderFavoritesInput`.
+- `src/loaders.rs`: `EntityFavoriteLoader` — the per-entity "is this
+ favorited/what position" edge used from other GraphQL object types.
+
+## Scope
+
+- Owns: GraphQL types/resolvers for favorites and the favorite edge other
+ object types embed.
+- Not here: favorite storage and ordering logic → `crates/favorites`.
+
+## Boundaries
+
+- Depends on: `favorites` (ports only), `entity_mutation`,
+ `graphql_entity_mutation`, `graphql_soup`, `graphql_common`.
+- Used by: `complete_graph` (schema composition).
+
+## Recipes
+
+- Add a favorite field: `src/objects.rs` → `src/loaders.rs` if it needs a new
+ batched fetch.
+- Add a mutation: `src/mutations.rs` → the `favorites` domain port it calls.
+
+## Checks
+
+- `cargo test -p graphql_favorite` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/graphql_favorite/CLAUDE.md b/crates/graphql_favorite/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_favorite/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_initiative/AGENTS.md b/crates/graphql_initiative/AGENTS.md
new file mode 100644
index 0000000000..233d75a589
--- /dev/null
+++ b/crates/graphql_initiative/AGENTS.md
@@ -0,0 +1,45 @@
+# graphql_initiative
+
+## What it is
+
+Backs the Initiatives feature (named task groupings): the typed GraphQL
+inbound adapter exposing initiative queries, mutations, and loaders.
+
+## Start here
+
+- `src/context.rs`: `InitiativeGraphqlContext` and `InitiativeAuthorizer` —
+ how resolvers reach the `initiative` domain service.
+- `src/query.rs` / `src/mutation.rs`: `resolve_initiative`,
+ `InitiativeMutationRoot`.
+- `src/loaders.rs`: `InitiativeSummaryLoader` / `InitiativeDetailLoader` —
+ batched initiative fetches for Soup and detail views.
+- `src/lib.rs` `graphql_error`: maps `InitiativeError` to GraphQL error codes
+ (`NOT_FOUND`, `FORBIDDEN`, `BAD_USER_INPUT`, `CONFLICT`) — follow this
+ pattern rather than returning a bare `async_graphql::Error`.
+
+## Scope
+
+- Owns: GraphQL types, queries, mutations, and loaders for initiatives.
+- Not here: initiative lifecycle, assignment, and storage → `crates/initiative`;
+ initiative properties → `crates/graphql_properties`.
+
+## Boundaries
+
+- Depends on: `initiative` (ports only), `graphql_properties`, `graphql_soup`,
+ `graphql_permission`, `models_permissions`.
+- Used by: `complete_graph` (schema composition).
+
+## Recipes
+
+- Add a query field: `src/query.rs` → `src/loaders.rs` if it needs a new
+ batched fetch → `src/objects.rs`.
+- Add a mutation: `src/mutation.rs` → the `initiative::domain` port it calls →
+ `graphql_error` if it introduces a new `InitiativeError` variant.
+
+## Checks
+
+- `cargo test -p graphql_initiative` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/graphql_initiative/CLAUDE.md b/crates/graphql_initiative/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_initiative/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_notification/AGENTS.md b/crates/graphql_notification/AGENTS.md
new file mode 100644
index 0000000000..d062c39b43
--- /dev/null
+++ b/crates/graphql_notification/AGENTS.md
@@ -0,0 +1,45 @@
+# graphql_notification
+
+## What it is
+
+Backs the Notifications feature: the GraphQL inbound adapter exposing the
+notification object type, the DataLoader-backed entity notification edge,
+mutations, and the realtime subscription.
+
+## Start here
+
+- `src/objects.rs`: `GraphqlNotification`, `load_entity_notifications` — the
+ edge most other GraphQL object types embed.
+- `src/notification_event.rs` + `src/notification_event/*.rs`: typed
+ `GraphqlNotifEvent` payloads per source (CRM discussion, initiative
+ discussion, ...) — add a new file here per event kind.
+- `src/subscriptions.rs`: `workFeedUpdates`-style realtime notification push.
+- `src/mutations.rs`: mark read/unread for an entity or explicit id set.
+
+## Scope
+
+- Owns: GraphQL types/resolvers/subscriptions for notifications and the
+ notification edge.
+- Not here: notification generation, storage, and delivery → `crates/notification`,
+ `crates/notification_state`.
+
+## Boundaries
+
+- Depends on: `notification`, `notification_state` (graphql feature),
+ `model_notifications`, `graphql_common`.
+- Used by: `complete_graph` (schema composition), `graphql_work_feed`.
+
+## Recipes
+
+- Add a new notification event payload: `crates/notification` (domain event)
+ → `src/notification_event/<kind>.rs` → wire it into
+ `src/notification_event.rs`.
+- Add a mutation: `src/mutations.rs` → the `notification` domain port.
+
+## Checks
+
+- `cargo test -p graphql_notification` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/graphql_notification/CLAUDE.md b/crates/graphql_notification/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_notification/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_properties/AGENTS.md b/crates/graphql_properties/AGENTS.md
new file mode 100644
index 0000000000..4d4e6633d8
--- /dev/null
+++ b/crates/graphql_properties/AGENTS.md
@@ -0,0 +1,48 @@
+# graphql_properties
+
+## What it is
+
+Shared infrastructure for features that attach custom properties to entities
+(CRM, Initiatives): the GraphQL inbound adapter exposing property object
+types, definitions, filter inputs, and the DataLoader-backed entity property
+edge.
+
+## Start here
+
+- `src/objects.rs`: `GraphqlProperty`, per-data-type value types
+ (`GraphqlStringPropertyValue`, `GraphqlNumberPropertyValue`, ...), and
+ `load_entity_properties` — the edge embedded by other object types.
+- `src/definitions.rs`: `GraphqlPropertyDefinition`, option values — the schema
+ side (what properties exist), as opposed to `objects.rs` (values set on an
+ entity).
+- `src/mutations.rs`: `PropertiesMutationRoot` — setting/clearing a property
+ value on an entity.
+- `src/loaders.rs`: `EntityPropertiesLoader` batching.
+
+## Scope
+
+- Owns: GraphQL types/resolvers for property definitions and values.
+- Not here: property storage, selectable-option management, and filter
+ evaluation → `crates/properties`, `crates/models_properties`.
+
+## Boundaries
+
+- Depends on: `properties` (ports only), `models_properties`, `entity_access`,
+ `graphql_common` (re-exports its filter-expr types).
+- Used by: `complete_graph`, `graphql_initiative`, `graphql_crm`.
+
+## Recipes
+
+- Add a property data type's GraphQL value: `src/objects.rs` (value type) →
+ `src/definitions.rs` (option/definition shape if selectable) →
+ `src/mutations.rs` (`GraphqlSetPropertyValue` variant).
+- Add a field to property definitions: `src/definitions.rs` →
+ `load_property_definitions`.
+
+## Checks
+
+- `cargo test -p graphql_properties` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/graphql_properties/CLAUDE.md b/crates/graphql_properties/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_properties/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_scheduled_action/AGENTS.md b/crates/graphql_scheduled_action/AGENTS.md
new file mode 100644
index 0000000000..a323730f02
--- /dev/null
+++ b/crates/graphql_scheduled_action/AGENTS.md
@@ -0,0 +1,39 @@
+# graphql_scheduled_action
+
+## What it is
+
+Backs the AI routines (scheduled actions) feature: the GraphQL inbound
+adapter for listing `ScheduledAction` records. Read-only: no mutations.
+
+## Start here
+
+- `src/query.rs`: `resolve_scheduled_actions`.
+- `src/objects.rs`: `GraphqlScheduledAction`.
+- `src/context.rs`: `ScheduledActionGraphqlContext`.
+- `src/lib.rs` `unavailable`: wraps a `rootcause::Report` into a generic
+ `INTERNAL_SERVER_ERROR` GraphQL error without leaking details.
+
+## Scope
+
+- Owns: GraphQL types/query for listing scheduled actions.
+- Not here: routine scheduling, triggers, and execution →
+ `services/scheduled_action`.
+
+## Boundaries
+
+- Depends on: `scheduled_action` (the service crate, not a ports-only domain
+ crate — note this is the one `graphql_*` crate reaching into a `services/`
+ path).
+- Used by: `complete_graph` (schema composition).
+
+## Recipes
+
+- Add a field to the listing: `src/objects.rs` → `src/query.rs`.
+
+## Checks
+
+- `cargo test -p graphql_scheduled_action` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/graphql_scheduled_action/CLAUDE.md b/crates/graphql_scheduled_action/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_scheduled_action/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_soup/AGENTS.md b/crates/graphql_soup/AGENTS.md
index 61eb7aff05..836bde3000 100644
--- a/crates/graphql_soup/AGENTS.md
+++ b/crates/graphql_soup/AGENTS.md
@@ -1,7 +1,9 @@
# graphql_soup
-This crate provides the soup-domain GraphQL wrapper types. The composed
-schema (root query, viewer, SDL export) lives in `complete_graph` — see
-`../complete_graph/AGENTS.md` for the schema conventions (presence-of-`id`
-normalized-cache rules and the viewer pattern), which apply to every type
-defined here.
+## What it is
+
+Backs the Soup feature (the app's unified entity search/home surface): the
+soup-domain GraphQL wrapper types. The composed schema (root query, viewer,
+SDL export) lives in `complete_graph` — see `../complete_graph/AGENTS.md` for
+the schema conventions (presence-of-`id` normalized-cache rules and the
+viewer pattern), which apply to every type defined here.
diff --git a/crates/graphql_soup/CLAUDE.md b/crates/graphql_soup/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_soup/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/graphql_work_feed/AGENTS.md b/crates/graphql_work_feed/AGENTS.md
new file mode 100644
index 0000000000..95c4672807
--- /dev/null
+++ b/crates/graphql_work_feed/AGENTS.md
@@ -0,0 +1,43 @@
+# graphql_work_feed
+
+## What it is
+
+Belongs to the work feed feature: a viewer's aggregated feed of tasks and
+items needing attention. This crate is the GraphQL inbound adapter exposing
+the `workFeed` page, done/undo mutations, and the `workFeedUpdates`
+subscription.
+
+## Start here
+
+- `src/query.rs`: `resolve_work_feed`.
+- `src/objects.rs`: `GraphqlWorkFeedPage`, `GraphqlWorkFeedEntry`,
+ `GraphqlWorkFeedItem`, `GraphqlWorkFeedStack`, `GraphqlWorkFeedPatch`.
+- `src/mutations.rs`: mark-done / undo-done mutations.
+- `src/subscriptions.rs`: `WorkFeedSubscriptionRoot` — realtime patches.
+- `src/context.rs`: `WorkFeedGraphqlContext`, `WorkFeedViewerResolver`.
+
+## Scope
+
+- Owns: GraphQL types/resolvers/subscription for the work feed page.
+- Not here: feed composition and item ranking → `crates/work_feed`;
+ notification content → `crates/graphql_notification`.
+
+## Boundaries
+
+- Depends on: `work_feed`, `graphql_notification`, `graphql_soup`,
+ `entity_access` (inbound feature), `graphql_common`.
+- Used by: `complete_graph` (schema composition).
+
+## Recipes
+
+- Add a feed item field: `src/objects.rs` → `src/query.rs` if it needs new
+ input scoping (`src/inputs.rs`).
+- Add a mutation: `src/mutations.rs` → `work_feed` domain port.
+
+## Checks
+
+- `cargo test -p graphql_work_feed` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/graphql_work_feed/CLAUDE.md b/crates/graphql_work_feed/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/graphql_work_feed/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/gtm_invite/AGENTS.md b/crates/gtm_invite/AGENTS.md
new file mode 100644
index 0000000000..f8be33146f
--- /dev/null
+++ b/crates/gtm_invite/AGENTS.md
@@ -0,0 +1,46 @@
+# gtm_invite
+
+## What it is
+
+Belongs to growth/GTM tooling: personal, time-limited signup links Macro
+staff create for prospects. Redeeming one attributes the new account to the
+staff member and carries a promotional first month of Premium through
+checkout.
+
+## Start here
+
+- `src/domain/service.rs`: create/redeem/revoke/list link lifecycle.
+- `src/domain/ports.rs` + `src/domain/models.rs`: the repo port and link model.
+- `src/inbound/axum_router/`: one file per route (`create_link`, `get_offer`,
+ `redeem_link`, `resolve_link`, `revoke_link`, `list_links`); `gtm_macro_staff.rs`
+ gates routes to Macro staff.
+- `src/outbound/pg_gtm_invite_repo.rs`: the Postgres adapter.
+
+## Scope
+
+- Owns: GTM invite link creation, redemption, and the staff dashboard API.
+- Not here: checkout's application of the promotional credit, or account
+ creation itself.
+
+## Boundaries
+
+- Depends on: `macro_authorization` (axum), `rate_limit` (axum).
+- Used by: `services/authentication_service`, which mounts the router in its
+ `src/api.rs` and lists it in `src/api/swagger.rs`.
+
+## Recipes
+
+- Add a route: `src/domain/ports.rs` (if new repo behavior) →
+ `src/domain/service.rs` → `src/inbound/axum_router/<name>.rs` →
+ `src/inbound/axum_router.rs`.
+- Change persistence: `src/outbound/pg_gtm_invite_repo.rs` → its `test.rs`.
+
+## Checks
+
+- `cargo test -p gtm_invite` (`SQLX_OFFLINE` unset).
+- `nix develop --command just prepare_db` from the repo root after schema changes.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/security.md`
+- Skill: `cloud-storage-hexagonal-architecture`
diff --git a/crates/gtm_invite/CLAUDE.md b/crates/gtm_invite/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/gtm_invite/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/harnesses/AGENTS.md b/crates/harnesses/AGENTS.md
new file mode 100644
index 0000000000..bca58b4bee
--- /dev/null
+++ b/crates/harnesses/AGENTS.md
@@ -0,0 +1,45 @@
+# harnesses
+
+## What it is
+
+Belongs to agent sessions: registration for user-run agent harnesses
+(macrod). Owns device-code pairing (create, approve, claim), the harness
+list the settings UI renders, revocation, and the bound-agent listing the
+daemon reconciles its webhook feed from.
+
+## Start here
+
+- `src/domain/service.rs`: pairing, listing, revocation logic.
+- `src/domain/tokens.rs`: harness token minting/verification
+ (`constant_time_eq` comparison — don't swap in a non-constant-time check).
+- `src/domain/ports.rs` + `src/domain/models.rs`: repo port and harness model.
+- `src/inbound/axum_router.rs`: the HTTP surface.
+- `src/outbound/pg_harness_repo.rs`: the Postgres adapter.
+
+## Scope
+
+- Owns: harness registration, pairing, and the agent-binding list.
+- Not here: running an agent session or the ACP protocol itself →
+ `crates/agent_session`, `coding_agent_worker`.
+
+## Boundaries
+
+- Depends on: `harness_id`, `harness_token`, `bot_id`, `macro_authorization`.
+- Used by: `coding_agent_worker`.
+
+## Recipes
+
+- Add a registration field or state: `src/domain/models.rs` →
+ `src/domain/service.rs` → `src/outbound/pg_harness_repo.rs` →
+ `src/inbound/axum_router.rs`.
+- Change token scope/verification: `src/domain/tokens.rs` → its callers in
+ `src/domain/service.rs`.
+
+## Checks
+
+- `cargo test -p harnesses` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/security.md`
+- Skill: `cloud-storage-hexagonal-architecture`
diff --git a/crates/harnesses/CLAUDE.md b/crates/harnesses/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/harnesses/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/image_generation/AGENTS.md b/crates/image_generation/AGENTS.md
new file mode 100644
index 0000000000..c086a0b777
--- /dev/null
+++ b/crates/image_generation/AGENTS.md
@@ -0,0 +1,49 @@
+# image_generation
+
+## What it is
+
+Belongs to AI tools: generates images from a prompt (with up to three
+reference images), stores them as static files, and exposes the flow through
+an AI toolset (`GenerateImage`).
+
+## Start here
+
+- `README.md`: the request flow (reference resolution → provider → store) and
+ usage-attribution rules — read this first, it's accurate and current.
+- `src/domain/service.rs`: `ImageGenerationService` — validates the prompt,
+ resolves up to three reference images, calls the provider, saves the result.
+- `src/domain/ports.rs`: `ImageGenerator`, `ImageReferenceReader`, `ImageStore`
+ — the three seams a host composes.
+- `src/outbound/gemini.rs`: the Gemini provider adapter (records
+ `usageMetadata` before decode/save so cost survives failures).
+- `src/outbound/static_files.rs`: `StaticFileImageStore`.
+- `src/inbound/toolset/generate_image.rs`: the AI toolset entry point.
+
+## Scope
+
+- Owns: image generation orchestration, reference resolution, and the toolset
+ wrapper.
+- Not here: provider composition (which `ImageGenerator`/`ImageReferenceReader`
+ to use) — that's `ai_tools`, the host crate.
+
+## Boundaries
+
+- Depends on: `ai_toolset`, `ai_usage`, `attachment`, `lexical_client`,
+ `static_file_service_client`.
+- Used by: `ai_tools` (composes providers and wires the toolset).
+
+## Recipes
+
+- Add a reference source: implement `ImageReferenceReader` →
+ `src/outbound/references.rs` → wire it in the composing host (`ai_tools`).
+- Add a new provider: implement `ImageGenerator` → `src/outbound/<provider>.rs`
+ → wire it in `ai_tools`.
+
+## Checks
+
+- `cargo test -p image_generation`.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/code.md`
+ (GenAI telemetry/usage rules)
diff --git a/crates/image_generation/CLAUDE.md b/crates/image_generation/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/image_generation/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/import/AGENTS.md b/crates/import/AGENTS.md
new file mode 100644
index 0000000000..06953e1436
--- /dev/null
+++ b/crates/import/AGENTS.md
@@ -0,0 +1,54 @@
+# import
+
+## What it is
+
+Belongs to onboarding and AI chat: the import pipeline tracking external
+items (Linear issues, Notion pages, Slack channels) as they're discovered,
+accepted, and copied into Macro entities. Host-agnostic — onboarding
+(`/setup`) and AI chat both drive the same primitives, distinguished only by
+the `initiator` recorded on each row.
+
+Not to be confused with `crates/foreign_entity`: foreign entities stay live in
+the external system; an `ImportEntity` here is a ledger row for an item being
+copied in, moving `staged` → `importing` → `imported` (or `discarded`).
+
+## Start here
+
+- `src/domain/models.rs`: `ImportEntity` and its state machine — read the
+ module doc comment for the staged/importing/imported/discarded distinction.
+- `src/domain/service.rs` + `src/domain/service/admission.rs`: discovery and
+ acceptance logic.
+- `src/outbound/mcp_slack_source.rs`: Slack discovery via MCP tool calls, with
+ `fixtures/*.json` backing its tests.
+- `src/inbound/toolset.rs`: the AI-chat-facing import tools.
+- `src/inbound/axum_router.rs`: the `/setup` onboarding-facing routes.
+
+## Scope
+
+- Owns: the import ledger, discovery/admission logic, and both the
+ onboarding and AI-chat entry points into it.
+- Not here: live references to external items that never get copied in →
+ `crates/foreign_entity`.
+
+## Boundaries
+
+- Depends on: `ai_toolset`, `ai_usage`, `ai_billing`, `connection_gateway_client`,
+ `mcp_select`, `properties`.
+- Used by: `onboarding`, `ai_tools`, `slack_integration`.
+
+## Recipes
+
+- Add an import source: `src/outbound/<source>.rs` (implement the source port)
+ → `src/source_binding.rs` → `src/domain/service.rs`.
+- Add a toolset action: `src/inbound/toolset.rs` → `src/domain/service.rs`.
+- Add an onboarding route: `src/inbound/axum_router.rs` →
+ `src/domain/service.rs`.
+
+## Checks
+
+- `cargo test -p import` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
+- Skill: `cloud-storage-hexagonal-architecture`
diff --git a/crates/import/CLAUDE.md b/crates/import/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/import/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/import/src/domain/models.rs b/crates/import/src/domain/models.rs
index 496bb2b8fe..81e67c512d 100644
--- a/crates/import/src/domain/models.rs
+++ b/crates/import/src/domain/models.rs
@@ -53,7 +53,7 @@ impl ImportSource {
match self {
ImportSource::Linear => &["linear"],
ImportSource::Notion => &["notion"],
- // Keep the canonical fallback from docs/SLACK_LIVE_CHANNEL_IMPORT.md
+ // Keep the canonical fallback from docs/runbooks/slack-live-channel-import.md
// until live verification supports switching to `slack_v2`.
ImportSource::Slack => &["slack", "slack_v2"],
}
diff --git a/crates/initiative/AGENTS.md b/crates/initiative/AGENTS.md
new file mode 100644
index 0000000000..8b7216bec8
--- /dev/null
+++ b/crates/initiative/AGENTS.md
@@ -0,0 +1,51 @@
+# initiative
+
+## What it is
+
+Belongs to tasks/project management: initiatives are a named grouping of
+tasks. This crate owns initiative lifecycle, assignment policy, sharing,
+properties, and activity.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/service/reads.rs`: lifecycle and read
+ logic.
+- `src/domain/models.rs`: `Initiative`, `InitiativeError`.
+- `src/domain/assignees.rs`, `src/domain/history.rs`, `src/domain/activity.rs`:
+ assignment policy, change history, and activity recording.
+- `src/outbound/pg_initiative_repo.rs` (+ `create.rs`, `list.rs`, `members.rs`,
+ `share.rs`): the Postgres adapter, split by operation.
+- `src/inbound/toolset/`: AI toolset surface (lifecycle, reads, sharing).
+- `src/inbound/axum_router/`: REST surface (create/get/list/update/delete).
+- `fixtures/initiative_test_data.sql`: seed data for repo tests.
+
+## Scope
+
+- Owns: initiative CRUD, assignment, sharing, properties, and activity.
+- Not here: the GraphQL surface → `crates/graphql_initiative`; initiative
+ descriptions (collab surface) → `crates/initiative_description`.
+
+## Boundaries
+
+- Depends on: `entity_access` (ports), `activity`, `models_permissions`,
+ `macro_event_broker`/`macro_event_topics`, optionally `properties` /
+ `system_properties` (feature `resources`).
+- Used by: `graphql_initiative`, `ai_tools`, `initiative_description`,
+ `agent_trigger`, `messages`, `soup_realtime`.
+
+## Recipes
+
+- Add a field or lifecycle rule: `src/domain/models.rs` →
+ `src/domain/service.rs` → `src/outbound/pg_initiative_repo.rs` → the
+ relevant `src/inbound/` surface (`toolset/` or `axum_router/`).
+- Add a toolset action: `src/inbound/toolset/<area>.rs` →
+ `src/domain/service.rs`.
+
+## Checks
+
+- `cargo test -p initiative --all-features` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
+- Skill: `cloud-storage-hexagonal-architecture`
diff --git a/crates/initiative/CLAUDE.md b/crates/initiative/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/initiative/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/integration_tests/local_e2e/AGENTS.md b/crates/integration_tests/local_e2e/AGENTS.md
new file mode 100644
index 0000000000..1c974298e8
--- /dev/null
+++ b/crates/integration_tests/local_e2e/AGENTS.md
@@ -0,0 +1,43 @@
+# local_e2e (crates/integration_tests/local_e2e)
+
+## What it is
+
+Belongs to local dev tooling: end-to-end Rust tests
+(`local_e2e_integration_tests` package) that run against an isolated local
+stack started through the xtask local orchestrator, seeded with the same
+fixtures `seed_cli` and Playwright use.
+
+## Start here
+
+- `README.md`: how to run tests against a fresh or already-running stack, and
+ which env vars they read (`LOCAL_E2E_DATABASE_URL`,
+ `LOCAL_E2E_DOCUMENT_STORAGE_URL`).
+- `tests/`: one file per scenario (`bot_entity_access.rs`,
+ `channel_mutations.rs`, `channel_websocket.rs`).
+- `tests/support/`: shared HTTP and websocket helpers.
+- `src/lib.rs`: thin — most logic lives under `tests/`.
+
+## Scope
+
+- Owns: full-stack Rust integration tests that need a running local stack
+ (Postgres, DSS, gateway).
+- Not here: unit/integration tests scoped to one crate — those live beside
+ their crate.
+
+## Recipes
+
+- Add a scenario: `tests/<name>.rs` → reuse `tests/support/http.rs` /
+ `websocket.rs` for requests.
+
+## Checks
+
+- `just local-e2e-rust` runs the full suite against a fresh isolated stack.
+- `nix develop --command cargo test -p local_e2e_integration_tests --test <name> --no-run`
+ compiles a single test without requiring the stack.
+- `nix develop --command cargo test -p local_e2e_integration_tests --test <name> -- --ignored --nocapture`
+ runs it against an already-running stack. Tests are `#[ignore]`d so normal
+ workspace runs skip them.
+
+## Related
+
+- Docs: `docs/development/running-locally.md`
diff --git a/crates/integration_tests/local_e2e/CLAUDE.md b/crates/integration_tests/local_e2e/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/integration_tests/local_e2e/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/invite_email/AGENTS.md b/crates/invite_email/AGENTS.md
new file mode 100644
index 0000000000..46d86aab60
--- /dev/null
+++ b/crates/invite_email/AGENTS.md
@@ -0,0 +1,50 @@
+# invite_email
+
+## What it is
+
+Belongs to notifications: domain models and Askama templates for invitation
+emails — referral-to-Macro invites, team invites, channel invites, call
+invites, and the colleague-joined email.
+
+## Start here
+
+- `src/lib.rs`: `InviteToMacro`, `ReferralCode`, and the other top-level
+ notification metadata types — each derives `Template` against a file in
+ `templates/`.
+- `src/call_invite.rs`, `src/colleague_joined.rs`: the remaining notification
+ metadata types, one file each.
+- `templates/*.html`: the actual email markup (Askama/Jinja2-compatible
+ syntax).
+- `preview_invite.py`: renders `templates/invite.html` with dummy data via
+ Jinja2 and opens it in a browser — use this to check template changes
+ without sending an email (`pip3 install jinja2` if needed).
+
+## Scope
+
+- Owns: invite/referral/colleague-joined email notification metadata and
+ templates.
+- Not here: sending/queuing the notification → `crates/notification`; who
+ triggers an invite → `crates/call`, `crates/referral`, `model_notifications`.
+
+## Boundaries
+
+- Depends on: `notification` (for `Notification`, `NotificationExtEmail`
+ types), `macro_env`, `macro_user_id`, `model-entity`.
+- Used by: `model_notifications`, `call`, `referral`.
+
+## Recipes
+
+- Add a new invite email: new metadata type in `src/<name>.rs` deriving
+ `Template` → `templates/<name>.html` → `pub use` it from `src/lib.rs`.
+- Change an email's markup: `templates/<name>.html` → preview with
+ `preview_invite.py` (edit its dummy data / template path first) → verify
+ against the type's fields in `src/lib.rs`.
+
+## Checks
+
+- `cargo test -p invite_email`.
+
+## Related
+
+- Docs: `packages/email-renderer/README.md` (if rendering in the standalone
+ renderer rather than the email template pipeline here)
diff --git a/crates/invite_email/CLAUDE.md b/crates/invite_email/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/invite_email/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/item_filter_index/AGENTS.md b/crates/item_filter_index/AGENTS.md
new file mode 100644
index 0000000000..dfbb60c7d0
--- /dev/null
+++ b/crates/item_filter_index/AGENTS.md
@@ -0,0 +1,54 @@
+# item_filter_index
+
+## What it is
+
+Belongs to Search (Soup): compiles `EntityFilterAst` filter trees into the
+generic `predicate_index` IR that decides versioned flat Soup eligibility,
+one compiler per entity kind. Wasm-compatible (used in the browser soup
+engine) — keep it free of native-only dependencies.
+
+## Start here
+
+- `src/lib.rs`: the `SOUP_FLAT_V*` profile constants (stable profile names,
+ never renumber an existing one) and the `vocabulary` module.
+- `src/document.rs`, `src/mail.rs`, `src/channels.rs`, `src/properties.rs`:
+ one compiler module per entity kind, each turning that kind's
+ `*Literal` AST nodes into `PredicateExpr`/`IndexQuery`.
+- `src/test/`: compilation tests, including `confinement.rs` (that filters
+ can't reach data outside their declared scope).
+
+## Scope
+
+- Owns: AST → predicate-index compilation and the `soup-flat-v*` profile
+ vocabulary.
+- Not here: the filter AST itself → `crates/filter_ast`, `crates/item_filters`;
+ predicate index execution → `crates/predicate_index`; which fields a given
+ profile actually serializes → the soup projection crates
+ (`soup_filter_cache_adapter`, `soup_filter_projection`).
+
+## Boundaries
+
+- Depends on: `filter_ast`, `item_filters` (ports only), `predicate-index`.
+- Used by: `soup_filter_cache_adapter`, `soup_filter_projection`.
+
+## Recipes
+
+- Add a filterable field for an entity kind: the `*Literal` enum in
+ `item_filters` → the matching compiler module here (e.g. `src/document.rs`)
+ → its `test.rs`.
+- Add a new profile version: a new `SOUP_FLAT_V*` const in `src/lib.rs` →
+ add it to `vocabulary` → update the compiling crate(s) that mint it.
+
+## Checks
+
+- `cargo test -p item-filter-index`.
+
+## Gotchas
+
+- `STATUS_PROPERTY_DEFINITION_ID` hardcodes `SystemPropertyKey::STATUS_UUID`
+ to avoid a native dependency on `system_properties` for wasm; a native test
+ locks the two values together, so don't drift them independently.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/item_filter_index/CLAUDE.md b/crates/item_filter_index/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/item_filter_index/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/item_filters/AGENTS.md b/crates/item_filters/AGENTS.md
new file mode 100644
index 0000000000..80e255e39b
--- /dev/null
+++ b/crates/item_filters/AGENTS.md
@@ -0,0 +1,62 @@
+# item_filters
+
+## What it is
+
+Belongs to Search (Soup): typed filter DTOs for every entity type searchable
+in soup/search, plus the AST layer that expands them into a strict,
+logically-combinable query form.
+
+## Start here
+
+- `src/lib.rs`: the public filter structs (`DocumentFilters`, `EmailFilters`,
+ `ChannelFilters`, `CallFilters`, `EntityFilters`, ...) — one per entity type,
+ bundled together in `EntityFilters`.
+- `src/ast.rs` + `src/ast/<entity>.rs`: typed AST literals each filter struct
+ expands into, via `ExpandFrame`/`Expr` from `filter_ast`, for consumers that
+ need a logical (AND/OR/NOT) representation instead of a flat DTO.
+- `src/ast/tests.rs`: expansion test coverage per entity type.
+
+## Scope
+
+- Owns: the filter DTO shape for every soup entity type, their `IsEmpty`
+ semantics (an empty filter must impose no constraint), and the AST expansion
+ used to turn a filter into a query.
+- Not here: the `fef:` filter-query-language parser (`filter_ast`), applying
+ filters to a search backend (OpenSearch/Postgres), or authorization checks
+ on filter values (e.g. CRM domain/address ownership) — those live in the
+ service that calls in (e.g. `email`, `crm`).
+
+## Boundaries
+
+- Depends on: `filter_ast`, `document_sub_type`, `notification_state`,
+ `model_file_type`, `model_owner`, `macro_user_id`.
+- Used by: crates building soup/search queries (`graphql_soup`,
+ `database_sql`/`databases_sql`, `email`, `channels`, `crm`, `call`,
+ `github_pull_requests`, `ai_tools`, `search_service`, `item_filter_index`);
+ a new field here needs each `IsEmpty` impl updated or filters silently stop
+ being "no-ops" when empty.
+
+## Recipes
+
+- Add a filter field to an existing entity (e.g. `EmailFilters`): add the
+ field in `src/lib.rs` → update that struct's `IsEmpty` impl (the destructure
+ forces you not to forget it) → add/extend the matching AST literal in
+ `src/ast/<entity>.rs` → extend `src/ast/tests.rs`.
+- Add a new filterable entity type: new struct + `IsEmpty` impl in
+ `src/lib.rs` → new `src/ast/<entity>.rs` module declared in `src/ast.rs` →
+ field on `EntityFilters` → the caller's expansion code.
+
+## Checks
+
+- `cargo test -p item_filters` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Several entity types (initiatives, agent sessions) are opt-in: `include:
+ false` by default, and asking for specific ids/owners also implicitly opts
+ in — don't assume an empty `include` flag means "show everything".
+- `#![deny(missing_docs)]`: every new public field needs a doc comment.
+
+## Related
+
+- Rules: `.agents/rules/rust/code.md` (CS-54 missing-docs)
diff --git a/crates/item_filters/CLAUDE.md b/crates/item_filters/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/item_filters/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/jev/AGENTS.md b/crates/jev/AGENTS.md
new file mode 100644
index 0000000000..5260ac3935
--- /dev/null
+++ b/crates/jev/AGENTS.md
@@ -0,0 +1,42 @@
+# jev
+
+## What it is
+
+Belongs to automations: yes/no classification of arbitrary JSON against a
+list of questions, backed by TypeSafe's Jev model, with usage metering built
+in — used to gate scheduled-action triggers on a condition.
+
+## Start here
+
+- `src/domain/service.rs`: `JevClassifier` — the metered classification use
+ case; wraps a `JevProvider` and records token usage on every call.
+- `src/domain/ports.rs`: `JevProvider` / `YesNoClassifier` port traits.
+- `src/outbound/typesafe.rs`: the TypeSafe HTTP adapter (feature `outbound`).
+
+## Scope
+
+- Owns: the question/probability value objects, the `MAX_QUESTIONS` guard,
+ and metering every classification call through `ai_usage::UsageRecorder`.
+- Not here: the TypeSafe API contract itself, or deciding what questions to
+ ask — that's the caller's (`scheduled_action`'s trigger-gating logic).
+
+## Boundaries
+
+- Depends on: `ai_usage` (usage metering); `outbound` feature adds
+ `macro_env_var`, `reqwest`, `tokio`.
+- Used by: `scheduled_action` (gates event triggers on yes/no conditions).
+
+## Checks
+
+- `cargo test -p jev` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `classify` records usage even when the provider's answer count doesn't
+ match the question count — the call was billed regardless of whether the
+ response is usable; don't skip metering on a validation failure path.
+- Jev has no prompt cache, so every input token reports as uncached.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md` (CS-51/CS-52 hexagonal layering)
diff --git a/crates/jev/CLAUDE.md b/crates/jev/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/jev/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/last_online_tracker/AGENTS.md b/crates/last_online_tracker/AGENTS.md
new file mode 100644
index 0000000000..ae4d0998e9
--- /dev/null
+++ b/crates/last_online_tracker/AGENTS.md
@@ -0,0 +1,43 @@
+# last_online_tracker
+
+## What it is
+
+Belongs to notifications/presence: tracks each user's last-seen timestamp in
+Redis, written off the hot path through a background worker, for presence
+and notification decisions.
+
+## Start here
+
+- `src/domain/services.rs`: `LastOnlineService` — `record_last_online`,
+ `get_last_online`, `time_since_last_online`.
+- `src/inbound.rs`: `LastOnlineWorker` — an mpsc-backed background task that
+ batches writes, and `RecordOnDrop`, which fires a best-effort write when a
+ guard value drops (e.g. a connection/session going away).
+- `src/outbound/redis.rs`, `src/outbound/time.rs`: the `LastOnlineRepo` and
+ `SystemTime` port implementations.
+
+## Scope
+
+- Owns: the last-online timestamp per user and its Redis storage.
+- Not here: presence/online status derived from this data — that's the
+ caller's (`notification`).
+
+## Boundaries
+
+- Depends on: `macro_user_id`, `redis` (via its own client, not
+ `macro_redis`).
+- Used by: `notification`.
+
+## Checks
+
+- `cargo test -p last_online_tracker` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `RecordOnDrop::drop` uses `try_send` and only logs on failure — a full
+ channel silently drops the update; this is intentional (best-effort, not
+ on the hot path), don't "fix" it into a blocking send.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md` (CS-51/CS-52 hexagonal layering)
diff --git a/crates/last_online_tracker/CLAUDE.md b/crates/last_online_tracker/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/last_online_tracker/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/lexical_client/AGENTS.md b/crates/lexical_client/AGENTS.md
new file mode 100644
index 0000000000..39858ec4c9
--- /dev/null
+++ b/crates/lexical_client/AGENTS.md
@@ -0,0 +1,47 @@
+# lexical_client
+
+## What it is
+
+Belongs to Documents: the Rust-side HTTP client for `lexical_service`, plus
+a parser for Lexical's markdown subset, used by any backend crate that needs
+to read or render document content.
+
+## Start here
+
+- `src/lib.rs`: `LexicalClient::new` — builds the `reqwest::Client`, sets the
+ internal-access header, and trusts the checked-in local CA for local HTTPS.
+- `src/parse_markdown.rs` (+ `src/parse_markdown/test.rs`): markdown → Lexical
+ node tree parsing.
+- `src/types.rs`: the Lexical node/document types shared with the service.
+
+## Scope
+
+- Owns: the Rust-side HTTP client for `lexical_service` and markdown parsing
+ into Lexical's node shape.
+- Not here: the service itself, or the frontend's own Lexical node
+ implementations (`apps/web`) — those are kept in sync by hand, not shared
+ code.
+
+## Boundaries
+
+- Depends on: `agent_fold`, `messages`, `trigger_context`.
+- Used by: `documents`, `collab_surface`, `email`, `ai_tools`, `agent_harness`,
+ `agent_trigger`, `channel_bots`, `image_generation`,
+ `lexical_mention_extractor`, `memory`, `skills`, `task_dedup`.
+
+## Checks
+
+- `cargo test -p lexical_client` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `LexicalClient::new` embeds `infra/local/certs/ca.pem` via `include_str!`
+ and only trusts it when the URL is `localhost`/`127.0.0.1` over HTTPS —
+ don't point this client at a real HTTPS host expecting that cert to help.
+- The internal-access header name (`x-internal-auth-key`) must match what
+ `lexical_service` expects; it's not read from `macro_auth`'s header
+ constants.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md`
diff --git a/crates/lexical_client/CLAUDE.md b/crates/lexical_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/lexical_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/local_e2e_test_support/AGENTS.md b/crates/local_e2e_test_support/AGENTS.md
new file mode 100644
index 0000000000..233c68388b
--- /dev/null
+++ b/crates/local_e2e_test_support/AGENTS.md
@@ -0,0 +1,48 @@
+# local_e2e_test_support
+
+## What it is
+
+Belongs to local dev tooling: shared helpers for Rust local end-to-end
+tests — fixture loading, local JWTs, and local-only service URLs.
+
+## Start here
+
+- `src/services.rs`: standard local service URLs for the `run_local` stack;
+ refuses non-local URLs so tests can't mutate shared dev services.
+- `src/jwt.rs`: generates local Macro API JWTs via `macro_auth`.
+- `src/config.rs`: reads the xtask instance env file selected by
+ `LOCAL_E2E_ENV_FILE` (falling back to `.env`), with process env overrides.
+- `src/fixtures.rs`: loads fixture data from `tooling/seed_cli/seed`.
+- `src/bin/generate_local_e2e_token.rs`: standalone token-generation binary.
+
+## Scope
+
+- Owns: test-only plumbing for the local E2E harness — never used in
+ production services.
+- Not here: the harness itself (`just local-e2e-rust`) or stack
+ startup/seeding — see `crates/integration_tests/local_e2e`.
+
+## Boundaries
+
+- Depends on: `macro_auth`.
+- Used by: `crates/integration_tests/local_e2e`, run only from ignored
+ integration tests.
+
+## Recipes
+
+- Override a service URL for a test: `LOCAL_E2E_<SERVICE>_URL` env var (local
+ endpoints only — non-local values are rejected in `src/services.rs`).
+
+## Checks
+
+- `just local-e2e-rust` (starts and seeds an isolated named stack first; do
+ not run these tests directly without it).
+
+## Gotchas
+
+- These tests mutate an isolated named stack, not shared dev data — don't
+ bypass the harness and run them against a shared environment.
+
+## Related
+
+- Docs: `docs/development/rust.md`
diff --git a/crates/local_e2e_test_support/CLAUDE.md b/crates/local_e2e_test_support/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/local_e2e_test_support/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/macro_auth/AGENTS.md b/crates/macro_auth/AGENTS.md
new file mode 100644
index 0000000000..30742ce38c
--- /dev/null
+++ b/crates/macro_auth/AGENTS.md
@@ -0,0 +1,43 @@
+# macro_auth
+
+## What it is
+
+Belongs to shared infrastructure: low-level JWT and internal-credential
+primitives used across services — decoding Macro API tokens, validating the
+internal API key, and the Axum JWT-decode middleware.
+
+## Start here
+
+- `src/macro_api_token.rs`: the Macro API token (JWT) shape and claims.
+- `src/internal_api_key.rs`: `InternalApiKey`, the shared-secret credential
+ for service-to-service calls.
+- `src/middleware/decode_jwt.rs`: Axum middleware that decodes and attaches
+ the JWT to a request.
+- `src/headers.rs`: header name constants used across services.
+
+## Scope
+
+- Owns: token/credential parsing and validation primitives.
+- Not here: deciding whether a request is authorized — that's
+ `macro_authorization`, which builds on this crate for its JWT validator and
+ internal auth adapters.
+
+## Boundaries
+
+- Depends on: `macro_env`, `macro_env_var`, `macro_user_id`, `remote_env_var`.
+- Used by: `macro_authorization`, `agent_egress`, `ai_tools`, `decode_jwt`,
+ `local_e2e_test_support`, `search_service`.
+
+## Checks
+
+- `cargo test -p macro_auth` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- This crate only decodes/validates credentials; it has no concept of
+ principals, policies, or 403s — don't add authorization decisions here,
+ add them in `macro_authorization`.
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md`
diff --git a/crates/macro_auth/CLAUDE.md b/crates/macro_auth/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/macro_auth/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/macro_authorization/AGENTS.md b/crates/macro_authorization/AGENTS.md
new file mode 100644
index 0000000000..2e08ab1c40
--- /dev/null
+++ b/crates/macro_authorization/AGENTS.md
@@ -0,0 +1,62 @@
+# macro_authorization
+
+## What it is
+
+Belongs to shared infrastructure: transport-independent authorization used
+by nearly every authenticated service. Validates user, bot,
+internal-service, harness, and user-API-key credentials and returns a typed
+principal; the Axum layer (`axum` feature) exposes this as extractors keyed
+by policy.
+
+## Start here
+
+- `src/lib.rs`: doc comment has the full extractor/policy table (which
+ principals each `AuthorizationPolicy` admits, and its narrowed output type)
+ — read this before adding or choosing an extractor.
+- `src/domain/service.rs`: `MacroAuthorizationServiceImpl` — the composed
+ authorization service; bot and user-API-key authorizers are required
+ explicitly (pass `NoBotAuthorizer`/`NoUserApiKeyAuthorizer` to opt out).
+- `src/inbound/axum.rs`: the Axum extractors and rejection type.
+- `src/outbound/pg_*.rs`: Postgres-backed bot/harness/user-API-key
+ authorization repos (feature `postgres`).
+
+## Scope
+
+- Owns: authenticating a caller (user/bot/internal/harness/API-key) into a
+ typed principal, and the bot scope (`user`/`team`) header contract.
+- Not here: deciding whether that principal may act on a specific entity —
+ that's a typed entity-access receipt in the domain layer that calls in.
+
+## Boundaries
+
+- Depends on: `macro_auth` (outbound JWT validation), `bot_id`, `bot_token`,
+ `harness_id`, `harness_token`, `model_user`, `model-error-response`.
+- Used by: essentially every
+ authenticated HTTP surface (`agent_session`, `agent_harness`, `ai_tools`,
+ `bots`, `calendar_events`, `channels`, `chat`, `documents`, ...).
+
+## Recipes
+
+- Add a new axum policy: add the `AuthorizationPolicy` impl + its narrowed
+ output type in `src/inbound/axum.rs` → document it in the `lib.rs` table →
+ re-export both from `lib.rs`.
+- Wire a new service with MacroDB: `PgBotAuthorizer` + `PgUserApiKeyAuthorizer`
+ (feature `postgres`) in the composition root — see `calendar_service` or
+ any service in `services/` for the pattern.
+
+## Checks
+
+- `cargo test -p macro_authorization` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Both extractors reject (400) a request that combines explicit credential
+ types (internal key, bot token, user API key, bearer/query user) rather
+ than picking one — don't "fix" this by adding precedence logic.
+- Cookies are ambient and only considered when no explicit credential is
+ present; an explicit credential always wins over a cookie.
+- A valid principal not admitted by the chosen policy is a 403, not a 401.
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md`, `.agents/rules/rust/architecture.md`
diff --git a/crates/macro_authorization/CLAUDE.md b/crates/macro_authorization/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/macro_authorization/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/macro_cache_client/AGENTS.md b/crates/macro_cache_client/AGENTS.md
new file mode 100644
index 0000000000..bd744256b3
--- /dev/null
+++ b/crates/macro_cache_client/AGENTS.md
@@ -0,0 +1,45 @@
+# macro_cache_client
+
+## What it is
+
+Belongs to shared infrastructure (authentication): Redis-backed rate
+limiters for auth-adjacent flows, one module per limited action, each gated
+behind its own Cargo feature.
+
+## Start here
+
+- `src/lib.rs`: `MacroCache::new` — thin wrapper around `redis::Client`;
+ modules are enabled per feature (`auth_rate_limit`, `login_code_rate_limit`,
+ `notification_rate_limit`, `mobile_welcome_email_rate_limit`,
+ `verify_email_rate_limit`).
+- `src/passwordless_rate_limit.rs`, `src/create_user_rate_limit.rs`: the
+ `auth_rate_limit` feature's two limiters.
+- `src/auth.rs`: shared auth-cache helpers (feature `auth`).
+
+## Scope
+
+- Owns: rate-limit counters for auth-adjacent flows (login codes, account
+ creation, passwordless, verification emails).
+- Not here: general-purpose Redis operations — those are `macro_redis`
+ (which this crate does not depend on; it rolls its own Redis calls per
+ limiter module).
+
+## Boundaries
+
+- Depends on: `macro_redis`, `email_validator` (optional, per rate-limit
+ feature).
+- Used by: `authentication_service`.
+
+## Recipes
+
+- Add a new rate limit: new `src/<name>_rate_limit.rs` module → feature flag
+ in `Cargo.toml` → `pub mod` gated on it in `src/lib.rs` → add to the `all`
+ feature if it should ship by default.
+
+## Checks
+
+- `cargo test -p macro_cache_client` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md`
diff --git a/crates/macro_cache_client/CLAUDE.md b/crates/macro_cache_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/macro_cache_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/macro_db_client/AGENTS.md b/crates/macro_db_client/AGENTS.md
new file mode 100644
index 0000000000..9fb3ee2a93
--- /dev/null
+++ b/crates/macro_db_client/AGENTS.md
@@ -0,0 +1,61 @@
+# macro_db_client
+
+## What it is
+
+Belongs to shared infrastructure: the database client crate for MacroDB
+(Postgres), owning its migrations and most of the compile-time-checked
+queries used across Rust services.
+
+## Start here
+
+- `src/lib.rs`: the module list — one module per table/feature area
+ (`user.rs`, `document.rs`, `organization.rs`, `team/`, `item_access/`, ...).
+- `migrations/`: MacroDB's SQLx migrations, paired `.up.sql`/`.down.sql`, 500+
+ files; the only place MacroDB schema changes are made.
+- `tests/`: cross-table integration tests (e.g. `add_forms.rs`).
+
+## Scope
+
+- Owns: MacroDB's schema (`migrations/`) and the `sqlx::query!` call sites for
+ the tables listed in `src/lib.rs`.
+- Not here: domain logic, authorization decisions, or caching built on top of
+ these queries — those live in the owning domain crate/service that calls in.
+
+## Boundaries
+
+- Depends on: `entity_access_db_utils`, `entity_registry_db_utils`,
+ `models_permissions`, `models_entity_access_management`, `model`, `model-entity`.
+- Used by: most Rust services and several domain crates (e.g. `documents`,
+ `ai_tools`, `authentication_service`, `email_service`); a query here is
+ widely shared — check callers before changing a function's signature.
+
+## Recipes
+
+- Add a column or table: `sqlx migrate add --source crates/macro_db_client/migrations <name>`
+ → edit the generated `.up.sql`/`.down.sql` → the module in `src/<area>.rs`
+ (or `src/<area>/`) → `nix develop --command just prepare_db`.
+- Add a query to an existing table: the module in `src/<area>.rs` → its tests
+ → `nix develop --command just prepare_db` if cache metadata is missing.
+- Add a new owned area: `src/<area>.rs` → `pub mod <area>;` in `src/lib.rs` →
+ gate it behind a Cargo feature in `Cargo.toml` only if it's optional (see
+ `account_merge_request`, `team`).
+
+## Checks
+
+- `cargo test -p macro_db_client` (`SQLX_OFFLINE` unset; requires local MacroDB
+ — `just setup_macrodb`).
+- After schema or query changes: `nix develop --command just prepare_db` from
+ the repo root, then commit the regenerated root `.sqlx/`.
+
+## Gotchas
+
+- Migrations deploy before service code: never drop a column/table in the
+ same PR that removes its last usage (see `docs/development/database.md`).
+- Never hand-edit `.sqlx/query-*.json` or invent a migration timestamp.
+- Quote and alias camelCase columns to Rust field names
+ (`SELECT "userId" AS user_id`); don't guess spelling — check `migrations/`.
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md`, `.agents/rules/rust/architecture.md` ·
+ Docs: `docs/development/database.md` · Skill: `dump-schema`
diff --git a/crates/macro_db_client/CLAUDE.md b/crates/macro_db_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/macro_db_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/macro_entrypoint/AGENTS.md b/crates/macro_entrypoint/AGENTS.md
new file mode 100644
index 0000000000..691c118d0a
--- /dev/null
+++ b/crates/macro_entrypoint/AGENTS.md
@@ -0,0 +1,55 @@
+# macro_entrypoint
+
+## What it is
+
+Belongs to shared infrastructure: standardized binary initialization —
+tracing/logging/OTel setup and graceful shutdown — used as the first thing
+nearly every Rust service's `main.rs` calls.
+
+## Start here
+
+- `src/lib.rs`: `MacroEntrypoint::init` — builds the tracing subscriber stack
+ per `Environment` (local / develop / production), returning
+ `InitializedEntrypoint` as proof of initialization; call `.shutdown()`
+ before exit to flush OTel.
+- `src/datadog_fmt.rs`: JSON log format injecting `dd.trace_id`/`dd.span_id`
+ for prod/develop trace-log correlation.
+- `src/grafana.rs`: a second, best-effort span exporter that mirrors spans to
+ Grafana in `develop` without affecting the primary (Datadog) exporter.
+- `src/shutdown.rs`: `shutdown_signal` — the standard graceful-shutdown
+ future every service awaits on.
+
+## Scope
+
+- Owns: the tracing/logging/OTel subscriber setup and graceful shutdown
+ signal shared by every service's composition root.
+- Not here: per-service span content or business instrumentation — this
+ crate only wires the pipeline.
+
+## Boundaries
+
+- Depends on: `macro_env`, `macro_env_var`, `rootcause`/`rootcause-tracing`.
+- Used by: nearly every service in `services/` plus a few crates with their
+ own binaries (`documents`, `entity_access`, `memory`, `opensearch_client`,
+ `task_dedup`, `teams`).
+
+## Checks
+
+- `cargo test -p macro_entrypoint` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `RUST_LOG` is read through `macro_env_var`'s `APP_SECRETS_JSON`-first
+ convention, not `EnvFilter::from_default_env` directly — a bare
+ `std::env::var("RUST_LOG")` fallback would silently diverge from this.
+- An absent/empty `RUST_LOG` still gets an INFO floor (`rust_log_builder`);
+ this is intentional so a misconfigured service logs quietly rather than
+ not at all while still emitting spans.
+- Local OTLP export is opt-in (`OTEL_EXPORTER_OTLP_ENDPOINT` must be set);
+ xtask sets it only for trace-enabled local runs.
+- Prod/develop export logs as JSON on stdout for Datadog, not via OTLP — only
+ spans go through OTLP there.
+
+## Related
+
+- Skill: `new-service` · Docs: `docs/guides/new-service.md`
diff --git a/crates/macro_entrypoint/CLAUDE.md b/crates/macro_entrypoint/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/macro_entrypoint/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/macro_event_broker/AGENTS.md b/crates/macro_event_broker/AGENTS.md
new file mode 100644
index 0000000000..b79c0bdb7c
--- /dev/null
+++ b/crates/macro_event_broker/AGENTS.md
@@ -0,0 +1,49 @@
+# macro_event_broker
+
+## What it is
+
+Belongs to shared infrastructure: a Kafka-backed event broker,
+ports-and-adapters style, giving services a typed publish/consume API over
+Macro's event topics.
+
+## Start here
+
+- `src/lib.rs`: module-level doc maps the whole crate — `domain::models` for
+ `TopicEvent`/`MacroEvent` envelopes, `domain::ports` for `MacroEventBroker`
+ (inbound), `EventPublisher`/`EventConsumer`/`Spawner` (outbound), and
+ `domain::service` for `MacroEventBrokerService` /
+ `MacroEventConsumerService`.
+- `src/outbound/kafka_event_publisher.rs`, `kafka_event_consumer.rs`: the
+ Kafka adapters (feature `outbound`, via `kafka_util`/`rdkafka`).
+- `src/outbound/spawner.rs`: `GlobalSpawner`, the Tokio task-spawning adapter.
+- `examples/`: runnable usage examples.
+
+## Scope
+
+- Owns: the publish/consume abstraction and Kafka wiring for Macro's event
+ topics.
+- Not here: topic definitions (those live in `macro_event_topics`) or
+ per-domain event payload shapes (defined by each producing crate).
+
+## Boundaries
+
+- Depends on: `macro_event_topics`, `kafka_util` (optional, feature
+ `outbound`).
+- Used by: crates and services that publish or consume Macro events
+ (`agent_session`, `agent_trigger`, `activity`, `bots`, `calendar_events`,
+ `channels`, `chat`, `crm`, `databases`, `documents`, ...).
+
+## Checks
+
+- `cargo test -p macro_event_broker` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `NoopMacroEventBroker` exists for tests/local configs without Kafka — don't
+ reach for a hand-rolled in-memory broker instead.
+- Default feature is `outbound`; building without it (e.g. `schema`-only
+ consumers of the models) drops the Kafka adapters entirely.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md` (CS-51/CS-52 hexagonal layering)
diff --git a/crates/macro_event_broker/CLAUDE.md b/crates/macro_event_broker/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/macro_event_broker/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/macro_middleware/AGENTS.md b/crates/macro_middleware/AGENTS.md
new file mode 100644
index 0000000000..40c67dbc2a
--- /dev/null
+++ b/crates/macro_middleware/AGENTS.md
@@ -0,0 +1,49 @@
+# macro_middleware
+
+## What it is
+
+Belongs to shared infrastructure: a small grab bag of Axum middleware shared
+by several services, each piece gated behind its own Cargo feature.
+
+## Start here
+
+- `src/lib.rs`: `connection_drop_prevention_handler` — wraps
+ POST/PUT/PATCH/DELETE handlers in a spawned task so a dropped client
+ connection doesn't cancel an in-flight mutation.
+- `src/cloud_storage/mod.rs` (feature `cloud_storage`): middleware that needs
+ `macro_db_client`/`entity_access_db_utils`/`model_user`.
+- `src/tracking/mod.rs` (feature `tracking`): request tracking via
+ `ip_extractor`.
+- `src/error_handler.rs` (feature `cloud_storage`): shared error-response
+ mapping.
+
+## Scope
+
+- Owns: cross-cutting Axum middleware too small to justify their own crate.
+- Not here: anything specific enough to one service — keep that in the
+ service.
+
+## Boundaries
+
+- Depends on (feature-gated): `macro_db_client`, `entity_access_db_utils`,
+ `ip_extractor`, `macro_user_id`, `model_user`.
+- Used by: `document_storage_service`, `notification_service`,
+ `document_cognition_service`, `authentication_service`,
+ `image_proxy_service`, `search_processing_service`, `convert_service`,
+ `email_service`.
+
+## Checks
+
+- `cargo test -p macro_middleware` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `connection_drop_prevention_handler` only wraps mutating methods
+ (POST/PUT/PATCH/DELETE); GET/HEAD/etc. pass through unwrapped by design.
+- `CS-23`/`CS-28`: this is exactly the kind of catch-all crate that must
+ shrink, not grow — a new piece of middleware specific to one domain
+ belongs in that domain's crate, not here.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/macro_middleware/CLAUDE.md b/crates/macro_middleware/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/macro_middleware/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/macro_service_urls/AGENTS.md b/crates/macro_service_urls/AGENTS.md
new file mode 100644
index 0000000000..0401d3960c
--- /dev/null
+++ b/crates/macro_service_urls/AGENTS.md
@@ -0,0 +1,51 @@
+# macro_service_urls
+
+## What it is
+
+Belongs to shared infrastructure: typed per-environment URLs for every Macro
+service and gateway, resolved from `macro_env::Environment` with an
+`OVERRIDE_<NAME>` env var escape hatch.
+
+## Start here
+
+- `src/lib.rs`: the `service_url!` macro and the `ServiceUrls` collection — the
+ whole crate is this one file plus its macro-generated types.
+- `src/test.rs`: override-resolution tests; also shows the macro's expected usage.
+
+## Scope
+
+- Owns: the `local`/`dev`/`prod` default for every service URL, the
+ `OVERRIDE_*` env var convention, and the `ServiceUrl<'a>` string wrapper.
+- Not here: the URL value itself used outside Rust → `infra/packages/shared/src/service_urls.ts`,
+ `apps/web/src/lib/core/constant/servers.ts`, `packages/sdk/src/config.ts` (hand-kept
+ in sync; see the config rule).
+
+## Boundaries
+
+- Depends on: `macro_env` (for `Environment`).
+- Used by: nearly every Rust service that calls another service — construct a
+ type with `XServiceUrl::new()`, never a raw string or env var.
+
+## Recipes
+
+- Add a new service URL: add a field to the `service_url! { struct ServiceUrls { ... } }`
+ block in `src/lib.rs` with `local`/`dev`/`prod` values, then update the other
+ three copies of the table (see Related).
+
+## Checks
+
+- `cargo test -p macro_service_urls` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- The override env var name is derived from the struct name
+ (`CalendarServiceUrl` → `OVERRIDE_CALENDAR_SERVICE_URL`); renaming a struct
+ silently changes what override callers must set.
+- `local` defaults are host ports, not Docker-network addresses; a service
+ calling another from inside Docker needs an `OVERRIDE_*_URL` entry in
+ `local_env.rs`, not a different `local` default here.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md` ·
+ Docs: `docs/guides/new-service.md` (§5 Service discovery)
diff --git a/crates/macro_service_urls/CLAUDE.md b/crates/macro_service_urls/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/macro_service_urls/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/macro_sha_count_client/AGENTS.md b/crates/macro_sha_count_client/AGENTS.md
new file mode 100644
index 0000000000..d72ea75c2f
--- /dev/null
+++ b/crates/macro_sha_count_client/AGENTS.md
@@ -0,0 +1,42 @@
+# macro_sha_count_client
+
+## What it is
+
+Part of document/file storage. A Redis-backed reference counter for
+content-addressed file blobs (SHA keys), used to know when a blob's last
+reference is gone and it's safe to delete.
+
+## Start here
+
+- `src/lib.rs`: `Redis::increment_counts` / `release_shas` (decrement) /
+ `sha_exists` / `find_non_existing_shas(_string)`.
+- `src/increment_count.rs`, `src/decrement_count.rs`, `src/exists.rs`: the
+ underlying Redis operations.
+
+## Scope
+
+- Owns: reference counting for file content SHAs and the `bucket:sha-delete`
+ tracking used to find SHAs ready for cleanup.
+- Not here: actually deleting the underlying blob storage — this crate only
+ tracks the reference count.
+
+## Boundaries
+
+- Depends on: `model` (for `SaveBomPart`).
+- Used by: `documents`, `projects`, `document_storage_service`,
+ `docx_unzip_handler`.
+
+## Checks
+
+- `cargo test -p macro_sha_count_client` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `release_shas` collapses a list with duplicate SHAs into per-SHA counts
+ before decrementing (`reference_counts`) — releasing the same SHA twice in
+ one call removes two references, not one, so callers must pass every BOM
+ reference, not a deduplicated set.
+
+## Related
+
+- Skill: `dump-schema` (if cross-checking against `document.save_bom_part`)
diff --git a/crates/macro_sha_count_client/CLAUDE.md b/crates/macro_sha_count_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/macro_sha_count_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/macro_user_id/AGENTS.md b/crates/macro_user_id/AGENTS.md
new file mode 100644
index 0000000000..d72fe7a694
--- /dev/null
+++ b/crates/macro_user_id/AGENTS.md
@@ -0,0 +1,46 @@
+# macro_user_id
+
+## What it is
+
+Shared infrastructure: the identity type used across the whole backend. The
+`MacroUserId` newtype (`macro|<email>`) and its `nom`-based parser —
+parse-don't-validate for the single most widely used identity type in the
+backend.
+
+## Start here
+
+- `src/user_id.rs` (+ `src/user_id/tests.rs`): `MacroUserId<T>` — generic over
+ its string storage (`cowlike::CowLike`), parsed with `nom`.
+- `src/email.rs` (+ `src/email/tests.rs`): the email-part parser and `Email<T>`.
+- `src/lowercased.rs`: case-normalization wrapper used for lookups/comparisons.
+- `src/error.rs`: `ParseErr`.
+
+## Scope
+
+- Owns: parsing and representing the `macro|<email>` user id shape.
+- Not here: resolving a user id to a user record (MacroDB) — that's
+ `macro_db_client`/the owning domain crate.
+
+## Boundaries
+
+- Depends on: `cowlike` (generic Cow-like string storage), `doppleganger`,
+ `nom`.
+- Used by: essentially everywhere a user id crosses a function
+ boundary; a change to the parser or `Debug`/`PartialEq` semantics is
+ widely felt.
+
+## Checks
+
+- `cargo test -p macro_user_id` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `MacroUserId::eq` only compares the underlying string (`user_id`), not the
+ derived email offsets — don't add fields to the struct without checking
+ whether `PartialEq`/`Debug` need to account for them.
+- `features = ["sqlx"]` / `["schema"]` are additive, feature-gated impls
+ (`sqlx::Type`, `utoipa::ToSchema`) — most callers only need the default.
+
+## Related
+
+- Rules: `.agents/rules/rust/code.md` (CS-10 newtype ids)
diff --git a/crates/macro_user_id/CLAUDE.md b/crates/macro_user_id/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/macro_user_id/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/mcp_client/AGENTS.md b/crates/mcp_client/AGENTS.md
new file mode 100644
index 0000000000..0c1cae8400
--- /dev/null
+++ b/crates/mcp_client/AGENTS.md
@@ -0,0 +1,60 @@
+# mcp_client
+
+## What it is
+
+Part of agent sessions / AI tooling. An MCP (Model Context Protocol) client
+library: connects to user-configured MCP servers (including OAuth-protected
+ones) and executes their tools for agents.
+
+## How it works
+
+A user connects a server through the HTTP routes (OAuth callback if needed);
+the server config and OAuth tokens are stored via the outbound adapters
+(Postgres, Redis). When an agent calls one of that server's tools, the
+service orchestration layer looks up the connection and executes the tool
+through `rmcp`, returning the result to the caller's tool-calling loop.
+
+## Start here
+
+- `src/domain/service/`: connection/tool-execution orchestration
+ (`toolset.rs`, `server_access.rs`, `persisting_credential_store.rs`).
+- `src/domain/ports.rs`: `McpServerStore`, `OAuthStateStore`, and the OAuth
+ port the outbound adapters implement.
+- `src/domain/provider_registry.rs` (feature `providers`): pre-registered
+ OAuth credentials for known MCP providers, keyed off `macro_env_var`.
+- `src/inbound/axum_router.rs`: HTTP routes for server management and the
+ OAuth callback.
+- `src/outbound/`: `oauth.rs` (RMCP-backed OAuth), `pg_server_repo.rs`
+ (Postgres server store), `redis_state_store.rs` (OAuth state).
+
+## Scope
+
+- Owns: storing a user's/team's configured MCP servers, OAuth connect/refresh
+ flows for them, and invoking their tools through `rmcp`.
+- Not here: the agent's tool-calling loop itself (`agent`, `ai_toolset`) —
+ this crate is a tool *provider*, called by that loop.
+
+## Boundaries
+
+- Depends on: `agent`, `ai_toolset`, `macro_authorization` (feature `axum`),
+ `macro_user_id`, `rmcp`.
+- Used by: `agent_egress`, `agent_harness`, `ai_tools`, `mcp_select`,
+ `onboarding`.
+
+## Checks
+
+- `cargo test -p mcp_client` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- MCP tool names reaching this crate from a provider can be mangled;
+ `mcp_service` sanitizes them for provider matching — new
+ provider integrations should go through the existing registry pattern, not
+ a second ad hoc name-matching path.
+- OAuth state lives in Redis (`redis_state_store.rs`) separately from the
+ server config in Postgres (`pg_server_repo.rs`) — a server record surviving
+ doesn't mean its OAuth state did.
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md`, `.agents/rules/rust/architecture.md`
diff --git a/crates/mcp_client/CLAUDE.md b/crates/mcp_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/mcp_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/mcp_toolset/AGENTS.md b/crates/mcp_toolset/AGENTS.md
new file mode 100644
index 0000000000..c5f020d5d1
--- /dev/null
+++ b/crates/mcp_toolset/AGENTS.md
@@ -0,0 +1,41 @@
+# mcp_toolset
+
+## What it is
+
+Part of agent sessions / AI tooling. A shared `ai_toolset::ToolSet` adapter
+over already-connected MCP server sessions: lists their tools, mangles
+names, and routes calls back to the right server.
+
+## Start here
+
+- `src/lib.rs`: `client_info()` and the `McpServer` session type.
+- `src/toolset.rs`: `RemoteMcpToolSet` — the `ToolSet` impl, `ConnectedServer`/`ListedServer`.
+- `src/mangle.rs`: the `mcp__<server>__<tool>` name encoding/decoding.
+- `src/call_tool_result.rs`: `CallToolResultExt` for converting MCP results.
+
+## Scope
+
+- Owns: tool listing, provider-safe name mangling, and call routing for any
+ already-connected MCP server session.
+- Not here: opening/authenticating MCP sessions — Pipedream's connection flow
+ lives in `pipedream_mcp`; in-process ACP session wiring lives in `agent_inmem`.
+
+## Boundaries
+
+- Depends on: `ai_toolset`, `rmcp` (client feature).
+- Used by: `agent_inmem`, `pipedream_mcp`.
+
+## Recipes
+
+- Change how a tool name is mangled/recovered: `src/mangle.rs` →
+ `src/mangle/test.rs`.
+- Change how a tool call result is surfaced to the model: `src/call_tool_result.rs`
+ → `src/call_tool_result/test.rs`.
+
+## Checks
+
+- `cargo test -p mcp_toolset` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/mcp_toolset/CLAUDE.md b/crates/mcp_toolset/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/mcp_toolset/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/memory/AGENTS.md b/crates/memory/AGENTS.md
new file mode 100644
index 0000000000..39eea3d324
--- /dev/null
+++ b/crates/memory/AGENTS.md
@@ -0,0 +1,48 @@
+# memory
+
+## What it is
+
+Part of agent sessions. Generates and stores a per-user AI memory (a
+free-text summary an agent can load as context) by running the agent loop
+over that user's own tools.
+
+## Start here
+
+- `src/main.rs`: CLI entrypoint — loads one user id from env, generates and
+ stores their memory, waits for the event broker to drain, exits.
+- `src/domain/service.rs` + `src/domain/ports.rs`: `MemoryServiceImpl`,
+ `MemoryRepo` port, and `MemoryError`.
+- `src/inbound/axum_router.rs`: the HTTP read path, mounted by callers that
+ need an existing memory record rather than generating one.
+- `src/outbound/pg_memory_repo.rs`: the Postgres adapter.
+- `src/context.rs`: builds the `ToolServiceContext` used to run the agent loop.
+
+## Scope
+
+- Owns: memory generation (prompting the agent with the user's tools),
+ storage, and the read router.
+- Not here: the agent loop itself → `agent`; AI billing/usage enforcement →
+ `ai_billing`, `ai_usage`.
+
+## Boundaries
+
+- Depends on: `agent`, `ai_tools`, `ai_toolset`, `ai_billing`, `ai_usage`,
+ `macro_authorization`, and the large "ToolServiceContext" dependency set in
+ `Cargo.toml` (most domain crates with AI tools).
+- Used by: `agent_inmem` (reads memory into agent context),
+ `document_cognition_service`.
+
+## Recipes
+
+- Change what the generation prompt covers: `src/domain/service.rs` →
+ `src/context.rs` (tool context) → `src/main.rs`.
+- Add a read endpoint: `src/inbound/axum_router.rs` → `src/domain/ports.rs`
+ (`MemoryRepo`) → `src/outbound/pg_memory_repo.rs`.
+
+## Checks
+
+- `cargo test -p memory` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md`
diff --git a/crates/memory/CLAUDE.md b/crates/memory/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/memory/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/mention_utils/AGENTS.md b/crates/mention_utils/AGENTS.md
new file mode 100644
index 0000000000..30d5fd5185
--- /dev/null
+++ b/crates/mention_utils/AGENTS.md
@@ -0,0 +1,43 @@
+# mention_utils
+
+## What it is
+
+Shared infrastructure for the `@mention` feature, used by messages,
+documents, and notifications. Parses and serializes `@mention` XML chips
+(`<m-user>`, `<m-channel>`, `<m-bot>`, GitHub PR links, etc.) shared between
+AI editors, lexical, and notification text.
+
+## Start here
+
+- `src/parse.rs`: `nom` parsers for each mention chip XML tag.
+- `src/serialize.rs`: renders mentions back to chip XML or plain text.
+- `src/tests.rs`: round-trip parse/serialize cases.
+
+## Scope
+
+- Owns: the mention chip wire format (XML-ish tags embedded in message/doc
+ text) and parsing it into typed references (`macro_user_id`, `BotIdStr`,
+ `ChannelSender`, GitHub PR URLs).
+- Not here: rendering mentions in the UI (web app), or deciding who gets
+ notified for a mention → `model_notifications`, `messages`.
+
+## Boundaries
+
+- Depends on: `bot_id`, `channel_sender`, `macro_user_id`, `nom`.
+- Used by: `authentication_service`, `model_notifications`, `notification_service`,
+ `scheduled_action`, `search_processing_service`, `slack_import_worker`,
+ `slack_integration`.
+
+## Recipes
+
+- Add a new mention chip type: `src/parse.rs` (new `nom` parser + tag) →
+ `src/serialize.rs` (render it back) → `src/tests.rs`.
+
+## Checks
+
+- `cargo test -p mention_utils` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- New chip parsers should use `nom`, matching the rest of this crate, rather
+ than hand-rolled string scanning.
diff --git a/crates/mention_utils/CLAUDE.md b/crates/mention_utils/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/mention_utils/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/messages/AGENTS.md b/crates/messages/AGENTS.md
new file mode 100644
index 0000000000..6c8eb4d98d
--- /dev/null
+++ b/crates/messages/AGENTS.md
@@ -0,0 +1,62 @@
+# messages
+
+## What it is
+
+The messaging/discussions feature: anchored discussions on channels and
+documents. This domain crate owns the models, authorization, and the
+HTTP/Postgres/delivery adapters, feature-gated so callers pull in only what
+they need.
+
+## Start here
+
+- `src/domain/models.rs`: shared message/thread models.
+- `src/domain/service.rs` + `src/domain/ports.rs`: use-case orchestration and
+ the repository/delivery ports (feature `ports`).
+- `src/domain/api.rs`: `MessageServiceApi`, the boundary HTTP/agents/channel
+ adapters call through.
+- `src/inbound/axum_router.rs`: the HTTP surface (feature `inbound`).
+- `src/outbound/pg_message_repo.rs` + `pg_discussion_context.rs`: Postgres
+ adapters (feature `outbound`).
+- `src/outbound/connection_gateway.rs`, `notification_sender.rs`, `broker.rs`:
+ realtime/notification delivery adapters (features `outbound`/`broker`).
+
+## Scope
+
+- Owns: message and discussion domain logic, mentions, notification policy
+ for messages, and their delivery/storage adapters.
+- Not here: channel membership and chat domain logic → `channels`, `chat`;
+ who gets notified in general → `model_notifications`.
+
+## Boundaries
+
+- Depends on (by feature): `entity_access` (ports/inbound), `model` (annotations),
+ `properties`/`models_properties`/`model_notifications`/`notification`
+ (delivery), `initiative` (outbound), `macro_event_broker`/`macro_event_topics`
+ (broker).
+- Used by: `agent_harness`, `agent_session`, `agent_trigger`, `ai_tools`, `bots`,
+ `channel_bots`, `channels`, `coding_agent_worker`, `crm`, `documents`,
+ `lexical_client`, `lexical_mention_extractor`, `macro_db_client`,
+ `soup_realtime`, `webhook`.
+
+## Recipes
+
+- Add a message use case: `src/domain/ports.rs` (port) → `src/domain/service.rs`
+ → `src/domain/api.rs` → `src/inbound/axum_router.rs`.
+- Add a delivery channel: `src/domain/delivery.rs` → new adapter under
+ `src/outbound/` → feature-gate it in `Cargo.toml`.
+
+## Checks
+
+- `cargo test -p messages --all-features` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Most modules are feature-gated (`annotations`, `broker`, `delivery`,
+ `inbound`, `outbound`, `ports`, `schema`); a caller enabling the wrong
+ combination gets a missing-module compile error, not a runtime one — check
+ `Cargo.toml`'s `[features]` table before adding a dependency edge.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/db.md` ·
+ Skill: `collab-surface-core`
diff --git a/crates/messages/CLAUDE.md b/crates/messages/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/messages/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/model/AGENTS.md b/crates/model/AGENTS.md
new file mode 100644
index 0000000000..0084a51c80
--- /dev/null
+++ b/crates/model/AGENTS.md
@@ -0,0 +1,56 @@
+# model
+
+## What it is
+
+Shared infrastructure underlying Documents, chat, and authentication. Core
+wire/domain models for documents, items, chat, projects, threads, and
+authentication — one of the most widely depended-on crates in the backend.
+
+## Start here
+
+- `src/document.rs` + `src/document/`: document models, `DocumentFamily`,
+ file type, listing, and API responses.
+- `src/item.rs` + `src/item/map_item.rs`: the generic item abstraction shared
+ across documents/folders/projects.
+- `src/chat.rs`, `src/thread.rs`, `src/project.rs`: chat, thread, and project
+ models.
+- `src/authentication/`: user, permission, and Google token models.
+- `src/annotations.rs`: PDF/document annotation create/edit/delete payloads.
+
+## Scope
+
+- Owns: the shared request/response and storage-facing models for documents,
+ items, folders, projects, chat, threads, annotations, and authentication.
+- Not here: message/discussion models → `messages`; typed ownership →
+ `model_owner`; entity permissions → `models_permissions`; properties →
+ `models_properties`.
+
+## Boundaries
+
+- Depends on: `model-entity`, `model_owner`, `model_file_type`, `model_user`,
+ `models_permissions`, `models_pagination`, `models_bulk_upload`.
+- Used by: dozens of services and crates — `agent_harness`, `ai_tools`,
+ `authentication_service(_client)`, `chat`, `collab_surface`,
+ `document_storage_service(_client)`, `documents`, `email_service(_client)`,
+ `entity_access`, `macro_db_client`, `messages`, `models_soup`, `projects`,
+ `search_service`, `sync_service_client`, and more — check reverse
+ dependents before changing a public type's shape.
+
+## Recipes
+
+- Add a document-facing field: `src/document.rs` or `src/document/response.rs`
+ → callers in `document_storage_service`, `documents`.
+- Add an annotation operation: `src/annotations.rs` → `src/annotations/{create,edit,delete}.rs`.
+
+## Checks
+
+- `cargo test -p model` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- This crate is a shared dependency for most of the backend; a breaking
+ change to a public struct ripples widely — grep reverse dependents first.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/model/CLAUDE.md b/crates/model/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/model/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/model_notifications/AGENTS.md b/crates/model_notifications/AGENTS.md
new file mode 100644
index 0000000000..3b8711fad1
--- /dev/null
+++ b/crates/model_notifications/AGENTS.md
@@ -0,0 +1,46 @@
+# model_notifications
+
+## What it is
+
+Part of the notifications feature. Wire models for every notification kind
+Macro sends: metadata payloads, the digest state machine, device/unsubscribe
+types.
+
+## Start here
+
+- `src/lib.rs`: `NotificationTemporalData` and the full re-export list of
+ metadata types — the fastest way to see every notification kind that exists.
+- `src/metadata.rs` + `src/metadata/`: one metadata struct per notification
+ kind (channel, CRM discussion, initiative discussion, GitHub PR, reminder, …).
+- `src/digest_state.rs`: the digest batching state machine.
+- `src/device.rs`, `src/unsubscribe.rs`: device type and per-user unsubscribe.
+
+## Scope
+
+- Owns: the typed payload for each notification kind and digest/unsubscribe
+ state. Not the decision of *who* gets notified or delivery — those are
+ `notification`/`notification_service`.
+
+## Boundaries
+
+- Depends on: `macro_user_id`, `mention_utils`, `model-entity`, `model_owner`,
+ `models_pagination`, `notification`, `invite_email`.
+- Used by: `agent_harness`, `ai_tools`, `authentication_service`,
+ `calendar_events`, `channels`, `complete_graph`, `document_cognition_service`,
+ `document_storage_service`, `email_formatting`, `email_service`, `github`,
+ `graphql_notification`, `graphql_work_feed`, `messages`, `notification_db_client`,
+ `notification_service`, `properties`, `reminders`, `teams`, `work_feed`.
+
+## Recipes
+
+- Add a new notification kind: new struct in `src/metadata/<area>.rs` (or
+ `src/metadata.rs` for a small one) → re-export from `src/lib.rs` →
+ `notification_service` (dispatch) → `notification_db_client` (storage).
+
+## Checks
+
+- `cargo test -p model_notifications` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/model_notifications/CLAUDE.md b/crates/model_notifications/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/model_notifications/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/model_owner/AGENTS.md b/crates/model_owner/AGENTS.md
new file mode 100644
index 0000000000..c94f82f684
--- /dev/null
+++ b/crates/model_owner/AGENTS.md
@@ -0,0 +1,47 @@
+# model_owner
+
+## What it is
+
+Shared infrastructure used by nearly every domain crate with typed
+ownership. A typed owner reference (`Owner`/`OwnerType`) for Macro entities
+— a user, bot, or team principal, distinct from the acting user.
+
+## Start here
+
+- `src/lib.rs`: `Owner`, `OwnerType`, parsing/display of the
+ `user|bot|team` principal string forms.
+- `src/creation_principal.rs`: `CreationPrincipal` — who created an entity,
+ separate from who owns it.
+- `src/team.rs`: team-link audience policy (`OwnerTeamFacts`) — who an
+ owner's team-link grants access to; PostgreSQL's `owner_team` is the
+ set-based twin of this function and is tested against it.
+
+## Scope
+
+- Owns: the `Owner`/`OwnerType`/`CreationPrincipal` value types and the
+ team-audience policy function.
+- Not here: whether an owner actually has access to an entity →
+ `models_permissions`, `entity_access`.
+
+## Boundaries
+
+- Depends on: `bot_id`, `macro_user_id`.
+- Used by: nearly every domain crate with typed ownership — `agent_session`,
+ `agent_trigger`, `bots`, `channels`, `databases_sql`, `documents`,
+ `entity_access`, `entity_registry`, `model`, `model_notifications`,
+ `models_permissions`, `models_soup`, `projects`, `scheduled_action`,
+ `soup`, `teams`, and more.
+
+## Checks
+
+- `cargo test -p model_owner` (`SQLX_OFFLINE` unset; enable the `sqlx` feature
+ to exercise the Postgres type impl: `cargo test -p model_owner --features sqlx`).
+
+## Gotchas
+
+- `team.rs`'s `OwnerTeamFacts` must stay in lockstep with the `owner_team` SQL
+ set logic — a behavior change needs matching adapter tests on both sides.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/model_owner/CLAUDE.md b/crates/model_owner/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/model_owner/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/models_databases/AGENTS.md b/crates/models_databases/AGENTS.md
new file mode 100644
index 0000000000..bd84eb6eae
--- /dev/null
+++ b/crates/models_databases/AGENTS.md
@@ -0,0 +1,53 @@
+# models_databases
+
+## What it is
+
+Part of Macro Databases. The typed write vocabulary: ops, cell/column/view
+types, the cast rule, and fractional-index position keys — shared by the SQL
+engine (which also runs in the browser via wasm), the HTTP API, and the
+domain.
+
+## Start here
+
+- `src/ops.rs`: `DatabaseOp` and the row/column/view change/result types —
+ the core vocabulary everything else is built from.
+- `src/cast.rs`: the cell-value casting rule between column kinds.
+- `src/views.rs` + `src/views/`: view filter/sort evaluation (`eval.rs`),
+ Kanban lane keys (`lane_key.rs`, `lanes.rs`).
+- `src/formula.rs`: derived/formula column types.
+- `src/position.rs`: fractional-index row/column ordering.
+- `src/ids.rs`: all database id newtypes (`DatabaseId`, `TableId`, `RowId`, …).
+
+## Scope
+
+- Owns: the write-op vocabulary, cell casting, view evaluation, and position
+ keys — kept wasm-safe (no `workspace-hack` dependency; see `.config/hakari.toml`).
+- Not here: SQL execution or the domain port → `database_sql`, `databases_sql`;
+ Forms (a view of one table) → `models_forms`.
+
+## Boundaries
+
+- Depends on: `fractional_index`, `macro_user_id`, `macro_uuid` — no
+ `workspace-hack`, so new dependencies must stay wasm-compatible.
+- Used by: `crm`, `databases`, `database_sql`, `databases_sql`,
+ `document_storage_service`, `forms`, `graphql_crm`, `models_forms`.
+
+## Recipes
+
+- Add a column kind: `src/ops.rs` (`ColumnKind`, `CellValue`) → `src/cast.rs`
+ (casting rules) → `src/views/eval.rs` if it affects filtering/sorting →
+ consumers in `database_sql`/`databases_sql`.
+- Add a formula operator: `src/formula.rs` → `database_sql`'s formula evaluator.
+
+## Checks
+
+- `cargo test -p models_databases` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Stay wasm-safe: don't add a dependency that isn't already wasm-compatible,
+ and don't add `workspace-hack`.
+
+## Related
+
+- Skill: `database-core`
diff --git a/crates/models_databases/CLAUDE.md b/crates/models_databases/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/models_databases/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/models_email/AGENTS.md b/crates/models_email/AGENTS.md
new file mode 100644
index 0000000000..d8cb33d0de
--- /dev/null
+++ b/crates/models_email/AGENTS.md
@@ -0,0 +1,36 @@
+# models_email
+
+## What it is
+
+Part of the Email feature. Wire models for email and Gmail sync:
+thread/message API types, DB row types, and Gmail API response shapes.
+
+## Start here
+
+- `src/email/mod.rs` → `api`, `db`, `service`: the three-layer email model
+ split (API-facing, DB row, service-layer), mirroring `models_properties`.
+- `src/gmail.rs` + `src/gmail/`: Gmail API response types — `contacts.rs`,
+ `filters.rs`, `history.rs`, `inbox_sync.rs`, `labels.rs`, `gmail_ops.rs`,
+ `operations.rs`.
+
+## Scope
+
+- Owns: email/Gmail wire and DB-row models shared across email services.
+- Not here: calendar sync (moved out, see `#6826`) → `calendar_events`;
+ actual IMAP/SMTP or Gmail API calls → `email_service`, `gmail_client`.
+
+## Boundaries
+
+- Depends on: `email_utils`, `macro_user_id`, `models_pagination`.
+- Used by: `ai_tools`, `calendar_service`, `email_api_client`, `email_db_client`,
+ `email_refresh_handler`, `email_scheduled_handler`, `email_service(_client)`,
+ `gmail_client`, `search_processing_service`, `search_service`, `sqs_client`,
+ `teams`.
+
+## Checks
+
+- `cargo test -p models_email` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/models_email/CLAUDE.md b/crates/models_email/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/models_email/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/models_forms/AGENTS.md b/crates/models_forms/AGENTS.md
new file mode 100644
index 0000000000..a214e6cfd8
--- /dev/null
+++ b/crates/models_forms/AGENTS.md
@@ -0,0 +1,43 @@
+# models_forms
+
+## What it is
+
+Part of Macro Forms. The wire vocabulary: ids, layout, answers, submission
+outcomes, and summaries. A form is a view of one database table — answers
+reuse `models_databases` cells, gate rules reuse its filters, unchanged.
+
+## Start here
+
+- `src/form.rs`: `Form`, `CreateForm`, `UpdateForm`, `Audience`, `FormStatus`.
+- `src/layout.rs`: `FormLayout`/`FormSection` — how a table's columns map to
+ form questions, including booking sections (`BookingTarget`).
+- `src/response.rs`: `FormResponse`, `Answer`, tallying (`FormTally`,
+ `QuestionTally`) and `SubmissionOutcome`.
+- `src/detail.rs`: the expanded detail shape (`FormDetail`,
+ `FormQuestionDetail`) used by the builder UI.
+- `src/collaboration.rs`: `FormCollaboration`, `FormPublicationProblem`.
+
+## Scope
+
+- Owns: form ids, layout, response/tally, and error types.
+- Not here: database ops/cells/filters (reused as-is) → `models_databases`;
+ form service logic and storage → `forms`.
+
+## Boundaries
+
+- Depends on: `macro_uuid`, `models_databases` (feature `schema` forwards to
+ `models_databases/schema`).
+- Used by: `forms`.
+
+## Recipes
+
+- Add a question/layout kind: `src/layout.rs` → `src/detail.rs` →
+ `src/response.rs` (answer/tally shape) → `forms` service.
+
+## Checks
+
+- `cargo test -p models_forms` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Skill: `database-core`
diff --git a/crates/models_forms/CLAUDE.md b/crates/models_forms/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/models_forms/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/models_pagination/AGENTS.md b/crates/models_pagination/AGENTS.md
new file mode 100644
index 0000000000..24fdcffbc2
--- /dev/null
+++ b/crates/models_pagination/AGENTS.md
@@ -0,0 +1,47 @@
+# models_pagination
+
+## What it is
+
+Shared infrastructure. Typesafe, generic cursor pagination and simple sort
+methods, shared by almost every list endpoint in the backend.
+
+## Start here
+
+- `src/cursor.rs`: `Identify`, `Sortable`, `SortOn`, `Paginate`/`Paginated` —
+ the three traits an item/sort method must implement to be paginated, plus
+ the opaque base64 cursor types.
+- `src/sort.rs`: concrete sort methods (`CreatedAt`, `Frecency`, `NotifiedAt`,
+ `TouchedByMe`, `SimpleSortMethod`).
+- `src/collections.rs`: `CollectBy`/`CollectByIds` helpers.
+- `src/axum.rs` (feature `axum`): `BidirectionalCursor` extractor.
+
+## Scope
+
+- Owns: the cursor encoding, sort trait contracts, and axum query extraction
+ for paginated list endpoints.
+- Not here: the actual query/sort implementation for a given entity — that
+ lives in the owning domain crate (e.g. `soup`, `messages`).
+
+## Boundaries
+
+- Depends on: nothing domain-specific — pure pagination machinery
+ (`base64`, `ordered-float`, optional `axum`/`model-error-response`).
+- Used by: most list-returning crates — `ai_tools`, `calendar_events`, `call`,
+ `channels`, `complete_graph`, `databases_sql`, `email`, `email_db_client`,
+ `foreign_entity`, `github_pull_requests`, `graphql_activity`,
+ `graphql_calendar`, `graphql_initiative`, `graphql_soup`, `macro_db_client`,
+ `messages`, `model`, `model_notifications`, `models_email`, `models_soup`,
+ `notification`, `notification_db_client`, `skills`, `soup`, `teams`.
+
+## Recipes
+
+- Add a new sort method: `src/sort.rs` (impl `Sortable`/`SortOn`) → the
+ caller's `Identify` impl for its item type → its list query.
+
+## Checks
+
+- `cargo test -p models_pagination` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/models_pagination/CLAUDE.md b/crates/models_pagination/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/models_pagination/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/models_permissions/AGENTS.md b/crates/models_permissions/AGENTS.md
new file mode 100644
index 0000000000..781e7a5c2b
--- /dev/null
+++ b/crates/models_permissions/AGENTS.md
@@ -0,0 +1,46 @@
+# models_permissions
+
+## What it is
+
+Part of entity sharing/permissions, used across nearly every feature. Wire
+models for entity sharing: share permissions (user/team/link), access
+levels, and the computed `UserItemAccess` a caller has to an entity.
+
+## Start here
+
+- `src/share_permission.rs` + `src/share_permission/`: `SharePermissionV2`,
+ `access_level.rs` (`AccessLevel`), `channel_share_permission.rs`,
+ `team_share.rs`, `link_share.rs` (`LinkShare`).
+- `src/user_item_access.rs`: the resolved access an actor has to an item.
+
+## Scope
+
+- Owns: the share permission and access-level wire models.
+- Not here: authorization decisions or resolving access → `entity_access`,
+ `macro_authorization`; typed ownership → `model_owner`.
+
+## Boundaries
+
+- Depends on: `macro_user_id`, `model-entity`, `model_file_type`, `model_owner`.
+- Used by: `agent_session`, `ai_tools`, `authentication_service`, `call`,
+ `channels`, `chat`, `collab_surface`, `databases`, `document_cognition_service`,
+ `documents`, `document_storage_service(_client)`, `email_service`,
+ `entity_access(_db_utils)`, `entity_access_management`, `entity_mutation`,
+ `forms`, `github`, `graphql_entity_mutation`, `graphql_initiative`,
+ `initiative`, `macro_db_client`, `macro_middleware`, `model`, `projects`,
+ `properties`, `scheduled_action`, `share_permission_db_utils`, `teams`.
+
+## Recipes
+
+- Add a share kind (e.g. a new link-share variant): `src/share_permission/link_share.rs`
+ (or `team_share.rs`/`channel_share_permission.rs`) →
+ `src/share_permission/access_level.rs` if it changes effective access →
+ `share_permission_db_utils` (storage) → `entity_access` (resolution).
+
+## Checks
+
+- `cargo test -p models_permissions` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/models_permissions/CLAUDE.md b/crates/models_permissions/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/models_permissions/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/models_properties/AGENTS.md b/crates/models_properties/AGENTS.md
new file mode 100644
index 0000000000..7965bfbcc5
--- /dev/null
+++ b/crates/models_properties/AGENTS.md
@@ -0,0 +1,56 @@
+# models_properties
+
+## What it is
+
+Part of the custom-properties feature (custom fields on documents, CRM
+records, and other entities). Data models for the custom-properties system,
+split into three layers plus a `shared` layer used by all of them.
+
+## Start here
+
+- `src/shared/`: `EntityType`, `DataType`, `EntityReference`, `PropertyOwner`
+ — used by every layer below.
+- `src/db/`: database-row types (`entity_property.rs`,
+ `property_definition.rs`, `property_option.rs`) — used only by the
+ `properties` crate's outbound adapters.
+- `src/service/`: business-logic types used within `properties_service`
+ (property values, tag sets, per-entity-kind metadata like
+ `document_metadata.rs`, `thread_metadata.rs`).
+- `src/api/`: external-facing request/response types (`requests.rs`,
+ `responses.rs`, `property_target.rs`, `query_params.rs`).
+
+## Scope
+
+- Owns: the property system's models across its three layers, converted
+ db → service → api.
+- Not here: property authorization or storage logic → `properties`,
+ `properties_service`.
+
+## Boundaries
+
+- Depends on: `document_sub_type`.
+- Used by: `agent_trigger`, `ai_tools`, `complete_graph`, `crm`, `databases`,
+ `databases_sql`, `documents`, `document_storage_service`, `email_service`,
+ `forms`, `graphql_common`, `graphql_crm`, `graphql_initiative`,
+ `graphql_properties`, `graphql_soup`, `import`, `initiative`, `messages`,
+ `models_soup`, `properties`, `properties_service`, `scheduled_action`,
+ `search_service`, `soup`, `soup_realtime`, `system_properties`.
+
+## Recipes
+
+- Add a property-backed field for a new entity kind: `src/shared/entity_type.rs`
+ → `src/db/entity_property.rs` → `src/service/<kind>_metadata.rs` →
+ `src/api/responses.rs`.
+
+## Checks
+
+- `cargo test -p models_properties` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Respect the layering: `api` types convert from `service` types, which
+ convert from `db` types — don't reach from `api` straight into `db`.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/models_properties/CLAUDE.md b/crates/models_properties/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/models_properties/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/models_search/AGENTS.md b/crates/models_search/AGENTS.md
new file mode 100644
index 0000000000..b7fbe54cb9
--- /dev/null
+++ b/crates/models_search/AGENTS.md
@@ -0,0 +1,50 @@
+# models_search
+
+## What it is
+
+Part of the Search feature. Wire models for OpenSearch-backed full-text
+search results, one module per indexed entity kind, plus the unified
+cross-entity response.
+
+## Start here
+
+- `src/unified.rs`: `UnifiedSearchResponse` — combines every entity kind's
+ search item into one ranked response; the best map of what's indexed.
+- `src/document.rs`, `src/chat.rs`, `src/channel.rs`, `src/email.rs`,
+ `src/call_record.rs`, `src/crm_company.rs`, `src/calendar_event.rs`,
+ `src/agent_session.rs`, `src/project.rs`: per-entity response item types.
+- `src/score.rs`: relevance scoring types.
+- `src/simple.rs`: the simpler "goto" search response variants.
+
+## Scope
+
+- Owns: search response models per indexed entity kind and the unified
+ response shape.
+- Not here: the OpenSearch query/index logic itself → `search_service`,
+ `search_processing_service`; the indexed doc models → `models_opensearch`.
+
+## Boundaries
+
+- Depends on: `item_filters`, `model_file_type`, `models_opensearch`,
+ `models_soup`, `opensearch_client`, `document_sub_type`.
+- Used by: `ai_tools`, `search_processing_service`, `search_service(_client)`,
+ `skills`.
+
+## Recipes
+
+- Add a new indexed entity kind to search: new `src/<kind>.rs` → add its
+ variant to `src/unified.rs` → `search_service` (query/index) →
+ `search_processing_service` (indexing pipeline).
+
+## Checks
+
+- `cargo test -p models_search` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- An indexed `owner_id` is the owner's canonical principal string ("Mine"
+ filters compare it directly); preserve prefixes like `bot|` when indexing.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/models_search/CLAUDE.md b/crates/models_search/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/models_search/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/models_soup/AGENTS.md b/crates/models_soup/AGENTS.md
new file mode 100644
index 0000000000..ba9d92266e
--- /dev/null
+++ b/crates/models_soup/AGENTS.md
@@ -0,0 +1,47 @@
+# models_soup
+
+## What it is
+
+Part of the Soup feed (Home/Recent, the unified activity feed). Shared API
+models: one module per entity kind Soup can surface, plus the unified item
+model.
+
+## Start here
+
+- `src/item.rs`: the unified Soup feed item — the type every entity kind's
+ module converts into.
+- `src/document.rs`, `src/chat.rs`, `src/comms.rs` (channels), `src/crm_company.rs`,
+ `src/crm_contact.rs`, `src/database_row.rs`, `src/email_thread.rs`,
+ `src/initiative.rs`, `src/project.rs`, `src/call_record.rs`,
+ `src/calendar_event.rs`, `src/agent_session.rs`, `src/foreign_entity.rs`:
+ per-entity-kind Soup response models.
+- `src/properties.rs`: `SoupProperty` — properties attached to a Soup item.
+
+## Scope
+
+- Owns: the Soup response model per entity kind and the unified item type.
+- Not here: the GraphQL resolvers or feed query logic → `soup`, `graphql_soup`;
+ the Soup filter DSL → `item_filters`, `soup_filter_projection`.
+
+## Boundaries
+
+- Depends on: `call`, `channels`, `crm`, `document_sub_type`, `doppleganger`,
+ `email`, `macro_user_id`, `model`, `model-entity`, `model_owner`,
+ `models_pagination`, `models_properties`.
+- Used by: `ai_tools`, `complete_graph`, `databases_sql`, `graphql_initiative`,
+ `graphql_soup`, `models_search`, `search_service`, `skills`, `soup`,
+ `soup_filter_projection`, `work_feed`.
+
+## Recipes
+
+- Add a new entity kind to Soup: new `src/<kind>.rs` → wire it into
+ `src/item.rs`'s unified item → `soup` (feed query) →
+ `graphql_soup` (GraphQL exposure).
+
+## Checks
+
+- `cargo test -p models_soup` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/models_soup/CLAUDE.md b/crates/models_soup/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/models_soup/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/name_search/AGENTS.md b/crates/name_search/AGENTS.md
new file mode 100644
index 0000000000..e966d0c547
--- /dev/null
+++ b/crates/name_search/AGENTS.md
@@ -0,0 +1,37 @@
+# name_search
+
+## What it is
+
+Part of the Search feature. Postgres queries for server-side name search
+over channels and chats (used by AI tools and `search_service`'s name-match
+path), plus match highlighting.
+
+## Start here
+
+- `src/channel.rs` + `src/channel/test.rs`: `search_channel_names`.
+- `src/chat.rs` + `src/chat/test.rs`: `search_chat_names`.
+- `src/highlight.rs`: `highlight_name` — marks up matched substrings.
+- `fixtures/`: SQL seed fixtures (`channel.sql`, `chat.sql`, `chat_tags.sql`)
+ used by the tests.
+
+## Scope
+
+- Owns: name-search SQL queries and result cursors for channels/chats.
+- Not here: content/full-text search → `models_search`, `search_service`;
+ the OpenSearch-indexed entity types → `models_opensearch`.
+
+## Boundaries
+
+- Depends on: `channels` (outbound feature), `models_opensearch`,
+ `models_search_cursor`.
+- Used by: `search_service`.
+
+## Checks
+
+- `cargo test -p name_search` (`SQLX_OFFLINE` unset; requires local MacroDB).
+- `nix develop --command just prepare_db` from the repo root if SQLx cache
+ metadata is stale.
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md`
diff --git a/crates/name_search/CLAUDE.md b/crates/name_search/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/name_search/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/native_app_service/AGENTS.md b/crates/native_app_service/AGENTS.md
new file mode 100644
index 0000000000..c707932e74
--- /dev/null
+++ b/crates/native_app_service/AGENTS.md
@@ -0,0 +1,34 @@
+# native_app_service
+
+## What it is
+
+Part of the native apps (Tauri desktop and iOS). Server-side handlers for
+updating them: update checks and version negotiation.
+
+## Start here
+
+- `src/lib.rs`: module map — `domain` (business logic), `inbound` (axum
+ handlers), `outbound` (port implementations).
+- `src/domain/service.rs` + `src/domain/ports.rs`: update-check policy and
+ the ports it depends on.
+- `src/tests.rs`: service-level tests.
+
+## Scope
+
+- Owns: deciding what update (if any) a native app build should receive.
+- Not here: building or publishing the app binaries themselves → the native
+ app's own release pipeline.
+
+## Boundaries
+
+- Depends on: `macro_env_var` for config.
+- Used by: `services/authentication_service` (mounts the router with
+ `axum::Router::with_state`).
+
+## Checks
+
+- `cargo test -p native_app_service` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/guardrails.md`
diff --git a/crates/native_app_service/CLAUDE.md b/crates/native_app_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/native_app_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/notification/AGENTS.md b/crates/notification/AGENTS.md
new file mode 100644
index 0000000000..d0463d574a
--- /dev/null
+++ b/crates/notification/AGENTS.md
@@ -0,0 +1,70 @@
+# notification
+
+## What it is
+
+The notifications feature's hexagonal core. Fans a domain event out to
+in-app realtime (WebSocket/Kafka), push (mobile/web), and email digests, and
+manages per-item preferences, snoozing, and muting.
+
+## How it works
+
+A domain event arrives via HTTP, the queue worker, or the Kafka listener;
+the domain service applies per-user preferences/mute/snooze state, then
+dispatches to whichever outbound adapters apply (realtime fan-out, push,
+digest email). State transitions and device registration are read back
+through the same service.
+
+## Start here
+
+- `src/domain/service.rs` + `src/domain/ports.rs`: the notification policy
+ and every port an adapter must implement.
+- `src/inbound/http.rs`, `src/inbound/worker.rs`,
+ `src/inbound/notification_events_listener.rs`: HTTP routes, the queue
+ worker, and the Kafka event listener that trigger notification creation.
+- `src/outbound/`: one file per channel/concern — `fanout_realtime.rs` +
+ `kafka_realtime.rs` (live WebSocket fan-out), `mobile.rs` + `sns_endpoint.rs`
+ (push), `email.rs` + `digest_batcher.rs` (digest emails), `repository.rs`
+ (Postgres via `notification_db_client`), `item_preferences.rs` (snooze/mute).
+
+## Scope
+
+- Owns: notification creation, read/unread/snooze state transitions,
+ per-channel delivery, and device registration.
+- Not here: the lifecycle state enum itself and its transition rules →
+ `notification_state`; the Postgres queries → `notification_db_client`.
+
+## Boundaries
+
+- Depends on: `notification_db_client`, `notification_state`, `rate_limit`,
+ `macro_authorization`.
+- Used by: most feature crates that need to notify a user (`properties`,
+ `channels`, `reminders`, `teams`, `messages`, `calendar_events`, ...) and
+ `services/notification_service`, `services/agent_harness_service`,
+ `services/email_service`.
+
+## Recipes
+
+- Add a new delivery channel: a port in `src/domain/ports.rs` → an adapter
+ under `src/outbound/` → wire it in the service in `src/domain/service.rs`.
+- Add a new notification trigger: `src/inbound/notification_events_listener.rs`
+ (or the relevant inbound adapter) → `src/domain/models.rs` for the event
+ shape → `src/domain/service.rs`.
+
+## Checks
+
+- `cargo test -p notification` (`SQLX_OFFLINE` unset; needs local MacroDB).
+- `cargo test -p notification --features redis-tests` for the Redis-backed
+ preference paths.
+
+## Gotchas
+
+- Feature flags gate most adapters (`axum`, `ai_tool`, `clear_ios_push`,
+ `schema`); building without the feature a caller needs silently drops the
+ module instead of failing loudly — check `Cargo.toml` before assuming an
+ adapter is compiled in.
+- Notification payloads must not be logged on tracing spans (see the
+ `fix(notification): stop recording notification payloads` history).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/observability.md`
diff --git a/crates/notification/CLAUDE.md b/crates/notification/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/notification/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/notification_db_client/AGENTS.md b/crates/notification_db_client/AGENTS.md
new file mode 100644
index 0000000000..133dec78bf
--- /dev/null
+++ b/crates/notification_db_client/AGENTS.md
@@ -0,0 +1,44 @@
+# notification_db_client
+
+## What it is
+
+Part of the notifications feature. Query-only client for the notification
+tables in MacroDB: devices, user notifications, email-sent/unsubscribe
+records, and mute state.
+
+## Start here
+
+- `src/lib.rs`: the module list — one module per table
+ (`notification/`, `device.rs`, `user_notification/`,
+ `notification_email_sent/`, `unsubscribe/`, `user_mute_notification.rs`,
+ `email_unsubscribe_code.rs`, `channel_notification_email_sent/`).
+- `fixtures/*.sql`: seed data each module's tests build on.
+
+## Scope
+
+- Owns: the `sqlx::query!` call sites for notification-related tables.
+- Not here: the tables' schema/migrations → `crates/macro_db_client/migrations`
+ (search for `create_notification_tables`); notification business logic →
+ `notification`.
+
+## Boundaries
+
+- Depends on: `model_notifications`, `model-entity`, `models_pagination`.
+- Used by: `notification`, `services/notification_service`.
+
+## Recipes
+
+- Add a query to an existing table: the module in `src/<table>/` → its tests
+ → `nix develop --command just prepare_db` from the repo root if SQLx cache
+ metadata is missing.
+- Add a new table: migration in `crates/macro_db_client/migrations` first →
+ new module here, `pub mod` it in `src/lib.rs`.
+
+## Checks
+
+- `cargo test -p notification_db_client` (`SQLX_OFFLINE` unset; requires
+ local MacroDB — `just setup_macrodb`).
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md` · Docs: `docs/development/database.md`
diff --git a/crates/notification_db_client/CLAUDE.md b/crates/notification_db_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/notification_db_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/notification_state/AGENTS.md b/crates/notification_state/AGENTS.md
new file mode 100644
index 0000000000..8e77e896de
--- /dev/null
+++ b/crates/notification_state/AGENTS.md
@@ -0,0 +1,39 @@
+# notification_state
+
+## What it is
+
+Part of the notifications feature. Defines the shared `NotificationState`
+lifecycle enum (`Unseen` / `Seen` / `Done`) and its transition policy, kept
+dependency-light so it compiles to wasm.
+
+## Start here
+
+- `src/lib.rs`: the `NotificationState` enum and its invariants — read the
+ module doc comment first (viewing timestamps are historical metadata, not
+ another state representation).
+- `src/postgres.rs`: the `sqlx::Type` mapping to the Postgres
+ `notification_state` enum, gated behind the `postgres` feature.
+- `src/graphql.rs`: the `async-graphql` enum mapping, gated behind `graphql`.
+
+## Scope
+
+- Owns: the lifecycle enum, its `ACTIVE` set, and (de)serialization across
+ JSON, Postgres, and GraphQL.
+- Not here: how/when a notification transitions in response to app events →
+ `notification`.
+
+## Boundaries
+
+- Used by: `notification`, `item_filters`, `graphql_notification`,
+ `graphql_soup_filter_input` — including wasm builds, so this crate must
+ stay free of non-wasm-safe dependencies outside the optional features.
+
+## Checks
+
+- `cargo test -p notification_state` (`SQLX_OFFLINE` unset).
+- `cargo test -p notification_state --features postgres,graphql` for the
+ adapter mappings.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/notification_state/CLAUDE.md b/crates/notification_state/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/notification_state/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/onboarding/AGENTS.md b/crates/onboarding/AGENTS.md
new file mode 100644
index 0000000000..04d031986b
--- /dev/null
+++ b/crates/onboarding/AGENTS.md
@@ -0,0 +1,45 @@
+# onboarding
+
+## What it is
+
+Part of the onboarding feature (`/setup`). Tracks one row per user for
+whether they are still in the flow, and starts import gather runs when
+connectors authenticate during onboarding.
+
+## Start here
+
+- `src/lib.rs`: crate doc comment — read it first, it states the boundary
+ with `import` precisely.
+- `src/domain/service.rs` + `src/domain/ports.rs`: flow state transitions and
+ the ports they need.
+- `src/outbound/pg_onboarding_repo.rs`: the single Postgres adapter.
+- `src/inbound/axum_router.rs`: the `/setup` HTTP routes.
+
+## Scope
+
+- Owns: the per-user onboarding flag/state and starting auto-import gathers
+ while onboarding is active.
+- Not here: the import machinery itself (staging, dedup, gather/import jobs)
+ → `import`.
+
+## Boundaries
+
+- Depends on: `import`, `mcp_client`, `mcp_select`, `generic_email_domains`,
+ `macro_authorization`.
+- Used by: `services/document_cognition_service`,
+ `services/authentication_service` (onboarding deletes its row during
+ account deletion).
+
+## Checks
+
+- `cargo test -p onboarding` (`SQLX_OFFLINE` unset; requires local MacroDB).
+
+## Gotchas
+
+- Account deletion must delete the `user_onboarding` row explicitly — it is
+ not cascaded (see `fix(auth): delete user_onboarding row during account
+ deletion`).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/onboarding/CLAUDE.md b/crates/onboarding/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/onboarding/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/opensearch_client/AGENTS.md b/crates/opensearch_client/AGENTS.md
new file mode 100644
index 0000000000..85880ae761
--- /dev/null
+++ b/crates/opensearch_client/AGENTS.md
@@ -0,0 +1,48 @@
+# opensearch_client
+
+## What it is
+
+Part of the Search feature. Typed client for Macro's search index:
+per-entity-type upsert/delete and search for documents, emails, channel
+messages, chats, agent sessions, calendar events, call records, and
+projects.
+
+## Start here
+
+- `src/lib.rs`: `OpensearchClient` construction (URL + basic auth).
+- `src/upsert/<entity>.rs` + `src/delete/<entity>.rs`: one pair per indexed
+ entity type — the shape each indexer must produce.
+- `src/search/builder.rs` + `src/search/unified.rs`: the cross-entity search
+ request builder and the unified result model.
+- `examples/`: runnable usage beyond the README.
+
+## Scope
+
+- Owns: index document shapes, OpenSearch request/response mapping, and the
+ unified search query across entity types.
+- Not here: the generic query DSL used to build those requests →
+ `opensearch_query_builder`; deciding what gets (re)indexed and when →
+ `search_service`, `services/search_processing_service`.
+
+## Boundaries
+
+- Depends on: `opensearch_query_builder`, `models_opensearch`,
+ `models_search_cursor`.
+- Used by: `models_search`, `search_service`,
+ `services/document_storage_service`, `services/search_processing_service`.
+
+## Recipes
+
+- Index a new entity type: add `src/<entity>.rs` (doc shape) →
+ `src/upsert/<entity>.rs` + `src/delete/<entity>.rs` → a `src/search/<entity>.rs`
+ query if it needs its own search endpoint → wire into
+ `services/search_processing_service`.
+
+## Checks
+
+- `cargo test -p opensearch_client` (`SQLX_OFFLINE` unset; needs a running
+ OpenSearch — see `crates/opensearch_query_builder/docker-compose.yml`).
+
+## Related
+
+- Docs: `README.md`, `examples/`
diff --git a/crates/opensearch_client/CLAUDE.md b/crates/opensearch_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/opensearch_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/opensearch_query_builder/AGENTS.md b/crates/opensearch_query_builder/AGENTS.md
new file mode 100644
index 0000000000..9db70cd67a
--- /dev/null
+++ b/crates/opensearch_query_builder/AGENTS.md
@@ -0,0 +1,41 @@
+# opensearch_query_builder
+
+## What it is
+
+Part of the Search feature. Type-safe builders for OpenSearch query DSL
+and request bodies (bool, match, range, nested, terms, function_score,
+...), each implementing `ToOpenSearchJson`, used by `opensearch_client`.
+
+## Start here
+
+- `src/lib.rs`: the `ToOpenSearchJson` trait and the public re-exports — the
+ crate's whole surface.
+- `src/query/`: one file per query type.
+- `src/request.rs` + `src/request/`: sort, highlight, collapse, and
+ aggregation request fragments.
+
+## Scope
+
+- Owns: building valid OpenSearch JSON query/request bodies from typed Rust
+ structs.
+- Not here: knowing which entity fields to query or how to index documents
+ → `opensearch_client`.
+
+## Boundaries
+
+- Used by: `opensearch_client` only.
+
+## Recipes
+
+- Add a new query type: `src/query/<name>.rs` (struct + builder + `impl
+ ToOpenSearchJson`) → `pub use` it in `src/lib.rs` → `src/query.rs` module
+ declaration.
+
+## Checks
+
+- `cargo test -p opensearch_query_builder` (`SQLX_OFFLINE` unset).
+- `docker-compose.yml` here starts a local OpenSearch for `examples/`.
+
+## Related
+
+- Docs: `README.md`, `examples/`
diff --git a/crates/opensearch_query_builder/CLAUDE.md b/crates/opensearch_query_builder/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/opensearch_query_builder/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/pipedream_mcp/AGENTS.md b/crates/pipedream_mcp/AGENTS.md
new file mode 100644
index 0000000000..218e18108c
--- /dev/null
+++ b/crates/pipedream_mcp/AGENTS.md
@@ -0,0 +1,39 @@
+# pipedream_mcp
+
+## What it is
+
+Part of the AI agent tools feature. Lets users connect third-party apps
+through Pipedream Connect (Pipedream owns grants/tokens/refresh), and the
+AI loop calls their tools through Pipedream's remote MCP server.
+
+## Start here
+
+- `src/lib.rs`: crate doc comment — explains why this is fully separate from
+ the native `mcp_client` stack.
+- `src/domain/ports.rs` + `src/domain/models.rs`: connection model and ports.
+- `src/outbound/api.rs`: the Pipedream HTTP API client.
+- `src/outbound/pg_connection_repo.rs`: the `pipedream_mcp_connections` table.
+- `src/inbound/toolset.rs`: how connected apps surface as agent tools.
+
+## Scope
+
+- Owns: Pipedream connect-flow state, the `pipedream_mcp_connections` table,
+ and loading a user's Pipedream tools into the agent toolset.
+- Not here: deciding whether a user's tools come from Pipedream or the native
+ MCP stack → `mcp_select`.
+
+## Boundaries
+
+- Depends on: `ai_toolset`, `mcp_toolset`, `macro_authorization`,
+ `macro_user_id`.
+- Used by: `ai_tools`, `agent_egress`, `agent_harness`, `mcp_select`,
+ `services/document_cognition_service`, `services/mcp_service`,
+ `services/agent_harness_service`.
+
+## Checks
+
+- `cargo test -p pipedream_mcp` (`SQLX_OFFLINE` unset; requires local MacroDB).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/pipedream_mcp/CLAUDE.md b/crates/pipedream_mcp/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/pipedream_mcp/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/pptx_engine/AGENTS.md b/crates/pptx_engine/AGENTS.md
new file mode 100644
index 0000000000..08c9284b0b
--- /dev/null
+++ b/crates/pptx_engine/AGENTS.md
@@ -0,0 +1,48 @@
+# pptx_engine
+
+## What it is
+
+Part of the Documents feature (presentations). A from-scratch PowerPoint
+(`.pptx`) engine — parse, render, edit, and save — compiled both natively
+and to WebAssembly for the browser presentation editor.
+
+## Start here
+
+- `README.md`: architecture, the editing model, testing, and known gaps —
+ read before `src/lib.rs`.
+- `src/edit/ops.rs`: the `EditOp` vocabulary shared by the browser editor and
+ the `EditPresentation` AI tool.
+- `src/model.rs` + `src/opc.rs` + `src/xml.rs`: the part/model/XML layers
+ edits and rendering both go through.
+- `src/wasm.rs`: the wasm-bindgen API surface for the browser worker.
+
+## Scope
+
+- Owns: `.pptx` parsing, the editable presentation model, rendering,
+ editing, collaboration mapping, and fidelity scoring.
+- Not here: the browser worker that hosts this engine →
+ `apps/web/src/lib/core/pptx-engine`; AI tool wiring → `documents`.
+
+## Boundaries
+
+- Used by: `docx_engine` (shared containers/fonts/rasterizer), `documents`
+ (AI tools), `services/convert_service`.
+
+## Recipes
+
+- Add an edit operation: `src/edit/ops.rs` (variant + schema) →
+ `src/edit.rs`/the relevant `src/edit/<area>.rs` (apply logic) →
+ `src/edit/test.rs` → corpus round-trip check.
+- Add a render feature: `src/model/` (data) → `src/render/` (scene/paint) →
+ `src/render/test.rs` + the corpus baseline (`tests/corpus/README.md`).
+
+## Checks
+
+- `cargo test -p pptx_engine` (`SQLX_OFFLINE` unset) — includes the corpus
+ regression test against `tests/corpus/baseline.json`.
+- `cargo test -p pptx_engine --features cli` for the `pptx_corpus` CLI.
+- `just build-pptx-engine-wasm` (from `apps/web`) for the wasm build.
+
+## Related
+
+- Docs: `README.md`, `tests/corpus/README.md`
diff --git a/crates/pptx_engine/CLAUDE.md b/crates/pptx_engine/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/pptx_engine/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/projects/AGENTS.md b/crates/projects/AGENTS.md
new file mode 100644
index 0000000000..c95f31414e
--- /dev/null
+++ b/crates/projects/AGENTS.md
@@ -0,0 +1,48 @@
+# projects
+
+## What it is
+
+Part of the Projects feature (folder organization for documents and other
+entities). Owns the project entity: hierarchy, sharing/team-share policy,
+soft delete/restore/purge, and bulk upload into a project tree.
+
+## Start here
+
+- `src/domain/ports.rs`: `ProjectRepo`, `ProjectService`, and the upload/search
+ ports — start here to see the contract before the implementation.
+- `src/domain/service.rs`: the concrete service (access checks, team-share
+ authorization, soft-delete/restore/purge, bulk upload orchestration).
+- `src/domain/events.rs`: the `ProjectMacroEvent` variants published to the
+ event broker.
+- `src/outbound/pg_project_repo.rs`, `src/outbound/dynamo_bulk_upload.rs`,
+ `src/outbound/s3_upload_urls.rs`, `src/outbound/sqs_search_indexer.rs`:
+ the adapters behind those ports.
+
+## Scope
+
+- Owns: project CRUD, hierarchy, team-share authorization for projects, and
+ bulk-upload-into-project orchestration.
+- Not here: generic item access/sharing primitives → `entity_access`,
+ `entity_access_management`; property values on a project → `properties`.
+
+## Boundaries
+
+- Depends on: `entity_access`, `entity_access_management`,
+ `macro_event_broker`, `model_owner`, `models_permissions`.
+- Used by: `ai_tools` (project tools), `soup_realtime`,
+ `services/deleted_item_poller`, `services/search_processing_service`.
+
+## Recipes
+
+- Add a mutation route: `src/domain/ports.rs` (`ProjectService` method) →
+ `src/domain/service.rs` → `src/inbound/axum_router.rs`.
+- Add an AI tool: `src/inbound/toolset.rs` → the `ai_tools` feature gate in
+ `Cargo.toml`.
+
+## Checks
+
+- `cargo test -p projects` (`SQLX_OFFLINE` unset; requires local MacroDB).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/security.md`
diff --git a/crates/projects/CLAUDE.md b/crates/projects/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/projects/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/prompt/AGENTS.md b/crates/prompt/AGENTS.md
new file mode 100644
index 0000000000..d10f4443f8
--- /dev/null
+++ b/crates/prompt/AGENTS.md
@@ -0,0 +1,43 @@
+# prompt
+
+## What it is
+
+Part of the agent sessions feature. Static prompt fragments composed into
+AI system prompts: one module per prompt section, each exporting a
+`StaticPrompt` (or a dynamically-built `ComposedPrompt`) that chains via
+`StaticPrompt::compose`.
+
+## Start here
+
+- `src/lib.rs`: the module list — one file per topic (`about_macro.rs`,
+ `agent_identity.rs`, `mentions.rs`, `databases.rs`, `crm_pipelines.rs`, ...).
+- `src/types.rs`: `StaticPrompt` and `ComposedPrompt` — the composition
+ mechanism every module uses.
+- `src/databases.rs` / `src/crm_pipelines.rs`: examples pairing a `.rs` module
+ with a sibling `.md` file for the actual prompt text.
+
+## Scope
+
+- Owns: the wording of static, reusable prompt sections and how they compose.
+- Not here: deciding which sections go into a given agent's final prompt, or
+ per-turn dynamic context → `agent`, `agent_harness`.
+
+## Boundaries
+
+- Used by: `ai_tools`, `agent_inmem`, `channel_bots`, `agent`,
+ `system_skills`, `services/document_cognition_service`,
+ `services/mcp_service`, `services/agent_harness_service`.
+
+## Recipes
+
+- Add a prompt section: new `src/<topic>.rs` (+ `src/<topic>.md` if the text
+ is long) exporting a `pub static PROMPT: StaticPrompt` → `pub mod` it in
+ `src/lib.rs` → compose it where the caller builds its prompt.
+
+## Checks
+
+- `cargo test -p prompt` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/prompt/CLAUDE.md b/crates/prompt/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/prompt/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/properties/AGENTS.md b/crates/properties/AGENTS.md
new file mode 100644
index 0000000000..6f550bf42c
--- /dev/null
+++ b/crates/properties/AGENTS.md
@@ -0,0 +1,54 @@
+# properties
+
+## What it is
+
+Part of the Databases and CRM features. Entity properties: definitions,
+selectable options (including tags), per-entity values, and the CRM
+pipeline/stage definitions built on them. Publishes property mutation
+events to the `macro.properties` Kafka topic.
+
+## Start here
+
+- `README.md`: the published event catalog (`property.created`,
+ `entity_property.updated`, ...) — read before changing anything that writes
+ a property or option.
+- `src/domain/service_impl.rs` + `src/domain/ports.rs`: the service and the
+ writer/notification/permission ports it composes.
+- `src/domain/model.rs`: `EntityPropertiesKey`, `PropertyTargetKey`, and the
+ CRM team-stage definition constant.
+- `src/outbound/properties_pg_repo.rs` +
+ `src/outbound/*_queries.rs`: the Postgres adapters, one file per concern
+ (definitions, options, entity values, metadata, tag promotion).
+
+## Scope
+
+- Owns: property definitions/options/values and tag promotion across entity
+ types.
+- Not here: the generic database engine (tables/columns/cells) → `databases`;
+ notification delivery → `notification`.
+
+## Boundaries
+
+- Depends on: `entity_access`, `macro_event_broker`, `model_owner`,
+ `notification` (optional, `outbound` feature).
+- Used by: `databases`, `ai_tools`, `agent_trigger`, `initiative`, `messages`,
+ `search_service`, `soup`, `crm`, `graphql_properties`, `properties_service`,
+ `services/document_storage_service`, `services/agent_trigger_service`,
+ `services/search_processing_service`.
+
+## Recipes
+
+- Add a property event: `src/domain/events.rs` → emit it in
+ `src/domain/service_impl.rs` after the write succeeds → document it in
+ `README.md`'s event table.
+- Add a query: `src/outbound/<concern>_queries.rs` → its sibling `_test.rs`.
+
+## Checks
+
+- `cargo test -p properties` (`SQLX_OFFLINE` unset; requires local MacroDB).
+- `cargo test -p properties --no-default-features --features outbound` to
+ check the outbound-only build other services depend on.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md` · Docs: `README.md`
diff --git a/crates/properties/CLAUDE.md b/crates/properties/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/properties/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/properties/README.md b/crates/properties/README.md
index 5b0c09f307..8783114451 100644
--- a/crates/properties/README.md
+++ b/crates/properties/README.md
@@ -163,11 +163,10 @@ no-op default and do not publish property events:
- `crates/properties_service/src/api/context.rs` omits the broker generic from
its concrete `PropertiesService` alias.
-- `crates/ai_tools/src/tool_context.rs` omits the broker generic from
- `ToolPropertiesService`, and `build_properties_service` does not attach a
- broker. Property and task-property writes through contexts built there,
- including document cognition, MCP, memory, and the shared AI tool context,
- therefore do not publish.
+- `crates/ai_tools/src/tool_context.rs` builds `ToolPropertiesService` over
+ `MaybeToolEventBroker`. Hosts that call `build_properties_service_with_broker`
+ publish; `build_properties_service` uses the no-op variant, so writes through
+ hosts that build it that way (no Kafka configured) do not publish.
These are explicit producer coverage boundaries, not fallback delivery paths.
diff --git a/crates/properties_service/AGENTS.md b/crates/properties_service/AGENTS.md
new file mode 100644
index 0000000000..7b17c80344
--- /dev/null
+++ b/crates/properties_service/AGENTS.md
@@ -0,0 +1,41 @@
+# properties_service
+
+## What it is
+
+Part of the Databases and CRM features. Composition shim binding the
+`properties` crate's axum router to concrete domain and authorization
+service types, for embedding in a host service.
+
+Note: `README.md` describes an older, service-owned-logic shape
+(`properties_db_client`, `local_auth`) that no longer matches this crate —
+the routes and domain logic now live entirely in `properties`.
+
+## Start here
+
+- `src/api/context.rs`: the concrete type aliases (`PropertiesService`,
+ `AuthorizationServiceType`, `PropertiesHandlerState`) — this is the whole
+ wiring decision this crate makes.
+- `src/api.rs`: `router()`, which just returns
+ `properties::inbound::axum_router::router()`.
+- `src/openapi.rs`: the standalone OpenAPI-generation binary
+ (`properties_service_openapi`).
+
+## Scope
+
+- Owns: picking concrete adapter types (Postgres repo, MacroAuthorization,
+ SQS notification ingress) for `properties`' generic router.
+- Not here: route handlers or domain logic → `properties`.
+
+## Boundaries
+
+- Depends on: `properties`, `entity_access`, `macro_authorization`,
+ `notification`.
+- Used by: `services/document_storage_service`.
+
+## Checks
+
+- `cargo test -p properties_service` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/properties_service/CLAUDE.md b/crates/properties_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/properties_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/psd_engine/AGENTS.md b/crates/psd_engine/AGENTS.md
new file mode 100644
index 0000000000..cc6409502b
--- /dev/null
+++ b/crates/psd_engine/AGENTS.md
@@ -0,0 +1,48 @@
+# psd_engine
+
+## What it is
+
+Part of the Documents feature (image editing). A from-scratch Photoshop
+(`.psd`/`.psb`) engine — read, composite, edit with undo, collaborate, and
+save — compiled both natively and to WebAssembly for the browser Photoshop
+editor.
+
+## Start here
+
+- `README.md`: the PSD format primer and module map — read before
+ `src/lib.rs`.
+- `src/document.rs`: the editable document model edits and rendering go
+ through.
+- `src/edit/ops.rs`: the edit operation vocabulary.
+- `src/collab.rs` + `src/collab/tile.rs`: the CRDT mapping and fractional
+ tile ordering (uses `fig_engine`'s fractional positions).
+- `src/wasm.rs`: the wasm-bindgen API surface for the browser worker.
+
+## Scope
+
+- Owns: `.psd`/`.psb` parsing, compositing, editing, collaboration mapping,
+ and saving.
+- Not here: font registry, glyph outlines, image decoding, the JPEG encoder,
+ and fractional-position ordering primitives → `fig_engine`; the browser
+ worker → `apps/web/src/lib/core/psd-engine`.
+
+## Boundaries
+
+- Depends on: `fig_engine` (default features off).
+- Used by: `documents` (AI tools), `services/search_processing_service`.
+
+## Recipes
+
+- Add an edit operation: `src/edit/ops.rs` → `src/edit.rs`/the relevant
+ `src/edit/<area>.rs` → `src/edit/test.rs`.
+- Add a codec feature (a new tagged block or resource): `src/codec/<area>.rs`
+ → `src/model/<area>.rs` → `src/render/` if it affects compositing.
+
+## Checks
+
+- `cargo test -p psd_engine` (`SQLX_OFFLINE` unset).
+- `cargo test -p psd_engine --features cli` for the `psd_render` CLI.
+
+## Related
+
+- Docs: `README.md`
diff --git a/crates/psd_engine/CLAUDE.md b/crates/psd_engine/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/psd_engine/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/rate_limit/AGENTS.md b/crates/rate_limit/AGENTS.md
new file mode 100644
index 0000000000..65ff7c1e40
--- /dev/null
+++ b/crates/rate_limit/AGENTS.md
@@ -0,0 +1,45 @@
+# rate_limit
+
+## What it is
+
+Part of shared infrastructure. Generic rate limiting: a hashed-key
+sliding-window counter, checked and rolled back atomically via Redis.
+
+## Start here
+
+- `src/domain/ports.rs`: `RateLimitPort` (atomic check/decrement) and
+ `RateLimitService` (ticket-returning `check_rate_limit` +
+ `rollback_ticket`) — read these before the implementation.
+- `src/outbound/redis.rs`: the Redis-backed adapter.
+- `src/domain/models.rs`: `RateLimitKey`/`RateLimitKeyBuilder` — callers
+ build the key from whatever data should be rate-limited; the crate never
+ interprets it.
+
+## Scope
+
+- Owns: the check/decrement/ticket protocol and its Redis implementation.
+- Not here: what gets rate-limited or at what threshold — that's each
+ caller's `RateLimitConfig` and key construction.
+
+## Boundaries
+
+- Used by: `dictation`, `contacts`, `webhook`, `call`, `notification`,
+ `referral`, `gtm_invite`, `services/document_storage_service`,
+ `services/notification_service`, `services/contacts_service`,
+ `services/authentication_service`.
+
+## Recipes
+
+- Rate-limit a new action: build a `RateLimitKey` with
+ `RateLimitKeyBuilder` → call `check_rate_limit` before the action →
+ `rollback_ticket` if the action then fails.
+
+## Checks
+
+- `cargo test -p rate_limit` (`SQLX_OFFLINE` unset).
+- `cargo test -p rate_limit --features testing` to exercise the
+ testing-only constructors in `src/domain/models.rs`.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/rate_limit/CLAUDE.md b/crates/rate_limit/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/rate_limit/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/referral/AGENTS.md b/crates/referral/AGENTS.md
new file mode 100644
index 0000000000..f437fcd2b7
--- /dev/null
+++ b/crates/referral/AGENTS.md
@@ -0,0 +1,36 @@
+# referral
+
+## What it is
+
+Part of the billing feature (referrals). Generates/redeems referral codes,
+grants the Stripe discount, and notifies the referrer for the
+invite-to-Macro flow.
+
+## Start here
+
+- `src/domain/service.rs`: `ReferralServiceImpl` — referral code generation,
+ invite handling, and discount/notification orchestration.
+- `src/domain/ports.rs`: `ReferralRepo`, `DiscountClient`, `ReferralService`.
+- `src/outbound/pg_referral_repo.rs` + `src/outbound/stripe_discount_client.rs`:
+ the Postgres and Stripe adapters.
+
+## Scope
+
+- Owns: referral code lifecycle and invite-to-Macro.
+- Not here: the discount's actual billing effect → Stripe (via
+ `stripe_discount_client.rs`, a thin client only); sending the notification
+ itself → `notification`.
+
+## Boundaries
+
+- Depends on: `notification`, `macro_user_id`, `rate_limit` (via
+ `services/authentication_service`'s wiring).
+- Used by: `services/authentication_service`.
+
+## Checks
+
+- `cargo test -p referral` (`SQLX_OFFLINE` unset; requires local MacroDB).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/referral/CLAUDE.md b/crates/referral/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/referral/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/reminders/AGENTS.md b/crates/reminders/AGENTS.md
new file mode 100644
index 0000000000..5a84b25b6f
--- /dev/null
+++ b/crates/reminders/AGENTS.md
@@ -0,0 +1,44 @@
+# reminders
+
+## What it is
+
+Part of the Email feature. Private email snoozes: durable inbox
+restoration, scheduled dispatch, and notification delivery, plus email
+follow-up reminders.
+
+## Start here
+
+- `src/domain.rs` module list: `email_collection` (snooze/restore) and
+ `email_followup` (follow-up reminders), each with its own `service.rs`.
+- `src/domain/service/dispatch.rs`: the recurring dispatch loop shared by both.
+- `src/inbound/dispatch_worker.rs`: the queue worker entry point (`dispatch` feature).
+- `src/outbound/pg_reminders_repo.rs`: Postgres repo, split by sub-area.
+
+## Scope
+
+- Owns: email snooze scheduling/restoration, email follow-up reminders, and
+ their dispatch/notification delivery.
+- Not here: the Reminders *view* in the web app, or general task reminders →
+ `apps/web`.
+
+## Boundaries
+
+- Depends on: `entity_access` (ports), `email` (ports), `notification` /
+ `model_notifications` (the `notify` feature), `macro_uuid`/`sqlx` (`postgres`).
+- Used by: `memory`.
+
+## Recipes
+
+- Add a new reminder kind: `src/domain/models.rs` (model) → new
+ `src/domain/<kind>/service.rs` → `src/outbound/pg_reminders_repo/<kind>.rs` →
+ wire into `src/domain/service/dispatch.rs`.
+- Change dispatch behavior: `src/domain/service/dispatch.rs` →
+ `src/inbound/dispatch_worker.rs` → `src/outbound/sqs_dispatch_queue.rs`.
+
+## Checks
+
+- `cargo test -p reminders` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Skill: `cloud-storage-hexagonal-architecture` · Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/reminders/CLAUDE.md b/crates/reminders/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/reminders/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/roles_and_permissions/AGENTS.md b/crates/roles_and_permissions/AGENTS.md
new file mode 100644
index 0000000000..858fb06de1
--- /dev/null
+++ b/crates/roles_and_permissions/AGENTS.md
@@ -0,0 +1,37 @@
+# roles_and_permissions
+
+## What it is
+
+Part of shared infrastructure. Domain for user roles and permissions (not
+item-level sharing — see Scope).
+
+## Start here
+
+- `src/domain/model.rs`: the role/permission types.
+- `src/domain/port.rs` + `src/domain/service.rs`: the port trait and its
+ default implementation.
+- `src/outbound/pgpool.rs`: the Postgres adapter (`outbound` feature).
+
+## Scope
+
+- Owns: user-level role/permission domain logic and its Postgres adapter.
+- Not here: item/document share permissions → `share_permission_db_utils`;
+ authorization decisions for a request → `macro_authorization`.
+
+## Boundaries
+
+- Depends on: `macro_user_id`, `non_empty`.
+- Used by: `agent_inmem`, `ai_billing`, `chat`, `teams`.
+
+## Recipes
+
+- Add a permission check: `src/domain/model.rs` → `src/domain/port.rs` →
+ `src/domain/service.rs` → `src/outbound/pgpool.rs`.
+
+## Checks
+
+- `cargo test -p roles_and_permissions` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Skill: `cloud-storage-hexagonal-architecture` · Rules: `.agents/rules/rust/security.md`
diff --git a/crates/roles_and_permissions/CLAUDE.md b/crates/roles_and_permissions/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/roles_and_permissions/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/routines/AGENTS.md b/crates/routines/AGENTS.md
new file mode 100644
index 0000000000..31dd2cf737
--- /dev/null
+++ b/crates/routines/AGENTS.md
@@ -0,0 +1,39 @@
+# routines
+
+## What it is
+
+Part of the agent sessions feature. Validated routine (scheduled-action)
+commands and AI tools for agents to schedule themselves or another
+persona/model to run later.
+
+## Start here
+
+- `src/domain.rs`: `RoutineTarget` (model vs. agent persona) and
+ `RoutineSchedule` (`Once` / `Cron`) — the validated command shapes.
+- `src/inbound.rs`: the AI toolset exposed to MCP and embedded agents.
+- `src/outbound.rs`: the HTTP client to the owning scheduled-action service.
+
+## Scope
+
+- Owns: routine command validation and the agent-facing tools to create/manage
+ them.
+- Not here: the cron engine and durable schedule storage, owned by the
+ scheduled-action service this crate's `outbound` calls into.
+
+## Boundaries
+
+- Depends on: `ai_toolset`, `macro_authorization`, `macro_user_id`.
+- Used by: `ai_tools`.
+
+## Recipes
+
+- Add a routine tool: `src/domain.rs` (command/schema) → `src/outbound.rs`
+ (HTTP call) → `src/inbound.rs` (tool registration).
+
+## Checks
+
+- `cargo test -p routines` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Skill: `create-ai-tool` · Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/routines/CLAUDE.md b/crates/routines/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/routines/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/s3_client/AGENTS.md b/crates/s3_client/AGENTS.md
new file mode 100644
index 0000000000..396d5b363e
--- /dev/null
+++ b/crates/s3_client/AGENTS.md
@@ -0,0 +1,37 @@
+# s3_client
+
+## What it is
+
+Part of shared infrastructure (cloud storage). Thin async wrapper around
+`aws-sdk-s3`: get/put/delete/exists/copy, folder variants, and presigned
+URLs, all behind one `S3` struct.
+
+## Start here
+
+- `src/lib.rs`: the `S3` struct — every public method is a one-line delegate
+ to its sibling module (`get.rs`, `put.rs`, `delete.rs`, `copy.rs`,
+ `exists.rs`, `get_folder.rs`).
+
+## Scope
+
+- Owns: a generic S3 operation surface, independent of bucket/key semantics.
+- Not here: what a bucket key looks like for a given entity → `s3_key`.
+
+## Boundaries
+
+- Used by: `convert_service`, `dataloss_prevention_handler`,
+ `docx_unzip_handler`, `email_service`, `search_processing_service`.
+
+## Recipes
+
+- Add an operation: new `src/<op>.rs` (free function taking
+ `&aws_sdk_s3::Client`) → a delegating method on `S3` in `src/lib.rs` with
+ `#[tracing::instrument(skip(self))]`.
+
+## Checks
+
+- `cargo test -p s3_client` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/code.md` (CS-22 on `#[tracing::instrument]`)
diff --git a/crates/s3_client/CLAUDE.md b/crates/s3_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/s3_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/s3_key/AGENTS.md b/crates/s3_key/AGENTS.md
new file mode 100644
index 0000000000..40c1be2e29
--- /dev/null
+++ b/crates/s3_key/AGENTS.md
@@ -0,0 +1,45 @@
+# s3_key
+
+## What it is
+
+Part of shared infrastructure (cloud storage). S3 key building and
+parsing for every cloud-storage bucket Macro uses: documents, bulk
+uploads, Slack imports, and static files.
+
+## Start here
+
+- `src/document_key.rs` (425 lines, the largest): `DocumentKey`, conversion
+ and upgrade key builders, and the sync-service snapshot prefix — read this
+ one first, the others follow its pattern.
+- `src/bulk_upload_key.rs`, `src/slack_import_key.rs`, `src/static_file_key.rs`:
+ one key type per bucket/use case, each with its own parse/build pair.
+
+## Scope
+
+- Owns: how an owner/entity id maps to an S3 key string, and parsing a key
+ back into its typed parts.
+- Not here: the bucket name itself (service config) or the S3 calls → `s3_client`.
+
+## Boundaries
+
+- Depends on: `model_owner` (owner segment encoding).
+- Used by: `documents`, `dynamodb_client`, `projects`, `slack_integration`,
+ `sqs_client`.
+
+## Recipes
+
+- Add a key type for a new bucket/use case: new `src/<name>_key.rs` (build +
+ parse + roundtrip test) → `pub use` it from `src/lib.rs`.
+
+## Checks
+
+- `cargo test -p s3_key` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- The owner segment is an encoded principal string, not a raw id — see
+ `build_cloud_storage_bucket_document_key`; don't hand-roll owner encoding.
+
+## Related
+
+- Rules: `.agents/rules/rust/code.md` (CS-10 newtype ids)
diff --git a/crates/s3_key/CLAUDE.md b/crates/s3_key/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/s3_key/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/search_service/AGENTS.md b/crates/search_service/AGENTS.md
new file mode 100644
index 0000000000..b092ebd183
--- /dev/null
+++ b/crates/search_service/AGENTS.md
@@ -0,0 +1,51 @@
+# search_service
+
+## What it is
+
+Part of the Search feature. OpenSearch-backed search API —
+per-entity-type search plus a unified search across them — mounted into
+`document_storage_service`, not run standalone.
+
+## Start here
+
+- `src/api.rs` + `src/api/search.rs`: the router; one file per entity type
+ under `src/api/search/` (`document.rs`, `email.rs`, `chat.rs`, `channel.rs`,
+ `calendar_event.rs`, `call_record.rs`, `crm_company.rs`, `project.rs`,
+ `agent_session.rs`), plus `unified.rs` for cross-type search.
+- `src/api/search/simple/`: a second, simpler request/response shape per type
+ used by AI tools — kept in sync with the full one by hand.
+- `src/api/context.rs`: `SearchHandlerState`, the shared handler state.
+- `src/outbound.rs` + `src/outbound/agent_session.rs`: the OpenSearch query
+ builders.
+
+## Scope
+
+- Owns: query construction against the `models_opensearch` index and the
+ HTTP surface for searching each entity type.
+- Not here: indexing/backfill (the writer side) or the service binary that
+ hosts this router → `document_storage_service`.
+
+## Boundaries
+
+- Depends on: `opensearch_client`, `models_opensearch`, `macro_db_client`,
+ `entity_access`, `properties`, `crm`, `item_filters`.
+- Used by: `document_storage_service` (mounts `search_router`); called
+ through `search_service_client`.
+
+## Recipes
+
+- Add search for a new entity type: `src/api/search/<type>.rs` (handler) →
+ `src/outbound.rs` (OpenSearch query) → `src/api/search.rs` (route) →
+ `src/openapi.rs` → a matching `src/api/search/simple/simple_<type>.rs` if
+ AI tools need it.
+- Change the unified search ranking/shape: `src/api/search/unified.rs` and
+ its `src/api/search/simple/simple_unified.rs` counterpart together.
+
+## Checks
+
+- `cargo test -p search_service` (`SQLX_OFFLINE` unset).
+- `SQLX_OFFLINE=true cargo check` (`just check` recipe in `justfile`).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/search_service/CLAUDE.md b/crates/search_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/search_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/search_service_client/AGENTS.md b/crates/search_service_client/AGENTS.md
new file mode 100644
index 0000000000..9a5c78c93d
--- /dev/null
+++ b/crates/search_service_client/AGENTS.md
@@ -0,0 +1,35 @@
+# search_service_client
+
+## What it is
+
+Part of the Search feature. HTTP client for `search_service`,
+authenticating with the internal API key header instead of a user JWT.
+
+## Start here
+
+- `src/lib.rs`: `SearchServiceClient::new` — sets `INTERNAL_API_KEY_HEADER` on
+ every request via `reqwest::Client::builder().default_headers(...)`.
+- `src/search_unified.rs` / `src/search_channel_name.rs`: one file per endpoint.
+
+## Scope
+
+- Owns: typed calls into `search_service`'s HTTP API.
+- Not here: the search implementation or its OpenSearch index → `search_service`.
+
+## Boundaries
+
+- Depends on: `models_search` (request/response types).
+- Used by: `ai_tools`, `memory`, `skills`, `document_cognition_service`, `mcp_service`.
+
+## Recipes
+
+- Add an endpoint: define the route + types in `search_service` (`src/api.rs`,
+ `src/openapi.rs`) → new `src/<endpoint>.rs` here using `SearchServiceClient`.
+
+## Checks
+
+- `cargo test -p search_service_client` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md` · Skill: `add-sdk-endpoint`
diff --git a/crates/search_service_client/CLAUDE.md b/crates/search_service_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/search_service_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/ses_client/AGENTS.md b/crates/ses_client/AGENTS.md
new file mode 100644
index 0000000000..e3c5e76440
--- /dev/null
+++ b/crates/ses_client/AGENTS.md
@@ -0,0 +1,45 @@
+# ses_client
+
+## What it is
+
+Part of shared infrastructure (transactional email). Outbound email
+delivery: SES in dev/prod, local SMTP (Mailpit) when `SMTP_HOST` is set,
+used by `authentication_service` for invite emails.
+
+## Start here
+
+- `src/lib.rs`: `SesClient`/`Ses` (aliased to `MockSesClient` under `#[cfg(test)]`
+ via `mockall::automock`) and the `Transport` enum that picks SES vs. SMTP.
+- `src/send_email.rs` / `src/send_email_smtp.rs`: the two delivery paths.
+- `src/invite_user.rs`: the invite email template and subject.
+
+## Scope
+
+- Owns: choosing and driving the email transport, and the invite-email template.
+- Not here: other transactional email templates (those compose their own HTML
+ and call `send_email`).
+
+## Boundaries
+
+- Depends on: `macro_env_var` (the `SMTP_HOST`/`SMTP_PORT` escape hatch).
+- Used by: `authentication_service`.
+
+## Recipes
+
+- Send a new kind of email: build its HTML, call `Ses::send_email` (or
+ `invite_user` as a template) — don't add a new transport branch per email kind.
+
+## Checks
+
+- `cargo test -p ses_client` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `#[cfg(test)] pub use MockSesClient as Ses` means tests always get the mock;
+ there is no way to exercise the real `SesClient` type under `cargo test`.
+- The local SMTP transport is plaintext (`builder_dangerous`) — never route
+ through it outside local dev.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md`
diff --git a/crates/ses_client/CLAUDE.md b/crates/ses_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/ses_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/share_permission_db_utils/AGENTS.md b/crates/share_permission_db_utils/AGENTS.md
new file mode 100644
index 0000000000..231fc2b0a4
--- /dev/null
+++ b/crates/share_permission_db_utils/AGENTS.md
@@ -0,0 +1,44 @@
+# share_permission_db_utils
+
+## What it is
+
+Part of shared infrastructure (sharing and permissions). Small SQL helpers
+for `SharePermission` and `ChannelSharePermission` rows — specifically
+team-level link-share defaults and team sharing.
+
+## Start here
+
+- `src/lib.rs`: `get_team_default_link_share` — resolves a user's team's
+ link-share preference, with the strongest membership winning on multi-team
+ users (mirrors `entity_access::get_user_team`).
+- `src/team_share.rs`: team share-permission helpers.
+
+## Scope
+
+- Owns: a handful of standalone SQL queries against `team`/`team_user` and
+ the share-permission tables, for callers that need them without pulling in
+ a full domain crate.
+- Not here: authorization decisions or general entity access → `entity_access`,
+ `entity_access_db_utils`; a user's own role/permission grants →
+ `roles_and_permissions`.
+
+## Boundaries
+
+- Depends on: `entity_access_db_utils`, `models_permissions`, `macro_user_id`,
+ `macro_uuid`, `model_owner`.
+- Used by: `agent_session`, `call`, `channels`, `chat`, `documents`,
+ `initiative`, `projects`.
+
+## Recipes
+
+- Add a query: `src/lib.rs` or `src/team_share.rs` (follow the existing
+ `sqlx::query!` + doc-comment style) → fixtures in `fixtures/` if a new
+ table shape is needed → test in the sibling `test.rs`.
+
+## Checks
+
+- `cargo test -p share_permission_db_utils` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md`, `.agents/rules/rust/architecture.md` (CS-27)
diff --git a/crates/share_permission_db_utils/CLAUDE.md b/crates/share_permission_db_utils/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/share_permission_db_utils/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/skills/AGENTS.md b/crates/skills/AGENTS.md
new file mode 100644
index 0000000000..27abcd2e54
--- /dev/null
+++ b/crates/skills/AGENTS.md
@@ -0,0 +1,44 @@
+# skills
+
+## What it is
+
+Part of the agent sessions feature. Skill discovery and reading for AI
+agents: skills are markdown documents (document sub type `skill`) whose
+instructions an agent follows when the skill is referenced in its input.
+
+## Start here
+
+- `src/lib.rs` module doc: the crate's architecture summary (domain/inbound/outbound).
+- `src/domain/ports.rs` + `src/domain/service.rs`: `SkillService` and its
+ default implementation.
+- `src/inbound/toolset.rs`: the three AI tools — `search_skills.rs`,
+ `list_skills.rs`, `read_skill.rs`.
+- `src/outbound/`: `document_skill_reader.rs` (reads skill content),
+ `search_service_searcher.rs` (search), `soup_skill_lister.rs` (listing).
+
+## Scope
+
+- Owns: skill discovery/search/read as AI tools and their adapters.
+- Not here: the skill document's own editor/storage surface → `documents`;
+ how it's injected into a prompt → the agent harness.
+
+## Boundaries
+
+- Depends on: `document_sub_type`, `entity_access` (ports); `outbound` feature
+ additionally needs `documents`, `search_service_client`, `soup`,
+ `lexical_client`, `item_filters`, `filter_ast`.
+- Used by: `ai_tools`.
+
+## Recipes
+
+- Add a skill tool: `src/domain/ports.rs` (port method) →
+ `src/domain/service.rs` → `src/inbound/toolset/<name>.rs` → register in
+ `src/inbound/toolset.rs`.
+
+## Checks
+
+- `cargo test -p skills` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Skill: `create-ai-tool`, `cloud-storage-hexagonal-architecture`
diff --git a/crates/skills/CLAUDE.md b/crates/skills/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/skills/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/slack_integration/AGENTS.md b/crates/slack_integration/AGENTS.md
new file mode 100644
index 0000000000..2566a6a612
--- /dev/null
+++ b/crates/slack_integration/AGENTS.md
@@ -0,0 +1,56 @@
+# slack_integration
+
+## What it is
+
+Part of the channels/chat (messaging) feature — lets a team bring its Slack
+history into Macro. Browser-staged Slack archive imports: upload a Slack
+export, map it onto Macro channels/messages/users, and import it as a job.
+
+## Start here
+
+- `src/domain/importer.rs` + `src/domain/importer/stream.rs`/`targets.rs`:
+ the import pipeline and its target resolution (which Macro entities a
+ Slack channel/user maps to).
+- `src/domain/slack/`: Slack-format parsing — `mrkdwn.rs`, `reactions.rs`,
+ `threads.rs`, `users.rs`, `references.rs`, `export.rs`.
+- `src/domain/service.rs`: the job lifecycle service.
+- `src/inbound/axum_router.rs` (`create.rs`, `uploads.rs`, `jobs.rs`) and
+ `src/inbound/worker.rs`: the upload/create HTTP routes and the import worker.
+- `src/outbound/pg_slack_import_repo.rs`: job/batch/upload/reference persistence.
+
+## Scope
+
+- Owns: parsing a Slack export, staging its upload, and running the import
+ job end to end (including search backfill and reference reconciliation).
+- Not here: the resulting Macro channel/message storage itself → `channels`,
+ `chat`.
+
+## Boundaries
+
+- Depends on: `mention_utils`; feature-gated: `s3_key`/`aws-sdk-s3` (`s3`),
+ `connection_gateway_client` (`gateway`), `aws-sdk-sqs`/`macro_queues` (`sqs`),
+ `import` (`ledger`), `reqwest` (`search`).
+- Used by: `document_storage_service`, `slack_import_worker`.
+
+## Recipes
+
+- Add a Slack format quirk (new mrkdwn token, reaction, reference type):
+ `src/domain/slack/<area>.rs` → its sibling `test.rs` →
+ `src/domain/importer/targets.rs` if it changes what the importer maps to.
+- Add an import stage: `src/domain/importer.rs` →
+ `src/outbound/pg_slack_import_repo/lifecycle.rs` →
+ `src/inbound/worker.rs`.
+
+## Checks
+
+- `cargo test -p slack_integration` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- References (channel/user mentions) are reconciled after import, not at
+ parse time — see `src/domain/reference_reconciliation.rs`; don't resolve
+ them inline in `slack/references.rs`.
+
+## Related
+
+- Skill: `cloud-storage-hexagonal-architecture` · Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/slack_integration/CLAUDE.md b/crates/slack_integration/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/slack_integration/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/slack_integration/src/domain/models.rs b/crates/slack_integration/src/domain/models.rs
index 72284e188e..0a4c93c05e 100644
--- a/crates/slack_integration/src/domain/models.rs
+++ b/crates/slack_integration/src/domain/models.rs
@@ -1,4 +1,4 @@
-//! Stable import identities, commands and receipts. See `docs/SLACK_ARCHIVE_IMPORT_CONTRACT.md`.
+//! Stable import identities, commands and receipts. See `docs/runbooks/slack-archive-import-contract.md`.
use std::{collections::BTreeMap, fmt, str::FromStr};
diff --git a/crates/soup/AGENTS.md b/crates/soup/AGENTS.md
new file mode 100644
index 0000000000..a1baf49b17
--- /dev/null
+++ b/crates/soup/AGENTS.md
@@ -0,0 +1,69 @@
+# soup
+
+## What it is
+
+Backs the Home, Recent, Signal/work-feed, and GraphQL Soup query surfaces.
+Soup is the amalgamated query service: callers filter across many entity
+types (documents, channels, chats, calendar events, agent sessions, database
+rows, initiatives, ...) and get back a single unified, paginated result.
+
+## Start here
+
+- `src/domain/service.rs`: the main query service; `src/domain/ports.rs` for
+ its repository/collaborator traits.
+- `src/domain/models.rs` (+ `grouping.rs`, `exclusions.rs`, `contact_listing.rs`):
+ the unified `SoupItem`/grouping/exclusion shapes.
+- `src/domain/service/favorites.rs`, `agent_metadata.rs`: entity-kind-specific
+ query logic layered onto the core service.
+- `src/outbound/pg_soup_repo.rs`: the Postgres repo, split by entity kind
+ (`database_row.rs`, `calendar_event.rs`, `agent_session.rs`, `initiative.rs`,
+ `work_feed.rs`, `notified.rs`, `touched.rs`) and by shape
+ (`expanded/` hydrated, `unexpanded/` id-only).
+- `src/inbound/axum_router.rs` + `src/inbound/toolset/list_entities.rs`: the
+ HTTP route and the AI-tool surface over the same service.
+
+## Scope
+
+- Owns: cross-entity filtering, sorting, grouping, exclusion, and pagination
+ logic, and the Postgres queries that back it.
+- Not here: how a specific entity type is created/edited (channels, documents,
+ initiatives, ...); per-entity-type cache projection → `soup_filter_projection`;
+ realtime fan-out of Soup patches → `soup_realtime`.
+
+## Boundaries
+
+- Depends on: `entity_access`, `properties`, `crm`, `item_filters`,
+ `filter_ast`, `favorites`, `frecency`, `channels`, `email`, `call`,
+ `github_pull_requests`, `foreign_entity`, `activity`, `agent_changes`.
+- Used by: `ai_tools`, `complete_graph`, `databases_sql`, `graphql_initiative`,
+ `graphql_soup`, `graphql_work_feed`, `memory`, `skills`, `work_feed`,
+ `soup_filter_projection`.
+
+## Recipes
+
+- Add a new queryable entity kind: `src/domain/models.rs` (variant) →
+ `src/outbound/pg_soup_repo/<kind>.rs` (expanded + unexpanded if both apply) →
+ `src/domain/service.rs` wiring → `src/domain/ports.rs` if a new
+ collaborator is needed.
+- Add a filter/sort option: `item_filters`/`filter_ast` (the filter language) →
+ `src/domain/models.rs` → the matching `src/outbound/pg_soup_repo/*` query.
+- Change what the work feed/Signal surfaces: `src/domain/service/tests/work_feed.rs`
+ → `src/outbound/pg_soup_repo/work_feed.rs`.
+
+## Checks
+
+- `cargo test -p soup` (`SQLX_OFFLINE` unset; needs local MacroDB).
+- After schema/query changes: `nix develop --command just prepare_db` (see `justfile`).
+
+## Gotchas
+
+- `expanded/` vs `unexpanded/` queries exist because hydrating full entities
+ is expensive — don't widen `unexpanded` to return hydrated data; add a new
+ `expanded` path instead.
+- `candidate_gates.rs` encodes access-gate SQL shared across repo queries;
+ changing it changes what every entity kind can return.
+
+## Related
+
+- Skill: `database-core`, `cloud-storage-hexagonal-architecture` · Rules:
+ `.agents/rules/rust/db.md`, `.agents/rules/rust/architecture.md`
diff --git a/crates/soup/CLAUDE.md b/crates/soup/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/soup/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/soup_filter_cache_adapter/AGENTS.md b/crates/soup_filter_cache_adapter/AGENTS.md
new file mode 100644
index 0000000000..3cf8152b2e
--- /dev/null
+++ b/crates/soup_filter_cache_adapter/AGENTS.md
@@ -0,0 +1,55 @@
+# soup_filter_cache_adapter
+
+## What it is
+
+Part of the Soup query feature (Home/Recent/Signal) — the client-side piece
+that lets the app filter Soup locally without a server round-trip. A
+Soup-specific host adapter for the generic `predicate-index` cache: owns the
+application GraphQL schema and Soup projection policy, compiling GraphQL
+Soup-filter queries down to the generic query/projection IR the cache crates
+understand. Runs both natively (Tauri) and compiled to wasm (web).
+
+## Start here
+
+- `src/lib.rs`: the GraphQL `Document`/`Selection` → `ValidatedIndexQuery`
+ compile path (`compile_soup_flat_v4`) and crate-level docs.
+- `src/live_query.rs`: reactive query registration/re-evaluation.
+- `src/direct_patch.rs`, `src/notifications.rs`: optimistic local mutation
+ and notification projection updates applied without a server round-trip.
+- `src/channels.rs`, `src/database_rows.rs`, `src/mail.rs`, `src/properties.rs`:
+ per-entity-kind projection/patch logic.
+
+## Scope
+
+- Owns: translating GraphQL Soup filter queries into the generic cache IR,
+ and projecting/patching cached entities for each kind.
+- Not here: the generic predicate-index cache engine itself → `cache-core`,
+ `item_filter_index`, `predicate_index`; the wire-format encoding of a
+ projected entity → `soup_filter_projection`.
+
+## Boundaries
+
+- Depends on: `cache-core`, `item_filter_index`, `predicate_index`,
+ `graphql_soup_filter_input`, `soup_filter_projection` (no-default-features).
+- Used by: `apps/web/tauri/graphql_cache_plugin` (native) and
+ `crates/client/cache-wasm` (wasm, web).
+
+## Recipes
+
+- Add a filterable/projectable field: `item_filter_index`/`predicate_index`
+ (if the vocabulary is new) → `soup_filter_projection` (wire encoding) →
+ the matching `src/<kind>.rs` here (projection + optimistic patch).
+
+## Checks
+
+- `cargo test -p soup-filter-cache-adapter` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- This crate must stay wasm-compatible — no `sqlx`, no native-only crates in
+ default features; native-only test fixtures live under
+ `[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]`.
+
+## Related
+
+- Rules: `.agents/rules/web/data.md`
diff --git a/crates/soup_filter_cache_adapter/CLAUDE.md b/crates/soup_filter_cache_adapter/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/soup_filter_cache_adapter/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/soup_filter_projection/AGENTS.md b/crates/soup_filter_projection/AGENTS.md
new file mode 100644
index 0000000000..ad2f9d80f1
--- /dev/null
+++ b/crates/soup_filter_projection/AGENTS.md
@@ -0,0 +1,56 @@
+# soup_filter_projection
+
+## What it is
+
+Part of the Soup query feature (Home/Recent/Signal) — direct-field Soup
+projection helpers and the versioned wire format for caching an authoritative
+Soup entity's filterable facts, shared by server and client-side cache code.
+
+## Start here
+
+- `src/lib.rs`: `validate_soup_flat_v2/v3/v4` (profile versions) and the
+ top-level projection error type.
+- `src/wire.rs`: the capsule wire format (`SoupCacheProjectionCapsuleV1/V2/V3`,
+ `encode_cache_projection_supplement`/`decode_cache_projection_supplement`) —
+ the versioning scheme a cache client decodes against.
+- `src/channel.rs`, `src/database_row.rs`, `src/profile.rs`: per-entity-kind
+ projection from a hydrated model (behind the `models` feature) to the flat
+ cache shape.
+
+## Scope
+
+- Owns: the versioned flat-projection schema and its encode/decode, decoupled
+ from any specific cache engine.
+- Not here: compiling GraphQL filter queries or applying optimistic patches →
+ `soup_filter_cache_adapter`; the Soup domain models themselves → `soup`.
+
+## Boundaries
+
+- Depends on: `item_filter_index`, `predicate_index`, `document_sub_type`;
+ `models`/`soup` only with default features enabled (native builds).
+- Used by: `complete_graph`, `graphql_soup`, `soup_filter_cache_adapter`.
+
+## Recipes
+
+- Bump the wire format: add a new `SoupCacheProjectionCapsuleVN` + version
+ const in `src/wire.rs`, keep decoding every older version, and update
+ `SOUP_CACHE_PROJECTION_WIRE_VERSION` to the new default.
+- Add a projectable field: the matching `src/<kind>.rs` → `src/profile.rs`
+ validation → `src/wire.rs` if it needs a new capsule version.
+
+## Checks
+
+- `cargo test -p soup-filter-projection` (`SQLX_OFFLINE` unset).
+- `cargo test -p soup-filter-projection --no-default-features` for the
+ wasm-facing (model-free) build.
+
+## Gotchas
+
+- `default-features = false` (no `models`) is the wasm-safe build; don't add a
+ non-optional dependency on `soup`/`models_soup` outside the `models` feature.
+- Decoding must stay backward-compatible with every `SOUP_CACHE_PROJECTION_WIRE_VERSION_V*`
+ still in the wild — never remove an old decode branch.
+
+## Related
+
+- Rules: `.agents/rules/web/data.md`
diff --git a/crates/soup_filter_projection/CLAUDE.md b/crates/soup_filter_projection/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/soup_filter_projection/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/soup_realtime/AGENTS.md b/crates/soup_realtime/AGENTS.md
new file mode 100644
index 0000000000..6f756e3e1c
--- /dev/null
+++ b/crates/soup_realtime/AGENTS.md
@@ -0,0 +1,61 @@
+# soup_realtime
+
+## What it is
+
+Part of the Soup query feature (Home/Recent/Signal) — keeps cached Soup
+results live by turning document/project/chat/email/channel/property Kafka
+events into recipient-targeted Soup patches, and fanning those out to
+instance-local, user-keyed subscriptions. No composition root; starts no
+tasks itself.
+
+## Start here
+
+- `src/domain/service.rs`: expands current access for an event and publishes
+ one `Patch` per recipient to `macro.soup`.
+- `src/domain/models.rs` + `src/domain/ports.rs`: the `Patch<Entity>` shape
+ and the ports the service depends on.
+- `src/inbound/kafka_consumer.rs`: maps each source Kafka event to
+ `Patch::Updated`/`Patch::Deleted` (`consumer` feature).
+- `src/outbound/soup_consumer.rs`: `SoupRealtimeConsumerService`, consuming
+ recipient-targeted patches into per-user subscriptions.
+- `src/outbound/kafka_publisher.rs`, `entity_access.rs`, `agent_sessions.rs`:
+ the Kafka and access-expansion adapters.
+
+## Scope
+
+- Owns: event → recipient-targeted Soup patch mapping, and local fan-out of
+ those patches to subscribers.
+- Not here: the Soup query/filter logic itself → `soup`; deciding what's
+ filterable/cacheable per entity → `soup_filter_projection`.
+
+## Boundaries
+
+- Depends on: `macro_event_broker`, `macro_event_topics`, `model-entity`,
+ `model_owner`; feature-gated: `channels`, `chat`, `documents`, `email`,
+ `github_pull_requests`, `initiative`, `properties`, `projects`,
+ `system_properties`, `rdkafka` (`consumer`), `agent_session`/`entity_access`
+ (`outbound`).
+- Used by: `complete_graph`, `graphql_soup`, `work_feed`.
+
+## Recipes
+
+- Add a new source event: `src/inbound/kafka_consumer.rs` (map to `Patch`) →
+ `src/domain/service.rs` if access expansion differs → its test in
+ `src/inbound/kafka_consumer/test/`.
+
+## Checks
+
+- `cargo test -p soup_realtime` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Delivery is at least once: offsets commit only after successful fan-out,
+ and exhausted retries stop the consumer for supervisor restart — downstream
+ consumers must tolerate duplicate patches.
+- Property definition/option lifecycle events are intentionally ignored; they
+ don't identify every affected entity.
+- Channel threads use their containing channel as the access source.
+
+## Related
+
+- `README.md` (same content as above, kept for non-agent readers)
diff --git a/crates/soup_realtime/CLAUDE.md b/crates/soup_realtime/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/soup_realtime/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/sqs_client/AGENTS.md b/crates/sqs_client/AGENTS.md
new file mode 100644
index 0000000000..f1b73fad91
--- /dev/null
+++ b/crates/sqs_client/AGENTS.md
@@ -0,0 +1,53 @@
+# sqs_client
+
+## What it is
+
+Shared infrastructure — a thin SQS client plus one queue-specific enqueue
+module per consumer, gated behind Cargo features, used by any service or
+crate that produces or consumes an SQS queue.
+
+## Start here
+
+- `src/queue.rs`: the `SQS` transport (`send_fifo_message`, `receive_messages`,
+ delete/visibility) every feature module calls into.
+- `src/message_attribute.rs`: typed SQS message attributes shared across queues.
+- One module per feature (`chat`, `document`, `email`, `gmail`,
+ `organization_retention`, `search`, `upload_extractor`): each defines its own
+ enqueue function and message shape for one downstream consumer.
+
+## Scope
+
+- Owns: SQS send/receive plumbing and the message schema for each queue this
+ crate produces or consumes.
+- Not here: the Lambda/service handlers that drain these queues — each queue's
+ consuming service (e.g. `services/email_sfs_delete_handler`,
+ `services/upload_extractor_lambda_handler`) owns its own receive loop.
+
+## Boundaries
+
+- Depends on: `aws-sdk-sqs`; optional `email`, `model`, `models_email`,
+ `models_ai_projection` behind their matching features.
+- Used by: most SQS-producing services (`document_storage_service`,
+ `email_service`, `search_processing_service`, `authentication_service`,
+ the `*_handler`/`*_trigger` Lambda services) and `crates/teams`,
+ `crates/webhook`, `crates/documents`, `crates/ai_projections`,
+ `crates/ai_tools`, `crates/projects`, `crates/memory`.
+
+## Recipes
+
+- Add a new queue producer: new `src/<area>.rs` module → feature flag in
+ `Cargo.toml` → `pub mod <area>;` behind `#[cfg(feature = "<area>")]` in
+ `src/lib.rs` → add it to `default` if every consumer needs it.
+- Add a field to an existing queue's message: the module's message struct →
+ its consuming service's deserialization (grep the queue name/feature across
+ `services/`).
+
+## Checks
+
+- `cargo test -p sqs_client` (`SQLX_OFFLINE` unset).
+- `cargo test -p sqs_client --no-default-features --features <area>` when
+ changing a single feature's gating.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/sqs_client/CLAUDE.md b/crates/sqs_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/sqs_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/static_file/AGENTS.md b/crates/static_file/AGENTS.md
new file mode 100644
index 0000000000..4d39ce9f0e
--- /dev/null
+++ b/crates/static_file/AGENTS.md
@@ -0,0 +1,44 @@
+# static_file
+
+## What it is
+
+Shared infrastructure for attachments and uploads — a hex crate for
+resolving static file (SFS) references into URLs or metadata without callers
+depending on `attachment` directly.
+
+## Start here
+
+- `src/domain/ports.rs`: the `StaticFileResolver` port callers depend on.
+- `src/inbound/attachment.rs` (feature `attachment`): adapts `attachment`
+ entities onto the port.
+- `src/outbound/sfs_client.rs` (feature `outbound`): resolves via
+ `static_file_service_client` against the real static file service.
+
+## Scope
+
+- Owns: the port abstraction between "something references a static file" and
+ "static file service resolves/serves it."
+- Not here: the static file service's HTTP client itself →
+ `crates/static_file_service_client`; attachment storage/lifecycle →
+ `crates/attachment`.
+
+## Boundaries
+
+- Depends on: `macro_user_id`, `non_empty`; optional `attachment`,
+ `model-entity` (feature `attachment`), `reqwest` (feature `outbound`).
+- Used by: `crates/ai_tools`, `crates/agent_trigger`, `services/document_cognition_service`,
+ `services/agent_trigger_service`, `services/agent_harness_service`.
+
+## Recipes
+
+- Resolve a new kind of static file reference: `src/domain/ports.rs` (port
+ method) → `src/inbound/attachment.rs` or a new inbound adapter → composition
+ root wiring the outbound adapter.
+
+## Checks
+
+- `cargo test -p static_file` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/static_file/CLAUDE.md b/crates/static_file/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/static_file/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/static_file_service_client/AGENTS.md b/crates/static_file_service_client/AGENTS.md
new file mode 100644
index 0000000000..63319ebb23
--- /dev/null
+++ b/crates/static_file_service_client/AGENTS.md
@@ -0,0 +1,39 @@
+# static_file_service_client
+
+## What it is
+
+Shared infrastructure for attachments and uploads — the HTTP client for the
+static file service (SFS): put, get, and delete a file by key over
+internal-auth-key-authenticated requests.
+
+## Start here
+
+- `src/lib.rs`: `StaticFileServiceClient`, constructed with the internal auth
+ key and base URL; sets `x-internal-auth-key` on every request.
+- `src/put_file.rs`, `src/get_file.rs`, `src/delete_file.rs`: one request each.
+
+## Scope
+
+- Owns: the raw HTTP contract with the static file service.
+- Not here: deciding what gets uploaded or how a static file reference is
+ modeled for a feature → `crates/static_file`, `crates/attachment`.
+
+## Boundaries
+
+- Depends on: `models_sfs`, `macro_aws_config`, `reqwest`.
+- Used by: `services/document_storage_service`, `services/agent_harness_service`,
+ `services/email_service`, `crates/channels`, `crates/cursor_cloud_agents`,
+ `crates/ai_tools`, `crates/image_generation`.
+
+## Recipes
+
+- Add a new SFS endpoint: new `src/<verb>_file.rs` → `pub mod` in `src/lib.rs`
+ → method on `StaticFileServiceClient`.
+
+## Checks
+
+- `cargo test -p static_file_service_client` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md`
diff --git a/crates/static_file_service_client/CLAUDE.md b/crates/static_file_service_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/static_file_service_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/stream/AGENTS.md b/crates/stream/AGENTS.md
new file mode 100644
index 0000000000..eda41c093a
--- /dev/null
+++ b/crates/stream/AGENTS.md
@@ -0,0 +1,36 @@
+# stream
+
+## What it is
+
+Shared infrastructure — a Redis Streams abstraction (typed append/read/ack
+over `model-entity` payloads) for services that want an ordered,
+consumer-group event log without a full Kafka dependency.
+
+## Start here
+
+- `src/domain/traits.rs`: the stream port(s) consumers implement against.
+- `src/domain/types.rs`: stream entry and cursor types.
+- `src/outbound/mod.rs`: the Redis-backed adapter.
+- `src/bin/stream_stdin.rs`: a CLI for piping stdin lines onto a stream, handy
+ for manual testing against a local Redis.
+
+## Scope
+
+- Owns: the Redis Streams read/append/ack contract and its Redis adapter.
+- Not here: Kafka topics or `macro_event_broker` — this is for services that
+ want an ordered, consumer-group log without a full Kafka dependency.
+
+## Boundaries
+
+- Depends on: `model-entity`, `redis` (streams/aio/tokio-comp).
+- Used by: `services/document_cognition_service`, `services/connection_gateway`.
+
+## Checks
+
+- `cargo test -p stream` for unit tests (no Redis required).
+- `just crates/stream/test_integration` — starts a local Redis container via
+ the `redis-test` feature, for the `#[ignore]`d integration tests.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/stream/CLAUDE.md b/crates/stream/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/stream/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/sync_service/AGENTS.md b/crates/sync_service/AGENTS.md
new file mode 100644
index 0000000000..226aeb808c
--- /dev/null
+++ b/crates/sync_service/AGENTS.md
@@ -0,0 +1,35 @@
+# sync_service
+
+## What it is
+
+Part of the Documents (collaborative editing/sync) feature — a hex crate
+defining the sync service's domain ports and an axum router shim, used by
+`document_storage_service`'s in-process sync integration. Package name is
+`sync_service_hex` (not `sync_service`) — depend on it with
+`path = "../sync_service", package = "sync_service_hex"`.
+
+## Start here
+
+- `src/domain/models.rs`, `src/domain/ports.rs`: the domain's document-state
+ port, implemented by the actual sync-service document store.
+- `src/inbound/axum_router.rs` (feature `inbound`): HTTP router shim.
+
+## Scope
+
+- Owns: the port contract for document sync state used by
+ `services/document_storage_service`'s in-process sync integration.
+- Not here: the deployed Cloudflare Durable Object sync service itself →
+ `services/sync-service`; calling it over HTTP → `crates/sync_service_client`.
+
+## Boundaries
+
+- Depends on: `macro_authorization` (feature `inbound`).
+- Used by: `services/document_storage_service`, `crates/sync_service_client`.
+
+## Checks
+
+- `cargo test -p sync_service_hex` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/sync_service/CLAUDE.md b/crates/sync_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/sync_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/sync_service_client/AGENTS.md b/crates/sync_service_client/AGENTS.md
new file mode 100644
index 0000000000..bc181e00f5
--- /dev/null
+++ b/crates/sync_service_client/AGENTS.md
@@ -0,0 +1,44 @@
+# sync_service_client
+
+## What it is
+
+Part of the Documents (collaborative editing/sync) feature — the HTTP client
+for the deployed sync service (`services/sync-service`, a Cloudflare Durable
+Object): document CRUD, state, surfaces, and wakeup calls.
+
+## Start here
+
+- `src/lib.rs`: `SyncServiceClient`, built with an internal auth key and base
+ URL; trusts the checked-in local CA when the URL is `https://localhost(:port)`
+ so local HTTPS stacks work without a system cert.
+- One module per endpoint: `initialize.rs`, `get_raw.rs`, `document_state.rs`,
+ `copy_document.rs`, `delete.rs`, `exists.rs`, `metadata.rs`, `surface.rs`,
+ `wakeup.rs`. Each has a colocated `test.rs` where present.
+
+## Scope
+
+- Owns: the HTTP contract with the sync service.
+- Not here: the sync service's own domain/ports → `crates/sync_service`;
+ the sync service implementation itself → `services/sync-service`.
+
+## Boundaries
+
+- Depends on: `macro_sync_service_jwt`, `model`, `sync_service_hex`
+ (`crates/sync_service`, aliased).
+- Used by: `services/document_storage_service`, `services/document_cognition_service`,
+ `services/document_upload_finalizer_handler`, `services/mcp_service`,
+ `crates/documents`, `crates/collab_surface`, `crates/ai_tools`,
+ `crates/memory`, `tooling/seed_cli`.
+
+## Recipes
+
+- Add a new endpoint: new `src/<verb>.rs` module → `pub mod` in `src/lib.rs` →
+ method on `SyncServiceClient` → matching handler in `services/sync-service`.
+
+## Checks
+
+- `cargo test -p sync_service_client` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md`
diff --git a/crates/sync_service_client/CLAUDE.md b/crates/sync_service_client/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/sync_service_client/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/system_properties/AGENTS.md b/crates/system_properties/AGENTS.md
new file mode 100644
index 0000000000..6c6e831f82
--- /dev/null
+++ b/crates/system_properties/AGENTS.md
@@ -0,0 +1,47 @@
+# system_properties
+
+## What it is
+
+Part of the shared properties feature — database operations for
+system-managed properties: predefined properties (e.g. email attachments,
+CRM stage definitions) that users apply to entities but cannot create or
+delete. Consumed by CRM, projects, initiatives, and other entity-kind crates
+for their fixed property catalogs.
+
+## Start here
+
+- `src/domain/service.rs`: `SystemPropertiesServiceImpl`, the entry point for
+ setting/reading system property values.
+- `src/domain/port.rs`: the repository port.
+- `src/outbound/pgpool.rs`: the Postgres adapter.
+
+## Scope
+
+- Owns: the fixed catalog of system property definitions and the operations
+ to attach their values to entities.
+- Not here: user-defined properties → `crates/properties`; CRM-specific
+ property usage → `crates/crm` (consumes this crate for stage definitions).
+
+## Boundaries
+
+- Depends on: `macro_user_id`, `macro_uuid`, `models_properties`, `sqlx`.
+- Used by: `crates/crm`, `crates/initiative`, `crates/projects`,
+ `crates/messages`, `crates/soup`, `crates/soup_realtime`, `crates/ai_tools`,
+ `crates/agent_trigger`, `crates/item_filter_index`, `crates/task_dedup`,
+ `services/agent_harness_service`, `services/agent_trigger_service`,
+ `services/email_service`, `services/scheduled_action`.
+
+## Recipes
+
+- Add a new system property: define it in `src/domain/mod.rs` (model) →
+ `src/domain/port.rs` (repository method, if new storage shape) →
+ `src/domain/service.rs` → `src/outbound/pgpool.rs`.
+
+## Checks
+
+- `cargo test -p system_properties` (`SQLX_OFFLINE` unset).
+- After query changes: `nix develop --command just prepare_db` from the repo root.
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md`
diff --git a/crates/system_properties/CLAUDE.md b/crates/system_properties/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/system_properties/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/task_dedup/AGENTS.md b/crates/task_dedup/AGENTS.md
new file mode 100644
index 0000000000..dd9eebfaaf
--- /dev/null
+++ b/crates/task_dedup/AGENTS.md
@@ -0,0 +1,51 @@
+# task_dedup
+
+## What it is
+
+Part of the Projects/Tasks feature — detects duplicate tasks by embedding a
+task, searching a pgvector corpus, and judging candidate duplicates with an
+LLM.
+
+## Start here
+
+- `src/lib.rs`: `TaskDedupService<Embedder, VectorDb, Judge>` and the
+ production `TaskDedup` type alias (OpenAI embeddings + Postgres/pgvector +
+ Cohere reranker).
+- `src/domain/service.rs`: the duplicate-detection workflow, generic over the
+ embedding, vector-db, and judge ports.
+- `src/outbound/{cohere,connection_gateway,judge,postgres}.rs`: concrete
+ adapters for each port.
+- `src/eval/corpus.rs`: labeled-corpus loading for the semantic eval.
+
+## Scope
+
+- Owns: the embed → search → rerank → judge pipeline and its Postgres/pgvector
+ storage.
+- Not here: the embedding provider implementation itself → `embedding` crate;
+ task domain logic → `crates/documents`/wherever tasks are modeled.
+
+## Boundaries
+
+- Depends on: `agent`, `embedding`, `lexical_client`; `backfill`-feature-gated
+ `macro_entrypoint`, `macro_aws_config`, `secretsmanager_client`.
+- Used by: `services/document_storage_service`, `crates/documents`.
+
+## Recipes
+
+- Add a judge or embedding provider: implement the matching port in
+ `src/domain/ports.rs` → new `src/outbound/<provider>.rs` → wire into the
+ `TaskDedup` alias in `src/lib.rs`.
+- Add an eval case: drop a file under `tests/eval/cases/` (auto-discovered by
+ `tests/eval/main.rs`) → `just crates/task_dedup/eval [name]`.
+
+## Checks
+
+- `cargo test -p task_dedup` (`SQLX_OFFLINE` unset).
+- `just crates/task_dedup/eval` — real OpenAI/Anthropic/Cohere calls against
+ the labeled corpus; needs local MacroDB plus `OPENAI_API_KEY`,
+ `ANTHROPIC_API_KEY`, `CEREBRAS_API_KEY`. Costs money and is noisy; read
+ before running (see `justfile`).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/task_dedup/CLAUDE.md b/crates/task_dedup/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/task_dedup/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/teams/AGENTS.md b/crates/teams/AGENTS.md
new file mode 100644
index 0000000000..a89a4153a4
--- /dev/null
+++ b/crates/teams/AGENTS.md
@@ -0,0 +1,52 @@
+# teams
+
+## What it is
+
+Part of account/workspace management — team membership, invites, roles,
+CRM/analytics settings, and the `macro.teams` lifecycle event producer that
+other features (billing, CRM) subscribe to. See `README.md` for the full
+event contract (schema, sanitization, delivery semantics).
+
+## Start here
+
+- `src/domain/team_service.rs`: the main service — creation, invites,
+ membership, role changes, auto-join-domain toggle.
+- `src/domain/owned_entity_cleanup.rs` + `open_seat_release.rs`: account/team
+ deletion side effects (owned-entity transfer, seat release).
+- `src/inbound/axum_router.rs` / `src/inbound/toolset.rs`: HTTP routes and AI
+ tool surface.
+- `src/outbound/team_repo.rs`: the Postgres repository.
+
+## Scope
+
+- Owns: the `"Team"` table's lifecycle, membership, invites, and the
+ `macro.teams` Kafka producer.
+- Not here: billing/seat pricing logic → `crates/ai_billing` (consumes this
+ crate); CRM company/contact sync → `crates/crm` (this crate only enqueues).
+
+## Boundaries
+
+- Depends on: `entity_access`, `channels` (feature `backfill_binary`),
+ `analytics_client`, `ai_toolset` (feature `ai_tools`).
+- Used by: `services/authentication_service`, `services/document_storage_service`,
+ `services/calendar_service`, `services/agent_harness_service`,
+ `services/mcp_service`, `services/scheduled_action`, `crates/ai_tools`,
+ `crates/ai_billing`, `crates/calendar_scheduling`.
+
+## Recipes
+
+- Add a team mutation: `src/domain/team_service.rs` → `src/domain/events.rs`
+ (new event variant, if it should publish) → `src/outbound/team_repo.rs` →
+ `src/inbound/axum_router.rs`.
+- Repair missed teammate DMs: `just crates/teams/backfill_teammate_dms_local`
+ (see README's "Delivery semantics" for when this is needed).
+
+## Checks
+
+- `cargo test -p teams` (`SQLX_OFFLINE` unset).
+- After query changes: `nix develop --command just prepare_db` from the repo root
+ inside Nix.
+
+## Related
+
+- Docs: `crates/teams/README.md` · Rules: `.agents/rules/rust/db.md`
diff --git a/crates/teams/CLAUDE.md b/crates/teams/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/teams/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/unfurl/AGENTS.md b/crates/unfurl/AGENTS.md
new file mode 100644
index 0000000000..a820007f9a
--- /dev/null
+++ b/crates/unfurl/AGENTS.md
@@ -0,0 +1,39 @@
+# unfurl
+
+## What it is
+
+Shared infrastructure for link previews, used by email and CRM — a hex crate
+for URL unfurling: fetches a URL's meta tags (title, description, image,
+favicon) with SSRF protections.
+
+## Start here
+
+- `src/domain/service.rs`: the unfurl workflow.
+- `src/outbound/http_safety.rs`: URL validation and private-IP blocking —
+ read before touching any outbound fetch path, it's what keeps this crate
+ from being an SSRF vector against the internal network.
+- `src/outbound/reqwest_fetcher.rs`: the real HTTP fetcher.
+- `src/inbound/axum_router.rs` (feature `axum`): HTTP routes.
+
+## Scope
+
+- Owns: fetching and parsing a URL's unfurl metadata.
+- Not here: rendering the unfurl card in the UI, or caching it long-term.
+
+## Boundaries
+
+- Depends on: `scraper`, `reqwest` (feature `outbound`).
+- Used by: `services/unfurl_service`, `services/email_service`, `crates/crm`.
+
+## Checks
+
+- `cargo test -p unfurl` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Any change to URL validation or redirect handling must keep private/loopback
+ IPs blocked — see `src/outbound/http_safety.rs`'s doc comment.
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md`
diff --git a/crates/unfurl/CLAUDE.md b/crates/unfurl/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/unfurl/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/user_api_key/AGENTS.md b/crates/user_api_key/AGENTS.md
new file mode 100644
index 0000000000..c198d28747
--- /dev/null
+++ b/crates/user_api_key/AGENTS.md
@@ -0,0 +1,33 @@
+# user_api_key
+
+## What it is
+
+Part of account security — creates, lists, and deletes a user's API keys.
+Authenticating a request *with* a key lives in `macro_authorization`, not
+here.
+
+## Start here
+
+- `src/domain/service.rs`: create/list/delete operations.
+- `src/outbound/pg_user_api_keys_repo.rs`: the `"UserApiKey"` table repository
+ (feature `postgres`); also exposes lookup-by-key for `macro_authorization`.
+- `src/inbound/axum_router.rs` (feature `inbound`): HTTP routes.
+
+## Scope
+
+- Owns: the `"UserApiKey"` table's lifecycle.
+- Not here: validating the `x-macro-user-api-key` header on an incoming
+ request → `macro_authorization`.
+
+## Boundaries
+
+- Depends on: `macro_user_id`, `macro_authorization` (feature `inbound`).
+- Used by: `services/document_storage_service`.
+
+## Checks
+
+- `cargo test -p user_api_key` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md`
diff --git a/crates/user_api_key/CLAUDE.md b/crates/user_api_key/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/user_api_key/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/webhook/AGENTS.md b/crates/webhook/AGENTS.md
new file mode 100644
index 0000000000..d1236df5be
--- /dev/null
+++ b/crates/webhook/AGENTS.md
@@ -0,0 +1,48 @@
+# webhook
+
+## What it is
+
+Part of the integrations feature — lets external systems subscribe to Macro
+events. Outbound webhook management, Kafka event ingestion, FIFO SQS
+fan-out, and tracked HTTP delivery. `README.md` has the full contract (event
+names, filter semantics, delivery retry schedule, queue config) — read it
+before changing ingestion or delivery behavior.
+
+## Start here
+
+- `src/domain/ingestion.rs`: event matching (workspace/filter/id rules).
+- `src/domain/delivery.rs`: the delivery state machine and retry policy.
+- `src/inbound/kafka_consumer.rs` / `kafka_stream_consumer.rs`: ingestion
+ consumers for `macro.documents`, `macro.channels`, `macro.messages`,
+ `macro.webhooks`, `macro.agent_sessions`, `macro.agent_session_lifecycle`.
+- `src/inbound/worker.rs`: the SQS delivery worker.
+- `src/outbound/http_delivery.rs`: signed HTTPS POST to the webhook endpoint.
+
+## Scope
+
+- Owns: webhook CRUD/validation, event ingestion matching, and delivery.
+- Not here: the business events themselves — this crate only consumes them.
+
+## Boundaries
+
+- Depends on: `channels`, `documents`, `messages`, `agent_session`,
+ `agent_trigger`, `entity_access`, `macro_event_broker`, `kafka_util`,
+ `rdkafka`, `rate_limit`.
+- Used by: `services/document_storage_service`, `crates/coding_agent_worker`.
+
+## Recipes
+
+- Add a new ingestible event: `src/domain/ingestion.rs` (match rule) →
+ `src/inbound/kafka_consumer.rs` (subscribe/decode) → README's event table.
+- Change delivery retry behavior: `src/domain/delivery.rs` → README's retry
+ schedule table (keep them in sync).
+
+## Checks
+
+- `cargo test -p webhook` (`SQLX_OFFLINE` unset).
+- `RUST_LOG=info,webhook=trace cargo run ...` for ingestion/delivery tracing
+ (see README's Tracing section for span fields).
+
+## Related
+
+- Docs: `crates/webhook/README.md` · Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/webhook/CLAUDE.md b/crates/webhook/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/webhook/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/work_feed/AGENTS.md b/crates/work_feed/AGENTS.md
new file mode 100644
index 0000000000..462802f34f
--- /dev/null
+++ b/crates/work_feed/AGENTS.md
@@ -0,0 +1,42 @@
+# work_feed
+
+## What it is
+
+Part of Home — the combined work feed: one paginated, stacked, live-updating
+list of things that need the viewer's attention plus work they recently did.
+
+## Start here
+
+- `src/domain/service.rs`: page, recompute, done/undo use cases.
+- `src/domain/policy.rs`: item membership policy — what belongs in the feed.
+- `src/domain/stacking.rs`: how related notifications collapse into one entry.
+- `src/domain/realtime.rs`: live-update signals.
+- `src/outbound/source.rs`: adapters over Soup, notifications, email, and
+ activity that supply the underlying items.
+
+## Scope
+
+- Owns: feed membership, stacking, seen/done state, and pagination.
+- Not here: the underlying item data itself (notifications, soup rows,
+ activity) → `crates/notification`, `crates/soup`, `crates/activity`.
+
+## Boundaries
+
+- Depends on: `entity_access`, `filter_ast`, `item_filters`, `notification`,
+ `model_notifications`; optional `activity`, `email`, `soup`, `soup_realtime`,
+ `models_soup` (feature `outbound`).
+- Used by: `services/document_storage_service`, `crates/graphql_work_feed`,
+ `crates/complete_graph`.
+
+## Recipes
+
+- Add a new feed item source: implement a port in `src/domain/ports.rs` → new
+ adapter in `src/outbound/` → wire into `src/domain/policy.rs`.
+
+## Checks
+
+- `cargo test -p work_feed` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/crates/work_feed/CLAUDE.md b/crates/work_feed/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/work_feed/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/crates/worker-rs-otel/AGENTS.md b/crates/worker-rs-otel/AGENTS.md
new file mode 100644
index 0000000000..d9b25f7be0
--- /dev/null
+++ b/crates/worker-rs-otel/AGENTS.md
@@ -0,0 +1,47 @@
+# worker-rs-otel
+
+## What it is
+
+Shared infrastructure for observability — OpenTelemetry tracing support for
+Cloudflare Workers built with `worker-rs` (used by `services/sync-service`).
+Hand-rolled OTLP transport/buffer/flush because wasm Workers can't use the
+regular `opentelemetry-otlp` exporter.
+
+## Start here
+
+- `src/layer.rs`: the `tracing_subscriber::Layer` that closes spans into the
+ buffer.
+- `src/exporter.rs`: thread-local span/log buffers and the flush-to-OTLP path,
+ gated by the `OTEL_EXPORTER_OTLP_ENDPOINT` and `ENVIRONMENT` vars.
+- `src/trace_context.rs`: W3C traceparent parsing/propagation for incoming
+ requests.
+- `src/proto.rs` / `src/model.rs`: real `opentelemetry-proto` wire types for
+ serialization — not a hand-rolled schema.
+
+## Scope
+
+- Owns: span/log buffering and OTLP export for one Cloudflare Worker
+ invocation, plus traceparent propagation.
+- Not here: Rust-service or browser OTel — those use the regular
+ `opentelemetry` SDK or `packages/observability`.
+
+## Boundaries
+
+- Depends on: `opentelemetry`, `opentelemetry-proto`, `opentelemetry_sdk`,
+ `worker` (Cloudflare Workers runtime), `getrandom` (`wasm_js` feature).
+- Used by: `services/sync-service`.
+
+## Checks
+
+- `cargo test -p worker-rs-otel` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `getrandom`'s `wasm_js` feature must stay enabled — wasm Workers have no OS
+ randomness source otherwise.
+- Buffers are thread-local and capped (`MAX_BUFFERED_SPANS`/`MAX_BUFFERED_LOGS`
+ = 512); a Worker invocation that exceeds this silently drops the overflow.
+
+## Related
+
+- Rules: `.agents/rules/observability.md`
diff --git a/crates/worker-rs-otel/CLAUDE.md b/crates/worker-rs-otel/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/crates/worker-rs-otel/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
deleted file mode 100644
index 09c25dc25d..0000000000
--- a/docs/AGENT_GUIDE/surfaces.md
+++ /dev/null
@@ -1,3000 +0,0 @@
-# Other Surfaces
-
-## Home list loading
-
-Home shows compact row skeletons during initial loading, with taller notification
-placeholders on touch devices. Date grouping includes a placeholder heading.
-Pagination appends three placeholders without replacing existing items; refresh
-keeps loaded items visible. Wait for real rows before navigating or selecting.
-
-## Top bars
-
-Low-emphasis right-aligned split-header actions (including Calendar's touch/preview
-New event and Channel's idle Call and Ask Macro) are borderless with a rounded-xl
-background on hover. Emphasized variants retain their treatment, including an
-active call's green ink and outline frame. Channel, company, contact, and project
-content tabs use inset controls in the top bar. Button sizes do not change variant colors or framing; individual
-framed controls default to glass on touch and flat on desktop. Use `glass={true}`
-to enable glass on all devices, or `glass={false}` to disable it everywhere.
-Embedded and low-emphasis actions use `ghost`; inline calendar-invitation text
-actions remove the transparent border to keep their text alignment.
-
-## Dialog actions
-
-Cancel uses a ghost button. Confirm, save, and create actions use strong: the
-outline surface and border with semibold text, without inverted colors. Disabled
-and pending primary actions retain the strong variant. Mobile confirmation drawers
-use the same action hierarchy.
-
-## List-item sharing
-
-Right-click a shareable list row and choose **Share**. The sharing dialog must
-remain open after the context menu closes, with recipient selection and the
-optional message available. Dismiss it with Cancel, then reopen Share on the
-same row and confirm focus enters the recipient selector again. Opening or
-cancelling the dialog does not change access; do not submit shares on real dev
-data unless authorized.
-
-## User cards
-
-Avatar and user-mention cards open on hover on pointer devices and as a bottom
-sheet on touch devices. With a keyboard on a touch device, Tab to the trigger and
-press Enter or Space; verify focus enters the sheet and returns to the opener
-after dismissal or copying, including after reopening. DM, Open contact, and
-Assign task should leave focus in their destination when the sheet closes.
-On pointer devices, avatars should stay out of the Tab order while still opening
-their cards on hover. Copy email/name confirms only after the clipboard
-write succeeds: the hover card shows a checkmark, while the sheet closes. A failed
-write shows failure feedback and leaves the card open for retry.
-
-## Canvas colors
-
-To check the default canvas color, create a rectangle and a text box without
-changing the swatch. The rectangle should have a light neutral fill and a dark
-outline; the text should be dark and visible. Also check the neutral swatch after
-selecting another color. Neutral colors use an OKLCH `none` hue, which must render
-as gray rather than transparent.
-
-## Canvas link paste
-
-Pasting a supported routed Macro app link onto the canvas creates a text
-node with an entity mention, as legacy links do. Routed links retain compatible
-block targets, but not workspace paths or pane-local search state; unsupported
-links remain text.
-
-## Live updates in flat Soup lists
-
-The normalized cache retains at most 64 flat/grouped Soup page snapshots per
-viewer, with a combined 512 KiB encoded budget. Older pages can require a network
-refetch when revisited; normalized entities and queued offline edits are not
-removed. Backfills hydrate entities/indexes without retaining their pagination
-wrappers. Existing oversized viewer records compact once on a compatible open,
-without resetting storage generation or pending mutations. To verify, load many
-pages, revisit an evicted page online, and confirm an offline property edit still
-replays after reopening the app.
-
-With browser or native Tauri GraphQL caching enabled, locally supported flat lists reconcile their
-loaded server pages with matching cached entities. Complete matching updates can
-appear without a list refetch; confirmed non-matches and explicit deletions disappear.
-Rows whose current predicate facts are unknown retain their previous server membership
-and sort evidence until hydration or a network refresh resolves them. Unrelated
-notification-only cache records do not block other rows' updates. While recomputation
-is pending, the last rendered result for the same query and cache generation stays
-visible; local results do not trigger the tab-loading bar. A fresh server response
-still replaces that result, and initial loads without usable data retain normal loading
-indicators. A transport failure does not hide usable current-query local results,
-including empty results; HTTP responses and GraphQL errors still surface.
-To check reconnect behavior, load a non-Mail list online, let background hydration
-advance its cache while offline, then reconnect without delivering a fresh network
-response. The newer local result must remain visible; connectivity alone must not
-restore the older network snapshot. A fresh network response can take authority again.
-
-This is a best-effort display, not proof that every matching entity is cached. Outside
-the supported cached-Mail slice below, loading more follows the original server cursors
-and preserves already loaded pages.
-Newly loaded server rows join the retained display immediately, without duplicates or
-waiting for local recomputation to succeed. Removing pages from the server baseline
-invalidates overlays built from those pages.
-Changing filters or resetting the cache discards prior reconciliation evidence. Grouped
-lists, unsupported filters/sorts, and non-cache transports keep their existing
-network behavior.
-
-For Documents (including Tasks), Projects, Chats, and participating Channels,
-exact `UNSEEN`/`SEEN` notification filters also reconcile locally with
-created/updated timestamp sorts.
-Marking a notification done removes only that notification's contribution immediately;
-other active notifications can keep the entity in the list. Seen/reopen operations
-update filter membership on the authoritative reply, not from a guessed optimistic
-state. Rollback restores only the failed operation's contribution. `DONE` predicates,
-other entity partitions, and notified-at sorting still use the network path.
-
-The Mark done action (`e`, row menu) hides its rows at once from GraphQL lists that
-exclude done items, such as Email Important/Noise and Home Signal, without waiting
-for the server. Email All keeps the row and flips its done indicator immediately.
-GraphQL Undo is offered as soon as Done applies locally, even while its initial
-write is pending. Undo restores the row and focus immediately; its server write
-waits for the initial outcomes and uses only acknowledged notification IDs.
-A late Done reply must not settle or overwrite the newer Undo display intent.
-Undo also restores a previously admitted row after the cache has removed it,
-without waiting for the reversal's server reply; changing filters/sort clears
-those view-local restoration snapshots. Home's separate recent-activity inclusion
-rules are unchanged. Test Done/Undo/Redo with delayed replies and verify both flat
-and grouped rows/counts. A failure must roll back only its own local intent.
-Test mixed committed/queued/rejected archives and notification writes,
-including an archive that fails while its notifications succeed (and vice versa). Accepted writes retain Undo; rejected siblings must neither
-reappear in its request nor be retried by Redo. Partial feedback keeps an Undo
-action. A reply with no matching notification IDs must release that target's
-optimistic hide and notification overrides immediately, even if Undo was never
-clicked and mounted readers remain stale. Do not wait for acknowledgement or a
-timer when there is no receipt. Accepted siblings keep their own display intent;
-a no-op target cannot borrow their IDs to restore its row. Mixed accepted/no-op
-results replace the optimistic full-count toast with the actual completed count
-and retain Undo for accepted writes. An empty notification receipt alone must not
-make a successfully archived email or completed reminder look partially failed.
-Partial Undo/Redo failures retry only the failed writes.
-If every initial write fails, retire its pending Undo/Redo entry and unwind both
-Done and any early Undo overrides. Disposal or clearing history while a reversal
-is pending must not resurrect that entry when its response arrives. Also delay
-Redo, then perform a new action: the late Redo's success or failure must not
-repopulate either history stack or show its stale completion toast. The next Undo
-must still target the newer action; already-dispatched network writes are not
-cancelled by this history fence.
-Newer in-scope activity can re-admit a row, but loading an older notification or
-activity in a separate channel thread must not. Redo targets the original exact
-notification IDs, not notifications received since the original action. A newer
-Done must win over an older retained overlay. Delay reconciliation past a minute:
-pending/stale state must not simply expire and resurrect the row. Once committed,
-mounted cache readers must acknowledge the intent before its overlay is released.
-GraphQL display intents are scoped to the authenticated viewer and login session.
-Login/logout retires old buckets; even same-account native reauthentication must
-not let old overlay Undo/Redo handles or a late refresh republish old intent.
-Verify account changes with overlapping entity IDs and a pending/failed refresh.
-After a successful Done, verify that the row stays gone after a reload.
-Test GraphQL list optimism independently of REST: block REST Soup, email-thread,
-and user-notification data endpoints before page initialization, then confirm
-GraphQL alone populates the list. Hold GraphQL mutation replies while testing
-Done/Undo/Redo and rejection: row feedback must not depend on REST cache reads,
-patches, cancellation, or invalidation. Auth/account metadata is outside this
-row-data boundary. Test the REST path separately, not as a GraphQL fallback.
-Email Reminders contains original email rows: Done archives those conversations,
-with the same immediate GraphQL Undo behavior as the other email tabs.
-In Tasks, Email, Home and Drive, rows keep their DOM when the list updates. A
-property edit or a rename updates the edited row in place instead of rebuilding
-every visible row. To verify, watch the row nodes with a `MutationObserver` while
-editing: only moved or removed rows should be added or removed. Rename a row and
-then drag it: its drag label/payload must use the new fields without another
-registration/layout measurement.
-
-Desktop multi-select filter menus in Home, Tasks, Drive, Email, Reviews, Search,
-CRM, Calendar, and database option-value filters close after an ordinary click or
-Enter. Hold Shift while clicking or pressing Enter to toggle individual options
-and keep the menu open for further selections. Shift does not select a range.
-Single-select controls and mobile filter drawers retain their existing behavior.
-
-Channels use the same general Soup reconciliation path, not a separate local page
-chain. Channel ID, type, team, organization, importance, and participant-scoped
-filters operate over synchronized channel metadata. The default channel scope
-requires active participation. Filters that widen to unjoined team channels,
-message sender/mentions, and channel threads remain network-only. Missing channel
-metadata or notification snapshots are unknown, not empty. The existing core
-backfill checkpoint is refreshed to index channel rows; queued work is preserved.
-
-Notification facts use the existing active-only GraphQL edge and primary entity
-association. Missing/partial or over-budget snapshots remain incomplete, never an
-empty notification set; display metadata decoding omissions remain a best-effort
-limitation. The current `soup-flat-v5` projection retains notification IDs and
-adds complete select-option/entity-reference property snapshots. Tags, task status,
-priority and assignee selections compose with owner and type filters. The shared
-256-fact per-entity budget still applies: missing, malformed or over-budget property
-snapshots are unknown, never evidence of absence. Property-only mutations update
-these postings atomically; rollback does not restore unrelated property values.
-Checkpoint v14 rehydrates older projections without wiping normalized records or
-queued mutations. General Soup still uses its existing server pagination; filter-only
-offline checks use an ungrouped view with a created/updated timestamp sort.
-
-Realtime Soup batches coalesce repeated entity IDs (including entity type), keeping
-that entity's last operation in the batch. Emitted `SoupUpdated` items are non-null.
-If viewer-scoped hydration finds no item, the backend logs and omits that update;
-it does not imply deletion. Only explicit `GraphqlCacheDeletion` events remove records.
-
-## Email reminder delivery
-
-An email snooze returns its original conversation to the inbox and adds a
-notification to that email row in Home. It has no separate reminder toast or
-detail view. See [Email reminders](reminders.md#delivery-and-undo).
-
-## Home (desktop) / Notifications (mobile) — `/app/home`
-
-Touch devices render the Inbox as **Notifications**: a floating Signal/Noise
-pill strip with a leading filter drawer (Status and Type), pull-to-refresh,
-and swipe-left to mark done. On touch, Signal is a pure notification feed — the viewer's own
-touched-by-me recents are not merged in; that merge is desktop Home's Signal
-only, so sent mail and AI chats without notifications appear only on desktop.
-
-On a cold launch, notification transport follows the GraphQL Soup flag reactively:
-if the flag arrives after REST starts, the GraphQL notification query must actually
-start too. Verify a reload with delayed flags retains non-email notifications once
-loading settles, including when the list itself uses REST (notified-at sorting).
-Email alone is not sufficient verification: its inbox membership does not require
-the global notification feed.
-
-Check live Home recency with two accounts: leave the recipient on Home without
-opening the conversation, then send a DM from the other account. The row should
-move into **Last few minutes** and show unread without reloading, including when
-notifications use GraphQL but Home's notified-at list uses REST. Read the DM,
-return to Home, and repeat; also check a row previously marked done and a thread
-reply. Delay the Home list response while allowing single-entity hydration to
-finish: hydration must not cancel the list refresh or leave an old notification
-timestamp. Older in-flight snapshots must not move the delivered row backward.
-Also test a stale response that entirely omits a just-restored, previously done
-row: the row must stay visible. Marking it done again must override that restore,
-and other filter scopes must not inherit the retained membership.
-
-GraphQL-attached notification rows share the global feed's local seen/done
-overrides: Mark Done and Undo reflect local intent without waiting for an older
-cached notification snapshot to be replaced. These display overrides do not turn
-incomplete predicate-index facts into authoritative membership evidence.
-
-On desktop with the new app views enabled, Home defaults to a Signal feed merging
-notifications with Activity's `touched_by_me` recents, including sent emails and
-AI chats. Recent emails must be classified as Signal by the server; touching a
-Noise email must not bring it into Home, including through local search. Verify
-that a recently viewed Noise email stays absent while a Signal email and recent
-chat remain visible, and that loading older rows still works through pages of
-Noise-only email activity. Each entity appears once, ordered by its latest
-notification or own action. On desktop, the funnel button to the right of **Home**
-opens **Filter Home**.
-
-With the GraphQL Soup flag on, desktop Signal reads
-the server work feed (`user.workFeed` plus the `workFeedUpdates` subscription)
-instead of merging sources in the browser; Noise, search, and touch devices keep
-the merged feed. Verify these against a backend that serves the work feed: a
-document you edited with no notifications appears read and offers no **Mark Done**.
-**Mark Done** clears a row's notifications (and archives an inbox email): a row
-that is only notifications leaves and stays gone after a reload, while a row you
-also worked on stays, read, at the time of your own work. **Undo** brings a done
-row back in place. A new comment on a months-old document appears at the top. With
-two sessions of the same account, marking a row done in one removes it from the
-other without reloading. A channel thread and its channel remain separate rows, and
-completing the channel leaves the thread.
-The menu shares the legacy compact submenus: **Status** offers **Unread**, **Read**,
-and **All** as single-select radio items with a checkmark on the right of the selected
-option, and **Type** contains the entity checkboxes. Status closes the menu
-after selection; type selections leave it open. Press **f** to open the menu.
-Entity type checkboxes start checked. Unchecking **Email** hides received
-and sent mail. **Channels** controls
-both channels and reply threads; **Chats** and **Agents** have separate toggles.
-Unchecking every type shows an empty feed. **Reset filters** shows every type and
-both read states again. A badge counts hidden types plus an active status filter.
-Read status and type selections persist.
-There are no desktop Signal/Noise tabs. A **Home** heading
-labels the top left of the block, matching the **Email**, **Tasks**, **Chat**, and
-**Agents** sidebar headings. The full-width **New chat** plus pill below the heading clears the preview and returns to the Home
-starting pane; it does not create a chat. Email and Tasks have matching top pills
-for **New email** and **New task**.
-
-The Home provider honors an explicit initial tab, search, grouping, and facet
-selection. Filters persist per user across reloads and fresh Home navigation;
-split history restores that entry's filter selection. An explicit facet selection
-overrides saved filters. Returning through split history resets navigation to Signal.
-
-Channel thread replies remain separate Home entries from their parent channel,
-using single-line rows and a reply arrow icon on desktop, labeled
-with the sender and channel (for example, **Peter in #battlefield**). Channel names
-prefer the current channel cache, then a matching thread notification's name,
-then **Unknown channel** if neither source has a name. Selecting a
-thread opens that thread in the channel preview; Shift-click opens it in a split.
-
-Items in the 256px desktop rail use single-line pills with 16px icons: profile photos for
-DMs and model logos for AI chats (Claude sunburst or ChatGPT knot). Other items
-use the same glyphs as entity rows elsewhere: document file-type and
-task/snippet/skill variants, hashes for channels, read/unread envelopes or
-calendar invites for email, sparkles for agents, folders for projects, and alarms
-for reminders. Pull requests retain open, merged, and closed status glyphs and
-colors; unknown foreign sources use the generic file icon.
-New agent-session rows always use a sparkle in the left slot, including while
-working. A coding session adds a second line with repository, captured working
-branch (when available), and PR number/status. Non-coding sessions stay on one
-line. Their timestamps and unread dots stay visible. Missing repository metadata
-is omitted.
-The Agents workspace uses a single left dot for activity and unread state in
-place of the sparkle. Opening a loaded session from Home or Agents marks its
-notifications read after the viewing delay, including notifications arriving
-while that session remains active.
-Other Home items have no title tooltips, and their timestamps are
-visible only while hovering the row. An unread
-dot remains visible. Click a row to preview it; `j`/`k` navigate and update the
-preview; alternate activation and Shift-click open a split.
-
-On desktop, before selecting a row, the main pane shows a centered single-line chat
-composer under “What should we get done in Macro?”. Attachment, text, model, and
-send controls share one row; longer prompts expand the input as needed.
-Home uses the shared app font and composer theme tokens; suggestion text and
-hover states use the same semantic colors as other app surfaces.
-Type in “Type @ to reference / for skills”, use the attachment button for
-attachments and the model menu to choose a model, then press Enter or Send to
-create and open an AI chat. If chat creation fails, the submitted text and attachments
-are restored, including before a chat-limit paywall opens. With agents disabled,
-the input stays 32px above the vertical center as suggestions load. With agents
-enabled, the composer uses the same topbar offset and 24/64 padding as the
-Agents new-conversation page so the two inputs share a baseline; suggestions
-still load below it without moving the input. Up to three cached AI
-suggestions appear below the
-composer, using the existing fast/smart recommendation projections. Compact rows
-use one line: reason — Phosphor icon and item name, followed by Open, all at the same font size. Clicking a
-suggestion fills the input and replaces its context attachments without sending;
-the Open action opens its source item in a new split, preserving the editor type
-for tasks, skills, snippets, and other documents. Suggestion loading/errors
-are isolated from the input. If generation stalls for 45 seconds, the shimmer
-is replaced with a retry action; a late result still appears automatically.
-Generation status updates do not extend that deadline. Retry starts a fresh
-45-second wait. Shift+Enter adds a line. Selecting a Home row replaces
-the composer with its preview. Home uses the shared 256px sidebar and collapses
-navigation below 720px. The hamburger or `Cmd+.` opens the full feed as a
-slide-over. Activating a row or **New chat** closes that overlay to show content;
-arrow-key browsing keeps it open. Preview headers start with **Home >**. Clicking
-**Home** clears the preview and returns to the starting pane without changing
-sidebar visibility. Use the hamburger to reopen the feed. Mobile continues to
-show the activity list alone.
-
-Document previews opened from Home expose **Share** and **Copy Share Link** before
-the details toggle, including tasks, snippets, skills, canvases, PDFs, images,
-code, and videos. Share uses the selected item's permissions and updates when
-switching items; copied links point to the entity rather than the Home feed.
-
-AI chat, agent, and channel message bodies use 15px text, including thread replies.
-Desktop AI chats, agents, and channel composers share Home's rounded composer
-surface: a muted dark fill or a white light-mode surface with a soft shadow,
-15px input text, and circular controls. Composer geometry is scaled to 15/16
-of the original design (48.75px single-line height); the Home composer is at most
-720px wide. In narrower desktop splits, the Home heading wraps and the composer
-shrinks to the available pane width; suggestion text truncates while Open stays
-visible. Plain channel messages use a compact row;
-multiline messages, formatting, and attachments retain a full-width editor and
-footer. Switching between compact and expanded layouts keeps the same editor and
-draft. Mobile composer styling and send behavior are unchanged.
-
-Sections are Last few minutes (under five minutes), Last hour, This evening
-(6pm onward), This afternoon (noon–6pm), This morning (6am–noon), Earlier today,
-Yesterday, and the existing older-date groups. Sections always follow this order,
-with newest rows first and entity identity breaking equal-timestamp ties.
-The reference clock uses whole minutes, so refreshing within the same minute
-preserves grouping. Rolling five-minute/hour windows continue across midnight;
-future timestamps caused by clock skew stay in the newest section, and invalid
-dates go last. Calendar sections use local time. The clock is checked every 30
-seconds without a new action. Scrolling near the bottom automatically
-loads older items. Home buffers older rows until both notification and own-activity
-pages have loaded through their timestamp, then advances the shallower feed first.
-Fetched rows still advance this boundary when display filters hide them;
-older cache-only rows do not.
-Rows tied at a page boundary appear together, so loading another page does not
-insert older history above already displayed rows. Live actions and refreshes
-can still reorder rows. Short or fully filtered pages continue loading until the list
-fills or there are no more results. A failed
-source shows a retry notice while the other source stays usable. Document typing
-starts an Edited activity for that editing session. Human edits
-are attributed to the signed-in editor; agent edits retain their agent attribution.
-
-Calendar reminder rows use the reminder delivery time for Home's date section,
-including on a cold GraphQL load with notification sorting disabled. Verify that
-an older reminder stays in its older section after the event's metadata syncs;
-opening its details should show the expected occurrence. A newer reminder or your
-own later activity can move the row forward, but a calendar sync alone should not.
-
-On mobile, the dock and search scope use the bell icon and **Notifications**
-label; Home is desktop-only. Notifications has no merged own-activity feed or
-chat starting pane. Opening a row navigates to its entity. On iOS, rows fade
-underneath the filters and status bar using the shared top edge gradient.
-
-Notifications have three lifecycle states: `unseen`, `seen`, and `done`. Active means
-unseen or seen. Viewing must not reopen a done notification; undoing done (`Ctrl+Z`
-or `⌘Z`) returns it to seen, not unseen. The row returns to the active inbox without
-an unread badge. Applying the active Inbox preset preserves read/unread selections:
-read (`seen` or `done`) narrows to `seen`, not to all active states. Email read/unread
-is separate from notification lifecycle state.
-
-Agent sessions notify through the same inbox. `<bot> finished <session>` goes to the
-owner and everyone who has prompted or answered in that session when a turn ends with
-nothing queued; `<bot> needs your answer in <session>` goes to the same people when the
-agent stops to ask (anyone with edit access may answer); `<user> mentioned you in <session>`
-goes to users @-mentioned in a prompt - when the author can edit the session, the mention
-grants them edit access first, so the link leads somewhere they can act. All three are
-filed under the session itself: the inbox shows an agent-session row (agent icon, session
-name, the bot or mentioner as sender, the excerpt or question as the body) and clicking it
-opens the session. They are
-not retracted automatically yet: answering the question or starting the next turn leaves
-the earlier notification until you mark it done. The chip announcement post itself no
-longer notifies the thread. Settings → notifications lists them under `AI`.
-
-## Tasks — `/app/component/tasks`
-
-Task navigation uses `My Tasks`, `All Tasks`, and `Created by me`. The desktop
-sidebar has a full-width `New task` action and a collapsible list of task favorites;
-tag filtering lives in the `Filter` menu. Favorite rows open their tasks.
-Normal row and favorite activation replaces the list with the editable task
-document; its originating-tab breadcrumb returns to the list and its
-header exposes Share and the task Details/Properties panel. Shift-click opens
-the task in a new split instead. While the list is visible, `J` and `K` move
-focus without opening a task until activation. In an open task detail, they
-replace it with the next or previous task in the same filtered order.
-
-When `enable-tasks-reviews` is enabled, `Reviews` appears above `My Tasks` as a
-shortcut to the separate Reviews view. It lists accessible GitHub pull requests;
-Open/Closed tabs below search and filters default to Open; Closed includes merged
-PRs. Status also remains in the filter menu. Custom multi-status selections hide
-the tabs except for the combined Closed preset.
-The list topbar says Reviews at narrow widths or with its sidebar collapsed;
-selecting one opens `/app/reviews/pr/<foreignEntityId>` with a Reviews breadcrumb.
-See [Tasks](tasks.md#reviews-view) for verification.
-
-The desktop `Create` → `Task` modal uses the standard dialog panel, circular
-icon controls, and a pill-shaped `Create Task` button with 16px outer padding.
-The mobile task drawer retains its existing layout.
-
-## Email — `/app/component/mail`
-
-Email's Tags sidebar uses the [nested tag tree](tasks.md#nested-sidebar-tags).
-Carets and folder-only parents expand branches; actual tags select their exact ID
-and switch the mailbox to All. Parent selection does not include descendant tags.
-Unlike Calls, it lists only personal tags; team-shared tags are hidden,
-and its `New tag` action creates a personal tag with no Team sharing option.
-
-Full email client. Tabs: `Signal` / `Noise` / `Favorites` / `Sent` / `Scheduled` / `Calendar` / `Drafts` / `Shared` /
-`Archived` / `All`. Compose via the `Email` button (or `Create` → `Email E`). On a fresh local user it
-shows `Connect your email` (Gmail/Google Workspace OAuth) — most functionality needs a
-connected account. Search is `Ctrl+F` within the surface.
-
-Sender names use each message's `From` display name, falling back to the
-address-book name when it is absent. Multiple people or bots sending through
-one address (such as GitHub notifications) retain distinct names within and
-across threads. Verify in Mail and in Search with the Email filter and an empty
-query: load more threads from the same address, then check that existing row
-names and their hover cards do not change. Repeat with a text query to exercise
-the search-service results.
-
-`Favorites`, directly below Noise, lists starred Macro emails across Signal,
-Noise, and archived mail. It respects the selected inboxes and filters; search
-within the tab is also restricted to favorites. Removing a star removes the row
-from this view. The tab persists across reloads. With `enable-graphql-soup` on,
-the paginated GraphQL Soup query uses `favoritesOnly: true`. With the flag off,
-REST Soup uses `favorites_only: true`. Starring changes membership without
-changing the list query. Text search still resolves favorite IDs for the search
-service. An empty favorites list shows `No favorite emails`.
-
-`Archived`, directly before All, lists your own archived (Mail Done) threads: the
-All mailbox with Done applied, excluding threads teammates shared with you. It
-respects the selected inboxes and filters. The search service cannot filter
-archive state, so search within the tab keeps only archived hits on the client.
-Rows offer **Unarchive email**;
-unarchiving removes the row at once. The tab persists across reloads. An empty
-list shows `No archived email`.
-
-On desktop, a favorited email keeps a filled, muted star just before its
-timestamp. Other rows reserve only that small star slot. Hovering reveals
-**Star email** (Macro favorites), **Archive email** (Mark Done, with Undo), and
-**Open command menu** for that email. The star stays in place; archive and commands
-replace the timestamp within its existing space. Archived rows offer
-**Unarchive email**; the archive control is disabled in tabs that do not support
-Mark Done. The icons also appear when a button receives keyboard focus. Clicking
-an icon neither opens the thread nor applies the action to other selected rows.
-Touch devices retain the swipe actions.
-Search results use the same reserved column, with actions aligned to the first
-line; snippets, highlighted matches, and expanded hits remain unobstructed.
-
-When switching email tabs or inboxes, the list shows current-query cached results
-or a scoped `Loading email` spinner until they arrive—not the previous tab's rows
-under the new heading. Active searches also hide retained results and show loading
-while selected tag sets are pending. Background refreshes retain the current list. To check this,
-rapidly alternate Signal, Noise, and Sent, then change inboxes; a delayed cache or
-network read must not leave the old rows visible or expose their Load more action.
-
-Opening an email shows loading while its local draft identity and thread data
-resolve. Verify a cold open and switching directly between threads with delayed
-cache reads: neither should flash "Sorry, an unexpected error has occurred" or
-show the previous email. A failed load must still show its error and Retry action;
-reconciling an already-open offline draft must preserve its composer and text.
-If local cache initialization fails, ordinary server threads must still load
-through the session's uncached GraphQL client, including the thread being opened.
-In that fallback, leave a thread open and mark it Done/Not Done from its list:
-only the matching open thread refreshes through GraphQL after the committed archive
-mutation, including its loaded message pages. Mark Seen/Unread and generic Soup
-refreshes must not refetch open threads. Disabled/unmounted readers must not refetch.
-Also delay cache initialization failure until after the first identity lookup fails:
-an uncertain server route must then load and participate in archive refreshes,
-while a positively identified unsynced local draft must never be sent to the server.
-Keep already-resolved server aliases through that fallback. With the normalized
-cache active, the shared email record updates the thread without an extra network
-refresh. Neither path relies on REST thread-cache invalidation.
-
-If a saved inbox selection references an unlinked account, successfully loading
-linked accounts resets the filter to All inboxes while preserving an open or
-restored thread. Check this with a stale saved scope and a thread route, including
-when no linked accounts remain. Explicitly choosing another inbox or All inboxes
-still closes the thread.
-
-The new views reuse the legacy filter option rows and searchable submenus.
-Their triggers are icon-only buttons matching the surrounding view controls;
-Clear/Reset filters and the mobile Clear all action use destructive text styling.
-Both layouts show a small accent dot beside categories with active refinements;
-default All selections are not marked.
-Email Status and Done are single choices that close the menu; attachment filters
-stay open for multiple selections. Tags supports search, pins selected tags first
-on opening, and is omitted when no tags exist. **f** opens the filter menu.
-
-### Read state and trash
-
-In the Email view, Status filters discovery on the server **before pagination**,
-for both the mailbox list and service-backed search. With Unread selected, opening
-or marking an admitted row read keeps its position across refreshes. Separate
-lookups, bounded to 100 already-admitted thread IDs each, omit only the read filter;
-they still enforce the tab, inbox, other facets, and (for search) the search text.
-A snapshot bridges a pending lookup, but a confirmed non-match removes the row,
-so archive/trash cannot be resurrected by retention. Changing the search text,
-filters, tab, inbox, or user resets admission. Check that unread mail is discovered
-even after 100 newer read threads, then verify focus through Mark Read and refresh
-in both list and search, including with more than one loaded page.
-
-With GraphQL Soup enabled, **Mark read/unread** updates the normalized email row
-optimistically. Permanent server errors roll it back; retryable transport failures
-can leave the action in the durable queue. Mark unread sends only the thread ID;
-the server resolves that inbox's UNREAD label and returns the canonical thread
-(`__typename`, `id`, `isRead`) to reconcile the cache. The row should flip immediately
-even when the client labels cache is missing or stale—no label fetch precedes the
-optimistic update. Queued read/unread writes retain revalidation descriptors for
-active flat and grouped lists, including loaded continuation pages. Once replay
-commits (even after a reload), those queries refresh from the server; they should
-not refetch over the optimistic state merely because a write was queued. Trash
-and its Undo refresh mounted GraphQL lists after the server operation finishes.
-The GraphQL-disabled REST path is unchanged. With GraphQL enabled, archive-based
-Mark Done, Mark Not Done, and Undo/Redo use `setEmailThreadArchived`: `inboxVisible`
-updates optimistically in the normalized cache, and each reversal is a distinct
-ordered queue entry. The server resolves the thread's owning/delegated inbox;
-no client INBOX-label lookup is needed. Confirmed writes revalidate mounted lists,
-including continuation pages; queued writes retain those descriptors for replay
-without refetching over optimism. Callers preserve the queued disposition and
-skip REST/TanStack email invalidations as well, including Done/Undo batches and
-thread archive replay. Committed writes and failed non-queued batches still
-reconcile. Permanent failures roll back the failed intent.
-Check Signal/Noise removal and All's done indicator, then Undo/Redo, including an
-offline action followed by reconnect. Also wait for provider/metadata synchronization
-before Undo, and repeat after reloading: an archived received thread can lose its
-inbox-sorting timestamp but must still be unarchivable. Sent-only threads and
-unsent drafts cannot be unarchived; sent mail addressed back to its sender can.
-With GraphQL Soup enabled, bulk Mark Not Done settles per email: a rejected
-sent-only/draft thread stays done, while successful and durably queued siblings
-remain restored. Only accepted
-threads get their notifications restored. Notification or list-refresh failures
-warn without rolling back accepted unarchives. Verify mixed committed/queued/
-rejected selections, partial-success counts, and that a queued sibling prevents
-shared-list refetch even when notification restoration fails. GraphQL reversals
-rely on normalized writes and their durable revalidation, not an extra REST Soup
-refetch after rows settle. Verify the open-thread header too: with GraphQL enabled,
-Mark Not Done remains available for an archived thread whose inbox timestamp is
-missing; the server decides whether its received-message history allows restoration.
-The REST path retains its timestamp preflight, whole-batch handling, notification
-ordering, and existing cache reconciliation.
-For optimistic mutation interface changes, delay the network response and verify
-that only the affected row's read/done indicator changes, with scroll position and
-unrelated rows retained. Quickly reverse the action, then reject the first request:
-the later intent must remain visible. A stale refresh while either write is pending
-must not clear its optimistic state. A retryable failure should remain queued;
-a permanent failure should restore only the failed intent's fields.
-With two views of the same thread mounted, a read/unread or archive scalar
-change should update both existing query stores without a full query reread.
-Observers of unrelated fields should stay idle. Changes to links, record
-identity, or unsupported query projections still take the cache reread path;
-a subsequent scalar update must not cancel that pending structural refresh.
-
-The service retains both replica-backed Soup reads and a primary-backed email
-writer. Email mutations and their uncached reply reloads use the primary; ordinary
-GraphQL/REST lists, direct Soup lookups, and realtime Soup hydration use the replica.
-A mutation reply is fresh, but subsequent list refetches are eventually consistent
-and can still return replica-stale read/archive state. Test that boundary separately
-from mutation reply correctness. GraphQL application errors, including a failed
-post-commit reply load, release the queued mutation rather than retrying forever.
-Transport failures retain the existing retry policy. Draft recovery preserves local
-content and offers explicit Retry using the original handle. Deploy
-the backend schema containing `setEmailThreadArchived` before this client.
-Browser WASM and native cache builds must include the regenerated schema metadata;
-native offline archive support therefore requires a full app build, not just OTA.
-
-### Cached Mail filtering
-
-The per-query caches for email threads, channels, and native offline document
-context reopen closed IndexedDB connections. Verify a cached read and a subsequent
-write after closing the connection, then clear/logout during recovery: old-account
-entries must not return. Only transaction creation retries automatically; persistent
-storage failures still follow the existing cache fallback behavior.
-
-Performance check: switch Signal → All twice against a large synchronized cache.
-Dense local pages use bounded sort-index candidates rather than sorting the entire
-mailbox. Sparse filters and large timestamp ties retain the exact fallback plan.
-A filter result, row fragments, and final revision that agree must be accepted even
-when background hydration advanced past the revision observed before the request;
-that alone must not trigger another filter scan. Also verify local Load more,
-same-timestamp ordering, and pending archive/read changes.
-
-With GraphQL caching enabled (browser or native Tauri) and the email metadata backfill synchronized,
-All, Signal, Noise, Drafts, Sent, Calendar, and Shared support tab changes and new
-filter combinations while offline: account selection
-(including delegated inboxes), read/unread, and archive-based Done/Not Done. Mail Done
-means `inboxVisible = false`; it is **not** notification lifecycle state. Signal/Noise
-retain their Inbox scope, so archived mail is found in Archived (All + Done).
-
-A `Showing cached mail` notice identifies results over synchronized metadata, not a
-claim of complete mailbox coverage. These lists paginate locally beyond the first
-page without a server cursor. Filter, revision, or engine-generation changes restart
-the local page chain; online server results take over again when available. After
-reconnecting, `Load more` follows the same server page chain as the displayed rows,
-not a leftover local cursor. Account choices are cached in the viewer-scoped GraphQL catalog. Timestamp ordering and date
-headers use the selected Mail view's indexed timestamps, not a preview cached from
-another view. Drafts and Sent display their latest eligible message snapshot, even
-when a newer normal message is the ALL preview; no message bodies are needed.
-Sent also requires a canonical outbound timestamp. Trashed messages cannot supply
-any preview. Calendar uses the authoritative thread calendar-attachment flag.
-
-Shared requires a last-known thread grant through the viewer, a team, or an active
-channel, plus the existing Mail UI rule excluding viewer-owned threads. Merely
-having a different owner or a delegated inbox does not qualify. Shared metadata has
-its own full-scan backfill before body hydration. A successful complete scan marks
-old entries it did not return incomplete (not deleted); a failed or cancelled scan
-preserves last-known evidence. If concurrent cache changes invalidate the prior
-membership snapshot, hydration continues but that scan cannot revoke old evidence.
-Interrupted Shared scans restart at the beginning so
-scope reconciliation never mistakes a suffix for a full scan. Offline access is
-necessarily evaluated from the last synchronized grants.
-
-The lightweight metadata backfill runs before body hydration. Its refreshes scan all
-metadata: message-time watermarks alone miss archive/read changes on old threads.
-Filter availability therefore does not guarantee that opening every message body works offline. Missing
-projection proof is unknown, never false. Tag selections use cached property postings;
-attachment chips refine the cached rows on the client. Sender/recipient filters and
-non-created/updated sorts remain outside this local profile. Grouping and sort-selector
-coverage are separate from the filter-selection matrix. No cache-format wipe is required: Mail uses a separate versioned profile
-and a new backfill checkpoint, preserving existing queued work. Deploy the backend
-schema additions before the client: it selects canonical message eligibility/recency
-fields, body-free canonical preview references, and viewer-relative share facts.
-The `soup-mail-v3` property-aware profile and new backfill checkpoint rebuild Mail proof without
-changing the persisted mutation queue format. Native Tauri maintains the same
-predicate projections and revision-bound local page contract as the browser.
-Checkpoint v14 restarts older scans to populate property-aware indexes without wiping
-queued work. A background network failure does not hide a usable current-query
-cached Mail page; server-reported GraphQL errors still surface.
-
-Native filter evaluation requires a full native app update, not just an OTA
-frontend update. Older binaries retain their previous unsupported-filter fallback
-while Shared Mail network backfill continues. The temporary compatibility guard
-can be removed once a full native release includes the filter command and OTA
-delivery excludes older binaries.
-
-For Linux desktop automation, see the [native E2E guide](../../apps/web/tests/native/README.md).
-The first scenario covers Signal → Noise → All after disconnecting both native
-HTTP and WebSockets. iOS shares the native cache code but is not yet covered by
-that driver.
-
-In the new Email view, ordinary row activation opens the thread inside
-`/app/component/mail`; the view breadcrumb (for example Signal) has a hover
-background and returns to the filtered list. Pressing `Escape` in the open thread
-with focus outside any input does the same once there is nothing left to unwind
-(an open reply, an expanded body, or a focused message each take one `Escape`
-first); the list keeps the row you came from focused. The inline header uses the existing
-email title menu: open the menu button beside the subject for **Ask AI**, **Create a
-Task**, and the other thread actions. On desktop, **Mark as unread**, **Mark done**,
-and **Previous item** / **Next item** sit at the right of that header. The arrows
-follow the current filtered list and disable at its ends. Mark done advances in
-that list. Mark as unread (in the header or title menu) returns to the originating
-list with its tab, inbox, and filters preserved. Mark as not done and Mark as read
-stay on the current thread.
-Opening a saved draft from **Drafts** keeps the subject breadcrumb, title menu,
-and applicable header controls visible above the composer. Verify these remain
-available when returning to Drafts and reopening the draft.
-**Delete** in the title menu moves the thread to Trash and returns to the same
-filtered list. Its toast offers **Undo** to restore the email.
-Verify that opening the title menu, returning to the list, and reopening a thread
-preserve working menu actions and header controls. Repeatedly navigate forward
-and backward, including after returning to the list: the subject and email body
-should remain visible without reloading.
-Shift-click opens a standalone split at `/app/email/<thread-id>`, which remains
-the destination for direct links and legacy surfaces. Click a message header to
-expand or collapse it; `Show N hidden messages` reveals the collapsed middle of
-a longer conversation. A standalone link with
-`?email_message_id=<message-id>` loads older pages as needed, expands the target,
-scrolls it into view, and briefly highlights it. For navigation regressions,
-exercise both a recent message and one outside the first page. Open another
-target while loading or highlighting: the previous request must not scroll the
-new thread or clear its highlight. Closing the split cancels pending positioning.
-The load gate and message body share one live thread source in both hosts. Cached
-body rendering should not wait for a second thread fetch, optional References,
-or inbox metadata. Inbox-dependent actions stay gated while ownership is unknown;
-explicit inbox IDs must never silently route to primary while links are loading.
-Background refreshes and older-message loading still update the same thread.
-Verify with API traffic delayed and with previously opened bodies offline.
-Collapsed thread cards use a compact text snippet; expanding mounts the message
-body and its attachments. On phones, messages form flat rows with horizontal
-separators and 16px side gutters; collapsed previews show one line. Desktop
-keeps rounded cards matching the chat composer: soft shadows in light mode,
-the same subtle 3D rim in dark mode, and a faint hover tint. Desktop selection
-does not add an accent-colored ring; keyboard focus has a neutral outline.
-Replies appear inline on desktop and in a composer drawer on touch devices.
-Desktop draft bodies and app-controlled message text use 15px, matching channels.
-HTML messages with preserved sender typography retain their explicit sizes.
-Desktop reply actions sit together at the bottom right: discard, attach, schedule,
-then Send, with circular hover backgrounds inside the card's 16px padding.
-Standalone compose uses one right-aligned row inside its 16px content padding:
-delete, attach, format, schedule, and send. Touch compose uses its header toolbar.
-`R` and `Alt+R` (`Option+R` on macOS) open reply-all for the selected message,
-or the latest message when none is selected. `F` opens a forward and focuses To.
-While an editable field is focused, Escape is handled by that field before the
-close-reply shortcut.
-An edited reply remains a draft when navigating away and returning. Standalone
-compose also flushes pending edits when leaving through app navigation. Switch
-views immediately after typing, before the 500 ms autosave debounce: the old
-thread must close, further navigation must work, and reopening must retain the
-last edit. Repeat with an existing draft and a new reply. During
-mobile Save Draft navigation, a failed local flush is reported and keeps the
-back menu and editor open with their contents intact. After another edit saves
-successfully, Save Draft can leave the composer. Reopen an existing reply after
-clearing its body: the saved empty body must not restore the original quoted HTML.
-During send or discard, its sender and scheduling controls cannot change the operation.
-Attachments that can be opened are buttons named by their filename; Tab to one
-and press Enter or Space. Removal is a separate button named `Remove <filename>`.
-Removing a forwarded file keeps the received original.
-When checking draft autosave, edit the body of a draft with uploaded or forwarded
-attachments, wait for the save, and reopen it; the attachments should remain visible.
-AI email tool drafts persist body-only edits; changing recipients or the subject
-is not required to save the body.
-
-With GraphQL draft queuing enabled, working copies and pending attachment bytes
-are saved on this device independently of the mutation queue. A failed server
-save must leave the draft discoverable in **Drafts** (including grouped views)
-and in its reply thread. **Draft saved** sits immediately left of the desktop
-delete button after editing pauses for 500 ms and the latest local save completes,
-then fades out after two seconds, including offline saves. Resuming typing hides
-it immediately; another pause and saved version restart the timer. Background
-sync updates do not. Failures replace it with persistent **Retry** in the same place; hover for details.
-Clicking Send must not show the badge for its preparatory draft save, including
-when delivery fails. Later edits can show it again after the usual pause.
-Verify the label does not cycle through saving/syncing text on each edit and
-that retry remains accessible beside the actions on mobile. Editing while failed
-continues saving locally without repeatedly submitting the rejected request.
-Local draft storage reopens unexpectedly closed IndexedDB connections. If creating
-a transaction fails because the connection is closing, it retries once before
-running any writes. Verify by closing the draft database connection, then editing:
-the latest content must persist locally and server autosave must continue without
-reloading. Repeat across background/resume on an iPhone. A transaction that has
-already started is never automatically replayed. Persistent failures still block
-server autosave; copy unsaved content before restarting. Storage failures and
-recovery report current page visibility and network state without draft content.
-
-Repeated local-save failures show one persistent warning per composer; recovery
-or closing that composer dismisses it. A later failure shows a new warning.
-Retry preserves the original draft handle. An already-sent rejection drops the
-local copy rather than recreating the sent message. The REST compose path keeps
-its existing behavior.
-
-Native draft recovery requires a full app update containing queue inspection and
-durable mutation metadata support. An older app receiving an OTA bundle shows
-**Macro update required** and uses the existing uncached fallback. Its old queue
-must remain intact, with no new claims or queued writes, until the native update.
-When the cache becomes unavailable, draft saves and discards must not bypass its
-preserved queue through GraphQL or REST fallback. Local editing stays durable;
-reload or update the app to resume server sync. Verify this after a native
-upgrade-required error and a worker initialization failure; ordinary reads still work.
-
-For recovery verification, reject a draft save with a GraphQL error (including
-legacy `retryable: true` metadata), then perform an unrelated queued action: the
-failed save must release the queue. Reload and reopen the draft; verify subject,
-recipients, body, and pending file contents. Retry and check that exactly one
-server draft exists. If per-mutation recovery preparation fails or times out,
-the mutation must fail and release the queue too, including legacy drafts that
-have not been copied into recovery storage. Existing local working copies remain;
-an unmigrated legacy edit can be lost if the queue held its only durable copy.
-Verify that an unrelated queued action still completes in both cases.
-Repeat with two tabs, a save response arriving after a newer
-edit, an attachment upload completing during another local save, and Discard
-while an attachment snapshot is still being saved. A snapshot based on an older
-local revision must fail without replacing newer content or files, including
-when another tab saves first. Reopen the draft to use the latest version.
-A completed discard must not resurrect on reload. A clean,
-fully synchronized local copy must not hide newer server edits or sent state.
-While online, create a disposable reply, wait for its server identity, discard
-it, then leave and reopen the thread and reload. Its local body and attachment
-bytes must be gone and the server draft must stay deleted. Repeat with a second
-tab holding the same draft under its server ID: a delayed save from that tab must
-not recreate the discarded working copy. Repeat after Undo revives the draft:
-the old tab must not overwrite the restored copy even when revisions match.
-A newly composed reply still saves.
-
-For offline replies, use a received email so recipients come from its contacts.
-Type a reply, leave the thread, and reopen it while still offline; repeat both
-immediately after typing and after waiting for autosave. The reply body and
-recipients must remain, including after reload. Delay local draft discovery while
-the cached thread is available: the reply editor must wait for the recovered
-draft before it can accept edits. When several local replies target the same
-message, reopen the most recently edited draft. This exercises the real form-to-
-storage boundary as well as queued saves; plain hand-built save inputs alone
-do not cover it.
-
-Explicit sign-out warns before removing unsynchronized local drafts and files.
-Cancel must retain them; confirm must clear them and fence in-flight work so the
-next account cannot see them. If local storage cannot be inspected, sign-out must
-still offer a warning and a way to continue. Do not verify this by deleting real
-user drafts; use disposable drafts in an isolated test session.
-The three-dot button beneath a body reveals quoted content and a trimmed
-signature. Plaintext and Macro Markdown use the existing Markdown renderer;
-Macro Markdown messages retain document mentions. Ordinary HTML bodies use an
-open shadow root: Playwright text locators can reach them, but a card's ordinary
-`innerText` or `querySelector` does not traverse that root.
-
-Sending a reply from an inbox thread marks that thread done but stays on it;
-only the explicit Mark done action opens the next email.
-Sending a message shows it in the open thread immediately, while delivery is
-still pending. It stays visible until the thread refresh confirms it, with no
-duplicate message. Failed delivery removes that message and restores the reply
-draft; a successful Undo Send removes it and reopens the draft. This temporary
-thread display uses the existing REST delivery path.
-Sending must leave the new message's reply composer closed. After delivery,
-focus belongs to the sent message card in the same thread pane, even while
-the thread refresh is still pending. Replying again requires clicking Reply
-or using a reply shortcut.
-
-After a successful send, the `Email sent` notice offers `Undo`. Undo restores the
-sent envelope and editable content, including when the reply used another inbox;
-a slow background refresh must not keep the restored editor disabled. A rejected
-send reports failure and restores its original reply editor if it is still mounted.
-A failure from an older, unmounted editor must not overwrite a newer edited reply.
-A presentation or refresh error after successful delivery is not a reason to send
-again. After the undo window and provider acceptance, send finalization supplies
-any missing delivery timestamp before publishing the realtime update. The cached
-Sent list must therefore admit the message without waiting for Gmail inbox sync
-or an online visit to Sent. Verify by sending from another Mail tab, receiving the
-final sent update, then switching offline and opening Sent. Existing provider
-timestamps and timestamps from repeated finalization remain unchanged; an unsent
-or cancelled draft must not acquire Sent membership.
-
-Send and schedule are refused with a notice while the device is offline, while a
-draft is still syncing (its save was accepted locally but not yet confirmed by the
-server; retry after a moment), or while an attachment has no completed upload. The
-composer keeps its content in each case. Attachments cannot be added while
-offline: a blocking notice explains and nothing is attached.
-For a new standalone email, a failed REST draft save is best-effort: Send can
-still proceed without a draft ID when no save was queued and no attachment is
-waiting to upload. A server rejection blocks sending even an existing draft.
-GraphQL draft saves automatically retry only network failures. GraphQL errors,
-including internal, invalid, and unauthorized errors, fail the mutation and
-release the queue. The local working copy offers explicit Retry; Send stays
-blocked until a save is confirmed.
-A successful save response with an invalid cache identity binding still commits
-its normalizable server data and reports a cache diagnostic without replaying
-the mutation or asking the user to save again. If that response also cannot be
-normalized, the attempt stops retrying and reports a permanent cache failure.
-If a queued GraphQL save is permanently rejected after reconnect, the draft status
-offers **Retry** using the original draft handle and latest locally saved content.
-Further typing saves locally without retrying the rejected write. Verify that
-pending attachment bytes survive reopening and that a reply stays in its
-conversation.
-An already-sent rejection after reconnect follows the same path as an immediate
-already-sent response: announce that the email or reply was sent, clear the local
-composer, and cancel pending autosave. It must never offer Retry for that draft.
-Verify this in standalone and reply composers, including a queued edit awaiting
-its debounce and a failure racing the first identity read. A settlement for a
-previous or different draft must not clear the current editor.
-Repeat with the composer closed before reconnect: terminal queue failures must
-refresh the saved thread and list queries without requiring an open editor, so
-an already-sent draft does not remain in Drafts solely because nobody observed it.
-With cached inbox metadata available before viewer information loads, saving a
-new offline draft must still create its Mail thread. The selected inbox supplies
-the owner, including delegated inboxes. If that account metadata is unavailable,
-the save must fail before queueing; retain the editor content for a later retry.
-Test this with a previously saved draft as well as a new one: a queued edit must
-block Send and scheduling until a save commits. Reopening a cached draft while
-offline must retain its uploaded attachments and confirmed scheduled time.
-Open a reply draft while its durable identity read is still pending: REST lifecycle
-reads and attachment actions must wait for confirmation. Editing keeps the seed ID
-as a handle; a committed cache read or save unlocks server-only actions. A failed
-identity read must not mark a queued draft committed. Verify an autosave failure
-shows one notice in both standalone and reply composers. If the live mail transport
-switches to GraphQL while the editor is open, queued saves must still adopt their server
-identity after settlement without replacing the editor's current text.
-
-
-With the persistent GraphQL Email cache enabled, a new standalone draft saved
-offline appears immediately in Drafts and the other matching Mail tabs, including
-date-grouped lists. A draft changes a conversation's preview, read state, and sort
-time according to that tab; discarding it restores the remaining conversation's
-metadata. `Showing cached mail` still means only synchronized and locally created
-items are available.
-
-Verify the durable lifecycle: create a standalone draft offline, enter recipients,
-subject and body, close the composer, then restart while still offline. Open it
-from Drafts and confirm its content and sending inbox; edit it again. Reconnect
-and check that exactly one draft remains and the open editor keeps any new text.
-On a cold app start, reopen a local draft thread before another GraphQL query has
-initialized the cache. Its subscription must observe settlement and adopt the
-server ID. If its identity read fails, it must remain cache-only until a later
-cache event resolves it; never send the unresolved handle to the server.
-Keep a reopened offline draft open while reconnecting: the composer must remain
-mounted when the local thread handle resolves to its server ID. After syncing,
-reopen the original local thread URL and confirm the composer still loads; then
-open a different thread and confirm the previous draft is not shown there.
-Reply from a different sending inbox, save, and reopen the original conversation:
-its original messages must remain there even if the reply belongs to a new thread.
-Repeat after changing the sender on a saved reply; neither conversation may become
-an alias for the other.
-Throttle the next email's response while navigating within the inline detail:
-the previous subject and composer must disappear during loading, and the new
-thread must not be marked read using the previous thread's sending inbox.
-Make multiple edits while offline, reconnect, wait for syncing to finish, then
-send. Repeat after refreshing with queued edits: the first attempted save must
-recover its server identity and let newer saves complete, rather than leaving
-Send permanently blocked by "Draft still syncing".
-After restarting offline, reconnect and visit Signal and Drafts. The queued draft
-must stay visible when the first server list arrives, including in date-grouped
-views, until its save settles; it must not briefly appear and then disappear.
-Repeat with discard before reconnect, including a save that was already attempted
-before connectivity dropped. The discarded draft must stay absent after restart
-and reconnect. Opening through an older local thread link must reach the same
-server thread after synchronization. Repeat with an existing reply and confirm
-that other messages, attachments, and the Sent preview remain intact.
-
-With GraphQL Mail enabled, discarding the last draft in a thread must remove the
-thread from every local Mail view, including after queued replay. Discarding a
-standalone draft from its composer returns to the previous list after deletion
-is accepted, including offline; a failed deletion keeps the composer open.
-Check both the toolbar trash button and the mobile Delete Draft action.
-In Email's inline detail, deletion closes the detail and preserves the current
-mail tab and filters; it must not navigate split history to an older composer.
-Discarding a reply draft must preserve the remaining conversation. A previously
-cached thread that the server no longer has must leave the lists after opening it or receiving
-a 404 while changing its labels; a cached record must not override the server's
-not-found response. Check the same behavior after REST discard. Offline/network
-errors alone must never evict a cached thread.
-
-Choosing or clearing a send time is local preparation only. The composer remains
-editable and autosaves normally, shows **Scheduled send: ...** (the time and the
-viewer's timezone, e.g. **Sep 25 at 8:00 AM EDT**) in a bar attached
-below the composer (a strip along the bottom of the message card for replies), and
-performs no schedule, unschedule, archive, or delivery request. The bar's **Cancel**,
-at its far right, clears the local choice; the clock's tooltip reads **Schedule send
-time**. The clock and
-primary arrow remain icon-sized; the clock turns accent-colored when a time is
-selected, while the primary action's accessible name and tooltip change from
-**Send email** to **Schedule send**. Clicking it or pressing `Ctrl`/`Cmd`+`Enter
-runs the same validation and is the only initial scheduling commitment. A selected
-time that has passed is rejected at submission rather than falling back to immediate
-send. Touch toolbars keep the summary inline beside their icons, with Cancel next to
-the time; when space is tight, that summary truncates or wraps separately from the
-fixed icon group. The
-former picker-auto-commit behavior was a defect and must not be restored.
-
-Only a successful scheduling response or authoritative lifecycle reconciliation
-shows **Scheduled for ...**. Confirmed scheduled composers are content-locked.
-Picking another time creates a local proposal while the original remains active;
-the bar continues to show the original time plus the proposed replacement and
-explains that the original remains active. **Update schedule** commits the proposal.
-Clearing that proposal does not cancel the original. **Cancel schedule** is a
-separate explicit action, and only its
-confirmed success returns the message to an editable draft. Failed schedule,
-update, or cancel requests retain the user's local intent and last authoritative
-time, and never fall through to immediate Send. At narrow split widths the bar's
-label truncates while Cancel stays at its far edge; the bar never covers discard,
-attachment, formatting, the clock, or the primary action. Reply recipients
-cannot be edited or dragged during a confirmed schedule or active delivery mutation.
-
-When verifying, use an intercepted or isolated delivery fixture: choose a time,
-confirm that the editable **Scheduled send** preview makes zero delivery calls, then use
-the primary button and `Ctrl`/`Cmd`+`Enter separately to confirm exactly one schedule
-call. Reopen a confirmed schedule to exercise proposal/update and explicit cancel.
-If a later lifecycle refresh fails, the confirmed result remains in place; stale
-observations must not undo it or create a recovery draft after a failed inbox move.
-Reconciliation resumes when a fresh poll or event-driven read succeeds.
-If scheduling succeeds but marking the thread done fails, the email remains
-scheduled and a notice explains the separate failure. Check the confirmed time
-before retrying; do not treat that notice as a failed schedule.
-Keep a scheduled composer open through its due time when verifying the flow. It
-reconciles on email events, tab focus/reconnect, cross-tab schedule changes, and a
-short due-time poll. Confirmed delivery closes or disables the old composer and
-stops autosave/delete against the sent ID. Text from an edit that raced delivery
-is preserved as a new unsent draft, never submitted with the sent message ID.
-Recovery re-uploads local attachment files and restores forwarded attachments.
-Remote-only draft attachments cannot be copied after the original draft is gone;
-their pills are removed and a notice asks you to attach those files again.
-
-A successful initial schedule shows an **Email scheduled** notice whose description
-gives the full send time, with **Undo** and **View message** on their own row below
-it; a rescheduled email
-shows **Email rescheduled** with **View message**. Undo cancels the captured draft in
-the captured inbox and restores its editable body, envelope, and attachments; it must
-not overwrite a newer reply. View message opens the scheduled thread, or scrolls an
-inline reply back into view.
-The Email view's **Scheduled** tab lists only server-confirmed scheduled drafts,
-soonest first across the selected inboxes, as ordinary email rows: the recipients,
-subject, and snippet, with a clock-and-time badge (for example **Tomorrow, 2:12
-PM**) in place of the row's date; hovering it gives the full date, time, and
-timezone.
-Opening a row previews its thread like any other email; cancel from the opened
-message's bar. Search and filters are hidden on this tab. Immediate-send undo-window
-queue rows are not scheduled drafts and must not appear.
-
-With the new app views enabled, mobile and tablet Email use a floating, horizontally
-scrolling row of those tabs, with `Open email filters` at the left. The rest of the
-view is the email list, which scrolls beneath the header and supports pull to refresh
-and swiping left to mark emails done in Signal and Noise. The filter button opens a
-glass bottom sheet for status, done, attachment, calendar and tag filters, plus an `Inbox`
-section when the user can pick one: `All inboxes` or a single address, never several.
-`Clear all` resets those filters and the inbox selection. Desktop keeps its sidebar,
-search field, filter menu and preview control. The sidebar lists the inboxes above the
-`New email` button and tabs as plain rows; clicking one shows only that inbox.
-`Connect another account` starts the add-inbox flow from its own row below the
-scrolling list. `New email` prefills From with the selected inbox, or the primary
-inbox when All inboxes is selected; reopening a draft keeps its saved sender.
-The From menu groups each connected inbox with its verified Gmail send-as aliases.
-Replies default to an address on the thread's own inbox: preserve an outgoing
-message's From, otherwise match To before Cc/Bcc (prefer an alias within each
-recipient group). A manual choice or saved draft takes precedence over late
-account refreshes. Reply-all excludes the inbox's primary address and its aliases.
-Aliases are scoped to their owning inbox, even when two inboxes share an address.
-A failed alias lookup for one inbox does not hide other inboxes' aliases. An
-invalid or unavailable selected alias is rejected on save/send, never silently
-replaced with the primary address.
-
-The sidebar and mobile inbox picker also list aliases beneath their inbox.
-Selecting one scopes mail to that inbox and the exact address in From/To/Cc/Bcc;
-search candidates are checked against the same GraphQL scope. Search and Reminders
-automatically advance nonmatching candidate pages until a match or exhaustion;
-while alias membership is loading, wait rather than treating it as an empty inbox.
-Refresh retries both search and alias membership. A failed retained membership
-lookup shows an error without discarding already-confirmed rows. If a saved alias
-disappears from the catalog, the primary address must not look selected; use
-`All inboxes` or choose an available address to clear that scope. Scheduled mail
-matches its saved sender. `All inboxes` clears both the inbox and alias selection,
-and the selection survives reloads. With one inbox **and aliases**, the All row
-and address pickers remain available. To check without sending real mail, open
-both pickers, select an alias, switch to the primary address, reopen a saved alias
-draft, and confirm the address remains unchanged. Alias discovery uses
-`MailAccounts`, draft saves use `saveEmailDraft`, and delivery uses
-`sendEmailMessage` in GraphQL; the existing undo-send window still applies.
-
-If an explicitly selected sending inbox is unavailable, Send reports
-`Unable to find linked email account. Select a sending inbox.` without delivering
-through another account. The From picker stays available as `Select sending inbox`,
-including when only one linked inbox remains. On mobile, expand `Cc/Bcc, From:`
-to choose the sender. Selecting an available inbox clears the error and allows
-sending; the picker never displays another inbox as selected before that choice.
-With no explicit selection, an unavailable primary still falls back to
-the first linked inbox.
-Sidebar rows, including `All inboxes`, replace their icon with an accent-colored checkmark when
-selected. With exactly one connected inbox and no aliases, only its address appears as the selected
-row, followed by `Connect another account`; there is no `All inboxes` row, title
-inbox dropdown, or inbox section in the mobile filter drawer. The inbox section shows up to four rows (including `All inboxes`), then
-scrolls independently without overscroll so the email tabs stay in place. With many
-accounts, scroll to the last inbox and check that selecting it updates the header filter.
-Selecting one inbox also shows `from [email address]` beside the list title.
-The address is a borderless ghost dropdown with the title's font weight and a
-consistent 14px font size at all widths; `from` is 12px. Both align to the title's baseline, without
-a tooltip or a separate clear button.
-Its single-select menu includes `All inboxes`, which clears the account selection
-and removes the filter. Saved selections from the old multi-select picker restore
-the first saved inbox; an empty saved selection restores All inboxes. Once linked
-accounts load successfully, a selected inbox that no longer exists resets to All
-inboxes. This runs for the whole email view, including on touch devices before
-the filter drawer opens. New email uses the originating email-view split even if another split
-is active. Verify that
-sidebar and menu selection stay in sync and that clearing preserves the current tab and other filters.
-Sidebar rows, `New`, and the panel's back, forward and close controls act on primary-button
-mousedown, so the selection changes before the click completes; a normal click
-still works. The sidebar ends with a collapsible `Tags` section (every personal and
-team tag, plus a `New tag` button): clicking a tag opens the `All` tab filtered to
-threads carrying it, clicking it again clears it, and choosing any tab clears it like
-the other filters.
-Rows have trailing selection checkmarks; Close filters dismisses the sheet
-without resetting its selections.
-
-## Search
-
-Sidebar `Search` button → `/app/search` with a focused query box. Results
-(including a `Featured Results` group) filter live as you type; no Enter needed. `Ctrl+K` is
-usually faster for jump-to-entity; `/` opens workspace search when no editor is focused.
-
-On touch devices, the dock's **Search** button opens a persistent input. Type a
-query, then switch the scope pills between **All**, **Notifications**, **Email**,
-**Channels**, **Files**, **Agents**, and **Tasks**. The selected view searches with
-the same query and retains its tab/facet restrictions. Channels searches
-conversation names. Clearing the
-input restores the current scope's unsearched list; **Close search** ends the
-session. Switching scopes keeps the input mounted and focused. The dock query is
-not saved into the view's desktop search or restored entry state. Home and
-top-level Tasks use this same overlay; embedded project task lists retain their
-own search while the dock is open.
-
-Search snippets carry their target in the destination pane's route search. Channel
-messages open Chat at the message (replies open their parent thread); email snippets
-open the matching message, Markdown snippets the matching node, PDFs the matching
-page and highlighted text, agent snippets the matching turn/author, and call
-snippets the matching transcript segment. Plain rows keep their existing behavior:
-email rows open normally, while agent and call content results use their first hit.
-
-Verify both a cold open and a result whose entity is already open in another pane,
-including a Home or Drive detail: reuse keeps that pane's workspace and filters,
-leaves the search pane intact, and scrolls to the target. Scroll away and click the
-same snippet again to verify it re-targets. Repeat with Shift-click and Cmd/Ctrl-click
-(new split and new browser tab), and check Back/Forward restores the earlier target.
-Channel checks should include an older offscreen message, a reply, and then a root
-message to ensure the previous thread target is cleared.
-For a PDF that is still loading, clear its route target before pages become visible.
-The old search hit must not apply afterward, and its normal initial position should
-still restore if no target has been applied. A newer mention or preview target must
-survive that cleanup and still open when the viewer is ready.
-
-Agent-session results use the robot icon and show a highlighted transcript snippet.
-`Show more [N]` expands additional matches, labeled **User / Agent · Turn N**.
-Click a snippet to open `/app/agent/<uuid>` at that folded message; a plain row click
-opens the first content match, or opens the session normally for a title-only hit. These are
-ACP-backed sessions, distinct from legacy chat results. Legacy chat rename, delete,
-copy, and move-to-folder actions are not offered on agent-session search rows.
-
-## Files — `/app/component/documents`
-
-Tabs `Owned` / `Shared` / `Attachments` / `Folders` / `All`; `New` menu; rows show title,
-tags, updated time. Clicking a row opens the doc.
-
-Shared always excludes files owned by you. Selecting **Created by → Me** therefore
-returns no files; selecting Me together with another creator returns only that
-other creator's shared files. Clearing the creator selection restores all Shared
-results. This applies to restored filters and flat/grouped list requests—not
-just client-side row filtering. Cached inserts enforce the same rule before a
-refetch, including expanded groups and inactive cached Shared queries. Until
-viewer identity is available, document inserts into Shared are rejected.
-
-Files opens **Drive** using the same shell as Tasks, on desktop and touch
-devices alike.
-
-With `enable-databases` enabled, **My Files** includes owned databases and
-**Shared with me** includes databases shared by other owners. **All files**
-also includes accessible databases owned by others. **Search Drive** matches
-database names and **Filter → Type → Database** narrows the list. **New →
-Database** creates and opens a database from file tabs or the folder overview;
-it is absent inside a folder because databases have no folder membership yet.
-Database rows open their database block, including Enter and Open in new split.
-Use the database block's own actions to rename, share or trash it. The list
-omits unsupported duplicate, delete and move-to-folder actions for databases.
-Databases have no view history and do not appear in **Recent**, folder contents,
-or **Email attachments**. Creation time orders them when the selected sort has
-no corresponding database timestamp.
-
-On touch devices (phones and tablets), the Drive header is a scrollable pill
-strip — **Recent**, **My Files**, **Shared with me**, and **Folders** — with a
-leading filter-drawer button, like Tasks. Opening Files from the mobile dock
-starts on **Recent**; explicit tab and folder links keep their destination. The
-first pill is Recent. The drawer holds Sort (hidden on Recent, where the viewer's own
-edit order applies) and, on tab locations only, the same filter groups as the
-desktop **Filter** menu; active selections show a count badge on the trigger
-and a `Clear all` action in the drawer. The in-view `Search Drive` field, the
-Sort/Filter dropdowns, and the header New menu are desktop-only — search on
-touch uses the global search overlay and creation uses the dock's New button.
-The **Folders** pill opens the folder overview and stays highlighted inside
-any folder; tapping it from inside a folder returns to the overview, and
-selecting another pill leaves the folder tree. The sidebar contains `New file or folder`, `My Files`, `Recent`,
-`Shared with me`, collapsible Favorites, and a searchable folder hierarchy. Filter
-by tag from the **Filter** menu's Tags submenu; navigating to another tab or folder
-clears tag filters. A folder with no files matching the active tag
-shows the list's no-match state rather than `This folder is empty`.
-Drive omits split-history back/forward buttons in both wide and narrow layouts;
-the split close button remains available when multiple splits are open.
-Files opened in place from Drive show a return link labeled with their originating
-subview (such as `My Files`, `Recent`, or `Shared with me`) or folder name. The text-only
-label's font weight matches the file title. The link
-restores the originating Drive view.
-The `Drive` folder row opens the folder overview. Click a folder name to browse
-its contents in the main pane; its separate expand/collapse button reveals child
-folders without navigating. With GraphQL caching enabled and membership metadata
-hydrated, a never-visited folder can immediately show cached documents, chats,
-and subfolders for supported created/modified sorts and filters. Email remains
-server-owned: the full mixed GraphQL query still refreshes in the background,
-keeps loaded email rows, and owns pagination. A non-email projection with no visible
-rows, including when pending deletions hide every cached row, must not show
-`This folder is empty` while that initial request is pending or failed. Verify that
-loading and transport errors remain visible in this case; releasing a failed deletion
-restores cached rows without a refetch.
-Verify with a folder-specific GraphQL response delayed, then navigate to another
-folder before it completes; neither cached rows nor late results may leak across
-folders. The top bar keeps the full folder and file detail
-path in one breadcrumb trail. Folder containment uses `/` separators, while the
-transition to a file detail and nested detail navigation use the default `>`
-separator. Choosing a folder breadcrumb returns to that folder and clears newer
-file details. Empty folders show `This folder is empty` and a `Back to Drive`
-action that returns to the folder overview. Folder search retains matching
-descendants' ancestors and reveals their branches.
-
-`Search Drive` searches the current tab or folder overview; search within a folder
-is temporarily hidden, including its Cmd+F shortcut. The sidebar's folder-name
-search remains available. Right-click any Drive view, the Drive folder overview,
-or a folder at any depth for **Open in new split**, **Open in current split**, and
-**Open fullscreen** (when multiple splits are open). Opening a location in a new
-split clears search and filters in the destination, leaving the original split
-unchanged. Folder menus also offer Favorite/Unfavorite, Move to folder, Copy Link,
-and owner-only Rename and Delete.
-A folder's Share dialog, when the owner belongs to a team, has Team access
-(None, View, Comment, or Edit) without a Link sharing card or Link tab.
-Favorites use the same open actions and **Remove from favorites** menu as Tasks.
-The **Filter** menu uses the same controls as Tasks: **Type**, searchable **Tags**,
-and **Created by** submenus alongside **Files** for Default, All files, and Email
-attachments. Options within a group match any selected option; different groups
-combine to narrow the results. Created by is hidden while My Files
-is restricted to your own files. Recent offers only file-scope filtering.
-Hold Shift while selecting or deselecting Type options to keep the submenu open
-and combine several file types without reopening it. Desktop filter submenus allow a
-250 ms grace period when the mouse crosses the parent menu's padding; entering
-the submenu cancels the pending close. While the mouse heads toward an open
-submenu, including one that opens to the left, the categories it crosses on the
-way do not take over. A category the mouse moves to directly, or rests on for
-300 ms, opens in its place. Escape and outside clicks still dismiss immediately.
-`Sort files` offers modified, created, and viewed dates.
-Recent uses the viewer's own interaction order and does not offer a sort override.
-The New menu and drag/drop uploads target the selected folder. **New → Folder**
-and the launcher’s **Folder** action open the folder composer. Enter **Folder name**,
-choose **Add tags**, and stage files or nested folders in the large drop area
-(or use **Add files** / **Add folder**). Staged items can be removed before
-**Create Folder** (Cmd/Ctrl+Enter); nothing uploads until submission. Confirmation
-closes the composer immediately while creation and uploads finish in the background.
-On touch devices, the folder composer uses the same bottom drawer as Task, with
-the name and tags fields; the upload area and file/folder picker buttons are hidden.
-Expanding into a split keeps the draft. Creation preserves the current location
-and offers an **Open** toast action when finished. On failure, the toast’s **Retry**
-action restores the draft, retaining any created folder and only unsuccessful uploads. Close an unused draft
-without submitting when verifying against hosted dev data. In a folder
-opened in its own split or an inline preview, drop files from the computer onto
-the empty state or file list, then reopen the folder to verify membership.
-Check both one file and multiple files; the nested list drop target must retain
-the open folder as the upload destination.
-File rows retain
-selection and context menus; ordinary folder clicks and Enter browse inside Drive,
-while Markdown, code/CSV, image, video, PDF/DOCX, canvas, and unrecognized file
-clicks and Enter replace the list with a breadcrumbed detail. Those detail
-menus include Duplicate, Rename, Move to folder, and Delete. Code, CSV, image,
-video, canvas, PDF, DOCX, and unrecognized files also include Download. PDF
-details include Print, and DOCX files include Download DOCX. Markdown details
-use the document menu, which already includes Download. Spreadsheets keep the
-editor's Import and export menu for Excel and CSV downloads. Choose the current location
-breadcrumb to return to the list; choosing an ancestor file drops newer detail
-entries. Opening a list row or sidebar favorite pushes a new one-item detail path;
-sidebar favorites start from My Files instead of inheriting a previously selected
-folder. Only navigation originating inside a detail appends to that path. Browser
-Back and Forward restore the exact path saved with each entry, and renamed files
-update in mounted ancestor breadcrumbs without rewriting history. Cmd/Ctrl-clicking a
-row toggles selection; Shift-clicking a checkbox selects a range, and Shift+Enter
-opens the focused row in a new split. Cmd/Ctrl-clicking a row's folder link or
-search hit opens a new tab. Short filtered pages load more results automatically;
-a failed page shows a retry action instead of silently stopping. On touch, tabs
-switch via the header pills; on narrow desktop layouts the header keeps a plain
-title and navigation goes through the hamburger overlay. Location, search,
-filters, expanded folders, list focus, and scroll position are restored when
-returning from an opened file.
-
-## Calendar — `/app/calendar/<month-or-week-or-day>`
-
-Event composer dropdown triggers and date/time inputs use the theme control
-surface, so they blend with the dialog instead of using the darker page fill.
-Their menus stay inside the composer's portal scope. Verify that calendar,
-recurrence, Guests, conferencing, Location, and Notifications open on the first
-click from the title field and accept changes without closing the composer.
-Open the start/end date picker and its nested time list; selecting a time keeps
-the date picker open. Escape dismisses the active menu before the composer.
-
-The path selects the Month, Week, or Day period, and choosing another period updates
-that path. Calendar navigation defaults to Day on phones and Week on desktop; the most
-recent choice is remembered locally for navigation that does not specify a period. An
-opened event is reflected in the pane-owned `sN.calendar.eventId` search parameter.
-
-Period selection updates its label and route immediately. The active grid redraws
-on a deferred task; hidden neighboring periods follow on separate tasks. Calendar
-grids stay mounted and undimmed while occurrences load. An uncached range never
-shows events from the previous range. After a short delay, representative event
-skeletons appear without adding synthetic FullCalendar events. Week/Day use sparse
-blocks with varied start times and durations, plus separate all-day bars. Month mixes
-filled bars for all-day/multi-day-style entries with single subtle text lines for
-single-day timed-style entries, without placeholder dots or time chips. Patterns stay
-stable for each date and clear the date headers. Skeletons preserve the grid, scroll
-position, and navigation.
-Quick loads skip the skeletons. Real events lay out underneath during the brief
-minimum display, then fade in as the skeletons fade out. Changing period during a
-load carries feedback into the new cells without restarting the appearance delay.
-Background refreshes retain current events without skeletons or a transient loading
-pill. On a cold reload, the first event paint waits for calendar metadata so events
-appear in their configured colors. A REST/GraphQL handoff for the same user and
-date range keeps the visible events and calendar list while the new reader loads;
-changing the user or date range must not retain the old events. Verify both handoff
-directions with delayed responses and delay calendar metadata past occurrences.
-If metadata fails, events remain usable with the default calendar presentation.
-Provider backfill shows a persistent `Syncing your calendar…` banner above the
-grid, explaining that events will appear automatically and Macro remains usable.
-The banner stays visible as partial results arrive and disappears when sync finishes.
-Errors retain the separate retry state. Verify delayed occurrence
-responses: switch Month/Week/Day rapidly and navigate without blanking the grid.
-Confirm mixed event shapes, stable positions, clean handoff, and an uncovered Retry.
-Reduced-motion mode disables pulses and transitions. The page stays busy until the
-handoff starts. Hidden pages do not animate. Resize to confirm skeleton alignment.
-
-Imported timed events with identical start and end are points: they show a compact
-chip with one time and `No duration` in details, and do not block availability.
-Future points also appear in Upcoming events, without becoming ongoing meetings.
-Grid dragging and resizing are disabled for points. An owned point's metadata,
-RSVP, and deletion still work; metadata saves preserve its exact provider time.
-Creating an event or changing its time requires positive duration. Shared points
-remain read-only and appear only when their details are shared.
-An existing Macro call can keep its schedule during point metadata edits; adding
-a new Macro call requires giving the event a duration first.
-
-Calendar reads come from the local GraphQL cache when both `enable-graphql-soup`
-and `enable-graphql-calendar` are on (PostHog in production, on by default in dev
-for the calendar flag; set `VITE_ENABLE_GRAPHQL_CALENDAR=false` to test the REST
-path). A range the cache has covered renders with no occurrence request, and a far
-jump fetches only the uncovered weeks. A `refresh_calendar` poke, reconnecting,
-coming online, or returning to the tab runs one `CalendarChanges` delta that
-applies edits made elsewhere. RSVPs, edits, deletions, and creates show at once
-through the durable mutation queue: a rejected write rolls back with the usual
-error, and a write made offline stays visible and replays on reconnect. Native
-apps whose engine lacks the calendar cache commands keep the REST path. Until the
-cache answers its first calendar read, viewports wait at most a second and then
-read from REST, and writes use REST, so a cache that is slow to start or fails
-("Local cache unavailable") never leaves the calendar on skeletons. Writes in
-that window behave as on the REST path: offline, they roll back with an error
-instead of replaying.
-
-A single period arrow retains its slide. Rapid arrow clicks and period hotkeys
-accumulate against the requested date and interrupt unfinished slides, without
-waiting for event responses or hidden-page redraws. Verify repeated forward clicks
-and mixed directions reach the cumulative date while events are still loading.
-Touch swipes retain their page-readiness gates.
-
-Quick-call creation, incoming invitations, Live lists, Macro meeting links, and
-the `/app/meet/*` routes require the PostHog flag `enable-quick-calls`. While the
-flag loads or is off, those controls stay hidden and meeting routes do not mount
-call setup. Existing channel calls and the upcoming-events list remain available.
-For local verification, set `VITE_ENABLE_QUICK_CALLS=true` or `false` explicitly.
-
-During a quick or scheduled call, signed-in participants can open **Call chat**
-from its separate button at the far right of the bottom toolbar. Messages persist
-with that call session and are visible in its recording page after it ends.
-Guests do not see chat. The `@` menu includes Macro and available agents;
-mentioning one invokes it in the call thread. Reply on any live message, including
-your own, quotes it in the bottom composer. Verify the reply preserves a draft,
-an agent reply appears, and messages remain in the saved history; starting a
-new session from the same meeting link must start a separate chat thread.
-
-
-Calendar event creation and editing open in a bottom sheet on touch devices,
-with scrollable content above the keyboard. Desktop retains the centered dialog.
-Dismissing a changed event still asks before discarding the draft.
-
-On phones, event details use inset round action buttons and a transparent RSVP
-footer. Answering a recurring invitation opens a rounded glass sheet: choose
-`This event` or `All events`, then `Save response`. Cancel or Close returns to
-the event details without sending a response.
-
-Calendar scheduling is on by default in dev. Production uses the PostHog flag
-`enable-calendar-scheduling` and stays off unless enabled remotely. Set
-`VITE_ENABLE_CALENDAR_SCHEDULING=false` to test the disabled state locally.
-While off, the Calendar settings tab and calendar booking shortcuts are hidden;
-public booking and receipt links show an unavailable page without fetching
-scheduling data. When enabling a production rollout, include anonymous visitors
-so invitees can open those links. A public booking link stays available when
-the flag request gets no answer, for example when a browser blocks it.
-
-Calendar connections live in **Settings → Calendar** (`/app/settings/calendar`).
-Scheduling lives in the separate **Settings → Booking links** item
-(`/app/settings/booking-links`). Use the owner menu at the top right to choose
-**Personal** or **Team · team name**,
-then use **Links**, **Availability**, **Booking page**, **Bookings**, or **Insights**.
-Every section and creation action applies to that selected owner. The default is
-Personal. **Manage teams** in that menu opens team settings. The calendar toolbar’s booking
-actions open Booking links; connection shortcuts continue to open Calendar.
-**New booking link** and **New schedule** create for the selected owner and open
-inline editors. Save changes or Cancel returns to that owner's list.
-Connected calendars offers Connect account (the existing Google consent flow),
-Connect calendar for accounts missing calendar permission, and Disconnect with
-confirmation. Disconnect removes calendar access/data, not the Gmail connection.
-Account checkboxes show/hide all child calendars; partial selection is shown as
-mixed. Individual calendars can also be shown/hidden. The account color is the
-default for its calendars; a child color overrides it. Click a color dot to open
-the theme-matched picker: drag the color field and hue slider, choose a named
-swatch, or enter a three- or six-digit hex value. Arrow keys adjust the focused
-color field (Shift makes larger steps). **Reset to default** clears the override.
-Visibility and colors share the calendar sidebar's browser-local preferences,
-survive reload, and do not change the Google calendar or booking conflict checks.
-Booking status filters use the same segmented control as the CRM sidebar.
-In Availability, each weekday has an enable switch, time ranges, an add button,
-and a copy-hours menu; select target days and Apply before saving the schedule.
-Date overrides and the searchable timezone picker sit below the weekly hours.
-The header shows the selected owner; team owners have an explicit **Team** label.
-Links and availability use flat rows, with actions beside each item.
-Booking pages, bookings, and insights show only the selected owner. Search filters
-that owner’s links and clears when switching owners. Any team member can edit
-team links. Hosts can cancel or reschedule the meetings they host; team
-owners/admins can also manage teammates’ bookings and approve pending ones.
-`Links` creates, edits, pauses,
-duplicates, previews, and copies booking links. Event settings include a
-video choice. New links default to a Macro call, which is created when
-someone books and attached to the calendar invitation. Google Meet and no
-video link remain available. Event settings also include
-weekly availability, collective/all-host or round-robin/one-host assignment,
-notice, buffers, booking horizon, daily limits, and custom questions. New event
-types stay paused until `Accept bookings` is selected and changes are saved.
-`Availability` manages named weekly schedules and date overrides in an IANA time
-zone. Set a default schedule for new event types; a schedule cannot be deleted
-until its event types use another one. Collective and round-robin team meetings
-respect each host’s personal default hours when configured, plus busy calendars.
-**Manage teams** opens team settings, where the member roster lives. Choose hosts
-for a team booking link inside its editor.
-`Booking page` edits the public name and description. `Bookings` shows
-upcoming, unconfirmed, past, and cancelled meetings; admins can confirm requests,
-reschedule, or cancel them. Choose From/Through dates to load bookings (initially 30 days before and after today), then search by guest/title/email and filter by event type. Dates use your browser time zone; shorten the range if more than 5,000 bookings match.
-Cancellation asks for confirmation. After a confirmed meeting ends, an assigned
-host or team admin can mark attendance or a host/guest no-show. Pending requests
-from older configurations appear under Unconfirmed. New approval-only links are disabled;
-new links use automatic confirmation and provider calendar invitations. Existing approval
-links must switch to automatic confirmation before accepting new bookings.
-
-`Insights` reports the selected personal/team owner with 7/30/90-day or custom
-ranges, event/host filters, previous-period comparisons, event trends, meeting
-hours, no-shows, popular events, and host counts. Download exports the filtered
-bookings to CSV. Metrics use booking start dates in the default schedule’s time
-zone; failed/processing requests are excluded. Completed means ended confirmed
-bookings excluding recorded no-shows. Rescheduled counts bookings with recorded
-reschedule history. Ratings/CSAT are not shown because no survey data is collected.
-Oversized result sets return an error instead of silently truncating insights.
-
-The calendar header includes `Copy booking link` and `Open calendar scheduling
-settings`. Copy opens settings when no active personal link exists. Public
-`/app/book/:profile/:slug?` pages accept bookings without Macro sign-in. The website
-opens them in its own dialog; framed there, a booking page and its receipt drop their
-Macro heading and footer, and the booking page tells the website when a booking is
-made. Only macro.com can frame them. Uncertain
-calendar writes retain the booking and show its private receipt while automatic recovery runs.
-After a network response cannot be verified, `Check booking status` retries the original request;
-do not create a replacement booking. Receipt pages poll while the calendar update is pending. Visitors
-choose their time zone, date, time, and required details. The private
-`/app/booking/:id#token` receipt supports cancellation and rescheduling; preserve
-that private link. Rescheduling dates are labelled in the availability schedule's
-time zone. Calendar provider failures show an error; they never report a
-confirmed booking. Current integrations check hosts' connected calendars and
-write invitations/Google Meet through the existing calendar service.
-
-The standalone Calendar view has a left navigation sidebar. The `New` menu
-above the mini calendar offers `Event`, feature-gated `Call`, and feature-gated
-`Reminder`. An icon-only shortcut in the `Upcoming events` header opens the
-availability dialog. Start/end time selectors and a weekend switch sit above
-copy ranges that wrap on narrow screens. The dialog checks all ranges using one
-calendar-occurrence query; ranges without free time are disabled, show an X
-instead of the copy icon, and retain a reason tooltip that can receive keyboard
-focus.
-Copying rechecks the occurrences and current time, so changes since opening do
-not enter the copied text. The option keeps its width while a left spinner and
-`Copying…` crossfade to `Copied` with a green check icon; the button keeps its
-neutral styling. Reduced-motion preferences skip the crossfade and spin.
-Collapsible `Upcoming events` and `Calendars` sections follow; calendar
-account rows use Drive-style trailing disclosure buttons and animated nested
-branches. Their 14px visibility checkboxes precede the swatch and label, with
-separate account and individual-calendar visibility controls. `Team out of office`
-is feature-gated and lists teammates with 24px avatars; its section switch
-toggles the entire grid overlay. Clicking a teammate's row navigates to that
-date, opens read-only event details, and marks the row active. The icon-only
-`Calendar settings` control fills the sidebar footer.
-An account checkbox toggles its calendars together in one update. The checkbox
-responds immediately; the upcoming list and each grid page refresh on deferred
-tasks rather than re-rendering all pages during the click.
-The sidebar can be resized or collapsed on desktop; in narrow desktop panes
-it opens over the grid. Phones do not show the sidebar or its navigation drawer.
-The mobile split header places a month selector and Today in its left island;
-selecting the month opens the date-selection drawer. The right island keeps
-full-sized Availability, Search, and Settings actions. The New menu
-beside the bottom AI input offers Event, feature-gated Call, and feature-gated
-Reminder. Inline Calendar previews retain their host's chrome without adding
-another sidebar; their left header island has a compact New menu because the
-bottom New action follows the foreground host view.
-
-With `enable-calendar-team-sharing` enabled, **Settings → Calendar** also has
-**Team sharing**: `Busy blocks` (the default), `Event details`, and `Nothing`.
-These are Macro read permissions. They do not change Google Calendar ACLs,
-invite teammates to meetings, or let teammates edit, RSVP, or manage reminders.
-The sharing choice covers every currently authorized calendar synced to Macro.
-Private/confidential events only expose generic time blocks; event details
-come from one authorized source copy. Disconnecting an account or losing
-source access removes its team projection.
-
-**Calendars that count as busy** controls which calendars represent the user's
-personal schedule. Primary calendars count by default; other calendars require
-explicit inclusion. Meetings the user attends also contribute, except declined
-meetings. Following a coworker's calendar does not automatically make that
-coworker's events occupy the user's time. In team overlays, `Busy` means the
-block contributes to that teammate's availability; `Shared calendar block`
-means it belongs to a calendar the teammate can access and does not count
-toward their busy time. Event details show the same distinction explicitly.
-
-The sidebar's **Team calendars** section has a master `Show team calendars`
-switch and per-teammate checkboxes; Settings exposes the same display controls.
-Display toggles affect this viewer's grid only. Team chips are prefixed with
-the sharer's name and open read-only details. Copy-event links, guest-email
-actions, RSVP, editing, and deletion are unavailable on team projections.
-A directly accessible copy retains its own actions; another person's projection
-of the same meeting may appear separately, with its sharing provenance.
-Distinct authorized source copies may also appear separately for the same
-teammate and meeting: their detail masking and availability contribution can differ.
-Team projections and availability use server-confirmed copies. An offline queued
-edit appears in the editor's own calendar, but reaches teammates only after the
-server commits the provider-backed change and their shared projection refreshes.
-An unavailable team fetch displays a warning and removes stale shared details.
-Sharing-change notifications clear open shared details before refetching;
-focus/reconnect and a 30-second refresh provide a fallback. Shared details also
-disappear when an offline refresh is paused; they are not persisted for offline
-use. While the app is running, team responses and in-flight requests expire
-after 60 seconds, so a hung refresh cannot retain old details. Replacing a login
-session clears team data and open shared details before the new identity loads.
-Legacy out-of-office rows are read-only status displays and do not claim
-that every absence blocks availability.
-
-The `GetTeamAvailability` AI tool checks the requester together with the selected
-teammates. It reports confirmed free windows only when every participant has
-complete availability coverage. Hidden, disconnected, stale, or incomplete
-calendars are reported as unknown, never free. Busy blocks contain no event
-titles or private event metadata.
-
-The in-view desktop Calendar header uses one responsive top bar. The viewed
-month and year stay on the left in a heading that scales from 16px in narrow
-splits to a maximum of 24px, with a compact `New` menu when the sidebar is closed.
-An icon-only ghost `Search events` button sits on the right, before a slightly
-larger gap and the `Today`, period selector, and previous/next controls.
-Click Search or press Cmd/Ctrl+F to expand and focus the wider inline search field.
-The field slides out with a short width transition and focuses immediately.
-The results popup stays hidden until the field contains non-whitespace text,
-then fades and slides in once expansion is nearly complete. Clearing the field
-hides the popup without collapsing search. Reduced-motion preferences skip
-both transitions.
-Close search, Escape, selecting a result, or clicking outside collapses it back
-to the icon without clearing the query. Activating a period control also
-collapses search after the action runs. Escape and Close restore focus to the
-Search button. The expanded field exposes Filters and, after typing, the
-icon-only Exact-match toggle. The filter button stays before Close. The filter
-menu opens below the button, aligned to its right edge: Search in is
-single-select, while Status, Organizer, and Attendee allow multiple values.
-Organizer and Attendee virtualize their contact lists; selected contacts stay
-in place, while custom email addresses appear first. Adding a valid email clears
-the contact search. Filter selections apply immediately, and only these filters
-mark the filter button, not Exact mode. Search opens a calendar-search hint
-until at least three characters are entered; searches show skeleton rows while
-loading. Empty results show an illustrated empty state. Result titles show a calendar-color
-swatch when the event is loaded in the visible range, falling back to the
-default calendar color otherwise. A result shows its location after the
-date/time when available. Each result offers at most one rounded Join action:
-matching occurrence content takes precedence over series metadata. Macro links
-use a neutral button, Google Meet uses a solid blue button in light mode and a
-subtle blue button in dark mode, and other conference links use a neutral button.
-All Join buttons use a camera icon. Generated Macro invitation paragraphs are
-hidden from event descriptions. Google Meet URLs in an event's location or
-description also supply Join actions. Recurring results wait for matching
-occurrence details before showing Join. Selecting a result preserves the search
-text. Availability lives in the desktop sidebar's Upcoming events section and
-in the mobile header.
-
-The period controls move into a separate row below 600px of calendar-pane width,
-with `New` on the left and navigation on the right. With a docked sidebar, the
-header needs fewer controls and stays inline down to 480px. This avoids wrapping
-and immediately unwrapping when the sidebar hides. Expanded search does not
-force early wrapping; its results popup stays directly below the search field.
-Below 1040px, search slides over the month title without moving any controls or
-changing the header height. `New` stays outside the search overlay. Resizing the
-pane keeps the search field mounted and preserves its query and focus. Today
-and New retain their text labels until the controls row runs out of room, then
-become icon buttons.
-Touch devices keep the month selector and header controls without separate
-create or call buttons in the right island. Mobile header islands omit Search.
-The desktop sidebar's mini calendar remains navigable by date and month.
-
-Active Quick Calls you created, participated in, or were invited to appear above your
-next five events (including ones in progress), whether or not they have call links.
-The active area is hidden when no calls are active. Upcoming event rows show a
-calendar color swatch, the name, and the time; click one to open its details and
-highlight the active row.
-An event with a call link shows `Join` while it is in progress. Upcoming events
-follow today's date even when you browse another week; hidden calendars,
-cancelled events, and invitations you declined are omitted.
-`New Call` opens `/app/meet/new` without creating a meeting. The `Invite Teammates`
-button above `Start call` opens the task assignee picker with name search, profile
-pictures and multiple selections, without bots or external contacts. The closed
-button shows up to three stacked selected profile pictures and the total teammate
-count; hover shows selected names, and reopening keeps the same selections. Selection
-stays local until `Start call` creates the Quick Call, connects the creator, and
-rings selected teammates. Microphone and camera are not shared before starting.
-If invitations fail after connecting, `Retry invites` sends them again without
-creating another call. Shared-link join screens do not show the teammate picker.
-Incoming invitations appear in a bottom-left notification with the call name,
-caller initials/name, and `Decline` and `Join` buttons. This stays visible across
-app pages, including call setup, hidden sidebars, narrow splits, and mobile (above
-the bottom dock). The card uses the app's menu surface, with semantic success
-color for `Join` and danger color for `Decline`. A top bar and seconds counter
-show the time remaining before the 30-second dismissal deadline.
-`Join` opens call setup; `Decline` stops ringing across the
-recipient's tabs. Unanswered invitations disappear and stop ringing after 30 seconds.
-Declining or timing out does not remove an invited live call from Channels `Live`.
-The list updates as calls end and new calls start. Calls from other conferencing
-providers open their own join links. A failed upcoming-list request has a `Retry`
-action and does not prevent creating a call.
-Working locations (such as `Office` or `Home`) stay on the calendar grid but are
-excluded from Upcoming events, including both all-day and hourly locations.
-Events require connecting a Google account (`Connect calendar`). The
-`Calendar settings` (gear) menu has an `Accounts`
-section listing each connected account with a per-account `Enable` (grant calendar),
-`Reconnect` (expired Google authorization), or `Turn off` action, plus
-`Connect another account` to connect a new Google account
-(email + calendar).
-
-`Turn off` keeps its confirmation open with `Turning off…` until removal finishes;
-re-enabling is not offered while the old calendar is still being deleted. Reconnecting
-an inbox that used calendar requests email and calendar together, while an explicit
-calendar opt-out remains off during an email-only reconnect. Per-inbox actions
-preselect that Google account. The consent callback explains that it is finishing
-the connection, provides `Back to app`, and restores the previous layout on completion.
-It applies the grant even if the old inbox list is still loading.
-
-An AI event draft defaults to the primary inbox's primary calendar. If that calendar
-is disconnected or still syncing, the draft offers reconnection or an explicit
-calendar choice and disables submission until a usable calendar is selected. It
-does not silently send the invitation from another connected inbox.
-Failed calendar or account queries show `Could not load your calendars.` with
-`Try again`, rather than offering consent or presenting the failure as backfill.
-
-`New event` opens the compact composer with All day in the date/time fields.
-The meeting-link selector lists `Macro call`, `Google Meet`, then `No meeting link`
-for new events, defaulting to `Macro call` when quick calls are enabled. Keeping
-that selection creates and attaches a Macro call after the event saves. Selecting
-`Google Meet` or `No meeting link` skips the Macro call. Out-of-office entries do
-not create calls. There is no separate call toggle or Scheduled Call menu option.
-All-day events get an untimed call link, so setup does not display a misleading midnight time.
-A failed link attachment keeps the composer open with a retry message; Save reuses
-the saved event and call instead of creating duplicates. The invitation includes
-the call link in its description and, when no location was entered, its location.
-Event details show a plain icon row with a standard gray `Join Macro call` button
-and `Copy call link`, without an enclosing border or the full URL.
-Editing or rescheduling an owned event retains and updates its selected Macro call.
-Selecting `Macro call` on an owned editable event without one adds a call on save;
-choosing another option removes its generated Macro link from the invitation.
-Removing the link or deleting the calendar event does not revoke the reusable call.
-The AI's `CreateCalendarEvent` composer (chat, agent sessions, channel review cards)
-offers the same selector under the same quick-calls flag; `Macro call` there maps to
-the tool's `addMacroCall`, and the call is created when the tool executes, before the
-event is written, so the single invitation already carries the link. The MCP server
-and channel bot accept `addMacroCall` directly. `addMacroCall` and `addGoogleMeet`
-are mutually exclusive, and out-of-office entries accept neither.
-
-The sidebar's `Calendars` section folds each connected account into a collapsible
-group: a caret plus the account address header with a checkbox that shows or hides all of
-that account's calendars at once, and the account's calendars listed beneath it (color dot,
-name, per-calendar checkbox). Accounts start collapsed. Subscribed system calendars
-(Google holidays, birthdays) carry a small RSS icon. A calendar whose sync has been failing persistently carries a small
-warning icon whose tooltip shows the provider error; the account keeps syncing its other
-calendars and the badge clears on its own once that calendar syncs again.
-
-On desktop, clicking or dragging empty grid time opens the event composer.
-While an event's details are open, a press on empty grid time closes them and
-does not start a new event; the next press creates one. Clicking another event
-switches the open details.
-Desktop event details stay inside the visible calendar grid, including Home
-previews and narrow splits. They overlap wide Day-view events when needed and
-shrink to fit the pane; long details scroll while the RSVP row stays visible.
-
-The `New event` composer (also opened by dragging a range on the grid) has an `Event kind`
-pill choosing between `Event` and `Out of office`. Picking `Out of office` hides the guests,
-conferencing, and location pills and the description field (Google rejects them on this
-type), forces a timed (not all-day) range, restricts the calendar
-pill to primary calendars, and shows a `Decline meetings` pill (`Don't decline meetings` /
-`Decline new meetings` / `Decline all meetings`) plus, when declining, an optional
-`Decline message` pill; a warning note discloses the away/auto-decline effect before saving.
-When editing an existing event the kind is read-only (Google treats it as immutable), and an
-out-of-office event's decline settings can still be changed — they read as unset because the
-provider does not report the stored ones. Timed and all-day events use solid calendar-color
-blocks with dark text on desktop and mobile. Unanswered and tentative invitations have
-lighter fills; declined events are desaturated and struck through. Month-view timed events
-keep their compact dot treatment. Out-of-office details show an `Out of office` line under
-the schedule.
-An event that Google carries on several of an account's calendars (a shared calendar's
-re-import of a member's own event, for example) renders as one chip, not one per calendar:
-the details popover's color square shows its calendars. The chip shows the title, color, and
-editability of the first shown copy in primary-first order — hiding the primary calendar
-switches the chip to the shared copy, hiding every one of its calendars hides the chip.
-Reminders, guests, and conferencing always show and follow the primary copy, since that is
-the copy Macro's alerts fire from and whose guest list and join link Macro records, and the
-editor only lets them be changed there. Answering an invitation likewise addresses the
-primary copy. The details popover and the editor act on the displayed copy, so editing or
-deleting it targets that calendar's event at Google.
-When changing only a reminder in the event editor, choose `All events` to apply it
-to the recurring series or `This event` for one occurrence. Saving preserves the
-existing dates, time zone, title, location, description, and repeat rule unless those controls
-changed. To verify, open a later occurrence of an event you were invited to,
-change the reminder, and inspect the PATCH: it should include only `reminders`
-plus the calendar and scope identifiers. Also verify that intentional edits to
-the start, end, all-day setting, title, location, description, or repeat rule are still sent.
-Test reminder removal as well as changing its time, including a series whose stored
-rule contains `INTERVAL=1`, `WKST`, differently ordered weekdays, or a precise `UNTIL`:
-an untouched rule must not be reformatted and included in a reminder-only PATCH.
-As in Google Calendar, the guests row of the details popover (a bottom sheet on phones)
-carries `Copy guest emails` and `Email guests` icon buttons. Copying puts every guest's
-address on the clipboard, comma-separated. Emailing opens a new email addressed to every
-guest but you — in a split beside the calendar on desktop, as the full-screen composer on
-touch devices — and is hidden when you are the only guest.
-
-With the `enable-calendar-team-ooo` flag on, teammates' Google Calendar out-of-office events
-overlay the grid as read-only chips titled `<name>: <event title>`. The sidebar's
-`Team out of office` section (shown only when the user belongs to a team with other members)
-has a checkbox in its header row toggling the whole overlay on or off — all teammates or
-none — and lists the next 90 days of teammate absences; clicking a row navigates the grid to
-that date. Coverage depends on each teammate having connected their own calendar and using
-Google's out-of-office event type.
-
-A calendar event mentioned in a channel message opens the calendar focused on the viewer's
-own copy of the meeting. When a person holds the event on their own calendar and posts the
-mention, it is shared read-only with the channel's current members: a member without a copy of
-their own sees the mention's title and time, and its hover card adds a `Shared with you · not on
-your calendar` line with no open action. Clicking such a mention shows that hover card
-instead of opening the calendar. A classic `@Macro` reply that mentions an event does not share
-it by posting the chip. It asks whether to share with the channel, and a yes in that thread
-writes the same channel grant. Private and confidential events are never shared this way.
-Every calendar mention's hover card shows the schedule, location, organizer and attendee
-count, plus the first lines of the event description (its links open), and no last-updated
-byline.
-
-## Pull requests — `/app/reviews/pr/<foreignEntityId>`
-
-Opening **Reviews** from the mobile dock's **More** drawer starts on **Pull
-requests** (the **All** scope). Explicit review-tab links keep their selected
-scope; desktop's default scope remains **Involves me**.
-
-Macro-linked GitHub pull requests open inside the Reviews shell, with a Reviews
-breadcrumb, PR title/status, linked GitHub metadata, discussion timeline, and Details/Checks
-side panel below the top bar. An open PR that is not a draft, and whose checks
-have all finished with a success, skipped, or neutral conclusion, also shows a
-**Merge** button in the top bar beside **Changes**. It opens a confirmation with the repository, PR number,
-and title, then merges on GitHub as the signed-in user through their linked account.
-GitHub's permissions and branch protections decide; a refusal appears as a toast
-with GitHub's reason, and a merge refreshes the PR status in place. Without a linked
-GitHub account the toast points to Settings. Draft PRs, PRs with no checks, and PRs
-whose checks are still running or failing have no Merge button. Merged and closed
-PRs have no Merge button. PRs are not tasks and do not appear in the Tasks list.
-The metadata pills beneath the PR title include linked agent sessions, using the
-agent sparkle icon. A single session shows its name; several sessions show a
-count chip opening a session list. Selecting a session opens it, with Shift-click
-on the single-session chip opening another split. The same chip appears in PR
-list metadata without activating its containing PR row. Empty links show no chip;
-loading or inaccessible session previews are not navigable. PR status pills stay
-passive; status filtering uses the Reviews list's Open/Closed sliding tabs and
-filter menu.
-Opening **Changes** slides a full-height pane in from the right beside the PR details,
-including beside the PR top bar rather than underneath it. The PR details shrink
-alongside the entry slide instead of eagerly jumping narrower. The Changes pane
-has no outer top, right, or bottom border. The PR's `+N −M` diff count pill also
-opens the pane when changes are available; it remains a passive count without a
-Changes controller or when changes are unavailable.
-Closing slides the pane fully off the right edge while expanding the left pane,
-without fading in either direction or a final width snap. From full width, the PR
-details appear behind the sliding pane, without blank space. Reopening during exit
-keeps the same pane mounted.
-The pane shell opens before the diff bodies render. Reduced-motion preferences
-disable both animations.
-The PR breadcrumb and side-panel toggle remain above the left pane. The
-**Changes** toggle stays visible in split view, ghost while closed and accent text
-on a tinted background while open; clicking it again closes the pane. There is no standalone **Open on
-GitHub** button: the pane header has no visible Changes title, and its
-`head → base · #N` is one plain-text GitHub link, underlined on hover without a
-pill background or icon. GitHub diff totals and five green/red squares appear
-beside the PR number in both split and full-width layouts. The squares summarize
-the addition/deletion mix; the numbers retain exact totals. At full width, a smaller
-PR title appears before the link. Both title and totals come from the existing PR
-query; unavailable values stay hidden, without placeholders or captured-count
-fallbacks. File headers highlight on hover. When space is tight, the smaller
-branch/PR/count metadata wraps below the title, while pane actions stay separate.
-The Changes toggle has no diff totals and becomes icon-only below 28rem of header
-width, retaining its name, tooltip, and active state. Breadcrumbs keep their existing layout.
-The full-height file tree has a fixed header with its file count on the left and
-**Hide file tree** on the right. Borderless diff controls float above the diff stack
-rather than spanning the pane in a second toolbar. Unified/Split retains text labels
-at narrow non-touch widths on the left, with diff collapse/expand and refresh on
-the right. Hiding the tree moves its count
-and **Show file tree** above the diffs, as described in
-[AI Chat](ai-chat.md#reviewing-a-linked-github-pull-request).
-Spotlighting changes hides the left pane and its top bar; **Back to the split**
-restores the prior divider position and retains the draft, diff state, and scroll.
-At host widths of 720px or less, Changes opens full-width automatically without
-that width toggle; widening restores the requested wide layout and split ratio.
-Narrow file trees start closed. **Show file tree** opens an animated drawer over the
-diffs without resizing them, including on phones. File selection, Escape, the
-backdrop, or **Hide file tree** closes the drawer and restores focus to its opener.
-The drawer does not change the saved wide-tree visibility or preferred width.
-Closing releases the drawer's dialog handlers immediately while its inert visual
-frame finishes exiting, so rapid reopening does not restore focus to a stale opener.
-The file tree has its own draggable, keyboard-resizable divider and remembers its
-width locally. Tree visibility uses the sidebar's shared width transition while
-retaining directory state and diff owners. Reduced motion skips this transition.
-The divider remains visible but inert through the tree's exit. Resizing the outer
-split or viewport settles active tree motion before applying the new geometry.
-**Copy path** briefly shows a non-pulsing success checkmark without collapsing
-the file. The PR viewer stays read-only and does not offer agent review notes.
-Copy Link from a PR in Quick Access copies `/app/reviews/pr/<foreignEntityId>`.
-Old `/app/pr/<foreignEntityId>` links redirect to Reviews. Check a copied link,
-a PR opened from a list or agent session, a second split, breadcrumb return,
-side-panel toggle, and phone layout. If no GitHub data loads, the detail shows
-an error banner with a Retry button; pressing it refetches the PR in place.
-
-PR metadata changes should update an already loaded Reviews list row and the
-linked agent session's PR status without reloading the page. To verify, keep
-both rows visible and change the PR in GitHub; check the status after the
-webhook arrives. Include a team-owned PR and a PR also stored for your personal
-account. In the network panel, confirm the update arrives on the Soup GraphQL
-subscription without triggering a refetch of every Soup list. Replaying an
-unchanged webhook should not produce another Soup update. The PR detail's
-separate diff and discussion requests are outside this subscription behavior.
-
-## Calls — `/app/component/calls`
-
-On desktop a collapsible sidebar holds the search field (`Search calls`, `⌘F`),
-the views `All` / `Missed` / `Unattended`, a `Type` section (`Internal` /
-`External`; External means at least one guest without a Macro account joined),
-a `Channels` section listing channels seen in loaded calls, and `Tags`. Choosing
-a type, channel, or tag shows only that one; choosing it again clears it. These
-refinements carry across the three views. Sort, group, filter, and `New call`
-sit in the list's top bar. Phones keep pill tabs and the header search.
-With `enable-quick-calls` enabled, `New call` opens a menu with `Start an instant
-call`, `Call a channel or contact`, and `Manage call links`; without the flag it
-opens the recipient picker directly. `Start an instant call` opens `/app/meet/new`
-without creating a meeting, the same setup reached from `New Call` beside
-Calendar's `New event` or `Create` → `Call` (`C C`). Scheduled calls are created
-through Calendar and can be shared with people who do not have a Macro account.
-The channel/contact option opens the recipient picker.
-Recordings, transcriptions
-and summaries appear here; empty state notes "Calls are available to agents."
-
-Opening a recording uses `/app/drive/call/<callId>` inside the Drive shell,
-with one breadcrumbed header (`My Files > <recording name>`) and a route back to
-Drive. The Drive file list does not include calls.
-Old copied `/app/call/<callId>` links redirect to the Drive detail without losing
-the transcript target. The detail shows a loading state, recording/transcript/summary,
-Share, and a call side panel below the breadcrumb header; a failed load shows Try again.
-`call_transcript_id=<segmentId>` seeks the matching video segment after loading.
-Check a direct link, an old copied link, a Calls-list click, a second split,
-the breadcrumb return, and clicking the same transcript search hit twice after
-playing elsewhere. On phones, recorded call headers omit **Call Again**.
-
-A channel's `Calls` tab lists that channel's recordings with the same rows, filtered
-by the channel id. Its search field matches call names and transcripts in that
-channel.
-
-In the native iOS call drawer, the horizontal participant row excludes the person
-shown in the large video. While holding or scrolling the row (including momentum),
-the displayed primary and row membership stay fixed; speaking indicators still
-update. The latest primary and membership update together after scrolling settles,
-preserving a surviving participant's position where possible. Verify that dragging
-does not pin someone, tapping pins the displayed person, and a participant who
-leaves during a held touch cannot be selected. Exercise speaker changes and
-departures during row gestures on a physical iPhone as well as the simulator.
-
-If a recording fails to play, reload the page to obtain a fresh recording link,
-or use **Open or download recording**. The playback warning does not assume
-that the failure is caused by an unsupported media format.
-
-### Call links and guests — `/app/meet/join/:shareToken`
-
-These routes require `enable-quick-calls` for both signed-in users and guests.
-In Calendar, create an event with `Macro call` selected (the default).
-The composer waits for the quick-call flag to load before choosing its default.
-Saving creates the call and includes its link in the invitation;
-the room starts on the first join. Use Calendar to edit the event or invite guests.
-Teammate rings require a live call; selecting teammates during new-call setup
-sends invitations after the call connects.
-
-`New call` → `Manage call links` lists your standalone links with `Join call`, `Copy
-link`, and `Revoke link`. Revocation prevents new joins; it does not delete calendar
-events or disconnect current participants. Each active channel call also shows its
-URL and `Copy link`. A channel call's link stops working when that call ends.
-
-Guests can use standalone meeting links without a Macro account. Links to channel
-calls only admit signed-in Macro users; visitors without an account see a sign-in
-prompt instead of the guest name form. Inside a channel call, the shareable link is
-created on request via `Get shareable call link`.
-
-New calls use `/app/meet/new`; shared links open setup at
-`/app/meet/join/:shareToken`. A successful connection replaces the URL with
-`/app/meet/:shareToken` without restarting the call. Leaving returns to Macro.
-An unexpected disconnection returns to setup so the user can retry.
-Opening or reloading an in-call URL returns to setup and requires a deliberate
-join; existing shared links continue to work.
-
-Guests enter `Your name`, choose their microphone and camera preferences, and
-press `Join call`. Setup requests microphone permission and waits until that
-prompt finishes before requesting the camera, then previews video locally;
-sharing starts only after joining.
-Permission denial leaves the affected device off and still allows joining.
-Shared-link setup shows the people currently connected, with avatars, names, and
-an attendee count. It refreshes every 15 seconds while setup is open; guests see
-this only for standalone links. Empty calls show `No one else is here yet`; a
-failed roster request leaves joining available. Transcription agents and past
-attendees are excluded.
-
-The preview and full-width join button retain their size while joining.
-The call runtime preloads while setup is open. New-call setup also reserves an
-empty room, without starting a meeting, recording, or invitations. Leaving setup
-cancels that reservation; abandoned rooms expire after five minutes. Starting
-still works if preparation fails or expires.
-Entry waits for the room connection;
-teammate invitations continue afterward. For a newly started call, transcription
-and recording start in the background instead of delaying join credentials.
-Copying the meeting URL is available after joining, in the in-call header.
-
-The creator presses `Start call`; invitees press `Join call`. Loading the page or
-completing authentication never joins automatically, including old `?join=true`
-URLs. `Back to Macro` exits setup.
-Channel-linked calls require sign-in. While authentication is loading or the
-viewer is signed out, setup must not request microphone or camera access; the
-guest name form is available only for standalone meetings.
-
-The call page shows a recording/transcription notice. It uses the normal call controls
-for audio, video, device selection, screen sharing, and effects. `Leave call` returns
-to Macro. `Copy Meeting Url` is available during the call.
-Rejoining from a new page waits for the prior page's pending leave cleanup before
-requesting another connection, so a slow leave cannot disconnect the replacement.
-Leaving the last participant archives the session first and tears down its media
-in the background, so the next call does not wait for that room to be deleted.
-It keeps its label and shows a checkmark for a few seconds after copying, then
-restores the copy icon.
-
-Guest access is limited to the call room; joining does not expose the channel or grant
-anonymous access to saved transcripts and recordings. Guest names are preserved in
-the host's call history. Signed-in attendees receive access to that session's saved
-call without gaining access to the channel.
-
-The join screen, in-call participant tiles, and incoming direct-call badges use
-profile pictures; initials are the fallback when no photo is available.
-The join screen has microphone, camera, and background effects buttons over the
-preview, with pill selectors below for microphone, speaker, camera, and
-backgrounds. The background button over the preview toggles the selected effect
-off and back on; when no effect has been selected, it enables Strong blur.
-Backgrounds use a simple menu with None, Light blur, Strong blur, and image upload
-(JPG, PNG, or WebP, up to 10 MB). Dot icons distinguish the two blur strengths.
-Selected devices and backgrounds carry into the call; unsupported browsers use
-the system speaker. If a background cannot be applied, the camera stays off
-until the user retries or chooses None. The screen uses a gray join
-button. The in-call header has a gray `Copy Meeting Url` button with a copy icon
-and shows the current local time before the call name. Owners can click the name
-to rename it, then Save or press Enter; Cancel or Escape discards the edit. Guests and other participants see a
-read-only name.
-
-Join-preview and in-call controls use the standard Macro icon buttons. Pause
-over the microphone, camera, or background group to reveal an animated settings popover
-above the call toolbar; click its caret to keep it open. Brief pointer passes
-do not open settings, and moving into the popover keeps it open. Settings
-respect reduced-motion preferences. The toolbar and settings panels use Macro's
-shared glass surface in both light and dark themes.
-Audio settings include microphone, speaker, and noise suppression. Camera
-settings include the camera selector. Clicking the background icon toggles the
-selected effect off/on, restoring the last blur strength or image (Strong blur
-by default). Its hover panel contains the same None, Light blur, Strong blur,
-and image-upload menu as the join screen; the caret pins this panel for keyboard
-and touch access. Click outside or press Escape to close the settings.
-The controls also work by keyboard and touch.
-
-### Sharing a call
-
-With quick calls enabled, channel calls use the same **Copy Meeting Url** button
-as instant and scheduled calls. Clicking it creates the share link and copies it;
-opening the call tab alone does not create a link. If loading fails, click again
-to retry. If clipboard access fails, a selectable URL appears below the button.
-
-A channel call's **Share** dialog has a `Team access` control (None or View) for the same canonical
-team share. Its side panel has a `Sharing` section with one `Share with team` checkbox, and the
-in-call controls carry the same checkbox while a call is live. It is canonical team sharing (the
-same `Team access` model documents and AI chats use), fixed at **view**. While the call is **live**
-the checkbox is a pending toggle (on by default for channel calls)
-that any participant with edit access can flip;
-other participants see it update live. When the call ends it is applied: with the toggle on,
-everyone on the creator's team can open the recorded call, read the transcript and AI summary,
-and find it under Calls and in search; off means nothing is shared. Afterwards only the call's
-**creator** can change it — everyone else sees the checkbox read-only with a note saying so.
-Team sharing is independent of channel access and of link sharing.
-
-Standalone instant and scheduled calls are excluded from team memory. They have no
-`Share with team` or `Team access` controls during the call or on the saved recording.
-Signed-in participants keep direct access to their recordings, transcripts, and summaries;
-joining a standalone call never makes its content available to the wider team.
-
-## Customers (CRM) — `/app/component/companies`
-
-On desktop, the local sidebar uses the same navigation primitives as Email and Tasks.
-Its **New** menu creates a **Company**, a **Contact**, or a **Pipeline** (Pipeline
-only when pipelines are enabled; disabled until the team's CRM is enabled). The
-**Records** section lists **Companies** and **People**; Pipelines and Lists follow.
-There are no built-in company views or Board/List layout. Companies and People
-are plain soup lists with the shared pagination. Existing personal/team saved
-views stay in the toolbar's Views menu.
-
-The selected Customers tab is stored on the pane as `sN.crm.tab`. People uses
-`people`, a pipeline uses `pipeline:<uuid>`, a list uses `list:<uuid>`, and
-hidden companies use `hidden`. Companies is the default and omits the key.
-Choosing Companies, People, a pipeline, or a list updates that parameter.
-Browser Back and Forward restore the tab and close an open record.
-
-Companies lists every visible company, grouped by Stage by default, with Owner,
-Revenue and Last Interaction columns. A Stage column is off by default; turn it
-on, or hide Owner or Revenue, under **Display options**. Its toolbar holds
-sort, group, filter, display options, saved views, and **New company** at the
-right end.
-
-People lists contacts across every CRM-enabled team the viewer belongs to, from
-the same Soup query with only CRM contacts opted in (`crmf`). The server collapses
-duplicate full email addresses (case-insensitive) to one contact. Hidden contacts
-and contacts under hidden companies are excluded. Columns are Person (name and
-email), Company and Last contacted (sortable). `Search people` matches name or
-email on the server after a short typing pause, so results include contacts not
-yet scrolled into view. **New contact** sits at the right end of the toolbar. Its
-dialog asks for a company through a **Choose a company** pill (searchable by name
-or domain, from the up to 500 most relevant companies with a domain) and fixes
-the email to that company's primary domain; **Add contact** on a company's Team
-tab skips the company pill. The company, contact and pipeline dialogs share the
-task/project composer layout: name on the first row beside **Close**, details
-below, and a **Create …** button that also submits on Command-Enter.
-
-`Search companies` and `Search people` use the shared Email/Tasks search bar.
-Command-F focuses it, `Clear search` resets it, and Escape leaves the field.
-
-On touch devices, CRM uses the same scrollable pill tabs as Tasks in the top
-header: Companies, People, available pipelines, and enabled lists. Swipe the
-strip horizontally to reach every destination; the selected tab stays visible.
-The tabs remain available inside pipelines, with no hamburger button. Company
-filters lead the strip when available. On mobile, pipelines omit their title
-and sharing row and use an edge-to-edge table, below the top safe area and above
-the bottom dock. The compact **Pipeline actions** button in the table toolbar
-opens rename and sharing controls; only owners see **Trash pipeline**, which
-requires confirmation. Sharing opens the existing share dialog. Companies uses
-the full-frame list with the global **+ Company** action above the dock. People keeps its search and **New contact** below the tab
-strip. The embedded detail stack stays out of the mobile flow, so selecting a
-row navigates in place.
-
-On desktop, clicking a company or a person in the list (or pressing Enter on a
-focused row) opens its details inside the CRM workspace, keeping the left
-navigation visible. The top breadcrumb reads `<Companies, People or list> >
-<record>`; click the first segment to return with the same filters and list
-scroll position. Selecting another sidebar entry closes the details. Shift-click
-still opens the record in a separate split. Direct company and contact links use
-the standalone pages.
-Each record opened from the details appends a breadcrumb: a contact from a
-company's Team tab gives `Companies > <company> > <contact>`, and a person's
-Company link gives `People > <contact> > <company>`. Opening a record already in
-the trail (such as the contact's own company from `Companies > <company> >
-<contact>`) returns to it instead of adding a duplicate. The CRM sidebar stays
-visible throughout.
-Company and contact headers have `Copy link` beside the side-panel toggle.
-Their information panel starts closed and opens as a floating bubble at every
-width, without shrinking the record content. Click outside the bubble or use
-the toggle to dismiss it; the open state is not restored on a later visit.
-It copies the record's direct URL and shows a confirmation toast; this is also
-available in the embedded company and contact breadcrumb header.
-
-The Team, Emails, Files, Tasks, and Calls tabs share a compact toolbar: search on
-the left, with available filters and actions on the right. Search remains visible
-for empty lists. `Add contact` and `New task` match the project task list's
-creation button: a rounded outline, standard height, and leading plus icon.
-The associated-tab search fields match the creation buttons' height.
-Team rows show a profile photo when available, otherwise a
-letter avatar at the same 16px size as channel list icons. Team uses the same Soup
-row component as Emails, Files, and Calls: the avatar, name, and email are inline,
-the last-contacted timestamp sits at the right, and the side gutters and row
-spacing match. There is no column-heading row.
-Emails, Files, and Calls search the loaded row titles and supporting text and
-continue loading pages when the current pages have no match.
-
-A company is laid out like a project. Its split header or embedded breadcrumb
-header shows inset `Overview`, `Team`, `Emails`, `Files`, `Tasks`, and `Calls`
-tabs, collapsing to icons when narrow. Overview shows the name, pills
-for each domain and `Last interacted`, the generated description, a
-**Pipelines** section and the Discussion. Pipelines stacks one full-width card
-per row of a pipeline you can open that references the record. A card's header
-strip names the pipeline (a lock marks a private one); below it, the row's first
-four fields sit side by side, label over value, and the rest wait behind
-`Show N more`. Cells edit like the pipeline table's when you can edit that
-pipeline. Inside Customers, the header's `Open <pipeline>` button opens it. The
-`Pipelines` caret header collapses and expands the cards, like the Discussion
-header; both start expanded on each visit. The
-section is absent when the record is in no pipeline.
-Team lists the contacts with `Add contact`. Emails keeps the
-`Signal`/`All` and `Team`/`Me` toggles; `Team` shows teammates' threads even to
-a viewer with no connected mailbox. Files, Tasks, and Calls list items
-*associated* with the company: its `Companies` property names the company, its
-`Contacts` property names one of the company's contacts, or it @mentions (or a
-message attaches) the company or one of those contacts. Contacts beyond the Team
-tab's first page count, hidden contacts count only for team admins and owners,
-and an item matching several ways appears once. Files lists non-task documents
-plus attachments of emails with the company's domains. Tasks is the Tasks list
-with that scope, grouping, and Load more; `Search tasks` matches task names
-within the scope (not content). Its `New task` composer pre-fills the company.
-Calls includes calls linked automatically from their participants and calls
-whose thread mentions the company. The side panel keeps Properties and Sharing,
-and adds **References**: associated items of any type (documents, tasks,
-channel messages, email threads and calls with the property, events, chats,
-projects, and companies or contacts whose properties or Discussion name the
-company) as compact icon-and-name rows, paged as it scrolls. A channel message
-row opens its thread; a reply surfaces as its thread's row. A document
-Discussion message makes its document the item. Initiatives and database rows
-are not listed.
-When a record list fails to refresh (for example, the record became
-inaccessible), it replaces its rows with `Couldn't load this list.` and
-`Retry` reloads it; a failed later page keeps the rows and shows `Couldn't
-load more.`
-A contact has the same layout with `Overview`, `Emails`, `Files`, `Tasks` and
-`Calls`: Overview pills show the email, the company (opens it) and `Last
-interacted`, followed by the contact's Pipelines cards. Its Files, Tasks, Calls,
-and References show items associated with the contact itself (its `Contacts`
-property or an @mention of it), not everything associated with its company;
-Files also includes attachments of emails with its address. Tasks created from a
-contact also reference its company. The side panel keeps Sharing (admins only)
-and adds References.
-
-Mentioning a company or contact with `@` in a document or task records it as a
-reference of that record (removing the chip removes it) without sharing the
-document, inviting anyone, or notifying the contact; channel and Discussion
-messages record their CRM mentions when sent or edited. Open record lists
-refresh after a CRM mention or a `Companies`/`Contacts` property changes. To
-verify, mention a contact in a document, then check the contact's and its
-company's References and Files without reloading; remove the chip and confirm it
-drops out.
-
-Company and contact pages have a **Discussion** section built from the same
-message conversation as a document's Discussion: threaded replies, reactions,
-attachments, and edit/delete from the message menu. `@` suggests the team's
-members and agents. A message's copied link is the standalone record URL
-with `comment_id`; opening it, or a CRM discussion notification, scrolls to and
-highlights that message. Deleting a thread's first comment deletes the thread.
-
-Company selection actions **Set owner** and **Set revenue** remain available
-while team deal-stage definitions are loading. **Set stage** waits for the active
-team definition rather than opening an editor with system defaults. Check both
-the entity actions menu and command menu with stage requests delayed; cancel the
-editors without changing hosted data.
-
-`Collapse CRM sidebar` persists across visits; `Expand CRM sidebar` restores it.
-At narrow widths, `Show CRM navigation` opens the same navigation in a menu.
-The sidebar's Records and Lists sections can also collapse independently.
-
-**Pipelines** in the CRM sidebar hold company or contact entries in the shared
-records editor. They have their own identity, ownership and sharing; their
-storage does not appear as a separate database in navigation.
-**New pipeline** is disabled until the team's CRM is enabled. For a new team,
-use **Open CRM settings** in the empty state to enable CRM, then return to
-Customers to create a pipeline. Verify this with a newly created team as well as
-an existing CRM-enabled team.
-Choose **New pipeline**, enter a name in the dialog's first row, pick
-**Companies** (the default) or **Contacts** from the record-type pill, and tick
-**Share with my team** to share it (unticked keeps it private). **Create
-pipeline** or Command-Enter submits. Creating opens the pipeline's
-editable table. Team members can edit shared pipelines; the creator owns them.
-Anyone who can edit a pipeline can share it from the standard **Share** dialog.
-Pick people or channels and an access level, and the message carries the pipeline.
-The **People** list changes or removes their access. A teammate who receives a private
-pipeline sees it in their Customers sidebar. Only the owner sees **Team access**:
-choose **Edit** to share with the team or **None** to make the pipeline private.
-Viewers see only **Copy Link**. **Copy Link** copies a CRM link that opens this pipeline for
-anyone who has access; pasted into an editor it becomes a pipeline mention (see
-[CRM pipeline mentions](documents.md#crm-pipeline-mentions)). On mobile, team
-access is in the **Team** tab.
-
-The first column is a required company/contact reference. Clicking a filled
-reference, or pressing Enter on it, opens that company or contact; on desktop it
-opens in place with the pipeline name in its breadcrumb (choose it to return),
-and on mobile in its own view. The same applies to the reference shown as a
-board card's or record panel's title. To change which record a row references,
-focus the cell and press F2 or start typing; an empty reference cell opens the
-picker on click. The same company or contact can occur in multiple rows in a
-pipeline and can also belong to other pipelines. Each row has its own field
-values; **Duplicate** copies a row into a new entry referencing the same company or contact. The reference column
-can be renamed but cannot be removed or changed to another type. Stage, Owner,
-and Revenue are independent pipeline fields; editing them does not modify the
-company's CRM fields. Use **Add column** or a column header's menu to customize
-columns. Pipeline Stage options initially copy the team's current deal stages. Open
-pipelines refresh other editors' changes periodically; a local edit refreshes
-immediately after saving.
-A pipeline page uses the database page's styling with one table and no table
-tabs. Its header shows the name, edited in place by editors, a **Pipeline
-actions** menu (**Rename**; **Trash pipeline** for the owner) and **Share**. The
-toolbar below has **All records**, the pipeline's stored views and **New view**
-(Table or Board), plus Group by (boards), Filter and Sort, then **Add company**
-or **Add contact** (by the pipeline's record type) for editors, which starts a
-row whose reference cell picks the record.
-Stored views are everyone's and are written through the pipeline, so changing one
-changes it for all viewers; All records is each viewer's own. A board can move a
-card to another group from its card menu or by dragging, which sets the row's
-grouping cell. Card order within a group is not read back after a reload, and
-views cannot be reordered yet. The selected view is remembered per pipeline.
-**Trash pipeline** removes its table from navigation without deleting the linked
-companies or contacts, then returns to Companies.
-
-CRM lists are currently disabled by `enableCrmLists` (default `false`). The sidebar
-Lists section, list editor, and company membership controls only mount when enabled.
-Existing list data is preserved; a restored list view returns to All companies while
-disabled. Saved filter views remain available.
-
-When enabled, lists are personal, team-scoped collections of explicit company IDs, persisted through
-saved-view storage separately from saved filter views. `New list` opens a name and
-company picker; `Edit list` changes membership or deletes the collection. An empty list
-must not show every company. The picker browses up to 500 recent companies. Canceling
-never saves the draft. Saving only closes the dialog after the server succeeds.
-
-Company detail pages show a **Lists** section in the right panel, with current
-personal list memberships as chips. **Manage lists** expands a searchable checkbox
-picker. Checking or unchecking saves immediately and refreshes the CRM sidebar's
-membership counts. Changes are disabled while saving; failures show an inline retry
-message and keep the last saved membership. With no lists, create one in the CRM sidebar.
-
-`New company` uses the existing creation dialog. `Import` previews a CSV with `name`
-and `domain` columns (1–100 rows, at most 1 MB). The explicit Import button writes the
-previewed companies. Partial failures retain only failed rows for retry. Use preview
-and cancel for browser checks against hosted dev data. `CRM settings` opens the existing
-settings panel. Requires a team with CRM enabled.
-
-`Export` opens options for companies. Choose Current view
-(respects filters/search) or All records across views (each visible record once), then
-select CSV columns. Company exports include Stage, Owner, Revenue and optional custom
-properties. `Prepare export` fetches every page and shows a count and three-row preview;
-it does not download. `Download CSV` saves the prepared snapshot using the selected
-columns. Changing scope requires preparing again. Cancel stops preparation. CSV uses UTF-8,
-quoted fields, original date timestamps and spreadsheet formula escaping.
-
-## Activity — `/app/component/activity`
-
-To verify document content activity, keep Activity open in one tab and edit an
-existing document's body in another, without renaming it. The editor's Edited
-entry should arrive for the first edit. Keep typing across multiple saves: the
-activity count must stay unchanged. After five minutes without editing, the next
-edit should add one new event. Reconnecting within that window and opening or
-closing a document without edits must not add an event.
-
-Requires authentication and the `enable-activity-feed` flag. Direct navigation and
-restored splits wait for flags to load; when disabled, they redirect to Home
-(`/app/home`) without loading the activity feed.
-
-When checking Activity, enable GraphQL Soup as well as the activity flag. Verify
-that an initial visit resolves entity names in both the feed and Most active,
-then reload and scroll through another page. Preview loading and live name
-updates should keep the page responsive without repeatedly fetching previews.
-
-Activity refreshes live after recorded actions. With two pages loaded, make an
-action in another tab and verify the feed retains its page-boundary rows while
-the action count and heatmap update. An open entity activity panel should also
-refresh for actions by another authorized user. After disconnecting and
-reconnecting the websocket, verify recovery without requiring another action.
-Hidden tabs defer refresh until visible; purges refresh all mounted activity
-queries through the normal access checks.
-
-GitHub-style actions heatmap (one a11y node per day — makes snapshots huge; prefer saving the
-snapshot to a file), then a `Most active` section header (styled like the feed's day headers)
-over a wrapping row of pill chips (entity icon, name, action count; click opens the entity,
-shift-click opens a new split; the section is absent when there are no entities), then a feed
-of "You edited/created X · 17h" entries grouped under day headers, with the compact relative
-time (`17h`, `8d`, `1mo`) inline after a middot rather than right-aligned; hovering the time
-shows the full date. Each row is a plain action glyph joined to its neighbours by a thin
-connector line (the line stops at day headers) and never wraps: a long entity name truncates
-with an ellipsis, and the full name is in the mention's hover preview. Consecutive same-actor,
-same-entity, same-action events within a day read as one line with a count (`You edited Doc X
-5 times · 2h`; property changes read the net change, `changed Status from A to C on Doc X · 3
-changes · 2h`), so the row count is lower than the event count (`[data-activity-run-size]`
-carries the fold size). The whole page is one virtualized list: only rows near the viewport
-are in the DOM, and scrolling near the bottom fetches the next page automatically (a
-`Loading…` tail appears while it lands). If a page fails, the tail reads `Couldn't load more.`
-with a `Retry` button and automatic paging stops until it is pressed. There is no `Show more`
-button.
-Once the heatmap card scrolls away, the day header for the topmost visible row stays pinned at
-the top of the list (`[data-activity-pinned-day]`, a non-interactive copy), so a snapshot taken
-mid-scroll shows that label twice at most. The heatmap always shows the whole year, including
-the partial first and current weeks, and spans the card at every width: in a wide pane the
-space between week columns opens up, its cells shrink from 14px to 8px as the pane narrows, and
-below that (a phone) the week area scrolls sideways with the month letters, opened on the newest
-week and with no visible scrollbar. Under ~672px the four stats read as a two-column grid; under
-~448px (a phone) the legend drops its `Fewer`/`More` words, each stat stacks its label over its
-value, and chips shorten. Rows stay on one line at every width. On touch devices the list rests
-below the floating page title and above the bottom toolbar.
-
-With Databases on, databases are activity entities too: creating, renaming, trashing,
-restoring, or permanently deleting one, and every write to its tables (grid edits and
-agent tools) lands on the acting user's feed as `You created/edited/deleted <database>`;
-the mention opens the database. Databases also appear in the Ctrl+K command menu under
-**All** and **Files**, ordered by creation time. Home's merged feed and the Recent view read Soup, which
-does not list databases.
-
-## Home — `/app/component/home`
-
-Greeting, example prompt buttons (`Draft a document`, `Draft an email`,
-`Search & research`), and the ubiquitous `Ask AI` composer. Finishing onboarding
-without a deep link lands here. The retired Getting Started page's old
-`/app/getting-started` and `/app/component/getting-started` links also open Home.
-
-On phones, shared confirmations (including Remove Member and Cancel Invitation)
-use a glass sheet with a title, description, Close confirmation button, and
-side-by-side cancel and confirm actions. Pending actions disable both buttons
-and prevent dismissal; canceling leaves the underlying data unchanged.
-
-## Onboarding bypass — `/app/onboarding`
-
-All `@macro.com` accounts see a **Bypass** button on every onboarding step. It
-skips the rest of the flow and leaves onboarding. Accounts on other domains
-do not see it.
-
-## Setup plan step — `/app/onboarding`
-
-Onboarding has no plan picker; it ends with the 30-day Premium trial offer and a
-Guest continuation (see [login](login.md#desktop-onboarding)). Plans are chosen
-afterwards in **Settings → Billing**, where Guest users can buy Premium or Max.
-
-## Settings — `/app/settings/<section>`
-
-### Slack archive import
-
-Temporary message storage recovers closed IndexedDB connections without restarting
-the import or deleting staged history. Verify closure between staging batches and
-between cursor pages: all messages must remain ordered, deduplicated, and within
-the original byte limit. Cancellation and cleanup still work during recovery.
-Deleted or replaced scratch databases fail the old import instead of silently
-continuing with incomplete history; its cleanup must leave a replacement intact.
-
-In **Team → Connections**, **Import from Slack** appears only for team admins
-and owners with `enable-slack-archive-import` enabled. Production rollout stays
-off until explicitly enabled. Select an export ZIP, filter the grouped conversation
-picker, optionally show archived conversations, and use Space to toggle focused
-checkboxes. **Select all visible conversations** preserves selections hidden by
-filters; unchecking it or **Clear visible selection** clears only visible selections.
-Rows show stable Slack IDs
-so duplicate names remain distinguishable. Counts are advisory when available,
-otherwise “not yet counted.” Discovery moves keyboard focus to the filter.
-Slack file/canvas discussion folders (`FC:<file-id>:<title>`) are ignored, not
-imported as channels; their presence must not prevent channel discovery.
-
-Review email attribution and external membership implications, choose whether to
-include history, and confirm the immutable Slack workspace binding before
-**Import selected channels (N)**. At least one selection is required. File selection
-alone makes no server writes. Close/Escape or cancel before confirmation discards
-the archive and selection without creating a job; reopening requires choosing a
-file again. After confirmation the selected IDs/options are frozen. Closing and
-reopening then retains the upload session; keep Team Settings open until it finishes.
-The dialog restores focus to its opener, and polling should not blank Settings.
-
-Use **Job history** (including older pages) for server progress after a reload.
-It displays the persisted selected names/IDs/kinds, history option and selected
-failures/skips without the ZIP. Unselected channels are not skipped work. Reload
-recovers server tracking, **not interrupted local uploads**; finalize verified work
-with skips or cancel and explicitly confirm a new import/token.
-**Cancel import (keep partial results)** does not delete committed messages or
-channels; running work may finish. An interrupted upload offers **Recover job
-receipt**, then **Finalize with skips** or cancellation. Channel links appear only
-when the server confirms current participation and the viewer's channel list
-confirms access. Verify counters, errors and skip
-reasons at narrow widths, using synthetic exports and a test backend rather than
-importing customer data into hosted dev.
-
-For a release check, inspect the actual create request and then reload the server
-receipt: both must contain exactly the selected Slack IDs and history option.
-Select two rows with the same display name, filter both out, and confirm the
-selected total remains unchanged. Cancel before confirmation and verify there
-were no create, registration or PUT requests. An open job must reject tampered
-registration/sealing of an unselected ID; a client-only picker test is insufficient.
-Check desktop web and Tauri: opening Settings alone creates no ZIP worker, and
-signed PUTs work without dropping checksum or conditional headers. A 412 upload
-retry verifies the existing object instead of overwriting it. Keep an active job
-open through websocket disconnect/reconnect to verify polling remains usable.
-The [runbook](../SLACK_ARCHIVE_IMPORT_RUNBOOK.md) distinguishes fixture tests from
-live-backend release gates and documents staging retention and recovery.
-
-### Email signatures
-
-Open **Settings → Email → Signatures**. Each owned inbox has a visible editor;
-there is no expand/collapse control. Format the text, add links or images, and
-choose **Save signature**. **Clear signature** removes only the signature, while
-**Remove inbox** in Accounts uses the existing inbox removal confirmation.
-**Add to replies & forwards** saves that preference immediately. On desktop,
-**Import from Gmail** in each inbox's header fetches that account's Gmail
-signature and saves it right away, replacing any unsaved draft; a toast reports
-when Gmail has no signature. Unsaved drafts
-survive switching settings pages. On phones, signature editing remains desktop-only;
-the replies/forwards toggle and clear action are available.
-Email accounts can also be managed from **Integrations**. Its **Email settings**
-link opens the dedicated page, and Email links to Notifications and Calendar.
-With a composer open, save a changed signature or reply-signature preference and
-verify its preview updates. Once the account refresh completes, reopen a composer
-offline and confirm it uses the saved settings.
-
-### Notification snoozes
-
-Open **Settings → Notifications** to see **Snoozed items** and their local resume
-times. **Change time** opens the same searchable time picker used by entity
-actions; **Resume** cancels a snooze immediately. Permanent mutes appear separately
-under **Muted items**, with **Snooze instead** to replace one with a timed pause.
-
-The Chat detail pane also supplies these commands for its current channel or DM;
-focus the conversation before opening the command menu.
-
-To snooze an entity, right-click its row (long-press on mobile) and choose
-**Snooze notifications…**, or select/open the entity and search for that command
-in Cmd/Ctrl+K. Multi-selection applies the chosen deadline to all selected items.
-Use arrow keys and Enter, click a preset, or type a future date/time such as
-`2h` or `tomorrow 10am`. The next morning means the next local 9 AM; the weekend
-preset resumes on Monday at 9 AM. The picker displays the exact local date and
-time before saving. Escape closes the picker; before choosing a time, it makes
-no changes.
-
-Snoozing pauses notifications only: it does not hide, archive, mark read, or mark
-done. Channel message/thread rows target their parent channel, matching mute.
-The server enforces expiration even when no client is open. Displayed snooze
-state refreshes when the window regains focus or a mute/snooze changes; the
-client does not poll. A failed save keeps the picker open for retry; a successful
-save appears in notification settings.
-If only some selected items save, the picker shows the saved count and retries
-only the remaining items. Closing it keeps any snoozes already saved.
-
-On phones, long-press opens the entity actions drawer. The snooze time picker
-uses the same responsive `Dialog`, width, and `CommandMenuShell` as Cmd/Ctrl+K,
-with larger touch targets and tap instructions. Swipe the preset list when the
-viewport is short. In **More views → Settings → Notifications**, item names and
-deadlines sit above **Change time** and **Resume**. Saving or cancelling a picker
-returns to the settings sheet. Start new snoozes from an entity's actions or
-Cmd/Ctrl+K; Settings manages existing snoozes and mutes.
-
-Design references: [Slack notification pause/resume](https://slack.com/help/articles/214908388-Pause-your-Slack-notifications)
-and [Superhuman's keyboard-driven Remind Me picker](https://new.superhuman.com/remind-me-29124).
-Macro applies the temporary pause per entity and keeps the entity visible.
-
-### Team membership
-
-Team membership has no size cap, including free teams. Invitations and domain
-auto-join must keep working beyond five members and the former stage-plan limits.
-Free-team joins do not create a paid subscription, bill a seat, or grant premium
-roles. Teams with an existing paid subscription retain their per-seat billing;
-enterprise teams retain their billing bypass.
-
-On a local stack started with `--no-doppler`, verify free-team creation from a
-fresh passwordless signup. It must work without Stripe credentials.
-
-Under **Team**, owners/admins can turn **Auto-join on domain** off and can restrict
-invitations to admins with **Members can invite**. These controls still apply.
-To verify the membership flow, use a local free team with five members: invite
-and accept a sixth member, then sign up another user on its enabled auto-join
-domain. Both should appear in the team's member list and configured auto-join
-channels without an upgrade prompt. Repeat with auto-join disabled to verify a
-same-domain signup is not added automatically.
-
-### Navigation
-
-On phones, **More views → Settings** opens an inset glass sheet over the current
-page. The main page has a profile shortcut and the same grouped Blocks, Personal, Workspace,
-and Developer sections as desktop, plus enabled admin settings. Search finds
-individual settings; selecting a result opens its page and reveals the section. Tap a row to open that settings
-page inside the sheet; **Back to settings** returns to the grouped list at its
-previous scroll position. `API Keys` is desktop-only and has no row here.
-**Close settings** at the top right, Escape, an
-outside tap, or a downward swipe dismisses the sheet. A tap that dismisses a
-menu opened inside the sheet leaves the sheet itself open. Opening Settings again
-starts at the main page; explicit links (for example Account) open their
-section directly. Existing settings URLs open the requested section in the sheet
-and restore the underlying app route. The header stays visible while forms
-scroll, including with the keyboard open. On desktop, Settings is an ordinary
-split view: the rail's gear button (or `Ctrl ;`) opens it in the active split
-like any other rail item, and Shift-click opens it in a new split.
-`/app/settings/<tab>` opens it as the only split with the app rail still
-visible, and `/app/home/~/settings/<tab>` places it beside Home. Its inner
-sidebar matches Email and Tasks: a **Settings** title bar, a rounded
-**Search settings** field, the grouped section pills, and **Log out** pinned to
-the bottom. Unlike other views, it cannot be hidden at desktop widths: there is
-no **Hide navigation** toggle and `Cmd .` does nothing, even if it was hidden
-before. Below 720px the sidebar becomes an overlay opened from **Show
-navigation** (or `Cmd .`), which starts closed. Escape closes a
-settings split that shares the layout, or steps back to the previous view when
-it is the only split (Home when there is none). Leave settings by picking any
-other rail item; there is no separate back or fullscreen control.
-
-Settings pages use the email composer’s raised surfaces on the page background.
-Section headings and controls share a white surface in light mode and the
-composer border in dark mode, with subtle row separators. The compact sidebar
-uses the shared workspace width.
-
-When a newer version is ready, an **Update available** button (a download icon
-in a subtle accent circle that a glowing comet periodically circles) appears in
-the sidebar rail above the mobile-app and settings icons. Its popover (a title,
-a short description, and one action) opens by itself once per update until
-dismissed (click outside or Escape); the button stays until the update is
-applied. Its wording and action depend on the update: **New version available**
-/ **Reload** for a newer web build, **Update ready** / **Update** for a
-downloaded bundle in the desktop app, and **Desktop app update ready** /
-**Restart and update** for a native desktop update. When part of the app fails
-to load because a newer web build replaced it, the same button appears and its
-popover opens again (even if dismissed) with **Reload**; there is no blocking
-alert. Touch layouts have no rail, so a newer web build shows a **Reload** toast
-there instead.
-
-On desktop release builds, **Account → Desktop app update** shows native update
-progress. While preparing to restart, the popover can't be dismissed and its
-action is disabled. Restart waits for pending canvas/PDF saves and
-local persistence; active calls, uploads, and imports must finish first. A ready
-update also installs on normal app quit. Closing a window only triggers
-installation if it exits the app. Browser, mobile, and development builds do not
-show this native updater row.
-
-Below Profile, **Account** shows a card naming the current plan (**Free plan**,
-**Pro plan**, or **Max plan**; **Loading plan…** until the billing summary
-arrives). Clicking it opens **Billing** settings.
-
-Left nav (feature and platform gates still apply):
-
-- **Blocks**: Email, Calendar, Agents, CRM.
-- **Personal**: Account, Appearance, Notifications, Keyboard shortcuts, Usage, Billing, Desktop App, Mobile App.
-- **Workspace**: Team, Tags, Integrations (personal Gmail/GitHub accounts).
-- **Developer**: Agent connections, Runtimes, MCP server, API Keys, Bots.
-
-**Desktop App** (`/app/settings/desktop-app`) shows a compact version and
-build-date card in the desktop app. The date is when the running app bundle was
-built, not when it was installed on the computer. In the browser it links to the
-latest desktop release on GitHub, and only appears when the `desktop-app` PostHog
-flag is enabled. Native desktop always shows this section regardless of the flag;
-native mobile never shows it.
-
-Search checks individual setting titles and keywords, tolerates common typos,
-and shows the parent page below each control result. Selecting a result opens
-that page, scrolls to its section or row, and briefly highlights it. Try
-`singature`, `email digest`, `calendar color`, or `cursor`. Arrow Down from search
-focuses the first result; Tab moves through controls normally. Escape in the
-search field clears the query. Clearing search restores the grouped navigation. Keyboard shortcuts are listed
-by category with the action on the left and keys on the right; expand **Keyboard
-preview** for the visual key map.
-Appearance starts with visual **System**, **Light**, and **Dark** mode choices.
-The previews use the saved themes; System follows the device and exposes both
-per-mode theme selectors. Light or Dark shows its own theme selector. Each selector
-retains theme search, editing, copying, and custom theme creation.
-
-Existing settings URLs remain valid; `connections` still opens Integrations,
-`agent-connections` opens Agent connections, and `harness` aliases Runtimes.
-
-`Usage` appears directly above Billing, including for Free accounts. In
-production, the `enable-ai-usage-billing` PostHog flag controls activation. While
-it is off or loading, the page shows **AI billing changes take effect on October
-8, 2026.** and all Usage controls are disabled. Turning the flag on activates the
-page and removes the announcement. Dev and local remain interactive even with
-the flag off. The production usage-limit dialog follows the same flag. Its
-**Monthly limit** meter displays a percentage using the backend's current-period
-usage and allowance. The info button explains AI agent chat and AI document
-editing. **Usage Credits** shows the dollar balance and `Add more`, which opens
-**Need more usage?** with `$25` / `$50` / `$100` / `Other`. Supported amounts
-redirect to Stripe Checkout; unsupported custom amounts are disabled. Free
-accounts see `View plans` instead of purchase or reload controls; paid team
-members who are not the payer see only “Usage credits are managed by your team.”
-Their credit balance and automatic reload row are hidden, with no
-credit-purchase action.
-Team owners who pay for their team's seats manage the shared credit balance and
-automatic reload here in Usage, including purchases, balance thresholds, the
-monthly reload cap, and payment methods. Team payers see **Team Usage
-Credits**, “Credits are shared by your entire team.” and **Shared team balance**.
-The purchase and auto-reload dialogs also identify the team-wide credit balance.
-Team settings manages seats. Included
-usage remains per seat: the owner's Monthly limit meter describes their own
-usage, not the sum of the team's allowances. Team payers with a finite
-allowance see “This is your personal monthly usage limit.” beneath the meter.
-Unlimited enterprise plans show `Unlimited` and do not offer credit purchases
-or automatic reload. The development paid-plan preview can still display
-those controls, with purchases disabled.
-
-The **Automatic reload** switch opens **Auto-Reload** without toggling directly.
-It contains Minimum balance (default `$10`), Target balance (default `$100`),
-optional Maximum monthly spend (`No limit`), a payment-method management link,
-and the automatic-charge warning. The dialog saves for paid payers:
-`Turn on auto-reload` enables automatic credit purchases with those thresholds,
-`Save` updates them while on, and `Turn off` disables automatic reload. The monthly
-limit caps reload purchases per UTC calendar month. The **Automatic reload**
-switch reflects the saved state and is the billing opt-in indicator. Paid team
-members who are not the payer see
-`Only the account that pays for this plan can change automatic reload.` and
-cannot save. After a failed automatic reload the Usage row shows
-`Paused — payment failed` while preserving the enabled setting. The dialog shows `Your last
-automatic reload could not be charged. Update your payment method, then save to
-try again.`; saving retries. Extra usage is funded entirely by prepaid credits.
-If the reload budget runs out or payment fails, uncovered usage cannot trigger a
-direct usage charge; with quota enforcement enabled, exhausted credits and
-allowance block further AI requests. Historical direct-charge invoices are still
-recognized by webhooks, but settlement never creates or retries them. Local
-**Developer tools** offer
-`Preview Free plan` and `Preview paid plan` to display either Usage page with
-sample usage, regardless of the signed-in account's tier.
-`Open Free usage-limit dialog` and `Open paid usage-limit dialog` open the
-corresponding exhausted-usage prompt directly. The previews also work before
-the usage summary loads or when it fails. The paid-plan preview allows
-testing Auto-Reload settings. Purchases and payment management are disabled during any
-preview; `Reset preview` restores server data and closes the usage-limit dialog.
-`Preview production before Oct 8` shows the October 8 announcement and disables
-Usage controls, including usage-limit dialogs. Dev tools remain interactive:
-Free and paid previews can be combined with this state, and `Reset preview`
-restores the normal dev view.
-
-Local **Developer tools → Open Billing Lab** opens `/billing-lab.html`, a
-standalone simulator with no login or billing API calls. Its 20 presets include
-Max with a pending Pro downgrade, exhausted allowances, credits, payment
-failures, team roles, loading, and errors. Select **Max → Pro at renewal**
-to start with a scheduled downgrade, and choose **Advance to
-renewal**: Max stays active until renewal, then Pro becomes active and included
-usage resets. Billing displays the scheduled downgrade and effective date;
-**Keep Max plan** cancels it and preserves the active plan and usage. The
-timeline also offers **Cancel scheduled change**. Purchases open a simulated checkout with explicit completion;
-**Fail the next billing request** enables error and retry checks. Scenario links
-restore the preset, not edits. **Monthly reload limit reached** opens Usage with
-a notice banner: **Monthly auto-reload $50 limit reached**, with **resets Nov 1**
-on the right. **Adjust limit** opens Auto-Reload; **Add credits** opens credit purchase.
-Manual credits do not count toward the monthly reload cap, which resets at the
-UTC month boundary. Live Usage shows this same banner from the API's monthly
-reload commitments and reset date, including when remaining cap room is below
-the minimum reload charge. Paid/pending reloads and failed invoices that can
-still collect count toward the cap. Older backends without these facts show no notice.
-The **Teams** scenario group opens Usage directly. **Mixed-plan team owner**
-previews shared credits and enabled reload for one Max and three Pro seats;
-**Team credits exhausted**, **Team reload paused**, and **Team monthly reload
-limit** exercise the owner's purchase, payment-recovery, and cap controls through
-the same Usage dialogs. Credit purchases add to the shared balance, while the
-included-usage meter remains scoped to the viewer's own seat. **Team-paid Max
-member** previews the notice-only member view. The simulator does not meter
-other members' activity or perform automatic charges.
-See [Billing Lab setup and boundaries](../../apps/web/src/features/billing-lab/README.md).
-
-`Billing` shows the current plan and `Manage`. Free users see separate Pro
-(`Get Pro`) and Max (`Get Max`) cards, side by side when the panel is wide enough
-and stacked on narrow panels. The Pro card shows `Free for one month!` for Free
-users. `Get Pro` requests the same server-validated 30-day first-subscription
-trial as onboarding; checkout redirects only after the server confirms the trial.
-Ineligible accounts see the rejection reason and are not silently charged.
-`Get Max` keeps standard paid terms. Prices read `/ month` for solo users and
-`per seat / month` for team accounts. Each card puts its button beside the price when wide enough and below
-the price when narrow. Free lists 2 connected email accounts; Pro and Max list
-unlimited connected email accounts. Pro users see a Max card (`Upgrade to Max`); Max
-users keep their current plan. Cards appear only for users who can
-manage their subscription. Team-paid members see no plan options, including
-on Free seats. Member options stay hidden until the billing summary confirms
-they pay for their own seat. On a team, a plan change moves only the viewer's
-own seat. Max lists "10x more AI usage than Pro"; Free and Pro allowance labels
-still follow the `enable-ai-usage-billing` flag. Usage controls live in Usage.
-The upgrade modal and Billing use the same plan cards and benefits, including
-the same flag-gated AI usage label and responsive card layout. The modal offers
-Pro and Max to Free accounts, only Max to Pro accounts, and no upgrade cards to
-Max accounts. Cards in the modal show benefits without purchase buttons. The footer’s
-`Manage plan` closes the modal and opens Billing settings, where checkout and
-plan changes take place. Team-paid members see a message
-to contact their team owner. Plan options wait for the billing summary and team
-lookup; failed lookups show `Try again` rather than guessed upgrade options.
-
-On a local HMR dev server, `Preview billing & paywall` opens an opt-in preview in
-Billing. Choose Solo, a team-paid member, a self-paying member, or a team owner,
-and Free, Pro, or Max. `Permissions, loading, and feature states` exposes the
-billing summary status, billing permission, active/trialing license, AI usage
-flag, and pending plan actions. The preview uses the real Billing UI with local
-fixtures; checkout, plan changes, Manage, and Team settings only show preview
-status messages. `Preview paywall` opens the same modal for the selected state,
-without developer controls inside it. Dismissing the modal returns to Billing
-with the selection preserved. `Manage plan` returns to the selected Billing preview.
-`Reset preview` restores Solo/Free; `Exit preview` restores
-the signed-in account. State is not persisted and resets on leaving Billing.
-These controls are excluded from deployed builds, including dev.macro.com.
-
-Billing shows the current billing period end and any scheduled downgrade date.
-Max stays active until renewal; **Keep Max plan** cancels a pending downgrade
-without resetting usage. Failed renewal-detail reads offer **Try again**.
-Team members who cannot manage billing see the notice without its action.
-
-`Team` (members list; on a paid team each row shows the seat's plan,
-and admins/owners can move a seat between Pro and Max with the `Seat plan`
-menu; Max upgrades are immediate and prorated, Pro downgrades start at renewal.
-**Keep Max** appears only for a confirmed pending downgrade and cancels it;
-failed scheduled-plan reads offer **Try again**, while teams without applicable
-scheduled plans show no retry notice). CRM (enable/disable; once enabled, a `Deal stages` section
-with `Customize stages`, inline rename, reorder by drag handle or arrow keys (up/down
-buttons on touch), delete, `Add stage`, `Reset to defaults`, and `Closed stages`
-checkboxes, editable by the role set as `edit_stages_role`)
-
-`Agents` unifies agent definitions and runtime configuration in one page, also used by the Agents workspace. Its `Agents` section lists team and private agents. `New agent` / `Edit <name>` open full-page forms grouped
-Profile, Behavior, Runtime, Connections, Channels, Share. Connections is a radio pair:
-`Use my connected apps` (default; the agent gets whatever the person running it has
-connected) or `Specific apps`, which reveals a `Search connectors` box over the whole
-Pipedream catalog (results are `option` rows; picking one adds it) and a row per picked app
-with a connected / not-connected dot for the *current viewer* plus an inline `Connect`
-that opens the Pipedream Connect flow inside the page. Unconnected picks never block
-saving; each teammate connects their own account. An agent session that calls a picked
-but unconnected app gets a tool result saying so, and the agent's reply renders a
-`Connect <app>` chip that opens Agents → Connections for that app. The same page
-is also available as Settings → Agent connections.
-
-To change an agent's picture, open `Edit <name>`, choose an image with `Upload`,
-wait for `Uploading…` to finish, then click `Save changes`. Images up to 16 MB
-are uploaded to image storage; Save stays disabled during the upload. A failed
-upload shows an error and keeps the previous picture so you can retry. Verify
-the picture after reopening settings and after a page reload, then type `@` and
-the agent's name in a channel to check its mention-menu picture. Team agents
-available in all channels should refresh there without reloading the channel.
-
-With `pipedream-mcp` enabled, Connections (in Agents or Settings) has `Connected` and `Discover`
-tabs. Connected groups GitHub, Linear, Notion, and Slack tool grants by provider,
-lists other catalog connections alongside them, and puts custom MCP servers in
-a separate section. Discover offers featured providers, a searchable catalog,
-and `Add custom MCP`. Pipedream Slack OAuth is available in production and
-development from the featured Slack provider. Connecting Slack here grants tool
-access; channel import is a separate action where the user chooses channels.
-Provider Back returns to the tab that opened it; navigation is local to each
-Connections page and starts at Connected on a fresh visit.
-
-Macro agents and external AI clients using Macro's MCP server can run
-`ImportNotionPage` and the shared import ledger tools against the user's
-connections saved in Macro.
-Verify a Notion import returns a document and a repeated import returns the
-existing document; Linear imports recorded with `CreateImportEntity` should
-appear in `ListImportEntities`. These calls must not report that import tracking
-is unavailable.
-On hosts without Pipedream credentials, saved Pipedream accounts must not hide
-native Notion, Linear, or Slack connections when selecting import tools.
-
-Provider and custom-server More menus contain Disable, Reconnect, and Disconnect;
-custom servers also offer Rename. Disabled grants show Enable. Unauthenticated
-custom servers show Connect and Remove. Disconnect/Remove require confirmation.
-Adding a custom MCP saves its name and URL; Connect on its row starts OAuth.
-Enabled custom servers are offered to the owner's agent sessions (Cursor, Claude,
-Codex, macrod, in-memory) alongside connected apps, through the same session
-egress path: the sandbox sees the server under its name and a URL key, never the
-server's address or token. A disabled server is not offered. If a server's
-connection has expired, its tool calls return a message telling the agent to
-have the owner use Reconnect under Custom MCP; there is no `Connect` chip for
-custom servers. Agents configured with a fixed app selection do not receive the
-owner's custom servers.
-An agent reply's `Connect <app>` chip still starts that app's connection flow.
-Cursor stays in Agents → Runtimes with its API key and default model controls; it is not
-featured or offered in the Connections catalog. Personal Gmail and GitHub account
-links remain in Settings → Integrations. The native-only Connections page remains
-available when `pipedream-mcp` is disabled.
-Open Settings with the rail's gear button or `Ctrl+;`; leave it by picking any other rail item.
-
-`Agents` → `New agent` (or edit an existing agent) opens a full-page form. The
-`Instructions` field is a Lexical contenteditable textbox, not a textarea. It
-supports Markdown headings, lists, emphasis, code, links, and the normal `@`
-mention picker; select text to open the formatting menu. Saved instructions
-retain mention identities using the shared editor's Markdown format and reopen
-with their formatting intact. Enter adds a new paragraph; use `Create agent` or
-`Save changes` to submit. The form also includes runtime selectors.
-Under the runtime, `Answering a mention` chooses between `Coding agent` (a
-channel mention is answered with a magic chip that opens into the live session)
-and `Chat agent` (the agent replies in the thread, like `@macro`). It is the
-agent's own setting and always saved: a new form starts from the selected runtime
-- Macro's in-memory runtime as chat, every other runtime as coding - and picking a
-different runtime resets it to that default, but only the saved choice counts.
-The model list is loaded live and independently for Macro Agent, connected Cursor, and every
-registered macrod harness. The selected harness stays selected when the list refreshes.
-A paired macrod connects on startup, so models can load before any agents are bound.
-A harness can show `Loading models…`, an unsupported message, or
-a retryable error without hiding the other harnesses. Editing preserves a saved model that
-is no longer offered and labels it `saved, unavailable`. A macrod with no responding runtime
-can remain loading until the 10-second discovery timeout; use Retry after reconnecting it.
-New macrod sessions use the agent's saved model before sending the first prompt.
-Changing that default applies to new sessions; existing sessions keep their selected model.
-If the runtime rejects the saved model, the prompt fails instead of using a different model.
-
-The `Runtimes` section shows built-in Macro, Cursor, Claude, and Codex configuration, followed by paired macrod runtimes. Claude's card appears only with the `claude-cloud` flag, and Codex's only within the agents and Codex rollouts. The “Bring your own agent” card sits above the Agents / Runtimes navigation and is visible on both sections. It rotates Claude Code, OpenCode, OpenClaw, and Hermes; reduced motion keeps a static name. Its `New runtime` action opens the full-page pairing flow from either section: enter the code, look up the request, review the machine, name, sharing and permission consent, then Approve and Done. Back/Cancel returns to the runtime list. Destructive removal still requires confirmation. `/settings/runtimes` opens this section; legacy `/settings/harness?pair=…` links remain supported.
-Connection chips in agent replies open this page, including before any account is connected. Cursor's default-model picker uses
-the same live model discovery and retains its existing save action.
-
-The Codex row uses the OpenAI logo and the same icon, button, and status styling
-as Cursor. Under **Codex**, choose **Connect with ChatGPT**, copy the displayed device code,
-and use **Continue to ChatGPT** to finish sign-in in the provider tab. The Macro
-page displays pending, expired, failed, and retryable error states; **Cancel
-sign-in** cancels the attempt. After connecting, choose a **Cloud environment**
-and click **Save Codex settings** before using Codex. Options show their
-repositories. New sessions always use the `main` branch; there is no branch
-picker or automatic repository selection. Changed selections display **Unsaved
-changes** until the server confirms them. The save button is disabled until an
-environment is selected, and when it matches the saved environment.
-These choices apply to new sessions. **Disconnect** in the Codex row (accessible
-name **Disconnect ChatGPT**) asks for confirmation before removing the connection.
-Claude, Cursor, and Connections disconnect actions use the same shared confirmation
-dialog (a drawer on mobile); Cancel leaves the connection intact. Claude's row
-keeps its layout while status loads, and sign-in details appear only after Connect.
-The UI never asks for an
-OAuth token.
-
-The Codex section and its auth/config requests were exercised in Chromium with
-mocked backend responses on 2026-09-15. Provider login and a full deployed Macro
-session were not exercised by that UI check.
-
-## Notifications
-
-In the desktop app, **Settings → Notifications → Delivery → Desktop notifications**
-controls system notification delivery for this installation. The Notifications
-page is always present, in the same place on web, desktop, and mobile; Account
-has no notification switch.
-Turning it off takes effect immediately and persists across app restarts; turning
-it on requests permission and resumes delivery when authorized. On macOS the
-switch reads the actual system authorization, and enabling it requests macOS
-permission if it has not been decided. If macOS reports denial, enabling the switch
-shows directions to **System Settings → Notifications → Macro → Allow notifications**
-without requesting permission again; returning to Macro refreshes the switch.
-It does not change inbox items or other devices. Focus and presentation settings
-can still suppress alerts even when authorization is granted.
-Verify off/on and persistence after restarting; on the Notifications page, a failed
-toggle should show an error toast and allow retry.
-
-On Linux desktop builds with native notification activation, clicking a system
-notification (or its **Open** action) restores/presents Macro and opens that
-notification's target using the normal in-app navigation. Dismissing or expiring
-an alert must not navigate. With two alerts, click the older one to check that the
-correct target opens. Also test with Macro hidden/minimized and on another
-workspace: Wayland focus requires the notification daemon to supply an activation
-token. This needs a native AppImage update, not just a frontend update; an older
-binary reports **Update Macro to receive desktop notifications.** Activation is
-supported while the app process is running, not after quitting it. The isolated
-Linux WebKit/D-Bus regression is `bun run native:e2e:notifications`; compositor
-focus behavior still needs a real Wayland/X11 desktop check.
-
-On native Android, enable notifications in Settings while signed in. Android 13+
-also asks for system permission; the system's **Activity** notification channel
-must be enabled. Remote push owns system notification display after registration,
-so the same WebSocket event should not create a second local notification. Tapping
-a notification opens its target; simply receiving one does not navigate. Check
-this with the app foregrounded, backgrounded, and after ordinary process death.
-Logout clears delivered notifications and disables receipt for the old account.
-After a transient native listener failure, verify that notification taps recover
-without restarting the app. Android alerts without display text show
-`New notification`; silent read/done clears must remain silent.
-Also verify logout and notification opt-out while registration is pending: late
-backend or native completions must leave the receiver disabled. If a new account
-signs in before cleanup finishes, its registration must remain active afterward.
-
-Toast regions are labeled `Notifications (alt+T)`; seven empty live regions always exist in
-the a11y tree (ignore them when parsing snapshots).
-
-Staff Noise emails still create in-app notification rows, but do not send a new-notification
-event over GraphQL or the legacy WebSocket gateway, so they do not trigger browser popups.
-Those rows are available on the next fetch/refetch. Signal delivery and the existing
-staff/customer eligibility rules are unchanged; no browser eligibility request is needed.
-
-Discussion composers on companies, contacts, documents, tasks, and PRs use the
-shared channel/AI composer surface, 26.25px desktop corners, 15px desktop text, and
-a circular neutral Send button. Edit with AI uses the same composer treatment.
-Inline comments, replies, and their edits use a plain
-input without a surface background, rounded frame, or shadow. Attachment and
-formatting actions stay available.
-On mobile, open documents and tasks put their new-comment composer in the
-accessory dock above navigation, using the channel input's compact pill and
-expanded surface. Ask AI and New are hidden in these open views only when the
-comment composer is available; their list screens keep those controls. Users
-without comment permission have no comment composer, so Ask AI remains visible.
-
-On touch devices, an email thread's floating action bar has Previous email and
-Next email arrows beside the larger Mark done checkmark. The arrows follow the
-source list's filtered order, skip non-email items, and disable at its ends.
-`J` / `ArrowRight` and `K` / `ArrowLeft` use that same order in the Email view.
-Arrow keys in a reply editor or other text input keep their normal editing behavior. They do not wrap; a thread
-opened without a source list has disabled arrows.
-Mark done archives the current thread and opens the next email in that same
-filtered list, loading pages until another email is found or the list ends.
-On native mobile, stepping replaces the current email while preserving the
-filtered list behind it for swipe-back. In the newer Email view it retargets the
-view-owned detail stack instead of opening another block. To verify, open the
-first email from Signal or Noise, tap Next and then Previous, and return to the
-same filtered list.
-Leaving the email cancels pending
-navigation and archiving while a page loads. At the end it opens the previous
-email; with no neighboring email it stays on the archived thread. Mark as not done
-does not advance. Undo restores the archived email and returns to it.
-
-The mobile reply/forward drawer uses matching circular glass buttons for
-discard, attachments, and send, with the dock's button/icon sizing and regular
-Phosphor icons. Send remains disabled until the draft is valid and shows a
-spinner while sending.
-
-The mobile new-email composer nests the channel-style Send button inside its
-top-right glass toolbar, with an even 5px inset on the top, bottom, and right.
-The toolbar is 46px tall; attachment and schedule controls align with Send.
-
-Channel, email, Markdown, and composer body text use `text-base`: 15px at the
-default root size. Supporting `text-sm` text is 14px and `text-xs` is 12px.
-Desktop and mobile share this scale, with accessibility text scaling preserved.
-
-Desktop channel and AI composers use an `Attach files` paperclip that opens the file picker directly, without a plus menu. Comment composers open the image picker directly. Channels and DMs always open in message mode; create tasks through the task creation dialog. Shift+Enter, including an empty new line, expands channel and AI inputs so text starts above the toolbar at the left inset. Sent AI message bubbles use the ink fill with a contrasting foreground in each theme.
-
-### Calendar invitations in email
-
-In `/app/component/mail`, open an invitation message; the same card appears in
-`/app/email/:threadId`. Saved details appear below the sender without waiting for calendar
-sync. Expand guests and descriptions with their explicit controls. `View original email`
-is an accessible disclosure that starts closed; attachments remain below it.
-Related recurring components are grouped behind their own disclosure. Only mail synced
-after the feature shipped gets a card; older invitations render as plain email.
-A newly arrived scheduling update shows RSVP and Join only once its calendar state has
-been checked. A series invitation shows its current or next live occurrence.
-
-Descriptions render sanitized rich text, including emphasis, links, and lists.
-Plain-text line breaks and literal angle brackets (such as `<[email protected]>`)
-remain readable. Use `Show more` / `Show less` to expand or collapse the description;
-description links use the host's normal link-opening behavior.
-
-A connected, resolved invitation shows the responding address and Yes / Maybe / No.
-Calendars connected through a linked inbox also resolve here, using that inbox's
-address for responses. Access is limited to the delegated inbox; another inbox owned
-by the same account stays private, and removing the link removes invitation access.
-Local verification requires both email and calendar services: email supplies saved
-snapshots and resolves them against the synced calendar, while calendar service handles
-the RSVP write. With calendar service's `CALENDAR_SYNC_ENABLED` off, its RSVP route is
-not mounted, so a response fails with an error. Seeded local accounts have no Google
-token, so an RSVP there fails at the provider write and rolls back.
-The selected response remains pressed while a save is pending. Recurring invitations ask
-for `This event` or `All events`. Failures keep the card in place and report a retryable
-error; offline responses are not sent. Cancellation and response/proposal notifications
-do not offer RSVP or Join. Disconnected, ambiguous, and syncing states explain why an
-action is unavailable.
-
-`Open in calendar` focuses the current occurrence, even if its date changed.
-`View your day` opens a compact agenda without changing the active split; Close returns
-focus to its trigger. Busy overlapping events are labeled, while cancelled, declined,
-and free events do not count as conflicts. Calendar 12/24-hour preferences apply to
-already-open invitation cards as well as the calendar view.
-
-### Agent reasoning effort
-
-Open the model selector and hover a model to choose its reasoning effort in the
-submenu. Keyboard users open it with Right Arrow; touch users tap the model.
-Cursor and Macro's in-memory agent load the hovered model's own advertised
-choices. The selected label includes the effort, such as `Sonnet 5 · High`;
-there is no separate effort control in the input box. Models without effort
-support remain selectable through `Use <model>` (or a desktop click/Enter).
-Default keeps the model's existing behavior.
-
-In an open session, choosing a different model's effort confirms the model first,
-then validates and applies effort. Wait for the selector to become available
-again. If the model succeeds but effort is rejected, the new model remains
-selected with its confirmed effort; the error is shown and no unsupported
-setting is presented as accepted.
-
-New conversations confirm selected model and effort settings before sending the
-first message. If startup reports a rejected setting or timeout, the first prompt
-has not been sent. See [effort capabilities](../AGENT_EFFORT.md) for the harness
-contracts and test coverage.
-
-### Floating block information panels
-
-Actions live in the top bar immediately before Share, with consistent compact
-buttons (labels collapse on narrow headers). There are no Actions sections in
-information panels. Markdown/tasks include Ask Macro and document/task dispatch; email
-includes Ask Macro and Create task; PDF and calls include Ask Macro. Native
-projects put Delete in the `Project actions` menu after the project title.
-
-Standard metadata is quiet, non-collapsible text at the bottom of each panel,
-separated by a muted divider. Owner and available timestamps share one format;
-Markdown adds word/character counts. There is no standard Details or Stats
-disclosure. Agent runtime information remains in its dedicated Session section.
-
-Block information panels float over the right side of the block without changing
-the content width or its centered position. A single rounded bubble fits its
-contents, with `edge-muted` dividers between sections. Its height is capped at
-the block height with internal scrolling. At every width it starts closed and
-acts as a split-local overlay menu on desktop. The top-right sidebar icon, rotated
-180 degrees, opens it, and clicking outside dismisses it. On touch devices the
-control uses the Phosphor info-circle icon and opens the standard bottom drawer
-with a drag handle, scrollable sections, and safe-area/keyboard-aware spacing.
-Dismiss the drawer by swiping down or tapping its backdrop. Opening is never
-restored from saved preferences or triggered by the global chrome shortcut. The 320px bubble enters
-with a slight slide from the right and a 120ms fade;
-closing fades it out in 70ms.
-This applies across Markdown/tasks,
-snippets, email, calls, agents, pull requests, projects, and all file blocks
-including PDFs, images, code, video, canvas, unknown file types, and CRM company
-and contact views (both inside the CRM workspace and in standalone blocks).
-
-### Email reminders
-
-Email's **Reminders** tab contains original conversations with active snoozes,
-ordered by return time. Each row's clock opens the shared reminder command menu;
-see [collection verification](reminders.md#email--reminders).
-
-Use **H** on one selected email or its open conversation, **Remind me** in the
-menu, or the header bell. These share the [email reminder menu](reminders.md#snooze-or-change-a-conversation).
-A confirmed save archives the thread and advances within the invoking list.
-Cancel and failed saves keep the current email. H on a pending snooze edits it;
-**Remove reminder** returns it to the inbox. Bare H in a reply or search field
-remains ordinary typing.
diff --git a/docs/README.md b/docs/README.md
new file mode 100644
index 0000000000..f5037ef77b
--- /dev/null
+++ b/docs/README.md
@@ -0,0 +1,12 @@
+# Docs
+
+| Directory | Contents |
+| --- | --- |
+| [`development/`](development/) | How to build, run, test, and style code in this repository. |
+| [`guides/`](guides/) | End-to-end walkthroughs: adding a service, entity, block, and more. |
+| [`architecture/`](architecture/) | How shipped systems work today. |
+| [`design/`](design/) | Proposals, plans, and audits; check each doc's status. |
+| [`runbooks/`](runbooks/) | Rollouts, migrations, imports, and demos with operational steps. |
+| [`agent-guide/`](agent-guide/) | How browser agents operate the app, not how to develop it. |
+
+Docs that belong to one app, service, or crate live next to its code.
diff --git a/docs/STYLE_GUIDE.md b/docs/STYLE_GUIDE.md
deleted file mode 100644
index 527615a509..0000000000
--- a/docs/STYLE_GUIDE.md
+++ /dev/null
@@ -1,318 +0,0 @@
-# Code Review Style Guide
-
-**Check locally.** `just check` is the single gate: format + lint + code rules, scoped
-to your changes vs `origin/main`, every finding printed as `file:line [rule-id]` with
-the command that fixes it. `just check full` adds tsc + clippy.
-
-**Format.** One rule per line: `<id> [scope] rule (evidence · enforcement · docs)`.
-The id prefix is the domain:
-
-- `CS-##` — Rust backend (`crates/`, `services/`, `tooling/`)
-- `FE-##` — frontend and shared TypeScript (`apps/web`, `packages/`)
-
-IDs are stable — cite them in review comments ("see CS-30", "FE-12"), never renumber or
-reuse them; deletions leave gaps and new rules append with the next free number. Scope
-tags make the list greppable.
-
-CS scopes: `[db]` database & migrations · `[types]` type design · `[cfg]` config, env,
-secrets · `[err]` errors & observability · `[arch]` architecture & boundaries · `[api]`
-API & handler design · `[sec]` security & permissions · `[rust]` Rust idioms · `[perf]`
-performance · `[test]` testing
-
-FE scopes: `[data]` data fetching & queries · `[solid]` Solid reactivity & state ·
-`[async]` async & error handling · `[arch]` architecture & module hygiene · `[ts]`
-TypeScript · `[ui]` UI / UX conventions
-
----
-
-## Rust backend (`crates/`, `services/`, `tooling/`)
-
-- **CS-01** `[db]` Generate ids as UUIDv7 in application code — never `gen_random_uuid()`
- (UUIDv4); v7 ids sort by creation time. (#4296)
-- **CS-02** `[db]` Make seed/backfill inserts and anything that can race idempotent with
- an `ON CONFLICT` handler. (#4296, #4498)
-- **CS-03** `[db]` Prefer natural/composite keys over surrogate ids when the table is
- queried/sorted by those columns anyway, and key REST routes on the natural id.
- (#4296, #4498)
-- **CS-04** `[db]` Name user columns `user_id` — not `owner_user_id` or other variants;
- follow existing tables. (#4498)
-- **CS-05** `[db]` New tables need a deliberate cascade/cleanup story, not whatever the
- default happens to be. (#4296)
-- **CS-06** `[db]` Don't add redundant indexes — a column already covered as the leading
- part of the primary key does not need its own index. (#3961)
-- **CS-07** `[db]` Don't store columns that are implicit in context (e.g. a scoping id
- already fixed per durable object / per tenant). (#3961)
-- **CS-08** `[db]` Use `sqlx::query!` / `query_as!` (compile-time checked) by default;
- the non-macro form is only for queries that genuinely cannot be statically known.
- (#4156 · enforced: clippy `disallowed-methods` · workflow: [database development](DATABASE_DEVELOPMENT.md))
-- **CS-09** `[db]` The `.sqlx` cache lives at the workspace root — run
- `nix develop --command just prepare_db` from the repository root; never commit a
- `.sqlx` directory inside an individual crate. (#4577 · workflow: [database development](DATABASE_DEVELOPMENT.md))
-- **CS-10** `[types]` Newtype your identifiers and tokens — wrap raw `String`
- ids/tokens/model-ids in a validated newtype that checks shape at construction.
- (#4020, #4077, #4276)
-- **CS-11** `[types]` A closed set of string values is an enum, not a `String` — impl
- `Display`/`FromStr` as needed. (#4296, #4410)
-- **CS-12** `[types]` Optional means `Option<T>` — don't rely on sentinel values or
- convention to express absence. (#4296)
-- **CS-13** `[types]` Model tri-state data (not-loaded / missing / present) as one flat
- enum, not nested `Option`s or ad-hoc flags. (#4527)
-- **CS-14** `[cfg]` All env access goes through `macro_env_var` / `macro_config` — never
- `std::env::var`, never hand-rolled wrappers; use `MaybeEnvVar` for optional vars. The
- same goes for AWS config instantiation (`macro_aws_config`) and tracing subscriber
- setup (`macro_entrypoint`): use the shared crates.
- (#4306, #4334, #4380 · enforced: clippy `disallowed-methods`)
-- **CS-15** `[cfg]` Fail fast: validate config at service instantiation, not deep inside
- request handling — a missing env var should kill startup, not a request. (#4077, #4156)
-- **CS-16** `[cfg]` Don't add `.context()` to env-var macro errors — the macro error
- already statically names the missing variable. (#4156)
-- **CS-17** `[cfg]` Doppler secret key names must exactly match the env var name
- referenced in code. (#4525)
-- **CS-18** `[cfg]` Register new environment variables in Doppler. They are plain
- env vars, not `LocalOrRemote`/doppler-wrapped; non-secret config goes in Doppler as
- raw values, not AWS Secrets Manager secrets. (#4305, #4525)
-- **CS-19** `[err]` Give third-party errors their own variant — don't collapse e.g. a
- `jsonwebtoken` failure into a generic internal error. (#4020)
-- **CS-20** `[err]` Depending on a rate-limited external provider requires a fallback
- (fallback model, retry story, or documented degradation). (#4296)
-- **CS-21** `[err]` Wire usage metering on every invocation path — MCP-triggered tool
- calls count too, not just the primary path. (#4296)
-- **CS-22** `[err]` When adding `#[tracing::instrument]`, include `err` on `Result`
- functions and omit it on other return types. Never set `level = "info"` on the
- attribute. Log errors as structured fields (`tracing::error!(error=?e, "msg")`);
- prefer `.inspect_err` over `if let Err(e)` for logging.
-- **CS-23** `[arch]` Do not grow `macro_db_client` — new domain logic gets a new crate;
- the catch-all crates must shrink, not accumulate. (#4380)
-- **CS-24** `[arch]` Keep source files under ~1000 lines — split before a reviewer has
- to ask. (#4364)
-- **CS-25** `[arch]` `mod.rs` declares submodules; it doesn't host logic — prefer the
- `foo.rs` + `foo/` file-and-directory style for modules with logic. (#4175 · enforced:
- ast-grep `rust-mod-rs-declarations-only`, error)
-- **CS-26** `[arch]` Reuse before reimplementing — if the logic plausibly exists
- (service clients, permission checks, oauth utils, the `agent` crate), find it and
- reuse/extract it instead of writing a second copy. (#3692, #4020, #4380, #4485)
-- **CS-27** `[arch]` Shared domain tables are only touched by their owning crate — e.g.
- `entity_access` mutations go through `entity_access`/`entity_access_db_utils`, never
- raw SQL elsewhere. (#3769)
-- **CS-28** `[arch]` Don't extract single-use code into shared crates prematurely, and
- watch dependency direction: general-purpose crates must not import from specific ones.
- (#4410)
-- **CS-29** `[arch]` Group proliferating root files (e.g. Dockerfiles) into a dedicated
- folder. (#4380)
-- **CS-30** `[api]` Axum handlers take shared services via `State`, not `Extension`.
- (#4556 · enforced: ast-grep `rust-no-axum-extension-param`, warning)
-- **CS-31** `[api]` Attach cross-cutting services to the owning domain service, not ad
- hoc at the router/handler layer — e.g. `EntityAccessManagementService` hangs off the
- email/document service itself, the way the documents crate does. (#4572)
-- **CS-32** `[api]` New API/soup models mirror the shape of their existing counterpart:
- omit fields derivable from a nested field, keep lazily-loaded collections lazy,
- include only fields relevant to the new context. (#4165)
-- **CS-33** `[api]` Trait methods every implementor must consciously declare get no
- default impl (e.g. schema version) — defaults are for genuine defaults, not escape
- hatches. (#4276)
-- **CS-34** `[api]` Design generic abstractions to map `T -> U`, not just `T -> T`, when
- mapping is the point of the abstraction. (#4396)
-- **CS-35** `[api]` Keep sibling endpoints on a resource using the same DTO shape;
- migrate them together rather than changing one in isolation. (#4386)
-- **CS-36** `[sec]` Permission grants are stateless HTTP endpoints, not channel
- messages — in-memory channel flows don't survive reconnects. (#4201, #4296)
-- **CS-37** `[sec]` Mint narrowly-scoped tokens instead of forwarding the user's full
- JWT downstream — least privilege by construction. (#4296)
-- **CS-38** `[sec]` Tool responses must be valid members of the message chain — include
- `tool_call_id` and required chain metadata. (#4296)
-- **CS-39** `[sec]` Pin third-party GitHub Actions to a commit SHA, not a movable tag.
- (#4276)
-- **CS-40** `[rust]` Repeated literals become named consts. (#4020)
-- **CS-41** `[rust]` Don't use `#[allow(...)]` — use `#[expect(..., reason = "...")]`
- on the narrowest item it applies to; `allow` silently rots when the lint stops firing,
- `expect` warns. (#4396, #4647)
-- **CS-42** `[rust]` Don't re-state trait bounds already implied by a supertrait. (#4276)
-- **CS-43** `[rust]` Use the smallest sufficient integer type — a version counter that
- can't plausibly pass 255 is a `u8`. (#4396)
-- **CS-44** `[rust]` Large inline strings belong in files — use `include_str!`. (#4156)
-- **CS-45** `[rust]` CLI binaries use `clap`, not hand-rolled arg parsing. (#3678)
-- **CS-46** `[rust]` Use `rootcause` for error handling in new code — it's preferred
- over `anyhow` these days. In code that's still on anyhow, prefer `bail!` for early
- error returns.
-- **CS-47** `[perf]` Keep latency-critical services thin: push bytes directly instead of
- round-tripping through presigned URLs or extra services; dispatch non-blocking
- background work with `wait_until`. (#3781)
-- **CS-48** `[perf]` Don't do per-message work on hot websocket paths — accumulate and
- flush on a timer/alarm. (#3961)
-- **CS-49** `[test]` Tests live in a sibling `test.rs`, not inline `#[cfg(test)]` blocks
- in the implementation file. (#4647 · example: [Rust development](RUST_DEVELOPMENT.md#test-the-affected-packages))
-- **CS-50** `[test]` Update affected tests for db-crate changes. Refresh SQLx metadata
- when queries/schema change or required cache data is missing, not for unrelated
- Rust-only edits. Run affected tests with `SQLX_OFFLINE` unset.
- (workflow: [database development](DATABASE_DEVELOPMENT.md))
-- **CS-51** `[arch]` Domain modules reference no infrastructure or transport: no AWS
- SDKs, redis, reqwest, opensearch, kafka, axum, or http types under `src/domain/**` —
- wrap clients in outbound adapters behind ports; response mapping lives in inbound.
- (enforced: ast-grep `rust-no-infra-in-domain` warning,
- `rust-no-transport-in-domain` error · also: cloud-storage-hexagonal-architecture
- skill)
-- **CS-52** `[arch]` Dependencies point inward: `src/domain/**` never imports
- `crate::inbound`/`crate::outbound`, and `src/outbound/**` never imports
- `crate::inbound` — define a port in domain and implement it in the adapter.
- (enforced: ast-grep `rust-domain-no-adapter-imports` warning,
- `rust-outbound-no-inbound-imports` error)
-- **CS-53** `[arch]` Inbound adapters run no database queries — handlers, tools, and
- listeners call a domain service backed by an outbound repository, never sqlx
- directly. (enforced: ast-grep `rust-no-sqlx-in-inbound`, warning)
-- **CS-54** `[rust]` New crates put `#![deny(missing_docs)]` in `lib.rs` and document
- all public items. Do not mark documentation code blocks `ignore` to skip doctests
- unless explicitly directed.
-- **CS-55** `[err]` AI spans follow the OpenTelemetry GenAI conventions (`gen_ai.*`,
- see `crates/genai_telemetry`). Agent sessions of every harness are traced in one
- place: the session actor projects each session's ACP frames onto `invoke_agent` /
- `execute_tool` spans (`crates/agent_session/src/domain/session/telemetry.rs`), so
- do not add GenAI spans to a harness runtime — `agent_inmem` runs its agent loop with
- `with_genai_telemetry(false)` for that reason. Outside sessions (chat in
- `document_cognition_service`), the agent loop and `ai_toolset::ToolSet::try_tool_call`
- emit and enrich the `invoke_agent` / `chat` / `execute_tool` spans; do not open tool
- spans in tools or toolsets, and never record prompts, tool arguments or tool results
- as span fields or logs — they are content, recorded on the spans under the
- `OTEL_INSTRUMENTATION_GENAI_CAPTURE_MESSAGE_CONTENT` policy and a size budget.
-
-## Frontend and shared TypeScript (`apps/web`, `packages/`)
-
-- **FE-01** `[data]` Never call a service client outside the `queries` package — UI code
- calling an endpoint directly is usually re-fetching data an existing query already
- caches. (#3750, #3961 · enforced: ast-grep `ts-no-service-client-outside-queries` +
- `tsx-no-service-client-outside-queries`, warning · also: AGENTS.md)
-- **FE-02** `[data]` Every query module has a `keys.ts` structured like the existing
- ones. (#3710)
-- **FE-03** `[data]` Conditional fetching uses a debounced signal passed to TanStack
- Query's `enabled`, not a custom resource. (#3961)
-- **FE-04** `[data]` Pre-populating data means exposing a cache-seeding method on the
- query, not an ad hoc manual cache. (#4020)
-- **FE-05** `[data]` Data-dependent UI that must not suspend uses `queryReadyGate`.
- (#4077)
-- **FE-06** `[data]` Extend `QUERY_FILTERS_BASE` instead of re-deriving filter
- exclusions per query, and prefer explicit include lists — exclude lists silently break
- when a new entity type is added. (#3947, #4260)
-- **FE-07** `[data]` Don't hardcode backend-owned config in the frontend (e.g. system
- bot config) — fetch it dynamically or generate types from the backend source of
- truth. (#3692)
-- **FE-08** `[solid]` No ad-hoc global state modules — shared state for a subtree lives
- in a Context scoped to a clear ownership boundary. (#3750 · also: AGENTS.md)
-- **FE-09** `[solid]` Derive, don't sync — an effect that only copies one signal into
- another similarly-shaped signal should be a derived signal at the appropriate level.
- (#3898)
-- **FE-10** `[solid]` `createEffect` is for external/imperative systems only (DOM APIs,
- third-party libs, navigation events) — never for deriving state; use `on()` to make
- dependencies explicit when an effect is warranted. Prefer wrapping the setter over
- `createEffect(() => { if (signal()) sideEffect() })` when setting a value should also
- clear related UI, blur a control, or scroll. (#3750, #3898, #6038 · also: AGENTS.md)
-- **FE-11** `[solid]` Check `solid-primitives` before writing a custom reactive utility.
- (also: AGENTS.md)
-- **FE-12** `[async]` `async`/`await` with `try`/`catch`, not `.then()`/`.catch()`
- chains. (#3716, #3781 · enforced: oxlint `promise/prefer-await-to-then` —
- `bun run lint:oxlint` from the repository root)
-- **FE-13** `[async]` Extract multi-step async coordination into named helper functions,
- and make intentionally-unawaited promises explicit — no bare floating promises.
- (#3781)
-- **FE-14** `[async]` Keep neverthrow `Result`/`ResultAsync` intact end-to-end — use the
- existing helpers (`ResultAsync`, `throwOnError` in `queryOptions`, `catchToResult`)
- instead of ad hoc `Promise <-> Result` conversions. (#3781, #4373)
-- **FE-15** `[async]` Guard once, at the top — missing/invalid state gets an early
- return at the start of the function or hook, not a repeated check in every branch or
- a silent fall-through. (#3750, #4057)
-- **FE-16** `[arch]` Keep modules single-purpose: feature-specific logic out of generic
- util files, generic/collaboration logic decoupled from feature specifics, styling out
- of core business logic. (#3750, #3781, #3947)
-- **FE-17** `[arch]` Reuse existing shared utilities and primitives before hand-rolling
- (`removeNodeAndRestoreSelection`, Kobalte components) — re-implementations
- reintroduce bugs that were already fixed. (#4281, #4321 · also: AGENTS.md)
-- **FE-18** `[arch]` Within a package, use relative imports — don't route through the
- package's own barrel file; it adds indirection and invites circular dependencies.
- (#3692)
-- **FE-19** `[ts]` Trust `match` narrowing — an exhaustive `ts-pattern` match already
- narrows the type inside each closure; a manual `Extract<>` alias is redundant. (#4201)
-- **FE-20** `[ts]` Exhaustive branching uses `match` from `ts-pattern`. (also: AGENTS.md)
-- **FE-21** `[ts]` No `any` — proper types or `unknown` + type guards. (also: AGENTS.md)
-- **FE-22** `[ui]` Pending or permission-gated actions render as a dimmed version of the
- real UI with inline accept/reject controls — not a generic placeholder icon. (#4201)
-- **FE-23** `[ui]` Disclosure carets rotate 180° to point down when expanded, matching
- Discussion, SplitFileMenu, CollapsibleMessage, etc. (#4582)
-- **FE-24** `[ui]` Truncated/collapsed controls get a tooltip (matching the app's
- tooltip pattern) so the lost label stays discoverable. (#4492)
-- **FE-25** `[ui]` Semantic color tokens, not raw Tailwind palette classes — the default
- palette is disabled via `--color-*: initial` in `apps/web/src/index.css`, so
- classes like `text-red-500` silently render nothing. (enforced: ast-grep
- `tsx-no-raw-tailwind-palette`, CI error · also: AGENTS.md)
-- **FE-26** `[ui]` Prefer composition over configurability; keep reusable components
- small and free of queries/complex state. (also: AGENTS.md)
-- **FE-27** `[ui]` Don't add `cursor-pointer` to clickable elements. (enforced: ast-grep
- `tsx-no-cursor-pointer`, warning · also: AGENTS.md)
-- **FE-28** `[ui]` Dialogs rely on Kobalte's default autofocus: make the intended
- target the first tabbable element and preserve focus ownership for restoration.
- Override `onOpenAutoFocus` only for a proven lifecycle requirement, and verify
- `document.activeElement` after both opening and reopening in the live app.
-- **FE-29** `[data]` Every new query call site (`useQuery`/`useInfiniteQuery` or a hook
- from `src/lib/queries/**`) needs a deliberate `Suspense` boundary: reading
- `query.data` suspends to the *nearest ancestor* boundary. When reviewing, walk up
- the component tree from the call site and determine which boundary would catch it.
- If none exists below the app root, or the nearest one is far outside the component's
- own UI scope (e.g. the route-level boundary in `apps/web/src/routes/Root.tsx`, whose
- fallback blanks unrelated UI), flag it and ask which boundary is intended.
-- **FE-30** `[ui]` Never hoist Tailwind class strings into named constants
- (`const DAY_CELL_CLASS = '...'`) — shared markup+styling is a component; a class
- string can't carry structure, props, or behavior. Extract a component, or inline the
- literal at its single use; styling variants are component props, not exported
- strings. (enforced: ast-grep `tsx-no-class-string-consts`, warning)
-- **FE-31** `[ts]` Never cast a string to `ItemType` — parse it with `stringToItemType`
- from `@service-storage/client`, the one owner of entity-type spellings (email
- threads alone are stored as `email`, `thread`, and `email_thread`). (#6043 ·
- enforced: ast-grep `ts-no-item-type-cast` + `tsx-no-item-type-cast`, CI error)
-- **FE-32** `[ui]` Prefer styling in the component (Tailwind on the markup). Reserve
- `@utility` in `apps/web/src/index.css` for styles widely shared across many
- components — not one-off or two-callsite layouts. (#6038 · also: apps/web/AGENTS.md)
-- **FE-33** `[arch]` New features and feature restructures use the
- [layered feature architecture](FRONTEND_FEATURE_ARCHITECTURE.md), with
- `features/activity` as the reference. Use `core/` for pure feature types and
- functions, `queries/` for wire adapters and query factories, `primitives/` for
- reactive state/actions without JSX, `components/` for presentation from props,
- and `views/` for use-case composition. `context/` holds feature-owned capability
- contracts and the provider/consumer, without production imports or fallback.
- An app-facing entry point constructs real adapters and supplies the provider;
- missing provider setup fails clearly. Meaningful reactive decisions depend on
- narrow feature sources, not concrete query adapters or raw clients. Adapters
- implement those contracts using existing query/cache infrastructure; Solid
- accessors and ownership remain part of the reactive foundation. Per-host behavior
- belongs in callback props, and flags gate mounting outside the capability contract.
- Primitives and adapters depend on feature-owned contracts; views depend on
- primitives and components, and core stays independent. Components may import
- context display types only. Keep data availability in source adapters and
- presentation decisions in primitives; avoid interfaces with no independent
- behavior to protect.
- Controllers receive only their named capabilities; production environments and
- presentation wiring stay in views. Reuse query/mutation infrastructure rather
- than adding a generic async wrapper. Keep request failures distinct from errors
- after a successful write, and require promises when callers depend on completion.
- Use view-state unions when the use case has distinct states; small helpers can
- return accessors.
- Test feature behavior through injected capabilities, with shared helpers in
- `tests/`. Use fake sources for primitive unit tests and fake clients for adapter
- tests, retaining integration coverage of both. Activity still has combined
- context/production wiring, raw-client injection, and UI/import-side-effect
- stubs; these are documented migration gaps.
- The detailed document covers layer responsibilities, narrow reference exceptions,
- adoption, and review.
- Register adopting feature paths in both language variants of every feature
- rule. (enforced: ast-grep `ts-/tsx-feature-core-pure`,
- `ts-/tsx-feature-components-presentational`, `ts-/tsx-feature-data-no-ui`,
- `ts-/tsx-feature-layers-use-context`, warning; currently scoped to activity.
- Separate production composition and source-contract inversion still require
- explicit review; the existing rules do not enforce them.)
-- **FE-34** `[arch]` Treat the legacy block state system as adapter-boundary code,
- not state management for new or refactored surfaces. Do not add new
- `useBlock*`, `createBlock*`, block-scoped signal/store/memo/resource, or block
- permission dependencies. An existing block adapter may read legacy state once
- and translate it into a feature-owned context or explicit props; descendants
- and reusable components receive identity, permissions, state, and lifecycle
- owners through those contracts and must remain mountable without `<Block>`.
- Never add a `<Block>` wrapper merely to satisfy a missing dependency. If shared
- code needs an owner or other host capability, expose it through the owning
- surface context instead of borrowing `BlockContext`. (also:
- apps/web/AGENTS.md)
diff --git a/docs/AGENT_GUIDE/README.md b/docs/agent-guide/README.md
similarity index 71%
rename from docs/AGENT_GUIDE/README.md
rename to docs/agent-guide/README.md
index 8ad237cabf..e59c543758 100644
--- a/docs/AGENT_GUIDE/README.md
+++ b/docs/agent-guide/README.md
@@ -12,12 +12,26 @@ verified live against a local stack (`just run_local`).
| [databases.md](databases.md) | Properties, records, kanban boards, saved views, AI questions, live answers |
| [forms.md](forms.md) | Forms: create doors, builder (drag and drop, gates), respond route, Responses grid, sharing, polls |
| [ai-chat.md](ai-chat.md) | Standalone and doc-scoped AI chat |
-| [../CLAUDE_CLOUD_DEMO.md](../CLAUDE_CLOUD_DEMO.md) | Claude in Harness settings, encrypted saved connection, Open in Claude, and cloud-side transcript polling |
+| [claude-cloud-demo.md](../runbooks/claude-cloud-demo.md) | Claude in Harness settings, encrypted saved connection, Open in Claude, and cloud-side transcript polling |
| [channels.md](channels.md) | Channels: create, invite, message, participants, bots |
| [tasks.md](tasks.md) | Task list and creation dialog |
| [view-tours.md](view-tours.md) | Desktop feature flyovers, dismissal, targeting, and embedded videos |
| [reminders.md](reminders.md) | Email snoozing, the reminder command menu, delivery, and safe failure verification |
-| [surfaces.md](surfaces.md) | Every other surface: inbox, email, search, files, calendar, calls, customers, activity, settings |
+| [home.md](home.md) | Home and the mobile Notifications inbox |
+| [email.md](email.md) | Mail: threads, read state, trash, cached filtering, reminders |
+| [calendar.md](calendar.md) | Calendar views, events, and invitations in email |
+| [search.md](search.md) | Search |
+| [files.md](files.md) | Files (Drive) |
+| [calls.md](calls.md) | Calls, call links, guests, and sharing |
+| [crm.md](crm.md) | Customers (CRM) |
+| [pull-requests.md](pull-requests.md) | Pull request review |
+| [activity.md](activity.md) | Activity |
+| [notifications.md](notifications.md) | Notifications |
+| [settings.md](settings.md) | Settings sections, including Slack import and team membership |
+| [onboarding.md](onboarding.md) | Onboarding bypass and setup plan |
+| [canvas.md](canvas.md) | Canvas colors and link paste |
+| [soup-live-updates.md](soup-live-updates.md) | Live updates in flat Soup lists |
+| [ui-conventions.md](ui-conventions.md) | Shared UI behavior: list loading, top bars, dialog actions, user cards, information panels |
| [browser-technique.md](browser-technique.md) | Generic chrome-devtools MCP lessons learned on this app |
| [observability.md](observability.md) | Correlating a UI action to backend traces/logs with the Grafana MCP |
diff --git a/docs/agent-guide/activity.md b/docs/agent-guide/activity.md
new file mode 100644
index 0000000000..f74cc97068
--- /dev/null
+++ b/docs/agent-guide/activity.md
@@ -0,0 +1,62 @@
+# Activity
+
+## Activity — `/app/component/activity`
+
+To verify document content activity, keep Activity open in one tab and edit an
+existing document's body in another, without renaming it. The editor's Edited
+entry should arrive for the first edit. Keep typing across multiple saves: the
+activity count must stay unchanged. After five minutes without editing, the next
+edit should add one new event. Reconnecting within that window and opening or
+closing a document without edits must not add an event.
+
+Requires authentication and the `enable-activity-feed` flag. Direct navigation and
+restored splits wait for flags to load; when disabled, they redirect to Home
+(`/app/home`) without loading the activity feed.
+
+When checking Activity, enable GraphQL Soup as well as the activity flag. Verify
+that an initial visit resolves entity names in both the feed and Most active,
+then reload and scroll through another page. Preview loading and live name
+updates should keep the page responsive without repeatedly fetching previews.
+
+Activity refreshes live after recorded actions. With two pages loaded, make an
+action in another tab and verify the feed retains its page-boundary rows while
+the action count and heatmap update. An open entity activity panel should also
+refresh for actions by another authorized user. After disconnecting and
+reconnecting the websocket, verify recovery without requiring another action.
+Hidden tabs defer refresh until visible; purges refresh all mounted activity
+queries through the normal access checks.
+
+GitHub-style actions heatmap (one a11y node per day — makes snapshots huge; prefer saving the
+snapshot to a file), then a `Most active` section header (styled like the feed's day headers)
+over a wrapping row of pill chips (entity icon, name, action count; click opens the entity,
+shift-click opens a new split; the section is absent when there are no entities), then a feed
+of "You edited/created X · 17h" entries grouped under day headers, with the compact relative
+time (`17h`, `8d`, `1mo`) inline after a middot rather than right-aligned; hovering the time
+shows the full date. Each row is a plain action glyph joined to its neighbours by a thin
+connector line (the line stops at day headers) and never wraps: a long entity name truncates
+with an ellipsis, and the full name is in the mention's hover preview. Consecutive same-actor,
+same-entity, same-action events within a day read as one line with a count (`You edited Doc X
+5 times · 2h`; property changes read the net change, `changed Status from A to C on Doc X · 3
+changes · 2h`), so the row count is lower than the event count (`[data-activity-run-size]`
+carries the fold size). The whole page is one virtualized list: only rows near the viewport
+are in the DOM, and scrolling near the bottom fetches the next page automatically (a
+`Loading…` tail appears while it lands). If a page fails, the tail reads `Couldn't load more.`
+with a `Retry` button and automatic paging stops until it is pressed. There is no `Show more`
+button.
+Once the heatmap card scrolls away, the day header for the topmost visible row stays pinned at
+the top of the list (`[data-activity-pinned-day]`, a non-interactive copy), so a snapshot taken
+mid-scroll shows that label twice at most. The heatmap always shows the whole year, including
+the partial first and current weeks, and spans the card at every width: in a wide pane the
+space between week columns opens up, its cells shrink from 14px to 8px as the pane narrows, and
+below that (a phone) the week area scrolls sideways with the month letters, opened on the newest
+week and with no visible scrollbar. Under ~672px the four stats read as a two-column grid; under
+~448px (a phone) the legend drops its `Fewer`/`More` words, each stat stacks its label over its
+value, and chips shorten. Rows stay on one line at every width. On touch devices the list rests
+below the floating page title and above the bottom toolbar.
+
+With Databases on, databases are activity entities too: creating, renaming, trashing,
+restoring, or permanently deleting one, and every write to its tables (grid edits and
+agent tools) lands on the acting user's feed as `You created/edited/deleted <database>`;
+the mention opens the database. Databases also appear in the Ctrl+K command menu under
+**All** and **Files**, ordered by creation time. Home's merged feed and the Recent view read Soup, which
+does not list databases.
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/agent-guide/ai-chat.md
similarity index 98%
rename from docs/AGENT_GUIDE/ai-chat.md
rename to docs/agent-guide/ai-chat.md
index aefb0d96ef..e8d0999f8b 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/agent-guide/ai-chat.md
@@ -709,7 +709,7 @@ toast. Legacy chat tool errors carrying a recognized quota code also open it.
### Quota manual checks
Use an isolated local backend with local billing fixtures, not real hosted
-accounts. See [quota rollout and coverage](../AI_QUOTA_ENFORCEMENT.md) for setup
+accounts. See [quota rollout and coverage](../runbooks/ai-quota-enforcement.md) for setup
and the full matrix. Record both browser behavior and the Network/protocol result;
recognized foreground quota refusals open the shared dialog when the frontend
rollout is active (always in dev and local; flag-controlled in production).
@@ -1533,7 +1533,7 @@ setting is presented as accepted.
New conversations confirm selected model and effort settings before sending the
first message. If startup reports a rejected setting or timeout, the first prompt
-has not been sent. See [effort capabilities](../AGENT_EFFORT.md) for the harness
+has not been sent. See [effort capabilities](../architecture/agent-effort.md) for the harness
contracts and test coverage.
Routine model/agent pickers retain model-only selection: they do not offer effort
@@ -1697,3 +1697,24 @@ All AI hosts, including MCP, also provide:
measure scheduled duration; completion does not claim verified attendance.
These tools use the same domain permissions and booking lifecycle as the UI.
+
+## Agent reasoning effort
+
+Open the model selector and hover a model to choose its reasoning effort in the
+submenu. Keyboard users open it with Right Arrow; touch users tap the model.
+Cursor and Macro's in-memory agent load the hovered model's own advertised
+choices. The selected label includes the effort, such as `Sonnet 5 · High`;
+there is no separate effort control in the input box. Models without effort
+support remain selectable through `Use <model>` (or a desktop click/Enter).
+Default keeps the model's existing behavior.
+
+In an open session, choosing a different model's effort confirms the model first,
+then validates and applies effort. Wait for the selector to become available
+again. If the model succeeds but effort is rejected, the new model remains
+selected with its confirmed effort; the error is shown and no unsupported
+setting is presented as accepted.
+
+New conversations confirm selected model and effort settings before sending the
+first message. If startup reports a rejected setting or timeout, the first prompt
+has not been sent. See [effort capabilities](../architecture/agent-effort.md) for the harness
+contracts and test coverage.
diff --git a/docs/AGENT_GUIDE/browser-technique.md b/docs/agent-guide/browser-technique.md
similarity index 100%
rename from docs/AGENT_GUIDE/browser-technique.md
rename to docs/agent-guide/browser-technique.md
diff --git a/docs/agent-guide/calendar.md b/docs/agent-guide/calendar.md
new file mode 100644
index 0000000000..f6c020fd7f
--- /dev/null
+++ b/docs/agent-guide/calendar.md
@@ -0,0 +1,509 @@
+# Calendar
+
+## Calendar — `/app/calendar/<month-or-week-or-day>`
+
+Event composer dropdown triggers and date/time inputs use the theme control
+surface, so they blend with the dialog instead of using the darker page fill.
+Their menus stay inside the composer's portal scope. Verify that calendar,
+recurrence, Guests, conferencing, Location, and Notifications open on the first
+click from the title field and accept changes without closing the composer.
+Open the start/end date picker and its nested time list; selecting a time keeps
+the date picker open. Escape dismisses the active menu before the composer.
+
+The path selects the Month, Week, or Day period, and choosing another period updates
+that path. Calendar navigation defaults to Day on phones and Week on desktop; the most
+recent choice is remembered locally for navigation that does not specify a period. An
+opened event is reflected in the pane-owned `sN.calendar.eventId` search parameter.
+
+Period selection updates its label and route immediately. The active grid redraws
+on a deferred task; hidden neighboring periods follow on separate tasks. Calendar
+grids stay mounted and undimmed while occurrences load. An uncached range never
+shows events from the previous range. After a short delay, representative event
+skeletons appear without adding synthetic FullCalendar events. Week/Day use sparse
+blocks with varied start times and durations, plus separate all-day bars. Month mixes
+filled bars for all-day/multi-day-style entries with single subtle text lines for
+single-day timed-style entries, without placeholder dots or time chips. Patterns stay
+stable for each date and clear the date headers. Skeletons preserve the grid, scroll
+position, and navigation.
+Quick loads skip the skeletons. Real events lay out underneath during the brief
+minimum display, then fade in as the skeletons fade out. Changing period during a
+load carries feedback into the new cells without restarting the appearance delay.
+Background refreshes retain current events without skeletons or a transient loading
+pill. On a cold reload, the first event paint waits for calendar metadata so events
+appear in their configured colors. A REST/GraphQL handoff for the same user and
+date range keeps the visible events and calendar list while the new reader loads;
+changing the user or date range must not retain the old events. Verify both handoff
+directions with delayed responses and delay calendar metadata past occurrences.
+If metadata fails, events remain usable with the default calendar presentation.
+Provider backfill shows a persistent `Syncing your calendar…` banner above the
+grid, explaining that events will appear automatically and Macro remains usable.
+The banner stays visible as partial results arrive and disappears when sync finishes.
+Errors retain the separate retry state. Verify delayed occurrence
+responses: switch Month/Week/Day rapidly and navigate without blanking the grid.
+Confirm mixed event shapes, stable positions, clean handoff, and an uncovered Retry.
+Reduced-motion mode disables pulses and transitions. The page stays busy until the
+handoff starts. Hidden pages do not animate. Resize to confirm skeleton alignment.
+
+Imported timed events with identical start and end are points: they show a compact
+chip with one time and `No duration` in details, and do not block availability.
+Future points also appear in Upcoming events, without becoming ongoing meetings.
+Grid dragging and resizing are disabled for points. An owned point's metadata,
+RSVP, and deletion still work; metadata saves preserve its exact provider time.
+Creating an event or changing its time requires positive duration. Shared points
+remain read-only and appear only when their details are shared.
+An existing Macro call can keep its schedule during point metadata edits; adding
+a new Macro call requires giving the event a duration first.
+
+Calendar reads come from the local GraphQL cache when both `enable-graphql-soup`
+and `enable-graphql-calendar` are on (PostHog in production, on by default in dev
+for the calendar flag; set `VITE_ENABLE_GRAPHQL_CALENDAR=false` to test the REST
+path). A range the cache has covered renders with no occurrence request, and a far
+jump fetches only the uncovered weeks. A `refresh_calendar` poke, reconnecting,
+coming online, or returning to the tab runs one `CalendarChanges` delta that
+applies edits made elsewhere. RSVPs, edits, deletions, and creates show at once
+through the durable mutation queue: a rejected write rolls back with the usual
+error, and a write made offline stays visible and replays on reconnect. Native
+apps whose engine lacks the calendar cache commands keep the REST path. Until the
+cache answers its first calendar read, viewports wait at most a second and then
+read from REST, and writes use REST, so a cache that is slow to start or fails
+("Local cache unavailable") never leaves the calendar on skeletons. Writes in
+that window behave as on the REST path: offline, they roll back with an error
+instead of replaying.
+
+A single period arrow retains its slide. Rapid arrow clicks and period hotkeys
+accumulate against the requested date and interrupt unfinished slides, without
+waiting for event responses or hidden-page redraws. Verify repeated forward clicks
+and mixed directions reach the cumulative date while events are still loading.
+Touch swipes retain their page-readiness gates.
+
+Quick-call creation, incoming invitations, Live lists, Macro meeting links, and
+the `/app/meet/*` routes require the PostHog flag `enable-quick-calls`. While the
+flag loads or is off, those controls stay hidden and meeting routes do not mount
+call setup. Existing channel calls and the upcoming-events list remain available.
+For local verification, set `VITE_ENABLE_QUICK_CALLS=true` or `false` explicitly.
+
+During a quick or scheduled call, signed-in participants can open **Call chat**
+from its separate button at the far right of the bottom toolbar. Messages persist
+with that call session and are visible in its recording page after it ends.
+Guests do not see chat. The `@` menu includes Macro and available agents;
+mentioning one invokes it in the call thread. Reply on any live message, including
+your own, quotes it in the bottom composer. Verify the reply preserves a draft,
+an agent reply appears, and messages remain in the saved history; starting a
+new session from the same meeting link must start a separate chat thread.
+
+
+Calendar event creation and editing open in a bottom sheet on touch devices,
+with scrollable content above the keyboard. Desktop retains the centered dialog.
+Dismissing a changed event still asks before discarding the draft.
+
+On phones, event details use inset round action buttons and a transparent RSVP
+footer. Answering a recurring invitation opens a rounded glass sheet: choose
+`This event` or `All events`, then `Save response`. Cancel or Close returns to
+the event details without sending a response.
+
+Calendar scheduling is on by default in dev. Production uses the PostHog flag
+`enable-calendar-scheduling` and stays off unless enabled remotely. Set
+`VITE_ENABLE_CALENDAR_SCHEDULING=false` to test the disabled state locally.
+While off, the Calendar settings tab and calendar booking shortcuts are hidden;
+public booking and receipt links show an unavailable page without fetching
+scheduling data. When enabling a production rollout, include anonymous visitors
+so invitees can open those links. A public booking link stays available when
+the flag request gets no answer, for example when a browser blocks it.
+
+Calendar connections live in **Settings → Calendar** (`/app/settings/calendar`).
+Scheduling lives in the separate **Settings → Booking links** item
+(`/app/settings/booking-links`). Use the owner menu at the top right to choose
+**Personal** or **Team · team name**,
+then use **Links**, **Availability**, **Booking page**, **Bookings**, or **Insights**.
+Every section and creation action applies to that selected owner. The default is
+Personal. **Manage teams** in that menu opens team settings. The calendar toolbar’s booking
+actions open Booking links; connection shortcuts continue to open Calendar.
+**New booking link** and **New schedule** create for the selected owner and open
+inline editors. Save changes or Cancel returns to that owner's list.
+Connected calendars offers Connect account (the existing Google consent flow),
+Connect calendar for accounts missing calendar permission, and Disconnect with
+confirmation. Disconnect removes calendar access/data, not the Gmail connection.
+Account checkboxes show/hide all child calendars; partial selection is shown as
+mixed. Individual calendars can also be shown/hidden. The account color is the
+default for its calendars; a child color overrides it. Click a color dot to open
+the theme-matched picker: drag the color field and hue slider, choose a named
+swatch, or enter a three- or six-digit hex value. Arrow keys adjust the focused
+color field (Shift makes larger steps). **Reset to default** clears the override.
+Visibility and colors share the calendar sidebar's browser-local preferences,
+survive reload, and do not change the Google calendar or booking conflict checks.
+Booking status filters use the same segmented control as the CRM sidebar.
+In Availability, each weekday has an enable switch, time ranges, an add button,
+and a copy-hours menu; select target days and Apply before saving the schedule.
+Date overrides and the searchable timezone picker sit below the weekly hours.
+The header shows the selected owner; team owners have an explicit **Team** label.
+Links and availability use flat rows, with actions beside each item.
+Booking pages, bookings, and insights show only the selected owner. Search filters
+that owner’s links and clears when switching owners. Any team member can edit
+team links. Hosts can cancel or reschedule the meetings they host; team
+owners/admins can also manage teammates’ bookings and approve pending ones.
+`Links` creates, edits, pauses,
+duplicates, previews, and copies booking links. Event settings include a
+video choice. New links default to a Macro call, which is created when
+someone books and attached to the calendar invitation. Google Meet and no
+video link remain available. Event settings also include
+weekly availability, collective/all-host or round-robin/one-host assignment,
+notice, buffers, booking horizon, daily limits, and custom questions. New event
+types stay paused until `Accept bookings` is selected and changes are saved.
+`Availability` manages named weekly schedules and date overrides in an IANA time
+zone. Set a default schedule for new event types; a schedule cannot be deleted
+until its event types use another one. Collective and round-robin team meetings
+respect each host’s personal default hours when configured, plus busy calendars.
+**Manage teams** opens team settings, where the member roster lives. Choose hosts
+for a team booking link inside its editor.
+`Booking page` edits the public name and description. `Bookings` shows
+upcoming, unconfirmed, past, and cancelled meetings; admins can confirm requests,
+reschedule, or cancel them. Choose From/Through dates to load bookings (initially 30 days before and after today), then search by guest/title/email and filter by event type. Dates use your browser time zone; shorten the range if more than 5,000 bookings match.
+Cancellation asks for confirmation. After a confirmed meeting ends, an assigned
+host or team admin can mark attendance or a host/guest no-show. Pending requests
+from older configurations appear under Unconfirmed. New approval-only links are disabled;
+new links use automatic confirmation and provider calendar invitations. Existing approval
+links must switch to automatic confirmation before accepting new bookings.
+
+`Insights` reports the selected personal/team owner with 7/30/90-day or custom
+ranges, event/host filters, previous-period comparisons, event trends, meeting
+hours, no-shows, popular events, and host counts. Download exports the filtered
+bookings to CSV. Metrics use booking start dates in the default schedule’s time
+zone; failed/processing requests are excluded. Completed means ended confirmed
+bookings excluding recorded no-shows. Rescheduled counts bookings with recorded
+reschedule history. Ratings/CSAT are not shown because no survey data is collected.
+Oversized result sets return an error instead of silently truncating insights.
+
+The calendar header includes `Copy booking link` and `Open calendar scheduling
+settings`. Copy opens settings when no active personal link exists. Public
+`/app/book/:profile/:slug?` pages accept bookings without Macro sign-in. The website
+opens them in its own dialog; framed there, a booking page and its receipt drop their
+Macro heading and footer, and the booking page tells the website when a booking is
+made. Only macro.com can frame them. Uncertain
+calendar writes retain the booking and show its private receipt while automatic recovery runs.
+After a network response cannot be verified, `Check booking status` retries the original request;
+do not create a replacement booking. Receipt pages poll while the calendar update is pending. Visitors
+choose their time zone, date, time, and required details. The private
+`/app/booking/:id#token` receipt supports cancellation and rescheduling; preserve
+that private link. Rescheduling dates are labelled in the availability schedule's
+time zone. Calendar provider failures show an error; they never report a
+confirmed booking. Current integrations check hosts' connected calendars and
+write invitations/Google Meet through the existing calendar service.
+
+The standalone Calendar view has a left navigation sidebar. The `New` menu
+above the mini calendar offers `Event`, feature-gated `Call`, and feature-gated
+`Reminder`. An icon-only shortcut in the `Upcoming events` header opens the
+availability dialog. Start/end time selectors and a weekend switch sit above
+copy ranges that wrap on narrow screens. The dialog checks all ranges using one
+calendar-occurrence query; ranges without free time are disabled, show an X
+instead of the copy icon, and retain a reason tooltip that can receive keyboard
+focus.
+Copying rechecks the occurrences and current time, so changes since opening do
+not enter the copied text. The option keeps its width while a left spinner and
+`Copying…` crossfade to `Copied` with a green check icon; the button keeps its
+neutral styling. Reduced-motion preferences skip the crossfade and spin.
+Collapsible `Upcoming events` and `Calendars` sections follow; calendar
+account rows use Drive-style trailing disclosure buttons and animated nested
+branches. Their 14px visibility checkboxes precede the swatch and label, with
+separate account and individual-calendar visibility controls. `Team out of office`
+is feature-gated and lists teammates with 24px avatars; its section switch
+toggles the entire grid overlay. Clicking a teammate's row navigates to that
+date, opens read-only event details, and marks the row active. The icon-only
+`Calendar settings` control fills the sidebar footer.
+An account checkbox toggles its calendars together in one update. The checkbox
+responds immediately; the upcoming list and each grid page refresh on deferred
+tasks rather than re-rendering all pages during the click.
+The sidebar can be resized or collapsed on desktop; in narrow desktop panes
+it opens over the grid. Phones do not show the sidebar or its navigation drawer.
+The mobile split header places a month selector and Today in its left island;
+selecting the month opens the date-selection drawer. The right island keeps
+full-sized Availability, Search, and Settings actions. The New menu
+beside the bottom AI input offers Event, feature-gated Call, and feature-gated
+Reminder. Inline Calendar previews retain their host's chrome without adding
+another sidebar; their left header island has a compact New menu because the
+bottom New action follows the foreground host view.
+
+With `enable-calendar-team-sharing` enabled, **Settings → Calendar** also has
+**Team sharing**: `Busy blocks` (the default), `Event details`, and `Nothing`.
+These are Macro read permissions. They do not change Google Calendar ACLs,
+invite teammates to meetings, or let teammates edit, RSVP, or manage reminders.
+The sharing choice covers every currently authorized calendar synced to Macro.
+Private/confidential events only expose generic time blocks; event details
+come from one authorized source copy. Disconnecting an account or losing
+source access removes its team projection.
+
+**Calendars that count as busy** controls which calendars represent the user's
+personal schedule. Primary calendars count by default; other calendars require
+explicit inclusion. Meetings the user attends also contribute, except declined
+meetings. Following a coworker's calendar does not automatically make that
+coworker's events occupy the user's time. In team overlays, `Busy` means the
+block contributes to that teammate's availability; `Shared calendar block`
+means it belongs to a calendar the teammate can access and does not count
+toward their busy time. Event details show the same distinction explicitly.
+
+The sidebar's **Team calendars** section has a master `Show team calendars`
+switch and per-teammate checkboxes; Settings exposes the same display controls.
+Display toggles affect this viewer's grid only. Team chips are prefixed with
+the sharer's name and open read-only details. Copy-event links, guest-email
+actions, RSVP, editing, and deletion are unavailable on team projections.
+A directly accessible copy retains its own actions; another person's projection
+of the same meeting may appear separately, with its sharing provenance.
+Distinct authorized source copies may also appear separately for the same
+teammate and meeting: their detail masking and availability contribution can differ.
+Team projections and availability use server-confirmed copies. An offline queued
+edit appears in the editor's own calendar, but reaches teammates only after the
+server commits the provider-backed change and their shared projection refreshes.
+An unavailable team fetch displays a warning and removes stale shared details.
+Sharing-change notifications clear open shared details before refetching;
+focus/reconnect and a 30-second refresh provide a fallback. Shared details also
+disappear when an offline refresh is paused; they are not persisted for offline
+use. While the app is running, team responses and in-flight requests expire
+after 60 seconds, so a hung refresh cannot retain old details. Replacing a login
+session clears team data and open shared details before the new identity loads.
+Legacy out-of-office rows are read-only status displays and do not claim
+that every absence blocks availability.
+
+The `GetTeamAvailability` AI tool checks the requester together with the selected
+teammates. It reports confirmed free windows only when every participant has
+complete availability coverage. Hidden, disconnected, stale, or incomplete
+calendars are reported as unknown, never free. Busy blocks contain no event
+titles or private event metadata.
+
+The in-view desktop Calendar header uses one responsive top bar. The viewed
+month and year stay on the left in a heading that scales from 16px in narrow
+splits to a maximum of 24px, with a compact `New` menu when the sidebar is closed.
+An icon-only ghost `Search events` button sits on the right, before a slightly
+larger gap and the `Today`, period selector, and previous/next controls.
+Click Search or press Cmd/Ctrl+F to expand and focus the wider inline search field.
+The field slides out with a short width transition and focuses immediately.
+The results popup stays hidden until the field contains non-whitespace text,
+then fades and slides in once expansion is nearly complete. Clearing the field
+hides the popup without collapsing search. Reduced-motion preferences skip
+both transitions.
+Close search, Escape, selecting a result, or clicking outside collapses it back
+to the icon without clearing the query. Activating a period control also
+collapses search after the action runs. Escape and Close restore focus to the
+Search button. The expanded field exposes Filters and, after typing, the
+icon-only Exact-match toggle. The filter button stays before Close. The filter
+menu opens below the button, aligned to its right edge: Search in is
+single-select, while Status, Organizer, and Attendee allow multiple values.
+Organizer and Attendee virtualize their contact lists; selected contacts stay
+in place, while custom email addresses appear first. Adding a valid email clears
+the contact search. Filter selections apply immediately, and only these filters
+mark the filter button, not Exact mode. Search opens a calendar-search hint
+until at least three characters are entered; searches show skeleton rows while
+loading. Empty results show an illustrated empty state. Result titles show a calendar-color
+swatch when the event is loaded in the visible range, falling back to the
+default calendar color otherwise. A result shows its location after the
+date/time when available. Each result offers at most one rounded Join action:
+matching occurrence content takes precedence over series metadata. Macro links
+use a neutral button, Google Meet uses a solid blue button in light mode and a
+subtle blue button in dark mode, and other conference links use a neutral button.
+All Join buttons use a camera icon. Generated Macro invitation paragraphs are
+hidden from event descriptions. Google Meet URLs in an event's location or
+description also supply Join actions. Recurring results wait for matching
+occurrence details before showing Join. Selecting a result preserves the search
+text. Availability lives in the desktop sidebar's Upcoming events section and
+in the mobile header.
+
+The period controls move into a separate row below 600px of calendar-pane width,
+with `New` on the left and navigation on the right. With a docked sidebar, the
+header needs fewer controls and stays inline down to 480px. This avoids wrapping
+and immediately unwrapping when the sidebar hides. Expanded search does not
+force early wrapping; its results popup stays directly below the search field.
+Below 1040px, search slides over the month title without moving any controls or
+changing the header height. `New` stays outside the search overlay. Resizing the
+pane keeps the search field mounted and preserves its query and focus. Today
+and New retain their text labels until the controls row runs out of room, then
+become icon buttons.
+Touch devices keep the month selector and header controls without separate
+create or call buttons in the right island. Mobile header islands omit Search.
+The desktop sidebar's mini calendar remains navigable by date and month.
+
+Active Quick Calls you created, participated in, or were invited to appear above your
+next five events (including ones in progress), whether or not they have call links.
+The active area is hidden when no calls are active. Upcoming event rows show a
+calendar color swatch, the name, and the time; click one to open its details and
+highlight the active row.
+An event with a call link shows `Join` while it is in progress. Upcoming events
+follow today's date even when you browse another week; hidden calendars,
+cancelled events, and invitations you declined are omitted.
+`New Call` opens `/app/meet/new` without creating a meeting. The `Invite Teammates`
+button above `Start call` opens the task assignee picker with name search, profile
+pictures and multiple selections, without bots or external contacts. The closed
+button shows up to three stacked selected profile pictures and the total teammate
+count; hover shows selected names, and reopening keeps the same selections. Selection
+stays local until `Start call` creates the Quick Call, connects the creator, and
+rings selected teammates. Microphone and camera are not shared before starting.
+If invitations fail after connecting, `Retry invites` sends them again without
+creating another call. Shared-link join screens do not show the teammate picker.
+Incoming invitations appear in a bottom-left notification with the call name,
+caller initials/name, and `Decline` and `Join` buttons. This stays visible across
+app pages, including call setup, hidden sidebars, narrow splits, and mobile (above
+the bottom dock). The card uses the app's menu surface, with semantic success
+color for `Join` and danger color for `Decline`. A top bar and seconds counter
+show the time remaining before the 30-second dismissal deadline.
+`Join` opens call setup; `Decline` stops ringing across the
+recipient's tabs. Unanswered invitations disappear and stop ringing after 30 seconds.
+Declining or timing out does not remove an invited live call from Channels `Live`.
+The list updates as calls end and new calls start. Calls from other conferencing
+providers open their own join links. A failed upcoming-list request has a `Retry`
+action and does not prevent creating a call.
+Working locations (such as `Office` or `Home`) stay on the calendar grid but are
+excluded from Upcoming events, including both all-day and hourly locations.
+Events require connecting a Google account (`Connect calendar`). The
+`Calendar settings` (gear) menu has an `Accounts`
+section listing each connected account with a per-account `Enable` (grant calendar),
+`Reconnect` (expired Google authorization), or `Turn off` action, plus
+`Connect another account` to connect a new Google account
+(email + calendar).
+
+`Turn off` keeps its confirmation open with `Turning off…` until removal finishes;
+re-enabling is not offered while the old calendar is still being deleted. Reconnecting
+an inbox that used calendar requests email and calendar together, while an explicit
+calendar opt-out remains off during an email-only reconnect. Per-inbox actions
+preselect that Google account. The consent callback explains that it is finishing
+the connection, provides `Back to app`, and restores the previous layout on completion.
+It applies the grant even if the old inbox list is still loading.
+
+An AI event draft defaults to the primary inbox's primary calendar. If that calendar
+is disconnected or still syncing, the draft offers reconnection or an explicit
+calendar choice and disables submission until a usable calendar is selected. It
+does not silently send the invitation from another connected inbox.
+Failed calendar or account queries show `Could not load your calendars.` with
+`Try again`, rather than offering consent or presenting the failure as backfill.
+
+`New event` opens the compact composer with All day in the date/time fields.
+The meeting-link selector lists `Macro call`, `Google Meet`, then `No meeting link`
+for new events, defaulting to `Macro call` when quick calls are enabled. Keeping
+that selection creates and attaches a Macro call after the event saves. Selecting
+`Google Meet` or `No meeting link` skips the Macro call. Out-of-office entries do
+not create calls. There is no separate call toggle or Scheduled Call menu option.
+All-day events get an untimed call link, so setup does not display a misleading midnight time.
+A failed link attachment keeps the composer open with a retry message; Save reuses
+the saved event and call instead of creating duplicates. The invitation includes
+the call link in its description and, when no location was entered, its location.
+Event details show a plain icon row with a standard gray `Join Macro call` button
+and `Copy call link`, without an enclosing border or the full URL.
+Editing or rescheduling an owned event retains and updates its selected Macro call.
+Selecting `Macro call` on an owned editable event without one adds a call on save;
+choosing another option removes its generated Macro link from the invitation.
+Removing the link or deleting the calendar event does not revoke the reusable call.
+The AI's `CreateCalendarEvent` composer (chat, agent sessions, channel review cards)
+offers the same selector under the same quick-calls flag; `Macro call` there maps to
+the tool's `addMacroCall`, and the call is created when the tool executes, before the
+event is written, so the single invitation already carries the link. The MCP server
+and channel bot accept `addMacroCall` directly. `addMacroCall` and `addGoogleMeet`
+are mutually exclusive, and out-of-office entries accept neither.
+
+The sidebar's `Calendars` section folds each connected account into a collapsible
+group: a caret plus the account address header with a checkbox that shows or hides all of
+that account's calendars at once, and the account's calendars listed beneath it (color dot,
+name, per-calendar checkbox). Accounts start collapsed. Subscribed system calendars
+(Google holidays, birthdays) carry a small RSS icon. A calendar whose sync has been failing persistently carries a small
+warning icon whose tooltip shows the provider error; the account keeps syncing its other
+calendars and the badge clears on its own once that calendar syncs again.
+
+On desktop, clicking or dragging empty grid time opens the event composer.
+While an event's details are open, a press on empty grid time closes them and
+does not start a new event; the next press creates one. Clicking another event
+switches the open details.
+Desktop event details stay inside the visible calendar grid, including Home
+previews and narrow splits. They overlap wide Day-view events when needed and
+shrink to fit the pane; long details scroll while the RSVP row stays visible.
+
+The `New event` composer (also opened by dragging a range on the grid) has an `Event kind`
+pill choosing between `Event` and `Out of office`. Picking `Out of office` hides the guests,
+conferencing, and location pills and the description field (Google rejects them on this
+type), forces a timed (not all-day) range, restricts the calendar
+pill to primary calendars, and shows a `Decline meetings` pill (`Don't decline meetings` /
+`Decline new meetings` / `Decline all meetings`) plus, when declining, an optional
+`Decline message` pill; a warning note discloses the away/auto-decline effect before saving.
+When editing an existing event the kind is read-only (Google treats it as immutable), and an
+out-of-office event's decline settings can still be changed — they read as unset because the
+provider does not report the stored ones. Timed and all-day events use solid calendar-color
+blocks with dark text on desktop and mobile. Unanswered and tentative invitations have
+lighter fills; declined events are desaturated and struck through. Month-view timed events
+keep their compact dot treatment. Out-of-office details show an `Out of office` line under
+the schedule.
+An event that Google carries on several of an account's calendars (a shared calendar's
+re-import of a member's own event, for example) renders as one chip, not one per calendar:
+the details popover's color square shows its calendars. The chip shows the title, color, and
+editability of the first shown copy in primary-first order — hiding the primary calendar
+switches the chip to the shared copy, hiding every one of its calendars hides the chip.
+Reminders, guests, and conferencing always show and follow the primary copy, since that is
+the copy Macro's alerts fire from and whose guest list and join link Macro records, and the
+editor only lets them be changed there. Answering an invitation likewise addresses the
+primary copy. The details popover and the editor act on the displayed copy, so editing or
+deleting it targets that calendar's event at Google.
+When changing only a reminder in the event editor, choose `All events` to apply it
+to the recurring series or `This event` for one occurrence. Saving preserves the
+existing dates, time zone, title, location, description, and repeat rule unless those controls
+changed. To verify, open a later occurrence of an event you were invited to,
+change the reminder, and inspect the PATCH: it should include only `reminders`
+plus the calendar and scope identifiers. Also verify that intentional edits to
+the start, end, all-day setting, title, location, description, or repeat rule are still sent.
+Test reminder removal as well as changing its time, including a series whose stored
+rule contains `INTERVAL=1`, `WKST`, differently ordered weekdays, or a precise `UNTIL`:
+an untouched rule must not be reformatted and included in a reminder-only PATCH.
+As in Google Calendar, the guests row of the details popover (a bottom sheet on phones)
+carries `Copy guest emails` and `Email guests` icon buttons. Copying puts every guest's
+address on the clipboard, comma-separated. Emailing opens a new email addressed to every
+guest but you — in a split beside the calendar on desktop, as the full-screen composer on
+touch devices — and is hidden when you are the only guest.
+
+With the `enable-calendar-team-ooo` flag on, teammates' Google Calendar out-of-office events
+overlay the grid as read-only chips titled `<name>: <event title>`. The sidebar's
+`Team out of office` section (shown only when the user belongs to a team with other members)
+has a checkbox in its header row toggling the whole overlay on or off — all teammates or
+none — and lists the next 90 days of teammate absences; clicking a row navigates the grid to
+that date. Coverage depends on each teammate having connected their own calendar and using
+Google's out-of-office event type.
+
+A calendar event mentioned in a channel message opens the calendar focused on the viewer's
+own copy of the meeting. When a person holds the event on their own calendar and posts the
+mention, it is shared read-only with the channel's current members: a member without a copy of
+their own sees the mention's title and time, and its hover card adds a `Shared with you · not on
+your calendar` line with no open action. Clicking such a mention shows that hover card
+instead of opening the calendar. A classic `@Macro` reply that mentions an event does not share
+it by posting the chip. It asks whether to share with the channel, and a yes in that thread
+writes the same channel grant. Private and confidential events are never shared this way.
+Every calendar mention's hover card shows the schedule, location, organizer and attendee
+count, plus the first lines of the event description (its links open), and no last-updated
+byline.
+
+## Calendar invitations in email
+
+In `/app/component/mail`, open an invitation message; the same card appears in
+`/app/email/:threadId`. Saved details appear below the sender without waiting for calendar
+sync. Expand guests and descriptions with their explicit controls. `View original email`
+is an accessible disclosure that starts closed; attachments remain below it.
+Related recurring components are grouped behind their own disclosure. Only mail synced
+after the feature shipped gets a card; older invitations render as plain email.
+A newly arrived scheduling update shows RSVP and Join only once its calendar state has
+been checked. A series invitation shows its current or next live occurrence.
+
+Descriptions render sanitized rich text, including emphasis, links, and lists.
+Plain-text line breaks and literal angle brackets (such as `<[email protected]>`)
+remain readable. Use `Show more` / `Show less` to expand or collapse the description;
+description links use the host's normal link-opening behavior.
+
+A connected, resolved invitation shows the responding address and Yes / Maybe / No.
+Calendars connected through a linked inbox also resolve here, using that inbox's
+address for responses. Access is limited to the delegated inbox; another inbox owned
+by the same account stays private, and removing the link removes invitation access.
+Local verification requires both email and calendar services: email supplies saved
+snapshots and resolves them against the synced calendar, while calendar service handles
+the RSVP write. With calendar service's `CALENDAR_SYNC_ENABLED` off, its RSVP route is
+not mounted, so a response fails with an error. Seeded local accounts have no Google
+token, so an RSVP there fails at the provider write and rolls back.
+The selected response remains pressed while a save is pending. Recurring invitations ask
+for `This event` or `All events`. Failures keep the card in place and report a retryable
+error; offline responses are not sent. Cancellation and response/proposal notifications
+do not offer RSVP or Join. Disconnected, ambiguous, and syncing states explain why an
+action is unavailable.
+
+`Open in calendar` focuses the current occurrence, even if its date changed.
+`View your day` opens a compact agenda without changing the active split; Close returns
+focus to its trigger. Busy overlapping events are labeled, while cancelled, declined,
+and free events do not count as conflicts. Calendar 12/24-hour preferences apply to
+already-open invitation cards as well as the calendar view.
diff --git a/docs/agent-guide/calls.md b/docs/agent-guide/calls.md
new file mode 100644
index 0000000000..c5a3f90701
--- /dev/null
+++ b/docs/agent-guide/calls.md
@@ -0,0 +1,172 @@
+# Calls
+
+## Calls — `/app/component/calls`
+
+On desktop a collapsible sidebar holds the search field (`Search calls`, `⌘F`),
+the views `All` / `Missed` / `Unattended`, a `Type` section (`Internal` /
+`External`; External means at least one guest without a Macro account joined),
+a `Channels` section listing channels seen in loaded calls, and `Tags`. Choosing
+a type, channel, or tag shows only that one; choosing it again clears it. These
+refinements carry across the three views. Sort, group, filter, and `New call`
+sit in the list's top bar. Phones keep pill tabs and the header search.
+With `enable-quick-calls` enabled, `New call` opens a menu with `Start an instant
+call`, `Call a channel or contact`, and `Manage call links`; without the flag it
+opens the recipient picker directly. `Start an instant call` opens `/app/meet/new`
+without creating a meeting, the same setup reached from `New Call` beside
+Calendar's `New event` or `Create` → `Call` (`C C`). Scheduled calls are created
+through Calendar and can be shared with people who do not have a Macro account.
+The channel/contact option opens the recipient picker.
+Recordings, transcriptions
+and summaries appear here; empty state notes "Calls are available to agents."
+
+Opening a recording uses `/app/drive/call/<callId>` inside the Drive shell,
+with one breadcrumbed header (`My Files > <recording name>`) and a route back to
+Drive. The Drive file list does not include calls.
+Old copied `/app/call/<callId>` links redirect to the Drive detail without losing
+the transcript target. The detail shows a loading state, recording/transcript/summary,
+Share, and a call side panel below the breadcrumb header; a failed load shows Try again.
+`call_transcript_id=<segmentId>` seeks the matching video segment after loading.
+Check a direct link, an old copied link, a Calls-list click, a second split,
+the breadcrumb return, and clicking the same transcript search hit twice after
+playing elsewhere. On phones, recorded call headers omit **Call Again**.
+
+A channel's `Calls` tab lists that channel's recordings with the same rows, filtered
+by the channel id. Its search field matches call names and transcripts in that
+channel.
+
+In the native iOS call drawer, the horizontal participant row excludes the person
+shown in the large video. While holding or scrolling the row (including momentum),
+the displayed primary and row membership stay fixed; speaking indicators still
+update. The latest primary and membership update together after scrolling settles,
+preserving a surviving participant's position where possible. Verify that dragging
+does not pin someone, tapping pins the displayed person, and a participant who
+leaves during a held touch cannot be selected. Exercise speaker changes and
+departures during row gestures on a physical iPhone as well as the simulator.
+
+If a recording fails to play, reload the page to obtain a fresh recording link,
+or use **Open or download recording**. The playback warning does not assume
+that the failure is caused by an unsupported media format.
+
+### Call links and guests — `/app/meet/join/:shareToken`
+
+These routes require `enable-quick-calls` for both signed-in users and guests.
+In Calendar, create an event with `Macro call` selected (the default).
+The composer waits for the quick-call flag to load before choosing its default.
+Saving creates the call and includes its link in the invitation;
+the room starts on the first join. Use Calendar to edit the event or invite guests.
+Teammate rings require a live call; selecting teammates during new-call setup
+sends invitations after the call connects.
+
+`New call` → `Manage call links` lists your standalone links with `Join call`, `Copy
+link`, and `Revoke link`. Revocation prevents new joins; it does not delete calendar
+events or disconnect current participants. Each active channel call also shows its
+URL and `Copy link`. A channel call's link stops working when that call ends.
+
+Guests can use standalone meeting links without a Macro account. Links to channel
+calls only admit signed-in Macro users; visitors without an account see a sign-in
+prompt instead of the guest name form. Inside a channel call, the shareable link is
+created on request via `Get shareable call link`.
+
+New calls use `/app/meet/new`; shared links open setup at
+`/app/meet/join/:shareToken`. A successful connection replaces the URL with
+`/app/meet/:shareToken` without restarting the call. Leaving returns to Macro.
+An unexpected disconnection returns to setup so the user can retry.
+Opening or reloading an in-call URL returns to setup and requires a deliberate
+join; existing shared links continue to work.
+
+Guests enter `Your name`, choose their microphone and camera preferences, and
+press `Join call`. Setup requests microphone permission and waits until that
+prompt finishes before requesting the camera, then previews video locally;
+sharing starts only after joining.
+Permission denial leaves the affected device off and still allows joining.
+Shared-link setup shows the people currently connected, with avatars, names, and
+an attendee count. It refreshes every 15 seconds while setup is open; guests see
+this only for standalone links. Empty calls show `No one else is here yet`; a
+failed roster request leaves joining available. Transcription agents and past
+attendees are excluded.
+
+The preview and full-width join button retain their size while joining.
+The call runtime preloads while setup is open. New-call setup also reserves an
+empty room, without starting a meeting, recording, or invitations. Leaving setup
+cancels that reservation; abandoned rooms expire after five minutes. Starting
+still works if preparation fails or expires.
+Entry waits for the room connection;
+teammate invitations continue afterward. For a newly started call, transcription
+and recording start in the background instead of delaying join credentials.
+Copying the meeting URL is available after joining, in the in-call header.
+
+The creator presses `Start call`; invitees press `Join call`. Loading the page or
+completing authentication never joins automatically, including old `?join=true`
+URLs. `Back to Macro` exits setup.
+Channel-linked calls require sign-in. While authentication is loading or the
+viewer is signed out, setup must not request microphone or camera access; the
+guest name form is available only for standalone meetings.
+
+The call page shows a recording/transcription notice. It uses the normal call controls
+for audio, video, device selection, screen sharing, and effects. `Leave call` returns
+to Macro. `Copy Meeting Url` is available during the call.
+Rejoining from a new page waits for the prior page's pending leave cleanup before
+requesting another connection, so a slow leave cannot disconnect the replacement.
+Leaving the last participant archives the session first and tears down its media
+in the background, so the next call does not wait for that room to be deleted.
+It keeps its label and shows a checkmark for a few seconds after copying, then
+restores the copy icon.
+
+Guest access is limited to the call room; joining does not expose the channel or grant
+anonymous access to saved transcripts and recordings. Guest names are preserved in
+the host's call history. Signed-in attendees receive access to that session's saved
+call without gaining access to the channel.
+
+The join screen, in-call participant tiles, and incoming direct-call badges use
+profile pictures; initials are the fallback when no photo is available.
+The join screen has microphone, camera, and background effects buttons over the
+preview, with pill selectors below for microphone, speaker, camera, and
+backgrounds. The background button over the preview toggles the selected effect
+off and back on; when no effect has been selected, it enables Strong blur.
+Backgrounds use a simple menu with None, Light blur, Strong blur, and image upload
+(JPG, PNG, or WebP, up to 10 MB). Dot icons distinguish the two blur strengths.
+Selected devices and backgrounds carry into the call; unsupported browsers use
+the system speaker. If a background cannot be applied, the camera stays off
+until the user retries or chooses None. The screen uses a gray join
+button. The in-call header has a gray `Copy Meeting Url` button with a copy icon
+and shows the current local time before the call name. Owners can click the name
+to rename it, then Save or press Enter; Cancel or Escape discards the edit. Guests and other participants see a
+read-only name.
+
+Join-preview and in-call controls use the standard Macro icon buttons. Pause
+over the microphone, camera, or background group to reveal an animated settings popover
+above the call toolbar; click its caret to keep it open. Brief pointer passes
+do not open settings, and moving into the popover keeps it open. Settings
+respect reduced-motion preferences. The toolbar and settings panels use Macro's
+shared glass surface in both light and dark themes.
+Audio settings include microphone, speaker, and noise suppression. Camera
+settings include the camera selector. Clicking the background icon toggles the
+selected effect off/on, restoring the last blur strength or image (Strong blur
+by default). Its hover panel contains the same None, Light blur, Strong blur,
+and image-upload menu as the join screen; the caret pins this panel for keyboard
+and touch access. Click outside or press Escape to close the settings.
+The controls also work by keyboard and touch.
+
+### Sharing a call
+
+With quick calls enabled, channel calls use the same **Copy Meeting Url** button
+as instant and scheduled calls. Clicking it creates the share link and copies it;
+opening the call tab alone does not create a link. If loading fails, click again
+to retry. If clipboard access fails, a selectable URL appears below the button.
+
+A channel call's **Share** dialog has a `Team access` control (None or View) for the same canonical
+team share. Its side panel has a `Sharing` section with one `Share with team` checkbox, and the
+in-call controls carry the same checkbox while a call is live. It is canonical team sharing (the
+same `Team access` model documents and AI chats use), fixed at **view**. While the call is **live**
+the checkbox is a pending toggle (on by default for channel calls)
+that any participant with edit access can flip;
+other participants see it update live. When the call ends it is applied: with the toggle on,
+everyone on the creator's team can open the recorded call, read the transcript and AI summary,
+and find it under Calls and in search; off means nothing is shared. Afterwards only the call's
+**creator** can change it — everyone else sees the checkbox read-only with a note saying so.
+Team sharing is independent of channel access and of link sharing.
+
+Standalone instant and scheduled calls are excluded from team memory. They have no
+`Share with team` or `Team access` controls during the call or on the saved recording.
+Signed-in participants keep direct access to their recordings, transcripts, and summaries;
+joining a standalone call never makes its content available to the wider team.
diff --git a/docs/agent-guide/canvas.md b/docs/agent-guide/canvas.md
new file mode 100644
index 0000000000..2130dba0f5
--- /dev/null
+++ b/docs/agent-guide/canvas.md
@@ -0,0 +1,16 @@
+# Canvas
+
+## Canvas colors
+
+To check the default canvas color, create a rectangle and a text box without
+changing the swatch. The rectangle should have a light neutral fill and a dark
+outline; the text should be dark and visible. Also check the neutral swatch after
+selecting another color. Neutral colors use an OKLCH `none` hue, which must render
+as gray rather than transparent.
+
+## Canvas link paste
+
+Pasting a supported routed Macro app link onto the canvas creates a text
+node with an entity mention, as legacy links do. Routed links retain compatible
+block targets, but not workspace paths or pane-local search state; unsupported
+links remain text.
diff --git a/docs/AGENT_GUIDE/channels.md b/docs/agent-guide/channels.md
similarity index 99%
rename from docs/AGENT_GUIDE/channels.md
rename to docs/agent-guide/channels.md
index 2ecdc98478..5a7d2334e7 100644
--- a/docs/AGENT_GUIDE/channels.md
+++ b/docs/agent-guide/channels.md
@@ -65,7 +65,7 @@ skipped, deleted and inaccessible targets retain safe source-only fallbacks, and
another viewer must not gain access through a rendered mention. Code examples
remain literal; source-controlled tags must not inject entities. Test live edits
and deletion before deferred reconciliation: neither may be overwritten or revived.
-See the [rollout/recovery gates](../SLACK_ARCHIVE_IMPORT_RUNBOOK.md).
+See the [rollout/recovery gates](../runbooks/slack-archive-import.md).
## Collapsed reply chains
diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.md
new file mode 100644
index 0000000000..dfed0ede81
--- /dev/null
+++ b/docs/agent-guide/crm.md
@@ -0,0 +1,241 @@
+# Customers (CRM)
+
+## Customers (CRM) — `/app/component/companies`
+
+On desktop, the local sidebar uses the same navigation primitives as Email and Tasks.
+Its **New** menu creates a **Company**, a **Contact**, or a **Pipeline** (Pipeline
+only when pipelines are enabled; disabled until the team's CRM is enabled). The
+**Records** section lists **Companies** and **People**; Pipelines and Lists follow.
+There are no built-in company views or Board/List layout. Companies and People
+are plain soup lists with the shared pagination. Existing personal/team saved
+views stay in the toolbar's Views menu.
+
+The selected Customers tab is stored on the pane as `sN.crm.tab`. People uses
+`people`, a pipeline uses `pipeline:<uuid>`, a list uses `list:<uuid>`, and
+hidden companies use `hidden`. Companies is the default and omits the key.
+Choosing Companies, People, a pipeline, or a list updates that parameter.
+Browser Back and Forward restore the tab and close an open record.
+
+Companies lists every visible company, grouped by Stage by default, with Owner,
+Revenue and Last Interaction columns. A Stage column is off by default; turn it
+on, or hide Owner or Revenue, under **Display options**. Its toolbar holds
+sort, group, filter, display options, saved views, and **New company** at the
+right end.
+
+People lists contacts across every CRM-enabled team the viewer belongs to, from
+the same Soup query with only CRM contacts opted in (`crmf`). The server collapses
+duplicate full email addresses (case-insensitive) to one contact. Hidden contacts
+and contacts under hidden companies are excluded. Columns are Person (name and
+email), Company and Last contacted (sortable). `Search people` matches name or
+email on the server after a short typing pause, so results include contacts not
+yet scrolled into view. **New contact** sits at the right end of the toolbar. Its
+dialog asks for a company through a **Choose a company** pill (searchable by name
+or domain, from the up to 500 most relevant companies with a domain) and fixes
+the email to that company's primary domain; **Add contact** on a company's Team
+tab skips the company pill. The company, contact and pipeline dialogs share the
+task/project composer layout: name on the first row beside **Close**, details
+below, and a **Create …** button that also submits on Command-Enter.
+
+`Search companies` and `Search people` use the shared Email/Tasks search bar.
+Command-F focuses it, `Clear search` resets it, and Escape leaves the field.
+
+On touch devices, CRM uses the same scrollable pill tabs as Tasks in the top
+header: Companies, People, available pipelines, and enabled lists. Swipe the
+strip horizontally to reach every destination; the selected tab stays visible.
+The tabs remain available inside pipelines, with no hamburger button. Company
+filters lead the strip when available. On mobile, pipelines omit their title
+and sharing row and use an edge-to-edge table, below the top safe area and above
+the bottom dock. The compact **Pipeline actions** button in the table toolbar
+opens rename and sharing controls; only owners see **Trash pipeline**, which
+requires confirmation. Sharing opens the existing share dialog. Companies uses
+the full-frame list with the global **+ Company** action above the dock. People keeps its search and **New contact** below the tab
+strip. The embedded detail stack stays out of the mobile flow, so selecting a
+row navigates in place.
+
+On desktop, clicking a company or a person in the list (or pressing Enter on a
+focused row) opens its details inside the CRM workspace, keeping the left
+navigation visible. The top breadcrumb reads `<Companies, People or list> >
+<record>`; click the first segment to return with the same filters and list
+scroll position. Selecting another sidebar entry closes the details. Shift-click
+still opens the record in a separate split. Direct company and contact links use
+the standalone pages.
+Each record opened from the details appends a breadcrumb: a contact from a
+company's Team tab gives `Companies > <company> > <contact>`, and a person's
+Company link gives `People > <contact> > <company>`. Opening a record already in
+the trail (such as the contact's own company from `Companies > <company> >
+<contact>`) returns to it instead of adding a duplicate. The CRM sidebar stays
+visible throughout.
+Company and contact headers have `Copy link` beside the side-panel toggle.
+Their information panel starts closed and opens as a floating bubble at every
+width, without shrinking the record content. Click outside the bubble or use
+the toggle to dismiss it; the open state is not restored on a later visit.
+It copies the record's direct URL and shows a confirmation toast; this is also
+available in the embedded company and contact breadcrumb header.
+
+The Team, Emails, Files, Tasks, and Calls tabs share a compact toolbar: search on
+the left, with available filters and actions on the right. Search remains visible
+for empty lists. `Add contact` and `New task` match the project task list's
+creation button: a rounded outline, standard height, and leading plus icon.
+The associated-tab search fields match the creation buttons' height.
+Team rows show a profile photo when available, otherwise a
+letter avatar at the same 16px size as channel list icons. Team uses the same Soup
+row component as Emails, Files, and Calls: the avatar, name, and email are inline,
+the last-contacted timestamp sits at the right, and the side gutters and row
+spacing match. There is no column-heading row.
+Emails, Files, and Calls search the loaded row titles and supporting text and
+continue loading pages when the current pages have no match.
+
+A company is laid out like a project. Its split header or embedded breadcrumb
+header shows inset `Overview`, `Team`, `Emails`, `Files`, `Tasks`, and `Calls`
+tabs, collapsing to icons when narrow. Overview shows the name, pills
+for each domain and `Last interacted`, the generated description, a
+**Pipelines** section and the Discussion. Pipelines stacks one full-width card
+per row of a pipeline you can open that references the record. A card's header
+strip names the pipeline (a lock marks a private one); below it, the row's first
+four fields sit side by side, label over value, and the rest wait behind
+`Show N more`. Cells edit like the pipeline table's when you can edit that
+pipeline. Inside Customers, the header's `Open <pipeline>` button opens it. The
+`Pipelines` caret header collapses and expands the cards, like the Discussion
+header; both start expanded on each visit. The
+section is absent when the record is in no pipeline.
+Team lists the contacts with `Add contact`. Emails keeps the
+`Signal`/`All` and `Team`/`Me` toggles; `Team` shows teammates' threads even to
+a viewer with no connected mailbox. Files, Tasks, and Calls list items
+*associated* with the company: its `Companies` property names the company, its
+`Contacts` property names one of the company's contacts, or it @mentions (or a
+message attaches) the company or one of those contacts. Contacts beyond the Team
+tab's first page count, hidden contacts count only for team admins and owners,
+and an item matching several ways appears once. Files lists non-task documents
+plus attachments of emails with the company's domains. Tasks is the Tasks list
+with that scope, grouping, and Load more; `Search tasks` matches task names
+within the scope (not content). Its `New task` composer pre-fills the company.
+Calls includes calls linked automatically from their participants and calls
+whose thread mentions the company. The side panel keeps Properties and Sharing,
+and adds **References**: associated items of any type (documents, tasks,
+channel messages, email threads and calls with the property, events, chats,
+projects, and companies or contacts whose properties or Discussion name the
+company) as compact icon-and-name rows, paged as it scrolls. A channel message
+row opens its thread; a reply surfaces as its thread's row. A document
+Discussion message makes its document the item. Initiatives and database rows
+are not listed.
+When a record list fails to refresh (for example, the record became
+inaccessible), it replaces its rows with `Couldn't load this list.` and
+`Retry` reloads it; a failed later page keeps the rows and shows `Couldn't
+load more.`
+A contact has the same layout with `Overview`, `Emails`, `Files`, `Tasks` and
+`Calls`: Overview pills show the email, the company (opens it) and `Last
+interacted`, followed by the contact's Pipelines cards. Its Files, Tasks, Calls,
+and References show items associated with the contact itself (its `Contacts`
+property or an @mention of it), not everything associated with its company;
+Files also includes attachments of emails with its address. Tasks created from a
+contact also reference its company. The side panel keeps Sharing (admins only)
+and adds References.
+
+Mentioning a company or contact with `@` in a document or task records it as a
+reference of that record (removing the chip removes it) without sharing the
+document, inviting anyone, or notifying the contact; channel and Discussion
+messages record their CRM mentions when sent or edited. Open record lists
+refresh after a CRM mention or a `Companies`/`Contacts` property changes. To
+verify, mention a contact in a document, then check the contact's and its
+company's References and Files without reloading; remove the chip and confirm it
+drops out.
+
+Company and contact pages have a **Discussion** section built from the same
+message conversation as a document's Discussion: threaded replies, reactions,
+attachments, and edit/delete from the message menu. `@` suggests the team's
+members and agents. A message's copied link is the standalone record URL
+with `comment_id`; opening it, or a CRM discussion notification, scrolls to and
+highlights that message. Deleting a thread's first comment deletes the thread.
+
+Company selection actions **Set owner** and **Set revenue** remain available
+while team deal-stage definitions are loading. **Set stage** waits for the active
+team definition rather than opening an editor with system defaults. Check both
+the entity actions menu and command menu with stage requests delayed; cancel the
+editors without changing hosted data.
+
+`Collapse CRM sidebar` persists across visits; `Expand CRM sidebar` restores it.
+At narrow widths, `Show CRM navigation` opens the same navigation in a menu.
+The sidebar's Records and Lists sections can also collapse independently.
+
+**Pipelines** in the CRM sidebar hold company or contact entries in the shared
+records editor. They have their own identity, ownership and sharing; their
+storage does not appear as a separate database in navigation.
+**New pipeline** is disabled until the team's CRM is enabled. For a new team,
+use **Open CRM settings** in the empty state to enable CRM, then return to
+Customers to create a pipeline. Verify this with a newly created team as well as
+an existing CRM-enabled team.
+Choose **New pipeline**, enter a name in the dialog's first row, pick
+**Companies** (the default) or **Contacts** from the record-type pill, and tick
+**Share with my team** to share it (unticked keeps it private). **Create
+pipeline** or Command-Enter submits. Creating opens the pipeline's
+editable table. Team members can edit shared pipelines; the creator owns them.
+Anyone who can edit a pipeline can share it from the standard **Share** dialog.
+Pick people or channels and an access level, and the message carries the pipeline.
+The **People** list changes or removes their access. A teammate who receives a private
+pipeline sees it in their Customers sidebar. Only the owner sees **Team access**:
+choose **Edit** to share with the team or **None** to make the pipeline private.
+Viewers see only **Copy Link**. **Copy Link** copies a CRM link that opens this pipeline for
+anyone who has access; pasted into an editor it becomes a pipeline mention (see
+[CRM pipeline mentions](documents.md#crm-pipeline-mentions)). On mobile, team
+access is in the **Team** tab.
+
+The first column is a required company/contact reference. Clicking a filled
+reference, or pressing Enter on it, opens that company or contact; on desktop it
+opens in place with the pipeline name in its breadcrumb (choose it to return),
+and on mobile in its own view. The same applies to the reference shown as a
+board card's or record panel's title. To change which record a row references,
+focus the cell and press F2 or start typing; an empty reference cell opens the
+picker on click. The same company or contact can occur in multiple rows in a
+pipeline and can also belong to other pipelines. Each row has its own field
+values; **Duplicate** copies a row into a new entry referencing the same company or contact. The reference column
+can be renamed but cannot be removed or changed to another type. Stage, Owner,
+and Revenue are independent pipeline fields; editing them does not modify the
+company's CRM fields. Use **Add column** or a column header's menu to customize
+columns. Pipeline Stage options initially copy the team's current deal stages. Open
+pipelines refresh other editors' changes periodically; a local edit refreshes
+immediately after saving.
+A pipeline page uses the database page's styling with one table and no table
+tabs. Its header shows the name, edited in place by editors, a **Pipeline
+actions** menu (**Rename**; **Trash pipeline** for the owner) and **Share**. The
+toolbar below has **All records**, the pipeline's stored views and **New view**
+(Table or Board), plus Group by (boards), Filter and Sort, then **Add company**
+or **Add contact** (by the pipeline's record type) for editors, which starts a
+row whose reference cell picks the record.
+Stored views are everyone's and are written through the pipeline, so changing one
+changes it for all viewers; All records is each viewer's own. A board can move a
+card to another group from its card menu or by dragging, which sets the row's
+grouping cell. Card order within a group is not read back after a reload, and
+views cannot be reordered yet. The selected view is remembered per pipeline.
+**Trash pipeline** removes its table from navigation without deleting the linked
+companies or contacts, then returns to Companies.
+
+CRM lists are currently disabled by `enableCrmLists` (default `false`). The sidebar
+Lists section, list editor, and company membership controls only mount when enabled.
+Existing list data is preserved; a restored list view returns to All companies while
+disabled. Saved filter views remain available.
+
+When enabled, lists are personal, team-scoped collections of explicit company IDs, persisted through
+saved-view storage separately from saved filter views. `New list` opens a name and
+company picker; `Edit list` changes membership or deletes the collection. An empty list
+must not show every company. The picker browses up to 500 recent companies. Canceling
+never saves the draft. Saving only closes the dialog after the server succeeds.
+
+Company detail pages show a **Lists** section in the right panel, with current
+personal list memberships as chips. **Manage lists** expands a searchable checkbox
+picker. Checking or unchecking saves immediately and refreshes the CRM sidebar's
+membership counts. Changes are disabled while saving; failures show an inline retry
+message and keep the last saved membership. With no lists, create one in the CRM sidebar.
+
+`New company` uses the existing creation dialog. `Import` previews a CSV with `name`
+and `domain` columns (1–100 rows, at most 1 MB). The explicit Import button writes the
+previewed companies. Partial failures retain only failed rows for retry. Use preview
+and cancel for browser checks against hosted dev data. `CRM settings` opens the existing
+settings panel. Requires a team with CRM enabled.
+
+`Export` opens options for companies. Choose Current view
+(respects filters/search) or All records across views (each visible record once), then
+select CSV columns. Company exports include Stage, Owner, Revenue and optional custom
+properties. `Prepare export` fetches every page and shows a count and three-row preview;
+it does not download. `Download CSV` saves the prepared snapshot using the selected
+columns. Changing scope requires preparing again. Cancel stops preparation. CSV uses UTF-8,
+quoted fields, original date timestamps and spreadsheet formula escaping.
diff --git a/docs/AGENT_GUIDE/databases.md b/docs/agent-guide/databases.md
similarity index 99%
rename from docs/AGENT_GUIDE/databases.md
rename to docs/agent-guide/databases.md
index da3d7337f5..3464c0ac95 100644
--- a/docs/AGENT_GUIDE/databases.md
+++ b/docs/agent-guide/databases.md
@@ -92,7 +92,7 @@ to switch between **None** (private) and **Edit** (team). A pipeline's primary
company/contact reference is required. The same company or contact can appear
in multiple independent rows, including through the row menu's **Duplicate** action.
The reference column and table are protected against removal or type changes. See
-[Customers (CRM)](surfaces.md#customers-crm--appcomponentcompanies) for the flow.
+[Customers (CRM)](crm.md#customers-crm--appcomponentcompanies) for the flow.
Teams migrated from the legacy CRM have a team-shared **Sales** pipeline with
their visible companies and copied Stage, Owner and Revenue values, including
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/agent-guide/documents.md
similarity index 100%
rename from docs/AGENT_GUIDE/documents.md
rename to docs/agent-guide/documents.md
diff --git a/docs/agent-guide/email.md b/docs/agent-guide/email.md
new file mode 100644
index 0000000000..a41ca8f058
--- /dev/null
+++ b/docs/agent-guide/email.md
@@ -0,0 +1,679 @@
+# Email
+
+## Email reminder delivery
+
+An email snooze returns its original conversation to the inbox and adds a
+notification to that email row in Home. It has no separate reminder toast or
+detail view. See [Email reminders](reminders.md#delivery-and-undo).
+
+## Email — `/app/component/mail`
+
+Email's Tags sidebar uses the [nested tag tree](tasks.md#nested-sidebar-tags).
+Carets and folder-only parents expand branches; actual tags select their exact ID
+and switch the mailbox to All. Parent selection does not include descendant tags.
+Unlike Calls, it lists only personal tags; team-shared tags are hidden,
+and its `New tag` action creates a personal tag with no Team sharing option.
+
+Full email client. Tabs: `Signal` / `Noise` / `Favorites` / `Sent` / `Scheduled` / `Calendar` / `Drafts` / `Shared` /
+`Archived` / `All`. Compose via the `Email` button (or `Create` → `Email E`). On a fresh local user it
+shows `Connect your email` (Gmail/Google Workspace OAuth) — most functionality needs a
+connected account. Search is `Ctrl+F` within the surface.
+
+Sender names use each message's `From` display name, falling back to the
+address-book name when it is absent. Multiple people or bots sending through
+one address (such as GitHub notifications) retain distinct names within and
+across threads. Verify in Mail and in Search with the Email filter and an empty
+query: load more threads from the same address, then check that existing row
+names and their hover cards do not change. Repeat with a text query to exercise
+the search-service results.
+
+`Favorites`, directly below Noise, lists starred Macro emails across Signal,
+Noise, and archived mail. It respects the selected inboxes and filters; search
+within the tab is also restricted to favorites. Removing a star removes the row
+from this view. The tab persists across reloads. With `enable-graphql-soup` on,
+the paginated GraphQL Soup query uses `favoritesOnly: true`. With the flag off,
+REST Soup uses `favorites_only: true`. Starring changes membership without
+changing the list query. Text search still resolves favorite IDs for the search
+service. An empty favorites list shows `No favorite emails`.
+
+`Archived`, directly before All, lists your own archived (Mail Done) threads: the
+All mailbox with Done applied, excluding threads teammates shared with you. It
+respects the selected inboxes and filters. The search service cannot filter
+archive state, so search within the tab keeps only archived hits on the client.
+Rows offer **Unarchive email**;
+unarchiving removes the row at once. The tab persists across reloads. An empty
+list shows `No archived email`.
+
+On desktop, a favorited email keeps a filled, muted star just before its
+timestamp. Other rows reserve only that small star slot. Hovering reveals
+**Star email** (Macro favorites), **Archive email** (Mark Done, with Undo), and
+**Open command menu** for that email. The star stays in place; archive and commands
+replace the timestamp within its existing space. Archived rows offer
+**Unarchive email**; the archive control is disabled in tabs that do not support
+Mark Done. The icons also appear when a button receives keyboard focus. Clicking
+an icon neither opens the thread nor applies the action to other selected rows.
+Touch devices retain the swipe actions.
+Search results use the same reserved column, with actions aligned to the first
+line; snippets, highlighted matches, and expanded hits remain unobstructed.
+
+When switching email tabs or inboxes, the list shows current-query cached results
+or a scoped `Loading email` spinner until they arrive—not the previous tab's rows
+under the new heading. Active searches also hide retained results and show loading
+while selected tag sets are pending. Background refreshes retain the current list. To check this,
+rapidly alternate Signal, Noise, and Sent, then change inboxes; a delayed cache or
+network read must not leave the old rows visible or expose their Load more action.
+
+Opening an email shows loading while its local draft identity and thread data
+resolve. Verify a cold open and switching directly between threads with delayed
+cache reads: neither should flash "Sorry, an unexpected error has occurred" or
+show the previous email. A failed load must still show its error and Retry action;
+reconciling an already-open offline draft must preserve its composer and text.
+If local cache initialization fails, ordinary server threads must still load
+through the session's uncached GraphQL client, including the thread being opened.
+In that fallback, leave a thread open and mark it Done/Not Done from its list:
+only the matching open thread refreshes through GraphQL after the committed archive
+mutation, including its loaded message pages. Mark Seen/Unread and generic Soup
+refreshes must not refetch open threads. Disabled/unmounted readers must not refetch.
+Also delay cache initialization failure until after the first identity lookup fails:
+an uncertain server route must then load and participate in archive refreshes,
+while a positively identified unsynced local draft must never be sent to the server.
+Keep already-resolved server aliases through that fallback. With the normalized
+cache active, the shared email record updates the thread without an extra network
+refresh. Neither path relies on REST thread-cache invalidation.
+
+If a saved inbox selection references an unlinked account, successfully loading
+linked accounts resets the filter to All inboxes while preserving an open or
+restored thread. Check this with a stale saved scope and a thread route, including
+when no linked accounts remain. Explicitly choosing another inbox or All inboxes
+still closes the thread.
+
+The new views reuse the legacy filter option rows and searchable submenus.
+Their triggers are icon-only buttons matching the surrounding view controls;
+Clear/Reset filters and the mobile Clear all action use destructive text styling.
+Both layouts show a small accent dot beside categories with active refinements;
+default All selections are not marked.
+Email Status and Done are single choices that close the menu; attachment filters
+stay open for multiple selections. Tags supports search, pins selected tags first
+on opening, and is omitted when no tags exist. **f** opens the filter menu.
+
+### Read state and trash
+
+In the Email view, Status filters discovery on the server **before pagination**,
+for both the mailbox list and service-backed search. With Unread selected, opening
+or marking an admitted row read keeps its position across refreshes. Separate
+lookups, bounded to 100 already-admitted thread IDs each, omit only the read filter;
+they still enforce the tab, inbox, other facets, and (for search) the search text.
+A snapshot bridges a pending lookup, but a confirmed non-match removes the row,
+so archive/trash cannot be resurrected by retention. Changing the search text,
+filters, tab, inbox, or user resets admission. Check that unread mail is discovered
+even after 100 newer read threads, then verify focus through Mark Read and refresh
+in both list and search, including with more than one loaded page.
+
+With GraphQL Soup enabled, **Mark read/unread** updates the normalized email row
+optimistically. Permanent server errors roll it back; retryable transport failures
+can leave the action in the durable queue. Mark unread sends only the thread ID;
+the server resolves that inbox's UNREAD label and returns the canonical thread
+(`__typename`, `id`, `isRead`) to reconcile the cache. The row should flip immediately
+even when the client labels cache is missing or stale—no label fetch precedes the
+optimistic update. Queued read/unread writes retain revalidation descriptors for
+active flat and grouped lists, including loaded continuation pages. Once replay
+commits (even after a reload), those queries refresh from the server; they should
+not refetch over the optimistic state merely because a write was queued. Trash
+and its Undo refresh mounted GraphQL lists after the server operation finishes.
+The GraphQL-disabled REST path is unchanged. With GraphQL enabled, archive-based
+Mark Done, Mark Not Done, and Undo/Redo use `setEmailThreadArchived`: `inboxVisible`
+updates optimistically in the normalized cache, and each reversal is a distinct
+ordered queue entry. The server resolves the thread's owning/delegated inbox;
+no client INBOX-label lookup is needed. Confirmed writes revalidate mounted lists,
+including continuation pages; queued writes retain those descriptors for replay
+without refetching over optimism. Callers preserve the queued disposition and
+skip REST/TanStack email invalidations as well, including Done/Undo batches and
+thread archive replay. Committed writes and failed non-queued batches still
+reconcile. Permanent failures roll back the failed intent.
+Check Signal/Noise removal and All's done indicator, then Undo/Redo, including an
+offline action followed by reconnect. Also wait for provider/metadata synchronization
+before Undo, and repeat after reloading: an archived received thread can lose its
+inbox-sorting timestamp but must still be unarchivable. Sent-only threads and
+unsent drafts cannot be unarchived; sent mail addressed back to its sender can.
+With GraphQL Soup enabled, bulk Mark Not Done settles per email: a rejected
+sent-only/draft thread stays done, while successful and durably queued siblings
+remain restored. Only accepted
+threads get their notifications restored. Notification or list-refresh failures
+warn without rolling back accepted unarchives. Verify mixed committed/queued/
+rejected selections, partial-success counts, and that a queued sibling prevents
+shared-list refetch even when notification restoration fails. GraphQL reversals
+rely on normalized writes and their durable revalidation, not an extra REST Soup
+refetch after rows settle. Verify the open-thread header too: with GraphQL enabled,
+Mark Not Done remains available for an archived thread whose inbox timestamp is
+missing; the server decides whether its received-message history allows restoration.
+The REST path retains its timestamp preflight, whole-batch handling, notification
+ordering, and existing cache reconciliation.
+For optimistic mutation interface changes, delay the network response and verify
+that only the affected row's read/done indicator changes, with scroll position and
+unrelated rows retained. Quickly reverse the action, then reject the first request:
+the later intent must remain visible. A stale refresh while either write is pending
+must not clear its optimistic state. A retryable failure should remain queued;
+a permanent failure should restore only the failed intent's fields.
+With two views of the same thread mounted, a read/unread or archive scalar
+change should update both existing query stores without a full query reread.
+Observers of unrelated fields should stay idle. Changes to links, record
+identity, or unsupported query projections still take the cache reread path;
+a subsequent scalar update must not cancel that pending structural refresh.
+
+The service retains both replica-backed Soup reads and a primary-backed email
+writer. Email mutations and their uncached reply reloads use the primary; ordinary
+GraphQL/REST lists, direct Soup lookups, and realtime Soup hydration use the replica.
+A mutation reply is fresh, but subsequent list refetches are eventually consistent
+and can still return replica-stale read/archive state. Test that boundary separately
+from mutation reply correctness. GraphQL application errors, including a failed
+post-commit reply load, release the queued mutation rather than retrying forever.
+Transport failures retain the existing retry policy. Draft recovery preserves local
+content and offers explicit Retry using the original handle. Deploy
+the backend schema containing `setEmailThreadArchived` before this client.
+Browser WASM and native cache builds must include the regenerated schema metadata;
+native offline archive support therefore requires a full app build, not just OTA.
+
+### Cached Mail filtering
+
+The per-query caches for email threads, channels, and native offline document
+context reopen closed IndexedDB connections. Verify a cached read and a subsequent
+write after closing the connection, then clear/logout during recovery: old-account
+entries must not return. Only transaction creation retries automatically; persistent
+storage failures still follow the existing cache fallback behavior.
+
+Performance check: switch Signal → All twice against a large synchronized cache.
+Dense local pages use bounded sort-index candidates rather than sorting the entire
+mailbox. Sparse filters and large timestamp ties retain the exact fallback plan.
+A filter result, row fragments, and final revision that agree must be accepted even
+when background hydration advanced past the revision observed before the request;
+that alone must not trigger another filter scan. Also verify local Load more,
+same-timestamp ordering, and pending archive/read changes.
+
+With GraphQL caching enabled (browser or native Tauri) and the email metadata backfill synchronized,
+All, Signal, Noise, Drafts, Sent, Calendar, and Shared support tab changes and new
+filter combinations while offline: account selection
+(including delegated inboxes), read/unread, and archive-based Done/Not Done. Mail Done
+means `inboxVisible = false`; it is **not** notification lifecycle state. Signal/Noise
+retain their Inbox scope, so archived mail is found in Archived (All + Done).
+
+A `Showing cached mail` notice identifies results over synchronized metadata, not a
+claim of complete mailbox coverage. These lists paginate locally beyond the first
+page without a server cursor. Filter, revision, or engine-generation changes restart
+the local page chain; online server results take over again when available. After
+reconnecting, `Load more` follows the same server page chain as the displayed rows,
+not a leftover local cursor. Account choices are cached in the viewer-scoped GraphQL catalog. Timestamp ordering and date
+headers use the selected Mail view's indexed timestamps, not a preview cached from
+another view. Drafts and Sent display their latest eligible message snapshot, even
+when a newer normal message is the ALL preview; no message bodies are needed.
+Sent also requires a canonical outbound timestamp. Trashed messages cannot supply
+any preview. Calendar uses the authoritative thread calendar-attachment flag.
+
+Shared requires a last-known thread grant through the viewer, a team, or an active
+channel, plus the existing Mail UI rule excluding viewer-owned threads. Merely
+having a different owner or a delegated inbox does not qualify. Shared metadata has
+its own full-scan backfill before body hydration. A successful complete scan marks
+old entries it did not return incomplete (not deleted); a failed or cancelled scan
+preserves last-known evidence. If concurrent cache changes invalidate the prior
+membership snapshot, hydration continues but that scan cannot revoke old evidence.
+Interrupted Shared scans restart at the beginning so
+scope reconciliation never mistakes a suffix for a full scan. Offline access is
+necessarily evaluated from the last synchronized grants.
+
+The lightweight metadata backfill runs before body hydration. Its refreshes scan all
+metadata: message-time watermarks alone miss archive/read changes on old threads.
+Filter availability therefore does not guarantee that opening every message body works offline. Missing
+projection proof is unknown, never false. Tag selections use cached property postings;
+attachment chips refine the cached rows on the client. Sender/recipient filters and
+non-created/updated sorts remain outside this local profile. Grouping and sort-selector
+coverage are separate from the filter-selection matrix. No cache-format wipe is required: Mail uses a separate versioned profile
+and a new backfill checkpoint, preserving existing queued work. Deploy the backend
+schema additions before the client: it selects canonical message eligibility/recency
+fields, body-free canonical preview references, and viewer-relative share facts.
+The `soup-mail-v3` property-aware profile and new backfill checkpoint rebuild Mail proof without
+changing the persisted mutation queue format. Native Tauri maintains the same
+predicate projections and revision-bound local page contract as the browser.
+Checkpoint v14 restarts older scans to populate property-aware indexes without wiping
+queued work. A background network failure does not hide a usable current-query
+cached Mail page; server-reported GraphQL errors still surface.
+
+Native filter evaluation requires a full native app update, not just an OTA
+frontend update. Older binaries retain their previous unsupported-filter fallback
+while Shared Mail network backfill continues. The temporary compatibility guard
+can be removed once a full native release includes the filter command and OTA
+delivery excludes older binaries.
+
+For Linux desktop automation, see the [native E2E guide](../../apps/web/tests/native/README.md).
+The first scenario covers Signal → Noise → All after disconnecting both native
+HTTP and WebSockets. iOS shares the native cache code but is not yet covered by
+that driver.
+
+In the new Email view, ordinary row activation opens the thread inside
+`/app/component/mail`; the view breadcrumb (for example Signal) has a hover
+background and returns to the filtered list. Pressing `Escape` in the open thread
+with focus outside any input does the same once there is nothing left to unwind
+(an open reply, an expanded body, or a focused message each take one `Escape`
+first); the list keeps the row you came from focused. The inline header uses the existing
+email title menu: open the menu button beside the subject for **Ask AI**, **Create a
+Task**, and the other thread actions. On desktop, **Mark as unread**, **Mark done**,
+and **Previous item** / **Next item** sit at the right of that header. The arrows
+follow the current filtered list and disable at its ends. Mark done advances in
+that list. Mark as unread (in the header or title menu) returns to the originating
+list with its tab, inbox, and filters preserved. Mark as not done and Mark as read
+stay on the current thread.
+Opening a saved draft from **Drafts** keeps the subject breadcrumb, title menu,
+and applicable header controls visible above the composer. Verify these remain
+available when returning to Drafts and reopening the draft.
+**Delete** in the title menu moves the thread to Trash and returns to the same
+filtered list. Its toast offers **Undo** to restore the email.
+Verify that opening the title menu, returning to the list, and reopening a thread
+preserve working menu actions and header controls. Repeatedly navigate forward
+and backward, including after returning to the list: the subject and email body
+should remain visible without reloading.
+Shift-click opens a standalone split at `/app/email/<thread-id>`, which remains
+the destination for direct links and legacy surfaces. Click a message header to
+expand or collapse it; `Show N hidden messages` reveals the collapsed middle of
+a longer conversation. A standalone link with
+`?email_message_id=<message-id>` loads older pages as needed, expands the target,
+scrolls it into view, and briefly highlights it. For navigation regressions,
+exercise both a recent message and one outside the first page. Open another
+target while loading or highlighting: the previous request must not scroll the
+new thread or clear its highlight. Closing the split cancels pending positioning.
+The load gate and message body share one live thread source in both hosts. Cached
+body rendering should not wait for a second thread fetch, optional References,
+or inbox metadata. Inbox-dependent actions stay gated while ownership is unknown;
+explicit inbox IDs must never silently route to primary while links are loading.
+Background refreshes and older-message loading still update the same thread.
+Verify with API traffic delayed and with previously opened bodies offline.
+Collapsed thread cards use a compact text snippet; expanding mounts the message
+body and its attachments. On phones, messages form flat rows with horizontal
+separators and 16px side gutters; collapsed previews show one line. Desktop
+keeps rounded cards matching the chat composer: soft shadows in light mode,
+the same subtle 3D rim in dark mode, and a faint hover tint. Desktop selection
+does not add an accent-colored ring; keyboard focus has a neutral outline.
+Replies appear inline on desktop and in a composer drawer on touch devices.
+Desktop draft bodies and app-controlled message text use 15px, matching channels.
+HTML messages with preserved sender typography retain their explicit sizes.
+Desktop reply actions sit together at the bottom right: discard, attach, schedule,
+then Send, with circular hover backgrounds inside the card's 16px padding.
+Standalone compose uses one right-aligned row inside its 16px content padding:
+delete, attach, format, schedule, and send. Touch compose uses its header toolbar.
+`R` and `Alt+R` (`Option+R` on macOS) open reply-all for the selected message,
+or the latest message when none is selected. `F` opens a forward and focuses To.
+While an editable field is focused, Escape is handled by that field before the
+close-reply shortcut.
+An edited reply remains a draft when navigating away and returning. Standalone
+compose also flushes pending edits when leaving through app navigation. Switch
+views immediately after typing, before the 500 ms autosave debounce: the old
+thread must close, further navigation must work, and reopening must retain the
+last edit. Repeat with an existing draft and a new reply. During
+mobile Save Draft navigation, a failed local flush is reported and keeps the
+back menu and editor open with their contents intact. After another edit saves
+successfully, Save Draft can leave the composer. Reopen an existing reply after
+clearing its body: the saved empty body must not restore the original quoted HTML.
+During send or discard, its sender and scheduling controls cannot change the operation.
+Attachments that can be opened are buttons named by their filename; Tab to one
+and press Enter or Space. Removal is a separate button named `Remove <filename>`.
+Removing a forwarded file keeps the received original.
+When checking draft autosave, edit the body of a draft with uploaded or forwarded
+attachments, wait for the save, and reopen it; the attachments should remain visible.
+AI email tool drafts persist body-only edits; changing recipients or the subject
+is not required to save the body.
+
+With GraphQL draft queuing enabled, working copies and pending attachment bytes
+are saved on this device independently of the mutation queue. A failed server
+save must leave the draft discoverable in **Drafts** (including grouped views)
+and in its reply thread. **Draft saved** sits immediately left of the desktop
+delete button after editing pauses for 500 ms and the latest local save completes,
+then fades out after two seconds, including offline saves. Resuming typing hides
+it immediately; another pause and saved version restart the timer. Background
+sync updates do not. Failures replace it with persistent **Retry** in the same place; hover for details.
+Clicking Send must not show the badge for its preparatory draft save, including
+when delivery fails. Later edits can show it again after the usual pause.
+Verify the label does not cycle through saving/syncing text on each edit and
+that retry remains accessible beside the actions on mobile. Editing while failed
+continues saving locally without repeatedly submitting the rejected request.
+Local draft storage reopens unexpectedly closed IndexedDB connections. If creating
+a transaction fails because the connection is closing, it retries once before
+running any writes. Verify by closing the draft database connection, then editing:
+the latest content must persist locally and server autosave must continue without
+reloading. Repeat across background/resume on an iPhone. A transaction that has
+already started is never automatically replayed. Persistent failures still block
+server autosave; copy unsaved content before restarting. Storage failures and
+recovery report current page visibility and network state without draft content.
+
+Repeated local-save failures show one persistent warning per composer; recovery
+or closing that composer dismisses it. A later failure shows a new warning.
+Retry preserves the original draft handle. An already-sent rejection drops the
+local copy rather than recreating the sent message. The REST compose path keeps
+its existing behavior.
+
+Native draft recovery requires a full app update containing queue inspection and
+durable mutation metadata support. An older app receiving an OTA bundle shows
+**Macro update required** and uses the existing uncached fallback. Its old queue
+must remain intact, with no new claims or queued writes, until the native update.
+When the cache becomes unavailable, draft saves and discards must not bypass its
+preserved queue through GraphQL or REST fallback. Local editing stays durable;
+reload or update the app to resume server sync. Verify this after a native
+upgrade-required error and a worker initialization failure; ordinary reads still work.
+
+For recovery verification, reject a draft save with a GraphQL error (including
+legacy `retryable: true` metadata), then perform an unrelated queued action: the
+failed save must release the queue. Reload and reopen the draft; verify subject,
+recipients, body, and pending file contents. Retry and check that exactly one
+server draft exists. If per-mutation recovery preparation fails or times out,
+the mutation must fail and release the queue too, including legacy drafts that
+have not been copied into recovery storage. Existing local working copies remain;
+an unmigrated legacy edit can be lost if the queue held its only durable copy.
+Verify that an unrelated queued action still completes in both cases.
+Repeat with two tabs, a save response arriving after a newer
+edit, an attachment upload completing during another local save, and Discard
+while an attachment snapshot is still being saved. A snapshot based on an older
+local revision must fail without replacing newer content or files, including
+when another tab saves first. Reopen the draft to use the latest version.
+A completed discard must not resurrect on reload. A clean,
+fully synchronized local copy must not hide newer server edits or sent state.
+While online, create a disposable reply, wait for its server identity, discard
+it, then leave and reopen the thread and reload. Its local body and attachment
+bytes must be gone and the server draft must stay deleted. Repeat with a second
+tab holding the same draft under its server ID: a delayed save from that tab must
+not recreate the discarded working copy. Repeat after Undo revives the draft:
+the old tab must not overwrite the restored copy even when revisions match.
+A newly composed reply still saves.
+
+For offline replies, use a received email so recipients come from its contacts.
+Type a reply, leave the thread, and reopen it while still offline; repeat both
+immediately after typing and after waiting for autosave. The reply body and
+recipients must remain, including after reload. Delay local draft discovery while
+the cached thread is available: the reply editor must wait for the recovered
+draft before it can accept edits. When several local replies target the same
+message, reopen the most recently edited draft. This exercises the real form-to-
+storage boundary as well as queued saves; plain hand-built save inputs alone
+do not cover it.
+
+Explicit sign-out warns before removing unsynchronized local drafts and files.
+Cancel must retain them; confirm must clear them and fence in-flight work so the
+next account cannot see them. If local storage cannot be inspected, sign-out must
+still offer a warning and a way to continue. Do not verify this by deleting real
+user drafts; use disposable drafts in an isolated test session.
+The three-dot button beneath a body reveals quoted content and a trimmed
+signature. Plaintext and Macro Markdown use the existing Markdown renderer;
+Macro Markdown messages retain document mentions. Ordinary HTML bodies use an
+open shadow root: Playwright text locators can reach them, but a card's ordinary
+`innerText` or `querySelector` does not traverse that root.
+
+Sending a reply from an inbox thread marks that thread done but stays on it;
+only the explicit Mark done action opens the next email.
+Sending a message shows it in the open thread immediately, while delivery is
+still pending. It stays visible until the thread refresh confirms it, with no
+duplicate message. Failed delivery removes that message and restores the reply
+draft; a successful Undo Send removes it and reopens the draft. This temporary
+thread display uses the existing REST delivery path.
+Sending must leave the new message's reply composer closed. After delivery,
+focus belongs to the sent message card in the same thread pane, even while
+the thread refresh is still pending. Replying again requires clicking Reply
+or using a reply shortcut.
+
+After a successful send, the `Email sent` notice offers `Undo`. Undo restores the
+sent envelope and editable content, including when the reply used another inbox;
+a slow background refresh must not keep the restored editor disabled. A rejected
+send reports failure and restores its original reply editor if it is still mounted.
+A failure from an older, unmounted editor must not overwrite a newer edited reply.
+A presentation or refresh error after successful delivery is not a reason to send
+again. After the undo window and provider acceptance, send finalization supplies
+any missing delivery timestamp before publishing the realtime update. The cached
+Sent list must therefore admit the message without waiting for Gmail inbox sync
+or an online visit to Sent. Verify by sending from another Mail tab, receiving the
+final sent update, then switching offline and opening Sent. Existing provider
+timestamps and timestamps from repeated finalization remain unchanged; an unsent
+or cancelled draft must not acquire Sent membership.
+
+Send and schedule are refused with a notice while the device is offline, while a
+draft is still syncing (its save was accepted locally but not yet confirmed by the
+server; retry after a moment), or while an attachment has no completed upload. The
+composer keeps its content in each case. Attachments cannot be added while
+offline: a blocking notice explains and nothing is attached.
+For a new standalone email, a failed REST draft save is best-effort: Send can
+still proceed without a draft ID when no save was queued and no attachment is
+waiting to upload. A server rejection blocks sending even an existing draft.
+GraphQL draft saves automatically retry only network failures. GraphQL errors,
+including internal, invalid, and unauthorized errors, fail the mutation and
+release the queue. The local working copy offers explicit Retry; Send stays
+blocked until a save is confirmed.
+A successful save response with an invalid cache identity binding still commits
+its normalizable server data and reports a cache diagnostic without replaying
+the mutation or asking the user to save again. If that response also cannot be
+normalized, the attempt stops retrying and reports a permanent cache failure.
+If a queued GraphQL save is permanently rejected after reconnect, the draft status
+offers **Retry** using the original draft handle and latest locally saved content.
+Further typing saves locally without retrying the rejected write. Verify that
+pending attachment bytes survive reopening and that a reply stays in its
+conversation.
+An already-sent rejection after reconnect follows the same path as an immediate
+already-sent response: announce that the email or reply was sent, clear the local
+composer, and cancel pending autosave. It must never offer Retry for that draft.
+Verify this in standalone and reply composers, including a queued edit awaiting
+its debounce and a failure racing the first identity read. A settlement for a
+previous or different draft must not clear the current editor.
+Repeat with the composer closed before reconnect: terminal queue failures must
+refresh the saved thread and list queries without requiring an open editor, so
+an already-sent draft does not remain in Drafts solely because nobody observed it.
+With cached inbox metadata available before viewer information loads, saving a
+new offline draft must still create its Mail thread. The selected inbox supplies
+the owner, including delegated inboxes. If that account metadata is unavailable,
+the save must fail before queueing; retain the editor content for a later retry.
+Test this with a previously saved draft as well as a new one: a queued edit must
+block Send and scheduling until a save commits. Reopening a cached draft while
+offline must retain its uploaded attachments and confirmed scheduled time.
+Open a reply draft while its durable identity read is still pending: REST lifecycle
+reads and attachment actions must wait for confirmation. Editing keeps the seed ID
+as a handle; a committed cache read or save unlocks server-only actions. A failed
+identity read must not mark a queued draft committed. Verify an autosave failure
+shows one notice in both standalone and reply composers. If the live mail transport
+switches to GraphQL while the editor is open, queued saves must still adopt their server
+identity after settlement without replacing the editor's current text.
+
+
+With the persistent GraphQL Email cache enabled, a new standalone draft saved
+offline appears immediately in Drafts and the other matching Mail tabs, including
+date-grouped lists. A draft changes a conversation's preview, read state, and sort
+time according to that tab; discarding it restores the remaining conversation's
+metadata. `Showing cached mail` still means only synchronized and locally created
+items are available.
+
+Verify the durable lifecycle: create a standalone draft offline, enter recipients,
+subject and body, close the composer, then restart while still offline. Open it
+from Drafts and confirm its content and sending inbox; edit it again. Reconnect
+and check that exactly one draft remains and the open editor keeps any new text.
+On a cold app start, reopen a local draft thread before another GraphQL query has
+initialized the cache. Its subscription must observe settlement and adopt the
+server ID. If its identity read fails, it must remain cache-only until a later
+cache event resolves it; never send the unresolved handle to the server.
+Keep a reopened offline draft open while reconnecting: the composer must remain
+mounted when the local thread handle resolves to its server ID. After syncing,
+reopen the original local thread URL and confirm the composer still loads; then
+open a different thread and confirm the previous draft is not shown there.
+Reply from a different sending inbox, save, and reopen the original conversation:
+its original messages must remain there even if the reply belongs to a new thread.
+Repeat after changing the sender on a saved reply; neither conversation may become
+an alias for the other.
+Throttle the next email's response while navigating within the inline detail:
+the previous subject and composer must disappear during loading, and the new
+thread must not be marked read using the previous thread's sending inbox.
+Make multiple edits while offline, reconnect, wait for syncing to finish, then
+send. Repeat after refreshing with queued edits: the first attempted save must
+recover its server identity and let newer saves complete, rather than leaving
+Send permanently blocked by "Draft still syncing".
+After restarting offline, reconnect and visit Signal and Drafts. The queued draft
+must stay visible when the first server list arrives, including in date-grouped
+views, until its save settles; it must not briefly appear and then disappear.
+Repeat with discard before reconnect, including a save that was already attempted
+before connectivity dropped. The discarded draft must stay absent after restart
+and reconnect. Opening through an older local thread link must reach the same
+server thread after synchronization. Repeat with an existing reply and confirm
+that other messages, attachments, and the Sent preview remain intact.
+
+With GraphQL Mail enabled, discarding the last draft in a thread must remove the
+thread from every local Mail view, including after queued replay. Discarding a
+standalone draft from its composer returns to the previous list after deletion
+is accepted, including offline; a failed deletion keeps the composer open.
+Check both the toolbar trash button and the mobile Delete Draft action.
+In Email's inline detail, deletion closes the detail and preserves the current
+mail tab and filters; it must not navigate split history to an older composer.
+Discarding a reply draft must preserve the remaining conversation. A previously
+cached thread that the server no longer has must leave the lists after opening it or receiving
+a 404 while changing its labels; a cached record must not override the server's
+not-found response. Check the same behavior after REST discard. Offline/network
+errors alone must never evict a cached thread.
+
+Choosing or clearing a send time is local preparation only. The composer remains
+editable and autosaves normally, shows **Scheduled send: ...** (the time and the
+viewer's timezone, e.g. **Sep 25 at 8:00 AM EDT**) in a bar attached
+below the composer (a strip along the bottom of the message card for replies), and
+performs no schedule, unschedule, archive, or delivery request. The bar's **Cancel**,
+at its far right, clears the local choice; the clock's tooltip reads **Schedule send
+time**. The clock and
+primary arrow remain icon-sized; the clock turns accent-colored when a time is
+selected, while the primary action's accessible name and tooltip change from
+**Send email** to **Schedule send**. Clicking it or pressing `Ctrl`/`Cmd`+`Enter
+runs the same validation and is the only initial scheduling commitment. A selected
+time that has passed is rejected at submission rather than falling back to immediate
+send. Touch toolbars keep the summary inline beside their icons, with Cancel next to
+the time; when space is tight, that summary truncates or wraps separately from the
+fixed icon group. The
+former picker-auto-commit behavior was a defect and must not be restored.
+
+Only a successful scheduling response or authoritative lifecycle reconciliation
+shows **Scheduled for ...**. Confirmed scheduled composers are content-locked.
+Picking another time creates a local proposal while the original remains active;
+the bar continues to show the original time plus the proposed replacement and
+explains that the original remains active. **Update schedule** commits the proposal.
+Clearing that proposal does not cancel the original. **Cancel schedule** is a
+separate explicit action, and only its
+confirmed success returns the message to an editable draft. Failed schedule,
+update, or cancel requests retain the user's local intent and last authoritative
+time, and never fall through to immediate Send. At narrow split widths the bar's
+label truncates while Cancel stays at its far edge; the bar never covers discard,
+attachment, formatting, the clock, or the primary action. Reply recipients
+cannot be edited or dragged during a confirmed schedule or active delivery mutation.
+
+When verifying, use an intercepted or isolated delivery fixture: choose a time,
+confirm that the editable **Scheduled send** preview makes zero delivery calls, then use
+the primary button and `Ctrl`/`Cmd`+`Enter separately to confirm exactly one schedule
+call. Reopen a confirmed schedule to exercise proposal/update and explicit cancel.
+If a later lifecycle refresh fails, the confirmed result remains in place; stale
+observations must not undo it or create a recovery draft after a failed inbox move.
+Reconciliation resumes when a fresh poll or event-driven read succeeds.
+If scheduling succeeds but marking the thread done fails, the email remains
+scheduled and a notice explains the separate failure. Check the confirmed time
+before retrying; do not treat that notice as a failed schedule.
+Keep a scheduled composer open through its due time when verifying the flow. It
+reconciles on email events, tab focus/reconnect, cross-tab schedule changes, and a
+short due-time poll. Confirmed delivery closes or disables the old composer and
+stops autosave/delete against the sent ID. Text from an edit that raced delivery
+is preserved as a new unsent draft, never submitted with the sent message ID.
+Recovery re-uploads local attachment files and restores forwarded attachments.
+Remote-only draft attachments cannot be copied after the original draft is gone;
+their pills are removed and a notice asks you to attach those files again.
+
+A successful initial schedule shows an **Email scheduled** notice whose description
+gives the full send time, with **Undo** and **View message** on their own row below
+it; a rescheduled email
+shows **Email rescheduled** with **View message**. Undo cancels the captured draft in
+the captured inbox and restores its editable body, envelope, and attachments; it must
+not overwrite a newer reply. View message opens the scheduled thread, or scrolls an
+inline reply back into view.
+The Email view's **Scheduled** tab lists only server-confirmed scheduled drafts,
+soonest first across the selected inboxes, as ordinary email rows: the recipients,
+subject, and snippet, with a clock-and-time badge (for example **Tomorrow, 2:12
+PM**) in place of the row's date; hovering it gives the full date, time, and
+timezone.
+Opening a row previews its thread like any other email; cancel from the opened
+message's bar. Search and filters are hidden on this tab. Immediate-send undo-window
+queue rows are not scheduled drafts and must not appear.
+
+With the new app views enabled, mobile and tablet Email use a floating, horizontally
+scrolling row of those tabs, with `Open email filters` at the left. The rest of the
+view is the email list, which scrolls beneath the header and supports pull to refresh
+and swiping left to mark emails done in Signal and Noise. The filter button opens a
+glass bottom sheet for status, done, attachment, calendar and tag filters, plus an `Inbox`
+section when the user can pick one: `All inboxes` or a single address, never several.
+`Clear all` resets those filters and the inbox selection. Desktop keeps its sidebar,
+search field, filter menu and preview control. The sidebar lists the inboxes above the
+`New email` button and tabs as plain rows; clicking one shows only that inbox.
+`Connect another account` starts the add-inbox flow from its own row below the
+scrolling list. `New email` prefills From with the selected inbox, or the primary
+inbox when All inboxes is selected; reopening a draft keeps its saved sender.
+The From menu groups each connected inbox with its verified Gmail send-as aliases.
+Replies default to an address on the thread's own inbox: preserve an outgoing
+message's From, otherwise match To before Cc/Bcc (prefer an alias within each
+recipient group). A manual choice or saved draft takes precedence over late
+account refreshes. Reply-all excludes the inbox's primary address and its aliases.
+Aliases are scoped to their owning inbox, even when two inboxes share an address.
+A failed alias lookup for one inbox does not hide other inboxes' aliases. An
+invalid or unavailable selected alias is rejected on save/send, never silently
+replaced with the primary address.
+
+The sidebar and mobile inbox picker also list aliases beneath their inbox.
+Selecting one scopes mail to that inbox and the exact address in From/To/Cc/Bcc;
+search candidates are checked against the same GraphQL scope. Search and Reminders
+automatically advance nonmatching candidate pages until a match or exhaustion;
+while alias membership is loading, wait rather than treating it as an empty inbox.
+Refresh retries both search and alias membership. A failed retained membership
+lookup shows an error without discarding already-confirmed rows. If a saved alias
+disappears from the catalog, the primary address must not look selected; use
+`All inboxes` or choose an available address to clear that scope. Scheduled mail
+matches its saved sender. `All inboxes` clears both the inbox and alias selection,
+and the selection survives reloads. With one inbox **and aliases**, the All row
+and address pickers remain available. To check without sending real mail, open
+both pickers, select an alias, switch to the primary address, reopen a saved alias
+draft, and confirm the address remains unchanged. Alias discovery uses
+`MailAccounts`, draft saves use `saveEmailDraft`, and delivery uses
+`sendEmailMessage` in GraphQL; the existing undo-send window still applies.
+
+If an explicitly selected sending inbox is unavailable, Send reports
+`Unable to find linked email account. Select a sending inbox.` without delivering
+through another account. The From picker stays available as `Select sending inbox`,
+including when only one linked inbox remains. On mobile, expand `Cc/Bcc, From:`
+to choose the sender. Selecting an available inbox clears the error and allows
+sending; the picker never displays another inbox as selected before that choice.
+With no explicit selection, an unavailable primary still falls back to
+the first linked inbox.
+Sidebar rows, including `All inboxes`, replace their icon with an accent-colored checkmark when
+selected. With exactly one connected inbox and no aliases, only its address appears as the selected
+row, followed by `Connect another account`; there is no `All inboxes` row, title
+inbox dropdown, or inbox section in the mobile filter drawer. The inbox section shows up to four rows (including `All inboxes`), then
+scrolls independently without overscroll so the email tabs stay in place. With many
+accounts, scroll to the last inbox and check that selecting it updates the header filter.
+Selecting one inbox also shows `from [email address]` beside the list title.
+The address is a borderless ghost dropdown with the title's font weight and a
+consistent 14px font size at all widths; `from` is 12px. Both align to the title's baseline, without
+a tooltip or a separate clear button.
+Its single-select menu includes `All inboxes`, which clears the account selection
+and removes the filter. Saved selections from the old multi-select picker restore
+the first saved inbox; an empty saved selection restores All inboxes. Once linked
+accounts load successfully, a selected inbox that no longer exists resets to All
+inboxes. This runs for the whole email view, including on touch devices before
+the filter drawer opens. New email uses the originating email-view split even if another split
+is active. Verify that
+sidebar and menu selection stay in sync and that clearing preserves the current tab and other filters.
+Sidebar rows, `New`, and the panel's back, forward and close controls act on primary-button
+mousedown, so the selection changes before the click completes; a normal click
+still works. The sidebar ends with a collapsible `Tags` section (every personal and
+team tag, plus a `New tag` button): clicking a tag opens the `All` tab filtered to
+threads carrying it, clicking it again clears it, and choosing any tab clears it like
+the other filters.
+Rows have trailing selection checkmarks; Close filters dismisses the sheet
+without resetting its selections.
+
+## Email reminders
+
+Email's **Reminders** tab contains original conversations with active snoozes,
+ordered by return time. Each row's clock opens the shared reminder command menu;
+see [collection verification](reminders.md#email--reminders).
+
+Use **H** on one selected email or its open conversation, **Remind me** in the
+menu, or the header bell. These share the [email reminder menu](reminders.md#snooze-or-change-a-conversation).
+A confirmed save archives the thread and advances within the invoking list.
+Cancel and failed saves keep the current email. H on a pending snooze edits it;
+**Remove reminder** returns it to the inbox. Bare H in a reply or search field
+remains ordinary typing.
diff --git a/docs/agent-guide/files.md b/docs/agent-guide/files.md
new file mode 100644
index 0000000000..8ed5e18f27
--- /dev/null
+++ b/docs/agent-guide/files.md
@@ -0,0 +1,139 @@
+# Files
+
+## Files — `/app/component/documents`
+
+Tabs `Owned` / `Shared` / `Attachments` / `Folders` / `All`; `New` menu; rows show title,
+tags, updated time. Clicking a row opens the doc.
+
+Shared always excludes files owned by you. Selecting **Created by → Me** therefore
+returns no files; selecting Me together with another creator returns only that
+other creator's shared files. Clearing the creator selection restores all Shared
+results. This applies to restored filters and flat/grouped list requests—not
+just client-side row filtering. Cached inserts enforce the same rule before a
+refetch, including expanded groups and inactive cached Shared queries. Until
+viewer identity is available, document inserts into Shared are rejected.
+
+Files opens **Drive** using the same shell as Tasks, on desktop and touch
+devices alike.
+
+With `enable-databases` enabled, **My Files** includes owned databases and
+**Shared with me** includes databases shared by other owners. **All files**
+also includes accessible databases owned by others. **Search Drive** matches
+database names and **Filter → Type → Database** narrows the list. **New →
+Database** creates and opens a database from file tabs or the folder overview;
+it is absent inside a folder because databases have no folder membership yet.
+Database rows open their database block, including Enter and Open in new split.
+Use the database block's own actions to rename, share or trash it. The list
+omits unsupported duplicate, delete and move-to-folder actions for databases.
+Databases have no view history and do not appear in **Recent**, folder contents,
+or **Email attachments**. Creation time orders them when the selected sort has
+no corresponding database timestamp.
+
+On touch devices (phones and tablets), the Drive header is a scrollable pill
+strip — **Recent**, **My Files**, **Shared with me**, and **Folders** — with a
+leading filter-drawer button, like Tasks. Opening Files from the mobile dock
+starts on **Recent**; explicit tab and folder links keep their destination. The
+first pill is Recent. The drawer holds Sort (hidden on Recent, where the viewer's own
+edit order applies) and, on tab locations only, the same filter groups as the
+desktop **Filter** menu; active selections show a count badge on the trigger
+and a `Clear all` action in the drawer. The in-view `Search Drive` field, the
+Sort/Filter dropdowns, and the header New menu are desktop-only — search on
+touch uses the global search overlay and creation uses the dock's New button.
+The **Folders** pill opens the folder overview and stays highlighted inside
+any folder; tapping it from inside a folder returns to the overview, and
+selecting another pill leaves the folder tree. The sidebar contains `New file or folder`, `My Files`, `Recent`,
+`Shared with me`, collapsible Favorites, and a searchable folder hierarchy. Filter
+by tag from the **Filter** menu's Tags submenu; navigating to another tab or folder
+clears tag filters. A folder with no files matching the active tag
+shows the list's no-match state rather than `This folder is empty`.
+Drive omits split-history back/forward buttons in both wide and narrow layouts;
+the split close button remains available when multiple splits are open.
+Files opened in place from Drive show a return link labeled with their originating
+subview (such as `My Files`, `Recent`, or `Shared with me`) or folder name. The text-only
+label's font weight matches the file title. The link
+restores the originating Drive view.
+The `Drive` folder row opens the folder overview. Click a folder name to browse
+its contents in the main pane; its separate expand/collapse button reveals child
+folders without navigating. With GraphQL caching enabled and membership metadata
+hydrated, a never-visited folder can immediately show cached documents, chats,
+and subfolders for supported created/modified sorts and filters. Email remains
+server-owned: the full mixed GraphQL query still refreshes in the background,
+keeps loaded email rows, and owns pagination. A non-email projection with no visible
+rows, including when pending deletions hide every cached row, must not show
+`This folder is empty` while that initial request is pending or failed. Verify that
+loading and transport errors remain visible in this case; releasing a failed deletion
+restores cached rows without a refetch.
+Verify with a folder-specific GraphQL response delayed, then navigate to another
+folder before it completes; neither cached rows nor late results may leak across
+folders. The top bar keeps the full folder and file detail
+path in one breadcrumb trail. Folder containment uses `/` separators, while the
+transition to a file detail and nested detail navigation use the default `>`
+separator. Choosing a folder breadcrumb returns to that folder and clears newer
+file details. Empty folders show `This folder is empty` and a `Back to Drive`
+action that returns to the folder overview. Folder search retains matching
+descendants' ancestors and reveals their branches.
+
+`Search Drive` searches the current tab or folder overview; search within a folder
+is temporarily hidden, including its Cmd+F shortcut. The sidebar's folder-name
+search remains available. Right-click any Drive view, the Drive folder overview,
+or a folder at any depth for **Open in new split**, **Open in current split**, and
+**Open fullscreen** (when multiple splits are open). Opening a location in a new
+split clears search and filters in the destination, leaving the original split
+unchanged. Folder menus also offer Favorite/Unfavorite, Move to folder, Copy Link,
+and owner-only Rename and Delete.
+A folder's Share dialog, when the owner belongs to a team, has Team access
+(None, View, Comment, or Edit) without a Link sharing card or Link tab.
+Favorites use the same open actions and **Remove from favorites** menu as Tasks.
+The **Filter** menu uses the same controls as Tasks: **Type**, searchable **Tags**,
+and **Created by** submenus alongside **Files** for Default, All files, and Email
+attachments. Options within a group match any selected option; different groups
+combine to narrow the results. Created by is hidden while My Files
+is restricted to your own files. Recent offers only file-scope filtering.
+Hold Shift while selecting or deselecting Type options to keep the submenu open
+and combine several file types without reopening it. Desktop filter submenus allow a
+250 ms grace period when the mouse crosses the parent menu's padding; entering
+the submenu cancels the pending close. While the mouse heads toward an open
+submenu, including one that opens to the left, the categories it crosses on the
+way do not take over. A category the mouse moves to directly, or rests on for
+300 ms, opens in its place. Escape and outside clicks still dismiss immediately.
+`Sort files` offers modified, created, and viewed dates.
+Recent uses the viewer's own interaction order and does not offer a sort override.
+The New menu and drag/drop uploads target the selected folder. **New → Folder**
+and the launcher’s **Folder** action open the folder composer. Enter **Folder name**,
+choose **Add tags**, and stage files or nested folders in the large drop area
+(or use **Add files** / **Add folder**). Staged items can be removed before
+**Create Folder** (Cmd/Ctrl+Enter); nothing uploads until submission. Confirmation
+closes the composer immediately while creation and uploads finish in the background.
+On touch devices, the folder composer uses the same bottom drawer as Task, with
+the name and tags fields; the upload area and file/folder picker buttons are hidden.
+Expanding into a split keeps the draft. Creation preserves the current location
+and offers an **Open** toast action when finished. On failure, the toast’s **Retry**
+action restores the draft, retaining any created folder and only unsuccessful uploads. Close an unused draft
+without submitting when verifying against hosted dev data. In a folder
+opened in its own split or an inline preview, drop files from the computer onto
+the empty state or file list, then reopen the folder to verify membership.
+Check both one file and multiple files; the nested list drop target must retain
+the open folder as the upload destination.
+File rows retain
+selection and context menus; ordinary folder clicks and Enter browse inside Drive,
+while Markdown, code/CSV, image, video, PDF/DOCX, canvas, and unrecognized file
+clicks and Enter replace the list with a breadcrumbed detail. Those detail
+menus include Duplicate, Rename, Move to folder, and Delete. Code, CSV, image,
+video, canvas, PDF, DOCX, and unrecognized files also include Download. PDF
+details include Print, and DOCX files include Download DOCX. Markdown details
+use the document menu, which already includes Download. Spreadsheets keep the
+editor's Import and export menu for Excel and CSV downloads. Choose the current location
+breadcrumb to return to the list; choosing an ancestor file drops newer detail
+entries. Opening a list row or sidebar favorite pushes a new one-item detail path;
+sidebar favorites start from My Files instead of inheriting a previously selected
+folder. Only navigation originating inside a detail appends to that path. Browser
+Back and Forward restore the exact path saved with each entry, and renamed files
+update in mounted ancestor breadcrumbs without rewriting history. Cmd/Ctrl-clicking a
+row toggles selection; Shift-clicking a checkbox selects a range, and Shift+Enter
+opens the focused row in a new split. Cmd/Ctrl-clicking a row's folder link or
+search hit opens a new tab. Short filtered pages load more results automatically;
+a failed page shows a retry action instead of silently stopping. On touch, tabs
+switch via the header pills; on narrow desktop layouts the header keeps a plain
+title and navigation goes through the hamburger overlay. Location, search,
+filters, expanded folders, list focus, and scroll position are restored when
+returning from an opened file.
diff --git a/docs/AGENT_GUIDE/forms.md b/docs/agent-guide/forms.md
similarity index 100%
rename from docs/AGENT_GUIDE/forms.md
rename to docs/agent-guide/forms.md
diff --git a/docs/agent-guide/home.md b/docs/agent-guide/home.md
new file mode 100644
index 0000000000..6afe30f262
--- /dev/null
+++ b/docs/agent-guide/home.md
@@ -0,0 +1,216 @@
+# Home
+
+## Home (desktop) / Notifications (mobile) — `/app/home`
+
+Touch devices render the Inbox as **Notifications**: a floating Signal/Noise
+pill strip with a leading filter drawer (Status and Type), pull-to-refresh,
+and swipe-left to mark done. On touch, Signal is a pure notification feed — the viewer's own
+touched-by-me recents are not merged in; that merge is desktop Home's Signal
+only, so sent mail and AI chats without notifications appear only on desktop.
+
+On a cold launch, notification transport follows the GraphQL Soup flag reactively:
+if the flag arrives after REST starts, the GraphQL notification query must actually
+start too. Verify a reload with delayed flags retains non-email notifications once
+loading settles, including when the list itself uses REST (notified-at sorting).
+Email alone is not sufficient verification: its inbox membership does not require
+the global notification feed.
+
+Check live Home recency with two accounts: leave the recipient on Home without
+opening the conversation, then send a DM from the other account. The row should
+move into **Last few minutes** and show unread without reloading, including when
+notifications use GraphQL but Home's notified-at list uses REST. Read the DM,
+return to Home, and repeat; also check a row previously marked done and a thread
+reply. Delay the Home list response while allowing single-entity hydration to
+finish: hydration must not cancel the list refresh or leave an old notification
+timestamp. Older in-flight snapshots must not move the delivered row backward.
+Also test a stale response that entirely omits a just-restored, previously done
+row: the row must stay visible. Marking it done again must override that restore,
+and other filter scopes must not inherit the retained membership.
+
+GraphQL-attached notification rows share the global feed's local seen/done
+overrides: Mark Done and Undo reflect local intent without waiting for an older
+cached notification snapshot to be replaced. These display overrides do not turn
+incomplete predicate-index facts into authoritative membership evidence.
+
+On desktop with the new app views enabled, Home defaults to a Signal feed merging
+notifications with Activity's `touched_by_me` recents, including sent emails and
+AI chats. Recent emails must be classified as Signal by the server; touching a
+Noise email must not bring it into Home, including through local search. Verify
+that a recently viewed Noise email stays absent while a Signal email and recent
+chat remain visible, and that loading older rows still works through pages of
+Noise-only email activity. Each entity appears once, ordered by its latest
+notification or own action. On desktop, the funnel button to the right of **Home**
+opens **Filter Home**.
+
+With the GraphQL Soup flag on, desktop Signal reads
+the server work feed (`user.workFeed` plus the `workFeedUpdates` subscription)
+instead of merging sources in the browser; Noise, search, and touch devices keep
+the merged feed. Verify these against a backend that serves the work feed: a
+document you edited with no notifications appears read and offers no **Mark Done**.
+**Mark Done** clears a row's notifications (and archives an inbox email): a row
+that is only notifications leaves and stays gone after a reload, while a row you
+also worked on stays, read, at the time of your own work. **Undo** brings a done
+row back in place. A new comment on a months-old document appears at the top. With
+two sessions of the same account, marking a row done in one removes it from the
+other without reloading. A channel thread and its channel remain separate rows, and
+completing the channel leaves the thread.
+The menu shares the legacy compact submenus: **Status** offers **Unread**, **Read**,
+and **All** as single-select radio items with a checkmark on the right of the selected
+option, and **Type** contains the entity checkboxes. Status closes the menu
+after selection; type selections leave it open. Press **f** to open the menu.
+Entity type checkboxes start checked. Unchecking **Email** hides received
+and sent mail. **Channels** controls
+both channels and reply threads; **Chats** and **Agents** have separate toggles.
+Unchecking every type shows an empty feed. **Reset filters** shows every type and
+both read states again. A badge counts hidden types plus an active status filter.
+Read status and type selections persist.
+There are no desktop Signal/Noise tabs. A **Home** heading
+labels the top left of the block, matching the **Email**, **Tasks**, **Chat**, and
+**Agents** sidebar headings. The full-width **New chat** plus pill below the heading clears the preview and returns to the Home
+starting pane; it does not create a chat. Email and Tasks have matching top pills
+for **New email** and **New task**.
+
+The Home provider honors an explicit initial tab, search, grouping, and facet
+selection. Filters persist per user across reloads and fresh Home navigation;
+split history restores that entry's filter selection. An explicit facet selection
+overrides saved filters. Returning through split history resets navigation to Signal.
+
+Channel thread replies remain separate Home entries from their parent channel,
+using single-line rows and a reply arrow icon on desktop, labeled
+with the sender and channel (for example, **Peter in #battlefield**). Channel names
+prefer the current channel cache, then a matching thread notification's name,
+then **Unknown channel** if neither source has a name. Selecting a
+thread opens that thread in the channel preview; Shift-click opens it in a split.
+
+Items in the 256px desktop rail use single-line pills with 16px icons: profile photos for
+DMs and model logos for AI chats (Claude sunburst or ChatGPT knot). Other items
+use the same glyphs as entity rows elsewhere: document file-type and
+task/snippet/skill variants, hashes for channels, read/unread envelopes or
+calendar invites for email, sparkles for agents, folders for projects, and alarms
+for reminders. Pull requests retain open, merged, and closed status glyphs and
+colors; unknown foreign sources use the generic file icon.
+New agent-session rows always use a sparkle in the left slot, including while
+working. A coding session adds a second line with repository, captured working
+branch (when available), and PR number/status. Non-coding sessions stay on one
+line. Their timestamps and unread dots stay visible. Missing repository metadata
+is omitted.
+The Agents workspace uses a single left dot for activity and unread state in
+place of the sparkle. Opening a loaded session from Home or Agents marks its
+notifications read after the viewing delay, including notifications arriving
+while that session remains active.
+Other Home items have no title tooltips, and their timestamps are
+visible only while hovering the row. An unread
+dot remains visible. Click a row to preview it; `j`/`k` navigate and update the
+preview; alternate activation and Shift-click open a split.
+
+On desktop, before selecting a row, the main pane shows a centered single-line chat
+composer under “What should we get done in Macro?”. Attachment, text, model, and
+send controls share one row; longer prompts expand the input as needed.
+Home uses the shared app font and composer theme tokens; suggestion text and
+hover states use the same semantic colors as other app surfaces.
+Type in “Type @ to reference / for skills”, use the attachment button for
+attachments and the model menu to choose a model, then press Enter or Send to
+create and open an AI chat. If chat creation fails, the submitted text and attachments
+are restored, including before a chat-limit paywall opens. With agents disabled,
+the input stays 32px above the vertical center as suggestions load. With agents
+enabled, the composer uses the same topbar offset and 24/64 padding as the
+Agents new-conversation page so the two inputs share a baseline; suggestions
+still load below it without moving the input. Up to three cached AI
+suggestions appear below the
+composer, using the existing fast/smart recommendation projections. Compact rows
+use one line: reason — Phosphor icon and item name, followed by Open, all at the same font size. Clicking a
+suggestion fills the input and replaces its context attachments without sending;
+the Open action opens its source item in a new split, preserving the editor type
+for tasks, skills, snippets, and other documents. Suggestion loading/errors
+are isolated from the input. If generation stalls for 45 seconds, the shimmer
+is replaced with a retry action; a late result still appears automatically.
+Generation status updates do not extend that deadline. Retry starts a fresh
+45-second wait. Shift+Enter adds a line. Selecting a Home row replaces
+the composer with its preview. Home uses the shared 256px sidebar and collapses
+navigation below 720px. The hamburger or `Cmd+.` opens the full feed as a
+slide-over. Activating a row or **New chat** closes that overlay to show content;
+arrow-key browsing keeps it open. Preview headers start with **Home >**. Clicking
+**Home** clears the preview and returns to the starting pane without changing
+sidebar visibility. Use the hamburger to reopen the feed. Mobile continues to
+show the activity list alone.
+
+Document previews opened from Home expose **Share** and **Copy Share Link** before
+the details toggle, including tasks, snippets, skills, canvases, PDFs, images,
+code, and videos. Share uses the selected item's permissions and updates when
+switching items; copied links point to the entity rather than the Home feed.
+
+AI chat, agent, and channel message bodies use 15px text, including thread replies.
+Desktop AI chats, agents, and channel composers share Home's rounded composer
+surface: a muted dark fill or a white light-mode surface with a soft shadow,
+15px input text, and circular controls. Composer geometry is scaled to 15/16
+of the original design (48.75px single-line height); the Home composer is at most
+720px wide. In narrower desktop splits, the Home heading wraps and the composer
+shrinks to the available pane width; suggestion text truncates while Open stays
+visible. Plain channel messages use a compact row;
+multiline messages, formatting, and attachments retain a full-width editor and
+footer. Switching between compact and expanded layouts keeps the same editor and
+draft. Mobile composer styling and send behavior are unchanged.
+
+Sections are Last few minutes (under five minutes), Last hour, This evening
+(6pm onward), This afternoon (noon–6pm), This morning (6am–noon), Earlier today,
+Yesterday, and the existing older-date groups. Sections always follow this order,
+with newest rows first and entity identity breaking equal-timestamp ties.
+The reference clock uses whole minutes, so refreshing within the same minute
+preserves grouping. Rolling five-minute/hour windows continue across midnight;
+future timestamps caused by clock skew stay in the newest section, and invalid
+dates go last. Calendar sections use local time. The clock is checked every 30
+seconds without a new action. Scrolling near the bottom automatically
+loads older items. Home buffers older rows until both notification and own-activity
+pages have loaded through their timestamp, then advances the shallower feed first.
+Fetched rows still advance this boundary when display filters hide them;
+older cache-only rows do not.
+Rows tied at a page boundary appear together, so loading another page does not
+insert older history above already displayed rows. Live actions and refreshes
+can still reorder rows. Short or fully filtered pages continue loading until the list
+fills or there are no more results. A failed
+source shows a retry notice while the other source stays usable. Document typing
+starts an Edited activity for that editing session. Human edits
+are attributed to the signed-in editor; agent edits retain their agent attribution.
+
+Calendar reminder rows use the reminder delivery time for Home's date section,
+including on a cold GraphQL load with notification sorting disabled. Verify that
+an older reminder stays in its older section after the event's metadata syncs;
+opening its details should show the expected occurrence. A newer reminder or your
+own later activity can move the row forward, but a calendar sync alone should not.
+
+On mobile, the dock and search scope use the bell icon and **Notifications**
+label; Home is desktop-only. Notifications has no merged own-activity feed or
+chat starting pane. Opening a row navigates to its entity. On iOS, rows fade
+underneath the filters and status bar using the shared top edge gradient.
+
+Notifications have three lifecycle states: `unseen`, `seen`, and `done`. Active means
+unseen or seen. Viewing must not reopen a done notification; undoing done (`Ctrl+Z`
+or `⌘Z`) returns it to seen, not unseen. The row returns to the active inbox without
+an unread badge. Applying the active Inbox preset preserves read/unread selections:
+read (`seen` or `done`) narrows to `seen`, not to all active states. Email read/unread
+is separate from notification lifecycle state.
+
+Agent sessions notify through the same inbox. `<bot> finished <session>` goes to the
+owner and everyone who has prompted or answered in that session when a turn ends with
+nothing queued; `<bot> needs your answer in <session>` goes to the same people when the
+agent stops to ask (anyone with edit access may answer); `<user> mentioned you in <session>`
+goes to users @-mentioned in a prompt - when the author can edit the session, the mention
+grants them edit access first, so the link leads somewhere they can act. All three are
+filed under the session itself: the inbox shows an agent-session row (agent icon, session
+name, the bot or mentioner as sender, the excerpt or question as the body) and clicking it
+opens the session. They are
+not retracted automatically yet: answering the question or starting the next turn leaves
+the earlier notification until you mark it done. The chip announcement post itself no
+longer notifies the thread. Settings → notifications lists them under `AI`.
+
+## Home — `/app/component/home`
+
+Greeting, example prompt buttons (`Draft a document`, `Draft an email`,
+`Search & research`), and the ubiquitous `Ask AI` composer. Finishing onboarding
+without a deep link lands here. The retired Getting Started page's old
+`/app/getting-started` and `/app/component/getting-started` links also open Home.
+
+On phones, shared confirmations (including Remove Member and Cancel Invitation)
+use a glass sheet with a title, description, Close confirmation button, and
+side-by-side cancel and confirm actions. Pending actions disable both buttons
+and prevent dismissal; canceling leaves the underlying data unchanged.
diff --git a/docs/AGENT_GUIDE/login.md b/docs/agent-guide/login.md
similarity index 99%
rename from docs/AGENT_GUIDE/login.md
rename to docs/agent-guide/login.md
index dea35dbc27..41459661f2 100644
--- a/docs/AGENT_GUIDE/login.md
+++ b/docs/agent-guide/login.md
@@ -87,7 +87,7 @@ Root links must preserve query parameters through the welcome or inbox redirect,
including when Android delivers the link after the session gate mounts. Test
with a harmless marker query; checkout return parameters can trigger analytics
and license refreshes and should only be exercised in a checkout test.
-See [Android development](../ANDROID_DEVELOPMENT.md) for build commands and
+See [Android development](../development/android.md) for build commands and
certificate-dependent domain verification. Provider completion, account linking,
and verified links still require end-to-end qualification.
diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/agent-guide/navigation.md
similarity index 100%
rename from docs/AGENT_GUIDE/navigation.md
rename to docs/agent-guide/navigation.md
diff --git a/docs/agent-guide/notifications.md b/docs/agent-guide/notifications.md
new file mode 100644
index 0000000000..54f9b55d04
--- /dev/null
+++ b/docs/agent-guide/notifications.md
@@ -0,0 +1,97 @@
+# Notifications
+
+## Notifications
+
+In the desktop app, **Settings → Notifications → Delivery → Desktop notifications**
+controls system notification delivery for this installation. The Notifications
+page is always present, in the same place on web, desktop, and mobile; Account
+has no notification switch.
+Turning it off takes effect immediately and persists across app restarts; turning
+it on requests permission and resumes delivery when authorized. On macOS the
+switch reads the actual system authorization, and enabling it requests macOS
+permission if it has not been decided. If macOS reports denial, enabling the switch
+shows directions to **System Settings → Notifications → Macro → Allow notifications**
+without requesting permission again; returning to Macro refreshes the switch.
+It does not change inbox items or other devices. Focus and presentation settings
+can still suppress alerts even when authorization is granted.
+Verify off/on and persistence after restarting; on the Notifications page, a failed
+toggle should show an error toast and allow retry.
+
+On Linux desktop builds with native notification activation, clicking a system
+notification (or its **Open** action) restores/presents Macro and opens that
+notification's target using the normal in-app navigation. Dismissing or expiring
+an alert must not navigate. With two alerts, click the older one to check that the
+correct target opens. Also test with Macro hidden/minimized and on another
+workspace: Wayland focus requires the notification daemon to supply an activation
+token. This needs a native AppImage update, not just a frontend update; an older
+binary reports **Update Macro to receive desktop notifications.** Activation is
+supported while the app process is running, not after quitting it. The isolated
+Linux WebKit/D-Bus regression is `bun run native:e2e:notifications`; compositor
+focus behavior still needs a real Wayland/X11 desktop check.
+
+On native Android, enable notifications in Settings while signed in. Android 13+
+also asks for system permission; the system's **Activity** notification channel
+must be enabled. Remote push owns system notification display after registration,
+so the same WebSocket event should not create a second local notification. Tapping
+a notification opens its target; simply receiving one does not navigate. Check
+this with the app foregrounded, backgrounded, and after ordinary process death.
+Logout clears delivered notifications and disables receipt for the old account.
+After a transient native listener failure, verify that notification taps recover
+without restarting the app. Android alerts without display text show
+`New notification`; silent read/done clears must remain silent.
+Also verify logout and notification opt-out while registration is pending: late
+backend or native completions must leave the receiver disabled. If a new account
+signs in before cleanup finishes, its registration must remain active afterward.
+
+Toast regions are labeled `Notifications (alt+T)`; seven empty live regions always exist in
+the a11y tree (ignore them when parsing snapshots).
+
+Staff Noise emails still create in-app notification rows, but do not send a new-notification
+event over GraphQL or the legacy WebSocket gateway, so they do not trigger browser popups.
+Those rows are available on the next fetch/refetch. Signal delivery and the existing
+staff/customer eligibility rules are unchanged; no browser eligibility request is needed.
+
+Discussion composers on companies, contacts, documents, tasks, and PRs use the
+shared channel/AI composer surface, 26.25px desktop corners, 15px desktop text, and
+a circular neutral Send button. Edit with AI uses the same composer treatment.
+Inline comments, replies, and their edits use a plain
+input without a surface background, rounded frame, or shadow. Attachment and
+formatting actions stay available.
+On mobile, open documents and tasks put their new-comment composer in the
+accessory dock above navigation, using the channel input's compact pill and
+expanded surface. Ask AI and New are hidden in these open views only when the
+comment composer is available; their list screens keep those controls. Users
+without comment permission have no comment composer, so Ask AI remains visible.
+
+On touch devices, an email thread's floating action bar has Previous email and
+Next email arrows beside the larger Mark done checkmark. The arrows follow the
+source list's filtered order, skip non-email items, and disable at its ends.
+`J` / `ArrowRight` and `K` / `ArrowLeft` use that same order in the Email view.
+Arrow keys in a reply editor or other text input keep their normal editing behavior. They do not wrap; a thread
+opened without a source list has disabled arrows.
+Mark done archives the current thread and opens the next email in that same
+filtered list, loading pages until another email is found or the list ends.
+On native mobile, stepping replaces the current email while preserving the
+filtered list behind it for swipe-back. In the newer Email view it retargets the
+view-owned detail stack instead of opening another block. To verify, open the
+first email from Signal or Noise, tap Next and then Previous, and return to the
+same filtered list.
+Leaving the email cancels pending
+navigation and archiving while a page loads. At the end it opens the previous
+email; with no neighboring email it stays on the archived thread. Mark as not done
+does not advance. Undo restores the archived email and returns to it.
+
+The mobile reply/forward drawer uses matching circular glass buttons for
+discard, attachments, and send, with the dock's button/icon sizing and regular
+Phosphor icons. Send remains disabled until the draft is valid and shows a
+spinner while sending.
+
+The mobile new-email composer nests the channel-style Send button inside its
+top-right glass toolbar, with an even 5px inset on the top, bottom, and right.
+The toolbar is 46px tall; attachment and schedule controls align with Send.
+
+Channel, email, Markdown, and composer body text use `text-base`: 15px at the
+default root size. Supporting `text-sm` text is 14px and `text-xs` is 12px.
+Desktop and mobile share this scale, with accessibility text scaling preserved.
+
+Desktop channel and AI composers use an `Attach files` paperclip that opens the file picker directly, without a plus menu. Comment composers open the image picker directly. Channels and DMs always open in message mode; create tasks through the task creation dialog. Shift+Enter, including an empty new line, expands channel and AI inputs so text starts above the toolbar at the left inset. Sent AI message bubbles use the ink fill with a contrasting foreground in each theme.
diff --git a/docs/AGENT_GUIDE/observability.md b/docs/agent-guide/observability.md
similarity index 100%
rename from docs/AGENT_GUIDE/observability.md
rename to docs/agent-guide/observability.md
diff --git a/docs/agent-guide/onboarding.md b/docs/agent-guide/onboarding.md
new file mode 100644
index 0000000000..cc843acff0
--- /dev/null
+++ b/docs/agent-guide/onboarding.md
@@ -0,0 +1,13 @@
+# Onboarding
+
+## Onboarding bypass — `/app/onboarding`
+
+All `@macro.com` accounts see a **Bypass** button on every onboarding step. It
+skips the rest of the flow and leaves onboarding. Accounts on other domains
+do not see it.
+
+## Setup plan step — `/app/onboarding`
+
+Onboarding has no plan picker; it ends with the 30-day Premium trial offer and a
+Guest continuation (see [login](login.md#desktop-onboarding)). Plans are chosen
+afterwards in **Settings → Billing**, where Guest users can buy Premium or Max.
diff --git a/docs/agent-guide/pull-requests.md b/docs/agent-guide/pull-requests.md
new file mode 100644
index 0000000000..ebdef24bc8
--- /dev/null
+++ b/docs/agent-guide/pull-requests.md
@@ -0,0 +1,91 @@
+# Pull requests
+
+## Pull requests — `/app/reviews/pr/<foreignEntityId>`
+
+Opening **Reviews** from the mobile dock's **More** drawer starts on **Pull
+requests** (the **All** scope). Explicit review-tab links keep their selected
+scope; desktop's default scope remains **Involves me**.
+
+Macro-linked GitHub pull requests open inside the Reviews shell, with a Reviews
+breadcrumb, PR title/status, linked GitHub metadata, discussion timeline, and Details/Checks
+side panel below the top bar. An open PR that is not a draft, and whose checks
+have all finished with a success, skipped, or neutral conclusion, also shows a
+**Merge** button in the top bar beside **Changes**. It opens a confirmation with the repository, PR number,
+and title, then merges on GitHub as the signed-in user through their linked account.
+GitHub's permissions and branch protections decide; a refusal appears as a toast
+with GitHub's reason, and a merge refreshes the PR status in place. Without a linked
+GitHub account the toast points to Settings. Draft PRs, PRs with no checks, and PRs
+whose checks are still running or failing have no Merge button. Merged and closed
+PRs have no Merge button. PRs are not tasks and do not appear in the Tasks list.
+The metadata pills beneath the PR title include linked agent sessions, using the
+agent sparkle icon. A single session shows its name; several sessions show a
+count chip opening a session list. Selecting a session opens it, with Shift-click
+on the single-session chip opening another split. The same chip appears in PR
+list metadata without activating its containing PR row. Empty links show no chip;
+loading or inaccessible session previews are not navigable. PR status pills stay
+passive; status filtering uses the Reviews list's Open/Closed sliding tabs and
+filter menu.
+Opening **Changes** slides a full-height pane in from the right beside the PR details,
+including beside the PR top bar rather than underneath it. The PR details shrink
+alongside the entry slide instead of eagerly jumping narrower. The Changes pane
+has no outer top, right, or bottom border. The PR's `+N −M` diff count pill also
+opens the pane when changes are available; it remains a passive count without a
+Changes controller or when changes are unavailable.
+Closing slides the pane fully off the right edge while expanding the left pane,
+without fading in either direction or a final width snap. From full width, the PR
+details appear behind the sliding pane, without blank space. Reopening during exit
+keeps the same pane mounted.
+The pane shell opens before the diff bodies render. Reduced-motion preferences
+disable both animations.
+The PR breadcrumb and side-panel toggle remain above the left pane. The
+**Changes** toggle stays visible in split view, ghost while closed and accent text
+on a tinted background while open; clicking it again closes the pane. There is no standalone **Open on
+GitHub** button: the pane header has no visible Changes title, and its
+`head → base · #N` is one plain-text GitHub link, underlined on hover without a
+pill background or icon. GitHub diff totals and five green/red squares appear
+beside the PR number in both split and full-width layouts. The squares summarize
+the addition/deletion mix; the numbers retain exact totals. At full width, a smaller
+PR title appears before the link. Both title and totals come from the existing PR
+query; unavailable values stay hidden, without placeholders or captured-count
+fallbacks. File headers highlight on hover. When space is tight, the smaller
+branch/PR/count metadata wraps below the title, while pane actions stay separate.
+The Changes toggle has no diff totals and becomes icon-only below 28rem of header
+width, retaining its name, tooltip, and active state. Breadcrumbs keep their existing layout.
+The full-height file tree has a fixed header with its file count on the left and
+**Hide file tree** on the right. Borderless diff controls float above the diff stack
+rather than spanning the pane in a second toolbar. Unified/Split retains text labels
+at narrow non-touch widths on the left, with diff collapse/expand and refresh on
+the right. Hiding the tree moves its count
+and **Show file tree** above the diffs, as described in
+[AI Chat](ai-chat.md#reviewing-a-linked-github-pull-request).
+Spotlighting changes hides the left pane and its top bar; **Back to the split**
+restores the prior divider position and retains the draft, diff state, and scroll.
+At host widths of 720px or less, Changes opens full-width automatically without
+that width toggle; widening restores the requested wide layout and split ratio.
+Narrow file trees start closed. **Show file tree** opens an animated drawer over the
+diffs without resizing them, including on phones. File selection, Escape, the
+backdrop, or **Hide file tree** closes the drawer and restores focus to its opener.
+The drawer does not change the saved wide-tree visibility or preferred width.
+Closing releases the drawer's dialog handlers immediately while its inert visual
+frame finishes exiting, so rapid reopening does not restore focus to a stale opener.
+The file tree has its own draggable, keyboard-resizable divider and remembers its
+width locally. Tree visibility uses the sidebar's shared width transition while
+retaining directory state and diff owners. Reduced motion skips this transition.
+The divider remains visible but inert through the tree's exit. Resizing the outer
+split or viewport settles active tree motion before applying the new geometry.
+**Copy path** briefly shows a non-pulsing success checkmark without collapsing
+the file. The PR viewer stays read-only and does not offer agent review notes.
+Copy Link from a PR in Quick Access copies `/app/reviews/pr/<foreignEntityId>`.
+Old `/app/pr/<foreignEntityId>` links redirect to Reviews. Check a copied link,
+a PR opened from a list or agent session, a second split, breadcrumb return,
+side-panel toggle, and phone layout. If no GitHub data loads, the detail shows
+an error banner with a Retry button; pressing it refetches the PR in place.
+
+PR metadata changes should update an already loaded Reviews list row and the
+linked agent session's PR status without reloading the page. To verify, keep
+both rows visible and change the PR in GitHub; check the status after the
+webhook arrives. Include a team-owned PR and a PR also stored for your personal
+account. In the network panel, confirm the update arrives on the Soup GraphQL
+subscription without triggering a refetch of every Soup list. Replaying an
+unchanged webhook should not produce another Soup update. The PR detail's
+separate diff and discussion requests are outside this subscription behavior.
diff --git a/docs/AGENT_GUIDE/reminders.md b/docs/agent-guide/reminders.md
similarity index 100%
rename from docs/AGENT_GUIDE/reminders.md
rename to docs/agent-guide/reminders.md
diff --git a/docs/agent-guide/search.md b/docs/agent-guide/search.md
new file mode 100644
index 0000000000..d75e644adf
--- /dev/null
+++ b/docs/agent-guide/search.md
@@ -0,0 +1,44 @@
+# Search
+
+## Search
+
+Sidebar `Search` button → `/app/search` with a focused query box. Results
+(including a `Featured Results` group) filter live as you type; no Enter needed. `Ctrl+K` is
+usually faster for jump-to-entity; `/` opens workspace search when no editor is focused.
+
+On touch devices, the dock's **Search** button opens a persistent input. Type a
+query, then switch the scope pills between **All**, **Notifications**, **Email**,
+**Channels**, **Files**, **Agents**, and **Tasks**. The selected view searches with
+the same query and retains its tab/facet restrictions. Channels searches
+conversation names. Clearing the
+input restores the current scope's unsearched list; **Close search** ends the
+session. Switching scopes keeps the input mounted and focused. The dock query is
+not saved into the view's desktop search or restored entry state. Home and
+top-level Tasks use this same overlay; embedded project task lists retain their
+own search while the dock is open.
+
+Search snippets carry their target in the destination pane's route search. Channel
+messages open Chat at the message (replies open their parent thread); email snippets
+open the matching message, Markdown snippets the matching node, PDFs the matching
+page and highlighted text, agent snippets the matching turn/author, and call
+snippets the matching transcript segment. Plain rows keep their existing behavior:
+email rows open normally, while agent and call content results use their first hit.
+
+Verify both a cold open and a result whose entity is already open in another pane,
+including a Home or Drive detail: reuse keeps that pane's workspace and filters,
+leaves the search pane intact, and scrolls to the target. Scroll away and click the
+same snippet again to verify it re-targets. Repeat with Shift-click and Cmd/Ctrl-click
+(new split and new browser tab), and check Back/Forward restores the earlier target.
+Channel checks should include an older offscreen message, a reply, and then a root
+message to ensure the previous thread target is cleared.
+For a PDF that is still loading, clear its route target before pages become visible.
+The old search hit must not apply afterward, and its normal initial position should
+still restore if no target has been applied. A newer mention or preview target must
+survive that cleanup and still open when the viewer is ready.
+
+Agent-session results use the robot icon and show a highlighted transcript snippet.
+`Show more [N]` expands additional matches, labeled **User / Agent · Turn N**.
+Click a snippet to open `/app/agent/<uuid>` at that folded message; a plain row click
+opens the first content match, or opens the session normally for a title-only hit. These are
+ACP-backed sessions, distinct from legacy chat results. Legacy chat rename, delete,
+copy, and move-to-folder actions are not offered on agent-session search rows.
diff --git a/docs/agent-guide/settings.md b/docs/agent-guide/settings.md
new file mode 100644
index 0000000000..238da8e292
--- /dev/null
+++ b/docs/agent-guide/settings.md
@@ -0,0 +1,475 @@
+# Settings
+
+## Settings — `/app/settings/<section>`
+
+### Slack archive import
+
+Temporary message storage recovers closed IndexedDB connections without restarting
+the import or deleting staged history. Verify closure between staging batches and
+between cursor pages: all messages must remain ordered, deduplicated, and within
+the original byte limit. Cancellation and cleanup still work during recovery.
+Deleted or replaced scratch databases fail the old import instead of silently
+continuing with incomplete history; its cleanup must leave a replacement intact.
+
+In **Team → Connections**, **Import from Slack** appears only for team admins
+and owners with `enable-slack-archive-import` enabled. Production rollout stays
+off until explicitly enabled. Select an export ZIP, filter the grouped conversation
+picker, optionally show archived conversations, and use Space to toggle focused
+checkboxes. **Select all visible conversations** preserves selections hidden by
+filters; unchecking it or **Clear visible selection** clears only visible selections.
+Rows show stable Slack IDs
+so duplicate names remain distinguishable. Counts are advisory when available,
+otherwise “not yet counted.” Discovery moves keyboard focus to the filter.
+Slack file/canvas discussion folders (`FC:<file-id>:<title>`) are ignored, not
+imported as channels; their presence must not prevent channel discovery.
+
+Review email attribution and external membership implications, choose whether to
+include history, and confirm the immutable Slack workspace binding before
+**Import selected channels (N)**. At least one selection is required. File selection
+alone makes no server writes. Close/Escape or cancel before confirmation discards
+the archive and selection without creating a job; reopening requires choosing a
+file again. After confirmation the selected IDs/options are frozen. Closing and
+reopening then retains the upload session; keep Team Settings open until it finishes.
+The dialog restores focus to its opener, and polling should not blank Settings.
+
+Use **Job history** (including older pages) for server progress after a reload.
+It displays the persisted selected names/IDs/kinds, history option and selected
+failures/skips without the ZIP. Unselected channels are not skipped work. Reload
+recovers server tracking, **not interrupted local uploads**; finalize verified work
+with skips or cancel and explicitly confirm a new import/token.
+**Cancel import (keep partial results)** does not delete committed messages or
+channels; running work may finish. An interrupted upload offers **Recover job
+receipt**, then **Finalize with skips** or cancellation. Channel links appear only
+when the server confirms current participation and the viewer's channel list
+confirms access. Verify counters, errors and skip
+reasons at narrow widths, using synthetic exports and a test backend rather than
+importing customer data into hosted dev.
+
+For a release check, inspect the actual create request and then reload the server
+receipt: both must contain exactly the selected Slack IDs and history option.
+Select two rows with the same display name, filter both out, and confirm the
+selected total remains unchanged. Cancel before confirmation and verify there
+were no create, registration or PUT requests. An open job must reject tampered
+registration/sealing of an unselected ID; a client-only picker test is insufficient.
+Check desktop web and Tauri: opening Settings alone creates no ZIP worker, and
+signed PUTs work without dropping checksum or conditional headers. A 412 upload
+retry verifies the existing object instead of overwriting it. Keep an active job
+open through websocket disconnect/reconnect to verify polling remains usable.
+The [runbook](../runbooks/slack-archive-import.md) distinguishes fixture tests from
+live-backend release gates and documents staging retention and recovery.
+
+### Email signatures
+
+Open **Settings → Email → Signatures**. Each owned inbox has a visible editor;
+there is no expand/collapse control. Format the text, add links or images, and
+choose **Save signature**. **Clear signature** removes only the signature, while
+**Remove inbox** in Accounts uses the existing inbox removal confirmation.
+**Add to replies & forwards** saves that preference immediately. On desktop,
+**Import from Gmail** in each inbox's header fetches that account's Gmail
+signature and saves it right away, replacing any unsaved draft; a toast reports
+when Gmail has no signature. Unsaved drafts
+survive switching settings pages. On phones, signature editing remains desktop-only;
+the replies/forwards toggle and clear action are available.
+Email accounts can also be managed from **Integrations**. Its **Email settings**
+link opens the dedicated page, and Email links to Notifications and Calendar.
+With a composer open, save a changed signature or reply-signature preference and
+verify its preview updates. Once the account refresh completes, reopen a composer
+offline and confirm it uses the saved settings.
+
+### Notification snoozes
+
+Open **Settings → Notifications** to see **Snoozed items** and their local resume
+times. **Change time** opens the same searchable time picker used by entity
+actions; **Resume** cancels a snooze immediately. Permanent mutes appear separately
+under **Muted items**, with **Snooze instead** to replace one with a timed pause.
+
+The Chat detail pane also supplies these commands for its current channel or DM;
+focus the conversation before opening the command menu.
+
+To snooze an entity, right-click its row (long-press on mobile) and choose
+**Snooze notifications…**, or select/open the entity and search for that command
+in Cmd/Ctrl+K. Multi-selection applies the chosen deadline to all selected items.
+Use arrow keys and Enter, click a preset, or type a future date/time such as
+`2h` or `tomorrow 10am`. The next morning means the next local 9 AM; the weekend
+preset resumes on Monday at 9 AM. The picker displays the exact local date and
+time before saving. Escape closes the picker; before choosing a time, it makes
+no changes.
+
+Snoozing pauses notifications only: it does not hide, archive, mark read, or mark
+done. Channel message/thread rows target their parent channel, matching mute.
+The server enforces expiration even when no client is open. Displayed snooze
+state refreshes when the window regains focus or a mute/snooze changes; the
+client does not poll. A failed save keeps the picker open for retry; a successful
+save appears in notification settings.
+If only some selected items save, the picker shows the saved count and retries
+only the remaining items. Closing it keeps any snoozes already saved.
+
+On phones, long-press opens the entity actions drawer. The snooze time picker
+uses the same responsive `Dialog`, width, and `CommandMenuShell` as Cmd/Ctrl+K,
+with larger touch targets and tap instructions. Swipe the preset list when the
+viewport is short. In **More views → Settings → Notifications**, item names and
+deadlines sit above **Change time** and **Resume**. Saving or cancelling a picker
+returns to the settings sheet. Start new snoozes from an entity's actions or
+Cmd/Ctrl+K; Settings manages existing snoozes and mutes.
+
+Design references: [Slack notification pause/resume](https://slack.com/help/articles/214908388-Pause-your-Slack-notifications)
+and [Superhuman's keyboard-driven Remind Me picker](https://new.superhuman.com/remind-me-29124).
+Macro applies the temporary pause per entity and keeps the entity visible.
+
+### Team membership
+
+Team membership has no size cap, including free teams. Invitations and domain
+auto-join must keep working beyond five members and the former stage-plan limits.
+Free-team joins do not create a paid subscription, bill a seat, or grant premium
+roles. Teams with an existing paid subscription retain their per-seat billing;
+enterprise teams retain their billing bypass.
+
+On a local stack started with `--no-doppler`, verify free-team creation from a
+fresh passwordless signup. It must work without Stripe credentials.
+
+Under **Team**, owners/admins can turn **Auto-join on domain** off and can restrict
+invitations to admins with **Members can invite**. These controls still apply.
+To verify the membership flow, use a local free team with five members: invite
+and accept a sixth member, then sign up another user on its enabled auto-join
+domain. Both should appear in the team's member list and configured auto-join
+channels without an upgrade prompt. Repeat with auto-join disabled to verify a
+same-domain signup is not added automatically.
+
+### Navigation
+
+On phones, **More views → Settings** opens an inset glass sheet over the current
+page. The main page has a profile shortcut and the same grouped Blocks, Personal, Workspace,
+and Developer sections as desktop, plus enabled admin settings. Search finds
+individual settings; selecting a result opens its page and reveals the section. Tap a row to open that settings
+page inside the sheet; **Back to settings** returns to the grouped list at its
+previous scroll position. `API Keys` is desktop-only and has no row here.
+**Close settings** at the top right, Escape, an
+outside tap, or a downward swipe dismisses the sheet. A tap that dismisses a
+menu opened inside the sheet leaves the sheet itself open. Opening Settings again
+starts at the main page; explicit links (for example Account) open their
+section directly. Existing settings URLs open the requested section in the sheet
+and restore the underlying app route. The header stays visible while forms
+scroll, including with the keyboard open. On desktop, Settings is an ordinary
+split view: the rail's gear button (or `Ctrl ;`) opens it in the active split
+like any other rail item, and Shift-click opens it in a new split.
+`/app/settings/<tab>` opens it as the only split with the app rail still
+visible, and `/app/home/~/settings/<tab>` places it beside Home. Its inner
+sidebar matches Email and Tasks: a **Settings** title bar, a rounded
+**Search settings** field, the grouped section pills, and **Log out** pinned to
+the bottom. Unlike other views, it cannot be hidden at desktop widths: there is
+no **Hide navigation** toggle and `Cmd .` does nothing, even if it was hidden
+before. Below 720px the sidebar becomes an overlay opened from **Show
+navigation** (or `Cmd .`), which starts closed. Escape closes a
+settings split that shares the layout, or steps back to the previous view when
+it is the only split (Home when there is none). Leave settings by picking any
+other rail item; there is no separate back or fullscreen control.
+
+Settings pages use the email composer’s raised surfaces on the page background.
+Section headings and controls share a white surface in light mode and the
+composer border in dark mode, with subtle row separators. The compact sidebar
+uses the shared workspace width.
+
+When a newer version is ready, an **Update available** button (a download icon
+in a subtle accent circle that a glowing comet periodically circles) appears in
+the sidebar rail above the mobile-app and settings icons. Its popover (a title,
+a short description, and one action) opens by itself once per update until
+dismissed (click outside or Escape); the button stays until the update is
+applied. Its wording and action depend on the update: **New version available**
+/ **Reload** for a newer web build, **Update ready** / **Update** for a
+downloaded bundle in the desktop app, and **Desktop app update ready** /
+**Restart and update** for a native desktop update. When part of the app fails
+to load because a newer web build replaced it, the same button appears and its
+popover opens again (even if dismissed) with **Reload**; there is no blocking
+alert. Touch layouts have no rail, so a newer web build shows a **Reload** toast
+there instead.
+
+On desktop release builds, **Account → Desktop app update** shows native update
+progress. While preparing to restart, the popover can't be dismissed and its
+action is disabled. Restart waits for pending canvas/PDF saves and
+local persistence; active calls, uploads, and imports must finish first. A ready
+update also installs on normal app quit. Closing a window only triggers
+installation if it exits the app. Browser, mobile, and development builds do not
+show this native updater row.
+
+Below Profile, **Account** shows a card naming the current plan (**Free plan**,
+**Pro plan**, or **Max plan**; **Loading plan…** until the billing summary
+arrives). Clicking it opens **Billing** settings.
+
+Left nav (feature and platform gates still apply):
+
+- **Blocks**: Email, Calendar, Agents, CRM.
+- **Personal**: Account, Appearance, Notifications, Keyboard shortcuts, Usage, Billing, Desktop App, Mobile App.
+- **Workspace**: Team, Tags, Integrations (personal Gmail/GitHub accounts).
+- **Developer**: Agent connections, Runtimes, MCP server, API Keys, Bots.
+
+**Desktop App** (`/app/settings/desktop-app`) shows a compact version and
+build-date card in the desktop app. The date is when the running app bundle was
+built, not when it was installed on the computer. In the browser it links to the
+latest desktop release on GitHub, and only appears when the `desktop-app` PostHog
+flag is enabled. Native desktop always shows this section regardless of the flag;
+native mobile never shows it.
+
+Search checks individual setting titles and keywords, tolerates common typos,
+and shows the parent page below each control result. Selecting a result opens
+that page, scrolls to its section or row, and briefly highlights it. Try
+`singature`, `email digest`, `calendar color`, or `cursor`. Arrow Down from search
+focuses the first result; Tab moves through controls normally. Escape in the
+search field clears the query. Clearing search restores the grouped navigation. Keyboard shortcuts are listed
+by category with the action on the left and keys on the right; expand **Keyboard
+preview** for the visual key map.
+Appearance starts with visual **System**, **Light**, and **Dark** mode choices.
+The previews use the saved themes; System follows the device and exposes both
+per-mode theme selectors. Light or Dark shows its own theme selector. Each selector
+retains theme search, editing, copying, and custom theme creation.
+
+Existing settings URLs remain valid; `connections` still opens Integrations,
+`agent-connections` opens Agent connections, and `harness` aliases Runtimes.
+
+`Usage` appears directly above Billing, including for Free accounts. In
+production, the `enable-ai-usage-billing` PostHog flag controls activation. While
+it is off or loading, the page shows **AI billing changes take effect on October
+8, 2026.** and all Usage controls are disabled. Turning the flag on activates the
+page and removes the announcement. Dev and local remain interactive even with
+the flag off. The production usage-limit dialog follows the same flag. Its
+**Monthly limit** meter displays a percentage using the backend's current-period
+usage and allowance. The info button explains AI agent chat and AI document
+editing. **Usage Credits** shows the dollar balance and `Add more`, which opens
+**Need more usage?** with `$25` / `$50` / `$100` / `Other`. Supported amounts
+redirect to Stripe Checkout; unsupported custom amounts are disabled. Free
+accounts see `View plans` instead of purchase or reload controls; paid team
+members who are not the payer see only “Usage credits are managed by your team.”
+Their credit balance and automatic reload row are hidden, with no
+credit-purchase action.
+Team owners who pay for their team's seats manage the shared credit balance and
+automatic reload here in Usage, including purchases, balance thresholds, the
+monthly reload cap, and payment methods. Team payers see **Team Usage
+Credits**, “Credits are shared by your entire team.” and **Shared team balance**.
+The purchase and auto-reload dialogs also identify the team-wide credit balance.
+Team settings manages seats. Included
+usage remains per seat: the owner's Monthly limit meter describes their own
+usage, not the sum of the team's allowances. Team payers with a finite
+allowance see “This is your personal monthly usage limit.” beneath the meter.
+Unlimited enterprise plans show `Unlimited` and do not offer credit purchases
+or automatic reload. The development paid-plan preview can still display
+those controls, with purchases disabled.
+
+The **Automatic reload** switch opens **Auto-Reload** without toggling directly.
+It contains Minimum balance (default `$10`), Target balance (default `$100`),
+optional Maximum monthly spend (`No limit`), a payment-method management link,
+and the automatic-charge warning. The dialog saves for paid payers:
+`Turn on auto-reload` enables automatic credit purchases with those thresholds,
+`Save` updates them while on, and `Turn off` disables automatic reload. The monthly
+limit caps reload purchases per UTC calendar month. The **Automatic reload**
+switch reflects the saved state and is the billing opt-in indicator. Paid team
+members who are not the payer see
+`Only the account that pays for this plan can change automatic reload.` and
+cannot save. After a failed automatic reload the Usage row shows
+`Paused — payment failed` while preserving the enabled setting. The dialog shows `Your last
+automatic reload could not be charged. Update your payment method, then save to
+try again.`; saving retries. Extra usage is funded entirely by prepaid credits.
+If the reload budget runs out or payment fails, uncovered usage cannot trigger a
+direct usage charge; with quota enforcement enabled, exhausted credits and
+allowance block further AI requests. Historical direct-charge invoices are still
+recognized by webhooks, but settlement never creates or retries them. Local
+**Developer tools** offer
+`Preview Free plan` and `Preview paid plan` to display either Usage page with
+sample usage, regardless of the signed-in account's tier.
+`Open Free usage-limit dialog` and `Open paid usage-limit dialog` open the
+corresponding exhausted-usage prompt directly. The previews also work before
+the usage summary loads or when it fails. The paid-plan preview allows
+testing Auto-Reload settings. Purchases and payment management are disabled during any
+preview; `Reset preview` restores server data and closes the usage-limit dialog.
+`Preview production before Oct 8` shows the October 8 announcement and disables
+Usage controls, including usage-limit dialogs. Dev tools remain interactive:
+Free and paid previews can be combined with this state, and `Reset preview`
+restores the normal dev view.
+
+Local **Developer tools → Open Billing Lab** opens `/billing-lab.html`, a
+standalone simulator with no login or billing API calls. Its 20 presets include
+Max with a pending Pro downgrade, exhausted allowances, credits, payment
+failures, team roles, loading, and errors. Select **Max → Pro at renewal**
+to start with a scheduled downgrade, and choose **Advance to
+renewal**: Max stays active until renewal, then Pro becomes active and included
+usage resets. Billing displays the scheduled downgrade and effective date;
+**Keep Max plan** cancels it and preserves the active plan and usage. The
+timeline also offers **Cancel scheduled change**. Purchases open a simulated checkout with explicit completion;
+**Fail the next billing request** enables error and retry checks. Scenario links
+restore the preset, not edits. **Monthly reload limit reached** opens Usage with
+a notice banner: **Monthly auto-reload $50 limit reached**, with **resets Nov 1**
+on the right. **Adjust limit** opens Auto-Reload; **Add credits** opens credit purchase.
+Manual credits do not count toward the monthly reload cap, which resets at the
+UTC month boundary. Live Usage shows this same banner from the API's monthly
+reload commitments and reset date, including when remaining cap room is below
+the minimum reload charge. Paid/pending reloads and failed invoices that can
+still collect count toward the cap. Older backends without these facts show no notice.
+The **Teams** scenario group opens Usage directly. **Mixed-plan team owner**
+previews shared credits and enabled reload for one Max and three Pro seats;
+**Team credits exhausted**, **Team reload paused**, and **Team monthly reload
+limit** exercise the owner's purchase, payment-recovery, and cap controls through
+the same Usage dialogs. Credit purchases add to the shared balance, while the
+included-usage meter remains scoped to the viewer's own seat. **Team-paid Max
+member** previews the notice-only member view. The simulator does not meter
+other members' activity or perform automatic charges.
+See [Billing Lab setup and boundaries](../../apps/web/src/features/billing-lab/README.md).
+
+`Billing` shows the current plan and `Manage`. Free users see separate Pro
+(`Get Pro`) and Max (`Get Max`) cards, side by side when the panel is wide enough
+and stacked on narrow panels. The Pro card shows `Free for one month!` for Free
+users. `Get Pro` requests the same server-validated 30-day first-subscription
+trial as onboarding; checkout redirects only after the server confirms the trial.
+Ineligible accounts see the rejection reason and are not silently charged.
+`Get Max` keeps standard paid terms. Prices read `/ month` for solo users and
+`per seat / month` for team accounts. Each card puts its button beside the price when wide enough and below
+the price when narrow. Free lists 2 connected email accounts; Pro and Max list
+unlimited connected email accounts. Pro users see a Max card (`Upgrade to Max`); Max
+users keep their current plan. Cards appear only for users who can
+manage their subscription. Team-paid members see no plan options, including
+on Free seats. Member options stay hidden until the billing summary confirms
+they pay for their own seat. On a team, a plan change moves only the viewer's
+own seat. Max lists "10x more AI usage than Pro"; Free and Pro allowance labels
+still follow the `enable-ai-usage-billing` flag. Usage controls live in Usage.
+The upgrade modal and Billing use the same plan cards and benefits, including
+the same flag-gated AI usage label and responsive card layout. The modal offers
+Pro and Max to Free accounts, only Max to Pro accounts, and no upgrade cards to
+Max accounts. Cards in the modal show benefits without purchase buttons. The footer’s
+`Manage plan` closes the modal and opens Billing settings, where checkout and
+plan changes take place. Team-paid members see a message
+to contact their team owner. Plan options wait for the billing summary and team
+lookup; failed lookups show `Try again` rather than guessed upgrade options.
+
+On a local HMR dev server, `Preview billing & paywall` opens an opt-in preview in
+Billing. Choose Solo, a team-paid member, a self-paying member, or a team owner,
+and Free, Pro, or Max. `Permissions, loading, and feature states` exposes the
+billing summary status, billing permission, active/trialing license, AI usage
+flag, and pending plan actions. The preview uses the real Billing UI with local
+fixtures; checkout, plan changes, Manage, and Team settings only show preview
+status messages. `Preview paywall` opens the same modal for the selected state,
+without developer controls inside it. Dismissing the modal returns to Billing
+with the selection preserved. `Manage plan` returns to the selected Billing preview.
+`Reset preview` restores Solo/Free; `Exit preview` restores
+the signed-in account. State is not persisted and resets on leaving Billing.
+These controls are excluded from deployed builds, including dev.macro.com.
+
+Billing shows the current billing period end and any scheduled downgrade date.
+Max stays active until renewal; **Keep Max plan** cancels a pending downgrade
+without resetting usage. Failed renewal-detail reads offer **Try again**.
+Team members who cannot manage billing see the notice without its action.
+
+`Team` (members list; on a paid team each row shows the seat's plan,
+and admins/owners can move a seat between Pro and Max with the `Seat plan`
+menu; Max upgrades are immediate and prorated, Pro downgrades start at renewal.
+**Keep Max** appears only for a confirmed pending downgrade and cancels it;
+failed scheduled-plan reads offer **Try again**, while teams without applicable
+scheduled plans show no retry notice). CRM (enable/disable; once enabled, a `Deal stages` section
+with `Customize stages`, inline rename, reorder by drag handle or arrow keys (up/down
+buttons on touch), delete, `Add stage`, `Reset to defaults`, and `Closed stages`
+checkboxes, editable by the role set as `edit_stages_role`)
+
+`Agents` unifies agent definitions and runtime configuration in one page, also used by the Agents workspace. Its `Agents` section lists team and private agents. `New agent` / `Edit <name>` open full-page forms grouped
+Profile, Behavior, Runtime, Connections, Channels, Share. Connections is a radio pair:
+`Use my connected apps` (default; the agent gets whatever the person running it has
+connected) or `Specific apps`, which reveals a `Search connectors` box over the whole
+Pipedream catalog (results are `option` rows; picking one adds it) and a row per picked app
+with a connected / not-connected dot for the *current viewer* plus an inline `Connect`
+that opens the Pipedream Connect flow inside the page. Unconnected picks never block
+saving; each teammate connects their own account. An agent session that calls a picked
+but unconnected app gets a tool result saying so, and the agent's reply renders a
+`Connect <app>` chip that opens Agents → Connections for that app. The same page
+is also available as Settings → Agent connections.
+
+To change an agent's picture, open `Edit <name>`, choose an image with `Upload`,
+wait for `Uploading…` to finish, then click `Save changes`. Images up to 16 MB
+are uploaded to image storage; Save stays disabled during the upload. A failed
+upload shows an error and keeps the previous picture so you can retry. Verify
+the picture after reopening settings and after a page reload, then type `@` and
+the agent's name in a channel to check its mention-menu picture. Team agents
+available in all channels should refresh there without reloading the channel.
+
+With `pipedream-mcp` enabled, Connections (in Agents or Settings) has `Connected` and `Discover`
+tabs. Connected groups GitHub, Linear, Notion, and Slack tool grants by provider,
+lists other catalog connections alongside them, and puts custom MCP servers in
+a separate section. Discover offers featured providers, a searchable catalog,
+and `Add custom MCP`. Pipedream Slack OAuth is available in production and
+development from the featured Slack provider. Connecting Slack here grants tool
+access; channel import is a separate action where the user chooses channels.
+Provider Back returns to the tab that opened it; navigation is local to each
+Connections page and starts at Connected on a fresh visit.
+
+Macro agents and external AI clients using Macro's MCP server can run
+`ImportNotionPage` and the shared import ledger tools against the user's
+connections saved in Macro.
+Verify a Notion import returns a document and a repeated import returns the
+existing document; Linear imports recorded with `CreateImportEntity` should
+appear in `ListImportEntities`. These calls must not report that import tracking
+is unavailable.
+On hosts without Pipedream credentials, saved Pipedream accounts must not hide
+native Notion, Linear, or Slack connections when selecting import tools.
+
+Provider and custom-server More menus contain Disable, Reconnect, and Disconnect;
+custom servers also offer Rename. Disabled grants show Enable. Unauthenticated
+custom servers show Connect and Remove. Disconnect/Remove require confirmation.
+Adding a custom MCP saves its name and URL; Connect on its row starts OAuth.
+Enabled custom servers are offered to the owner's agent sessions (Cursor, Claude,
+Codex, macrod, in-memory) alongside connected apps, through the same session
+egress path: the sandbox sees the server under its name and a URL key, never the
+server's address or token. A disabled server is not offered. If a server's
+connection has expired, its tool calls return a message telling the agent to
+have the owner use Reconnect under Custom MCP; there is no `Connect` chip for
+custom servers. Agents configured with a fixed app selection do not receive the
+owner's custom servers.
+An agent reply's `Connect <app>` chip still starts that app's connection flow.
+Cursor stays in Agents → Runtimes with its API key and default model controls; it is not
+featured or offered in the Connections catalog. Personal Gmail and GitHub account
+links remain in Settings → Integrations. The native-only Connections page remains
+available when `pipedream-mcp` is disabled.
+Open Settings with the rail's gear button or `Ctrl+;`; leave it by picking any other rail item.
+
+`Agents` → `New agent` (or edit an existing agent) opens a full-page form. The
+`Instructions` field is a Lexical contenteditable textbox, not a textarea. It
+supports Markdown headings, lists, emphasis, code, links, and the normal `@`
+mention picker; select text to open the formatting menu. Saved instructions
+retain mention identities using the shared editor's Markdown format and reopen
+with their formatting intact. Enter adds a new paragraph; use `Create agent` or
+`Save changes` to submit. The form also includes runtime selectors.
+Under the runtime, `Answering a mention` chooses between `Coding agent` (a
+channel mention is answered with a magic chip that opens into the live session)
+and `Chat agent` (the agent replies in the thread, like `@macro`). It is the
+agent's own setting and always saved: a new form starts from the selected runtime
+- Macro's in-memory runtime as chat, every other runtime as coding - and picking a
+different runtime resets it to that default, but only the saved choice counts.
+The model list is loaded live and independently for Macro Agent, connected Cursor, and every
+registered macrod harness. The selected harness stays selected when the list refreshes.
+A paired macrod connects on startup, so models can load before any agents are bound.
+A harness can show `Loading models…`, an unsupported message, or
+a retryable error without hiding the other harnesses. Editing preserves a saved model that
+is no longer offered and labels it `saved, unavailable`. A macrod with no responding runtime
+can remain loading until the 10-second discovery timeout; use Retry after reconnecting it.
+New macrod sessions use the agent's saved model before sending the first prompt.
+Changing that default applies to new sessions; existing sessions keep their selected model.
+If the runtime rejects the saved model, the prompt fails instead of using a different model.
+
+The `Runtimes` section shows built-in Macro, Cursor, Claude, and Codex configuration, followed by paired macrod runtimes. Claude's card appears only with the `claude-cloud` flag, and Codex's only within the agents and Codex rollouts. The “Bring your own agent” card sits above the Agents / Runtimes navigation and is visible on both sections. It rotates Claude Code, OpenCode, OpenClaw, and Hermes; reduced motion keeps a static name. Its `New runtime` action opens the full-page pairing flow from either section: enter the code, look up the request, review the machine, name, sharing and permission consent, then Approve and Done. Back/Cancel returns to the runtime list. Destructive removal still requires confirmation. `/settings/runtimes` opens this section; legacy `/settings/harness?pair=…` links remain supported.
+Connection chips in agent replies open this page, including before any account is connected. Cursor's default-model picker uses
+the same live model discovery and retains its existing save action.
+
+The Codex row uses the OpenAI logo and the same icon, button, and status styling
+as Cursor. Under **Codex**, choose **Connect with ChatGPT**, copy the displayed device code,
+and use **Continue to ChatGPT** to finish sign-in in the provider tab. The Macro
+page displays pending, expired, failed, and retryable error states; **Cancel
+sign-in** cancels the attempt. After connecting, choose a **Cloud environment**
+and click **Save Codex settings** before using Codex. Options show their
+repositories. New sessions always use the `main` branch; there is no branch
+picker or automatic repository selection. Changed selections display **Unsaved
+changes** until the server confirms them. The save button is disabled until an
+environment is selected, and when it matches the saved environment.
+These choices apply to new sessions. **Disconnect** in the Codex row (accessible
+name **Disconnect ChatGPT**) asks for confirmation before removing the connection.
+Claude, Cursor, and Connections disconnect actions use the same shared confirmation
+dialog (a drawer on mobile); Cancel leaves the connection intact. Claude's row
+keeps its layout while status loads, and sign-in details appear only after Connect.
+The UI never asks for an
+OAuth token.
+
+The Codex section and its auth/config requests were exercised in Chromium with
+mocked backend responses on 2026-09-15. Provider login and a full deployed Macro
+session were not exercised by that UI check.
diff --git a/docs/agent-guide/soup-live-updates.md b/docs/agent-guide/soup-live-updates.md
new file mode 100644
index 0000000000..fb61a8fd48
--- /dev/null
+++ b/docs/agent-guide/soup-live-updates.md
@@ -0,0 +1,136 @@
+# Live updates in flat Soup lists
+
+## Live updates in flat Soup lists
+
+The normalized cache retains at most 64 flat/grouped Soup page snapshots per
+viewer, with a combined 512 KiB encoded budget. Older pages can require a network
+refetch when revisited; normalized entities and queued offline edits are not
+removed. Backfills hydrate entities/indexes without retaining their pagination
+wrappers. Existing oversized viewer records compact once on a compatible open,
+without resetting storage generation or pending mutations. To verify, load many
+pages, revisit an evicted page online, and confirm an offline property edit still
+replays after reopening the app.
+
+With browser or native Tauri GraphQL caching enabled, locally supported flat lists reconcile their
+loaded server pages with matching cached entities. Complete matching updates can
+appear without a list refetch; confirmed non-matches and explicit deletions disappear.
+Rows whose current predicate facts are unknown retain their previous server membership
+and sort evidence until hydration or a network refresh resolves them. Unrelated
+notification-only cache records do not block other rows' updates. While recomputation
+is pending, the last rendered result for the same query and cache generation stays
+visible; local results do not trigger the tab-loading bar. A fresh server response
+still replaces that result, and initial loads without usable data retain normal loading
+indicators. A transport failure does not hide usable current-query local results,
+including empty results; HTTP responses and GraphQL errors still surface.
+To check reconnect behavior, load a non-Mail list online, let background hydration
+advance its cache while offline, then reconnect without delivering a fresh network
+response. The newer local result must remain visible; connectivity alone must not
+restore the older network snapshot. A fresh network response can take authority again.
+
+This is a best-effort display, not proof that every matching entity is cached. Outside
+the supported cached-Mail slice below, loading more follows the original server cursors
+and preserves already loaded pages.
+Newly loaded server rows join the retained display immediately, without duplicates or
+waiting for local recomputation to succeed. Removing pages from the server baseline
+invalidates overlays built from those pages.
+Changing filters or resetting the cache discards prior reconciliation evidence. Grouped
+lists, unsupported filters/sorts, and non-cache transports keep their existing
+network behavior.
+
+For Documents (including Tasks), Projects, Chats, and participating Channels,
+exact `UNSEEN`/`SEEN` notification filters also reconcile locally with
+created/updated timestamp sorts.
+Marking a notification done removes only that notification's contribution immediately;
+other active notifications can keep the entity in the list. Seen/reopen operations
+update filter membership on the authoritative reply, not from a guessed optimistic
+state. Rollback restores only the failed operation's contribution. `DONE` predicates,
+other entity partitions, and notified-at sorting still use the network path.
+
+The Mark done action (`e`, row menu) hides its rows at once from GraphQL lists that
+exclude done items, such as Email Important/Noise and Home Signal, without waiting
+for the server. Email All keeps the row and flips its done indicator immediately.
+GraphQL Undo is offered as soon as Done applies locally, even while its initial
+write is pending. Undo restores the row and focus immediately; its server write
+waits for the initial outcomes and uses only acknowledged notification IDs.
+A late Done reply must not settle or overwrite the newer Undo display intent.
+Undo also restores a previously admitted row after the cache has removed it,
+without waiting for the reversal's server reply; changing filters/sort clears
+those view-local restoration snapshots. Home's separate recent-activity inclusion
+rules are unchanged. Test Done/Undo/Redo with delayed replies and verify both flat
+and grouped rows/counts. A failure must roll back only its own local intent.
+Test mixed committed/queued/rejected archives and notification writes,
+including an archive that fails while its notifications succeed (and vice versa). Accepted writes retain Undo; rejected siblings must neither
+reappear in its request nor be retried by Redo. Partial feedback keeps an Undo
+action. A reply with no matching notification IDs must release that target's
+optimistic hide and notification overrides immediately, even if Undo was never
+clicked and mounted readers remain stale. Do not wait for acknowledgement or a
+timer when there is no receipt. Accepted siblings keep their own display intent;
+a no-op target cannot borrow their IDs to restore its row. Mixed accepted/no-op
+results replace the optimistic full-count toast with the actual completed count
+and retain Undo for accepted writes. An empty notification receipt alone must not
+make a successfully archived email or completed reminder look partially failed.
+Partial Undo/Redo failures retry only the failed writes.
+If every initial write fails, retire its pending Undo/Redo entry and unwind both
+Done and any early Undo overrides. Disposal or clearing history while a reversal
+is pending must not resurrect that entry when its response arrives. Also delay
+Redo, then perform a new action: the late Redo's success or failure must not
+repopulate either history stack or show its stale completion toast. The next Undo
+must still target the newer action; already-dispatched network writes are not
+cancelled by this history fence.
+Newer in-scope activity can re-admit a row, but loading an older notification or
+activity in a separate channel thread must not. Redo targets the original exact
+notification IDs, not notifications received since the original action. A newer
+Done must win over an older retained overlay. Delay reconciliation past a minute:
+pending/stale state must not simply expire and resurrect the row. Once committed,
+mounted cache readers must acknowledge the intent before its overlay is released.
+GraphQL display intents are scoped to the authenticated viewer and login session.
+Login/logout retires old buckets; even same-account native reauthentication must
+not let old overlay Undo/Redo handles or a late refresh republish old intent.
+Verify account changes with overlapping entity IDs and a pending/failed refresh.
+After a successful Done, verify that the row stays gone after a reload.
+Test GraphQL list optimism independently of REST: block REST Soup, email-thread,
+and user-notification data endpoints before page initialization, then confirm
+GraphQL alone populates the list. Hold GraphQL mutation replies while testing
+Done/Undo/Redo and rejection: row feedback must not depend on REST cache reads,
+patches, cancellation, or invalidation. Auth/account metadata is outside this
+row-data boundary. Test the REST path separately, not as a GraphQL fallback.
+Email Reminders contains original email rows: Done archives those conversations,
+with the same immediate GraphQL Undo behavior as the other email tabs.
+In Tasks, Email, Home and Drive, rows keep their DOM when the list updates. A
+property edit or a rename updates the edited row in place instead of rebuilding
+every visible row. To verify, watch the row nodes with a `MutationObserver` while
+editing: only moved or removed rows should be added or removed. Rename a row and
+then drag it: its drag label/payload must use the new fields without another
+registration/layout measurement.
+
+Desktop multi-select filter menus in Home, Tasks, Drive, Email, Reviews, Search,
+CRM, Calendar, and database option-value filters close after an ordinary click or
+Enter. Hold Shift while clicking or pressing Enter to toggle individual options
+and keep the menu open for further selections. Shift does not select a range.
+Single-select controls and mobile filter drawers retain their existing behavior.
+
+Channels use the same general Soup reconciliation path, not a separate local page
+chain. Channel ID, type, team, organization, importance, and participant-scoped
+filters operate over synchronized channel metadata. The default channel scope
+requires active participation. Filters that widen to unjoined team channels,
+message sender/mentions, and channel threads remain network-only. Missing channel
+metadata or notification snapshots are unknown, not empty. The existing core
+backfill checkpoint is refreshed to index channel rows; queued work is preserved.
+
+Notification facts use the existing active-only GraphQL edge and primary entity
+association. Missing/partial or over-budget snapshots remain incomplete, never an
+empty notification set; display metadata decoding omissions remain a best-effort
+limitation. The current `soup-flat-v5` projection retains notification IDs and
+adds complete select-option/entity-reference property snapshots. Tags, task status,
+priority and assignee selections compose with owner and type filters. The shared
+256-fact per-entity budget still applies: missing, malformed or over-budget property
+snapshots are unknown, never evidence of absence. Property-only mutations update
+these postings atomically; rollback does not restore unrelated property values.
+Checkpoint v14 rehydrates older projections without wiping normalized records or
+queued mutations. General Soup still uses its existing server pagination; filter-only
+offline checks use an ungrouped view with a created/updated timestamp sort.
+
+Realtime Soup batches coalesce repeated entity IDs (including entity type), keeping
+that entity's last operation in the batch. Emitted `SoupUpdated` items are non-null.
+If viewer-scoped hydration finds no item, the backend logs and omits that update;
+it does not imply deletion. Only explicit `GraphqlCacheDeletion` events remove records.
diff --git a/docs/AGENT_GUIDE/tasks.md b/docs/agent-guide/tasks.md
similarity index 97%
rename from docs/AGENT_GUIDE/tasks.md
rename to docs/agent-guide/tasks.md
index 52860298d7..22398f9aee 100644
--- a/docs/AGENT_GUIDE/tasks.md
+++ b/docs/agent-guide/tasks.md
@@ -838,3 +838,28 @@ Use the caret to expand or collapse a branch. A folder-only parent expands witho
filtering; clicking an actual tag selects only that tag, including when it has
children. Personal and team paths stay separate. Ancestors of restored selected
tags start expanded. Filter-menu options continue to show full tag names.
+
+## Tasks — `/app/component/tasks`
+
+Task navigation uses `My Tasks`, `All Tasks`, and `Created by me`. The desktop
+sidebar has a full-width `New task` action and a collapsible list of task favorites;
+tag filtering lives in the `Filter` menu. Favorite rows open their tasks.
+Normal row and favorite activation replaces the list with the editable task
+document; its originating-tab breadcrumb returns to the list and its
+header exposes Share and the task Details/Properties panel. Shift-click opens
+the task in a new split instead. While the list is visible, `J` and `K` move
+focus without opening a task until activation. In an open task detail, they
+replace it with the next or previous task in the same filtered order.
+
+When `enable-tasks-reviews` is enabled, `Reviews` appears above `My Tasks` as a
+shortcut to the separate Reviews view. It lists accessible GitHub pull requests;
+Open/Closed tabs below search and filters default to Open; Closed includes merged
+PRs. Status also remains in the filter menu. Custom multi-status selections hide
+the tabs except for the combined Closed preset.
+The list topbar says Reviews at narrow widths or with its sidebar collapsed;
+selecting one opens `/app/reviews/pr/<foreignEntityId>` with a Reviews breadcrumb.
+See [Tasks](tasks.md#reviews-view) for verification.
+
+The desktop `Create` → `Task` modal uses the standard dialog panel, circular
+icon controls, and a pill-shaped `Create Task` button with 16px outer padding.
+The mobile task drawer retains its existing layout.
diff --git a/docs/agent-guide/ui-conventions.md b/docs/agent-guide/ui-conventions.md
new file mode 100644
index 0000000000..52a0e0a848
--- /dev/null
+++ b/docs/agent-guide/ui-conventions.md
@@ -0,0 +1,78 @@
+# UI conventions
+
+## Home list loading
+
+Home shows compact row skeletons during initial loading, with taller notification
+placeholders on touch devices. Date grouping includes a placeholder heading.
+Pagination appends three placeholders without replacing existing items; refresh
+keeps loaded items visible. Wait for real rows before navigating or selecting.
+
+## Top bars
+
+Low-emphasis right-aligned split-header actions (including Calendar's touch/preview
+New event and Channel's idle Call and Ask Macro) are borderless with a rounded-xl
+background on hover. Emphasized variants retain their treatment, including an
+active call's green ink and outline frame. Channel, company, contact, and project
+content tabs use inset controls in the top bar. Button sizes do not change variant colors or framing; individual
+framed controls default to glass on touch and flat on desktop. Use `glass={true}`
+to enable glass on all devices, or `glass={false}` to disable it everywhere.
+Embedded and low-emphasis actions use `ghost`; inline calendar-invitation text
+actions remove the transparent border to keep their text alignment.
+
+## Dialog actions
+
+Cancel uses a ghost button. Confirm, save, and create actions use strong: the
+outline surface and border with semibold text, without inverted colors. Disabled
+and pending primary actions retain the strong variant. Mobile confirmation drawers
+use the same action hierarchy.
+
+## List-item sharing
+
+Right-click a shareable list row and choose **Share**. The sharing dialog must
+remain open after the context menu closes, with recipient selection and the
+optional message available. Dismiss it with Cancel, then reopen Share on the
+same row and confirm focus enters the recipient selector again. Opening or
+cancelling the dialog does not change access; do not submit shares on real dev
+data unless authorized.
+
+## User cards
+
+Avatar and user-mention cards open on hover on pointer devices and as a bottom
+sheet on touch devices. With a keyboard on a touch device, Tab to the trigger and
+press Enter or Space; verify focus enters the sheet and returns to the opener
+after dismissal or copying, including after reopening. DM, Open contact, and
+Assign task should leave focus in their destination when the sheet closes.
+On pointer devices, avatars should stay out of the Tab order while still opening
+their cards on hover. Copy email/name confirms only after the clipboard
+write succeeds: the hover card shows a checkmark, while the sheet closes. A failed
+write shows failure feedback and leaves the card open for retry.
+
+## Floating block information panels
+
+Actions live in the top bar immediately before Share, with consistent compact
+buttons (labels collapse on narrow headers). There are no Actions sections in
+information panels. Markdown/tasks include Ask Macro and document/task dispatch; email
+includes Ask Macro and Create task; PDF and calls include Ask Macro. Native
+projects put Delete in the `Project actions` menu after the project title.
+
+Standard metadata is quiet, non-collapsible text at the bottom of each panel,
+separated by a muted divider. Owner and available timestamps share one format;
+Markdown adds word/character counts. There is no standard Details or Stats
+disclosure. Agent runtime information remains in its dedicated Session section.
+
+Block information panels float over the right side of the block without changing
+the content width or its centered position. A single rounded bubble fits its
+contents, with `edge-muted` dividers between sections. Its height is capped at
+the block height with internal scrolling. At every width it starts closed and
+acts as a split-local overlay menu on desktop. The top-right sidebar icon, rotated
+180 degrees, opens it, and clicking outside dismisses it. On touch devices the
+control uses the Phosphor info-circle icon and opens the standard bottom drawer
+with a drag handle, scrollable sections, and safe-area/keyboard-aware spacing.
+Dismiss the drawer by swiping down or tapping its backdrop. Opening is never
+restored from saved preferences or triggered by the global chrome shortcut. The 320px bubble enters
+with a slight slide from the right and a 120ms fade;
+closing fades it out in 70ms.
+This applies across Markdown/tasks,
+snippets, email, calls, agents, pull requests, projects, and all file blocks
+including PDFs, images, code, video, canvas, unknown file types, and CRM company
+and contact views (both inside the CRM workspace and in standalone blocks).
diff --git a/docs/AGENT_GUIDE/view-tours.md b/docs/agent-guide/view-tours.md
similarity index 100%
rename from docs/AGENT_GUIDE/view-tours.md
rename to docs/agent-guide/view-tours.md
diff --git a/docs/AGENT_EFFORT.md b/docs/architecture/agent-effort.md
similarity index 100%
rename from docs/AGENT_EFFORT.md
rename to docs/architecture/agent-effort.md
diff --git a/docs/CANVAS_LEGACY_BRIDGE.md b/docs/architecture/canvas-legacy-bridge.md
similarity index 91%
rename from docs/CANVAS_LEGACY_BRIDGE.md
rename to docs/architecture/canvas-legacy-bridge.md
index 061d06c27c..de862b2936 100644
--- a/docs/CANVAS_LEGACY_BRIDGE.md
+++ b/docs/architecture/canvas-legacy-bridge.md
@@ -35,6 +35,6 @@ Unsupported records and unknown versions show an error without changing the
saved document. Validate any expanded import support against representative
fixtures before allowing write-back.
-See the [architecture overview](CANVAS_ARCHITECTURE.md),
-[parity plan](GRAPHICS_PARITY.md), and
-[Canvas Next format notes](../apps/web/src/features/block-canvas/README.md).
+See the [architecture overview](canvas.md),
+[parity plan](../design/graphics-parity.md), and
+[Canvas Next format notes](../../apps/web/src/features/block-canvas/README.md).
diff --git a/docs/CANVAS_ARCHITECTURE.md b/docs/architecture/canvas.md
similarity index 87%
rename from docs/CANVAS_ARCHITECTURE.md
rename to docs/architecture/canvas.md
index 8b6b409988..b846705df1 100644
--- a/docs/CANVAS_ARCHITECTURE.md
+++ b/docs/architecture/canvas.md
@@ -38,7 +38,7 @@ integration and conflict-policy approval remain separate work.
- Add capabilities through typed definitions and explicit adapters.
- Keep application migration and compatibility logic outside graphics core.
-See the [graphics package README](../packages/graphics/README.md),
-[scene foundation](GRAPHICS_SCENE_FOUNDATION.md),
-[Canvas Next README](../apps/web/src/features/block-canvas/README.md),
-and [collaboration notes](../packages/graphics/src/loro/README.md).
+See the [graphics package README](../../packages/graphics/README.md),
+[scene foundation](graphics-scene-foundation.md),
+[Canvas Next README](../../apps/web/src/features/block-canvas/README.md),
+and [collaboration notes](../../packages/graphics/src/loro/README.md).
diff --git a/docs/CLOUD_STORAGE.md b/docs/architecture/cloud-storage.md
similarity index 78%
rename from docs/CLOUD_STORAGE.md
rename to docs/architecture/cloud-storage.md
index e995c06d04..31f3825982 100644
--- a/docs/CLOUD_STORAGE.md
+++ b/docs/architecture/cloud-storage.md
@@ -5,17 +5,17 @@ libraries in `crates/`, and deployment definitions in `infra/`.
## Development and testing
-- [Rust development](RUST_DEVELOPMENT.md): toolchain, build/check commands, and
+- [Rust development](../development/rust.md): toolchain, build/check commands, and
tests for the affected packages.
-- [Database development](DATABASE_DEVELOPMENT.md): local test databases,
+- [Database development](../development/database.md): local test databases,
migrations, SQLx cache preparation, and approved destructive resets.
-- [Running locally](RUNNING_LOCALLY.md): frontend against hosted services or a
+- [Running locally](../development/running-locally.md): frontend against hosted services or a
full local stack.
-- [Cursor Cloud](CURSOR_CLOUD.md): Cloud-only setup and rebuild entry points.
+- [Cursor Cloud](../development/cursor-cloud.md): Cloud-only setup and rebuild entry points.
## Deployment
-To learn more read the [infra](../infra/README.md) documentation.
+To learn more read the [infra](../../infra/README.md) documentation.
## Instructions
diff --git a/docs/CURSOR_AGENT_TRANSPORT.md b/docs/architecture/cursor-agent-transport.md
similarity index 100%
rename from docs/CURSOR_AGENT_TRANSPORT.md
rename to docs/architecture/cursor-agent-transport.md
diff --git a/docs/EMAIL_FEATURE_ARCHITECTURE.md b/docs/architecture/email.md
similarity index 99%
rename from docs/EMAIL_FEATURE_ARCHITECTURE.md
rename to docs/architecture/email.md
index b7db1572e5..7a0526e642 100644
--- a/docs/EMAIL_FEATURE_ARCHITECTURE.md
+++ b/docs/architecture/email.md
@@ -1,7 +1,7 @@
# Email feature architecture
Email applies the stronger composition and capability
-boundaries in [Frontend feature architecture](FRONTEND_FEATURE_ARCHITECTURE.md).
+boundaries in [Frontend feature architecture](frontend-features.md).
Its reusable packages live under `apps/web/src/features/`. The application still
opens `/app/email/:threadId`, and existing drafts and mailto composition use the
same application routes.
@@ -298,7 +298,7 @@ refined in documentation.
## State and lifetime rules
Ordinary email body rendering is now owned by
-[`packages/email-renderer`](../packages/email-renderer/README.md). Its default
+[`packages/email-renderer`](../../packages/email-renderer/README.md). Its default
entry point prepares serializable HTML from a narrow content input without DOM,
Solid, flags, or services. Its `/browser` entry point owns Shadow DOM, computed
styles, containment, width fitting, and resource cleanup. `email-message` only
diff --git a/docs/FRONTEND_FEATURE_ARCHITECTURE.md b/docs/architecture/frontend-features.md
similarity index 94%
rename from docs/FRONTEND_FEATURE_ARCHITECTURE.md
rename to docs/architecture/frontend-features.md
index e83b2e6207..4814825243 100644
--- a/docs/FRONTEND_FEATURE_ARCHITECTURE.md
+++ b/docs/architecture/frontend-features.md
@@ -7,7 +7,7 @@ restructuring an existing feature, with the stronger production-composition and
feature-contract boundaries defined here. Activity is a worked example with
documented migration gaps, not a complete implementation of every rule below.
This is the detailed companion to FE-33 in
-[the style guide](STYLE_GUIDE.md).
+[`web/architecture.md`](../../.agents/rules/web/architecture.md).
The goal is to make ownership visible: feature logic can run without the app,
reactive behavior can be tested without rendering, and the same visual component
@@ -137,9 +137,9 @@ level; a component chooses the corresponding color and icon. Tests of grouping
or descriptions should need ordinary inputs and assertions, without an app
provider or mocked service.
-See [event.ts](../apps/web/src/features/activity/core/event.ts),
-[describe-action.ts](../apps/web/src/features/activity/core/describe-action.ts), and
-[intensity.ts](../apps/web/src/features/activity/core/intensity.ts).
+See [event.ts](../../apps/web/src/features/activity/core/event.ts),
+[describe-action.ts](../../apps/web/src/features/activity/core/describe-action.ts), and
+[intensity.ts](../../apps/web/src/features/activity/core/intensity.ts).
### `queries/`: adapt transport and own query mechanics
@@ -154,7 +154,7 @@ An urql client is appropriate as an adapter input; it should not become the
reactive feature consumer's capability contract. Adapters implement the narrow
sources described in [Feature-owned contracts](#feature-owned-contracts).
-The current [feed-query.ts](../apps/web/src/features/activity/queries/feed-query.ts)
+The current [feed-query.ts](../../apps/web/src/features/activity/queries/feed-query.ts)
illustrates query mechanics and decoding but still accepts the old context's
`graphql` field. Generated documents and transport types are appropriate in this
layer. Return feature models to consumers instead of leaking fragments into
@@ -163,7 +163,7 @@ reserve `decode`/`parse` for actual decoding or validation. Keep only consumed
fields, and return small domain results instead of unnecessary transport envelopes.
Keep differences such as missing entity versus found entity with no history
explicit, as in
-[select-entity-activity.ts](../apps/web/src/features/activity/queries/select-entity-activity.ts).
+[select-entity-activity.ts](../../apps/web/src/features/activity/queries/select-entity-activity.ts).
Query inputs that can change should stay reactive. Pause unsupported or incomplete
requests through the existing query wrapper's enabled mechanism. Choose stale-data
@@ -224,10 +224,10 @@ Use derived accessors for cheap computations and memos for expensive derivations
or referential stability. Follow the existing Solid guidance on avoiding effects
for derived state and guarding resource reads. Activity's urql behavior does not
override the warnings about eager TanStack `query.data` reads in
-[apps/web/AGENTS.md](../apps/web/AGENTS.md).
+[apps/web/AGENTS.md](../../apps/web/AGENTS.md).
-See [my-activity.ts](../apps/web/src/features/activity/primitives/my-activity.ts) and
-[entity-opener.ts](../apps/web/src/features/activity/primitives/entity-opener.ts).
+See [my-activity.ts](../../apps/web/src/features/activity/primitives/my-activity.ts) and
+[entity-opener.ts](../../apps/web/src/features/activity/primitives/entity-opener.ts).
### `components/`: props in, JSX out
@@ -248,8 +248,8 @@ it should not take an entity ID and secretly resolve all its app dependencies.
Resolve shared metadata once in the composed owner and pass it to its children.
See the presentational
-[activity-timeline-row.tsx](../apps/web/src/features/activity/components/activity-timeline-row.tsx)
-and [top-entities.tsx](../apps/web/src/features/activity/components/top-entities.tsx).
+[activity-timeline-row.tsx](../../apps/web/src/features/activity/components/activity-timeline-row.tsx)
+and [top-entities.tsx](../../apps/web/src/features/activity/components/top-entities.tsx).
### `views/`: compose a use case
@@ -265,7 +265,7 @@ owns its “Show all” toggle locally. The architecture does not require a sepa
primitive for every signal or a separate exported component for every wrapper.
The two `activity-timeline-row.tsx` files show the intended split. The
-[view](../apps/web/src/features/activity/views/activity-timeline-row.tsx) obtains
+[view](../../apps/web/src/features/activity/views/activity-timeline-row.tsx) obtains
entity display, property definitions, and callback-based handlers, then passes
them to the presentational row. External hosts choose the view when they want
that wiring, and the component when they already have resolved values.
@@ -292,7 +292,7 @@ useful capability signatures. Replace its raw `graphql` capability for state
consumers with narrow feature sources as described below. Display contracts can
include a resolved icon accessor; they do not have core's purity requirement.
-The existing [activity-context.tsx](../apps/web/src/features/activity/context/activity-context.tsx)
+The existing [activity-context.tsx](../../apps/web/src/features/activity/context/activity-context.tsx)
combines this contract with a production fallback. That is a migration gap.
## Separate production composition
@@ -445,7 +445,7 @@ to replace. Activity computes the browser time zone in the query layer.
For navigation, the primitive translates an interaction into a target and the
host decides what to do with it. `createEntityOpener` passes `block`, `id`,
`params`, and `newSplit` to `onOpen`; the host's
-[open-entity-in-split.ts](../apps/web/src/features/activity/open-entity-in-split.ts)
+[open-entity-in-split.ts](../../apps/web/src/features/activity/open-entity-in-split.ts)
calls the app navigation API. Ordinary feature layers do not import that API.
Shared event-translation helpers are allowed in primitives when they delegate
the actual action to the supplied callback.
@@ -469,7 +469,7 @@ the Solid feature translates accessors to plain values and registers disposal.
Supply policy and host capabilities explicitly. Do not let the library import
app flags, clients, routes, or block signals through a convenience barrel.
-[`packages/email-renderer`](../packages/email-renderer/README.md) demonstrates
+[`packages/email-renderer`](../../packages/email-renderer/README.md) demonstrates
this split: HTML/CSS preparation compiles without DOM libraries and runs under
Node; the browser layer handles Shadow DOM, computed colors, layout and resource
lifetimes; the email-message adapter retains Solid and Macro Markdown integration.
@@ -491,9 +491,9 @@ current-user hook, or display resolvers.
| Host integration | Browser verification on the relevant surfaces | Flag gates, mounting, real mentions, navigation, focus/scroll behavior |
The reference's
-[mock-context.ts](../apps/web/src/features/activity/tests/mock-context.ts) supplies
+[mock-context.ts](../../apps/web/src/features/activity/tests/mock-context.ts) supplies
defaults and overrides for the capability record.
-[mock-graphql.ts](../apps/web/src/features/activity/tests/mock-graphql.ts) exposes
+[mock-graphql.ts](../../apps/web/src/features/activity/tests/mock-graphql.ts) exposes
pending operations that tests resolve or fail, exercising the real query and
primitive code. Its fake implements the query methods those tests need; extend a
fake for new operations rather than assuming it is a complete urql client.
@@ -509,8 +509,8 @@ Check that context/state imports work without production-service quarantine and
that omitted provider setup fails clearly. Use existing import smoke tests where
available, or inspect and exercise the import boundary when migrating it.
-See [my-activity.test.ts](../apps/web/src/features/activity/primitives/my-activity.test.ts)
-and [my-activity-view.test.tsx](../apps/web/src/features/activity/views/my-activity-view.test.tsx).
+See [my-activity.test.ts](../../apps/web/src/features/activity/primitives/my-activity.test.ts)
+and [my-activity-view.test.tsx](../../apps/web/src/features/activity/views/my-activity-view.test.tsx).
The current view test still stubs shared layout/Markdown UI and quarantines
websocket import-time effects with `vi.mock`. Those are integration limitations;
feature data and capability behavior are supplied through the provider. Do not
@@ -533,7 +533,7 @@ bun run check
```
Replace the test path with the feature under change. Exercise user-visible changes
-in a browser using [the frontend instructions](../apps/web/AGENTS.md). Documentation
+in a browser using [the frontend instructions](../../apps/web/AGENTS.md). Documentation
changes alone do not require bringing up a frontend or backend stack.
## Adopting the structure
@@ -564,13 +564,13 @@ changes alone do not require bringing up a frontend or backend stack.
7. **Register enforcement and verify.** Add the adopting feature's layer globs to
both TypeScript and TSX feature rules below. Test the changed behavior, inspect
warnings, and exercise affected UI surfaces. Update
- [the agent interaction guide](AGENT_GUIDE/README.md) if routes or interaction
+ [the agent interaction guide](../agent-guide/README.md) if routes or interaction
behavior changed; a file move alone does not change that guide.
## Enforcement and reference limitations
-The rules live in [rules/ast-grep](../rules/ast-grep), configured by
-[sgconfig.yml](../sgconfig.yml). Each family has a `ts-` and `tsx-` rule because
+The rules live in [rules/ast-grep](../../rules/ast-grep), configured by
+[sgconfig.yml](../../sgconfig.yml). Each family has a `ts-` and `tsx-` rule because
the scanner treats those languages separately. When a feature adopts the layout,
update `files` in all eight rule files with the corresponding layer paths:
@@ -658,7 +658,7 @@ general exceptions without a concrete need and an updated explanation.
## Email application of the stronger boundaries
-[Email feature architecture](EMAIL_FEATURE_ARCHITECTURE.md) documents the complete
+[Email feature architecture](email.md) documents the complete
`block-email` experiment: separate `email-thread`, `email-message`, and
`email-compose` ownership, a thin block adapter, production entry points, domain
sources, and tests of imports and instance lifetimes. Use it alongside activity
diff --git a/docs/GRAPHICS_API.md b/docs/architecture/graphics-api.md
similarity index 91%
rename from docs/GRAPHICS_API.md
rename to docs/architecture/graphics-api.md
index e9f1e09200..20997f9c94 100644
--- a/docs/GRAPHICS_API.md
+++ b/docs/architecture/graphics-api.md
@@ -33,6 +33,6 @@ Host applications provide text measurement and editing, asset resolution,
navigation, permissions, storage, and service integration. Graphics stores opaque
text and stable asset/entity references; it does not import application services.
-See the [package README](../packages/graphics/README.md),
-[scene foundation](GRAPHICS_SCENE_FOUNDATION.md), and
-[Canvas architecture](CANVAS_ARCHITECTURE.md).
+See the [package README](../../packages/graphics/README.md),
+[scene foundation](graphics-scene-foundation.md), and
+[Canvas architecture](canvas.md).
diff --git a/docs/GRAPHICS_SCENE_FOUNDATION.md b/docs/architecture/graphics-scene-foundation.md
similarity index 91%
rename from docs/GRAPHICS_SCENE_FOUNDATION.md
rename to docs/architecture/graphics-scene-foundation.md
index b82977ad90..3a24bff5b2 100644
--- a/docs/GRAPHICS_SCENE_FOUNDATION.md
+++ b/docs/architecture/graphics-scene-foundation.md
@@ -38,6 +38,6 @@ maps the same logical tree to collaborative storage and uses native local undo.
Production use still requires approved conflict behavior for concurrent reparent,
delete, ordering, and pose edits.
-See the [graphics README](../packages/graphics/README.md),
-[Loro notes](../packages/graphics/src/loro/README.md), and
-[architecture overview](CANVAS_ARCHITECTURE.md).
+See the [graphics README](../../packages/graphics/README.md),
+[Loro notes](../../packages/graphics/src/loro/README.md), and
+[architecture overview](canvas.md).
diff --git a/docs/ACP_ELICITATION.md b/docs/design/acp-elicitation.md
similarity index 99%
rename from docs/ACP_ELICITATION.md
rename to docs/design/acp-elicitation.md
index 95462d6f5e..6b78408565 100644
--- a/docs/ACP_ELICITATION.md
+++ b/docs/design/acp-elicitation.md
@@ -147,7 +147,7 @@ do next?". Different UX, different policy, different defaults.
## What Macro does today
Macro is an ACP **Client**. The harness does not care which agent is on the
-other end of the pipe (`docs/CURSOR_AGENT_TRANSPORT.md`). The pieces that
+other end of the pipe (`docs/architecture/cursor-agent-transport.md`). The pieces that
matter:
```text
@@ -1053,7 +1053,7 @@ eyeballed without an agent.
#### Agent guide
-`docs/AGENT_GUIDE/ai-chat.md`: one paragraph — an agent session may show
+`docs/agent-guide/ai-chat.md`: one paragraph — an agent session may show
a form or a link-consent card; answer it or press Stop; queued messages
send after the agent finishes.
diff --git a/docs/ANDROID_READINESS_AUDIT.md b/docs/design/android-readiness-audit.md
similarity index 72%
rename from docs/ANDROID_READINESS_AUDIT.md
rename to docs/design/android-readiness-audit.md
index 359d4a1015..af7184d09a 100644
--- a/docs/ANDROID_READINESS_AUDIT.md
+++ b/docs/design/android-readiness-audit.md
@@ -8,7 +8,7 @@ Scope: parity with the current iPhone app, including sign-in/onboarding, messagi
## What can be reused
-- The checked-in Android Gradle project already uses `com.macro.app.prod`, SDK/target 36, minimum SDK 24, Firebase Messaging, and custom-scheme/HTTP App Link intent filters. See [Android Gradle configuration](../apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts) and [manifest](../apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml).
+- The checked-in Android Gradle project already uses `com.macro.app.prod`, SDK/target 36, minimum SDK 24, Firebase Messaging, and custom-scheme/HTTP App Link intent filters. See [Android Gradle configuration](../../apps/web/tauri/src-tauri/gen/android/app/build.gradle.kts) and [manifest](../../apps/web/tauri/src-tauri/gen/android/app/src/main/AndroidManifest.xml).
- The shared Solid frontend recognizes Android, has mobile layouts, and already routes native HTTP/WebSocket traffic through Tauri. There is Android safe-area initialization.
- Native GraphQL caching and the bundle updater have cross-platform Rust implementations; the updater already reads Android's native build number.
- Device registration, Android device models, an SNS FCM transport, and dev/prod FCM infrastructure exist. **Delivery is incomplete**, as detailed below.
@@ -20,7 +20,7 @@ Priorities: **P0** blocks a usable initial release; **P1** is required for full
### 1. Repair the Android build and plugin dependency graph — P0, medium
-**Confirmed:** [app Cargo.toml](../apps/web/tauri/src-tauri/Cargo.toml) declares only `rlib` and `staticlib`; Android needs the shared library output (`cdylib`). The shared [mobile capability](../apps/web/tauri/src-tauri/capabilities/mobile.json) applies to Android but references edit-menu, pasteboard, photo-library, network-status, and call-kit permissions whose dependencies are restricted to iOS. The pinned Tauri build code validates these permissions against available plugin manifests.
+**Confirmed:** [app Cargo.toml](../../apps/web/tauri/src-tauri/Cargo.toml) declares only `rlib` and `staticlib`; Android needs the shared library output (`cdylib`). The shared [mobile capability](../../apps/web/tauri/src-tauri/capabilities/mobile.json) applies to Android but references edit-menu, pasteboard, photo-library, network-status, and call-kit permissions whose dependencies are restricted to iOS. The pinned Tauri build code validates these permissions against available plugin manifests.
More seriously, the pinned auth dependency (`macro-inc/tauri-plugins`, revision `6ddd6600e20436388f169e936b610fe93944b7b0`) has no Android implementation. Its [src/mobile.rs](https://github.com/macro-inc/tauri-plugins/blob/6ddd6600e20436388f169e936b610fe93944b7b0/packages/tauri-plugin-auth/src/mobile.rs) declares `handle` only under `cfg(target_os = "ios")`, then unconditionally constructs `Auth(handle)`. Its build script also references a nonexistent Android directory. This is a source-level Android build blocker, not just an unused feature.
@@ -32,7 +32,7 @@ The pinned virtual-keyboard dependency (`70e8e8325b5ff7d681ef5f3b996ac083d4fc5a0
### 2. Implement Android authentication and connected-account handoff — P0, large
-**Confirmed:** [useSsoLogin.ts](../apps/web/src/features/auth/useSsoLogin.ts) uses the native callback/session redemption flow only for iOS. Android falls through to browser navigation and sets `original_url` to the WebView's local origin. [The navigation plugin](../apps/web/tauri/navigation_plugin/src/lib.rs) opens external destinations in the system browser, where that local origin does not return the user to the app. The same iOS-only split appears in [Gmail linking](../apps/web/src/lib/core/email-link/index.ts) and [GitHub onboarding](../apps/web/src/features/mobile-onboarding/OnboardingConnectAccounts.tsx).
+**Confirmed:** [useSsoLogin.ts](../../apps/web/src/features/auth/useSsoLogin.ts) uses the native callback/session redemption flow only for iOS. Android falls through to browser navigation and sets `original_url` to the WebView's local origin. [The navigation plugin](../../apps/web/tauri/navigation_plugin/src/lib.rs) opens external destinations in the system browser, where that local origin does not return the user to the app. The same iOS-only split appears in [Gmail linking](../../apps/web/src/lib/core/email-link/index.ts) and [GitHub onboarding](../../apps/web/src/features/mobile-onboarding/OnboardingConnectAccounts.tsx).
**Do:** implement an Android browser/Custom Tabs authentication bridge with app callback delivery, cancellation, request correlation, and the existing one-time session-code exchange. Apply it consistently to every supported login provider, Gmail/calendar consent, account linking, and reauthentication. Reuse the backend session model; do not assume browser cookies automatically become native HTTP cookies. Keep intended destination/referral/onboarding state through the round trip and process recreation.
@@ -40,7 +40,7 @@ The pinned virtual-keyboard dependency (`70e8e8325b5ff7d681ef5f3b996ac083d4fc5a0
### 3. Complete backend Android push delivery — P0, large
-**Confirmed:** [notification ingress](../crates/notification/src/domain/service/ingress.rs), around lines 365 and 561, explicitly filters out `DeviceEndpoint::Android` for push delivery and push clearing. [NotificationChannel](../crates/notification/src/domain/models/queue_message.rs) has only iOS, email, and connection-gateway variants. [The Android payload model](../crates/notification/src/domain/models/android.rs) still has `new_temporary_empty` and `"Temporary placeholder"`; it is not a production message builder. Existing registration and [FCM infrastructure](../infra/stacks/notification-service/index.ts) do not connect this missing delivery path.
+**Confirmed:** [notification ingress](../../crates/notification/src/domain/service/ingress.rs), around lines 365 and 561, explicitly filters out `DeviceEndpoint::Android` for push delivery and push clearing. [NotificationChannel](../../crates/notification/src/domain/models/queue_message.rs) has only iOS, email, and connection-gateway variants. [The Android payload model](../../crates/notification/src/domain/models/android.rs) still has `new_temporary_empty` and `"Temporary placeholder"`; it is not a production message builder. Existing registration and [FCM infrastructure](../../infra/stacks/notification-service/index.ts) do not connect this missing delivery path.
**Do:** add Android message construction, queue/worker handling, and dispatch. Preserve notification IDs, permissions, user preferences, grouping, read/dismiss synchronization, retry semantics, and invalid-token cleanup. Use a correct SNS/FCM payload contract, not the placeholder model. SNS supports an explicit [FCM HTTP v1 envelope](https://docs.aws.amazon.com/sns/latest/dg/sns-fcm-v1-payloads.html).
@@ -48,7 +48,7 @@ The pinned virtual-keyboard dependency (`70e8e8325b5ff7d681ef5f3b996ac083d4fc5a0
### 4. Complete the Android push receiver and frontend contract — P0, large
-**Confirmed:** the pinned notifications plugin's [Android implementation](https://github.com/macro-inc/tauri-plugins/blob/6ddd6600e20436388f169e936b610fe93944b7b0/packages/tauri-plugin-notifications/android/src/main/java/NotificationsPlugin.kt) initializes Firebase, requests permission, and fetches a token. It lacks the `watchNotifications` method called by [PushNotification.tsx](../apps/web/src/lib/tauri/PushNotification.tsx), and the audited app/plugin sources contain no custom `FirebaseMessagingService`, token refresh handler, or notification-tap intent bridge. Inherited Tauri `checkPermissions` returns a permission alias map (`postNotification`), while the Rust/JS contract expects a `status` field.
+**Confirmed:** the pinned notifications plugin's [Android implementation](https://github.com/macro-inc/tauri-plugins/blob/6ddd6600e20436388f169e936b610fe93944b7b0/packages/tauri-plugin-notifications/android/src/main/java/NotificationsPlugin.kt) initializes Firebase, requests permission, and fetches a token. It lacks the `watchNotifications` method called by [PushNotification.tsx](../../apps/web/src/lib/tauri/PushNotification.tsx), and the audited app/plugin sources contain no custom `FirebaseMessagingService`, token refresh handler, or notification-tap intent bridge. Inherited Tauri `checkPermissions` returns a permission alias map (`postNotification`), while the Rust/JS contract expects a `status` field.
**Do:** normalize permission responses, handle pre/post Android 13 permission behavior, implement receive/tap/token-refresh handling, notification channels and icons, foreground behavior, and cold-start event buffering. Configure matching Firebase Android apps and supply ignored `google-services.json` files per environment. Validate SNS credentials/project alignment; their configuration references already exist.
@@ -58,7 +58,7 @@ The frontend currently suppresses local notifications once remote push reports g
### 5. Implement Android keyboard, insets, and text-input behavior — P0, medium/large
-**Confirmed:** [useAppSquishHandlers.ts](../apps/web/src/components/app/useAppSquishHandlers.ts) expects native `keyboardWillShow` / `keyboardWillHide` events on *both* mobile platforms. The pinned Android keyboard plugin implements only an example `ping` command. [TauriProvider.tsx](../apps/web/src/lib/tauri/TauriProvider.tsx) reads Android safe-area insets once on mount. The activity already enables edge-to-edge.
+**Confirmed:** [useAppSquishHandlers.ts](../../apps/web/src/components/app/useAppSquishHandlers.ts) expects native `keyboardWillShow` / `keyboardWillHide` events on *both* mobile platforms. The pinned Android keyboard plugin implements only an example `ping` command. [TauriProvider.tsx](../../apps/web/src/lib/tauri/TauriProvider.tsx) reads Android safe-area insets once on mount. The activity already enables edge-to-edge.
**Do:** provide Android IME/window-inset events, reconcile viewport resizing with keyboard height to avoid double subtraction, and update insets after rotation, navigation-mode changes, and window resizing. Test editor focus, caret visibility, bottom toolbars, sheets, scrolling, selection, clipboard menus, and keyboard dismissal. Review the iOS cursor-scroll plugin, currently enabled for all native mobile platforms in multiple editors, for Android behavior.
@@ -68,9 +68,9 @@ Test Gboard and Samsung Keyboard, composition/non-Latin input, dictation, emoji,
### 6. Fix App Links and unify the WebView origin — P0, medium
-**Confirmed:** [assetlinks.json](../apps/web/tauri/src-tauri/.well-known/assetlinks.json) names `com.tauri.dev`; the application ID is `com.macro.app.prod`. Intent filters already exist for macro.com, dev.macro.com, and staging.macro.com, but the deployed association files were not verified. The native-app service's dynamic verification model currently supplies iOS association data only.
+**Confirmed:** [assetlinks.json](../../apps/web/tauri/src-tauri/.well-known/assetlinks.json) names `com.tauri.dev`; the application ID is `com.macro.app.prod`. Intent filters already exist for macro.com, dev.macro.com, and staging.macro.com, but the deployed association files were not verified. The native-app service's dynamic verification model currently supplies iOS association data only.
-There is also a concrete configuration mismatch to resolve: [lib.rs](../apps/web/tauri/src-tauri/src/lib.rs) passes `https://tauri.localhost` to the custom protocol on Android, while its navigation allowlist includes only the HTTP form. [tauri.conf.json](../apps/web/tauri/src-tauri/tauri.conf.json) does not enable `useHttpsScheme` (false by default in the pinned Tauri code), and [backend CORS](../crates/macro_cors/src/lib.rs) includes HTTP, not HTTPS. This needs an actual device test to identify each failing request, but the inconsistent definitions are visible in source.
+There is also a concrete configuration mismatch to resolve: [lib.rs](../../apps/web/tauri/src-tauri/src/lib.rs) passes `https://tauri.localhost` to the custom protocol on Android, while its navigation allowlist includes only the HTTP form. [tauri.conf.json](../../apps/web/tauri/src-tauri/tauri.conf.json) does not enable `useHttpsScheme` (false by default in the pinned Tauri code), and [backend CORS](../../crates/macro_cors/src/lib.rs) includes HTTP, not HTTPS. This needs an actual device test to identify each failing request, but the inconsistent definitions are visible in source.
**Do:** choose the origin before launch and align protocol rewriting, navigation, browser API requirements, cookies, CORS where applicable, workers, and asset URLs. Changing the origin later changes browser-storage identity. Publish correct association files for the selected hosts and **Play App Signing** certificate, with separate debug/dev associations as needed. [Android's verification guidance](https://developer.android.com/training/app-links/verify-applinks) also covers the stricter multi-host behavior on older versions.
@@ -78,7 +78,7 @@ There is also a concrete configuration mismatch to resolve: [lib.rs](../apps/web
### 7. Build native Android calling parity — P1, large
-**Confirmed:** [CallKit setup](../apps/web/src/features/channel/Call/use-callkit.ts) is iOS-only; the native media session, audio routing, incoming-call coordination, and picture-in-picture implementation live in Swift under [callkit_plugin](../apps/web/tauri/callkit_plugin). [Backend VoIP dispatch](../crates/notification/src/domain/service/voip.rs) selects only `IosVoip` endpoints. Existing browser LiveKit calls are a reusable foreground path, not evidence of background or lock-screen calling support.
+**Confirmed:** [CallKit setup](../../apps/web/src/features/channel/Call/use-callkit.ts) is iOS-only; the native media session, audio routing, incoming-call coordination, and picture-in-picture implementation live in Swift under [callkit_plugin](../../apps/web/tauri/callkit_plugin). [Backend VoIP dispatch](../../crates/notification/src/domain/service/voip.rs) selects only `IosVoip` endpoints. Existing browser LiveKit calls are a reusable foreground path, not evidence of background or lock-screen calling support.
**Do:** implement the Android call lifecycle using an appropriate Telecom/Core-Telecom integration, incoming-call FCM delivery, ongoing-call foreground support, answer/decline/end actions, and an Android media session. Cover microphone/camera runtime permissions, audio focus, Bluetooth/speaker/headset routing, interruptions, reconnection, camera switching, background audio, and video/PiP parity. Handle stale/cancelled rings and calls answered on another device. [Core-Telecom](https://developer.android.com/develop/connectivity/telecom/voip-app/telecom) provides system call and foreground integration.
@@ -86,7 +86,7 @@ There is also a concrete configuration mismatch to resolve: [lib.rs](../apps/web
### 8. Add receiving shares from other Android apps — P1, medium
-**Confirmed:** [share_target.rs](../apps/web/tauri/src-tauri/src/share_target.rs) selects the no-op implementation outside iOS. [ShareTargetProvider](../apps/web/src/lib/tauri/ShareTargetProvider.tsx) and [NativeShareSheet](../apps/web/src/features/sharing/native-share-sheet/NativeShareSheet.tsx) explicitly exclude Android. The manifest has no SEND/SEND_MULTIPLE filters.
+**Confirmed:** [share_target.rs](../../apps/web/tauri/src-tauri/src/share_target.rs) selects the no-op implementation outside iOS. [ShareTargetProvider](../../apps/web/src/lib/tauri/ShareTargetProvider.tsx) and [NativeShareSheet](../../apps/web/src/features/sharing/native-share-sheet/NativeShareSheet.tsx) explicitly exclude Android. The manifest has no SEND/SEND_MULTIPLE filters.
**Do:** support Android share intents for text, URLs, images, and files; stage `content://` resources while permission grants remain valid; handle multiple files, MIME types, size limits, cancellation, cleanup, cold start, and an authentication detour. Reuse the destination picker/upload logic after removing iOS-specific assumptions. Scope FileProvider paths to the data actually shared.
@@ -94,7 +94,7 @@ There is also a concrete configuration mismatch to resolve: [lib.rs](../apps/web
### 9. Verify and complete attachments, clipboard, downloads, and outgoing sharing — P1, medium
-**Confirmed:** photo-library and pasteboard native implementations are iOS-only. [nativePhotoLibrary.ts](../apps/web/src/lib/core/mobile/nativePhotoLibrary.ts) invokes its plugin on every Tauri platform, catches failure, and permits a file-input fallback; ordinary Android attachments are therefore **unverified, not proven absent**. [Clipboard image recovery](../apps/web/src/lib/core/mobile/mobileClipboardImageRecovery.ts) similarly attempts an unavailable native command. [downloadFile](../apps/web/src/lib/filesystem/download.ts) uses a browser Blob/anchor, and [imageActions](../apps/web/src/lib/core/util/imageActions.ts) relies on Web Share/browser behavior.
+**Confirmed:** photo-library and pasteboard native implementations are iOS-only. [nativePhotoLibrary.ts](../../apps/web/src/lib/core/mobile/nativePhotoLibrary.ts) invokes its plugin on every Tauri platform, catches failure, and permits a file-input fallback; ordinary Android attachments are therefore **unverified, not proven absent**. [Clipboard image recovery](../../apps/web/src/lib/core/mobile/mobileClipboardImageRecovery.ts) similarly attempts an unavailable native command. [downloadFile](../../apps/web/src/lib/filesystem/download.ts) uses a browser Blob/anchor, and [imageActions](../../apps/web/src/lib/core/util/imageActions.ts) relies on Web Share/browser behavior.
**Do:** exercise actual Android WebView file picking and cloud content providers. Implement native Photo Picker/Storage Access Framework and staging only where the existing path cannot meet requirements. Add reliable save/export/open/share adapters for Blob and authenticated downloads as necessary; do not assume desktop anchor downloads work. Validate camera capture if exposed, large files/video, progress, failures, cancellation, clipboard images, and image saving. Restrict permissions to the chosen flows; inspect the merged manifest rather than assuming the app manifest is the complete permission list.
@@ -102,7 +102,7 @@ There is also a concrete configuration mismatch to resolve: [lib.rs](../apps/web
### 10. Integrate system Back, haptics, and Android UI behavior — P1, small/medium
-**Confirmed:** the pinned Tauri Android activity has default WebView-history Back behavior. No app listener for its `back-button` API was found; application drawers, overlays, and split navigation need an explicit behavior review. [Haptic calls](../apps/web/src/lib/core/mobile/haptics.ts) run for Tauri, but [native plugin registration](../apps/web/tauri/src-tauri/src/lib.rs) places haptics inside the iOS-only block.
+**Confirmed:** the pinned Tauri Android activity has default WebView-history Back behavior. No app listener for its `back-button` API was found; application drawers, overlays, and split navigation need an explicit behavior review. [Haptic calls](../../apps/web/src/lib/core/mobile/haptics.ts) run for Tauri, but [native plugin registration](../../apps/web/tauri/src-tauri/src/lib.rs) places haptics inside the iOS-only block.
**Do:** define/test Back priority (IME, overlay/sheet, nested screen, top-level exit), gesture/predictive Back, and unsent-draft preservation; use the existing Tauri mechanism where sufficient. Register haptics on Android and handle unsupported/error cases. Verify notification prompts/settings wording, TalkBack, large text, contrast, touch targets, rotation, tablets/foldables, split-screen, and external keyboards. Decide supported form factors explicitly; the scaffold also advertises a TV launcher category that should be removed unless intentionally supported.
@@ -110,7 +110,7 @@ There is also a concrete configuration mismatch to resolve: [lib.rs](../apps/web
### 11. Prove offline, resume, and process-death reliability — P1, medium validation
-**Existing foundation:** native cache, queued mutations, native HTTP/WebSockets, and resume handling. **Confirmed gap:** [native-network-status.ts](../apps/web/src/lib/core/mobile/native-network-status.ts) and [query online-state integration](../apps/web/src/lib/queries/client.ts) use native reachability only on iOS. Android falls back to browser connectivity behavior; this is not proof that Android offline mode is broken.
+**Existing foundation:** native cache, queued mutations, native HTTP/WebSockets, and resume handling. **Confirmed gap:** [native-network-status.ts](../../apps/web/src/lib/core/mobile/native-network-status.ts) and [query online-state integration](../../apps/web/src/lib/queries/client.ts) use native reachability only on iOS. Android falls back to browser connectivity behavior; this is not proof that Android offline mode is broken.
**Do:** test Android's default connectivity behavior first; add ConnectivityManager monitoring if needed. Validate session refresh, WebSocket resubscription, missed-event replay, optimistic writes, unsent drafts, pending uploads, cached reads, and cross-account isolation after background suspension and process death. Audit Android backup/restore exclusions for credentials and account-specific caches. Measure cold launch, cache hydration, long lists, large documents, memory pressure, and battery use on a lower-end device.
@@ -118,7 +118,7 @@ There is also a concrete configuration mismatch to resolve: [lib.rs](../apps/web
### 12. Make OTA updates safe across two mobile platforms — P1, medium
-**Existing foundation:** Android native version retrieval, bundle checksums, compatibility/revocation policies, and update state UI. **Confirmed design constraint:** [native_app_service](../crates/native_app_service/src/domain/service.rs) fetches one bundle manifest with one `min_native_build`; target-specific policy rules exist, but the minimum is shared. Android and iOS native build numbering/capabilities must not be assumed equivalent.
+**Existing foundation:** Android native version retrieval, bundle checksums, compatibility/revocation policies, and update state UI. **Confirmed design constraint:** [native_app_service](../../crates/native_app_service/src/domain/service.rs) fetches one bundle manifest with one `min_native_build`; target-specific policy rules exist, but the minimum is shared. Android and iOS native build numbering/capabilities must not be assumed equivalent.
**Do:** use aligned compatibility numbering or platform-specific minimum/capability metadata; prevent a shared JS update from invoking unavailable Android plugins. Test native build-number detection, interrupted download/extraction, cache eviction, incompatible updates, revocation, embedded-bundle fallback, and resume/apply behavior. Give Android users a working Play Store update destination. Check release update controls, not only development mode.
@@ -126,11 +126,11 @@ There is also a concrete configuration mismatch to resolve: [lib.rs](../apps/web
### 13. Establish Play distribution, billing behavior, and release operations — P1, medium; billing may be large
-**Confirmed:** no Android signing/release workflow was found in the audited GitHub workflows, and no release signing configuration appears in the checked-in Gradle app. External signing/Play setup may exist. [Billing](../apps/web/src/features/settings/Billing.tsx) and [paywalls](../apps/web/src/features/paywall/PaywallComponent.tsx) launch Stripe checkout without an Android-specific branch. [MobileApp settings](../apps/web/src/features/settings/MobileApp.tsx) advertise only the Apple App Store. Account deletion already exists in [Account settings](../apps/web/src/features/settings/Account.tsx).
+**Confirmed:** no Android signing/release workflow was found in the audited GitHub workflows, and no release signing configuration appears in the checked-in Gradle app. External signing/Play setup may exist. [Billing](../../apps/web/src/features/settings/Billing.tsx) and [paywalls](../../apps/web/src/features/paywall/PaywallComponent.tsx) launch Stripe checkout without an Android-specific branch. [MobileApp settings](../../apps/web/src/features/settings/MobileApp.tsx) advertise only the Apple App Store. Account deletion already exists in [Account settings](../../apps/web/src/features/settings/Account.tsx).
**Do:** establish application ownership, Play App Signing/upload-key handling, monotonic version codes, reproducible CI AAB builds, release R8 testing, native symbols/source maps, crash/ANR monitoring, internal testing, staged rollout, and rollback procedures. Verify final launcher/adaptive/monochrome icons, splash screen, store listing/screenshots, support links, environment separation, and reviewer account access.
-Current [Play target API requirements](https://support.google.com/googleplay/android-developer/answer/11926878?hl=en) call for API 36 for new phone apps/updates; the project already targets 36. Verify **16 KB page-size compatibility for every shipped native library**, including Rust/cache/media dependencies. The [Android tooling shell](../nix/tauri-dev-shells.nix) pins NDK 26.3; upgrade or explicitly configure and verify alignment rather than assuming compliance. See [Android's page-size guidance](https://developer.android.com/guide/practices/page-sizes).
+Current [Play target API requirements](https://support.google.com/googleplay/android-developer/answer/11926878?hl=en) call for API 36 for new phone apps/updates; the project already targets 36. Verify **16 KB page-size compatibility for every shipped native library**, including Rust/cache/media dependencies. The [Android tooling shell](../../nix/tauri-dev-shells.nix) pins NDK 26.3; upgrade or explicitly configure and verify alignment rather than assuming compliance. See [Android's page-size guidance](https://developer.android.com/guide/practices/page-sizes).
Choose a billing strategy for the intended countries: Play Billing, an applicable enrolled alternative program, or a consumption-only Android app with appropriate purchase UI. Existing Stripe links are not automatically acceptable everywhere; [Google's policy](https://support.google.com/googleplay/android-developer/answer/10281818?hl=en) distinguishes these cases. Play Billing would add entitlement synchronization, restoration, cancellation/refund handling, and backend purchase verification work.
@@ -143,7 +143,7 @@ Complete privacy/Data safety declarations against actual SDK/data behavior and v
3. **Complete parity:** native calls, inbound/outbound sharing, exports, clipboard, offline/process recovery, and OTA compatibility.
4. **Qualify the release:** billing decision, store setup, automated smoke coverage, real-device testing, observability, and staged Play rollout.
-Build Android-native smoke coverage rather than treating mobile browser emulation as acceptance. Existing [native tests](../apps/web/tests/native/README.md) focus on Linux cache behavior, while the dedicated mobile smoke runner is [iOS-only](../apps/web/tests/native/ios/README.md).
+Build Android-native smoke coverage rather than treating mobile browser emulation as acceptance. Existing [native tests](../../apps/web/tests/native/README.md) focus on Linux cache behavior, while the dedicated mobile smoke runner is [iOS-only](../../apps/web/tests/native/ios/README.md).
| Test dimension | Minimum coverage |
| --- | --- |
diff --git a/docs/CALENDAR_SCHEDULING_V1.md b/docs/design/calendar-scheduling-v1.md
similarity index 99%
rename from docs/CALENDAR_SCHEDULING_V1.md
rename to docs/design/calendar-scheduling-v1.md
index 474b9292a1..9125f29f81 100644
--- a/docs/CALENDAR_SCHEDULING_V1.md
+++ b/docs/design/calendar-scheduling-v1.md
@@ -54,7 +54,7 @@ status filtering, authorization, attendance, host availability, and transactiona
reservations. Browser checks cover page navigation, filters, chart interactions,
CSV trigger, no-show-to-insights updates, defaults, schedule deletion protection,
read-only scopes, event creation, and both themes. See the crate README for backend
-setup and operational details; `docs/AGENT_GUIDE/surfaces.md` describes the UI.
+setup and operational details; `docs/agent-guide/calendar.md` describes the UI.
Pre-production checks also exercise lost provider responses and duplicate-provider
conflicts, database completion failures, recovery lease takeover, repeated cancellation,
diff --git a/docs/calendar-team-sharing.md b/docs/design/calendar-team-sharing.md
similarity index 97%
rename from docs/calendar-team-sharing.md
rename to docs/design/calendar-team-sharing.md
index 953cc28301..7a94b125af 100644
--- a/docs/calendar-team-sharing.md
+++ b/docs/design/calendar-team-sharing.md
@@ -306,12 +306,12 @@ checks before enabling reads again.
## Implementation references
-- [Team policy and source models](../crates/calendar_events/src/domain/team.rs)
-- [Source repository](../crates/calendar_events/src/outbound/pg_team.rs)
-- [Availability calculation](../crates/calendar_events/src/domain/team_availability.rs)
-- [AI adapter](../crates/calendar_events/src/inbound/team_toolset.rs)
-- [HTTP adapter](../crates/calendar_events/src/inbound/team_router.rs)
-- [Database workflow](DATABASE_DEVELOPMENT.md)
+- [Team policy and source models](../../crates/calendar_events/src/domain/team.rs)
+- [Source repository](../../crates/calendar_events/src/outbound/pg_team.rs)
+- [Availability calculation](../../crates/calendar_events/src/domain/team_availability.rs)
+- [AI adapter](../../crates/calendar_events/src/inbound/team_toolset.rs)
+- [HTTP adapter](../../crates/calendar_events/src/inbound/team_router.rs)
+- [Database workflow](../development/database.md)
[google-sharing]: https://developers.google.com/workspace/calendar/api/concepts/sharing
[google-copies]: https://developers.google.com/workspace/calendar/api/concepts/inviting-attendees-to-events
diff --git a/docs/CRM_REFERENCES_SCOPE.md b/docs/design/crm-references-scope.md
similarity index 99%
rename from docs/CRM_REFERENCES_SCOPE.md
rename to docs/design/crm-references-scope.md
index 7f7e019fb2..0c5626da00 100644
--- a/docs/CRM_REFERENCES_SCOPE.md
+++ b/docs/design/crm-references-scope.md
@@ -175,7 +175,7 @@ package tests, and `just check`.
Exercise the resulting UI against the changed backend in an isolated local
stack, including company/contact References, Files, Tasks, Calls, and message
navigation. A frontend talking only to the deployed dev backend cannot verify
-new query behavior. Update the CRM section in `docs/AGENT_GUIDE/surfaces.md` and
+new query behavior. Update the CRM section in `docs/agent-guide/crm.md` and
any changed mention/navigation guide. Report blocked checks precisely.
## Delivery boundary
diff --git a/docs/GRAPHICS_PARITY.md b/docs/design/graphics-parity.md
similarity index 89%
rename from docs/GRAPHICS_PARITY.md
rename to docs/design/graphics-parity.md
index 8ef087a645..376d846a3c 100644
--- a/docs/GRAPHICS_PARITY.md
+++ b/docs/design/graphics-parity.md
@@ -36,7 +36,7 @@ copy the legacy or Excalidraw data model into the new transform tree. Each new
renderer must preserve shared paint order, reverse hit order, and stable mounted
identity.
-See the [Canvas architecture](CANVAS_ARCHITECTURE.md),
-[legacy bridge](CANVAS_LEGACY_BRIDGE.md),
-[graphics README](../packages/graphics/README.md), and
-[Canvas Next README](../apps/web/src/features/block-canvas/README.md).
+See the [Canvas architecture](../architecture/canvas.md),
+[legacy bridge](../architecture/canvas-legacy-bridge.md),
+[graphics README](../../packages/graphics/README.md), and
+[Canvas Next README](../../apps/web/src/features/block-canvas/README.md).
diff --git a/docs/INITIATIVES_PROJECTS_PLAN.md b/docs/design/initiatives-projects.md
similarity index 78%
rename from docs/INITIATIVES_PROJECTS_PLAN.md
rename to docs/design/initiatives-projects.md
index 9bb0ac141e..79a9ec701a 100644
--- a/docs/INITIATIVES_PROJECTS_PLAN.md
+++ b/docs/design/initiatives-projects.md
@@ -42,7 +42,7 @@ feedback.
### What already exists
-[`crates/initiative`](../crates/initiative/src/lib.rs) owns lifecycle and task membership through domain ports, a service, a PostgreSQL adapter, and HTTP handlers. DSS mounts these routes:
+[`crates/initiative`](../../crates/initiative/src/lib.rs) owns lifecycle and task membership through domain ports, a service, a PostgreSQL adapter, and HTTP handlers. DSS mounts these routes:
| Operation | Existing route |
| --- | --- |
@@ -51,36 +51,36 @@ feedback.
| Assign or move tasks | `PUT /initiatives/{initiative_id}/tasks` |
| Remove one task | `DELETE /initiatives/{initiative_id}/tasks/{task_id}` |
-The [membership schema](../crates/macro_db_client/migrations/20260910144344_create_initiative.sql) already enforces **at most one initiative per task** through the `task_id` primary key. Deleting an initiative removes associations without deleting its tasks. Assignment deduplicates inputs, caps each request at 100 unique tasks, and reports per-task results.
+The [membership schema](../../crates/macro_db_client/migrations/20260910144344_create_initiative.sql) already enforces **at most one initiative per task** through the `task_id` primary key. Deleting an initiative removes associations without deleting its tasks. Assignment deduplicates inputs, caps each request at 100 unique tasks, and reports per-task results.
-[Initiative access](../crates/entity_access/src/outbound/pg_access_repo/queries/initiative_access.rs) supports explicit user/team/channel grants and link permissions. The [initiative service](../crates/initiative/src/domain/service.rs) enforces owner-only share-policy changes. Members receive edit grants on the initiative and its description document through [member writes](../crates/initiative/src/outbound/pg_initiative_repo/members.rs).
+[Initiative access](../../crates/entity_access/src/outbound/pg_access_repo/queries/initiative_access.rs) supports explicit user/team/channel grants and link permissions. The [initiative service](../../crates/initiative/src/domain/service.rs) enforces owner-only share-policy changes. Members receive edit grants on the initiative and its description document through [member writes](../../crates/initiative/src/outbound/pg_initiative_repo/members.rs).
-Every initiative already has a required, distinct Markdown description document. [Creation and deletion](../crates/initiative/src/domain/service.rs) coordinate with a document port; DSS supplies the adapter at this baseline; the implementation moves the reusable adapter into [`initiative_documents`](../crates/initiative_documents/src/lib.rs). Link/team/member sharing is coordinated across both entities. Keep this foundation while deferring description editing to the last frontend step.
+Every initiative already has a required, distinct Markdown description document. [Creation and deletion](../../crates/initiative/src/domain/service.rs) coordinate with a document port; DSS supplies the adapter at this baseline; the implementation moves the reusable adapter into [`initiative_documents`](../crates/initiative_documents/src/lib.rs). Link/team/member sharing is coordinated across both entities. Keep this foundation while deferring description editing to the last frontend step.
### Gaps against the task
| Requirement / concern | Finding | Required work |
| --- | --- | --- |
-| Status, priority, assignees, due date | [Initiative models](../crates/initiative/src/domain/models.rs) contain none of these. [Property storage types](../crates/models_properties/src/shared/entity_type.rs) have no initiative variant, and [property mapping](../crates/properties/src/domain/model.rs) explicitly returns `None` for initiatives. | Add canonical initiative property support and reuse task system definitions, defaults, validation, and clearing behavior. Do not reuse the existing `PROJECT` storage type. |
-| Default team sharing | [Create](../crates/initiative/src/domain/service.rs) shares with the team only for `share_with_team == Some(true)`. An omitted value selects `Unshared`. The team's link-sharing default is a separate setting. | Default new projects to the creator's team using task policy; preserve an explicit opt-out and valid behavior for users without a team. Apply consistently to UI and MCP. |
-| Usable permission metadata | [Repository detail conversion](../crates/initiative/src/outbound/pg_initiative_repo.rs) sets `user_access_level` to the constant `View`; [get/update handlers](../crates/initiative/src/inbound/axum_router/get.rs) do not correct it. | Have the domain response reflect the verified caller's effective permission. Owner/editor controls would otherwise be disabled despite authorized requests. |
+| Status, priority, assignees, due date | [Initiative models](../../crates/initiative/src/domain/models.rs) contain none of these. [Property storage types](../../crates/models_properties/src/shared/entity_type.rs) have no initiative variant, and [property mapping](../../crates/properties/src/domain/model.rs) explicitly returns `None` for initiatives. | Add canonical initiative property support and reuse task system definitions, defaults, validation, and clearing behavior. Do not reuse the existing `PROJECT` storage type. |
+| Default team sharing | [Create](../../crates/initiative/src/domain/service.rs) shares with the team only for `share_with_team == Some(true)`. An omitted value selects `Unshared`. The team's link-sharing default is a separate setting. | Default new projects to the creator's team using task policy; preserve an explicit opt-out and valid behavior for users without a team. Apply consistently to UI and MCP. |
+| Usable permission metadata | [Repository detail conversion](../../crates/initiative/src/outbound/pg_initiative_repo.rs) sets `user_access_level` to the constant `View`; [get/update handlers](../../crates/initiative/src/inbound/axum_router/get.rs) do not correct it. | Have the domain response reflect the verified caller's effective permission. Owner/editor controls would otherwise be disabled despite authorized requests. |
| Assignments versus collaboration | `member_ids` excludes the owner and grants edit access; it is not a task-style assignee field. | Keep collaborators/access membership distinct from the multi-user Assignees property. The owner must remain assignable. |
| Consistent task mutation authorization | [Assign handler](../crates/initiative/src/inbound/axum_router/assign_tasks.rs) checks task edit access but discards the receipt into a forgeable `Candidate` value. [Unassign](../crates/initiative/src/inbound/axum_router/unassign_task.rs) checks initiative edit access only. Moving checks the destination and task, without an explicit source-project policy. | Define one domain policy for assign/move/remove and carry typed task capabilities or obtain them through an injected domain port. HTTP and MCP must enforce the same rules. Bound/dedupe requests before expensive receipt generation. |
-| Task visibility inside projects | [Detail loading](../crates/initiative/src/outbound/pg_initiative_repo.rs) returns every associated task ID without checking each task's visibility. Association itself does not grant task access. | Return authorized task pages/counts, and avoid exposing inaccessible task metadata through activity, chips, or progress totals. |
+| Task visibility inside projects | [Detail loading](../../crates/initiative/src/outbound/pg_initiative_repo.rs) returns every associated task ID without checking each task's visibility. Association itself does not grant task access. | Return authorized task pages/counts, and avoid exposing inaccessible task metadata through activity, chips, or progress totals. |
| Project chip on task rows | `task_initiative` reads/writes are confined to the initiative crate. Task/Soup projections do not expose this association. Existing frontend `projectId` means folder/container. | Add a batched, authorized initiative-reference read and project-scoped task pagination. Preserve the separate folder relationship. |
-| Project listing and search | [List](../crates/initiative/src/outbound/pg_initiative_repo/list.rs) returns an unpaginated list with name, description-document ID, and updated time only. No search/filter/sort contract or row properties/counts. | Add cursor pagination, search and required filters/sorts, with useful row projections. Keep discovery scoped to grants/team access; public-link access alone should not enumerate unrelated projects. |
-| Activity feed | Initiative service has no event publisher/activity projection. [Activity storage](../crates/activity/src/outbound/pg_activity_repo.rs) already includes initiative among its rankable entity types, but [Soup entity loading](../crates/graphql_soup/src/loaders.rs) rejects initiatives and the current frontend entity-history query depends on Soup. | Publish initiative domain facts into the existing activity pipeline; add authorized entity history, display metadata, audience delivery and refresh behavior. Merely mounting the current entity activity component will not work. |
-| New discussions | [`MessageParent`](../crates/messages/src/domain/models.rs) supports only channel/document. [Discussion delivery context](../crates/messages/src/outbound/pg_discussion_context.rs) is document-specific. | Add initiative as a first-class parent throughout messages, access, persistence validation, delivery, notifications and client adapters. General project comments belong to the initiative ID. |
-| Share menu | Initiative PATCH supports share policy, but [generic entity mutations](../services/document_storage_service/src/service/entity_mutation.rs) reject initiative sharing. The [global share modal's type set](../apps/web/src/features/sharing/global-share-modal/shareable-entity.ts) excludes initiatives. | Add a view-compatible sharing adapter using the initiative service and existing share UI primitives, with current permission data. |
-| Cmd+K | Existing [project commands](../apps/web/src/features/command/useCommandItems.ts) target folder entities; initiatives are not represented by Soup. | Add an initiative-backed command source, display as Projects, and open native project views. Preserve folder search and folder actions. |
-| Full MCP coverage | Initiative exposes only HTTP inbound adapters. [`ai_tools::tools_for`](../crates/ai_tools/src/lib.rs) registers existing folder project tools but no initiative tools. [MCP service](../services/mcp_service/src/main.rs) serves that assembled toolset. | Add domain-backed initiative tools plus coverage through property, activity, message and description tools; wire every supported host, generated schemas, result links and frontend renderers. |
-| Description last | [The description migration](../crates/macro_db_client/migrations/20260917140621_add_initiative_description_document.up.sql) makes the document mandatory today. Failure compensation can log an orphan if purging fails. | Keep creating the empty backing document. Close lifecycle/cleanup gaps in PR 1, and add the description editor as the last frontend step in PR 6. General project discussions use the initiative parent. |
+| Project listing and search | [List](../../crates/initiative/src/outbound/pg_initiative_repo/list.rs) returns an unpaginated list with name, description-document ID, and updated time only. No search/filter/sort contract or row properties/counts. | Add cursor pagination, search and required filters/sorts, with useful row projections. Keep discovery scoped to grants/team access; public-link access alone should not enumerate unrelated projects. |
+| Activity feed | Initiative service has no event publisher/activity projection. [Activity storage](../../crates/activity/src/outbound/pg_activity_repo.rs) already includes initiative among its rankable entity types, but [Soup entity loading](../../crates/graphql_soup/src/loaders.rs) rejects initiatives and the current frontend entity-history query depends on Soup. | Publish initiative domain facts into the existing activity pipeline; add authorized entity history, display metadata, audience delivery and refresh behavior. Merely mounting the current entity activity component will not work. |
+| New discussions | [`MessageParent`](../../crates/messages/src/domain/models.rs) supports only channel/document. [Discussion delivery context](../../crates/messages/src/outbound/pg_discussion_context.rs) is document-specific. | Add initiative as a first-class parent throughout messages, access, persistence validation, delivery, notifications and client adapters. General project comments belong to the initiative ID. |
+| Share menu | Initiative PATCH supports share policy, but [generic entity mutations](../../services/document_storage_service/src/service/entity_mutation.rs) reject initiative sharing. The [global share modal's type set](../../apps/web/src/features/sharing/global-share-modal/shareable-entity.ts) excludes initiatives. | Add a view-compatible sharing adapter using the initiative service and existing share UI primitives, with current permission data. |
+| Cmd+K | Existing [project commands](../../apps/web/src/features/command/useCommandItems.ts) target folder entities; initiatives are not represented by Soup. | Add an initiative-backed command source, display as Projects, and open native project views. Preserve folder search and folder actions. |
+| Full MCP coverage | Initiative exposes only HTTP inbound adapters. [`ai_tools::tools_for`](../../crates/ai_tools/src/lib.rs) registers existing folder project tools but no initiative tools. [MCP service](../../services/mcp_service/src/main.rs) serves that assembled toolset. | Add domain-backed initiative tools plus coverage through property, activity, message and description tools; wire every supported host, generated schemas, result links and frontend renderers. |
+| Description last | [The description migration](../../crates/macro_db_client/migrations/20260917140621_add_initiative_description_document.up.sql) makes the document mandatory today. Failure compensation can log an orphan if purging fails. | Keep creating the empty backing document. Close lifecycle/cleanup gaps in PR 1, and add the description editor as the last frontend step in PR 6. General project discussions use the initiative parent. |
### Architectural assessment
The hexagonal boundary was checked. Lifecycle and owner-only sharing policy already live in the initiative domain service, with concrete document wiring in DSS. Preserve that shape. Task receipt erasure and asymmetric unassignment checks need a shared domain contract before a second inbound adapter is added. Cross-domain reads and writes should use owning services/ports; initiative, messages and activity adapters must not import each other's outbound modules.
-This audit did not execute the existing Rust tests. Existing [service](../crates/initiative/src/domain/service/test.rs), [router](../crates/initiative/src/inbound/axum_router/test.rs), and [repository](../crates/initiative/src/outbound/pg_initiative_repo/test.rs) coverage are starting points for the implementation PRs.
+This audit did not execute the existing Rust tests. Existing [service](../../crates/initiative/src/domain/service/test.rs), [router](../../crates/initiative/src/inbound/axum_router/test.rs), and [repository](../../crates/initiative/src/outbound/pg_initiative_repo/test.rs) coverage are starting points for the implementation PRs.
## 2. Linear UI findings and the Macro adaptation
@@ -115,8 +115,8 @@ The user request takes precedence over Linear differences: Macro Projects live u
- Backend/API/storage entity: `initiative`. Frontend product copy: **Project**.
- New feature: `apps/web/src/features/projects/`; decode `Initiative*` transport DTOs to a feature-owned Project model.
- Preserve existing folder `project`, `projectId`, `/projects` APIs, block routes and tools. New task relationship fields use `initiativeId`/`initiative` internally.
-- Register component splits through [componentRegistry](../apps/web/src/components/app/split-layout/componentRegistry.tsx), using a project-specific component identity such as `initiative-view~<id>~<tab>`. Follow existing ID serialization patterns; component params alone are lost on URL restore. Host adapters translate all project links, command results and notification targets into this identity.
-- Existing task grouping named `project` currently means folder grouping in [task-query](../apps/web/src/features/tasks-view/queries/task-query.ts). Add a distinct initiative grouping key if grouping is exposed, and label the existing folder operation clearly. Never silently reinterpret persisted folder filters.
+- Register component splits through [componentRegistry](../../apps/web/src/components/app/split-layout/componentRegistry.tsx), using a project-specific component identity such as `initiative-view~<id>~<tab>`. Follow existing ID serialization patterns; component params alone are lost on URL restore. Host adapters translate all project links, command results and notification targets into this identity.
+- Existing task grouping named `project` currently means folder grouping in [task-query](../../apps/web/src/features/tasks-view/queries/task-query.ts). Add a distinct initiative grouping key if grouping is exposed, and label the existing folder operation clearly. Never silently reinterpret persisted folder filters.
### Properties, permissions and membership
@@ -151,7 +151,7 @@ merged activity/discussion timeline is future work and is not part of this stack
### Frontend architecture
-Follow [FRONTEND_FEATURE_ARCHITECTURE](FRONTEND_FEATURE_ARCHITECTURE.md), including its stronger contracts beyond the current activity example:
+Follow [frontend feature architecture](../architecture/frontend-features.md), including its stronger contracts beyond the current activity example:
```text
features/projects/
@@ -167,7 +167,7 @@ features/projects/
No `BlockProvider`, block signals, block lifecycle or `block-project` dependencies. The production entry point supplies real sources and permissions; tests inject feature-owned sources. Presentational components do not fetch or navigate. Register the feature in both TS and TSX architecture-rule families.
-The Solid/TanStack production playbook (query-key and mutation rules in §11) informed these decisions: complete key factories, one cache owner per domain, reactive inputs, cancellation-aware immutable optimistic writes, rollback and targeted invalidation. These complement the repository's [frontend style rules](STYLE_GUIDE.md). Use shared query infrastructure and retain the existing task/Soup cache instead of copying it into a project store. Include user scope, entity ID and all filter/sort inputs in keys. Retain same-project data during refresh, clear previous-project data on navigation, and release subscriptions with their Solid owner. Derive state rather than synchronizing signals with effects.
+The Solid/TanStack production playbook (query-key and mutation rules in §11) informed these decisions: complete key factories, one cache owner per domain, reactive inputs, cancellation-aware immutable optimistic writes, rollback and targeted invalidation. These complement the repository's [frontend style rules](../development/style-guide.md). Use shared query infrastructure and retain the existing task/Soup cache instead of copying it into a project store. Include user scope, entity ID and all filter/sort inputs in keys. Retain same-project data during refresh, clear previous-project data on navigation, and release subscriptions with their Solid owner. Derive state rather than synchronizing signals with effects.
## 4. Accepted six-PR stack
diff --git a/docs/PROPERTY_TARGET_ENTITY_TYPE_PLAN.md b/docs/design/property-target-entity-types.md
similarity index 100%
rename from docs/PROPERTY_TARGET_ENTITY_TYPE_PLAN.md
rename to docs/design/property-target-entity-types.md
diff --git a/docs/ANDROID_DEVELOPMENT.md b/docs/development/android.md
similarity index 99%
rename from docs/ANDROID_DEVELOPMENT.md
rename to docs/development/android.md
index 9c73668090..1b61556264 100644
--- a/docs/ANDROID_DEVELOPMENT.md
+++ b/docs/development/android.md
@@ -770,7 +770,7 @@ never use it for Play uploads. To build an emulator APK, run
above. Keep OTA enabled for update acceptance; `--no-default-features` qualifies
only embedded behavior. Shared OTA builds need both `MIN_NATIVE_BUILD_ANDROID`
and `MIN_NATIVE_BUILD_IOS`; see the
-[native compatibility contract](../apps/web/tauri/src-tauri/README.md).
+[native compatibility contract](../../apps/web/tauri/src-tauri/README.md).
Android ConnectivityManager reports the validated default network and takes a
fresh snapshot on resume. Captive/unvalidated networks count as offline. Older
diff --git a/docs/CURSOR_CLOUD.md b/docs/development/cursor-cloud.md
similarity index 87%
rename from docs/CURSOR_CLOUD.md
rename to docs/development/cursor-cloud.md
index 1ec8b12e97..10300c824d 100644
--- a/docs/CURSOR_CLOUD.md
+++ b/docs/development/cursor-cloud.md
@@ -1,8 +1,8 @@
# Cursor Cloud
**Only for Cursor Cloud VMs.** On a local machine, `.cursor/*.sh` can prompt for
-sudo and are the wrong entry points. Use [running locally](RUNNING_LOCALLY.md)
-and the [web agent guide](../apps/web/AGENTS.md) instead.
+sudo and are the wrong entry points. Use [running locally](running-locally.md)
+and the [web agent guide](../../apps/web/AGENTS.md) instead.
## Start only what the task needs
@@ -25,11 +25,11 @@ nix develop --command env -u SQLX_OFFLINE cargo test -p <package>
Run tests per affected crate, with `SQLX_OFFLINE` unset. Installation baked the
initial database and test envs; apply new migrations as needed. Use
-[database development](DATABASE_DEVELOPMENT.md) for SQLx preparation and errors.
+[database development](database.md) for SQLx preparation and errors.
## Run and verify the app
-Follow the [run-app skill](../.claude/skills/run-app/SKILL.md) for the full browser
+Follow the [run-app skill](../../.agents/skills/run-app/SKILL.md) for the full browser
walkthrough, frontend restarts, and login troubleshooting.
- App: <http://localhost:3000/app>; backend proxy: <https://localhost:8090>
@@ -67,16 +67,16 @@ agent after adding the token.
This section is for Cloud environment setup, not ordinary feature work.
-- [`install.sh`](../.cursor/install.sh) prepares durable dependency caches,
+- [`install.sh`](../../.cursor/install.sh) prepares durable dependency caches,
databases, test dependencies, frontend dependencies, service binaries, and a
stack-init snapshot. It then stops dockerd and nix-daemon so the bake can exit.
-- [`start.sh`](../.cursor/start.sh) runs at boot and only ensures the Nix daemon
+- [`start.sh`](../../.cursor/start.sh) runs at boot and only ensures the Nix daemon
and cache links, keeping sessions and subagents cheap to start.
- Nix is the only host dependency. The pinned shell provides Docker CLI/daemon,
Compose, `fuse-overlayfs`, and OpenSSH; use its `ssh-keygen`.
- Service binaries are built/cached as `.#local-stack-binaries`, realized with
`nix build .#local-stack-binaries`. The
- [`push_local_stack_binaries.yml`](../.github/workflows/push_local_stack_binaries.yml)
+ [`push_local_stack_binaries.yml`](../../.github/workflows/push_local_stack_binaries.yml)
workflow pushes them to the private S3 Nix cache on main; it is separate from
the deploy pipeline.
- Set `NIX_CACHE_AWS_ACCESS_KEY_ID` and `NIX_CACHE_AWS_SECRET_ACCESS_KEY` as Cursor
diff --git a/docs/DATABASE_DEVELOPMENT.md b/docs/development/database.md
similarity index 78%
rename from docs/DATABASE_DEVELOPMENT.md
rename to docs/development/database.md
index b683871be6..6c3f2634d2 100644
--- a/docs/DATABASE_DEVELOPMENT.md
+++ b/docs/development/database.md
@@ -2,19 +2,20 @@
Read this for SQLx queries, migrations, database-backed tests, and cache errors.
Commands run from the repository root inside `nix develop` unless shown with an
-explicit Nix invocation. See also [Rust development](RUST_DEVELOPMENT.md).
+explicit Nix invocation. See also [Rust development](rust.md).
## Locate the schema and owner
-- MacroDB migrations live in [`crates/macro_db_client/migrations/`](../crates/macro_db_client/migrations/).
+- MacroDB migrations live in [`crates/macro_db_client/migrations/`](../../crates/macro_db_client/migrations/).
Check the owning crate's migrations/recipes before assuming another database
uses the same setup.
-- Inspect migrations or use the [dump-schema skill](../.agents/skills/dump-schema/SKILL.md)
+- Inspect migrations or use the [dump-schema skill](../../.agents/skills/dump-schema/SKILL.md)
against the local database. Do not guess table or column spelling.
- Quote camelCase identifiers and alias selected columns to their Rust field
names: `SELECT "userId" AS user_id FROM "UserInsights"`.
-- Use the owning domain's database adapter; follow the style guide's `[db]` rules
- (CS-01–09) and ownership rule (CS-27) in [STYLE_GUIDE.md](STYLE_GUIDE.md).
+- Use the owning domain's database adapter; follow the `[db]` rules
+ (CS-01–09) in [`rust/db.md`](../../.agents/rules/rust/db.md) and ownership rule
+ (CS-27) in [`rust/architecture.md`](../../.agents/rules/rust/architecture.md).
## Set up local test databases
@@ -28,11 +29,11 @@ just setup_macrodb
`run_dbs` creates the required networks/volumes and starts Postgres and Redis.
`setup_macrodb` creates and migrates MacroDB; `initialize_dbs` is its alias.
-The default local URL is defined in [database.just](../tooling/just/database.just).
+The default local URL is defined in [database.just](../../tooling/just/database.just).
These recipes target that default database, not a named local-stack instance.
On **Cursor Cloud**, installation already prepares the database and test envs.
-Start the infrastructure with `bash .cursor/infra.sh`; see [Cursor Cloud](CURSOR_CLOUD.md).
+Start the infrastructure with `bash .cursor/infra.sh`; see [Cursor Cloud](cursor-cloud.md).
Apply any new migrations before testing.
### Pre-migrated test template
@@ -62,7 +63,7 @@ This convention starts with `database_entities`; it is new for databases and is
the convention for new entities going forward. It does not require renaming
existing entity tables. `database_entities.database_id` is both the entity's key
and a reference to `databases.id`. See the
-[database backend](../crates/databases/README.md) for the storage boundary and
+[database backend](../../crates/databases/README.md) for the storage boundary and
the explicitly destructive database cutover.
### Compatible migrations
@@ -97,7 +98,7 @@ compatible with the service code currently deployed, not just the code in its PR
2. **Use compile-time checked queries** (`query!`, `query_as!`, `query_scalar!`,
`query_file!`) by default. Dynamic SQL is only for genuinely dynamic queries;
bind values and allowlist dynamic identifiers. Review indexes, bounded results,
- and access-control predicates with the [SQLx query validator](../.pi/skills/sqlx-query-validator/SKILL.md).
+ and access-control predicates with the [SQLx query validator](../../.agents/skills/sqlx-query-validator/SKILL.md).
3. **Apply schema changes** to the local database:
@@ -105,11 +106,15 @@ compatible with the service code currently deployed, not just the code in its PR
just crates/macro_db_client/migrate_db
```
+ Migrations deploy before services and must survive a rolling deploy: give
+ new `NOT NULL` columns a default, and for large tables set `lock_timeout` and
+ use `NOT VALID` + `VALIDATE` or `CREATE INDEX CONCURRENTLY` (CS-70).
+
4. **Update affected tests/fixtures and run package tests** from the root with
`SQLX_OFFLINE` unset. Test between batches of query changes, not just at the end.
-5. **Refresh the workspace SQLx cache** when queries (including test queries) or
- schema change, or when required metadata is missing. From the repository root:
+5. **Refresh the workspace SQLx cache** when non-test queries or schema
+ change, or when required metadata is missing. From the repository root:
```bash
nix develop --command just prepare_db
@@ -123,29 +128,20 @@ compatible with the service code currently deployed, not just the code in its PR
6. **Rerun the affected tests** after preparation or fixes. Cache preparation is
not a substitute for `cargo test -p <package>` against the live local database.
-### Include test-only queries in preparation
-
-The root `prepare_db` wrapper takes **no flags**. If SQLx needs metadata for
-queries compiled only in tests, call the workspace helper from the root. First
-set `DATABASE_URL` to your intended local database URL, replacing the placeholders
-below with your local connection details:
-
-```bash
-export DATABASE_URL='postgres://<user>:<password>@<host>:<port>/<database>'
-nix develop --command just sqlx::prepare_db "$DATABASE_URL" --tests
-```
+### Test queries are not cached
-The helper in
-[sqlx.just](../tooling/just/sqlx.just) forwards `--tests` to Cargo while keeping
-workspace scope and the root `.sqlx` directory. Do not run preparation from an
-individual crate or try `just prepare_db --tests`.
+Tests compile against a live database with `SQLX_OFFLINE` unset, and the offline
+checks (`just rust-check`, `just clippy`) don't compile tests, so test-only queries
+never need `.sqlx` metadata. Prepare with the root `prepare_db` wrapper only. Never
+pass `--tests` to `sqlx::prepare_db` or `cargo sqlx prepare`, and don't commit
+cache entries for test queries.
## Troubleshooting
- **Connection or schema errors:** confirm local Postgres is running, test envs
point to the intended local database, and migrations have been applied.
-- **Missing cached query data:** use the preparation commands above, including
- `--tests` through the helper for test-only queries. Leave `SQLX_OFFLINE` unset
+- **Missing cached query data:** run `just prepare_db` as above. If the missing
+ query is test-only, the test is running offline: leave `SQLX_OFFLINE` unset
for `cargo test`; enabling it can hide schema drift and produce misleading
type-inference errors. Offline mode is only for builds/checks/lints.
- **Preparation still fails:** fix in-scope query/schema issues; if the blocker
@@ -163,5 +159,5 @@ just setup_macrodb
```
Do not use this on hosted dev/production databases or delete unrelated containers.
-For a named local stack, follow [its instance-specific commands](RUNNING_LOCALLY.md)
+For a named local stack, follow [its instance-specific commands](running-locally.md)
so you do not reset the default database by mistake.
diff --git a/docs/development/infrastructure.md b/docs/development/infrastructure.md
new file mode 100644
index 0000000000..a7f1847855
--- /dev/null
+++ b/docs/development/infrastructure.md
@@ -0,0 +1,179 @@
+# Infrastructure
+
+Macro's AWS infrastructure is Pulumi in TypeScript under `infra/`, run with Bun,
+in `us-east-1`; the observability pilot (`infra/stacks/observability`) runs in
+`us-east-2`. Cloudflare Workers deploy with `wrangler`, not Pulumi. This
+guide covers how the code is laid out, the patterns to copy, how deploys happen,
+and the traps. To add a whole service, follow the
+[new service guide](../guides/new-service.md).
+
+> **Agents never deploy.** Do not run `pulumi up`, `pulumi destroy`,
+> `wrangler deploy`, `wrangler secret put`, or a deploy workflow dispatch unless the
+> user explicitly asks for that deploy in this conversation. Preparing a change,
+> "wiring it up", or bootstrapping is not permission. `pulumi preview` is fine.
+
+## Layout
+
+| Path | Contents |
+| --- | --- |
+| `infra/stacks/<name>/` | One Pulumi project per directory. `Pulumi.yaml` plus `Pulumi.dev.yaml` / `Pulumi.prod.yaml`. |
+| `infra/packages/shared` | Constants, config singletons, typed stack references, gateway priorities, Doppler, service URLs. |
+| `infra/packages/resources` | Reusable components: ALB, target group, queue, RDS, Redis, DynamoDB, Kafka, buckets, Datadog sidecars, alarms. |
+| `infra/packages/service` | `EcrImage`, least-privilege DynamoDB, cluster stack reference. |
+| `infra/packages/lambda` | `Lambda` component and `WorkerTrigger`. |
+| `infra/packages/vpc` | IDs of the one VPC everything runs in (`get_coparse_api_vpc()`). |
+
+Stacks are `macro-inc/dev` and `macro-inc/prod`; a few are prod-only
+(`monitoring`, `doppler-projects`) or dev-only (`github-runners`,
+`web-app-preview`). The project name is usually the directory name. It matters:
+Doppler, `services-config.json`, and the nix `serviceName` all key on it.
+
+### Stack references
+
+Stacks read each other's outputs as `macro-inc/<project>/${stack}`, so dev only
+ever reads dev. Use the typed helpers in `packages/shared` rather than a raw
+`StackReference`:
+
+- `getGatewayAlb()` for the shared gateway ALB and HTTPS listener.
+- `document-storage` outputs the shared ECS cluster (`cloudStorageClusterArn`);
+ `packages/service/src/cluster.ts` wraps it.
+- `getKafkaClusterPolicy()`, `getMacroNotify()`, `getSearchEventQueue()`,
+ `getAiToolsInfra()`, and similar for other shared resources.
+
+The first argument to `StackReference` is a logical name that must be unique in
+the program; prefix it when a helper and its caller reference the same stack.
+References imply deploy order, so a new reference can create a bootstrap cycle.
+
+## The current ECS service pattern
+
+Copy `infra/stacks/calendar-service/` or `infra/stacks/lexical-service/`. There is
+no generic service component; each stack defines a small `ComponentResource` that
+composes these pieces:
+
+1. **Task role** with only the policies the service needs: `GetSecretValue` on the
+ specific secret ARNs, SQS on specific queues, `getKafkaClusterPolicy()`.
+2. **Image** with `EcrImage` (`docker/Dockerfile`, build arg `SERVICE_NAME`). CI
+ swaps in the prebuilt Dockerfile that copies nix-built binaries; a new
+ Dockerfile must be added to that map in `packages/service/src/ecr.ts`.
+3. **Gateway routing** with `ServiceTargetGroup({ service: GatewayService.X,
+ pathPatterns: ['/<prefix>', '/<prefix>/*'] })` on `getGatewayAlb()`.
+4. **Secrets** with `DopplerEcsEnvironment(pulumi.getProject())`: an execution role
+ plus one container secret, `APP_SECRETS_JSON`.
+5. **Service** with `awsx.ecs.FargateService`: private subnets, the deployment
+ circuit breaker with rollback, `continueBeforeSteadyState:
+ DEFAULT_CONTINUE_BEFORE_STEADY_STATE`, containers `log_router`
+ (`fargateLogRouterSidecarContainer`), `datadog_agent`
+ (`datadogAgentContainer`), and the service, and `dependsOn` the target group's
+ listener rule (ECS rejects a target group not yet attached to a listener).
+6. **Autoscaling** on ALB requests per target, CPU, and memory.
+7. **Alarms**: `EcsDeploymentFailureAlarm` plus CPU, memory, and target 5xx,
+ routed to `CLOUD_TRAIL_SNS_TOPIC_ARN`.
+
+Health checks, deregistration delay, and steady-state behaviour come from
+`packages/resources/src/resources/ecs_deployment_defaults.ts`. The container
+listens on `8080` and serves `GET /health`.
+
+A worker with no port (SQS or Kafka consumer) follows
+`infra/stacks/cloud-storage-service/slack-import-worker.ts`: no target group, an
+egress-only security group, explicit CPU and memory, and a longer `stopTimeout`.
+
+## Gateway routing
+
+`gateway.macro.com` (`dev-gateway.macro.com` in dev) is one ALB owned by the
+`gateway` stack. Services attach to its HTTPS listener with path rules.
+
+- Rule priorities live only in `GATEWAY_PRIORITIES`
+ (`packages/shared/src/gateway_priorities.ts`). Add a `GatewayService` member and
+ a unique priority there; duplicates throw at load time.
+- The ALB matches the lowest priority number first. A broad prefix with a lower
+ number shadows yours: calendar's `/calendar` was swallowed by email-service
+ until its priority was fixed.
+- The ALB forwards the path unchanged, so the Rust router must also mount under
+ `/<prefix>` (see `services/calendar_service/src/api.rs`).
+- ALB and target group names are capped at 32 characters, including the `-tg`
+ suffix.
+
+## Secrets and configuration
+
+How values reach code is covered by the
+[config rule](../../.agents/rules/config-and-service-urls.md). For infrastructure
+specifically:
+
+- **Doppler is the source.** `infra/stacks/doppler-projects` creates one project per
+ service with `lcl`, `dev`, and `prd` environments, synced to Secrets Manager at
+ `/doppler-sync/<project>/<dev|prod>`. Add the service to `SERVICE_NAMES`, using
+ the Pulumi project name.
+- **`MacroConfig` reads only `APP_SECRETS_JSON` in ECS.** A plain container
+ `environment:` entry is invisible to it. Put values that infra produces (ARNs,
+ endpoints) into Doppler with a Pulumi `doppler.Secret`, as
+ `infra/stacks/preview-gateway` does. Plain `environment:` is for `ENVIRONMENT`,
+ `DD_*`, and values read through `macro_env_var` or `OVERRIDE_*`.
+- **Secrets go in Doppler, not Secrets Manager.** Add the value to the service's
+ Doppler project; it reaches the task through `DopplerEcsEnvironment` and the
+ `/doppler-sync/` sync. Creating standalone Secrets Manager secrets, putting their
+ names in Pulumi config, and resolving them with
+ `aws.secretsmanager.getSecretVersionOutput(...)` is the old pattern; older stacks
+ still do it, don't copy them. Use `secure:` config only for the few values that
+ must live in Pulumi itself.
+- Never resolve `secretString` into a plaintext env var.
+
+## Other resources
+
+| Need | Use | Example |
+| --- | --- | --- |
+| SQS queue + DLQ + alarms | `Queue` (`packages/resources`) named to match the `macro_queues` constant | `calendar-service/index.ts` |
+| Kafka topic | Add to `crates/macro_event_topics`, run `cargo x kafka-topics`; never hand-edit `.github/kafka-cluster-topics.json` | `kafka-cluster/topics.ts` |
+| Kafka access | `getKafkaClusterPolicy()` on the task role, brokers from `bootstrapBrokersSaslIam` | `calendar-service/service.ts` |
+| Lambda | `Lambda` (`packages/lambda`), binary listed under `deploy_lambdas` | `deleted-item-poller/lambda.ts` |
+| Redis | `Redis` (`packages/resources`) | `calendar-service/index.ts` |
+| DynamoDB | `ServiceDynamoDBTable` (least privilege), not `DynamoDBTable` (`dynamodb:*`) | `packages/service/src/dynamodb.ts` |
+| Bucket | `createBucketV2` | `packages/resources/src/resources/bucket.ts` |
+| Datadog monitor | `infra/stacks/monitoring` (prod only, manual deploy) | `monitoring/monitors/ai-editing.ts` |
+
+When you add a prod queue or bucket, also add it to the local catalog in
+`tooling/xtask/crates/xtask_local/src/local/resources.rs`; Pulumi does not create
+local resources.
+
+## Conventions
+
+- Name resources `${BASE_NAME}-<thing>-${stack}` with `BASE_NAME =
+ pulumi.getProject()`. Component type tokens are `my:components:<Name>`.
+- Pass the stack's `tags` object (`environment`, `tech_lead`, `project`) to every
+ resource; there are no default tags.
+- Inside components, pass `{ parent: this }`.
+- `protect` stateful or adopted resources (MacroDB, KMS keys, WAF, Kafka in prod).
+ Turning off a `deploy_*` config gate destroys what it guarded.
+- Remove `import:` options after adopting a resource, or the next run replaces it.
+- Format with Biome; `infra/biome.jsonc` excludes files uploaded verbatim.
+
+## Deploys
+
+| Trigger | What runs |
+| --- | --- |
+| Push to `main` | `deploy_on_push.yml`: builds nix binaries and Lambdas, runs migrations on the in-VPC runner, then `pulumi up` on dev for every service in `.github/services-config.json` |
+| Published GitHub release | `release-production.yml`: the same flow against prod, then workers, website, and web app |
+| Pull request touching a mapped stack | `pulumi_preview_pr.yml` previews against dev and comments; `code_check_infra.yml` runs Biome and `tsc` |
+| Manual | `deploy-pulumi-stack.yml`, `deploy-service-generic.yml`, `migrate-macro-db.yml` |
+
+- Only stacks listed in `services-config.json` deploy automatically. `gateway`,
+ `macrodb`, `doppler-projects`, `monitoring`, and a few others are manual.
+- Services marked `bootstrap_pending` or `deploy_enabled: false` are skipped.
+- **Migrations deploy before services** and must work with the code already
+ running ([database guide](database.md)).
+- `continueBeforeSteadyState` means a green deploy job does not prove old tasks
+ stopped. The circuit breaker rolls back failed deployments; otherwise roll
+ forward or redeploy an older ref.
+
+## Legacy patterns not to copy
+
+- Per-service ALBs via `serviceLoadBalancer()` (auth, document cognition, MCP,
+ static files). New HTTP services go on the gateway.
+- Raw `aws.sqs.Queue` instead of `Queue`; `createImage`; `createServiceRole`
+ (grants `dynamodb:*`).
+- Lambda env vars holding resolved secret values.
+- `web-app` and `website` pin `@pulumi/aws` v6 and are excluded from `tsc`.
+
+Stale docs to treat with suspicion: `SLACK_IMPORT_ROLLOUT.md` (the worker is on
+and receives `APP_SECRETS_JSON` now), `web-app/README.md` (`yarn`),
+`fusion-auth/README.md`. `lexical-service` runs on ECS, but
+`deploy-lexical-service.yml` still deploys its old Cloudflare worker.
diff --git a/docs/RUNNING_LOCALLY.md b/docs/development/running-locally.md
similarity index 98%
rename from docs/RUNNING_LOCALLY.md
rename to docs/development/running-locally.md
index df0d81aae6..96e9beacc5 100644
--- a/docs/RUNNING_LOCALLY.md
+++ b/docs/development/running-locally.md
@@ -45,7 +45,7 @@ experimental-features = nix-command flakes
The default shell does not include the Tauri platform dependencies. They are large, so they live in their own shells. For Linux desktop development, use `nix develop .#tauri-linux`. For Android development on x86_64 Linux, use `nix develop .#tauri-android`.
For automated Linux desktop offline tests, use `nix develop .#tauri-e2e` and the
-[native E2E guide](../apps/web/tests/native/README.md). It runs the real Tauri
+[native E2E guide](../../apps/web/tests/native/README.md). It runs the real Tauri
webview/native cache with deterministic API fixtures, without the local stack.
## Run the frontend against hosted services
@@ -70,7 +70,7 @@ The first run, or a run after a wasm version change, may build wasm packages.
Vite detects your hostname and prints `https://<hostname>:3000/app/` when ready
(`PORT` overrides the port). It generates a certificate with the same stable
development CA as `just local`; trust `infra/local/certs/ca.pem` once on the
-machine running the browser. See the [certificate README](../infra/local/certs/README.md).
+machine running the browser. See the [certificate README](../../infra/local/certs/README.md).
The visiting machine must resolve the hostname and reach that port. No Docker
proxy or Tailscale is needed. Vite forwards hosted development API and WebSocket
requests through `/__macro_dev/` on this same origin, so arbitrary machine
@@ -183,7 +183,7 @@ or delete the FusionAuth database. Diagnose other bind-mount denials separately;
private labels must not be applied to directories shared by several containers.
For the synthetic Slack recovery harness and separate browser/native coverage,
-see [the Slack import runbook](SLACK_ARCHIVE_IMPORT_RUNBOOK.md).
+see [the Slack import runbook](../runbooks/slack-archive-import.md).
### Seeding sample data (recommended)
@@ -255,7 +255,7 @@ across instances) debugging containers:
`.cursor/mcp.json` points at it). Watch what an agent is doing live at
http://localhost:6080/vnc.html.
-See `.claude/skills/live-debug/SKILL.md` for query recipes (Tempo/Loki HTTP
+See `.agents/skills/live-debug/SKILL.md` for query recipes (Tempo/Loki HTTP
APIs) and the browser-debugging workflow.
For agent turns, use Tempo's TraceQL query
@@ -336,7 +336,7 @@ listener. After applying an updated proxy configuration, restart only the
instance's proxy and reload the page; existing databases and volumes can stay.
Trust `infra/local/certs/ca.pem` in the visiting browser once (see the
-[certificate README](../infra/local/certs/README.md)), then open that URL.
+[certificate README](../../infra/local/certs/README.md)), then open that URL.
The visiting machine must resolve the hostname and reach the proxy port over
your network. Tailscale is not required. The generated certificate also covers
`localhost`, `*.localhost`, `127.0.0.1`, and `::1`. Other aliases require a
diff --git a/docs/RUST_DEVELOPMENT.md b/docs/development/rust.md
similarity index 78%
rename from docs/RUST_DEVELOPMENT.md
rename to docs/development/rust.md
index a2015b9e68..5b345ef51b 100644
--- a/docs/RUST_DEVELOPMENT.md
+++ b/docs/development/rust.md
@@ -1,32 +1,33 @@
# Rust development
Read this for backend changes in `crates/`, `services/`, or Rust tooling.
-Return to the [repository guide](../AGENTS.md) for other task guides.
+Return to the [repository guide](../../AGENTS.md) for other task guides.
## Before editing
-- Read the Rust section of the [style guide](STYLE_GUIDE.md). It owns the coding
- rules, including configuration, errors, tracing, public docs, and test layout.
-- Follow the [hexagonal architecture skill](../.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md)
+- The Rust rules in [`.agents/rules/rust/`](../../.agents/rules/rust/) own the coding
+ conventions, including errors, tracing, public docs, and test layout; the
+ [config rule](../../.agents/rules/config-and-service-urls.md) owns configuration.
+- Follow the [hexagonal architecture skill](../../.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md)
before changing backend Rust. Keep domain policy and authorization in domain
services; inbound adapters call services and outbound adapters implement ports.
- Find the owning crate before adding logic. Do not grow catch-all crates or
bypass the owning domain's APIs with direct database access.
-- For queries, migrations, or SQLx failures, use [database development](DATABASE_DEVELOPMENT.md).
+- For queries, migrations, or SQLx failures, use [database development](database.md).
## Environment
Run commands from the repository root inside `nix develop`, unless a guide says
otherwise. Nix supplies Cargo, the Rust toolchain, `just`, SQLx, and the other
-build tools; see [local prerequisites](RUNNING_LOCALLY.md#shared-prerequisites).
+build tools; see [local prerequisites](running-locally.md#shared-prerequisites).
Database-backed tests need running local Postgres (and Redis where used).
Crates with compile-time SQLx macros may need Postgres even to compile their
unit tests. Standalone pure-logic crates need no database setup.
- **Local machine:** use the database guide for test infrastructure, or
- [running locally](RUNNING_LOCALLY.md#run-the-local-stack) for the full product.
-- **Cursor Cloud:** use [the Cloud entry points](CURSOR_CLOUD.md), not the local
+ [running locally](running-locally.md#run-the-local-stack) for the full product.
+- **Cursor Cloud:** use [the Cloud entry points](cursor-cloud.md), not the local
stack TUI. Run `bash .cursor/infra.sh` before DB-backed tests.
## Build and check
@@ -49,8 +50,8 @@ service's build recipe, e.g. `just services/document_text_extractor/build`.
Use `just --show <recipe>` to check prerequisites; do not assume all Lambdas
have the same build requirements.
-Command definitions live in [rust.just](../tooling/just/rust.just) and
-[check.just](../tooling/just/check.just).
+Command definitions live in [rust.just](../../tooling/just/rust.just) and
+[check.just](../../tooling/just/check.just).
## Test the affected packages
@@ -64,7 +65,7 @@ cargo test -p <package>
There is no root `just test` recipe. Tests use the live local schema, not offline
query metadata. If a test reports missing SQLx cache data, follow the
-[database troubleshooting workflow](DATABASE_DEVELOPMENT.md#troubleshooting);
+[database troubleshooting workflow](database.md#troubleshooting);
do not enable offline mode to work around it.
Keep tests in a sibling `test.rs` (CS-49). For example, `src/user.rs` declares:
diff --git a/docs/development/style-guide.md b/docs/development/style-guide.md
new file mode 100644
index 0000000000..7458128dbe
--- /dev/null
+++ b/docs/development/style-guide.md
@@ -0,0 +1,45 @@
+# Code review style guide
+
+Code conventions are agent rules in [`.agents/rules/`](../../.agents/rules/). Agents
+load each file when they touch matching paths; reviewers and CodeRabbit read the
+same files. This page explains the scheme and indexes the rule files.
+
+**Check locally.** `just check` is the single gate: format, lint, and code rules,
+scoped to your changes against `origin/main`, with every finding printed as
+`file:line [rule-id]` and the command that fixes it. `just check full` adds `tsc`
+and clippy. Mechanically enforceable rules live in [`rules/ast-grep/`](../../rules/ast-grep/).
+
+## IDs
+
+Each rule has a stable ID: `CS-##` for the Rust backend, `FE-##` for frontend and
+shared TypeScript. Cite IDs in reviews ("see CS-30"). Never renumber or reuse an
+ID; deletions leave gaps and new rules take the next free number. A rule line reads
+`<id> rule`, optionally followed by how it is enforced.
+
+## Rule files
+
+| File | IDs | Applies to |
+| --- | --- | --- |
+| [`config-and-service-urls.md`](../../.agents/rules/config-and-service-urls.md) | CS 14–18 | Everywhere |
+| [`CODING.md`](../../CODING.md) | CS 24, 26, 28, 29, 32–35, 71 | Everywhere; read before writing code |
+| [`observability.md`](../../.agents/rules/observability.md) | | Everywhere |
+| [`rust/guardrails.md`](../../.agents/rules/rust/guardrails.md) | | Backend: tests, migrations, crate boundaries |
+| [`rust/db.md`](../../.agents/rules/rust/db.md) | CS | Migrations, SQL, DB clients, outbound adapters |
+| [`rust/architecture.md`](../../.agents/rules/rust/architecture.md) | CS | Rust |
+| [`rust/code.md`](../../.agents/rules/rust/code.md) | CS | Rust |
+| [`rust/libraries.md`](../../.agents/rules/rust/libraries.md) | CS 56–67 | Rust and `Cargo.toml` |
+| [`rust/security.md`](../../.agents/rules/rust/security.md) | CS | Rust |
+| [`web/data.md`](../../.agents/rules/web/data.md) | FE | `apps/web`, `packages` |
+| [`web/solid.md`](../../.agents/rules/web/solid.md) | FE | `apps/web`, `packages` |
+| [`web/architecture.md`](../../.agents/rules/web/architecture.md) | FE | `apps/web`, `packages` |
+| [`web/libraries.md`](../../.agents/rules/web/libraries.md) | FE 35–46 | `apps/web`, `packages` |
+| [`web/ui.md`](../../.agents/rules/web/ui.md) | FE | `.tsx` |
+| [`web/mobile.md`](../../.agents/rules/web/mobile.md) | | `apps/web` UI and CSS on touch and phones |
+| [`web/ui-primitives.md`](../../.agents/rules/web/ui-primitives.md) | | `apps/web/src/components/ui` |
+| [`web/startup-bundle.md`](../../.agents/rules/web/startup-bundle.md) | | `apps/web/src` |
+| [`web/lexical-nodes.md`](../../.agents/rules/web/lexical-nodes.md) | | Lexical nodes and decorators |
+| [`infra/pulumi.md`](../../.agents/rules/infra/pulumi.md) | | `infra/`, deploy config |
+
+To find a rule by ID: `rg 'CS-30' .agents/rules`. To add one, use the
+[rule template](../../.agents/templates/rule.md); an ID-bearing rule goes in the
+file for its scope with the next free number.
diff --git a/docs/guides/README.md b/docs/guides/README.md
new file mode 100644
index 0000000000..eef69e2f81
--- /dev/null
+++ b/docs/guides/README.md
@@ -0,0 +1,21 @@
+# Guides
+
+End-to-end walkthroughs for common changes. Each lists every place the change
+touches, in order, with the existing code to copy.
+
+| Adding | Guide or skill |
+| --- | --- |
+| A deployable service, worker, or Pulumi stack | [new-service.md](new-service.md) |
+| A new entity type (document, channel, form, ...) | [add-entity.md](add-entity.md) |
+| A web block (file viewer or entity editor) | [add-block.md](add-block.md) |
+| An HTTP endpoint, domain to web client | [add-http-endpoint.md](add-http-endpoint.md) |
+| A GraphQL field, query, mutation, or subscription | [add-graphql-field.md](add-graphql-field.md) |
+| A notification kind | [add-notification-kind.md](add-notification-kind.md) |
+| A Kafka topic, event, or consumer | [add-kafka-event.md](add-kafka-event.md) |
+| A MacroDB table, column, or query | [database guide](../development/database.md) |
+| An AI tool | [`create-ai-tool` skill](../../.agents/skills/create-ai-tool/SKILL.md) |
+| A backend endpoint to the TypeScript SDK | [`add-sdk-endpoint` skill](../../.agents/skills/add-sdk-endpoint/SKILL.md) |
+| A feature flag (web or backend) | [`feature-flags` skill](../../.agents/skills/feature-flags/SKILL.md) |
+| A view's feature tour | [`add-tour` skill](../../.agents/skills/add-tour/SKILL.md) |
+| Collaborative markdown on a feature | [`collab-surface-core` skill](../../.agents/skills/collab-surface-core/SKILL.md) |
+| A feature on shared database storage | [`database-core` skill](../../.agents/skills/database-core/SKILL.md) |
diff --git a/docs/guides/add-block.md b/docs/guides/add-block.md
new file mode 100644
index 0000000000..357208c310
--- /dev/null
+++ b/docs/guides/add-block.md
@@ -0,0 +1,364 @@
+# Adding a block
+
+Blocks are a legacy pattern we live with (FE-47). A block is a thin shell: a
+`definition.ts` that registers and lazy-loads, and an adapter that translates
+block state once. Everything else is an ordinary layered feature that works
+without a block.
+
+A block is the web app's viewer or editor for one file type or entity:
+`apps/web/src/features/block-<name>/`, mounted by the block loader whenever a
+split opens `<name>/<id>`. A new block touches a dozen or more places across
+the web app, the file-type and entity models, search, AI tools, and the build.
+Each section below is one of them, in the order you reach them. The lessons from
+past launches and their follow-up fixes are called out inline.
+
+## Pick a model to copy
+
+| Building | Copy | Why |
+| --- | --- | --- |
+| Editor for a file type with a Rust engine | `block-psd` + `crates/psd_engine` + `apps/web/src/lib/core/psd-engine` | Newest full example: layered feature, worker-hosted wasm engine, feature flag, create flow, search parser, AI read tool, browser fixture |
+| Editor that takes over a type that used to download | `block-pptx`, `block-write` | Flag-off path keeps download-only; `write` shows how a type switches blocks behind a flag |
+| Entity that is not a document (own table and API) | `block-form` | Entity type, item type, previews, sharing, Quick Access, a public route, production composition split out (`form-context-production.tsx`) |
+| Feature layering in general | `features/activity`, `block-form` | The FE-33 reference and a block that follows it end to end |
+
+Don't copy `block-channel` or `block-pdf` ([web agent guide](../../apps/web/AGENTS.md)).
+Read [FE-33 and FE-34](../../.agents/rules/web/architecture.md),
+[frontend feature architecture](../architecture/frontend-features.md), and the
+[startup bundle rule](../../.agents/rules/web/startup-bundle.md) before writing
+the block.
+
+**File-backed or entity-backed.** A file-backed block opens a document stored in
+document storage (`source.type === 'dss'`, a `fileType`, bytes behind a
+presigned URL); you add a file type and usually an engine. An entity-backed
+block opens a row of its own table through its own API; you add an entity type
+and none of the file-type steps. Sections 4 and 5 are one or the other.
+
+## 1. Folder, definition, and registry
+
+- Add the name to `BlockRegistry` in
+ `apps/web/src/lib/constants/block-registry.ts`.
+- Create `apps/web/src/features/block-<name>/definition.ts` exporting
+ `definition = defineBlock({...})` with `name` as a string literal.
+ `apps/web/src/lib/core/constant/allBlocks.ts` discovers every
+ `features/*/definition.ts` with `import.meta.glob` and throws at boot on a
+ name missing from the registry or defined twice; `allBlocks.test.ts` checks
+ the same by reading the literal. There is no separate list of "virtual"
+ blocks any more: every registry name needs a real definition.
+- **`definition.ts` is eager.** The glob puts every definition in the entry
+ chunk. Blocks used to import their components statically here, which put
+ every block's UI in the startup bundle until a sweep made them lazy. Use
+ `component: lazy(() => import('./<name>-block'))` and dynamic-import query
+ modules inside `load` (`block-form/definition.ts`). A `loading` placeholder is
+ allowed but must be a tiny skeleton with no editor or engine imports. Making a
+ block eager is a measured trade (the agent block is eager on purpose, as the
+ hot path), not a default. No test guards this; the build only fails on a
+ file over 10 MB, so check the entry chunk yourself (see
+ [Verify locally](#verify-locally)).
+- `load(source, intent)`:
+ - Return `LoadErrors.INVALID` (or `MISSING`) for sources you don't handle.
+ - Answer `intent === 'preload'` before fetching bytes.
+ - Load from where the bytes actually live. A stored binary uses
+ `fetchBinaryDocumentData` and `fetchBinary` (`block-psd`). A file seeded
+ into the sync service on first open uses `fetchFileDocumentOpenContext`
+ (`block-write`). The DOCX editor first shipped with the Markdown loader,
+ which requires a sync location an uploaded file doesn't have yet, and
+ every upload failed to open.
+ - Use the typed fetch helpers as they are. A cast hid `'arraybuffer'` versus
+ `'arrayBuffer'` in the DOCX download and broke it.
+ - When the block's feature flag is off, return the file with `bytes: null`
+ so the block offers a download (`block-psd/definition.ts`).
+ - Start the engine's wasm fetch while storage answers, except on preload
+ (`block-fig/definition.ts`, `warmEngine`).
+- Options: `accepted` (extension → MIME; `{}` for entities),
+ `liveTrackingEnabled` (presence indicators), `editPermissionEnabled` (the
+ share menu inside the block offers Edit only when set), `openTrackingEnabled`
+ (defaults on and writes a history row; turn it off when there is nothing to
+ record, as `block-database` does), `defaultFilename`, `aliases`.
+- Gate the block with a flag in `apps/web/src/lib/core/constant/featureFlags.ts`
+ via the [feature-flags skill](../../.agents/skills/feature-flags/SKILL.md).
+ `isFeatureEnabled` answers `false` until PostHog has loaded, so on a cold deep
+ link a PostHog-gated block reads as off. Wait for the decision in both
+ `component` and `load`, as `block-database/queries/database-rollout.ts` does.
+- A lazy view inside the block needs its own `<Suspense>`. Without one the
+ suspension reaches the app shell, which blanked the screen on mobile.
+
+### Layering
+
+New blocks use the layered structure (`core/`, `queries/`, `primitives/`,
+`components/`, `views/`, `context/`), not the legacy block state system. The
+one file allowed to read legacy state is the adapter, `<name>-block.tsx`: it
+reads `blockDataSignal`, `useBlockId`, `useCanEdit` and friends **once** and
+hands identity, permissions, and host actions to a feature context or props
+(`block-psd/psd-block.tsx`, `block-form/form-block.tsx`). Never call `useBlock*`
+below the adapter: components that did crashed with "must be used within a
+Block component" once they were mounted outside `<Block>` (for example in
+Drive's detail pane), which is what FE-34 came from.
+
+Register the layer directories in **all eight** `rules/ast-grep/{ts,tsx}-feature-*.yml`
+rules, or the layer lint never runs on them. `block-pptx`, `block-fig`, and
+`block-database` are unregistered and `block-psd` is only in six; copy the
+`block-form` entries.
+
+## 2. Maps keyed by block name
+
+With the name in `BlockRegistry`, `bun run type-check` fails until you add it to
+the exhaustive maps:
+
+- `apps/web/src/lib/core/block.ts`: `_ValidBlockCombinations` (which blocks may
+ share a split) and `ValidNestingCombinations` (where it may render nested;
+ `new Set([])` unless it really embeds, as form cards do in `md` and
+ `channel`).
+- `apps/web/src/lib/core/blockMethodRegistry.ts`: `EmptySpec` unless other code
+ calls methods on the block.
+- `apps/web/src/lib/core/component/EntityIcon.tsx`: `ENTITY_ICON_CONFIGS`
+ (icon, bold icon, colors, `prettyName`). Lists, previews, drag images, and
+ the create menus all read it.
+- `apps/web/src/lib/core/component/FileList/constants.tsx`: `_fileTypeColors`.
+- `apps/web/src/features/entity/utils/buildEntityData.ts`: the document arm for
+ file-backed blocks, the `undefined` arm for entities that don't come from Soup.
+
+Not type-enforced: an entity-backed block also goes in `NonDocumentBlockTypes`
+in `block.ts`.
+
+## 3. Routes and splits
+
+- **No route to add for the block itself.** `/app/<name>/<id>` resolves through
+ `legacyContentRoute` and `decodeLegacyPair`
+ (`apps/web/src/components/app/split-layout/split-router/legacy-route.ts`), and
+ Home's inline route takes any registered name (`homePreviewRouteParams` in
+ `apps/web/src/features/home/home-route-schema.ts`, derived from
+ `BlockRegistry`). Home's schema once excluded `write`, so DOCX files didn't
+ open from Home; don't add per-block exclusions there.
+- `apps/web/src/components/app/split-layout/componentRegistry.tsx` is for
+ views (Home, Drive, Settings), not blocks. Don't register a block there.
+- **Inline detail panes.** Drive and entity detail panes open a document inline
+ only for the types in `entityDetailBlockType`
+ (`apps/web/src/components/entity-detail/EntityDetail.tsx`) and
+ `DRIVE_DOCUMENT_TYPES`
+ (`apps/web/src/features/drive-view/primitives/drive-route-schema.ts`);
+ everything else opens as a full block in a split. Leave a new block out
+ unless you also build an inline detail view for it.
+- **A standalone page** (public, outside the split layout, such as a form's
+ respond link): a `defineRoute` in `apps/web/src/routes/routes.ts`, a page in
+ `apps/web/src/routes/pages.tsx` that lazily imports the feature, a `lazyNamed`
+ export in `apps/web/src/routes/lazy-route-views.ts`, and a `<Route>` in
+ `apps/web/src/routes/app-router-view.tsx` under the shell it needs from
+ `apps/web/src/routes/shells.tsx` (`withFormRespondShell` is the model). The
+ shell is chosen per route now; don't match path prefixes in `Root.tsx`, as
+ booking and respond links once did.
+- Entity-backed: add the type to `getEntitySplitContent` in
+ `apps/web/src/components/app/split-layout/components/SplitHeader.tsx` (drag
+ into a split) and to `IdOnlyPreviewSelection` in
+ `apps/web/src/components/app/previewTarget.ts`.
+
+## 4. File type (file-backed blocks)
+
+Skip this section if the type already exists in `crates/model_file_type` and
+you are only giving it an editor (as `pptx` and `docx` did).
+
+- **Backend enum.** Add a `generate_file_types!` row to
+ `crates/model_file_type/src/lib.rs`: variant, extension, MIME, app category.
+ Check `ContentTypeExt` in `crates/model/src/document/file_type.rs`: Photoshop
+ files carry an `image/` MIME and had to be excluded from `is_image`, or image
+ pipelines would try to decode them.
+- **Generated clients.** The `FileType` enum reaches the storage, cognition, and
+ search OpenAPI specs. Regenerate the web clients (`bun run gen-api` in
+ `apps/web`) and the SDK (`just update-generated` in `packages/sdk`); CI's
+ Generated Code Check fails on stale output. The `item_filters` snapshot
+ `crates/item_filters/src/ast/tests/other.json` also changes with each new
+ type in a category it expands.
+- **Frontend mirror.** `apps/web/src/lib/service-clients/service-storage/fileTypeMap.ts`
+ is a copy of the Rust enum that no codegen step refreshes. Generate the rows
+ with `cargo run -p model_file_type --bin generate_typescript_types` (it
+ writes `generated/fileTypeMap.ts` under the current directory) and copy the
+ new ones in. Uploads resolve a missing or `application/octet-stream` content
+ type from this map (`apps/web/src/lib/core/util/uploadContentType.ts`).
+- **Other allowlists.** Channel attachments accept only
+ `apps/web/src/features/channel/Input/accepted-file-types.ts`. Quick Access
+ reads `fileType` from GraphQL; it once dropped the field, so new spreadsheets
+ showed a generic icon and Cmd+K opened the wrong item. Add the type to the
+ cases in `apps/web/src/lib/queries/history/tests/graphql.test.ts`.
+- **`accepted`** in the definition drives `fileTypeToBlockName` and the
+ upload MIME → extension lookup, where the first block to claim a MIME wins.
+ Two extensions sharing one MIME (`psd`, `psb`) map back to the first.
+- **Uploads.** Extensions arrive in any case (`.PSD`); uppercase extensions
+ once failed uploads. Upload a real file of the type, at the size limit, from
+ the drop zone and the file picker.
+- **Taking over an existing type behind a flag.** Keep the flag-off branch in
+ `load` download-only. If the type used to route to another block, branch in
+ `fileTypeToBlockName` and `verifyBlockName` in `allBlocks.ts` as `write`
+ does.
+- **Search.** Add the type to `is_searchable_file_type` in
+ `crates/models_search/src/unified.rs`, a parser in
+ `services/search_processing_service/src/parsers/<type>.rs` (registered in
+ `parsers/mod.rs`), and the dispatch in
+ `services/search_processing_service/src/process/document/raw_document.rs`.
+- **AI tools.** To let agents read or edit the file, add a domain module and
+ toolset under `crates/documents` (`domain/photoshop.rs`,
+ `inbound/toolset/photoshop.rs`), route it in
+ `inbound/toolset/read_content.rs`, and give attachments context in
+ `inbound/attachment/service.rs`. Follow the
+ [create-ai-tool skill](../../.agents/skills/create-ai-tool/SKILL.md) for
+ wiring, `bun run gen-tools`, the tool-call UI
+ (`apps/web/src/lib/core/component/AI/component/tool/handler.tsx`,
+ `apps/web/src/features/block-agent/component/parts/MacroToolCall.tsx`,
+ `apps/web/src/features/block-agent/state/tool-approval-wording.ts`), and the
+ MCP docs pages under `apps/docs/AI/mcp/tools/`.
+- **Saving.** Save through document storage from `queries/` (service clients
+ outside `queries/` fail the `ts-no-service-client-outside-queries` rule).
+ Await the final save before the engine closes, or edits are lost when the
+ user navigates away. A save of a file at the upload size limit must still fit
+ under the endpoint's body limit (`simple_save::MAX_BODY_BYTES` in
+ `services/document_storage_service/src/api/documents.rs` allows for the
+ multipart framing; it once didn't).
+
+## 5. Entity type (entity-backed blocks)
+
+The backend entity comes first: `EntityType` in `crates/model-entity/src/lib.rs`,
+`crates/graphql_common/src/entity_type.rs`, access checks in
+`crates/entity_access`, and a domain crate. Use the
+[database-core](../../.agents/skills/database-core/SKILL.md) and
+[collab-surface-core](../../.agents/skills/collab-surface-core/SKILL.md) skills
+when they apply. Then, on the web:
+
+- `apps/web/src/lib/service-clients/service-storage/itemType.ts`: `ItemType`,
+ `stringToItemType`, and `blockNameToItemType`. Never cast a string to
+ `ItemType` (FE-31).
+- `apps/web/src/features/entity/types/entity.ts`: an `<Name>Entity` type in
+ `EntityData` and `ENTITY_TYPE_VALUES`.
+- `apps/web/src/lib/core/component/EntityIcon.tsx`: an arm in
+ `getEntityIconType`.
+- `apps/web/src/lib/core/component/BlockContainer.tsx` (`resolveEntityType`)
+ and `apps/web/src/lib/core/internal/trackBlockOpened.ts` (`isSoupEntityTag`).
+- Previews: a fetcher in `apps/web/src/lib/queries/preview/fetchers.ts`, so
+ cards and mentions show a name, `no_access`, or `does_not_exist`.
+- Quick Access (`apps/web/src/lib/core/context/quickAccess/types.ts`), sharing
+ (`apps/web/src/features/sharing/global-share-modal/shareable-entity.ts`),
+ Drive's data sources and filters (`apps/web/src/features/drive-view/`), and
+ the Soup row actions in `apps/web/src/features/next-soup/actions/`. An entity
+ outside Soup is invisible in Drive, search, and Cmd+K until each is wired;
+ databases shipped missing from Drive and needed a follow-up for all of them.
+- Agent mentions: add the `blockName` to `crates/prompt/src/mentions.rs`, or
+ agents link the entity as a plain URL.
+
+## 6. Wasm engine (blocks with a Rust engine)
+
+Engines are Rust crates in this repo, compiled to wasm for the browser and used
+natively by search and AI tools. The DOCX editor launched on an npm runtime and
+was moved onto `crates/docx_engine` the next day; start with a crate.
+
+- **Crate.** `crates/<x>_engine`, a workspace member in the root `Cargo.toml`,
+ and a `[profile.<x>-engine-wasm]` (`inherits = "release"`, `lto = "fat"`,
+ `codegen-units = 1`). Add it to the wasm-safe exclusion list in
+ `.config/hakari.toml`, then run `just hakari` and commit
+ `crates/workspace-hack` and `.github/workspace-dep-closures.json`.
+- **Build recipes** in `apps/web/justfile`: `build-<x>-engine-wasm` (wasm-pack
+ into `src/lib/core/<x>-engine/wasm`) and `ensure-<x>-engine-wasm` (rebuild only
+ when the crate, or a crate it depends on such as `fig_engine`, is newer than
+ the output). Add the build recipe to `build-wasm`, which CI's web build and
+ the release builds run, and the ensure recipe to `dev:prepare` in
+ `apps/web/package.json` and to `apps/web/tests/native/build.sh`.
+ `build-tauri-dev`, which builds iOS PR previews, lists its wasm recipes
+ separately and builds no engines today; add yours there if the block must
+ work in those previews.
+- **Output stays out of git.** Put a `.gitignore` containing `wasm/` in
+ `src/lib/core/<x>-engine/`. If the crate has a Rust module named `build`,
+ un-ignore it in the root `.gitignore`; `**/build` silently drops its files.
+- **Assets the engine embeds.** Files read with `include_bytes!` must match
+ `assetFilter` in `nix/cloud-storage.nix` for any service that links the
+ engine; `.ttf` and `.xml` were missing and broke the deploy.
+- **Client** in `apps/web/src/lib/core/<x>-engine/`: `client.ts` (typed
+ requests), `<x>.worker.ts`, `protocol.ts`, `types.ts`, `wasm-module.ts`.
+ - Construct the `Worker` on first use, never at module load: an eager module
+ worker deadlocks WKWebView on iOS ([web agent guide](../../apps/web/AGENTS.md)).
+ - Write `new Worker(new URL('./<x>.worker.ts', import.meta.url), { type: 'module' })`
+ inline. Vite only bundles the worker in that exact shape; hoisting the URL
+ shipped raw TypeScript to production.
+ - Load the binary with a static
+ `new URL('./wasm/<x>_engine_bg.wasm', import.meta.url)` passed to the
+ generated init. The generated JS's own relative URL 404s in production
+ builds.
+ - Keep the engine out of the entry chunk: `definition.ts` and shared helpers
+ import only types from it, and nothing touches it at module load.
+ - Open the block in the native iOS app once. Relative wasm URLs there were
+ routed to native HTTP until `apps/web/src/index.tsx` resolved them first.
+- **Untrusted input.** Parsers get fixed budgets for decompression, pixel
+ counts, and allocation that never trust sizes declared in the file.
+- CI's vitest job builds no engine wasm. Unit tests must not load it; mock
+ the engine client or test pure `core/` functions.
+
+## 7. Create flows
+
+- `queries/create-<name>.ts` (`block-psd/queries/create-psd.ts`): create the
+ document (`storageServiceClient.createDocument`, then `uploadToPresignedUrl`)
+ or the entity through its API, then `postNewHistoryItem`, `setPreviewOnCreate`,
+ `refetchSoupEntity`, and `analytics.track('create_entity', ...)`.
+- `apps/web/src/features/command/Launcher.tsx`:
+ - a case in `runCreateAction`, behind the flag;
+ - an entry in `CREATABLE_BLOCKS` with an unused one-letter `hotkey`;
+ - the flag subscribed in `useCreateMenuBlocks`, or a flag that resolves after
+ mount leaves the menu stale until reload.
+
+ `CREATABLE_BLOCKS` also feeds the sidebar, Drive, and mobile create menus.
+- `apps/web/src/features/command/core/create-menu-details.ts`: a `DETAILS`
+ entry (group, tagline, details, examples) and a `SHORT_TAGLINES` entry, both
+ keyed by the launcher **label**. A label with no entry silently lands in
+ "Other".
+- `apps/web/src/lib/core/hotkey/tokens.ts`: `TOKENS.create.<name>` and
+ `<name>NewSplit`.
+- `apps/web/src/features/block-project/component/ProjectCreateMenu.tsx`: a
+ spec, plus the flag check in both filters.
+- `apps/web/src/features/command/Launcher.test.ts` and `Launcher.test.tsx`: mock
+ your create module and flag. The test fails on duplicate hotkeys.
+
+## 8. Tests
+
+- Colocated vitest for `core/`, `primitives/` (with fake sources), and
+ `queries/` (with fake clients), per [frontend feature
+ architecture](../architecture/frontend-features.md#testing-the-boundaries).
+- **Test the real load path.** The DOCX load failure in section 1 shipped
+ because the editor's standalone harness skips the block loader. Add a
+ `definition.test.ts` that drives `load` the way the app does
+ (`block-write/definition.test.ts`).
+- Engine editors get a browser fixture in `block-<name>/browser-test/`
+ (`vite.config.ts`, `playwright.config.ts`, `README.md`; see
+ `block-psd/browser-test/README.md`). These don't run in CI; run them before
+ you push.
+- Backend: tests beside each new parser, toolset, and domain module.
+
+## 9. Agent guide
+
+The block adds a route and a create flow, so add a section to
+[`docs/agent-guide/documents.md`](../agent-guide/documents.md) (or its own
+page, as [`forms.md`](../agent-guide/forms.md) is) and update the table in
+[`docs/agent-guide/README.md`](../agent-guide/README.md) in the same change.
+Cover how to create one, what the editor's controls are, and how to verify a
+save.
+
+## Verify locally
+
+```sh
+cd apps/web
+just ensure-<x>-engine-wasm # engine blocks
+bun run type-check
+bun run test -- src/features/block-<name> src/lib/core/constant src/features/command
+bunx playwright test --config src/features/block-<name>/browser-test/playwright.config.ts
+PORT=3003 bun run dev # any free port in 3000-3009
+```
+
+```sh
+cargo test -p <x>_engine -p documents -p search_processing_service -p model_file_type
+just check
+```
+
+In the browser, with the flag on and then off:
+
+- create one from Cmd+K, the sidebar, and a project, and from the hotkey;
+- upload a real file (file-backed), including an uppercase extension;
+- open it from Home, Drive, search, a mention, and a pasted `/app/<name>/<id>`
+ link, in a new split, and on a phone-width window;
+- share it as view and edit with a second account and edit together;
+- reload and confirm the last edit was saved.
+
+Then check the startup bundle didn't grow: run `bun run build` here and on
+`main`, and compare the scripts `dist/index.html` loads directly.
diff --git a/docs/guides/add-entity.md b/docs/guides/add-entity.md
new file mode 100644
index 0000000000..2d9868a2b3
--- /dev/null
+++ b/docs/guides/add-entity.md
@@ -0,0 +1,494 @@
+# Adding an entity type
+
+An entity type is a first-class item with its own id, permissions, and lifecycle
+(document, channel, chat, project, task, initiative, database, form, CRM pipeline).
+A new one is registered in dozens of places across the backend and web app. The
+compiler finds some of them through exhaustive matches. The rest are allow-lists,
+deny-lists, `_ =>` arms, SQL constraints, and string unions that accept a missing
+kind without complaint. Every launch so far missed at least one and needed a
+follow-up fix; those misses are called out inline.
+
+> **Agents never deploy or touch production.** Everything here is code, migrations,
+> and generated files in a PR. Deploying the services and Kafka topics is done by a
+> person, or by an agent when a person explicitly asks.
+
+## Pick a model to copy
+
+| Building | Copy | Why |
+| --- | --- | --- |
+| The smallest correct registration | `CrmPipeline` (`crates/crm`, `crm_pipeline_entities`) | Newest kind; touches every core registration point with the least feature code |
+| A full-stack kind outside Soup | Forms (`crates/forms`, `apps/web/src/features/block-form`) | Newest end-to-end launch: access, public audience, entity mutation, mentions, Drive catalog, AI tools, SDK entity, agent guide |
+| A Soup kind with properties, discussions, activity, MCP | Initiatives (`crates/initiative`, `crates/graphql_initiative`) | Built in clean layers; the [design doc](../design/initiatives-projects.md) records the order |
+| A kind on reusable storage | Databases (`crates/databases`, `database_entities`) | Separates storage from the app entity; read the [database-core skill](../../.agents/skills/database-core/SKILL.md) |
+
+Collaborative markdown on the entity (descriptions, notes) follows the
+[collab-surface-core skill](../../.agents/skills/collab-surface-core/SKILL.md).
+
+**Find the silent registration points by grepping your model.** After the steps
+below, run `rg -l "EntityType::CrmPipeline|'crm_pipeline'"` (substitute your
+model's spellings, such as `EntityType::Form` and `'form'`) and visit every hit
+outside its own crate and feature. That list is the real
+checklist; this guide explains what each entry means.
+
+## Decide the scope first
+
+Not every entity needs every capability. Decide each one up front and write it
+into the PR description, because the optional steps fail silently when skipped.
+
+| Capability | Needed when | Section |
+| --- | --- | --- |
+| Soup kind (Home, Recent, inbox, GraphQL Soup lists) | It appears in unified lists | 8 |
+| Own catalog instead of Soup | It only appears in Drive or its own view (forms, databases) | 8 |
+| Properties | It has status, assignees, dates, or tags | 6 |
+| Discussions and notifications | People comment on it | 10 |
+| Channel sharing by mention | Posting it in a channel should grant access | 11 |
+| Search | Full-text search must find it | 12 |
+| Favorites | It can be starred | 5 |
+| Collab surface | It has collaborative markdown | collab-surface-core skill |
+
+Ship in layers, each reviewable alone: type and access, then domain and lifecycle,
+then properties and GraphQL, then discussions, then activity, then AI tools, then
+the frontend. A layer may land a stub only if nothing consumes it yet. Hide the
+UI behind a [feature flag](../../.agents/skills/feature-flags/SKILL.md)
+until the backend is complete.
+
+## 1. The entity type
+
+- **`crates/model-entity/src/lib.rs`:** add the `EntityType` variant (strum
+ `snake_case`; that string is stored in `entity_access.entity_type`) and its arm
+ in `is_valid_entity_access_entity`. Add a round-trip case in `src/tests.rs`.
+- **`crates/graphql_common/src/entity_type.rs`:** both directions of
+ `GraphqlEntityType`, and `GraphqlSoupEntityType::try_new` (`None` unless it is a
+ Soup kind).
+- Fix every exhaustive match the compiler now reports. Do not add `_ =>` arms to
+ make it compile; each arm is a decision about the new kind.
+- **Entity registry (decide explicitly):**
+ `crates/entity_registry/shared_entity_registry/src/lib.rs` `RegisteredEntityType`
+ plus `crates/entity_registry/entity_registry/src/domain/owner_grant_policy.rs` records one owner per
+ resource; team deletion cleans up only registered kinds. The `TryFrom` there has
+ a catch-all, and the `entity` table's CHECK constraint lists the allowed kinds,
+ so an unregistered kind is rejected silently. Recent kinds did not register;
+ if yours does, widen the constraint in a migration.
+- Regenerate every client that embeds `EntityType` (storage, cognition,
+ connection, notification, properties, search): `cd apps/web && bun run gen-api`,
+ then `cd packages/sdk && just update-generated`. Run
+ `cd apps/web && bun run gen-dynamic-ui-schema` too; it regenerates
+ `crates/ai_tools/src/display_results/schema.generated.json`, which embeds
+ `EntityType`.
+
+## 2. Schema and migrations
+
+Follow the [database guide](../development/database.md) for generating
+migrations, the SQLx cache, and tests.
+
+- **Table:** a plural `<kind>_entities` table holds identity, name, `user_id`,
+ timestamps, and `trashed_at`. Rust types stay singular. Older kinds (`forms`,
+ `initiative`) predate this; don't copy their names. Reusable storage gets its own
+ table referenced by a foreign key (see database-core).
+- **Grant cleanup trigger:** `entity_access`, `entity_properties`, `favorite`, and
+ collab surfaces have no foreign key to your table. Add an `AFTER DELETE` trigger
+ that deletes the kind's `entity_access` rows, as `database_entities`,
+ `crm_pipeline_entities`, and `forms` do. Initiatives lack one, so deleting an
+ owner's account can orphan their grants.
+- **Enum values get their own migration.** `ALTER TYPE ... ADD VALUE` cannot be
+ used in the transaction that adds it, and SQLx runs each file in one
+ transaction. Add the value in one migration and backfill in the next (see
+ `20260922164805_add_initiative_property_entity_type.sql` and the backfill after
+ it). Backfills use `ON CONFLICT DO NOTHING`.
+- **Widen CHECK constraints in two steps** on large tables: add the new
+ constraint `NOT VALID` with `SET LOCAL lock_timeout`, then `VALIDATE CONSTRAINT`
+ in a later migration (`20260922164641_initiative_discussion_parents.sql` and
+ `20260927022538_validate_initiative_discussion_parents.sql`).
+- **Migrations deploy before the services** and must work with the running binary.
+ The databases app-entity split dropped columns the deployed service still read,
+ as a deliberate destructive cutover; initiatives dropped a column without a
+ compatibility step. Don't repeat either: add, migrate readers, then remove in a
+ later PR.
+
+## 3. The domain crate and its hosts
+
+- Create `crates/<kind>` with `domain/{models,ports,service}`, `inbound/`
+ (`axum_router`, `toolset`), and `outbound/` (`pg_<kind>_repo`), each behind
+ features. Follow the
+ [hexagonal architecture skill](../../.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md).
+ Add it to `members` in the root `Cargo.toml` and run `just hakari`.
+- **Host it in `services/document_storage_service`:** nest the router in
+ `src/api.rs`, add state types to `src/api/context.rs`, construct the service in
+ `src/server.rs` (not `main.rs`, which is now a stub), and register the OpenAPI
+ paths in `src/api/swagger.rs`.
+- Other services build the same domain service (agent harness, agent trigger,
+ authentication, MCP, document cognition). Give the crate one `wiring.rs` that
+ every host calls, as `crates/forms/src/wiring.rs` does. Hosts built separately
+ drift: tools in one host have pointed at the wrong service, and writes from a
+ host with a no-op event broker never reached the activity feed.
+- If it calls `sqlx::query!`, run `nix develop --command just prepare_db` and
+ commit `.sqlx/`.
+
+## 4. Access and sharing
+
+The `crates/entity_access/AGENTS.md` recipe is ports, then service, then
+Postgres repo.
+
+- **`src/domain/ports.rs`:** `get_<kind>_access`. Add `list_<kind>_access` only if
+ a catalog needs every grant at once.
+- **`src/outbound/pg_access_repo/queries/<kind>_access.rs`** (registered in
+ `queries.rs`): union the caller's `entity_access` rows with link, team, and
+ public grants; exclude trashed rows; require the `<kind>_entities` row to exist.
+ Copy `form_access.rs` for a public audience, `pipeline_access.rs` for the
+ minimum. Add `explain_<kind>_access` behind `explain_binary`, and new
+ `AccessGrant` variants in `crates/entity_access/src/domain/models/access_explanation.rs` if the kind
+ introduces a new grant.
+- **`src/outbound/pg_access_repo.rs`:** the trait impl and the
+ `get_team_entity_access` arm.
+- **`src/domain/service.rs`, three runtime traps:**
+ - `get_optimized_access` ends in `unreachable!`. Missing the arm panics.
+ - `get_users_by_entity` ends in a `BadRequest` arm. Missing it silently breaks
+ notification and realtime audiences.
+ - `get_team_scope_permission` decides bot and team receipts.
+- **`src/inbound/axum_extractors/<kind>.rs`** plus `axum_extractors.rs`: handle
+ users, bots, internal callers, and anonymous public callers if supported.
+- **`crates/entity_access_db_utils/src/lib.rs`:** the channel-share matches.
+- **Legacy `SharePermission` storage** is only for initiative-style kinds; new
+ kinds keep grants in `entity_access` plus an audience column. If you do use it,
+ `share_permission_db_utils::get_share_permission_id` ends in `bail!`, and
+ `models_permissions` needs a `TeamShareCreation` variant.
+- **Get the permission model right in the first PR.** Initiatives shipped with
+ these gaps and needed a dedicated fix:
+ - Return the caller's effective access level from the receipt on every
+ create, get, and update response; never hard-code it.
+ - Sharing changes (members, team, link) are owner-only, even through a general
+ update endpoint.
+ - Operations that touch two entities (assigning a task) need an edit receipt
+ for both, from the same actor, and the domain checks each receipt's type.
+ - Default team sharing must succeed when the creator has no team.
+
+## 5. Lifecycle: rename, trash, delete, favorites
+
+- **`crates/macro_db_client/src/item_access/delete.rs`:** put the kind in the arm
+ for kinds with `entity_access` rows.
+- **Entity mutation:** implement the `crates/entity_mutation` capability traits
+ (`RenameEntity`, `TrashEntity`, `RestoreEntity`, `DeleteEntityPermanently`, ...)
+ in the domain crate, as `crates/forms/src/domain/entity_mutation.rs` does, then
+ add the arms in `services/document_storage_service/src/service/entity_mutation.rs`
+ and the adapters in `src/outbound/entity_mutation.rs`. GraphQL mutations
+ (`crates/graphql_entity_mutation`) are generic. Initiatives still use a
+ hand-written delete route; don't copy that.
+- **Owned content:** purge owned documents through the documents domain
+ (`crates/documents/src/domain/purge.rs`). Initiatives first reimplemented the
+ purge in the service with raw SQL and queue messages, and lost the content
+ cleanup when the purge failed after the row was deleted. Owned collab surfaces
+ are retired through `OwnedSurfaceService`.
+- **Trash auto-purge:** `services/deleted_item_poller` purges trashed items after
+ 30 days only for kinds it knows; its `AGENTS.md` has the recipe. Forms,
+ databases, and pipelines are not there yet, so their trash is never emptied.
+- **Favorites (optional):** `crates/favorites/src/domain/mutation_service.rs`
+ `validate_favoritable` is exhaustive; recent kinds return unsupported. If you
+ enable favorites, also update `crates/graphql_favorite` and clean up `favorite`
+ rows on delete, since nothing else does.
+
+## 6. Properties (optional)
+
+- `crates/models_properties/src/shared/entity_type.rs` (maps to the Postgres enum
+ `property_entity_type`; see the enum rule in section 2) and
+ `src/api/property_target.rs`.
+- `crates/properties/src/domain/model.rs` (`canonical_entity_type`,
+ `storage_entity_type`; return `None` if the kind has no properties), plus
+ `inbound/axum_router/extract.rs`, `outbound/permission_queries.rs`,
+ `outbound/permission_service.rs`, and `domain/activity.rs`.
+- System properties: `crates/system_properties/src/domain/model/constants/system_property_key.rs`
+ and an `attach_<kind>_properties` call at create in
+ `crates/system_properties/src/domain/service.rs`.
+- Filters: `crates/graphql_common/src/property_filter.rs` and
+ `crates/graphql_properties`.
+- **Lessons:** a create that fails after properties are attached must remove
+ them (`entity_properties` has no foreign key). Reusing another kind's property
+ definition (task status) exposed options that are invalid for the new kind;
+ give it its own definitions.
+
+## 7. Events and activity
+
+Required for anything people act on; Recent is built from activity.
+
+- **Topic:** add it to `topics!` in `crates/macro_event_topics/src/lib.rs` (and its
+ test), then `cargo x kafka-topics`. Never hand-edit
+ `.github/kafka-cluster-topics.json`. The topic must exist before the producer
+ deploys, or events are lost.
+- **Events:** `crates/<kind>/src/domain/events.rs`, serde-tagged, with
+ `attribution` (actor and on-behalf-of), published from the domain service.
+ Every host must get the real publisher, not a no-op.
+- **Activity:** implement `activity::ActivitySource` in
+ `crates/<kind>/src/domain/activity.rs` with an exhaustive match. Shared actions
+ use `CommonAction`; new `Action` variants go in
+ `crates/activity/src/domain/models.rs` (codec and `ActionTag`),
+ `crates/activity/src/inbound/toolset/read_activity.rs`, and
+ `crates/graphql_activity/src/objects.rs`.
+- Register the topic in `services/document_storage_service/src/service/activity.rs`
+ (`declare_topics!` and an `ingest` arm). Hard deletes return `Ingest::Purge`.
+- **`crates/activity/src/outbound/pg_activity_repo.rs`:** the const fn
+ `_rankable_entity_types_are_exhaustive` forces an arm, but the list in
+ `rankable_entity_types()` beside it is not checked. Update both.
+- **Lesson:** events that reference other entities (an initiative's tasks) must be
+ filtered by the viewer's access to those entities, in feeds and in realtime.
+- Persisted payloads that readers parse later carry a version, and readers refuse
+ unknown versions.
+
+## 8. Soup, Home, and Recent
+
+Choose one shape.
+
+**Soup kind** (initiatives, agent sessions, database rows). GraphQL Soup is the
+target, but REST Soup still serves users behind `enable-graphql-soup`, so the
+kind must work on both; a kind that only worked on one path showed empty lists
+on the other.
+
+- **Model:** `crates/models_soup/src/<kind>.rs` and a `SoupItem` variant in
+ `item.rs`.
+- **Filters:** `crates/item_filters/src/ast/<kind>.rs`, a field on
+ `EntityFilterAst` in `ast.rs` (plus `expand_ast` and `IsEmpty`), and
+ `<Kind>Filters` in `lib.rs`. Make the kind **opt-in**: an empty filter excludes
+ it. Set the new field in every `EntityFilterAst { .. }` literal the compiler
+ reports.
+- **Postgres legs** in `crates/soup/src/outbound/pg_soup_repo/`: `<kind>.rs` with
+ `<kind>/by_ids.sql` (hydration, registered in both by-ids paths of
+ `pg_soup_repo.rs`); `expanded/dynamic/<kind>.rs` with detail and grouped SQL;
+ an `include_<kind>` gate in both builders of `expanded/dynamic.rs`; and a
+ `NULL::` column in every other detail clause so the UNION lines up. Gate the
+ arm off when its filter cannot match: an ungated arm once broke every grouped
+ view with a bind-placeholder collision.
+- **Feeds** (if it belongs in Recent, inbox, or the Home work feed):
+ `candidate_gates.rs`, `touched.rs` (Recent, which reads activity, so section 7
+ is a prerequisite), `notified.rs` with `notified/query.sql`, `work_feed/`, and
+ the routing arms in `crates/soup/src/domain/service.rs` and
+ `domain/service/favorites.rs`. Keep new gates index-only; these queries have
+ been cancelled on the replica in production for scanning too much.
+- **Prefer a listing port** owned by your crate (`crates/soup/src/domain/models/contact_listing.rs`
+ is the pattern) over SQL inside `crates/soup` when the kind's data lives in its
+ own crate.
+- **Projection:** `crates/soup_filter_projection/src/lib.rs` returns `Ok(None)` and
+ `crates/item_filter_index/src/lib.rs` returns `Unsupported(..)` unless you build
+ local-first filtering.
+- **Realtime:** `crates/soup_realtime/src/inbound/kafka_consumer.rs`: add the topic
+ to `declare_topics!`, write `patches_from_<kind>_event`, map property events in
+ `soup_entity_type_from_property`, and add the channel-reference arm; add the
+ crate to the `consumer` feature in `crates/soup_realtime/Cargo.toml`. Kinds have
+ launched without realtime and lists stopped repainting. Patch the single
+ entity; never invalidate every Soup list, which once saturated the production
+ replica. Delivery is at least once.
+
+**Own catalog** (forms, databases): no Soup kind. Return `None` from
+`GraphqlSoupEntityType::try_new`, error in the `graphql_soup` loader arm, and
+list the kind through its own query merged into Drive (section 15). It will not
+appear in Home or Recent; say so in the PR.
+
+## 9. GraphQL
+
+- **Soup object:** in `crates/graphql_soup/src/objects.rs`, a `GraphqlSoup<Kind>`
+ implementing `GraphqlSoupEntity`, its `type_name` and `SoupItem` arms, and
+ `impl_common_interface_edges!`; re-export in `lib.rs`. Add the filter input to
+ `crates/graphql_soup_filter_input`, edges to `crates/complete_graph/src/edges.rs`,
+ and the possible-types assertion (and count) in
+ `crates/client/cache-core/src/meta/test.rs`.
+- **Kind crate (optional):** `crates/graphql_<kind>` with `context`, `inputs`,
+ `loaders`, `mutation`, `objects`, `query`, copied from `crates/graphql_initiative`.
+ Compose it in `crates/complete_graph/src/schema.rs`; viewer-scoped reads go under
+ `GraphqlUser` (see `crates/complete_graph/AGENTS.md`). Wire it in
+ `services/document_storage_service/src/api/graphql_soup.rs` and `src/server.rs`.
+- **Read-after-create goes to the primary.** GraphQL Soup reads the replica, which
+ lags seconds in production and not at all locally. A new agent session read
+ back as "not accessible" and lost its first prompt. Build the by-id loader from
+ `primary_entity_soup` in `server.rs`, as `crates/graphql_initiative/src/mutation.rs`
+ does, and test with an empty replica fake.
+- **Regenerate:** `cargo run -p complete_graph --bin graphql_schema -- static_assets/schema.graphql`,
+ then `cd apps/web && bun run gen-graphql` (codegen plus the cache entity resolver
+ schema). `sdl_matches_committed_schema_graphql` fails on drift, and
+ `bun run check-graphql-cache-schema` (part of `bun run check`, not a separate CI
+ job) fails on a stale `apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts`.
+ Any SDL change resets every client's persisted cache.
+
+## 10. Discussions and notifications (optional)
+
+- **Parent:** a `MessageParent` variant in `crates/messages/src/domain/models.rs`
+ and a migration widening the parent-type CHECK (two-step, section 2). The
+ compiler then walks you through `crates/messages`, `agent_trigger`,
+ `agent_harness`, `agent_session`, `channel_bots`, and `coding_agent_worker`.
+ The discussion-parent authorization in `crates/messages/src/domain/service.rs`
+ ends in a `Forbidden` arm.
+- **Not caught by the compiler:** the zod enum in
+ `services/lexical-service/src/endpoints/agent-context.ts` and
+ `AgentContextParent` in `packages/lexical-core/utils/agent-context.ts`. CRM
+ discussions missed both, and agents mentioned there got no context.
+- **Notifications:** a metadata module in `crates/model_notifications/src/metadata/`
+ with its `define_notif_event!` variant, a GraphQL event in
+ `crates/graphql_notification/src/notification_event/`, the sender in
+ `crates/messages/src/outbound/notification_sender.rs`, and
+ `BLOCKABLE_NOTIFICATIONS` in `services/notification_service/src/api/user_notification.rs`.
+ The web list in `apps/web/src/features/notifications/notification-event-catalog.ts`
+ must match it by hand.
+- A new **agent-trigger event** shape also needs an arm in
+ `crates/webhook/src/domain/ingestion.rs`, or the SSE fan-out drops it silently.
+
+## 11. Mentions and channel references
+
+Four vocabularies must agree:
+
+1. `packages/lexical-core/utils/mentions.ts` (block name to reference type). Its
+ match ends in `P._ => 'document'`, so a missing kind becomes a document.
+2. `packages/lexical-core/utils/message-references.ts` (allowed reference kinds).
+3. `crates/messages/src/domain/mentions.rs` `MessageReferenceKind` and the
+ reference authorization in `crates/messages/src/domain/service.rs`. Unknown
+ kinds are stored without an access check.
+4. `crates/channels/src/domain/models.rs` `ReferencedShareItemType` and
+ `reference_sharing.rs`. **`grant_level` defaults any kind to View**, so
+ posting a mention shares the entity with the whole channel unless you decide
+ otherwise (initiatives opt out). Add the kind to the `matches!` list in
+ `crates/channels/src/outbound/pg_channel_reference_share_permissions.rs`, or it
+ falls through to legacy share permissions and fails at runtime.
+
+- **Agent prompt:** add the kind to `crates/prompt/src/mentions.rs` and, if it has
+ URLs, `crates/prompt/src/mcp_item_links.rs`. Without it agents linked forms as
+ plain URLs.
+- **Deploy skew:** lexical-service deploys on every push to `main` that touches
+ `packages/lexical-core` or `services/lexical-service`, but the web app ships on
+ releases. New node data must parse in the old composer and vice versa; run
+ `bun run check` in `services/lexical-service`, and bump
+ `MARKDOWN_VERSION_COUNTER` per `.agents/rules/web/lexical-nodes.md`.
+- Record mentions on create as well as on edit, or References misses them.
+
+## 12. Search (optional)
+
+Initiatives, forms, and databases are not in OpenSearch; Cmd+K finds them through
+Quick Access (section 15) and agents through their list tools. That is the
+minimum.
+
+For full-text search, follow the `AGENTS.md` recipes in
+`crates/opensearch_client` (index shapes), `crates/models_search`,
+`crates/search_service` (queries), and `services/search_processing_service`
+(Kafka consumer and backfill). Agent sessions are the newest example.
+`crates/name_search` covers name-only search from Postgres. **Deploys never
+create OpenSearch indices or aliases**; that is a manual step for a person, and
+upserts must not create an index by accident.
+
+## 13. AI and MCP tools
+
+Follow the [create-ai-tool skill](../../.agents/skills/create-ai-tool/SKILL.md)
+and `crates/ai_toolset/TOOL_DESIGN.md`. A new kind adds a whole toolset, which
+the skill doesn't cover:
+
+- Register it in `crates/ai_tools/src/lib.rs` (`subagent_toolset()` or the
+ host-specific branches of `tools_for`), eager or deferred.
+- Give its context to every place `ToolServiceContext` is built:
+ `crates/ai_tools/src/build_context.rs`,
+ `services/document_cognition_service/src/server.rs` and its
+ `services/document_cognition_service/src/api/context/test.rs`, and `services/mcp_service/src/context.rs`. Add it to
+ `with_actor` in `crates/ai_tools/src/tool_context.rs`, or agent writes are
+ attributed to the default bot. Add a test in `crates/ai_tools/src/test.rs` that
+ the tools resolve on every host; hosts have shipped with tools unwired.
+- Prompt guidance: a section in `crates/prompt/src/` (see `databases`,
+ `crm_pipelines`).
+- Web: a renderer in `apps/web/src/lib/core/component/AI/component/tool/` with
+ `handler.tsx`, and wording in `apps/web/src/features/block-agent/state/tool-approval-wording.ts`.
+- Regenerate: `cd apps/web && bun run gen-tools` and
+ `cd apps/docs && bun run generate:tools` (never hand-edit the MCP tool pages).
+- Gemini rejects recursive schemas and drops records (`additionalProperties`).
+ Use key/value pair lists, and keep recursive input types out of tool schemas.
+
+## 14. SDK
+
+Follow the [add-sdk-endpoint skill](../../.agents/skills/add-sdk-endpoint/SKILL.md).
+A new noun gets `packages/sdk/src/entities/<noun>/` registered in
+`src/macro.ts` (forms is the model); methods take entity handles, never raw ids.
+Endpoints you don't wrap go in `src/coverage/skipped.ts` with a reason. Run
+`just update-generated && just check && just coverage` in `packages/sdk`.
+
+## 15. Frontend
+
+Read `apps/web/AGENTS.md`. Paths below are under `apps/web/src/` unless they
+start with `rules/` or `packages/`. Build the feature as `apps/web/src/features/<kind>/`
+with layered `core`, `queries`, `primitives`, `components`, `views`, `context`
+([frontend features](../architecture/frontend-features.md), FE-33); the block
+adapter translates legacy block state into feature context (FE-34).
+`features/block-form` is the newest example. Register its paths in all eight
+`rules/ast-grep/{ts,tsx}-feature-*.yml` files.
+
+**Exhaustiveness.** New branches on a kind use `match().exhaustive()` or a
+`Record<Kind, ...>`, never `.otherwise`, `P._`, `default`, or `switch`. Never cast
+a string to `ItemType`; parse it with `stringToItemType` (FE-31, enforced by
+`rules/ast-grep/ts-no-item-type-cast.yml`). Existing catch-alls hide the new kind,
+so grep for the sibling kind.
+
+- **Item type:** `apps/web/src/lib/service-clients/service-storage/itemType.ts`:
+ the `ItemType` union, `stringToItemType` (an allow-list; add a test case), and
+ `blockNameToItemType`. Both functions end in `.otherwise`.
+- **Block:** `lib/constants/block-registry.ts`, `lib/core/block.ts` (nesting
+ combinations decide where cards render), `lib/core/blockMethodRegistry.ts`, and
+ `features/<kind>/definition.ts` (found by `apps/web/src/lib/core/constant/allBlocks.ts`,
+ which throws at boot when a registry name has no definition).
+- **Routes (optional):** opening in a split is generic. Pages outside the split
+ layout need `routes/routes.ts`, `routes/pages.tsx`, `routes/lazy-route-views.ts`,
+ and `routes/app-router-view.tsx`; a chrome-free public page uses
+ `FocusedShell` in `routes/shells.tsx` (see `formRespondRoute`).
+- **Entity model:** `apps/web/src/features/entity/types/entity.ts` (`EntityData`),
+ `utils/buildEntityData.ts`, `utils/shared.ts`, `extractors/entity-title.tsx`,
+ `extractors-property/entity-key-properties.tsx`, `queries/rename.ts`.
+- **Icon:** `apps/web/src/lib/core/component/EntityIcon.tsx` and
+ `apps/web/src/lib/core/component/FileList/constants.tsx`.
+- **Queries:** keys in `lib/queries/storage/keys.ts`, a module
+ `lib/queries/storage/<kind>.ts` (plus `<kind>-sync.ts` for realtime), and a
+ client in `lib/service-clients/service-storage/<kind>.ts` attached in
+ `client.ts`.
+- **Soup kind:** `soup.graphql` fragment, `graphql-soup.ts` mapper,
+ `lib/queries/soup/transform-utils.ts`, `graphql/entity-input.ts`,
+ `normalized-cache/operations.ts` (mirror the server's opt-in rule), and
+ `features/next-soup/filters/{query-filters,inbox-filters}.ts`. A missing
+ fragment, mapper, or filter branch shows an empty list, not an error.
+- **Own catalog:** a Drive source like `features/drive-view/queries/drive-forms.ts`,
+ merged in `drive-data-source.ts` and `drive-results.ts`, a facet in
+ `filters/drive-facets.ts`, and the create menu in `drive-create-menu.tsx`.
+- **Actions:** the deny-lists in `features/next-soup/actions/make-{copy,delete,move-to-project,rename,share}-action.ts`.
+- **Preview:** `lib/queries/preview/fetchers.ts` (REST) and
+ `lib/queries/preview/graphql.ts`, plus `components/app/previewTarget.ts` and
+ `components/app/split-layout/components/SplitHeader.tsx`. Initiatives launched
+ without a preview fetcher, so their mentions reported no access and ignored
+ clicks.
+- **Mentions:** `lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/`
+ (`MentionsMenu.tsx`, `utils/entityUtils.ts`, `utils/mentionHandlers.ts`),
+ `plugins/mentions/mentionsPlugin.ts`, `component/decorator/DocumentMention.tsx`
+ and `DocumentCard.tsx`, and section 11.
+- **Discovery:** `lib/core/context/quickAccess/types.ts` and
+ `QuickAccessSource.tsx`, `features/command/useCommandItems.ts`,
+ `features/command/Launcher.tsx`, and `create.<kind>` tokens in
+ `lib/core/hotkey/tokens.ts`. Quick Access and Cmd+K are separate
+ registrations; CRM contacts reached one weeks before the other.
+- **Sharing:** `features/sharing/global-share-modal/shareable-entity.ts`,
+ `GlobalShareModal.tsx`, `lib/core/component/TopBar/ShareButton.tsx`, and
+ `linkShare.ts` if team-shareable.
+- **Optional by capability:** properties (`features/property/utils/entityConversion.ts`,
+ `editors/selectors/entityUtils.ts`, `hooks/usePropertyEntityDisplay.tsx`),
+ activity (`features/activity/core/{event,describe-action}.ts`,
+ `queries/decode.ts`, `components/action-glyph.tsx`), notifications
+ (`features/notifications/*`, `features/entity/extractors-notification/*`,
+ `lib/queries/notification/notification-soup.ts`).
+- **Analytics:** `lib/core/internal/trackBlockOpened.ts`.
+
+## 16. Agent guide
+
+Add `docs/agent-guide/<kind>.md` and a row in `docs/agent-guide/README.md`
+covering routes, creation, and editing, and update `ai-chat.md` for new tools.
+
+## Verify locally
+
+```sh
+cargo test -p <kind> -p entity_access -p soup -p complete_graph # SQLX_OFFLINE unset
+just rust-check && just clippy
+cargo x deps --check && cargo x kafka-topics --check
+cd apps/web && bun run gen-api -- --check && bun run check
+cd packages/sdk && just check && just coverage
+just check full
+just run_local # or just stack up
+```
+
+In the browser (the `browser-verifier` subagent): create the entity, share it with
+a second user and a team, mention it in a document and a channel, open it from
+Cmd+K and the mention, trash and restore it, and watch a second session update.
+Ask an agent to read and change it through its tools. Use the `live-debug` skill
+for traces and logs.
diff --git a/docs/guides/add-graphql-field.md b/docs/guides/add-graphql-field.md
new file mode 100644
index 0000000000..b6c3e94fea
--- /dev/null
+++ b/docs/guides/add-graphql-field.md
@@ -0,0 +1,220 @@
+# Adding a GraphQL field, query, mutation, or subscription
+
+The GraphQL API is composed in `crates/complete_graph` from per-domain adapter
+crates (`crates/graphql_<domain>`), served by `document_storage_service`, and read
+by the web app through a normalized cache. One change touches the adapter crate,
+the composed schema, the service wiring, the committed SDL, the web documents,
+and the cache's mutation policy. Most misses compile cleanly and fail at runtime
+as a `null`, an empty list, or a stuck mutation queue; they're called out inline.
+
+This guide covers fields, types, and operations on existing entities. For a whole
+new entity kind, see [add-entity.md](add-entity.md).
+
+Read first: [`crates/complete_graph/AGENTS.md`](../../crates/complete_graph/AGENTS.md)
+(the `id` convention, the viewer pattern, the Soup entity interface), the owning
+`crates/graphql_<domain>/AGENTS.md`, and section 8 of
+[the normalized cache plan](../../apps/web/docs/graphql-normalized-cache-plan.md).
+
+## Pick a model to copy
+
+| Adding | Copy |
+| --- | --- |
+| User-scoped reads | `crates/graphql_calendar/src/user_query.rs`, flattened into `GraphqlUser` |
+| A mutation with typed errors | `crates/graphql_calendar/src/mutation.rs` + `src/writes.rs` |
+| A field on a Soup entity backed by another domain | `pipelineEntries`: `crates/graphql_crm/src/loaders.rs` + `SoupCrmRecordEdges` in `crates/complete_graph/src/edges.rs` |
+| A filter or limit argument on an edge | `GraphqlNotificationFilter` in `crates/graphql_notification/src/query.rs` |
+| A subscription | `agentSessionLogAppended`: `crates/complete_graph/src/realtime.rs` |
+
+## 1. Design the shape
+
+- **`id: ID!` means global identity.** The client cache keys records by
+ `__typename:id` and merges equal keys everywhere. Name a field `id` only when it
+ identifies that object globally; reference ids get descriptive names
+ (`propertyDefinitionId`). Types without `id` are embedded in their parent. Never
+ add a constant or synthetic `id`; it merges every instance into one record.
+- **User-scoped data hangs off `user: GraphqlUser!`**, not new root fields.
+- **A field every Soup entity has** goes on the `GraphqlSoupEntity` interface and
+ its SDL contract test (`complete_graph/AGENTS.md` §3).
+- **Additive only.** Deployed web bundles and native apps keep sending their
+ existing documents, and the native cache rejects conflicting field shapes. New
+ arguments and input fields are nullable or defaulted (`Option<T>`). Don't rename,
+ remove, retype, or change the nullability of a field a shipped client selects.
+ Add the replacement, move clients, and remove the old field later. See step 8.
+- **Lists take `filter` and `limit` arguments, applied in the domain query before
+ the limit.** Unbounded edges made the web fetch whole notification histories to
+ draw unread dots; the fix added a server-side filter and a one-row limit.
+- **Document every type, field, and argument.** `#![deny(missing_docs)]` and the
+ `schema_types_and_fields_have_descriptions` test in
+ `crates/complete_graph/src/sdl_test.rs` both enforce it. Doc comments become
+ the SDL descriptions.
+
+## 2. The adapter crate (`crates/graphql_<domain>`)
+
+It is an inbound adapter: resolvers convert input, call the domain service, and
+map output. No SQL here ([CS-53](../../.agents/rules/rust/architecture.md)). If the
+domain operation doesn't exist, add it to the domain crate first.
+
+- **Services come from request data.** Define a context struct (for example
+ `CalendarGraphqlContext` in `src/reads.rs`) and read it with
+ `ctx.data::<CalendarGraphqlContext>()?`. Don't add another type parameter to
+ the schema; older adapters carry generics, but new ones don't.
+- **Authorize.** Use `require_authenticated_user` / `require_authorized_user` from
+ `crates/graphql_common/src/authorization.rs`. The viewer comes from the request
+ context, never an argument. Lookups must cover every access path (owned,
+ shared, team). A direct load that only queried owned email threads returned
+ `null` for shared ones. See the [security rules](../../.agents/rules/rust/security.md).
+- **Batch per-entity edges with a DataLoader.** A field resolved once per list row
+ goes through a keyed `Loader` (copy `crates/graphql_crm/src/loaders.rs`). Poll
+ hydration futures concurrently so the loader can batch them.
+- **Typed errors.** Set `extensions.code` with the crate's helper (copy `bad_input`
+ / `unavailable` in `crates/graphql_calendar/src/lib.rs`, or `mutation_error` in
+ `src/mutation.rs`). Log internal details and return a generic message. The web
+ reads codes with `thrownResultErrorHasCode` (`apps/web/src/lib/core/util/result.ts`).
+- **Never make a committed write look retryable.** The web's durable mutation
+ queue retries only transport failures and releases the queue on any GraphQL
+ error (`apps/web/src/lib/service-clients/service-storage/graphql-mutation-retry.ts`).
+ An archive mutation whose post-write reload found nothing once retried hundreds
+ of times and blocked every queued write behind it. If the write committed but
+ the reload is empty, return a terminal `NOT_FOUND`.
+- **Skip unknown variants instead of erroring.** An error on a non-null field
+ nulls its parents up to `user` and blanks the screen. Loaders that met an
+ unknown entity type used to fail the whole response; log and omit instead.
+- **Keep payloads off spans.** Use `#[tracing::instrument(skip_all, err(Debug))]` as
+ the calendar resolvers do ([observability rule](../../.agents/rules/observability.md)).
+- **Cross-domain fields on Soup entities.** `graphql_soup` can't depend on your
+ crate. Declare an associated type and constructor on `SoupEntityEdges`
+ (`crates/graphql_soup/src/objects.rs`), flatten it into the entity object
+ (`crates/graphql_soup/src/objects/crm_contact.rs`), and implement it in
+ `crates/complete_graph/src/edges.rs`. Every test implementation of
+ `SoupEntityEdges` also needs the new type: `crates/graphql_initiative/src/test.rs`,
+ `crates/graphql_favorite/src/mutations/test.rs`, and
+ `crates/graphql_entity_mutation/src/mutations/test.rs`.
+- **New crate?** Add it to `members` in the root `Cargo.toml` and as a dependency
+ of `complete_graph` and `document_storage_service`. Then run `cargo x deps` and
+ commit `crates/workspace-hack` and `.github/workspace-dep-closures.json`. Add an
+ `AGENTS.md` from `.agents/templates/`.
+
+## 3. Compose it in `crates/complete_graph/src/schema.rs`
+
+- **Query:** flatten onto `GraphqlUser`, like the calendar fields:
+ `#[graphql(flatten)] async fn calendar(&self) -> GraphqlCalendarQuery`.
+- **Mutation:** add your root to the `CompleteMutationRoot` tuple and to its `new()`.
+- **Subscription:** add a root to `CompleteSubscriptionRoot`. Put its source in
+ request data, as `realtime.rs` does, not in a schema type parameter.
+- **Tests:** execute operations through the composed schema in
+ `src/schema/test/<domain>.rs` (copy `calendar.rs`). Assert the new SDL lines in
+ `src/sdl_test.rs` (copy `calendar_reads_hang_off_the_authenticated_user`).
+
+## 4. Wire it into `document_storage_service` (required)
+
+1. Build the context in `src/server.rs`.
+2. Add a field to `ApiContext` in `src/api/context.rs`.
+3. `data.insert(...)` it in `insert_graphql_context_data` in
+ `src/api/graphql_soup.rs`. HTTP and websocket requests share this one function.
+
+Nothing checks this at compile time. A missing insert surfaces only when a client
+selects the field, as a "data does not exist" error. The `complete_graph` tests
+insert their own data, so they don't catch it.
+
+**Replica or primary.** Ordinary queries, lists, and subscription hydration read
+the replica (`readonly_db`). In production it lags 1–9 s. Mutation replies, and
+anything read right after a write (a just-created entity, a subscribe-then-query
+log), need a primary-backed loader. Copy `AgentSessionEntityLoader` in
+`crates/graphql_soup/src/loaders.rs` or `email_mutation_thread_loader` in
+`crates/graphql_soup/src/mutation_thread.rs`. A new agent session read from the
+replica came back `null` and the client reported "not accessible". Local stacks
+can't reproduce this because their replica URL is the primary, so decide
+deliberately.
+
+## 5. Regenerate the SDL (required)
+
+```sh
+SQLX_OFFLINE=true cargo run -p complete_graph --bin graphql_schema -- static_assets/schema.graphql
+```
+
+Commit `static_assets/schema.graphql`; never hand-edit it.
+`sdl_matches_committed_schema_graphql` fails when it is stale. The web bundle
+ships this file as the cache's runtime schema, so a frontend change that selects
+new fields needs the regenerated SDL in the same change.
+
+## 6. Web documents and codegen
+
+- Add or extend a document in
+ `apps/web/src/lib/service-clients/service-storage/graphql/<area>.graphql`, with a
+ unique operation name.
+- **Select `id` on every type that has one, and `__typename` on interfaces and
+ unions.** Otherwise the cache rejects the response ("every query fetching `X`
+ must select its key").
+- **If one selection has the same field name with different nullability on two
+ union members, alias it.** Codegen rejects the conflict; `soup.graphql` uses
+ `reminderDescription: description`.
+- **Soup list rows:** a field that rows render goes into the `SoupItemFields`
+ fragment in `soup.graphql` *and* into `mapGraphqlSoupItem` in
+ `apps/web/src/lib/service-clients/service-storage/graphql-soup.ts`. Reminders
+ once shipped with no `... on` selection, a mapper returning `null`, and a
+ dropped filter branch. Each failed silently, and the view was simply empty.
+ Data that only one view needs gets its own small document instead
+ (`home-unread.graphql`); keep the shared Soup document lean.
+- Regenerate. This writes `graphql/generated/graphql.ts` and
+ `apps/web/src/lib/graphql-cache/generated/entity-resolver-schema.ts`. CI does not diff
+ them, so commit both.
+
+ ```sh
+ cd apps/web && bun run gen-graphql
+ ```
+
+- Read through `createLiveQuery` from a query module, not from UI code. Copy
+ `apps/web/src/features/crm/queries/pipeline-entries.ts`. See
+ [FE-01 and FE-38](../../.agents/rules/web/data.md) and
+ [libraries](../../.agents/rules/web/libraries.md).
+
+## 7. Cache policy
+
+- **Every mutation document needs a policy** in
+ `apps/web/src/lib/queries/mutation-coverage.test.ts`: `resolver`, `custom: …`,
+ `authoritative: …`, or `inactive: …`. The test fails without one.
+- **`resolver`:** register one `optimisticResolver` per mutation *field* in
+ `apps/web/src/lib/queries/optimistic-resolvers.ts` (entity-generic ones go in
+ `entity-optimistic-resolvers.ts`). The representative document passes every field
+ argument as a same-named variable with the schema's exact type. A second
+ registration for the same field throws. Resolvers used to be keyed by document
+ text; now any document that selects the field gets the prediction. If one
+ shouldn't, list it in `declinedByResolver` and return `undefined` for it.
+- **Don't predict what the server decides:** assigned ids, permission outcomes,
+ undo targets. Those mutations are `authoritative`.
+- **Return the changed entity, with its `id`,** from every mutation so
+ normalization updates every view that shows it. Don't refetch lists.
+- **Optional:** if a query takes an id argument and returns a keyed entity, add an
+ `entityFromArgument` to `entityResolvers` in `graphql-soup.ts` so the cached
+ entity answers offline.
+- **Live updates.** Changes made elsewhere reach clients only through Soup
+ realtime patches. A field derived from another domain's data refreshes only if
+ that domain publishes an event that `crates/soup_realtime/src/inbound/kafka_consumer.rs`
+ maps to a patch. GitHub PR metadata missed this and needed a follow-up.
+- **Local filtering or search** on a new field also needs a projection in
+ `crates/soup_filter_cache_adapter`. That is native code and ships only with a
+ native release.
+
+## 8. Compatibility and rollout
+
+- Deploy the schema before a frontend that selects it. A DSS without the field
+ rejects the whole document.
+- Additive fields keep existing client caches. An incompatible change to identity
+ or field shape needs a bump of `CACHE_SCHEMA_COMPATIBILITY_EPOCH` in
+ `crates/client/cache-core/src/codec.rs` and a native release, because the
+ native cache retains old definitions and rejects conflicting ones (see
+ [`crates/client/README.md`](../../crates/client/README.md)). Prefer a new field.
+
+## Verify locally
+
+```sh
+cargo test -p graphql_<domain>
+cargo test -p complete_graph # SDL contract + schema tests; SQLX_OFFLINE unset
+SQLX_OFFLINE=true cargo check -p document_storage_service
+cd apps/web && bun run gen-graphql && bun run check
+cd apps/web && bunx vitest run src/lib/queries/mutation-coverage.test.ts
+```
+
+Then start the stack ([running locally](../development/running-locally.md)), run
+the operation in GraphiQL (`GET` on DSS `/items/soup/graphql`), and exercise the
+view in a browser. Use the `live-debug` skill for traces.
diff --git a/docs/guides/add-http-endpoint.md b/docs/guides/add-http-endpoint.md
new file mode 100644
index 0000000000..8af51bf52c
--- /dev/null
+++ b/docs/guides/add-http-endpoint.md
@@ -0,0 +1,209 @@
+# Adding an HTTP endpoint
+
+A REST endpoint on an existing service touches the domain crate, its router, the
+service's OpenAPI document, two generated clients, a hand-written web client, a
+query module, and the SDK. Each section below is one place, in order. The misses
+that needed follow-up fixes are called out inline.
+
+Scope: an endpoint on a service that already serves HTTP and already has a web
+client. For a new service, follow [new-service.md](new-service.md) §7 for the
+client plumbing. For an AI or MCP tool, use the
+[`create-ai-tool` skill](../../.agents/skills/create-ai-tool/SKILL.md).
+
+## Pick a model to copy
+
+| Building | Copy |
+| --- | --- |
+| Read one entity by id, access-checked | `get_github_pull_request_handler` in `crates/github_pull_requests/src/inbound/axum_router.rs` |
+| A new router in a domain crate: scoped CRUD, path and body types, mounted in DSS | `crates/channel_labels/src/inbound/axum_router.rs` and its wiring in `services/document_storage_service/src/` |
+| A compatible change to an existing endpoint (optional query param, new response field) | `services/notification_service/src/api/unsubscribe/unsubscribe_item.rs` |
+| Web query module for it | `apps/web/src/lib/queries/channel-labels/` (`keys.ts` + query/mutation file) |
+
+## 1. Domain service (required)
+
+- Add the operation to the service trait in `crates/<domain>/src/domain/ports.rs`,
+ implement it in `domain/service.rs`, and add any repository method to the
+ outbound adapter. Follow the
+ [hexagonal architecture skill](../../.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md):
+ handlers run no SQL (CS-53), domain imports no transport (CS-51/52).
+- Take the access receipt (`EntityAccessReceipt<ViewAccessLevel>` etc.) as the
+ argument, not a raw id plus a user id, so the domain can't be called without the
+ check. Report the caller's permission from that receipt; an initiative endpoint
+ shipped returning a placeholder `userAccessLevel` from the repository.
+- Return expected outcomes ("not linked", "not connected", "not found") as domain
+ results or typed error variants, not as a database error string-matched upward.
+ The GitHub link status endpoint answered "not linked" through the error path and
+ logged three ERROR lines per call across every `#[instrument(err)]` layer.
+- New queries: follow the [database guide](../development/database.md) and run
+ `nix develop --command just prepare_db` before step 6, which builds offline.
+
+## 2. Route and handler (required)
+
+Put the handler in the owning crate's `src/inbound/axum_router.rs`. Some older
+services (notification, auth) keep handlers in `services/<svc>/src/api/`; extend
+those in place, but new routers live in the crate.
+
+- **Authentication:** `MacroAuthorizationExtractor<Auth, Policy>` with the
+ narrowest policy in `crates/macro_authorization/src/inbound/axum/policy.rs`
+ (`UserOnly`, `UserOrInternal`, `InternalOnly`, `UserOrBot`, ...).
+- **Authorization: every route keyed by an entity id needs that entity's access
+ extractor** from `crates/entity_access/src/inbound/axum_extractors/`
+ (`DocumentAccessExtractor`, `ForeignEntityAccessLevelExtractor`,
+ `ChannelAccessLevelExtractor`, ...) at the right level (`ViewAccessLevel`,
+ `EditAccessLevel`, `OwnerAccessLevel`, team roles). A DSS job-results route
+ shipped authenticated but without any access check; team bot and channel label
+ routes shipped with a level that was too loose and were tightened later. Decide
+ owner-only vs editor operations explicitly.
+- **Middleware the extractor depends on:** `DocumentAccessExtractor` and handlers
+ that read `Extension<DocumentBasic>` need `ensure_document_exists_middleware` on
+ that route. Without it every request is a 500; eight DSS internal routes were
+ dead this way. Layer it like `services/document_storage_service/src/api/documents.rs`.
+- Shared services come in through `State`, never `Extension` (CS-30).
+- Paths use axum 0.8 syntax: `/{id}`.
+- **Status codes:** implement `IntoResponse` for the domain error in the inbound
+ module (copy `impl IntoResponse for GithubPullRequestError` in the same router
+ file). Map client and expected states to 4xx: missing entity 404, no grant 401/403, "not connected"
+ 409. A missing Cursor key mapped to 502 made up 95% of a service's prod 5xx.
+ Distinguish "doesn't exist (yet)" from "refused": a read racing its own create
+ was reported to users as permanent no-access. Don't echo internal error text in
+ 500 bodies.
+- `#[tracing::instrument(err, skip_all)]` on the handler; spans and log levels
+ follow the [observability rule](../../.agents/rules/observability.md) and CS-22
+ in [rust/code.md](../../.agents/rules/rust/code.md). Expected 4xx outcomes are
+ not ERROR logs.
+- Never put a secret in the path (it lands in access logs and traces); key routes
+ on the record's id.
+
+## 3. Mount the router (only for a new router)
+
+Adding a route to an existing router needs nothing here. For a new router in DSS,
+copy `channel_labels`:
+
+- `services/document_storage_service/src/api/context.rs`: type aliases for the
+ service and router state, and a field on the context.
+- `services/document_storage_service/src/server.rs`: construct the state.
+- `services/document_storage_service/src/api.rs`: `.nest("/<prefix>", ...)` inside
+ `dss_router`.
+- If the service now depends on a crate it didn't before, add it to the service's
+ `Cargo.toml` and run `cargo x deps` (`just hakari`); commit
+ `crates/workspace-hack` and `.github/workspace-dep-closures.json`.
+
+## 4. OpenAPI registration (required)
+
+- Annotate the handler with `#[utoipa::path]`: method, `tag`, a unique
+ `operation_id` (it becomes the generated function name), `path`, `params`,
+ `request_body`, and every status the handler can return with
+ `body = ErrorResponse` for errors.
+- **`path` is the route as the service serves it, nest prefix included, without
+ the gateway prefix** (`/github_pull_requests/{id}`, not
+ `/dss/github_pull_requests/{id}`). Clients carry the gateway prefix in their base
+ URL. Calendar once baked `/calendar` into its annotations and the SDK had to
+ strip it; that was reverted to root-relative.
+- Path and query structs derive `IntoParams` (with
+ `#[into_params(parameter_in = Path)]` for path params); bodies and responses
+ derive `ToSchema`.
+- **Register the handler** in the service's `#[openapi(paths(...))]` list and its
+ types in `components(schemas(...))`, in `services/<svc>/src/api/swagger.rs`
+ (properties: `crates/properties_service/src/api/swagger.rs`). An unregistered
+ handler serves traffic but never reaches any client. A domain crate was once merged with
+ its routes unwired and needed a second PR to mount and register them.
+- Schema names are global per spec. Give types domain-specific names (or
+ `#[schema(as = ...)]`) so two `ListResponse`s don't collide.
+
+## 5. Wire shape (required)
+
+- Derive `Serialize`/`Deserialize`/`ToSchema` on the domain type itself; add a
+ separate wire type only when the shape genuinely differs (CS-69).
+- Match the casing of sibling endpoints (`#[serde(rename_all = "camelCase")]` in
+ newer DSS routers, snake_case in notification). Sibling endpoints on a resource
+ share one DTO shape (CS-35), and new models mirror their existing counterpart
+ (CS-32).
+- Closed string sets are enums (CS-11); optional is `Option<T>` (CS-12), which
+ the generated types render as `field?: T | null`; handle both absent and `null`.
+- Timestamps are `chrono::DateTime<Utc>`, not `String`, so the spec says
+ `format: date-time`.
+- IDs that can exceed 2^53 (GitHub ids are `u64`) lose precision as JS numbers;
+ serialize them as strings in responses the web reads.
+- **Deployed clients outlive your PR.** Web, the iOS app, the SDK, MCP clients,
+ and other services run older code against the new server, and web can ship
+ before the backend. Add fields and params as optional; keep accepting old values
+ (`unsubscribe_item.rs` still accepts `"email"` and `"thread"` item types); never
+ rename or remove a field, path, or status in place. Removing an endpoint comes
+ after every caller is gone. Migrations follow the
+ [compatible migrations rules](../development/database.md#compatible-migrations).
+
+## 6. Regenerate clients (required)
+
+From `apps/web`:
+
+```sh
+bun run gen-api <service> # e.g. cloud-storage, notification-service, agent-harness
+```
+
+Names come from `apps/web/scripts/services.ts`. This builds
+`<crate>_openapi` with `SQLX_OFFLINE=true`, writes
+`apps/web/src/lib/service-clients/service-<name>/openapi.json`, and reruns orval
+into `generated/`. Then from `packages/sdk`:
+
+```sh
+bun run sync-specs && bun run generate
+```
+
+`just update-generated` in `packages/sdk` does both steps, for every service.
+
+- Commit `openapi.json`, `generated/`, `packages/sdk/specs/`, and
+ `packages/sdk/generated/`. The *Generated Code Check* job in
+ `.github/workflows/web-app-check-main.yml` reruns both and fails on any diff.
+- Never hand-edit `generated/`, `openapi.json`, or the SDK specs. Fix the Rust
+ annotation and regenerate.
+
+## 7. Web client and query (required if the web app calls it)
+
+- Add a method to `apps/web/src/lib/service-clients/service-<name>/client.ts`,
+ typed with the generated schema types (`./generated/schemas/<type>`). DSS calls
+ go through `dssFetch`, other services through `fetchWithToken` with their
+ `SERVER_HOSTS` entry. The orval-generated `client.ts` functions are not used by
+ the app; don't build URLs from another service's host (calendar calls built on
+ the email host 404'd when routes moved).
+- Wrap it in a query or mutation under `apps/web/src/lib/queries/<area>/` (or the
+ feature's `queries/` directory) with a `keys.ts`. UI never imports a service
+ client (FE-01, enforced by ast-grep). Follow the
+ [data rule](../../.agents/rules/web/data.md) for query factories, `enabled`,
+ cache seeding, and Suspense boundaries.
+- Optimistic mutations that mint ids client-side must survive an older backend
+ that ignores the id: reconcile with the id the server returns.
+
+## 8. SDK (required)
+
+Wrap the endpoint or record it as skipped with the
+[`add-sdk-endpoint` skill](../../.agents/skills/add-sdk-endpoint/SKILL.md).
+`.github/workflows/sdk-check.yml` runs `bun run coverage` and fails on an
+uncovered endpoint.
+
+## 9. Other callers (optional)
+
+- **Other Rust services:** extend the hand-written client crate
+ (`crates/document_storage_service_client`, `crates/email_service_client`, ...)
+ and gate the route with `InternalOnly`/`UserOrInternal`.
+- **New top-level path on a gateway service:** a path outside the service's
+ existing prefix isn't routed until its gateway path patterns cover it (see
+ `infra/packages/shared/src/gateway_priorities.ts` and the service's stack).
+ Prefer staying under the existing prefix.
+- **User-visible behavior:** update the matching page in
+ [docs/agent-guide](../agent-guide/README.md).
+
+## Verify locally
+
+```sh
+cargo test -p <domain crate> # SQLX_OFFLINE unset
+just rust-check && just clippy
+(cd apps/web && bun run gen-api <service> --check)
+(cd packages/sdk && just coverage)
+just check
+```
+
+Run the stack ([running locally](../development/running-locally.md)) and call the
+route through the proxy, for example
+`curl https://localhost:8090/dss/<path>` with a token, once with access and once
+without. Confirm the denied call is a 4xx, not a 500. Exercise the UI that uses it,
+and find the request's trace with the `live-debug` skill.
diff --git a/docs/guides/add-kafka-event.md b/docs/guides/add-kafka-event.md
new file mode 100644
index 0000000000..b210918b23
--- /dev/null
+++ b/docs/guides/add-kafka-event.md
@@ -0,0 +1,225 @@
+# Adding a Kafka event
+
+An event touches more than its producer: the topic registry, every composition
+root that builds the producing service, and every consumer already subscribed to
+the topic. Several of those consumers drop what they don't recognize without
+failing, so a missed step looks like a healthy publish and no effect. Each
+section below is one place, in order; past misses are called out inline.
+
+> **Agents never deploy.** Topic creation in MSK happens when the
+> `kafka-cluster` stack deploys. See the
+> [infrastructure guide](../development/infrastructure.md).
+
+## Pick a model to copy
+
+| Adding | Copy | Why |
+| --- | --- | --- |
+| A topic | The `macro.messages` registration: `crates/macro_event_topics/src/lib.rs`, its `test.rs`, `.github/kafka-cluster-topics.json` | Three files, shipped as its own PR ahead of the producer |
+| Events on a topic | `crates/github_pull_requests/src/broker.rs` (one variant), `crates/messages/src/outbound/broker.rs` (several) | Topic enum, keyed envelope, broker-backed adapter for a domain port |
+| A durable consumer | `crates/crm/src/inbound/call_archived.rs` | Smallest grouped consumer: poison commit, bounded retry, commit after work, cancel-safe |
+| An at-least-once consumer that must not skip | `crates/webhook/src/inbound/kafka_consumer.rs` | Transient vs permanent errors; exits uncommitted so a restart redelivers |
+| A per-process fan-out (GraphQL subscription, SSE) | `crates/agent_session_realtime/src/outbound/log_topic_consumer.rs` | Ungrouped, starts at `Latest`, commits nothing |
+
+Background: `crates/macro_event_broker/AGENTS.md` maps the broker crate;
+`crates/properties/README.md` ("Delivery semantics and compatibility") states the
+delivery contract every producer has.
+
+## 1. Register the topic (new topics only)
+
+Add a variant to an existing topic when the event is about the same entity as
+the topic's other events; add a topic only for a new entity stream.
+
+- Add `MacroXTopic => "macro.<snake_plural>"` with a doc comment to `topics!` in
+ `crates/macro_event_topics/src/lib.rs`, and an assertion to
+ `all_topic_names_includes_declared_topics` in `src/test.rs`.
+- Run `cargo x kafka-topics` and commit `.github/kafka-cluster-topics.json`. Never
+ hand-edit it. CI (`check_generated`) fails when it is stale, and the
+ `kafka-cluster` stack creates MSK topics only from this file.
+- Ship the registration as its own PR, merged before the producer. A producer
+ that starts before its topic exists loses events: publication is
+ fire-and-forget and the request still succeeds.
+- Locally the broker auto-creates unknown topics with **one** partition, so a
+ missing registration still "works" on your machine. Don't treat a local
+ publish as proof the topic is registered.
+
+## 2. Define the event (producing crate)
+
+Put the types next to the domain that owns the fact
+(`src/domain/events.rs` or `src/broker.rs`):
+
+- A topic enum with `#[serde(tag = "event_type", content = "metadata")]` and
+ `#[serde(rename = "<entity>.<past_tense>")]` per variant, implementing
+ `TopicEvent { type Topic; const SCHEMA_VERSION: u8 }`.
+- A `XMacroEvent { key, event: Event<XTopicEvent> }` implementing `MacroEvent`,
+ with one constructor per variant. Build envelopes with `Event::new` (UUIDv7
+ `event_id`).
+- **The key is the ordering unit.** Kafka orders per partition, so key by the
+ entity whose events must stay ordered: the thread root for messages, the
+ session for agent sessions, the lowercased PR key for pull requests. Every
+ variant on a topic must use the same keying.
+- Metadata carries ids and the committed state consumers need; consumers should
+ not have to read back the database to act. Never put secrets or header values
+ in metadata (see the webhook README's management events).
+- Domain crates depend on `macro_event_broker` with `default-features = false`.
+ Only composition roots pull in the Kafka adapters; event types consumed by the
+ self-hosted daemon once dragged `rdkafka` into its build.
+
+## 3. Publish after the commit
+
+- Define a publisher port in the domain and implement it in an adapter over
+ `MacroEventBroker` (`GithubPullRequestEventPublisher` +
+ `BrokerGithubPullRequestPublisher`, `MessageEventPublisher` +
+ `BrokerMessagePublisher`). Small domains such as `crates/forms` take
+ `B: MacroEventBroker` directly; either keeps Kafka types out of
+ `src/domain/**` ([CS-51](../../.agents/rules/rust/architecture.md)).
+- Publish only after the transaction commits, from committed state (see
+ `PropertiesServiceImpl` building update events "from committed persistence
+ state"). A publish inside the transaction announces changes that may roll back.
+- A failed publish is logged, never surfaced: the change already committed.
+ There is no outbox; delivery is at most once relative to the write.
+- Tests: a recording `MacroEventBroker` that captures topic, key, and
+ `serde_json::to_value(event.event())`, asserting the full JSON literal
+ (`crates/messages/src/outbound/broker/test.rs`). That literal is the wire
+ contract.
+
+## 4. Wire a real broker into every composition root
+
+Services default their broker generic to `NoopMacroEventBroker`, so a composition
+that forgets it compiles and silently publishes nothing.
+
+- Find every place the producing service is constructed: its service binaries,
+ `crates/ai_tools/src/tool_context.rs` (AI tools and MCP; use
+ `MaybeToolEventBroker`), and any other host. A write path left on the no-op
+ broker is a write that never produces an event.
+- Build the broker as `MacroEventBrokerService::new(KafkaEventPublisher::new(..)?,
+ tracker)` with a `TaskTracker`, and on shutdown close the tracker and wait with
+ a timeout so in-flight publishes drain. Copy `services/calendar_service/src/main.rs`
+ (`EVENT_BROKER_DRAIN_TIMEOUT`).
+- A host that has never published needs `KAFKA_BROKERS` config and Kafka IAM; see
+ [new-service.md](new-service.md) sections 3 and 4.
+
+## 5. Teach every existing consumer of the topic
+
+Consumers decode with the same Rust enum, so a new variant compiles everywhere;
+what each one *does* with it is decided by its match. List them:
+
+```sh
+rg -l 'declare_topics!' crates services | xargs rg -l '<XMacroEvent>'
+```
+
+| Consumer | What to add | Silent-drop behavior if you don't |
+| --- | --- | --- |
+| Webhook ingestion and SSE, `crates/webhook/src/domain/ingestion.rs` + `ingestion/stream.rs`, topic list in `crates/webhook/src/topics.rs` | A normalization arm and audience, a case in `ingestion/test.rs`, a row in the README event table | An agent-trigger shape with no arm is rejected as `InvalidEntityId` ("unrecognized agent-trigger event shape") and committed; the error is logged in DSS, not by the producer, so the producer looks healthy while nothing reaches the daemon |
+| Realtime Soup, `crates/soup_realtime/src/inbound/kafka_consumer.rs` | Patches for every Soup item the event changes, including items reached through the event (entities shared into a channel) | No patch means no realtime update; the channel-shared case was missed once |
+| Activity, `services/document_storage_service/src/service/activity.rs` and the owning domain's activity mapping | Map the variant to an activity row | No activity entry |
+| Search, `services/search_processing_service/src/inbound/kafka_consumer.rs` | Index or delete | Stale search results |
+| Routines and scheduled actions, `services/scheduled_action/src/inbound/kafka_consumer.rs` | Trigger filter support | Routine never fires |
+| Agent triggers, `crates/agent_trigger/src/domain/sources.rs` | Trigger input, when the event should start an agent | No agent session |
+
+Adding a **new topic** to an existing consumer means adding its `XMacroEvent` to
+that consumer's `declare_topics!` list. The group then reads a partition it has
+never committed on: with the default `InitialOffset::Earliest` it replays the
+topic's full 7-day retention. Every group that took on `macro.messages` had to be
+switched to `INITIAL_OFFSET = InitialOffset::Latest` for this reason; set it
+deliberately when you extend a subscription.
+
+## 6. Add a consumer (optional)
+
+A consumer is an inbound adapter: decode, call a domain service, commit. No SQL in
+it ([CS-53](../../.agents/rules/rust/architecture.md)).
+
+- **Grouped or ungrouped.** Durable work (indexing, linking, delivery) uses a
+ group: a marker type implementing `kafka_util::GroupName` with a stable
+ kebab-case `GROUP_NAME` and a deliberate `INITIAL_OFFSET`. Per-process fan-out
+ to connected clients (GraphQL subscriptions, SSE) uses `Ungrouped` at
+ `InitialOffset::Latest` and commits nothing; clients that miss events refetch.
+- **Group names are identities.** Renaming one starts from scratch (replay or
+ skip, depending on `INITIAL_OFFSET`). Two binaries that share a group split
+ the partitions, so each sees only part of the stream. Locally, a grouped consumer pointed at dev
+ Kafka takes partitions from the deployed consumers; keep such workers off dev
+ infrastructure (see [new-service.md](new-service.md) section 6).
+- **Decode failures.** `decode_payload` fails for unknown topics, malformed
+ JSON, unknown variants, and `UnsupportedSchemaVersion`. Log and commit them so
+ one bad record cannot wedge a partition.
+- **Commit after the work, never before.** Retry transient failures in process
+ with bounded exponential backoff (`tokio_retry`), keeping the worst case well
+ under librdkafka's 300 s `max.poll.interval.ms`. Then either commit (success or
+ logged terminal failure) or return an error without committing so the
+ supervisor restarts and Kafka redelivers. Commits are cumulative: committing a
+ later offset skips an earlier failed one, so a consumer that wants to hold a
+ record must stop or call `pause_message_partition`. Realtime Soup first left
+ failed records uncommitted for a restart to redeliver; it was rewritten to
+ retry with backoff and then commit, so one failing fan-out cannot stall the
+ partition.
+- **Idempotency.** Delivery is at least once and replays happen after
+ cancellation. Make handlers insert-if-absent or full-state, or dedupe on
+ `event_id`.
+- **Cancellation.** Select on the shutdown future around both `recv` and the
+ work; leave an interrupted event uncommitted.
+- **Tracing.** Wrap decode, handling, and commit in
+ `kafka_util::consumer_span(message, GROUP_NAME)` so the consumer joins the
+ producer's trace (producers inject trace headers automatically), and record
+ failures with `record_span_error`. See the
+ [observability rule](../../.agents/rules/observability.md).
+- **Spawn it.** A consumer that is built but never spawned was shipped once.
+ Run it in the host's `consumer_tracker` with a restart loop, a delay between
+ restarts, and the shared cancellation token; copy the CRM call-link block in
+ `services/document_storage_service/src/server.rs`. A brand-new consumer
+ service follows [new-service.md](new-service.md), using
+ `services/agent_trigger_service` as the model.
+
+## 7. Change an existing payload safely
+
+Producers and consumers deploy separately, and topics retain 7 days, so every
+payload change must be readable by both the deployed code and the new code.
+
+- **Additive only.** A new field is `Option<_>` with `#[serde(default)]`
+ (`previous_value` on property update events), or it fails to decode every
+ retained message published before it. A new variant is fine for consumers
+ already on the new code; consumers still on old code fail to decode it and
+ commit it as poison, so deploy consumers that must act on it first.
+- **Never rename or remove** a field, variant, or `event_type` string in place.
+ Add the new one, migrate consumers, then remove the old one in a later PR.
+- **`SCHEMA_VERSION` bumps are breaking.** `declare_topics!` rejects any version
+ other than the consumer's compiled one, in both directions. Additive changes
+ do not bump it.
+
+## 8. Public contract (webhook-delivered topics only)
+
+Variants on `macro.documents`, `macro.channels`, `macro.messages`, and
+`macro.agent_session_lifecycle` reach customers through `WebhookEvent`
+(`crates/webhook/src/domain/events.rs`), which is part of the storage OpenAPI spec.
+
+- Derive `utoipa::ToSchema` on the new metadata under the crate's `schema` or
+ `inbound` feature, like `MessageTopicEvent`.
+- Regenerate: `bun run gen-api cloud-storage` in `apps/web`, then
+ `just update-generated` in `packages/sdk`. Commit both generated trees.
+- Hydrate it in the SDK (`packages/sdk/src/events/hydrate/`, routed from
+ `src/events/receiver.ts`); see the
+ [add-sdk-endpoint skill](../../.agents/skills/add-sdk-endpoint/SKILL.md) for
+ SDK conventions.
+
+## Verify locally
+
+```sh
+cargo x kafka-topics --check
+cargo test -p macro_event_topics -p <producer> -p <each consumer you touched> # SQLX_OFFLINE unset
+just rust-check && just clippy
+just run_local
+```
+
+A restored init snapshot does not include a topic added since it was taken
+(snapshots are not keyed on topics), so create it on the running broker. Find the
+container with `docker ps --filter name=kafka`:
+
+```sh
+docker exec <kafka-container> /opt/kafka/bin/kafka-topics.sh --bootstrap-server kafka:29092 \
+ --create --if-not-exists --topic macro.<name> --partitions 6
+docker exec <kafka-container> /opt/kafka/bin/kafka-console-consumer.sh --bootstrap-server kafka:29092 \
+ --topic macro.<name> --from-beginning
+```
+
+Trigger the write in the app, confirm the envelope shape and key on the console
+consumer, then confirm each consumer from section 5 acted (webhook delivery,
+realtime update, activity row). Find the producer-to-consumer trace in Tempo with
+the `live-debug` skill.
diff --git a/docs/guides/add-notification-kind.md b/docs/guides/add-notification-kind.md
new file mode 100644
index 0000000000..e166e19b7e
--- /dev/null
+++ b/docs/guides/add-notification-kind.md
@@ -0,0 +1,271 @@
+# Adding a notification kind
+
+A notification kind is one `NotifEvent` variant. It is stored as a tagged JSON row,
+pushed to phones, streamed to clients, served over REST and GraphQL, and rendered
+by a dozen web modules. The compiler finds the Rust half; TypeScript finds most of
+the web half; the rest is listed here. Most past kinds needed a follow-up fix, and
+those misses are called out inline.
+
+If the notification is about an entity type that has never carried notifications
+(it has no inbox rows, mark-done, or mute yet), do that first with
+[add-entity.md](add-entity.md); this guide assumes the entity side exists.
+
+## Pick a model to copy
+
+| Building | Copy | Why |
+| --- | --- | --- |
+| A kind on an existing entity, sent from a domain service | `ChannelMessageReaction` (`crates/channels/src/outbound/notification_sender.rs`) | Newest end-to-end kind: push, realtime, GraphQL, inbox stacking, settings toggle |
+| Kinds planned from domain events, with derived ids | `AgentSession*` (`crates/agent_harness/src/domain/notifications.rs`) | Pure planner function, audience rules, idempotent ids, port + ingress adapter |
+| A scheduled kind | `CalendarEventReminder` (`crates/calendar_events/src/outbound/notification_notifier.rs`) | Fired by a poller, collapse key per occurrence |
+
+Names: the variant is `PascalCase`; `Notification::TYPE_NAME`, the serde tag, the
+`notification_event_type` column, and the web `tag` are all its `snake_case`
+(`channel_message_reaction`). Pick it once. A rename later needs a serde alias
+*and* a data migration (see "Renaming" below).
+
+## 1. Metadata type (required)
+
+In `crates/model_notifications/src/metadata.rs` (or a submodule like
+`metadata/crm_discussion.rs`):
+
+- Define `<Name>Metadata` with `#[derive(Serialize, Deserialize, Debug, Clone, ToSchema)]`
+ and `#[serde(rename_all = "camelCase")]`. Doc every field; utoipa and GraphQL
+ descriptions come from them.
+- Carry what clients need to render and navigate without another fetch (ids, a
+ short content excerpt, display names). Do not carry anything you would not put
+ in a push banner; the payload lands in the database, on phones, and in Kafka.
+- Display names: carry a display name when the actor is not a Macro user (a bot,
+ a GitHub login, an agent). Kinds that only carried an id later showed raw ids or
+ emails in the inbox and needed fixes for bot and agent senders.
+- Every field added *after* the first deploy must be `Option` or
+ `#[serde(default)]`: rows already in the `notification` table lack it, and a row
+ that fails to decode silently disappears from lists.
+- `impl Notification` with `const TYPE_NAME = "<snake_name>"`.
+- `impl NotificationTitle` (`format_title` / `format_body`). This text is the push
+ banner, the Android notification, and the email digest preview. Branch on
+ subtype where it changes the noun (a document mention of a task says "task";
+ that was a fix). Render mention XML through the existing
+ `parse_message_plain_text` helpers so bot and user mentions show their names.
+- Push-capable kinds: `impl NotificationExtIos`. Build the alert with
+ `alert_apns`, and choose `collapse_key` deliberately. It replaces an earlier
+ banner on the device and is also the Android identifier, so key it on what a
+ newer notification should supersede (the reaction keys on message + emoji, a
+ reminder on its reminder id). Android pushes are derived from the APNS payload
+ in `crates/notification/src/domain/service/egress.rs`; there is no separate
+ Android formatter.
+- Add title/body tests to `crates/model_notifications/src/metadata/test.rs`.
+
+Only invite-style kinds send direct email (`NotificationExtEmail`, see
+`crates/invite_email`). Everything else reaches email through the digest, which
+formats any `NotifEvent` via `NotificationTitle`.
+
+## 2. Register the variant (required)
+
+In `crates/model_notifications/src/lib.rs`:
+
+- Re-export the type from the `pub use metadata::{...}` list.
+- Add the variant **at the end** of `NotifEvent` inside `define_notif_event!`. The
+ macro fails the build if `TYPE_NAME` is not the variant's `snake_case`. Order
+ matters for generated code: orval names union members by position
+ (`notifEventOneOfFivefive`), so inserting in the middle renames dozens of
+ generated web files.
+- Add arms to both `format_title` and `format_body` in `impl NotificationTitle for NotifEvent`.
+
+Then decide two lists in other crates; nothing will force you to:
+
+- **Blockable:** add `<Name>Metadata::TYPE_NAME` to `BLOCKABLE_NOTIFICATIONS` in
+ `services/notification_service/src/api/user_notification.rs` unless users must
+ not be able to turn it off (account-security kinds like `inbox_reauth_required`
+ stay out). The preferences endpoint rejects disabling any type not listed.
+- **Category filter:** check `push_include_types_filter` in
+ `crates/notification/src/outbound/repository.rs`. Categories mostly match on
+ `event_item_type`, and `Message` also matches any metadata with a `messageId`.
+ A new kind filed under an existing entity type joins that category, which leaked
+ agent rows into the channel filter once. GitHub kinds are a hand-kept list
+ (`GITHUB_EVENT_TYPES_SQL`) because this crate cannot see `model_notifications`.
+
+Add a `to_typed_row_<snake_name>` case to
+`services/notification_service/src/api/user_notification/test.rs`.
+
+## 3. Send it from the owning domain (required)
+
+Follow the [hexagonal architecture skill](../../.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md):
+the domain decides *whether* and *to whom*; an outbound adapter calls
+`NotificationIngress::send_notification`.
+
+1. **Plan in the domain.** A pure function from the domain fact to the
+ notifications it warrants, with tests for every audience rule. Copy
+ `crates/agent_harness/src/domain/notifications.rs`.
+2. **Port + adapter.** A domain port (e.g. `AgentSessionNotifier`) and an outbound
+ adapter generic over `notification::domain::service::NotificationIngress`
+ (`crates/agent_harness/src/outbound/notifications.rs`). Build the request with
+ `SendNotificationRequestBuilder { notification_entity, secondary_notification_entity, notification, sender_id, recipient_ids }`,
+ then `.into_request()`, `.with_apns()` for a push, and `.with_conn_gateway()`
+ for live delivery.
+3. **Wire the composition root.** Services construct
+ `SqsNotificationIngress { queue: SqsQueue::new(sqs, macro_queues::NotificationIngressQueue::new().to_string()) }`
+ (see `services/agent_harness_service/src/main.rs`). A service that has never
+ notified also needs `sqs:SendMessage` on the ingress queue: take
+ `notificationIngressQueueArn` from `getMacroNotify()`
+ (`infra/packages/shared/src/macro_notify.ts`), as `infra/stacks/email-service/index.ts` does.
+
+Pitfalls, each of which shipped once:
+
+- **Sender.** Set `sender_id` to the acting Macro user; ingress then drops the
+ sender from recipients. When the actor is not a Macro user id (GitHub, bots),
+ filter the actor out yourself; users were notified of their own PR activity.
+- **Audience.** Recipients must be people who can open the entity, computed from
+ live data. Participants from deleted messages, and the callee instead of the
+ caller in DM call titles, were both fixes.
+- **Double notifying.** If another path already notifies the same people about
+ the same thing (a channel message mentioning them), emit nothing. Agent mention
+ notifications duplicated channel mention notifications until fixed.
+- **No-op changes.** Gate on whether the state actually changed. An
+ `ON CONFLICT DO NOTHING` re-add of a reaction still published "added" and
+ re-notified.
+- **Idempotent ids.** For event-driven producers, use `into_request_with_id` with a
+ UUIDv5 derived from everything that makes two notifications distinct; ingress
+ creates idempotently on the id. Leaving out a component (the question within a
+ turn) silently swallows the second notification. Ingress also returns early for
+ an existing id, so retrying a send whose row was written does not re-push.
+- **Failure handling.** A failed enqueue is logged and dropped, not retried into
+ the caller's transaction (see the adapter's doc comment).
+
+Push banners are rendered in the **producing** service (ingress messages carry the
+built APNS payload), so a `format_title` change only reaches phones once that
+producer redeploys.
+
+## 4. GraphQL (required)
+
+In `crates/graphql_notification/src/notification_event.rs`:
+
+- A wrapper `pub struct Graphql<Name>Metadata(<Name>Metadata);` with an
+ `#[Object]` impl exposing each field (ids as `ID`).
+- A variant in the `GraphqlNotifEvent` union and an arm in
+ `From<NotifEvent> for GraphqlNotifEvent`.
+
+Regenerate the SDL and the web client (see `crates/complete_graph/AGENTS.md`):
+
+```sh
+cargo run -p complete_graph --bin graphql_schema -- static_assets/schema.graphql
+cd apps/web && bun gen-graphql
+```
+
+Any SDL change rotates every persisted client GraphQL cache; that is expected.
+
+## 5. REST spec and generated clients (required)
+
+`NotifEvent` is registered in `services/notification_service/src/api/swagger.rs`,
+so new metadata types are pulled in transitively; listing them there is optional.
+Regenerate and commit:
+
+```sh
+cd apps/web && bun run gen-api notification-service # openapi.json, schemas, zod.ts
+cd packages/sdk && bun run sync-specs && bun run generate
+```
+
+The web validates realtime notifications with the generated `zod.ts`; a stale one
+logs parse warnings for the new kind. Never hand-edit `generated/` or `specs/`.
+
+## 6. Web (required for anything user-visible)
+
+The GraphQL union is mapped back to the REST `NotifEvent` shape, and every web
+consumer matches on `notification_metadata.tag`.
+
+1. `apps/web/src/lib/service-clients/service-storage/graphql/soup.graphql`: add
+ `... on Graphql<Name>Metadata` to `SoupNotificationNavigationMetadataFields`
+ (fields needed to route a click) or `SoupNotificationMetadataFields`. Alias
+ every field with a variant prefix (`channelMessageReactionMessageId: messageId`);
+ union members share field names with different types, which GraphQL rejects
+ unaliased. Rerun `bun gen-graphql`.
+2. `apps/web/src/lib/service-clients/service-storage/graphql-soup.ts`: an arm in
+ `mapGraphqlNotificationMetadata` ending in `satisfies NotifEventMember<'<snake_name>'>`.
+ Every GraphQL notification must go through `mapGraphqlNotification`; a past bug
+ bypassed it.
+3. Exhaustive matches, which type-check will flag:
+ - `apps/web/src/features/notifications/notification-preview.ts` (label)
+ - `apps/web/src/features/notifications/notification-metadata.ts` (action text, target)
+ - `apps/web/src/features/notifications/notification-navigation.ts` (click target)
+ - `apps/web/src/features/entity/extractors-notification/notification-icon.tsx`
+ - `apps/web/src/features/entity/extractors-notification/notification-description-helpers.ts`
+ - `apps/web/src/features/entity/utils/notification.ts`
+4. Non-exhaustive matches that silently fall through; check each:
+ - `apps/web/src/features/notifications/use-notification-updates.ts`: refresh
+ only the affected Soup entity. Broad invalidation here caused list refresh
+ storms.
+ - `apps/web/src/features/notifications/notification-stacking.ts` and
+ `apps/web/src/features/notifications/notification-source.ts` (`CHANNEL_EVENT_TYPES`)
+ - Channel-thread scoping: `apps/web/src/features/notifications/channel-thread-root.ts`,
+ `apps/web/src/features/notifications/top-level-channel-notification.ts`,
+ `apps/web/src/features/soup/entity-notifications.ts`, and
+ `apps/web/src/features/entity/utils/channel-thread-name.ts`. Reactions
+ initially vanished from thread rows because one helper did not know the tag.
+ - Inbox: `apps/web/src/features/next-soup/soup-view/views/inbox/inbox-card-layouts.tsx`
+ and `apps/web/src/features/next-soup/soup-view/views/inbox/utils.ts`.
+ - Desktop banners: `apps/web/src/features/notifications/notification-platform.ts`
+ and `apps/web/src/features/notifications/notification-sender.ts` when the
+ sender is not `sender_id`.
+5. Settings: if blockable, add an entry to `NOTIFICATION_EVENT_GROUPS` in
+ `apps/web/src/features/notifications/notification-event-catalog.ts`. It must
+ match `BLOCKABLE_NOTIFICATIONS`; no test checks that.
+6. Mobile push taps carry only the notification id; the app loads the
+ notification and routes through `notification-navigation.ts`, so step 3 covers
+ phones too.
+
+Mark done and mute act on the notification's entity, so an existing entity type
+needs nothing more. Copy `.otherwise` arms rather than throwing: older tabs ignore
+kinds introduced by a newer backend.
+
+## 7. Server-built feeds (when relevant)
+
+- **Home work feed:** `crates/work_feed/src/domain/stacking.rs` attributes channel
+ notifications to thread roots and stacks comment events. A new kind defaults to
+ a standalone stack (`_ => None`); add it to the thread-root and
+ `is_channel_event` / `is_comment_event` matches if it belongs to a conversation.
+- **Channel unread scoping:** channel thread SQL in
+ `crates/notification/src/outbound/entity_notifications.rs` lists event types by
+ name. Add a channel-scoped kind there, with tests beside it.
+
+## 8. Docs
+
+Update the [app agent guide](../agent-guide/README.md) page for the surface where
+the notification appears (`channels.md`, `home.md`, `notifications.md`, ...).
+
+## Compatibility and observability
+
+- **Deploy order.** Readers skip rows they can't decode: REST lists and the digest
+ drop them with a warning, and the web ignores unknown tags. A single
+ `GET` by id errors, and the document storage service's realtime consumer
+ rejects unknown kinds. Ship the variant in the same change as its producer, and
+ don't let a separately released producer emit before `notification_service` and
+ `document_storage_service` are deployed.
+- **Renaming.** Keep the old tag readable with `#[serde(alias = "<old>")]` on the
+ variant and a migration rewriting `notification.notification_event_type` and
+ `user_notification_type_preference.notification_event_type`. Copy
+ `crates/macro_db_client/migrations/20260618152324_rename_call_started_notification_type.sql`
+ (generate the file with `sqlx migrate add`; see the
+ [database guide](../development/database.md)).
+- **Privacy.** Never put notification payloads on spans or in logs. Use
+ `#[tracing::instrument(skip_all, fields(...))]` with ids and the type name only;
+ `ret` and default argument capture leaked payloads and were fixed twice. See the
+ [observability rule](../../.agents/rules/observability.md).
+- **Malformed messages.** Ingress acknowledges and drops messages it can't decode;
+ don't rely on SQS retries to fix a bad payload.
+
+## Verify locally
+
+```sh
+cargo test -p model_notifications
+cargo test -p notification_service
+cargo test -p graphql_notification
+cargo test -p <producing crate> # with SQLX_OFFLINE unset
+cargo run -p complete_graph --bin graphql_schema -- static_assets/schema.graphql
+cd apps/web && bun run gen-api --check && bun run check
+cd packages/sdk && just check && just coverage
+```
+
+Then trigger the event on a local stack ([running locally](../development/running-locally.md))
+and confirm the row in the inbox, its click target, the live update in a second
+tab, and the settings toggle. The `live-debug` skill shows the ingress and egress
+spans; local-e2e notification tests live in
+`crates/integration_tests/local_e2e/tests/channel_mutations.rs`.
diff --git a/docs/guides/new-service.md b/docs/guides/new-service.md
new file mode 100644
index 0000000000..24ecb79490
--- /dev/null
+++ b/docs/guides/new-service.md
@@ -0,0 +1,166 @@
+# Creating a new service
+
+A new deployable service is registered in about a dozen places. Each section below
+is one place, in the order you'll reach it. Most past launches missed at least one
+and needed a follow-up fix; those misses are called out inline.
+
+> **Agents never deploy.** Everything here is code and config in a PR. The first
+> deploy, Doppler secrets, and DNS are done by a person or on their explicit
+> request. See the [infrastructure guide](../development/infrastructure.md).
+
+## Pick a model to copy
+
+| Building | Copy | Why |
+| --- | --- | --- |
+| HTTP service behind the gateway | `services/calendar_service` + `infra/stacks/calendar-service` | Newest full example: own stack, gateway route, local stack, OpenAPI, web and SDK clients |
+| SQS worker, no port | `services/slack_import_worker` | No router, opt-in locally, deployed inside an existing stack |
+| Kafka consumer | `services/agent_trigger_service` | `KafkaConsumerAdapter` with explicit offset commits |
+| Cloudflare Worker | `services/cla-worker` | Wrangler, generated deploy workflow; none of the Rust, ECS, or Doppler steps apply |
+
+Names: the crate is `snake_case` (`calendar_service`); everything else uses the
+kebab-case name (`calendar-service`) and it must be **identical** across
+`services-config.json`, the nix `serviceName`, the Pulumi project name, and the
+Doppler project. Calendar's `DOPPLER_PROJECT: 'calendar_service'` env var is the
+cautionary example.
+
+## 1. The crate
+
+- Create `services/<snake_name>/` and add it to `members` in the root
+ `Cargo.toml`. Third-party dependencies use `{ workspace = true }`; add
+ `workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }`.
+- Run `just hakari` (`cargo x deps`) and commit the regenerated
+ `crates/workspace-hack` and `.github/workspace-dep-closures.json`. CI and nix both
+ fail without it.
+- The binary is a composition root. Domain logic goes in `crates/<domain>` with
+ `inbound/`, `domain/`, and `outbound/` (see the
+ [hexagonal architecture skill](../../.agents/skills/cloud-storage-hexagonal-architecture/SKILL.md)).
+- If it uses `sqlx::query!`, run `nix develop --command just prepare_db` and commit
+ the root `.sqlx/` ([database guide](../development/database.md)).
+
+### `main.rs`, in order
+
+Follow `services/calendar_service/src/main.rs`, except that `main` returns
+`Result<(), rootcause::Report>` (CS-56; calendar still returns `anyhow::Result`):
+
+1. `MacroEntrypoint::default().init()` first. Keep the returned handle and call
+ `.shutdown()` before exit so telemetry flushes.
+2. Load config once: a `#[derive(MacroConfig)]` struct in `src/config.rs`, loaded
+ with `macro_config::ConfigLoader::load`. See the
+ [config rule](../../.agents/rules/config-and-service-urls.md).
+3. Build clients: `macro_aws_config`, Postgres pool, `XServiceUrl::new()` for every
+ service you call.
+4. If the binary dials TLS through rustls directly (not via `reqwest`), install the
+ `aws_lc_rs` crypto provider before anything else, or rustls panics.
+5. Auth state (`MacroAuthorizationState`, internal API key, user API keys).
+6. Router: `TraceLayer`, `macro_cors::cors_layer()`, compression; state via `State`,
+ not `Extension`. Mount it at `/` **and** under `/<prefix>`, because the gateway
+ forwards the path unchanged.
+7. `GET /health` returning 200, matching the Pulumi and compose health checks.
+8. Graceful shutdown: `axum::serve(..).with_graceful_shutdown(shutdown_signal())`;
+ background tasks on a `CancellationToken` + `TaskTracker`; drain the Kafka
+ publisher with a timeout.
+
+Listen on `8080` by default; the Dockerfile sets `PORT=8080`.
+
+## 2. Deploy inventory
+
+- **`.github/services-config.json`:** add `"<kebab-name>": { source_paths,
+ stack_path, deploy_binaries }`. Add `"bootstrap_pending": "<reason>"` until the
+ Doppler project and first deploy exist; CI skips the service while it's set.
+- **`nix/cloud-storage.nix`:** add `{ serviceName; packageName; binaries }` to
+ `deployServiceBinaryDefinitions`, and to `localStackDeployServiceNames` if it
+ runs locally. *Missed by both calendar and the Slack import worker;* the deploy
+ fails at `nix build .#deploy-service-binaries-<name>`. Files you `include_str!`
+ must also match the nix `assetFilter`.
+- **`.github/workflows/deploy-service-generic.yml`:** add the name to the dispatch
+ list. It's hand-maintained and was forgotten twice.
+- If you changed a workflow generator, run `cargo x workflows`.
+
+## 3. Infrastructure
+
+Follow the [infrastructure guide](../development/infrastructure.md) for the pattern itself.
+
+- Create `infra/stacks/<kebab-name>/` (`Pulumi.yaml`, `Pulumi.dev.yaml`,
+ `Pulumi.prod.yaml`, `package.json`, `tsconfig.json`, `index.ts`, `service.ts`) by
+ copying `calendar-service`, and update `infra/bun.lock`.
+- **Doppler project:** add the name to `SERVICE_NAMES` in
+ `infra/stacks/doppler-projects/index.ts`. Until that stack is deployed and the
+ project has `dev`/`prd` values, a deploy can't read its secret; keep
+ `bootstrap_pending` set.
+- **Gateway:** add a `GatewayService` member and a unique priority in
+ `infra/packages/shared/src/gateway_priorities.ts`, then a `ServiceTargetGroup`.
+ Check that no existing rule with a lower number matches your prefix.
+- Queues with the `Queue` component, Kafka access with `getKafkaClusterPolicy()`,
+ alarms copied from `calendar-service/service.ts`.
+
+## 4. Config and secrets
+
+- Put every key the service reads into Doppler `<kebab-name>` for `dev` and `prd`,
+ with names identical to the code. The `doppler_config` CI check fails otherwise.
+- Add the keys to the shared `local/lcl_personal` config, and a `BootStubEnv`
+ placeholder in `tooling/xtask/crates/xtask_local/src/local/local_env.rs` so
+ `--no-doppler` still boots.
+- Add a `src/doppler_config.rs` binary like `services/contacts_service`'s so CI
+ validates your config against Doppler on every change.
+
+## 5. Service discovery
+
+- Add a `service_url!` entry to `crates/macro_service_urls/src/lib.rs` with
+ `local`, `dev`, and `prod` values.
+- Add the in-network override in `local_env.rs`:
+ `OVERRIDE_<NAME>_URL = http://<compose-alias>:8080`. The `local` default is a host
+ port, which inside Docker points back at the caller.
+- If the frontend calls it, add it to `serverHostLocal`, `directServerHostRemote`, and
+ `proxyServers()` in `apps/web/src/lib/core/constant/servers.ts`. A test fails if
+ the proxy prefix is missing.
+- If infra needs the URL, add it to `infra/packages/shared/src/service_urls.ts`.
+
+## 6. Local stack
+
+- `docker/docker-compose.yml`: a block using `<<: [*common-env,
+ *rust-services-image]`, `command: ["/app/out/<bin>"]`, a network alias, a
+ `/health` healthcheck, and a port. Workers with no port go under a `profiles:`
+ entry.
+- `tooling/xtask/crates/xtask_local/src/local/inventory.rs`: a `RustService` entry,
+ and bump the count in `inventory/test.rs`. A worker that consumes shared queues
+ must be `opt_in` or `modes: &[Mode::Local]`, or `run_dev` steals dev messages.
+- `local/instance.rs`: add the `Port` variant **at the end**; offsets come from
+ declaration order.
+- `local/resources.rs` and `crates/macro_queues`: any queue or bucket the service
+ needs. A worker whose queue doesn't exist locally spins in a tight loop.
+
+## 7. API clients (HTTP services)
+
+- Add a `<crate>_openapi` binary (`src/openapi.rs`).
+- Web: `serviceToCrate` in `apps/web/scripts/generate-api-schema.ts`, an entry in
+ `apps/web/scripts/services.ts`, an orval target in
+ `apps/web/src/lib/service-clients/orval.config.ts`, and a path alias in
+ `apps/web/tsconfig.json`.
+- SDK: follow the [add-sdk-endpoint skill](../../.agents/skills/add-sdk-endpoint/SKILL.md),
+ including `ACCESSORS` in `src/coverage/check.ts`, then `just coverage`.
+
+## 8. Kafka topics (only if you add one)
+
+Add it to the `topics!` list in `crates/macro_event_topics/src/lib.rs` and run
+`cargo x kafka-topics`. Never hand-edit `.github/kafka-cluster-topics.json`.
+
+## Verify locally
+
+```sh
+cargo build -p <package>
+just rust-check && just clippy
+cargo test -p <package> # with SQLX_OFFLINE unset
+cargo x deps --check && cargo x workflows --check
+just run_local # or just stack up
+curl http://localhost:<port>/health
+curl https://localhost:8090/<prefix>/health # through the local proxy
+```
+
+Use the `live-debug` skill for traces and logs. For opt-in workers, start the
+compose profile.
+
+## After merge
+
+A person (or an agent on explicit request) creates the Doppler values, deploys
+`doppler-projects`, removes `bootstrap_pending`, and lets the next push to `main`
+deploy dev. Production follows the next release.
diff --git a/docs/AI_BILLING_ROLLOUT.md b/docs/runbooks/ai-billing-rollout.md
similarity index 99%
rename from docs/AI_BILLING_ROLLOUT.md
rename to docs/runbooks/ai-billing-rollout.md
index a2e8fe88f7..55ccdd8c3b 100644
--- a/docs/AI_BILLING_ROLLOUT.md
+++ b/docs/runbooks/ai-billing-rollout.md
@@ -7,7 +7,7 @@ for the Rust paths below. It does not activate financial admission, credit holds
credit debits, postpaid liability, or collection. Observations must never be
replayed as financial authorizations or converted into historical customer debt.
-The separate [legacy quota rollout](AI_QUOTA_ENFORCEMENT.md) adds default-off
+The separate [legacy quota rollout](ai-quota-enforcement.md) adds default-off
`ENABLE_AI_USAGE_ENFORCEMENT`: snapshot-based allowance admission and prospective
`ai_usage.count_usage` writes by existing aggregate producers. Billing reads only
persisted counted rows; historical/default-false rows remain uncounted. This is
diff --git a/docs/AI_QUOTA_ENFORCEMENT.md b/docs/runbooks/ai-quota-enforcement.md
similarity index 72%
rename from docs/AI_QUOTA_ENFORCEMENT.md
rename to docs/runbooks/ai-quota-enforcement.md
index f8e439db91..06e4c0666f 100644
--- a/docs/AI_QUOTA_ENFORCEMENT.md
+++ b/docs/runbooks/ai-quota-enforcement.md
@@ -9,14 +9,14 @@ cap, a reservation system, or activation of financial admission. It does not sel
customer debt. Usage-driven credit consumption and Stripe settlement are gated by
the separate default-off [`ENABLE_AI_USAGE_BILLING`](#settlement-enable_ai_usage_billing)
policy, never by this flag or the deployment environment. See
-[the separate observation/financial rollout](AI_BILLING_ROLLOUT.md).
+[the separate observation/financial rollout](ai-billing-rollout.md).
-The [startup loader](../crates/ai_usage/src/config.rs) accepts only raw `true` or
+The [startup loader](../../crates/ai_usage/src/config.rs) accepts only raw `true` or
`false`; absent means false. Empty, quoted, `null`, or otherwise malformed present
values fail startup. Hosts load the policy once, not per request. Changing it
requires restarting/redeploying every participating process.
-The [shared policy](../crates/ai_usage/src/domain/counting.rs) is identical for
+The [shared policy](../../crates/ai_usage/src/domain/counting.rs) is identical for
admission and recording:
| Policy / work | Admission | New `ai_usage.count_usage` |
@@ -46,19 +46,19 @@ automatic reload opt-in, and denial decisions remain in the legacy ledger.
### Persistence
-The [usage service](../crates/ai_usage/src/domain/service.rs) computes the boolean
+The [usage service](../../crates/ai_usage/src/domain/service.rs) computes the boolean
for both `record()` and `record_now()`, before the
-[repository insert](../crates/ai_usage/src/outbound/pg_usage_repo.rs). Clients cannot
-supply it. The [billing reader](../crates/ai_billing/src/outbound/pg_usage_reader.rs)
+[repository insert](../../crates/ai_usage/src/outbound/pg_usage_repo.rs). Clients cannot
+supply it. The [billing reader](../../crates/ai_billing/src/outbound/pg_usage_reader.rs)
uses the persisted literal `count_usage = TRUE`, not a mutable feature exclusion
list. User/team-seat scoping, `[start, end)` periods, at-cost arithmetic, and
fallback pricing for null totals are retained. Admin analytics still includes
uncounted rows; repricing can change totals, never eligibility.
-[Counting tests](../crates/ai_usage/src/domain/counting/test.rs),
-[recording tests](../crates/ai_usage/src/domain/service/test.rs),
-[persistence/repricing tests](../crates/ai_usage/src/outbound/pg_usage_repo/test.rs),
-and [billing-reader tests](../crates/ai_billing/src/outbound/pg_usage_reader/test.rs)
+[Counting tests](../../crates/ai_usage/src/domain/counting/test.rs),
+[recording tests](../../crates/ai_usage/src/domain/service/test.rs),
+[persistence/repricing tests](../../crates/ai_usage/src/outbound/pg_usage_repo/test.rs),
+and [billing-reader tests](../../crates/ai_billing/src/outbound/pg_usage_reader/test.rs)
cover these distinctions. Historical analytics and observations must never be
backfilled into counted usage or financial authorizations.
@@ -67,7 +67,7 @@ backfilled into counted usage or financial authorizations.
`ENABLE_AI_USAGE_BILLING` enables **legacy settlement of counted usage past a
payer's allowance**: prepaid credits are consumed and optional automatic reloads
purchase more credits through Stripe. Direct usage charges are disabled. The
-[startup loader](../crates/ai_billing/src/config.rs)
+[startup loader](../../crates/ai_billing/src/config.rs)
parses it exactly like the enforcement flag (absent means false; only raw `true`
or `false`; malformed present values fail startup) and hosts load it once. It is
independent of `ENABLE_AI_USAGE_ENFORCEMENT` and of the deployment environment:
@@ -75,8 +75,8 @@ there is no longer an `Environment::Develop` safeguard, so a true value settles
in production.
Pricing is four mandatory Doppler values, loaded once at startup by every host that
-composes `ai_billing` (see [`config.rs`](../crates/ai_billing/src/config.rs) and
-[`pricing.rs`](../crates/ai_billing/src/domain/pricing.rs)): one allowance per plan,
+composes `ai_billing` (see [`config.rs`](../../crates/ai_billing/src/config.rs) and
+[`pricing.rs`](../../crates/ai_billing/src/domain/pricing.rs)): one allowance per plan,
measured at provider cost — `AI_USAGE_FREE_INCLUDED_ALLOWANCE_CENTS` (the free plan's
hard cap, per user per UTC calendar month), `AI_USAGE_INCLUDED_ALLOWANCE_CENTS`
(Premium, per seat per subscription period), and `AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS`
@@ -99,11 +99,11 @@ The hosts that participate:
| Host | Gate | When disabled |
| --- | --- | --- |
-| Authentication service | [`BillingServiceImpl::settle`](../crates/ai_billing/src/domain/service.rs) guards every caller: summary reads, automatic reload changes, credit-purchase webhooks, the internal settle endpoint, and the [reconciliation sweep](#reconciliation-sweep-and-closed-periods). It also reserves and collects automatic credit reloads | Returns without reading entitlements, consuming credits, reloading credits, or touching Stripe; the sweep is not started. Credit purchases are still booked and remain unconsumed |
-| Document cognition, agent harness, MCP, and scheduled action services | [`SettlingUsageRecorder`](../crates/ai_billing/src/outbound/settling_recorder.rs) requests settlement after counted usage lands. Document cognition composes it inline around its admission instance; the other three compose it through [`pg_settling_recorder`](../crates/ai_billing/src/composition.rs) with the [`SettlementRoute`](../crates/ai_billing/src/composition.rs) their configuration resolves | Usage is still recorded and counted; no settlement request is sent |
+| Authentication service | [`BillingServiceImpl::settle`](../../crates/ai_billing/src/domain/service.rs) guards every caller: summary reads, automatic reload changes, credit-purchase webhooks, the internal settle endpoint, and the [reconciliation sweep](#reconciliation-sweep-and-closed-periods). It also reserves and collects automatic credit reloads | Returns without reading entitlements, consuming credits, reloading credits, or touching Stripe; the sweep is not started. Credit purchases are still booked and remain unconsumed |
+| Document cognition, agent harness, MCP, and scheduled action services | [`SettlingUsageRecorder`](../../crates/ai_billing/src/outbound/settling_recorder.rs) requests settlement after counted usage lands. Document cognition composes it inline around its admission instance; the other three compose it through [`pg_settling_recorder`](../../crates/ai_billing/src/composition.rs) with the [`SettlementRoute`](../../crates/ai_billing/src/composition.rs) their configuration resolves | Usage is still recorded and counted; no settlement request is sent |
Every host composes admission through
-[`pg_admission_service`](../crates/ai_billing/src/composition.rs) (or document
+[`pg_admission_service`](../../crates/ai_billing/src/composition.rs) (or document
cognition's inline equivalent), which never settles regardless of
configuration. The authentication service's policy is authoritative: a request
from another host is a no-op there while its flag is false, and with every
@@ -128,12 +128,12 @@ reload whose collector died between reserving and invoicing) or never come (a
period that closed after the payer's last completion). Two mechanisms in the
authentication service recover such usage without a customer action:
-- **The sweep.** [`SettlementSweep`](../crates/ai_billing/src/domain/sweep.rs)
+- **The sweep.** [`SettlementSweep`](../../crates/ai_billing/src/domain/sweep.rs)
runs on a schedule
- ([`run_settlement_sweep`](../crates/ai_billing/src/inbound/sweep_worker.rs):
+ ([`run_settlement_sweep`](../../crates/ai_billing/src/inbound/sweep_worker.rs):
a minute after boot, then hourly) and settles, once each, every metered
payer with a candidate in the last 24 hours
- ([`PgSettlementCandidates`](../crates/ai_billing/src/outbound/pg_settlement_candidates.rs)):
+ ([`PgSettlementCandidates`](../../crates/ai_billing/src/outbound/pg_settlement_candidates.rs)):
users with counted usage, payers whose anchored subscription period began or
ended, and payers holding a credit reload reserved more than ten minutes ago
that was never collected. A failure for one payer is logged and the sweep
@@ -142,7 +142,7 @@ authentication service recover such usage without a customer action:
shutdown.
- **Closed periods.** `settle` no longer stops at the previous period. Before
the open period it settles every period frozen within the last
- [`RECONCILED_CLOSED_PERIODS`](../crates/ai_billing/src/domain/service.rs)
+ [`RECONCILED_CLOSED_PERIODS`](../../crates/ai_billing/src/domain/service.rs)
(three) periods, each against its own frozen allowance and keyed exactly as
its ledger, oldest first. A frozen period ends where the next period
begins. The derived previous period is settled (from the live entitlement,
@@ -205,7 +205,7 @@ and is the only surface that turns usage billing on.
## Public failure contracts
-The [shared admission port](../crates/ai_billing/src/domain/admission.rs) returns
+The [shared admission port](../../crates/ai_billing/src/domain/admission.rs) returns
`Denied(DenyReason)` or sanitized `Unavailable`. Authorization runs first; quota
errors are not permission grants and must not disclose another user's quota.
@@ -217,7 +217,7 @@ errors are not permission grants and must not disclose another user's quota.
| Overage payment failed | 402 | `ai_overage_payment_failed` | Billing problem must be resolved |
| Could not validate billing | 503 | `ai_billing_unavailable` | Retry later with bounded backoff; never execute on uncertainty |
-The [common HTTP body](../crates/ai_billing/src/inbound/admission.rs) is
+The [common HTTP body](../../crates/ai_billing/src/inbound/admission.rs) is
`{"error":"<public explanation>","code":"<stable code>"}`. The 503 explanation is
`AI usage validation is temporarily unavailable. Please try again.` Internal
reports are logged server-side, not serialized. A `Retry-After` header is not
@@ -247,7 +247,7 @@ inspect the content type and code rather than assuming every 503 is billing.
reservation. On exhaustion, the waiting queue is durably removed before queue
updates, failed announced-reply resolution, and
`agent_session.command_rejected` lifecycle publication. Its
- [metadata](../crates/agent_session/src/domain/events.rs) contains `identity`,
+ [metadata](../../crates/agent_session/src/domain/events.rs) contains `identity`,
`action_id`, `actor`, optional `announcement_message_id`, and
`failure: {code, message, retryable}`. It does not invent a runtime turn.
- Queue validation unavailability preserves FIFO work for a later ordinary
@@ -293,34 +293,34 @@ selection, and tool calls still have their own gates.
Links below identify the actual boundary, production injection/recorder constructor,
and local regression suite. They are not evidence of live-provider, browser, or
-deployed coverage. Shared factory [R](../crates/ai_usage/src/lib.rs) means
+deployed coverage. Shared factory [R](../../crates/ai_usage/src/lib.rs) means
`pg_recorder_with_enforcement`: configured analytics plus separate `pg_tracking`.
-Shared tools [T](../crates/ai_tools/src/build_context.rs) construct configured
+Shared tools [T](../../crates/ai_tools/src/build_context.rs) construct configured
admission and take the host's recorder (R, or
-[`pg_settling_recorder`](../crates/ai_billing/src/composition.rs) where the host
+[`pg_settling_recorder`](../../crates/ai_billing/src/composition.rs) where the host
requests settlement). Admission itself never records usage or calls settlement.
| Surface / feature | Admission boundary | Production recorder / composition | Regression tests |
| --- | --- | --- | --- |
-| Cognition chat / Chat | [chat handler](../services/document_cognition_service/src/api/stream/chat_message.rs) | [DCS main](../services/document_cognition_service/src/main.rs): configured `UsageServiceImpl` inside `SettlingUsageRecorder`, wrapped with `with_tracking` | [pre-creation refusal and permission precedence](../services/document_cognition_service/src/api/stream/chat_message/test.rs) |
-| Structured completion / DynamicCompletionsApi | [completion handler](../services/document_cognition_service/src/api/structured_completion.rs) | DCS main, same recorder across both phases | [both phases and OpenAPI](../services/document_cognition_service/src/api/structured_completion/test.rs) |
-| Chat naming / ChatRename | [chat renamer](../services/document_cognition_service/src/service/chat_renamer.rs) | DCS main, same recorder | [safe naming skip](../services/document_cognition_service/src/service/chat_renamer/test.rs) |
-| Direct subagent / inherited feature | [operations service](../crates/ai_tools/src/ai_operations.rs), [subagent](../crates/ai_tools/src/subagent.rs) | Host common context: T, DCS main, or [MCP context](../services/mcp_service/src/context.rs) using `pg_settling_recorder` | [zero provider calls](../crates/ai_tools/src/ai_operations/test.rs), [concurrent caller isolation](../crates/ai_tools/src/subagent/test.rs) |
-| Native Anthropic WebSearch/WebFetch/code tools / inherited feature | [invoke_server_tool](../crates/anthropic/src/toolset.rs) before both provider branches | Same common contexts via `FromRef`; observation only, **no legacy aggregate producer** | [tool attribution/refusal](../crates/anthropic/src/toolset/test.rs) |
-| AI document editing / AiEditing | [document orchestration](../crates/documents/src/domain/ai_editing.rs) after verified edit receipt | Common context's recorder, existing per-model worker usage | [domain](../crates/documents/src/domain/ai_editing/test.rs), [direct tool and permission precedence](../crates/documents/src/inbound/toolset/edit_document/test.rs) |
-| AI gather/Notion imports / Import | [import admission](../crates/import/src/domain/service/admission.rs), [execution/rechecks](../crates/import/src/domain/service.rs) | DCS main, wrapped recorder | [initial/retry/delayed/deterministic cases](../crates/import/src/domain/service/test/admission.rs), [HTTP](../crates/import/src/inbound/axum_router/test.rs) |
-| Channel responder / ChannelBot | [bot service](../crates/channel_bots/src/domain/service.rs) | [DSS main](../services/document_storage_service/src/main.rs), common context T | [response refusal](../crates/channel_bots/src/domain/service/tests.rs) |
-| Optional channel classification / ChannelBot | [trigger detector](../crates/channel_bots/src/domain/trigger_detector.rs) | DSS main, independent R for classifier | [explicit routing and inference skip](../crates/channel_bots/src/domain/trigger_detector/tests.rs) |
-| Trigger inference and image captions / Automation | [trigger service](../crates/agent_trigger/src/domain/service.rs) | [standalone trigger main](../services/agent_trigger_service/src/main.rs) R; [harness trigger](../services/agent_harness_service/src/trigger.rs) receives the harness's settling recorder from harness main | [classification/caption refusal](../crates/agent_trigger/src/domain/service/test/admission.rs), [no system fallback](../crates/agent_trigger/src/outbound/fast_model_judge/test.rs) |
-| Managed session ingress/dispatch/queue / AgentSession | [harness admission](../crates/agent_harness/src/domain/service/admission.rs) | [harness main](../services/agent_harness_service/src/main.rs): one `pg_settling_recorder` shared with T for in-memory; managed sandbox inference has **no `ai_usage` producer** | [owner, authorization, runtime funding, restart, queue rejection/outage](../crates/agent_harness/src/domain/service/test/quota.rs), [HTTP](../crates/agent_session/src/inbound/axum_router/test.rs), [event shape](../crates/agent_session/src/domain/events/test.rs) |
-| Direct in-memory ACP/provider commands / AgentSession | [admit_turn](../crates/agent_inmem/src/domain/admission.rs), [agent execution](../crates/agent_inmem/src/domain/agent.rs) | Harness main → manager → `RigTurnEngine`, the harness's settling recorder passed into T | [direct ACP, queue, cancel, history](../crates/agent_inmem/src/domain/agent/test.rs), [manager](../crates/agent_inmem/src/outbound/manager/test.rs) |
-| Session naming / ChatRename | [name generator gate](../crates/agent_session/src/domain/name_generation.rs) | Harness main, the same settling recorder for `HaikuAgentSessionNameGenerator` (exempt, so never counted or settled) | [fallback without provider calls](../crates/agent_session/src/domain/name_generation/test.rs) |
-| Repository chooser / AgentRepositoryChoice | [repository choice service](../crates/agent_harness/src/domain/repository_choice.rs) | Harness main → `CursorContainerManager`, the same settling recorder | [deterministic bypass / typed model refusal](../crates/agent_harness/src/domain/repository_choice/test.rs) |
-| Scheduled manual/cron/event model work / Automation | [shared executor](../services/scheduled_action/src/domain/execution.rs) | [scheduled service](../services/scheduled_action/src/bins/service.rs): `pg_settling_recorder` for the condition classifier; agent targets are funded and metered by the harness | [claims, schedules, terminal events](../services/scheduled_action/src/domain/execution/test.rs), [manual HTTP](../services/scheduled_action/src/inbound/axum_router/test.rs) |
-| Scheduled agent targets / session funding policy | [target runner](../services/scheduled_action/src/domain/target_runner.rs) → session/harness admission | Target runtime's recorder, not duplicate scheduler metering | [delegation and typed errors](../services/scheduled_action/src/domain/target_runner/test.rs), [routine error transport](../crates/agent_session/src/inbound/routine_sessions/test.rs) |
-| Memory, projection, call summary, dictation, chat rename / exempt | [shared admission policy](../crates/ai_billing/src/domain/admission.rs) skips quota; ordinary permissions still apply | DCS/DSS configured recorders; [memory context](../crates/memory/src/context.rs) uses T; DSS independent call-summary/dictation recorders use R | [all exempt features](../crates/ai_usage/src/domain/counting/test.rs), [no billing I/O](../crates/ai_billing/src/domain/admission/test.rs), [configured recording](../crates/ai_billing/src/composition/test.rs) |
-| Existing system task duplicate judge / Automation | [system attribution](../crates/task_dedup/src/outbound/judge.rs), no user quota gate | DSS main, independent R; system events stay uncounted | [system counting](../crates/ai_usage/src/domain/counting/test.rs), [system recorder behavior](../crates/ai_billing/src/outbound/settling_recorder/test.rs) |
-| Billing summary (not execution) | [billing service policy](../crates/ai_billing/src/domain/service.rs) | [authentication main](../services/authentication_service/src/main.rs) configures the same flag plus `ENABLE_AI_USAGE_BILLING`, no usage producer | [settlement policy/free/unlimited/settlement](../crates/ai_billing/src/domain/service/test.rs), [authentication configuration](../services/authentication_service/src/config/test.rs) |
+| Cognition chat / Chat | [chat handler](../../services/document_cognition_service/src/api/stream/chat_message.rs) | [DCS main](../../services/document_cognition_service/src/main.rs): configured `UsageServiceImpl` inside `SettlingUsageRecorder`, wrapped with `with_tracking` | [pre-creation refusal and permission precedence](../../services/document_cognition_service/src/api/stream/chat_message/test.rs) |
+| Structured completion / DynamicCompletionsApi | [completion handler](../../services/document_cognition_service/src/api/structured_completion.rs) | DCS main, same recorder across both phases | [both phases and OpenAPI](../../services/document_cognition_service/src/api/structured_completion/test.rs) |
+| Chat naming / ChatRename | [chat renamer](../../services/document_cognition_service/src/service/chat_renamer.rs) | DCS main, same recorder | [safe naming skip](../../services/document_cognition_service/src/service/chat_renamer/test.rs) |
+| Direct subagent / inherited feature | [operations service](../../crates/ai_tools/src/ai_operations.rs), [subagent](../../crates/ai_tools/src/subagent.rs) | Host common context: T, DCS main, or [MCP context](../../services/mcp_service/src/context.rs) using `pg_settling_recorder` | [zero provider calls](../../crates/ai_tools/src/ai_operations/test.rs), [concurrent caller isolation](../../crates/ai_tools/src/subagent/test.rs) |
+| Native Anthropic WebSearch/WebFetch/code tools / inherited feature | [invoke_server_tool](../../crates/anthropic/src/toolset.rs) before both provider branches | Same common contexts via `FromRef`; observation only, **no legacy aggregate producer** | [tool attribution/refusal](../../crates/anthropic/src/toolset/test.rs) |
+| AI document editing / AiEditing | [document orchestration](../../crates/documents/src/domain/ai_editing.rs) after verified edit receipt | Common context's recorder, existing per-model worker usage | [domain](../../crates/documents/src/domain/ai_editing/test.rs), [direct tool and permission precedence](../../crates/documents/src/inbound/toolset/edit_document/test.rs) |
+| AI gather/Notion imports / Import | [import admission](../../crates/import/src/domain/service/admission.rs), [execution/rechecks](../../crates/import/src/domain/service.rs) | DCS main, wrapped recorder | [initial/retry/delayed/deterministic cases](../../crates/import/src/domain/service/test/admission.rs), [HTTP](../../crates/import/src/inbound/axum_router/test.rs) |
+| Channel responder / ChannelBot | [bot service](../../crates/channel_bots/src/domain/service.rs) | [DSS main](../../services/document_storage_service/src/main.rs), common context T | [response refusal](../../crates/channel_bots/src/domain/service/tests.rs) |
+| Optional channel classification / ChannelBot | [trigger detector](../../crates/channel_bots/src/domain/trigger_detector.rs) | DSS main, independent R for classifier | [explicit routing and inference skip](../../crates/channel_bots/src/domain/trigger_detector/tests.rs) |
+| Trigger inference and image captions / Automation | [trigger service](../../crates/agent_trigger/src/domain/service.rs) | [standalone trigger main](../../services/agent_trigger_service/src/main.rs) R; [harness trigger](../../services/agent_harness_service/src/trigger.rs) receives the harness's settling recorder from harness main | [classification/caption refusal](../../crates/agent_trigger/src/domain/service/test/admission.rs), [no system fallback](../../crates/agent_trigger/src/outbound/fast_model_judge/test.rs) |
+| Managed session ingress/dispatch/queue / AgentSession | [harness admission](../../crates/agent_harness/src/domain/service/admission.rs) | [harness main](../../services/agent_harness_service/src/main.rs): one `pg_settling_recorder` shared with T for in-memory; managed sandbox inference has **no `ai_usage` producer** | [owner, authorization, runtime funding, restart, queue rejection/outage](../../crates/agent_harness/src/domain/service/test/quota.rs), [HTTP](../../crates/agent_session/src/inbound/axum_router/test.rs), [event shape](../../crates/agent_session/src/domain/events/test.rs) |
+| Direct in-memory ACP/provider commands / AgentSession | [admit_turn](../../crates/agent_inmem/src/domain/admission.rs), [agent execution](../../crates/agent_inmem/src/domain/agent.rs) | Harness main → manager → `RigTurnEngine`, the harness's settling recorder passed into T | [direct ACP, queue, cancel, history](../../crates/agent_inmem/src/domain/agent/test.rs), [manager](../../crates/agent_inmem/src/outbound/manager/test.rs) |
+| Session naming / ChatRename | [name generator gate](../../crates/agent_session/src/domain/name_generation.rs) | Harness main, the same settling recorder for `HaikuAgentSessionNameGenerator` (exempt, so never counted or settled) | [fallback without provider calls](../../crates/agent_session/src/domain/name_generation/test.rs) |
+| Repository chooser / AgentRepositoryChoice | [repository choice service](../../crates/agent_harness/src/domain/repository_choice.rs) | Harness main → `CursorContainerManager`, the same settling recorder | [deterministic bypass / typed model refusal](../../crates/agent_harness/src/domain/repository_choice/test.rs) |
+| Scheduled manual/cron/event model work / Automation | [shared executor](../../services/scheduled_action/src/domain/execution.rs) | [scheduled service](../../services/scheduled_action/src/bins/service.rs): `pg_settling_recorder` for the condition classifier; agent targets are funded and metered by the harness | [claims, schedules, terminal events](../../services/scheduled_action/src/domain/execution/test.rs), [manual HTTP](../../services/scheduled_action/src/inbound/axum_router/test.rs) |
+| Scheduled agent targets / session funding policy | [target runner](../../services/scheduled_action/src/domain/target_runner.rs) → session/harness admission | Target runtime's recorder, not duplicate scheduler metering | [delegation and typed errors](../../services/scheduled_action/src/domain/target_runner/test.rs), [routine error transport](../../crates/agent_session/src/inbound/routine_sessions/test.rs) |
+| Memory, projection, call summary, dictation, chat rename / exempt | [shared admission policy](../../crates/ai_billing/src/domain/admission.rs) skips quota; ordinary permissions still apply | DCS/DSS configured recorders; [memory context](../../crates/memory/src/context.rs) uses T; DSS independent call-summary/dictation recorders use R | [all exempt features](../../crates/ai_usage/src/domain/counting/test.rs), [no billing I/O](../../crates/ai_billing/src/domain/admission/test.rs), [configured recording](../../crates/ai_billing/src/composition/test.rs) |
+| Existing system task duplicate judge / Automation | [system attribution](../../crates/task_dedup/src/outbound/judge.rs), no user quota gate | DSS main, independent R; system events stay uncounted | [system counting](../../crates/ai_usage/src/domain/counting/test.rs), [system recorder behavior](../../crates/ai_billing/src/outbound/settling_recorder/test.rs) |
+| Billing summary (not execution) | [billing service policy](../../crates/ai_billing/src/domain/service.rs) | [authentication main](../../services/authentication_service/src/main.rs) configures the same flag plus `ENABLE_AI_USAGE_BILLING`, no usage producer | [settlement policy/free/unlimited/settlement](../../crates/ai_billing/src/domain/service/test.rs), [authentication configuration](../../services/authentication_service/src/config/test.rs) |
## Limits and operational risks
@@ -339,7 +339,7 @@ requests settlement). Admission itself never records usage or calls settlement.
- `ai_usage_observation` and `ai_financial_invocation` are separate accounting
systems, not additional counted aggregates. Never sum them with `ai_usage` or
replay observations into debt. Observation retention/erasure approval remains a
- deployment gate in the [observation rollout](AI_BILLING_ROLLOUT.md).
+ deployment gate in the [observation rollout](ai-billing-rollout.md).
- Default-disabled constructors remain for internal/evaluation callers. Production
must use configured admission and R (or explicitly configure DCS's inner usage
service). A new producer must be audited at both its admission and recorder
@@ -355,8 +355,8 @@ No hosted configuration change or collection activation is authorized by this
procedure. Operators must approve and record each release gate.
1. **Compatible schema first.** Apply
- [the default-false column migration](../crates/macro_db_client/migrations/20260930145625_add_ai_usage_count_usage.sql)
- and [the concurrent partial-index migration](../crates/macro_db_client/migrations/20260930145626_ai_usage_counted_user_created_at_idx.sql).
+ [the default-false column migration](../../crates/macro_db_client/migrations/20260930145625_add_ai_usage_count_usage.sql)
+ and [the concurrent partial-index migration](../../crates/macro_db_client/migrations/20260930145626_ai_usage_counted_user_created_at_idx.sql).
Keep the full analytics/old-service index. Verify historical rows and old
inserts remain false. Verify `pg_index.indisvalid` and `pg_get_indexdef` for
`ai_usage_counted_user_created_at_idx`: `(user_id, created_at DESC) WHERE
@@ -423,7 +423,7 @@ checks, not a claim that a particular deployment has passed them.
not a passing check. Compare two generated trees for determinism and run direct
scoped checks when blocked; record the limitation.
- Run the matrix's affected Rust packages individually from the repository root
- with `SQLX_OFFLINE` unset; use [database setup](DATABASE_DEVELOPMENT.md).
+ with `SQLX_OFFLINE` unset; use [database setup](../development/database.md).
Include `ai_usage`, `ai_billing`, and composition tests. Test counted/uncounted,
historical/default rows, multiple users/seats, period boundaries, null totals,
repricing stability, and partial-index eligibility on representative local data.
@@ -437,7 +437,7 @@ checks, not a claim that a particular deployment has passed them.
running flags and scheduled claims/finalization, plus cancellation during admission.
- Start an isolated stack with
`nix develop --command just run_local --instance ai-quota`. Use local identities
- and billing fixtures. Perform the [AI chat manual checks](AGENT_GUIDE/ai-chat.md#quota-manual-checks):
+ and billing fixtures. Perform the [AI chat manual checks](../agent-guide/ai-chat.md#quota-manual-checks):
no orphaned chat/stream on refusal, direct AI edit failure, observable queue
rejection, usable cancellation, and recovery after consistently disabling.
A frontend against hosted dev cannot validate these local backend changes.
diff --git a/docs/ANDROID_TASKS.md b/docs/runbooks/android-release-tasks.md
similarity index 98%
rename from docs/ANDROID_TASKS.md
rename to docs/runbooks/android-release-tasks.md
index 3c3d1457e0..4c0a3732b5 100644
--- a/docs/ANDROID_TASKS.md
+++ b/docs/runbooks/android-release-tasks.md
@@ -1,6 +1,6 @@
# Android release tasks
-Created in Macro from `docs/ANDROID_READINESS_AUDIT.md` on September 21, 2026 (source snapshot `1c26a7c4fe`).
+Created in Macro from `docs/design/android-readiness-audit.md` on September 21, 2026 (source snapshot `1c26a7c4fe`).
All six tasks verified: **Priority: High · Assignee: Peter ([email protected]) · Personal tag: android · Status: Not Started**. No due dates set.
diff --git a/docs/CLAUDE_CLOUD_DEMO.md b/docs/runbooks/claude-cloud-demo.md
similarity index 100%
rename from docs/CLAUDE_CLOUD_DEMO.md
rename to docs/runbooks/claude-cloud-demo.md
diff --git a/docs/comment-schema-drop.md b/docs/runbooks/comment-schema-drop.md
similarity index 98%
rename from docs/comment-schema-drop.md
rename to docs/runbooks/comment-schema-drop.md
index 4b2a173261..351becb771 100644
--- a/docs/comment-schema-drop.md
+++ b/docs/runbooks/comment-schema-drop.md
@@ -4,7 +4,7 @@
the final PDF highlight query fix and the legacy schema drop in one release.
The user explicitly accepted temporary PDF highlight discussion failures on
October 2, overriding the usual separate-release rule in
-[Database development](DATABASE_DEVELOPMENT.md#safe-database-schema-changes)
+[Database development](../development/database.md#safe-database-schema-changes)
for this change. The separate prerequisite PR #7358 is superseded.
The combined change also adapts the historical Slack message writer/reader and
channel search-backfill query added by #7311 on newer `main` to parent identity.
diff --git a/docs/legacy-comment-import.md b/docs/runbooks/legacy-comment-import.md
similarity index 100%
rename from docs/legacy-comment-import.md
rename to docs/runbooks/legacy-comment-import.md
diff --git a/docs/review-media/slack-import/README.md b/docs/runbooks/media/slack-import/README.md
similarity index 100%
rename from docs/review-media/slack-import/README.md
rename to docs/runbooks/media/slack-import/README.md
diff --git a/docs/review-media/slack-import/channel-only.jpg b/docs/runbooks/media/slack-import/channel-only.jpg
similarity index 100%
rename from docs/review-media/slack-import/channel-only.jpg
rename to docs/runbooks/media/slack-import/channel-only.jpg
diff --git a/docs/review-media/slack-import/choices.jpg b/docs/runbooks/media/slack-import/choices.jpg
similarity index 100%
rename from docs/review-media/slack-import/choices.jpg
rename to docs/runbooks/media/slack-import/choices.jpg
diff --git a/docs/review-media/slack-import/slack-import-flow.mp4 b/docs/runbooks/media/slack-import/slack-import-flow.mp4
similarity index 100%
rename from docs/review-media/slack-import/slack-import-flow.mp4
rename to docs/runbooks/media/slack-import/slack-import-flow.mp4
diff --git a/docs/review-media/slack-import/upload.jpg b/docs/runbooks/media/slack-import/upload.jpg
similarity index 100%
rename from docs/review-media/slack-import/upload.jpg
rename to docs/runbooks/media/slack-import/upload.jpg
diff --git a/docs/notification-retention.md b/docs/runbooks/notification-retention.md
similarity index 100%
rename from docs/notification-retention.md
rename to docs/runbooks/notification-retention.md
diff --git a/docs/notification-state-migration.md b/docs/runbooks/notification-state-migration.md
similarity index 100%
rename from docs/notification-state-migration.md
rename to docs/runbooks/notification-state-migration.md
diff --git a/docs/SLACK_ARCHIVE_IMPORT_CONTRACT.md b/docs/runbooks/slack-archive-import-contract.md
similarity index 100%
rename from docs/SLACK_ARCHIVE_IMPORT_CONTRACT.md
rename to docs/runbooks/slack-archive-import-contract.md
diff --git a/docs/SLACK_ARCHIVE_IMPORT_RUNBOOK.md b/docs/runbooks/slack-archive-import.md
similarity index 97%
rename from docs/SLACK_ARCHIVE_IMPORT_RUNBOOK.md
rename to docs/runbooks/slack-archive-import.md
index ef8bcfc548..8add679895 100644
--- a/docs/SLACK_ARCHIVE_IMPORT_RUNBOOK.md
+++ b/docs/runbooks/slack-archive-import.md
@@ -5,9 +5,9 @@ archives and isolated local resources for verification. Do not deploy, import
customer archives, reset databases, purge queues, or delete staging/history to
troubleshoot without separate approval.
-See [the contract](SLACK_ARCHIVE_IMPORT_CONTRACT.md),
-[local setup](RUNNING_LOCALLY.md), [database workflows](DATABASE_DEVELOPMENT.md),
-and [the Settings interaction guide](AGENT_GUIDE/surfaces.md#slack-archive-import).
+See [the contract](slack-archive-import-contract.md),
+[local setup](../development/running-locally.md), [database workflows](../development/database.md),
+and [the Settings interaction guide](../agent-guide/settings.md#slack-archive-import).
## Deployment order and configuration
@@ -55,7 +55,7 @@ restart tasks when changing values. `APP_SECRETS_JSON` can override ordinary
configuration: do not introduce contradictory values there. No secrets or Doppler
changes are supplied by this runbook. Worker provisioning is separately gated by
Pulumi's `deploy_slack_import_worker` (default `false`); enable it only after the
-dedicated secret exists, following the [worker rollout guide](../infra/stacks/cloud-storage-service/SLACK_IMPORT_ROLLOUT.md).
+dedicated secret exists, following the [worker rollout guide](../../infra/stacks/cloud-storage-service/SLACK_IMPORT_ROLLOUT.md).
Keep that deployment gate enabled once provisioned; use `SLACK_IMPORT_ENABLED`
to pause intake without deleting the worker.
@@ -238,7 +238,7 @@ separate live probes below.
For a **new disposable** browser instance, use the local launcher and seed an admin
team against that named instance. For an existing instance, follow
-[non-destructive recovery](RUNNING_LOCALLY.md#recover-an-existing-instance-without-resetting-data)
+[non-destructive recovery](../development/running-locally.md#recover-an-existing-instance-without-resetting-data)
instead: neither `run_local` nor `stack up` is a data-preserving restart. Enable
DSS/worker admission and the frontend override, and use the local E2E backend
origin/JWT setup without invoking a stack-resetting harness. No-Doppler default
diff --git a/docs/SLACK_LIVE_CHANNEL_IMPORT.md b/docs/runbooks/slack-live-channel-import.md
similarity index 99%
rename from docs/SLACK_LIVE_CHANNEL_IMPORT.md
rename to docs/runbooks/slack-live-channel-import.md
index 210ce3a323..02baa9346c 100644
--- a/docs/SLACK_LIVE_CHANNEL_IMPORT.md
+++ b/docs/runbooks/slack-live-channel-import.md
@@ -254,7 +254,7 @@ gates, not successful observations:
```sh
ls crates/import/src/outbound/mcp_slack_source/fixtures/
jq . crates/import/src/outbound/mcp_slack_source/fixtures/*.json
-grep -n "Canonical slug" docs/SLACK_LIVE_CHANNEL_IMPORT.md
+grep -n "Canonical slug" docs/runbooks/slack-live-channel-import.md
grep -rn "@" crates/import/src/outbound/mcp_slack_source/fixtures/ | grep -v example.com
```
diff --git a/infra/README.md b/infra/README.md
index 52bb3a5e07..05fc2a2066 100644
--- a/infra/README.md
+++ b/infra/README.md
@@ -1,12 +1,12 @@
# Macro Cloud Infra
-This monorepo contains the code for all Macro Cloud IaC.
+Pulumi (TypeScript, Bun) for all of Macro's AWS infrastructure. Production is in
+`us-east-1`; the [observability pilot](stacks/observability/README.md) runs
+independently in `us-east-2`.
-## IaC
-Infrastructure is written with [pulumi](https://www.pulumi.com/docs/) with typescript and bun.
+Each directory under `stacks/` is one Pulumi project with `dev` and `prod` stacks;
+shared components live in `packages/`.
-We use AWS for all infrastructure so ask to be added to the aws org and setup [pulumi with aws](https://www.pulumi.com/registry/packages/aws/installation-configuration/). Production infrastructure is in `us-east-1`; the [observability pilot](stacks/observability/README.md) runs independently in `us-east-2`.
-
-The stacks directory represents the infrastructure for each service and pulumi should be run from inside a stack directory. From `stacks/my-service/` run `pulumi up --stack [dev | prod]` to deploy.
-
-We use datadog (on `us-central-1`) for logging.
+Read the [infrastructure guide](../docs/development/infrastructure.md) before
+changing anything here, and the [new service guide](../docs/guides/new-service.md)
+before adding a stack. Deploys run from CI; see the guide's deploy section.
diff --git a/infra/stacks/cloud-storage-service/SLACK_IMPORT_ROLLOUT.md b/infra/stacks/cloud-storage-service/SLACK_IMPORT_ROLLOUT.md
index 53b462b96f..a3dfea39f9 100644
--- a/infra/stacks/cloud-storage-service/SLACK_IMPORT_ROLLOUT.md
+++ b/infra/stacks/cloud-storage-service/SLACK_IMPORT_ROLLOUT.md
@@ -100,7 +100,7 @@ instead, so maintenance and DLQ reconciliation continue.
## Local execution (explicit opt-in)
-Start a local stack using [the local guide](../../../docs/RUNNING_LOCALLY.md),
+Start a local stack using [the local guide](../../../docs/development/running-locally.md),
never `run_dev` or a shared-dev environment. The inventory deliberately excludes
this worker from default builds/startup. Local provisioning creates both queues
and reapplies visibility/redrive/retention settings after all queues exist.
diff --git a/opencode.json b/opencode.json
index bd179f5128..51c076953b 100644
--- a/opencode.json
+++ b/opencode.json
@@ -34,6 +34,11 @@
"type": "remote",
"url": "https://mcp.us5.datadoghq.com/api/unstable/mcp-server/mcp?referrer_ide=opencode-plugin&plugin_version=0.7.13",
"oauth": {}
+ },
+ "posthog": {
+ "type": "remote",
+ "url": "https://mcp.posthog.com/mcp",
+ "oauth": {}
}
}
}
diff --git a/packages/graphics/README.md b/packages/graphics/README.md
index 9874296255..f496421975 100644
--- a/packages/graphics/README.md
+++ b/packages/graphics/README.md
@@ -3,15 +3,15 @@
Experimental graphics editor with a framework-independent scene tree.
For a short implementation-based reference, start with the
-[Graphics API guide](../../docs/GRAPHICS_API.md).
+[Graphics API guide](../../docs/architecture/graphics-api.md).
-Status reviewed 2026-09-28. The [parity plan](../../docs/GRAPHICS_PARITY.md) is the
+Status reviewed 2026-09-28. The [parity plan](../../docs/design/graphics-parity.md) is the
progress/next-checkpoint index. Canvas Next now includes rich text/mentions,
shape labels, connectors, media, document cards and full embeds as the default
canvas editor. Versioned JSON persistence is wired at the Canvas host boundary.
The Loro adapter remains experimental; production collaboration is not wired.
The next product checkpoint is a
-[legacy bridge and color policy](../../docs/CANVAS_LEGACY_BRIDGE.md), kept outside
+[legacy bridge and color policy](../../docs/architecture/canvas-legacy-bridge.md), kept outside
the pure core. Expanding peer support is deferred.
- `@macro-inc/graphics`: document, affine math, scene queries, selection, editing,
@@ -225,7 +225,7 @@ Affine reflection/shear compose correctly, but have no dedicated UI controls.
SyncService integration remains separate work. The two-peer Loro experiment uses
native local undo; never apply local item-delta undo to a shared document.
-The [scene foundation specification](../../docs/GRAPHICS_SCENE_FOUNDATION.md)
+The [scene foundation specification](../../docs/architecture/graphics-scene-foundation.md)
describes the intended longer-term boundary and collaboration questions.
Run `bun run test` and `bun run type-check` here. Tests cover tree invariants,
transform math, document reset, pose preservation, nested editing, history, selection,
diff --git a/packages/graphics/src/loro/README.md b/packages/graphics/src/loro/README.md
index 715f7ffd35..8990fc1897 100644
--- a/packages/graphics/src/loro/README.md
+++ b/packages/graphics/src/loro/README.md
@@ -1,9 +1,9 @@
# Two-peer scene experiment
-Status reviewed 2026-09-28. See the [main progress plan](../../../../docs/GRAPHICS_PARITY.md).
+Status reviewed 2026-09-28. See the [main progress plan](../../../../docs/design/graphics-parity.md).
Automated mapping coverage now includes pencil, rich text/labels, connectors and
media/document references. Full Canvas Next integration is deferred while the
-[legacy bridge and colors](../../../../docs/CANVAS_LEGACY_BRIDGE.md) take priority.
+[legacy bridge and colors](../../../../docs/architecture/canvas-legacy-bridge.md) take priority.
`@macro-inc/graphics/loro` is an experimental adapter with an in-memory transport
harness used by tests. It uses the workspace Loro version (1.16.3). No SyncService,
diff --git a/rules/ast-grep/rust-mod-rs-declarations-only.yml b/rules/ast-grep/rust-mod-rs-declarations-only.yml
index 9cbf3456a2..b098c2d19a 100644
--- a/rules/ast-grep/rust-mod-rs-declarations-only.yml
+++ b/rules/ast-grep/rust-mod-rs-declarations-only.yml
@@ -3,7 +3,7 @@ language: rust
severity: error
message: mod.rs should only declare submodules and re-exports; move logic into its own module file.
note: |-
- Rule CS-25 in docs/STYLE_GUIDE.md, mined from PR #4175.
+ Rule CS-25 in docs/development/style-guide.md, mined from PR #4175.
Prefer the file-and-directory module style: put logic and submodule
declarations in `foo.rs` with submodules under `foo/` (Rust supports both
coexisting) — that is how all legacy violations were resolved. If you keep
diff --git a/rules/ast-grep/rust-no-axum-extension-param.yml b/rules/ast-grep/rust-no-axum-extension-param.yml
index 2837e1e80d..92836a9f0f 100644
--- a/rules/ast-grep/rust-no-axum-extension-param.yml
+++ b/rules/ast-grep/rust-no-axum-extension-param.yml
@@ -3,7 +3,7 @@ language: rust
severity: warning
message: Axum handlers should take shared services via State, not Extension.
note: |-
- Rule CS-30 in docs/STYLE_GUIDE.md. Recent reviews enforce
+ Rule CS-30 in docs/development/style-guide.md. Recent reviews enforce
State for shared services (PR #4556); attach cross-cutting services to the
owning domain service rather than wiring them at the router layer (CS-31,
PR #4572). ~200 legacy uses exist — don't add new ones.
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
index 952816e962..1a881635b3 100644
--- a/rules/ast-grep/ts-feature-components-presentational.yml
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -5,7 +5,7 @@ language: typescript
severity: warning
message: Feature components take resolved values and return JSX. Data, reactivity wiring, and navigation belong to primitives/ and views/.
note: |-
- Rule FE-33 in docs/STYLE_GUIDE.md. `components/` never imports
+ Rule FE-33 in docs/development/style-guide.md. `components/` never imports
`queries/`, `primitives/`, `views/`, `@queries/*`, urql, or the split
navigation helpers. It renders what views hand it: domain values from
`core/`, resolved display (typed in `context/`), and event handlers. The
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
index 3789eb0ceb..0ae28093c5 100644
--- a/rules/ast-grep/ts-feature-core-pure.yml
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -5,7 +5,7 @@ language: typescript
severity: warning
message: Feature core modules stay pure TypeScript — no Solid, urql, queries, generated GraphQL, app modules, or sibling layers.
note: |-
- Rule FE-33 in docs/STYLE_GUIDE.md. `core/` owns the feature's vocabulary
+ Rule FE-33 in docs/development/style-guide.md. `core/` owns the feature's vocabulary
and the functions that describe, group, and summarize it. Wire types,
clients, reactivity, and UI stay outside so a schema rename or a
framework upgrade cannot churn core tests. Decode lives in `queries/`,
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
index 32b8e42ea2..a9fae4dcfc 100644
--- a/rules/ast-grep/ts-feature-data-no-ui.yml
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -5,7 +5,7 @@ language: typescript
severity: warning
message: Feature queries/ and primitives/ never import components, views, or UI primitives. They produce data and view-state; views render it.
note: |-
- Rule FE-33 in docs/STYLE_GUIDE.md. `queries/` adapts wire types and
+ Rule FE-33 in docs/development/style-guide.md. `queries/` adapts wire types and
builds query factories; `primitives/` consumes feature-owned capabilities
to produce state and actions with Solid primitives but no JSX. Test adapters
with fake clients and controllers with fake capabilities; neither imports
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
index 0a784cedd1..817fa1586f 100644
--- a/rules/ast-grep/ts-feature-layers-use-context.yml
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -5,7 +5,7 @@ language: typescript
severity: warning
message: Supply app capabilities through feature-owned contracts; construct production adapters at the feature root.
note: |-
- Rule FE-33 in docs/STYLE_GUIDE.md. Inside a layered feature, `queries/`,
+ Rule FE-33 in docs/development/style-guide.md. Inside a layered feature, `queries/`,
`primitives/`, `components/`, and `views/` never import the app's singletons
or context hooks (GraphQL soup client, user context, display names,
entity display, openDocument, PostHog). Those arrive through the
diff --git a/rules/ast-grep/ts-no-item-type-cast.yml b/rules/ast-grep/ts-no-item-type-cast.yml
index 995f032133..26a8b409e5 100644
--- a/rules/ast-grep/ts-no-item-type-cast.yml
+++ b/rules/ast-grep/ts-no-item-type-cast.yml
@@ -5,7 +5,7 @@ language: typescript
severity: error
message: Don't cast to ItemType — parse the string with stringToItemType from @service-storage/client.
note: |-
- Rule FE-31 in docs/STYLE_GUIDE.md. Entity-type strings arrive in several
+ Rule FE-31 in docs/development/style-guide.md. Entity-type strings arrive in several
stored spellings (email threads alone are `email`, `thread`, and
`email_thread`), so a cast smuggles a value no preview fetcher handles.
stringToItemType in src/lib/service-clients/service-storage/itemType.ts is
diff --git a/rules/ast-grep/ts-no-service-client-outside-queries.yml b/rules/ast-grep/ts-no-service-client-outside-queries.yml
index d8ac27e105..4b8010ea63 100644
--- a/rules/ast-grep/ts-no-service-client-outside-queries.yml
+++ b/rules/ast-grep/ts-no-service-client-outside-queries.yml
@@ -5,7 +5,7 @@ language: typescript
severity: warning
message: Don't import a service client outside the queries package — wrap the call in a query/mutation under queries/ and import that instead.
note: |-
- Rule FE-01 in docs/STYLE_GUIDE.md (also apps/web/AGENTS.md, General). UI code
+ Rule FE-01 in docs/development/style-guide.md (also apps/web/AGENTS.md, General). UI code
calling an endpoint directly is usually re-fetching data an existing query
already caches, and it bypasses the cache seeding / invalidation the query
layer owns. Add (or reuse) a query or mutation in src/lib/queries (shared)
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
index 2ed34fed53..ce5fafca9b 100644
--- a/rules/ast-grep/tsx-feature-components-presentational.yml
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -5,7 +5,7 @@ language: tsx
severity: warning
message: Feature components take resolved values and return JSX. Data, reactivity wiring, and navigation belong to primitives/ and views/.
note: |-
- Rule FE-33 in docs/STYLE_GUIDE.md. `components/` never imports
+ Rule FE-33 in docs/development/style-guide.md. `components/` never imports
`queries/`, `primitives/`, `views/`, `@queries/*`, urql, or the split
navigation helpers. It renders what views hand it: domain values from
`core/`, resolved display (typed in `context/`), and event handlers. The
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
index 124415ab0b..4a29b665c8 100644
--- a/rules/ast-grep/tsx-feature-core-pure.yml
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -5,7 +5,7 @@ language: tsx
severity: warning
message: Feature core modules stay pure TypeScript — no Solid, urql, queries, generated GraphQL, app modules, or sibling layers.
note: |-
- Rule FE-33 in docs/STYLE_GUIDE.md. `core/` owns the feature's vocabulary
+ Rule FE-33 in docs/development/style-guide.md. `core/` owns the feature's vocabulary
and the functions that describe, group, and summarize it. Wire types,
clients, reactivity, and UI stay outside so a schema rename or a
framework upgrade cannot churn core tests. Decode lives in `queries/`,
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
index 0f9ef0bba0..9f63ba2c75 100644
--- a/rules/ast-grep/tsx-feature-data-no-ui.yml
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -5,7 +5,7 @@ language: tsx
severity: warning
message: Feature queries/ and primitives/ never import components, views, or UI primitives. They produce data and view-state; views render it.
note: |-
- Rule FE-33 in docs/STYLE_GUIDE.md. `queries/` adapts wire types and
+ Rule FE-33 in docs/development/style-guide.md. `queries/` adapts wire types and
builds query factories; `primitives/` consumes feature-owned capabilities
to produce state and actions with Solid primitives but no JSX. Test adapters
with fake clients and controllers with fake capabilities; neither imports
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
index eb48b11366..d7cc83994f 100644
--- a/rules/ast-grep/tsx-feature-layers-use-context.yml
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -5,7 +5,7 @@ language: tsx
severity: warning
message: Supply app capabilities through feature-owned contracts; construct production adapters at the feature root.
note: |-
- Rule FE-33 in docs/STYLE_GUIDE.md. Inside a layered feature, `queries/`,
+ Rule FE-33 in docs/development/style-guide.md. Inside a layered feature, `queries/`,
`primitives/`, `components/`, and `views/` never import the app's singletons
or context hooks (GraphQL soup client, user context, display names,
entity display, openDocument, PostHog). Those arrive through the
diff --git a/rules/ast-grep/tsx-no-class-string-consts.yml b/rules/ast-grep/tsx-no-class-string-consts.yml
index 936cd7bc0d..48f00e3b6e 100644
--- a/rules/ast-grep/tsx-no-class-string-consts.yml
+++ b/rules/ast-grep/tsx-no-class-string-consts.yml
@@ -3,7 +3,7 @@ language: tsx
severity: warning
message: Don't hoist Tailwind class strings into named constants — shared markup+styling is a component, not a string.
note: |-
- Rule FE-30 in docs/STYLE_GUIDE.md. A named class-string constant
+ Rule FE-30 in docs/development/style-guide.md. A named class-string constant
(`const DAY_CELL_CLASS = 'aspect-square w-full shrink-0'`) is a
component's render detail leaking into module scope: it can't carry
structure, props, or behavior, and every consumer re-implements the
diff --git a/rules/ast-grep/tsx-no-cursor-pointer.yml b/rules/ast-grep/tsx-no-cursor-pointer.yml
index 29c4e82600..5f2e52f0b7 100644
--- a/rules/ast-grep/tsx-no-cursor-pointer.yml
+++ b/rules/ast-grep/tsx-no-cursor-pointer.yml
@@ -3,7 +3,7 @@ language: tsx
severity: warning
message: Don't add cursor-pointer to clickable elements.
note: |-
- Rule FE-27 in docs/STYLE_GUIDE.md (also apps/web/AGENTS.md, Styling). The
+ Rule FE-27 in docs/development/style-guide.md. The
app deliberately does not use pointer cursors on clickable elements.
files:
- apps/web/**
diff --git a/rules/ast-grep/tsx-no-item-type-cast.yml b/rules/ast-grep/tsx-no-item-type-cast.yml
index d3bd0eedd3..caed64ab4d 100644
--- a/rules/ast-grep/tsx-no-item-type-cast.yml
+++ b/rules/ast-grep/tsx-no-item-type-cast.yml
@@ -5,7 +5,7 @@ language: tsx
severity: error
message: Don't cast to ItemType — parse the string with stringToItemType from @service-storage/client.
note: |-
- Rule FE-31 in docs/STYLE_GUIDE.md. Entity-type strings arrive in several
+ Rule FE-31 in docs/development/style-guide.md. Entity-type strings arrive in several
stored spellings (email threads alone are `email`, `thread`, and
`email_thread`), so a cast smuggles a value no preview fetcher handles.
stringToItemType in src/lib/service-clients/service-storage/itemType.ts is
diff --git a/rules/ast-grep/tsx-no-raw-tailwind-palette.yml b/rules/ast-grep/tsx-no-raw-tailwind-palette.yml
index ba193b7f09..0b6320e479 100644
--- a/rules/ast-grep/tsx-no-raw-tailwind-palette.yml
+++ b/rules/ast-grep/tsx-no-raw-tailwind-palette.yml
@@ -3,7 +3,7 @@ language: tsx
severity: error
message: Raw Tailwind palette classes are disabled in @theme and render NOTHING. Use semantic color tokens.
note: |-
- Rule FE-25 in docs/STYLE_GUIDE.md. The default palette is reset via
+ Rule FE-25 in docs/development/style-guide.md. The default palette is reset via
`--color-*: initial` in apps/web/src/index.css, so classes like
`text-red-500` silently produce no CSS. Use semantic tokens instead:
failure/failure-bg/failure-ink, success-*, alert-*, accent, ink-muted, etc.
diff --git a/rules/ast-grep/tsx-no-service-client-outside-queries.yml b/rules/ast-grep/tsx-no-service-client-outside-queries.yml
index bcb246d7cc..1bd23152c7 100644
--- a/rules/ast-grep/tsx-no-service-client-outside-queries.yml
+++ b/rules/ast-grep/tsx-no-service-client-outside-queries.yml
@@ -5,7 +5,7 @@ language: tsx
severity: warning
message: Don't import a service client outside the queries package — wrap the call in a query/mutation under queries/ and import that instead.
note: |-
- Rule FE-01 in docs/STYLE_GUIDE.md (also apps/web/AGENTS.md, General). UI code
+ Rule FE-01 in docs/development/style-guide.md (also apps/web/AGENTS.md, General). UI code
calling an endpoint directly is usually re-fetching data an existing query
already caches, and it bypasses the cache seeding / invalidation the query
layer owns. Add (or reuse) a query or mutation in src/lib/queries (shared)
diff --git a/services/agent_harness_service/AGENTS.md b/services/agent_harness_service/AGENTS.md
new file mode 100644
index 0000000000..0fe89e03e6
--- /dev/null
+++ b/services/agent_harness_service/AGENTS.md
@@ -0,0 +1,56 @@
+# agent_harness_service
+
+## What it is
+
+Part of the agent sessions feature — the composition root for coding-agent
+sessions: agent-session trigger events in, sandboxed coding agent sessions
+(Daytona containers or the in-process ACP runtime) out.
+
+## Start here
+
+- `src/main.rs`: composition root — builds Postgres repositories, the
+ container manager, channel/session services, and wires
+ `macro.channels`-derived triggers into `macro.agent_sessions`.
+- `src/api.rs`: the full agent-session HTTP API (durable metadata/log reads
+ plus live in-memory transport operations), composed from each domain
+ crate's own router (`agent_session`, `agent_changes`, `agent_egress`,
+ `agent_harness`).
+- `src/model_providers/`: per-harness runtime adapters — `cursor.rs`,
+ `macrod.rs`, `in_memory.rs`.
+- `src/containers.rs`: Daytona sandbox lifecycle; local Docker opt-in.
+- `src/trigger.rs`: turns channel/webhook triggers into sessions.
+- `src/internal_mcp.rs`: the internal MCP server exposed to running sessions.
+
+## Scope
+
+- Owns: the deployed process wiring every agent-session domain crate
+ together — not the domain logic itself, which lives in `crates/agent_harness`,
+ `crates/agent_session`, `crates/agent_changes`, `crates/agent_egress`,
+ `crates/folds/agent_fold`, `crates/agent_inmem`, `crates/agent_trigger`.
+- Not here: coding-agent business logic for a specific runtime (e.g. Cursor
+ API calls) → `crates/codex_connection`, `crates/codex_cloud_agents`.
+
+## Recipes
+
+- Add a new agent-session route: the owning domain crate's `inbound::axum_router`
+ → mount it in `src/api.rs`.
+- Add a new model/runtime provider: `src/model_providers/<provider>.rs` →
+ `src/model_providers/mod.rs` → wire into `src/main.rs`.
+- Inspect a session's protocol log: `just session-log <channel_id>`.
+
+## Checks
+
+- `cargo test -p agent_harness_service` (`SQLX_OFFLINE` unset).
+- `just check` (`SQLX_OFFLINE=true cargo check`).
+- `just run-local` — needs `DAYTONA_API_KEY`, `DAYTONA_SNAPSHOT`,
+ `GITHUB_TOKEN` in the environment or a local `.env`.
+
+## Gotchas
+
+- Two managed bots run on different runtimes: `@coder` (`HARNESS_BOT_ID`) in a
+ Daytona sandbox, `@macro-new`/`@macro` (`INMEM_BOT_ID`) on the in-process ACP
+ runtime — check which one a bug report is about before debugging containers.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/config-and-service-urls.md`
diff --git a/services/agent_harness_service/CLAUDE.md b/services/agent_harness_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/agent_harness_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/ai-editing-worker/AGENTS.md b/services/ai-editing-worker/AGENTS.md
new file mode 100644
index 0000000000..4bb286d011
--- /dev/null
+++ b/services/ai-editing-worker/AGENTS.md
@@ -0,0 +1,59 @@
+# ai-editing-worker
+
+## What it is
+
+Part of Documents' AI editing feature — a Cloudflare Worker that joins a
+document as a real Loro collaboration peer and streams AI-driven edits
+through it. `AI_EDITING.md` has the full flow (interpreter/supervisor/writer
+agents, the QuickJS sandbox → `DocumentOp[]` → animation pipeline). Read it
+before touching the edit flow.
+
+## Start here
+
+- `src/index.ts` / `src/endpoints/index.ts`: the hono app and route table
+ (`POST /edit` and friends).
+- `src/run-edit.ts`: `runEditSession` — joins the sync-service WebSocket,
+ drives the agents, flushes commits back.
+- `src/ai-editing/`: the agent loop, prompts, tools, and op queue.
+- `src/endpoints/`: one file per surface — `edit.ts`, `docx.ts`, `forms.ts`,
+ `spreadsheet.ts`, `comment-mark.ts`.
+- `src/sandbox.ts` / `scripts/generate-sandbox.ts`: the QuickJS sandbox the
+ model's generated code runs in (regenerated by `prebuild`, not hand-edited).
+
+## Scope
+
+- Owns: the AI document-editing session (joining the doc, agent orchestration,
+ applying edits), DOCX/forms/spreadsheet AI endpoints, and comment-mark anchoring.
+- Not here: the Loro/sync-service wire protocol itself, shared with the web
+ app via `@macro-inc/collaboration`; browser auth and sync HTTP policy stay
+ in `apps/web`.
+
+## Recipes
+
+- Add or change a prompt section: `src/ai-editing/prompts/index.ts` composes
+ `GROUND_RULES`, `TEAM`, `EDITING_RULES`, `API_COMPLETE`, plus one role file
+ per agent — put a rule in the one shared section both roles need, not in
+ both role files.
+- Add a new AI editing endpoint: `src/endpoints/<name>.ts` → register in
+ `src/endpoints/index.ts`.
+- Change the sandboxed edit API: `src/ai-editing/doc/` or `src/ai-editing/editor/`
+ → `scripts/generate-sandbox.ts` (regenerates `src/editor-sandbox-code.ts`).
+
+## Checks
+
+- `bun run type-check` (`tsc --noEmit`).
+- `bunx vitest run` for most unit tests (co-located `*.test.ts`); spreadsheet
+ has its own configs: `bun run test:spreadsheet` and
+ `bun run test:spreadsheet:integration`.
+- `just dev` for `wrangler dev --env local`. (`just dev-local` points at a
+ `src/server.ts` that no longer exists.)
+
+## Gotchas
+
+- This worker never deploys without explicit approval — `just deploy-dev` /
+ `deploy-prod` run `generate-sandbox` first; don't run them unprompted.
+
+## Related
+
+- Docs: `services/ai-editing-worker/AI_EDITING.md`,
+ `services/ai-editing-worker/src/spreadsheet/README.md`
diff --git a/services/ai-editing-worker/CLAUDE.md b/services/ai-editing-worker/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/ai-editing-worker/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/ai_projections_refresh_handler/AGENTS.md b/services/ai_projections_refresh_handler/AGENTS.md
new file mode 100644
index 0000000000..8f2d959844
--- /dev/null
+++ b/services/ai_projections_refresh_handler/AGENTS.md
@@ -0,0 +1,39 @@
+# ai_projections_refresh_handler
+
+## What it is
+
+Part of the AI projections feature (cached AI-generated views of a user's
+data, e.g. a dashboard widget) — a scheduled Lambda that sweeps
+`ai_projection` instances for one refresh cadence: deletes inactive ones and
+enqueues a refresh for stale ones.
+
+## Start here
+
+- `src/event.rs`: `RefreshCadence` and the EventBridge payload shape (a
+ constant `{"refresh_cadence":"high"}` per scheduled rule — not the usual
+ EventBridge envelope).
+- `src/refresh.rs`: the whole sweep — delete/claim decision rules in the module
+ doc comment, all SQL lives here.
+- `src/main.rs`: composition root (db pool, SQS client, `context::Context`).
+
+## Scope
+
+- Owns: the periodic sweep deciding delete/refresh/leave for
+ `user_ai_projection` rows and enqueuing refresh messages via
+ `macro_queues::AiProjectionQueue`.
+- Not here: materializing a projection's result — that's the queue consumer.
+
+## Recipes
+
+- Change delete/refresh thresholds or add a decision rule: `src/refresh.rs`
+ (SQL + doc comment) → `src/refresh/test.rs`.
+- Add a field to the EventBridge payload: `src/event.rs` → the EventBridge rule
+ definition in `infra/`.
+
+## Checks
+
+- `cargo test -p ai_projections_refresh_handler` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md`
diff --git a/services/ai_projections_refresh_handler/CLAUDE.md b/services/ai_projections_refresh_handler/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/ai_projections_refresh_handler/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/authentication_service/AGENTS.md b/services/authentication_service/AGENTS.md
new file mode 100644
index 0000000000..a342cfa223
--- /dev/null
+++ b/services/authentication_service/AGENTS.md
@@ -0,0 +1,59 @@
+# authentication_service
+
+## What it is
+
+Account sign-in and identity feature: FusionAuth-backed login, session/JWT
+issuance, signup policy and allowlisting, OAuth/OAuth2 account linking
+(Google/Microsoft/GitHub), subscription checkout status, Cursor/Codex API
+key issuance, and account merge/link flows.
+
+## Start here
+
+- `src/api.rs`: route module list (`login`, `oauth`, `oauth2`, `session`,
+ `jwt`, `webhooks`, `signup_policy`, `codex`, `cursor_api_key`, `merge`, ...).
+- `src/service/signup_policy/`: `SignupPolicy` built at startup; enforced
+ authoritatively by the FusionAuth `user.create` webhook
+ (`src/api/webhooks`), not by the public precheck routes.
+- `src/config.rs` + `src/doppler_config.rs`: env vars and the Doppler config
+ validator binary (`authentication_service_doppler_config`).
+- `README.md`: the Develop signup allowlist (bypass flag, rollout/rollback
+ steps) and GTM invite links — read before touching signup policy.
+
+## Scope
+
+- Owns: FusionAuth-backed login/session issuance, JWT minting, signup
+ allowlisting, OAuth/OAuth2 account linking, GTM invite links, shared-mailbox
+ relocation signup, Cursor/Codex API key endpoints.
+- Not here: authorization/permission decisions on other entities →
+ `crates/macro_authorization`; subscription/billing logic itself →
+ `crates/ai_billing`, `crates/initiative`.
+
+## Recipes
+
+- Add a route: domain crate (if any) → `src/api/<area>.rs` → `src/api.rs`
+ (router) → `src/openapi.rs`.
+- Change signup policy: `src/service/signup_policy/` → `src/config.rs` → the
+ Develop allowlist rollout steps in `README.md`.
+- Add a config value: `src/config.rs` → Doppler project
+ `authentication-service` → verify with
+ `authentication_service_doppler_config`.
+
+## Checks
+
+- `cargo test -p authentication_service` (`SQLX_OFFLINE` unset).
+- Signup-policy changes specifically:
+ `env -u DATABASE_URL cargo test -p authentication_service --bin authentication_service config::test`
+ and `cargo run -p authentication_service --bin authentication_service_doppler_config`.
+
+## Gotchas
+
+- The signup allowlist has a temporary Develop-only bypass
+ (`DEVELOPMENT_BYPASS_SIGNUP_ALLOWLIST`) that overrides the allowlist even
+ when present; see `README.md` before changing signup behavior.
+- Denial responses and policy errors must never disclose configured allowlist
+ addresses; never paste operational addresses into code, logs, or docs.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md`,
+ `.agents/rules/rust/security.md` · Skill: `new-service`
diff --git a/services/authentication_service/CLAUDE.md b/services/authentication_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/authentication_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/calendar_service/AGENTS.md b/services/calendar_service/AGENTS.md
new file mode 100644
index 0000000000..9a3e95ed29
--- /dev/null
+++ b/services/calendar_service/AGENTS.md
@@ -0,0 +1,54 @@
+# calendar_service
+
+## What it is
+
+Calendar feature: deployable service hosting Google Calendar sync,
+user-initiated calendar mutations, and calendar scheduling behind the
+gateway `/calendar` prefix.
+
+## Start here
+
+- `src/main.rs`: composition root — config, db/redis, event broker, workers, router.
+- `src/api.rs` + `src/api/context.rs`: HTTP surface and shared `ApiContext`.
+- `src/calendar_backfill.rs` + `src/backfill_queue.rs`: SQS backfill consumer.
+- `src/calendar_outbox.rs`: sync scheduler and outbox drain loop.
+
+## Scope
+
+- Owns: the Google Calendar push webhook, calendar mutation routes, calendar
+ sync scheduling/outbox, and the backfill queue worker.
+- Not here: calendar domain logic and the Postgres/Google adapters →
+ `crates/calendar_events`, `crates/calendar_scheduling`.
+
+## Boundaries
+
+- Depends on: `calendar_events`, `calendar_scheduling` (domain crates owning
+ the Postgres/Google adapters), `connection_gateway_client`,
+ `authentication_service_client`, `macro_authorization`, `macro_service_urls`.
+- Used by: the web app and SDK calendar clients, through the gateway.
+
+## Recipes
+
+- Add a mutation route: `crates/calendar_events` (domain + Postgres adapter) →
+ `src/api/context.rs` → `src/api.rs` (router) → `src/openapi.rs`.
+- Add a backfill step: `src/calendar_backfill.rs` → `src/calendar_backfill_adapters.rs`
+ → `src/backfill_queue.rs`.
+- Add a config value: `src/config.rs` → Doppler (`calendar-service` project) →
+ `tooling/xtask/crates/xtask_local/src/local/local_env.rs` for `--no-doppler`.
+
+## Checks
+
+- `cargo test -p calendar_service` (`SQLX_OFFLINE` unset).
+- `curl http://localhost:8088/health` after `just run_local` or `just stack up`.
+
+## Gotchas
+
+- The router is mounted at both `/` and `/calendar` (`GATEWAY_PATH_PREFIX` in
+ `src/api.rs`) because the gateway forwards the path unchanged.
+- Reauth-required notifications ride the shared `LinkManagerQueue`, consumed by
+ `email_service`; don't add a second calendar-specific reconnect notification.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md` · Skill: `new-service` ·
+ Docs: `docs/guides/new-service.md` (uses this service as the model)
diff --git a/services/calendar_service/CLAUDE.md b/services/calendar_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/calendar_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/call_recording_preview_handler/AGENTS.md b/services/call_recording_preview_handler/AGENTS.md
new file mode 100644
index 0000000000..2e887737b7
--- /dev/null
+++ b/services/call_recording_preview_handler/AGENTS.md
@@ -0,0 +1,40 @@
+# call_recording_preview_handler
+
+## What it is
+
+Calls feature: S3-triggered Lambda that generates a JPEG preview thumbnail
+for a call recording MP4, using ffmpeg/ffprobe.
+
+## Start here
+
+- `src/event.rs`: the S3 event handler — decides whether to process, probes
+ duration, extracts a midpoint frame, uploads the preview.
+- `src/key.rs`: pure key-decision logic (`KeyDecision`/`SkipReason`) for which
+ S3 keys are eligible — read this before changing what counts as "a call
+ recording".
+- `src/ffmpeg.rs`: `FfmpegTools` wrapper around the `ffmpeg`/`ffprobe`
+ subprocesses, with a timeout and a frame-extraction fallback.
+- `scripts/package-ffmpeg.sh`: bundles static ffmpeg/ffprobe binaries into the
+ Lambda zip at build time — the binaries aren't a Cargo dependency.
+
+## Scope
+
+- Owns: deciding which uploaded `calls/.../*.mp4` objects need a
+ `PREVIEW.jpg`, and producing it.
+
+## Recipes
+
+- Change which uploads get previews: `src/key.rs` → `src/key/test.rs`.
+- Change frame extraction (timing, fallback, timeout): `src/ffmpeg.rs` →
+ `src/ffmpeg/test.rs`.
+
+## Checks
+
+- `cargo test -p call_recording_preview_handler` (`SQLX_OFFLINE` unset).
+- `just build` packages ffmpeg via `scripts/package-ffmpeg.sh`; a local
+ `cargo build` alone won't produce a deployable zip.
+
+## Gotchas
+
+- `#![deny(missing_docs)]` in `src/lib.rs` — every new public item needs a doc
+ comment.
diff --git a/services/call_recording_preview_handler/CLAUDE.md b/services/call_recording_preview_handler/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/call_recording_preview_handler/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/coding-agent-worker/AGENTS.md b/services/coding-agent-worker/AGENTS.md
new file mode 100644
index 0000000000..ce71dadaa5
--- /dev/null
+++ b/services/coding-agent-worker/AGENTS.md
@@ -0,0 +1,54 @@
+# coding-agent-worker
+
+## What it is
+
+Agent sessions feature: Bun/Hono service that boots a sandboxed container
+running a coding agent (opencode) and relays ACP frames between it and
+`agent_proxy`, triggered by a `start_agent_session <repo-url> [prompt...]`
+chat message.
+
+## Start here
+
+- `index.ts`: webhook ingress — matches the trigger message, resolves the repo,
+ kicks off a session.
+- `src/session.ts`: `SessionRouter` — relays ACP frames verbatim between the
+ sandbox's websocket and `UpstreamLink`. This worker never speaks ACP itself;
+ `agent_proxy` owns the ACP session and handshake.
+- `src/provision.ts`: the idempotent script that turns a booted container into
+ a ready sandbox (clone repo, start the sidecar). Coupled to the container
+ image (`container/Dockerfile`), not to any provider.
+- `src/providers/daytona.ts`: the current `CommandRunner`/`AgentSandbox`
+ implementation (Daytona). Add a new provider by implementing `interfaces.ts`.
+- `src/webhook.ts`: registers/repairs the Macro webhook subscription
+ (`message.posted`) via `@macro-inc/sdk`.
+- `container/`: the Dockerfile and flake baking the dev shell + opencode
+ sidecar into the sandbox image.
+
+## Scope
+
+- Owns: provisioning sandboxes, relaying ACP frames, and the chat trigger that
+ starts a session.
+- Not here: the ACP protocol/session semantics themselves → `agent_proxy`; the
+ Rust-side agent runtime protocol types → `crates/agent_runtime_protocol`
+ (regenerate `src/protocol/generated.ts` from there, don't hand-edit it).
+
+## Recipes
+
+- Add a sandbox provider: implement `CommandRunner`/`AgentSandbox` from
+ `src/interfaces.ts` → wire it in `src/session.ts`.
+- Regenerate protocol types after a Rust change:
+ `just gen-protocol` (runs `cargo run -p agent_runtime_protocol --bin export_types`).
+- Change the container image: `container/Dockerfile` → `just build-image`.
+
+## Checks
+
+- `just typecheck` (`bunx tsc --noEmit`).
+- `bun test` for `src/*.test.ts` (`src/upstream.test.ts`, `src/provision.test.ts`).
+
+## Gotchas
+
+- `src/protocol/generated.ts` is generated from Rust Specta types; never
+ hand-edit it — rerun `just gen-protocol`.
+- `assertSafeRepoUrl` in `src/provision.ts` is the only guard against shell
+ injection into the provisioning script; any new provisioning step that
+ interpolates untrusted strings needs the same care.
diff --git a/services/coding-agent-worker/CLAUDE.md b/services/coding-agent-worker/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/coding-agent-worker/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/connection_gateway/AGENTS.md b/services/connection_gateway/AGENTS.md
new file mode 100644
index 0000000000..2975e6ae05
--- /dev/null
+++ b/services/connection_gateway/AGENTS.md
@@ -0,0 +1,56 @@
+# connection_gateway
+
+## What it is
+
+Shared infrastructure: manages per-entity WebSocket connections so other
+services can push messages to a specific connected entity without holding
+the socket themselves.
+
+## Start here
+
+- `src/api/connection.rs`: WebSocket upgrade endpoint and connection lifecycle.
+- `src/api/message.rs`: HTTP endpoint other services call to send a message to
+ a connected entity.
+- `src/service/connection.rs` + `src/service/dynamodb.rs`: connection registry,
+ backed by DynamoDB (tracks which entity is on which instance).
+- `src/service/sender.rs` + `src/service/redis.rs`: cross-instance message
+ relay (Redis pub/sub) so a send reaches a connection on another instance.
+- `scripts/stale_connections.rs` (`stale_connections` bin): scans DynamoDB for
+ connections past the 60s timeout; `README.md` has usage.
+
+## Scope
+
+- Owns: WebSocket connection tracking and message delivery to a connected
+ entity, across instances.
+- Not here: the message/event payloads themselves, or who is authorized to
+ send to whom — callers decide that before calling in.
+
+## Boundaries
+
+- Depends on: `connection_gateway_models`, `macro_authorization`.
+- Used by: nearly every other service, through `connection_gateway_client`
+ (document_storage_service, document_cognition_service, email_service,
+ calendar_service, agent_harness_service, mcp_service, scheduled_action,
+ agent_trigger_service, preview_gateway, and domain crates like `channels`,
+ `messages`, `databases`, `ai_tools`).
+
+## Recipes
+
+- Add a message/event type sendable over the gateway: `src/model/message.rs` →
+ `src/api/message.rs` → `connection_gateway_client` (the crate callers use).
+- Debug/clean stale connections: `scripts/stale_connections.rs` (see `README.md`).
+
+## Checks
+
+- `cargo test -p connection_gateway` (`SQLX_OFFLINE` unset).
+- `cargo run --features local_auth` then connect on port 8085 (see `README.md`).
+
+## Gotchas
+
+- A send can target a connection on a different instance — it always goes
+ through the Redis relay in `src/service/redis.rs`, never a direct in-process
+ lookup; don't bypass it when adding a new send path.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md`
diff --git a/services/connection_gateway/CLAUDE.md b/services/connection_gateway/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/connection_gateway/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/contacts_service/AGENTS.md b/services/contacts_service/AGENTS.md
new file mode 100644
index 0000000000..5c2a0444f7
--- /dev/null
+++ b/services/contacts_service/AGENTS.md
@@ -0,0 +1,45 @@
+# contacts_service
+
+## What it is
+
+Contacts/CRM feature: thin composition root for the `contacts` domain
+crate — HTTP router, an SQS worker that ingests connection events, and an
+outbox worker that notifies `connection_gateway`.
+
+## Start here
+
+- `src/main.rs`: wires `contacts::domain::service::ContactsDomainService`,
+ `contacts::inbound::http::contacts_router`, and the SQS/outbox workers — the
+ actual logic lives in `crates/contacts`, not here.
+- `src/config.rs`: env vars and per-environment DB pool sizing.
+- `src/health.rs`: health check endpoint.
+
+## Scope
+
+- Owns: process startup, config, and composing `crates/contacts`'s
+ inbound/outbound adapters.
+- Not here: contact-matching/connection domain logic, repository queries, or
+ the gateway-notification adapter — all in `crates/contacts`
+ (`domain/service`, `outbound/repository`, `outbound/gateway`).
+
+## Recipes
+
+- Add an HTTP route: `crates/contacts` (`inbound/http`) → wired automatically
+ via `contacts_router` in `src/main.rs`.
+- Test the local SQS/outbox pipeline: `just create-localstack` → `just create-queue`
+ → `just sqs-worker` → `just sqs-test-message`.
+
+## Checks
+
+- `cargo test -p contacts_service` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `README.md` and the `just` recipes reference a `connections` table and a
+ `my-test-queue`/local-SQS workflow predating the current
+ `ContactsDomainService`/outbox design; treat them as a local-SQS smoke-test
+ recipe, not a description of the current schema.
+
+## Related
+
+- Domain crate: `crates/contacts`
diff --git a/services/contacts_service/CLAUDE.md b/services/contacts_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/contacts_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/convert_service/AGENTS.md b/services/convert_service/AGENTS.md
new file mode 100644
index 0000000000..ab08e9e8e2
--- /dev/null
+++ b/services/convert_service/AGENTS.md
@@ -0,0 +1,44 @@
+# convert_service
+
+## What it is
+
+Documents feature: converts uploaded Office documents (docx/xlsx/legacy
+Office formats) into Macro documents using LibreOfficeKit, triggered
+synchronously via HTTP or asynchronously via SQS.
+
+## Start here
+
+- `src/process/convert.rs` + `src/process/runner.rs`: the LibreOfficeKit
+ conversion pipeline and the SQS-driven worker loop.
+- `src/api/convert.rs`: the synchronous HTTP conversion endpoint.
+- `src/api/backfill.rs` + `helpers/backfill.ts`: backfilling existing documents
+ through conversion (bun script, hits the deployed gateway endpoint).
+- `src/main.rs`: `smoke_test_lok` — forks a child process at startup to verify
+ LibreOfficeKit's shared libraries load before accepting traffic.
+
+## Scope
+
+- Owns: office-document-to-Macro conversion and its worker/backfill paths.
+
+## Recipes
+
+- Change conversion behavior: `src/process/convert.rs` → `src/process/test.rs`.
+- Backfill existing documents: `helpers/backfill.ts` (`bun backfill`, needs
+ `BASE_URL`/`INTERNAL_API_KEY`/`LIMIT`/`OFFSET` — see `helpers/README.md`).
+- Load-test: `load-test/artillery.yml` (`artillery run artillery.yml`).
+
+## Checks
+
+- `cargo test -p convert_service` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Startup fails fast if LibreOfficeKit can't load (`smoke_test_lok`); a
+ conversion regression that looks like a code bug may actually be a missing
+ LOK shared library in the environment.
+- The `disable_cleanup`/`disable_worker`/`local_queue` Cargo features gate
+ local-dev behavior — don't assume they're enabled in deployed builds.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md`
diff --git a/services/convert_service/CLAUDE.md b/services/convert_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/convert_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/delete_chat_handler/AGENTS.md b/services/delete_chat_handler/AGENTS.md
new file mode 100644
index 0000000000..f55d51ed49
--- /dev/null
+++ b/services/delete_chat_handler/AGENTS.md
@@ -0,0 +1,42 @@
+# delete_chat_handler
+
+## What it is
+
+Chat feature: SQS-triggered Lambda that permanently deletes a chat once it
+has been marked deleted.
+
+## Start here
+
+- `src/handler.rs`: reads the `chat_id` SQS message attribute, checks
+ `is_chat_deleted`, then calls `delete_chat`. Expects exactly one record per
+ invocation (queue is configured for batch size 1).
+- `src/service/db/`: `delete_chat.rs` and `get_chat.rs` — the only DB queries
+ this lambda needs.
+
+## Scope
+
+- Owns: the final, permanent deletion of a chat already soft-deleted
+ elsewhere.
+- Not here: marking a chat deleted, or deleting other entity types →
+ `services/deleted_item_poller` (documents/projects/chats sweep that enqueues
+ this lambda).
+
+## Recipes
+
+- Change what deleting a chat cleans up: `src/service/db/delete_chat.rs`.
+
+## Checks
+
+- `cargo test -p delete_chat_handler` (`SQLX_OFFLINE` unset; requires local
+ MacroDB).
+- `nix develop --command just prepare_db` from the repo root after query changes (local Postgres on `localhost:5432`).
+
+## Gotchas
+
+- `handler.rs` hard-fails (returns `Err`) if the SQS batch doesn't contain
+ exactly one record — the queue's batch size is part of this lambda's
+ contract, not just an optimization.
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md`
diff --git a/services/delete_chat_handler/CLAUDE.md b/services/delete_chat_handler/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/delete_chat_handler/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/deleted_item_poller/AGENTS.md b/services/deleted_item_poller/AGENTS.md
new file mode 100644
index 0000000000..b6e782f5e2
--- /dev/null
+++ b/services/deleted_item_poller/AGENTS.md
@@ -0,0 +1,37 @@
+# deleted_item_poller
+
+## What it is
+
+Shared infrastructure: EventBridge-scheduled Lambda that sweeps users'
+deleted items (chats, documents, projects) older than 30 days and queues
+them for permanent deletion.
+
+## Start here
+
+- `src/handler.rs`: runs `handle_chats`, `handle_documents`, `handle_projects`
+ concurrently via `tokio::try_join!`; each publishes purge events through
+ `MacroEventBroker` (chats/documents) or queues deletion directly (projects).
+- `src/context.rs`: DB pool + event broker + queue clients.
+
+## Scope
+
+- Owns: finding items past the retention window and triggering their deletion
+ across chats, documents, and projects.
+- Not here: the actual permanent deletion of a chat →
+ `services/delete_chat_handler` (consumes the event this lambda publishes).
+
+## Recipes
+
+- Add a new deletable entity type: `src/handler.rs` (new `handle_<entity>`
+ joined into the `try_join!`) → its domain crate's purge event type → a
+ consumer lambda/worker.
+- Change the retention window: the domain crate's query
+ (`documents`/`chat`/`projects`), not this lambda.
+
+## Checks
+
+- `cargo test -p deleted_item_poller` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md`
diff --git a/services/deleted_item_poller/CLAUDE.md b/services/deleted_item_poller/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/deleted_item_poller/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/document_cognition_service/AGENTS.md b/services/document_cognition_service/AGENTS.md
new file mode 100644
index 0000000000..20ad11cadc
--- /dev/null
+++ b/services/document_cognition_service/AGENTS.md
@@ -0,0 +1,54 @@
+# document_cognition_service
+
+## What it is
+
+AI chat feature: deployable service (mounted at `/cognition` behind the
+gateway) hosting completions, streaming, tool selection, structured
+completion, citations, and chat/attachment management.
+
+## Start here
+
+- `src/api.rs`: route module list — `completions`, `stream`, `chats`,
+ `tool_selection`, `structured_completion`, `citations`, `attachments`,
+ `preview`, `context`, `id_mapping`.
+- `src/api/stream/chat_message.rs`: HTTP-POST-based chat streaming — replaces
+ the old WebSocket approach; delivery to clients goes through
+ `connection_gateway`, not this service's own socket.
+- `src/api/structured_completion.rs` and `src/api/tool_selection.rs`: the
+ structured-output and tool-selection completion paths used by `crates/agent`
+ and `crates/ai_tools`.
+- `src/service/ai_stream_registry.rs`: tracks in-flight streams so a stop
+ request (`stream/stop.rs`) can cancel the right one.
+- `README.md`: Doppler-based local setup (forking `document_cognition_service`
+ project configs, `just init_local_db`, `just debug`).
+
+## Scope
+
+- Owns: the HTTP surface for AI chat completions/streaming/tool-selection and
+ this service's own chat/attachment/context models.
+- Not here: agent orchestration logic, tool implementations, or AI billing —
+ `crates/agent`, `crates/ai_tools`, `crates/ai_toolset`, `crates/ai_billing`
+ (this service composes them).
+
+## Recipes
+
+- Add or change a completion/stream endpoint: the relevant `crates/ai_*` or
+ `crates/agent` logic → `src/api/<area>.rs` → `src/api.rs` (router) →
+ `src/openapi.rs`.
+- Add a config value: `src/config.rs` → Doppler project
+ `document_cognition_service` → `document_cognition_service_doppler_config`.
+- Debug a running stream: `just debug` (sets `RUST_LOG` for `document_cognition_service,ai,ai_tools,anthropic`),
+ `just log <since>`.
+
+## Checks
+
+- `cargo test -p document_cognition_service` (`SQLX_OFFLINE` unset; needs
+ MacroDB — `just run_dbs` from repo root).
+- After query changes: `nix develop --command just prepare_db` from the repo root.
+- Swagger validity: `npx @apidevtools/swagger-cli validate "http://localhost:8084/api-doc/openapi.json"`
+ with the service running.
+
+## Related
+
+- Skills: `debug-service`, `live-debug` · Rules: `.agents/rules/rust/db.md`,
+ `.agents/rules/observability.md`
diff --git a/services/document_cognition_service/CLAUDE.md b/services/document_cognition_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/document_cognition_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/document_storage_service/AGENTS.md b/services/document_storage_service/AGENTS.md
new file mode 100644
index 0000000000..699d4aec17
--- /dev/null
+++ b/services/document_storage_service/AGENTS.md
@@ -0,0 +1,60 @@
+# document_storage_service
+
+## What it is
+
+Documents feature: deployable service (DSS) hosting document/item CRUD, the
+"Soup" GraphQL API, and most cross-entity concerns — history, annotations,
+threads, pins, recents, notifications, folders, activity.
+
+## Start here
+
+- `src/api.rs`: route module list — `documents`, `items`, `entity`,
+ `folders_query`, `graphql_soup`, `threads`, `annotations`, `history`,
+ `pins`, `recents`, `notification`, `instructions`, `internal`.
+- `src/api/graphql_soup.rs`: the `/soup/graphql` (+ `/soup/graphql/ws`
+ subscriptions) GraphQL API — the frontend's main read path for Home/Recent/
+ search ("Soup" items); see `crates/graphql_soup` for resolvers/loaders.
+- `src/service/entity_mutation.rs`: generic entity-mutation plumbing used
+ across item types.
+- `src/service/delete_document_worker.rs`: background worker handling document
+ deletion side effects (feature-gated: `delete_document_worker`).
+- `src/service/conn_gateway.rs`: pushes realtime updates through
+ `connection_gateway` (feature-gated: `connection_gateway`).
+- `README.md`: local setup (`just run_dbs`, `.env` from `.env.sample`).
+
+## Scope
+
+- Owns: document/item HTTP CRUD, the Soup GraphQL schema, and cross-entity
+ surfaces (history, annotations, threads, pins, recents, notifications,
+ folders, saved views, activity).
+- Not here: document content/collaboration itself → `crates/collab_surface`
+ and the sync service; AI chat → `document_cognition_service`.
+
+## Recipes
+
+- Add a Soup GraphQL field: resolver/loader in `crates/graphql_soup` →
+ `src/api/graphql_soup.rs` if wiring changes.
+- Add a REST route: `src/api/<area>.rs` → `src/api.rs` (router) →
+ `src/openapi.rs`.
+- Add a config value or feature-gated behavior: `src/config.rs` → the
+ `[features]` table in `Cargo.toml` if it should be independently toggleable.
+
+## Checks
+
+- `cargo test -p document_storage_service` (`SQLX_OFFLINE` unset; needs
+ MacroDB + Redis — `just run_dbs` from repo root; DynamoDB local via
+ `just ensure::ensure_dynamodb`, see `justfile`).
+- After query changes: `nix develop --command just prepare_db` from the repo root.
+
+## Gotchas
+
+- Several behaviors are Cargo-feature-gated (`connection_gateway`,
+ `delete_document_worker`, `location_check`, all on by `default`) — a feature
+ disabled locally can hide a bug that only shows in deployed builds.
+- Soup GraphQL reads a replica with multi-second lag; a read immediately after
+ a write through the same request needs the primary-reading loader, not the
+ default one — see `crates/graphql_soup`.
+
+## Related
+
+- Rules: `.agents/rules/rust/db.md`, `.agents/rules/observability.md`
diff --git a/services/document_storage_service/CLAUDE.md b/services/document_storage_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/document_storage_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/document_text_extractor/AGENTS.md b/services/document_text_extractor/AGENTS.md
new file mode 100644
index 0000000000..1a1519d9e8
--- /dev/null
+++ b/services/document_text_extractor/AGENTS.md
@@ -0,0 +1,42 @@
+# document_text_extractor
+
+## What it is
+
+Documents feature: Lambda that extracts text and citations from uploaded
+documents (including PDF rendering via pdfium) and stores the result in
+MacroDB, feeding search and citations elsewhere.
+
+## Start here
+
+- `src/handler.rs` + `src/handler/extract_text_citations.rs`: the SQS/EventBridge
+ entry point and extraction logic.
+- `src/service/s3.rs`, `src/service/db.rs`: S3 fetch and Postgres write adapters.
+- `README.md`: local setup (cargo lambda, `.env`, sample invocations).
+
+## Scope
+
+- Owns: turning a stored document (PDF, etc.) into extracted plaintext/citations
+ and persisting it; skips unopenable PDFs and deleted documents rather than
+ retrying them.
+- Not here: the document upload pipeline itself → `document_upload_finalizer_handler`.
+
+## Recipes
+
+- Change extraction behavior: `src/handler/extract_text_citations.rs` →
+ `src/service/s3.rs` / `src/service/db.rs` as needed.
+- Add a field read from the document key: `src/model/key.rs`.
+
+## Checks
+
+- `cargo test -p document_text_extractor` (`SQLX_OFFLINE` unset; needs local
+ MacroDB — `just run_dbs`, `just initialize_dbs`).
+- `just services/document_text_extractor/build` from the repo root for the
+ deployable Lambda build (never build for deployment from this directory).
+
+## Gotchas
+
+- `pdfium-lib/` vendors the PDF rendering library; the `macos` feature switches
+ `cargo lambda watch` to a Mac-compatible pdfium build for local runs.
+- Build this crate's `local`/`local-extract` features only for local
+ iteration — the deployed binary is built via the `just ... /build` recipe,
+ not `cargo build` from this directory.
diff --git a/services/document_text_extractor/CLAUDE.md b/services/document_text_extractor/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/document_text_extractor/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/document_upload_finalizer_handler/AGENTS.md b/services/document_upload_finalizer_handler/AGENTS.md
new file mode 100644
index 0000000000..6b7e75473e
--- /dev/null
+++ b/services/document_upload_finalizer_handler/AGENTS.md
@@ -0,0 +1,50 @@
+# document_upload_finalizer_handler
+
+## What it is
+
+Documents feature: Lambda that finalizes a document upload after the object
+lands in S3 — resolves file type, upgrades legacy Office formats, and
+initializes markdown content.
+
+## Start here
+
+- `src/lib.rs`: module overview — production runs through the EventBridge
+ adapter, local dev through a LocalStack SQS poller; both normalize into
+ `app::ObjectCreated` and call the same use case.
+- `src/app.rs` + `src/app/tests.rs`: `DocumentUploadFinalizer` use case (hexagonal
+ core) and its tests.
+- `src/ports.rs`: inbound ports the use case depends on (`DocumentUploadMetadataPort`,
+ `DocumentObjectReader`).
+- `src/inbound/`: `eventbridge.rs` (prod), `local_sqs.rs` (local), `s3_notification.rs`.
+- `src/outbound.rs` + `src/outbound/tests.rs`: concrete adapters (S3, document ports).
+- `src/bin/local_worker.rs`: standalone binary for local SQS polling.
+
+## Scope
+
+- Owns: turning an S3 object-created event into a finalized document (file type
+ detection, legacy Office/`.xlsm` upgrade via `documents::domain::legacy_office_upgrade`,
+ markdown initialization).
+- Not here: text/citation extraction from the finalized document →
+ `document_text_extractor`; the docx-specific unzip/BOM pipeline →
+ `docx_unzip_handler`.
+
+## Boundaries
+
+- Depends on: `documents` (domain use cases/ports), `bots`, `lexical_client`,
+ `sync_service_client`, `entity_registry`/`entity_registry_db_utils`.
+- Used by: triggered by S3 `ObjectCreated` via EventBridge in production.
+
+## Recipes
+
+- Add a new upgraded office format: `s3_key::UpgradedOfficeFormat` →
+ `src/app.rs` (`upgraded_file_type`) → `documents::domain::legacy_office_upgrade`.
+- Change what counts as "finalized": `src/app.rs` (`DocumentUploadFinalizer`) →
+ `src/ports.rs` if a new capability is needed → `src/outbound.rs`.
+
+## Checks
+
+- `cargo test -p document_upload_finalizer_handler` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Skill: `new-service`
diff --git a/services/document_upload_finalizer_handler/CLAUDE.md b/services/document_upload_finalizer_handler/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/document_upload_finalizer_handler/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/docx_unzip_handler/AGENTS.md b/services/docx_unzip_handler/AGENTS.md
new file mode 100644
index 0000000000..14cc55a8f9
--- /dev/null
+++ b/services/docx_unzip_handler/AGENTS.md
@@ -0,0 +1,38 @@
+# docx_unzip_handler
+
+## What it is
+
+Documents feature: Lambda that unzips uploaded `.docx` files from S3 and
+converts their XML parts into a Bill Of Materials (BOM) stored in MacroDB.
+
+## Start here
+
+- `src/handler.rs`: S3 event entry point — loops over records, resolves bucket/key.
+- `src/service/document.rs`: pipeline — `unzip` → `process` (BOM parts) →
+ `upload_bom_parts`, with `handle_docx_unzip_failure` for error notification.
+- `README.md`: local setup, `make build`, and the manual invoke payload.
+
+## Scope
+
+- Owns: unzipping `.docx` archives and extracting their parts into the BOM
+ representation; notifying on unzip failure.
+- Not here: the upload-finalize step that triggers this (file type detection,
+ legacy format upgrade) → `document_upload_finalizer_handler`.
+
+## Recipes
+
+- Add a new BOM part type: `src/service/document/bom_parts.rs` (or sibling
+ module under `src/service/document/`) → `src/service/document.rs` re-export.
+- Change failure handling: `src/service/document/notify_docx_upload_job.rs`.
+
+## Checks
+
+- `cargo test -p docx_unzip_handler` (`SQLX_OFFLINE` unset; needs local MacroDB
+ — `just run_dbs`, `just initialize_dbs`, plus `CREATE EXTENSION IF NOT EXISTS
+ "uuid-ossp";` per the README's one-time setup).
+- `nix develop --command just prepare_db` from the repo root after schema/query changes, before `make build`.
+
+## Gotchas
+
+- Do not build this crate for deployment from this directory — use the repo's
+ Lambda build path (`make build` here targets the Lambda release artifact).
diff --git a/services/docx_unzip_handler/CLAUDE.md b/services/docx_unzip_handler/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/docx_unzip_handler/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/email_refresh_handler/AGENTS.md b/services/email_refresh_handler/AGENTS.md
new file mode 100644
index 0000000000..e9571eb17a
--- /dev/null
+++ b/services/email_refresh_handler/AGENTS.md
@@ -0,0 +1,24 @@
+# email_refresh_handler
+
+## What it is
+
+Email feature: Lambda, triggered hourly by EventBridge, that re-subscribes a
+slice of Gmail inboxes to push notifications (each inbox refreshed once per
+day) by enqueuing `LinkManagerMessage`s for `email_service` to process.
+
+## Start here
+
+- `src/handler.rs`: picks the due subset of email subscriptions and enqueues
+ refresh messages; `README.md` explains the once-per-day cadence.
+- `src/context.rs` / `src/config.rs`: DB pool and env setup.
+
+## Scope
+
+- Owns: selecting which Gmail subscriptions are due for a `users.watch` refresh
+ and publishing the SQS messages.
+- Not here: actually calling the Gmail `users.watch` endpoint → the
+ `LinkManagerQueue` consumer in `email_service` (`src/pubsub/link_manager`).
+
+## Checks
+
+- `cargo test -p email_refresh_handler` (`SQLX_OFFLINE` unset).
diff --git a/services/email_refresh_handler/CLAUDE.md b/services/email_refresh_handler/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/email_refresh_handler/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/email_scheduled_handler/AGENTS.md b/services/email_scheduled_handler/AGENTS.md
new file mode 100644
index 0000000000..9f3312e452
--- /dev/null
+++ b/services/email_scheduled_handler/AGENTS.md
@@ -0,0 +1,28 @@
+# email_scheduled_handler
+
+## What it is
+
+Email feature: Lambda, triggered every minute by EventBridge, that finds
+scheduled email drafts whose `send_time` has passed and publishes a
+`ScheduledPubsubMessage` per draft for `email_service` to actually send.
+
+## Start here
+
+- `src/handler.rs`: `fetch_pending_scheduled_messages` query + publish loop;
+ `README.md` explains the trigger cadence and the `scheduled_messages` table.
+
+## Scope
+
+- Owns: finding due scheduled sends and enqueuing them exactly once.
+- Not here: sending the email itself, or the enqueue-failure recovery path →
+ `email_service`'s scheduled message worker (`src/pubsub/scheduled`).
+
+## Checks
+
+- `cargo test -p email_scheduled_handler` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- #6617 reverted a "replay historical sends" change and #6580 fixed a send
+ stranded by a failed enqueue — read those commits before changing the
+ fetch/publish ordering (`git log -- services/email_scheduled_handler`).
diff --git a/services/email_scheduled_handler/CLAUDE.md b/services/email_scheduled_handler/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/email_scheduled_handler/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/email_service/AGENTS.md b/services/email_service/AGENTS.md
new file mode 100644
index 0000000000..d3c3bb32af
--- /dev/null
+++ b/services/email_service/AGENTS.md
@@ -0,0 +1,56 @@
+# email_service
+
+## What it is
+
+Email feature: deployable service hosting Gmail sync, email send/schedule/
+draft routes, calendar invitation handling, and contacts/CRM sync, behind
+the gateway `/email` prefix.
+
+## Start here
+
+- `src/main.rs` / `src/lib.rs`: entrypoint and `run()`.
+- `src/api.rs` + `src/api/context.rs`: HTTP surface and `ApiContext`.
+- `src/pubsub/`: SQS pubsub workers, one module per concern — `inbox_sync`,
+ `link_manager` (Gmail re-subscribe), `scheduled` (scheduled sends),
+ `sfs_uploader`/`sfs_deleter` (attachment storage), `gmail_ops`, `backfill`,
+ `crm_cleanup`, `worker_lifecycle`.
+- `src/backfill_outbox.rs`, `src/backfill_init_service.rs`,
+ `src/backfill_completion_service.rs`: Gmail history backfill orchestration.
+- `src/bin/`: standalone binaries — `pubsub_workers` (the queue consumer
+ process), plus one-off backfill/cleanup scripts.
+
+## Scope
+
+- Owns: Gmail/email API routes, email-side calendar invitation handling,
+ contacts sync, and all `src/pubsub/` queue consumers listed above.
+- Not here: Google Calendar sync itself → `crates/calendar_events`,
+ `calendar_service`; scheduled-send and SFS-cleanup *triggering* (cron) →
+ `email_scheduled_handler`, `email_sfs_delete_handler`, `email_refresh_handler`
+ (this service consumes the queues they publish to).
+
+## Recipes
+
+- Add an email API route: `src/api/email.rs` (or `src/api/gmail.rs`,
+ `src/api/calendar_invitations.rs`) → `src/api/context.rs` → `src/openapi.rs`.
+- Add a pubsub consumer: new module under `src/pubsub/` → wire into
+ `src/pubsub/mod.rs` and the `pubsub_workers` binary.
+- Add a backfill step: `src/backfill_init_service.rs` →
+ `src/backfill_completion_service.rs` → `src/backfill_outbox.rs`.
+
+## Checks
+
+- `cargo test -p email_service` (`SQLX_OFFLINE` unset).
+- `just check` (from this directory) runs `cargo check` with `SQLX_OFFLINE=true`.
+- Local SQS: `just create-localstack` / `create-queues` before running
+ `pubsub_workers` locally; queue names are in the `justfile`.
+
+## Gotchas
+
+- Macro's own digest emails are filtered out of Signal/email notifications
+ (#7039) — don't reintroduce a path that notifies on our own sends.
+- Long attachment names are truncated to the DSS limit before upload (#7893);
+ don't remove that truncation when touching `util/upload_attachment.rs`.
+
+## Related
+
+- Rules: `.agents/rules/config-and-service-urls.md` · Skill: `new-service`
diff --git a/services/email_service/CLAUDE.md b/services/email_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/email_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/email_sfs_delete_handler/AGENTS.md b/services/email_sfs_delete_handler/AGENTS.md
new file mode 100644
index 0000000000..b21b0e322b
--- /dev/null
+++ b/services/email_sfs_delete_handler/AGENTS.md
@@ -0,0 +1,22 @@
+# email_sfs_delete_handler
+
+## What it is
+
+Part of Email's attachment storage cleanup. A Lambda, triggered daily by
+EventBridge, that finds orphaned static file service (SFS) email attachments
+and enqueues delete messages for the SFS delete worker.
+
+## Start here
+
+- `src/handler.rs`: queries `email_attachments_sfs` for rows with a NULL
+ `attachment_id` and publishes `SFSDeleteMessage`s.
+
+## Scope
+
+- Owns: detecting orphaned SFS attachment rows and enqueuing their deletion.
+- Not here: actually deleting from SFS or the DB row → the SFS delete worker
+ in `email_service` (`src/pubsub/sfs_deleter`).
+
+## Checks
+
+- `cargo test -p email_sfs_delete_handler` (`SQLX_OFFLINE` unset).
diff --git a/services/email_sfs_delete_handler/CLAUDE.md b/services/email_sfs_delete_handler/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/email_sfs_delete_handler/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/image_optimizer/AGENTS.md b/services/image_optimizer/AGENTS.md
new file mode 100644
index 0000000000..74db24313b
--- /dev/null
+++ b/services/image_optimizer/AGENTS.md
@@ -0,0 +1,29 @@
+# image_optimizer
+
+## What it is
+
+Shared infrastructure for serving images (documents, email, attachments,
+etc.). A Lambda behind CloudFront (triggered via Function URL) that
+resizes/transcodes images on first request and caches the result in S3 at a
+variant key.
+
+## Start here
+
+- `src/handler.rs`: `handle_async_resize` — fetch original from S3, transform,
+ write the variant back to S3 with a long cache TTL so CloudFront/S3 serve it
+ directly on subsequent requests (falls back to caching the original on a
+ transform failure, to avoid retry storms).
+- `src/request.rs`: parses the CloudFront-rewritten `rawPath` (e.g.
+ `/file/{uuid}/format=avif,size=1080`) into `FilePath` / `AsyncResizeRequest`.
+- `src/transform.rs`: `TransformParams` validation (`MAX_SIZE = 4096`, no
+ upscaling) and the actual `image` crate resize/encode.
+
+## Scope
+
+- Owns: on-demand image resize/format conversion and its S3 variant cache.
+- Not here: the CloudFront URL rewrite that produces the `format=...,size=...`
+ suffix (infra-side), or general authenticated image fetching → `image_proxy_service`.
+
+## Checks
+
+- `cargo test -p image_optimizer` (`SQLX_OFFLINE` unset).
diff --git a/services/image_optimizer/CLAUDE.md b/services/image_optimizer/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/image_optimizer/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/image_proxy_service/AGENTS.md b/services/image_proxy_service/AGENTS.md
new file mode 100644
index 0000000000..b67f862534
--- /dev/null
+++ b/services/image_proxy_service/AGENTS.md
@@ -0,0 +1,37 @@
+# image_proxy_service
+
+## What it is
+
+Shared infrastructure for rendering remote images safely, used by Email
+rendering among other callers. A deployable service that proxies arbitrary
+remote image URLs through an authenticated, SSRF-guarded fetch.
+
+## Start here
+
+- `src/api/proxy.rs`: the `/proxy` route — size cap (`MAX_IMAGE_SIZE` 10 MB),
+ redirect cap, timeouts, and a browser-like User-Agent to clear strict WAFs.
+- `src/api/proxy/resolver.rs`: `PrivateIpFilteringResolver` — blocks DNS
+ resolution to private/loopback IPs to prevent SSRF.
+- `src/api/context.rs`: `ApiContext` / `AuthorizationService`.
+- `src/openapi.rs`, `src/doppler_config.rs`: separate `[[bin]]` targets for
+ OpenAPI generation and Doppler config.
+
+## Scope
+
+- Owns: fetching and streaming back a remote image URL on behalf of an
+ authenticated caller, with SSRF and resource-exhaustion protections.
+- Not here: resizing/transcoding Macro's own stored images →
+ `image_optimizer`.
+
+## Checks
+
+- `cargo test -p image_proxy_service` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Never bypass or weaken `PrivateIpFilteringResolver` — it is the only thing
+ stopping this service from being an SSRF vector into internal infra.
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md` · Skill: `new-service`
diff --git a/services/image_proxy_service/CLAUDE.md b/services/image_proxy_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/image_proxy_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/lexical-service/AGENTS.md b/services/lexical-service/AGENTS.md
new file mode 100644
index 0000000000..b23c7a6fcf
--- /dev/null
+++ b/services/lexical-service/AGENTS.md
@@ -0,0 +1,62 @@
+# lexical-service
+
+Status: migrating from Cloudflare Workers to ECS; `wrangler.jsonc` and
+`deploy-lexical-service.yml` still deploy the old worker.
+
+## What it is
+
+Serves Documents: a Bun server exposing stateless Lexical document
+conversions (plaintext, search/cognition preprocessing, markdown, HTML, XML)
+over an internal HTTP API, used by search indexing, AI agent context, and
+comment/markdown rendering. Production runs on ECS behind the gateway at
+`/lexical` (`infra/stacks/lexical-service`, `docker/lexical-service.Dockerfile`).
+
+## Start here
+
+- `src/index.ts`: Hono app wiring every endpoint behind `x-internal-auth-key`
+ middleware.
+- `src/endpoints/`: one file per route (`plaintext.ts`, `search-text.ts`,
+ `cognition-text.ts`/`cognition-v2.ts`, `markdown.ts`, `markdown-snapshot.ts`,
+ `html.ts`, `xml.ts`, `comment-mark.ts`, `comment-only-change.ts`,
+ `image-markdown.ts`, `agent-context.ts`, `agent-announcement.ts`,
+ `extract-reply.ts`, `mentions.ts`).
+- `src/lib/`: conversion logic the endpoints call into (`editor.ts`,
+ `markdown.ts`, `html.ts`, `comment-only-change.ts`, `comment-mark.ts`,
+ `sync-service.ts` client, `schemas.ts`).
+- `README.md`: endpoint reference, local `.dev.vars.local` secrets, deploy commands.
+
+## Scope
+
+- Owns: pure/stateless transforms of a Lexical document (or markdown) fetched
+ from `sync-service`; defines Lexical-editor utilities in
+ `packages/lexical-core` first and binds them to a route here.
+- Not here: Lexical node/editor primitives themselves → `packages/lexical-core`;
+ document persistence and CRDT sync → `sync-service`.
+
+## Recipes
+
+- Add a conversion endpoint: utility in `packages/lexical-core` → `src/lib/`
+ wrapper → new file in `src/endpoints/` → register in `src/index.ts`.
+- Change the comment-grant gate: `src/lib/comment-only-change.ts` +
+ `src/endpoints/comment-only-change.ts` (fails closed; needs
+ `LEXICAL_SERVICE_AUTH_KEY` set before deploy).
+
+## Checks
+
+- `bun test test/tests.ts` and the `*.test.ts` files beside their endpoints
+ (`bun test`).
+- `bun run check` (`tsc --noEmit --project tsconfig.check.json`).
+- `bun run plaintext|search|cognition <document-id>` against a local dev server
+ (`bun run dev`, port 8931) to sanity-check an endpoint end to end.
+
+## Gotchas
+
+- Called only internally, authenticated by `x-internal-auth-key`
+ (`INTERNAL_API_SECRET_KEY`); it also calls `sync-service` with
+ `SYNC_SERVICE_AUTH_KEY`. On ECS both come from its Doppler project; locally
+ from `.dev.vars.local`.
+- Never deploy without explicit permission, by either path.
+
+## Related
+
+- Docs: `packages/lexical-core` (shared node/utility source of truth)
diff --git a/services/lexical-service/CLAUDE.md b/services/lexical-service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/lexical-service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/mcp_auth_proxy/AGENTS.md b/services/mcp_auth_proxy/AGENTS.md
new file mode 100644
index 0000000000..efdc93e17b
--- /dev/null
+++ b/services/mcp_auth_proxy/AGENTS.md
@@ -0,0 +1,53 @@
+# mcp_auth_proxy
+
+## What it is
+
+Supports agent sessions: lets external MCP clients (e.g. cursor.com)
+authenticate against Macro. A library crate (mounted into `mcp_service`, not
+its own binary) implementing an OAuth 2.1 Dynamic Client Registration broker
+in front of FusionAuth, which doesn't support DCR itself.
+
+## Start here
+
+- `README.md`: the security model — which redirect URIs are usable, and which
+ client a grant belongs to. Read before touching `/register`, `/authorize`,
+ or `/token` logic.
+- `src/domain/service.rs` + `src/domain/service/test.rs`: the broker's core
+ logic (registration, authorize, token/refresh).
+- `src/domain/redirect_uri.rs`: the redirect URI usability policy from the README.
+- `src/domain/ports.rs`: `ClientRegistrationStore`, `OAuthProvider`,
+ `RefreshTokenBindingStore` — the ports the service depends on.
+- `src/inbound/axum_router.rs`: HTTP routes; `src/inbound/middleware.rs`: auth.
+- `src/outbound/fusionauth.rs`, `src/outbound/redis.rs`: concrete adapters
+ (gated behind the `outbound` feature; `inbound`/`outbound` are each optional).
+
+## Scope
+
+- Owns: DCR-compliant client registration, authorization-code issuance, and
+ refresh-token rotation/binding, all proxied in front of FusionAuth.
+- Not here: the MCP tool surface itself → `mcp_service`.
+
+## Recipes
+
+- Change redirect URI policy: `src/domain/redirect_uri.rs` → update the README
+ section it implements → `services/mcp_service/src/config.rs`
+ (`DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS`) if the default allowlist changes.
+- Add a new grant type: `src/domain/models.rs` → `src/domain/service.rs` →
+ `src/outbound/fusionauth.rs` → `src/inbound/axum_router.rs`.
+
+## Checks
+
+- `cargo test -p mcp_auth_proxy` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `client_id` is not a secret; every endpoint must still check it against a
+ live registration — see README "Which client a grant belongs to" before
+ changing token/refresh validation.
+- Refresh tokens are bound by SHA-256 digest with rotate-before-drop ordering;
+ don't weaken that to avoid a race, and remember pre-binding-era refresh
+ tokens have no binding (clients reauthorize once).
+
+## Related
+
+- Skill: `new-service` (for how this is wired as a dependency, not a deploy)
diff --git a/services/mcp_auth_proxy/CLAUDE.md b/services/mcp_auth_proxy/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/mcp_auth_proxy/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/mcp_service/AGENTS.md b/services/mcp_service/AGENTS.md
new file mode 100644
index 0000000000..5bab282abb
--- /dev/null
+++ b/services/mcp_service/AGENTS.md
@@ -0,0 +1,56 @@
+# mcp_service
+
+## What it is
+
+Lets external AI clients act as Macro agent sessions: a deployable service
+exposing Macro's AI toolset (the same tools the agent chat/stream API uses)
+as a Streamable HTTP MCP server, authenticated via OAuth 2.1 backed by
+FusionAuth.
+
+## Start here
+
+- `src/main.rs`: composition root — builds `McpAuthProxyService`
+ (from `mcp_auth_proxy`), the `rmcp` streamable HTTP transport, and
+ `AuthenticatedToolService`.
+- `src/tool_service.rs`: `ServerHandler` impl — extracts the authenticated
+ user from request parts and maps `ai_toolset` tools/annotations onto the
+ MCP wire format.
+- `src/config.rs`: typed env vars (`macro_config`/`macro_env_var` pattern),
+ including `DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS`.
+- `src/markdown_images.rs`: resolves markdown image references in tool output.
+- `src/tool_response.rs`: shapes tool results (incl. media) for MCP responses.
+
+## Scope
+
+- Owns: the MCP transport/handler layer and OAuth wiring around Macro's
+ shared AI toolset.
+- Not here: the OAuth broker logic itself → `mcp_auth_proxy` (mounted as a
+ library, same binary); the tool implementations → `crates/ai_toolset`,
+ `crates/ai_tools`.
+
+## Boundaries
+
+- Depends on: `mcp_auth_proxy` (OAuth broker), `ai_toolset`/`ai_tools`
+ (the tool implementations), `fusionauth`, plus the domain crates each tool
+ touches (`documents`, `databases`, `chat`, `crm`, `channels`, etc.).
+- Used by: external/browser-based MCP clients (e.g. cursor.com) through the
+ gateway; `MCP_ALLOWED_REDIRECT_HOSTS` controls which such clients are trusted.
+
+## Recipes
+
+- Add an MCP tool: implement it in `crates/ai_toolset` (shared with chat) →
+ no changes usually needed here unless the tool needs MCP-specific response
+ shaping → `src/tool_response.rs` / `src/markdown_images.rs`.
+- Add a config value: `src/config.rs` → Doppler → the `mcp_service_doppler_config`
+ binary validates it in CI.
+- Allow a new MCP client origin: `src/config.rs`
+ (`DEFAULT_MCP_ALLOWED_REDIRECT_HOSTS`) — see `mcp_auth_proxy/README.md` for
+ the redirect URI policy this feeds.
+
+## Checks
+
+- `cargo test -p mcp_service` (`SQLX_OFFLINE` unset).
+
+## Related
+
+- Skill: `create-ai-tool`, `new-service` · `services/mcp_auth_proxy/AGENTS.md`
diff --git a/services/mcp_service/CLAUDE.md b/services/mcp_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/mcp_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/notification_service/AGENTS.md b/services/notification_service/AGENTS.md
new file mode 100644
index 0000000000..f20246957e
--- /dev/null
+++ b/services/notification_service/AGENTS.md
@@ -0,0 +1,49 @@
+# notification_service
+
+## What it is
+
+Serves Notifications across the product: a deployable service that composes
+the `notification` domain crate into a running process. Exposes an HTTP API
+for reading/unsubscribing from notifications, plus the Kafka-driven egress
+worker that sends email/mobile-push/websocket notifications.
+
+## Start here
+
+- `src/main.rs`: composition root — wires `NotificationEgressService`,
+ `NotificationWorker`, `NotificationEventsListener`, and the outbound adapters
+ (`EmailAdapter`, `MobilePushAdapter`, `WebSocketGatewayAdapter`,
+ `Kafka*RealtimePublisher`, `RedisRateLimitAdapter`) from `crates/notification`.
+- `src/api.rs` + `src/api/context.rs`: HTTP routes — `user_notification.rs`
+ (list/read), `unsubscribe.rs`, `health.rs`.
+- `src/model/notification.rs`: service-local request/response shapes.
+- `README.md`: local DB setup (`sqlx database setup` from
+ `crates/notification_db_client`).
+
+## Scope
+
+- Owns: process wiring (config, adapters, HTTP routes) for notifications; the
+ domain logic (digesting, egress rules, send decisions) lives in
+ `crates/notification` and `crates/notification_db_client`.
+- Not here: notification domain logic itself → `crates/notification`.
+
+## Recipes
+
+- Add a notification HTTP route: `src/api/user_notification.rs` (or a new
+ module) → `src/api.rs` → `src/openapi.rs`.
+- Add a new egress channel: implement the port in `crates/notification`
+ (`outbound/`) → wire the adapter in `src/main.rs`.
+
+## Checks
+
+- `cargo test -p notification_service` (`SQLX_OFFLINE` unset; needs local
+ MacroDB — `just run_dbs -d`, then `sqlx database setup` from
+ `crates/notification_db_client`).
+
+## Gotchas
+
+- Don't log notification payloads on tracing spans (#7892) — they can carry
+ sensitive content; log ids/types instead.
+
+## Related
+
+- Skill: `new-service`
diff --git a/services/notification_service/CLAUDE.md b/services/notification_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/notification_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/organization_retention_handler/AGENTS.md b/services/organization_retention_handler/AGENTS.md
new file mode 100644
index 0000000000..6a18f22211
--- /dev/null
+++ b/services/organization_retention_handler/AGENTS.md
@@ -0,0 +1,40 @@
+# organization_retention_handler
+
+## What it is
+
+Shared infrastructure for organization data retention policies. A Lambda
+that consumes `OrganizationRetentionQueue` SQS messages, finds items older
+than an organization's retention window, and enqueues them for deletion.
+
+## Start here
+
+- `src/handler.rs`: reads `organization_id`/`retention_days` from SQS message
+ attributes, fetches violating items, and splits them by entity type.
+- `src/service/db/get_violating_items.rs`: the query that finds stale items.
+- `src/main.rs`: Lambda wiring (DB pool, SQS client with document/chat delete
+ queues).
+
+## Scope
+
+- Owns: turning one organization's retention check into per-item delete-queue
+ messages (`DocumentDeleteQueue`, `ChatDeleteQueue`).
+- Not here: deciding which organizations have retention enabled or when to run
+ → `services/organization_retention_trigger`, which produces this Lambda's
+ input; deleting the items themselves → whatever consumes the delete queues.
+
+## Checks
+
+- `cargo test -p organization_retention_handler` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- The handler requires exactly one SQS record per invocation (enforced in
+ `src/handler.rs`) — the queue's batch size must stay at 1 or the Lambda
+ errors out.
+- Only `"document"` and `"chat"` item types are recognized; other item type
+ strings from `get_violating_items` are silently dropped from both delete
+ lists.
+
+## Related
+
+- Rules: `.agents/rules/rust/guardrails.md`
diff --git a/services/organization_retention_handler/CLAUDE.md b/services/organization_retention_handler/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/organization_retention_handler/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/organization_retention_trigger/AGENTS.md b/services/organization_retention_trigger/AGENTS.md
new file mode 100644
index 0000000000..7c1afc0389
--- /dev/null
+++ b/services/organization_retention_trigger/AGENTS.md
@@ -0,0 +1,33 @@
+# organization_retention_trigger
+
+## What it is
+
+Shared infrastructure for organization data retention policies. A Lambda
+fired on an EventBridge schedule that reads each organization's retention
+settings and enqueues one SQS message per organization.
+
+## Start here
+
+- `src/main.rs`: the whole Lambda — handler, DB pool, SQS client wiring.
+- `src/service/db/get_organization_retention.rs`: the query that reads
+ retention settings.
+
+## Scope
+
+- Owns: the scheduled trigger that fans out organization retention checks
+ onto `OrganizationRetentionQueue`.
+- Not here: evaluating which items are stale and deleting them →
+ `services/organization_retention_handler`, which consumes that queue.
+
+## Checks
+
+- `cargo test -p organization_retention_trigger` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- One EventBridge invocation handles the full organization list in a single
+ Lambda execution, unlike the handler it feeds, which is one-message-per-Lambda.
+
+## Related
+
+- Rules: `.agents/rules/rust/guardrails.md`
diff --git a/services/organization_retention_trigger/CLAUDE.md b/services/organization_retention_trigger/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/organization_retention_trigger/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/preview_gateway/AGENTS.md b/services/preview_gateway/AGENTS.md
new file mode 100644
index 0000000000..a1c16e0b2d
--- /dev/null
+++ b/services/preview_gateway/AGENTS.md
@@ -0,0 +1,43 @@
+# preview_gateway
+
+## What it is
+
+Serves agent sessions: lets people view a coding agent's running dev-server
+preview from the browser. A composition root exposing coding-agent dev-server
+previews over SSH tunnels and short-lived browser tickets, on its own
+`macro-agent-gateway.com` domain.
+
+## Start here
+
+- `README.md`: the full design — SSH tunnel protocol, ticket/cookie flow,
+ limits, Pulumi deployment, and local-stack verification. Read it before
+ changing this service; this file only points at it.
+- `src/adapters.rs`: wires `agent_preview`'s ports (`Authority`, `Events`) to
+ real session/permission/realtime services — the actual preview logic lives
+ in `crates/agent_preview`, not here.
+- `src/main.rs`: router, SSH server, and sweeper startup.
+
+## Scope
+
+- Owns: composing `agent_preview`'s domain with Macro's session, entity
+ access, and connection-gateway services; the Pulumi deployment at
+ `infra/stacks/preview-gateway`.
+- Not here: the preview/SSH/ticket domain logic itself → `crates/agent_preview`;
+ the SSH transport primitives → `crates/agent_egress`.
+
+## Checks
+
+- From the repo root, `SQLX_OFFLINE` unset:
+ `cargo test -p agent_preview && cargo test -p preview_gateway && cargo test -p agent_egress`.
+
+## Gotchas
+
+- Runs as a single Fargate replica with no autoscaling — SSH, HTTP, and
+ control requests share one in-memory lease/ticket registry (see README
+ "Deployment"). Scaling requires explicit cross-replica routing first.
+- Never deploy (`pulumi up`) without explicit approval; see root guardrails.
+
+## Related
+
+- Skill: `run-app` (`--with-cf-tunnel` for external runtimes) · Docs:
+ `this directory's README.md`
diff --git a/services/preview_gateway/CLAUDE.md b/services/preview_gateway/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/preview_gateway/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/scheduled_action/AGENTS.md b/services/scheduled_action/AGENTS.md
new file mode 100644
index 0000000000..198503bea8
--- /dev/null
+++ b/services/scheduled_action/AGENTS.md
@@ -0,0 +1,59 @@
+# scheduled_action
+
+## What it is
+
+Serves agent sessions' automations ("routines"): a deployable service for
+scheduled and event-triggered agent automations — cron-style schedules plus
+Kafka/Jev-gated event triggers that run a target (agent, workflow) and track
+each run.
+
+## Start here
+
+- `src/lib.rs`: module map — `domain`, `inbound`, `outbound`, `config`, `swagger`.
+- `src/domain/service.rs` + `src/domain/ports.rs`: the orchestration service
+ and the ports its adapters implement.
+- `src/domain/event_trigger.rs` + `src/domain/target_runner.rs`: how an event
+ (Kafka or polled) turns into a dispatched run.
+- `src/inbound/axum_router.rs`, `src/inbound/kafka_consumer.rs`,
+ `src/inbound/event_run_worker.rs`: the three inbound adapters.
+- `src/bins/service.rs` / `src/bins/openapi.rs`: the deployed binary and the
+ OpenAPI generator binary.
+
+## Scope
+
+- Owns: scheduled-action and event-trigger CRUD, dispatch (in-process or
+ tokio), run history, and live-update notifications over the connection
+ gateway.
+- Not here: the target being run (an agent turn, a routine's tool logic) →
+ `crates/agent_session`, `ai_tools`; Jev condition evaluation → `crates/jev`.
+
+## Boundaries
+
+- Depends on: `agent_session`, `trigger_context`, `jev`, `channels`, `crm`,
+ `documents`, `macro_event_broker`/`macro_event_topics` (Kafka), `macro_db_client`.
+- Used by: the web app's automations/routines UI and agent tooling, through
+ the gateway.
+
+## Recipes
+
+- Add a new event trigger source: `src/domain/event_trigger.rs` →
+ `src/inbound/kafka_consumer.rs` (if Kafka-sourced) →
+ `src/outbound/event_content.rs` (decode payload) → test in the matching
+ `test.rs` beside each file.
+- Add an API route: `src/domain/service.rs` → `src/inbound/axum_router.rs` →
+ `src/swagger.rs`.
+- Change dispatch behavior: `src/outbound/pg_polling_dispatcher.rs` /
+ `src/outbound/tokio_dispatcher.rs` → `src/domain/execution.rs`.
+
+## Checks
+
+- `cargo test -p scheduled_action` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `TODO.md` tracks open follow-ups (unified history list, delete schedules,
+ sharing/permissions) — check it before assuming a listed gap is unintentional.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`, `.agents/rules/rust/guardrails.md`
diff --git a/services/scheduled_action/CLAUDE.md b/services/scheduled_action/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/scheduled_action/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/search_processing_service/AGENTS.md b/services/search_processing_service/AGENTS.md
new file mode 100644
index 0000000000..a2ae1fa022
--- /dev/null
+++ b/services/search_processing_service/AGENTS.md
@@ -0,0 +1,51 @@
+# search_processing_service (sps)
+
+## What it is
+
+Powers Search: a hexagonal service owning the search-event pipeline. Indexes
+calls, agent sessions, documents, emails, and other entities into
+OpenSearch, and exposes backfill HTTP routes for each.
+
+## Start here
+
+- `README.md`: the authoritative guide — architecture diagram, Kafka delivery
+ contract, agent-session indexing/rollout, backfill routes table, and
+ running/monitoring instructions. Read it before changing this service.
+- `src/domain/service.rs` + `src/domain/ports.rs`: the `BackfillService`
+ orchestrator — the single inbound contract for HTTP handlers.
+- `src/inbound/kafka_consumer.rs`: live event decoding, ordering, commit, and
+ retry logic.
+- `src/process/`: indexing logic shared by the SQS and Kafka inbound adapters.
+- `src/api/internal/backfill.rs`: the backfill HTTP handlers (thin
+ pass-throughs to the orchestrator).
+
+## Scope
+
+- Owns: OpenSearch indexing for calls, agent sessions, documents, emails,
+ channels, and other search entities; their Kafka/SQS ingestion and HTTP
+ backfill routes.
+- Not here: OpenSearch client/index mapping primitives → `crates/opensearch_client`;
+ agent-session fold/transcript assembly → `crates/folds/agent_fold`.
+
+## Checks
+
+- From repo root, `SQLX_OFFLINE` unset:
+ `cargo test -p search_processing_service --no-default-features --features processing,service`
+- `cargo test -p agent_fold` and `cargo test -p opensearch_client` for the
+ crates it depends on most.
+- With local OpenSearch on `localhost:9200`:
+ `cargo test -p opensearch_client empty_index_accepts_both_authors -- --ignored`
+ (creates/deletes only a scratch index).
+
+## Gotchas
+
+- Deployment never creates OpenSearch indices/aliases — provision and verify
+ the alias manually first (README "Agent-session indexing and rollout").
+- Kafka offsets commit on in-memory handoff, not after OpenSearch write —
+ there is a crash-loss window; recovery is the backfill routes, not replay.
+- Full-scan backfills page by UUID, not `modified_at`, and cannot discover
+ already-deleted IDs — target specific IDs for those.
+
+## Related
+
+- Docs: this directory's `README.md` · Rules: `.agents/rules/rust/architecture.md`
diff --git a/services/search_processing_service/CLAUDE.md b/services/search_processing_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/search_processing_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/sha_cleanup_worker/AGENTS.md b/services/sha_cleanup_worker/AGENTS.md
new file mode 100644
index 0000000000..9d7f26a7af
--- /dev/null
+++ b/services/sha_cleanup_worker/AGENTS.md
@@ -0,0 +1,38 @@
+# sha_cleanup_worker
+
+## What it is
+
+Shared infrastructure for document/attachment storage: a periodic worker
+that deletes S3 objects whose SHA was placed in the `bucket:sha-delete`
+Redis set, decrementing a shared reference count first.
+
+## Start here
+
+- `src/process.rs`: the cleanup loop — pulls SHAs from Redis, checks the
+ count, deletes from S3 when it hits zero.
+- `src/service/redis/{get_shas,increment,remove_set_member}.rs`: the Redis
+ operations this service makes.
+- `src/service/s3/delete.rs`, `src/service/db/get_sha_count.rs`: the S3 delete
+ and the Postgres reference-count lookup.
+
+## Scope
+
+- Owns: draining the sha-delete Redis set and the S3 deletes it triggers.
+- Not here: adding SHAs to that set, or the reference counting itself, which
+ happen wherever documents/attachments are written.
+
+## Checks
+
+- `cargo test -p sha_cleanup_worker` (`SQLX_OFFLINE` unset; needs the local
+ Postgres and Redis/macrocache up, per `README.md`).
+
+## Gotchas
+
+- `cargo run --features local` bypasses all AWS calls and returns dummy data
+ — use it only for wiring checks, not to verify real deletes.
+- Triggered on a schedule by `services/worker_trigger`'s ECS `RunTask`, not by
+ this crate's own binary running continuously.
+
+## Related
+
+- Rules: `.agents/rules/rust/guardrails.md`
diff --git a/services/sha_cleanup_worker/CLAUDE.md b/services/sha_cleanup_worker/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/sha_cleanup_worker/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/slack_import_worker/AGENTS.md b/services/slack_import_worker/AGENTS.md
new file mode 100644
index 0000000000..f7f0407359
--- /dev/null
+++ b/services/slack_import_worker/AGENTS.md
@@ -0,0 +1,43 @@
+# slack_import_worker
+
+## What it is
+
+Onboards new Channels (chat) customers from Slack: a composition root for
+importing Slack archive exports. Writes conversations, messages, and
+references into Macro as channels, and sends one best-effort colleague-join
+email.
+
+## Start here
+
+- `src/composition.rs`: cross-domain transaction coordination — this is the
+ one place that is allowed to coordinate `import` and `slack_integration`
+ domain crates together; don't add that coordination to either crate's own
+ adapter.
+- `src/composition/channel_sink.rs`: writes imported conversations as channels.
+- `src/composition/reference_reconciliation.rs` + `src/composition/references.rs`:
+ resolving cross-message references (replies, mentions) after import.
+- `src/composition/authorizer.rs`, `src/composition/join_announcer.rs`: access
+ checks and the join-email side effect.
+- `tests/archive_import.rs` + `tests/archive_import/`: end-to-end import tests,
+ including kill/recovery behavior (`process_recovery.rs`, `kill_boundaries.sql`).
+
+## Scope
+
+- Owns: turning a parsed Slack archive into Macro channels/messages and
+ reconciling references, as a durable, resumable process.
+- Not here: parsing the Slack export format or the import job ledger →
+ `crates/import`; Slack API/domain types → `crates/slack_integration`.
+
+## Checks
+
+- `cargo test -p slack_import_worker` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `tests/archive_import/process_recovery.rs` exercises killing the process
+ mid-import; `kill_boundaries.sql` encodes the exact points it resumes from —
+ a new write step likely needs a new boundary there.
+
+## Related
+
+- Rules: `.agents/rules/rust/architecture.md`
diff --git a/services/slack_import_worker/CLAUDE.md b/services/slack_import_worker/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/slack_import_worker/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/static_file_service/AGENTS.md b/services/static_file_service/AGENTS.md
new file mode 100644
index 0000000000..b40a1f3e04
--- /dev/null
+++ b/services/static_file_service/AGENTS.md
@@ -0,0 +1,42 @@
+# static_file_service (sfs)
+
+## What it is
+
+Shared infrastructure for file attachments across the product (documents,
+email, chat). A deployable service for uploading, storing, and serving file
+attachments: DynamoDB holds file metadata, S3 holds bytes, presigned URLs
+handle upload.
+
+## Start here
+
+- `src/api.rs` + `src/api/context.rs`: router setup and shared `AppState`.
+- `src/api/file/`: the HTTP surface — `put_presigned_url.rs` (upload),
+ `get_file.rs`, `metadata.rs`, `delete_file.rs`, `bulk_delete_file.rs`.
+- `src/api/event/`: S3 event handling (`s3_create.rs`, `s3_message.rs`) that
+ marks a file uploaded once S3 confirms the object exists.
+- `src/service/dynamodb/`: the DynamoDB item operations (`put_item.rs`,
+ `get_item.rs`, `mark_uploaded.rs`, `delete_item.rs`).
+- `src/service/s3/client.rs`: the S3 client wrapper.
+
+## Scope
+
+- Owns: file metadata (DynamoDB), file bytes (S3), presigned upload URLs, and
+ the S3-event-driven "mark uploaded" transition.
+- Not here: what entity a file is attached to (document, chat, etc.) — callers
+ pass `models_sfs` references; this service doesn't know its callers' domains.
+
+## Checks
+
+- `cargo test -p static_file_service` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- A file is "pending" in DynamoDB until the S3 create event
+ (`src/api/event/s3_create.rs`) marks it uploaded — a client finishing a
+ presigned PUT does not itself update file state.
+- `tree_trace` and `dynamodb_client_test` are test-only Cargo features; don't
+ enable them in a deployed build.
+
+## Related
+
+- Rules: `.agents/rules/rust/guardrails.md`, `.agents/rules/rust/security.md`
diff --git a/services/static_file_service/CLAUDE.md b/services/static_file_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/static_file_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/sync-service/AGENTS.md b/services/sync-service/AGENTS.md
new file mode 100644
index 0000000000..dee28ce67a
--- /dev/null
+++ b/services/sync-service/AGENTS.md
@@ -0,0 +1,65 @@
+# sync-service
+
+## What it is
+
+Powers real-time collaboration on Documents and other collab surfaces
+(spreadsheets, forms): a Cloudflare Worker (Rust compiled to wasm) hosting
+one Durable Object per collaborative document ("room"), syncing Loro CRDT
+updates over WebSocket.
+
+## Start here
+
+- `README.md`: project structure, Durable Object lifecycle (in-memory vs
+ persistent state, the keep-alive alarm), JWT auth, and Bebop codegen. Read
+ it before changing this service.
+- `src/durable_object.rs` + `src/durable_object/document_api.rs`: the Durable
+ Object — WebSocket handling, loro document state, alarm-driven snapshotting.
+- `src/durable_object/surface_api.rs`, `surface_migration.rs`: non-document
+ surfaces (spreadsheets, forms, etc.) hosted the same way.
+- `src/storage/` + `src/storage/backends/`: snapshot/op-log persistence,
+ pluggable across D1/KV/R2/combined backends (see the Cargo feature flags).
+- `src/auth.rs`: JWT verification against tokens minted by
+ `document_storage_service`.
+- `build.rs` + `bebop-schema/`, `bebop/`: Bebop wire schema and codegen for
+ Rust and TypeScript bindings.
+
+## Scope
+
+- Owns: real-time sync of Loro documents over WebSocket, snapshot
+ persistence, and the sync-service's own auth/permission checks on
+ established connections.
+- Not here: minting the document-access JWT → `document_storage_service`;
+ document domain logic → the owning domain crate (e.g. `collab_surface`).
+
+## Recipes
+
+- Change the wire protocol: `bebop/schema.bop` → `cd bebop && npx bebop-tools build`
+ (TS bindings) → `worker-build` regenerates Rust bindings via `build.rs`.
+- Add a storage backend: `src/storage/backends/` (new file + `mod.rs`) → gate
+ it behind a new feature in `Cargo.toml` → wire into `src/storage.rs`.
+- Add a non-document surface: `src/durable_object/surface_api.rs` →
+ `src/domain/` (surface-specific logic) → migration in
+ `src/durable_object/surface_migration.rs` if it changes stored shape.
+
+## Checks
+
+- `just test` (runs `worker-build`, then `npx vitest run` and `cargo test`)
+ from this directory.
+- `just test-no-alarm` to verify core logic without `alarm-keep-alive`.
+- Use Node.js 22.12+/24.x/26+ for Vitest 5; install JS deps with `npm ci`
+ (`package-lock.json` is authoritative, not `bun.lock`).
+
+## Gotchas
+
+- Bumping `loro-crdt` touches three lockfiles: `bun.lock`, the workspace
+ `Cargo.lock`, and this directory's `package-lock.json` — update all three.
+- Durable Object in-memory state (including the loro document) evicts after
+ 10s of inactivity even with open connections; the alarm-based heartbeat in
+ `src/keepalive.rs` is what keeps it warm, not WebSocket traffic.
+- `migration-test-hooks` is test-only fault injection — never enable it in a
+ deployed worker (see the feature's doc comment in `Cargo.toml`).
+- Never run `just deploy-dev` / `just deploy-prod` without explicit approval.
+
+## Related
+
+- Docs: this directory's `README.md`
diff --git a/services/sync-service/CLAUDE.md b/services/sync-service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/sync-service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/unfurl_service/AGENTS.md b/services/unfurl_service/AGENTS.md
new file mode 100644
index 0000000000..105c810068
--- /dev/null
+++ b/services/unfurl_service/AGENTS.md
@@ -0,0 +1,41 @@
+# unfurl_service
+
+## What it is
+
+Shared infrastructure for rendering link previews wherever a URL is pasted
+(documents, chat, email). A deployable service that fetches link previews
+(title, description, image, favicon) for arbitrary URLs and proxies image
+responses, with SSRF protections since both accept user-supplied URLs.
+
+## Start here
+
+- `src/unfurl.rs` + `src/api/unfurl/get_unfurl.rs`: the unfurl domain logic
+ and its HTTP handler.
+- `src/http_safety.rs` + `src/http_safety/resolver.rs`: the shared
+ SSRF-safe HTTP client — private-IP filtering resolver, redirect limits,
+ size limits. Both unfurl and proxy fetches go through this.
+- `src/api/proxy.rs`: the image proxy endpoint.
+
+## Scope
+
+- Owns: fetching and parsing link metadata, and safely proxying external
+ images, for any caller inside Macro.
+- Not here: anything unrelated to fetching third-party URLs.
+
+## Checks
+
+- `cargo test -p unfurl_service` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- Any change that fetches a user-supplied URL must go through
+ `SsrfSafeHttpClient` in `src/http_safety.rs` — it blocks internal/private
+ IPs including after redirects, which a plain `reqwest::Client` would not do
+ (see PR history: `fix(unfurl): prevent ssrf`, #5708).
+- `MAX_REDIRECTS` (5) and response size limits are enforced per-request, not
+ globally; a new endpoint that fetches external content needs to apply them
+ itself.
+
+## Related
+
+- Rules: `.agents/rules/rust/security.md`
diff --git a/services/unfurl_service/CLAUDE.md b/services/unfurl_service/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/unfurl_service/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/services/worker_trigger/AGENTS.md b/services/worker_trigger/AGENTS.md
new file mode 100644
index 0000000000..94a017bd38
--- /dev/null
+++ b/services/worker_trigger/AGENTS.md
@@ -0,0 +1,32 @@
+# worker_trigger
+
+## What it is
+
+Shared infrastructure for document/attachment storage cleanup: an
+EventBridge-scheduled Lambda that starts an ECS `RunTask` for the
+`sha_cleanup_worker` task definition.
+
+## Start here
+
+- `src/main.rs`: the whole Lambda — reads the EventBridge event and invokes
+ `service::ecs::run_task`.
+- `src/service/ecs/run_task.rs`: the `RunTask` call itself.
+
+## Scope
+
+- Owns: translating an EventBridge schedule tick into one ECS task launch.
+- Not here: the cleanup logic that task runs →
+ `services/sha_cleanup_worker`.
+
+## Checks
+
+- `cargo test -p worker_trigger` (`SQLX_OFFLINE` unset).
+
+## Gotchas
+
+- `cargo run --features local` (or `cargo lambda watch --features local`)
+ skips the real ECS call — only use it to exercise request parsing.
+
+## Related
+
+- Rules: `.agents/rules/rust/guardrails.md`
diff --git a/services/worker_trigger/CLAUDE.md b/services/worker_trigger/CLAUDE.md
new file mode 120000
index 0000000000..47dc3e3d86
--- /dev/null
+++ b/services/worker_trigger/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/sgconfig.yml b/sgconfig.yml
index 71ce4b06cb..a210a9750a 100644
--- a/sgconfig.yml
+++ b/sgconfig.yml
@@ -5,7 +5,7 @@
# - local runs (bunx @ast-grep/cli scan)
# - CodeRabbit (reviews.tools.ast-grep.rule_dirs in .coderabbit.yaml)
#
-# Rules encode conventions from docs/STYLE_GUIDE.md (repo root). severity: error
+# Rules encode conventions from docs/development/style-guide.md (repo root). severity: error
# rules are CI-blocking (zero existing violations); severity: warning rules
# surface on changed code via CodeRabbit without failing CI while existing
# violations are burned down.
diff --git a/tooling/just/check.just b/tooling/just/check.just
index c775388846..a01f22dad3 100644
--- a/tooling/just/check.just
+++ b/tooling/just/check.just
@@ -2,7 +2,7 @@
# changed vs origin/main (merge-base, plus uncommitted and untracked work) so
# the output is exactly what is wrong with YOUR changes — legacy findings in
# untouched files never appear. Findings print as file:line with the rule id;
-# ast-grep rule ids map to docs/STYLE_GUIDE.md (its `severity: error` rules fail
+# ast-grep rule ids map to docs/development/style-guide.md (its `severity: error` rules fail
# the run, warnings/hints only print; oxlint is warn-only for now).
#
# just check fast: rustfmt + biome + oxlint + ast-grep (~seconds)
@@ -69,11 +69,11 @@ check *ARGS:
|| { echo " fix: (\cd packages/sdk && bun run format && bun run lint), then re-check"; fail=1; }
fi
fi
- echo "── oxlint (warn-only; docs/STYLE_GUIDE.md FE-12)"
+ echo "── oxlint (warn-only; docs/development/style-guide.md FE-12)"
(cd apps/web && bunx --yes [email protected] "${js_paths[@]}") || fail=1
fi
if [ -n "$sg" ]; then
- echo "── ast-grep code rules (rule ids map to docs/STYLE_GUIDE.md)"
+ echo "── ast-grep code rules (rule ids map to docs/development/style-guide.md)"
bunx --yes @ast-grep/[email protected] scan --report-style=short $sg || fail=1
fi
if [ "{{ ARGS }}" = "full" ]; then
diff --git a/tooling/seed_cli/README.md b/tooling/seed_cli/README.md
index bd7debaf57..87207ee8bb 100644
--- a/tooling/seed_cli/README.md
+++ b/tooling/seed_cli/README.md
@@ -2,7 +2,7 @@
Used to populate your local environment with sample data.
-Please ensure you have read [RUNNING\_LOCALLY](../../docs/RUNNING_LOCALLY.md) and
+Please ensure you have read [RUNNING\_LOCALLY](../../docs/development/running-locally.md) and
have your local environment setup.
## Usage
diff --git a/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_conventions.rs b/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_conventions.rs
index 870ec3dd41..465069ec2a 100644
--- a/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_conventions.rs
+++ b/tooling/xtask/crates/xtask_workflows/src/workflows/code_check_conventions.rs
@@ -5,7 +5,7 @@
//! (config: `sgconfig.yml` at the repo root). The scan fails only on
//! `severity: error` findings; `warning`/`hint` rules surface through
//! CodeRabbit's ast-grep integration on changed code instead. The rules encode
-//! conventions from `docs/STYLE_GUIDE.md` at the repo root.
+//! conventions from `docs/development/style-guide.md` at the repo root.
use gh_workflow::{
Concurrency, Event, Expression, Job, Level, Permissions, PullRequest, PullRequestType, Run,