chore: cut agent governance to a single constitution

Replace CLAUDE.md with a short decision-rule constitution; move PRDs,
architecture, development and design docs and repo skills out of the tree;
delete the docs tooling (docsgen, prdlint, docdrift, docsite, contractaudit,
reachaudit) and its gate steps; stop install.sh copying repo skills into
runtime skills.
This commit is contained in:
sam committed 2026-10-03 21:47:46 +10:00
1 parent a45300d626
commit 42988970fe
190 files changed
+151 -31692

No files matched your search

-57
View File
@@ -1,57 +0,0 @@
# Architecture Decision Index
**Status:** Approved
**Date:** 2026-07-28
**Beads issue:** `archie-core-5d7`
## Purpose
This file is the navigation point for Archie's target architecture. It is
deliberately short. Architectural decisions are separated by domain or
requirement so an implementation task can load only the rules governing its
scope.
Implementers MUST read the decision document for the domain or requirement they
are changing. They MUST NOT infer permission to change neighbouring domains from
a broader restructuring objective.
## Global invariants
- Organise code around cohesive application responsibilities, not generic
technical mechanisms.
- Domains own their behaviour, vocabulary, state, commands, events, policy
implementations, runtime settings, and required service contracts.
- Domains do not depend on infrastructure or manipulate another domain.
- `internal/app` owns composition; `cmd/*` remains thin.
- Cross-domain work uses an explicitly owned command, event, or approved shared
contract.
- Process boundaries are deployment choices and do not determine source-code
ownership.
- Existing package names and boundaries have no presumption of survival.
The words **MUST**, **MUST NOT**, **SHOULD**, and **MAY** are normative.
## Decision documents
| Scope | Authoritative document |
| --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
| Repository layout, domains, composition, deployments, and optional material | [architecture/organisation.md](../architecture/organisation.md) |
| Dependency direction, domain contracts, infrastructure, commands, events, and wire contracts | [architecture/dependencies-and-contracts.md](../architecture/dependencies-and-contracts.md) |
| External configuration, runtime settings, and dissolution of `internal/config` | [architecture/configuration.md](../architecture/configuration.md) |
| Persistent actor identity, ownership, lifecycle, and attribution | [architecture/identity.md](../architecture/identity.md) |
| Agent definitions, workflows, workflow executions, tools, and worker boundaries | [architecture/agent-system.md](../architecture/agent-system.md) |
| Personal-assistant interactions, messaging channels, and optional promotion into durable work | [architecture/messaging-and-work-intake.md](../architecture/messaging-and-work-intake.md) |
| Shared policy evaluation and domain-owned policy semantics | [architecture/policy.md](../architecture/policy.md) |
| Safe source/configuration changes, health supervision, and recovery | [architecture/safe-change-and-recovery.md](../architecture/safe-change-and-recovery.md) |
| Plugin framework, plugin implementations, and extension isolation | [architecture/plugins-and-extensions.md](../architecture/plugins-and-extensions.md) |
| Generated references, deprecations, and changelog generation | [architecture/generated-documentation.md](../architecture/generated-documentation.md) |
| Remaining package destinations, data migrations, runtime cutover, and completion criteria | [architecture/migration-decisions.md](../architecture/migration-decisions.md) |
| Domain/feature research, design interview, and required handoff | [architecture/package-review.md](../architecture/package-review.md) |
## Deferred decisions
The remaining package-placement, data-migration, shared-mechanics, process-
boundary, and cutover decisions are maintained in
[architecture/migration-decisions.md](../architecture/migration-decisions.md).
Each decision is made in its focused document after code-grounded review.
-42
View File
@@ -1,42 +0,0 @@
# PRD writing rules
These rules apply to every file in `docs/prds/`.
- Search existing PRDs, issues, architecture records, and code first. Do not ask
the maintainer to repeat recorded requirements.
- A newer maintainer decision overrides an older design. Mark the old design as
superseded instead of preserving or defending it.
- Write plain English. Use a technical term only when the reader needs that
exact contract or concept.
- Use the shortest direct sentence. Write “When upgraded, existing instances
are migrated to the database,” not a description of an importer seeding
absent resources.
- State each fact once. Do not repeat a heading, summarise a list before showing
it, or restate a decision afterward.
- Every sentence must add a decision, requirement, constraint, evidence, or
verification step. Delete narration and explanations of obvious text.
- Do not turn a requested outcome into extra product features. Keep inferences
open until the maintainer or repository evidence settles them.
- Do not create a process for a logical boundary. Add one only when it must
deploy, scale, start, secure, or fail separately.
- Describe working behaviour, not explanatory UI around missing behaviour. State
what users can do and how success is proved.
- Before approval, use independent read-only reviewers to check a cross-cutting
PRD for missing behaviour and exaggerated claims. Verify and synthesise their
findings; do not copy their prose.
- Before requesting approval, review every sentence for complexity, repetition,
and unsupported scope.
- Write nothing whose truth expires. No `file.go:123` citations (cite the file
and the symbol), no progress reports on the work being designed, no dated
status claims, and no record of how a finding was produced. A phased plan is
durable design; which phase is finished is not. Do not refer to what this
document used to say: the reader cannot see it. A supersede marker is fine
when it names a file, a section or a symbol they can find. `task docs:prds`
enforces this.
- Every PRD carries one of three statuses, and nothing else in that field.
`Draft` until the maintainer explicitly approves it, `Approved` once they
have and while the work is being built, `Finalised` when the work is
complete. A finalised PRD does not change; supersede it with a new one
instead. A revision number belongs in `**Revision:**`, a pointer to the
authoritative document in `**Authority:**`, and what a past revision changed
belongs in git.
-83
View File
@@ -1,83 +0,0 @@
# Running action playbooks
**Status:** Approved
**Date:** 2026-09-23
**Parent:** `docs/prds/multi-action-playbooks.md`, epic `archie-core-t2db`
**Beads issue:** `archie-core-t2db.31`
## Why this exists
An action playbook loads and type-checks but never runs: `Store.Dispatch`
skips it and the daemon logs a warning at boot (`multi-action-playbooks.md`,
D1). This document defines when it runs, what each action does, and how the
`playbook_dispatches` ledger gates it.
## When a playbook runs
The daemon runs action playbooks at the point it pins a task's workflow
definition (`Daemon.resolveWorkflowID`), using the same `DispatchInput` the
workflow playbooks use. The definition is pinned once per task, so the run
happens once per task.
- Every action playbook whose trigger matches runs, in load order. A workflow
playbook stops at the first match because it chooses one workflow; action
playbooks choose nothing, so no match suppresses another.
- A run never changes routing. The task is pinned by the workflow playbooks
and bindings exactly as when no action playbook exists.
- An action or playbook failure never parks or fails the task. It is logged
at warning level with the playbook, the action and the task.
- A task that already names a workflow (the approval requeue) is skipped, as
it is for workflow playbooks.
- Actions run synchronously in the pin path, bounded by the daemon's context.
The only Module kind, `log`, returns immediately. A slow kind must bring its
own timeout.
## What one action does
Actions run in order against one evaluation context whose `actions` map
starts empty.
1. Evaluate `when`. False or an evaluation error skips the action (J3). A
skipped action records nothing and produces no result.
2. Evaluate every `args` value. An evaluation error stops the playbook.
3. Call `playbook.InvokeOnce` with the Module invoke as its function. The
ledger row is written first. A duplicate row skips the invoke.
4. An invoke error stops the playbook. The row stays, so the action is not
retried: the ledger promises at most once, not at least once.
5. On success, `ModuleRegistry.DecodeResult` converts the result, and it is
stored as `actions.<id>.result` when the action declares an id.
The event id in the ledger key is `DispatchInput.TaskID`, the issue's
idempotency key (`owner/repo/number`). An action therefore runs at most once
per issue for each playbook version. Editing a playbook changes its version
and lets it run again for issues it already handled.
A skipped duplicate has no result. A later action that reads it sees a
missing field: its `when` evaluates false, or its args fail and the playbook
stops. This only happens when the same issue is pinned twice under one
playbook version.
## Wiring
- `storecontract.PlaybookDispatcher` is lifted onto the daemon from the State
Store client in `internal/app/archied/bootstrap.go`, the same way
`BindingDispatcher` is.
- The daemon's `Playbooks` dependency gains the run method. The Module
registry is passed to the playbook store at load, so the daemon needs no
new dependency for it.
- With no `PlaybookDispatcher` wired, action playbooks do not run, and the
boot warning names each one. They never run without the ledger.
- The boot warning that action playbooks do not execute is removed when the
ledger is wired.
## Verification
- A matching two-action `log` playbook runs both actions in order, and the
second reads the first's result.
- Pinning the same task twice under one playbook version invokes each action
once.
- A `when` that evaluates false skips that action and the run continues.
- An invoke error stops the playbook. The task is still pinned to the same
workflow it would get with no action playbook.
- A non-matching trigger runs nothing.
- With no ledger wired, nothing runs and the warning names the playbook.
-164
View File
@@ -1,164 +0,0 @@
# Agent2Agent as archie's agent-to-agent protocol — decision
**Status:** Draft
**Date:** 2026-09-22
**Authority:** the A2A Protocol Specification v1.0.0 (`a2a-protocol.org`) for the
protocol, `docs/architecture/organisation.md` for package placement, and
`docs/architecture/migration-decisions.md` §2 for session and messaging design.
## Decision
A2A is the protocol archie speaks to other agents. It carries agent-to-agent
work: discovery of what a remote agent offers, delegation of a unit of work to it,
progress on that work, and the artifacts it produces.
## Layers
**MCP stays the tool layer.** MCP connects a model to tools and data; A2A connects
agents to agents. They are complementary and archie runs both:
`internal/tools/provider` registers MCP providers as optional capabilities, so an
A2A call and an MCP tool call are different kinds of traffic with different
owners.
**A2A rides archie's existing transports.** A2A's canonical data model is
Protocol Buffer messages and it defines a gRPC binding, so archie speaks A2A over
the gRPC and NATS it already runs. A second wire format, a second broker, or a
bespoke protocol for agent-to-agent traffic is a requirement not to introduce.
## Where A2A stops
A2A is not a general replacement for either of the two protocols archie already
has, and each boundary is a requirement rather than a preference.
- **`internal/domain/messaging` stays the human and channel layer.** A
Conversation is a ChannelID and a ThreadID, its participants are people on
Telegram, email, webhook and the dashboard, and its records are what a curator
reads. An A2A peer is not a channel participant and does not address a
Conversation.
- **`internal/agentexec` stays the daemon-to-worker execution protocol.** It
carries a Request, a Result, gate and budget policy, and capture tools between
the daemon and the agent container it owns. An A2A peer never receives that
protocol, and A2A never carries gate, budget or protection policy.
A2A is therefore an edge protocol: it exchanges work with peers outside archie's
own process boundary, and it composes with the two protocols above rather than
replacing or abstracting them.
## A2A Task mapping
**Decision: archie's work lifecycle is mapped to A2A's, not expressed in it. An
A2A Task is a view over archie's own task, and archie's status remains the record
of truth.**
This is the load-bearing decision, because A2A's Task carries its own state
machine and archie's lifecycle is the on-disk format of its task store, whose
status strings a rename migrates rather than changes.
The mapping is partial, and each gap is a case where archie knows something A2A's
states do not carry:
- **Completion by another system.** A2A's terminal states describe what the agent
did (`completed`, `failed`, `canceled`, `rejected`). archie's `merged` and
`rejected` describe what a forge did to a pull request after archie finished
its work. There is no A2A state for "an external system accepted this", so a
completed A2A task cannot express the outcome that matters most to the caller.
- **Handing work to a reviewer.** archie's `pr_open` means the work left
archie's hands for human review. A2A's `input-required` is the nearest state,
but it means the _client_ must send more input, and a reviewer is not the
client.
- **Operator decisions.** `declined`, `parked` and `dead` are outcomes of
archie's own policy and operator actions. A2A has no state for "the operator
refused this" or "a budget ran out and an operator must decide".
A WorkflowExecution is the unit an A2A task maps onto, because it is the attempt
that runs, streams and produces artifacts, and a follow-up attempt is a new
execution. A2A's own model agrees that a task is immutable once terminal and that
a refinement is a new task sharing the `contextId`, which is why archie's
per-attempt executions and A2A's per-request tasks correspond.
**Requirement:** the A2A state a peer sees is derived from archie's status by one
mapping, and archie's status is carried on the task so a peer can read what the
derivation lost. The mapping is total in the direction that matters -- every
archie status has an A2A state -- and deliberately not injective, because the
gaps above are facts A2A cannot hold.
**Requirement:** adopting A2A's state names as archie's persisted task status is
rejected. It would migrate the task store, and it would drop the forge outcomes
that tell a caller whether the work was accepted.
## What an A2A agent is
**An A2A agent is an archie Identity.** The Agent Card describes a durable,
addressable actor with an endpoint, capabilities and authentication requirements,
and an Identity is the actor archie persists, versions, suspends and scopes
credentials to.
An `agent.Persona` is not an A2A agent: a persona is prompt text selected for a
turn, and it has no endpoint or credential. An agent container is not an A2A
agent: it is task-scoped and ephemeral, and it terminates with the work it ran.
The daemon is not an A2A agent: it is the process that serves the identity.
## The Agent Card
**The Gateway serves the card, for the identity it is configured as.** A2A's
"Get Agent Card" is an abstract operation with a gRPC binding, so the card is
served through the binding archie runs and needs no HTTP listener.
**The card is derived, never hand-written.** Its skills come from the skill
catalogue, its identity from the configured Identity, and its capabilities from
what the process already advertises about itself. A card that restated
capabilities independently would be a second inventory of the same facts, which
is the class of drift the existing capability reporting exists to prevent.
**The card advertises the authentication archie applies**, and it carries no
secret. A card that named a token would be a credential published at a
well-known location.
## Server before client
**archie is an A2A server first.** Accepting A2A calls is the smaller direction
and the more valuable one: the work a peer would delegate -- an issue taken to a
pull request, through archie's gates, worktrees and review -- exists only inside
archie, and archie already serves its own contracts over gRPC to the Messaging
Service, the dashboard and the State Store. Acting as an A2A client to remote
agents is a later capability, and one that consumes the same contract.
## Authentication and authorisation
**An inbound A2A call is authenticated at the transport, by the same bearer-token
interceptor the Gateway applies to its other contracts.** A2A carries no identity
in its payload by design: identity is established where the connection is, so the
transport token is the identity and no field in a Message or Task names a caller.
**Authorisation is per skill**, which is A2A's own model: the card advertises
skills, and a caller may invoke the skills its credential is scoped to.
**Task-scoped grants are not A2A credentials.** They scope a worker's access to
one task's records inside the State Store and are issued by the daemon for its own
containers. Reusing one as an inbound A2A credential would let a peer act with a
worker's authority, which is the isolation the grants exist to enforce.
**The dashboard's authentication is not an A2A scheme.** It gates an operator
interface, not an endpoint that agents call, so it authenticates no A2A request.
## Package placement
- The contract -- A2A's data model, operations and the mapping from archie's
status -- lives in `internal/domain/<area>/`.
- The binding that carries it over gRPC lives in `internal/infrastructure/`,
beside the existing gRPC clients and servers.
- Wiring of the contract to the Gateway and the task store lives in
`internal/app/`.
## Verification
- A peer fetches the Agent Card over gRPC and receives the configured identity's
identity, skills and authentication requirements.
- A delegated task reaches an archie task, and the A2A state a peer observes
changes as archie's status changes, through the one mapping.
- A task that reaches `merged` reports an A2A state derived from it, and the
archie status is readable on the task.
- A call with no credential, and a call with a credential scoped to another
skill, are both refused, with the refusal A2A defines for them.
- A task-scoped grant presented as an inbound A2A credential is refused.
- No A2A traffic reaches `internal/domain/messaging` or `internal/agentexec`.
-83
View File
@@ -1,83 +0,0 @@
# Artifact sender
**Status:** Approved
**Revision:** 1
**Authority:** this document
## Purpose
archie-core publishes artifacts — design documents, review reports, research briefs,
runnable pages — to the offloaded.dev collaborative editor. A person reads the
artifact, comments on it, and the artifact page is the shared surface for iteration.
The receiving contract is owned by the editor: `POST /api/artifacts` with a bearer
service token, a closed field set, and server-side idempotency on `requestId` plus
last-write-wins on `sentAt`. This document owns only what archie-core sends.
## Scope
Version one publishes one-way: archie-core sends, the editor receives. The first
producer is the pull-request adversarial review: a completed `ReviewReport` is
rendered to markdown and published after the review completes.
Chat-surface tools (`create_artifact`, `update_artifact`), comment read-back, share
tokens, and runnable-format producers (`html`, `react`, `vue`) are later slices. The
receiving contract already carries them; version one does not exercise them.
## Configuration
- New `[artifacts]` section: `base_url` (site origin), `token` (`SecretRef`) with
`token_env` fallback naming `WORKSPACE_INGEST_TOKEN`.
- An empty `base_url` disables the sender: no client is constructed, nothing is
registered, and publishing degrades to a log line.
- The token is runtime configuration. It is never baked at build time.
## Sender
- New package `internal/infrastructure/artifactsync` exposing one method,
`Publish(ctx, Artifact) (string, error)`, where the string is the artifact URL.
One-method injected seam, concrete client constructed by the boot path when the
configuration resolves — the `crondelivery.Courier` posture.
- The client POSTs the frozen contract body. Each publish sends the complete
source: versions of record are full snapshots, never diffs.
- A `503` response is retried three times with backoff. `401` and `400` are not
retried; they are logged with the field reason the response names.
- `requestId` is `artifact:<task-id>:<version>` when the producer is task-backed,
otherwise `artifact:<identity>:<sentAt-utc>`. Sending the same `requestId` with
an equal or older `sentAt` must be a server-side no-op, which makes sender-side
retry safe.
## Report rendering
- `ReviewReport` gains a pure markdown renderer in `internal/domain/workflow`:
the summary as the lede, one finding per subsection with file, line, verdict,
level and the failure scenario, and the verified properties as a "checked
clean" list. Findings carry their disposition when present.
- The renderer performs no I/O and imports no infrastructure.
## Attribution
- `actor`: the producing identity. The reviewer publishes as `system:pr-reviewer`
when no task identity resolves; otherwise the task's identity name.
- `source`: the producing subsystem, `pr-review` for version one.
- `task`: owner, repository and issue number from the task when one exists.
## Failure behaviour
- Publishing never fails the producing work. A failed publish is logged with its
status and reason; the artifact is republished on the next production of the
same artifact.
- A successful publish records the artifact URL in the run report, so the PR
description or task log links to the readable artifact.
- The published URL is the editor deep link for the artifact, keyed on its
immutable id. archie-core never mints share links; sharing is an
account-holder decision made in the editor.
## Verification
- Client tests against a test server cover 201, 401, 400 with a field reason,
and 503 retry behaviour.
- The report renderer test covers a report with findings, checks, dispositions
and a not-run status.
- Configuration tests cover the disabled case, the `SecretRef` path and the
`token_env` fallback.
-115
View File
@@ -1,115 +0,0 @@
# Binding secret at-rest encryption -- decision
**Status:** Approved
**Date:** 2026-09-02
**Beads issue:** `archie-core-t2db.7` (P2), parent `archie-core-t2db`
## Problem
> Storage superseded: every store now lives in PostgreSQL behind
> `internal/domain/storecontract`, implemented in `internal/infrastructure/postgres`
> (`docs/prds/state-store-contract.md`). SQLite names below describe the
> original design.
`binding.Binding.Secret` (the per-source HMAC shared secret) is persisted as
plaintext in the `bindings.secret TEXT` column. Anyone with read access to the
SQLite file -- the same access level as `captured_events.body` and `tasks.body`
-- sees sender-side shared secrets. A leaked database file leaks secrets even
when the filesystem ACLs were correct at rest.
## Decision
Encrypt the `secret` column at rest with **AES-256-GCM** (stdlib
`crypto/aes` + `crypto/cipher`, no new dependency), transparently inside the
store: encrypt on write, decrypt on read. The store is the data boundary; its
consumers (dispatch loop, HMAC verification) receive the plaintext secret
exactly as and the webui already blanks `Secret` on every response.
### Cipher parameters
- **AEAD:** AES-256-GCM, 12-byte random nonce (`crypto/rand`), tag appended.
- **Key length:** 32 bytes, derived as `SHA-256(resolved_material)`. Kept as
SHA-256 (no Argon2id) because the source is a **32-byte high-entropy** value
resolved through the secret registry, so re-deriving to 32 bytes merely
re-shapes entropy rather than defending a weak passphrase.
- **AAD:** a static domain separator, `[]byte("arcie-binding-secret")`, so a
ciphertext cannot be relocated to a different field/column and still
authenticate. AAD is intentionally **not** row-bound: binding secrets are
random HMAC keys and are never used as lookup keys, so cross-row swap is not
a meaningful attack here.
### Envelope format
```
arcie-binding:v1:<keyFingerprint>:<base64url(nonce || ciphertext || tag)>
```
- `arcie-binding` -- domain marker
- `v1` -- format version (future cipher/KDF change is a new version, old rows
stay readable)
- `<keyFingerprint>` -- `hex(SHA-256(material))[:16]`, the identity of the key
that sealed the row, enabling rotation without a one-shot rewrite
- payload -- `base64url` of `nonce ‖ GCM.Seal(plaintext, aad)`
### Key source (confirmed with maintainer)
Resolved through the existing secret registry (`internal/secret`), the
established `SecretRef` pattern already used for `forge.webhook_secret`:
```toml
[bindings]
encryption_key = { engine = "env", key = "ARCHIE_BINDING_KEY" }
# Rotation: after swapping encryption_key to a new value, retain the previous
# material so rows sealed under the old key still decrypt.
previous_encryption_keys = [ { engine = "env", key = "ARCHIE_BINDING_KEY_OLD" } ]
```
The active key encrypts new writes; `previous_encryption_keys` are retained for
decrypt-only. Key identity is intrinsic to the material (the fingerprint), so
no manual key IDs are configured.
### Rotation story
Rotate by changing `encryption_key`, moving the old material into
`previous_encryption_keys`. Rows sealed under the old key still decrypt via
their embedded fingerprint; new writes use the new active key. Once no
remaining row references an old fingerprint, remove it from the config. Losing
a fingerprint's material before all its rows are rewritten makes those rows
unreadable -- the same operational rule as any key rotation, and the reason the
old material must be retained.
## Non-goals / deferred
- **`captured_events.body` redaction hardening** was completed alongside this
work (not deferred): `webhookguard.RedactPayload` now redacts an expanded set
of secret key markers (compound names like `access_token`, `client_secret`,
`signing_key`, `x_api_key`, …) as well as unambiguous value shapes (compact
JWTs, PEM private-key blocks) under any key. `gateway.sensitiveParameterKey`
was broadened identically to preserve the documented agreement. It remains
best-effort per `docs/prds/webhook-intake-security.md` point 5 -- a sender
that picks a name the heuristic misses is still captured.
- **Key re-derivation on config reload** is a startup concern: the store holds
the cipher for its lifetime, so a reload that changes `[bindings]` keys
requires a daemon restart to take effect. Documented, accepted.
## Wiring
- `internal/config`: add `BindingsConfig` (`encryption_key SecretRef`,
`previous_encryption_keys []SecretRef`) on `Config.Bindings`.
- `internal/app/archied/bootstrap.go` `openStores`: resolve both refs through
the already-built `secrets` registry, pass the material to `store.Open` via a
new option `store.WithBindingCipher(cipher)`.
- `internal/infrastructure/bindingcipher`: the `BindingCipher` interface and
concrete AES-GCM impl, consumed by the event-capture store; a `bindingCipher` field on `Store`, and the `Open`
option. **Nil cipher = plaintext**, so existing call sites and tests change
nothing and legacy deployments keep current behaviour until they set a key.
## Back-compat & tests
- `store.Open` gains the option variadically; all current call sites compile
unchanged.
- Existing plaintext rows are unaffected until a cipher is configured; rows
written before a cipher is installed remain plaintext and read as plaintext.
- Tests: cipher round-trip (Encrypt/Decrypt), wrong-key and tampered-ciphertext
integrity failure, envelope parse errors, and a store round-trip that asserts
the persisted column is NOT the plaintext while `GetBinding` returns it.
-158
View File
@@ -1,158 +0,0 @@
# Channel and Forge action positions (resolves `t2db.19`)
**Status:** Approved
**Date:** 2026-09-03
**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`
**Blocked on:** `archie-core-t2db.24` (the `playbook_dispatches` ledger) for
implementation of either position. Both are side-effecting, and `t2db.17`
resolved the keying scheme in design only.
## Forge
`internal/forge.Forge` is already exactly the shape a native-Go action position
needs -- a real, typed, general-purpose interface, not something that needs a
Yaegi/Module-style schema-generation detour:
```go
type Forge interface {
IssueForge // AssignedIssues, IssuesWithLabel, CloseIssue, ...
PullRequestForge // CreatePR, PRState
RepoForge // AcceptInvitations, VerifyPush, LinkBranch, ...
}
```
**Typed contract shape: native-Go-by-name, not a Module-kind.** Module's whole
reason to exist is giving _Yaegi-authored, operator-supplied_ code a typed
contract to implement. `Forge` is already a typed Go interface with real, tested
implementations (GitHub, Gitea) selected at daemon startup by `forge.New(...)`.
Wrapping it in a Module-kind schema/`go:generate` detour would duplicate a
contract that already exists. A Forge action position should be: a small set of
named operations (e.g. `close-issue`, `create-pr`, `link-branch`), each with a
typed `Args`/`Result` struct mirroring the matching method's parameters/return.
The dispatch target is `internal/domain/workflow.Forger`
(`CloseIssue`/`CreatePR`/`LinkBranch` -- already exists, already exactly these
three operations), **not** `internal/forge.Forge` directly. `organisation.md`'s
target structure places `forge/` under `internal/infrastructure/forge/`; the flat
`internal/forge` is a flat, unmigrated legacy package in the same position
`internal/workflow` was in before its own migration. A new domain package
depending on the flat package directly would create a domain-to-infrastructure
dependency that breaks the moment `forge` migrates. `workflow.Forger` is the
narrow, already-domain-owned contract that exists for exactly this reason -- the
daemon's real `forge.Forge` client satisfies it at the wiring layer.
Depend on `Forger`, not on `internal/forge`.
**Operation scope for a first slice:** `close-issue` and `link-branch`
(single-call, cleanly idempotent by event+issue identity) are the safe starting
set. `create-pr` is explicitly a heavier case -- opening a PR is a
harder-to-reverse action with its own dedup shape beyond "did this event fire
before" (a redelivered event must not open a second PR for the same logical
change) -- defer it to a follow-up slice once the keying scheme is proven on the
simpler operations, don't design it blind now.
**Host access:** the coordinator needs the same `Forge` instance
`internal/daemon`'s poller already holds (constructed once at startup via
`forge.New`). This is a daemon-composition wiring question (pass the existing
instance into the coordinator's constructor), not a new extensibility mechanism.
## Channel
### Constraints this satisfies
Messaging is the root, Channel is the integration layer, an implementation such
as Telegram sits under Channel. A channel is added by implementing one reusable
interface, and every channel must implement it. A notification mechanism belongs
under Messaging, and `channels.Channel` must not reach across into it.
### Notification is a Messaging contract, not a channel type
The contract lives in `internal/domain/messaging`. A channel implementation
satisfies it by importing its own parent, which it already does, so the
dependency stays `channels -> messaging` and nothing points back.
`channels.Channel` does not change. It gains no notification method and no
import, so the interface every channel must implement stays the lifecycle and
config contract it is. `internal/channels/telegram` satisfying both
contracts is an implementation choosing to, not the Channel layer knowing about
notification.
A notification is not a channel type because it has no lifecycle to start and
stop, no inbound direction, and no configuration schema of its own. Modelling it
as one would force `Start`/`Stop`/`ConfigSchema` onto something with no meaning
for them, and make every real channel declare whether it is a notification.
### Destinations are configured, never named by a playbook
`[notify]` becomes a set of named destinations. Each binds a name the operator
chooses to a channel already registered in the Messaging composition
(`internal/app/archiemessaging/compose.go` registers `telegram`, `email`,
`webhook`) plus that channel's own address, such as a Telegram chat id. The
existing single-webhook form keeps working as a destination named `webhook`.
A playbook action names a destination. It never names an address. Playbook
triggers are reachable from a public, unauthenticated intake surface, so an
action that could address an arbitrary chat would be a new exfiltration surface;
a destination the operator configured once is not.
### Args and Result
```go
type NotifyArgs struct {
Destination string // a name from [notify]
Text string
}
type NotifyResult struct {
Delivered bool
}
```
An unknown destination is a reported error at playbook load, not at dispatch:
the destination set is known at startup, so this follows the engine's
reject-at-load rule.
### Host access: no new process surface
`archie-messaging` is its own process (`cmd/archie-messaging`). It dials out to
the Gateway and the State Store and serves nothing, and it deliberately has no
NATS connection: `internal/app/archiemessaging/telegram_features.go` records
that it "must not decode" the daemon's `[nats]` config. So a notification cannot
be pushed into it by any route.
Delivery therefore travels the connection that already exists. Every process
that needs Messaging already dials the Gateway: `archied`
(`internal/app/archied/chat_service.go`), `archie-messaging`
(`internal/app/archiemessaging/run.go`) and `archie-ui`. The Gateway is the hub.
A new server-streaming RPC on `ChatService` lets `archie-messaging` subscribe at
startup and receive notifications the daemon publishes; Messaging then delivers
through the named channel instance it already holds in `Service.channels`. No
new listener, no NATS in Messaging, no change to how any process is reached.
The existing `Stream` RPC is not reused: it streams one chat turn's events for
one inbound message (`internal/infrastructure/gatewayrpc/server.go:Stream`).
### Out of scope
Giving playbook-originated sends the session and approval scoping the
interactive channels use. Configured destinations carry the address, so there is
no conversation to anchor to and no scoping mechanism to generalise.
## Packages this touches
- `internal/domain/eda` (or a new sibling package, e.g.
`internal/domain/eda/forgeaction`): typed `Args`/`Result` per operation, a
small registry keyed by operation name, dispatched against a
`workflow.Forger`-typed value -- not `internal/forge.Forge` directly (see
correction above).
- `internal/app/archied`: wiring the coordinator's constructor to receive the
daemon's already-built `forge.Forge` client, passed in as the
`workflow.Forger` it already satisfies -- no new lifecycle to manage, and no
change to `internal/forge` itself.
- `internal/domain/messaging`: the notification contract and its
`NotifyArgs`/`NotifyResult`.
- `internal/config`: `[notify]` becomes named destinations.
- `proto/gateway/v1` and `internal/infrastructure/gatewayrpc`: the
server-streaming notification RPC.
- `internal/app/archiemessaging`: subscribe at startup, resolve a destination to
a registered channel instance, deliver.
-110
View File
@@ -1,110 +0,0 @@
# Code graph over MCP (`tools/codegraph`)
**Status:** Draft
**Supersedes:** `symbol-reference-index.md`, which scoped only the data layer.
## The problem
Establishing what a change touches costs an agent eight to fifteen
greps, and the answers are wrong in specific ways. `grep -rn "Register("`
cannot separate `plugin.Registry.Register` from `captureintake.Receiver.Register`
from `forgerpc.Server.Register`, all of which exist here. It also matches the
sibling checkouts under `.worktrees/`, which are near-complete copies of the
module, so every count is silently inflated.
That cost lands hardest in investigation, triage and the TDD loop, where the
first question is always "what does this touch".
## Decision: exact analysis, not semantic retrieval
Tools like Greptile parse with tree-sitter, summarise each node, embed the
summaries, and retrieve semantically. That design exists because they must
serve any language. This repository is one Go module, and Go's type checker is
ground truth:
| Question | Source of truth |
| --------------------------- | ------------------------------------------------ |
| Who references this symbol? | `go/packages` + `go/types`, resolved by identity |
| What calls what? | `callgraph` RTA over SSA |
| What imports what? | `go list -deps` |
No vector database, no embedding cost, no edges invented by a summary that
drifted from the code. For a single-language repository this is both cheaper
and strictly more accurate. Copy the interface those tools expose, not their
architecture.
**A code graph does not power a documentation chatbot.** It answers structural
questions about Go symbols. Answering "how do I configure a second identity"
means retrieving prose from markdown, which needs chunking, embedding and
similarity search over a different corpus entirely. That remains a separate
capability with its own design. Conflating the two would build one system that
does neither well.
## Interface: an MCP server
`archied` already consumes MCP as a client (`internal/app/agentworker`
starts providers) and serves none. Exposing the graph over MCP reaches Claude
Code, pi, codex and Archie's own agents through one surface, with no coupling
to the daemon: it is configured like any other entry in `[[mcp_servers]]`.
Four tools, each returning JSON with file:line citations:
- `references(symbol)` — every reference site, classified `prod` / `test` /
`generated` / `dynamic`
- `callers(symbol, depth)` — inbound call edges
- `callees(symbol, depth)` — outbound call edges
- `blast_radius(file | symbol)` — the transitive neighbourhood a change reaches,
which is the single call meant to replace the grep sequence
Diagrams are deliberately not a tool. A model given an accurate subgraph writes
its own Mermaid; a diagram endpoint would only fix the rendering of something
the model already has.
## Decisions
**Every answer declares what it could not see.** RTA over-approximates
interface dispatch, and reflection is invisible: every `reflect.ValueOf` entry
in `wfextract`, `gateextract`, `pluginextract`, `secretextract` and
`logextract` makes a symbol look reachable whether or not anything calls it.
Each response carries a `dynamic_edges` field naming those boundaries. An agent
trusting a confident wrong graph is worse off than one that greps, so the graph
states its own limits rather than implying completeness.
**Warm in memory, keyed on HEAD, never persisted to disk.** `deadcode` does
whole-program RTA in under seven seconds; this does less work. The server
rebuilds when HEAD changes and refuses its cache outright when the tree is
dirty. Nothing is written to disk, because a persisted index becomes a rendered
view that outlives its evidence. That is the failure that made `STATUS.md`
report 90 of 91 findings re-verified while most statuses were 77 commits stale,
and the same one that made `reachaudit` serve a previous tree's analysis from
`/tmp` until its cache was keyed on HEAD.
**`tools/codegraph`, not `internal/`.** It is developer tooling, not daemon
runtime, so it belongs beside `docsgen`, `contractaudit` and `reachaudit` in
the `tools` module, which `task test:tools` already covers. Start as a single
Go file; split only when it earns it.
**No new dependency.** `golang.org/x/tools` is already in `go.sum` at v0.49.0.
## How it is verified
Red first. Table-driven tests against small fixture modules built in
`t.TempDir()`, asserting the behaviour that distinguishes this from grep:
1. Two methods spelled `Register` on different types resolve to two separate
records, and a reference to one does not increment the other.
2. A symbol referenced only from `_test.go` reports zero `prod` references.
3. A symbol referenced only from a `reflect.ValueOf` table reports zero `prod`
references and one `dynamic`, and names the table in `dynamic_edges`.
4. A generated file's references land in `generated`, not `prod`.
Mutation-verify each: reintroduce the conflated behaviour and watch the
assertion fail.
Acceptance is a live cross-check rather than a unit test. Run it against this
tree and confirm it reports zero production references for
`worktree.Manager.Resume`, `webui.NewDangerousService` and
`secret.DefaultRegistry`. All three were confirmed dead by hand, and `deadcode`
either stayed silent on them or, in the case of a package var, cannot represent
them at all. Agreeing with `deadcode` is not the bar. Catching what `deadcode`
structurally cannot is.
-123
View File
@@ -1,123 +0,0 @@
# Example-config and generated-config drift — decision
**Status:** Approved
**Date:** 2026-09-15
**Closes:** the checked-in-config half of audit findings `config-1` and
`repo-root-deployment-2`; strengthens `doc-drift` findings generally.
**Authority:** extends `docs/architecture/generated-documentation.md` and
`docs/prds/config-schema.md`; does not replace either.
## Question
Should `config.example.toml` and `deployments/*.toml` be _generated_, so they
cannot drift from the config code?
## Decision
**No — do not generate them. Gate them instead.** Neither file is a projection
of the schema, and generating either would destroy the thing that makes it
useful. Three verified reasons, in order of weight:
1. **`config.example.toml`'s value is its comments.** It documents **137 keys**
(measured: active _and_ commented-out), and those hand-written comments are
the file's purpose — `docs/architecture/configuration.md` states outright
that "`config.example.toml` carries documentation users are meant to
hand-edit". TOML round-tripping does not preserve comments, which is exactly
why `tomlwrite` does line-oriented edits rather than decode/encode. A
generator would emit a correct file with the documentation deleted.
2. **`docs/prds/config-schema.md` forbids building on `config.Config`.** That PRD
rejects "a reflection-based schema over `config.Config`" because the struct is
"scheduled for dissolution". A generator deriving the example from its struct
tags would build on a foundation this repo has already decided to remove.
3. **`docs/architecture/generated-documentation.md` prohibits it.** "Adding
another hardcoded type list to `docsgen` is prohibited" — so any generator
must consume a domain-owned registry, which does not exist for configuration
yet. Creating one is the config-domain migration's job, not this change's.
The deployment profiles are also not a projection: they set **3-46 keys** against
the example's 137, and they are curated overlays ("a complete config, not an
overlay", per their own headers), not near-duplicates. Generating them would add
machinery to remove duplication that largely is not there.
## The gap that is real
**Unknown config keys are silently ignored.** Verified at
`internal/infrastructure/configuration/decode.go`:
```go
if _, err := toml.DecodeFile(path, target); err != nil {
```
There is no `MetaData.Undecoded()` check, so a typo — `max_concurrancy = 4` —
parses clean, validates clean, and does nothing. That is the same failure shape
this repo's audit found repeatedly: a setting that looks applied and is not. It
is also detectable **without any hand-maintained list**, because `BurntSushi/toml`
reports exactly which keys the target did not consume.
Note the second, separate gap already admitted in writing:
`generated-documentation.md` — "`task check` does not run `docs:check`, so
generated drift is ungated."
## What to build
**1. Unknown-key detection at the loader (behaviour).** Decode with metadata and
collect `Undecoded()`. Report it as a warning at startup listing the offending
keys, and expose it so tests can assert emptiness.
**Deliberately a warning, not a fatal error.** `configuration.md`'s settled
startup policy is "a missing credential disables a capability; only an invalid
config stops the daemon". A stray key is far more likely to be an operator typo
in a file they are otherwise happy with than a reason to refuse to boot, and
`[web]` is documented as landing in a _different_ binary
(`internal/app/archieui`), so a key unknown to one process is legitimately known
to another. Failing closed here would break working deployments on upgrade.
**2. A checked-in-config contract test (gate).** Load `config.example.toml` and
every `deployments/*.toml` through the real loader and assert `Undecoded()` is
empty, with an explicit allowlist for keys another binary owns. This is the
mechanism that would have caught a renamed key left behind in an example, and it
needs no inventory.
**3. Gate generated data in `task check`.** Done. `task docs:check` runs in the
gate, closing the admitted "generated drift is ungated" hole. The
check mode did not exist when this was written; it was added for issue #855,
which also made the check non-destructive so the gate can never rewrite the
artifact it is judging.
**4. Explicitly NOT now: a generated key inventory.** `configuration.md`'s
completion criteria want "generated documentation lists every external key,
default, constraint, mutability class, owner". That is a real target and it is
the config domain's, once a domain-owned registry exists — the prohibition above
means it cannot be bootstrapped from a list inside `docsgen`. Recorded as
deferred, not rejected.
## Non-goals
- No generation of `config.example.toml` or `deployments/*.toml`.
- No reflection-based schema over `config.Config`.
- No new type list inside `docsgen`.
- No change to `archied setup`'s template: `configtemplate.Example` stays the
verbatim embedded example, hand-maintained, and `setup` continues to _edit_ it
via `tomlwrite` rather than regenerate it.
## A withdrawn premise, recorded so it is not reused
An earlier measurement claimed 17 keys were "set by a profile but documented
by no example", and used it to argue for generation. It was an
artifact: the extractor stripped comment markers and tracked a single table
variable, so commented blocks were mis-attributed. Re-checking refuted it —
`providers.<name>.api_key_env` is a real, documented backwards-compatible field
(`internal/config/config.go`, `config.example.toml`) and `[[identities]]`
is documented at `config.example.toml`. The decision above does not rest on
that measurement.
## Acceptance criteria
1. A config file containing an unknown key surfaces those keys to the operator at
startup, and the daemon still starts.
2. `config.example.toml` and every `deployments/*.toml` are loaded by a test that
fails if any key is undecoded, except keys explicitly attributed to another
binary.
3. `task check` fails when committed generated data is stale.
4. Introducing a renamed key into `config.example.toml` fails the gate (prove it
by doing it, not by asserting it).
-171
View File
@@ -1,171 +0,0 @@
# Backend-owned configuration schema for the webui -- decision
**Status:** Approved
**Date:** 2026-09-02
**Beads issue:** `archie-core-b6ew` (epic), with children `.1`-`.5`
## Decision
The dashboard's Configuration page keeps reading a secret-free,
hand-picked view of `config.Config` -- that allowlist is a safety
boundary and stays exactly as it is. What changes is who defines the
page around it: `ui/src/settings/settings.js` and
`config-row.js` hardcode every row's label, section, type, and
editability by hand; after this, the backend attaches that metadata to
each field it already allows through, and the frontend renders
sections and fields generically from what the backend sends.
This is **not** a reflection-based schema over `config.Config`.
`internal/config/config.go`'s own package doc states it is "scheduled
for dissolution: its types and methods are to be reassigned to the
domains whose behaviour they describe" -- building a generic
schema-from-struct-tags mechanism over a struct on its way out would be
building on a foundation this repo has already decided to remove.
Instead, every field already in `ConfigView` (`internal/webui/api_config.go`)
got there because someone deliberately vetted it as safe to show; the
schema adds a hand-authored descriptor to that same deliberate act,
not a new mechanism that re-derives safety automatically.
## Why now
Task #6's investigation (`/9/26`) found the concrete failure this
produces: `Repo.AllowConcurrent` and `Repo.MaxRetries` already reach
`GET /api/config` (`RepoView` in `api_config.go`), but the
repositories card renders a static read-only table that never shows
them, so the fix for "why isn't a second agent running" required an
agent tracing Go source instead of a checkbox on the dashboard.
`Repo.ReviewEnabled` is worse: it never reaches the API at all. Both
are symptoms of the same root cause -- the frontend decides what a
field means and whether it's shown, and nothing keeps that in sync
with what the backend actually allows.
## Shape
```go
// internal/webui/config_schema.go (new)
type ConfigFieldType string
const (
FieldString ConfigFieldType = "string"
FieldInt ConfigFieldType = "int"
FieldBool ConfigFieldType = "bool"
FieldDuration ConfigFieldType = "duration"
FieldEnum ConfigFieldType = "enum"
FieldStructured ConfigFieldType = "structured" // repositories, models, providers
)
type ConfigField struct {
Key string `json:"key"` // dotted path, matches UpdateConfig's key space
Label string `json:"label"`
Description string `json:"description,omitempty"`
Type ConfigFieldType `json:"type"`
Value any `json:"value"`
Editable bool `json:"editable"`
LockedReason string `json:"locked_reason,omitempty"`
Overridden bool `json:"overridden"`
Options []string `json:"options,omitempty"` // enum only
RestartRequired bool `json:"restart_required"`
}
type ConfigSection struct {
ID string `json:"id"`
Label string `json:"label"`
Fields []ConfigField `json:"fields"`
}
```
`handleConfig` builds `[]ConfigSection` from the existing per-field
values it already assembles, plus `overlay.DeniedKeys` for
`LockedReason` and the existing `Overridden` list -- both already
computed just re-attached per field instead of returned as
side-channel maps the frontend cross-references by key string.
`Locked`/`Overridden`/`Reload`/`Provenance` stay as top-level
`ConfigView` fields; they describe runtime state (what happened on
the last reload, which keys the overlay refuses), not the field
catalogue, and duplicating that logic per-field would be the same drift
risk this change exists to remove.
`FieldStructured` fields (repositories, models, providers) carry
`Value` as structured JSON and are rendered by dedicated
editors, not the generic renderer -- see "What this does not do".
## Sections
Matches the cards the settings page already has: `identity`,
`repositories`, `models`, `providers`, `budgets`, `storage`,
`containers`, `web`. No new sections; this is metadata on existing
rows, not new configuration surface.
## Frontend
`config-row.js`'s `row(label, value, opts)` becomes the renderer's
private implementation detail, called generically:
```js
for (const section of schema.sections) {
const rows = section.fields
.filter((f) => f.type !== "structured")
.map((f) =>
row(f.label, f.value, {
key: f.key,
type: f.type,
options: f.options,
locked: f.locked_reason,
overridden: f.overridden,
restartRequired: f.restart_required,
}),
);
// structured fields render through their dedicated editor (b6ew.4)
}
```
`settings.js` stops knowing that `containers.max_concurrency` is an
`int`, belongs in the "Sandboxed containers" card, or requires a
restart. It knows how to render a section and a field of a given type.
## What this does not do
- **Does not marshal `config.Config` wholesale or add reflection over
it.** The allowlist boundary in `api_config.go` is unchanged; this
adds a label next to a value that was already being shown.
- **Does not make every backend field appear automatically.** A field
still requires someone to write its descriptor, same as it requires
someone to add it to `ConfigView` -- the fix is one
source of truth instead of two, not zero review.
- **Does not solve structured editing generically.** Repositories and
maps get their own typed editor (`archie-core-b6ew.4`), not a
generic "array of objects" renderer -- a repo's fields have their
own validation shape (owner/name pair identity, gate command
argv) that a generic structured-field renderer would either get
wrong or reinvent per-type anyway.
- **Does not change what `UpdateConfig`/`overlay.DeniedKeys` accept.**
`Editable` on a field descriptor mirrors that existing policy; it
does not grant new write access.
## Acceptance criteria (epic-level; see child issues for per-task detail)
1. Every field rendered as a hardcoded row in `settings.js`
has a backend-authored descriptor with type, label, and section.
2. `Repo.ReviewEnabled` reaches the API and the dashboard, alongside
`AllowConcurrent` and `MaxRetries`.
3. Adding a new scalar field to the schema requires one backend
descriptor and zero frontend changes to appear correctly labelled,
sectioned, and editable.
4. `TestHandleConfigNeverLeaksSecrets`-style coverage extends to the
schema response; no descriptor exists for a secret-bearing field.
5. A schema-fixture-driven frontend test asserts the generic renderer
needs no field-specific branch to render every scalar field type.
## Work breakdown
- `archie-core-b6ew.1` -- descriptor types + hand-authored section/field
metadata for every existing `ConfigView` field.
- `archie-core-b6ew.2` -- `handleConfig` returns the schema-driven
shape (depends on `.1`).
- `archie-core-b6ew.3` -- generic frontend renderer for scalar/bool/
int/enum/duration fields (depends on `.2`).
- `archie-core-b6ew.4` -- structured editors: repositories (incl. the
`ReviewEnabled` gap), models, providers (depends on `.2`).
- `archie-core-b6ew.5` -- contract tests for metadata completeness,
secret-safety, and generic-renderer coverage (depends on `.3`, `.4`).
-175
View File
@@ -1,175 +0,0 @@
# Contract conformance audit — decision
**Status:** Finalised
**Scope:** an **advisory** report, deliberately **not** part of `task check`.
**Date:** 2026-09-15
**Authority:** sibling to `archie-core-06ag` (standing reachability audit) and
`docs/architecture/dependencies-and-contracts.md`. Replaces neither.
**Open:** withdraw it, or rebuild it structurally. See "Open decision" — not to
be resolved by hardening the regexes.
## Question
Does every declared contract surface have a consumer, or an explicit declaration
that it has none?
Reachability (`tools/reachaudit`) asks the complementary question — _is this code
in a shipped binary?_ — and cannot see a capability that is **reachable and
unconsumed**. `ratelimit` was in the binary closure and called by nothing
(`archie-core-6wxb`); reachability would not have found that.
## Decision
Yes, as an advisory survey. `tools/contractaudit` classifies each subject of each
surface:
| Classification | Meaning | Fails `--strict`? |
| ----------------------- | ----------------------------------------------------------------------------- | ----------------- |
| `CONSUMED` | a call site exercises it | no |
| `DECLARED-UNCONSUMED` | allowlisted in `docs/contract-declarations.json`, with a reason and a tracker | no |
| `UNDECLARED-UNCONSUMED` | nobody reaches it, nobody declared it | **yes** |
| `STALE-DECLARATION` | an allowlist entry that is no longer true | **yes** |
There are **four** classes and **two** of them fail. The allowlist must match
reality exactly, and it fails in both directions: a missing entry is a finding,
and an entry that outlived its subject is a finding, because a stale allowlist is
how a check quietly stops checking anything.
**Not gated.** `task contract` is advisory and `task check` does not run it,
matching `tools/reachaudit`. The surfaces are discovered by scanning source text,
so a rename or a reformat elsewhere in the tree can change the output with nothing
actually wrong. It has already produced 16 false "unconsumed" readings once, when
the dashboard's request helper was renamed. A check that can fail for reasons
unrelated to what it measures must not be able to break a build.
## Surfaces actually built — three, not five
| Surface | Subjects | "Consumed" means |
| ------------------------------------ | ------------- | -------------------------------------------------------- |
| `proto/state/v1` `StateStoreService` | **45 RPCs** | an adapter body calls `client.<Rpc>(...)` |
| `proto/gateway/v1` `ChatService` | **21 RPCs** | same |
| `internal/webui` dashboard routes | **49 routes** | a path literal appears as a call argument under `ui/src` |
Consumption for the gRPC surfaces is established by **scanning adapter source
text** for calls through the generated client, not by reflection. See the errata
below: the first revision of this document claimed reflection, and the first
implementation did use it, but the shipped mechanism is a regex and the document
was not updated to match.
## What this audit has actually found
**Nothing actionable.** On the current tree it reports 0 undeclared and 0 stale.
Its only allowlisted entries are two RPCs superseded by their streaming variants
(`ListCaptures`, `ListUndispatchedCaptures`), which were already known from the
source comment on `staterpc.Client.ListCaptures`.
Every real defect found in the session that produced this tool was found by other
means:
- the three 415 refusals, by reading `authorizeTaskMutation` and reproducing the
browser's exact headers against the real handler;
- the dashboard client's duplicated request plumbing, by reading the module.
Recorded plainly because a survey that has never found anything is evidence about
the survey, not about the tree.
## Errata — claims in the first revision of this document that were false
- **"RPC coverage is derived by reflection over the exported client type."**
It is not. `proto.go` regex-scans adapter bodies for `client.Method(` calls.
The reflection version was replaced and the document was not updated. The unused
`google.golang.org/grpc` family in `tools/go.mod` was residue from that
iteration; `go mod tidy` removed it on 2026-09-15.
- **Surface sizes of "43 / 12 / 52".** The real counts are 45 / 21 / 49.
- **"Three classifications, and the third is the only finding."** Four classes,
two of which fail.
- **"Raw `fetch()` calls caused 401s to render as `refused`/`broken`."** Wrong.
Every raw call site passed `res.status` to `ApiError`, so `classifyActionError`
already mapped 401 to `session-expired`; the chat stream never classified at
all. The real defect in that area was different (below).
- **A five-surface "Shape" naming `surface.go`, `generated.go`,
`declarations.go`, and `testdata/`.** None were written. The real files are
`main.go`, `audit.go`, `proto.go`, `webui.go`.
## The two gaps this was aimed at
**1. `docsgen check` is documented and does not exist.** Closed by issue #855.
(issue #855 / `archie-core-5gzx`). `tools/docsgen` now has a `check` subcommand
and `task docs:check`, wired into `task check`: it generates into a temporary
directory, compares against the committed artifact, names the authoritative Go
definition behind each mismatch, and never writes to the working tree.
`docsgen data` and `docsgen asyncapi` remain target-only.
**2. The dashboard's client was not centralised while its own docstring claimed
it was.** Now closed by `18e8f8f`. The docstring said "Single place that knows how
to talk to archied… so auth handling and error shape live in one file" while 22
call sites built their own `fetch`, headers, timeout and error handling, and
`chat.jsx` built a 23rd. The defect actually present there was that three
bodyless mutations — `bindingApprove`, `mappingDelete`, `bindingDelete` — omitted
`Content-Type` and were refused **415** on every use, because
`authorizeTaskMutation` requires a JSON media type even when there is no body.
The Go tests missed it because their helper set `Content-Type` unconditionally,
including for a nil body.
## Testing rule — applies to this tool and to anything like it
**Do not assert on the wording, formatting, or content of generated or
hand-authored text and config files.** A test that pins a source snippet, injects
text into a fixture, or counts an identifier in a file is testing that file's
formatting rather than the behaviour under test: an extra space, a newline, a
rename, or a comment that merely mentions the token breaks it, and the
maintenance burden is permanent. A test that cannot tell "the code is wrong" from
"the file is formatted differently" is testing the wrong thing.
Assert behaviour on the observable effect — the request a client makes, the value
a function returns — and keep parsing out of the assertion. Where a parser must
exist, test it through its own interface with in-memory input, not through a file
on disk.
The first revision of this tool violated this in six tests (four that injected
text into fixtures, two that asserted on a source file's contents). All six were
deleted on 2026-09-15. The dashboard suite's "api.jsx holds exactly one fetch
call" check was deleted for the same reason: it broke on a reformat and on a
comment that mentioned `fetch`, and it was patched with a comment-stripper instead
of being removed. Every `api.*` method is covered behaviourally instead, by
asserting the headers and body each one sends.
## Open decision
1. **Withdraw.** Delete the tool, the allowlist, this document, and the `contract`
task. It has found nothing, its mechanism is unsound, and the same question is
better asked by a behavioural test per method.
2. **Rebuild structurally.** Take the contract from the compiler instead of from
text: the generated `StateStoreServiceClient` / `ChatServiceClient` interfaces
give the exact RPC set, and `go/ast` over the adapter bodies and
`internal/webui/server.go` is formatting-insensitive where a regex is not.
Cost: the dashboard-consumer half has no Go-native JS parser, so it is either
dropped or replaced by a behavioural test per route — which is what would have
caught the 415s.
Neither is "make the regexes cleverer". Recorded here rather than acted on
unilaterally because withdrawing a capability and rebuilding one are both larger
decisions than adding a report.
## Acceptance
1. `task contract` prints a report and exits 0.
2. Every unconsumed subject appears with a classification, and where declared with
a reason and a tracker id.
3. `--strict` fails on an undeclared entry **and** on a stale one. Verified by
construction against a copy of the tree, not by asserting on the tree's text.
4. The tool neither deletes nor rewrites anything.
5. No test in this tool asserts on the content or formatting of another file.
## Non-goals
- No runtime schema validation of HTTP responses. The webui handlers already
return non-nil slices on every empty path (`[]SkillView{}`, `[]CuratorView{}`,
`make([]taskView, len(tasks))`), so the nil-slice class does not apply; adding a
live-stack validator before it has a defect to find is scaffolding. Deferred,
and filed as `archie-core-nddv`.
- No re-parse of the `.proto` as a second source of truth; `buf lint` and
`buf breaking` already own it.
- No generation of `config.example.toml` or `deployments/*.toml` — settled
against in `config-example-drift.md`.
- No change to `tools/reachaudit`'s scope or report shape.
-122
View File
@@ -1,122 +0,0 @@
# Control-plane apply status
**Status:** Approved
**Date:** 2026-09-21
**Tracking:** `archie-core-pskb`, and `archie-core-nwa0` which depends on it
## Outcome
An operator who edits a control-plane resource can see which processes are
running that version, which are still on an older one, which rejected it, and
which have stopped reporting.
`docs/prds/runtime-control-plane.md` requires this and does not say where the
report goes. This decides that.
## Where the report goes
Apply status is a State Store contract surface. `ControlPlaneService` is the
surface for editing a resource, and a status report is not an edit. The
precedent is the config snapshot pair: a process publishes what it knows, the
UI process reads it, and both RPCs are administrative, so a task-scoped grant
reaches neither. That denial needs no new rule: `authorizesTaskScopedCall`
names three methods and denies everything else.
`docs/prds/state-store-contract.md` gains the pair in its inventory, and its
RPC count at two places moves from 45 to 47.
The read returns all records as a list, including an empty one. The
`found=false` convention for absent single rows does not apply.
## What is reported
One record per process and resource kind, replaced in place. It holds the
process name, the resource kind, the version applied, the error if the process
could not apply it, and the time it reported.
Each process re-stamps its records every 30 seconds. A record is stale once it
is older than 90 seconds, and a stale record means the process that wrote it is
no longer running. The report time is therefore a liveness signal, not only a
write timestamp.
A process reports at the point it applies a resource, so the record says what
happened rather than what was intended. Nothing probes.
Process names come from one shared constant naming `archied`, `archie-gateway`
and `archie-messaging`. A deployment runs at most one of each. Writer and
reader are bound to that constant by test, because a drifted name is
indistinguishable from a process that never reported.
## Which processes report
- `archied` and `archie-gateway` apply every restart-required kind through
`boot.runtimeConfig`, at boot and on SIGHUP.
- `archied` also applies the live kinds it watches, and reports each update it
applies.
- `archie-messaging` applies channel settings at startup and reports that kind.
## What can be reported, and what cannot
A process reaches its apply point only after the State Store has answered it.
At startup, when the State Store is unreachable, the process exits or refuses
to start and writes no record. A live watcher that loses its established
control-plane stream reports the connection failure against its last applied
version while it retries. Re-establishing the stream clears that outage record
without clearing a versioned document rejection. A transport failure is not a
document rejection; it reports that live delivery is unavailable.
Absence has two meanings and the UI never collapses them: no process applies
this kind, or a process that applies other kinds has not reported this one.
## Relationship to the reload status
Apply status covers control-plane resource kinds. `ReloadStatus` covers the
file document and stays the only report for a SIGHUP that failed to resolve or
validate it. Neither is derived from the other.
Writing a record is best-effort. On the SIGHUP path it takes its own bounded
context, separate from the budget the reload spends reading the control plane,
and a failed write is logged rather than turned into a failed reload.
## What the UI shows
The settings page shows, per resource, the stored version beside each process's
applied version, error, and report time. A process on an older version of a
restart-required resource is pending a restart. A process with an error is
failed, with the error beside it. A process whose record is stale is unknown,
never current.
## A record outlives the process that wrote it
Records are replaced in place, so a process that applies a version and then
stops would otherwise leave a record asserting that version indefinitely, and
the settings page would show a dead process as current.
`docs/prds/status-health-surface.md` faced the same choice and stamped the start
of a poll pass so a wedged poller reads as stale rather than healthy.
Settled: the re-stamp above. The alternatives considered were
carrying the instance identity generated at process start, which detects a
restart but not a death, and accepting the limitation with the page saying so.
## Verification
- A process that applies a resource writes a record carrying that version.
- A process whose apply fails validation writes a record carrying the error and
no new version.
- A live watch outage is reported against the last applied version until the
stream is re-established; re-establishment preserves any outstanding
versioned rejection.
- A reload that fails leaves the previously applied version recorded.
- A record written under a process name outside the shared constant fails the
test binding writer to reader.
- A task-scoped credential is refused by both RPCs.
- A failed report does not fail the reload that produced it.
- A record that stops being re-stamped renders as unknown rather than current.
## Not included
- History of past applies. Records are current state; resource history already
records what was written.
- Checking a live replacement before switching to it. That is
`archie-core-nwa0`, which reports its failures through this surface.
- Any change to how a resource is applied.
-177
View File
@@ -1,177 +0,0 @@
# Curator sampler wave 1: `Sampler` interface + four cheap strategies -- decision
**Status:** Approved
**Date:** 2026-09-05
**Beads issue:** bead `archie-core-1786637500776-416-600a66e5` / GitHub #437
covers the embedding-backed follow-on strategy only. This PRD covers the
prerequisite interface and the cheap strategies.
**Parent epic:** `archie-core-1786637500725` (curator engine)
**Depends on:** nothing shipped (this is itself a prerequisite)
**Blocks:** the embedding-backed surprisal strategy (GitHub #437), which
implements this same interface once the embeddings capability
(`internal/domain/embedding`, this change) lands
## Problem
A future curator that reviews a large body of content (memories, sessions,
skills) cannot always afford to run its agentic budget over every candidate
every pass. It needs to pick a bounded subset first. GitHub #437's acceptance
criteria requires that subset-picking to sit "behind a `Sampler` interface
that wave 1 of the curator epic ships (cheap strategies: recency, random,
all, staleness proxy)" and that the embedding-backed strategy implement "the
same interface" later. No such interface, and none of the four cheap
strategies, exist anywhere in the codebase (bead 434e5bb9's closure
without a linked PR was the tracker being wrong, not the code existing) --
this PRD is the one-page settled design for it, per this repo's Scope
Discipline rule.
## Decision
A `Sampler` is a pure, call-scoped selection function: given a fixed slice of
candidates and a request, it returns a subset. No lifecycle, no host access,
no I/O for the four wave-1 strategies -- they are computation only, so they
live directly in `internal/domain/sampling` (a domain package, not
`internal/infrastructure/*`) alongside the contract, the same way
`curator/activity.go`'s pure ring buffer sits next to `curator/contract.go`
rather than in an infrastructure package.
```go
// Package sampling is the curator sampler family: given a bounded set of
// candidates, pick a subset to spend a curator pass's agentic budget on.
// See docs/prds/curator-sampler-wave1.md.
package sampling
// Candidate is one item eligible for sampling. It is deliberately narrow:
// an opaque identifier, the timestamp the timestamp-based strategies score
// against, and an open Metadata bag for whatever a future strategy needs
// (e.g. the embedding-backed surprisal strategy's vector) without widening
// this struct for every strategy that comes after wave 1.
type Candidate struct {
ID string
At time.Time
Metadata map[string]any
}
// Request carries the knobs every strategy shares: a selection cap and a
// deterministic seed. Both are optional -- Cap 0 means unlimited (the "all"
// strategy relies on this), Seed 0 is a valid seed, not "unset".
type Request struct {
Cap int
Seed int64
}
// Sampler selects a subset of candidates to spend a curator pass's agentic
// budget on. Every implementation -- the four here and the future
// embedding-backed surprisal strategy (GitHub #437) -- must be
// deterministic given the same candidates and Request: same inputs, same
// output, every time. That is what makes a pass reproducible and testable,
// and is GitHub #437's stated acceptance criterion for the strategy it
// adds behind this same interface.
type Sampler interface {
// Name identifies the strategy for logging/attribution (e.g.
// "recency", "random", "all", "staleness", later "surprisal").
Name() string
// Sample selects from candidates per req. Implementations must not
// mutate candidates or rely on anything but candidates and req --
// determinism depends on that.
Sample(ctx context.Context, candidates []Candidate, req Request) ([]Candidate, error)
}
```
### The four wave-1 strategies
All four are `internal/domain/sampling` types constructed with `NewX(...)`,
each implementing `Sampler`:
- **`recency`** (`NewRecency()`): sorts candidates newest-`At`-first (stable
sort, ties keep input order so output is deterministic even when two
candidates share a timestamp), then truncates to `req.Cap` (0 = all).
- **`staleness`** (`NewStaleness()`): the mirror of recency -- sorts oldest-
`At`-first, then truncates to `req.Cap`. This is explicitly a _proxy_:
"hasn't been touched in the longest time" using whatever timestamp the
caller populated `Candidate.At` with (created, updated, or
last-reviewed -- the caller's choice, not this package's), never the
embedding-based surprisal calculation GitHub #437 owns.
- **`all`** (`NewAll()`): no filtering. Returns candidates in input order,
truncated to `req.Cap` (0 = every candidate). Input order is the only
order this strategy has an opinion about, and preserving it is what makes
it deterministic.
- **`random`** (`NewRandom()`): a uniform-random subset, sized to
`req.Cap` (0 = every candidate, order-shuffled). Determinism comes from
`req.Seed`: `math/rand/v2`'s `rand.New(rand.NewPCG(seed, seed))` seeded
per call (not a package-level or struct-level generator), so the same
`(candidates, req)` pair always produces the same permutation regardless
of call order or concurrent callers -- required for GitHub #437's
determinism criterion and for this package's own tests.
### Why one shared `Request` and not one options struct per strategy
The embedding-backed strategy (GitHub #437) is deferred, but its stated
shape -- "sample up to a candidate cap," a seed for reproducible tie-
breaking in the power-iteration -- already fits `Request{Cap, Seed}`
without modification. A per-strategy options type would mean GitHub #437
either reuses this one (proving it was unnecessary to split) or grows its
own incompatible shape that the `Sampler` interface can't express without a
breaking change later. One shared, small `Request` is the smallest thing
that already accommodates the known future consumer.
### Why `Candidate.Metadata map[string]any` instead of a typed field per strategy
Only `ID` and `At` are used by any wave-1 strategy. `Metadata` exists solely
so GitHub #437 can carry an embedding vector (or whatever else the k-NN/
power-iteration step needs) through the _same_ `Candidate` type without this
package importing `internal/domain/embedding` or growing a `Vector` field
that every non-surprisal strategy ignores. Untyped and optional, exactly
like `image.GenerateRequest.Options` and `curator.Action.Detail`'s existing
"provider-specific overflow" convention elsewhere in this codebase.
## What we deliberately do NOT do
- **No curator-family wiring.** `curator.Registrar` gains no `Sampler`
field and no curator declares one in this change. Nothing in
`internal/domain/curator` consumes `sampling.Sampler` yet -- there is no
curator that samples anything. Wiring a sampler into a real
curator's `Pass` is that future curator's job, not this prerequisite's.
- **No embedding-backed strategy.** That is GitHub #437, explicitly
deferred behind the embeddings capability this same change also adds
(`internal/domain/embedding`) -- see that issue for the k-NN graph /
power-iteration / surprisal-scoring algorithm. This package only
guarantees the interface shape GitHub #437 must implement.
- **No persistence, no candidate discovery.** `Sampler.Sample` takes
`candidates` as a plain slice; where they come from (a memory store, a
session list, a skill directory) is entirely the caller's concern, same
boundary `curator.Registrar`'s `SkillStore`/`ConversationSource` already
draw between "the curator finds candidates" and "the curator engine acts
on them."
- **No configuration surface.** Strategy selection (which `Sampler` a
curator uses) is a future curator's constructor argument, not a new
`[curator]` config section -- no curator exists yet to configure.
## Acceptance criteria
1. `Sampler` interface plus `Candidate`/`Request` types exist in
`internal/domain/sampling`, importing nothing from
`internal/infrastructure/*` or `internal/app/*` (domain-layer rule).
2. Four `Sampler` implementations (`recency`, `random`, `all`, `staleness`)
with table-driven tests proving: correct selection per strategy,
`Cap` truncation (including `Cap` larger than the candidate count, and
`Cap` 0 meaning unlimited), and -- for `random` -- that the same
`(candidates, req)` produces the same output across repeated calls
(determinism), while a different `req.Seed` can produce a different
permutation.
3. Every strategy's `Sample` leaves the input `candidates` slice
unmodified (verified by a shared test helper across all four).
4. The interface shape is reviewed against GitHub #437's stated
acceptance criteria ("a `Sampler` given fixed inputs producing
deterministic selection," "sample up to a candidate cap") and
accommodates them without a breaking change -- this document's
"Why one shared `Request`" section is that review.
## Files this change adds
- `internal/domain/sampling/contract.go` -- `Sampler`, `Candidate`,
`Request`
- `internal/domain/sampling/recency.go`, `staleness.go`, `all.go`,
`random.go` -- the four strategies
- `internal/domain/sampling/*_test.go` -- table-driven tests per strategy
plus the shared non-mutation test helper
@@ -1,135 +0,0 @@
# Dashboard-aware chat: Archie sees the page, and points the operator there
**Status:** Approved
**Date:** 2026-08-26
**Compound:** the "chat available on any page" surface work (global chat presence)
## Decision
Make the web chat **dashboard-aware**: the agent is told which dashboard page
the operator has _open_, knows what each page is for, and can **point**
the operator to the relevant page with a **clickable destination chip** the UI
renders and follows - Option B (context + navigate), not just "tell me in text."
Three seams, each an existing extension point, one new tool and one message field:
1. **Current page, into the prompt.** The browser sends its route with every
chat message; the gateway threads it into the system prompt's runtime-metadata
env block. Archie always knows where the operator is looking.
2. **Page index.** A page_index tool lists the dashboard pages and what each one
shows, so Archie knows what to point at - the agent "has the map".
3. **Navigate.** A dashboard_navigate tool returns a structured path/label; the web
UI renders it as a clickable chip that routes the operator there. This is the
"plenty of resources" the requirement named.
We deliberately keep the agent's answer honest: the chip is _evidence_ it can
validly produce because dashboard_navigate is a real tool whose result is
rendered, not a markdown link the model invents.
## Why now
This is the natural next step of the "chat on any page" work, and the original
request named it explicitly: _"archie should be able to see what page you're on
too. and point out where to go. so it needs plenty of resources."_ The chat
is a full-page route with no knowledge of the rest of the dashboard; the agent
cannot see which page the operator is on and cannot reliably direct them anywhere.
The critique of the chat UI already identified "chat is not available on any page"
as the largest structural gap (P1). This design is the capability that makes that
gap worth closing.
## Shape of the API
### Message field (gateway.go)
Add Page to Message:
```go
// Page is the dashboard route the operator is on when they sent this message
// (e.g. "/tasks", "/logs"). Empty for non-web channels, which have no page
// context. It is per-message, not per-session: the operator navigates freely
// while a conversation stays open.
Page string
```
### Web request (api_chat.go)
chatMessageRequest gains Page, decoded into Message.Page in decodeChatMessage.
### System prompt config (prompt.go)
SystemPromptConfig gains Page; BuildSystemPrompt passes it through to the template.
The env block of archie.md.tpl renders the current page when set.
### Page index (dashboard_tools.go, new)
A package-level registry mapping route to {Label, Description}. page_index returns
the list so the model knows what each page shows:
```go
type DashboardPage struct {
Path string // "/tasks"
Label string // "Tasks"
Description string // "Issues Archie picked up, and where they stand."
}
```
### Navigation tool (dashboard_tools.go)
dashboard_navigate validates its path against the registry and returns the resolved
path/label. Unknown path means a clear error, not a guess. The model must call the
tool (not invent a link) to produce a chip, so the chip is honest.
### Tool wiring (turn.go)
extraTools already merges TaskTools + SessionTools. Add the dashboard tools alongside
them, gated on the channel being the web UI. The tool list is built from the same
registry the prompt's page line comes from, so the agent never points at a page it
was not told about.
### Web UI (chat-render.js, chat-tools.js)
A dashboard_navigate tool call renders as a **clickable chip**: an anchor with
href="/tasks" and the label. The chip is a
real link that works from any page once the chat is a global presence. The chip is
styled as an action, not a code line, so it visibly invites a click.
### Route transfer (chat.js)
Each sendMessage includes the current location.hash route as page in the stream
request body, so the backend gets the operator's live position.
## What we deliberately do NOT do
- **No navigation from a markdown link.** The model must use dashboard_navigate; a
bare "click here" is not rendered as a trusted route.
- **No full-page route hijack from the chat.** The chip sets location.hash.
- **No page index for non-web channels.** Telegram/discord have no dashboard.
- **No automatic history annotation.** Page is per-message from the browser.
- **No change to the dangerous-action approval flow.** Separately tracked.
## Acceptance criteria
1. Chat messages from any page carry the current page to the agent's prompt.
2. page_index returns every dashboard page with a plain-language description.
3. dashboard_navigate renders a clickable chip that routes to the target page.
4. dashboard_navigate rejects an unknown route with a clear error, no chip.
5. Non-web chat channels get neither tool, and Message.Page stays empty.
6. Tests cover prompt page line; navigate resolve/reject; non-web exclusion; and the
web request decoder round-trips page.
## Files this change touches
- internal/gateway/gateway.go - Message.Page
- internal/gateway/prompt.go + templates/archie.md.tpl - SystemPromptConfig.Page, env line
- internal/gateway/dashboard_tools.go (new) - registry, page_index, dashboard_navigate
- internal/gateway/turn.go - merge dashboard tools into extraTools
- internal/gateway/prompt_test.go + dashboard_tools_test.go (new) - prompt + tool tests
- internal/webui/api_chat.go - chatMessageRequest.Page, decoder
- ui/src/chat/chat.js - send page with each stream request; render navigate chips
- ui/src/chat/chat-render.js + chat-tools.js + chat.css - clickable chip
- ui/src/main.js + shell - persistent chat presence + current-page tracking (separate)
> The persistent "chat on any page" surface (drawer/launcher in the shell) is the
> companion change that makes the chip navigable from anywhere. It is the same
> capability and should land with or just before it, but is not required for the
> backend to be correct and testable on its own.
-52
View File
@@ -1,52 +0,0 @@
# Dashboard live state
**Status:** Approved
## Decision
The dashboard must not require passive **Refresh** buttons. One app-wide Pinia
store owns the existing `/api/stream` EventSource and translates backend events
into resource revision counters. Pages load their authoritative HTTP projection
on entry and re-read it when the relevant revision changes. Event payloads are
invalidation signals, not substitute read models.
SSE remains the transport. Dashboard updates are server-to-client only, and the
existing stream already provides replay, reconnect, and persisted ordering; a
WebSocket would add a second transport without adding a capability.
The first slice covers resources for which the backend already emits a truthful
signal:
- task events invalidate the dashboard, task board, workflow statistics, and
the matching task-run page;
- capture events invalidate the capture list;
- curator events invalidate curator status, and curator actions also invalidate
the skill catalogue;
- update reports invalidate System status;
- opening a page always loads its resource, and reopening the SSE stream
invalidates mounted projections after a connection loss.
Logs retain their dedicated SSE tail. Local mutations continue to re-read their
own resource after success. Configuration, channels, and catalogues that have no
backend change event load on route entry; future write contracts must emit an
owner-specific event rather than introduce polling or restore a button.
## Boundaries
The Pinia store owns browser connection state and invalidation only. It does not
become an alternate backend cache or copy domain state into a generic global
object. Existing feature modules continue to own their DTOs and API reads.
Operational commands are not refresh controls. Channel **Reload** remains an
explicit adapter lifecycle action. Authentication recovery is also not a data
refresh: a 401 moves the application into shared authentication state; reloading
the same URL cannot restore Archie's missing or rotated token and must not be
offered as a fix.
## Verification
- No passive page action renders the label **Refresh** or **Retry** for a read.
- Only one shared `/api/stream` EventSource is opened by the application.
- Resource classification tests distinguish task, capture, curator, skill, and
update invalidations.
- UI tests, type checking, generated asset freshness, and `task check` pass.
-101
View File
@@ -1,101 +0,0 @@
# Dashboard port: what the agent delivers
**Status:** Approved
**Date:** 2026-09-20
**Beads:** `archie-core-tavn` (epic), `archie-core-ocfm` (navigation)
**Reads with:** `docs/prds/vue-migration-checklist.md` (the item-by-item)
This is the standard the port is held to. The checklist says what to port; this
says how, and what counts as done. It exists because the first attempt ported
the flat topbar verbatim and invented a palette, both of which had already been
decided elsewhere.
## The deliverable
The Preact dashboard, rebuilt in Vue 3 with shadcn-vue, feature complete
against the checklist, gate clean, with `ui/dist` rebuilt and committed in the
same commit as the source it was built from.
## Non-negotiables
- **Vue 3 + shadcn-vue (Reka UI, Tailwind v4, Lucide).** A component that
exists in shadcn-vue is not hand-rolled. Add it with the CLI
(`npx shadcn-vue@latest add <name>`), do not paste it in.
- **History routing.** `createWebHistory`, `base: "/"`. No hash routing.
`src/legacy-hash-redirect.ts` handles old `#/path` links and stays.
- **No test port.** 43 Preact test files are deliberately dropped.
`task test:ui` is a `vue-tsc` typecheck. Write a test when there is a real
failure to pin, not to re-assert a port.
- **Do not downgrade TypeScript.** The target is TS 7 native, not TS 5.
- **`ui/dist` is law.** Never hand-edit it, never omit it, never revert it.
- **`task check` is the gate.** Not an assembled substitute for it.
- **Beads, not markdown TODOs**, for anything that outlives the change.
- **Conventional commits**, scoped `feat(webui):`. Commit gate-clean work
without asking. Do not push without being told.
## Componentisation
One component, one job, one file. A surface is composed from named components,
not assembled inside a single large file. The topbar is the worked example and
the required shape:
```
components/topbar/
Topbar.vue composes the header, owns nothing else
Brand.vue Logo + BrandName, links to /
Logo.vue
BrandName.vue
Nav.vue reads the nav model, renders links and groups
NavTrigger.vue the shared top-level control, link or dropdown trigger
NavGroup.vue one dropdown
NavItem.vue one item inside a dropdown, with its tooltip
SearchBar.vue
SupportLink.vue
ThemeToggle.vue
ProfileDropdown.vue
```
The same rule applies to every page ported after it. If a file is doing the
work of four named things, it is four files. Data and behaviour that more than
one component needs lives in `src/lib/`, not passed down through a chain of
props.
## Ordering
Build the navigation restructure during the port, not after it. Porting the
flat eleven-item bar first and restructuring later means writing the topbar
twice and touching the Go route registry twice. The approved design is five
top-level items (Dashboard, Work, Agent, Events, System), items renamed because
their group carries the context, per-item descriptions shown as hover tooltips,
Configuration split into `/system/*`, `/settings` kept as a redirect, and Logs
finally given a nav entry.
## Design authority
- The approved documents win. Where a document decides something, implement it
rather than re-deciding it.
- **Do not invent a visual direction.** Palette, typography and density are the
maintainer's call. A palette change is its own request, never a side effect
of a port.
- Contrast is AA against every surface the foreground lands on, hover states
included. The corrected values (`--fg-subtle`, the dark
`--primary-foreground`) came from a measured failure and must survive.
- `color-scheme` follows the theme so the UA paints controls, scrollbars and
overscroll to match.
## Code style
Comment the non-obvious why: an invariant, a trap, a measurement, a contract
another file depends on. Do not narrate what the code plainly does, do not
explain a choice that was never in question, and do not write migration phase
history into a diff. That history belongs in the commit message.
## Done, per surface
1. Renders with real data against `task dev`, not just typechecks.
2. Keyboard reachable, focus visible, and the nav announces where you are.
3. Works at 1440x900 and at 720px wide, with nothing clipped and no horizontal
page scroll.
4. Empty, loading, failed and unconfigured (501) states all say something true.
A section that cannot load says so; it does not render blank.
5. `task check` passes, `ui/dist` rebuilt, committed together.
-40
View File
@@ -1,40 +0,0 @@
# One source for the dashboard's server vocabularies
**Status:** Finalised
## Problem
The dashboard kept its own copies of two vocabularies the daemon owns:
- the changed-file statuses (`added`, `modified`, `deleted`, `renamed`,
`typechange`), which are the `Change*` constants in
`internal/domain/workflow/task`;
- the schema stamp on a `config_captured` payload, `events.ConfigCapturedSchema`.
Nothing derived one side from the other, while `/api/task-meta` already served
the status and action vocabularies for exactly this reason.
## Decision
`GET /api/task-meta` also serves `change_statuses` (id and label) and
`config_schema`. `buildTaskMeta` in `internal/webui/api_task_meta.go` takes the
ids from the `Change*` constants and the stamp from `events.ConfigCapturedSchema`.
The dashboard renders `ui/src/lib/task-meta-snapshot.ts` until the served
catalogue arrives, or when archied is unreachable. `loadTaskMeta` replaces only
the keys the payload carries, so a server without the new keys leaves the
snapshot in place. `changeStatusLabel` and `configSchema` in
`ui/src/lib/task-meta.ts` are the only readers; an unknown status renders as
its id.
## Verification
- `TestTaskMetaChangeStatusesAreDeliberate` fails when a `Change*` constant is
added without a label.
A rename on one side therefore fails a test on the other.
## Rejected
Deleting `/api/task-meta` and accepting hand-copied constants. The endpoint is
live, and deleting it would still leave the two copies this document removes.
-384
View File
@@ -1,384 +0,0 @@
# Deep research capability — design
**Status:** Draft
**Date:** 2026-09-14
**Scope:** A deep-research capability in archie-core: an orchestrator that
spawns 1..N subagents to explore and research in parallel, collates their
findings, and returns one cited report. Grounded in web search and web fetch.
**Beads issue:** none yet (this document is the input to it)
**Depends on:** nothing shipped for slice 1; slice 2 depends on slice 1.
## §0 Implementation status
Every claim in this document is mapped to what exists in the tree.
| Claim | Status | Where it stands |
| ---------------------------------------------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `web_fetch` tool (URL → readable text) | **Implemented** | `internal/tools/webfetch/{tool.go,webfetch.go}`; registered in `internal/app/archied/bootstrap.go` `registerStandaloneTools`, disabled-by-config returns `nil` |
| **Web search** (query → result list) | **Aspirational — zero code** | No search provider, no search tool, no config block anywhere in the tree or in `ai-sdk` v0.1.32 |
| `agent.Subagent` — nested agent in a fresh context window | **Implemented** (dependency) | `github.com/samcharles93/ai-sdk@v0.1.32/agent/subagent.go`. Synchronous, non-streaming, own model/system/toolset, `MaxSteps` defaults to 10, nesting depth capped at 5, returns final text only |
| Subagent used in production | **Implemented, one consumer** | `internal/app/agentworker/review.go` — the adversarial reviewer. That is the only non-test use of `Subagent` in the repo |
| A **delegate/subagent tool** on the chat surface | **Aspirational — zero code** | No `subagent`/`delegate` tool name is registered anywhere |
| **Fan-out orchestration** (N missions, one collator) | **Aspirational — zero code** | `agentloop`'s package doc states it runs _one_ mission: "orchestration across missions lives with the caller". No caller does this yet |
| Parallel-safe tool execution | **Aspirational — zero code** | The unreachable `internal/tools/dispatch.go` dispatch/gating engine (`ExecutionClass`, `DispatchSequential`/`DispatchConcurrent`/`ClassifyEntry`) was deleted as dead code (tools-core-1); live concurrency is ai-sdk's `GenerateOptions.MaxParallelToolCalls`, which archie-core never sets |
| Per-result caps + spill-to-disk | **Implemented** | `internal/agentexec/toolset.go` `ToolLimits{MaxResultChars,SpillDir}`, applied in `toolExecute` via `tools.CapPayload` (`limit.go`); no **aggregate** turn cap by design (`toolset.go`). `config.ToolPolicy.SpillDir`; default cap 50k chars, spill dir deliberately not defaulted |
| Tool guardrails (repeat-failure / no-progress) | **Implemented, not on the call path** | `internal/tools/guardrail.go` engine exists. Its only non-test caller is `dispatchOne` — which is itself unreachable — so **the chat path never consults it**, and the agent path only records per _stage_ (`domain/workflow/agent.go`) |
| Structured capture tools (model reports into a typed store, not prose) | **Implemented** | `internal/app/agentworker/review.go` `record_finding` / `record_checked` — `core.NewTypedTool` appending to a caller-owned slice. This is the pattern a research source ledger should reuse |
| Curator engine (interval, declared tool set, lifecycle) | **Implemented, tools broken** | `internal/domain/curator`; a curator declaring tools is **refused** at registration (`registry.go`, no `ToolBuilder` implementation) and `curatorLLMRunner` (`internal/app/archied/main.go`) drops `ChatRequest.Tools`. Budgets are time+concurrency only (`runtime.go`) — **no token budget** |
| Cron / scheduling + delivery router | **Implemented, wired into the daemon** | `internal/domain/scheduling` (ticker engine), `internal/infrastructure/cronstore` (schema v2, `Kind` discriminator), and `internal/infrastructure/crondelivery`; `internal/app/archied/scheduling.go` composes them and `main.go` starts the engine. |
| Workflow engines (multi-stage, resumable) | **Implemented, worktree-bound** | `internal/domain/workflow` — every non-triage workflow opens with `StagePrepareWorktree()` and mounts `tc.Dir` into a container; the task persists after every stage (`workflow.go`). `triage.go` documents there is "no cheaper directory-less classification primitive" |
| Long-running chat-initiated work with progress | **Partial** | Chat turns run **once, synchronously**, inline in the channel's turn runner (`internal/gateway/turn.go`). Chat can spawn a _workflow task_ (`task_spawn`) which is asynchronous — but that path is worktree/PR-shaped |
| **Operator-push delivery of an async result** | **Aspirational — zero code** | Nothing pushes a finished result to a chat. No channel subscribes to the event bus (Telegram only _publishes_ `KindTurnCompleted`); `crondelivery.Courier` is the intended seam but has **no implementation and no caller**; `send_file` works only inside the live turn. The one out-of-band notification in the tree is feasibility's n8n webhook (`feasibility.go`) |
| Citation storage / source ledger | **Aspirational — zero code** | No source, citation, or provenance store exists for research output |
> **Target state, not current state.** Everything marked aspirational below is
> design, not a description of the daemon as it runs.
## Problem
Sam's requirement: _"Deep research should spawn 1 or many subagents for
exploration or research work. And they should collate all findings, they
should use web search/fetch features."_
None of the three primitives that sentence needs can be assembled from what
ships:
1. **Web search does not exist.** `web_fetch` reads a URL you already have. A
research loop's first act is to _discover_ URLs from a query, and there is
no tool, provider, or config for that — in archie-core or in the shared SDK.
2. **Nothing can fan out.** `agent.Subagent` can nest _one_ nested generation,
synchronously, and only the PR reviewer calls it. There is no N-way fan-out,
no bounded concurrency, no shared budget across children, no collation pass.
`agentloop` explicitly refuses to orchestrate: it runs one mission and the
caller owns orchestration — and no caller orchestrates.
3. **A research run outlives a chat turn.** A chat turn is synchronous and
inline: the operator waits, and the turn's own context window is what
carries the result. A fan-out over N subagents with web search is minutes to
tens of minutes of wall clock. It cannot be a turn.
The interesting part is not the loop. It is where the boundary sits: which
existing long-running mechanism this reuses, how citations survive collation
when the thing being collated is model-written prose, and what stops a run
from spending unbounded money.
## What the run actually is
Six stages, each of which must be a _stage_ rather than a prompt instruction:
1. **Frame.** One cheap model call turns the request into a research brief: the
question, 3..N distinct sub-questions, and a per-sub-question budget. Output
is structured (a capture tool), not prose — the fan-out width comes from
this step, so it must be a number the code reads, not a sentence.
2. **Fan out.** One subagent per sub-question, **in parallel**, with a bounded
concurrency, each running a read-only research toolset (search + fetch +
read) against its own fresh context window, each required to record its
findings as _typed source records_ before finishing, and each compressing
what it returns.
3. **Cross-check.** Deterministic, no model: group by canonical URL and by
claim, flag single-sourced claims, mark conflicts. See D6.
4. **Collate.** One model pass over the children's _conclusions and source
records_ — never their transcripts — that writes the report body against the
pre-reconciled source set.
5. **Citation pass.** Its own stage: validate every marker in the body resolves
to a stored source, and every stored source was fetched successfully.
6. **Render.** The citation list is rendered from the **source store**, not
from the collator's prose, so a URL can only appear in a report if some
subagent actually recorded it.
Stages 5 and 6 are the load-bearing decision, and they are what the commercial
products' published failure modes point at: a synthesizer that is free to write
citations will invent them, and a citation that cannot be traced to a fetch is
worse than no citation.
## Prior art: what the disclosed designs and the open-source field say
Two external research passes inform this design — one on the commercial
products (official engineering blogs, model docs, system cards, plus
peer-reviewed benchmarks), one on open-source deep-research implementations
read at pinned commits. The findings that changed decisions:
**Only one fan-out unit buys capacity.** Four different units are in use:
Anthropic fans out _agents with their own context windows_; Google fans out
_queries_; Perplexity fans out _generated programs_; OpenAI uses pipeline-stage
agents for query enrichment only. Query fan-out is cheap and buys breadth of
retrieval; agent fan-out is what buys context capacity. Our step 2 is agent
fan-out, deliberately, because context isolation is the thing a single GPU
cannot otherwise buy.
**Nobody collates section-by-section.** The open-source survey found one merge
prompt over concatenated child summaries (`final_report_generation` in
`langchain-ai/open_deep_research`), lead-agent synthesis (Anthropic), a
code-level reconcile (Perplexity), or single-model continuation. STORM is the
only demonstrated section-mapped merge. This confirms D3: one collation pass,
not a mapped merge.
**Citations are lost at the merge in 8 of 10 surveyed repos.** Only `lajosdeme/mole`
assigns citation markers **mechanically in code before the prompt is built** —
its `internal/output/report.go` carries the comment _"it cannot introduce a
citation, because the citation markers are assigned mechanically before the
prompt is built"_ — and stores a verbatim `Quote` plus a `QuoteOffset` (byte
offset into the fetched document) so a citation can be re-verified later.
Claims whose quote is not found in the source are dropped by code
(`internal/actors/mine.go`: `"claim rejected: quote not found in source"`).
This is the strongest available argument for D1, and `QuoteOffset` is worth
adopting: it makes re-verification cheap and turns "the model said so" into
"the document says so, here".
**The failure is measurable and it is at the orchestrator.** An EMNLP 2026
study localising errors across three top-ranked open-source deep-research
systems found **84.7% of final-report errors originate at the orchestrator,
roughly 31% of them hallucinations and the rest citation mistakes**, with
information passing "through agents like a telephone game"
(https://arxiv.org/abs/2608.24306). Anthropic's own mitigations for this are a
separate **CitationAgent** pass after synthesis and a filesystem-artefact
pattern — subagents store work externally and pass back lightweight references
rather than full outputs. Perplexity reached the same conclusion independently.
Both are adopted here: D1 (store, not prose) and a citation pass that is its
own stage.
**A cross-check stage that no vendor has.** Worker A and worker B never compare
notes in any disclosed design, and nothing in the published set _resolves_
conflicts — Perplexity only "notes" them. Grouping findings by URL and by claim,
flagging single-sourced claims, and marking unresolved conflicts is the
cheapest correctness win available and is where a local implementation can beat
the frontier products rather than imitate them.
**Fan-out is expensive in tokens, and on one GPU that is wall clock.** Anthropic
discloses ~15x tokens for multi-agent versus ~4x for a single agent, and
explicit tier rules in the orchestrator prompt (1 agent / 3-10 tool calls;
2-4 subagents / 10-15 calls each; >10 subagents for complex research, 3-5
spawned concurrently). On a single card, N concurrent workers contend for the
same weights and KV budget, so **wall clock scales roughly linearly with worker
count** — the isolation benefit survives, the throughput benefit does not. One
instrumented study puts **web search at 73% of wall-clock time on average (up to
91%)** (https://cseweb.ucsd.edu/~yiying/2025_NIPS_ERW_Deep_Research_Perf_Study.pdf),
which is the argument for fanning out _retrieval_ aggressively and _generation_
sparingly, and for overlapping generation with retrieval.
**Frontier citation volume is not a target.** Frontier runs emit 41-113
citation URLs per query, while 3-13% of citation URLs are hallucinated and "more
citations per query do not mean fewer errors per citation"
(https://arxiv.org/abs/2604.03173). Ten to twenty _verified_ citations is a
defensible, evidence-backed target.
**Do not port Perplexity's style.** Search-as-code-generation needs
frontier-class codegen against a bespoke SDK and an atomised self-owned search
stack. Port the _intent_ — deterministic fan-out, dedupe and filter in code
before anything reaches a model — and leave the code generation to the Go
orchestrator.
## Architecture: three candidate shapes
| # | Shape | Where a run starts | Durability | New code | Cost |
| ----- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- | ----------------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| **A** | New capability family `internal/domain/research` + `infrastructure/research`, typed engine, owning registry, lifecycle, background run, completion delivered through an injected courier | A chat tool `research_start` returns a run id | Runs survive the turn; progress observable; resumable | Domain + infra + store + wiring + UI + config | Largest |
| **B** | A fourth cron job kind (`KindResearch`) in `crondelivery`, reusing `scheduling` + `cronstore` + the delivery router | Chat enqueues a one-shot immediate job | Same store and delivery as cron; no new persistence | Runner + kind + blueprint only | Medium — but fakes "on demand" as a scheduled job, and a job store keyed on a schedule is the wrong shape for a request |
| **C** | A `deep_research` **tool** that runs the whole fan-out synchronously inside one chat turn, using `agent.Subagent` for the children | Directly — the model calls the tool | None: the run dies with the turn | Search seam + tool + fan-out helper | Smallest |
**Recommendation: ship C's machinery, then promote it to A.** Slice 2 (below)
builds the orchestrator as a tool because that is the smallest thing that
delivers Sam's stated design and reuses the `Subagent` primitive that already
works. Slice 3 lifts the identical orchestrator behind a durable run once its
runtime cost and shape are known from real use — which is exactly the order
AGENTS.md's solo-project rule asks for ("prefer the smallest workable change"),
and it avoids inventing persistence for a shape that has not been exercised.
Shape B is rejected as the primary path: `cronstore.JobSpec` is a _schedule_
(cron expression, next-run, catch-up); an on-demand research request is not.
Reusing it would mean every ad-hoc research run leaves a permanent job row.
### Where the pieces live (shape C, then A)
| Piece | Home | Contract |
| ----------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Search provider seam | `internal/domain/research` (interface) + `internal/infrastructure/research/search/<provider>` (impls) | `Searcher.Search(ctx, query, opts) ([]Result, error)`; `Result{URL, Title, Snippet, RetrievedAt}`. Consumer-owned and one-method, per the `crondelivery.Courier` precedent — nothing here talks to a network |
| `web_search` tool | `internal/tools/search` | Mirrors `internal/tools/webfetch`: `Tool(cfg) *tools.ToolEntry`, returns `nil` when disabled, `ClassIdempotent`, `Toolset: "web"` |
| Source store | `internal/domain/research` entity + store | `Source{ID, URL, CanonicalURL, Title, RetrievedAt, Hash, State(ok/failed/duplicate), CitedBy []subq}` |
| Fan-out orchestrator | `internal/domain/research` (pure) with the model/tool access injected | Bounded worker pool over sub-questions; per-child `agent.Subagent`-shaped `Researcher` seam; shared step/token/wall-clock budget |
| Collator | `internal/domain/research` | Model pass over `[]ChildConclusion` + source store → report body |
| Report renderer | `internal/domain/research` | Markdown + numbered citation list rendered **from the store** |
| Chat trigger | slice 2: `internal/tools/research`; slice 3: gateway tool + courier in `internal/app/archied` | — |
| Durable run + delivery (slice 3) | `internal/domain/research` + `internal/infrastructure/research` + `internal/app/archied` wiring | Follows the strict plugin-engine rule in `docs/architecture/plugins-and-extensions.md` ("Plugin engine |
| rule (strict)"): typed contract, owning registry with start/health/stop, narrow typed registrar |
### Why not the curator
The curator family already looks like the right home — a declared interval, a
declared tool set, an owning registry, per-pass budgets and panic isolation.
Two facts rule it out as the host for _this_:
- **Its tool path does not work.** A curator declaring tools is refused
registration because `ToolBuilder` has no implementation, and even if it were
bound, `curatorLLMRunner` drops `ChatRequest.Tools` (`main.go`). Fixing
that is `archie-core-trnd.1`, an independent piece of work.
- **Its contract is maintenance, not requests.** The isolation invariant
(`docs/architecture/agent-system.md`, "Curator isolation invariant") defines
curators as periodic peers reasoning over memory. A deep-research run is
operator-initiated work with a deliverable, on the operator's clock.
A research _curator_ is a legitimate later idea — "research this standing topic
weekly" — but it is a consumer of this capability, not its foundation.
## Decisions this design takes
### D1. Citations come from a store, never from prose
Each subagent gets a `record_source` typed tool (the `record_finding` pattern,
`review.go`) whose handler canonicalises the URL, deduplicates against the
store, marks which sub-question recorded it, and appends. The collator may
_select and order_ sources; it may not author them. Rendering the reference
list is then a pure function of the store.
The strongest prior art goes further, and one step of it is worth adopting:
store a **verbatim quote plus a byte offset into the fetched document** with
each claim, and drop any claim whose quote cannot be found in the source
(`lajosdeme/mole`: `FindQuote` + `Claim.QuoteOffset`, with the miner logging
`"claim rejected: quote not found in source"`). That converts an unfalsifiable
"the model said so" into a re-checkable "the document says so, at offset N", and
it makes citation re-verification cheap rather than a second research run.
_Rejected alternative:_ require the child to end with a JSON block of sources
and parse it. A parse failure loses every source in the child's run, and a
model that reformats its output for readability silently drops citations.
### D2. Fan-out is parallel, bounded, and shares one budget
`agent.Subagent.Run` is synchronous, so N children means N goroutines behind a
semaphore — concurrency from config, sized from the VRAM budget rather than
from the research question. Two reasons to keep it small: the shared model
runtime also serves chat, and on a single GPU N concurrent workers contend for
the same weights and KV budget, so **wall clock scales roughly linearly with
worker count**. The isolation benefit of fan-out survives that; the throughput
benefit does not.
Fan-out width and per-child `MaxSteps` are enforced by the orchestrator, not
requested in a prompt, against a whole-run wall clock and token ceiling.
`agentloop.Budget` already carries `MaxSteps`, `MaxTokens`, `WallClock`, and
`TokenBudgetIs(maxTokens)` exists as a stop condition (`agentloop.go`) —
the shape exists, the fan-out owner does not.
**Fan out retrieval aggressively and generation sparingly.** Web search is 73%
of wall-clock time on average (up to 91%) in the one instrumented study
available, so retrieval is where the parallel win lives; generation is the
serialised, expensive half.
### D3. The orchestrator never holds child transcripts
`Subagent.Run` sends a prompt and returns a string; the parent's history is
never passed down and the child's is never returned. That is the property that
makes N children affordable at all — the parent's context grows by N
conclusions, not N conversations. This is also why collation is a _separate
pass_ rather than an accumulating agent loop: the collator is the only place
that must hold all N conclusions, and it holds nothing else.
Each child compresses its own findings before returning, so what crosses the
boundary is a summary, not a transcript. Anthropic names the same pattern
(filesystem artefacts with lightweight references back) and Perplexity arrived
at it independently; it is the one disclosed primitive that _increases_
effective capacity without a bigger context window.
### D4. Search is a provider seam with no silent default
`web_search` is registered only when a provider resolves, following two
existing conventions: return `nil` for a disabled capability
(`webfetch/tool.go` — "an advertised tool that never works costs a round
trip") and resolve the credential _before_ registering
(`registerMinimaxTool`, `bootstrap.go`). At least two implementations are
wanted — a self-hosted meta-search endpoint (no per-query cost, no data egress)
and one hosted API (quality fallback) — behind the same one-method interface,
selected by config.
### D5. A run reports what it could not establish
The collator is required to emit, alongside the report, the sub-questions that
returned nothing usable and the sources that failed to fetch. A research report
that omits its own gaps reads as authoritative over a hole, and the operator
cannot tell a negative finding from a missing one.
### D6. Two stages no surveyed design has: a mechanical cross-check and a separate citation pass
Children never compare notes in any disclosed design, and nothing in the
published set _resolves_ conflicts — Perplexity only "notes" them. Because
84.7% of final-report errors originate at the orchestrator (mostly citation
errors), both gaps are worth closing in code rather than in a prompt:
- **Cross-check (deterministic, no model).** Group findings by canonical URL and
by claim. Flag single-sourced claims, mark unresolved conflicts explicitly,
and count sources per sub-question. This runs _before_ the collator, so the
collator receives a pre-reconciled set rather than raw prose to untangle.
- **Citation pass (its own stage, after collation).** Anthropic runs synthesis
and then a separate CitationAgent. Here the pass is cheaper for being partly
mechanical: it validates that every marker in the body resolves to a stored
source, and that every stored source was actually fetched successfully.
Both stages are small, both are testable without a model, and together they are
where this implementation can be _better_ than the frontier products rather
than an imitation of them. A run that is expected to emit 10-20 well-verified
citations rather than 41-113 partly-unverified ones is making a deliberate,
evidence-supported trade.
## Open decisions
1. **Trigger surface.** A chat tool that blocks the turn (shape C) is
immediately useful but the operator waits; a durable run (shape A) is the
right end state. Does slice 2 ship the blocking tool, or does the capability
go straight to durability?
2. **Delivery for a durable run.** Which channel gets the finished report, and
is the report an inline message, a file, or a served page? The
`crondelivery.Courier` seam covers the chat case; a long cited report
probably wants a document, since chat surfaces render markdown but not
footnotes well.
3. **Search provider choice and egress.** A hosted search API sends every query
to a third party; a self-hosted meta-search keeps it local. This is an
operator decision with a real privacy dimension, and the default matters.
4. **Report persistence and reuse.** Does a report become a memory, a document,
or neither? Reusing a prior report is the difference between "research" and
"research again next week".
5. **Cost ceiling.** What is the per-run token ceiling, and is it a config
value, a per-request parameter, or derived from the fan-out width?
## Failure and security paths
- **SSRF.** Search results are attacker-influenceable (a page can rank for a
query). `web_fetch` already vets the _resolved address_ at dial time with
`AllowPrivateNetworks` off, which is the property to preserve — a search
tool must not become a way to reach the daemon's own control surfaces by
returning an internal URL.
- **Prompt injection.** Fetched pages are untrusted content and will contain
instructions. Subagents fetch; the orchestrator and collator must never
execute an instruction sourced from a page. Bounded by giving subagents a
read-only toolset with no shell and no write.
- **Runaway spend.** Unbounded fan-out × unbounded steps is the failure mode.
Bounded concurrency, per-child step caps, a whole-run wall clock, and a
token ceiling, all enforced in code.
- **Degenerate fan-out.** A model asked for "N sub-questions" will produce N
near-duplicates of the same question. Deduplicate sub-questions before
dispatch, and require distinct search queries per child.
- **Failed dependencies.** Search provider down: the tool is absent (D4), not
broken. Fetch fails: recorded as a `failed` source so the report can say so.
- **Collator degradation.** If the collator call fails or truncates, the report
must still be rendered from the source store and the child conclusions —
degraded, not empty. This mirrors the reviewer's rule that findings captured
before a failed run are still real (`review.go`).
## Slices
1. **Search seam + `web_search` tool.** Interface, one implementation, config
block, tool registration, tests. Independently useful to every chat turn.
2. **Fan-out orchestrator + collation, as a tool.** `record_source` capture
tool (with quote + offset), bounded parallel children with per-child
compression, cross-check, collator pass, citation pass, store-rendered
citations. Triggerable from chat; blocks the turn.
3. **Durable run + delivery.** Promote the orchestrator behind the engine
contract, add the run store, progress events, and completion delivery.
4. **UI + reuse.** Dashboard surface for runs and past reports; optional
research curator on a schedule.
## Non-goals
- Replacing `web_fetch`; research uses it.
- A general multi-agent collaboration framework (`archie-core-1786637492113-89`
owns that question).
- Report publication to a static site or external destination.
- Fine-tuning or a dedicated model: the capability is orchestration, and it
must work on whatever model the operator has configured.
-192
View File
@@ -1,192 +0,0 @@
# Dynamically-defined curators -- decision
**Status:** Approved
**Date:** 2026-09-12
**GitHub epic:** [#789](https://github.com/samcharles93/archie-core/issues/789)
**Parent epic (curator engine):** [#435](https://github.com/samcharles93/archie-core/issues/435) (closed)
**Depends on:** nothing shipping; this resolves the open question that epic #435's
"registered and configured declaratively, not hardcoded" criterion left open.
## §0 Implementation status
Every claim in this document is mapped to what exists in the tree.
| Claim | Status | Where it stands |
| --------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Curator engine family: typed contract, owning registry, start/health/stop, narrow host access | **Implemented** | `internal/domain/curator/{contract,registry,runtime,registrar,activity,wake}.go` |
| Curator declared shape (`Manifest`: interval, cooldown, on_input, tools, skills, memory engine, conversations, model) | **Implemented** | `internal/domain/curator/contract.go`; `Validate()` requires `Interval > 0` |
| Two reference curators run through the registry | **Implemented** | `internal/infrastructure/skillcurator`, `internal/infrastructure/sessioncurator` |
| Curator definitions as persisted, API-editable data | **Aspirational -- zero code** | No table, no entity, no RPC, no config block |
| Generic definition-driven engine that executes a declared tool set + free-form instructions | **Aspirational -- zero code** | Only the two code-registered curators exist |
| `Registrar.Tools` (`ToolBuilder`) resolved and bound at registration | **Partial** | Interface declared (`registrar.go`); **no implementation anywhere**; `bootstrap.go` builds the `Registrar` with no `Tools` field |
| A curator can declare tools at all | **Partial** | `Manifest.Tools` exists, but `registry.go` fails registration with `"curator manifest: declares tools but the registrar has no ToolBuilder"` |
| Curator passes that actually reach a model with tools | **Cosmetic only** | `curator.ChatRequest` carries `Tools`/`MaxSteps`; `curatorLLMRunner` (`internal/app/archied/main.go`) drops both and returns `ChatResult{Text}` only |
| Dynamic registration / removal (no restart) | **Aspirational -- zero code** | `Registry` has `Register`, no `Unregister`; `Runtime` has `Start`/`Nudge`/`Stop`, no `Add`/`Remove`; `Start()` snapshots membership |
| Curator definition CRUD over REST | **Partial** | `GET /api/curators` read-only (`internal/webui/server.go`); no write routes |
| Curator definition config | **Aspirational -- zero code** | No `[curator]` block in `internal/config/config.go` |
| Store/API as definition authority | **Aspirational -- zero code** | No curator persistence of any kind |
| No live-path defaults for interval/cooldown/tools/model/memory engine | **Partial** | `skillcurator.DefaultInterval` / `sessioncurator.DefaultInterval` are Go consts read at registration; `curator.NewRuntime(..., RuntimeConfig{})` uses code defaults for pass timeout and concurrency |
| Idle curators are observable in logs | **Partial** | `runtime.go` logs nothing when `Check` reports not-due; the session-memory curator's hourly pass is the only curator activity ever logged |
| Sampler family | **Implemented** | `internal/domain/sampling`, shipped; no curator consumes a `Sampler` yet |
| Forge/issue reach from chat | **Implemented** (via `shell`) | No dedicated issue tool exists, but the chat agent's `shell` is unconfined (`chat.unrestricted_filesystem = true`), so `gh issue edit | comment | create | close` works. Dedicated tools (#161) are convenience, not a blocker |
> **Target state, not current state.** Everything below marked aspirational is
> design, not a description of the daemon as it runs.
## Problem
A curator exists only if a Go package implements `curator.CuratorEngine`
and `bootstrap.go/1025` names it in a `Register` call. Nothing about a
curator is definable as data. Worse, no curator can declare a tool set at all:
the `ToolBuilder` interface has no implementation in the repo, so the registry
refuses (correctly, fail-closed) any curator that declares tools -- and the
daemon's model adapter drops the tools even if it were bound. The curator family
therefore has exactly one shape (cheap, tool-less maintenance pass) and its only
extension point is compiling Go.
Sam's requirement is the opposite: _"Curators should be dynamically created and
defined, in addition to being able to be defined in code/config/webui"_ and _"No
configuration should ever be hard-coded."_ The motivating consumer is a
project/orchestrator curator -- declared as data, given forge issue tools, and
pointed at a repo to review, refine, and propose issues.
## Decision
**A curator definition is data: a persisted entity whose declared shape is
exactly `curator.Manifest` plus identity, free-form instructions, and an enabled
flag. One generic engine interprets any definition.** The shape is not a second
invention -- `Manifest` already encodes interval, cooldown, on-input, tools,
skills, memory engine, conversations, and model, and `Validate()` already
enforces what a valid shape means. The definition adds only what `Manifest`
cannot express:
| Definition field | Relationship to `Manifest` |
| -------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| `name`, `enabled` | Identity and lifecycle; the registry's key is the name |
| `instructions` | **Free-form** system prompt for the generic engine -- the piece that makes a definition more than a knob set |
| interval, cooldown, on_input, tools, skills, memory_engine, conversations, model | The existing `Manifest` fields verbatim; the definition **is** a `Manifest` |
Code-registered engines keep `CuratorEngine` unchanged. A data-defined curator is
served by one registered engine whose `Manifest()` is the stored definition and
whose `Pass` composes `instructions` with the built tool set.
This is the curator domain's missing half, not a standalone tool: it lands in
`internal/domain/curator` (entity + engine), `internal/infrastructure/postgres` (persistence),
`internal/webui` (CRUD), and `internal/app/archied` (seed + apply wiring).
## Definition sources and the merge rule
Three sources, per Sam's requirement. **The store is authoritative.**
| Source | Role | Collision behaviour |
| --------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| **Code** (a registered Go engine) | The escape hatch: a curator whose strategy is Go, not tools+instructions | Wins over data for its own name -- a data definition cannot silently replace a compiled engine; the store refuses the collision and logs it |
| **Config** (`[[curators]]`) | **Seed data only**, merged at startup | Insert-if-absent. A store row of the same name is never overwritten, and deleting a store row is not undone by config on the next boot |
| **WebUI/API** (the store) | **Authoritative** | Wins over config on a name collision; the only source of truth after first boot |
Config existing at all is what makes a definition reproducible on a fresh host;
making it authoritative would make the API a lie, so it is seed data with a
one-way merge. The alternative -- config authoritative, store a cache -- would
mean an API edit silently reverts on restart. Rejected.
## How the generic engine executes a definition
A pass is: resolve the declared tools, compose the prompt, run the model loop,
record actions.
1. **Tool resolution.** `Registrar.Tools.Build(ctx, declared)` returns exactly
the declared set, never a broader registry. A declared name with no
implementation fails the pass rather than silently running with fewer tools.
This is the enforcement point, and it is why the `ToolBuilder` binding is
load-bearing rather than a convenience: without an implementation, no curator
can declare tools at all (the `registry.go` guard).
2. **Tool-carrying model call.** `curator.ChatRequest` already carries
`Tools []tools.ToolEntry` and `MaxSteps`; `curatorLLMRunner` must pass them
into `core.GenerateOptions` (which has `Tools`, `ToolChoice`, `MaxSteps`, and
already executes the tool loop) instead of dropping them. `ChatResult` is
widened only as far as attributing the pass's actions requires.
3. **Prompt.** The system prompt is the definition's `instructions` plus the
declared tool summaries -- rendered from the same set that was built, never
from a wider list. Each pass records `Action`s so activity stays attributable
through the existing registry `activity` surface and events.
A bespoke non-tool strategy (the skill curator's structural validation, the
session-memory curator's own extraction) remains a registered Go engine. That is
the escape hatch, not the mode: the mode is tools + instructions as data.
## Dynamic registration and mutation
A definition change must apply without a daemon restart, which the runtime
cannot do (`Start()` snapshots membership into one goroutine per curator;
no `Unregister`, no `Add`/`Remove`).
- `Registry.Unregister(name)` -- valid while running, same failure isolation as
`Register` (a rejected removal affects only that curator).
- `Runtime.Add(engine)` / `Runtime.Remove(name)` -- `Remove` cancels the removed
curator's in-flight pass context and stops its goroutine within a bounded
wait; it never holds the registry mutex across a pass.
- The app layer owns the apply sequence (stop old, register new, start) so the
registry stays the membership authority and the runtime the scheduler.
Removal must not be able to orphan a loop, and a pass that ignores cancellation
must not block removal forever.
## REST / WebUI surface
Mirror `internal/webui/api_binding.go`, not a new pattern:
| Route | Handler shape |
| --------------------------------------------- | ------------------------------------------------------------------- |
| `GET /api/curators` | Existing read-only list, fields unchanged (dashboard keeps working) |
| `POST /api/curators` | `handleCuratorCreate` |
| `GET /api/curators/{id}` / `PATCH` / `DELETE` | `handleCuratorGet` / `Update` / `Delete` |
All mutations behind `authorizeTaskMutation`, same as bindings and mappings. A
successful mutation goes through the runtime apply path above, so it is live
without a restart.
## Sequencing: persistence and the State Store
The State Store is a standalone process that solely owns the task database; the daemon
and Gateway never open it (`TestOpenStoresNeverOwnsTaskDB` guards this), and
`proto/state/v1/state.proto` is one gRPC service fronting every ratified store
contract. AGENTS.md forbids adding a Go interface method without a matching RPC.
That fixes the order:
| Phase | Ships | Proto work |
| ------------------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1. Engine + config source | `ToolBuilder`, tool-carrying passes, generic engine, `[[curators]]`, idle logging | None -- nothing persisted yet |
| 2. Runtime mutation | `Unregister`, `Add`/`Remove`, apply path | None -- in-memory membership |
| 3. Persistence | definition entity + store schema, config seed (store authoritative), REST CRUD | **Same change**: request/response messages + RPCs, `staterpc.Client` façade, `mapError`/`unmapError`, and an update to `docs/prds/state-store-contract.md` |
Phases 1 and 2 are genuinely independent of the wire boundary, so they are not
blocked on it. Phase 3 is where the boundary is unavoidable: a definition the
WebUI can edit must be reachable from the WebUI, and the WebUI reaches the store
through the State Store, not by opening the database. Splitting the RPCs into a
later change would leave a table nothing can read -- rejected. Deferring the
whole phase is the same rejection, later.
## No live-path constants
No default may be a live-path constant. Interval, cooldown, tools, model, memory
engine, pass timeout, and concurrency are definition or config values. A
definition missing `interval` is refused with a clear error, never defaulted at
pass time; `skillcurator.DefaultInterval` and `sessioncurator.DefaultInterval`
stop being read at registration (the value becomes seed data), and
`curator.NewRuntime(..., RuntimeConfig{})` stops relying on code defaults.
## What this deliberately does NOT do
- **No fixed catalogue of curator "types".** A definition is arbitrary tools +
instructions, not a union of known kinds.
- **No chat tool that mints curators.** A definition grants an LLM a tool set; a
curator able to create curators is privilege escalation. Mutation is REST with
the same authority as bindings -- not exposed on the chat tool surface.
- **No dashboard SPA editor page.** The REST surface is the WebUI definition
source; the dashboard can adopt it separately.
- **No forge issue tools here.** This design only ensures a curator _can declare_
tools. Dedicated issue tools (#161) are a convenience, not a prerequisite: the
chat agent already reaches issues through the unconfined `shell` tool
(`gh issue edit|comment|create|close`). See the correction on #789.
- **No second authority.** No file-per-curator definition store, no parallel
config reader.
-114
View File
@@ -1,114 +0,0 @@
# Dynamic workflow triage
**Status:** Finalised
Epic: archie-core-enfj. Scope: give `workflow.Route()` a real, content-aware
fallback instead of unconditionally defaulting every unlabelled task to the
heaviest workflow.
## Problem
`Route()` (`internal/domain/workflow/workflow.go`) has exactly two real
signals: an explicit `t.Workflow`, and label matches via
`workflowForLabels` (`routing.go`, `bug`→tdd, `feature`→feasibility,
bootstrap→bootstrap). Anything else — which is every chat-spawned task,
since `task_spawn` rarely sets labels — falls straight through to
`reg["implement"]`, the full `prepare → baseline → plan → build →
commit-push → review → open-pr` pipeline, regardless of what the task
actually asks for.
`task_spawn`'s own tool schema overpromises: _"workflow: … Omit to let the
daemon route it"_ (`internal/gateway/task_tools.go`) implies real
routing exists. It doesn't — "route" means "check labels, then
give up and run the heaviest workflow anyway."
Confirmed in production: a chat-spawned task whose
entire content was "this is just a test, close it when you receive it" ran
the full `implement` pipeline end to end — 669,421 tokens, ~7 minutes —
when nothing about the request needed a worktree-driven build at all. The
`plan` stage's own LLM output _correctly_ concluded no code change was
needed, but that conclusion arrives two expensive stages (`baseline`,
`plan`) too late to save anything.
## Decision
Add a **`triage` workflow**: cheap, classifies once, then either closes the
task immediately or hands off to the workflow the task actually needs.
`Route()`'s final fallback (`reg["implement"]`) becomes
`reg["triage"]` when a `triage` entry is registered, else the existing
`implement` fallback — a two-line change, fully backward compatible when
`triage` isn't wired up.
Triage does **not** replace label-based routing. A labelled task
(`bug`/`feature`/bootstrap) already has a free, reliable signal and goes
straight to its known workflow unchanged — spending a classification
call there would be pure waste. Triage only fires in the gap that
defaults to `implement` blindly: no explicit workflow, no label match.
### Triage workflow shape
```
StagePrepareWorktree() -- still needed: AgentStage mounts tc.Dir into the
agent container: internal/domain/workflow/agent.go:74
passes tc.Dir straight through. No cheaper
primitive exists in this codebase for a
directory-less classification call.
AgentStage "classify" -- ReadOnly, ONE cheap agent turn, no exploration
tools required beyond what ReadOnly already
grants. Mirrors feasibility.go's decideCaptureTools
pattern: a structured capture tool, called
exactly once, MaxCalls: 1.
```
Mission: read the task's title/body/labels (already in `taskPromptBlock`)
and decide, via a captured `decide` tool call:
```json
{"needs_code_change": bool, "workflow": "implement" | "tdd" | "feasibility", "reasons": "..."}
```
`needs_code_change: false` → close path: reuse `closeNoChangesIssue`
(`steps.go`) directly — issue closed if forge-backed, task marked
`StatusMerged`/`"completed -- no changes required"` otherwise. No baseline,
no plan, no build, no commit, no PR. This is the actual fix for the
production incident: a no-op request now costs one classification call
(low thousands of tokens) instead of 669,421.
`needs_code_change: true` → sets `tc.Task.Workflow` to the classifier's
chosen workflow (`implement`/`tdd`/`feasibility`, defaulting to
`implement` if the field is missing or unrecognised) and an Outcome that
requeues the task under it, the same requeue mechanism
`chatTaskControllerAdapter.ApproveChatTask` already uses
(`main.go`, `requeue(ctx, taskID, fromStatus, workflow)`). The task then
re-enters `Route()` on its next claim with `t.Workflow` now set, and takes
the normal path for that workflow from there — triage never runs its
classification twice for the same task.
### Non-goals (v1)
- Full bug/feature intent classification quality — the classifier only
needs to be _directionally_ right; a wrong `tdd` vs `implement` call
still produces a working PR, just via a slightly less-tailored pipeline.
Tightening this is a follow-up, not a blocker.
- Any change to label-based routing, `Route()`'s explicit-workflow branch,
or `Bootstrap()`/`Feasibility()`/`TDD()` themselves.
- Triage for forge-sourced (real GitHub issue) tasks with no labels —
in scope structurally (same fallback branch), but the dominant case this
fixes is chat-spawned tasks, which essentially never carry labels.
## Testing
- `workflow_test.go`: `Route()` picks `reg["triage"]` over `reg["implement"]`
for an unlabelled task when both are registered; falls back to
`reg["implement"]` unchanged when `triage` isn't registered (regression
guard for every existing `Route()` test).
- New `triage_test.go`: classify → `needs_code_change: false` closes
without ever calling `tc.Trees.Prepare` a second time or touching
`tc.Agent.Run` again; classify → `needs_code_change: true` sets
`tc.Task.Workflow` and produces a requeue Outcome, using a fake
`agentRunnerFunc` returning a captured decision, mirroring
`feasibility_test.go`'s existing `decideCaptureTools` test style.
- Integration-shaped test reproducing the production scenario: a
chat-spawned task with no labels, title "this is just a test, close it
when you receive it" — asserts the task closes without ever reaching a
`baseline`/`plan`/`build` stage.
-678
View File
@@ -1,678 +0,0 @@
# EDA playbook engine -- design
**Status:** Draft
**Date:** 2026-09-03
**Beads epic:** `archie-core-t2db`
## Problem
"Which workflow runs for which trigger" is hardcoded Go: a literal
label vocabulary (`workintake.labelKinds`) and a literal label->workflow map
(`workflow/routing.go`), extended only by adding a Go case or shipping a
skill whose `metadata.archie.workflow` overrides one _named_ built-in
workflow. Extending the system to a new trigger, a new action, or a new
event source means a feature branch, a code change in a hardcoded
path, and new Go tests -- for every addition. That is the barrier this
document exists to remove.
The goal: triggers, the actions they run, and the
conditions that connect them should be **drop-in and load**, not **drop-in
and touch application code**. Yaegi-evaluated Go is the unit of imperative
"do a thing" logic; YAML playbooks are pure orchestration data -- no logic,
just "on this event, with this data, call these actions, in this order,
under these conditions." The daemon's event coordinator doesn't know what a
`bugfix` or `image-gen` action does, it resolves the name against a
registry and pipes typed data through.
This is explicitly **not** scoped to code-generation workflows. A playbook
action can be any registered capability -- run a codegen workflow, send a
message on a channel, open something on a forge, generate an image -- so
long as it's implemented behind one of the typed engine families below.
## Relationship to existing decisions
- `docs/prds/event-sources-and-reactions.md` ruled
that reactions in the two epics it covers are **producer-only** (no veto,
no mutation of in-flight work) and explicitly rejected a single generic
`Source` interface as "the untyped-hook shape the plugin engine rule
exists to prevent." **This document extends that scope**: playbooks can
dispatch to multiple typed action kinds, not just "produce a
`TaskEnvelope`." It does not relitigate producer-only-ness (still no
veto/mutation of in-flight work here) and it does not introduce one
generic interface -- see "Typed positions, not one generic hook" below,
which is how it stays compliant with the plugin engine rule instead of
reopening that document's #4.
- `docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict`
governs every extension point
introduced here. Every position below is a typed domain contract with an
owning registry, not a generic callback map. This is a hard constraint,
confirmed against the existing rule text before writing this doc.
- Yaegi is already a proven in-process extension mechanism
(`internal/plugin`, `internal/domain/workflow/wfeval/yaegi.go`,
`internal/gate/gateeval/yaegi.go`, `internal/skill/plugin.go`) -- this
design generalises its existing role, it does not introduce a new
execution mechanism.
- `internal/domain/workflow/skillbuild.BuildRegistry` already composes a
`workflow.Registry` from a skills catalogue, plugin-defined overriding
built-in. The playbook loader described here supersedes label routing
specifically; it does not replace `skillbuild`'s workflow-composition role,
it becomes an additional input the daemon composes at startup.
- Webhook event intake is a separate design. This
document defines the router each webhook-sourced event should be able to
reach; it does not redesign webhook receipt itself.
## Shape: four logic positions, each a typed engine family
Every entrypoint kind (mechanism, action, loop, schedule, route, trigger) is itself a schema emitter: defining a new kind produces the
generated contract downstream tooling consumes. The kinds slot into a fixed
hierarchy of logic positions:
```
Workflow -> Module -> Channel (telegram/whatsapp/email/...)
-> Forge (GitHub/Gitea/GitLab/...)
```
Each position is its own typed engine family per the plugin engine rule:
identity + capability-specific operations, an owning `Registry`/`Manager`,
explicit lifecycle where the implementation owns resources, narrow host
access. Concretely:
- **Workflow** -- already exists (`internal/domain/workflow`). A playbook
action of kind `workflow` invokes a registered `workflow.Registry` entry
by name, unchanged from the existing execution path.
- **Module** -- the new general-purpose action position. A `Module` is a
Yaegi-evaluated implementation of a generated interface (args in, typed
result out) for one declared action kind (e.g. `image-gen`, `notify`,
`open-pr-comment`). This is the position that makes actions "not
restricted to code-generation." Full design (schema-per-kind, the
registry shape, the trust boundary, the recommended first slice):
`docs/prds/module-position.md`.
- **Channel** -- already exists as `channels.Channel` (telegram, email,
webhook). A playbook action of kind `channel` sends through a named,
already-registered channel. No new mechanism; this document just makes it
addressable from a playbook.
- **Forge** -- forge clients (GitHub, Gitea, GitLab) become an addressable
action position the same way Channel is, so a playbook can say "comment
on this forge issue" without that being a special case wired only into
the poller.
**Typed positions, not one generic hook.** There is no single `Action`
interface with an `any` payload. Each position keeps its own typed
contract; the playbook YAML names a position and an implementation, and the
event coordinator resolves that pair against the matching typed registry.
This is what keeps the design compliant with the plugin engine rule and
with `event-sources-and-reactions.md`'s rejection of a generic `Source`/
hook interface -- the generality lives in the YAML data model (which
positions exist, which named implementations are registered), not in a
runtime `any`-typed dispatch path.
## `go:generate`-driven schemas, from day one
Schemas are not a future nicety bolted onto an ad hoc
YAML shape. They are the struct+interface contracts for each logic
position, and they drive code generation from the start.
- Each logic position (Workflow/Module/Channel/Forge) has a schema source
(Go-annotated types, following the existing pattern elsewhere in the
repo) from which `go:generate` emits the interface and struct scaffolding
an implementation must satisfy.
- A Yaegi module implements the generated interface for its position. The
generated contract is what makes an implementation valid, not hand-review.
- The schema is also what the linter and LSP (below) validate a playbook
YAML against -- one source of truth for codegen, startup loading, and
authoring-time tooling, so the three can't drift from each other.
- Schema versioning is explicit per position, independent of a playbook's
own workflow version (see collision handling below).
The generator itself is not designed here. The constraint is
schema-first, `go:generate`-driven, per logic position.
## Playbook YAML: pure orchestration data
A playbook declares no embedded logic -- only:
- **trigger**: the event predicate (e.g. forge issue assigned + labelled
`bugfix`, a schedule tick, a webhook payload shape).
- **actions**: an ordered list, each naming a logic position and a
registered implementation, with typed argument data and optional
conditions.
- **data flow between actions**: results/facts from one action available to
later actions in the same playbook run -- exact interpolation syntax is
an open point, not decided here (see Open questions).
Playbooks live in a configured directory (repo/directory-scoped, per Sam's
"define repos, directories, playbooks" framing) and are loaded at archied
startup, alongside the existing skills-catalogue composition.
## Dedup: detect and log, no arbitration mechanism
No runtime auto-resolution rule. An automatic "pick a winner" algorithm
(e.g. by version) is itself a mechanism that can fail and need debugging
when a collision happens -- the wrong kind of complexity to introduce for
a case that should just be visible and fixed by a human. Instead:
- **At daemon startup:** if independently-sourced playbook directories
declare a collision on the same trigger, that is a definition failure.
The colliding definitions are dropped (not loaded) and the failure is
logged plainly (which sources, which trigger) and reported back to the
caller that requested the load -- not swallowed as a background log line
only. The schema is the definition; a schema conflict is a reported
failure, not something the daemon silently arbitrates.
- **Linter**: a CI/dev-time tool, reading the same generated schemas, that
flags duplicate or conflicting trigger definitions _within_ a single
maintained tree before merge.
**Resolved** (`archie-core-t2db.12`). A standalone
gopls-shaped binary (`cmd/archie-playbooks`, lint subcommand) validates
playbook directories against the exact loaders the daemon uses
(`LoadPlaybookDirs`/`LoadKindWorkflowsYAML`/`LoadLabelWorkflowsYAML`),
exiting non-zero on any collision / malformed file / invalid binding.
A finding about one binding key leads with the key's `file:line`, read
from the `yaml.Node` the loader decodes; the linter agrees with runtime
validation by construction, which is the load-bearing property. `-eda-dir`
lints an `eda_playbook_dir` the same way, through `playbook.Load` with its
CEL, action-id and args checks.
Discoverable via `task lint:playbooks` or direct `go run
./cmd/archie-playbooks lint -dir ...`. The LSP/serve mode is a later
entrypoint of the SAME binary, per the shared-package decision above.
- **LSP**: same schema source again, feeding author-time hover/completion/
inline errors while someone edits a playbook YAML in an editor. Kept
explicitly in scope per Sam (not deferred), because it's the same schema
artifact as the linter's, just a different consumer.
`archie-playbooks serve` is the language server, over stdio. When a file is
opened or saved it lints the file's saved directory with the loader the
daemon runs for it (a file with a top-level `trigger` key is an EDA
playbook, anything else a routing binding file) and publishes the findings
for that file as error diagnostics, each on the line of the key, action,
`when` or args key it names; a file-level finding sits on the first line.
Unsaved edits are not validated. Hover and completion are later additions.
The startup log-and-refuse path exists for what the linter/LSP structurally
cannot see -- sources composed together only at daemon startup, never
checked against each other by either tool. If the linter and LSP do the job
they're built for, a real collision reaching that startup path should be
rare in practice, not a routine occurrence the design leans on.
**Shared package, thin consumers -- not a bundled-vs-standalone choice.**
The validation logic (`LoadKindWorkflowsYAML`, `LoadLabelWorkflowsYAML`, the
directory-merge from t2db.11) lives in `internal/domain/workflow`, a plain
Go package with no knowledge of which binary calls it. This makes "should
the linter/LSP be bundled into archied or a separate tool" a non-question:
- `archied` already imports the package directly and validates in-process
at startup -- no subprocess, no external tool call.
- An agent that needs to validate a playbook in-process can import the same
package directly, for the same reason.
- The standalone `cmd/` binary (t2db.12, gopls-shaped: one binary, a lint
mode now, an LSP/serve mode later) exists only because CI and editors are
out-of-process consumers by nature -- a CI step needs an exit code, an
editor speaks LSP over a process boundary, neither can `import` a Go
package. It is a thin wrapper per `organisation.md`'s `cmd/` rule, not a
second implementation.
Folding CLI/LSP protocol handling into `archied` itself would grow the
daemon into unrelated concerns, against the plugin-engine rule's spirit of
narrow capability families.
## Execution-time gaps (both resolved)
Everything above covers _loading_ a playbook. Nothing above covers what
happens while one _runs_. Two gaps, both load-bearing enough to resolve
before implementation, not defer:
### 1. Mid-playbook action failure
**Resolved** (`archie-core-t2db.18`). The default below
is a committed decision, not a candidate list; changing it later would
require its own decision. Gap 2 below is resolved by `archie-core-t2db.17`.
A playbook is an ordered action list with data flowing between steps. If
action 2 of 4 fails at runtime (an image-gen API times out, a forge call
403s), the run needs a defined outcome. This
codebase already answers a structurally identical question for its
existing workflow engine, precisely enough to reuse rather than
re-derive: `workflow.Run` (`internal/domain/workflow/workflow.go`)
draws a three-way distinction on a stage failure, and a playbook run
draws the same one on an action failure.
**Decision: reuse `Run`'s three-way distinction directly.** The stated
default is **stop-on-first-failure**: a real action error halts the
playbook run immediately and is reported, with no continue-to-next-action
and no automatic retry or compensating follow-up. The three points below
are the complete decision.
1. **A real action error** (the action's own logic failed -- an API
error, a validation failure inside the action) stops the run
immediately. No later actions execute. The failure is reported the
same way a load collision is reported -- dropped, logged plainly
(which action and why), and returned to the caller, never swallowed
as a background log line only (the Dedup section's drop-and-report
rule). `Run` is the mechanical
precedent for the stop itself: a stage error sets the park reason and
returns without running further stages (`workflow.go`). This
is stop-on-first-failure, matching the document's existing bias
against clever automatic recovery, and it is now a stated decision
rather than a nobody-chose default.
2. **Interruption** (the daemon is shutting down mid-dispatch, `ctx.Err()
!= nil`) is explicitly **not** a failure. `Run` already treats this
case specially -- "Daemon shutdown is not a workflow failure. Leave
the task running ...; parking here would publish a false failure and
require manual intervention" (`workflow.go`) -- and the same
reasoning applies to a playbook run: an in-flight dispatch interrupted
by restart must not be recorded as a broken playbook. What "leave it
alone for restart" means for a playbook run (there is no `store.Task`
row a playbook run inherently owns the way a workflow stage does) is
an open implementation detail for whoever builds the coordinator, not
decided here -- but the _semantic_ (interruption ≠ failure) is decided.
3. **A run that produces no outcome at all** (every action ran without
error, but nothing was assigned to happen) is itself an error
condition, matching `Run`'s own "a workflow must end with an explicit
outcome; not doing so is a definition bug, which still must not vanish
silently" (`workflow.go`). A playbook with actions that all ran
but never reached a coherent terminal state is a definition bug in the
playbook, reported as such.
**Rollback:** explicitly **not attempted**, for exactly the reason the
gap's own description named -- a posted forge comment is not revocable.
This is not a limitation to work around later; it is the correct
semantic. An operator who needs a corrective action after a failure
writes a _new_ playbook/action for that, they do not get automatic
undo.
**This stays inside the producer-only rule.** Stop-on-first-failure is the
run deciding its own terminal state from its own action's error. Nothing
already in flight is blocked or altered; the run only declines to start
actions that had not started yet, and it records the failure on its own
unit the way `Run` sets a park reason and transitions the task to
`StatusParked`. A future compensating action ("if the notify action
failed, also log an incident") would be producing new work, which the rule
already permits. No syntax for it is designed here.
**J3 relationship, stated explicitly:** J3 (a CEL `when` condition
erroring at eval time → treated as false → skip that action → run
continues) is a **different case from an action failure** and is not
revisited by this resolution. A condition error means "we couldn't
determine whether to run this action," which this document already
resolved as "then don't, and move on." An action failure means "we tried
to run this action and it broke," which stops the run per point 1 above.
The two must not be conflated: a coordinator implementation should be
able to point at one `when`-evaluation code path and one
action-invocation code path and show they use different outcomes.
### 2. Idempotency at execution time
**Resolved** (`archie-core-t2db.17`, a
design-investigation ticket: resolve, do not implement). The decision
below is the answer; the keying scheme itself is separate follow-up work
and is intentionally not built here. It **extends**
`event-sources-and-reactions.md`'s existing contract -- it does not
contradict it (relationship argued at the end).
**Problem (unchanged):** `event-sources-and-reactions.md` decided
reactions ride `internal/eventbus`'s at-least-once delivery specifically
so `PublishUnique`/idempotency keys absorb redelivery without duplicate
side effects. This document inherits that for free only for
`workflow`-kind actions, because `TaskEnvelope` already carries an
idempotency key. It said nothing for `channel`, `forge`, or `module`
actions with real side effects -- a posted comment, a sent message, a
billed image generation.
One correction to the problem statement, checked against the code rather
than assumed, because it changes what the answer must be:
**`PublishUnique`'s dedup is not a consumer-redelivery guard at all.**
`PublishUnique` only sets the JetStream `Nats-Msg-Id` header on the
outgoing message (`internal/infrastructure/eventbus/nats/publisher.go`;
key constant `message.go`); JetStream suppresses _republished_
messages carrying a repeated key inside `Config.DedupWindow`
(`client.go`, `Duplicates: cfg.DedupWindow`), default 2 minutes
(`config.go`, `DefaultDedupWindow = 2 * time.Minute`). A consumer
redelivery is the same _stored_ message re-delivered on Nak or
acknowledge-timeout (`internal/eventbus/eventbus.go`: "a handler
returning an error causes redelivery") -- not a republish; its
`Nats-Msg-Id` is never re-firewalled, and even if it were, two minutes is
not an at-most-once guarantee for a side effect that must never repeat.
**Conclusion: side-effecting action kinds need a consumer-side, durable
dedup record; the bus cannot supply it.** That is precisely the situation
`binding_dispatches` was built for -- so the decision below reuses its
mechanism rather than designing a new one.
#### Decision
**Granularity: per-action-per-event -- one dedup record per
(action, event) pair, not per playbook run.** Whole-run keying, the
obvious alternative, has two crash windows: the run row is written when the run starts, so a crash mid-run
leaves the run "started" and a redelivery skips _every remaining
action_ (work silently lost); a crash before the row write re-runs
_every already-fired action_ (duplicate side effects -- the exact harm
this gap exists to prevent). Per-action keys collapse both into one
window and one behaviour: an action's record is written immediately
before that action's side effect is invoked, so an action fires iff its
own record is absent, no fired action ever re-fires, and a redelivered
event resumes at the first unrecorded action. For the shipped
single-action playbooks the two granularities are equivalent in effect;
the difference starts with multi-action runs -- where whole-run keying
would already be wrong.
> Storage superseded: every store now lives in PostgreSQL behind
> `internal/domain/storecontract`, implemented in `internal/infrastructure/postgres`
> (`docs/prds/state-store-contract.md`). SQLite names below describe the
> original design.
**Storage/lookup: a new durable ledger table `playbook_dispatches` in
the event-capture store, copying `binding_dispatches`'s conventions exactly**
(durable table, `INSERT OR IGNORE`, sentinel error, rows freed with
their parent, survives daemon restarts -- `RecordDispatch`):
```sql
CREATE TABLE playbook_dispatches (
playbook_id TEXT NOT NULL,
playbook_version TEXT NOT NULL,
event_id TEXT NOT NULL,
action_id TEXT NOT NULL,
dispatched_at TEXT NOT NULL,
PRIMARY KEY (playbook_id, playbook_version, event_id, action_id)
);
```
Written with the same `INSERT OR IGNORE` + sentinel-error convention
(`ErrAlreadyDispatched`, `bindings.go`), so a duplicate is a no-op
write rather than a constraint error, and the caller matches it with
`errors.Is` the way the binding dispatch loop already does
(`internal/daemon/daemon.go` -- "another cycle already won this
race," not an error to surface). The record is consumed by the playbook
coordinator at dispatch time through a domain-side interface implemented
by the event-capture store -- the same shape as `BindingDispatcher`
(`internal/domain/storecontract`) -- and the table lands in the
store's schema migrations. No change
to `internal/eventbus`; no per-message dedup state on the client.
**Lifetime: no time-based expiry, and no automatic reclamation.** Rows are
retained until an explicit `DeletePlaybookDispatches` for their playbook.
Removing a playbook file does not delete its rows: playbooks are read only
at boot, so the only place to notice a removal is a boot-time reconcile,
and a boot that finds the directory missing or unmounted loads as "no
playbooks" and would reclaim the whole ledger, letting redelivered events
fire their side effects again. A binding's rows go with an explicit
operator delete (`bindings.go`, same transaction); a file disappearing is
not an equally deliberate act. The at-most-once guarantee must not
silently decay, which is exactly the property that disqualifies
`DedupWindow` above; table growth is bounded by distinct (playbook,
event, action) pairs and is accepted, the same tradeoff
`binding_dispatches` already makes.
**Redelivery behaviour: skip the recorded action and continue the run.**
A detected duplicate is not re-invoked, is not reported to the caller as
an error, and is logged at debug level rather than as a warning -- this
is the expected, correct behaviour of at-least-once delivery, not an
anomaly (same treatment as `ErrAlreadyDispatched` at
`daemon.go`).
The run continues with the next action (or ends, for a single-action
playbook whose one action is recorded), which is what makes a redelivery
a resume rather than a dead restart.
**Key derivation: a fixed composition of four structural identities,
computed by the coordinator -- not a CEL expression.** The key is the
`(playbook_id, playbook_version, event_id, action_id)` tuple above, where:
- `playbook_id` is `Playbook.ID` -- the playbook file's path relative to
its configured directory root, slash-normalised, unique within the load
composition by construction (`internal/domain/eda/playbook`).
- `playbook_version` is `Playbook.Version` -- a SHA-256 of the loaded
file, recomputed on every load (`internal/domain/eda/playbook`),
mirroring `Binding.Version`'s provenance-pinning purpose: the dispatch
is pinned to the exact definition that was active when it fired. A
changed playbook definition is a different key and may fire again for
the same event -- deliberate, not a bug.
- `event_id` is `DispatchInput.TaskID` (`playbook.go`), which
carries the `TaskEnvelope.IdempotencyKey()` value
(`"archie:" + owner/repo/number`,
`internal/domain/workintake/envelope.go`). It is chosen over
`store.Task.ID` because the trigger vocabulary is issue-level
workintake label/kind, dispatched at discovery time (pollNATS, forge
webhook receiver), where no task row exists yet (`playbook.go`
comment; `playbook_test.go`: "the value available at the
discovery/dispatch point... NOT a store.Task.ID int64"). Keying on the
issue identity rather than the delivery source is the load-bearing
property the existing contract already established for `TaskEnvelope`
(`event-sources-and-reactions.md` question 4: a webhook-sourced
envelope for the same issue produces the _same_ idempotency key as a
poll-discovered one; `internal/forge/webhook/receiver.go` --
"Idempotency is not this package's job"); this resolution inherits that
property rather than re-deciding it. Consequence, stated explicitly:
same-issue re-discoveries (a re-label that re-triggers the same kind)
are the _same event_ by design -- the workintake trigger vocabulary is
issue-granular, exactly as `TaskEnvelope`'s own key is. A future
capture/binding-originated trigger type keys on `captured_events.id`
instead; derivation is per-trigger-type, not one formula for all
triggers (rule carried over unchanged from the draft).
- `action_id` is the action's declared `id` -- J1's named ids, "a
required field on every action that later actions reference", unique
and stable-identifier-shaped, validated at load (the CEL resolution's
J1 and its context table above in this document). For an action declaring no `id`
(permitted by J1 while unreferenced), the key uses the action's 1-based
position in the playbook: deterministic and stable for the
single-action playbooks, and a later reorder is a file edit whose
content hash changes `playbook_version` with it, so a positional
fallback cannot silently collide with a prior definition.
**No CEL in the key -- stated explicitly because the CEL resolution
flagged this as gap 2's "first real exercise"** ("CEL's read-only result
access makes gap 2's keying derivation readable" -- the CEL resolution's
closing note). Readability
is not the binding constraint; **determinism under redelivery is**, and
CEL key expressions lose three ways. First, they are not load-checkable:
`event` stays `dyn` by the resolved J4 (schema-by-example), so
a key expression over event fields cannot be type-checked at load,
violating the document's reject-at-load philosophy. Second, they can
fail at dispatch (a missing field is a CEL error), and a key that cannot
be computed is an unfireable state -- neither "skip" nor "fire" is safe
without losing or duplicating work. Third, the contract needs one
derivation, and two authors writing different key expressions would
fragment the ledger. The key is therefore structural by construction:
every component above is an immutable identity of the run's inputs, so
two deliveries of the same event derive the same key with no evaluation.
The exercise's actual outcome is the derivation rule above; CEL remains
a _condition_ surface (`when`), never a key surface. An action kind that
genuinely needs finer granularity than (action, event), such as "per
comment, not per issue", arrives with its own trigger type and its own
event identity, per the per-trigger-type rule.
**Record-before-invoke -- one deliberate divergence from
`binding_dispatches`, justified by the harm profile.** The binding
dispatch loop enqueues the task first and records the ledger row after
(`daemon.go`), accepting that racing cycles may both enqueue
("the duplicate task remains queued... delete-on-races is its own can of
worms"); the selection query excludes already-dispatched captures
(`bindings.go`), but the race window remains. That ordering is
correct there because the duplicate artifact is an internal task row --
recoverable, low-harm. The playbook ledger's ordering is reversed on
purpose: **the row is written and committed before the action's side
effect is invoked** -- the `INSERT OR IGNORE` is the atomic gate, and
the lost-write loser skips without invoking. The cost is stated, not
hidden: a crash between the row commit and the invoke loses that one
action's side effect, repairable by hand -- the reverse direction of the
same window that would otherwise duplicate a posted comment or
re-bill an image generation. For side effects whose duplication is
externally visible and not revocable, at-most-once is the required
direction; the binding system's at-least-once-tolerant ordering is not
the precedent for this ledger.
**Gap-1 interplay, stated to keep the two mechanisms separate:** the
ledger answers one question per action -- has this action already fired
for this event? It does not answer whether the run continues, stops, or
is re-attempted; that is gap 1's coordinator concern (a run-outcome
record; gap 1 explicitly leaves "what leave it alone for restart means
for a playbook run" to whoever builds the coordinator). One consequence
of record-before: an action that FAILED (gap 1's real-action-error case)
has a ledger row, so a later redelivery of the same event skips it --
consistent with gap 1's "no automatic retry" resolve (a corrective
action is a _new_ playbook/action, per gap 1's rollback paragraph). A
failed action is never re-attempted by the bus; if a run must be
recovered, an operator edits the playbook -- new version, new key --
rather than fighting ledger state.
**Relationship to `event-sources-and-reactions.md` -- extension, not
contradiction.** Keyed to that document's sections:
1. Its decision 2 commits reactions to at-least-once delivery via
`PublishUnique`'s "without duplicate enqueue" guarantee -- which, with
the code facts above, is accurate for the _publish_ path only:
`PublishUnique` absorbs duplicate publishes of the same event (poll
vs. webhook), which is what that decision was actually about. This
document's own problem statement, taken literally, overstates it
("keys absorb redelivery without duplicate side effects") -- that
overstatement is exactly what this gap exists to correct. The
existing contract never claimed consumer redeliveries of
side-effecting reactions were absorbed, so nothing it says contradicts
a consumer-side ledger; this resolution pins down the boundary the
sentence left implicit (publish-path dedup vs. consumer-path dedup)
rather than changing either.
2. Its decision 3 is untouched: the ledger is the run's own bookkeeping
about its own actions, suppressing a re-fire and nothing else.
3. Its decision 4 (no generic `Source` interface; `TaskEnvelope` is the
typed contract, keyed on issue identity, not delivery source): the
event half of the playbook key IS that same identity
(`TaskEnvelope.IdempotencyKey()`), and the per-trigger-type rule
means any future trigger type brings its own identity rather than a
new generic one -- the playbook ledger introduces no second identity
vocabulary and no untyped payload. The only new type in this
resolution is the ledger's own value object, consumed through a
narrow interface like `BindingDispatcher` -- the same shape the
document's "typed families" rule (decision 1, plugin engine rule)
already blesses.
**Scope: this is the `channel`/`forge`/`module` decision, not a
`workflow`-position change.** Workflow-kind actions keep their existing
keying claim unchanged -- the `TaskEnvelope` path that this document
already inherits for free (`daemon.go`, `PublishTask` publishes
with `task.IdempotencyKey()`), with its cross-poll/webhook property
untouched. The ledger gate applies to the side-effecting positions
(channel, forge, module), which is why the closing statement below
still holds: the first slice (Module + loader + workflow-kind dispatch)
was buildable without this resolution, and channel/forge/multi-action
playbooks were not. A coordinator MAY implement one position-uniform
gate as a simplification; what this resolution requires is only that
the side-effecting positions are gated.
## Resolved questions
1. **Data-flow/condition syntax.** Does this project want a small existing
Go expression evaluator (there may be one already in the codebase worth
checking, e.g. anything backing gate conditions), or a bespoke minimal
grammar?
**Resolved** (`archie-core-t2db.14`). CEL (`cel.dev/cel-go`, pinned) is
the one mechanism for both an action's `when` condition and its `args`
values. The trust boundary, evaluation context, load-time validation and
the five judgement calls are in
`docs/prds/playbook-expression-syntax.md`.
2. **Playbook directory config field.** Where this lives in
`internal/config` / `configuration.Document`, and whether it's one
directory or a list (mirroring `SkillsDir`'s shape) -- follow existing
config precedent, not invented fresh.
**Resolved** (`archie-core-t2db.11`). The directory
shape landed as `playbook_dirs` (a LIST of directories of
`*.yaml`/`*.yml` binding files), loaded at startup as an additional
input to the two single-file fields, which remain supported unchanged.
A single `playbook_dir` would contradict
supporting multiple independently-maintained playbook sources, which
the Dedup section already assumes ('independently-sourced playbook
directories collide'), so the field is a list. Cross-source collision
(same key in two directories, or in a single-file field and a
directory) is reported like an in-directory collision -- nothing is
arbitrated by source precedence. This is what finally exercises the
design doc's drop-and-report collision rule, since a single file
cannot collide with itself. Repo-scoping (tying directories to
`Config.Repos` owner/name) is explicitly deferred to a separate,
later decision; org/tenant keying is out of scope (no auth/identity
model).
Decisions recorded from the label-vocabulary slice:
- Arbitrary labels bind to registered workflow names via
`LabelWorkflows` + `LoadLabelWorkflowsYAML`/`SetLabelWorkflows`
(`internal/domain/workflow/routing.go`).
- The closed `Kind`/NATS-subject set is untouched; the label map only
extends binding authority for labels the kind layer does not own.
- Collision rule: a label already owned by the
kind set (bug/feature/bootstrap), an empty label, an empty workflow
name, or a duplicate binding is a reported load failure -- dropped
and logged, the error returned to the caller. Nothing is silently
arbitrated by schema/version. This is the "schema defines the
accepted message; anything else is the caller's fault" rule applied
to the label layer.
- Precedence in `Route()`: explicit `t.Workflow` → arbitrary-label
binding → kind binding → triage → implement → default.
3. **Trust boundary for Module Yaegi code.** The plugin engine rule's
invariant 6 draws a line between operator-trusted in-process code and
repository-supplied code that must run in a container.
**Resolved** in `docs/prds/module-position.md`, "Trust boundary": a
Module is operator-installed, in-process and daemon-privileged, the same
tier as `PluginDir` and `SecretEngineDir`, never repository-supplied
task code.
4. **First implementation slice.** Recommend: Module position + the
playbook loader + trigger-to-workflow dispatch only (subsuming the existing
label routing) first, proving the schema-gen -> Yaegi -> playbook path
end to end on the smallest useful case, before adding Channel/Forge
action kinds or the linter/LSP.
**Resolved** (`archie-core-t2db.13`, `.14`, `.15`). The Module position
(registry + log kind, t2db.13), the CEL expression environment
(t2db.14), and the playbook document + event coordinator with
single-action workflow-kind dispatch (t2db.15) are shipped.
**Resolved** (`archie-core-t2db.23`): the coordinator selects a real
task's workflow. The wiring point is the daemon's definition pin
(`Daemon.resolveWorkflowID`, consumed by `pinWorkflowFromCollection` in
`internal/daemon`), not `pollNATS`/`publishTask`. Routing belongs to the
pin because a workflow definition is a
database row pinned before dispatch, which makes the pin the one place a
task's workflow is chosen. Precedence there is explicit `Task.Workflow`
(the waiting_human -> approved requeue) → matching playbook →
`workflow.ResolveWorkflowID`'s label binding → kind binding → triage →
implement. A playbook naming an undefined workflow is a reported failure
that parks the task rather than a silent fall-through to the binding's
choice.
`Store.Dispatch` returns the selected workflow _name_ and the matching
playbook's id and version, not a compiled `workflow.Workflow`: the
production caller decides against the active definition collection, and
the id and version are the first two components of the gap-2 idempotency
key. The playbook package does not import `internal/domain/workflow`.
A `when` condition at this point reads what the intake knows about the
originating issue: `kind`, `labels`, `owner`, `repo`, `number`, `title`,
`body`, `source`, built by `playbookInput` in `internal/daemon`.
The trigger shape reuses the existing workintake kind/label vocabulary.
The single-action hard boundary is superseded by
`docs/prds/multi-action-playbooks.md` (two-shape rule); Module, Channel,
and Forge positions still have no production dispatch path.
## Standing constraint
This may be commercialised, and is to be discernible from other open-source
event-driven-automation tooling. No design decision follows from that yet;
it bears on licensing or feature-gating questions about playbook authoring
and the LSP when they arise.
## Packages this touches (first slice)
- New: a schema-generation package/convention (`go:generate` source +
emitted contracts) for the Module position.
- New: playbook loader + event coordinator (name/location TBD -- likely
`internal/domain/eda` or similar, following the domain-layer rule: no
infrastructure imports, no untyped hooks).
- `internal/domain/workflow`: dispatch target for `workflow`-kind actions,
unchanged in its own contracts.
- `internal/domain/workintake`: `labelKinds`/routing becomes one playbook
among others once the loader subsumes it; existing Go fallback stays for
backward compatibility until playbooks fully replace it (mirrors the
`dynamic-workflow-triage.md` precedent of a two-line fallback change, not
a rip-and-replace).
-76
View File
@@ -1,76 +0,0 @@
# Embedded NATS execution -- decision
**Status:** Finalised
**Date:** 2026-08-24
**Beads epic:** `archie-core-q15y`
This decision supersedes the position that embedded NATS was only a
distribution mechanism and could not be an agent-execution topology. That was
true only because the embedded listener was unauthenticated loopback. It left a
second production architecture in which `archied` ran autonomous workflows in
its own process, weakening the isolation boundary that managed task containers
exist to provide.
## One execution architecture, two broker deployments
Every autonomous repository workflow is handed over as one complete task via
NATS and runs in a task-scoped `archie-agent` container. `archied` remains a
native, long-lived orchestration and interactive-chat process; its operator
configured host filesystem access is unchanged. It owns task admission,
state, forge and worktree operations, container lifecycle, and the broker when
the embedded deployment is selected. It does not run an autonomous model loop.
NATS has two supported deployment shapes:
| mode | meaning |
| ---------- | --------------------------------------------------------- |
| `embedded` | `archied` owns an in-process JetStream server (default). |
| `external` | `archied` and workers connect to the configured NATS URL. |
Both shapes have identical task semantics: one container and one full-task
request per workflow. Broker placement must not select a different executor.
The legacy `agent` section and `containers.enabled` key remain decode-only
migration inputs. `nats.mode = "off"`, per-stage NATS, in-process execution,
and subprocess execution are not production choices.
SQLite remains authoritative for task state. NATS is the sole autonomous work
handoff. SQLite recovery may identify work that needs republishing, but it must
not cause `archied` to call `workflow.Run` locally.
## Embedded reachability and authentication
An embedded listener uses a cryptographically random bearer token generated for
each daemon start. The token exists only in process memory and the environment
of managed worker containers; it is never written to config or logs.
For a native daemon with managed containers, startup resolves the Docker bridge
the workers will join. The listener binds only to that bridge's host gateway
address on a random port. Both the native daemon and workers use that same
reachable endpoint, and every client supplies the generated token. Binding a
Docker bridge address keeps the listener off ordinary LAN interfaces without
publishing a host port. A configured user bridge is respected; otherwise the
Docker default bridge is used. A network without a usable local IPv4 gateway is
a startup error for autonomous execution.
If Docker is unavailable, interactive chat may still start and embedded NATS
may remain loopback-only, but autonomous tasks park with an explicit container
capability failure. They never fall back to host execution.
## Ownership and lifecycle
- `internal/infrastructure/eventbus/nats` owns the authenticated embedded
server and exposes its runtime endpoint, not the server implementation.
- `internal/container` resolves the worker bridge and gateway and owns task
container lifecycle.
- `internal/app` composition selects embedded or external broker deployment,
freezes the connected runtime endpoint for worker environments, and wires the
full-task handoff.
- `cmd/archied` remains process input only as the domain migration reaches this
composition path.
The daemon starts the embedded server before its client, closes clients before
the server, and keeps JetStream data beneath the daemon data directory. NATS URL
and token are startup-built values: a reload cannot send new workers to a broker
different from the one the daemon is using.
-233
View File
@@ -1,233 +0,0 @@
# Event automation: identified events, typed parameters, purpose-built agents
**Status:** Approved
**Date:** 2026-09-23
**Parent:** epic `archie-core-t2db`
## Why this exists
Archie is an event-driven automation system. Any system that can send a
webhook (a forge, an error tracker, a firewall, a monitoring stack) should be
able to start an agent built for that job. The shape this replaces cannot:
- A binding matches only the URL segment an event was posted to, and a source
may have one binding. Two kinds of event from one sender cannot go to
different workflows.
- A mapping is a list of JSON paths written against one example payload.
Nothing recognises what kind of event arrived.
- Mapped values reach the task only as `key=value` lines in its body text.
- Every task needs a repository and runs in a git worktree.
- Every agent runs the same image with the same forwarded keys.
## The model
```
source ─▶ event type ─▶ mapping ─▶ binding ─▶ workflow ─▶ agent profile
(identified) (params) (+ filter, (inputs, (image, tools)
repo) profile)
```
### Sources
A source is the endpoint one sender posts to. Its path is a generated UUIDv7
(`/webhooks/capture/0199…`), so an endpoint cannot be guessed or collide. The
operator may replace it with a custom path for a sender that cannot use that
format; a custom path must be unique and URL-safe, and is refused otherwise.
A source owns the signing setting:
- **Signed** (default). Archie generates the secret. Only events with a valid
`X-Hub-Signature-256` or `X-Signature-256` HMAC are dispatched.
- **Unsigned.** The operator turns signing off for a sender that cannot sign.
The source and every event from it are marked unsigned in the inspector,
the binding list and the task timeline. Turning signing off needs the same
approval as arming a binding.
Unauthenticated events on a signed source are captured and never
dispatched.
### Event types
An event type is a named kind of event from one source, such as
`github / pull_request.opened` or `firewall / blocked_connection`. It is
defined by a match rule:
- header equality (`X-GitHub-Event = pull_request`), and
- payload conditions (`action = "opened"`, or a path being present).
An event type can be created two ways:
- **From an example payload.** The operator pastes a payload (and optionally
its headers), and archie converts it to the type's schema. No event needs to
have arrived.
- **From captures.** Archie proposes types from what has arrived, as below.
Either way, archie infers the schema, not the operator:
- Each capture gets a structural signature: the set of JSON paths with their
value types, plus the headers that look like discriminators (`*-Event`,
`*-Type`, `Content-Type`).
- Captures from one source that share a signature are grouped. The inspector
shows each group as a proposed event type, with its inferred schema, its
number of events and a sample, until the operator names it or dismisses it.
- The proposed match rule is the set of discriminators that separates the
group from its siblings. The operator can edit it before saving.
- A capture that matches no named type is shown as unidentified. It is never
dispatched.
Two event types on one source whose rules can match the same event are
refused when the second one is saved.
### Mappings
A mapping belongs to an event type. It maps payload paths to named, typed
parameters, and it is checked against the type's inferred schema, so a path
the type does not have is refused when the mapping is saved. Any number of
bindings may reuse one mapping.
Each mapping shows how many events it has matched, with the time of the most
recent, so an operator can see which mappings are live and which have never
fired.
### Workflows declare inputs
A workflow definition declares its inputs:
```yaml
id: firewall-investigate
inputs:
src_ip: { type: string, required: true }
severity: { type: string }
repository: none # none | optional | required
profile: network-investigator
steps: ...
```
- `repository: none` runs the agent in a scratch workspace with no clone.
`required`, the default, gives the agent a worktree of the task's
repository. `optional` gives it a worktree when the binding names a
repository and a scratch workspace when it does not.
- A workflow whose `repository` is not `required` may use only steps that need
no repository. `agent.run` is one: it runs one agent mission and finishes
the task as done, with no pull request.
- The declared inputs reach the agent as structured data in the task brief
and in the agent's context. They are not body text.
- A workflow may declare `outputs`, the structured result it returns when it
finishes.
### Workflows call workflows
A workflow step can call another workflow. The call passes the callee's
inputs, and the callee runs as its own run with its own agent profile, so one
event can start an investigator that then calls a containment workflow:
```yaml
steps:
- type: workflow.call
workflow: firewall-contain
inputs: { src_ip: inputs.src_ip }
wait: true # false starts the callee and continues
```
- With `wait: true` the caller receives the callee's outputs and fails if the
callee fails. With `wait: false` the caller continues and the callee's
outcome is reported on its own run.
- A call's inputs are checked against the callee's declared inputs when the
calling workflow is saved.
- A workflow that calls itself, directly or through other workflows, is
refused when it is saved. Calls are limited to a fixed depth at run time.
- A callee must be enabled for the caller's org.
### Bindings
A binding connects an event type to one workflow:
- an optional filter on mapped parameters (`severity in ["high", "critical"]`),
written in the CEL the playbook engine already uses;
- an assignment of workflow inputs from mapped parameters or constants,
checked against the workflow's declared inputs when the binding is saved;
- a repository, when the workflow's `repository` is not `none`: either fixed
(`acme/api`) or taken from a parameter (the GitHub webhook's
`repository.full_name`). A repository taken from a parameter must be a
configured one, or the event does not dispatch.
Any number of bindings may use one event type. Approval and re-approval after
an edit are unchanged. A binding whose workflow input types no longer match is
refused at dispatch and reported on the binding.
### Agent profiles
A profile is a named execution environment that a workflow selects:
- the container image;
- an allowlist over the tools Archie adds to the agent: MCP servers,
repository scripts and skill plugins. The agent's own file tools are always
present;
- the secrets injected into it, by reference to the secret store, never
inline (superseded by `docs/prds/orgs-and-access.md`: secrets are granted to
identities, and a profile holds no secrets);
- its network access and forge access (superseded by
`docs/prds/orgs-and-access.md`: permissions are granted to identities).
Profiles are configured under `[containers.profiles.<name>]`. The global
`[containers].image` becomes the default profile, so existing workflows are
unchanged. A task whose workflow names an unconfigured profile is parked for
an operator. A secret or permission is granted to an identity, never to a binding, so an
event can never widen what an agent can do (`docs/prds/orgs-and-access.md`).
### Workflows belong to orgs
Archie ships a default workflow catalogue that every org can use. An org can
add its own workflows, and can enable or disable any workflow, default or its
own, for itself. A binding can target only a workflow enabled for its org, and
disabling a workflow stops its bindings dispatching and marks them on the
binding list.
## Delivery order
1. Event types: structural signatures, grouping, naming, match rules, and the
inspector view of proposed and unidentified events.
2. Mappings per event type, and multiple bindings per source.
3. Workflow inputs, structured parameters in the task brief, and
`repository: none | optional | required`.
4. Agent profiles with image and tools.
5. Signing as a source setting, with the unsigned option; UUIDv7 source paths
with a custom-path override.
6. Workflows calling workflows, with declared outputs.
7. Org-scoped workflow catalogue, once orgs exist.
Each step ships usable on its own. Step 3 is the first where an event that has
nothing to do with a repository can run a workflow.
## Out of scope
- How forge-issue playbook triggers (`internal/domain/eda/playbook`) relate to
event types. They stay as they are until event types exist.
- Built-in catalogues of event types for known senders.
- Orgs themselves: membership, access, and how sources and bindings belong to
one. This design needs only an org to own workflows and their enabled state.
- Running an agent outside a container.
## Verification
- Two GitHub webhooks with different `X-GitHub-Event` headers posted to one
source are grouped into two proposed event types, and a firewall payload
with a different shape is grouped separately.
- A capture matching no named type is shown as unidentified and starts
nothing.
- A firewall event runs a `repository: none` workflow with its mapped inputs
readable by the agent as structured data, and no clone is made.
- A GitHub `pull_request.opened` event runs a PR review workflow against the
repository named in the payload.
- An event type created from a pasted payload has that payload's schema, and a
later matching event is identified as it.
- A new source gets a UUIDv7 path; a custom path that is already taken is
refused.
- A workflow that calls another with `wait: true` receives its outputs; one
that calls itself through another workflow is refused when saved.
- A mapping's matched-event count rises by one for each event it resolves.
- A workflow disabled for an org cannot be targeted, and its existing bindings
stop dispatching.
- A binding whose filter excludes an event does not dispatch it.
- An agent receives only the secrets its identity is granted.
- An unsigned event on a signed source is captured and not dispatched. An
event on an unsigned source is dispatched and marked unsigned.
-150
View File
@@ -1,150 +0,0 @@
# Event capture storage -- decision
**Status:** Finalised
**Date:** 2026-08-22
**Beads issue:** `archie-core-t2db.1`
`webhook-intake-security.md` decided points 1-5 (auth split, approval gate,
rate limits, blast radius, retention/redaction) and explicitly left the
storage mechanism open, forward-pointing at "`7d5u.2`, embedded NATS." That
pointer predates `7d5u.3`'s 2026-08-22 narrowing, which assigned capture
storage to this bead by name and told it to decide NATS-vs-SQLite itself
rather than inherit an answer. This document is that decision.
## Decision: SQLite, not NATS JetStream
Captured events are stored in archied's existing SQLite database, in a new
`captured_events` table following the same shape as `internal/store/events.go`
(`internal/store`, `*Store`, SQL migrations inline in Go). No JetStream
stream is introduced for capture.
### Why
**NATS availability does not make capture a broker concern.** NATS is now
unconditional for autonomous workflow handoff, including embedded mode, but
capture is also used by deployments with no repository workflow configured.
SQLite is guaranteed present because it backs daemon state, and keeps
capture inspection independent of broker retention and consumer lifecycle.
The original version of this decision cited optional NATS as an additional
reason; that premise was superseded by `archie-core-q15y`, while the storage
fit and independence arguments remain.
**Capture's access pattern doesn't need what JetStream is for.** JetStream
earns its complexity for reaction delivery (`7d5u.2`) because multiple
independent consumers need fan-out, at-least-once redelivery, and Ack/Nak
semantics -- exactly the trap `CLAUDE.md` documents about `WorkQueuePolicy`
and overlapping consumers. Capture has exactly one writer (the HTTP handler)
and one reader (a human via the dashboard inspector, `t2db.2`). There is no
competing-consumer problem to solve and no redelivery semantics to get right,
so JetStream's core value proposition doesn't apply here. A bounded SQL
table is a better fit on the merits, not merely as a fallback.
**Reusing `7d5u.2`'s stream, once it exists, would still be wrong.** That
stream is provisioned for fan-out reaction delivery with its own retention
policy decision. Capture's retention need -- age- and count-bounded, prune
on write, no replay -- is a different shape. Building a second stream just
for capture, gated on an unrelated bead landing first, would trade a small
amount of duplication now for a hard dependency on `7d5u.2`'s timeline that
this bead's own acceptance criteria say not to accrue by accident.
This does not foreclose NATS later. If cross-daemon capture sharing or
durable replay becomes a real requirement, that is a new decision made
against a real need, not now against a speculative one.
## Storage shape
`captured_events` table (`internal/store/captures.go`, mirrors
`internal/store/events.go`'s pattern):
| column | type | notes |
| ------------- | ------- | ------------------------------------------------------------------ |
| id | INTEGER | primary key, autoincrement |
| received_at | TEXT | RFC3339Nano |
| source | TEXT | opaque path segment chosen by the sender's operator |
| remote_addr | TEXT | `RemoteAddr` at capture time |
| content_type | TEXT | `Content-Type` header |
| headers | TEXT | JSON, redacted |
| body | TEXT | JSON, redacted (`webhookguard.RedactPayload`) |
| authenticated | INTEGER | 0/1; always 0 until a source registers a secret (future: `t2db.4`) |
Indexed on `(source, id)` for per-source listing and pruning, and `id` alone
for the global cap.
## Disk-bound mechanics
Three independent bounds, composed, per `webhook-intake-security.md` point 5
and this bead's own "capture cannot exhaust disk" criterion:
1. **Per-request size cap.** The HTTP handler reads the body through
`http.MaxBytesReader` (256 KiB default, configurable). A single oversized
POST is rejected (413) before redaction or storage sees it.
2. **Per-remote-address rate limit.** `webhookguard.RateLimiter`, keyed by
the request's remote address, applied before the body is even read.
_Not_ keyed by the `source` path segment: `RateLimiter`'s own doc comment
states its bucket map assumes a bounded, operator-registered key space,
never evicted. `source` is exactly the opposite here -- an unregistered,
attacker-chosen URL segment, since capturing senders with no registration
yet is this endpoint's entire purpose. Keying on it would let one sender
bypass the limit by rotating the segment every request (a fresh key
always starts with a full burst) and grow the bucket map without bound.
Remote address is the bounded identity actually available pre-auth.
Over-budget requests get 429, observable per point 3 of the security
decision.
3. **Retention prune-on-write.** Every insert prunes, in the same
transaction: rows older than `retention_days` (default 7, per the
security decision) OR beyond `max_events` total rows (default 5000, this
bead's own addition -- age alone doesn't bound disk under a sustained
flood inside the retention window; a count cap does). No background
sweep goroutine; the daemon doesn't need one for this.
Together these give a deterministic worst-case: `max_events * max_body_bytes`
regardless of sender behaviour, independent of whether the age-based or
count-based bound is what actually fires first.
## HTTP surface
Mounted on the existing `internal/webui` dashboard server
(`Server.Handler`'s `top` mux), not a new listener. `POST
/webhooks/capture/{source}` bypasses `requireToken` the same way `/healthz`
already does -- capture must accept unauthenticated senders by design (that
is the entire point: you cannot HMAC-verify a source you haven't configured
a secret for yet). Reachability is therefore whatever already exposes the
dashboard in a given deployment; no new port/host config surface is added,
and no new claim about public reachability is made beyond what already
exists for the dashboard.
Amended 2026-09-10 by the UI cutover (`archie-core-8cda.5.4`): the one
process serving the dashboard is now the standalone archie-ui service, so
the receiver mounts there, composed from the UI process's own State Store
client. The binding-dispatch loop that turns captures into tasks stays in
the daemon, consuming the same store, so the HTTP front door moved without
moving work intake.
`GET` listing/inspection endpoints (`t2db.2`) stay behind `requireToken` like
every other `/api/*` route -- captured payloads are visible only to an
authenticated operator, per the security decision's point 5 visibility rule.
## Config
New `[capture]` section in `config.example.toml` / `internal/config`:
```toml
[capture]
retention_days = 7
max_events = 5000
max_body_bytes = 262144
rate_per_second = 1.0
rate_burst = 5
```
All fields have defaults; an empty `[capture]` section (or its absence) is
valid and produces the defaults above -- capture is on by default, since an
unbound POST being captured rather than rejected is this bead's acceptance
criterion, not an opt-in.
## What this does not decide
Binding a captured event to a workflow, the draft/pending_approval/armed
state machine, and per-source HMAC secret registration are `t2db.3`/`t2db.4`.
The dashboard inspector UI is `t2db.2`. This bead ships capture and storage
only.
-134
View File
@@ -1,134 +0,0 @@
# Event sources and reactions -- decision
**Status:** Approved
**Date:** 2026-08-22
**Beads issue:** `archie-core-7d5u.1`, blocks `7d5u.2/.3/.4/.5`
Answers the four questions in `7d5u.1`'s description. Investigated against
the actual tree, not designed from scratch: three mechanisms already in this
codebase answer most of this, and the job here is picking the right one for
each question and saying which packages change.
## 1. In-process typed families, not out-of-process dispatch
Archie has no out-of-process extension mechanism. The plugin engine
rule (`docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict`,
mechanically checked by
`internal/plugin/architecture_test.go`) keeps every capability family
in-process behind a narrow typed registrar; NATS RPC exists for
daemon<->agentexec, a different actor with a different trust boundary (task
execution, not third-party extension code), not a precedent for generic
plugin dispatch. Neither epic's near-term payoff -- react to a labelled
issue, bind a captured webhook to a workflow -- needs extension code in
another language or process. Building out-of-process dispatch now would be
designing for a requirement neither epic states.
`docs/architecture/plugins-and-extensions.md` does **not** need amending.
The line that looked like a blanket ban on hooks (`archie-core-7d5u`'s notes
record the correction) is scoped to Workflow semantics specifically, and
nothing decided here touches Workflow's ownership of its own contracts.
## 2. Reaction delivery: `internal/eventbus`'s contract, a NEW stream
`internal/eventbus.Publisher`/`Consumer` already has everything a reaction
needs: `PublishUnique(subject, idempotencyKey, payload)` for at-least-once
without duplicate enqueue, `Ack`/`Nak` with "a handler returning an error
causes redelivery." Do not design new delivery semantics; use this contract.
**Do not reuse the existing `nats.Client` as-is.** `Config.StreamName` and
`Config.Subjects` are already composition-supplied ("the bus must not know
which subjects belong to which domain," `config.go`), but the
retention policy is not parameterised: `New` hardcodes
`Retention: jetstream.WorkQueuePolicy` (`client.go`), the competing-consumer
policy correct for `ARCHIE_TASKS` task distribution -- one message, claimed by
exactly one consumer -- and wrong for reactions. Two independent reactions
both wanting to see the same event under `WorkQueuePolicy` hit exactly the
trap `CLAUDE.md` already documents: overlapping filter subjects on a
work-queue stream mean the second consumer silently gets nothing. Reactions
need fan-out, not claim-once, so the client needs retention made a `Config`
field (defaulting to `WorkQueuePolicy` so `ARCHIE_TASKS` is
unaffected), and a second stream (`ARCHIE_REACTIONS` or similar) configured
under a fan-out-capable policy, alongside the existing task-distribution
stream -- not instead of it.
This is where `7d5u.2`'s embedded-vs-external axis attaches: whichever NATS
instance backs `ARCHIE_TASKS` also backs the reaction stream. NATS is not
optional as a technology -- the choice is only
whether it runs as an external server or embedded in-process
(`github.com/nats-io/nats-server/v2` is already a direct, test-proven
dependency, just never wired into production startup). `7d5u.2` wires that;
this document does not re-decide it.
## 3. Reactions in these two epics are producer-only
No veto, no mutation of in-flight work. Two existing shapes cover everything
either epic actually needs, and neither is a hook that can block something
else:
- **Cheap wake, no payload.** `internal/domain/curator/wake.go`'s
`WakeOnPrimaryInput` subscribes to the lossy `events.Bus` and nudges a
runtime to check sooner; a dropped event only delays a check-in, never
loses work, because the trigger decision is a deterministic state read at
pass time, not the event payload. Model any "check something sooner"
reaction on this, unchanged.
- **Produce new work, real payload.** `daemon.go`'s existing `pollNATS` ->
`publishTask` path is already exactly a reaction that observes forge state
and produces a `workintake.TaskEnvelope`. A webhook source is a second
producer into the same path, not a new capability -- see question 4.
A reaction that can veto or mutate an _in-flight_ task (block a PR from
opening, alter a running stage) is a different, harder problem with its own
ordering and failure semantics, and belongs to `archie-core-h019` (adversarial
self-review) if and when that epic needs one -- not here. Do not build a
general block-capable hook mechanism for either epic; nothing in their stated
scope requires it, and it would duplicate whatever h019 eventually needs.
## 4. No single generic intake interface; each domain keeps its own
A `Source` interface generic enough to cover a forge issue, a chat message,
and a cron tick would need an `any` payload -- the untyped-hook shape the
plugin engine rule exists to prevent, just moved into a new package instead
of the old one.
**What's genuinely shared, and belongs in a small cross-cutting package**
(imports nothing per the cross-cutting rule): the mechanics from
`archie-core-t2db.5` that apply to any inbound HTTP source regardless of what
consumes it -- HMAC verification (already a standalone function,
`internal/channels/webhook/webhook.go`'s `validateHMAC`), per-source rate
limiting, capture/audit, and the draft/pending_approval/armed gate. This
package owns none of forge, chat, or workintake's vocabulary.
**What stays domain-owned, per existing convention:**
- Forge-issue intake needs no new type. `internal/domain/workintake.TaskEnvelope`
already is the typed contract -- `Subject()`, `IdempotencyKey()` (keyed on
`owner/repo/number`, not on delivery source), `Encode()`. A webhook-sourced
envelope for the same issue produces the _same_ idempotency key as a
poll-discovered one, so `PublishUnique` dedups the two paths for free. This
is `7d5u.5`'s answer, not a new mechanism: reuse `TaskEnvelope` and
`publishTask`, don't invent a second envelope shape.
- Chat-webhook intake stays exactly what it is:
`internal/channels/webhook`'s `RouteConfig` routes into `gateway.Router`,
documented as chat-scoped ("External services push messages into
archie-core's gateway for LLM processing"). Do not generalise this package
into a multi-domain receiver -- it already does one thing per "a package
owns its own format end to end."
- A forge webhook receiver (`7d5u.4`) is new: it builds on the shared
mechanics above, decodes a GitHub payload into the _same_
`workintake.TaskEnvelope`, and calls the _same_ `publishTask` the poller
calls. It does not get its own dispatch predicate -- `7d5u.4`'s bead
already requires reusing the poller's label/assignee predicate rather than
reimplementing it, and this decision extends that to the envelope and
publish path too.
## Packages this touches
- New: a cross-cutting intake-mechanics package (HMAC, rate limit, capture,
approval state machine) -- name and exact location decided in `t2db.1`/`t2db.5`.
- `internal/infrastructure/eventbus/nats`: a second stream/consumer
configuration for reactions, distinct retention policy from `ARCHIE_TASKS`.
- `internal/domain/workintake`: unchanged in shape; `TaskEnvelope` is reused,
not extended.
- `internal/daemon`: gains a webhook-sourced call path into the existing
`publishTask`, alongside the existing poll-sourced one.
- `internal/channels/webhook`: unchanged. Not the forge receiver.
-200
View File
@@ -1,200 +0,0 @@
# Execution tree and enforced state machine
**Status:** Approved
**Authority:** `docs/architecture/agent-system.md` (canonical workflow model);
settles the "enforced WorkflowExecution state machine" item in
`docs/architecture/migration-decisions.md` section 4.
**Compounds with:** `docs/prds/task-run-detail.md` (attempt attribution),
`docs/prds/state-store-contract.md` (wire contract and task-scoped grants).
## Decision
A WorkflowExecution becomes the root of a tree of StepExecutions. Every stage
run, and every agent call a stage makes, is its own durable record with a
parent, an attempt, a status and an outcome. Both levels move only through a
declared transition table, enforced by the State Store in the same transaction
that writes the audit row and the domain event.
## Problem
- A run is one `tasks` row. The only per-step record is the mutable `stage`
column, overwritten as `workflow.Run` advances, plus observability events.
A failed attempt cannot say which step failed or what its children did
without replaying the event stream.
- `Store.Transition` guards on the expected `from` status, but any `from` to
any `to` is accepted. A `queued` to `merged` write succeeds.
- Stop cancels one context in `daemon.runningTasks`. Nothing persisted says
which work was in flight, so an agent call that outlives its stage (a
reviewer, a container) is invisible to the store.
- `workflow.Run` writes `tc.Store.Update` and discards the error, then emits
`KindStageStart` separately. State and events can diverge.
## Model
```text
WorkflowExecution (tasks row, id E)
└── attempt N
├── StepExecution stage "plan" depth 0
├── StepExecution stage "implement" depth 0
│ └── StepExecution agent "implement" depth 1
└── StepExecution stage "review" depth 0
├── StepExecution agent "review:1" depth 1
└── StepExecution agent "review:2" depth 1
```
- A StepExecution belongs to exactly one WorkflowExecution and one attempt.
`parent_id` is null for a stage and names the enclosing StepExecution
otherwise. Depth is derived from the parent, never supplied by the caller.
- `kind` is `stage`, `agent` or `call`. A new kind needs a named consumer
before it is added.
- A `workflow.call` step (`docs/prds/event-automation.md`) is a `call`
StepExecution in the caller's tree. The callee is its own
WorkflowExecution, with its own tree, acting as its own identity, and the
`call` step records the callee's execution ID. Trees never nest across
executions, so each run's tree stays inside that run's authority.
- A retry starts a new attempt. Earlier attempts' StepExecutions are never
rewritten.
## Transition tables
WorkflowExecution statuses are the existing `taskstate` constants, persisted
strings unchanged. `taskstate` gains the one table every writer checks:
| From | To |
| --------------- | ---------------------------------------------------------- |
| `queued` | `running`, `closed_wont_do` |
| `running` | `queued` (crash recovery), `waiting_human`, `pr_open`, `completed`, `parked`, `closed_wont_do` |
| `waiting_human` | `queued` (approve), `closed_wont_do` |
| `parked` | `queued` (retry), `dead` (abandon), `closed_wont_do` |
| `pr_open` | `merged`, `rejected`, `queued` (remediation), `closed_wont_do` |
| terminal | none |
StepExecution statuses:
| From | To |
| --------- | ------------------------------------------------------ |
| `pending` | `running`, `cancelled` |
| `running` | `succeeded`, `failed`, `cancelled`, `interrupted` |
| terminal | none |
`interrupted` means the process running the step died or shut down. It is
distinct from `cancelled`, which an operator or a parent asked for, and from
`failed`, which the step reported.
A StepExecution cannot reach `running` while its WorkflowExecution is not
`running`, and cannot start under a terminal parent.
## Enforcement
- The table lives in `taskstate` (no dependencies), so the store, daemon and
gateway share one copy.
- Every store method that changes `tasks.status` checks the table and writes
the audit and event rows, not only `Transition`. That includes the claim,
`ParkTask`, `Requeue`, `RetryTask`, `BeginRemediation` and `RecoverStale`
paths, several of which change status without an audit row.
- The State Store rejects an illegal transition with a new sentinel,
`ErrIllegalTransition`, carried across the wire through `mapError` like
`ErrStaleTransition`. A stale `from` stays `ErrStaleTransition`.
- Each transition is one transaction: guarded row update, audit row, domain
event row. The events table is written by the store, not emitted beside it.
`KindStageStart` and `KindStageFinish` are produced by the step transition
and published to the bus after commit.
- `workflow.Run` stops discarding persistence errors. A failed step write
parks the execution; the step does not run unrecorded.
## Cancellation
Stopping a run is one store call, `CancelExecution(E, reason)`. In one
transaction it moves every non-terminal StepExecution of the current attempt
to `cancelled` and the WorkflowExecution to `closed_wont_do` or `parked`,
whichever the operator action names. The daemon then cancels the in-memory
context. A worker whose step write returns `ErrStaleTransition` because its
step is already `cancelled` stops without writing further.
Cancelling a caller cancels each callee it is waiting on (`wait: true`),
through `CancelExecution` on the callee under the callee's own lifecycle. A
callee started with `wait: false` runs on.
The store is the record of cancellation. The context cancel is the delivery
mechanism, so a lost cancel still leaves the store correct and the worker's
next write fails.
## Crash recovery
`RecoverStale` moves every `running` StepExecution of an interrupted
execution to `interrupted` in the same transaction that requeues the
execution. The next attempt starts with fresh steps.
## Wire contract
New State Store RPCs, each with a matching Go method on a narrow consumer
facade:
- `StartStep(execution, attempt, parent, kind, name) -> step id`
- `FinishStep(step, from, to, detail, tokens_used)`
- `CancelExecution(execution, reason, to)`
- `ListSteps(execution, attempt)`
The run credential of `docs/prds/orgs-and-access.md` authorises `StartStep`
and `FinishStep` on its own execution only, and the container records its own
agent calls with it. `CancelExecution` and `ListSteps` are dashboard, API and
dispatch actions, decided by the Authorizer: `update` and `read` on the run.
## Organisations
`docs/prds/orgs-and-access.md` is the boundary. A StepExecution belongs to its
WorkflowExecution's org and workspace and carries their `org_id` and
`workspace_id`, like every owned record. The State Store stamps both from the
credential on `StartStep` and ignores them in the request. `ListSteps` for an
execution in another org returns the store's ordinary not-found error.
## Storage
One new table, `step_executions`: `id`, `org_id`, `workspace_id`,
`execution_id`, `attempt`, `parent_id`, `depth`, `kind`, `name`,
`called_execution_id`, `status`, `detail`, `tokens_used`, `started_at`,
`finished_at`. Indexed on `(execution_id, attempt, id)`.
Deleting an execution (archive, clearing terminal tasks) deletes its steps.
Existing rows gain no backfilled steps. Their history stays in `transitions`
and `events`.
`tasks.stage` is written from the step transition while any reader still uses
it, then dropped once the dashboard reads `ListSteps`.
## Out of scope
- Running sibling steps in parallel. The tree records concurrency; changing
the stage runner is separate work.
- Cost in currency. `tokens_used` per step is the only usage field.
- Workflow definition versioning and the `tasks` to `workflow_executions`
rename.
- A harness contract for swappable coding agents.
## Plan
1. `taskstate` transition tables with table-driven tests covering every
legal and a sample of illegal pairs.
2. `ErrIllegalTransition` enforced in the Postgres store and mapped over the
wire.
3. `step_executions` migration, `StartStep`/`FinishStep`, grant rules;
`workflow.Run` records stages; events written in the transition
transaction.
4. Agent-call children recorded from the agent runtime.
5. `CancelExecution`; daemon stop and chat/dashboard actions route through it.
6. `RecoverStale` interrupts running steps.
7. Dashboard run detail reads `ListSteps`; `tasks.stage` dropped.
## Verification
- An illegal WorkflowExecution or StepExecution transition returns
`ErrIllegalTransition` over gRPC, and `errors.Is` matches on the client.
- Killing the daemon mid-stage, then restarting, leaves that stage
`interrupted` and the execution `queued` with a new attempt.
- Stopping a run during review leaves every review child `cancelled`, and a
late `FinishStep` from the container returns `ErrStaleTransition`.
- A run credential cannot `StartStep` on another execution, and a member of
org A listing steps of an org B execution gets not-found.
- Cancelling a caller cancels its `wait: true` callee and leaves a
`wait: false` callee running.
- For every step transition there is exactly one event row, written in the
same transaction.
-174
View File
@@ -1,174 +0,0 @@
# Extensions centre
**Status:** Draft
> Superseded by `docs/prds/store.md`.
Epic: `archie-core-1786637490708-35-38424ead` / GitHub `#56` ("Replace Skills
with a bundled Extensions centre").
Skills, Workflows, and Tools/MCP already exist as separate, working
inventories with their own APIs (`api_skills.go`, `api_workflows.go`,
config-driven MCP servers) and their own family-owned controller pattern
(`curator.Registry`, `health.Registry`, `image.Registry`,
`workflow.Registry` all already prove this shape). `plugin.Plugin`
(`internal/plugin/plugin.go`) is already metadata-only, per
`docs/architecture/plugins-and-extensions.md`. None of that is rebuilt here.
What's missing, confirmed by grep, is: any config schema for enabling or
disabling a capability, any "pending restart" state tracking, and any single
inventory that reconciles configured/bundled/discovered/active state across
families. This document decides those three things and the UI surface that
presents them. It extends `plugins-and-extensions.md` rather than replacing
it — that doc's decisions (metadata-only `Plugin`, typed capability
families, no generic dispatch) are unchanged.
Out of scope: any remote or arbitrary-URL plugin installation path (the
epic's own acceptance criteria forbid this, and `plugin.LoadDir`
(`plugin.go`) already only reads `~/.config/archie/plugins/*.go` — this
document does not add a fetch-by-URL variant to it).
## Problem
`internal/config/config.go`'s `MCPServer` and `ToolsConfig` structs have no
`enabled` field (confirmed by the investigation grep). `api_config.go`'s
`UpdateConfig`/`handleConfigUpdate` seam persists changes but has no state
distinguishing "saved, takes effect now" from "saved, needs restart" — the
only existing reload path (`ReloadChannel`, `server.go`) is
channel-specific and explicitly does not cover plugins or MCP servers.
`server.go` already wires five separate optional inventories
(Workflows, Skills, Curators, Channels, Captures/Mappings/Bindings) as
independent fields with no unifying type — an operator has no single
place to see "what's available, what's enabled, what's actually running,
and what's degraded" across all of them. `ui/src/` has `settings/`,
`skills/`, and `workflows/` directories already; there is no
`ui/src/extensions/`.
## Design
### Unified inventory type
```go
package extensions // internal/domain/extensions — new, app-level aggregator
type State string
const (
StateAvailable State = "available" // bundled, not configured
StateEnabled State = "enabled" // configured on, not yet live
StateActive State = "active" // configured on and running
StateDegraded State = "degraded" // active but unhealthy
StateSkipped State = "skipped" // optional, disabled by config
StatePendingRestart State = "pending_restart" // config changed, not yet live
)
type Entry struct {
Family string // "skill" | "workflow" | "tool" | "plugin" | "integration"
Name string
Core bool // non-disableable
State State
Health string // reuses whatever the family's own registry already reports
}
type Inventory interface {
List(ctx context.Context) ([]Entry, error)
}
```
**Decision.** `extensions.Inventory` is a read-only aggregator, not a new
domain that owns state. It queries each family's existing registry
(`curator.Registry`, `health.Registry`, `workflow.Registry`, the MCP client
set, `plugin.LoadDir`'s result) for live state, and compares that against
the config-desired state (below) to compute `StatePendingRestart` — the diff
is computed on read, not persisted, so there is no new durable state to keep
consistent with the registries themselves. This follows
`migration-decisions.md`'s rule that cross-cutting aggregation composes
existing domain-owned contracts rather than duplicating their state.
**Call site.** New package `internal/domain/extensions/inventory.go`.
Composed in `internal/app/archied` (wherever `server.go`'s other optional
fields — Workflows, Skills, Curators — are wired) since it needs
references to every family's registry, which only application-layer
composition has.
### Config-backed enablement
**Decision.** Add `enabled bool` (default `true` for pre-existing configured
entries, so no upgrade silently disables anything already configured) to
each family's config element: `MCPServer.Enabled`, and equivalent fields on
whatever config types back skills/workflows/plugins if they don't already
have an on/off switch. Core capabilities (identity, workflow engine, State
Store connectivity — named in `organisation.md`'s cross-cutting packages)
have no `enabled` field at all; a config value can't be added to something
that doesn't expose the toggle, which is the "non-disableable" property
enforced structurally rather than by a runtime check that could be
bypassed.
**Call site.** `internal/config/config.go` — add the field per family
struct, not one generic `map[string]bool` (typed fields keep
`docsgen`/`contracts.json` generation working, per `tools/docsgen`'s
"treat flags as executable truth" rule — a generic map has no type to
generate from). `config.example.toml` documents each new field with its
default.
**Reuse check.** The config `Holder` overlay system
(`internal/infrastructure/configuration`) already handles safe saves; this
adds fields to existing structs, it does not add a second config-write path.
### Pending-restart and reconciliation
**Decision.** No new "pending restart" flag is persisted. `Inventory.List`
computes `StatePendingRestart` by comparing the config's `Enabled` value
against whether the family's registry reports that entry as
live — if they disagree, the entry is pending restart. This is simpler than
tracking a flag through a save-then-restart cycle and can never go stale,
because it's recomputed on every read.
**Call site.** `internal/domain/extensions/inventory.go`'s comparison logic.
### API and UI surface
**Decision.** New `api_extensions.go` alongside the existing `api_skills.go`
/`api_workflows.go` pattern, exposing `Inventory.List` and a save endpoint
that writes through the existing `UpdateConfig` seam (`api_config.go`) —
this document does not add a second config-write endpoint. New
`ui/src/extensions/` (colocated `.js`/`.css` per CLAUDE.md's frontend rule)
as an index/dashboard that **links to**, not replaces, the existing
`ui/src/skills/` and `ui/src/workflows/` detail views — Extensions centre is
where an operator sees everything and toggles enablement; the family-specific
pages remain where they inspect a family's own detail.
**Call site.** `internal/webui/api_extensions.go` (new, follows
`api_skills.go`'s shape), `ui/src/extensions/` (new).
## Call site inventory
| concern | file | change |
| ------------------------------------------------------------- | ------------------------------------------------------------------------------- | --------------------------------------------------- |
| Plugin metadata type | `internal/plugin/plugin.go` | none — already handles this |
| Family controllers (curator/health/image/workflow registries) | `internal/domain/curator/registry.go`, `internal/domain/health/health.go`, etc. | none — pattern already proven, reused not rewritten |
| Unified inventory | `internal/domain/extensions/inventory.go` | new |
| Composition wiring | `internal/app/archied/server.go` (near existing optional fields) | new |
| Config enablement fields | `internal/config/config.go` | new fields per family |
| Config docs | `config.example.toml` | new field documentation |
| API surface | `internal/webui/api_extensions.go` | new |
| Existing skills/workflows APIs | `internal/webui/api_skills.go`, `api_workflows.go` | none — linked from, not replaced |
| Config save path | `internal/webui/api_config.go` (`UpdateConfig`) | reused, not duplicated |
| UI | `ui/src/extensions/` | new |
| Existing UI detail views | `ui/src/skills/`, `ui/src/workflows/` | none — linked from Extensions centre |
## Execution: multi-agent team breakdown
| sub-feature | issue | implementer scope | suggested council lenses | why |
| ------------------------------------ | ---------------------- | ---------------------------------------------------------------- | ----------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| Unified inventory type + composition | file as child of `#56` | `internal/domain/extensions/inventory.go`, wiring in `server.go` | `lens-boundary`, `lens-deletionist` | boundary: aggregator must not duplicate family-owned state; deletionist: must not become a new domain that shadows existing registries |
| Config enablement fields | file as child of `#56` | `config.go` per-family `Enabled` fields, `config.example.toml` | `lens-contract` | config field is a wire contract other tooling (`docsgen`) generates from |
| API + UI surface | file as child of `#56` | `api_extensions.go`, `ui/src/extensions/` | `lens-maintainer` | new user-facing state machine (available/enabled/active/degraded/skipped/pending-restart) must be legible to an operator with no prior context |
## File and link the beads
- `#56` itself has no filed children yet — file the three rows above as
child issues linking to this doc's matching `##` heading.
- Each issue's acceptance criteria should restate this doc's per-family
`Enabled` default (`true` for existing config, no field at all for core
capabilities) so "non-disableable core" isn't re-litigated per bead.
- Add the suggested lenses to each issue.
-306
View File
@@ -1,306 +0,0 @@
# External agent harnesses
**Status:** Approved
**Authority:** `docs/architecture/agent-system.md` (agent execution as a data
boundary); settles the harness non-goal deferred by
`docs/prds/service-decomposition.md`.
**Compounds with:** `docs/prds/execution-tree-state-machine.md` (a harness
run is one `agent` StepExecution), `docs/prds/binding-secret-encryption.md`
(the at-rest envelope reused for harness credentials).
## Decision
A workflow stage can run on an external coding-agent CLI instead of the
built-in agent loop: Claude Code, Codex, Pi, OMP, GitHub Copilot CLI, or any
other CLI packaged as a Docker Sandbox Kit v3. Each authenticates with an API
key or the operator's subscription login, and can carry the operator's own
skills, plugins, subagents and instructions.
Two boundaries hold regardless of what the harness does:
- **The real credential never enters the container.** The container sees
sentinel values; archie's egress proxy substitutes the real credential on
outbound requests and performs OAuth refresh on the host.
- **Archie's workflow guarantees are enforced outside the harness.** Git,
protected paths, read-only stages, gates and budgets are checked by archie
around the process and against the worktree afterwards.
## Kits
A harness is packaged as a Kit v3 image: an OCI image whose
`vnd.docker.sandbox.kit.descriptor` manifest annotation declares what the
harness needs. Archie reads descriptors with the published
`github.com/docker/sandbox-kit-spec/v3/spec` package and does not maintain
its own descriptor format. Published Kits run unmodified.
Archie is a partial Kit runtime. It implements these capability types:
| Type | Archie behaviour |
| ------------------- | ----------------------------------------------------------------------------------------- |
| `credential@1` | Proxy-managed only, described below. |
| `network-policy@1` | Enforced by the egress proxy. |
| `volume@1` | A Docker volume keyed by WorkflowExecution, deleted with it. |
| `lifecycle@1` | Install and startup hooks run on container create. |
| `agent-sessions@1` | The headless `prompt` and `resume` invocations for the stage. |
| `agent-skills@1` | The operator's skills store (`skills_dir`), mounted read-only whatever the Kit asks. |
| `agent-context@1` | The workload's profile file beside the workspace, indexing each Kit's guidance. |
| `resources@1` | Container CPU and memory limits. |
Every other type fails closed: a required entry refuses the launch, an
optional one is skipped and recorded on the step. `credential@1` with
`passthrough: true` and any credential for a forge service are refused.
The operator's own setup (plugins, subagents, instructions, settings) is a
mixin Kit, published with the harness Kit as a Kit set: the set merges their
layers into one image. It is versioned image content, rewritten on every
create, never state a run can modify.
## Contract
A harness run is a second implementation of `agentexec.Runner`. It takes the
same `Request` and returns the same `Result`, so workflows, the daemon and
the State Store do not know which runner ran a stage.
`agent-sessions@1` supplies the invocation. Archie supplies, per CLI, an
output adapter that translates the CLI's JSON output stream into
`ToolCallReporter` calls, `Usage` and a session ID. A CLI with no adapter can
run stages with no capture tools, reporting no usage; its token budget falls
back to wall clock.
Workflow definition validation rejects, at load time, a stage whose needs the
selected harness cannot meet: capture tools without an adapter, or a gate
retry without a `resume` verb.
## Selection
A harness is an agent profile. `docs/prds/event-automation.md` defines a
profile as the execution environment a workflow selects; a harness profile
names one Kit pinned by digest, a workload Kit or a published Kit set, in
place of a container image. Archie runs that Kit's image and composes no Kits
itself; a bare mixin is refused. Everything else about profiles
holds: a workflow names its profile, a stage may name a different one, and a
profile holds no secrets.
`archie-agent` builds the stage's runner from the stage's profile: the
ai-sdk agent loop for an image profile, the harness runner for a Kit
profile. Image profiles, and every workflow already written against them,
are unchanged. A Kit profile named by no workflow is a validation error.
A stage naming a different profile than its workflow's is a separate run,
not a mid-container runner switch: a Kit task runs in one container
provisioned for one profile (Container layout), so a stage that needs a
different one is its own callee, started the way `workflow.call` already
starts one (`docs/prds/event-automation.md` "Workflows call workflows"),
with its own agent profile resolved off its own task row. This needs no
mechanism beyond `workflow.call` plus per-task profile resolution
(`daemon.pinTaskProfile`), both of which already treat every task's
profile independently of any caller's -- see
`TestWorkflowCallerConformance` (staterpc) for the callee's independent
`Workflow` field and `TestWorkflowCallGivesACalleeItsOwnProfile` (daemon)
for the Kit-vs-image runner selection that independence produces.
Profiles are org resources in the State Store, so a Kit profile belongs to
one org, is granted to its workspaces like any profile, and applies without
a restart.
## Organisations
`docs/prds/orgs-and-access.md` is the boundary; a harness adds nothing that
crosses it.
- A Kit profile, its credential bindings and its OAuth tokens belong to one
org. No record is shared between orgs.
- A harness run is a run like any other: it acts as the workflow's identity,
under the run credential issued at dispatch.
- The egress proxy injects a credential only when the run credential carries
the secret the binding names. A Kit that declares a service the identity is
not granted gets no credential: a required one refuses the launch, an
optional one is skipped.
- A Kit's network policy is what the Kit asks for; the identity's network
grants are what the org allows. The proxy enforces the intersection.
- Concurrency slots are counted per binding within its org.
## Credentials
A credential binding maps a Kit's `credential@1` `service` name to an org
secret, which the org grants to identities like any secret. The secret holds
one of:
- **API key:** a value in the org's secret store.
- **OAuth:** tokens captured by the setup terminal, stored in the State Store
under the at-rest envelope of `binding-secret-encryption.md` with its own
domain separator.
The egress proxy resolves the binding for each request against the run
credential. The container gets the Kit's sentinel in the named variable or
credential file. OAuth refresh happens at the proxy, which intercepts the
Kit's `tokenEndpoint`, so a refreshed token is written to the State Store and
never returned to the container.
Runs sharing an OAuth binding share its subscription's rate limit.
`max_concurrent` on the binding (default 1) caps its simultaneous runs. A
stage waiting for a slot is `pending`, not `running`.
## Setup terminal
The dashboard opens a terminal (xterm.js over a WebSocket to a PTY) into an
ephemeral container built from a Kit profile, on the same egress path. The
member runs the CLI's own login. The proxy captures the tokens at the token
endpoint into the org secret the binding names. The container is removed when
the terminal closes. No worktree is mounted into it.
Opening the terminal is the `update` action on the secret, decided by the
Authorizer like any other; the shipped roles give it to org owners and
admins. It is the only interactive path into a harness container.
## Egress
Only Kit profiles run on the egress path. An image profile keeps the network
access its identity is granted, because workflows such as a network
investigator need raw DNS, ICMP and arbitrary TCP that no HTTP proxy
carries.
- **Sandbox network.** Each Kit run gets its own internal Docker bridge on
which the host holds no address. Host services, including those listening
on every interface, are unreachable from it by any address.
- **Relay.** One relay container, `archie-agent relay`, sits on the sandbox
networks under a fixed alias and on the host-reachable network. It
forwards three fixed ports, to the proxy, NATS and the State Store, and can
reach nothing else. It holds no secrets.
- **Proxy.** The proxy runs inside `archied`, listening on the host gateway
of the host-reachable network. It terminates TLS with a per-daemon CA
installed into the container at create, identifies the container by a
per-run proxy token, and applies that run's network policy and credential
inject rules. Upstream dials refuse loopback, and refuse internal addresses
unless the policy names the exact IP, so an allowed name cannot resolve
back into the host.
## Container layout
A Kit task runs in one container, from the Kit composition's image, on the
task's sandbox network. The worker and every harness invocation share it;
they are separated by user, not by container, so a run's cost scales with
the run and not with how many agents it fans out to.
- **Worker.** Archie mounts its own `archie-agent` binary read-only and runs
it as the container's entrypoint, as root. It holds the task's NATS and
State Store credentials in its own environment and in root-only files,
runs the workflow, and serves `archie-agent mcp`. The Kit image's
entrypoint is not PID 1.
- **Harness.** Every invocation runs as the Kit's user (the image's `User`,
default uid 1000) with an explicit environment: the Kit's variables, the
proxy environment and the credential sentinels, and nothing inherited from
the worker. That user cannot read the worker's environment or files, or
trace it. Sibling invocations in one run share the user and the worktree.
- **Hooks.** `lifecycle@1` install and startup hooks run as the user each
declares, before the worker accepts work.
- **Mounts.** The task worktree at the Kit's workspace directory, owned by the
Kit's user, and the read-only skills store. Nothing else from the host.
- **Network.** The relay forwards three fixed ports on the sandbox network:
the egress proxy, NATS and the State Store. The worker reaches NATS and the
State Store with its credentials; a harness can open those ports but holds
no credential either accepts.
- **Volumes.** `volume@1` paths persist for the life of the
WorkflowExecution, which covers session resume across gate iterations and
retries. They are not shared between executions.
## Archie tools inside the harness
Capture tools, which are how a stage returns structured results, are served
by `archie-agent mcp`, a stdio MCP server registered through the Kit's MCP
configuration or the adapter's flags. It serves the stage's `CaptureTools`
and the central tools the agent profile's `AllowTools` permits, never the
`workspace` toolset. The runner's `ToolLimits` bound its results; the
harness's own built-in tools are outside archie's limits.
## Enforcement around the harness
| Property | Enforcement |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Model never runs git | No forge credential can be bound. Archie records `HEAD` and every ref before the run; any change fails the step (`failed`, policy class). The workflow commits the stage's changes. |
| Protected paths | A diff touching a `Protection` path fails the step. |
| Read-only stage | Any worktree diff fails the step. |
| Gate | Archie runs the stage's gate after the harness exits. On failure it resumes the session with the gate output, up to the stage's iteration budget. |
| Budget | Archie kills the process on wall-clock timeout, or when streamed usage passes the token budget. |
| Cancellation | Cancelling the step kills the process group, then the container. |
| Egress | Only the proxy is reachable; the Kit's network policy decides the rest. |
Harness settings that deny git or protected paths are added where the CLI
supports them, to save wasted turns. They are never the enforcement.
## Execution tree
A harness run is one `agent` StepExecution. Subagents the harness spawns
internally are not recorded as children. Their usage is included in the
step's `tokens_used` when the adapter reports it.
## Agents never hold a harness
An Agent reaches a harness only by invoking a Workflow whose stage names it.
No Agent tool, chat tool or capability exposes a harness, its setup terminal
or its credential. The stage boundary is what carries the container, the git
and path checks, the gate and the budget; a harness outside a stage has none
of them.
## Out of scope
- Chat through a harness. The gateway chat loop stays on the built-in
runtime.
- `network-policy@2` HTTP method and path rules; a Kit requiring it is
refused.
- Recording the harness's internal subagents as StepExecutions.
- Cost in currency.
- Choosing a harness automatically per task.
## Plan
1. Descriptor resolution with the Kit spec package; capability support
table and fail-closed refusal.
2. Egress proxy: internal network, per-daemon CA, per-container token,
`network-policy@1`.
3. `credential@1`: API-key bindings, sentinel rendering, inject rules.
4. Harness `Runner`: container create with worktree, volumes, lifecycle
hooks and the mounted `archie-agent`; `agent-sessions@1` invocation;
worktree checks for git, protected paths and read-only; budget and
cancellation.
5. Claude Code output adapter; `archie-agent mcp`; gate-and-resume loop.
6. Kit profiles, runner selection from the stage's profile, and definition
validation.
7. OAuth bindings as org secrets: token-endpoint interception, encrypted
storage, per-binding concurrency; dashboard setup terminal.
8. Output adapters for Codex, Pi, OMP and GitHub Copilot CLI.
## Verification
- The same workflow definition completes on `builtin` and on the Claude Code
Kit with the same `Result` shape and captures.
- After `/login` in the setup terminal, the container's credential file holds
only sentinels, the State Store holds the encrypted token, and a task run
authenticates.
- A real API key or OAuth token never appears in the container environment,
filesystem, worktree, task log or event stream.
- A request to a host outside the Kit's runtime allow list fails, including a
direct connection that bypasses the proxy settings.
- A harness instructed to `git commit` fails its step, and the task branch is
unchanged.
- A harness edit to a protected test file fails the step in a TDD fix stage.
- A read-only feasibility stage that writes a file fails.
- A file a run writes into a Kit-managed path such as the CLI's settings file
is gone on the next execution.
- A Kit requiring an unsupported capability is refused at launch with the
capability named.
- A stage with a failing gate resumes the same session with the gate output,
then succeeds or exhausts its iterations.
- Two tasks sharing an OAuth binding with `max_concurrent = 1` run one at a
time; the second waits as `pending`.
- Stopping a run kills the harness process and removes the container.
- A harness invocation cannot read the worker's NATS or State Store
credential from its environment, its files or `/proc`.
- A run fanning out to many agent invocations uses one container.
- A Kit profile in org A cannot be selected, and its binding cannot be
resolved, by a workflow in org B.
- A harness run whose identity is not granted a Kit's required credential is
refused at launch; the proxy never injects a secret outside the run
credential.
- The firewall investigation example runs unchanged on an image profile with
direct network access.
-166
View File
@@ -1,166 +0,0 @@
# Identity for users, agents and external agents — decision
**Status:** Draft
**Date:** 2026-09-22
**Authority:** `docs/architecture/organisation.md` for placement;
`docs/architecture/migration-decisions.md` §3 for the attribution semantics this
document implements; `docs/prds/agent2agent-protocol.md` for the A2A surface that
consumes it.
## Decision
One identity record covers every actor archie has: users, agents, external agents,
service accounts and the system. Authentication is delegated to the estate's OIDC
provider, and attribution stays archie's.
Authentication and authorisation are OSS archie integrates; a design that
hand-rolls either fails this document.
## The provider
**Authelia is the only identity provider**, because the estate already runs it in
front of the dashboard and it issues credentials for both kinds of caller: humans
use the authorisation code flow, and machines use the `client_credentials` grant,
which yields a token whose subject is the client's own identifier.
**Each agent is its own provider client.** A shared client would make two agents
indistinguishable in the audit trail and revocable only together, which is the
property attribution needs and the reason per-client registration is a
requirement.
**A person's client and an agent's client are registered separately**, because the
two token shapes differ and a shared registration would collapse the distinction
the attribution rests on. A person's token names them in `sub`. A machine's token
carries no `sub` at all and names its client instead, so a machine identity is keyed
on its client registration and exists one per client. A token asserting neither is
refused.
**A person's token requests the audience at the authorisation endpoint**, not only
at the token endpoint. A provider that otherwise returns the audience empty
produces a valid token archie must refuse, and that refusal looks like a signing
fault rather than a missing request parameter.
**SPIFFE/SPIRE is not adopted.** It is adopted and maintained, and its attestation
is strictly stronger than a secret: a workload proves what it is rather than what
it holds. It is rejected here on operational fit, not on quality: it adds a
control plane archie does not have, and the property it buys — identity attested
from the platform rather than from a presented secret — answers a threat archie
does not face, because archie's agents run as containers the operator launches and
already receive their credentials from the daemon that owns them. It is the right
answer when agents run on infrastructure the operator does not control.
## What archie owns
- **The identity record.** `internal/domain/identity` survives as archie's own
record of an actor and is not replaced by the provider's directory, because the
record carries what the directory does not: the lifecycle, the bindings and the
attribution below.
- **The lifecycle.** Active, suspended and retired, with rename, suspend,
reactivate and retire, remain archie's. Suspending an identity must stop it
acting whether or not the provider still authenticates it.
- **The subject binding.** An identity that proves itself is bound to the provider
subject that asserts it. This is the same bridge `identity_aliases` already
provides from a legacy name to an identity, so the second binding is the same
mechanism rather than a new one.
- **Attribution.** Who acted, and under whose authority.
- **The audit trail of identity changes**, which already records an actor, a source
and a request identifier for every mutation.
## What archie never owns
A credential, a password, a session, a token, a signing key, a second-factor
enrolment, or a permission rule.
## How an agent proves who it is
**An agent authenticates by presenting a token the provider issued to its own
client**, and archie validates it against the provider's published signing keys and
takes its subject as the acting identity. The agent holds a client secret; archie
holds only the public keys, so a compromised archie cannot mint an identity.
**A WebMCP tool call is not a proof of agent identity and cannot be made one.** A
page can invoke its own tools, so an agent's call and a page script's call arrive
at archie identically. No field, header or convention distinguishes them, because
the difference does not exist on the wire.
**A WebMCP tool call is therefore attributed to the identity the request
presented, with its source recorded as a hint.** It may record that the request
came from the dashboard; it never records that an agent acted, and it never
records that a human approved. A tool call that a page script can forge must not
be the thing an audit trail rests on.
**Agent-initiated action therefore arrives on a surface that carries a credential**
— the A2A surface, or an authenticated agent call — because that is the only place
an agent's identity is verifiable. An approval an agent makes is recorded as an
agent's action.
## The two attributions
Every task action records two identities, and `taskactions` gains both:
- **The acting identity**: the identity that performed the action, derived from
the credential the request presented and never from a string the request
supplied.
- **The authorising principal**: the identity whose authority the action used.
**The event kind describes the actor.** An action performed by an agent is
recorded as an agent's action even when a human's standing approval permitted it,
so `KindHumanApproved` is recorded only when the acting identity is a human. An
agent acting under a standing approval records itself as the actor and the human
as the authorising principal.
**An action with no authorising principal is recorded as unattributed rather than
attributed to the actor's own authority.** An agent's own decision and an agent
executing a human's delegation are different facts, and a record that collapsed
them would answer the audit question "approved by whom" with the wrong identity.
**The review gate's approver is the authorising principal of the approval on that
task's action record.** A task parked for a person names that person, not the
surface they used.
## External agents
**External agents are first-class, not a special case.** A peer is an identity of
kind `service_account`, bound to its own provider client, with the same lifecycle
as any other identity.
The cost is a provider client per peer, a subject binding, and a client secret
whose rotation is the peer's responsibility — and retiring a peer is two
operations rather than one, because its record and its provider client are retired
separately.
**A peer's identity is attributed like any other.** The acting identity is the
peer; the authorising principal is the identity that delegated to it, so an
external agent acting for a user records both.
## Authorisation is deferred
**No authorisation engine is built, deployed or configured.** The credential's
scopes are the only permission input, and they are verified by the same provider
that issued them, so the interim authorisation is OSS archie does not maintain.
**Two things are not built now**: a policy language, and a decision point that
answers per-skill or per-task questions beyond a scope.
**When a caller must be limited to a subset of what a scope permits** — A2A's
per-skill model, where a peer may invoke some skills and not others — the decision
point is added behind a single archie interface that takes a subject, an action and
a resource. The engine behind it is an in-process library or a policy service, and
the choice waits for that requirement rather than being made now.
## Verification
- An agent obtains a token from the provider with its own client credentials and
acts; its identity is recorded as the acting identity.
- A call with no credential is refused, and a call with an expired or
wrongly-signed token is refused.
- A token issued to one agent is not accepted as another agent's identity.
- A suspended identity cannot act, with a valid provider token.
- A WebMCP tool call records the presented identity and its source, and never
records an agent as the actor or a human as the approver.
- An agent's approval records the agent as the acting identity and the human whose
authority it used as the authorising principal, and does not record the human as
the actor.
- An approval with no authorising principal is recorded as unattributed.
- No password, session, token, signing key or permission rule exists in archie's
storage.
-490
View File
@@ -1,490 +0,0 @@
# Image capability contract and configuration
**Status:** Approved
Epic: archie-core-1786748942120-1-6636e629 / GitHub #496 ("Image generation
capability: hosted API baseline plus local GPU workflows").
The contract and configuration (#497) shipped first and is settled — see
"Package: `internal/domain/image`" below. This document now covers the full
feature set: hosted provider (#498), local GPU provider (#499), `/image`
routing and clarification (#500), delivery through channels and web (#501).
Documentation (#502) and the cross-cutting test matrix (#503) are execution
work against the design below, not open design questions, so they are not
given their own sections — each preceding section states its own test
obligations inline.
## Problem
Archie needs a provider-neutral boundary for image generation/editing so a
hosted API (gpt-image-2-class) and a future local GPU backend can both
implement it without either one leaking into the domain contract. Nothing
in the repo defines this (`grep -ri image` over `internal/domain` and
`internal/config` returns nothing image-specific).
## Design
Follows the plugin engine family shape already established by
`internal/domain/curator` and `internal/domain/memory`
(`docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict`): a
typed contract with real domain operations,
an owning `Registry` (register/get/names, no start/stop lifecycle — see
below), and narrow host access via a `Registrar`.
### Package: `internal/domain/image`
**Why no `Lifecycle` (`Start/Health/Stop`)**: curator and memory engines are
long-running — they hold a background cadence or a persistent connection
worth health-checking. An image provider is call-scoped: it either serves a
`Generate`/`Edit` request or it does not. Health here means "is this
provider usable at call time", which is exactly what `Generate`/`Edit`
returning a typed `ErrUnavailable` already communicates — a separate
`Health()` poll would just duplicate that. `Registry` still owns
registration and lookup, so provider selection is testable with fakes per
the acceptance criteria, but there is no `Start`/`Stop` to orchestrate.
```go
// Capability declares what one provider supports, discoverable before a
// request is built so a caller can reject an unsupported combination (e.g.
// edit-with-mask on a generate-only provider) instead of sending it and
// parsing a provider-specific error back out.
type Capability struct {
Generate bool
Edit bool // edit requires at least one input image
Mask bool // edit supports a mask restricting the edited region
MaxInputs int // 0 = Edit unsupported
Sizes []string // provider-declared output sizes, e.g. "1024x1024"
}
// Provider is the typed contract every image backend implements — hosted
// (gpt-image-2-class) or local (GPU recipe). No Lifecycle: a provider is
// call-scoped, not long-running (see design doc rationale).
type Provider interface {
Name() string
// Class distinguishes hosted (spends money/quota per call) from local
// (spends host GPU/time). Selection logic and config validation key off
// this, never off Name, so a new provider cannot silently slip through
// the hosted-cost gate under an unrecognized name.
Class() ProviderClass
Capability() Capability
Generate(ctx context.Context, req GenerateRequest) (Result, error)
Edit(ctx context.Context, req EditRequest) (Result, error)
}
type ProviderClass string
const (
ClassHosted ProviderClass = "hosted"
ClassLocal ProviderClass = "local"
)
```
Request/result types (provider-neutral, no OpenAI types):
```go
type GenerateRequest struct {
Prompt string
Size string // "" = provider default
N int // number of images; 0 = 1
Options map[string]string // provider-specific overflow (e.g. "quality"),
// deliberately untyped so the contract does not
// grow a field per provider
}
type EditRequest struct {
Prompt string
Inputs []ImageData // 1..Capability.MaxInputs
Mask *ImageData // nil unless Capability.Mask
Size string
N int
Options map[string]string
}
// ImageData carries image bytes in-process, never a path or URL: the
// domain layer must not assume a filesystem or a fetchable location (mirrors
// why curator's Registrar never receives *daemon.Daemon — no ambient host
// access smuggled in through a "just a string" field).
type ImageData struct {
Bytes []byte
MIMEType string
}
type Result struct {
Images []ImageData
Provider string
Model string
CreatedAt time.Time
}
```
### Error taxonomy
```go
var (
ErrUnavailable = errors.New("image provider unavailable") // missing credential, backend down
ErrUnsupported = errors.New("image capability unsupported by provider") // e.g. Edit on generate-only
ErrInputTooLarge = errors.New("image input exceeds configured limit")
ErrTimeout = errors.New("image request timed out")
ErrCanceled = errors.New("image request canceled")
)
```
Every provider wraps these with `fmt.Errorf("%w: %s", ErrX, detail)` so
callers can `errors.Is` regardless of backend. `ErrUnavailable` is the
explicit instruction from the epic: "a missing credential or unavailable
backend must make the capability unavailable with a useful user-facing
error, not prevent Archie from starting or break text chat" — Register
never rejects the daemon's boot, only marks that one provider absent from
`Registry.Names()`.
### Registry
```go
type Registry struct { /* map[string]Provider, mutex, sorted Names() */ }
func NewRegistry() *Registry
func (r *Registry) Register(p Provider) error // ErrDuplicate on name clash
func (r *Registry) Get(name string) (Provider, bool)
func (r *Registry) Names() []string
func (r *Registry) ByClass(class ProviderClass) []string
```
No `Registrar`/host-injection type: unlike curator (needs `LLM`, `Skills`,
`Conversations`) and memory (needs `Clock`, `Events`), an image provider's
dependencies (HTTP client, API key, local backend handle) are entirely its
own construction-time concern in `internal/infrastructure/image/*`, not
daemon services it needs injected. Introducing an empty `Registrar` now
would be exactly the "field nobody sets" pattern to avoid.
### Configuration
Follows `MinimaxConfig`'s hosted-cost-guard convention exactly: absent
config or absent explicit `enabled = true` per provider means that
provider does not register, not "registers but errors on first call".
```go
// ImageConfig configures the image generation capability.
type ImageConfig struct {
// Default selects which registered provider name /image uses when the
// request/session has not already picked one. Empty means /image must
// always ask (the epic's stated default UX) — an empty Default is valid
// and is not a misconfiguration.
Default string `toml:"default"`
Hosted map[string]ImageHostedProvider `toml:"hosted"` // keyed by provider name
Local map[string]ImageLocalProvider `toml:"local"` // keyed by recipe name
}
// ImageHostedProvider configures one hosted (paid) provider. Mirrors
// MinimaxConfig: Enabled defaults false, spending real credits requires an
// explicit opt-in, never an inferred one from the presence of a key alone.
type ImageHostedProvider struct {
Enabled bool `toml:"enabled"`
Class string `toml:"class"` // "openai" today; provider-neutral field name
APIKeyEnv string `toml:"api_key_env"`
APIKey secret.SecretRef `toml:"api_key" json:"-"`
BaseURL string `toml:"base_url"`
}
// ImageLocalProvider configures one local GPU recipe. Enabled defaults
// false too: a local backend can still saturate the host GPU/CPU, which is
// its own kind of unwanted cost, so it gets the same explicit gate as a
// hosted provider rather than an on-by-default WebFetch-style treatment.
type ImageLocalProvider struct {
Enabled bool `toml:"enabled"`
Backend string `toml:"backend"` // recipe identifier, defined by the local-backend bead
}
```
Validation (`internal/infrastructure/configuration/validate.go`, alongside
`validateMemory`):
- `Default`, if set, must name a provider present (enabled) in `Hosted` or
`Local` — rejects a config that silently falls back to "always ask" when
the operator thought they'd pinned one.
- A `Hosted` entry with `Enabled = true` must have `Class` non-empty and
either `APIKeyEnv` or a resolvable `APIKey` — the same shape check
`Provider` (chat) already gets, not a new invention.
- No cross-field surprise: an _absent_ `[image]` section is valid and
produces zero registered providers, matching the epic's non-goal
("silently selecting a paid hosted provider" must never happen by
omission either).
### Capability discovery
`Registry.Names()` / `ByClass()` plus `Provider.Capability()` give a caller
(the future `/image` routing bead) everything needed to ask "what can I
offer this user" without a type switch on provider identity — this is the
whole point of the contract being provider-neutral.
### Timeouts, size limits, cancellation
- Every `Provider.Generate`/`Edit` call takes the caller's `ctx`; a
provider that ignores cancellation is a provider bug, not a contract gap
— mirrors every other Lifecycle-less call in the codebase (chat's
`runtime.Chat`).
- `ImageData` size limits are enforced by the _caller_ (the future routing
bead) before constructing a request, using a configured max — not by this
contract, which has no config surface for "current caller's limit". This
package only defines `ErrInputTooLarge` so a provider that discovers an
oversized input itself (rather than trusting the caller) has a typed way
to say so.
## Testing
- `internal/domain/image/{contract,registry}_test.go` mirror memory's test
suite shape: registration (duplicate, nil provider), `Names`/`ByClass`
filtering, `Get` miss, table-driven `Capability` checks via a fake
provider.
- `internal/infrastructure/configuration/validate_test.go` gains cases for
`ImageConfig`: absent section, valid hosted+local, missing `Class`,
missing credential, `Default` naming an unregistered/disabled provider.
- No provider implementation exists yet, so no live-call tests — those
belong to the hosted/local provider beads.
## Hosted provider (#498)
`github.com/samcharles93/ai-sdk` (already a repo dependency) has its own
provider-agnostic image facility: `image.Provider` (`Name`,
`GenerateImage(ctx, GenerateImageRequest) (GenerateImageResponse, error)`),
`image.Client`, and `registry.Registry.RegisterImage`/`.Image(name)` — the
same shape chat model registration already uses. Three backends implement it
(azure, togetherai, xai); OpenAI does not.
`internal/infrastructure/image.<name>Provider` wraps an `ai-sdk/image.Provider`
behind this package's `Provider` interface, the same way `curatorLLMRunner`
(`internal/app/archied/main.go`) adapts `runtime.Runtime` for chat rather
than the domain layer talking to ai-sdk directly.
**Decision: generation goes through ai-sdk, edit does not.** ai-sdk's
`image.GenerateImageRequest` is text-to-image only — no input-image or mask
fields — so there is nothing to adapt `EditRequest`/`Capability.Edit` onto.
Blocking the entire hosted provider on an upstream ai-sdk change is not
this epic's call to make on someone else's project's timeline. Instead:
- `Generate` wraps `ai-sdk/image.Client.GenerateImage` against whichever
backend `ImageHostedProvider.Class` names (azure/togetherai/xai).
- `Edit` is a direct HTTP client hitting the OpenAI-compatible
`/images/edits` multipart endpoint, built the same way `minimax.Client`
(`internal/tools/minimax/minimax.go`) is a direct client for an API
ai-sdk doesn't cover — not a second abstraction layer, one `http.Client`
call with request/response mapping into this contract's `EditRequest`/
`Result`.
- A provider that only wraps ai-sdk (no edit client configured) declares
`Capability{Generate: true, Edit: false}` truthfully rather than
returning `ErrUnsupported` at call time for something `Capability`
already said it couldn't do.
- If ai-sdk gains edit support upstream later, the direct client is deleted
and `Edit` moves onto it — recorded here so that's a known, not a
surprise, follow-up.
**Provider error mapping** (every ai-sdk/HTTP error translated at the
adapter boundary, never leaked as-is):
| ai-sdk / HTTP condition | contract error |
| ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `image.ErrNoProvider`, `image.ErrAuthFailed`, missing/invalid credential, backend unreachable | `ErrUnavailable` |
| `image.ErrEditNotSupported`, request needs a `Capability` the provider didn't declare | `ErrUnsupported` |
| input image over configured byte limit (checked before the call, per "Timeouts, size limits, cancellation" above) | `ErrInputTooLarge` |
| `ctx.Err() == context.DeadlineExceeded` | `ErrTimeout` |
| `ctx.Err() == context.Canceled` | `ErrCanceled` |
| `image.ErrRateLimited`, `image.ErrContentFiltered`, any other 4xx/5xx | wrapped verbatim under `ErrUnavailable` with the provider's own message as detail — a rate limit or content filter is "unavailable for this request", not a new sentinel the caller needs to branch on differently |
**Testing**: `httptest.Server` fixtures for the edit client (request
multipart shape, response decoding, 4xx/5xx mapping); a fake `ai-sdk/image.Provider`
for the generate path so the adapter's translation is tested without a live
backend, matching #498's "no live API key needed for tests" criterion.
## Local GPU provider (#499)
**Decision: ComfyUI is the baseline recipe**, not a name this doc picked
arbitrarily — it is the de facto scriptable HTTP API for Stable-Diffusion-class
local generation, already shaped like the async submit/poll pattern
`minimax.Client.GenerateAndWait` established in this codebase (submit a
workflow, poll `/history/{id}` until the output node has files, download).
No other local backend is referenced anywhere in this repo or its docs, so
this decision has no competing prior art to reconcile — it is a fresh
choice, recorded here so the implementing bead does not re-litigate it.
```go
// internal/infrastructure/image/comfyui
type Config struct {
Enabled bool
BaseURL string // e.g. http://127.0.0.1:8188
Workflow string // path to a saved ComfyUI workflow JSON template
// (prompt/size/seed substituted at call time)
Timeout time.Duration
PollInterval time.Duration
MaxWait time.Duration
}
```
- `Generate`/`Edit` load `Workflow`, substitute the templated fields (prompt,
size, seed, and for `Edit` the input image as a base64 node input — ComfyUI
supports img2img/inpaint workflows natively, so `Capability.Edit`/`Mask`
can both be true for a correctly authored workflow, unlike the hosted
provider), POST to `/prompt`, then poll `/history/{prompt_id}` the same
shape MiniMax's poll loop already proves out in this codebase.
- `Capability.Sizes` is empty (ComfyUI workflows declare their own
resolution in the template, not a fixed enum) — the contract already
allows an empty `Sizes` to mean "provider does not constrain size".
- Backend-down (`BaseURL` unreachable) and workflow-missing are both
`ErrUnavailable`, not a startup failure — same "degrade the capability,
never break text chat" rule the contract already states.
- Per #499's own acceptance criteria, at least one recipe must be exercised
end-to-end on real hardware or a reproducible harness, and no model
weights are ever committed or fetched by Archie itself — the operator
points `Workflow`/`BaseURL` at their own running ComfyUI instance and
already-downloaded checkpoint, exactly like `[providers.ollama]` points at
an already-running Ollama rather than Archie managing the model.
**Testing**: a fake HTTP server standing in for ComfyUI's `/prompt` and
`/history` endpoints (submit, poll, malformed history, timeout, job
not-found); a real-hardware smoke test documented as a manual `task`
target per #503, not part of `task check` — the same reasoning `task vuln`
and `task deadcode` are excluded from the gate.
## `/image` routing and clarification flow (#500)
**Call site: `internal/gateway/gateway.go`'s `Router`**, following the
`/model` shape exactly — `/model`, `/spawn`, `/approve` etc. are already
"commands handled without the LLM" (`Router.handleModel`, dispatched via
`isLocalCommand`/`parseCmd` against `messaging.LocalCommandSpecs()`).
`/image` is a new entry in `internal/domain/messaging/commands.go`'s
`localCommandSpecs`, and a new `Router.handleImage(ctx, arg)` beside
`handleModel`, gated on a new `Router.Images *image.Registry` field (nil =
"/image not configured", the same pattern `Models`/`Tasks`/`Controller`
already use — not a new gating convention).
**Decision: mechanism selection is per-request, not session-persisted.**
The epic allows "a remembered preference only where existing session/config
conventions support it" — and checking `Router`'s actual fields
(`ModelPersist`, `Identity`, the rest) shows there is no generic per-session
key/value store the neutral command path can lean on; `/model`'s own
`--session`/`--global` scoping lives entirely in
`internal/channels/telegram/model.go`, a Telegram-specific enrichment, not
something `Router` provides generically. Inventing a new generic
session-preference store just for `/image` would be exactly the kind of
scaffolding CLAUDE.md's Architectural Simplicity rule warns against for one
caller. So: every `/image` invocation with no explicit mechanism produces
the clarification prompt; an explicit `--hosted`/`--local` flag (mirroring
`parseModelRest`'s `--provider` flag shape) skips it for that one call.
Revisit if a second command wants session-scoped preference too — that's
the point at which shared infra earns its cost.
**Flow**, matching `handleModel`'s reply-string shape (no separate state
machine object, since the whole exchange is "ask once, use the answer
inline in the next message" — the model-selector's own worked example):
1. `/image <prompt>` with no `--hosted`/`--local` → reply lists the
registered classes (from `Registry.ByClass`) and asks the user to repeat
the command with `--hosted` or `--local`. No provider is called.
2. `/image --hosted <prompt>` or `--local` → resolves to
`Registry.ByClass(class)`, picks `ImageConfig.Default` if it names a
provider of that class, else the sole registered provider of that class,
else (more than one, no default) asks which named provider.
3. Edit requests (`/image --edit <prompt>` with an attached image on the
inbound message) validate against `Capability.Edit`/`MaxInputs`/`Mask`
before calling — an edit request to a generate-only provider is a
clarification reply ("this provider doesn't support editing"), not a
provider call that returns `ErrUnsupported`.
4. A successful call returns a `Result`; delivery is the next section's
concern, not this one's — `handleImage` returns the same
`(string, error)` shape `handleModel` does for the text portion, and a
separate mechanism (below) carries the actual image bytes.
**Testing**: channel-neutral state-machine tests for `handleImage` against
a fake `*image.Registry` (mirrors `#500`'s own acceptance criterion); Telegram
adapter tests only for wiring, not for re-testing the state machine.
## Delivery through channels and web (#501)
This is the smallest section because most of the delivery path **already
exists and is already proven** — by `generate_video`
(`internal/tools/minimax`), which ships. Do not rebuild it.
The existing pipeline: a result carrying media returns
`tools.MultimodalResult{IsMultimodal: true, URLs: []tools.MediaRef{{Type: "image", ...}}}`
→ `multimodalMediaRefs` (`internal/app/archied/telegram_setup.go`) decodes
it → `TurnStream.Media(gateway.MediaEvent)` → each channel's own
`Media`/`MediaAttachment` handling. `MediaRef.Type` already documents
`"image"` as a valid value alongside `"video"`; nothing in the pipeline is
video-specific.
**Per-channel state, checked directly rather than assumed:**
| channel | image delivery | evidence |
| ----------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Telegram | **already works** | `internal/channels/telegram/media.go`'s `telegramMediaSender.dispatch` already branches on `att.Type` and calls `bot.SendPhoto` for `"image"` (`SendVideo` for `"video"` is the same function) |
| Dashboard (webui) | **tracked gap, not new** | `internal/webui/api_chat.go`'s `chatStreamSink.Media` has no inline rendering path yet and degrades to a link/error string — already tracked as archie-core-1786748942243-6-f109697e. This epic does not need to fix it, but #501's acceptance criterion ("unsupported paths report a clear limitation") is already met by the existing degrade-to-text behaviour; closing the dashboard gap is that bead's job, not this one's |
| Email | **no attachment sender exists** | `grep MediaAttachment internal/channels/email` returns nothing. Out of scope for this epic per #496's non-goals (no channel-abstraction rework) — email delivery of a generated image degrades the same way the dashboard does which is acceptable under #501's "or unsupported paths report a clear limitation" clause |
| Webhook | not applicable | webhook is an inbound intake channel (`internal/channels/webhook`), not an outbound chat reply target — no `/image` command can originate there in the first place |
**The only new work `internal/tools/minimax` didn't already need**: the
autonomous-tool call site. `/image` (previous section) calls a provider
directly and does not go through the model's tool-calling loop at all.
Separately, exposing `generate_image`/`edit_image` as an ordinary tool
(so an agent task can generate a diagram or illustration mid-task, not only
a human typing `/image`) is a thin wrapper — `internal/tools/image/tool.go`,
same shape as `internal/tools/minimax/tool.go`, calling
`image.Registry.Get(name).Generate/Edit` and returning the identical
`MultimodalResult` shape. Wired in `bootstrap.go` next to
`registerMinimaxTool`, gated the same way (registered only when a provider
resolved a working credential/backend, never advertised broken). This
reuses the entire delivery pipeline above with zero new plumbing — the tool
call site is what's new, not the delivery.
**Testing**: `multimodalMediaRefs` already has coverage for the shape;
add a table case for `Type: "image"` if one doesn't already exist. The tool
wrapper gets the same fake-provider test shape as the routing flow above.
No new delivery-path tests are needed — that pipeline's tests belong to
whichever change originally proved it out.
## Call site inventory
Every file a full implementation touches, so no bead re-derives this by
grep:
| concern | file | change |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------- |
| domain contract | `internal/domain/image/{contract,registry}.go` | done (#497) |
| config schema + validation | `internal/infrastructure/configuration/{types,validate}.go` | done (#497); extended here only if ComfyUI's `Workflow` field needs a new validation rule (path exists, non-empty when `Local.Enabled`) |
| hosted provider | `internal/infrastructure/image/openai/*.go` (or per `Class`) | new (#498) |
| local provider | `internal/infrastructure/image/comfyui/*.go` | new (#499) |
| `/image` command spec | `internal/domain/messaging/commands.go` | new entry in `localCommandSpecs` |
| `/image` routing | `internal/gateway/gateway.go` (`Router.Images`, `handleImage`) | new (#500) |
| autonomous tool | `internal/tools/image/tool.go` | new (#501) |
| tool registration | `internal/app/archied/bootstrap.go` (`registerImageTool`, beside `registerMinimaxTool`) | new (#501) |
| `Registry` wiring | `internal/app/archied/bootstrap.go` (construct `image.Registry`, register configured providers, hand to `Router.Images`) | new — this is the "nothing to wire until a real provider exists" step the original contract doc deferred |
| Telegram delivery | `internal/channels/telegram/media.go` | none — already handles `"image"` |
| Dashboard delivery | `internal/webui/api_chat.go` | none in this epic — tracked separately (archie-core-1786748942243-6-f109697e) |
| docs | `docs/` user-facing guide (#502) | new, against this design |
## Execution: multi-agent team breakdown
Each row is independently implementable from its own section above plus the
call-site inventory — an implementer does not need this whole document
re-explained, only its row. Lenses are picked from
`.claude/workflows/council.js` (`boundary`, `contract`, `deletionist`,
`operator`, `maintainer`) by what each slice actually risks getting wrong,
not all five by default.
| sub-feature | issue | implementer scope (call-site rows) | suggested lenses | why |
| -------------------------- | ----- | ------------------------------------------------------------------------------------------------------- | ----------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Hosted provider | #498 | `internal/infrastructure/image/openai/*.go` (generate via ai-sdk, edit via direct HTTP client) | `lens-contract`, `lens-operator` | contract: the error-mapping table must actually produce the sentinels it claims, not leak ai-sdk/HTTP errors raw; operator: a live paid API's rate-limit/timeout/auth-failure paths are exactly the 3am-unattended-host case this lens exists for |
| Local GPU provider | #499 | `internal/infrastructure/image/comfyui/*.go` (submit/poll against ComfyUI) | `lens-operator`, `lens-deletionist` | operator: backend-down, workflow-missing, and stuck-job failure modes on a host the operator's GPU actually runs; deletionist: a second, unevidenced "recipe" added later without real-hardware proof is exactly the speculative scaffolding this lens rejects |
| `/image` routing | #500 | `internal/domain/messaging/commands.go`, `internal/gateway/gateway.go` (`Router.Images`, `handleImage`) | `lens-boundary`, `lens-maintainer` | boundary: a new `Router` field and its dependency on `image.Registry` must respect the same layering `Models`/`Tasks`/`Controller` already do; maintainer: this is the first local command with an explicit ask-once clarification exchange, not a single-shot reply — legibility for the next person who adds a command matters here |
| Delivery + autonomous tool | #501 | `internal/tools/image/tool.go`, `internal/app/archied/bootstrap.go` (`registerImageTool`) | `lens-deletionist`, `lens-contract` | deletionist: the whole point of this section is "reuse `generate_video`'s pipeline, do not rebuild it" — this lens is the check that the implementation actually did that; contract: the new tool's `MultimodalResult`/`MediaRef{Type: "image"}` output must match the shape `multimodalMediaRefs` already decodes, not a near-miss |
Run `/council --lenses <picked>` once a row's implementation is gate-clean
(`task check` passing), before opening its PR — same timing as any other
open-decision residue at the end of a session, not a standing per-commit
gate.
## File and link the beads
`#498`–`#501` already exist (bd `archie-core-1786748942169-3-ae7cfaea`,
`…-219-5-9844a72e`, `…-193-4-5072b564`, `…-243-6-f109697e`), filed under
epic #496 before this document's decisions were made. Each one's
description now links back to its matching section above instead of
restating it, and carries its row from the Execution table above so picking
it up needs no round-trip back to this document.
-147
View File
@@ -1,147 +0,0 @@
# Inline review -- decision
**Status:** Finalised
**Beads issue:** `archie-core-q9au`
**Builds on:** `archie-core-h019` (adversarial self-review)
## Problem
Findings reach the operator only as a flat list in the PR body
(`renderPRReviewSection`, h019.6): ``- `file.go` (confirmed, error): <defect>
— <scenario>``. That is a report _about_ the code, not a review _of_ it. A real
reviewer anchors each finding to the line it is about, so the author sees it in
context — and, when the fix is mechanical, attaches the replacement so it can be
applied in one click.
Both halves are missing:
- **No line-anchored comment.** `forge.Forge.Comment` posts to the PR
_conversation_ (`Issues.CreateComment`); nothing creates a review comment at
`path` + `line`.
- **No suggested fix.** `ReviewFinding` carries `File`/`Line`/`Defect`/
`FailureScenario`/`Verdict`/`Level`/`Category` — no replacement code, so even
an anchored comment could only describe the fix, not offer it.
## Decisions
### 1. A narrow, type-asserted write surface
The set of comments travels in one call, so a forge that can only carry them on
a submitted review needs one request rather than one per finding:
```go
type ReviewCommentWriter interface {
CreateReviewComments(ctx context.Context, owner, repo string, number int,
comments []InlineReviewComment) error
}
```
Type-asserted like `PullRequestReader`/`PullRequestReviewReader`, so a forge
that cannot do it is skipped rather than faked. The stage reaches it through
`workflow.Forger`, whose production implementation is `forgerpc.Client` — the
worker holds no forge credentials, so the daemon's forgerpc server type-asserts
`forge.ReviewCommentWriter` and answers an incapable forge with an error the
best-effort stage logs.
The comment's line is anchored to the pull request's **current head revision**,
resolved inside each implementation rather than passed in by the caller: it is
the revision the comments are attached to, and the caller that produced the line
numbers holds no forge credentials to read it. The caller does pass the revision
those line numbers were **measured on** (`TaskContext.ReviewedHeadSHA`,
recorded when `StageOpenPR` opens the pull request), and the implementation
posts only while the head it read still matches it — see §4.
Per-forge reality, verified against the SDKs:
- **GitHub** — direct: `PullRequests.CreateComment` with
`{Body, Path, Line, Side: "RIGHT", CommitID}`.
- **Gitea** — no direct inline-comment call. Inline comments ride on a submitted
review (`CreatePullReview` with `Comments` and a `COMMENT` state). The Gitea
implementation therefore submits a single `COMMENT`-state review carrying the
findings, or the capability is simply absent (the type assertion skips it).
Decided: implement Gitea as a `COMMENT`-state review; do not block the feature
on it.
### 2. `Suggestion`, and only on confirmed findings
`ReviewFinding` gains an optional `Suggestion string` — the replacement text for
the anchored line, rendered as a fenced `suggestion` block (GitHub's one-click
"Commit suggestion").
**Only `confirmed` findings may carry one.** A wrong suggestion is a
one-click path to breaking code a reviewer then has to notice; `confirmed` is by
definition the verdict the reviewer traced and can state the failure for. A
`plausible` finding is a worry, and a worry gets a sentence, not a patch. This is
the h019.5 calibration rule reused, not a new one.
`Suggestion` replaces the anchored line exactly, and is only rendered when
`Verdict == confirmed`. Single-line only in this cut;
multi-line (GitHub's `StartLine`/`StartSide`) is a follow-up, because a
multi-line suggestion that is off by one line silently corrupts the file. The
rule is enforced in `ReviewFinding.Validate` — an embedded newline is rejected
there, so the `record_finding` tool refuses it with feedback the model can act
on, rather than the renderer silently posting a fence that applies only its
first line.
### 3. Which findings are posted inline
Only findings that are **line-anchored** (`Line > 0`). A whole-file finding
(`Line == 0`, e.g. "README.md is stale") has no line to attach to and stays in
the PR-body list. The body section keeps listing everything, so it remains the
complete record and the fallback.
Findings that block never reach this path: a surviving blocking finding parks
the task before `StageOpenPR`, so there is no PR to comment on. Inline comments
are the non-blocking, line-anchored subset — which is exactly the set that would
otherwise be a body-only list the author has to map back to lines by hand.
### 4. A best-effort stage after `StageOpenPR`
New `StagePostReviewComments`, after `StageOpenPR`:
1. Read the report stashed by `StageReview` (`tc.ReviewReport`, h019.6).
2. Post each line-anchored finding as an inline comment, with a suggestion block
when `Verdict == confirmed && Suggestion != ""`. The head SHA the comments are
anchored to is resolved by the forge implementation, not here; there is no
`PullRequestReader` on this side of the agent boundary. The stage passes
`tc.ReviewedHeadSHA` alongside them.
Nothing in the run pushes between `StageReview` and this stage, so at that
moment the pull request's head _is_ the revision the review read. That was an
assumption, and a collaborator can falsify it by pushing to the branch between
the review and the posting. A line number is not validated against a revision:
both forges anchor it to whatever now occupies that line, so a stale anchor
mislabels rather than failing. The revision is therefore carried with the
comments and the set is refused when the head has moved off it
(`reviewHeadDrift`) — a refusal lands in the failure path below, leaving the PR
body as the record. With no measured revision (a `Trees` that cannot report one)
the comments post unverified rather than being dropped.
**Failures log and never fail the task.** The PR is already open; a comment that
failed to post must not park a task whose actual work succeeded, and the body
section already carries every finding. This mirrors `OpenPR`'s existing
best-effort `LinkBranch` call.
### 5. No separate opt-in flag
Inline comments are posted whenever a review ran and produced line-anchored
findings — the same `repo.review_enabled` gate already covers it. A second flag
is a knob to add if it proves noisy in practice; adding it speculatively is the
smallest-change principle's opposite.
## Out of scope
- Commenting on the blocking/parked case (no PR exists).
- Resolving/dismissing threads, or reacting to replies (that is the
`archie-core-8li9` remediation direction).
- Multi-line suggestions.
- Gitea's "suggested change" rendering: Gitea has no one-click apply, so the
`Suggestion` there is informational text in the comment body.
## Packages this touches
- `internal/domain/workflow` — `ReviewFinding.Suggestion`; `StagePostReviewComments`;
the `Forger` subset gains the writer (or `TaskContext` gains the writer seam).
- `internal/forge` — `ReviewCommentWriter`, GitHub + Gitea implementations.
- `internal/app/agentworker` — the reviewer prompt asks for a `Suggestion` on
confirmed, mechanically-fixable findings; `record_finding` accepts it.
-203
View File
@@ -1,203 +0,0 @@
# MCP client and tool-guardrail completion
**Status:** Approved
Epic: `archie-core-1786637493439-140-2cee2e9b` / GitHub `#161` ("[EPIC] Tools:
central registry, MCP client, guardrails").
This document is scoped to five sub-features of that epic: MCP
server-initiated sampling, the per-server parallel-tool-calls flag, sandboxed
MCP tool servers, a Firecracker sandbox backend, and sequential dispatch with
per-result previews.
Out of scope, and not to be touched: the central registry
(`internal/tools/registry.go`), all three MCP transports (stdio/HTTP/SSE,
`internal/tools/mcp/transport*.go`), reconnect-with-backoff
(`transport.go`), guardrail loop detection
(`internal/tools/guardrail.go`), idempotent/mutating classification
(`internal/tools/classification.go`), concurrent tool dispatch (`#183`), and
progressive disclosure wiring (`internal/app/archied`). These are settled and
production-wired.
## Problem
`bd search "MCP client"` shows five closed transport beads and one open:
server-initiated sampling (`#151`). `internal/tools/mcp/client.go`
holds a single `callMu *sync.Mutex` that serialises every `tools/call`
regardless of server — `ParallelToolCalls` does not exist on the `MCPServer`
config struct (`internal/config/config.go`), confirming `#177` is a
real gap, not a stale bead. `#178` (wire MCP tool servers for the chat agent,
sandboxed) and `#179` (Firecracker substrate) have no corresponding code —
MCP servers run as whatever the config's `Command`/`Args` launches,
unsandboxed. `#182` (sequential tool dispatch with per-result previews) is
open; concurrent dispatch (`#183`) is closed, so there are two dispatch paths
and this PRD decides how they coexist.
## Design
Sub-features are independent; there is no new shared type this document
introduces. Each section below stands alone.
## MCP server-initiated sampling (`#151`)
**Decision.** Implement as a callback on `mcp.Client`, not a second
transport. The MCP spec's `sampling/createMessage` request flows server→client
over the same connection each transport already maintains
(`transport.go`'s stdio/HTTP/SSE all multiplex request and response frames).
Add a `SamplingHandler func(context.Context, SamplingRequest) (SamplingResult, error)`
field to the client's config struct next to the existing transport fields,
defaulting to nil (server sampling requests get a JSON-RPC "not supported"
error when unset — never a silent drop).
**Call site.** `internal/tools/mcp/client.go` — add the handler field and a
dispatch branch in whatever function demuxes incoming server
messages by method name (the same switch that already routes
`notifications/*`). Wire a concrete handler in
`internal/app/archied/main.go` that routes the sampling request through the
same chat-model call path `chatGenerateOptions` already uses, so a
server-initiated sample gets the daemon's configured model, not a second
provider client. The agent worker hosts the same configured MCP servers on the
task path and runs its own model runtime, so `internal/app/agentworker` wires
the same seam from the task's builder model: a server that samples succeeds
inside a chat turn and inside a task, never one and not the other. The message
mapping and the token bound are shared (`internal/agentexec`, next to the
runtime both paths call models through) so both paths bound a sample
identically.
**Reuse check.** The chat model invocation path already exists
(`chatGenerateOptions`, `main.go`) and the task model path already exists
(`agentexec.NewRuntime`, the runtime an agent stage runs on); this reuses both
rather than adding a parallel model-calling path for MCP sampling.
**Failure mapping.**
| condition | contract error |
| ------------------------------- | ------------------------------------------------------------------------------------------ |
| no `SamplingHandler` configured | JSON-RPC method-not-found, per spec |
| handler returns error | JSON-RPC internal error, message from handler |
| handler timeout | JSON-RPC timeout error; use the transport's existing request-timeout config, not a new one |
**Testing.** Fakeable entirely — a stub `SamplingHandler` and a fake
transport that emits a `sampling/createMessage` frame. No real backend
needed; belongs in `task check`.
## Per-server parallel-tool-calls flag (`#177`)
**Decision.** `ParallelToolCalls bool` (default `false`) goes on `MCPServer`
in `internal/config/config.go`, next to `Transport`/`Command`. The
mutex in `client.go` becomes per-server: when `ParallelToolCalls` is
false (default, and the only behaviour), keep the single `callMu`
serialising that server's calls exactly as now; when true, drop the mutex for
that server's `Client` instance entirely and let the caller's own
concurrency (already proven by the closed concurrent-dispatch bead, `#183`)
handle it. This is additive — no server's behaviour changes unless an operator
opts in.
**Call site.** `internal/config/config.go` (struct field),
`internal/tools/mcp/client.go` (make the mutex conditional on the
field), and wherever `MCPServer` configs are turned into `Client` instances
at daemon startup (the constructor that reads `internal/config`'s MCP block).
`config.example.toml`'s commented MCP block gets the new field documented
with its default.
**Testing.** Unit test asserting two concurrent `Call`s to the same
`Client` block on each other when the flag is false and don't when true —
fakeable with a slow fake transport. `task check`.
## Sandboxed MCP tool servers for the chat agent (`#178`) and Firecracker substrate (`#179`)
**Decision.** These two beads are one design decision, not two: `#179` is an
alternate execution backend for `#178`, not separate scope. Sandbox MCP
servers that a chat-turn config marks as untrusted (a new
`Sandboxed bool` field on `MCPServer`, default `false` — existing
configured servers are unaffected) behind the same `ContainerPool` the
daemon already uses to run agent work
(`internal/container/pool.go`, per CLAUDE.md's `WriteTaskJSON` trap and the
`Acquire`/`Release` lifecycle `daemon.go`'s `acquireTaskContainer` already
proves). Do not build a second sandbox mechanism: an MCP stdio server is a
subprocess exactly like an agent task container's entrypoint, so launching it
via `ContainerPool.Acquire` with stdio piped to the `mcp.Client` transport is
the smallest change, not new plumbing.
Firecracker is **not** built now. `ContainerPool`'s existing Docker-backed
isolation is the shipped backend; Firecracker becomes a second
implementation of the same acquire/release contract only if a concrete
escape or resource-isolation gap is measured against Docker-backed sandboxing
in production. Recording this as the deletion/promotion gate keeps `#179`
honestly `OPEN` instead of speculatively building an unused backend, per
CLAUDE.md's Architectural Simplicity rule.
**Call site.** `internal/config/config.go` (`MCPServer.Sandboxed`), the MCP
client constructor (route sandboxed servers' process launch through
`container.Pool.Acquire` instead of `os/exec` directly), and
`internal/container/pool.go` (confirm its `Acquire` contract accepts a
stdio-piped, non-worktree workload — if it assumes a git worktree
per CLAUDE.md's `WriteTaskJSON` note, add the narrower entrypoint variant
there rather than duplicating the pool).
**Error/failure mapping.**
| condition | contract error |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| pool exhausted (no container slot) | MCP client returns connection-refused equivalent; server marked unavailable in the registry until retried |
| container fails health/start | same as `#151`'s handler-error path — surfaced through the client's existing reconnect/backoff (`transport.go`), not a new retry loop |
**Testing.** `Sandboxed=false` path is the existing, already-tested
unsandboxed flow — no change. `Sandboxed=true` needs a real
`ContainerPool` (Docker) — manual smoke command, not `task check`; document
the exact command in the runbook this PRD's issue links to once implemented.
## Sequential tool dispatch with per-result previews (`#182`)
**Decision.** This coexists with concurrent dispatch (`#183`, closed) as a
second, explicit mode selected by the caller — not a replacement. Concurrent
dispatch is for independent tool calls in one turn; sequential-with-preview
is for a turn where each result should be surfaced to the operator (or the
next tool call) before the next call fires — e.g. a mutating tool chain where
showing intermediate state matters. Add a `DispatchMode` enum
(`Concurrent`/`Sequential`) to whatever type selects the closed
`#183` concurrent path, defaulting to `Concurrent` (its only behaviour).
**Call site.** The tool-dispatch entry point that `#183`'s closed
implementation lives in (grep the concurrent-dispatch symbol added for
`#183` — same file gets the sequential branch, not a parallel file). Preview
surfacing reuses whatever channel-adapter interface already streams
intermediate turn output (the same seam `internal/channels/telegram/` and
other adapters use for streaming deltas) — do not invent a second preview
transport.
**Testing.** Fakeable with a fake tool that returns staged results; assert
preview callbacks fire in order before the next call starts. `task check`.
## Call site inventory
| concern | file | change |
| --------------------------------------------------- | ---------------------------------------------------------------------------------- | -------------------------------------------- |
| MCP client transports (stdio/HTTP/SSE) | `internal/tools/mcp/transport*.go` | none — already handles this |
| MCP client call serialisation | `internal/tools/mcp/client.go` | change (`#177`) |
| MCP server config | `internal/config/config.go` | new fields: `ParallelToolCalls`, `Sandboxed` |
| Sampling dispatch | `internal/tools/mcp/client.go` | new (`#151`) |
| Sampling handler wiring (chat path) | `internal/app/archied/main.go` | new (`#151`), reuses `chatGenerateOptions` |
| Sampling handler wiring (task path) | `internal/app/agentworker/mcp_sampling.go`, `mcp_providers.go` | new (`#151`), answers from the task's builder model |
| Sandboxed MCP launch | MCP client constructor + `internal/container/pool.go` | new (`#178`/`#179`) |
| Concurrent tool dispatch | dispatch entry point (closed `#183`) | none — already handles this |
| Sequential tool dispatch + previews | same dispatch entry point | new (`#182`) |
| Guardrails / classification / registry / disclosure | `internal/tools/guardrail.go`, `classification.go`, `registry.go`, `disclosure.go` | none — already handles this |
| `config.example.toml` MCP block | `config.example.toml` | doc update for new fields |
## Execution: multi-agent team breakdown
| sub-feature | issue | implementer scope | suggested council lenses | why |
| ------------------------------------ | -------------- | ---------------------------------------------------------------------------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------- |
| Server-initiated sampling | `#151` | `client.go` dispatch branch, chat-path and task-path handler wiring | `lens-contract` | new JSON-RPC method surface crossing the MCP wire contract |
| Parallel-tool-calls flag | `#177` | config field, conditional mutex, constructor wiring | `lens-boundary` | per-server behaviour change must not leak into other servers' serialisation |
| Sandboxed MCP + Firecracker deferral | `#178`, `#179` | config field, constructor routing through `ContainerPool`, pool entrypoint variant | `lens-operator`, `lens-deletionist` | operator: sandbox-down failure path; deletionist: keeps `#179` from becoming unused scaffolding |
| Sequential dispatch with previews | `#182` | `DispatchMode` enum, sequential branch, preview reuse of streaming seam | `lens-maintainer` | two coexisting dispatch modes need a reader to tell which applies without re-deriving both |
## File and link the beads
- `#151`, `#177`, `#178`, `#179`, `#182` each get their description updated to
point at this doc's matching `##` heading instead of restating the design.
- Close `#179` as a design decision (link here) rather than leaving it open
as separate scope — it is not built now, and the doc records why.
- Add the suggested lenses to each issue directly.
-366
View File
@@ -1,366 +0,0 @@
# Memory engine unification: four scopes, CRUD, and one write path -- decision
**Status:** Approved
**Date:** 2026-09-16
**Findings:** `memory-4` and its dependants in the adversarial sweep
(`.local/issue-tracker`); the real defect is the split described below, for
which `memory-4` is a symptom
**Supersedes:** the draft `memory-turn-context.md` (its synchronous-read
argument survives and is reused; its `Manager` method and consumer-owned port do
not)
**Settles:** four open items in `docs/architecture/migration-decisions.md#5`
(listed at the end)
## Problem
There are **two live memory stores for one assistant**, split by which component
writes them, and the chat turn reads neither.
| Family | Written by | Root | Format |
| ----------------------------------------------------------- | ----------------------------------------------------------------------------- | ------------------------- | ----------------------- |
| `internal/memory` (`Manager`, `builtin.Provider`) | the chat agent's `memory_edit` tool via `memorytoolprovider` (`bootstrap.go`) | `<workDir>/memory` | `MEMORY.md` / `USER.md` |
| `internal/domain/memory` + `internal/infrastructure/memory` | the session curator (`sessioncurator.go`) | `<workDir>/memory-engine` | identity-keyed blocks |
They share no code, no format and no scope vocabulary. Neither reaches a prompt:
`Manager.SystemPromptBlock` (`internal/memory/manager.go`) has no production
caller anywhere, so the agent can write memory through a tool and never read it
back.
Three further defects fall out of the same split:
1. **The engine's contract is not CRUD.** `Store` is `Write`/`Query`/`List`/
`Forget` — create, read, delete, and **no Update**. The retired file provider
_does_ have `handleAdd`/`handleReplace`/`handleRemove`, so the family being
deleted is operationally richer than its replacement.
2. **There is no scope model.** The contract carries one opaque `Identity
string`, and the curator fills it with a **session id** (`sessioncurator.go`)
— which is none of the four scopes `docs/architecture/agent-system.md`
requires, and stops meaning anything when the session ends.
3. **The chat turn has no user identity on half the channels.** Telegram and
email populate `SenderID` with a person; the dashboard populates it with
nothing, and a webhook populates it with nothing either — a route path names
a source, not a person, so `webhook.go` leaves `SenderID` empty and carries
the route in `Inbound.BudgetKey` for rate limiting. `sender_id` is persisted
(`session_store_postgres.go`), so whatever a channel puts there reaches the
consumers that read it.
`agent-system.md` says the write-scope selection and cross-scope sharing
rules "require a focused memory design decision". This is that decision.
## Decision
### 1. One engine, addressed by four typed scopes
`internal/domain/memory` is the only memory engine. `Observation.Identity`,
`Query.Identity`, `Record.Identity` and `List(identity)` are deleted, not
extended: a field whose meaning depends on the caller cannot carry a scope.
```go
type ScopeKind string
const (
ScopeGlobal ScopeKind = "global" // shared across the application
ScopeAgent ScopeKind = "agent" // private to one Agent
ScopeUser ScopeKind = "user" // one user, across their Agents
ScopeAgentUser ScopeKind = "agent-user" // one Agent's relationship with one user
)
type Scope struct {
Kind ScopeKind
Agent AgentID // required for ScopeAgent, ScopeAgentUser
User IdentityID // required for ScopeUser, ScopeAgentUser
}
func (s Scope) Validate() error // rejects a component present where it is not required
func (s Scope) Key() string // canonical, collision-free storage key
```
`AgentID` and `IdentityID` are opaque. This package never resolves or
canonicalises them.
A turn's resolved identity is one value:
```go
type Subject struct {
AgentID AgentID
UserID IdentityID // "" when the channel carries no per-person identity
}
func (s Subject) Scopes() []Scope // readable, most specific first
func (s Subject) WritableScopes() []Scope // never includes ScopeGlobal
```
**Access control is naming a scope, and nothing else.** The read path names
exactly the scopes of the resolved `Subject`; the engine never unions beyond what
it is handed and applies no policy of its own. An engine that enforced policy
would need to know about channels, sessions and bindings, and every backend would
reimplement it. "Agent-wide is private to its owning Agent by default"
(`agent-system.md`) falls out mechanically, because `ScopeAgent{a}` and
`ScopeAgent{b}` are different storage keys.
`ScopeGlobal` is never model-writable. Writing it is an operator action; nothing
produces one yet, but the contract models it because the read set includes it.
### 2. CRUD, with revisions retained
```go
type Store interface {
Create(ctx context.Context, in NewRecord) (Record, error)
Get(ctx context.Context, scope Scope, id RecordID) (Record, error) // ErrNotFound
Query(ctx context.Context, q Query) ([]Record, error) // heads only
List(ctx context.Context, scope Scope) ([]Record, error) // heads only
Update(ctx context.Context, in RecordUpdate) (Record, error) // ErrNotFound, ErrStaleRevision
Forget(ctx context.Context, scope Scope, id RecordID) error // idempotent
Revisions(ctx context.Context, scope Scope, id RecordID) ([]Revision, error)
}
```
`Get` and `Forget` take a scope. The current `Forget` scans every identity's
store to find a marker (`builtin_engine.go`) purely because the contract
gave it nothing better.
`Record` carries what `agent-system.md` requires be retained: `Scope`,
`Kind`, `Content`, `Revision`, `Author`, `OriginUser`, `Source`, `CreatedAt`,
`UpdatedAt`. `Metadata` is dropped — nothing sets it and the parser never
restores it, so it is a field that silently does not round-trip.
`Update` supersedes rather than overwrites. The superseded state is appended to
the scope's `HISTORY.md` **before** the live block is replaced, so a crash
between the two leaves an extra history entry and an unchanged record —
recoverable — never a record whose previous state was lost. `Update` carries no
`Scope`: a record may never move between scopes, and the API makes that
unrepresentable rather than validating it. `Expected` optionally names the
revision being replaced and returns `ErrStaleRevision` on mismatch, which matters
because two processes (`archied` and `archie-gateway`) can hold the same scope's
file.
`Forget` records a deleted revision before removing the live block, so a record's
provenance outlives its content.
### 3. The caller resolves identity; the engine never does
Resolution happens in the gateway turn path, where the native sender id and the
session are both in hand, and it is supplied **per channel by the composition**:
```go
// TurnRunnerConfig
// UserIdentity resolves the initiating user's identity for one inbound message.
// false means the channel carries no per-person identity, and the turn gets
// global and agent scopes only. Nil means the same.
UserIdentity func(msg messaging.Message) (IdentityID, bool)
```
This must be injectable rather than a blanket `channel + ":" + SenderID`
concatenation, because a channel's sender id is not necessarily a person: a
webhook's route path names a source, and treating it as an identity would give
a URL one -- which is why `webhook.go` leaves `SenderID` empty and carries the
route in `Inbound.BudgetKey` instead. Telegram and email supply their sender
id; the dashboard and webhook resolve nothing.
**Fail closed.** When `UserID` is empty the turn proceeds with global and agent
scopes only, and a write targeting `user` or `agent-user` fails with a clear
error. `agent-system.md` forbids showing one user's memory to another, so
"we do not know who this is" must mean "show none of it", never "fall back to a
wider scope".
### 4. The chat read path
Synchronous and total. It runs inside `prepareTurn` (`turn.go`) before the
prompt is built, never returns an error to the caller, and degrades to an empty
block on any engine failure or provider panic. A fire-and-forget hook would race
the prompt build in the same turn, which is why this is not a lifecycle hook.
The read is a scope-only `Query` over the subject's scopes — **not** ranked
search, which remains open in `migration-decisions.md#5`. A ranked read on the
hot path with no ranking implementation would be a lie.
`SystemPromptConfig` gains a `Memory` field, rendered into
`templates/archie.md.tpl` between the `<tools>` and `<env>` blocks:
```
<memory purpose="durable_context" trust="data">
```
`trust="data"` and inclusion in the precedence clause follow the `<tools>`/`<env>`
precedent exactly: memory content is model-written from untrusted input and must
be framed as data, never instructions. The rendered block carries each record's
short id, because the write path addresses records by id — one source of truth
for both directions.
Both a per-scope record limit and a byte cap on the rendered block are named
constants. The cap is about size, not latency; a local read needs no timeout.
**Prerequisite:** `setupGateways` runs before `setupMemoryAll`
(`main.go` vs `:428`), and `startGatewayRuntime` before `setupMemory`
(`gateway.go` vs `:115`), so the engine is nil at every turn-runner
construction site. The ordering is the root-cause fix and nothing in either
memory step reads what those later steps produce.
### 5. The chat write path
The memory tool is built **per turn**, not registered once at boot, because it
must write into a scope derived from the turn's resolved subject:
| action | engine call |
| -------- | ---------------- |
| `create` | `Create` |
| `update` | `Update` (by id) |
| `delete` | `Forget` (by id) |
| `list` | `List` |
**The model chooses the scope kind; it never chooses the ids.** Agent and user
ids come from the turn's resolution and there is no schema field to put anything
else in — even a model that emits another user's id has nowhere to write it. That
is the root-cause form of `agent-system.md`, matching this system's other
non-waivable boundaries (the model never runs git; gates cannot be waived by the
agent). `global` is not offered at all.
The tool takes a record **id** where the retired provider took a content
substring (`handleReplace`/`handleRemove`). The substring addressing existed
because a markdown file was hand-edited and the model had no stable handle on a
block; with ids rendered into the prompt it disappears, and one addressing scheme
replaces two.
### 6. The curator's write
`sessioncurator.reviewOne` stops writing `Identity: sessionID` and writes
`ScopeAgentUser{AgentID: <session's agent>, UserID: <participant>}`. Relationship
scope is the only defensible home: agent-wide is explicitly unsafe for user facts
and would leak user A's extracted facts to user B through the same agent;
user-wide would pool facts across agents; and a session id cannot survive the
session ending, which is the whole requirement.
This needs data the tree does not persist: the `messages` table
gains `sender_id`, and `curator.SessionSummary` / `ConversationMessage` gain the
agent and participant. The participant is derived from the session's own
user-role messages: exactly one distinct non-empty sender writes; zero (a
dashboard or webhook session) or several (a group chat) writes nothing and
records why. Ambiguity fails closed rather than guessing.
The payoff is the point of the exercise: chat-written and curator-derived memory
now occupy the same scopes, so a future turn's prompt contains both, and a
curator's bad note becomes id-addressable and therefore correctable by the agent.
### 7. The content scanner moves to the engine
`internal/memory/scanner.go` and its installation at `bootstrap.go` are what
make `configuration.md`'s "Memory safety scanner" row describe a control that
actually runs. Deleting the package would silently remove prompt-injection
scanning on memory writes. The scanner moves into the engine and is applied in
`Create` and `Update`, which is the single choke point every producer crosses —
so the curator's model-extracted content is covered too, not just the chat tool's.
### 8. `internal/memory` is deleted
Not shimmed, not partially, not behind a flag: `manager.go`, `provider.go`,
`lifecycle.go`, `sync.go`, `scanner.go` (moved), `schema.go`, `backup.go`,
`config.go`, `builtin/provider.go`, and their tests. Its markdown store
(`builtin/store.go`) is the one survivor, relocated to
`internal/infrastructure/memory/builtin/` — `organisation.md`'s "a package owns
its on-disk format end-to-end" makes infrastructure its correct home, and the
engine already parses that format.
Also deleted: `internal/tools/provider/memory`'s manager wrapping (rewired to the
engine), `config.Memory.{Provider,ProviderConfig}` and the
`validateMemory` rejection that exists only to complain about `Provider`
(`validate.go`), and `webui.MemoryStatus`/`MemoryProviderHandle` — never
implemented in production, so `/api/memory` reports empty forever unless it is
repointed at the engine registry.
Existing data at `<workDir>/memory` is left on disk, unreferenced. No migration.
`<workDir>/memory-engine` is likewise orphaned: its directories were keyed by
`sha256(sessionID)` and no scope key can hash to one.
## What we deliberately do NOT do
- **No cross-scope sharing or grants in this wave.** Promoting a record between
scopes is a future explicit command, and `Update` cannot change scope, so it
cannot happen by accident.
- **No canonical user identity.** `SenderID` is channel-native, so one person on
Telegram and email is two identities. Unifying needs an Identity aggregate that
does not exist (`internal/domain` has no identity package and `IdentityID`
appears nowhere in Go). The contract does not change when it lands.
- **No ranked retrieval.** `Query.Text` stays, unused by the prompt path.
- **No data migration**, per the decision above.
- **No prompt-memory timeout mechanism.** The read is bounded by construction.
- **No `Metadata` field.** It is write-only; a caller needing it later
needs one field, not a speculative contract.
## Acceptance criteria
1. A record created through the memory tool in turn 1 appears in turn 2's prompt,
asserted on content the test planted, with its id.
2. The same record is **absent** from a different user's prompt on the same
channel and agent. Isolation asserted end to end, not at the engine boundary.
3. An agent-scope record is visible to both of that agent's users; a global
record is visible to a second agent; an agent-user record is not.
4. A curator pass over a session writes a record a later turn reads, and which
survives that session being deleted.
5. `create` → prompt shows it; `update` → prompt shows new content and
`Revisions` returns the prior content with author and time; `delete` → gone
from prompt and `List`. Round-trip is asserted as `parse(render(r)) == r`,
never against a fixture string.
6. A panicking engine and a failing engine both complete the turn with no memory
block.
7. A channel with no resolvable user renders only global and agent scopes, and
the tool refuses `user`/`agent-user` with a reason. A webhook route path never
becomes a user identity.
8. A write that would exceed the file cap fails loudly rather than silently
dropping content.
9. `internal/memory` is gone, `task check` is green, and no document describes a
manager that no longer exists.
Every criterion asserts behaviour or planted content. None asserts on the text of
a hand-written file, and none pins that a method was called. In particular none
asserts the composition calls setup in a given order: if the ordering were
swapped back, criteria 1 and 4 would fail, and that is the assertion.
## Sequencing
Each step is independently verifiable and lands green on its own.
1. **Persist the participant.** `sender_id` column on `messages`,
insert/select/migration, `curator.SessionSummary.AgentID` and
`ConversationMessage.SenderID`. Touches no memory contract and is shippable
alone — nothing consumes it yet.
2. **Scope, CRUD and revisions.** The `internal/domain/memory` contract, the
builtin engine with `HISTORY.md`, the store relocation, the scanner move, and
the curator rewritten onto agent-user scope (it is the engine's only live
consumer, so it belongs in this slice). _Depends on 1 for the curator half._
3. **Chat read path.** The `Memory` seam, the template block, subject resolution,
and the composition-ordering fix. _Depends on 2._
4. **Chat write path.** The tool adapter onto CRUD and the turn's subject on the
context. _Depends on 3, because a write is only observable through the read._
5. **Delete `internal/memory` and the dead config/dashboard surface**, and
rewrite the "Memory engine family" section of
`docs/architecture/plugins-and-extensions.md` to describe the
engine family rather than a manager it deleted. _Depends on 3 and 4._
Steps 3 and 4 are separable from each other; step 1 is separable from everything.
## Settles these open items in `migration-decisions.md` §5
| §5 open item | Settled by |
| ---------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| authoritative memory record and revision model | §1, §2 — the live marker becomes JSON, since the ratified `<!--mem:<ulid>-->` cannot carry provenance; superseded states live in a per-scope `HISTORY.md` |
| provider and infrastructure boundaries | §2 — contract in `internal/domain/memory`, builtin format in `internal/infrastructure/memory/builtin` |
| retrieval and access enforcement | §1 — caller-named scope sets, no engine-side policy |
| provenance representation | §2 |
## Not determined
- **Group chats produce no derived memory**, because the curator fails closed on
mixed-sender sessions. Whether extraction should instead become
per-participant is a product call.
- **Two processes, one scope file.** After step 3 both `archied` and
`archie-gateway` hold an engine over the same root, and the engine caches a
store per scope and rewrites the whole file, so concurrent writers on one scope
can lose a block. `Update.Expected` makes that detectable for one record; it
does not make the file safe. A reload-before-mutate or advisory lock is the fix
and is not designed here.
- **Unbounded history.** `HISTORY.md` grows without limit; no compaction policy.
- **Size bounds.** `defaultMaxFileBytes` is now per scope rather than per
identity; whether that is right is unexamined.
- **Whether the dashboard should carry a user identity.** It has one bearer
token, not users. Until it has users, web turns are correctly limited to global
and agent scope.
-78
View File
@@ -1,78 +0,0 @@
# Messaging Service boundary and transport design
**Status:** Approved
**Revision:** 1
**Date:** 2026-09-19
**Beads issue:** `archie-core-8cda.6.1`
**Parent:** [`service-decomposition.md`](service-decomposition.md)
**Prerequisites:** Gateway contract extraction (Phase 1), State Store extraction (Phase 2), UI extraction (Phase 3)
This document is the authoritative specification for Phase 4: Messaging Service extraction. It fixes the process boundary, configuration ownership, client contracts, security posture, readiness behaviour, channel invariants, and deletion criteria required by `archie-core-8cda.6` and its child tasks.
## Decision
The Messaging Service (`cmd/archie-messaging`, composed via `internal/app/archiemessaging`) owns external channel connections (Telegram, email, webhook) and dispatches inbound messages and commands to the standalone Gateway Service over gRPC via `messaging.ChatContract`.
It is a peer service to the UI Service and the daemon:
- It serves external chat participants across configured communication platforms.
- It consumes Gateway's `messaging.ChatContract` exclusively for chat turn execution, streaming, session queries, cancellation, persona selection, and task control actions.
- It holds no direct database connections, owns no LLM execution or model provider credentials, and has no dependency on the daemon runtime or the UI HTTP server.
## Boundary and Ownership
| Concern | Messaging Service owns | Messaging Service consumes | Messaging Service must not own or link |
| ---------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------ |
| **Channel transports** | Telegram bot long-polling, Email IMAP/SMTP loops, Inbound Webhook HTTP listener | Gateway `ChatContract` | Direct LLM providers, model runtimes, tokenizer libraries |
| **Turn dispatch** | Inbound message packaging, typing indicators, live streaming updates | `ChatContract.Route`, `ChatContract.Stream` | `gateway.Router`, `runtime.Runtime`, agent prompt builders |
| **Sessions & History** | Platform-to-session key mapping, conversation thread ID translation | `ChatContract.GetSession`, `RecentMessages`, `RecentTurns` | store implementations, `SessionStore` database handles |
| **Control & Actions** | Platform command parsing (`/status`, `/tasks`, `/cancel`, `/stop`, `/persona`) | `ChatContract.Snapshot`, `ApplyTaskAction`, `Cancel`, `SetPersona` | `daemon.Daemon`, workflow execution engine, worktree operations |
| **Task Approvals** | Channel interactive keyboards, approval callbacks | `ChatContract.ApplyTaskAction` | Direct task status mutations, forge comment posters |
| **Configuration** | Platform bot tokens, allowed sender/user IDs, webhook listen ports | `[chat.*]` channel configs, Gateway target/token | `config.Holder`, forge tokens, repo configs, agent container specs |
| **Readiness** | Messaging process liveness, channel connectivity, Gateway probe | Gateway `ChatContract.Snapshot` | Internal daemon subsystem probes |
## Target Service Shape
1. **Binary entry point**: `cmd/archie-messaging/main.go` parses CLI flags (`-config`, `-config-overlay`, `-gateway-target`, `-gateway-token`) and hands execution to `internal/app/archiemessaging.Run`.
2. **Application composition**: `internal/app/archiemessaging/` wires:
- Config loading scoped strictly to `[chat.*]` and `[services.gateway]`.
- Secret resolution for channel credentials (e.g. Telegram bot token).
- Gateway gRPC client (`internal/infrastructure/gatewayrpc.Client`).
- Channel lifecycle managers (`internal/channels/status`).
- Channel instances (`internal/channels/telegram`, `email`, `webhook`).
3. **Turn and Stream Execution**:
- Channels adapt inbound platform messages to `messaging.Inbound`.
- Streaming channels (Telegram) consume `ChatContract.Stream(ctx, inbound)` which returns `<-chan messaging.ChatEvent`, mapping `started`, `delta`, `tool`, `media`, `done`, and `error` events directly to live message frames.
- Non-streaming channels (email, synchronous webhooks) consume `ChatContract.Route(ctx, inbound)`.
## Load-Bearing Channel Invariants
The Messaging Service preserves existing invariants defined in `AGENTS.md` and channel documentation:
1. **Telegram long-polling**: Must call `dropPendingUpdates(ctx, b)` before `b.Start(ctx)` and on `/restart`.
2. **Telegram command menus**: Must register command menus simultaneously to `default`, `all_private_chats`, and `all_group_chats` via `commands.go` to prevent menu shadowing.
3. **No UI detour**: Turns and task actions route directly to Gateway's `ChatContract`; no HTTP request may ever be sent to `archie-ui` or `internal/webui`.
4. **Sender Confinement**: Telegram sender checks against `allowed_user_ids` must continue to fail closed before initiating any turn dispatch.
## Configuration Ownership
`cmd/archie-messaging` reads only:
- `[services.gateway].target` and `[services.gateway].target_token` (or CLI flags).
- `[chat.telegram]` (token, allowed user IDs).
- `[chat.email]` (IMAP/SMTP host, ports, credentials).
- `[chat.webhook]` (listen address, secret).
- `[secrets]` (for resolving token secret references).
It does not read or decode `[forge]`, `[repos]`, `[models]`, `[providers]`, `[runners]`, `[containers]`, or `[nats]`.
## Deletion Gate and Verification
The extraction is guarded by `cmd/archie-messaging/architecture_test.go`, verifying that `go list -deps ./cmd/archie-messaging` links zero banned runtime packages:
- `modernc.org/sqlite`, `github.com/jackc/pgx`, `internal/infrastructure/postgres` and `internal/infrastructure/legacyread` (State Store)
- `internal/daemon`, `internal/app/archied`, `internal/container`, `internal/worktree` (Daemon runtime)
- `internal/domain/workflow`, `internal/agentexec`, `internal/taskrun` (Workflow engine)
- `internal/forge`, `internal/forgerpc` (Forge client)
- `internal/gateway` runtime (only `internal/domain/messaging` and `internal/infrastructure/gatewayrpc` are permitted)
- `internal/webui` (Dashboard)
-220
View File
@@ -1,220 +0,0 @@
# Module position -- design
**Status:** Draft
**Date:** 2026-09-03
**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`
## Problem
`eda-playbook-engine.md` names four logic positions a playbook action can
target: Workflow, Module, Channel, Forge. Workflow (`t2db.9`/`.10`/`.11`)
and the standalone lint tool (`t2db.12`) are shipped. Module -- the
position that makes an action "not restricted to code-generation" -- has
not started, because it needs a schema-generation mechanism the parent
doc deliberately deferred: "This document does not attempt to design the
full generator." This is that design.
## Do not invent a new mechanism -- generalise the one used three times
Yaegi-interpreted extension code with a fixed, resolved-by-name exported
function already exists in this codebase for three surfaces, and all three
follow the identical shape:
| Surface | Fixed signature | Export path | Symbol table |
| ----------------------------------------- | --------------------------------------- | -------------- | --------------------- |
| Custom gate (`internal/gate/gateeval`) | `func(gate.GateContext) []gate.Finding` | `"gate.Check"` | `gateextract.Symbols` |
| Workflow stage plugin (`skillbuild`) | stage-specific | skill-declared | `wfextract.Symbols` |
| Skill plugin (`internal/skill/plugin.go`) | `func(string) string` | `"main.Run"` | none (stdlib only) |
Each is: read a `.go` file -> `yaegiutil.New` with that surface's symbol
table -> `yaegiutil.Resolve[T](i, src, exportPath)` -> call the resolved
function wrapped in `yaegiutil.Safe` for panic recovery. **Module is a
fourth instance of this same shape**, parameterised by action kind instead
of hardcoded to one fixed signature. No new interpreter construction, no
new panic-recovery mechanism, no new symbol-table generation tool --
`go generate ... yaegi extract` is already how `wfextract`/`gateextract`
are produced that way (see their `//go:generate` directives), and Module
schema generation reuses that exact command.
## No generic `Module` interface -- one typed contract per action kind
The plugin engine rule's invariant 1 requires "real capability-specific
operations," and invariant 5 forbids adding capability methods to a
generic interface. A single `Module` interface with `Run(args any) (any,
error)` would be exactly the untyped hook the rule (and
`event-sources-and-reactions.md`'s rejection of a generic `Source`
interface) exists to prevent -- restating the mistake the whole EDA
document was written to move away from (`wfextract`'s hardcoded
`reflect.ValueOf(workflow.Implement)` table is what a closed, un-typed-per-
case system already looks like in this repo).
Instead, **each action kind is its own tiny package with its own
generated contract**, exactly like `gate.GateContext`/`gate.Finding` are
one hand-written Go file that `gateextract` turns into a Yaegi symbol
table:
```go
// internal/domain/eda/module/notify/types.go (hand-written, the schema source)
package notify
// SchemaVersion is independent of a playbook's own workflow_version, per
// eda-playbook-engine.md's schema-versioning point.
const SchemaVersion = 1
type Args struct {
Channel string
Message string
}
type Result struct {
Delivered bool
}
//go:generate go run github.com/traefik/yaegi/cmd/yaegi extract -name notifyextract github.com/samcharles93/archie-core/internal/domain/eda/module/notify
```
A Yaegi module implementing this kind exports a fixed function name
against these generated types, resolved the same way `gate.Check` is:
```go
// operator's notify.go, interpreted at load
package notify
func Run(a notify.Args) notify.Result { ... }
```
`internal/domain/eda/module/notify` is the schema; `notifyextract.Symbols`
is its generated Yaegi bridge; the operator's file is the implementation.
This is the same three-way split `internal/gate` / `gateextract` /
`.archie/gate.go` already has.
## The registry: `ModuleRegistry`, keyed by kind, not a service locator
Per invariant 2 (owning family manager) and invariant 4 (narrow host
access): a `ModuleRegistry` in `internal/domain/eda/module` maps a kind
name (`"notify"`, `"image-gen"`) to a resolved, type-erased invoker --
the same `map[string]reflect.Value`-shaped erasure `wfextract.Symbols`
already uses to bridge Yaegi and Go, not a new pattern and not exposed as
the plugin's contract with the daemon (the plugin still writes and is
checked against a fully typed `func(Args) Result`; the registry's
internal storage is the only place erasure appears, exactly as it already
does inside `wfextract`).
```go
type ModuleRegistry struct {
// kind -> (validate args against generated schema, invoke, marshal result)
}
func (r *ModuleRegistry) Register(kind string, dir string) error // discovers <kind>.go, resolves against that kind's generated symbols
func (r *ModuleRegistry) Invoke(ctx context.Context, kind string, rawArgs map[string]any) (map[string]any, error)
```
`Invoke` decodes `rawArgs` into that kind's generated `Args` struct before
calling the interpreted function -- a shape mismatch is a reported load/
dispatch failure per the design doc's "schema defines the accepted
message" rule, not a silent zero-value fill. This mirrors `plugin.Registry`
(`internal/plugin/plugin.go`)'s `Register`/dispatch split, scoped to one
capability family instead of generic daemon plugins.
Lifecycle (invariant 3): stateless invocation is the default -- explicit
no-op start/health/stop, matching "Stateless providers may make these
operations explicit no-ops." A future Module kind that owns a resource
(e.g. a persistent connection) can add optional lifecycle methods later,
the same way `internal/memory.MemoryProvider`'s optional capability
contracts (system-prompt contributions, prefetch, shutdown) layer onto a
minimal required set without forcing every provider to implement them.
## Trust boundary (closes `eda-playbook-engine.md` open question 3)
Invariant 6 draws the line: operator-trusted in-process code vs.
repository-supplied code that must run in a container. Module code is
**operator-installed, in-process, daemon-privileged** -- the same trust
tier as `PluginDir` (daemon plugins) and `SecretEngineDir` (secret engine
plugins) already occupy, both Yaegi-interpreted and already running
in-process. It is **not** repository-supplied code from a task
(that stays containerized, unchanged). A Module directory is therefore a
new config field the operator points at their own trusted directory,
mirroring `PluginDir`'s shape exactly -- not something a forge webhook or
an untrusted playbook source can populate.
## Playbook YAML shape for a Module action
```yaml
actions:
- position: module
kind: notify
args:
channel: telegram
message: "build finished"
```
`args` is validated against `notify.Args` (via the registry's decode
step) before invocation -- an unknown or missing required field is the
same "dropped and reported to the caller" failure the routing layer
already applies to unrecognised kinds/labels, not a new error philosophy.
## Interaction with the unresolved execution-time gaps
`eda-playbook-engine.md`'s "Execution-time gaps" section already gates
this: mid-run failure semantics and idempotency keying "must be resolved
before Channel/Forge actions or multi-action playbooks ship." Module is
where those gaps stop being theoretical -- a `notify` action has a real
side effect. Concretely:
- A **first Module kind should be side-effect-free** (e.g. a `log`/`echo`
kind that only writes to the daemon's own log) so the schema-gen ->
registry -> playbook-dispatch mechanism can be proven end to end without
yet needing an idempotency answer.
- **Any Module kind with a real external side effect (`notify`,
`image-gen`, forge writes) is blocked on resolving those two gaps
first** -- this document does not relitigate or resolve them, it
inherits the existing gate.
## Recommended first slice
1. `internal/domain/eda/module` package: `ModuleRegistry`, the
discover/resolve/invoke mechanics, generalising `gateeval`'s pattern.
2. One proof-of-concept kind, side-effect-free (`log`), with its schema
source + generated extract file, to prove schema -> `go:generate` ->
Yaegi load -> registry -> playbook dispatch end to end.
3. Config field for the Module directory (`ModuleDir`, mirroring
`PluginDir`), wired at daemon startup alongside the existing
`PlaybookDirs` loading.
4. Do **not** implement `notify` or any side-effecting kind in this slice
-- that is explicitly gated on the execution-time gaps above.
**Resolved** (`archie-core-t2db.13`). The schema-gen ->
go:generate -> Yaegi load -> registry mechanism is proven end to end with
`internal/domain/eda/module/log` (hand-written schema + `logextract`
generated symbols) and `ModuleRegistry` (Register/Invoke, strict arg
decode, panic recovery via yaegiutil -- no new interpreter-construction
or recovery mechanism). `ModuleDir` config field mirrors `PluginDir`;
wired in bootstrap.go with log-and-abort on load failure.
Playbook YAML action dispatch is **deliberately out of this slice**: a
minimal 'run this one module action, no chaining' dispatch still requires
the parent doc's data-flow mechanism (now resolved: CEL expressions
over an evaluation context -- see eda-playbook-engine.md's resolved open
question 1) and what the result feeds. Dispatch is a follow-up ticket
that lands once the coordinator exists, and it will consume this
registry as-is.
## Open questions
1. **Discovery convention.** Does a Module kind's implementation file need
to declare its kind name explicitly (frontmatter-style, like a skill's
`metadata.archie.workflow`) or is the kind inferred from directory/file
naming (`module/notify/impl.go` implies kind `notify`)? Follow the
skill catalogue's existing declared-metadata convention unless there's a
reason not to -- not decided here.
2. **Where schema source files live.** This doc assumes
`internal/domain/eda/module/<kind>/types.go` per kind, but the exact
package layout (one package per kind vs. one package with per-kind
subtypes) should be confirmed against `organisation.md`'s file-layout
rule before the first slice starts.
3. **Result surfacing.** A Module's `Result` needs to reach later actions
in the same playbook once data-flow is designed -- resolved in the
parent doc as CEL expressions over `actions.<id>.result.<field>` (see
eda-playbook-engine.md's resolved open question 1); the `map[string]any`
result shape above is what the evaluation context exposes, so it stays
compatible by construction.
-140
View File
@@ -1,140 +0,0 @@
# Multi-action playbooks and typed action results
**Status:** Approved
**Date:** 2026-09-22
**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`
**Beads issue:** `archie-core-nx30` (unblocks `archie-core-t2db.27` and `archie-core-t2db.31`)
## Why this exists
`eda-playbook-engine.md`'s hard boundary rejects any playbook that is not
exactly one `workflow` action, so the parent document's data-flow, Module and
Channel/Forge decisions have no loadable shape to attach to. The boundary's own
stated condition is now met: both execution-time gaps are resolved
(`eda-playbook-engine.md`, "Execution-time gaps"; the `playbook_dispatches`
ledger). This document designs the relaxation.
## A playbook is one of two shapes
- A **workflow playbook** is exactly one `workflow` action. Unchanged: it names
a workflow definition and is routed by the daemon's definition pin.
- An **action playbook** is one or more `module` actions in order. Each action
has an optional `id`, a `kind` naming a registered Module kind, `args`, and an
optional `when`.
One playbook does not mix the two shapes.
```yaml
trigger: { kind: bug }
actions:
- id: build
position: module
kind: log
args: { message: '"build started"' }
- id: done
position: module
kind: log
args: { message: '"done: " + string(actions.build.result.written)' }
when: actions.build.result.written == true
```
The first Module kind is the side-effect-free `log` kind
(`module-position.md`, "Recommended first slice"). A Module kind with an
external side effect, and the Channel and Forge positions, are out of scope.
## A result type is the kind's generated Result struct
Each Module kind owns a hand-written `Args` and `Result` struct
(`internal/domain/eda/module/log` is the worked example); `ModuleRegistry.Invoke`
returns the result as a flat `map[string]any`. `ModuleRegistry.DecodeResult`
(`internal/domain/eda/module`) is the single site that converts that map into
the kind's `Result` struct before a later expression reads it, so the value the
checker validates and the value the run reads have one definition.
`actions.<id>` is typed by the kind of the action that declares `<id>`:
`{ result: <KindResult> }`. `event` stays `dyn` (J4,
`playbook-expression-syntax.md`).
## Reject-at-load, preserved
Relaxing the boundary must not make a bad reference resolvable. The load fails,
naming the playbook and the offending action, for:
- an `id` missing where a later action references it, duplicated, or outside
its shape's grammar: a workflow action id keeps the shared
stable-identifier grammar (J1, already enforced), while a module action id
must be a lowercase CEL field name writable as `actions.<id>` (so a CEL
keyword such as `in`, `true`, `false`, or `null` is rejected at load);
- an `actions.<id>` read of an id no earlier action declares;
- an `actions` read that is not statically resolvable to an id (any map index,
literal or dynamic, `in`, a comprehension): the typed `actions` root is an
object type, so only field selection `actions.<id>` resolves and the
`actions["id"]` spelling is not accepted;
- a `result` field the referenced kind's `Result` does not define;
- a reference to an earlier action that produces no result;
- an unknown `position`, an unknown `kind`, or a `module` action with no `kind`;
- a field belonging to the other shape (`kind` on a `workflow` action, or
`workflow` on a `module` action);
- an arg KEY the kind's `Args` schema does not define;
- an arg value whose checked CEL type cannot fill its `Args` field (`'123'`
for a string field). A `dyn` value, such as an `event` read, passes: its
type is known only per event, and the module decode refuses a bad one at
run.
Declaring the kind's `Result` schema to CEL at load makes a result-field typo a
load failure rather than a dispatch failure. Matching arg keys against the
kind's `Args` schema makes an arg-key typo or a wrongly typed value a load
failure.
## The environment is per playbook
Result typing depends on the ids a playbook declares and the kind each id runs,
so the CEL environment is built from one playbook's action list rather than once
per `Store`, and `expr.NewEnv` takes that list: each declared id becomes a field
of the `actions` object typed by its kind's `Result`.
## Running an action playbook is out of scope
This document makes an action playbook load and its references type-check.
Running one is designed in `docs/prds/action-playbook-run.md`.
## Decisions
**D1 — dispatch before `t2db.31`.** Superseded by
`docs/prds/action-playbook-run.md`. Was: an action playbook loads and
validates but is not routed; the definition-pin dispatch reports no match for it,
and the daemon logs a visible warning naming it.
**D2 — mixing positions.** Settled: one shape per playbook. A `workflow` action
yields a task, not a result, so it cannot feed `actions.<id>.result`.
**D3 — the CEL typing mechanism.** Settled: a per-playbook environment whose
`actions` root is an object type with one field per declared id, each field typed
by the kind's `Result` struct. `internal/domain/eda/expr` implements it with the
generic `actionResultProvider`.
**D4 — `args` against the kind's `Args` schema.** Settled: keys and statically
typed values are checked at load; `dyn` values are checked by the module decode.
**D5 — where the result map becomes the `Result` struct.** Settled:
`ModuleRegistry` stays schema-agnostic. `ModuleRegistry.DecodeResult`
(`internal/domain/eda/module`) is the conversion site. It accepts a value only
when it already carries the field's declared type, and a map only when it
carries every declared field. A conversion changes the value's representation --
a number for a string field is the named case -- and an absent field reads as the
zero value, so each is reported rather than becoming a quietly wrong value in a
later expression.
## Verification
- A two-action `module` playbook with a valid `actions.<id>.result.<field>` read
loads; the same read of a field the kind's `Result` does not define fails the
load naming the field; a read of an id no earlier action declares fails; a
dynamically indexed `actions` read fails.
- An arg KEY the kind's `Args` schema does not define fails the load, and so
does `message: '123'` for the `log` kind. `message: event.title` loads.
- A result map missing a declared field, and one whose value is not already the
field's type, are both reported by the decode; a value that would only be
convertible (a number for a string field) is not accepted.
- The one-action `workflow` playbook shape, its dispatch, and its existing
load-time checks are unchanged.
-64
View File
@@ -1,64 +0,0 @@
# Public news and per-version release notes
**Status:** Approved
**Date:** 2026-09-21
**Beads issue:** `archie-core-2ncm.2`
**Superseded in part:** `docs/prds/release-stream-and-commit-rules.md` defines the
single release stream. `CHANGELOG.md` carries every release and one `vX.Y.Z` tag
names each release.
The Astro website renders public news and per-version release notes from the
artifacts generated here. Both derive from `CHANGELOG.md`, so publishing a
release adds no writing.
## Source of truth
Release notes come from the frozen sections in `CHANGELOG.md`:
`tools/release.sh --prepare` writes a section, and `--tag` refuses to tag a
version without it. The generated artifact has one entry per release version.
Tags and raw commits are not the source. The changelog is the edited release
record, and its `## [<version>] - <date>` headings provide the version and date.
## Release data
The generator skips `## [Unreleased]`. Any other `## [` heading that is not
`[version] - date` stops generation. A relative Markdown link in a changelog
body also stops generation because the Astro site must be able to render the
content without depending on repository-relative paths.
`archied` and `archie-agent` version independently. Each
`docs/news/releases.json` entry carries the tag prefix (`archied`, `archie`),
product name (`archied`, `archie-agent`), version, date, and changelog body.
`docs/news/redirects.json` maps retired per-component news URLs to each unified
release route. The Astro site must apply this table so previously published
release URLs continue to resolve.
Both JSON files are committed generated artifacts. `task news` regenerates
them, `task news:check` detects drift, and `tools/release.sh --tag` regenerates
and stages them with the release commit. The Astro site renders from these
artifacts rather than re-parsing `CHANGELOG.md`.
## Site ownership
The Astro website is maintained outside this repository and serves the
documentation at `offloaded.dev/docs/`. This repository generates and validates
the news and documentation data artifacts; it does not build, preview, or
deploy the Astro site.
## Not in scope
- Generated summaries, categories, or section headings; the changelog has no
structured summary field to derive one from.
- Per-release download or install links; where to get the artifacts is
documented once, not restated for every release.
- Hand-written news items.
- Changes to `infra/ansible` or to the external Astro website repository.
## Verification
- `go test ./tools/newsgen/...` covers parsing, ordering, artifact generation,
heading and link refusals, and check-mode drift.
- `task news:check` passes inside `task check`.
- `task docs:artifact:check` verifies the generated documentation data against
its Markdown sources.
-267
View File
@@ -1,267 +0,0 @@
# Orgs, workspaces and access control
**Status:** Approved
**Date:** 2026-09-24
**Parent:** `docs/prds/event-automation.md`, epic `archie-core-t2db`
## Why this exists
Archie has no tenant boundary and no access control: one operator, one shared
token, and no org on any record. The event automation design needs orgs to own
sources, bindings, workflows and agents, and an agent's reach must be decided
by the policies over it, never by the event that started it.
## Concepts
- **Org.** The tenant boundary. An instance admin creates an org and adds its
first owner. An owner or admin adds further members by the sign-in
provider's subject or email.
- **Workspace.** A division of an org, named freely (`networking-prd`,
`service-desk-dev`), with an optional `environment` attribute (any string)
that policies can test. Sources, event types, mappings, bindings and runs
belong to a workspace.
- **Identity.** Every principal is an identity (`internal/domain/identity`):
- a person is an identity of kind `user`, bound to the sign-in provider
through the existing subject binding;
- an agent is an identity of kind `bot` or `service_account`, assigned to
one org and granted access, secrets and permissions the way a user is.
Signing in and verifying credentials stay separate from identity; identity
is who acts. Memberships, roles, grants and audit records all reference the
identity ID.
- **Instance admin.** Operates the installation: orgs, the sign-in provider,
instance policies. Instance admins see an org's resources only as members
of it.
## What belongs where
| Level | Owns |
| --------- | ---------------------------------------------------------------------------------------------------------------- |
| Instance | the shipped workflow catalogue, instance policies |
| Org | members, identities and their grants, secrets, agent profiles, workspaces, org workflows and their enabled state |
| Workspace | sources, event types, mappings, bindings, runs, captures, run events and logs, chat sessions, memory |
Every owned record carries its `org_id`, and workspace records also carry their
`workspace_id`. An identity, secret or profile is used in a workspace only
after the org grants it to that workspace.
A secret is granted to an identity. An agent profile holds the container
image, tools and network access, and no secrets; this supersedes the secret
references in `event-automation.md`'s agent profiles.
A workflow names the identity it runs as. A workflow called by another runs
as its own identity, and the caller's identity must be permitted `run` on it.
## Access decisions
### Where it lives
- `internal/domain/access` owns the policy schema, the action list, how
principals and resources are turned into policy entities, and the
`Authorizer` contract.
- The Cedar implementation, using `github.com/cedar-policy/cedar-go`, lives in
`internal/infrastructure/access`; `internal/app` wires it.
- Exactly two places call the `Authorizer`: the dashboard and API request
path, and dispatch. Every other service verifies a credential and never
evaluates policy.
### The model
- **Principal:** an identity, with its memberships, roles and grants.
- **Resource:** the record acted on, with its workspace and org as parents,
its type, owner and state.
- **Action:** one of `read`, `create`, `update`, `delete`, `approve`, `run`,
`read_logs`, `read_secret`, `manage_members`, `manage_identities`,
`manage_policies`.
- **Context:** the event's signature result, the address it came from, the
time, and the run and step when the principal is an agent.
### The policy chain
```
instance (+ network rules) ─▶ org ─▶ workspace ─▶ identity + workflow ─▶ object
```
- **Instance** policies hold across every org. They include network rules:
which addresses may deliver events to any source on the instance.
- **Object** policies attach to one object (an event source, a secret, an
identity, a binding, a workflow): "only `soc-responder` may read this
secret", "this source accepts events only from 10.20.0.0/16".
- A request is allowed only if every level with policies for it permits it. A
lower level narrows and never widens; a forbid at any level wins; with no
permit the request is denied.
- The shipped role policies mean the org level always has policies, so an
object or workspace policy alone can never grant access.
- Archie ships an instance policy, which no org can remove, forbidding any
principal to act on a resource outside the orgs it belongs to.
### Storing and changing policies
- Policies are stored in the State Store per level, versioned, and every
change is an audit event naming who made it.
- A policy is checked against the current schema when it is saved, and every
stored policy is checked again when archie starts. An invalid org, workspace
or object policy makes its level deny everything and is reported as a health
issue naming the policy and the error. An invalid instance policy stops
archie serving until it is fixed, with the same report.
- A policy change that would leave no owner able to `manage_policies` is
refused.
### Roles
Archie ships these org roles as policies. A member may hold a different role in
each workspace.
| Role | Can |
| --------- | ----------------------------------------------------------------------------------- |
| Owner | everything in the org, including members, identities, policies and deleting the org |
| Admin | everything except deleting the org and changing owners |
| Developer | create and edit workspace resources and org workflows; run workflows; read logs |
| Viewer | read everything except secret values |
### Approvals
What needs approval, and who may give it, is org and workspace policy. Archie
ships one default: arming a binding needs a member other than the one who made
the change, holding the admin or owner role. No policy can let a change approve
itself.
### Denials
- A lookup is filtered by org before any policy check, so a record in another
org is never loaded and is reported as not found, with the same error the
store returns for a record that does not exist.
- A request denied inside the caller's org is reported as forbidden, without
the reason.
- Every denial is recorded with the principal, action, resource, the level
that decided, and the deciding policies. Admins can see this record for
their org; instance admins for instance policies.
### Recovering from a locked-out org
`archied access reset --org <org>` restores the shipped role policies for one
org and removes its other org-level policies; `--instance` does the same for
instance policies. It runs only on the State Store host, never over the
network, and is recorded as an audit event.
## Credentials
### People and services
- The State Store accepts two kinds of credential: the instance service
credential, held by the daemon and Gateway for dispatch and background work
across orgs, with every use attributed; and a principal credential issued to
one identity, from which the State Store derives the org and workspace scope
itself. No request field sets scope.
- A person signs in through the provider or uses a personal API token issued
to their identity. The shared token of a single-operator install
authenticates as the owner of the `default` org.
- If the sign-in provider is unreachable, sign-in fails with a health issue
distinct from a rejected credential, `archied access reset` still works, and
dispatch and running agents are unaffected.
### Agents: decided once, carried as a run credential
1. When a binding dispatches, the orchestrator evaluates the chain for the
workflow's identity: the identity may `run` this workflow in this
workspace, and the workflow and binding are enabled.
2. It issues one run credential holding the org, workspace, run, workflow,
identity, and the capabilities and secrets the identity is granted,
narrowed by the workflow's policy. This single credential replaces the
separate State Store and worktree grants.
3. The State Store, forge RPC, worktree RPC and secret retrieval each verify
every call against the credential and refuse anything outside it, recording
the refusal on the run. None of them evaluates policy. The State Store's
task-scoped calls stay limited to updating, transitioning and adding events
to the credential's own run.
4. The credential lives in the State Store, stored as a digest, so it survives
a restart. It expires at the workflow's timeout plus a margin, is revoked
when the run ends, and credentials of runs that are no longer running are
revoked when archie starts. A run whose credential is refused as unknown is
parked for retry, not failed.
5. Starting an identity is recorded as an audit event: identity, run,
workflow, the binding or member that started it, and the event behind it.
The State Store stamps the actor, principal, org and workspace on every
event from the credential and ignores those fields in the request.
Forge RPC subjects are keyed by the identity's immutable ID, so identities with
the same name in two orgs never share a responder.
## Events and task identity
- The capture receiver is the only place network rules are evaluated. A
refused event is not stored; it is counted on its source with the address it
came from (the most recent addresses only). A source that refuses more
events than it accepts over an hour is reported as a health issue.
- The task idempotency key is `org/identity/owner/repo/number`, produced in one
place. The poller and the webhook receiver both resolve the org and identity
before publishing, so the same issue delivered both ways still gives one
key. The review-comment key follows the same rule. Task uniqueness in the
store uses the same fields.
## Upgrading existing installs
- An install with no sign-in provider has one org, `default`, with one
workspace, `default`, and the local operator as owner.
- The upgrade runs in the State Store first, then in the event store, each
resumable from a recorded version, after a backup of the database. Every
existing record gets the `default` org and workspace, and every existing
identity belongs to the `default` org.
- The State Store refuses scoped calls until its upgrade has finished, rather
than serving records with no org.
- People's identities and memberships live in the State Store, not the event
store.
## Audit retention
Audit and denial records are kept for a configured number of days. Repeated
identical denials within a minute are stored once with a count. Their size is
shown on the health surface.
## Delivery order
1. Orgs, workspaces, people as identities, memberships, identities assigned to
orgs; `org_id` and `workspace_id` on every owned record; the resumable
`default` upgrade; the new idempotency key.
2. `internal/domain/access` with the chain, shipped roles, the cross-org
forbid and the startup re-check; applied to the dashboard, API and
dispatch; denial records; `archied access reset`.
3. Instance and principal credentials with server-derived scope; personal API
tokens.
4. Identity grants; the run credential replacing both existing grants; audit
on every start.
5. Approval policy with the shipped default.
6. Instance network rules at the capture receiver, and object policies.
7. Org, workspace and object policy editing.
## Out of scope
- Self-service org sign-up, billing and quotas.
- Groups or teams as principals.
- Agents acting with the permissions of the person who triggered an event.
## Verification
- A member of org A reading an org B record by ID gets the store's ordinary
not-found error, and org B records never appear in org A's lists.
- A workspace policy permitting what its org forbids has no effect.
- A developer can create a binding and cannot approve it; an admin can.
- A policy naming an unknown attribute is refused when saved; a stored policy
that became invalid after an upgrade denies its level and shows as a health
issue.
- A policy change leaving no owner with `manage_policies` is refused, and
`archied access reset --org` restores access for a locked-out org.
- An identity not granted `secret:firewall-api` cannot retrieve it, and the
refusal is on its run.
- A run keeps working across a State Store restart, and a crashed run's
credential is revoked at the next start.
- Every run shows the identity it started and what started it.
- An instance network rule refuses an event from outside its range for every
org, and the refusal is counted on the source.
- An object policy on a secret narrows which identities can read it.
- A policy forbidding `run` where `environment` is `production` applies to
every such workspace.
- The same issue delivered by webhook and by poll produces one task.
- A single-operator install upgrades with every record in `default` and works
unchanged; an interrupted upgrade resumes.
-165
View File
@@ -1,165 +0,0 @@
# Payload field mapping -- decision
**Status:** Approved
**Date:** 2026-08-22
**Beads issue:** `archie-core-t2db.3`, depends on `t2db.1`, blocks `t2db.4`
Answers what a "mapping" is, where it lives, and what "resolve against a
real event" means precisely enough to implement. `t2db.4` (binding: matcher
- mapping + workflow) is out of scope -- this bead ships the mapping
concept and its preview only, as a standalone entity `t2db.4` will later
reference by ID.
## Decision: a new `internal/domain/mapping` package, SQLite storage
> Storage superseded: every store now lives in PostgreSQL behind
> `internal/domain/storecontract`, implemented in `internal/infrastructure/postgres`
> (`docs/prds/state-store-contract.md`). SQLite names below describe the
> original design.
`internal/domain/mapping` owns the mapping vocabulary and the pure
resolve/preview rule; `internal/store` persists it (mirrors
`captures.go`'s shape exactly -- inline schema const, narrow store
interface, `*store.Store` implementation); `internal/webui/api_mapping.go`
is the transport. This follows `docs/prds/event-capture-storage.md`'s own
placement precedent: `internal/store` is where this daemon's persistence
already lives, not `internal/infrastructure` (that layer holds
cross-domain services -- config, eventbus, modelcatalog -- not this
daemon's primary store).
### Why a domain package and not just a store table
Resolving a path against a payload and deciding "missing vs null vs
type-changed" is a rule, not a query -- CLAUDE.md's domain layer owns
"language, state, rules, operations" precisely so this logic is testable
without a database and reusable by `t2db.4`'s runtime trigger path without
either package importing the other's transport concerns.
## Mapping shape
```go
type Mapping struct {
ID int64
Name string
SourceHint string // free-text label (e.g. "sentry"), organisational only -- not enforced against Capture.Source
Fields []Field
CreatedAt time.Time
UpdatedAt time.Time
}
type Field struct {
Name string // the name the workflow receives
Path string // dot/bracket path into the payload, see below
Type FieldType // expected type, checked at resolve time
Required bool // Required=false + missing is not a failure; Required=false + wrong type still is
}
type FieldType string // "string" | "number" | "bool" | "object" | "array" | "any"
```
`SourceHint` is advisory only: an operator authors a mapping by clicking
through one example capture, but the mapping is not pinned to that
capture's exact source string, because `t2db.4`'s matcher (not this bead)
decides which events a binding applies to. Pinning here would duplicate
that decision in the wrong layer.
## Path syntax
Dot-separated keys with `[N]` for array indices: `data.items[0].id`. No
wildcards, no filters, no external library -- the grammar is exactly what a
click-through UI needs to express (this key, then this key, then this
index), and every path in a mapping was generated by clicking a value in a
real payload, never hand-written against a spec. A hand-rolled parser
(~30 lines: split on `.`, strip `[N]` suffixes) is less risk than a new
dependency for a grammar this small.
## Resolve semantics (the preview AND the future runtime path)
```go
func Resolve(fields []Field, payload []byte) (values map[string]any, failures []Failure)
type Failure struct {
FieldName string
Path string
Reason string // "missing" | "null" | "type_mismatch"
}
```
Decode with `json.Decoder.UseNumber()` (matches `webhookguard.RedactPayload`'s
existing convention) so int/float distinction survives for type checking.
Walk each field's path independently -- one field's failure does not stop
resolution of the others, because the whole point of preview is showing
the operator every problem at once, not the first one.
- Path segment doesn't exist, or indexes past an array's length -> `missing`
- Path resolves to JSON `null` -> `null`
- Path resolves to a value whose JSON type doesn't match `Field.Type`
(`"any"` always matches) -> `type_mismatch`
- `Required: false` suppresses `missing` only, never `null` or
`type_mismatch` -- a field that's present but the wrong shape is always
worth surfacing, since silently coercing it is exactly the "agent
confabulates around a blank field" failure this bead exists to prevent.
**This is the same function both consumers use.** `t2db.3`'s preview calls
it against an operator-picked capture and renders every result, pass or
fail, in the UI -- that satisfies this bead's "fail loudly" acceptance
criterion, because at this stage the only runtime consumer of a mapping
_is_ the human previewing it. `t2db.4` will call the identical function
when a live event triggers a binding and turn any non-empty `failures` into
a visible operator-facing failure (park the task / surface in the
inspector) instead of starting a workflow with blank fields -- that wiring
is `t2db.4`'s job, not duplicated here.
## Storage
The `mappings` table: `id, name,
source_hint, fields_json, created_at, updated_at`. `fields_json` is the
`[]Field` slice JSON-encoded into one column -- fields have no independent
query need (nothing filters "mappings with a field named X"), so a
join table would be structure with no consumer, the same failure mode
`organisation.md` bans for empty layering.
`MappingStore` interface (narrow, mirrors `CaptureStore`):
`InsertMapping`, `ListMappings`, `GetMapping`, `UpdateMapping`,
`DeleteMapping`.
## HTTP surface
All under `/api/mappings`, token-gated like every other `/api/*` route (no
bypass -- unlike capture, nothing here accepts unauthenticated input):
- `GET /api/mappings` / `POST /api/mappings` -- list / create
- `GET|PATCH|DELETE /api/mappings/{id}`
- `POST /api/mappings/preview` -- body `{fields: []Field, capture_id:
int64}`, calls `mapping.Resolve` against that capture's stored (already
redacted) `Body` and returns `{values, failures}`. Deliberately takes
loose `fields` rather than a saved mapping ID, so an operator can iterate
before saving anything -- "never ship a mapping the operator has not seen
resolve against real data" requires preview to work pre-save.
Preview resolves against `CapturedEvent.Body`, which is already
redaction-passed (`webhookguard.RedactPayload`, per
`event-capture-storage.md`) -- a mapped field pointing at a
sensitive-keyed path previews as the literal string `"[redacted]"`, not the
real value. This is accepted, not fixed here: it is the stored ground
truth, the same payload `t2db.4`'s runtime path will resolve against, and a
preview mismatch would be worse than an honest one.
## Frontend
New `ui/src/mappings/` feature folder, same three-file split as
`ui/src/captures/`: `mappings.js` (page: list, fetch, create/edit flow),
`mapping-editor.js` (pure, unit-testable: renders a captured payload as a
clickable tree -- clicking a leaf appends a field row with `Path`
pre-filled -- plus the field table and preview-result rendering),
`mappings.css`. Creating a mapping starts from an existing captured event
(reuses `api.captures`), so the editor always has a real payload to click
through and preview against, never a blank form.
## What this does not decide
The binding entity, its matcher, its draft/pending_approval/armed state
machine, and turning a runtime `Resolve` failure into a parked task are
`t2db.4`. Per-source HMAC secret registration is `t2db.5`. This bead ships
the mapping concept, its storage, and its preview only.
-257
View File
@@ -1,257 +0,0 @@
# Playbook data-flow and condition syntax
**Status:** Approved
**Date:** 2026-09-03
**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`
**Beads issue:** `archie-core-t2db.14` (expression environment).
**Decision:** CEL via `cel.dev/cel-go` (v0.32.0), pinned. One expression
mechanism covers both an action's `when` condition and its `args` values.
## The requirement, stated directly
A playbook action is gated and parametrised by runtime data: (a) a condition
deciding whether the action runs; (b) a later action's `args` values referencing
an earlier action's `Result` and the triggering event's fields. Both are **CEL
expressions**, evaluated against one evaluation context. There is no separate
interpolation syntax: CEL reads nested maps and fields natively, so `args`
values that need data are written as CEL, and only plain literal args remain
plain YAML scalars.
Both halves are read-only: expressions may read context values and compute a
result from them, never mutate, never call host functions, never perform I/O.
CEL enforces this structurally (no side effects, linear evaluation when macros
are bounded, cost-limited).
```yaml
actions:
- id: build
position: module
kind: log
args:
message: '"build finished"' # literal
when: 'event.label == "bugfix"' # gate on event field
- position: module
kind: log
args:
message: '"done: " + string(actions.build.result.written)'
when: "actions.build.result.written == true"
```
## Trust boundary of the expression
A playbook YAML is **operator-installed, in-process, daemon-privileged** -- the
same tier as `ModuleDir`/`PluginDir`/`SecretEngineDir` (module-position.md's
trust-boundary section): loaded from a configured directory at startup, never
from a webhook body or task worktree. The schema-by-example flow uses live
events to _design against_; the saved playbook is operator-authored file content
in an operator-configured location.
Two consequences:
1. The expression string is **trusted**. Operator-authored config, not attacker
input; no sandboxing against a hostile expression string is required. If a
future playbook source is less trusted (auto-generated bindings from
unauthenticated captures), that is the playbook-file trust tier moving -- the
loader's acceptance check is the right place, not the evaluator.
2. The **data the expression reads is NOT trusted** (decoded webhook body, prior
results through the same pipeline). Robustness against hostile data is
required: no panic on wrong-typed/missing fields, no unbounded cost on
deep/cyclic maps, bounded evaluation time. CEL provides this structurally
(cost limits, linear non-Turing-complete evaluation, error values instead of
panics -- verified in the vetting record below).
## The gate precedent is deliberately NOT copied
`internal/gate/gateeval` evaluates arbitrary interpreted Go (`.archie/gate.go`)
as the repo's conditional-logic precedent. That is the wrong precedent for
playbook conditions because this document's premise is: **YAML is pure
orchestration data; Yaegi is where imperative logic lives** (Problem section;
module-position.md's "no generic hook" section). Yaegi snippets in YAML would
move imperative logic into the data layer -- the inversion this design exists to
prevent -- and make playbooks un-lintable.
The line: conditions are **declarative predicates over runtime data, not
programs**. CEL is non-Turing-complete and side-effect-free, so it cannot become
a program; a condition that needs real logic gets a Module kind (Yaegi),
referenced by the action, not a stronger expression body.
## Plugin-engine-rule interaction
The plugin engine rule forbids a generic `Module` interface with an `any`
payload; it exists to keep static implementation contracts typed. Evaluating CEL
against runtime `map[string]any` is **not the same problem**: the rule concerns
_implementation contracts_ (static operations a capability family exposes), not
_runtime data values_ (legitimately dynamic -- an event payload's shape is
unknown until it arrives). The Module contract stays fully typed (generated
`Args`/`Result` schemas); CEL is a read-only data reader under the playbook
engine family, not a new capability contract. Stated once.
## Minimum viable evaluation context (what expressions see)
One flat context, namespaced from the playbook run, built at dispatch time:
| Name | Type | Source |
| --------- | ------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `event` | `map(string, dyn)` | The triggering event's decoded payload (webhook body / forge issue / schedule tick). Field access via `event.<field>`, map access via `event["field"]`, presence via `has(event.<field>)`. |
| `actions` | per-playbook object type | Previous actions' results, one field per declared action `id` (`actions.<id>`), each field typed `{ result: <KindResult> }` so a later action reads an earlier one's `Result` struct (`actions.<id>.result.<field>`) with field-level checking. The current action and later actions are not present. |
Expressions may also read literal-only state (numbers, strings, booleans)
directly. CEL's `has()` macro covers the missing-key case (`has(event.labels)`
-> bool), which replaces any bespoke `has`/ `contains` operator.
`actions.<id>.result` is the kind's hand-written `Result` struct:
`ModuleRegistry.DecodeResult` converts `Module.Invoke`'s flat `map[string]any`
(`archie-core-t2db.13`) back into that struct before a later expression reads
it, so the checker and the run read the same typed value.
Judgement call J1: `action` id is a required field on every action that later
actions reference; ids are validated at load (unique, stable-identifier-shaped),
and a `when`/`args` expression referencing an unknown `actions.<id>` is a **load
failure**, not a runtime miss -- the same reject-at-load rule as collisions (see
below).
## Load-time validation (consistent with the collision rule)
The collision-handling rule is: schema defines the accepted message; anything
outside it is rejected at load, logged plainly, reported to the caller -- never
deferred to runtime. Expressions are validated the same way, at playbook load:
- **Syntax**: every `when` and every CEL-typed `args` value is parsed and
checked by CEL's checker when the playbook is loaded. A syntax or type error
is a reported load failure (the playbook is dropped and the error goes to the
caller), not a runtime surprise.
- **Context conformance**: with the context declared to CEL (`event` as
`map(string, dyn)`, `actions` as a per-playbook object type with one typed
field per declared id), unknown top-level identifiers are rejected at compile
time. Field-level typing inside `dyn` values is deferred to runtime by CEL's
design (verified: `data.items.lenght` with `data` dyn compiles clean and
errors at eval) -- so the loader declares as much type as the schema provides
(the action kinds' generated `Result` structs become CEL type declarations at
load, giving field-level rejection for result reads), and `event` stays `dyn`
because its shape is unknown by design (schema-by-example).
- **Names**: unknown `actions.<id>` references and unknown roots are
compile-time/lint-visible errors (J1).
This means the lint tool and the daemon share one checker -- same single-source
argument as the playbook loaders.
## Candidate comparison
| Candidate | Maintenance | Safety surface | Cost (measured) | Verdict |
| ------------------------ | -------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------ |
| **CEL (cel.dev/cel-go)** | Actively maintained (google/cel, monthly releases) | Non-Turing-complete, linear eval, `CostLimit`/`CostTracking`/`ParserRecursionLimit`, no side effects, error values not panics | **+13.0MB** (2.34MB -> 15.25MB) | **Chosen** |
| `expr-lang/expr` v1.17.8 | Actively maintained | Side-effect-free, `DisableAllBuiltins`, depth limits (CVE fixed w/ tests) | +3.9MB (2.34MB -> 6.28MB) | Not chosen: two safety CVEs this cycle; smaller ecosystem; no protobuf/type-model fit with future schema-gen |
| `gval` v1.2.3 | Maintained, slower | No builtin-restriction surface; extras (ternary/`??`) not wanted | +3.0MB (2 transitive deps) | Not chosen |
| `govaluate` | **ARCHIVED** (author archived 2024) | n/a | n/a | Not chosen: dead |
| `starlark-go` | Maintained (Bazel) | Turing-complete with step limits | large (full language) | Not chosen: whole-language surface |
## Vetting record
Source reviewed at HEAD:
- **Repo hygiene**: clean. No binaries/media in tree (the only non-source
artifacts are expected generated protobuf files); 16-line `.gitignore`.
- **Hard-boundary correctness**: the place correctness is hard for an expression
evaluator is bounding evaluation and surviving hostile input. Dedicated
regression tests exist and pass at HEAD: `TestCostLimit`, `TestCostTracking*`,
`TestParserRecursionLimit`, and a large conformance suite. Verified by
execution: evaluation against a 2000-deep nested map under `CostLimit`
completes in ~10 microseconds and returns an error value for a missing key --
no panic, no unbounded walk.
- **Dependency footprint**: antlr (parser), protobuf + genproto (CEL's type
model), `cel.dev/expr` (CEL spec types), yaml.v3. All mainstream, canonical,
vendored widely by Google-adjacent projects. No runtime-impure third-party
code; the REPL-only deps (readline, tview, tcell) are not in the library
import graph.
- **Security record**: no advisories on record for `cel.dev/cel-go` (GitHub
Advisory Database).
- **Module path**: migrated to `cel.dev/cel-go` (v0.32.0 is current); the old
`cel.dev/cel-go/cel` path is the pre-migration identity. Pin `cel.dev/cel-go`.
- **Binary size cost**: +13.0MB is the largest of the candidates (measured:
baseline 2.34MB -> 15.25MB with CEL). Accepted because: the daemon already
embeds a large Yaegi runtime; CEL's type model is the load-bearing win
(compile-time rejection of result-path typos, matching the reject-at-load
rule); and the alternative bespoke grammar would re-implement CEL's checker to
get the same guarantee. Flagged for sign-off: if 13MB is unacceptable for a
specific deployment target, the fallback is a bespoke grammar with a
re-implemented subset of this checker -- a strictly worse trade.
## Why bespoke was not sufficient
A bespoke grammar for the shipped cases (path read + comparison + bool
composition) is small, but the load-time-validation requirement makes the
comparison: the reject-at-load rule requires _field-level_ static checking of
result paths against generated `Result` schemas, which is CEL's type-checker's
job. Re-implementing that on a hand-rolled grammar means re-implementing a type
system -- more code than the grammar itself, with worse diagnostics, no
conformance suite, and no community surface for future expression needs (even
declarative ones). The bespoke option only wins on binary size, and the size
cost of CEL is measured and bounded.
## Judgement calls (flagged for sign-off)
- **J1 -- `id` required on referenced actions, unknown id = load failure.**
Matches the reject-at-load rule. Alternative considered: an alternative is
positional `actions[0]` access, which breaks on reorder; named is the
operator-friendlier shape.
- **J2 -- every `args` value is evaluated as a CEL expression.** No split
between "literal args" and "expression args": a plain string value is a CEL
string literal, a number is a CEL number literal, and any value that reads
context data is written in CEL. One mechanism, no interpolation marker, no
second syntax to learn. Alternative considered: cEL string literals must be
quoted inside YAML (e.g. `message: '"build finished"'`), which is slightly
noisy for mostly-literal args; accepted for uniformity -- the linter catches
quoting mistakes at load.
- **J3 -- condition failure semantics.** A condition that errors at runtime
(missing/wrong-typed field) evaluates to **false**: the action is skipped,
logged, run continues. This is the simplest candidate consistent with gap 1's
bias against clever recovery; gap 1 (`archie-core-t2db.18`) commits
stop-on-first-failure, so per-action control is not coming and J3 stands.
Alternative considered: cEL separates false from error; we treat evaluation
error as false + log.
- **J4 -- `event` stays `dyn` (schema-by-example).** Load-time we cannot know
event field types; declaring them typed would reject valid plays. Result reads
get field-level checking via generated schema declarations. Alternative
considered: when schema-by-example ships, tighten event field declarations
from captured samples.
- **J5 -- cost limit default.** A `CostLimit` at load time (e.g. 100,000) is
applied to every expression; the linter and daemon use the same value so they
agree. Alternative considered: exact number is a constant to tune at first
use.
- **J6 -- `args` failure semantics.** An `args` value that cannot be evaluated
aborts its playbook run: the action and every later action in that playbook do
not run, because data has no false value to fall back on and an action run
without its arguments is a silent one. Other playbooks matching the same event
still run, and the task is unaffected: a playbook run never changes routing.
The daemon log reports the failure, naming the task, the playbook and the
action; no task event is written. Alternative considered: mirroring J3,
rejected because a predicate has a meaningful false and data does not.
## Interaction with the execution-time gaps
This resolution does not resolve the execution-time gaps (both are resolved
separately: gap 1 by `archie-core-t2db.18`, gap 2 by the gap-2 decision).
Conditions make gap 1 concrete (condition-failure vs. action-failure semantics,
J3) and CEL's read-only result access makes gap 2's keying derivation readable
(an idempotency key expression can read event fields) -- both flagged as the
gaps' first real exercise. Gap 2's exercise is subsequently solved by that
decision: the answer is a fixed structural derivation, and idempotency keys are
deliberately NOT CEL expressions (see the "No CEL in the key" passage).
## Implementation placement (for the follow-up slice)
- New `internal/domain/eda/expr` package: builds the CEL environment (context
declarations, generated `Result` schema types as CEL type declarations, cost
limit), compiles/validates playbook expressions at load, evaluates them at
dispatch. Domain layer; no infrastructure imports; owned by the playbook
engine family. One new dependency: `cel.dev/cel-go` (pinned), `go.mod`
otherwise unchanged.
- Consumption: the playbook event coordinator (open question 4's loader)
evaluates `when` before dispatch and evaluates `args` values before
`Module.Invoke`; the lint tool (`archie-core-t2db.12`) shares the same
compile/validate path for author-time diagnostics.
- Schema integration: action kinds' generated `Result`/`Args` structs
(`archie-core-t2db.13`'s `logextract` pattern) are declared to CEL at load so
`actions.<id>.result.<field>` type-checks; `args` expressions type-check
against the target kind's `Args` schema before the playbook is accepted.
-134
View File
@@ -1,134 +0,0 @@
# Plugin settings reconcile live
**Status:** Draft
**Revision:** 2
**Tracking:** GitHub [#1154](https://github.com/samcharles93/archie-core/issues/1154), epic [#998](https://github.com/samcharles93/archie-core/issues/998)
**Authority:** `docs/prds/runtime-control-plane.md` decides each feature owns how
its changes take effect; `docs/architecture/plugins-and-extensions.md` owns the
plugin engine rule; `docs/prds/control-plane-apply-status.md` owns where apply
reports go.
## Outcome
An operator drops a plugin, module or secret-engine file into a configured
directory while archied runs, and the daemon loads it without a restart. An
edit to an installed file replaces what is running. A delete never stops running
code; apply status says so. A stored `plugin-settings` change applies live for
`plugin_dir`, `module_dir` and `secret_engine_dir`; a change to `skills_dir` is
refused.
## Triggers
`PluginSettingsKind` joins `runtimeResourceKinds` in
`internal/app/archied/control_plane.go`, and its descriptor `ApplyMode` becomes
`live` in `internal/app/controlplane/operational_settings.go`.
A poller reconciles on the apply-status restamp interval, so a dropped file
loads without a filesystem watch. Each tick re-runs both halves the boot path
runs, against the directories in the running config: the directory loads
(`secret.Registry.LoadDir`, `ModuleRegistry.Register`, `plugin.LoadDir`) and the
layering (`boot.runtimeConfig`), which re-resolves provider credentials. A
provider disabled at boot for an unresolvable engine is re-resolved on the first
tick that finds it; a changed directory retargets the next tick without a
restart.
## Rules
- Adding and changing load; removing never unloads. Yaegi interpreters are not
reclaimed while a caller still exists and there is no unload path; the running
set can only grow. A removal stays outstanding in the apply-status error until
the process restarts.
- Each file is loaded through a fresh interpreter (the boot pattern) and
content-hashed, so only new and changed files load.
- A file that fails to load is skipped and reported; already-running code keeps
running, the degrade-and-skip convention `plugin.LoadDir` and
`Registry.LoadDir` already apply at boot. Boot keeps its reject-at-load rule
for the module directory; a broken file at runtime skips without aborting.
- A directory that does not exist reconciles to an empty set.
## The three registries
- **Secret engines** (`internal/secret`). Reconciliation re-runs
`Registry.LoadDir` against the live directory. `Register` replaces by name, so
an edited engine takes effect for the next resolution and a dropped engine
resolves on the next tick. A deleted engine stays registered: existing
references keep resolving through it until restart. Engines are stateless
resolvers, so a swap needs no lifecycle step.
- **Modules** (`internal/domain/eda/module`). Reconciliation re-runs
`ModuleRegistry.Register` for the kind's file. Playbook dispatch resolves
through the registry at invoke time, so the swap reaches a running playbook
store unchanged; a deleted file leaves the old invoker in place, running.
- **Plugins** (`internal/plugin`). `Host` grows running-state operations beside
`Register`, `Start` and `Stop`, and `Register` keeps its rule that
registration is allowed only before the first `Start`, so these are new host
methods rather than a relaxed `Register`. One adds a single module while the
host is running: inserted in dependency order, started alone, and rolled back
alone on failure, leaving every previously started module running. The other
replaces a module whose manifest id matches: stop it, start the new one, and
restart the old one when the new start fails; replacing a module another
running module depends on is refused. A module's `Start` is its only check
(`plugin.Module` has no probe, and one manifest id cannot be registered
twice), so a replacement checks by starting and keeps a rollback rather than
switching first. These operations obey the plugin engine rule: the host
invokes start and stop itself and isolates the failure to one module. A
deleted file makes no host call: the module runs on.
## `skills_dir`
`skills_dir` is not part of this change. The daemon refuses a `plugin-settings`
document whose `skills_dir` differs from the value in force. The check is a
pre-layer comparison on the live path (`boot.applyRuntimeResourceUpdate` in
`internal/app/archied/control_plane.go`), not an addition to
`validatePluginSettings` in `internal/app/controlplane/operational_settings.go`,
which stays value-agnostic per the #1143 decision recorded there: a
change-immutability rule needs the running config, and #1143's validates-nothing
still holds for values. The write lands, the store keeps the version, the daemon
publishes nothing, the refusal is reported against that stored version, and
last-known-good keeps running.
The layering assigns all four directories from one document, so a refused
`skills_dir` refuses the whole document and the other kinds still layer. That is
acceptable: `skills_dir` is the one field with no live consumer, a
whole-document refusal is the honest signal that none of it took effect, and an
operator changing `skills_dir` alongside another directory writes the two
changes separately.
## Apply status
One record per process: `archied` on `plugin-settings`, reported against the
version the process is running. The record's error field carries the outstanding
problem: a deleted file still running, a file that failed to load, the directory
failing to read, or a refused replace of a module another running module depends
on. A clean reconciliation clears the error. An add that succeeded is live even
while a removal is outstanding, and the error says so rather than showing the
kind as restart-required.
`ApplyMode` becomes `live`, so `RestartPendingBanner` no longer names
`plugin-settings`. The gateway's lag is shown instead by the per-process
applied-version rows on the Plugins page, which read the state
`applyStatusForKind` derives from `applied_version < storedVersion` in
`ui/src/stores/control-plane.ts`; that derivation is independent of
`ApplyMode`.
`archie-gateway` layers the `plugin-settings` document at boot through
`boot.loadRuntimeConfig` and reports it, but never calls `boot.loadPlugins` or
`boot.loadModules` and never reads the four directories, so it loads no plugin,
module or secret engine. With no live watch its row lags the stored version
until restart; that lag is a reporting lag, not a behaviour gap.
## Verification
- A plugin, module and secret-engine file dropped while the daemon runs loads on
the next tick; an unchanged file is not reloaded.
- An edited file replaces the running interpretation; a deleted file leaves the
running code running, with the process's error naming it until restart.
- A `skills_dir` change refuses the document: the store keeps the version, the
record carries that version and the refusal, and the running `skills_dir` is
unchanged.
- A plugin replacement whose new `Start` fails restarts the old module and
reports the failure; a replacement of a depended-on module is refused and the
dependent keeps running.
- A provider disabled at boot for a missing engine resolves again after the
engine file loads and a tick re-layers.
- The gateway reports the last version it layered at boot, loads no directory,
and its lag appears in its applied-version row rather than the restart banner.
-211
View File
@@ -1,211 +0,0 @@
# PR review agent
**Status:** Approved
**Authority:** `docs/architecture/agent-system.md`; supersedes the earlier
reviewer executor and blocking rule.
**Compounds with:** `docs/prds/execution-tree-state-machine.md` (every agent
call is a StepExecution), `docs/prds/external-agent-harness.md` (any agent
step may run on a harness), `docs/prds/inline-review.md` (posting),
`docs/prds/pr-review-remediation.md` (consumes the findings).
## Decision
Archie ships a pull request reviewer as its first end-to-end product. It
reviews any pull request on a watched repository, a PR an operator names, and
archie's own PRs before they open.
The reviewer is a fixed pipeline, not a single agent. The review strategy is
generated per PR: three lens agents propose review dimensions from the PR's
content, one reviewer definition runs once per dimension, and later agents
verify, challenge and combine the findings. Everything that can be computed
is code: diff parsing, clustering, blast radius, evidence extraction,
scoring, deduplication, line mapping and the review event.
The pipeline is **recall-first**. It posts every evidenced finding above the
confidence threshold, up to the comment cap. A precision gate exists as an
operator dial and is off by default.
Acceptance is measured, not asserted: see Verification.
## Pipeline
Each numbered phase is a stage of the `pr-review` workflow. Each agent call is
an `agent` StepExecution; fan-out phases record one child per call.
1. **Intake.** Code reads the PR metadata and diff statistics: type,
complexity, languages, areas touched, risk signals. Depth comes from lines
changed: under 100 is `quick` (at most 3 dimensions), under 500 is
`standard` (6), otherwise `deep` (12). An operator may set depth
explicitly.
2. **Anatomy.** Code parses the diff into files and hunks, clusters related
files, and computes the blast radius: unchanged files that import or are
imported by changed files. One agent writes the PR narrative, risk
surfaces, changes that do not fit the narrative, and gaps between the
description and the diff.
3. **Dimension selection.** Three lens agents run in parallel over the intake
(including its machine-written score), anatomy and diff, each able to read
the repository. A PR that intake scores as likely machine-written adds a
hallucination-check dimension: claims, citations and behaviour the diff
does not actually implement.
- **behaviour:** where the old and new code diverge for any input; API
contracts, concurrency and state, security, error handling, data flow;
- **mechanics:** whether the code runs at the language and framework
level; types, signatures and every caller, decorators and middleware,
framework contracts, imports;
- **fit:** patterns, complexity, abstraction, test adequacy, documentation
that no longer matches, dependencies, migration completeness.
Each lens returns review dimensions: a name, a reviewer prompt written for
this PR, target files, context files and a priority. Code merges them,
drops duplicates and keeps the highest-priority dimensions up to the
depth's cap.
4. **Review.** One reviewer definition runs once per dimension, in parallel,
at most 8 at a time. Each reads its target and context files and may
follow references. Each finding carries file, line range, severity
(`critical`, `important`, `suggestion`, `nitpick`), title, body, an
optional suggested fix, quoted evidence, confidence and tags. A reviewer
that exhausts its turn cap or deadline before its terminal tool call
records a distinct StepExecution status from a reviewer that completed
and found nothing; synthesis and the posted review treat the two
differently (the former is unreviewed, the latter is reviewed-clean).
5. **Verification layer**, over the review findings:
- code extracts an evidence package per finding: the code at the cited
lines and snippets from its callers;
- an evidence verifier checks high-priority findings against their
packages;
- an adversary confirms or challenges each finding, looks for issues every
reviewer missed, and is more sceptical when intake scores the PR as
likely machine-written;
- a compound agent looks, within each cluster of confirmed findings, for
defects that only exist in combination.
6. **Coverage and consistency**, in parallel:
- a coverage gate checks every cluster and high-exposure blast-radius file
was reviewed, and runs gap reviewers for what was not, at most 2 rounds;
- consistency verification lists every cross-location obligation the
changed code creates (what must be true elsewhere for this line to be
correct), then verifies each by reading both ends. A broken obligation
becomes a finding.
7. **Synthesis**, code only:
- score = severity weight (1.0, 0.7, 0.3, 0.1) × confidence × multipliers:
compound 1.5, adversary-confirmed 1.3, adversary-challenged 0.5, likely
machine-written PR 1.2, blast radius over 10 files 1.2;
- drop findings under the severity's confidence floor: critical 0.2,
important 0.3, suggestion 0.4, nitpick 0.4;
- merge exact duplicates (file, overlapping lines, category) in code, and
near-duplicates through a small classification call that keeps both
when unsure;
- map lines to the diff's coordinates, sort by score, cap at 25 inline
comments.
8. **Merge gate.** One classification call per finding decides blocking or
advisory: blocking only for broken builds, security, data loss, contract
breaks and regressions. A failed call means advisory.
9. **Output.** One call per comment tightens its wording, running in a
bounded pool at most 8 at a time (matching phase 4), keeping the original
on failure. The review is posted as one forge review with inline
comments. Any blocking finding requests changes; otherwise the review is a
comment. Archie never posts an approval.
## Precision dial
With `review.precision_gate = true`, a post-worthiness pass runs after phase 4
and before the verification layer. It keeps every concrete, evidenced defect
and drops nitpicks, style and unverifiable claims, keeping a finding when
unsure. It trades recall for precision and cuts verification cost by
filtering early.
## Operator approval
With `review.approve_before_post = true`, synthesis ends in
`waiting_human`. The operator chooses which findings to post, rejects the
review, or asks for a re-review with instructions. A re-review reruns phases
3 to 8 with the instructions added to the lens and reviewer prompts, at most
2 times. A review with no findings posts nothing and does not wait. The gate
belongs to the standalone `pr-review` workflow only; archie's own-PR stage list
drops it, because a park there would end an implement run before its PR
exists (`docs/prds/pr-review-operator-response.md`,
"The gate is not reachable from archie's own PRs").
## Isolation
Every agent in the pipeline reads a `.git`-free snapshot of the PR head, with
read-only tools rooted at it, and never the implementer's worktree or
transcript. No pipeline agent holds a forge credential; posting is code.
## Budget
A run has a cost cap and a wall-clock cap, split into per-phase shares. A
phase whose share is spent is skipped and recorded on its StepExecution. The
posted review names every skipped phase, so an exhausted run never reads as a
clean one. A run whose review stage fails posts nothing and
fails.
## Triggers
- **Watched repositories:** a PR opened or updated on a repository with
`review.enabled` starts a run. An update cancels the in-flight run for the
same PR.
- **Operator:** a PR URL from the dashboard or chat starts a run on any
repository the identity can read.
- **Archie's own PRs:** the implement workflow runs the pipeline before
opening its PR. A blocking finding the adversary did not challenge parks
the task with the findings. A pipeline that fails parks the task. Advisory
findings are posted after the PR opens.
## Organisations
The reviewer is a workflow, so `docs/prds/orgs-and-access.md` applies to it
unchanged: it runs as the workflow's identity under the run credential, reads
only repositories that identity may read, and posts through the forge RPC
under that credential. A watched repository belongs to a workspace, and its
PR events start reviews through that workspace's bindings. Findings,
StepExecutions and the posted review carry the run's org and workspace.
## Models
Each agent phase names a model role. Lens, reviewer, verification,
adversary, compound and consistency agents use the review role. Intake,
coverage, dedup, merge gate and polish calls use the classification role.
Either role may run on the built-in runner or a harness.
## Out of scope
- SARIF and standalone report formats. The findings are StepExecution outputs
and the forge review.
- Reviewing a diff without a forge PR.
- Self-consistency reruns.
## Plan
1. Deterministic core: diff parsing, clustering, blast radius, evidence
extraction, scoring, dedup, line mapping, review event. Table-driven tests.
2. The benchmark harness (Verification), run against the deterministic core
with fixture findings.
3. `pr-review` workflow: intake, anatomy, lenses, reviewers, synthesis,
output, with the execution tree recording each call.
4. Verification layer, coverage loop and consistency verification.
5. Merge gate, polish, budget shares and skipped-phase reporting.
6. Benchmark acceptance run.
7. Triggers: operator, watched repositories, archie's own PRs replacing the
single-reviewer stage.
8. Precision dial and operator approval.
## Verification
- **Benchmark acceptance.** On the 38 runnable PRs of the Martian
Code-Review-Bench offline set, one blind run per PR at `deep` with the
review and classification roles on GLM-5.2, and an independent judge
(`anthropic/claude-sonnet-4.6`) matching posted comments to golden
comments: golden micro-recall is at least 0.70. Golden-only precision is
reported alongside it. The run is reproducible from a script in the
repository.
- Scoring, thresholds, dedup and line mapping give identical output for
identical findings.
- A run whose phase share is exhausted posts a review naming the skipped
phase.
- An update to a PR under review cancels the running review and its child
steps.
- No pipeline agent can write to the snapshot, and none can reach a forge
credential.
- Archie's own PR with an unchallenged blocking finding is parked, not
opened.
- Archie never submits an approving review.
-69
View File
@@ -1,69 +0,0 @@
# PR review: the operator's answer to the approval gate
**Status:** Draft
**Authority:** `docs/prds/pr-review-agent.md` ("Operator approval") for the gate, and `docs/prds/state-store-contract.md` (rev. 2e) for every task field that crosses the State Store.
**Compounds with:** `docs/prds/execution-tree-state-machine.md` (a run cannot resume partway through its stage list).
## Decision 1 — where the operator answers
The dashboard's `POST /api/tasks/{id}/action` (`internal/webui/api_tasks.go`, `handleTaskAction`) is the authoritative surface: the only one that resolves the actor from a credential and can carry a payload. Chat is a shortcut, not a second authority — `/approve` (`internal/gateway/gateway.go`, `Router.handleApprove`) answers the post decision with every offered finding selected, and gains no instruction or selection syntax.
`taskstate.Action` gains `rereview`, and `taskstate.Actions` returns `approve`, `reject` and `rereview` for `WaitingHuman`. `approve` posts the review, `reject` discards it through the existing terminal decline, `rereview` reruns the review phases with instructions. The action body carries `instructions`, required by `rereview`, and `findings`, the finding keys `approve` posts; an absent selection means all of them.
The path is `handleTaskAction` → `applyOperatorTaskAction` → `Chat.Contract.ApplyOperatorTaskAction` → the daemon's `LocalChatAdapter` → `taskactions.Client` (NATS `archie.gateway.task-action`) → `taskactions.Service.Apply` → one guarded store write that records the decision and requeues. Chat's `/approve` path (`StoreTaskController.Approve` → `chatTaskControllerAdapter.ApproveChatTask`) must reach that same write through the same function, so the two surfaces cannot record different decisions for one operator intent.
A requeue resumes the workflow the waiting state names, never a name the handler hardcodes. `taskactions.Service.apply` and `chatTaskControllerAdapter.ApproveChatTask` requeue with an empty workflow, which `Requeue` reads as "keep the task's", so neither surface hardcodes a workflow name: an approval whose wait recorded `pr-review` resumes `pr-review`. The feasibility handoff therefore has to name `implement` on the task before it enters the wait, which is the invariant the handler relies on — the workflow a task carries is the workflow it runs next. `Requeue` treats an empty workflow as "keep the task's".
### The review the operator answers
The gate writes the review it is holding onto the task before it ends the run: one JSON column, `review_gate`, a sibling of `review_payload`, holding the scored findings, the head SHA, the pull request's identity and the workflow the wait resumes. The run's existing `Store.Update` persists it. The same column carries the answer back: the response path's guarded write fills in the outcome, the selection and the instructions, and clears the offer for a re-review.
The operator reads the offer through the existing task read — `taskView.Task` on `GET /api/tasks` and `GET /api/tasks/{id}/debug` — so no new read endpoint is needed.
This record is load-bearing because the run that computed the findings ends at the gate and the engine cannot resume it partway. Without it, "post the selected findings" cannot mean the findings the operator saw: the resumed run recomputes them with agent calls. An `approve` resume therefore posts the recorded review filtered by the selection, and the review the resumed phases recompute never reaches the output.
## Decision 2 — the cap
The cap is a column: `rereview_rounds` on `tasks`, `bigint NOT NULL DEFAULT 0`, read by the response path and incremented in the same guarded write that requeues a re-review. A re-review at the cap is refused with the conflict sentinel the dashboard answers 409 with, and nothing is requeued. Two is a constant in the domain, not a config knob: the PRD fixes it.
`Task.Attempt` cannot carry the count, because it counts every requeue. The two alternatives are worse.
- The execution tree measures passes through the gate, not operator requests. A crash recovery (`RecoverStale`) or an operator retry re-runs the pipeline to the gate and would consume the cap; and a stage has no step read (`task.Store` carries none), so this route needs a new interface method anyway.
- `Task.Notes` is the agent memory ledger, not scratch. `AgentStage.buildRequest` passes it into every generic agent request, `agentexec` renders it as a prompt section, and `persistAppendedNotes` appends to it. A counter parsed out of a field agents write to is the encoded-state defect this repository rejects, and instructions parked there would reach every unrelated workflow's agents.
`RemediationRounds` is the precedent: one writer, one reader, one meaning, kept separate from `RetryCount` so unrelated retries cannot draw a budget down.
The write crosses the State Store. A goose migration adds the column; `internal/infrastructure/postgres/queries/tasks.sql` and its sqlc output carry it; `internal/infrastructure/postgres/store.go` maps it; `proto/state/v1/state.proto` carries it as a new `Task` field with its regenerated contracts and `staterpc/values.go` mapping both ways; `internal/domain/workflow/task/task.go` declares it; `internal/infrastructure/taskactions/store.go` adds it to the `taskactions.Task` projection the response path reads. The write itself is a guarded requeue method beside `RetryTask`, which increments a counter, and `BeginRemediation`, which records a payload in the same transaction: one transition-table guard, one increment and one requeue in one write. It must join every column-listing query, which `docs/development/state-store.md` names.
Tests that prove it: the guarded write increments for a re-review and for no other requeue; a re-review at the cap is refused and leaves the task waiting; and the field survives the wire, which `TestTaskProtoCarriesEveryDomainField` asserts for every field of the domain task.
## Decision 3 — how the instructions reach the stages
The recorded instructions enter the pipeline at phase 3 and phase 4 only, which is what the PRD asks for: a labelled operator-instructions block appended to `runLens`'s mission in `stagePRLenses` and to `runReviewer`'s mission.
They cannot ride `AgentStage.buildRequest`. Every pr-review stage builds its `agentexec.Request` in `runPRReviewAgentRecorded`, which sets no `Request.Notes`, so nothing the generic path threads reaches these calls. The pipeline restores the instructions from the task record at the same point it restores the review, and the two mission builders read them there.
## The gate is not reachable from archie's own PRs
`StagePRReviewAndOpenPR` splices `prReviewDecisionStages()`, the list `PRReview()` uses, so the gate is reachable from the implement workflow too. It must not be. The change is one entry moving: `stagePROperatorApproval()` leaves the shared list for `PRReview()`'s own stage list, immediately before the merge gate, and the own-PR splice keeps taking the shared list unchanged. This is a prerequisite for the response channel and a change of its own.
Three reasons, the second deciding it alone.
- The gate's question is which findings to post, and on archie's own PRs there is no pull request to post to at the point the splice reaches the gate. That trigger's human decision point is its park on an unchallenged blocking finding.
- Approving a wait inside the implement workflow re-enters that workflow at its first stage against a worktree that already carries the change. A builder that then reports no changes sets `BuildNoChanges`, `StageCommitPush` calls `closeNoChangesIssue`, and the issue is closed with no pull request ever opened. Nothing the gate decides is worth a route to silently closing an issue.
- Short-circuiting instead would put a conditional no-op in every stage whose work a wait had completed, which changes the resume semantics of the whole pipeline rather than this gate.
## What a full restart gives, and what it costs
A requeue re-runs the workflow's stage list from its first stage; the engine has no partway resume. That satisfies the PRD's "reruns phases 3 to 8" for free, and it is acceptable for the standalone pipeline precisely because that pipeline has no stage that writes and then closes. The costs:
- Phases 1 and 2 recompute. Both are code except two agent calls — the machine-written score and the anatomy narrative — so those re-run, and a changed score can change whether the hallucination-check dimension is added.
- The pull request's snapshot is checked out again.
- The run's cost and wall-clock budgets are per attempt, so a re-review starts with a fresh allowance, which the cap bounds.
## Verification
- A gate wait on the standalone `pr-review` workflow answered `approve` posts exactly the findings the operator selected, and no finding the resumed phases produced.
- A re-review at the cap is refused, the task stays waiting, and the count survives a store round trip.
- A re-review's instructions reach the lens and reviewer missions; a first run's do not.
- The gate is unreachable from the implement workflow's stage list.
-243
View File
@@ -1,243 +0,0 @@
# PR review comment remediation -- decision
**Status:** Approved
**Date:** 2026-09-10, amended and ratified 2026-09-19
**Beads issue:** (filed as `archie-core-…`, parent: `archie-core-7d5u` event sources and typed reactions)
Answers: how archie reacts to review comments on a PR it opened, from a human
or from another review bot, and remediates them. Built on two settled decisions — the review pipeline's
isolation contract (`docs/prds/pr-review-agent.md`, "Isolation") and the
event-sources decision (`docs/prds/event-sources-and-reactions.md`) — plus the
webhook intake security contract (`docs/prds/webhook-intake-security.md`).
Nothing here re-decides those; it names the one concrete reaction each one's
machinery was built to carry.
## Problem
Archie opens a PR (`pr_open`) and then never learns what a human said about
it. `forge.Forge` has no method to list PR reviews or review comments; the
daemon poll loop finds only new issues; the forge webhook receiver
(`internal/forge/webhook/receiver.go`) decodes only `issues` events and
explicitly ignores `pull_request` events. A "requested changes" review, or an
inline comment on a line, is invisible work.
## Decisions
### 1. Read surface: a narrow `PullRequestReviewReader`, type-asserted
A new forge interface, implemented by GitHub and Gitea, not folded into the
fat `Forge` interface (the h019.8 `PullRequestReader` precedent — the noop
forge cannot honestly provide it):
```go
type ReviewComment struct { ID int64; Author, Body, Path string; Line int; InReplyTo int64; CreatedAt time.Time }
type Review struct { ID int64; Author, State string /* requested_changes | approved | commented | dismissed */; SubmittedAt time.Time }
type PullRequestReviewReader interface {
ListReviews(ctx, owner, repo string, number, sinceID int64) ([]Review, error)
ListReviewComments(ctx, owner, repo string, number, sinceID int64) ([]ReviewComment, error)
// ReplyToReview posts a reply to a review or comment thread.
ReplyToReview(ctx, owner, repo string, number, inReplyTo int64, body string) error
}
```
GitHub: `pulls/{n}/reviews` + `pulls/{n}/comments`; reply via
`pulls/{n}/comments/{id}/replies`. Gitea: `pulls/{n}/reviews` +
`pulls/{n}/comments`; reply via `pulls/{n}/comments/{id}`. `sinceID` is the
cursor for both poll and webhook dedup.
### 2. Event source: webhook first, poll as the universal backstop
- **Webhook (GitHub, low latency):** extend `receiver.go` to also decode
`pull_request_review` and `pull_request_review_comment` events, behind the
existing HMAC verification, producing the same reaction as the poller. The
receiver stays a forge-intake surface — not the generic chat webhook, not a
new generic receiver (7d5u decision 4).
- **Poll (both forges, no webhook dependency):** a periodic scan of `pr_open`
tasks calls `ListReviews`/`ListReviewComments` with a persisted `sinceID`
cursor per task. This is the Gitea path and the deployment-without-webhook
path; it must stay first-class, not a legacy fallback (the repo's own
webhook-intake rule). It is **one shared scan over all `pr_open` tasks**,
not a scan inside each identity's poll loop, and it calls the forge client
the scanned task's own identity owns. This is `reconcilePRs`'s shape
exactly (`internal/daemon/daemon.go`: `Store.OpenPRs` then `forgeFor(&t)`).
A per-identity scan would call one identity's forge client against another
identity's PR.
Both paths emit the **same** typed reaction, so `PublishUnique` dedups them
for free — the `TaskEnvelope.IdempotencyKey` pattern (7d5u decision 4) applied
to reviews.
### 3. Reaction contract: producer-only, resolves to an existing task
A new `workintake.ReviewCommentEnvelope{Owner, Repo, PRNumber, Kind, CommentID,
ReviewID, Author, State, Body, Path, Line}`. Idempotency key is
`owner/repo/pr-number/kind/id` — source-independent, so a webhook delivery
and a poll of the same comment collapse.
`Kind` (`review` or `comment`) is part of the key because a review ID and a
review-comment ID come from independent forge sequences. Keying on the bare id
lets a review and an inline comment on the same PR collide, silently dropping
one of the two. This is a producer-only reaction
(7d5u decision 3): it never vetoes or mutates in-flight work; the target task
is idle (`pr_open`).
The daemon resolves `PRNumber` → the task that owns it. An unmatched PR (not
an archie task) is dropped with a counter — a public webhook must not be able
to start an agent against an arbitrary repository. A PR whose task is merged,
closed or archived is dropped through the same counter: the reaction is only
ever work against a PR archie itself opened _and still owns_.
That lookup does not exist. `pr_number` is written by
`internal/infrastructure/postgres/store.go` and never read in a `WHERE` clause, so this needs a
`TaskStore` method keyed on `(owner, repo, pr_number)`, a matching
`StateStoreService` RPC (a Go interface method on a store facade without one
is forbidden, `CLAUDE.md`), and an index on those three columns. It is the
authorisation boundary, so it is sequenced as its own step below rather than
carried along with the envelope.
**Identity is derived from the resolved task, never carried in the reaction.**
The task row already stores `identity` (`internal/infrastructure/postgres/store.go`), and it is
the resolved task's identity that selects the forge client, worktree manager,
repo config and `bot_user` for the remediation run and the `ReplyToReview`
reply, through the existing `forgeFor`/`treesFor`/`repoFor` helpers. That is
what decision 5's "the identity that owns the task" means, and it is the only
place identity enters this path.
Identity is deliberately **not** added to the envelope, the idempotency key or
the index:
- A PR number is unique within an `owner/repo`, and the tasks table is keyed
`UNIQUE(owner, repo, issue_number)` with no host or identity column, so
archie already treats `owner/repo` as globally unique across identities. A
`(owner, repo, pr_number)` lookup cannot return a task other than the one
that owns that PR; there is no cross-identity resolution to guard against.
- The webhook producer has no identity to carry: webhook intake refuses to
start when `[[identities]]` is configured (`setupForgeWebhook`,
`internal/app/archied/bootstrap.go`).
- Keying on a field only one of the two producers can populate is precisely
the delivery-source-specific key `CLAUDE.md` forbids, and it would break the
webhook/poll dedup the key exists for. An index column that never appears in
the `WHERE` clause is dead weight.
### 4. Remediation: a `remediate` workflow on the existing branch
A new workflow that runs when a reaction resolves to an archie-owned PR. It is
not a new branch/PR — it reuses the task's prepared worktree, refreshes it
onto the PR branch (the `worktree.Manager.refresh` idempotency), and:
1. Runs a builder agent whose mission is the review's actionable comments
(each with body, path, line): "Address these review comments with the
smallest change; run the gate." One agent run per review, per decision 5. The toolset is the normal builder toolset — edit + gate + (never
git; the orchestrator commits/pushes) — not the reviewer's read-only set.
2. Runs the repo gate (`[[repos.gate]]`) and `diff_cap_lines` — the same
enforcement as any other work (webhook-intake-security point 4; no
relaxation for review-triggered edits).
3. Commits and pushes to the **same** PR branch.
4. Replies to the review/comment via `ReplyToReview`, summarising what
changed.
The comment is injected through the task record (e.g. `Task.Notes` or a
dedicated review field), not through a prompt-only path, so the reaction is
recoverable and auditable.
### 5. Routing and lifecycle
A **review** is the unit of remediation, never an individual comment.
- `requested_changes` review → one remediation run addressing every actionable
comment in that review.
- `commented` review with actionable inline comments → one remediation run
addressing every actionable comment in that review.
- `approved` review → no remediation. Record the review state on the task;
do **not** auto-merge — merging stays an operator action (the dashboard/chat
`/approve` precedent). Auto-merge is a separate decision if ever wanted.
One run per review, strictly. A review carrying eight inline comments arrives
as one `pull_request_review` event plus eight `pull_request_review_comment`
events; remediating each separately means eight builder runs, eight gate runs
and eight pushes to answer one review. The comment events are collected
against their parent `ReviewID` and remediated together. A standalone comment
with no parent review is its own unit of one.
Remediation runs for a single task are **serialised**, whatever
`[[repos]].allow_concurrent` says. Two runs against one PR branch would race
on the shared worktree and on the push; `allow_concurrent` is about unrelated
tasks in a repo, not about one task reacting to itself.
#### Whose comments count
Only archie's **own** comments are excluded, matched on the forge identity
that owns the task (`bot_user`, or the identity's `bot_user` under
`[[identities]]`), so its `ReplyToReview` replies do not retrigger it.
Every other author is actionable, including other bots. The external review
bot on this repository is the main source of findings on an archie-opened PR,
and discarding comments because their author is a bot would discard the review
this feature exists to act on. There is no "is a bot" test anywhere in this
path.
(The original draft justified a broader exclusion by citing a `RepliesAfter`
`exclude` precedent. No such mechanism exists in the tree; the citation is
withdrawn.)
#### Bounding the exchange
Because bot comments are actionable, the exchange can run away without a human
ever touching it: archie pushes a remediation, the review bot re-reviews the
new commit, comments, archie remediates again. Nothing in the reaction path
terminates that on its own.
A task therefore carries a remediation round count, bounded by the repo's
existing `max_retries`. On the cap, archie stops remediating, posts one
comment saying it has stopped and why, and parks the task for an operator.
This is a hard stop, not a backoff: the failure it guards against is
unbounded spend, so slowing it down does not address it.
### 6. Security posture
The webhook reaction is not a public no-code binding, so it does not pass
through the `draft → pending_approval → armed` gate (webhook-intake-security
point 2) — but every other constraint holds: HMAC (already in the receiver),
per-source rate limiting (add when the receiver gains a second event family),
and blast radius bounded by the existing gate/sandbox/worktree enforcement,
**plus** the new archie-owned-task check (decision 3), which is the actual
authorisation boundary: a review event only ever causes work against a PR
archie itself opened and still owns.
Accepting other bots' comments (decision 5) does not widen that boundary: an
author is never a reason to act, only the owned-task check is. It does widen
the _spend_ surface, which the round cap bounds.
### 7. Sequencing
1. **The reaction stream.** `ARCHIE_REACTIONS`, under the fan-out
`jetstream.LimitsPolicy` the parent decision requires
(`event-sources-and-reactions.md` §2). `Config.Retention` is
parameterised for exactly this (`archie-core-7d5u.2`), but no reaction
stream exists and `ARCHIE_TASKS` carries `archie.task.>` only, so every
publish to `archie.reaction.*` fails against no matching
stream. This step is first because nothing after it can be exercised
without it.
2. `PullRequestReviewReader` + GitHub/Gitea implementations + `ReplyToReview`.
_(Landed.)_
3. `ReviewCommentEnvelope` + the kinded idempotency key.
4. **The owned-task guard**: `(owner, repo, pr_number)` lookup, its
`StateStoreService` RPC, its index, and the drop-with-counter path for an
unmatched, merged, closed or archived PR. Nothing may consume a reaction
before this exists.
5. `remediate` workflow: worktree refresh, one run per review, builder, gate,
push, reply, round cap.
6. Webhook receiver extension (`pull_request_review` / `_comment` events).
7. Poll backstop with the persisted `sinceID` cursor.
8. Tests + `task check`.
Steps 6 and 7 are the producers and come last on purpose. Building a producer
before its consumer and its authorisation guard yields a path that publishes
into nothing, and becomes an unguarded intake the moment a stream appears.
## Out of scope
- Auto-merge on approval (separate decision).
- Reacting to comments on PRs archie did not open.
- The calibration epic's confirm-before-surfacing (h019.5) — orthogonal.
-128
View File
@@ -1,128 +0,0 @@
# Progressive tool disclosure (bridge tools) — wiring
**Status:** Finalised
**Date:** 2026-08-15
**Compound:** the "keep the LLM tool schema small, give full access on demand" work (issue #167)
## Decision
The bridge-tool pattern is **implemented and tested** in
`internal/tools/disclosure.go` (`tool_search`, `tool_describe`, `tool_call`
- `ContextPressureGate` + `DisclosureMode`, section 17.14/17.15) — but it is
**never wired into the daemon**. `BridgeTools` and `ContextPressureGate` are
referenced only in `disclosure_test.go`. This task is therefore a **wiring**
task, not a feature build.
Wire the existing bridge into the per-chat-turn toolset:
1. **Compose a per-turn registry** seeded from the base registry plus the
per-turn extra tools, register the bridge tools into it, and hand it to both
the bridge handlers and the `ContextPressureGate`.
2. **Run the gate in `chatGenerateOptions`** (`internal/app/archied/main.go`)
so it decides full-vs-bridge disclosure per turn, and build the
`core.ToolSet` from the gate's filtered output.
3. **Thread the model's context window** into the preparation seam so the gate
has a real `ContextWindowSize` (it disables itself at 0, falling back to
full disclosure).
## Why the naive "register extras into the base registry" is wrong
`BuildToolSetFrom` (`internal/agentexec/toolset.go`) documents the invariant:
> the task tools carry the calling gateway's identity, so there is one set of
> them per gateway and they **cannot live in the process-wide registry**.
This is confirmed by wiring: gateways are per-channel
(`telegram_setup.go` build a `TurnRunner` per channel), and the extra
tools (`task_*`, `session_*`, `dashboard_*`) close over that channel's identity
via `TurnRunnerConfig` (`turn.go`). Registering them into `b.toolReg` would
let channel A's session/identity-bound tools be invoked by channel B — a real
cross-channel privilege bug. The bridge handlers iterate `reg.All()`
(`disclosure.go`), so the extras must be discoverable; the fix is a
**per-turn composed registry**, not a mutation of the process-wide one.
## Shape of the change
### 1. Per-turn composed registry + gate inside `chatGenerateOptions`
Replace the current base-set + extra-set merge (`main.go`) with a single
composed-registry pass:
```go
// new helper, in internal/tools/disclosure.go or the archied wiring package
func ComposeForTurn(reg *tools.Registry, extra []tools.ToolEntry) (*tools.Registry, error) {
composed := tools.NewRegistry()
for _, e := range reg.All() {
if err := composed.Register(e); err != nil { return nil, err }
}
for _, e := range extra {
if err := composed.Register(e); err != nil { return nil, err }
}
if _, err := composed.RegisterBatch(tools.BridgeTools(composed)); err != nil {
return nil, err
}
return composed, nil
}
```
`chatGenerateOptions` then:
```go
composed, err := ComposeForTurn(registry, extra)
// ...
gate := tools.NewContextPressureGate(contextWindow)
gate.SetAlwaysVisible(...) // e.g. session/session_resume, task/task_list
disclosed := gate.FilterTools(composed)
toolSet, err := agentexec.BuildToolSetFrom(disclosed, toolOpts)
```
`FilterTools` (`disclosure.go`) already returns `all` in full mode and
`bridge + always-visible` in bridge mode, and `BuildToolSetFrom` re-applies
availability/approval/schema rules, so the two layers compose cleanly.
### 2. Thread context window through the preparation seam
`ContextPressureGate` disables at `ContextWindowSize == 0`. The model context
window is resolved in `TurnRunner.prepareTurn` (`turn.go`) but is not
passed to `TurnModel.Prepare`. Extend the seam:
```go
type TurnPrepareContext struct {
Model string
Extra []tools.ToolEntry
ContextWindow int // model's context window in tokens; 0 = gate disabled
}
```
`TurnModel.Prepare(ctx, context TurnPrepareContext)`; `prepareTurn` fills
`ContextWindow` from `modelDetails.ContextWindow`. This touches one interface
(`turn.go`), one production impl (`chat_turn_model.go`), and the test
mock (`turn_test.go`).
### 3. Bridge-handler parity note
`bridgeCallHandler` calls `e.Handler` directly (`disclosure.go`), bypassing
`toolExecute` — so a `tool_call` invocation does **not** apply `CapPayload` /
`MaxResultSizeChars` spilling or `OnToolCall` reporting, and it pre-refuses
`RequiresApproval` tools (`disclosure.go`). This is acceptable for the
first wiring (the bridge is read-discover/describe plus a guarded call), but a
later hardening should route the invoked tool through the same
cap/approval path the model's direct call uses. Recorded as a follow-up, not a
blocker for this task.
## Files touched
- `internal/app/archied/main.go` — `chatGenerateOptions` composes + gates.
- `internal/app/archied/chat_turn_model.go` — `Prepare` accepts `TurnPrepareContext`.
- `internal/gateway/turn.go` — `TurnModel.Prepare` signature; `prepareTurn` fills context window.
- `internal/gateway/turn_test.go` — update the `turnTestModel.Prepare` mock.
- `internal/tools/disclosure.go` — add `ComposeForTurn` helper (or place in archied).
## Out of scope / follow-ups
- Delegate `tool_call` through `toolExecute` for cap/approval/observability parity.
- Cover the compose-and-gate path with tests (compressed footprint under a
small window; always-visible minus bridge margin).
- Reconcile any `ContextPressureGate` mode with the compression budget already
computed in `prepareTurn` (`turn.go`).
-75
View File
@@ -1,75 +0,0 @@
# Public and development documentation -- design
**Status:** Draft
**Date:** 2026-09-22
## Problem
One published set carries both kinds of document. A reader who wants to know
what Archie is and how to point an event at it lands in a sidebar that also
holds the repository organisation rules, the migration decision register, the
package review procedure and five PRDs. The PRDs are there for a reason that
has nothing to do with the reader: settled architecture cites them, and the
generator refuses a link whose target it holds back, so publishing them was the
only way to keep those citations alive.
Mixing them is not an exposure problem. Every one of these documents can be
public. It is a navigation problem: a customer reading the site meets
contributor material with no signal that it is not for them.
## Decision
One source tree, two published sets, two artifacts, two URL bases.
| Set | Holds | Served under | Artifact |
| ----------- | ------------------------ | ------------ | ----------------------------------- |
| Public | `index.md`, `guides/` | `/docs/` | `docs/data/generated/docs.json` |
| Development | `architecture/`, `prds/` | `/dev/` | `docs/data/generated/dev-docs.json` |
`archive/`, `inspiration/`, `news/` and `github-token.md` stay out of both, for
the reasons the generator already records.
The two artifacts have the same shape. A renderer reads a second file and
serves it under a second base; it needs no new field and no set discriminator,
because the file a page arrived in is the set it belongs to.
## Consequences the design depends on
**Every PRD publishes.** Selective PRD publication existed to keep citations
from settled architecture working. With both cited and citing documents in the
development set, that pressure is gone, and the rule that produced it goes with
it: `prds/` is a development tree, not a list of exceptions.
**Cross-set links resolve.** A link from a public page to an architecture page
rewrites to the development set's absolute path, and the reverse works the same
way. Both sets are generated in one pass over one url map, so a link and its
target cannot disagree about where the target lives. The generator's refusal
still fires, now only for a target genuinely in neither set.
**Assets keep the public base.** `docs/public/` is one file set, referenced
from either set, and serving one file under two paths would invent a second
location for it.
**The sidebar stays derived from the directory layout**, per set. A page added
under a directory appears without a second edit, which is the property the
current generator has and the reason its tree mirrors the tree on disk.
## The public set is thin, and that is the honest state
Two pages: the landing page and the playbook guide. Nothing is lost by the
split, because a reader was never served by the seventeen architecture pages
next to them. The pages a public site needs (installation, configuration
reference, the event sources, the actions a playbook can run) are written into
`guides/` and a `reference/` tree as they are written, and each lands in the
public set with no generator change.
## Verification
- `task docs:artifact` writes both files; `task docs:artifact:check` fails on a
stale copy of either, without touching the tree.
- A link from the public set to a development page, and a link the other way,
each resolve to the other set's base path in the generated body.
- A link to a page in neither set fails the generator, naming the file, the
line and the target.
- `docsgen` accounts for both artifacts, so neither tool reports the other's
file as unowned.
@@ -1,201 +0,0 @@
# One release stream, one page per version, and commit rules — decision
**Status:** Draft
**Date:** 2026-09-22
**Authority:** `RELEASING.md` for the process this changes, `AGENTS.md` for the
commit rules it enforces, and `tools/newsgen` for the artifact shape.
**Supersedes:** `docs/prds/news-and-releases.md`, sections "Source of truth" and
"Two components" — one changelog replaces two, and one page per version replaces
one page per component. Its remaining decisions stand.
## Decision
**A release is one version covering whatever changed.** One changelog holds every
release section, one generated page holds every version's notes, and an operator
cutting a release names one version.
## One changelog
Every release section lives in `CHANGELOG.md`, newest first. `CHANGELOG.archied.md`
and `CHANGELOG.archie.md` are deleted, and `CHANGELOG.md` stops being a pointer to
them. The changelog is the only source of release prose, and tags are not a source:
CI and deployment check out shallow, so tags are absent from a site build while the
changelog is always present.
### The merged history
Two version streams become one file, so a version that both components released
carries one heading and one date: **the newest date among that version's sections**,
because a version's date is when the last part of it shipped. Where a component's own
date differs from it, that component's section label carries its own date, so the
per-component fact survives the merge rather than being collapsed into the heading.
The merged history holds 65 versions: 33 that both components released, 31 only
`archied`, and one only `archie`, from 64 and 34 sections respectively, so 98
published pages become 65. `## [Unreleased]` is not a release -- it carries no
version and gets no page -- but it stays at the top of the file, because it is
the one place unfinished work is recorded. Counting `##` headings rather than
releases overcounts by one.
This ambiguity is historical only. One version stream with one tag gives a version
exactly one date, so the rule represents the merged past rather than a design that has
to hold.
The merge is verified by content, not by the generator succeeding: the section count
per source, the merged version set equal to the union of both sources with nothing
extra, and every section title still present. A generator that agrees with the file it
just wrote is evidence of nothing.
## One version stream
**`GATEWAY` and `RUNTIME` stop being release inputs.** `release:prepare` and
`release:tag` take one version, and `tools/release.sh` loses the two flags.
They may stay as build-time stamps, because a binary must still report what it
contains. A release that must name three versions forces an operator to pass skip
values for components that did not change, and that ceremony is what this decision
removes — along with the drift it allows, where two components' tags fall a release
apart.
**Per-component detail stays, as sections inside the release.** A reader still needs
to know whether `archied` or the agent changed; what goes away is the separate
numbers and the separate pages, not the information.
**History is not re-tagged.** Existing tags keep their names, because tags are not a
source and nothing reads them to build a page. A future reader must not "fix" the
unified changelog by rewriting tags to match it.
## One release page per version
`docs/news/<version>.md` replaces `docs/news/<component>/<version>.md`, carrying the
release's per-component sections inside it.
**Every release URL already published keeps working.** `/news/archied/<version>` and
`/news/archie/<version>` route to the unified page for that version. The generator
emits the redirect table beside the pages so it cannot drift from them; if the
renderer needs the table in its own repository, that is a change in that repository
rather than a hand-maintained list here.
## The reviewer runs between prepare and tag
Release notes are prose, and the review agent exists to review prose. **`release:tag`
refuses to tag when the review has not been run for that version, or when it reports
at the level.**
The invocation is verified rather than assumed. `tl rules --lint` reports `corpus ok`
and exits 0. `tl review <path> --deadline <ms> --max-turns <n>` reports
`0 findings (0 high, 0 medium) · 1/1 files reviewed · clean` and exits 0 on
`docs/news/archied/1.36.0.md`.
**`--fail-on` must be passed explicitly.** It defaults to `never`, so an invocation
without it cannot refuse anything and the step would be decorative. `--fail-on high`
is the level: a medium finding in a release note is worth acting on, and it should not
stop a release on its own.
**The rule is stated once.** It belongs in the reviewer's own rule set, which
`tl rules --from-doc` can draft from this document; `RELEASING.md` points at that
rule beside the step it governs rather than restating it, because two statements of
one rule drift.
## Commit rules and their enforcement
- **Conventional commits**, with the scope taken from the package map.
- **One logical change per commit.** A commit that does two things is two commits.
- **The subject is imperative and short**; the body says why the change is right
rather than restating the diff.
- **A commit depends on the gate's exit status.** The gate and the commit run as one
conditional chain, never as separate statements on one command line, where nothing
reads the gate's status but the operator who typed it.
- **Enforcement is a `commit-msg` hook** installed by one documented target, plus a
check in CI over the pushed range, so the rule holds for a person who never
installed the hook.
- **Scopes are derived, not invented**, and an unknown scope fails loudly rather than
being accepted.
## The release pipeline
**A Woodpecker workflow performs the release**: gate, generate the release page, run
the reviewer over it, commit the changelog and the generated pages, tag, push,
publish images, and trigger the site's artifact sync. No step in that list is an
operator's.
**It triggers on a push to main**, not on a manual run. A pipeline a human must start
is a pipeline that can be forgotten, which is the property this change removes. The
trigger is also not dependent on repairing manual triggering: in this estate a manual
run fails with zero steps while the same configuration runs on a push, and the
estate's own Woodpecker configurations trigger on push with cron, manual or
pull-request events _added_ to it rather than instead of it.
**Prerequisite: Woodpecker must watch this repository.** Adding the workflow to the
repository and enabling the repository in Woodpecker are two steps, and the second is
a configuration action rather than a file. A release pipeline that is correct and
never runs is invisible until someone asks why no release happened, so the repository
being enabled is a prerequisite of this design rather than an assumption behind it.
**One tag, and the duplicate-build problem shrinks as a consequence.** Concurrency
keyed on a commit identifier treats an annotated tag as a ref distinct from its
commit, which starts three builds for one release. One version and one tag removes
two of those refs. Nothing in the pipeline may depend on a tag object's
identity, and this is a consequence of one version stream rather than a separate fix.
### The version is computed, not typed
The version is derived from the conventional commits since the last release, which is
what the commit rules above exist for.
- `feat` bumps the minor version; `fix`, `perf` and `refactor` bump the patch.
- **A breaking change bumps the major version.** Its form is `!` after the type or
scope, as in `feat(api)!:`, and a `BREAKING CHANGE:` trailer — either marks it.
- `chore`, `docs`, `test`, `style` and `build` bump nothing alone.
- **The scope decides whether a commit is the product's.** A commit whose scope is
the repository's own machinery -- `release`, `ci`, `docs`, `build`, `test` -- does
not bump the version even when its type is `feat` or `fix`, because it changes how
the project is delivered rather than what it does. Without this filter the first
improvement anyone makes to the release process inflates the product's version.
- **No release is a legitimate outcome.** A commit set that justifies no version
produces no version, and the pipeline reports that rather than inventing one.
### `tools/release.sh` is designed for the pipeline
- **It never prompts.** Every input arrives as an argument or in the environment, so
it runs with no terminal.
- **Its version is a result as well as an argument.** It may be given one or asked to
derive one, and it reports the version it used in a form a pipeline can read.
- **"Nothing to release" has its own exit code**, distinct from failure, so the
pipeline finishes green without tagging.
- **It commits and tags nothing.** The pipeline owns the commit, the tag and the push;
the script writes the notes and reports what it did. A script that pushes cannot be
run twice safely, and this one runs on every push to main.
### Which CI is authoritative
Three surfaces exist: GitHub Actions, the Gitea workflow files, and Woodpecker.
- **Woodpecker owns releases**, which is the production path this repository's deploy
workflow already names.
- **GitHub Actions keeps the checks a pull request needs.**
- **The Gitea workflow files are retired in favour of Woodpecker** once Woodpecker
runs the same checks, and are not edited in the meantime: two copies of a pipeline
diverge.
- No check lives in two places with neither authoritative. Where a check must run in
both, the second runs the same file rather than a copy of it.
## Verification
- One changelog file exists, the two component changelogs do not, and the generated
pages match it.
- A release prepared with `VERSION` alone writes its notes and tags, with no
`GATEWAY` or `RUNTIME` input.
- Every release URL published before this change resolves.
- `release:tag` refuses after a review that reported at the level, and refuses when
no review ran.
- The `commit-msg` hook and the CI range check each refuse a non-conforming subject
and an unknown scope, with the hook absent and present.
- A push to main carrying releasable commits produces a version, a release page, a
tag and a published image with no operator step.
- A push whose commits justify no release ends green and tags nothing.
- `tools/release.sh` runs to completion with stdin closed, and exits with its
distinct code when there is nothing to release.
- The release workflow reads no tag object's identity, so one release starts one
build.
-123
View File
@@ -1,123 +0,0 @@
# Review settings resource
**Status:** Draft
**Beads issue:** `archie-core-0ry6`
**Authority:** `docs/prds/runtime-control-plane.md` for the resource model,
`docs/architecture/configuration.md` for ownership, and
`docs/prds/pr-review-agent.md` for what the two dials do.
## Decision
`review.precision_gate` and `review.approve_before_post` are one control-plane
resource, `review-settings`. The file's `[review]` section seeds it, the stored
document outranks the file from then on, and the dashboard writes it through the
same settings machinery as every other resource.
The resource is deployment-wide, like every definition the State Store seeds
(`storecontract.DefaultOrgID`): not per-repository, per-identity, or per-run.
## Why its own kind
The two dials are pr-review policy — what a review may post, and whether a human
decides — not a limit on a task run. The document that carries task limits
belongs to that feature. `runtime-control-plane.md` splits settings by feature
and refuses documents unrelated features share; `configuration.md` puts a typed
runtime setting with the domain whose behaviour it describes. One document per
feature is the rule, not one document per settings page.
A new kind also has no legacy documents. Its first value is the seed derived
from the file, so "the store outranks the file" begins from an explicit copy of
both fields rather than from a document that predates them.
## Document
New file `internal/app/controlplane/review_settings.go`:
```go
const ReviewSettingsKind = "review-settings"
type reviewSettings struct {
PrecisionGate bool `json:"precision_gate"`
ApproveBeforePost bool `json:"approve_before_post"`
}
```
Its `Definition` sets `ApplyMode: "live"`, `Document: reviewSettings{}`, and a
`Seed` returning `reviewSettings{cfg.Review.PrecisionGate, cfg.Review.ApproveBeforePost}`,
and a `Validate` wrapping `validateAs`: both fields are free booleans with no cross-field
rule, so the validator is a named place to put one rather than an inline no-op
(`validatePluginSettings` is the precedent). No `Normalize`, because the kind
has no second wire shape to converge.
## Seeding
`ImportConfig`/`seededValues` write the seed for a kind the store does not hold,
so a deployment that never edited the dials runs the values in `[review]`. Once
a document is stored, the file key stops mattering, which is the rule for every
database-owned setting.
## Apply
`runtimeConfigFrom` in `internal/app/controlplane/runtime_config.go` layers the
stored document over the file's `Review`, assigning `out.Review.PrecisionGate`
and `out.Review.ApproveBeforePost` field by field. Field-by-field, not
`out.Review = ...`: a field added to `config.Review` later keeps the file's value
until the document carries it.
`ReviewSettingsKind` joins `runtimeResourceKinds` in
`internal/app/archied/control_plane.go`, so a new stored version re-runs the
layering and republishes through `config.Holder`. Live rather than
restart-required, because every consumer re-reads it: `Review` is on
`reloadableFields` in `internal/app/archied/reload.go`, and the value reaches a
run through `Daemon.configFor` → `Config.ForTask` → `TaskConfig.ToConfig` →
`TaskContext.Cfg`, which `stagePRPrecisionGate` and `stagePROperatorApproval`
read. The next task run uses the new value; a run in flight keeps the value it
started with.
## Projection and page
`BuildConfigView` gains a plain `Review` field carrying both values out of
`cfg.Review`, the way `BudgetsView` carries the layered budgets, so the published
config snapshot tells any reader what is in force. The Review page renders the
two toggles from the control-plane store's draft for `review-settings` — the
shape `SystemTasksPage.vue` uses for `workflow-execution-settings` — and shows
the projected value beside them; a Settings route plus a `PAGE_RESOURCES` entry
(`ui/src/stores/control-plane.ts`) bind the page to the kind.
Nothing else re-advertises them. `configFieldDescriptors` and `ConfigView.Schema`
gain no `review.*` row: the config catalog's generic renderer was deleted, so a
descriptor row adds a field nothing can edit, which is the shape `becb0b5e`
removed.
## What the test proves
`internal/app/controlplane/runtime_config_test.go` adds the round trip that
builds the effective config the way boot does: seed the kind from a file config
with both dials set one way, store a document with both flipped, layer it
through `runtimeConfigFrom`, and assert the effective `cfg.Review` equals the
stored document. A second case covers the absent kind, where the file's values
stay in effect. The assertion is on `cfg.Review` — the value `TaskContext.Cfg`
carries into the two stages — not on a struct the test set directly.
`TestRuntimeResourceKindsApplyLive` gains `review-settings` as live. The
validator needs no `validators_agree_test.go` case: it wraps `validateAs` with
no rule, because no combination of the two booleans is invalid, and a case that
cannot fail is a test the project then carries for nothing.
## Rejected: extending workflow-execution-settings
That resource is `workflow.ExecutionSettings`, "the limits captured when a
workflow execution starts". Putting review policy in it makes the review feature
a field of the limits document, gives a boolean edit a ride on a document whose
candidate is validated and swapped as one unit with the budgets, and forces
absence-aware pointer fields onto booleans so a document stored before the fields
existed does not turn a file's `precision_gate = true` into `false`. It buys one
less kind at the cost of the ownership rule the model is built on.
## Out of scope
- Per-repository, per-identity, or per-workflow review settings. A scope key is
a later decision with its own resource shape.
- Any other review knob. A field joins the document only with a consumer, the
rule every config field carries.
- The reviewer pipeline's behaviour. This document places the settings; it does
not change what they do.
-139
View File
@@ -1,139 +0,0 @@
# Runtime control plane
**Status:** Approved
**Date:** 2026-09-20
**Tracking:** `archie-core-j28m`, `archie-core-1786637498420-327-bacadaae`
## Outcome
Archie can be managed from the Web UI or a messaging channel. Both use the same
API.
## Model
Each feature owns its settings and commands. The database stores them. There is
no global configuration document.
This includes:
- workflows;
- identities and bindings;
- providers and models;
- repository policies;
- channels and schedules;
- capture mappings and bindings;
- tool settings;
- prompts and personas;
- plugin settings.
Plugin code remains installed code. Only its settings are stored in the
database.
Each feature defines its data, validation, permissions, editor fields, and how
changes take effect. Each feature also defines its allowed actions. For example,
identities can be created, suspended, and retired.
Repository and identity settings remain separate. They are not stored as large
records that unrelated features must share.
The State Store process hosts the control-plane API on its existing gRPC server.
No new process is added. Feature code validates changes. Storage code only
writes versions and audit records.
Every write records who made it, where it came from, a request ID, and the
version being edited. The API layer sets the actor; the request body cannot.
The server validates the change, then writes it with its audit record. It rejects
edits to an old version.
The request ID is the write's idempotency key, and it is scoped per org and
per kind, never global. The key is `(org_id, kind, request_id)` — the unique
index `idx_resource_history_org_kind_request` (migration `0021_resources_per_org.sql`)
— so replaying a request ID is the same org's prior write of the same kind, and
a request ID reused across orgs or across kinds is a separate write. This is the
same scoping as the task idempotency key `org/identity/owner/repo/number`
(`docs/prds/orgs-and-access.md`).
## API
The API has four operations:
1. **Catalogue** tells clients what can be viewed or changed and how to edit it.
2. **Query** reads data and versions without exposing secrets.
3. **Command** asks the owning feature to make a change.
4. **Watch** streams changes and errors to clients.
Complex features can use custom screens. They still use the same commands.
A dashboard session or channel sender must map to an Archie identity before it
can run a command. Messaging syntax maps to the same commands as the Web UI.
`archie-ui` receives only an API client. It does not receive a database handle,
daemon pointer, global configuration object, or secret value.
The database stores the requested settings. Each process reports the version it
is using or why it failed. The UI shows both.
Some changes require a restart. The UI shows them as pending. When a live change
replaces a running component, Archie starts and checks the new one before
switching. If the check fails, the old one keeps running.
## Bootstrap, migration, and recovery
Bootstrap contains only the database path, listen addresses, credentials, TLS,
and encryption-key references. State Store and control-plane RPCs use the same
endpoint.
When upgraded, existing instances are migrated to the database. Existing
database values are not overwritten, with one exception: a resource whose
document the build ships is refreshed when the seed itself wrote the stored
copy, because that copy is a previous release's document rather than an
operator's. After migration, settings in TOML are ignored and cannot block
State Store startup.
The Web UI remains available when `archied` or Gateway is down. It shows failed
changes and can correct or roll them back.
Offline commands can back up, restore, validate, and roll back the database.
Recovery does not require `archied` or the Web UI. The database stores secret
references, not secret values.
## Workflows
Users create and edit workflows in the Web UI. Workflows are stored as versioned
YAML. Built-in workflows can be overridden and restored.
A workflow is a list of steps. Each step has a known type and its own settings.
A step type is part of the build's step vocabulary, contributed as a provider at
the composition root; interpreted plugins contribute none
(`docs/prds/workflow-step-vocabulary.md`). Each run keeps the workflow version it
started with.
Yaegi, `.archie/stages/*.go`, and `.archie/gate.go` will be removed. Their useful
behaviour must first be available as normal workflow steps.
## First implementation
The first implementation makes task limits editable: maximum model steps,
maximum runtime, and maximum consecutive gate failures.
It includes:
- validated task-limit fields;
- version history and audit records;
- the four API operations;
- authenticated Web UI and messaging access;
- live updates and apply status;
- a Pinia-backed editor in the Web UI;
- a messaging command using the same API;
- migration of existing `[budgets]` values;
- an end-to-end restart test.
Running tasks keep the limits they started with. New tasks use the latest applied
version. This replaces the old settings overlay instead of extending it.
## Not included in the first implementation
- Moving bootstrap or secret values into normal settings.
- A generic JSON editor.
- Rebuilding every settings screen at once.
- Changing the limits of a running task.
-221
View File
@@ -1,221 +0,0 @@
# Self-update: artifact install, topology migration, journaled transaction
**Status:** Draft
Epic: `archie-core-hj1t` / GitHub `#804` ("[EPIC] Self-update: artifact
install, topology migration, journaled transaction").
The update _contract_ (`internal/releaseupdate`: `Catalog.Check`,
`Installer.Install`, plus defer/watchdog/verify) is settled and unchanged by
this document — it stays a thin Go interface shelling out to
`CommandCatalog`/`CommandInstaller`. This document decides what the reference
adapter scripts (`scripts/archie-update-{check,install,watchdog}`) and
`install.sh` do behind that contract, and settles the one thing the epic's
own description got wrong: the dist-zip **is** already attached to GitHub
Releases (`.github/workflows/deploy.yml`, `gh release upload`), not
Actions-artifact-only. Artifact install is therefore a smaller change than
the epic assumed — pointing the installer at an existing asset, not standing
up new CI publishing. Topology migration and the journaled transaction are
genuinely greenfield: no topology-detection or transaction-journal code
exists anywhere in the tree.
Out of scope: rewriting the `internal/releaseupdate` Go interfaces
themselves, and any UI for triggering updates (channel dispatch, e.g.
Telegram `/update`, is unaffected — this only changes what happens once an
install is triggered).
## Problem
`scripts/archie-update-install:139-160` clones and compiles from source on
every update — the only path that exists. `deploy.yml` already publishes a
per-platform archive plus (implicitly) checksums as a release asset, so the
script not using it is a missed-reuse gap, not a missing-CI gap.
`install.sh:414-445` writes only `archied.service` while every shipped
deployment profile (`deployments/*.toml`) declares `[services.state]` and
`[services.gateway]` sections needing their own units — a fresh install
already reproduces the broken single-unit shape `deployment_contract_test.go`
doesn't even catch, because that test only checks profile
syntax, not installed topology. No code anywhere enumerates which systemd
units exist on a host or compares that against what a release requires — the
daemon fails at `bootstrap.go`'s `[services.state].target` check with no
prior diagnosis. The self-refresh trap is confirmed at
`scripts/archie-update-install:195-199`: new adapter copies land on disk but
bash keeps executing the in-memory copy, so a pre-flight check added to the
script only protects the _next_ update.
## Design
### Artifact install (`#804` item 1)
**Decision.** `CommandInstaller`'s default script downloads the per-platform
archive plus `SHA256SUMS` from the GitHub Release that `Catalog.Check`
resolved (the same release `deploy.yml` already publishes to), verifies the
checksum, and stages it — it does not clone/compile. Source build
(`scripts/archie-update-install`'s current clone+compile body) is kept as an
opt-in path selected by an explicit `--from-source` flag or
`ARCHIE_UPDATE_SOURCE_BUILD=1` env var, never the default, since a compile-on
every-host update is strictly slower and has a larger failure surface than
downloading a signed asset that CI already produced.
**Call site.** `scripts/archie-update-install` — replace the clone+compile
body with a download-and-verify step; move the existing
clone+compile body behind the opt-in flag rather than deleting it.
`internal/releaseupdate/command.go` (`CommandInstaller`) is unchanged —
it already just shells out.
**Reuse check.** `deploy.yml` already builds and publishes the
archive and uploads it as both an Actions artifact and a release asset; no
new CI work is needed, only pointing the installer at what exists.
**Testing.** Checksum-verification logic is a shell function, testable with
a fixture archive + `SHA256SUMS` pair — add to whatever test harness already
covers `scripts/`. Full download-from-real-release is a manual smoke command
(document the exact `archie-update-check`/`--dry-run` invocation once built),
not `task check`.
### Topology migration (`#804` item 2)
**Decision.** Add a topology _observer_ to the daemon, not the shell
adapter — CLAUDE.md's own "known trap" note says the shell copy is defence
in depth only, and the daemon is what "knows the deployment and holds the
approved snapshot." The observer inspects which systemd user units exist
(`systemctl --user list-unit-files 'archie*.service'` or equivalent) and
which config sections are present (`[services.state]`, `[services.gateway]`,
UI service config), producing an `ObservedTopology` value with one field per
unit: present/absent, and the config sections backing it. Each release's
`release.json` (already produced by `deploy.yml` per the artifact-install
work above) gains a `required_topology` field naming the units and config
sections that release's binaries need. `Catalog.Check` compares observed
against required; when the release needs a unit the host doesn't have, the
result is not an error — it's a `MigrationPlan` value naming exactly which
units and config blocks must be created and in what order (state store →
gateway → UI → daemon, per CLAUDE.md's process boundaries), which the
installer must apply before installing binaries, or refuse with that plan
printed to the operator.
**Call site.** New topology-observation code lives in
`internal/app/archied/` next to `bootstrap.go` (which already owns the
`[services.state]`/`[services.gateway]` checks this reuses), not in
`internal/releaseupdate` — the update package consumes the daemon's
observation, it doesn't reimplement config parsing. `install.sh:414-445`
reads the same `required_topology` declaration (from whichever profile the
operator selected) so first-install and self-update stop diverging — this is
the fix for the "three docs describe four units, install.sh writes one"
gap: one topology source of truth, consumed by both entry points.
`deployment_contract_test.go` gains an assertion that each shipped profile's
declared topology matches the units `install.sh` would create for it.
**Failure mapping.**
| condition | contract error |
| -------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| observed topology cannot be determined (systemctl unavailable, non-systemd host) | refuse with "topology unknown" plan naming the manual steps, never guess |
| required units missing, migration plan derivable | apply plan before binary install, in dependency order |
| required units missing, no derivable plan (e.g. conflicting existing unit) | refuse, print the plan, do not proceed |
**Testing.** `ObservedTopology`/`MigrationPlan` comparison logic is pure —
table-driven unit tests belong in `task check`. Actual `systemctl` inspection
needs a real systemd host; manual smoke test only.
### Journaled transaction (`#804` item 3)
**Decision.** Replace `archie-update-install`'s copy-and-trap body with: (1)
pre-flight (the existing check, kept), (2) write an intent journal
to a path outside every directory the install touches — e.g.
`${XDG_STATE_HOME:-~/.local/state}/archie/update.journal` — recording the
candidate version, the topology plan (if any), and each binary's
current-and-candidate path before touching anything; (3) stage each new
binary under a `.new` suffix in the same directory as the live binary, then
atomically rename over the live path (`rename(2)` is atomic on the same
filesystem — this replaces whatever non-atomic copy the current script uses)
rather than overwriting in place; (4) run each replaced binary's existing
health/ready check (the same checks `internal/domain/health` already exposes
per the health registry pattern, not a new one) against the _candidate_, not
a hardcoded default port/binary; (5) hold the process open for a bounded
observation window (e.g. 120s) watching for crash-loop before declaring
success; (6) on any failure at any stage, roll back using the journal:
restore prior binaries via the same atomic rename, restore prior unit files
and config if the topology-migration step touched them, and delete the
journal only on confirmed rollback completion; (7) on daemon boot, check for
a journal file and resume rollback if one exists uncommitted (crash-during
-update recovery). A single-writer lock (`flock` on a lock file outside the
replaced paths, e.g. next to the journal) prevents two concurrent updates.
**Call site.** `scripts/archie-update-install` (journal write, stage-then
-rename, lock acquisition), `internal/releaseupdate` package (health-check
invocation reusing whatever the health registry already exposes — cite the
concrete symbol once located, do not add a second health-check mechanism),
and `internal/app/archied` startup (resume-on-boot journal check, next to
existing bootstrap sequencing).
**Failure mapping.**
| condition | contract error |
| ---------------------------------------------- | ------------------------------------------------------------------------------------ |
| lock held by another update | refuse immediately, name the holder's PID/journal |
| health check fails post-switch | automatic rollback within the observation window, journal records the failure reason |
| crash mid-transaction, journal present at boot | daemon completes rollback before normal startup, logs it |
**Testing.** Stage-then-rename and rollback logic against a fixture
directory tree is fully fakeable — `task check`. Real systemd unit
start/stop as part of rollback needs a real host; manual smoke command.
### Channel, pinning, automation (`#804` item 4)
**Decision.** Add `channel = "stable" | "next" | "<exact-version-pin>"`
to whatever config section already governs update behaviour (next to
`ARCHIE_UPDATE_CHANNEL`'s existing chat-channel field in
`internal/releaseupdate/command.go` — name this new field distinctly,
e.g. `ReleaseChannel`, to avoid colliding with the existing chat-notification
channel of the same word). `Catalog.Check` filters candidate releases by
this field before returning the newest match. Runtime image pinning: every
shipped profile already pins by digest
(`deployments/*.toml` confirmed), so the remaining gap is
`scripts/archie-update-install`'s fallback default — it must read the
digest from the active profile's config rather than falling back to
`:latest` when none is configured; refuse the update (don't silently pull
`:latest`) if no digest is resolvable and the profile requires a pinned
image. Opt-in auto-update refuses to start when the daemon reports work in
flight (reuse whatever "tasks running" signal the daemon already
exposes for graceful shutdown — do not add a second in-flight tracker).
**Call site.** `internal/config/config.go` (new `ReleaseChannel` field),
`internal/releaseupdate` (`Catalog.Check` filtering),
`scripts/archie-update-install` (digest resolution, remove `:latest`
fallback), daemon shutdown/drain signal (reuse for the auto-update
in-flight check).
**Testing.** Channel filtering is pure — `task check`. Digest-refusal path
is a shell-script unit test against a fixture profile.
## Call site inventory
| concern | file | change |
| ------------------------------------------------ | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| Update contract (Catalogue/Installer interfaces) | `internal/releaseupdate/service.go` | none — already handles this |
| Command adapters | `internal/releaseupdate/command.go` | new `ReleaseChannel` field distinct from existing chat-channel field |
| Install script body | `scripts/archie-update-install:139-160,170,195-199` | replace clone+compile default with download+verify; add journal, lock, stage-then-rename, digest check |
| CI release publishing | `.github/workflows/deploy.yml` | none — already handles this |
| Deployment profiles | `deployments/*.toml` | none — already digest-pinned |
| First-install unit creation | `install.sh:414-445` | change — consume shared topology declaration |
| Topology assertions | `deployment_contract_test.go` | new assertion: profile topology matches install.sh output |
| Topology observation | `internal/app/archied/bootstrap.go` (new sibling code) | new |
| Resume-on-boot rollback | `internal/app/archied` startup | new |
| Health check reuse for candidate verification | `internal/domain/health` | reuse — confirm exact symbol before implementing |
## Execution: multi-agent team breakdown
| sub-feature | issue | implementer scope | suggested council lenses | why |
| -------------------------- | ------------------------ | ------------------------------------------------------------------------------------ | ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| Artifact install | item 1 (file if unfiled) | `archie-update-install` download+verify, opt-in source-build flag | `lens-deletionist` | must not leave the clone+compile path as silent default cruft |
| Topology migration | item 2 (file if unfiled) | daemon-side observer, `release.json` schema, `install.sh` consumption, contract test | `lens-boundary`, `lens-operator` | boundary: observation belongs in daemon not shell; operator: refusal-with-plan is the whole safety property |
| Journaled transaction | item 3 (file if unfiled) | journal format, stage-then-rename, lock, resume-on-boot | `lens-operator`, `lens-maintainer` | operator: crash-mid-update is the core failure mode; maintainer: someone must be able to read a journal file during an incident |
| Channel/pinning/automation | item 4 (file if unfiled) | config field, catalogue filtering, digest refusal, in-flight guard | `lens-contract` | digest-refusal changes what a config value is allowed to resolve to |
## File and link the beads
- The epic's four numbered work items are not yet individual child beads —
file one bead per item above, each linking to its matching `##` heading
here instead of restating the design, with acceptance criteria drawn from
this doc's failure-mapping tables.
- Add the suggested lenses to each new issue.
-253
View File
@@ -1,253 +0,0 @@
# Service decomposition -- decision
**Status:** Draft
**Date:** 2026-09-05
**Beads epic:** archie-core-8cda
**Prior art:** `docs/inspiration/2026-09-05-awx-service-decomposition-and-ansible-task-model.md`,
`docs/inspiration/module-reference-awx-decomposition-vs-archie.md`,
`docs/inspiration/service-discovery-research-2026-09-05.md`,
`/work/artefacts/archie-core-current-state-archify.html`,
`/work/artefacts/archie-core-ideal-state-archify.html`
The Phase 3 UI boundary and configuration decision is ratified in
[`ui-service-boundary.md`](ui-service-boundary.md). That focused document is
the implementation authority for `archie-core-8cda.5.2`; this parent remains
the broader service-distribution proposal.
## Decision
archie-core moves from one Go binary (`archied`) hosting every domain
in-process to a set of independently deployable services, each exposing
exactly one typed contract. Consumers depend on the contract; they never
reach into another service's internal types, session state, or config.
gRPC is the synchronous transport; NATS remains for asynchronous fan-out
(status, telemetry) rather than being replaced.
This is a **distribution decision**, not a rewrite of Archie's domain
model. The six-domain split already approved in
`docs/architecture/index.md` and `docs/architecture/organisation.md`
(Identity, Agent, Messaging, Workflow, Work Intake, Plugin) is unchanged;
this PRD is about how the _processes_ running that domain logic get
packaged, contracted, and discovered -- not about redrawing domain
boundaries.
### Target services
| Service | Contract it owns | Existing code it replaces/wraps |
| --------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| UI Service | thin client only; talks to Gateway and State Store contracts | `internal/webui` (SPA hosting stays; API surface becomes typed contract clients, not a peer with direct access) |
| Gateway Service | routing / turn / session contract | `internal/gateway` |
| Messaging Service | channel-plugin contract (Telegram, email, Discord, Teams, ...) | `internal/channels` |
| Curator Service | curator contract; **optional**, installs as a Gateway plugin | `internal/domain/curator` |
| Scheduler Service | cron/ticker contract | `internal/domain/scheduling` |
| Execution Environment | execution-dispatch contract | `internal/domain/workflow`, task dispatch paths |
| Runner | isolated worktree/container execution | `internal/container`, `internal/agentexec`, `internal/worktree` |
| State Store | state-access contract | `internal/infrastructure/postgres` |
### Discovery
Per `docs/inspiration/service-discovery-research-2026-09-05.md`:
- **Primary:** Kubernetes-native discovery (Service + headless-Service/DNS
- EndpointSlice, served by CoreDNS), delivered as a Helm chart + Operator,
on k3s for single-host installs and a real cluster for multi-host or a
hosted offering.
- **Fallback:** NATS-based discovery (micro `$SRV` announce + JetStream KV
registry) for no-K8s single-host installs, with a custom gRPC resolver
reading `host:port` from the KV bucket.
- Both implementations sit behind one internal interface:
```go
type ServiceRegistry interface {
Resolve(service string) []Endpoint
Watch(service string) <-chan Event // join/leave
}
```
- An optional service (Curator; others later) that is not installed
must resolve to a distinct `NotInstalled` outcome, never a `Down`/
`Unhealthy` one. Under K8s this falls out of DNS returning no record;
under the NATS fallback it requires an explicit "installed" marker in the
KV registry, not just absence-implies-down.
### Distribution model this supports
Both self-hosted (customer runs the Helm chart or the NATS-fallback
binaries themselves) and a managed/hosted offering (we run the same Helm
chart) are in scope -- this is the RHEL / Ansible Automation Platform
model: one architecture, sold both ways. This PRD does not decide the
business model; it decides that the architecture must not foreclose
either shape.
## Why this shape
`docs/inspiration/module-reference-awx-decomposition-vs-archie.md`
established that Archie's existing domain split already does what AWX's
service-decomposition post argues for -- boundaries exist. What didn't
exist was deployability: `internal/webui` was not a passive frontend. The
re-baselined coupling inventory is below, and the ratified boundary is
[`ui-service-boundary.md`](ui-service-boundary.md).
- Telegram task actions now call Gateway's `ChatContract` directly through
`chatTaskActorAdapter`; the old Telegram-to-webui HTTP detour is historical.
- `internal/webui/api_chat.go` now holds `gateway.ChatContract`; direct
`SessionStore`, `Router`, and `TurnHistory` access is historical.
- The third coupling is closed. UI extraction shipped (`archie-core-8cda.5`,
closed 2026-09-11): `cmd/archie-ui` serves the dashboard against remote
Gateway and State Store contracts, holds no `config.Holder`, and relinks no
daemon runtime (`cmd/archie-ui/architecture_test.go` enforces that on every
`task check`). The `b.web.Cfg = b.d.Cfg` alias left in `buildDaemon` is now
inside the daemon's own process -- it renders the published `ConfigView`
snapshot and holds the readiness probes -- so it no longer crosses a service
boundary. That cleanup is `archie-core-ml30` (P2); the UI boundary is
ratified in [`ui-service-boundary.md`](ui-service-boundary.md).
## Non-goals
- Redesigning the domain model (Identity/Agent/Messaging/Workflow/Work
Intake/Plugin boundaries are settled elsewhere and unchanged).
- Replacing NATS. It remains the async transport; this PRD only adds gRPC
for synchronous request/response and (optionally) K8s-native discovery.
- Deciding the business model (self-hosted vs. managed vs. both). Kept
open deliberately; the architecture must serve either.
- Config relocation (`config.toml` -> ConfigMaps/Secrets) is real work
implied by a K8s-native deployment but is its own decision, not decided
here. Flagged in the discovery research as a phased concern.
- Any concrete adoption of Pi (or another external agent harness) as an
execution runner. Raised in conversation alongside this decomposition,
but it is a separate decision (agent execution as a strict data
boundary, `docs/architecture/agent-system.md`) and does not gate or get gated by this PRD.
## Open questions
All ten are resolved; each carries its resolution inline. Three phases have
since shipped against them (Gateway, State Store, UI), so the framing here is
historical record rather than an outstanding gate.
1. **Extraction order.** Which service gets pulled out of the monolith
first? The webui entanglement findings above suggest Gateway Service's
`ChatContract` should exist before UI Service is extracted, since UI is
the most entangled consumer. Not yet sequenced.
**RESOLVED.** Gateway Service first, then State Store,
then UI, then Messaging, then Execution/Runner/Scheduler, then Curator
(optional) — preceded by an in-process "contract seams" (modular
monolith) phase. Confirms the hypothesis and strengthens it: the
Gateway is already store-decoupled (it uses narrow contract adapters,
not `internal/store`) and already owns an isolated session SQLite, so it
is both the stickiest capability _and_ the one with a ready seam and
isolated data — extractable alone, first. Full phase list and reasoning:
`docs/inspiration/service-decomposition-open-questions-research-2026-09-05.md#1`.
2. **Contract definition mechanism.** Protobuf/gRPC service definitions
need a home (a new `proto/` or `contracts/` tree, versioning scheme,
codegen wiring into `Taskfile.yml`). Not yet designed.
**RESOLVED.** buf v2 driving `protoc-gen-go` +
`protoc-gen-go-grpc` (grpc-go, not connect-go — connect-go's net/http
client breaks the discovery research's gRPC resolver plumbing for K8s
DNS and NATS-KV). One committed `proto/<service>/v1/` tree, generated
Go committed to `internal/contracts/<service>/v1/`, directory
versioning (breaking change -> new `vN`, enforced by `buf breaking` in
the gate), and `task proto:generate`/`proto:lint`/`proto:check` wired
into `task check` and mirrored into `.github/workflows/deploy.yml`
(CI does not run `task check`). Full toolchain comparison, layout
rationale, and scratch-verified `buf`/`buf breaking`/`connect-go`
results:
`docs/inspiration/service-decomposition-open-questions-research-2026-09-05.md#2`.
3. **In-process vs. out-of-process during migration.** Whether services
can run multiplexed inside one binary behind the same `ServiceRegistry`
interface during a transition period (so extraction is incremental and
testable) or whether each service must be a separate binary from day
one. Strongly recommend the former for a solo maintainer, but not
decided here.
**RESOLVED.** Multiplexed in-process is the migration
default -- this is `docs/architecture/organisation.md`'s standing
"Process boundaries" rule, not a new lean. Mechanism: one wire-safe Go
contract interface per service; a local adapter and a generated gRPC
client adapter, both satisfying the same interface via a compile-time
assertion (the `var _ workflow.Store = (*Client)(nil)` idiom;
`store.WorkflowStore` is superseded by the consumer-owned
`workflow.Store`); composition (not `ServiceRegistry`, which stays
network-only) picks the adapter by the presence of a
`[services.<name>].target` address -- empty = local (in-process) adapter,
set = dial the remote gRPC client. This replaced the earlier
`mode = "inproc" | "remote"` enum, which was dropped (see the gateway's
`services.gateway.target`). The adapter is chosen by presence of the
target; Phase 2 then deleted every local fallback, so remote is now the
only mode and an empty `[services.state].target` is a startup error
(docs/prds/state-store-contract.md §12 step 7). A
per-contract conformance suite runs against both adapters over
`bufconn`; the flip to a real process is a same-commit deletion of the
in-process path, no dual-live window. Consequence: Gateway's Phase 0
(`ChatContract` seam) ships in-process first, with the network protocol
staying out of the production path until Phase 1 -- no amendment to Q1's
phase list needed. Full mechanism and evidence:
`docs/inspiration/service-decomposition-open-questions-research-2026-09-05.md#3`
(the State Store's concrete ratified config shape is
`docs/prds/state-store-contract.md` §10).
4. **State Store's contract shape.** Whether every service gets its own
storage (true microservice isolation) or several services share the
State Store service's contract (less isolation, less migration risk).
Not yet decided.
**RESOLVED.** One State Store service owns the task data
(now PostgreSQL, see `docs/prds/state-store-contract.md`) behind narrow typed contracts (`TaskStore`,
`CaptureStore`, `MappingStore`, `BindingStore`, `WorkflowStore`) over
gRPC. _(Ratified 2026-09-06: the workflow contract is now the
domain-owned `workflow.Store`, which supersedes
`internal/store`'s `WorkflowStore`. See note below and
`docs/prds/state-store-contract.md`.)_
No physical database-per-service: the solo-maintainer / team-
topology rule of thumb plus the low value of per-service autonomy for
one person rule it out, and one store means no distributed-transactions
problem.
Concrete migration path (generalise `storerpc`, swap consumers one
contract at a time, stand up the store service, split the file only on
evidence):
`docs/inspiration/service-decomposition-open-questions-research-2026-09-05.md#4`.
**RATIFIED (2026-09-06, beads archie-core-8cda.4.1).** The authoritative
contract boundary & transport design for this is fixed in
`docs/prds/state-store-contract.md` (rev. 2c): one `StateStore` gRPC service,
42 RPCs; **ownership split** — consumer-owned `workflow.Store` +
`workflow.Task`/`Status`/`Source` in the workflow domain (dependency rules
#2/#7), producer-owned daemon/webui store surfaces in `internal/domain/storecontract`;
the `Task`/`Status`/`Source` + interface relocation is a Phase 2
prerequisite pulled from migration-decisions §4 (`store.Task →
WorkflowExecution`); `RecordDispatch` drops `*sql.Tx`; `Close` off-wire;
structured gRPC error codes with sanitised details; explicit agent State
Store gRPC handoff (`STATE_STORE_URL`/`STATE_STORE_TOKEN`); loopback+bearer
transport-security boundary; presence-based `[services.state].target`
defaulting local; migration order `workflow.Store -> archie-state-store ->
Capture -> Mapping -> Binding -> TaskStore`. `.4.2` and `.4.3` implement
against that doc.
5. **Helm chart / Operator ownership.** Net-new work with no existing
analogue in this repository (`deployments/` holds TOML profiles
and a `docker-compose.yml`, not Kubernetes manifests). Scoping not yet
started.
**RESOLVED.** Three charts: an `archie-library` chart
(shared Deployment/Service templates, named ports), an `archie` chart
for the 7 core services, and an `archie-curator` chart + Curator
Operator (CRD, controller, RBAC). The Curator reconciler is a
level-triggered loop that fetches the CR, builds Deployment + Service,
sets owner refs, applies idempotently (`CreateOrUpdate`), watches via
`Owns()`, and reports a `Ready` status condition. Smallest real
milestone (M1): install a Curator CR → Operator creates Deployment +
Service → CoreDNS serves `curator` → Gateway's resolver flips it from
`NotInstalled` to Installed with no redeploy; uninstall flips it back.
Full scoping and first bead-issue list:
`docs/inspiration/service-decomposition-open-questions-research-2026-09-05.md#5`.
## Completion criteria
Not applicable yet -- this PRD records the target shape and the discovery
decision. It does not authorise implementation. Before work begins: file
a beads epic, resolve the open questions above (at minimum #1-#3), and
get explicit go-ahead given the scale of this change relative to
`AGENTS.md`'s "smallest workable change" default for this solo project.
-112
View File
@@ -1,112 +0,0 @@
# Service registry — one declaration per service
**Status:** Draft
**Supersedes:** `state-store-contract.md` §10's `State ServiceConnection`
struct-field instruction.
**Base:** the `listen` field, `internal/app/archied/listen.go`, and the listen defaults cited
below exist on `feat/attempt-attribution`, not on `main`. This design therefore lands on top of
that branch: `RegisterService`'s `listen` argument has nothing to carry without it.
## Problem
A service is already one Go type, `config.ServiceConnection`. What is duplicated is its
**name**, in three layers:
| Layer | Location | What is hard-coded |
| ----------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |
| Declaration | `internal/config/services.go` | `Gateway` and `State` as struct fields |
| Defaulting | `internal/infrastructure/configuration/defaults.go` | three `if cfg.Services.X.Y == ""` branches |
| Consumption | `internal/app/archied/{bootstrap.go,state_store.go,gateway.go}`, `internal/app/archieui/config.go` | `cfg.Services.State` / `cfg.Services.Gateway` field access |
Adding a service means editing all three. The drift this permits is already visible:
`stateStoreResolvedToken` (`state_store_client.go`) and `gatewayResolvedToken`
(`chat_service.go`) are byte-identical apart from the env var name, and
`gateway.Target` is defaulted while `state.Target` is a startup error, with nothing
stating that asymmetry in one place.
`resolveServiceListen(service, flagValue, configured)` (`listen.go`) is already
name-parameterised. It is the shape the rest should follow.
## Decision
**Key services by name, and carry per-service asymmetry as registration data.**
### 1. Declaration collapses to a map
```go
// internal/config/services.go
type Services map[string]ServiceConnection
```
`ServiceConnection` is unchanged. The TOML shape is unchanged, so no deployment profile,
`config.example.toml`, or `install.sh` edit is required. An unrecognised `[services.foo]`
decodes without a code edit, satisfying criterion 5.
### 2. Registration is the single entry point
```go
// internal/config/servicespec.go
func RegisterService(context, name, target, listen, tokenEnv string)
```
registered once per service, at package init in `internal/config`:
```go
RegisterService("both", "gateway", "127.0.0.1:8585", "127.0.0.1:8585", "GATEWAY_TOKEN")
RegisterService("client", "state", "", "127.0.0.1:9090", "STATE_STORE_TOKEN")
```
Positional, five strings, as the story specifies. Each argument is data the current code
states in prose or in a branch:
- `context` is `client`, `server`, or `both`, and decides which fields must resolve
non-empty. `RegisterService` enforces it: an unknown context, or a hosted service with
no default `listen`, panics at registration. Registrations come from this repository's
own `init()`, never from operator input, so an invalid one is a programming error with
no caller positioned to handle an error return. A documented-but-unread `Context` would
be worse than no field at all.
- `target` is the **default**, and an empty default means the operator must supply one.
That single convention replaces the `state.target` required / `gateway.target` defaulted
asymmetry with no branch: `state` registers `""`, `gateway` registers an address.
- `listen` is the default listen address, feeding the existing
flag → `[services.<name>].listen` → default precedence unchanged.
- `tokenEnv` names the fallback env var, replacing the two copied resolvers with one.
### 3. Defaulting and consumption become loops and lookups
`applyDefaults` iterates the registry instead of naming services. Consumers read
`cfg.Services.Get("state")`, returning a `ServiceConnection` plus the spec, so
`stateStoreResolvedToken` and `gatewayResolvedToken` collapse into
`Services.ResolvedToken(name, secrets)`.
## Criteria satisfied
1. Declared once, in the `RegisterService` call.
2. No second location can contradict it; the map has no per-service fields to disagree with.
3. Registration is the entry point, with the five fields a service has.
4. A new service is one `RegisterService` line: no field, no default branch, no consumer edit.
5. The set of services is registry data, not a struct definition.
## Scope and risk
- `state-store-contract.md` §10 must be revised in the same change, or the tree contradicts
its own ratified authority. Its summary (`:7`) already says `[services.<name>]`.
- A typo'd `[services.gatway]` is **reported** (`UnknownKeys = [services.gatway,
services.gatway.target]`), because the struct form leaves it in `toml.MetaData.Undecoded()`.
A map decodes any section, so preserving that is a requirement, not an optional extra:
`unregisteredServiceKeys` asks the registry which names exist. This costs nothing in
extensibility, because the answer comes from registration data rather than a fixed list.
The typo is not silently ignored either way; the behaviour was measured.
- Existing tests reference `cfg.Services.State` directly (`state_store_client_test.go`,
`setup_test.go`, and others). They move to `Get`, mechanically.
- No wire contract, no RPC, and no persisted format is touched. The 42-RPC State Store
contract is unaffected.
## Acceptance
- Adding a third service is a one-line diff plus its consumer, proven by a test that
registers a throwaway service and asserts its defaults and token fallback resolve.
- `grep -rn 'Services\.\(State\|Gateway\)' --include='*.go'` returns nothing.
- The existing `services_test.go` default and precedence assertions pass unchanged in
behaviour, rewritten only to the new accessor.
-195
View File
@@ -1,195 +0,0 @@
# Persistent session-memory curator (reference implementation) -- decision
**Status:** Approved
**Date:** 2026-09-02
**Beads issue:** `archie-core-1786637499114`
**Parent epic:** `archie-core-1786637500725` (curator engine)
**Depends on:** `archie-core-1786637499636` (bind curators to memory
engines, shipped) and the `domain/memory` engine family (shipped)
## Decision
Each pass: find sessions with activity since the last pass, ask the
model to extract a short list of durable observations from each one's
recent messages, and write each through the curator's bound memory
engine. Extraction is **scoped to one session** -- `Observation.Identity`
is the session ID, not a user or cross-session identity. No
consolidation across sessions, no forgetting, no rewriting a prior
extraction: every pass only adds.
This is the second contract consumer the epic asks for, and the one that
exercises the curator/memory-engine binding
(`archie-core-1786637499636`) for real, unlike the skill curator, which
declares no memory engine at all.
## Why session-scoped, not user- or agent-wide
`docs/architecture/migration-decisions.md#5` lists the four required
memory scopes (global, agent-wide, user-wide, agent-user relationship)
as **still open** -- there is no decided mapping yet from a chat session
to a durable identity that would outlive that session (a Telegram chat
ID is not necessarily "the same person" as a web session; per-platform
identity resolution does not exist as a memory concern). Choosing
session-as-identity sidesteps a decision this issue has no business
making unilaterally: it is the narrowest scope that is unambiguous
(`gateway.SessionContext.SessionID` already exists, is already unique,
and already has no cross-platform identity claim attached to it), and
it is forward-compatible -- widening to a resolved user identity later
is a change to what `Identity` is populated with, not to the
extraction or write path.
## Why a new `curator.ConversationSource`, not `gateway.SessionStore` directly
`internal/domain/curator` is a domain package; `internal/gateway` is not
one of `internal/domain/*`'s dependencies by convention, and
`gateway.SessionStore`'s full CRUD surface (branch, fork, replace,
search) is far more than a curator needs or should be able to reach --
the same reasoning `ToolBuilder`/`SkillStore`/`MemoryEngineSource`
already established for every other host service this package depends
on. `curator.ConversationSource` is a two-method read-only interface;
`internal/app/archied` adapts the real `gateway.SessionStore` to it, the
same shape `MemoryEngineSource` already uses for
`domain/memory.Registry`.
```go
// ConversationSource is read-only conversation history, narrowed to
// what a curator needs to review recent activity -- never the full
// session CRUD/branch/search surface a chat gateway exposes.
type ConversationSource interface {
// RecentSessions returns every session touched at or after since,
// newest first.
RecentSessions(ctx context.Context, since time.Time) ([]SessionSummary, error)
// Messages returns the most recent n messages of one session, in
// chronological order.
Messages(ctx context.Context, sessionID string, n int) ([]ConversationMessage, error)
}
type SessionSummary struct {
ID string
LastActive time.Time
}
type ConversationMessage struct {
Role string // "user" or "assistant"
Content string
At time.Time
}
```
`Manifest` gains `Conversations bool`, gated exactly like `Skills`:
`Registry.validateDeclared` requires a `ConversationSource` on the host
when declared, `Registry.filter` clears it from a curator's view when
not. Role is derived the same way `gateway.compressTurnHistory` already
does (`message.From == botUser` -> `"assistant"`, else `"user"`) --
copied logic, not shared code, since the source type
(`gateway.Message`) is exactly the thing this package must not import.
## Extraction shape
`Pass`:
1. `Conversations.RecentSessions(ctx, effectiveSince(in.Since))` -- see
below for the zero-`Since` default.
2. For each session, `Conversations.Messages(ctx, id, 40)` -- the last
40 messages, not the full history. A session accumulates far more
history than a skill file accumulates content; unlike the skill
curator's "re-read everything, it's cheap," a full-history read here
is not cheap and is not needed -- durable facts worth keeping surface
in recent exchanges, and a 40-message tail is deliberately generous
against the model's own context rather than tuned tightly, since
getting this number exactly right is not this issue's job.
3. One model call per session: the message tail, plus an instruction to
return a JSON array of short strings, each one fact/preference/
correction worth keeping, or `[]` if nothing is. Capped at 5 items
per session per pass -- a session that produced more than 5 durable
facts in one pass is the extraction prompt's problem to get more
precise about, not a limit this curator should quietly lift.
4. A response that isn't valid JSON, or that fails to parse, is treated
as "nothing extracted" for that session, not a pass failure -- the
next pass tries again, and this is a curator, not a build gate.
5. Each extracted string becomes one `Write` through
`Registrar.MemoryEngines.Get("builtin")`
(`Observation{Identity: sessionID, Kind: "note", Content: text}`).
One `Action` per session summarises the count and lists the session
ID; a session with nothing extracted gets no `Action`, matching the
skill curator's "a pass with nothing to report is not an error, and
not every subject needs an entry every time."
`effectiveSince`: `PassInput.Since` zero (first pass, or the runtime
declining to name a horizon) resolves to 24 hours before now, not "the
beginning of time." Extracting from a session's entire history on the
very first pass is exactly the kind of unbounded-cost-on-cold-start
mistake `Check` exists to keep cheap, and 24h is long enough to catch
what a daily check-in cadence would have caught anyway.
`Check`: `len(RecentSessions(ctx, effectiveSince(zero-Since))) > 0` --
cheap (no model call), and answers "is there anything a pass would find"
honestly rather than always returning true.
## What we deliberately do NOT do
- **No cross-session or cross-user consolidation.** `Identity` is the
session ID; two sessions from the same human get two disjoint memory
scopes until the open identity-resolution decision in
`migration-decisions.md#5` is made.
- **No re-extraction guard, no deduplication.** A fact mentioned in two
overlapping passes may be written twice. `domain/memory.Query`
ranking/relevance is a read-side concern for whatever later consumes
these observations, not this curator's job to solve by inventing a
dedup index.
- **No `Forget`.** Nothing here decides a memory is stale; that is a
different, harder judgement call than "is this worth keeping," and nothing
reads these observations back into a chat turn to notice if
one turned out wrong.
- **No tool declarations.** `Manifest.Tools` is empty; the model call is
a plain completion (`ChatRequest.Tools` left nil), not agentic
tool-calling -- the extraction task does not need tools, and declaring
none is what keeps `Registrar.Tools` correctly absent from this
curator's view.
- **No feeding extracted observations back into the live system
prompt.** `internal/memory.Manager`'s existing frozen-snapshot
mechanism is untouched, same disclaimer as the memory-engine-contract
and builtin-engine issues before this one: the new `domain/memory`
path and the legacy live path run in parallel by design. Reading these
observations back into a chat turn is later, separate work.
## Acceptance criteria
Restated from the issue against this shape:
1. Registers and runs through `curator.Registry` with no special-casing
-- the existing `Register`/`Runtime` path, no new registry method.
2. Writes through the memory engine contract, never a concrete store:
every write goes through `Registrar.MemoryEngines.Get(name).Write`,
resolved by name at call time exactly like the skill curator resolves
nothing store-specific either.
3. Extraction runs off the hot path: the model call happens inside
`Pass`, which the curator runtime already runs off a chat turn's own
goroutine (existing runtime guarantee, not something this issue
builds).
4. What it wrote and why is inspectable: one `Action` per session with a
count and the session ID, through the existing curator activity
tracker -- no new observability surface.
5. Honours the trigger-accounting invariant: `Manifest.OnInput = true`
wakes it on `events.KindTurnCompleted` via the existing
`WakeOnPrimaryInput` wiring, which already excludes every
curator-derived event kind from the forwarded set -- this curator's
own writes cannot reschedule it, with no new code needed for that
guarantee.
## Files this change adds
- `internal/domain/curator/registrar.go` -- `ConversationSource`,
`SessionSummary`, `ConversationMessage`, new `Conversations` field
- `internal/domain/curator/registry.go` -- `Conversations` gated like
`Skills` in `validateDeclared`/`filter`
- `internal/domain/curator/registry_test.go` -- table cases + fakes for
the new field, mirroring the existing `Skills`/`MemoryEngines` cases
- `internal/infrastructure/sessioncurator/adapter.go` -- wraps
`gateway.SessionStore` as `curator.ConversationSource`
- `internal/infrastructure/sessioncurator/adapter_test.go`
- `internal/infrastructure/sessioncurator/sessioncurator.go` -- the
`CuratorEngine`
- `internal/infrastructure/sessioncurator/sessioncurator_test.go`
- `internal/app/archied/bootstrap.go` -- register it in `setupCurators`,
wired to `b.chatSessionStore` and `b.cfg.BotUser`
-176
View File
@@ -1,176 +0,0 @@
# Skill curator (reference implementation) -- decision
**Status:** Approved
**Date:** 2026-09-02
**Beads issue:** `archie-core-1786637499206`
**Parent epic:** `archie-core-1786637500725` (curator engine)
## Decision
The skill curator's v1 scope is **mechanical validation and safe
normalisation only** -- it never rewrites skill prose, never deletes a
skill, and never calls the model. Each pass:
1. Lists every skill under one configured root.
2. Reads each `SKILL.md` and attempts to parse its frontmatter
(`internal/skill.Parse`).
3. Records an `Action` for any structural problem: a parse failure, or a
missing `name`/`description` in the frontmatter that parsed.
4. Normalises trivial whitespace (trailing whitespace per line, exactly
one trailing newline) and writes back **only** when normalisation
actually changes the bytes, recording an `Action` for that write.
Nothing here needs judgement. "Review, prune, and improve" -- the epic's
framing -- is real for v1 but deliberately narrow: review is structural
validation, improve is whitespace normalisation, and prune is _reporting_
a problem, never removing a skill. `Manifest.Skills = true` still marks
this curator agentic (existing `agentic()` rule), so it receives model
access from the registrar -- unused but nothing about the contract
or the runtime needs to change to let a later version reason about
content quality using it.
## Why this scope, not more
An autonomous process that rewrites or deletes a user's skill content
is a real risk with no undo path (no draft/approval flow for
curator writes exists yet, unlike the workflow engine's PR-based review).
The epic's own stated purpose for this issue is proving the curator
contract holds for a second, structurally different consumer than the
session-memory curator (files-as-skills vs. observations-as-memory), not
solving "what makes a skill good." Mechanical validation is real,
useful, safe to run unattended, and fully exercises
List/Read/Write -- every method `curator.SkillStore` declares except
`Delete`, which this curator's Pass never has a safe reason to call in
v1 (kept implemented on the store adapter regardless, since the
interface requires it and a future consumer may).
## Why `internal/skill` isn't `curator.SkillStore` directly
`internal/skill.Discover` parses every `SKILL.md` under a root and
returns an error for the **whole** call if any one of them fails to
parse -- the read side was built for "load the catalogue to start the
daemon," where one bad skill failing the whole boot is arguably correct,
not for "review each skill and report what's wrong with it
individually." A per-skill parse failure must become one `Action`, not
abort the pass before any skill is reviewed. So
`internal/infrastructure/skillcurator` gets its own thin store adapter
that lists raw directory names and reads/writes raw `SKILL.md` bytes
per name; the skill curator itself calls `internal/skill.Parse` on each
one, isolated per skill.
## Root scope
One root only, resolved the same way `loadWorkflows` already resolves
`skillsBase` (`cfg.SkillsDir`, falling back to `cfg.WorkDir`) -- not
every root `skill.CatalogRoots`/`DefaultRoots` would read for a model
(which layers a shared dir over the per-profile one). Write and Delete
need one unambiguous target; a curator that could write into a shared,
multi-tenant skills directory is a bigger decision than this issue
covers. The model still sees the full multi-root catalogue through the
existing read path -- this curator only maintains the local one.
## Shape
### `internal/infrastructure/skillcurator/store.go`
```go
// Store implements curator.SkillStore over one root directory's
// .agents/skills/*/SKILL.md files, tolerating a per-skill parse failure
// as the curator's problem to report rather than this store's problem
// to abort on.
type Store struct { root string }
func NewStore(root string) *Store
func (s *Store) List(ctx context.Context) ([]curator.SkillRef, error)
func (s *Store) Read(ctx context.Context, name string) (curator.Skill, error)
func (s *Store) Write(ctx context.Context, sk curator.Skill) error
func (s *Store) Delete(ctx context.Context, name string) error
```
`Read` best-effort parses frontmatter for `Skill.Description` (empty on
parse failure -- not this method's job to report that; `Pass` does, via
its own `skill.Parse` call on `Skill.Content`). `Write` rejects a name
that does not already exist as a directory (this store curates existing
skills; creating a new one is out of scope). `Delete` removes the whole
skill directory, matching "delete a skill," not just `SKILL.md`.
### `internal/infrastructure/skillcurator/skillcurator.go`
```go
// Curator implements domain/curator.CuratorEngine. See
// docs/prds/skill-curator.md for what a pass does and why.
type Curator struct { /* unexported: registrar view, interval */ }
func New(interval time.Duration) *Curator
func (c *Curator) Manifest() curator.Manifest {
return curator.Manifest{Interval: c.interval, Skills: true}
}
func (c *Curator) Check(ctx context.Context) (bool, error) // len(skills) > 0
func (c *Curator) Pass(ctx context.Context, in curator.PassInput) (curator.PassResult, error)
```
`Pass` walks every skill via `Bind`'s `Skills` (the filtered
`SkillStore` the registry already narrows to declared curators, see
`Registry.filter`), classifying each into exactly one of:
- **parse failure** -- `Action{Type: "skill.invalid", Reason: "frontmatter failed to parse"}`
- **missing required field** -- `Action{Type: "skill.incomplete", Reason: "name" | "description"}`
- **normalised** -- content changed by whitespace cleanup, written back,
`Action{Type: "skill.normalized", Detail: "<name>: trimmed trailing whitespace"}`
- **clean** -- no action recorded (a pass with nothing to report is not
an error, and not every skill needs an entry every time)
One pass reviews every skill on disk; there is no
per-skill "already reviewed, skip" state; this errs toward re-checking
over missing a regression, and the cost is cheap (no model calls, just
file reads).
## What we deliberately do NOT do
- **No LLM-authored rewrites of skill content.** Real "improve" in the
sense of better prose is out of scope until there is a review/approval
path for autonomous content changes to something a human wrote.
- **No automatic deletion of a skill**, however broken. `Delete` exists
on the store for a future consumer; this curator's `Pass` never calls
it.
- **No dangling-tool-reference checking** (a skill's
`metadata.archie.tools` naming a tool that no longer exists). The
mechanism to check "does this tool exist" belongs to a tool registry
this curator has no access to and shouldn't be given for this --
`curator.ToolBuilder.Build` resolves the curator's _own_ declared
tools, not an arbitrary existence check against skill-referenced
names. A real fix here is a separate, better-scoped issue.
- **No multi-root awareness.** One configured root, matching
`loadWorkflows`'s existing resolution, not the full layered catalogue a
chat turn sees.
- **No new curator-specific webui or chat surface.** Activity is visible
through the existing curator observability surface
(`archie-core-1786637489932`) -- `/api/curators` and
the dashboard Curators page already show any registered curator's
recent actions.
## Acceptance criteria
Restated from the issue against this shape:
1. Registers and runs through `curator.Registry` with no curator-specific
special-casing in the runtime -- proven by using the existing
`Registry.Register`/`Runtime` path, no new registry method.
2. Its changes to skills are observable and attributable -- every write
is preceded by an `Action` recording what changed and why, surfaced
through the existing curator activity tracker.
3. It operates within its declared tool set and cannot reach tools it
did not declare -- `Manifest.Tools` is empty; nothing about this
curator ever touches `Registrar.Tools`.
## Files this change adds
- `internal/infrastructure/skillcurator/store.go` -- `curator.SkillStore` adapter
- `internal/infrastructure/skillcurator/store_test.go`
- `internal/infrastructure/skillcurator/skillcurator.go` -- the `CuratorEngine`
- `internal/infrastructure/skillcurator/skillcurator_test.go`
- `internal/app/archied/bootstrap.go` -- register it in `setupCurators`, root
resolved the same way `loadWorkflows` resolves `skillsBase`
-142
View File
@@ -1,142 +0,0 @@
# SOUL: an agent's user-authored personality
**Status:** Draft
**Authority:** `docs/architecture/identity.md`, “Three-layer identity model”;
`docs/prds/orgs-and-access.md` for identity and org ownership.
## Decision
SOUL supplies an agent's name, register and warmth. It belongs to the agent's
immutable `IdentityID`, not its session, model, installation or container
profile. Rename preserves it; changing a profile does not change who acts.
SOUL never changes attribution, credentials, grants or identity lifecycle.
`config.AgentProfile` remains an execution environment, not another identity.
Use the existing three layers: invariants, user-authored SOUL, and curator-derived
representation. Curators may propose SOUL changes but never apply them.
## Files and ownership
The config directory is `${XDG_CONFIG_HOME:-~/.config}/archie`, or the directory
of an explicitly selected config file. The default/root agent uses `SOUL.md`
directly there; additional agents use `agents/<identity-id>/SOUL.md`. The root is
the identity selected by application composition, never the initiating user or
a session's personality selection. No file creates or selects an identity.
The common case keeps a human-friendly filename; additional agents get separate
asset directories, following `.agents/skills/<name>/SKILL.md` without confusing
these directories with `[containers.profiles.<name>]`. Reject display-name or
slug directories: rename and same-name agents across orgs would require another
name-resolution rule. Immutable IDs avoid both problems without an org directory.
When a file-owned agent's file is absent, create the shipped default with
exclusive creation. Never overwrite an existing file, including an empty one.
A creation failure still permits the turn using the embedded shipped default.
Ship that document independently of `agent.ShippedPersonas`, so deleting personas
cannot delete the fallback.
Resolve once at the start of every new generation:
1. A stored SOUL entry for the acting identity is authoritative.
2. Without an entry, read that identity's file again.
3. An absent, empty, unreadable or invalid selected source uses the shipped default.
The first explicit dashboard/API save takes ownership permanently. Thereafter
file edits are ignored: emit one ownership notice and show the owning stored
version in the dashboard. Restoring the shipped default writes a stored value;
it does not remove ownership. Refuse writes that remove an owned entry.
This ownership boundary is the design's one stateful rule. Files seed the
editable value, not an automatic durable import. Reject seed-once import because
it breaks next-message file editing; reject file-always-wins because it makes
dashboard saves ineffective. Neither a restart nor an upgrade overwrites an
owned value, following the precedence of `controlplane.AgentProfileKind` without
copying its startup import timing.
## Prompt and failure contract
Keep `archie.md.tpl`'s XML-escaped
`<soul purpose="identity_and_style" trust="data">` block before
`<instruction_precedence>`. SOUL is style reference data; the invariant sections,
tool inventory and runtime metadata remain authoritative and uneditable.
Preserve `TestBuildSystemPromptSoulCannotOverrideInvariants`.
Accept UTF-8 plain Markdown with at most 8 KiB in its XML-escaped body. This bounds
personality to a small prompt contribution; count the complete rendered prompt
in the turn's context budget and never truncate invariant sections. Bound file
reads before decoding; reject oversize input rather than truncating instructions.
File and stored writes use the same validator; an invalid save leaves the stored
version unchanged. The shipped default must pass that validator.
Read and creation errors never fail a turn. Log once per identity/source failure
episode, retry on the next turn, and allow a new warning after recovery. If the
store cannot establish whether an owned entry exists, use the shipped default,
not a potentially shadowed file. Do not log SOUL text. Each turn keeps its resolved
snapshot; edits affect the next generation without restart or SIGHUP.
## Cross-layer delivery
- `internal/domain/agent` owns SOUL content validation and the identity-keyed read
contract; `internal/domain/identity` remains the actor/lifecycle authority.
- The configuration infrastructure resolves the config directory and handles
file discovery, exclusive default creation and bounded per-turn reads.
Application composition resolves the acting `IdentityID` through the existing
identity repository/bindings and supplies it to the gateway.
- Register `SoulKind` (`agent-souls`) in the control plane with a live descriptor
and an org-scoped document mapping identity IDs to `{text}`. Persist it through
the State Store's existing resource/history contracts, not a new table,
process or SOUL RPC. An empty map owns no identity; saves preserve other entries
and use expected-version checks. Validate that each key is an agent identity
in the resource's org; begin with the default org without inventing org setup.
Every save records the authenticated editor's identity, source, request ID and
timestamp; file installation records the system identity, not a fictitious user.
- Replace `TurnRunnerConfig.Personas` / `PersonaPromptSource` with the per-identity
source in `prepareTurn`; name the `SystemPromptConfig` input SOUL. Both normal
and streaming turns use this assembly path. Do not add personality to the
worker environment, `AgentProfile` or workflow-stage prompts.
- On an agent identity's dashboard page, expose its effective SOUL, file/default
or stored source, shadowed file path, owning version, and Markdown editing.
Save to the control plane, never the host file; show validation/version
conflicts and offer restoring shipped content or a history revision as a save.
Read effective file/default content and ownership metadata through a gateway
query using the turn resolver; the separate UI process never reads the
gateway host's files. Apply identity-management access rules and the existing
shared live-update hub.
- Update `docs/development/agent.md` and `control-plane.md` with this reach and
precedence, `frontend-ui.md` with the gateway query, and the config wiring
guidance with a copyable file example.
## Persona removal gate
SOUL supersedes `PersonaRegistry` and the persona-reconciliation proposal;
identity-per-action supersedes personas as an identity mechanism.
`PersonaRegistry.GetActive` composes the baseline with one of five styles from
`agent.ShippedPersonas`; SOUL replaces the baseline, not that style catalogue.
Per-session switching disappears: remove `/personality`, Telegram personality
callbacks, the dashboard persona page, and chat wire fields `personas`,
`active_personas` and `personas_available` without reusing their field numbers.
Do not merge session selections into SOUL or retain a separate style axis.
Custom persona text must remain available to copy before deleting its stored
resource; no migration guesses one agent's SOUL from several sessions.
Remove persona loading, selectors and commands only after every chat composition
supplies the identity-aware SOUL source, the fallback renders without personas,
and the dashboard can edit it. SOUL delivery does not wait for org creation or a
new container-profile model.
## Acceptance
- Two agents use distinct files and stored entries; renaming one or sharing a
container profile does not change or mix their SOULs.
- Before ownership, a file edit changes the next normal or streaming prompt;
creating defaults never clobbers an existing file.
- After a save, conflicting file edits and restarts cannot override the stored
value; the ignored file and owning version are visible. Updating one agent
preserves the other; stale saves fail and history restores are audited saves.
- Missing, empty, unreadable, malformed and oversize selected inputs render the
shipped default. Repeated read failures log once, recover on a later turn,
and never abort generation.
- Hostile markup stays escaped before singular, unchanged invariant blocks;
prompt budgeting includes SOUL and cannot drop the rules.
- Dashboard edits reach the next generation without restart; persona removal
leaves every channel with a nonempty identity slot and preserved custom text.
-748
View File
@@ -1,748 +0,0 @@
# State Store — contract boundary & transport (ratification)
**Status:** Approved
**Revision:** 2e
**Date:** 2026-09-06
This is the pre-implementation design document that Phase 2 subtasks `.4.2` (generalise
`storerpc` as the State Store gRPC contract) and `.4.3` (stand up `archie-state-store`)
implement against.
**Beads milestone:** archie-core-8cda.4.1
**Parent:** `docs/prds/service-decomposition.md` (open-question Q4 **RESOLVED**)
This document fixes the **contract boundary** and **transport** for the State Store service.
It does not redesign Archie's domain model, does not invent a second store, and does **not**
split `archie.db`. It records method ownership, DTO/wire representation, error semantics,
limits, mode/config shape, local-adapter compatibility, and cutover/deletion rules so that
`.4.2` and `.4.3` have exactly one authoritative surface to build against.
> **Storage superseded.** The store behind this contract is PostgreSQL:
> `internal/infrastructure/postgres` implements the producer-owned interfaces in
> `internal/domain/storecontract` and `workflow.Store`, over the database
> `database_url` names. `internal/store`, the SQLite file and the local adapter
> are gone; where this document says `archie.db`, `*store.Store` or
> `internal/store`, read the State Store's PostgreSQL database and
> `internal/infrastructure/postgres`. The contract, ownership split, error
> semantics and cutover rules stand.
> **Current state — read before `.4.2` starts.** The §12 step 2 relocation (`archie-core-8cda.
4.8`) has landed: `Task`/`Status*`/`Source*` and the 3-method `workflow.Store` now live in
> `internal/domain/workflow`, the six production workflow files import no `internal/store`
> symbol, and `storerpc`/the NATS transport assert against `workflow.Store` instead of
> `store.WorkflowStore`. The broader Phase 2 acceptance criterion (State Store as its own
> service behind gRPC) is still open — that is what `.4.2`/`.4.3` build next.
> **Relationship to migration-decisions §4 — not replaced.** `docs/architecture/
migration-decisions.md` §4 (`store.Task → WorkflowExecution`, `mutable Stage →
StepExecution history`, `RetryCount/Attempt → Attempt records`, versioned Workflow defs)
> **remains the authoritative, open document for the long-term Workflow migration.** This PRD
> does **not** replace it. It only pulls the minimal `Task`/`Status`/`Source` type + interface
> relocation forward as a Phase 2 prerequisite (because the acceptance criterion requires it);
> the rest of §4 stays its own migration and stays open.
---
## 1. Decision (the invariant everything follows)
Archie is composed such that a single **`archie-state-store`** service owns the one existing
SQLite file (`archie.db`) and exposes it over **gRPC behind narrow typed contracts**. There is
exactly one store, one file, one service. No database-per-service, no distributed
transactions, no second store abstraction.
Two adapter families satisfy the contract interfaces:
- **Local adapter** — `*store.Store` (the in-process SQLite implementation).
- **Remote adapter** — `*staterpc.Client` (wraps the generated gRPC client).
Each adapter carries an explicit compile-time assertion against the contract interfaces it
serves. Composition picks local vs. remote by the presence of `[services.state].target`
(empty = local; set = dial the gRPC service). Default is **local** (the State Store is not yet
extracted), which is the PRD §3 posture; it differs from the gateway's remote-default only
because the gateway is already a separate deployment and the State Store is not.
> **Contract-ownership fork, decided (rev. 2c — resolves the domain contradiction).**
> Ownership splits by the consumer's _layer_, per the dependency contract's rule #2
> ("a domain defines the smallest interfaces required to perform its work") and rule #7
> ("database rows … MUST NOT leak into domain models"):
>
> - The **workflow domain** (`internal/domain/workflow`) is the only domain-layer consumer of
> store state. It defines its own **consumer-owned** narrow `Store` interface
> (Update/Transition/InsertEvent) and its own **domain-owned** `Task` type plus
> `Status`/`Source` vocabulary. It imports **zero** `internal/store` symbols — satisfying the
> Phase 2 acceptance criterion. This is the minimal bound of migration-decisions §4
> (`store.Task → WorkflowExecution`), pulled forward **because** the acceptance criterion
> requires it.
> - The **daemon / webui / intake** store surfaces (`TaskStore`, `CaptureStore`,
> `MappingStore`, `BindingStore`, `BindingDispatcher`, `BindingTaskCreator`) stay
> **producer-owned** in `internal/store`, because those consumers are application and
> infrastructure layers, not domains — rule #2 does not apply to them.
So the State Store contract is **not** uniformly producer-owned: the domain-facing workflow
contract is consumer-owned (in the domain), while the daemon/webui store surfaces remain in
`internal/store`. `internal/store` imports `internal/domain/workflow` for the `Task`/`Status`/
`Source` types it persists (persistence → domain, the correct direction), and its `Store`
implementation satisfies `workflow.Store`. This is the single decision that makes the whole
Phase 2 acceptance criterion and the architecture's rules simultaneously satisfiable.
> **`internal/store` is a TRANSITIONAL compatibility location (rev. 2c).** The repository's target
> architecture (`docs/architecture/dependencies-and-contracts.md`, `organisation.md`) places
> persistence implementations under `internal/infrastructure/<capability>`. `internal/store`
> holding the task/capture/mapping/binding implementation and ALSO being the home of the
> producer-owned daemon/webui interfaces is acceptable **only as a transitional location**. The
> long-term home for the store implementation is `internal/infrastructure/store`; the
> producer-owned interfaces may move to the same infrastructure package (or an approved
> contract location) when the store implementation relocates. Agents must not treat
> `internal/store` as the final infrastructure boundary.
>
> **REV. 2d (archie-core-8cda.5.6): the producer-owned interfaces HAVE moved to an approved
> contract location** — `internal/domain/storecontract` (package `storecontract`), ahead of the
> store implementation's own relocation. The UI Service deletion gate required the archie-ui
> process to hold the contracts without linking `internal/store`'s SQL implementation, and
> `internal/contracts/` itself is ruled out: that tree is the `buf generate` output and
> `tools/proto.sh check` deletes hand-written files there. `internal/store` keeps type aliases
> (`type TaskStore = storecontract.TaskStore`, the sentinel `var`s, the value types) so
> daemon-side callers are unaffected; the sentinel message strings are unchanged and remain
> the wire contract (§4).
---
## 2. Contract boundary
**Ownership split** (see the fork in §1): the **workflow-domain consumer contract** is
`workflow.Store` (consumer-owned, in `internal/domain/workflow`); the **daemon/webui/intake
store surfaces** are the producer-owned interfaces in `internal/store/interface.go`.
`store.WorkflowStore` is **superseded** — it is replaced by the domain-owned `workflow.Store`,
and `internal/store`'s `Store` implementation satisfies `workflow.Store` directly. `TaskStore`
remains the only composite; every other interface is flat. Narrow slices are split along
consumer-capability lines so no consumer acquires a surface it does not need
(`interfacebloat` cap = 8).
| Interface (owner) | Embeds | Methods | Local impl | Remote impl |
| ---------------------------------- | --------------------------------------------------------------------------- | ---------- | ---------- | ------------------ |
| `TaskStore` (store) | `TaskLifecycle`, `TaskEvents`, `TaskQueries`, `TaskArchiver`, `TaskRetryer` | 24 (union) | `*Store` | `*staterpc.Client` |
| `TaskLifecycle` (store) | — | 8 | `*Store` | `*staterpc.Client` |
| `TaskEvents` (store) | — | 7 | `*Store` | `*staterpc.Client` |
| `TaskQueries` (store) | — | 7 | `*Store` | `*staterpc.Client` |
| `TaskArchiver` (store) | — | 1 | `*Store` | `*staterpc.Client` |
| `TaskRetryer` (store) | — | 1 | `*Store` | `*staterpc.Client` |
| `workflow.Store` (workflow domain) | — | 3 | `*Store` | `*staterpc.Client` |
| `CaptureStore` (store) | — | 2 | `*Store` | `*staterpc.Client` |
| `MappingStore` (store) | — | 5 | `*Store` | `*staterpc.Client` |
| `BindingStore` (store) | — | 6 | `*Store` | `*staterpc.Client` |
| `BindingDispatcher` (store) | — | 3 | `*Store` | `*staterpc.Client` |
| `BindingTaskCreator` (store) | — | 1 | `*Store` | `*staterpc.Client` |
| `PlaybookDispatcher` (store) | — | 2 | `*Store` | `*staterpc.Client` |
**Key property of the remote client:** `*staterpc.Client` is a _single_ adapter that wraps one
`StateStoreClient` and is asserted against **whichever narrow Go interfaces its caller needs**
(exactly as `gatewayrpc.Client` asserts both `gateway.ChatContract` and
`gateway.SessionStore`). The Go contracts stay narrow (≤8, the `interfacebloat` cap); the wire
is one service. `workflow.Store` introduces **no new RPCs** — it is a narrow consumer face over
the same `Update`/`Transition`/`InsertEvent` RPCs.
---
## 3. Method ownership
`*Store` remains the single implementation of the daemon/webui store surfaces and of
`workflow.Store`. Ownership below is about which **process** is the primary consumer of each
method and therefore which methods are genuinely cross-process on the wire vs.
daemon-internal.
Process legend: **DAEMON** = `archied` (incl. in-process webui + gateway runtime +
`storerpc.Server`); **AGENT** = `archie-agent` worker (no DB connection); **GATEWAY** = store
access through daemon-side narrow adapter interfaces.
| Contract | Primary consumers (process) | Remote on the wire? |
| ------------------------ | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| `TaskLifecycle` (8) | DAEMON (dispatch, claim, action) + **AGENT** (`Transition`, `Update` via storerpc) | `Transition`/`Update` = **YES** (agent); rest DAEMON |
| `TaskArchiver` (1) | DAEMON (`taskactions` archive) | not yet |
| `TaskRetryer` (1) | DAEMON (`taskactions` retry) | not yet |
| `TaskQueries` (7) | DAEMON + GATEWAY (status/list adapters) | not yet (`OpenPRs`/`Tasks`/`StatusCounts` cross to gateway adapters in-process) |
| `TaskEvents` (7) | DAEMON + **AGENT** (`InsertEvent` via storerpc) | `InsertEvent` = **YES** (agent); rest DAEMON |
| `workflow.Store` (3) | **AGENT** only | **YES** (the sole genuinely remote consumer) |
| `CaptureStore` (2) | DAEMON (webhook intake + mapping editor) | not yet |
| `MappingStore` (5) | DAEMON (dashboard editor + dispatch loop) | not yet |
| `BindingStore` (6) | DAEMON (dashboard editor + dispatch loop) | not yet |
| `BindingDispatcher` (3) | DAEMON (dispatch loop) | not yet |
| `BindingTaskCreator` (1) | DAEMON (dispatch loop) | not yet |
| `PlaybookDispatcher` (2) | DAEMON (EDA playbook dispatch loop) | **YES** (side-effecting-action idempotency ledger over gRPC) |
**Consequence for migration order:** the **agent's `workflow.Store` is already cross-process
already** (via the NATS `storerpc` surrogate), so it is the first contract to move to gRPC. The
daemon-internal surfaces (`Capture`/`Mapping`/`Binding`) stay in-process until the daemon
itself points at `archie-state-store`. `TaskStore` (the large composite) moves last.
**Two orphan methods** — `TaskQueries.ClearTerminalTasks` and
`TaskQueries.IncrementRetryCount` have **no production consumer** (only `*Store` tests). They
remain part of the Go `TaskQueries`/`TaskStore` surface, and therefore part of the wire
contract, but are flagged for deletion: they must **not** gain dedicated consumers or wire
methods in this work. Do not add the rest of the codebase to them.
---
## 4. Domain-facing types & consumer-owned contract — resolves the contradiction
The Phase 2 acceptance criterion ("`internal/domain/workflow` … no longer import
`internal/store` directly — they call the State Store contract") **cannot be met while**
`store.Task`, `store.Status*`, `store.Source*`, and `store.WorkflowStore` live in
`internal/store`. This section fixes where they move.
**The relocation (a prerequisite that must land before or with `.4.2`):**
| Current symbol (`internal/store`) | Moves to | Notes |
| ------------------------------------- | -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `Task` type | `internal/domain/workflow.Task` | The task-execution record the workflow domain operates on. `internal/store` persists this type (persistence → domain). |
| `Status` + `Status*` constants | `internal/domain/workflow` | e.g. `StatusClosedWontDo`, `StatusMerged`, `StatusPROpen`, `StatusWaitingHuman`, `StatusRunning` — task-lifecycle vocabulary. |
| `Source` + `Source*` constants | `internal/domain/workflow` | e.g. `SourceChat` — provenance vocabulary, follows `Task`. |
| `WorkflowStore` interface (3 methods) | `internal/domain/workflow.Store` | **Consumer-owned** (dependency rule #2). Supersedes `store.WorkflowStore`. |
**Resulting dependency direction (correct per the architecture):**
- `internal/domain/workflow` imports **no** `internal/store` symbols → the acceptance
criterion is satisfied. It consumes `store.Task`'s replacement as `workflow.Task`, uses
`workflow.Status*`/`workflow.Source*`, and depends on its own `workflow.Store` interface.
- `internal/store` imports `internal/domain/workflow` for the `Task`/`Status`/`Source` types it
reads and writes (infrastructure → domain). **NOTE: `internal/store` is a transitional
compatibility location only** — its long-term home is `internal/infrastructure/store` (see
the callout in §1). Do not treat `internal/store` as the final infrastructure boundary.
- Every store test that constructs `store.Task{…}` is updated to the relocated type as part of
this prerequisite. This is a mechanical rename across ~6 workflow production files
(`workflow.go`, `steps.go`, `triage.go`, `review.go`, `feasibility.go`, `implement.go`) and
their tests plus the store tests. `TestRecordDispatchViaExplicitTx` is removed rather than
updated — its non-nil `*sql.Tx` path has no production consumer (see §5's `RecordDispatch`
blocker).
**What this does NOT do:** it does not implement the full §4 Workflow migration
(`mutable Stage → StepExecution history`, `RetryCount/Attempt → Attempt records`,
`workflow.Registry → versioned Workflow definitions`, etc.). It lands only the minimal
task-type + `Status`/`Source` + consumer-owned-interface relocation that the Phase 2
domain-decoupling criterion requires. The residue of §4 remains its own migration.
**Forward-compatibility:** because the wire DTOs are derived from the domain `Task`/`Status`
(§5), when the full §4 migration later renames `workflow.Task` (or refines it into
`WorkflowExecution`), only `values.go` and the proto field mapping change — the RPC surface and
consumer interfaces are unaffected. The wire contract is deliberately type-agnostic at this
level.
---
## 5. DTO / wire representation
### Proto layout
- **Service:** `proto/state/v1/state.proto`, `package state.v1`, **one** `StateStore` service
(mirrors the gateway's single `ChatService`; proto bypasses the Go `interfacebloat` cap, as
`ChatContract` does via `//nolint:interfacebloat`).
- **Codegen:** the existing buf v2 pipeline. `proto/buf.yaml` (module, lint STANDARD, breaking
FILE against `main`), `proto/buf.gen.yaml` **managed mode** with
`go_package_prefix → github.com/samcharles93/archie-core/internal/contracts`, plugins
`protoc-gen-go` + `protoc-gen-go-grpc`, `out: ../internal/contracts`,
`opt: paths=source_relative`. **No `go_package` in source** — managed mode owns it. Generated
Go lands in `internal/contracts/state/v1/` (package `statev1`), committed (`proto:check`
fails on uncommitted/unmodified generated files).
- **Adapter package:** `internal/infrastructure/staterpc/` with `server.go` (registers the
generated server over the store), `client.go` (wraps the generated client into `store.*` and
`workflow.Store` facades), `values.go` (proto ⇄ domain mappers), and `conformance_test.go`
(bufconn local-vs-grpc dual-adapter suite), mirroring `internal/infrastructure/gatewayrpc/`.
- **Binary:** `cmd/archie-state-store/main.go`, mirroring `cmd/archie-gateway/main.go` and the
serve pattern in `internal/app/archied/gateway.go` (`serveGateway`).
### The `StateStore` RPC set (union of the contracts, grouped)
Methods are named after the store methods so the mapping is unambiguous. `workflow.Store` is a
_view_, not new RPCs — `Update`/`Transition`/`InsertEvent` are shared with
`TaskLifecycle`/`TaskEvents` and appear once.
| Group | RPCs |
| ------------------ | -------------------------------------------------------------------------------------------------------------------------- |
| Lifecycle | `EnqueueIssue`, `EnqueueChatTask`, `ClaimNext`, `ClaimByIssue`, `Transition`, `Update`, `Requeue`, `RecoverStale` |
| Archive / Retry | `ArchiveTask`, `RetryTask` |
| Queries | `TaskByIssue`, `OpenTaskByPR`, `TaskByID`, `OpenPRs`, `ClearTerminalTasks`, `Tasks`, `StatusCounts`, `IncrementRetryCount` |
| Events | `InsertEvent`, `EventsSince`, `TaskEvents`, `WorkflowStats`, `StageStats`, `TokensByDay` |
| Capture | `InsertCapture`, `ListCaptures` |
| Mapping | `InsertMapping`, `GetMapping`, `ListMappings`, `UpdateMapping`, `DeleteMapping` |
| Binding | `InsertBinding`, `GetBinding`, `ListBindings`, `UpdateBinding`, `DeleteBinding`, `ApproveBinding` |
| Dispatch | `ArmedBindingsForSource`, `RecordDispatch`, `ListUndispatchedCaptures` |
| Playbook | `RecordPlaybookDispatch`, `DeletePlaybookDispatches` |
| WorkflowCaller | `EnqueueCallTask`, `WorkflowCallStatus` |
| Step executions | `StartStep`, `FinishStep` |
| BindingTaskCreator | `EnqueueBindingTask` |
| Config snapshot | `PutConfigSnapshot`, `GetConfigSnapshot` |
| Apply status | `PutApplyStatus`, `ListApplyStatus` |
| Channel status | `PutChannelStatus`, `ListChannelStatus` |
| Task log | `ReadTaskLog`, `StreamTaskLogContent` |
That is **55 unique contract RPCs** across one service (the `TaskEvents.Close` method is dropped).
`Close()` is **excluded** from the wire (it is server lifecycle, not a client call) — see §11.
The channel-status pair follows the config snapshot's split for the same reason: the writer is the process that HOSTS the channels -- the Messaging Service, which alone observes whether a channel is starting, running or failed -- and the reader is the UI process. Both RPCs are administrative, so a task-scoped grant reaches neither. A channel's state is runtime state rather than a settings document, which is why it is not a `ControlPlaneService` resource kind: a failed channel is not a document anybody edits. Asking for a reload travels on its own surface rather than through this one; see `docs/architecture/migration-decisions.md`, "Channel state to the dashboard".
The config-snapshot pair was added by `archie-core-ymut` (see
`docs/architecture/migration-decisions.md`, "Dashboard configuration page"). It is the one
surface whose writer is the daemon and whose reader is the UI process, and both RPCs are
administrative: `authorizesTaskScopedCall` is deny-by-default, so a task-scoped grant reaches
neither. `ConfigSnapshot.document` is opaque to this contract — the store neither parses nor
validates it, and `schema` names the projection so a reader can refuse a shape it does not
understand.
The apply-status pair was added by `archie-core-pskb` (see
`docs/prds/control-plane-apply-status.md`). It is administrative for the same reason as the
config-snapshot pair, and deny-by-default in `authorizesTaskScopedCall` covers it without a
new rule. Unlike that pair, the read is a list: `ListApplyStatus` returns every process's
record and an empty slice means nothing has reported yet, so the `found=false` convention for
absent single rows does not apply. The rows are keyed on `(process, kind)` and replaced in
place, because each process re-stamps its record on an interval and no reader wants a history
of re-stamps.
The task-log pair was added by `archie-core-iaqx` (see `docs/prds/ui-service-boundary.md`'s
route inventory). It is the one surface whose payload is not a row: the store service reads
them out of the state directory it owns with `internal/logging`'s own reader, so the wire
carries `logging.Entry`/`logging.Query` values and neither side restates the JSONL format.
`ReadTaskLog` returns a decoded page and `StreamTaskLogContent` returns the raw bytes
server-streamed, because a log file rotates at 20 MB — past gRPC's 4 MiB unary cap — and the
same reasoning that made `StreamCaptures` supersede `ListCaptures` applies. `found=false` with
no error means the attempt has no log; a service with no reader answers `Unavailable` instead,
and the two answers are load-bearing for the dashboard: only the second is a deployment
condition, and the panel that collapsed them told operators task logging was switched off when
it was not. The Go facade is `storecontract.TaskLogStore` (2 methods), carried by
`*staterpc.Client` alongside the rest.
The step-execution pair was added by the execution tree's plan item 3 (see
`docs/prds/execution-tree-state-machine.md`), the surface a task-scoped grant reaches for
its own execution beyond the three `task.Store` RPCs and the workflow-caller pair: the
container records its stages and its own agent calls with the run credential. Both requests
carry the caller's execution ID, which the grant check verifies; `FinishStep` additionally
verifies, handler-side, that the step really is that execution's. The store writes each
transition's `stage_start`/`stage_finish` event row in the same transaction and returns it
for the caller's post-commit bus publish. `called_execution_id` is stored for the `call`
kind but not yet carried on the wire: the named consumer is the workflow-call recording
that will set it.
The workflow-caller pair was added by `archie-core-t2db.41` (see everything else from the caller's
row and refuses a caller that is not running or a call past the depth limit
(`ErrCallCallerNotRunning` / `ErrCallDepthExceeded`), and `WorkflowCallStatus`
re-checks the parent-child relation against the row before answering
(`ErrCallNotYours`), so the interceptor itself never reads the database. The
facade is `workflow/task.Caller` (2 methods), carried by `*staterpc.Client`
and the PostgreSQL store alike.
The playbook pair was added by `archie-core-t2db.17`'s implementation (see
`docs/prds/eda-playbook-engine.md`, execution-time gap 2). It is administrative
for the same reason as the config-snapshot and apply-status pairs, and
deny-by-default in `authorizesTaskScopedCall` covers it without a new rule. The
row is the structural `(playbook_id, playbook_version, event_id, action_id)`
tuple, written **before** the action's side effect fires (the reverse of
`binding_dispatches`), so a duplicate returns `store.ErrAlreadyDispatched` and
the coordinator skips the invoke rather than repeating a non-revocable side
effect. `DeletePlaybookDispatches` is the explicit reclamation primitive; nothing
calls it automatically, because a playbook file's absence at boot is not a
deliberate removal (`eda-playbook-engine.md`, "Lifetime"). The Go facade is
`storecontract.PlaybookDispatcher` (2 methods), carried by `*staterpc.Client`
alongside the rest.
### Domain types and `values.go` mapping
`values.go` maps proto ⇄ these types. The task model for the **agent** path is the domain-owned
`workflow.Task` (§4); the daemon/webui store surfaces return the same `workflow.Task` (the store
persists the domain type).
| Domain type | Package | Notes for `values.go` |
| ------------------------------------- | -------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `workflow.Task` | `internal/domain/workflow` | time fields stored as layout strings; convert to/from `google.protobuf.Timestamp` |
| `events.Event` | `internal/events` | `Timestamp` → `google.protobuf.Timestamp` |
| `store.CapturedEvent` | `internal/store` | headers/body/remote_addr; body capped 256 KiB |
| `mapping.Mapping` | `internal/domain/mapping` | JSON-path field bindings |
| `binding.Binding` | `internal/domain/binding` | secret is **already decrypted** before returning; keep decrypted form out of any durable/logged representation |
| `workflow.Status` / `workflow.Source` | `internal/domain/workflow` | enum-like; map to proto enum or string, keeping the names stable for compatibility |
| `store.WorkflowStat` | `internal/store` | aggregate row |
| `store.StageStat` | `internal/store` | aggregate row |
| `store.DayTokens` | `internal/store` | aggregate row |
### Wire-contract blocker fixed here: `RecordDispatch`
`store.BindingDispatcher.RecordDispatch(ctx, tx *sql.Tx, bindingID, bindingVersion int64,
captureID int64, taskID int64) error` takes a **`*sql.Tx`** that cannot cross a gRPC boundary.
**Evidence that the `*sql.Tx` is removable:** the dispatch loop calls `RecordDispatch(ctx, nil,
…)` (`internal/daemon/daemon.go`). The implementation falls back to the store's own
`*sql.DB` when `tx == nil` ("best-effort, not atomic"; the comment and the
`TestRecordDispatchViaExplicitTx` test are the only consumers of the non-nil `tx` path).
Production never opens the explicit transaction.
**Decision:** the contract drops `*sql.Tx` from `RecordDispatch` (the method becomes
`RecordDispatch(ctx, bindingID, bindingVersion, captureID, taskID) error`). The store service
owns any transaction boundary internally when atomicity is wanted; the at-most-once
guarantee is the `INSERT OR IGNORE` dedup row, which is already transactionless in production.
`TestRecordDispatchViaExplicitTx` is superseded by the store service's own internal-transaction
test. **This is a required interface migration that must land before or with `.4.2`** (the
current `interface.go` signature and test still use the transaction-bearing form).
---
## 6. Agent State Store client handoff
Moving the agent from NATS `storerpc` to gRPC `workflow.Store` requires the agent process to
receive a State Store endpoint. The agent already receives its NATS connection settings via
boot-time env/flags (see `cmd/archie-agent/main.go`: `-nats-url` / `NATS_URL`, `NATS_TOKEN`
env), and the daemon injects them into the task container. The State Store handoff follows the
same seam.
**Boot handoff contract (additive, not replacing the NATS settings):**
| Field | Where | Source | Notes |
| ------------------ | ---------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------- |
| `StateStoreTarget` | `agentworker.Settings` | env `STATE_STORE_URL` (or `-state-store-url` flag), set by the daemon in the container env | `host:port` of the State Store gRPC server. Loopback/Docker-bridge address — the agent reaches it the same way it reaches the daemon's NATS. |
| `StateStoreToken` | `agentworker.Settings` | env `STATE_STORE_TOKEN` (or `-state-store-token` flag) | Per-task bearer token carried in gRPC metadata by a client interceptor (see §9). |
| `StoreTimeout` | `agentworker.Settings` | a bounded per-call timeout | Mirrors `natsrpc.Client.Timeout` / the existing `rpcTimeout`; bounds each State Store call when the caller `ctx` has no deadline. |
**Wiring change in the transport façade:**
- `internal/infrastructure/agenttransport/nats.Transport` — `Store(timeout) store.WorkflowStore`
returns `&storerpc.Client{Conn: t.conn, Timeout: timeout}`. It becomes
`Store(timeout) workflow.Store` and returns a _single long-lived_ `staterpc.Client` dialled to
`settings.StateStoreTarget` (with the token interceptor and per-call timeout).
- `internal/app/agentworker/worker.go` `Settings` gains the three fields above; `taskServiceTransport`
and `taskDependencies` change their `store` type from `store.WorkflowStore` to
`workflow.Store` (via `domain/workflow.TaskContext{Store: …}`).
- Reconnect/deadline: `grpc.NewClient` (or the existing dial path) provides transparent reconnect;
each RPC is bounded by the per-call context deadline (`StoreTimeout`), matching the
request/reply timeout the NATS path used. No streaming is involved, so no server-sent
reconnect semantics apply.
**Deletion rule for the NATS path:** the NATS `storerpc` (Server, Client, subjects
`archie.store.update|transition|insert_event`) is deleted **only after** the agent has fully
moved to gRPC and the container env carries `STATE_STORE_URL`. Until then both paths may coexist
(agent flips when the daemon starts injecting `STATE_STORE_URL`); there is no dual-live window
across a single agent process, which is either NATS-backed or gRPC-backed, never both.
### Operational specifics (in-process listener → address → per-task injection)
- **Who binds the in-process State Store listener:** the daemon (`archied`), at bootstrap, when
the State Store is served in-process/multiplexed (mirroring `serveGateway` in
`internal/app/archied/gateway.go`): a `grpc.NewServer()` + `RegisterServer` + graceful stop on
`ctx.Done()`.
- **Address selection (Docker-bridge reachable):** reuse the host-gateway resolution already used
for embedded NATS (`internal/container/network.go` `RequireHostGateway` /
`resolveHostGateway`). Per §9's single listener-topology rule, the listener binds the
**host-gateway bridge address** when agent containers consume it (the Phase 2 default), or
loopback-only when the daemon is the sole consumer. The chosen address is stored on the daemon
as `d.ConnectedStateStore.URL` (analogous to `d.ConnectedNATS.URL`).
- **Per-task injection:** `containerEnv(task)` (`internal/daemon/daemon.go`) appends
`STATE_STORE_URL=<d.ConnectedStateStore.URL>` and `STATE_STORE_TOKEN=<token>` alongside the
existing `NATS_URL`/`NATS_TOKEN`. The agent reads them via env (`-state-store-url` /
`STATE_STORE_URL`, `-state-store-token` / `STATE_STORE_TOKEN`), the same seam as `NATS_URL`. A
reloaded `[services.state]` must not point new containers at a store the daemon is not serving
— the same immutability rule as NATS.
---
## 7. Error semantics
### Current state (both boundaries lose error identity)
- **NATS `natsrpc.Envelope`** (`internal/natsrpc/natsrpc.go`) serialises any error to a single
`err.Error()` string and rehydrates a fresh `errors.New(string)`. The original type, `%w`
chain, and sentinel identity are lost → `errors.Is(err, store.ErrStaleTransition)` is
**false** across the boundary.
- **gRPC `gatewayrpc`** returns raw `err` from handlers; gRPC-Go converts to
`codes.Unknown` with only the message. The **only** explicit code in the repo is
`codes.Unavailable` for a missing session store (`server.go`). No status-code mapping for
store errors exists.
### Decision — structured mapping so `errors.Is` survives
The `StateStore` service must map the store's sentinel errors to canonical gRPC codes and
rehydrate them to the _same_ sentinels on the client, so consumer `errors.Is` checks keep
working — an improvement over the flattening it replaces, not a regression.
| Store sentinel / outcome | gRPC code | Client rehydrates to |
| ------------------------------------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------- |
| `store.ErrStaleTransition` | `FailedPrecondition` | `store.ErrStaleTransition` |
| `store.ErrBindingNotFound` | `NotFound` | `store.ErrBindingNotFound` |
| `store.ErrMappingNotFound` | `NotFound` | `store.ErrMappingNotFound` |
| `store.ErrBindingOverlap` | `FailedPrecondition` | `store.ErrBindingOverlap` |
| `store.ErrBindingTransition` | `FailedPrecondition` | `store.ErrBindingTransition` |
| `store.ErrAlreadyDispatched` | `AlreadyExists` | `store.ErrAlreadyDispatched` |
| not-found-as-`(nil,nil)` (`TaskByID`, `GetBinding`, `GetMapping`, `ClaimNext`, `ClaimByIssue`, …) | `NotFound` with a `found=false` field (**not** an error) | `(nil, nil)` |
| infra / wrapped error | `Internal` (**sanitised** message, see below) | wrapped `fmt.Errorf(...%w)` |
| capability absent | `Unavailable` | context/typed error |
The `found=false`-not-error convention matters: the repo deliberately returns `(nil, nil)` for
not-found in reads and a sentinel for not-found in writes. The wire must preserve **both**
conventions (a `GoogleRPCStatus` with `NotFound` is an _error_, which would wrongly surface to
callers that expect `(nil, nil)`). Implement `found` as an explicit boolean field on read
responses, and map `(nil,nil)` ⇄ `found=false` + `OK`.
### Error-detail sanitisation (rev. 2c)
Full internal error messages must **not** be placed in gRPC `details` for remote callers. SQL
paths, provider/forge details, secrets, and stack traces are sensitive internals. The rule:
- **Sentinel errors** — the client rehydrates the sentinel from the code; the message string in
`status.Error` is a short, public, stable phrase (e.g. `"stale transition"`), not the raw
wrapped chain.
- **Infra errors** — the wire carries a **sanitised** public message + the `Internal` code.
The **full** error (with `%w` chain, SQL, provider detail) is logged **server-side only** by
the store service. The client rehydrates a generic wrapped error and must not surface the raw
text to users.
---
## 8. Limits
**Interface bloat (`interfacebloat` cap = 8)** — `.golangci.yml` `interfacebloat: max: 8`,
which overrides the upstream default of 10. The Go consumer facades must stay ≤8 methods.
`TaskLifecycle` is exactly 8 (at the cap); `TaskStore` is the 24-method composite that the cap
is why it is decomposed; proto services bypass the cap (like `ChatContract`).
**Payload caps:**
- Capture body: `defaultCaptureMaxBodyBytes = 256 KiB` (may reduce further; the wire message
must not exceed gRPC's default 4 MiB receive limit for a single capture). A single capture
fits, but a _batch_ of them did not: the caller-side cap of up to 100 captures at 256 KiB each
could exceed 4 MiB in one unary `ListCaptures`/`ListUndispatchedCaptures` response. `.4.7` adds
`StreamCaptures`/`StreamUndispatchedCaptures` (server-streaming, one capture per message) as
the path both `staterpc.Client` methods actually call; the original unary RPCs stay defined,
unmodified and deprecated, only so `buf breaking` protects an in-flight rolling deploy.
- Task `detail`/`park_reason`/event `Detail`: 4000-char hard cap (`clip(s, 4000)`).
**Retention (stays server-side in the store; the wire does not carry pruning decisions):**
- `events` table: **no prune, unbounded growth** — a known risk to revisit, not changed here.
- `captured_events`: prune-on-write, default 7 days / 5000 events.
**Pagination/arity:** store read methods take a raw `int limit` (no store-side cap); the
caller-side caps (task list 100, log 2000, captures 100, capture scan window 5000, binding
dispatch batch 100, session list 20) remain caller-side. The wire passes `limit int` and returns
`[]*` slices, mirroring the existing Go signatures — **no cursor/paging protocol is introduced**
in this work (the current `EventsSince(sinceID, limit)` offset cursor is the only one, and it
stays as-is).
---
## 9. Transport security boundary
The gateway precedent is loopback-only, unauthenticated gRPC. The State Store holds the
crown-jewel `archie.db` (task/event/capture/mapping/binding data), so its boundary must be
stated explicitly rather than left implicit.
**The State Store's equivalent boundary (rev. 2c):**
- **Listener topology — single rule (rev. 2c).** One in-process listener; its bind address is
chosen by the consumer set, never both at once:
- _Agent containers consume it_ (the Phase 2 driver during multiplexed serving) → bind to the
**host-gateway bridge address** so containers can reach it, and **token auth is mandatory**
(a bridge host is reachable by any process on that bridge). A container **cannot reach the
host's `127.0.0.1`**, so loopback-only is NOT usable for the agent-consumed path.
- _Only the daemon consumes it_ (no agent) → bind **loopback-only** (`--listen 127.0.0.1`),
`insecure` is fine because it is not network-reachable; no token required.
- There is **no dual-listener** design. The practical default during `.4.2` (the reason
in-process serving exists is to give the agent a gRPC target) is the **bridge address +
token**. `127.0.0.1` is reserved for the daemon-local-only case.
- **Agent access → the container bridge.** The agent runs in a task-scoped container on the
host and reaches the State Store over the Docker bridge gateway (the bind address from the
topology rule above), exactly as it reaches the daemon's NATS. To close the "any host
process could reach the store" gap, the agent **authenticates with a per-task bearer token**
carried in gRPC metadata by a client interceptor (`StateStoreToken`, §6). Network
reachability + the token is the trust boundary for the default bridge topology.
- **The daemon** uses the local adapter (`*store.Store`) in-process by default, so no network
boundary exists until `[services.state].target` is set; when it is set, the daemon client
authenticates with a token supplied alongside the target.
- **Non-loopback / k8s:** TLS/mTLS is an **operator decision**, not a default. Any non-loopback
exposure (e.g. `--listen 0.0.0.0`, a CDN, a cross-host service) requires an explicit decision
and mTLS or token auth — mirroring the gateway's `--listen`/`--enable-cors-header`
confirmation caveat. The NATS-KV discovery fallback supplies endpoints but does not add
transport security; that stays the operator's responsibility.
### Token lifecycle (rev. 2c; scoping added in `.4.7`)
- **Generation:** the daemon generates a per-task bearer token when it acquires the container
(or per incumbence) and injects it via `containerEnv` as `STATE_STORE_TOKEN`. A single token
may cover a task's container lifetime.
- **Registration (`.4.7`, post-standalone-cutover):** the State Store is now its own process
(`.4.3`/`.4.6`), so the daemon can no longer just hold an in-process issued-token set for the
server to check — it registers the token at the remote authority via the
`RegisterTaskGrant`/`RevokeTaskGrant` RPCs (`staterpc.GrantIssuer`, `daemon.StateStoreGrantIssuer`),
admin-token-authenticated calls a task-scoped token itself can never make.
- **Lifetime:** tied to the task + container grace period; rotated on a new container acquisition
for the same task; a token for a released container is invalidated (`RevokeTaskGrant`, deferred
alongside `ContainerPool.Release`). An unrevoked grant still expires server-side (bounded by
`RegisterTaskGrantRequest.lifetime_seconds`, capped at 7 days) so a daemon crash before revoke
cannot leave a grant valid indefinitely.
- **Validation and scope (`.4.7`):** a gRPC interceptor (`staterpc.TaskGrants.UnaryInterceptor`)
validates the token against the State Store's own issued-grant set; missing/unknown/expired →
`codes.Unauthenticated`. Unlike the daemon's own administrative token (full access to all RPCs),
a task-scoped grant additionally authorises only `Update`/`Transition`/`InsertEvent` on
its own task ID, plus the two workflow-caller RPCs naming that same task ID
(`EnqueueCallTask`/`WorkflowCallStatus`, `docs/prds/workflow-calls.md` — the one
sanctioned widening: the callee is the caller's child). Every other RPC, including the
streaming capture surface and
`RegisterTaskGrant`/`RevokeTaskGrant` themselves, is `codes.PermissionDenied` for a task-scoped
caller. The token is carried in gRPC metadata, never in a URL.
### Fail-closed on non-loopback (rev. 2c)
If `[services.state].target` points to a non-loopback address and **neither** TLS **nor** a token
is configured, the State Store client (daemon or agent) **fails closed** — it refuses to
start/dial rather than fall back to a plaintext, unauthenticated remote connection. This mirrors
the gateway's `--listen`/`--enable-cors-header` confinement caveat and prevents a silent
unauthenticated remote store. The loopback + token default is the only path that starts without
an explicit operator decision.
---
## 10. Mode / config shape
**Follow the gateway's presence-based `target` seam, not the NATS `mode` enum.**
- **Services are keyed by name, not named as struct fields.** A
`State ServiceConnection` field per service is the duplication
`docs/prds/service-registry.md` removes, and this document's summary describes
the seam as `[services.<name>]`:
```go
type Services map[string]ServiceConnection
```
registered once via `RegisterService(context, name, target, listen, tokenEnv)`. The TOML
shape below is unchanged, so nothing else in this section is affected; read
`cfg.Services.Get("state")` wherever it says `cfg.Services.State`.
- **Empty `Target` → startup error.** The local `*store.Store` adapter default was
withdrawn when the State Store was extracted (§12 step 7): the standalone `archie-state-store` process
exclusively owns `archie.db`, so both `archied` and `archie-gateway` now reject an empty
target (`internal/app/archied/bootstrap.go` and `state_store_client.go`: `services.state.target
is required`). **Set `Target` → dial gRPC** with `*staterpc.Client`; no client opens the
database itself. This differs from the gateway, where `Target` is defaulted to
`127.0.0.1:8585` because `archie-gateway` is already a separate process whose client and
server share one default.
- `[services.state]` is present and **uncommented** in `config.example.toml`, with `target`
marked REQUIRED, because the value is load-bearing for every client. A commented-out
`target` cannot boot, so the section ships uncommented.
- Composition root: `internal/app/archied/bootstrap.go` (the daemon) and
`internal/app/archieui/config.go` (the UI process) both read `cfg.Services.Get("state")` and
dial the remote State Store. The task store is built only in the standalone
`archie-state-store` process (`internal/app/archied/state_store.go`), which is the only path
that opens the task tables.
> **Mode fork, decided.** The gateway uses a single `target` address (no enum). The State Store
> boundary uses the same seam for symmetry, and **both now require a non-empty `target`**: the
> State Store's local-store default was withdrawn when the process was extracted (§12 step 7).
> No `mode` field is added. A companion `STATE_STORE_TOKEN` secret (or a
> `[services.state] target_token` key) carries authentication.
---
## 11. Local-adapter compatibility + conformance
- `*store.Store` (local) and `*staterpc.Client` (remote) satisfy the **same** contract
interfaces. Use **explicit** `var _` assertions on **both** adapters (the gateway's local
adapters use only structural/return-type assertions; the store precedent's explicit `var _`
style is stronger and should be adopted on both sides).
```go
var _ workflow.Store = (*staterpc.Client)(nil) // first contract to move (agent)
var _ store.TaskStore = (*staterpc.Client)(nil) // daemon path, added progressively
var _ store.CaptureStore = (*staterpc.Client)(nil)
var _ store.MappingStore = (*staterpc.Client)(nil)
var _ store.BindingStore = (*staterpc.Client)(nil)
var _ store.BindingDispatcher = (*staterpc.Client)(nil)
var _ store.BindingTaskCreator = (*staterpc.Client)(nil)
var _ store.PlaybookDispatcher = (*staterpc.Client)(nil)
// local side (in store), already present:
var _ workflow.Store = (*Store)(nil)
```
- **Conformance suite:** a `staterpc/conformance_test.go` bufconn suite runs the **same**
contract through both `"local"` and `"grpc"` adapters (mirroring
`gatewayrpc/conformance_test.go`), asserting error-sentinel fidelity and the
not-found-as-`(nil,nil)` convention both ways.
- **`Close()`:** stays on the Go store interfaces (so `TaskStore`/`TaskEvents` remain fully
satisfiable) but is **not** a `StateStore` RPC. The remote `staterpc.Client` implements
`Close()` as a **no-op**; the store service owns its own DB lifecycle. When the daemon hands
the store to `archie-state-store`, `b.cleanup()` no longer calls `store.Close()` on a remote
client (it is the daemon's own lifecycle only when it owns the store in-process).
---
## 12. Cutover / deletion rules
1. **Ratify the contract (this document).** No code.
2. **Domain type + interface relocation (prerequisite, coupled with §4).** Move `Task`/`Status`/
`Source` and the `WorkflowStore` interface into `internal/domain/workflow` (as
`workflow.Task`/`workflow.Status`/`workflow.Source`/`workflow.Store`), so
`internal/domain/workflow` imports no `internal/store`. Update the store tests and the 6
workflow production files. **This must land before or with `.4.2`, because `.4.2` cannot move
the agent's store contract off `store.WorkflowStore` while the domain still imports it.**
3. **`.4.2` — generalise `storerpc` to the gRPC contract.** Move the agent's `workflow.Store`
(`Update`/`Transition`/`InsertEvent`) from NATS JSON `storerpc` to `staterpc.Client` over
gRPC, using the §6 handoff. The daemon serves the gRPC `StateStore` server **in-process
(multiplexed)** first so the agent has a gRPC target before the standalone binary exists
(PRD §3 "multiplexed in-process is the migration default"). Bind the in-process listener and
inject `STATE_STORE_URL`/`STATE_STORE_TOKEN` per task (see §6 "Operational specifics"). Also
land the `RecordDispatch` `*sql.Tx` drop (see §5) in the same span. Flip the agent's
`Transport.Store` to a gRPC client once `STATE_STORE_URL` is injected.
4. **Delete NATS `storerpc` only after the agent is fully on gRPC** — delete `internal/storerpc`
(Server, Client, subjects `archie.store.update|transition|insert_event`), the
`natsrpc.RegisterAll` registration, and the now-unused `store.WorkflowStore` NATS path in
`internal/infrastructure/agenttransport/nats`, in the same commit.
5. **`[services.state].target` stays empty (inproc)** through `.4.2`; the `archie-state-store`
`cmd/` binary is **`.4.3`** and hosts the same `StateStore` gRPC service.
6. **Swap daemon-internal contracts one at a time** (only once the daemon points at
`archie-state-store`): `Capture → Mapping → Binding → TaskStore`. Each swap is independent —
add the remote-client composition path, run the per-contract conformance suite, flip
`[services.state].target`, delete the local use. A consumer mixes in-process and remote
contracts for a contract-code (no dual-live _window_; each contract is either local or remote
at a time).
7. **Final flip / deletion of the in-process serving path:** when the daemon no longer owns the
store (i.e. `TaskStore` has moved), delete the in-process task-store /
`wireWebStoreSurfaces` path in the daemon in a **same-commit** deletion — no dual-store
ownership. The single SQLite file remains owned by `archie-state-store`.
8. **Never** split `archie.db` or add a second store. The gateway keeps its own already-separate
session SQLite; that is unchanged and out of state-store scope.
---
## 13. Decisions recorded (for the review trail)
- **`internal/store` is a transitional compatibility location** (target
`internal/infrastructure/store`), not the final infrastructure boundary. The producer-owned
daemon/webui store surfaces live there now but may relocate with the implementation.
- **In-process listener + token lifecycle:** the daemon binds the in-process State Store
listener to the **host-gateway bridge address** when agent containers consume it (the Phase 2
default) or loopback-only when the daemon is the sole consumer — one listener, one address
rule, never both (rev. 2c). It selects the bridge address by reusing the embedded-NATS
host-gateway resolution and injects `STATE_STORE_URL`/`STATE_STORE_TOKEN` per task via
`containerEnv`. Token is per-incumbence (task + container grace period) and validated by a
gRPC interceptor → `codes.Unauthenticated` on missing/unknown/expired. Non-loopback targets
fail closed without TLS or a token.
- **§12 step 2 (domain type + interface relocation) is done** — `internal/domain/workflow`
imports no `internal/store` symbol and `store.WorkflowStore` is gone from `TaskContext`. The
broader Phase 2 acceptance criterion (State Store as its own gRPC service) is still open;
`.4.2` picks up from here.
- **Ownership split:** domain-facing workflow contract is **consumer-owned** in the domain
(`workflow.Store` + `workflow.Task`/`Status`/`Source`, per dependency rules #2 and #7);
daemon/webui store surfaces stay **producer-owned** in `internal/store`. `store.WorkflowStore`
is superseded by `workflow.Store`.
- **One `StateStore` gRPC service** (49 contract RPCs, grouped by contract) + narrow Go consumer facades
(≤8) on `staterpc.Client` — mirrors the single-`ChatService` precedent.
- **Domain type relocation** (`Task`/`Status`/`Source` → `internal/domain/workflow`) is a
Phase 2 prerequisite, pulled forward from migration-decisions §4 (minimal bound,
`Task → WorkflowExecution`); the rest of §4 stays a separate migration.
- **`RecordDispatch` drops `*sql.Tx`** (wire-blocker; production passes `nil`) — a
required interface migration landing before/with `.4.2`.
- **`Close()` not on the wire**; remote client `Close()` is a no-op.
- **Structured gRPC error codes** with client rehydration to store sentinels (preserves
`errors.Is`), a `found=false` + `OK` convention for read not-found, and **sanitised public
error details** (full detail logged server-side only).
- **Agent handoff:** `agentworker.Settings` gains `StateStoreTarget`/`StateStoreToken`/
`StoreTimeout`, injected as `STATE_STORE_URL`/`STATE_STORE_TOKEN` env (mirrors the NATS
handoff); `Transport.Store` returns a long-lived gRPC `workflow.Store` client.
- **Transport security + listener topology (rev. 2c):** one in-process listener, bound to the
host-gateway bridge address when agent containers consume it (the Phase 2 default) or
loopback-only for a daemon-local-only consumer. `insecure` only on loopback; mandatory
per-task bearer-token auth on the bridge; TLS/mTLS is an operator choice for any
non-loopback/k8s topology.
- **Mode = presence-based `[services.state].target`**, default **local** (not yet extracted);
add `[services.state]` to `config.example.toml`.
- **Explicit `var _` assertions on both adapters**; per-contract bufconn conformance.
- **Migration order:** domain type/interface relocation → `workflow.Store` (agent) → stand up
`archie-state-store` → `Capture` → `Mapping` → `Binding` → `TaskStore`; NATS `storerpc`
deleted once the agent is on gRPC; in-process store path deleted in a same-commit flip.
- **Orphans `ClearTerminalTasks`/`IncrementRetryCount`** retained but not built upon.
-160
View File
@@ -1,160 +0,0 @@
# /status health surface
**Status:** Finalised
**Beads issue:** `archie-core-wp9s`
A reported field must have a truthful source. `/status` reports broker
connectivity and the last chat-model call; the container pool, last poll and
channel state have no source in the process that answers the command, so they
are left out rather than faked.
## Background
`archie-core-wp9s` ("/status and /tasks have the wrong division of labour")
asked for two things: `/tasks` owning the live per-task work view, and
`/status` owning daemon health -- "broker connectivity, provider
reachability, channel state, container pool, queue depth, last poll,
version" -- with neither duplicating the other or static config available
elsewhere (`/model` already lists active provider/model).
## Phase 1
- `/tasks`: new command, `gateway.ChatTaskSummary` extended with
`Stage`/`Attempt`/`ParkReason`/`UpdatedAt` (all already persisted on
`store.Task`, zero new instrumentation), sorted actionable-first.
- `/status`: itemised per-status task counts replaced with one aggregate
`Queue: N in flight (...)` line (running/waiting/parked only -- queued and
terminal states excluded as not a health concern). Runtime
(provider/model) is temporarily left in place; see "Runtime (provider/model)"
under Phase 2's "Truthful or absent" for where that stands now.
Not touched: `/agents` (`gateway.AgentReader`/`Router.Agents`) is a separate,
pre-existing command that already has the right shape for "list active
work" but is never wired to a real implementation in any composition-root
call site (`bootstrap.go`, `telegram_setup.go`) -- it always answers "Agent
listing is not configured." in production. That is a standalone bug
(`archie-core-mxls`), not folded into this work: deciding whether to wire
it, repurpose it, or delete it in favour of `/tasks` is Sam's call, not
something to resolve by implication here.
## Phase 2 -- health checks, verified against the actual tree
Each bullet below was checked against real code before being called cheap
or not; nothing here is guessed. Both open questions were settled (see "The two
decisions"). The health section reports the broker connection and the last
chat-model call; the three facts the answering process cannot see are covered
under "Truthful or absent".
### Verified as cheap against the tree
- **Broker connectivity.** `internal/infrastructure/eventbus/nats.Client`
already exposes `CoreConn() (*nats.Conn, error)`
(`client.go`). The underlying `nats.Conn` (nats.go) has its own
`Status()`/`IsConnected()`. A `Client.Connected() bool` wrapper is a few
lines.
- **Container pool.** `container.Pool` already tracks `active int` under
its own mutex (`pool.go`) but has no public accessor. A
`Pool.Active() int` getter is a few lines.
- **Last poll.** Nothing tracks this. The daemon's poll loop
(`internal/daemon`) needs one `lastPollAt time.Time` field (atomic or
mutex-guarded, matching the pool's own pattern) set at the top of each
poll tick, with a getter.
- **Queue depth.** Covered by Phase 1.
### The two decisions
- **Provider reachability is last-known outcome, never a live probe.** A chat
command must not perform a blocking network call in its handler, and a probe
reports the probe's reachability rather than the daemon's. `/status` therefore
prints what actually happened -- the last chat-model call's model, age and
error, or "no calls attempted yet" when there has been none. Implemented as
`providerOutcomeRecorder`, written once in `sendChatTurn` (the single point
every chat-model call in the process passes through) and read back by
`newStatusHealth`. Nothing on this path dials a provider. The existing live
model reachability check (`readiness.go`'s `modelReachProbe`) is unchanged and
stays where it belongs: on `/health/detailed`, off the chat path.
- **Channel state comes from the existing ChannelManager.** `/status` reads
`status.Manager.Snapshot()` -- the same ledger the dashboard and the readiness
probe already use -- rather than re-deriving channel health from each adapter.
No method was added to the `Channel`/`Gateway` contract.
### Phase 2
- **Broker connectivity.** `internal/infrastructure/eventbus/nats.Client` gained
`Connected() bool`, which reads the connection the process already holds. The
standalone Gateway (which dials NATS itself for task actions) reports the same
fact from that connection.
- **Container pool.** `container.Pool.Active()` and `Pool.Cap()` read the pool's
own counter and configured `max_concurrency` -- not a Docker listing, which
would include containers this pool does not own. A cap of zero means
unlimited, so `/status` renders the count alone rather than "1/0 active".
- **Last poll.** `daemon.Daemon.LastPollAt()` reports when the most recent poll
pass _began_; both poll paths (`poll` for single-identity `Run`,
`pollForIdentity` for `runIdentities`) stamp it. A pass that hangs leaves the
stamp stale, which is the signal -- stamping completion instead would leave a
wedged poller looking healthy.
- **Queue depth.** Covered by Phase 1.
- **Rendering.** `gateway.formatHealth` renders one line per reported fact
(`Broker:`, `Containers:`, `Channels:`, `Chat model:`, `Last poll:`) between
the queue line and the runtime block. A `/status` reply carries `Broker:` and
`Chat model:`: the Gateway is the only process that serves a Router, and it
holds neither a container pool, a poll loop nor a channel manager. The other
three lines render when a report carries them. The broker source is a
function rather than a captured value because the connection differs by
composition: the daemon's shared eventbus client in one process, the
Gateway's own task-actions connection in the other.
### Truthful or absent -- what is deliberately not reported
- **Version.** Still excluded: `/version` owns it, and duplicating it back into
`/status` is the exact "answers something available elsewhere in chat"
complaint this ticket exists to fix.
- **Sections the standalone Gateway process cannot see.** The daemon owns the
poll loop, the container pool and the channel manager; the Gateway process
owns none of them. Its `/status` reports broker and chat-model health and
omits pool, polling and channels rather than printing zeroes. Aggregating them
across processes would need a new daemon RPC -- a new subsystem, out of scope
here. For the same reason the chat-model line is per process: the daemon
records the turns it runs (Telegram, email, webhook), the Gateway records the
web chat's, and the two do not pool outcomes. Each line is true of the process
answering the command. **Decided: they stay per-process.** Pooling
them would mean a new daemon↔gateway health RPC for one status line, and a
per-process line is true where an aggregate would be a claim about a process
the answering one cannot see. The composition root therefore builds the
health source from the broker connection and the chat-model recorder alone: a
producer for a daemon-owned fact would build a section no reply can carry.
- **A channel's failure reason can outlive the failure.** `status.Manager` keeps
the last non-empty `Detail` across state changes, and that one field carries
both a descriptor's standing caveat and a runtime failure reason, so a channel
that failed and later recovered can still render the old reason. Splitting the
two belongs at the producer (the manager and its descriptor), not in this
reader, which reads the field exactly as the dashboard does.
- **Container pool when Docker is unavailable.** Composition leaves
`containerPool` nil, so the section is absent. Naming a reason would mean
carrying Docker's startup error into the health surface.
- **Runtime (provider/model).** Phase 1 left this block in place; it is still
here. It is static config that `/model` and `/whoami` already answer, so it is
the only line in `/status` that this ticket's own rule says should not be
there -- but the maintainer reads `/status` daily to see the active model at a
glance, and one command answering both "is archie well" and "what is it
running on" is worth that duplication. **Decided: keep it.** It is
a settled product decision, not an oversight; do not remove it as a
mechanical follow-up.
- **`/agents` copy.** The menu still advertises "List tasks being
worked" while `Router.Agents` is never wired (`archie-core-mxls`), so that one
published description does not match what its command does. Deleting,
rewiring or redefining `/agents` is that bead's call and is not folded in here.
## Packages this touches (Phase 2)
- `internal/infrastructure/eventbus/nats`: `Client.Connected()`.
- `internal/container`: `Pool.Active()`, `Pool.Cap()`.
- `internal/daemon`: `lastPollAt`/`markPoll`/`LastPollAt()`.
- `internal/gateway`: `health.go` (health contract + renderer), `Router.Health`,
`formatStatus`.
- `internal/app/archied`: `status_health.go` (the composition-root bridge),
`ProviderOutcomes` threaded through `telegramSetup` into every turn runner,
and `sendChatTurn` recording each call's outcome.
- `internal/domain/messaging` + `internal/channels/telegram`: `/status` and
`/tasks` descriptions, which now describe both commands' actual jobs on both
published surfaces.
-159
View File
@@ -1,159 +0,0 @@
# Store
**Status:** Approved
**Authority:** `docs/architecture/plugins-and-extensions.md`; supersedes
`docs/prds/extensions-center.md`, whose installed-inventory states are
adopted below.
**Compounds with:** `docs/prds/external-agent-harness.md` (harness Kits),
`docs/prds/pr-review-agent.md` (the first package).
## Decision
Operators get capabilities from a store: browse, install, update and remove
packages from the dashboard, with no config file editing. A package is an
OCI image in a registry. A store catalogue is a list of package references.
Installing pins a digest. Every package declares the authority it needs, and
an update that asks for more stops for the operator's approval.
## Packages
Two kinds, both ordinary OCI images:
- **Harness Kits.** Kit v3 images, resolved as
`docs/prds/external-agent-harness.md` decides. Their authority is their
Kit permission surface.
- **Archie packages.** An image whose manifest annotation
`dev.archie.package.v1` carries the descriptor and whose single layer
carries files. A package contributes any of: workflow definitions,
prompts, skills, MCP server definitions, and default settings for them.
Archie packages are declarative. They carry no Go, Yaegi or script code that
archie executes on the host. Anything that runs code ships as a Kit and runs
in a sandbox. An archie package that references a Kit names it by digest,
and installing the package installs the Kit.
The descriptor declares: display name, description, version, the families
it contributes, the packages it requires, and its authority.
## Authority
A package's authority is the set of grants it needs to work:
- credential services (from its Kits and MCP servers);
- egress hosts (from its Kits);
- forge permissions its workflows use: read, comment, review, push, open
pull request;
- triggers it registers: watched-repository events, schedules;
- tools it enables for agents.
Install shows this list and records the operator's acceptance against the
digest. An update whose authority is equal or narrower applies under the
package's update policy. An update whose authority is wider waits for
approval, showing only what widened. Nothing a package does at runtime can
exceed its accepted authority: archie checks forge actions, triggers and
tool grants against it, and the egress proxy enforces the Kit's grants.
## Catalogues
A catalogue is an OCI artifact listing package references with digests,
signed by the catalogue's key. Archie ships with the default catalogue and
its public key configured. An operator can add catalogues, for example a
private registry, by reference and public key. A catalogue without a key is
refused unless the operator marks it unsigned, which the dashboard shows on
every package it supplies.
Install and update verify the catalogue signature and the package digest.
Archie never installs a tag it has not resolved to a digest through a
verified catalogue.
## Organisations
`docs/prds/orgs-and-access.md` is the boundary, and the store follows its
split between the instance and each org.
- **Instance.** Catalogues and their keys are instance configuration, set by
instance admins. Every org browses the same catalogues.
- **Org.** Installing, updating, removing, accepting authority and setting the
update policy are org actions. An installed package, its pinned digest and
its accepted authority belong to one org. Two orgs can run different
versions of one package.
- **Contributions** become org resources: workflows are org workflows,
profiles are org profiles, and credential bindings name org secrets. A
workspace uses them only once the org grants them to it.
- **Authority is an upper bound, not a grant.** Accepting a package's
authority permits the package to ask; the workflow's identity must still
hold each grant. A package never creates, grants to or widens an identity.
- Install and authority acceptance are the `create` and `approve` actions on
the package, decided by the Authorizer. Org approval policy decides who may
accept, and no member accepts authority they asked for.
## Install, update, remove
- Installed packages, their pinned digests, accepted authority and update
policy are org resources in the State Store. They apply without a restart.
- **Update policy** per package: `manual` (default) or `auto`. `auto` applies
non-widening updates when the catalogue lists them; widening updates always
wait.
- **Setup.** A package whose authority includes a credential with no binding
installs as `needs_setup`, and links to the binding form or the harness
setup terminal. Its triggers do not fire until setup completes.
- **Remove** stops its triggers, removes its contributions, and leaves any
credential bindings for the operator to delete. A package another
installed package requires cannot be removed first.
- Rolling back reinstalls the previously accepted digest.
## Inventory
The installed view lists every package and every bundled capability with
one state, computed on read and never persisted:
| State | Meaning |
| ------------- | -------------------------------------------------------- |
| `available` | in a catalogue or bundled, not installed |
| `needs_setup` | installed, waiting for a credential binding |
| `active` | installed and running |
| `degraded` | active, and its family's health check reports a fault |
| `pending` | an update waiting for approval of widened authority |
Core capabilities (identity, workflow engine, State Store) are listed and
cannot be removed.
## Out of scope
- Payment, licensing and paid packages.
- Publishing from the dashboard. Packages are built and pushed with standard
image tooling.
- Ratings and reviews.
## Plan
1. Archie package descriptor and its validation, including declarative-only
content.
2. Installed-package resources, digest pinning, install and remove for
archie packages from a local registry.
3. Authority model: extraction from packages and Kits, acceptance records,
runtime checks for forge actions, triggers and tools.
4. Signed catalogues and verification; the default catalogue.
5. Updates: widening detection, approval, `auto` policy, rollback.
6. Kit packages through the same flow; `needs_setup`.
7. Inventory states across packages and bundled capabilities.
8. The PR review agent published as the first package.
## Verification
- Installing the PR review package from the default catalogue on a fresh
instance, then binding a credential, reviews a PR without editing
configuration.
- An update adding a forge permission or egress host waits as `pending`,
showing only the added grant, and does not apply under `auto`.
- A workflow from a package that tries a forge action outside its accepted
authority fails the step.
- A tampered package digest or an unsigned catalogue refuses to install.
- A package containing executable host code is rejected at validation.
- Rolling back restores the prior digest and its accepted authority.
- A package installed in org A is invisible to org B, and org B's workflows
cannot select its profiles.
- A package whose workflow needs a forge permission the running identity was
never granted fails that step, even though the org accepted the package's
authority.
- A member cannot accept widened authority on an update they requested.
-196
View File
@@ -1,196 +0,0 @@
# task_logs pagination and bounded retrieval -- decision
**Status:** Approved
**Date:** 2026-08-26
**Beads issue:** `archie-core-vq92`
**Compounds with:** `archie-core-p1bl` (errors serialise as `{}`)
## Decision
`task_logs` becomes a _cursor-paginated, filterable_ bounded read, not a
one-shot head-of-file window. The reader in `internal/logging` gains a
second entry point (`Page`) that walks the file forward from a byte
offset; the tool schema in `internal/gateway/task_tools.go` surfaces
level, time-range and cursor parameters; the response carries an explicit
"more available" signal so a model can either keep paging or hand the
rest to `send_file` when the operator wants a complete archive.
We do NOT add an unbounded read path. A single response is still capped at
`MaxTailLines` (2000) entries. What changes is that pagination makes the
cap reachable in practice instead of silently terminal.
## Why now
`archie-core-vq92` is the right place to fix this: the chat tool is the
user-visible failure mode, but the same defect propagates to every caller
of `internal/logging.Tail` (`internal/webui/api_logs.go` and the
`chatTaskLogReaderAdapter` in `cmd/archied/main.go`). Patching the
reader and the tool together is one change in two layers, not two
changes; CLAUDE.md's "package owns its format end-to-end" rule means the
reader is the right place for cursor support regardless.
The compound with `p1bl` matters: a truncated window of uninformative
errors leaves an operator with nothing. Cursor pagination lets the model
walk the whole file when a level filter does not narrow enough, and the
response's "more available" signal means it can honestly say "I read N of
M and stopped there" instead of presenting the head as complete.
## Shape of the API
### Reader (`internal/logging`)
Add a second entry point next to `Tail`:
```go
// Page walks the log forward from cursor (a byte offset; 0 starts at
// the beginning of the scanned window), applying the same filters as
// Tail. PageResult.Cursor is the file offset just past the last line
// the walk returned; pass it back as Cursor to continue, and stop when
// MoreAvailable is false.
func Page(path string, q Query, cursor int64) (PageResult, error)
```
`PageResult` carries `Entries`, `Truncated` (the existing meaning --
older entries exist that were not examined within `maxScanBytes`),
`Cursor` (the byte offset the next page should resume from), and
`MoreAvailable` (true iff the scan saw more matching entries beyond the
returned page within the same call).
`Cursor` is a byte offset rather than an entry ID for two reasons.
First, `TaskSink` writes JSONL through `slog.NewJSONHandler` directly --
without routing through `FeedHandler` -- so the on-disk entries carry no
`id` field and a per-task attempt monotonic counter would require
either a sink-side change or a reader-side reconstruction that is
brittle against rotation. Second, the byte offset uniquely identifies
"the next unread position" in a sequential scan, which is exactly what
the call pattern needs. A cursor that points at or past the file's
current size is treated as end-of-stream (empty page, `MoreAvailable`
false).
The implementation is `readWindow` (reads the tail-most `maxScanBytes`
into a single in-memory buffer) plus `readLines` (clamps the cursor into
the window, drops a partial first line on the size-cap seek, then
delegates) plus `walkWindow` (walks the buffer line-by-line by exact
slice offset). Offsets are into one contiguous buffer, so they are
trivially correct -- unlike an incremental reader over the file, whose
`bufio.Reader` buffer-ahead would make its underlying file position
unusable as a cursor.
`Tail` is NOT a wrapper over `Page`: it keeps its legacy ring-buffer
semantics (newest `Limit` matches, oldest dropped, `Truncated` set on
ring overflow). They share `readWindow`/`walkWindow` but stay separate
entry points precisely so Tail's established behaviour is unchanged.
### `Query` gains two optional fields
```go
Since time.Time // inclusive lower bound on entry.Time
Until time.Time // inclusive upper bound on entry.Time
```
`Levels`, `Component`, `Contains`, `Limit` are unchanged. The existing
filter logic and tests move unchanged.
### Tool schema (`internal/gateway/task_tools.go`)
`ChatTaskLogQuery` gains three fields:
- `Level []string` (forwarded to `Query.Levels`)
- `Since time.Time` / `Until time.Time` (forwarded as `Query.Since/Until`)
- `AfterID int64` (the cursor; 0 to start at the beginning)
`ChatTaskLogResult` gains two fields:
- `Cursor int64` -- highest ID in this page; pass back as `AfterID` to continue
- `MoreAvailable bool` -- true iff the scan saw more matching entries that
did not fit in this page
The tool description is updated to teach the model the pagination
protocol in one sentence: "pass the previous `cursor` back as `after_id`
until `more_available` is false; for an entire archive, prefer
`send_file`."
### Production adapter (`cmd/archied/main.go`)
`chatTaskLogReaderAdapter` passes the new fields through to the reader.
`TaskRegistry.Path` is already attempt-scoped, so paging stays inside
one attempt.
## What we deliberately do NOT do
- **No time-range-only read without a cursor.** Time bounds are a filter,
not a window. A model that wants only "errors in the last hour" passes
both `Levels=[ERROR]` and `Since=now-1h`. The page is still the same
size; the response's `MoreAvailable` tells the caller whether the hour
fit.
- **No "save the full log" via the tool.** That is what
`archie-core-absb`'s `send_file` is for. The PRD description for vq92
raised this as an open question; the answer is "use the existing tool"
rather than building a parallel archive endpoint.
- **No reversal or random access.** Paging is forward-only on the byte
offset. Reverse scan would require either an index or a full file
pass; neither earns its cost given `Tail` already handles "show me
the end."
- **No bumping `MaxTailLines` past 2000.** A single response must not be
able to exhaust the model's context. Paging makes the cap _reachable_
but does not relax it.
- **No raising `maxScanBytes`, and no walking rotated generations.** See
the ceiling below; lifting it is a separate decision with its own cost.
## The scan-window ceiling, and what it means for "complete"
`maxScanBytes` (8 MiB) bounds the tail of the file any single call will
examine. Paging does **not** lift that bound: every call re-derives the
window from the file's _current_ size and clamps the incoming cursor up
into it, so a paging loop walks the window exhaustively and then stops.
For a log larger than 8 MiB the oldest bytes are unreachable through
`task_logs` at any cursor, and rotated generations (`attempt-N.jsonl.1`,
`.2`, ...) are separate files the reader never opens.
This is a deliberate limit, not an oversight, and it is why criterion 1
below says "paging **or** file delivery" rather than "paging". The
honest contract is:
- Within the window: paging reaches every matching entry, in order,
exactly once.
- Beyond it: `Truncated` is true, and that is the _only_ correct thing
to report. An agent that pages to `more_available == false` while
`truncated` is true has read the window, not the log, and must say so.
Lifting the ceiling would mean either buffering an unbounded file or
teaching the reader to walk rotation history. Neither is needed to close
vq92 — the issue's own text accepts file delivery as the answer for
"save the full logs" — so both are deliberately out of scope here.
## Acceptance criteria
The issue's criteria, restated against the new shape:
1. An operator can obtain a task's complete logs through the agent: by
paging when the log fits the scan window, and by file delivery
(`send_file`) when it does not.
2. A bounded response says so explicitly -- `MoreAvailable` for "more
matches this call did not return", `Truncated` for "the scan cap hid
older entries" -- so the agent can report honestly instead of
implying completeness.
3. `Levels`, `Since`, `Until` filters exist so a bounded call can answer
a specific question without paging.
4. The cap stays enforced: one response cannot exceed `MaxTailLines`,
and one call cannot examine more than `maxScanBytes`.
5. Tests cover a log larger than `MaxTailLines` and assert that repeated
paged calls retrieve every entry without gaps or duplication, plus a
log larger than `maxScanBytes` asserting the window is walked
contiguously and `Truncated` is set.
## Files this change touches
- `internal/logging/reader.go` -- add `Page`, expand `Query` with `Since/Until`
- `internal/logging/reader_test.go` -- new tests for `Page`, `Since/Until`, paging without gaps
- `internal/gateway/task_tools.go` -- new `ChatTaskLogQuery` and `ChatTaskLogResult` fields, schema description
- `internal/gateway/task_tools_test.go` -- new tests for the new fields on the tool
- `cmd/archied/main.go` -- adapter passes through the new fields
The webui handler in `internal/webui/api_logs.go` is untouched: it is
already filter-aware (Levels, Component, Contains, Limit) and is not the
failing surface vq92 reports. If the dashboard later wants the same
pagination, it consumes the same reader.
-293
View File
@@ -1,293 +0,0 @@
# Per-run task detail: attempts, stages, changes, config, debug
**Status:** Approved
**Authority:** the surface contract itself is
`docs/architecture/observability.md`.
**Date:** 2026-09-18
**Compounds with:** `docs/prds/task-logs-pagination.md` (a bounded read says
what it does not show), `docs/prds/status-health-surface.md` (no surface that
answers something already answered elsewhere).
## Decision
A task gets one detail page that answers "what did this run actually do?" per
**attempt**: an ordered stage rail, the change each commit/push produced, the
effective configuration the attempt ran under, the attempt's log, and the raw
record behind all of it.
The single organising idea is **attempt attribution**. The dashboard
renders a task's whole event stream as one flat timeline, so a retried task
reads as one long run with two of everything. Every new panel is scoped to one
attempt and says which one.
The second organising idea is **provenance, not re-derivation**. What a run
produced is captured at the producer, while the evidence exists, and persisted
durably. Nothing in this surface tries to reconstruct a past run from state
that has since moved on.
## The requirement set
| # | Requirement | Mechanism |
| --- | --------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| R1 | Per-attempt stage rail: stages with name, start, duration, terminal status and error, ordered within one attempt | `GET /api/tasks/{id}/attempts` reads the task's events and groups them by `attempt` |
| R2 | Events carry an attempt, migrated safely and carried on the wire | `events.attempt` column + presence-gated migrator arm; `Event.attempt = 11` |
| R3 | Changed files captured at commit/push, persisted per task, exposed, shown with repo/PR links | `changes_captured` durable event written by the commit/push steps; `GET /api/tasks/{id}/changes` |
| R4 | The effective configuration an attempt ran under, secrets redacted, shown | `config_captured` durable event written once per attempt; read from the events response the page already holds |
| R5 | Log pane filters by attempt, stage and level; absence stays distinct from an unreadable deployment | `logging.Query.Stage` + `ReadTaskLogRequest.stage = 9`; the pane keeps `disabled` and `found=false` apart |
| R6 | Retry is reachable from the run view and produces a new attempt shown as a new run | Existing retry action, labelled as a NEW run whose confirm states the previous attempt's commits are discarded |
| R7 | Raw JSON of the task record and its events for the selected attempt | `GET /api/tasks/{id}/debug` |
| R8 | Deep-linkable, reload-safe per-task detail page that keeps existing URLs working | `/tasks/{id}` route beside the existing `/tasks?task=N` and `/tasks?status=...` |
| R9 | Design polish: hierarchy, tokens, both themes, responsive rail, a11y, loading/empty/error states | UI lane; measured at 480px and 700px in both themes |
| R10 | Documentation of record | This document plus `docs/architecture/observability.md` |
| R11 | Red-first tests for every new behaviour, full gate, `task ui`, forced `go build ./...`, `go test -race` on touched packages | Per lane; the anti-cost-cutting requirement lives here |
## Attempt attribution: a column, not a guess
`events.Event.Attempt`, persisted as the `events.attempt` column
(`internal/infrastructure/postgres/migrations/0001_state_store.sql`), is a real column,
`NOT NULL DEFAULT 0`. It was chosen over segmenting the stream on `task_queued` /
`task_retried` because a fold would have to guess which side of a boundary an
event belongs to when the daemon restarts mid-attempt, when `RecoverStale`
requeues, or when two attempts interleave across a crash. A guess rendered as
structure is exactly the false fidelity this surface exists to avoid; a column
is durable, queryable and ordered by construction.
**`0` means "not attributable".** It is every row written before this change
plus the deliberately task-agnostic producers. It is not an attempt number and
is never rendered as one. The attempts endpoint reports the count of
unattributed events so the page can say so instead of presenting old history as
attempt 1.
## Migration against an existing `archie.db`
> Storage superseded: every store now lives in PostgreSQL behind
> `internal/domain/storecontract`, implemented in `internal/infrastructure/postgres`
> (`docs/prds/state-store-contract.md`). SQLite names below describe the
> original design.
The store's migrator (`migrateTasks` in `internal/store/store.go`) already reads
`PRAGMA table_info` through `tableColumns` and applies a presence-gated
`ALTER TABLE ... ADD COLUMN` list. This change adds an `events` arm: a
`tableColumns(ctx, tx, "events")` read beside the other two, and the entry
`ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`.
Three consequences a future maintainer must not get wrong:
- `eventsSchema` is `CREATE TABLE IF NOT EXISTS` (`internal/store/events.go`),
so on an existing database it is a **no-op**. The migrator arm is the only
thing that adds the column there. This is why the red test builds a raw
SQLite file with the pre-change `events` DDL and must fail before the arm
exists: every temp-database test passes either way.
- **`user_version` stays 3.** The loop is presence-gated, not version-gated;
bumping it would force an edit to the test that exists to prove a newer
schema is refused.
- **No backfill, ever.** Existing rows keep `attempt = 0`. Inferring an attempt
number for them would be fabrication.
## Changed files: captured at the producer
The measurement is taken inside the shared step library immediately after a
successful commit and after a successful push (`StageCommit` and
`StageCommitPush` in `internal/domain/workflow/steps.go`) — the one place
where the worktree, the branch, the base, the task and the store are all in
scope, and the only place that knows a push actually happened.
Both alternatives were rejected on evidence, not taste:
- **Reading the diff on demand** is impossible. The worktree is deleted on
merge, close and no-PR terminal states (`internal/worktree.(*Manager).Cleanup`,
called from the daemon's terminal paths) and a retry resets the branch onto
its base (`internal/worktree.(*Manager).refresh` → `resetOnto`). There is
nothing left to read.
- **Reading it from the forge** is impossible. The forge contract exposes
no changed-file capability, and adding one would cost three implementations
plus an RPC and would still fail for chat-sourced tasks with no PR.
Binding consequences:
- Capture **degrades, never parks**. A `Trees` implementation without the
capture seam captures nothing, logs, and lets the run continue. A reporting
failure must never fail a task.
- The value types live in `internal/domain/workflow/task` (`changes.go`), not in
package `workflow` and not in `internal/worktree`. Package `workflow` has no
import of `internal/worktree`, and this subpackage is not projected into the
interpreted-stage symbol table, so declaring the types here widens nothing and
needs no symbol-table regeneration. The capture method stays off that surface
entirely.
- `files` is capped at 200 entries because an event's `data` is not
length-limited by the store. `totals` always covers the **full** set and
`truncated: true` says when entries were dropped.
- `binary` means "no textual hunks", not "a binary file". Rename pairing is
go-git behaviour the lane pins with a test; where the repository records a
rename as add + delete, the surface reports what was recorded.
## Per-run configuration: a durable event, not a table
**Decision.** The effective configuration an attempt ran under is persisted as a
`config_captured` durable event (`internal/events.KindConfigCaptured`), on the
same attempt key R2 adds — not in a table, and not behind new RPCs.
**Why.** Three reasons, in order of weight:
1. Events are already this system's durable per-attempt provenance stream, and
they demonstrably carry aggregation (`StageStats`, `TokensByDay` both
aggregate over persisted events). R3 puts its diffstat there in this same
change. A table plus two RPCs would have given one feature **two provenance
mechanisms for one purpose**.
2. It adds no RPC, so the ratified state-store surface is untouched and nothing
in `docs/prds/state-store-contract.md` (rev 2c) changes.
3. The page already fetches the task's events to build the rail (R1) and to read
the diffstat (R3), so the document arrives in a fetch it already makes. There
is nothing to join.
The single-row `config_snapshot` table is deliberately **left alone**. It
answers "what is the running configuration now", is replaced on every publish,
and is pinned to one row by a test. It could not answer "what did attempt 2 run
under" in any case.
**Payload.** The result of `config.Config.ForTask()` — the non-secret
task-runtime subset — plus the schema constant `archie/task-config@1`. Not the
dashboard's configuration view: that is a larger projection carrying the full
schema catalogue, and it is the wrong object for this. Stored shape and the tab's
read rule are in `docs/architecture/observability.md`.
**Binding conditions.** It is emitted through the durable path, never the
lossy bus; it is written once per attempt, not once per stage; redaction is
proven **positively** by a canary-secrets test rather than assumed from the
producer's contract; the timeline gains one human line for it rather than
dumping a JSON blob; and an attempt with no such event renders "not captured for
this run", never an empty table implying defaults applied.
**Documented residual — the honest trust claim.** A task-scoped grant may insert
events on its own task ID; that is how `tool_call` and `agent_finish` already
work, so a task can in principle write its own `config_captured` event. This
**widens no capability** — the grant could already insert arbitrary events on
itself — but it does mean this provenance is exactly as trustworthy as the rest
of that task's event stream, and no more. It is not tamper-proofing and must
never be described as such.
## No new RPC and no new table
The entire wire change is two fields on existing messages:
```proto
// proto/state/v1/state.proto
message Event { int64 attempt = 11; }
message ReadTaskLogRequest { string stage = 9; }
```
No RPC was added, no store table was added, and no new configuration field was
introduced. `docs/prds/state-store-contract.md` is unchanged because no ratified
contract changed; the JSON document rides an existing `data` column over an
existing RPC.
Both fields are tolerant in both directions, and the degrade is stated rather
than hidden: an old server makes `attempt` read as `0` and `stage` match
nothing, so the page must say the deployment cannot attribute events to attempts
rather than show one run labelled "attempt 1". An old client shows
`config_captured` as an unknown kind, and the Config tab must then say "this
deployment cannot read per-run configuration" — a different claim from "not
captured for this attempt".
## Retry is a new run
The retry action is reachable from the run view and produces a new attempt that
appears as a new run. It is a **fresh** run: it resets the branch onto
`origin/<base>` (`internal/worktree.(*Manager).refresh` → `resetOnto`) and
**discards the previous attempt's commits**. Labelling it "restart" would imply
resumption that does not happen, so the control and its confirm copy say so.
## Honest limits the surface carries
These are the claims that would otherwise be overstated. Each is a copy or
rendering rule, not a caveat in a comment:
- **There is no exit code, so no stage shows pass/fail.** `stage_finish` carries
a duration and an optional error string and nothing else. A stage `ok` means
"returned without error", not "the work was correct". The agent's own verdict
is shown separately from the rail. A stage that parks after finishing cleanly
leaves that stage `ok` on a failed task, so attempt status is read together
with task status.
- **The log stage filter only matches lines the workflow bound a stage to.**
Agent and tool output carries no stage and never matches. The pane states that
coverage limit next to the control rather than presenting a filtered view as
the whole story.
- **Absence and unreadability are different answers.** A deployment that cannot
read task logs says so; an attempt whose log does not exist says that. They
are never collapsed, in either direction, for logs or for configuration.
- **An empty changed-files view never means "nothing changed".** No capture
exists for runs predating this change and the forge cannot supply one, so the
empty state reads "not captured for this run".
- **No run-duration figure is shown.** Per-stage durations only: a run can spend
days in `waiting_human`, and one number would understate wall time.
- **No duration is invented** for a stage with no `stage_start`; it reads "not
recorded".
- **Unattributed history is never presented as an attempt.** Events with
`attempt = 0` are reported as a count, not guessed into a run.
- **The configuration shown is the attempt's non-secret task-runtime subset** —
bot identity, models, limits, budgets, dispatch, diff cap, notifications,
forge host, tool policy. It is not the full dashboard configuration and must
never imply it contains providers, repositories, identities or credentials.
## Route and compatibility
`/tasks/{id}` is the detail route; it is deep-linkable and reload-safe.
`/tasks?task=N` and `/tasks?status=...` keep working and keep their existing
behaviour, including the nav highlight. The debug view is why the raw view
exists at all: the task list response is capped, so a client-side join has no
row for an older task, and a debug view that silently hid events would be worse
than useless.
## What this deliberately does not do
- **No new RPC, table, store interface or configuration field.** Nothing here
needed one, and each would have widened a ratified surface.
- **No exit status, no pass/fail gate badge, no "steps" in the CI sense.** The
reference layout is a CI pipeline; archie's stages are agent runs and the page
must not borrow CI's claims.
- **No backfill** of attempts, change captures or configurations onto runs that
predate the change.
- **No client-side join for configuration.** It arrives in the events response
the page already fetches; there is nothing to join.
- **No change to `docs/prds/state-store-contract.md`.** No ratified contract
moved.
## Files this change touches
- the State Store schema: the `events.attempt` column.
- `internal/events/`: `Event.Attempt`, `KindChangesCaptured`,
`KindConfigCaptured`, `ConfigCapturedSchema`.
- `internal/domain/workflow/task/changes.go`: the change value types.
- `internal/worktree/` + `internal/app/agentworker/`: the capture primitive and
its production forwarding.
- `internal/domain/workflow/steps.go`: the capture at commit and push.
- `internal/daemon/`: the per-attempt configuration emit at dispatch.
- `internal/logging/`: `Query.Stage`.
- `internal/webui/`: the three read endpoints and the `stage` log parameter.
- `proto/state/v1/state.proto` + generated stubs: the two field additions.
- `ui/src/`: the detail page, the tab primitive, the rail, and the panel copy.
- `docs/`: this document and `docs/architecture/observability.md`.
## Acceptance
1. Two attempts of one task render as two runs, and attempt 1's rail excludes
attempt 2's stages.
2. A task with no stages renders "no stages recorded", never an unexplained
empty rail.
3. A pre-change `archie.db` gains the `attempt` column with `user_version`
still 3, and its old events are reported as unattributed.
4. An attempt with a capture shows per-file added/deleted counts, status, repo
and PR links; an attempt without one says so and never says "no changes".
5. The Config tab shows the attempt's document for the selected attempt only,
with no secret value present in the serialised document.
6. Retry from the run view produces a new attempt shown as a new run, with copy
stating the previous attempt's commits are discarded.
7. The log stage filter narrows to stage-bound lines and the pane states the
coverage limit; `disabled` and `found=false` remain distinguishable.
8. `/tasks/{id}` survives reload, and `/tasks?task=N` / `/tasks?status=...`
are unchanged.
9. The debug view returns the task record and its unfiltered events, each
carrying `attempt`.
10. Run the gate and the dashboard build: `task check` passes clean, `task ui`
has been run so `ui/dist` matches the sources, and every touched package
builds and passes under `-race`.
-69
View File
@@ -1,69 +0,0 @@
# Task run detail as a master-detail split pane
**Status:** Approved
**Authority:** the panel contracts stay as ratified in
`docs/prds/task-run-detail.md`; this document changes only the run page's
arrangement of them.
**Compounds with:** `docs/prds/task-run-detail.md` (attempt attribution, the
log stage filter, the per-panel honesty rules).
## Decision
The run page's five tabs become two panes. The stage rail is the **master**,
always visible on the left. The four context panels — log, changed files,
configuration, debug — are the **inspector** on the right, and their tab bar
moves into the inspector. The "Stages" tab stops existing.
Selecting a stage switches the inspector to the log tab and sets the log
pane's stage filter to that stage. Changing the filter afterwards is the
operator's choice and is not overridden; rail selection never touches the
level filter. Clicking the selected stage again returns the filter to all
stages. A stage with no name is rendered but not selectable.
Switching attempts resets the stage filter to all stages: a selection was
commanded on the attempt it was made on, and a different attempt presents a
different stage list. Changed files, configuration and debug stay
attempt-scoped; a stage selection never scopes them.
## What does not change
- No new endpoint, RPC, table or configuration field. Every read is one the
page already makes.
- The URL contract: `tab` and `attempt` ride in the query string and survive
a reload. Log filters are not part of the URL; a reload returns the log to
all stages. `tab=stages` stays a valid URL and renders the log tab; the
page never generates it again.
- Attempt attribution, the log stage filter's coverage limit and every
honesty rule in `task-run-detail.md` still apply: each pane states what it
cannot show under that document's rendering rules.
- The task header and the attempt selector sit above both panes.
## Arrangement
- Left pane: fixed-width rail (20rem) with the attempt's stage rows. Status,
duration, error, the stage's agent report, the attempt's status badge and
start time, and the attempt-attribution footnotes render in the rail.
- Right pane: the inspector's tab bar plus the selected panel, filling the
remaining width.
- Below the shell's 900px frame breakpoint the rail stacks above the
inspector; neither pane is hidden.
- Keyboard: the rail keeps its list semantics and each stage row is a real
button, so selection and deselection work without a pointer; the inspector
keeps the WAI-ARIA tabs pattern the tab bar already provides.
## Acceptance
1. The rail is visible without opening any tab, and no "Stages" trigger exists.
2. Clicking a stage opens the log filtered to that stage; clicking it again
shows all stages.
3. After a stage selection, a filter change made by the operator is kept, and
the level filter survives the selection.
4. Switching attempts resets the stage filter to all stages, and no rail row
on the new attempt renders as selected unless the operator selected it
there.
5. `tab=stages` loads and renders the log tab.
6. Every inspector tab and attempt deep-link survives a reload.
7. A stage is selectable and deselectable by keyboard, and the selection
mirrors the log pane's stage filter.
8. Below 900px the rail stacks above the inspector.
9. `task check` passes clean and `ui/dist` matches the sources.
-337
View File
@@ -1,337 +0,0 @@
# UI Service boundary and configuration ownership
**Status:** Approved
**Revision:** 1
**Date:** 2026-09-07
**Beads issue:** `archie-core-8cda.5.1`
**Parent:** [`service-decomposition.md`](service-decomposition.md)
**Prerequisites:** Gateway contract extraction and State Store contract ratification
This document is the authority for Phase 3 UI Service implementation. It fixes
the process boundary, configuration ownership, client contracts, security
posture, readiness behaviour, and migration evidence required by
`archie-core-8cda.5.2` and later UI extraction work.
## Decision
The UI Service owns the operator-facing HTTP surface and the compiled SPA. It
serves `ui/dist` and exposes UI-specific JSON DTOs for dashboard views and
actions. It does not own conversations, task state, workflow execution,
channel lifecycle, forge access, or the daemon's runtime configuration.
The UI Service consumes two typed remote capabilities:
- Gateway's `gateway.ChatContract` through the versioned Gateway gRPC
contract, for chat snapshots, messages, turns, streaming, persona changes,
cancellation, and Gateway task actions.
- State Store's narrow read/write contracts through the versioned State Store
gRPC contract, for task views, events, captures, mappings, bindings, and
configuration data explicitly projected for the dashboard.
The UI process may compose local adapters during the migration seam, but the
adapter implements the same wire-safe contract as the remote client. The
production extraction cutover removes the in-process adapter in the same
change; a dual-live UI authority is not permitted.
## Boundary and ownership
| Concern | UI Service owns | UI Service may consume | UI Service must not own or receive |
| ------------------ | -------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| HTTP and SPA | routes, auth middleware, UI DTOs, assets, HTTP lifecycle | contract results and health snapshots | domain entities or infrastructure handles |
| Chat | request validation and response projection | Gateway `ChatContract` | `gateway.Router`, `SessionStore`, turn runner, model/provider runtime |
| Task dashboard | query/action DTOs and HTTP status mapping | State Store narrow contracts and explicitly ratified task-action contract | `*store.Store`, SQL connections, workflow registry, daemon pointer |
| Configuration page | secret-free view and update request validation | a UI configuration contract owned by the configuration/application boundary | `config.Config`, `config.Holder`, secret registry, reload implementation |
| Readiness | UI process liveness and dependency readiness aggregation | bounded health results from Gateway and State Store | direct probing of private databases or providers |
Every value crossing the process boundary is a versioned DTO or scalar contract
value. `internal/webui` may retain temporary Go-side adapters while the
migration is in progress, but handlers must map Gateway/State Store values to
UI-owned response types at the HTTP edge. A constructor accepting a concrete
Gateway, State Store, daemon, or `config.Holder` is not an approved final
boundary.
The existing UI routes remain behaviourally compatible during extraction,
including task actions, SSE event delivery, config views, chat streaming,
capture intake, mappings, bindings, update reporting, and health endpoints.
Compatibility preserves status codes, authentication requirements, redaction,
pagination/limits, event ordering, and failure degradation unless a separately
ratified contract changes them.
The route families have these target owners. This is the required inventory for
the implementation children; a route without an owner is not eligible for
cutover.
| Route family | Target owner consumed by UI | Migration status |
| ----------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `/api/chat/*` | Gateway `ChatContract` and its versioned client | contract seam exists; DTO and stream parity remain |
| `/api/tasks/*`, `/api/workflows`, `/api/setup` | State Store read/action contracts plus an explicit execution/admin action contract | State Store adapter exists; UI-facing narrow surface remains |
| `/events` | State Store `EventsSince`, polled by one UI-process pump feeding `Server.Broadcast` | RESOLVED (`archie-core-za9f`): see migration-decisions, "Dashboard live event delivery". No new RPC; replay cursor and drop-recovery are the existing `since` watermark in `sse.go` |
| `/api/logs`, `/api/logs/stream` | daemon diagnostic feed, host-local | unresolved: `logging.Feed` is in-process on the daemon host and has no contract. The per-task log routes moved off this row: see `/api/tasks/*` above |
| `/api/tasks/{id}/logs`, `/api/tasks/{id}/logs/download` | State Store task-log read contract (`TaskLogStore`: `ReadTaskLog` + `StreamTaskLogContent`), read by the UI process from the service that owns the state directory | RESOLVED (`archie-core-iaqx`): the UI process composes `TaskLogStore` from its own State Store client and serves the attempt log as JSON (`found` distinguishes "no log for this attempt" from "this process cannot read logs") and as a `Content-Disposition` attachment named `task-<id>-attempt-<n>.log`. The daemon's in-process registry is wired as the server-side reader in `internal/app/archied/state_store.go` only (`staterpc.Deps.TaskLogs`), so no process opens another process's log files |
| `/api/captures`, `/api/mappings`, `/api/bindings` | State Store contracts, with webhook verification owned by Work Intake/Messaging | RESOLVED (cutover, `archie-core-8cda.5.4`): the UI process composes CaptureStore/MappingStore/BindingStore and mounts the `captureintake.Receiver` from its own State Store client; the daemon's binding-dispatch loop keeps consuming captures from the same store |
| `/api/config` (read) | daemon-published `ConfigView` snapshot, read over the State Store contract | RESOLVED (`archie-core-ymut`): see migration-decisions, "Dashboard configuration page" |
| `/api/config` (write), `/api/config/reset`, `/api/config/repos/*` | a configuration write contract; the daemon stays the policy owner | DESCOPED for Phase 3 (`archie-core-ymut`), NOT abandoned: 503 in the UI process, SPA hides the controls, editing is config.toml plus reload. Dashboard editing is a tracked feature (`archie-core-1786637498420-327`) and its transport is `archie-core-j28m`; the handlers and their func-field seams on `webui.Server` are kept for it |
| `/api/channels`, reload, curators, memory, skills, version/update | owning capability contract or an explicitly removed route | owner and failure semantics remain to define |
| `/`, `/healthz`, `/health`, `/health/detailed` | UI HTTP process; readiness consumes per-service health contracts | current HTTP behaviour is the compatibility baseline |
## Configuration ownership
The UI Service owns only process-local settings:
- HTTP listen address and read/header/shutdown timeouts;
- UI asset source or build mode;
- UI authentication mode and token reference;
- Gateway endpoint and credential reference;
- State Store endpoint and credential reference;
- readiness endpoint and dependency timeout policy.
These settings are decoded into a UI-owned input DTO by the UI composition root.
The DTO contains endpoint references and secret references, never resolved
secret values or complete daemon configuration. The UI process resolves its
own credentials and builds its own clients. It does not read or mutate the
daemon's configuration file, runtime overlay, forge credentials, model catalogue,
workflow routing, NATS settings, filesystem jail, or agent/container settings.
The dashboard configuration API is a separate capability. Its secret-free,
allowlisted field projections remain governed by
[`config-schema.md`](config-schema.md). During the transition the daemon may
continue to perform validate-persist-publish for those updates through a
narrow application contract. The UI process must never implement that policy
by holding or mutating a shared `config.Holder`.
The daemon's `config.Holder` sharing was migration residue: `buildDaemon`
assigned `b.web.Cfg = b.d.Cfg`. Removed by `archie-core-ml30` -- the field no
longer exists, and boot owns the single Holder the daemon reads through.
For Phase 3, configuration ownership is split deliberately. The UI process
owns its listener, browser-auth, asset, dependency-target, and readiness
settings. The daemon/application configuration owner remains authoritative for
the dashboard's `/api/config` read, validation, persistence, overlay, reload,
and audit behaviour. The UI does not become the writer merely because it
renders the configuration page.
Amended 2026-09-11 by `archie-core-ml30`: the daemon's `config.Holder` sharing
is gone. `webui.Server` has no holder field, so the sharing this paragraph
describes cannot be reintroduced by wiring; the daemon owns one Holder and
publishes a rendered projection.
There is no single narrow admin contract carrying both the read and the write
(`archie-core-ymut`). The
read crosses as a daemon-published `ConfigView` snapshot over the State Store
contract, and the write is descoped for Phase 3 rather than contracted, on the
reasoning recorded in migration-decisions under "Dashboard configuration
page". A future dedicated Configuration Service is the natural owner of a
write contract, and designing one is that feature's work, not this migration's.
## Listen, authentication, and readiness
The extracted UI follows the current web UI security posture:
- loopback listeners may omit a dashboard token;
- non-loopback listeners require a non-empty token and fail closed when it is
absent;
- `/healthz` and `/health` are unauthenticated liveness probes;
- `/health/detailed` is authenticated and reports dependency readiness;
- capture webhooks retain their separately ratified source authentication and
rate-limit rules; they are not admitted by the dashboard token;
- Gateway and State Store credentials are service-to-service credentials, never
browser-visible dashboard tokens.
The UI is ready only when its HTTP server is serving and each mandatory remote
contract has passed its bounded readiness check. Each dependency must expose a
versioned health result or health endpoint that the UI can consume; the UI must
not inspect another service's concrete manager, registry, or database. Optional
dashboard sections may remain degraded with the current explicit
`503`/unavailable behaviour. A successful liveness response must never imply
dependency readiness.
## Migration sequence and evidence
The implementation must complete these gates in order:
1. Define the UI input DTO, Gateway client surface, State Store client surface,
and UI response DTOs. Add compile-time contract assertions and mapping
tests. No handler may depend on a concrete remote implementation.
2. Make the current in-process web UI consume the same narrow adapters and
preserve the current route, auth, redaction, stream, SSE, and degradation
behaviour. Add a composition test proving the selected adapter is the one
used by production wiring.
3. Remove direct `internal/gateway` session/router/runtime access from web UI
handlers. Remove direct store implementation access, SQL access,
daemon pointers, and broad runtime callback bundles from the UI constructor.
4. Replace the shared `config.Holder` with the UI-owned configuration DTO and
narrow configuration application contract. Prove reload/update atomicity
remains owned by the configuration/application boundary.
5. Add the standalone UI process and deployment wiring. It must obtain Gateway
and State Store endpoints from its own configuration, authenticate each
client independently, start liveness/readiness endpoints, and shut down
clients and HTTP listeners in bounded order.
6. Run dual-adapter contract tests and an HTTP parity suite covering every
retained route. Test remote failures, missing credentials, malformed DTOs,
stream cancellation, stale State Store data, and readiness degradation.
7. Cut over the supported composition to the UI process. The old in-process
`webui.Run` path is deleted in the same change; no fallback or second HTTP
authority remains.
The deletion gate is objective: `go list -deps` from the UI process shows no
daemon, SQL/store implementation, workflow, forge, channel, model, or secret
runtime package; production composition contains one UI HTTP listener; and
architecture tests reject `config.Holder`, concrete `*store.Store`, concrete
Gateway runtime types, and direct database drivers in the UI service.
Rollback is a deployment composition change that points the operator at the
last validated UI binary and restores the previous endpoint configuration. It
must not restore a second writer or reintroduce shared-holder mutation. UI
state is either remote contract state or existing durable state owned by its
current service; no UI-specific database migration is introduced by this
boundary decision.
## Current evidence and known delta
Current code proves the following migration inputs:
- `internal/app/archied/bootstrap.go:setupObservability` constructs
`webui.Server` and wires store, channels, events, logs, and config-related
callbacks.
- `internal/app/archied/bootstrap.go:buildDaemon` replaces the initial holder
with `b.d.Cfg`, explicitly sharing the daemon's live configuration.
- `internal/webui/api_chat.go` calls the Gateway contract but still imports
Gateway-owned request/value types; handlers must finish the DTO projection.
- `internal/webui/server.go:Handler` owns the route set, SPA fallback, health
split, capture bypass, and token wrapper.
- `internal/app/archied/state_store.go:RunStateStore` owns the task
database and serves the State Store gRPC contract; the UI must use that contract
rather than opening the database.
- `internal/app/archied/gateway.go:RunGateway` serves Gateway gRPC and owns
Gateway session persistence; the UI must use `ChatContract` rather than
Gateway internals.
The current code therefore satisfies the upstream prerequisites but does not
yet satisfy this boundary. This document is the ratified target; the
implementation child must prove each migration gate before claiming Phase 3.
### Phase 3 gates
Every gate below is proven by test, not by inspection:
| Gate | Evidence |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Deletion | `cmd/archie-ui/architecture_test.go` re-runs `go list -deps` on every `task check` and fails on any banned package, checked in both directions against its two exceptions |
| Composition | `internal/app/archieui/TestComposeUIServerHoldsNoDaemonState` fails on a concrete `*store.Store` or a Gateway that is not the gRPC client. The holder clause it also carried is enforced by the type: `webui.Server` has no `config.Holder` field (`archie-core-ml30`) |
| End-to-end | `cmd/archie-ui/main_test.go` builds the binary and drives it over HTTP against a live Gateway and State Store |
| No dual authority | The dashboard HTTP listener is `internal/app/archieui/run.go` only; the daemon's two `http.Server`s are its own health endpoint and the forge webhook receiver |
Acceptance criterion 1 was amended at the close of Phase 3 to name the UI
process rather than the `internal/webui` package, because the daemon still held
a holder inside its own process to render the published `ConfigView` snapshot.
`archie-core-ml30` removed that residue, so the criterion holds in its original
form again: `internal/webui` receives no holder in any process.
### Deletion gate: SATISFIED (archie-core-8cda.5.6, rev. 2)
The objective gate now holds. `go list -deps ./cmd/archie-ui` links **zero**
banned packages: no `modernc.org/sqlite`, no `github.com/jackc/pgx`, no `internal/infrastructure/postgres`, `internal/gateway`,
`internal/channels`, `internal/memory`, `internal/secret`, `internal/agentexec`,
`internal/tools`, `internal/skill`, `internal/yaegiutil`, `internal/domain/curator`,
or the workflow engine (`internal/domain/workflow`). How the runtime handles were
severed, each at the producer:
- **Store contracts** moved to `internal/domain/storecontract` (producer-owned
read contracts, state-store-contract rev. 2d).
- **Chat contracts** moved to `internal/domain/messaging`; `internal/gateway`
keeps aliases. The UI process holds `ChatContract`, `SessionStore`, turn and
stream types without linking the gateway runtime or its session store.
- **Webui-owned views** replaced concrete runtime handles on `webui.Server`:
channel lifecycle via `internal/channels/status`, memory via a `MemoryStatus`
interface, curators via a `CuratorStatus` interface, and the skill catalogue
via a `SkillCatalog` interface — each supplied by a daemon-side adapter at
bootstrap, each degrading to an empty page when unwired.
- **`config.SecretRef`** moved into `internal/config` (it is config vocabulary);
`internal/secret` keeps an alias and resolves through `Registry.Resolve`.
- **Task vocabulary** (`Task`, `Store`, `Definition`, status constants) split
into `internal/domain/workflow/task`; the pipeline engine stays in package
`workflow`, which keeps aliases. The UI process links the vocabulary only.
The gate is enforced, not just measured. `cmd/archie-ui/architecture_test.go`
re-runs `go list -deps` on every `task check` and fails on any package in a
banned category, so a single reference to a type sitting beside a runtime
cannot quietly relink it. Its exception list (`internal/channels/status`,
`internal/domain/workflow/task`) is checked in both directions: an exception
the UI stops needing is reported, so the allowlist cannot decay into an open
prefix. `internal/app/archieui`'s `TestComposeUIServerHoldsNoDaemonState`
covers the composition clauses, failing on a non-nil `config.Holder`, a
concrete `*store.Store`, or a Gateway that is not the gRPC client.
One piece of residue remained visible at the close of Phase 3: `webui.Server`
still declared `Cfg *config.Holder`, because the daemon kept a `webui.Server`
as the renderer that built the published `ConfigView` snapshot. That cleanup
landed as `archie-core-ml30`. `webui.Server` no longer has a configuration
holder, provenance store, reload-status callback or override-listing callback:
the projection is built by `webui.BuildConfigView`, a pure function the
configuration owner calls, and the daemon assembles its input from its own
state (`boot.configViewInput`). Readiness reads the daemon's own Holder,
channel manager and chat contract, and the health registry it produces is a
daemon field rather than a field on a server the daemon never serves.
`ConfigView.Editable` moved with it. It describes the rendering process's own
write path, so `handleConfig` sets it from `Server.UpdateConfig` rather than
any process baking it into the document. A future configuration write contract
(`archie-core-j28m`) makes the page editable by wiring that one field.
### Real-process evidence (archie-core-8cda.5.6)
`cmd/archie-ui/main_test.go` builds the binary and runs it against a State
Store and a Gateway on loopback gRPC, then drives it over HTTP: liveness
without a token, 401 for an API request without one, the `?t=` exchange into
an HttpOnly cookie, task rows with their forge links, the embedded SPA and its
assets, a chat stream relayed frame by frame from the Gateway, an operator
task action crossing to the Gateway (and refused without the CSRF header),
capture intake accepted unauthenticated, the ratified degradations, readiness
dropping when the State Store dies while liveness holds, and a clean SIGTERM.
Two dashboard values degraded here because the published projection did not
carry them: `chat.show_tool_calls` (the chat page never expanded tool calls)
and the `/api/setup` checklist (the panel was omitted rather than rendered).
Both are closed by `archie-core-ml30`: `ConfigView` gained a `chat` section
carrying `show_tool_calls`, the operator name, and whether any chat channel is
configured, and both surfaces now read the projection rather than a live
holder. The end-to-end suite drives the real binary and streams a turn, so the
`show_tool_calls` assertion is made on the frames a browser receives.
The checklist stays. The question raised when it was republished -- is a
read-only setup report wanted in a process that cannot apply the setup it
reports? -- resolves in favour of keeping it, because the panel never promised
to apply anything. It renders each step as a title, a detail and a done mark
with no control behind it, so it answers "what is this deployment missing?"
rather than "fix it here", and the page that CAN act on it (the Configuration
page) is where an operator goes next, in the daemon's own words. Removing it
would delete the one surface that distinguishes a fresh deployment from a
finished one for no gain, since the values it reads already cross the boundary
in `ConfigView` and the read path costs the daemon nothing. The write path
remains descoped (see `/api/config` (write) in the route table): the checklist
reports configuration, it does not change it.
`archie-core-ml30` published the channel flag from two of the three chat
front-ends, so an email-only deployment read as configured on `/api/channels`
and unconfigured on the checklist at the same time (GitHub #821). Both now
derive from `config.ChatConfig.FrontEnds`, the single definition of a configured
front-end, and a test pins the two surfaces to the same answer.
A third value degraded for the same reason and is closed by
`archie-core-pv6t`: in a deployment configuring `[[identities]]` the projection
carried the default identity's forge alone, so task rows withheld their links
rather than pointing every row at the wrong forge. `ConfigView` now also
publishes each identity's forge coordinates and the repositories it owns
(`identities`), which is what resolving a task to its owning forge needs —
coordinates and repository names only, never a token. The end-to-end suite
drives the real binary against a multi-identity projection and asserts each
row's issue link is built from the forge that owns it.
## Non-goals and open work
This ratification does not define a new domain model, move the dashboard's
allowlisted configuration schema, redesign Gateway or State Store RPCs, choose
Kubernetes versus local discovery, or authorise unrelated package migration.
Those decisions remain in their existing authority documents. Any new UI
capability that requires a wider Gateway or State Store surface must amend that
service's contract before implementation.
-269
View File
@@ -1,269 +0,0 @@
# Preact → Vue 3 + shadcn-vue migration checklist
**Status:** Approved
**Date:** 2026-09-20
**Bead:** `archie-core-tavn` (epic), `archie-core-ocfm` (navigation restructure)
**Bootstrap commit:** `e18fb8b2`
The Preact dashboard was deleted, not ported incrementally. This is the list of
what has to exist again, what must not be lost on the way, and the contracts
that break silently if missed.
Deleted source is recoverable at `git show e18fb8b2^:ui/src/<path>`. Every
claim below was cross-checked against that tree; where a number is a live
measurement rather than something recoverable from git, it says so.
## Invariants that outlive the framework
These are not features; they are things other processes depend on. Breaking one
does not show up as a broken page.
- [ ] **Embed contract.** `ui/embed.go` embeds a committed `ui/dist`. The build
must keep unhashed `assets/index.{js,css}`: dist/ lives in git, and
hashed names orphan a file on every rebuild.
- [ ] **Route registry.** `internal/gateway/dashboard_tools.go` hand-copies the
route table and `TestDashboardPagesRegistryCoversEveryRoute` parses
`ui/src/router/index.ts` to hold them in step. The parser needs
`const routes = [` on its own line, `path: "..."` on a single line per
route, and `nav: false` on any entry the registry should skip. That guard
caught a stale `/chat` entry earlier.
- [ ] **Mutation headers.** Every POST/PATCH/DELETE must send **both**
`X-Archie-CSRF: 1` and `Content-Type: application/json`. The server
returns 403 without the first and 415 without the second
(`internal/webui/api_tasks.go`, `authorizeTaskMutation`). GET sends
neither. This is the single most likely thing to silently break every
write after the port.
- [x] **History routing.** `createWebHistory`, `base: "/"`. Legacy `#/path`
links are rewritten by `src/legacy-hash-redirect.ts`. The chat navigate
chip should emit `/tasks`; the Go side already stores bare paths.
- [ ] **Capability gating.** `GET /api/capabilities`
(`internal/webui/api_capabilities.go`) returns a `sections` map of ten
booleans: chat, logs, skills, curators, channels, captures, mappings,
bindings, and workflows/settings which are always true. A route whose
section is false must be hidden, not rendered empty. **Fail open**: on a
failed or null response hide nothing — the old client used a bare
`.catch(() => {})` for exactly this. A page that says "unavailable" is
recoverable; a nav entry that vanished is not.
- [ ] **`LOG_LEVELS`** in `base/log-row.jsx` is a wire contract, not a display
list: the CSV level filter is matched server-side by `splitCSV` in
`internal/webui/api_tasks_logs.go`. A value mismatch breaks filtering
with no error.
- [ ] **SSE lifecycle.** Three streams, all `id: <n>\ndata: <json>\n\n` except
chat which omits the id:
`/events` (task lifecycle, `sse.go`, supports `?since=` and
`Last-Event-ID` resume), `/api/logs/stream` (`api_logs.go`, same
resume protocol), `/api/chat/stream` (`api_chat.go`, frames typed
delta/tool/media/navigate). Each must be closed on unmount or the app
leaks a connection per navigation. Preact used an `archie:teardown`
event; Vue should use `onUnmounted`.
> **On tests.** Per Sam's call, the 43-file suite was not ported and tests
> return when there is behaviour worth pinning. Flagging one exception for when
> that moment comes: the deleted `ui/test/api-client.test.js` classified every
> API method as mutation/read/stream/url and asserted the right headers per
> class. It is the only cheap guard on the CSRF contract above. (It did **not**
> text-scan for a second `fetch()` — that check was deliberately removed
> upstream for testing the file's wording rather than its behaviour.)
## Phase 1 — Foundation
- [x] **Theme.** `css/tokens.css` was a complete two-theme semantic token set
(`--fg-subtle`, `--accent`, `--ok/warn/danger`, surfaces, shadows). Mapped
onto Tailwind v4's `@theme` in `src/style.css`; the second system was not
kept.
- [x] **`color-scheme`.** `[data-theme="dark"] { color-scheme: dark }` and the
light equivalent. Without it the UA paints light scrollbars and light
native controls inside the dark app. Fixed; trivially lost.
- [x] **Contrast values.** The violet palette moved these off the values pinned
here, so they were recomputed against its own backgrounds instead of
carried: `--fg-subtle` `#A99DBD` dark (7.67:1, AAA) / `#6E6577` light
(4.87:1, AA), and `--fg-muted` `#B9AECB` / `#635B6B` (9.28:1 and 5.70:1).
The invariant the pin existed for holds; the values are the palette's.
- [x] **API client** (`base/api.jsx` → `src/lib/api.ts`). Keep `ApiError`
carrying `status`, and the 401/4xx/5xx classification callers branch on
(`classifyActionError`). `GET /api/bindings/{id}` and
`GET /api/mappings/{id}` exist server-side but were never called — do not
add clients for them without a reason.
- [x] **App shell** — the real source is `main.jsx` (410 lines), not just CSS.
Beyond the topbar and outlet it carries:
- [x] **Jump-to search**: Enter navigates to the first nav label matching the
typed prefix; Escape closes the field and calls `preventDefault` so it
does not also close the chat panel, which has its own Escape handler.
- [x] **`soon: true` nav entries** — greyed, labelled, non-navigable. An
affordance, not dead code.
- [x] **`loadTaskMeta()` at boot**, which re-renders the mounted route once
`/api/task-meta` lands so freeze-dried defaults are replaced.
- [x] **Route keying**: keyed on path + params but deliberately **not** the
query string, so a query-only change (a task-detail tab switch) does
not remount and lose state, while two different `:id`s do get fresh
instances.
- [x] `.shell` has `backdrop-filter`, making it a containing block for
`position: fixed` — the chat launcher must render outside it.
- [ ] **CSS inventory.** `layout.css` was reassessed rather than ported whole.
The command bar is a Vue component styled with Tailwind like every other
surface inside the shell, so it emits none of that file's `.topbar`,
`.nav`, `.topbar-search` or `.icon-btn` classes: only the frame those
rules bounded is kept (`body` canvas, `.shell`, `.main`, and the 900px
collapse), and the topbar/nav rules with their 1500px and 1270px
breakpoints were deleted as unconsumed. The command bar's own responsive
behaviour is the components' business, so "port from this file" applies
to the frame and, later, the chat dock, not to class names. Still to
port, when the pages that use them exist: `card.css`
(`.card`/`.grid-2`/`.grid-4`), `page.css`
(`.page-head`/`.page-title`/`.page-sub`/`.page-actions`), `pill.css` (the
ok/warn/danger/info/idle definitions a Badge port must match), and the
chat dock and morph Phases 3 and 5 describe. `base.css`,
`responsive.css` and `_main.css`'s import order are ported.
- [x] **Theme toggle** and its persistence.
## Phase 2 — Shared primitives
| Was | Is |
| -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `base/pill.jsx` | `Badge`, with five status variants (`ok`, `warn`, `danger`, `info`, `idle`) over the palette's status tokens |
| `base/statTile.jsx` | `base/StatTile.vue`: full `Card` composition (`CardHeader`, `CardTitle`, `CardDescription`, `CardAction`, `CardContent`), `base/Sparkline.vue`, and the `goodDirection` trend logic |
| `base/icons.jsx` | **Not ported as a module.** Its string-keyed lookup is the pattern shadcn-vue's rules name as wrong, so icons come from `@lucide/vue` at the call site |
| `base/gauge.jsx` | `base/Gauge.vue` and `base/SegmentBar.vue`, both ported. The gauge's `aria-label` announces the rounded percentage, which closes `86au` |
| `base/log-row.jsx` | `base/LogRow.vue` over `lib/log.ts` (`LOG_LEVELS`, `levelKind`, `shortTime`, `fmtValue`) |
| `base/format.jsx` | `lib/format.ts` (`ago`, `compact`) |
| `base/task-meta.jsx` | `lib/task-meta.ts`; Vue's reactivity replaces the manual boot-time re-render the Preact module needed |
Two decisions worth not re-litigating:
- The pill's dot did not come across to `Badge`. The Badge's own shape is the
affordance, and the same variant now covers things that are not status pills
(a trend indicator), where a dot reads as noise.
- The five bespoke glyphs (`dashboard`, `mappings`, `bindings`, `curators`,
`memory`) are not drawn yet because nothing consumes them: the navigation is
text with tooltips. If a page needs one, it becomes its own component at that
point rather than a glyph table waiting for a caller.
- [x] **Copy verbatim.** `dashboard/activity-detail.ts`, `chat/command-scroll.ts`,
`workflows/workflow-rows.ts`, `logs/logs-empty.ts`, and `lib/stream-state.ts`.
- [x] `base/uuid.jsx` → `src/lib/uuid.ts`.
- [x] `routing.jsx` is superseded by vue-router. Not ported.
## Phase 3 — Pages
In dependency order. Each is `git show e18fb8b2^:ui/src/<folder>/`. File counts
verified against the deletion diff.
Ported as named components, not as one file per page: see
`docs/prds/dashboard-port-brief.md#componentisation`. A page file composes and
holds nothing, shared state lives in a module beside it, and a lookup that maps
a string to a component is not written.
- [x] **Dashboard.** Health row, Throughput tiles, Token outlook, Live activity
table, the time-of-day `greeting()`, and the click-through from an
activity row to its task. The setup panel branches on the state machine
rather than on "is setup present", which had shown a 100% checklist where
the complete state belongs.
- [x] **Tasks.** List, filters, row actions, detail page with tab bar, stage
rail, changed files, attempt config, task logs, timeline, debug view.
Both interaction contracts survive: detail `tab`/`attempt` is written with
`router.replace` (never a hash, and replace so a tab click adds no history
entry and does not remount), and the list's reduced-motion-aware
scroll-to-row reveal for deep links. `1q89`'s column priority is applied.
One deliberate deviation: the list's inline timeline expansion is gone,
since the row now opens `/tasks/:id` and that page owns the timeline; the
phone layout's stacked cards are not reproduced and the table scrolls
inside its own container instead.
- [ ] **Chat.** In progress.
- [x] **Configuration**, split into the six `/system/*` routes the approved
design names, with the editable-vs-read-only dual mode intact: this
composition serves a published snapshot, so the pages say they are
read-only rather than rendering controls that cannot work.
- [x] **Logs.** Filters, live tail, pause. A 503 on the stream renders as
"Log stream unavailable" with the reason, not as a permanent
"reconnecting".
- [x] **Event inspector / captures.**
- [x] **Field mappings**, including the mapping editor. Its `mappingPreview`
`capture_id` is a number: the wire type is int64 and a JSON string is
rejected.
- [x] **Playbook bindings**, including the binding editor.
- [x] **Workflows**, keeping the "No stage data yet" state and omitting the
Start-work form when the endpoint serves no definitions (`3tij`).
- [x] **Skills**, **Curators**, **Channels.** Capability-gated and hidden on the
reference deployment, so all three were verified by their own empty state.
Every page was rendered against the running daemon at 1440x900 and 720px, with
no horizontal page scroll at either width.
## Phase 4 — Navigation restructure
Build it during the port rather than porting the flat bar first.
- [x] Five top-level items: Dashboard, Work, Agent, Events, System.
- [x] Rename under their group: Inspector, Mappings, Bindings.
- [x] Per-item hover tooltips carrying a one-line description.
- [x] Configuration splits into `/system/{status,appearance,tasks,models,repos,advanced}`.
- [x] `/settings` redirects to `/system/status` — it is in bookmarks and in the
Go route registry.
- [x] Add Logs to the nav. It was never in it.
- [x] Preserve the `soon:` entry treatment.
- [x] The theme control moves off the topbar and onto `/system/appearance`. Two
switches for one preference is two places to look and one of them to be
wrong; `components/topbar/ThemeToggle.vue` is deleted, not orphaned.
- [x] Update `dashboard_tools.go` for every new route in the same change. The
registry already carried all sixteen, so its parity test has been passing
throughout; it is the check that a route cannot be added here and
forgotten there.
## Phase 5 — Behaviour a naive port loses
This behaviour exists only in the deleted tree.
The implementation source for nearly all of it is
`git show e18fb8b2^:ui/src/css/layout.css` plus `main.jsx` and `chat/chat.jsx`.
- [ ] **Chat is a FAB, not a route.** No `/chat`, no nav entry, no topbar icon.
- [ ] **The panel grows out of the launcher**: collapsed to a pill over the
button, expanding with scale, border-radius and position interpolating
together; contents fade in after the shape arrives.
- [ ] **No scrim, no scroll lock.** The page stays readable and clickable.
- [ ] **No close button** — the FAB is the only toggle, and stays visible on
mobile where the panel becomes a sheet.
- [ ] Escape closes the panel **and returns focus to the launcher**; the dock
carries `aria-expanded`/`aria-controls`/`aria-hidden`.
- [ ] Header shows the open conversation's name (`panelTitle`).
- [ ] New chat = `message-circle-plus`, in the header.
- [ ] Slash palette is the only command surface; it floats above the input and
scrolls to keep the arrow-key selection visible.
- [ ] Settings popover closes on outside pointerdown and focus-out.
- [ ] Stop renders only while streaming; composer stays writeable and focused
during a send.
- [ ] Bubbles carry no speaker label.
- [ ] **Topbar cannot clip.** The nav is the only shrinkable region; search
collapses below 1500px; nav wraps below 1270px; sheet mode at 720px;
edge-to-edge at 900px. Previously the utility cluster was unreachable
between 1221px and ~1582px: measured at 1440x900, `.topbar-end` ended at
x=1515 against a shell edge of 1409, so 106px carrying the avatar, theme
toggle and documentation button was clipped with no scroll affordance.
That figure is a live measurement, not recoverable from git.
- [ ] **Live activity detail is clamped** to one line with the full payload on
the title. Unclamped it made the dashboard 7,481px tall.
- [ ] **HEALTH cards take their own height** (`align-items: start`).
- [ ] **Workflow rows merge** definitions with statistics.
- [ ] **Log stream reports `unavailable`** from `readyState`, not a permanent
"reconnecting".
- [ ] **Unconfigured capabilities say so** (501 → "Not configured on this
deployment") rather than rendering nothing.
- [ ] **Operator cards on Configuration**: update install/defer, dangerous
action approvals. Both absent when their endpoint 501s.
## Known-open, carry forward
Open beads against the old UI that the port should satisfy rather than
reintroduce: `1q89` (tasks column priority, wrapping row actions), `to2y`
(three empty-state treatments; Field mappings dead-ends), `gl96` (Logs missing
from nav), `86au` (gauge `aria-label` announces an unrounded percentage),
`6m8r` (mobile KPI cards push content below the fold; 89 sub-44px targets),
`ggqo` (config page width — moot once Configuration splits), `3tij`
(`/api/workflows` serves no definitions, so "Start work" never renders),
`oif3` (Reload Telegram, blocked on `ry4k`).
## Not doing
- Porting the 43 test files. Tests return when there is behaviour worth pinning
rather than a port to re-assert. `task test:ui` is a `vue-tsc` typecheck
meanwhile. See the note under Invariants for the one exception worth
reconsidering first.
-101
View File
@@ -1,101 +0,0 @@
# Webhook intake security -- decision
**Status:** Approved
**Date:** 2026-08-22
**Beads issue:** `archie-core-t2db.5`, blocks `archie-core-t2db.4`
## Why this is decided ahead of the code it constrains
`archie-core-t2db` (no-code playbooks) and `archie-core-7d5u` (typed event
sources) both land a public intake surface whose eventual output is an agent
with tool access and a repo. Neither capture (`t2db.1`) nor the intake family
(`7d5u.3`) has shipped yet, so this decision exists to be a contract the two
epics build against, not a retrofit once the surface exists. A webhook URL
that can start an agent is remote code execution with extra steps if any of
the five points below is missing on day one.
## 1. Per-source authentication
Reuse the per-route HMAC-SHA256 scheme already in
`internal/channels/webhook/webhook.go` (`validateHMAC`), unchanged: a source
registers with a shared secret; the signature is checked against the raw
body. Do not invent a second scheme for intake.
**Capture and triggering split at the signature, not at a separate flag.** An
event with a missing or invalid signature is still captured (visible in the
inspector, marked unauthenticated) so an operator can diagnose a
misconfigured sender -- but an unauthenticated event can never be matched
against a binding. Authentication is what promotes an event from "something
arrived" to "something that can run a workflow."
## 2. Human approval before a binding arms
A binding has three states: `draft -> pending_approval -> armed`. Only
`armed` bindings are evaluated against incoming events. Creating or editing a
binding's matcher, mapping, or target workflow always sets it to
`pending_approval`, including edits to an already-armed binding -- an edit is
not silently re-armed, or the approval gate is decorative. Approval requires
an authenticated dashboard session; there is no unattended approval path.
Model: `internal/channels/telegram`'s dangerous-command approval flow
(`dangerousAction` / `pendingApproval` in `dangerous.go` / `approval.go`) is
the existing precedent for "a human decision gates code from running" in this
codebase -- follow its shape rather than designing a new approval primitive.
## 3. Rate and volume limits, per source
A token-bucket limiter keyed by source ID, not global -- one noisy or hostile
sender must not exhaust another source's capture budget. Precedent for
per-key volume capping: `internal/pairing/store.go`'s `MaxPendingPerPlatform`.
On limit exceeded, the request is rejected (HTTP 429), not silently dropped.
A silently dropped event is indistinguishable from a sender that never fired
-- the same invisible-failure shape the update-verification work
(`archie-core-522`) exists to prevent. The rejection itself is observable in
the inspector as a distinct outcome from "not received."
## 4. Blast radius bounded by code, not by prompt wording
A playbook-triggered task runs through exactly the same enforcement as every
other task: the `[[repos.gate]]` quality gate, `diff_cap_lines`, the
sandboxed per-task container (`internal/container`), worktree isolation, and
"the model never runs git." No new relaxation is introduced for
playbook-triggered work, and none is needed -- the existing constraints are
the control.
Mapped payload fields are treated as ordinary user-controlled text inside an
agent prompt, exactly like an inbound chat message never as trusted
instructions. "The agent should ignore instructions in the payload" is not a
control and must not appear as one anywhere in this feature -- per the
environmental-enforcement principle (`docs/architecture/agent-system.md`,
"Existing invariants to preserve"), the boundary is the gate and the sandbox,
not a sentence in the system prompt.
## 5. Retention and redaction of captured payloads
**Retention:** captured events (bound or not) are purged after 7 days,
configurable per deployment. Unbound events exist to be mapped against; nothing
justifies keeping them indefinitely once that window has passed, and an
unbounded capture store is the same disk-exhaustion risk item 3 addresses at
the request-rate level.
**Redaction:** before a captured payload is persisted, apply the same
key-name heuristic `internal/gateway/stream.go`'s `sensitiveParameterKey`
already uses for tool-call parameters (matches `token`, `secret`, `password`,
`passwd`, `api_key`, `apikey`, `authorization`, `credential`, `cookie`,
`private_key` against normalised JSON keys) and replace matching values with
the same `[redacted]` marker. This is best-effort, not a guarantee -- a
sender that names a secret field something the heuristic misses will still
have it captured. Document that limitation where captured payloads are
displayed, rather than implying the redaction is complete.
**Visibility:** captured payloads, redacted or not, are visible only to an
authenticated dashboard operator -- the same authorisation boundary as every
other webui surface, not a separate or lower bar.
## What this does not decide
The intake family's registration interface (`7d5u.3`), the capture storage
mechanism (`7d5u.2`, embedded NATS), and the binding data model's persistence
and versioning (`t2db.4`) are separate decisions. This document constrains
all three: whatever they build must satisfy points 1-5 above.
-216
View File
@@ -1,216 +0,0 @@
# Declared outputs of a workflow run
**Status:** Draft
**Date:** 2026-09-30
**Bead:** `archie-core-t2db.43`
**Authority:** `docs/prds/event-automation.md` for what a declared output is,
`docs/prds/workflow-calls.md` for the call and its grants,
`docs/prds/state-store-contract.md` for the State Store contract the wire
change must satisfy.
**Supersedes:** `docs/prds/workflow-calls.md`, "Waiting on the callee": the
callee's transition detail is the human summary, not the stand-in for
structured outputs.
A workflow declares named, typed outputs. A run writes each one once. A
`wait: true` caller receives them, and may publish one as its own.
## Where outputs are declared
`outputs:` on the workflow definition, beside `inputs:`, decoded into
`task.WorkflowInterface.Outputs map[string]OutputSpec` where
`OutputSpec{Type, Required}`:
```yaml
id: firewall-contain
outputs:
contained: { type: bool, required: true }
summary: { type: string }
```
Names and types are the input grammar: the same identifier shape, the same
type set, and the same check in `WorkflowInterface.Validate`, which both
`ParseDefinition` and `ParseWorkflowInterface` call.
**Forced by:** `ParseDefinition` decodes with `KnownFields(true)`, so a key no
decoded struct declares is refused — the declaration must live on
`WorkflowInterface` for an author to write it at all, and that is where
`docs/development/workflows.md` puts every field a process without the engine
must read. The type set is the shared value vocabulary: `TypeAccepts` and
`ValueType` already check a mapped parameter and an input with it. `required`
defaults to false, and the generated YAML for a builtin that declares no
outputs is unchanged, because a definition's digest pins a run.
**Rejected:** outputs per step, or per call step, because a workflow returns a
result as itself rather than as one of its stages. Also `task.Definition`
gaining outputs: no reader needs them — a binding offers inputs, and a call's
outputs assignment is checked against the callee's YAML in the same
collection — and a declared field with no reader parses and does nothing.
## How a run writes one
Each declared output is offered to the run's agent stages as a capture tool
named after the output, whose arguments are `{"value": ...}`; the accepted
call's `value` member is the output's value. The engine holds the accepted
values on the task context and writes them into its own task row in the
`Store.Update` call the run already makes. A deterministic stage may set the
same values in Go, and the run's finish check validates them identically.
**Forced by:** a run's only structured results are capture calls
(`agentexec.CaptureTool`, `Result.Captures`), and the workflow interface
already declares when a stage needs them (`task.WorkflowNeeds.Captures`).
`WorkflowInterface.Needs` reports `captures` for a non-empty `Outputs`, so
declaring an output alone requires the capability and a Kit profile that
serves no capture tools is refused before dispatch.
Deriving the tools from the declaration means an output cannot be written
under a name nobody declared, and it keeps one route to structured agent
output rather than adding a second beside the capture path. The row write is
the run's existing write: the task row is where a run's own state lives, and
the container already holds `Update` on its own row.
The tool is offered with `MaxCalls: 1`, and a stage is not offered an output
the run has written, so a run writes each output once: a repeat within a stage
is answered with the tool's rejection and the agent carries on, and a later
stage cannot overwrite a value. A stage's own capture tool may not share a
name with a declared output, because the value would otherwise be ambiguous.
**Rejected:** a `workflow.output` step type, because assigning the run's
result from a step needs a grammar for "the previous stage's result" that does
not exist, and a step that reaches the agent would be the second path
`docs/development/workflows.md` forbids. Also a write RPC of its own: the
container's `Update` already reaches its own row, and a second write verb for
one column is a second thing to keep in step.
## How a caller receives one
On a successful `wait: true` call the caller's stage holds the callee's
outputs as a `map[string]any`. A call step's `outputs:` setting publishes one
as one of the caller's own outputs:
```yaml
steps:
- type: workflow.call
workflow: firewall-contain
wait: true
inputs: { src_ip: inputs.src_ip }
outputs: { contained: outputs.contained }
```
The key names the callee's declared name; the value names one of the caller's
own with the prefix the call's `inputs:` already uses. A published value joins
the caller's output set for its run, so a caller returns its callee's result to
its own caller, and a run may publish a callee's output and write its own
others.
Lifetime is the attempt. The run starts with an empty output set, every later
stage of that attempt sees the values, and the finish write replaces the row's
set wholesale — so nothing an attempt wrote survives into the next, and a run
that writes nothing stores nothing. Values reach a caller only from a
successful terminal state: the caller assigns them after `callSucceeded`, so a
parked or failed callee delivers nothing whatever its row holds. A call step
with `wait: false` and an `outputs:` block is refused when the definition is
saved, because nothing has finished when the caller moves on.
**Forced by:** caller and callee are separate runs in separate containers, so
the caller's own row is the only durable place to hold a received value. The
prefix rule is not a new grammar: in `inputs.<name>` the prefixed side is the
caller's own value and the map key is the callee's, and `outputs.<name>` reads
the same way in the other direction.
**Rejected:** an implicit same-name copy from callee to caller, because the
caller's contract would then depend on a callee it does not name, and swapping
the callee would silently change what the caller returns. Also letting a later
stage read a callee's output in its mission text: that needs a stage-result
reference namespace this model does not define.
## Failure rules
- **Undeclared value.** The agent path cannot produce one — the tool exists
only for a declared output. A Go stage that sets an undeclared key parks the
run before its outcome transition, and a stage capture tool sharing a
declared output's name is refused when the run starts.
- **Declared but never written.** With `required: true` the run parks naming
the output and reaches no successful terminal state, so no caller observes a
success missing a promised value. Without it the key is absent from the
object rather than null, and a written `null` counts as not written, as
`CheckInputs` treats a null input. A published output the callee never wrote
leaves the caller's output absent, which the caller's own `required` then
judges.
- **Save time.** `WorkflowInterface.Validate` refuses an unknown type and a
malformed name. A call step's `outputs:` assignment is checked by a
`checkCallOutputs` beside `checkCallInputs`: the key must be declared by the
callee, the reference must name an output the caller declares, and the
callee's declared type must satisfy the caller's.
- **Run time.** A captured value is re-validated against the declared type
when the run reads it back, for the reason `readCaptures` re-checks every
record: the captures file is writable by the harness user. A published
callee value is re-checked against the caller's declared type before it
enters the caller's set; a mismatch parks the caller naming the output.
**Rejected:** typing at save time only, because a captured value has no
save-time form; and at run time only, because a definition error would surface
as a failed run instead of a refused save.
## Storage and wire
- `tasks.outputs`, text, `NOT NULL DEFAULT ''`, written by the run's own row
write — the shape `tasks.inputs` already has, with `EncodeOutputs` and
`DecodeOutputs` beside `EncodeInputs`/`DecodeInputs`.
- The `Task` message carries it as `outputs_json`, because the container's
`Update` sends the whole row and a column the message cannot carry is a
column that write drops.
- `WorkflowCallStatusResponse` carries it as `outputs_json` beside `status`
and `detail`, read from the callee's row by the handler that already
verifies `call_parent_task_id`; `detail` keeps carrying the transition
detail. The Go facade stays the two methods of `task.Caller`; no interface
method is added.
**Forced by the grant:** a caller authenticates as its own task and may reach
`WorkflowCallStatus` on its own task ID, `Update`/`Transition`/`InsertEvent`
on its own row, and the step-execution pair on its own execution. It can read
neither the callee's row nor the callee's steps. `WorkflowCallStatus` is
therefore the only channel that exists, and it is already the sanctioned
cross-run read — this model fills the placeholder it carries. The values live
on the callee's row rather than on the caller's call step because the callee
writes them and the caller only receives them.
The write order is part of the contract: a run persists its outputs before its
outcome transition, so the status a caller sees when its wait ends already
carries them. A set whose encoded form passes the bound the store applies to a
structured payload (`clip`, as `ReviewPayload` is stored) is refused rather
than clipped, because clipped JSON does not parse.
No sentinel moves: a missing required output is an engine park reason, and a
caller asking about a task that is not its callee still gets `ErrCallNotYours`,
so nothing new crosses `mapError`/`unmapError` and no canonical message string
changes.
**Rejected:**
- A new read RPC (`WorkflowCallOutputs`) — a second poll of a row the caller
already polls, whose answer could disagree with the status beside it, and a
second grant-widening row for the same parent-child check.
- The step-execution record — `ListSteps` is granted by `read` on a run, so a
caller cannot read the callee's steps at all, and making them readable would
hand it the callee's whole step history, which the parent-child check exists
to prevent. A step's `detail` is text clipped like every other detail.
- The caller's call step as the store — the value originates in another
process and must outlive the container that produced it.
## Out of scope
- A run started by a binding: it has no caller, and its outputs live on its
own row only.
- A stage reference to a previous stage's captured value.
- Assigning outputs in a caller cancelled while it waits.
## Verification
- A definition whose output type is not in the vocabulary, and a call
publishing an output neither side declares, are refused when saved.
- A `wait: true` caller receives a value its callee wrote, returns it as its
own output, and the caller's row carries it.
- A run whose required output is never written parks, and its caller's stage
fails naming the output.
- A call step publishing an output over `wait: false` is refused when saved.
- A retried attempt that writes no outputs leaves an empty set on the row.
- An example under `examples/workflows/` carries an `outputs:` block and a
call that publishes one, which `TestExampleWorkflowsParse` covers.
-128
View File
@@ -1,128 +0,0 @@
# Workflows calling workflows
**Status:** Draft
**Date:** 2026-09-26
**Bead:** `archie-core-t2db.41`
**Extends:** `docs/prds/event-automation.md` (workflow/binding/profile model), `docs/prds/state-store-contract.md` (two new RPCs), `docs/prds/execution-tree-state-machine.md` (call kind)
## The call, end to end
```
caller run (in agent container)
workflow.call step ──StartCall──▶ State Store EnqueueCallTask(caller, workflow, inputs)
│ callee task row: org/identity/owner/repo
│ derived from the caller row server-side
▼
callee task (queued, org of the caller)
│ daemon claims, pins the callee's OWN
│ definition → its OWN agent profile
▼
callee run (its own container, own tree)
wait: true ──poll──▶ State Store WorkflowCallStatus(caller, callee)
wait: false ──continue
```
A `workflow.call` step starts the callee as a first-class task and, with
`wait: true`, waits for its terminal state. The callee is never run "inside"
the caller: it gets its own task row, its own pinned definition, its own
profile, its own container, and its own outcome on its own run
(`execution-tree-state-machine.md`).
## Save-time checks (the collection is the authority)
All semantic checks run in `workflow.ValidateDefinitionCollection`, the gate
every save and load of the `workflow-definitions` resource passes through.
A single-definition parse cannot see callees, so it validates shape only.
- **Callee exists.** A call to a workflow outside the collection is refused.
- **Inputs checked.** A call value is a literal or a reference
(`inputs.<name>`) to the calling workflow's declared input. References must
name a declared input; the resolved type must satisfy the callee's declared
type; unknown callee inputs are refused; a required callee input must be
assigned.
- **Self-calls refused.** The call graph over the collection is walked from
every workflow; a workflow that reaches itself, directly or through other
workflows, is refused with the cycle path. (Cycles can otherwise deadlock:
`wait: true` callers hold their containers.)
- **Repository.** `workflow.call` needs no repository, so it is legal in a
`repository: none` workflow: the callee inherits the caller's task record
(owner/repo/identity/org), and the callee's own `repository` mode decides
whether its run clones.
- **Org enablement** (bead `archie-core-t2db.42`): the single
instance-wide collection the current model serves is what "enabled for
the caller's org" resolves against — an undefined callee parks. The
callee's org is derived from the caller's row, so a callee is never
visible outside its caller's org. The per-org enable/disable catalogue
lands with `archie-core-t2db.42` and becomes the one source of this
predicate.
## Runtime
**Depth limit.** `workflow.MaxCallDepth` (5). The calling stage refuses a call
that would exceed it; the store re-checks on insert (callee depth = caller
depth + 1), so no path can enqueue past the limit.
**Starting the callee.** The caller runs inside a container whose task-scoped
State Store grant authorizes only `Update`/`Transition`/`InsertEvent` on its
own task — it can neither enqueue a task nor read another one. One new
contract RPC starts the callee:
- `EnqueueCallTask(caller_task_id, workflow, inputs_json) → task`
— the store reads the caller row, refuses a caller that is not `running`,
refuses past the depth limit, and inserts the callee row deriving org,
workspace, identity, owner, repo and a fresh synthetic issue number from
the caller (the same org COALESCE `EnqueueIssue`/`InsertChatTask` use). The
callee row carries `call_parent_task_id` and `call_depth`.
**Waiting on the callee.** One new read RPC returns a call's callee:
- `WorkflowCallStatus(caller_task_id, call_task_id) → (status, detail)` — the
handler verifies `call_parent_task_id` matches, so a caller reads only its
own callees, and returns the callee's status plus its latest transition
detail (the callee's summary — the wait:true "outputs" until a structured
outputs model lands).
Both RPCs are admitted to task-scoped grants on `caller_task_id == granted
task ID` (`authorizesTaskScopedCall` gains two request-shape cases). This is
the one sanctioned widening of a task grant: the callee is the caller's child,
and starting it is the mechanism by which one event becomes several runs. The
widenings stay request-shape checks; the parent-child authorization is a
handler-side row check, so the interceptor never reads the database.
**Schema.** `tasks` gains `call_parent_task_id` (bigint, default 0) and
`call_depth` (int, default 0); both cross the wire on the `Task` message.
Columns default so existing writers and rows read as depth-0 root runs.
**The engine capability.** The workflow domain owns a consumer facade,
`task.Caller` (2 methods), carried by `*staterpc.Client` and wired into
`TaskContext.Calls` by the agent worker's composition root — the same shape
as `workflow.Store`. A runner with no `Calls` capability fails a
`workflow.call` step with a named error rather than pretending.
**Semantics.**
- `wait: false` — start, record a durable `workflow_call_started` event, and
continue. The callee's outcome is reported on its own run.
- `wait: true` — start, then poll `WorkflowCallStatus` (2 s, bounded by the
task's wall clock) until the callee is terminal. `completed`, `pr_open` and
`merged` succeed the step; `parked`, `failed`, `rejected`, `dead` and
`closed_wont_do` fail it with the callee's detail in the error. A durable
`workflow_call_finished` event carries the terminal status and detail.
- The caller's own stage/attempt accounting is unchanged: the call is one
stage that took as long as its callee.
- A callee inherits the caller's task record but is otherwise independent:
retry, park and cancel of the callee never rewrite the caller. Cancelling a
caller cancels its callees through the operator action on each
(`execution-tree-state-machine.md` "Cancellation"); until the tree state
machine lands, a caller cancelled while waiting fails its stage and leaves
the callee running — the same semantics as `wait: false`.
## What is deliberately not here
- **Declared outputs.** `wait: true` receives the callee's terminal detail,
not structured outputs; the outputs model is its own bead.
- **The StepExecution tree.** The `call` kind is designed for in
`execution-tree-state-machine.md`; this design lands the behaviour without
the per-step records.
- **Per-org enablement** — bead `archie-core-t2db.42`'s catalogue is the
source once it exists.
-84
View File
@@ -1,84 +0,0 @@
# Workflow step vocabulary: what a step type is and how binaries agree on it
**Status:** Draft
**Date:** 2026-09-29
**Beads:** `archie-core-m7oc` (agreement between separately deployed binaries), `archie-core-ze7y` (the deleted `.archie/stages/*.go` equivalent)
**Extends:** `docs/architecture/plugins-and-extensions.md` (plugin engine rule), `docs/prds/event-automation.md` (the workflow model step types serve)
**Authority:** `docs/architecture/plugins-and-extensions.md` — the workflow step vocabulary is a Workflow capability family, and its extension point follows the plugin engine rule.
## Decision
A workflow step type is a named Go factory: the word a YAML workflow writes in
a step's `type` field, plus the factory that builds its stage. The name is a
stable identifier; the identity also declares what plugin family claims it,
so a contribution that shadows a shipped stage is refused instead of
overriding it.
The Workflow domain owns the typed family contract — `StepTypeProvider` for a
contribution and `Manager` as the owning registry. A provider contributes a
whole set of step types under its own stable-identifier name; the manager
validates the entire contribution before applying any of it (named provider,
well-formed step-type names, non-nil factories, no step type claimed twice,
no claim on a name another provider holds) and applies it atomically. The
generic `plugin.Plugin` contract stays metadata-only.
The vocabulary is a compiled-in, closed set. `internal/infrastructure/workflowsteps`
is the one place a step type is bundled into any binary that resolves one: the
shipped workflow stages, the repository-hook replacements (`gate.diff-rules`)
and the repository-free event steps each arrive as one provider, and adding a
step type means adding a provider to that set. Interpreted plugin sources
cannot contribute step types: the Yaegi plugin host satisfies only the
metadata contract, and no bridge to `StepFactory` exists.
Every binary that resolves a step type builds its manager from that same
provider set at its composition root, before its first resolution, and
injects the manager everywhere it resolves definitions. Agreement is per
build: the State Store, the daemon's workflow-definitions client and the agent
worker built from the same source register identical vocabularies by
construction; binaries built from different sources can disagree, and only a
matching deploy fixes that.
An unknown step type is refused twice, and never degraded. The validator
`ParseDefinition` refuses a definition naming an unregistered type at save
time, on the validating side the composition root built (the State Store's
workflow-definitions resource validates there before anything is stored). The
compiler refuses the same definition at run, so a binary handed a definition
written against a vocabulary it does not have fails that run loudly instead of
silently skipping steps. Both checks live in the Workflow domain against the
injected manager, which is why no binary can opt out of the check by
substituting its own registry.
## Relationship between the questions
`archie-core-ze7y` is the same question seen from the deleted
repository-authored stages: those `.archie/stages/*.go` files held arbitrary
stages, and their gate half landed as `gate.diff-rules` settings rather
than interpreted Go. No interpreted-Go stage type is built, and nothing
approximates one: the maintainer's trust decision (`archie-core-ndm8`) allows a
command step type instead, and it arrives as a provider in the compiled-in set
under the rules above — a new contributor of exactly one step type at a named
provider (`command.run`, contributed by `command`). It is not a plugin
contribution mechanism and it changes no other answer in this document. The
refusal of `.archie/stages/*.go` therefore names `command.run` as its migration
target, and each command it runs is the operator's own repository policy
expressed as argv.
## Rejected alternatives
- **A vocabulary version or hash on the wire.** The executing side already
refuses an unknown step type at its first compile, which is the mismatch
detector, and it fails closed. A wire field would only narrow the
deploy-skew window that a matching deploy closes, at the cost of a new
contract field.
- **A Yaegi-plugin-to-`StepFactory` bridge.** It would run repository-supplied
interpreted code inside the daemon's process with daemon privileges. The
trust boundary invariant requires repository-authored code to run in the
task container, not in an interpreter embeddable into any binary.
- **A package-level process-global registrar.** Global mutable registry state
is unreadable at the composition root, collides with itself when one
process builds the vocabulary twice, and is what made the first attempt at
this question worse instead of better.
- **Degrading on an unknown step type.** A run that skips steps it cannot
compile would finish green while silently dropping the behaviour the
definition asked for; refusal at save and at run is the only honest option.