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

-389
View File
@@ -1,389 +0,0 @@
# Agent System
**Status:** Current-state investigation in progress
**Date:** 2026-07-28
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Domain framing
The domain is the Agent System.
`Task` is not a core Agent System concept. Forge tasks, forge issues, Jira
issues, email, Telegram messages, webhooks, and future external inputs are
channel-specific messages. Channels translate those messages into requests to
the Agent System; external issue or task models MUST NOT shape execution state.
The current `store.Task` is a persisted workflow execution. Treating that row as
a task-domain aggregate would incorrectly turn Archie into an agentic issue
board.
## Canonical agent interaction model
An **Agent** is a persistent assistant selected for an interaction. It is not a
model invocation and is not a WorkflowExecution.
Each Agent has its own:
- immutable acting `IdentityID` for ownership and audit;
- durable memory and learned information about the user;
- perspective, specialisation, instructions, and communication behaviour;
- conversation history and channel bindings;
- available tools, capabilities, and policy;
- continuity across model or provider changes.
The underlying model is a replaceable runtime dependency. Changing a model,
provider, or model version MUST NOT create a new Agent, discard its memory, or
change ownership of its history.
A user MAY create multiple Agents. Each Agent develops its own memory and view
of the user from the interactions and responsibilities assigned to it. Memories
MUST NOT be silently pooled merely because Agents belong to the same user or
application.
Agent and Identity are separate aggregates. Every Agent references exactly one
acting IdentityID, and no two Agents share an agent identity. User, system, and
service-account identities may exist without an Agent.
An action initiated through an Agent records the Agent's acting IdentityID and,
when applicable, the initiating user's IdentityID. A future fully automated
WorkflowExecution MAY use an explicitly selected service-account identity for a
concrete unattended use case; this is not the default execution identity.
## Workflow execution identity
A Workflow is owned by an IdentityID. By default, every WorkflowExecution acts
as the Workflow owner's identity.
Future delegated execution MAY add an explicit `RunAsIdentityID` assignment to a
Workflow. This allows a Workflow owner to select another user or service-account
identity for execution without changing Workflow ownership. Until that
capability is deliberately introduced, owner identity and execution identity are
the same.
WorkflowExecution audit records MUST preserve the Workflow owner, effective
execution identity, initiating user when one exists, and any explicit delegation
that selected a different run-as identity.
## Memory scopes
The Agent System requires four distinct durable memory scopes:
- **global shared memory**: information intentionally available across the
Archie application;
- **agent-wide memory**: general expertise, operating knowledge, and perspective
owned by one Agent and safe for that Agent to use across users;
- **user-wide memory**: information associated with one user and available to
authorised Agents serving that user;
- **Agent-user relationship memory**: private history and learned context from
one particular Agent's relationship with one particular user.
Agent-wide memory is private to its owning Agent by default. Another Agent MUST
NOT read, inherit, search, or mutate it implicitly.
Agent-user relationship memory is addressed by both AgentID and User IdentityID.
Neither another Agent serving the same user nor another user speaking to the
same Agent may access it implicitly.
Archie is a multi-user system even when initially deployed for one person.
Multiple users, including family members, may interact with the same configured
Agents. Per-user memory is therefore an isolation and personalisation boundary,
not merely an attribution tag on the primary user's records.
An Agent MUST resolve the initiating user before assembling memory context.
Memory belonging to one user MUST NOT become visible to another user merely
because both users interact with the same Agent.
Shared memory does not erase provenance. Every memory record retains its scope,
author or acting identity, originating user when applicable, source, and
revision history. The rules for selecting a write scope, granting access
to global and user-wide memory, and authorising explicit cross-scope sharing are
settled by [`docs/prds/memory-engine-unification.md`](../prds/memory-engine-unification.md)
and recorded in [`migration-decisions.md`](migration-decisions.md#5-memory-placement-and-storage)
section 5.
An Agent interaction may answer conversationally, use a tool or capability, read
or send messages, retain information, or propose durable workflow-backed work.
None of these operations inherently requires a WorkflowExecution.
## Agent and Workflow domain boundary
Agent and Workflow are separate domains:
```text
internal/domain/agent
internal/domain/workflow
```
The Agent domain owns persistent assistants, their specialisation, instructions,
model-independent continuity, capability context, and associations with identity
and memory.
The Workflow domain owns reusable, user- or Agent-defined behaviour and every
durable execution of that behaviour. An Agent may invoke or define a Workflow,
but the Workflow is not part of the Agent aggregate and does not require a
conversational Agent interaction to execute.
## Canonical workflow model
The Workflow feature uses these canonical terms:
- **Workflow**: a reusable, versioned definition of how an agent behaves and
performs a kind of work.
- **WorkflowExecution**: one durable execution of a specific Workflow version.
- **WorkflowStep**: one defined operation in a Workflow.
- **StepExecution**: the recorded execution and outcome of one WorkflowStep.
- **Attempt**: a retry of the same WorkflowExecution, not a new execution.
A Workflow MAY structure any repeatable agent behaviour, including personal
assistance and scheduled routines. For example, a morning email review may
combine a schedule event, message retrieval tool, LLM classification and
summarisation, and delivery of the resulting rundown. Workflow is therefore not
restricted to forge work, source changes, or requests submitted by a user at
execution time.
Workflows are extensible through Workflow-owned plugins. The Workflow domain
defines the typed plugin registration, definition, validation, versioning, and
execution contracts. Users and Agents may define reusable Workflows through
those contracts.
The generic plugin contract remains metadata-only. It MUST NOT own Workflow
semantics or replace the Workflow registry with generic hooks.
`Workflow` and `WorkflowExecution` are the names used in architecture, generated
reference, configuration, commands, events, and external contracts. The
implementation MAY use package qualification to remain concise:
```go
workflow.Definition
workflow.Execution
workflow.Step
workflow.StepExecution
```
The unqualified name `Execution` MUST NOT be used in cross-domain contracts or
documentation because it is ambiguous among workflow, tool, command, policy, and
service execution.
## Current workflow-execution feature
The current feature takes a channel request through agent execution and a
durable outcome.
Current execution state includes source-message references, owning identity,
repository, selected workflow and stage, agent output, branch and pull-request
references, token and iteration counts, retry information, human-wait
information, and failure details.
The current `store.Task` lifecycle uses:
```text
queued -> running
running -> queued (crash recovery) | waiting_human | pr_open | completed | parked | closed_wont_do
waiting_human -> queued | closed_wont_do
parked -> queued | dead
pr_open -> merged | rejected
```
`merged` is reached only from `pr_open`. `completed` is terminal: it means a
workflow that opens no pull request finished its work.
Workflows select and sequence deterministic and agent-run stages. Implement,
TDD, feasibility, and bootstrap are current Workflow definitions.
Every WorkflowExecution is handed wholesale over core NATS to a task-scoped
`archie-agent` container, which owns the workflow stage loop.
## Current workflow-feature placement
The behaviour is divided across technical packages:
- `internal/domain/workflow` defines the current `Task` execution record and
status strings; `internal/infrastructure/postgres` persists mutable state
and transition history behind `internal/domain/storecontract`.
- `internal/daemon` discovers, claims, schedules, retries, recovers, processes,
waits for human input, and reconciles pull requests.
- `internal/domain/workflow` routes work, executes stages, mutates tasks, applies
outcomes, parks failures, and performs forge/worktree operations.
- `internal/agentexec` defines and runs individual autonomous-stage protocols.
- `internal/taskrun` hands a complete WorkflowExecution to a container worker.
- `internal/gate` and repository configuration define execution constraints.
- `internal/gateway` duplicates task status strings and applies task-control
rules.
- forge, worktree, NATS, PostgreSQL, containers, and agent runtimes are concrete
dependencies mixed into orchestration.
## Current `task` meanings and required replacements
The existing code uses `task` for unrelated concepts. Migration MUST resolve
each meaning deliberately; a global text replacement is prohibited.
| Current meaning | Representative locations | Target concept | Requirements |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Forge issue or external task | `internal/forge`, daemon polling | Channel message | Preserve the channel's native reference and payload. Translate it into an Agent System request without importing forge or issue semantics into Workflow. |
| Jira issue or other external work item | Messaging infrastructure adapter | Channel message or external artifact | The external system retains its own vocabulary inside its integration. Its record may lead to an accepted work request but is not a Workflow or WorkflowExecution. |
| Persisted `workflow.Task` row | `internal/infrastructure/postgres` | WorkflowExecution | Own identity, Workflow ID and version, lifecycle, source-message reference, outputs, attempts, and outcome. Persistence implements the Agent System repository contract. |
| Task status and transition history | `store.Status*`, `transitions` | WorkflowExecution lifecycle and domain events | Enforce legal transitions atomically. Domain events and state changes cannot diverge. Remove duplicated status strings from consumers. |
| Claimed or queued task | `ClaimNext`, `ClaimByIssue`, `RecoverStale` | Scheduled WorkflowExecution | Claim by WorkflowExecution ID and expected version/state. Crash recovery and leases must not silently create a new execution. |
| `workflow.TaskContext` | `internal/domain/workflow` | WorkflowExecution context | Replace the mutable service bag with execution state plus narrow step-required contracts. Complete application configuration and unrelated services are forbidden. |
| `taskrun.Request` and `taskrun.Response` | `internal/taskrun`; consumed by `internal/app/agentworker`, decoded by `internal/infrastructure/agenttransport/nats` | WorkflowExecution handoff | This is the versioned worker contract for executing a WorkflowExecution. It carries domain-owned execution data, not store rows or global configuration DTOs. |
| Per-stage `agentexec.Request.TaskID` | `internal/agentexec` | WorkflowExecutionID correlation | An agent invocation is a bounded WorkflowStep execution. Correlate request/result with WorkflowExecutionID, StepExecutionID, attempt, and protocol version. |
| NATS `TaskMessage` and `archie.task.*` | `internal/domain/workintake` (subjects, `TaskEnvelope`); `internal/infrastructure/agenttransport/nats` (transport) -- `internal/nats` no longer exists; whether this row's "current meaning" itself is now superseded by `TaskEnvelope` needs a closer look, not asserted here | Channel request or WorkflowExecution transport | Discovery messages and execution dispatch are different contracts and subjects. Domain meaning stays outside NATS infrastructure. Identity and source-message idempotency must be explicit. |
| `taskDispatcher` work item | `internal/daemon` | WorkflowExecution scheduling | Scheduling operates on execution references and declared concurrency policy. Repository serialisation is policy, not identity derived from an incomplete task struct. |
| `container.TaskPayload` and `task.json` | `internal/container`; read by `internal/infrastructure/agentboot` | WorkflowExecution brief | Rename the boot artifact and schema. It identifies the mounted execution and required workspace only; it is not an alternative execution definition. Missing or malformed input must fail startup before the worker subscribes. |
| `storage.TaskRef` | `internal/storage` | WorkflowExecution workspace lease | Storage receives the minimal execution/workspace reference and policy required to provision and release resources. It does not receive the WorkflowExecution aggregate. |
| Gateway `TaskCreator` | `internal/gateway` | Accepted work request handoff | A channel may carry a request for durable workflow-backed work, but it does not request or create a WorkflowExecution directly. Work intake admits and routes the request; the Agent System consumes the accepted work request and is the sole owner of selecting a Workflow version and creating the WorkflowExecution. Ordinary agent interactions do not require this handoff. |
| Gateway `TaskController` and `ChatTaskStatus` | `internal/gateway/tasks.go` | WorkflowExecution commands and query view | Approve, cancel, and status use Agent System contracts. Channel code does not duplicate lifecycle constants or decide transitions. |
| Gateway `TaskProfile` | `internal/gateway/tasks.go`, `cmd/archied` | Channel/identity execution defaults | This is configuration selecting allowed source targets and default Workflow inputs, not task state. Split it into settings owned by the relevant channel and Agent System features. |
| `config.TaskConfig` and `TaskForge` | `internal/config` | Worker execution settings and channel/service references | Dissolve with `internal/config`. Each field moves to its owning runtime settings or versioned WorkflowExecution handoff contract. Secrets and external configuration forms do not enter the domain. |
| `events.Event.TaskID`, task event timelines | `internal/events`, stores, web UI | WorkflowExecutionID and WorkflowExecution events | Authoritative events are Agent System events. Observability and timelines project those events rather than inventing parallel generic task events. |
| Web UI task lists and counts | `internal/webui`, store query APIs | WorkflowExecution read model | Dashboard status, history, and counts are projections of WorkflowExecution state and events. The UI does not depend on persistence records. |
| Task-scoped forge/store/worktree RPC | `forgerpc`, `storerpc`, `worktreerpc`, `registerTaskRPCServers` | Execution-scoped capability ports | Worker calls use narrow domain-required service contracts, carry WorkflowExecutionID and IdentityID, and resolve the owning capability binding. Root-client fallback is forbidden. |
| Per-task worktree, branch, volume, and cleanup | daemon, worktree, storage, container | WorkflowExecution workspace | Every WorkflowExecution receives isolated workspace state. Workspace lifecycle is explicit, identity-aware, recoverable, and controlled outside the model. |
| Task retry, dead, waiting-human, PR reconciliation | daemon, workflow, gateway | WorkflowExecution lifecycle policies | Retry, waiting, cancellation, reconciliation, and terminal outcomes are Agent System behaviour. Channels and infrastructure report facts or submit commands; they do not mutate state. |
| Task-run readiness and retry timeouts | daemon taskrun request loop | Worker-dispatch settings and policy | These settings govern WorkflowExecution handoff availability. They are not Workflow data and must be owned by the worker-dispatch capability. |
### Terms that do not migrate
- The `task` command in `Taskfile.yml` is the external Task build tool and keeps
its name.
- A forge may call its own records issues or tasks inside its channel adapter.
- General prose may use “task” informally only when it clearly refers to an
external system. Agent System contracts and generated reference MUST use the
canonical Workflow vocabulary.
## Current WorkflowExecution data inventory
This inventory is the migration ledger for data currently spread across
`store.Task`, database-only columns, `workflow.TaskContext`, worker messages,
and surrounding configuration. Implementation SHOULD NOT require another
repository-wide search to determine what existing execution data must be
preserved or deliberately removed.
| Current data | Current representation | Required target |
| ---------------------- | ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Execution identity | `Task.ID`, `task_id`, NATS subjects, logs | Immutable WorkflowExecutionID used consistently by state, events, workers, projections, and capability calls |
| Owning actor | `Task.Identity` string | Canonical IdentityID |
| Source type | `Task.Source` (`forge` or `chat`) | Typed channel and SourceMessageReference; no closed source enum in WorkflowExecution |
| Source address | `Owner`, `Repo`, `IssueNumber`; synthetic chat issue number | Channel-owned source reference with native message/thread/object identifiers; synthetic identifiers removed |
| Requested work | `Title`, `Body`, `Labels` | Immutable execution input captured from the source request; channel-specific metadata retained in the source envelope |
| Workflow selection | `Workflow` string | Immutable WorkflowID plus selected WorkflowVersion |
| Lifecycle | `Status` string | Enforced WorkflowExecution state |
| Current position | mutable `Stage` string | Derived current WorkflowStep reference plus durable StepExecution history |
| Attempts | `Attempt`, `RetryCount` | Execution attempt history and retry-policy evidence; distinguish worker delivery retry from workflow retry |
| Failure | `ParkReason`, transition detail, response errors | Typed failure classification, evidence, retryability, and resulting lifecycle event |
| Human wait | `WatchCommentID`, `waiting_human` | Channel-neutral wait condition and correlation reference; forge comment IDs stay in the forge channel |
| Workspace | `Dir`, `Branch`, worktree path, `task.json` | Execution workspace reference and independently managed workspace lifecycle |
| Change outcome | `BuildSummary`, `BuildNoChanges`, changed files | Step outputs and final WorkflowExecution outcome |
| Reproduction evidence | `ReproProof` | Typed TDD step evidence retained with the StepExecution and final outcome |
| Planning output | `Plan` | Typed step output referenced by later steps rather than a special aggregate field |
| Notes | `Notes`, appended agent notes | Ordered execution annotations with actor, source step, and timestamp |
| Pull request | `PRNumber`, forge host/repository assumptions | Forge-channel delivery reference and reconciliation state |
| Agent usage | `TokensUsed`, `Iterations` | StepExecution usage measurements aggregated into execution projections |
| Decision capture | private feasibility `decision`, capture-tool output | Typed WorkflowStep output defined by that Workflow version |
| Terminal outcome | mutable `Outcome{Status, Detail}` | Explicit WorkflowExecution outcome command/event validated by the state machine |
| Skill context | `SkillBody`, `SkillPlugins` | Resolved Workflow version dependencies or execution inputs, with provenance |
| Agent prompt context | `SystemPrompt`, `ExtraRules`, mission strings | Versioned WorkflowStep definition plus resolved execution context; mutable global prompt callbacks removed |
| Gates and protection | `Gate`, `Preflight`, `Protection`, repository config | Agent System policy definitions resolved for the WorkflowExecution and enforced outside the agent |
| Budgets | steps, tokens, wall clock, gate failures | Execution and StepExecution policy values with measured usage and evidence |
| Tool access | capture tools, registry, guardrails, skill plugins | Resolved step capability set and policy; global registry pointers do not enter execution state |
| Persistence timestamps | SQL `created_at` and `updated_at` | Domain timestamps and version used for optimistic concurrency and audit |
| Transition history | SQL `transitions` and generic events | Authoritative WorkflowExecution domain events stored atomically with state |
## Current runtime responsibilities to unify
The following behaviours currently act on the same WorkflowExecution but are
implemented in different packages:
- accept a request from a channel and enforce idempotency;
- select and version a Workflow;
- create, queue, claim, schedule, and execute a WorkflowExecution;
- serialise same-repository execution where policy requires it;
- resolve identity-specific capabilities;
- prepare, retain, recover, and clean up the workspace;
- run deterministic and agent-backed WorkflowSteps;
- enforce gates, budgets, protected paths, tool constraints, and result review;
- persist state and StepExecution outputs;
- publish authoritative lifecycle events;
- wait for channel input and resume;
- classify failure, retry, park, mark exhausted, cancel, or recover after crash;
- deliver and reconcile forge changes;
- project status, history, counts, and audit for channels and the web UI;
- hand execution to a worker without moving domain ownership to the worker.
## Current workflow-feature hazards
- State update and transition-history insertion are separate operations, so
state and audit can diverge.
- Callers frequently discard persistence and transition errors.
- Gateway task control duplicates lifecycle status constants by hand.
- `workflow.TaskContext` is a mutable service bag containing complete
configuration plus forge, store, worktree, agent, event bus, logging, memory,
guardrails, skills, and scratch state.
- Lifecycle changes occur in both daemon and workflow code.
- Workflow orchestration runs inside task-scoped agent containers while the
daemon retains lifecycle, admission, and authority-bearing RPC ownership.
- Forge-backed and chat-created work share one record through source flags and
synthetic issue numbers.
- Repository labels currently select workflows and mirror task state, coupling
domain transitions to forge presentation.
- Failure generally becomes `parked`, and the failure's classification is no
longer implicit: the persisted execution record carries the class the code
that parks recorded (the vocabulary lives in `internal/taskstate`), and
retryability is read from it rather than inferred from reason text.
- Generic observability events are emitted alongside state changes rather than
being the authoritative domain events.
## Existing invariants to preserve
- The model never performs git operations directly.
- Deterministic policy and gates cannot be waived by the agent.
- TDD captures a failing reproduction before implementation and protects the
test during the fix.
- Every run ends in an explicit outcome; definition errors and stage errors do
not disappear silently.
- Crash recovery requeues interrupted work.
- Agent execution crosses a versioned data boundary.
- Forge, persistence, workspace, transport, container, and model runtimes remain
replaceable infrastructure.
- Work from the same repository is serialised by default.
## Required migration
- Rename the current persisted `store.Task` concept to WorkflowExecution.
- Replace task lifecycle terminology in core commands, events, persistence,
worker contracts, logs, and generated reference.
- Preserve external source terminology only inside its channel adapter.
- Replace synthetic issue numbers with explicit source-message references.
- Associate every WorkflowExecution with an immutable Workflow identifier and
version.
- Record StepExecutions explicitly rather than treating one mutable `stage`
field as complete execution history.
- Keep Attempt as retry state within the same WorkflowExecution.
## Curator isolation invariant
Decided 2026-08-05
([#435](https://github.com/samcharles93/archie-core/issues/435) epic,
[#98](https://github.com/samcharles93/archie-core/issues/98) runtime).
Recovered 2026-08-09 from the pre-migration issue tracker.
**Curators are peers, not dependencies.** They must never block, delay, or take
down chat turns, agent runs, or the daemon.
1. Registry-owned goroutines, one per curator, with per-pass `recover()`,
per-pass budgets (max steps, tokens, timeout), and a configurable maximum of
concurrent passes (default 1) so curators cannot saturate the shared LLM
runtime against chat.
2. Wake events ride the in-process `events.Bus`, which is mutex fan-out with
bounded per-subscriber buffers that **drop** on overflow
(`internal/events/events.go`). A slow curator can never backpressure the chat
publisher.
3. Wake is a best-effort nudge. The trigger is a deterministic read of persisted
primary-input state at pass time, so a dropped wake only delays a run to the
next check-in and never corrupts trigger accounting
([#22](https://github.com/samcharles93/archie-core/issues/22)).
4. The curator registry lifecycle is independent of the agent loop. Daemon
shutdown cancels in-flight passes and waits bounded.
Chat turns keep their per-session lanes; agent runs keep their workflow
goroutines and containers. Rule of thumb: **no code path a curator executes may
ever appear on a chat turn's critical path.**
-195
View File
@@ -1,195 +0,0 @@
# Playbook bindings: model and threat model
**Status:** Approved foundation (documents shipped code: `archie-core-t2db.1`
through `.5`, `.7`, `.9`-`.15`)
**Date:** 2026-09-03
This document covers the binding model and the intake threat model portion
of `archie-core-t2db.6`. It does not cover the task-lifecycle provenance rule
(`messaging-and-work-intake.md`'s "Intake provenance") or the operator
walkthrough -- that walkthrough remains an open piece of the same ticket.
## What a binding is
A `binding` (`internal/domain/binding.Binding`) ties four things together:
a **matcher** (which captured events it applies to), a **mapping**
(`internal/domain/mapping.Mapping`, how fields are pulled out of a payload),
a **workflow** (which registered workflow runs on a match), and a **state
machine** governing whether it is live.
```go
type Binding struct {
ID, Name // identity
Matcher // { Source string } -- the webhook path segment, e.g. "sentry"
MappingID // which Mapping resolves payload fields; its event type is the binding's
Filter // optional CEL over the mapping's parameters
Workflow // registered workflow name to dispatch to
Version // bumped on every edit
Status // pending_approval | armed
Secret // HMAC-SHA256 shared secret, encrypted at rest, never returned by GET
}
```
Bindings live in the store (PostgreSQL), not `config.toml` -- operators author
them from the dashboard while the daemon runs, without a restart.
### Matching
A binding applies to a capture when the capture arrived on `Matcher.Source`,
was identified as the event type its mapping belongs to, and passes its
`Filter` (`binding.CompileFilter`, checked against the mapping's parameters on
save). Any number of bindings may share a source; each dispatches a capture at
most once, claimed in `binding_dispatches` keyed by (binding, capture) before
its task is enqueued. An event signed with any armed binding's secret on the
source is authenticated.
### Mapping
`mapping.Resolve(fields, payload)` walks a captured JSON payload against a
list of typed `Field`s (name, JSON path, expected type), returning resolved
values plus a `[]Failure` for anything that didn't parse or type-match. A
mapping belongs to an event type, and `mapping.CheckSchema` refuses a field
whose path or type the type's inferred schema lacks. Each capture a mapping
resolves at dispatch is counted once in `mapping_matches`, read back as
`MatchCount` and `LastMatchedAt`.
### Versioning
`Version` increments on every `UpdateBinding` call. This exists so an
editor's later change can never silently rewrite the historical provenance
of a task that already fired -- a dispatched task's binding reference is
pinned to the version that was armed when it fired, not "whatever the
binding currently says."
### State machine
```
create ---> pending_approval ---> armed
^ |
+----------------+
(any edit to an armed binding drops it back to pending_approval)
```
A binding is created `pending_approval`, so the operator who creates one can
approve it immediately. Bindings stored as `draft` by an earlier version are
moved to `pending_approval` when the EDA store opens.
Modelled directly on Telegram's existing `dangerousAction`/`pendingApproval`
flow (`internal/channels/telegram/dangerous.go`, `approval.go`) -- not a new
approval mechanism invented for this feature. **Only `armed` evaluates
against incoming events** (`binding.Matches`, `internal/domain/binding/
binding.go`); a `pending_approval` binding is inert. An edit to
an already-armed binding cannot bypass approval by silent mutation -- it
drops back to `pending_approval` and requires an explicit `Approve` call to
re-arm.
## The threat model
This is a public, unauthenticated-by-default intake surface whose output is
an agent with a repo, a worktree, and tool access. The design brief
(`archie-core-t2db.5`, `docs/prds/webhook-intake-security.md`) named five
non-negotiables; each is verified below against the actual shipped code,
not the design intent.
### 1. Per-source authentication
Reuses `internal/channels/webhook`'s existing HMAC-SHA256 scheme --
capture accepts unsigned events (visible in the dashboard, marked
unauthenticated), but **only authenticated events can ever match a
binding**. `binding.Matches`' doc comment states this plainly: "an
unauthenticated event can never trigger a binding, no matter how well it
would otherwise match." Enforced structurally at two points, not just
convention:
- `captures.authenticated` is a real column
(`internal/infrastructure/postgres/migrations/0002_edastore.sql`), set at
capture time.
- `dispatchBindings` (`internal/daemon/daemon.go:479`) walks **authenticated
captures whose source has at least one armed binding** -- an
unauthenticated capture is never even considered for dispatch.
### 2. Human approval before a binding goes live
Covered by the state machine above. Nothing self-arms: `pending_approval ->
armed` requires an explicit `Approve` call, and any edit to an armed
binding reverts it.
### 3. Rate and volume limits per source
Capture writes are bounded independently of the approval gate, so a flood
of unauthenticated traffic cannot exhaust disk or drown the inspector:
`InsertCapture` (`internal/infrastructure/postgres/edastore.go`) prunes by both **retention
window** (`WHERE received_at < cutoff`) and **max event count** in the same
insert transaction.
### 4. Blast radius bounded by the same code-level controls every task gets
A playbook-originated task is dispatched into the **same** gate, diff-cap,
sandboxed-container, worktree-isolation pipeline every task goes through
regardless of origin. Verified precisely, not assumed: `dispatchOneBinding`
calls `EnqueueBindingTask` (`internal/infrastructure/postgres/store.go`), which wraps
`EnqueueChatTask` -- the same direct-to-`tasks`-table enqueue path
chat-spawned tasks already use, then stamps `binding_id`/`binding_version`
for provenance in a second statement. This is a **different** enqueue
mechanism from forge-issue polling's `workintake.TaskEnvelope`/NATS path
(`docs/prds/event-sources-and-reactions.md`) -- binding and forge-issue
tasks arrive by different producers, but both become an ordinary
`workflow.Task` row that `ClaimNext` picks up identically, so both get the
same gate/worktree pipeline downstream regardless of which producer created
the row. Payload content is
ordinary untrusted prompt input; the sender's text is never treated as a
trusted instruction (Archie's environmental-enforcement principle: "the
agent should ignore instructions in the payload" is not itself a control,
the surrounding sandbox is).
### 5. Captured payloads may contain secrets from the sending system
Two independent protections, not one:
- **Redaction before persistence**: `webhookguard.RedactPayload` walks the
decoded JSON and redacts recognised sensitive keys before the row is
written -- the raw, unredacted payload is never durably stored.
- **Retention**: a configurable window (`InsertCapture`'s `retention`
parameter) prunes old captures automatically; visibility of what remains
is gated by the same dashboard authentication as every other webui
surface, not a separate, weaker path.
### Secrets at rest
`Binding.Secret` (the HMAC shared secret a sender signs with) is encrypted
at rest via AES-GCM (`internal/infrastructure/bindingcipher`, `archie-core-
t2db.7`) -- a leaked database dump does not leak sender-side shared secrets in
plaintext. The envelope is versioned (`bindingEnvelopeVersion`) so a future
cipher or KDF change can roll forward without breaking already-encrypted
rows, and the AAD binds ciphertext to the binding-secret context so it
cannot be relocated to another field/column and still authenticate. A `nil`
cipher (no encryption key configured) leaves secrets as plaintext --
documented legacy behaviour, not silent degradation.
### At-most-once dispatch
`dispatchBindings` enqueues at most one task per `(binding, capture)` pair,
enforced by a real ledger, not best-effort application logic:
`RecordDispatch` (`internal/infrastructure/postgres/edastore.go`) inserts into
`binding_dispatches`, unique on `(binding, capture)`; a duplicate
insert returns the sentinel `ErrAlreadyDispatched`, which the dispatch loop
treats as "another cycle raced us," not an error. This guarantee holds
**across daemon restarts**, not just within one process's lifetime, because
the ledger is a durable table, not in-memory state.
This ledger is also the direct precedent for the EDA playbook engine's
execution-time idempotency, now landed (`archie-core-t2db.17` closed): the
`playbook_dispatches` table (`RecordPlaybookDispatch`) copies
`binding_dispatches`'s unique-ledger conventions with a
`(playbook_id, playbook_version, event_id, action_id)` key
(`docs/prds/eda-playbook-engine.md` gap 2).
## What this document does not cover
- An end-to-end operator walkthrough (point an external app at archie,
build a first playbook) -- open, part of `archie-core-t2db.6`.
- The playbook YAML / CEL / Module/Channel/Forge action-position work
(`docs/prds/eda-playbook-engine.md`, `module-position.md`,
`channel-forge-positions.md`) -- a different, newer mechanism than the
binding model described here; the two are related but not the same
system, and this document does not attempt to unify them.
-435
View File
@@ -1,435 +0,0 @@
# Configuration
**Status:** Approved; existing-type assignment is ongoing
**Date:** 2026-07-28
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Ownership
Configuration has two separate responsibilities:
1. `internal/infrastructure/configuration` loads files, environment variables,
secret references, overlays, and compatibility representations.
2. Each domain and plugin owns the typed runtime settings required for its
behaviour.
`internal/app` translates external input into those settings, validates
cross-capability combinations, and supplies each component only its own
settings.
The following are prohibited:
- passing complete application configuration into a domain;
- making a domain depend on TOML, YAML, environment-variable names, secret
references, or a configuration library;
- defining a central runtime configuration type imported across the system;
- placing plugin options in an unrelated global configuration model.
## Private input document
`internal/infrastructure/configuration` MAY use a complete decoded document
while discovering files, decoding sections, and applying overlays. It is an
input-boundary DTO only.
The document:
- remains private to the configuration infrastructure;
- is composed from separately defined feature sections;
- is immediately translated by application composition;
- is never returned as the application's runtime model;
- is never passed through runtime components.
External DTOs and domain runtime settings are separate types.
Plugins supply external configuration definitions through a narrow extension
contract. The core loader MUST NOT gain a field or recognised filename for every
plugin.
Invalid configuration input MUST NOT replace active valid settings or terminate
unaffected capabilities. Configuration changes use the candidate validation,
promotion, audit, and recovery requirements in
[safe-change-and-recovery.md](safe-change-and-recovery.md).
## Dissolution of `internal/config`
`internal/config` has no target location. It MUST be dissolved and MUST NOT
survive as a shared package, configuration domain, or renamed global model.
Its loading behaviour moves to `internal/infrastructure/configuration`. Existing
types and methods are reassigned by behaviour. Repository execution policy,
dispatch policy, retry policy, ecosystem defaults, tool policy, memory settings,
provider settings, and channel settings move to their
respective owners.
## Repository settings
The existing `config.Repo` MUST NOT move intact into a repository domain or
shared settings package. A managed repository is an application association:
- work intake owns which repository references an identity monitors;
- task execution owns gates, preflight, test protection, ecosystem behaviour,
and change limits;
- task lifecycle owns retry behaviour;
- scheduling owns concurrency policy;
- workspace management owns base branch and persistent-storage requirements.
Application composition correlates these settings by repository reference. No
domain receives a universal repository profile.
## Documentation
Generated configuration reference describes external sections and their owning
capabilities. It MUST NOT establish a global Go configuration structure as the
public contract.
## Value classification rule
Every value that controls behaviour MUST have an explicit owner and MUST be
classified as exactly one of:
1. **Invariant** — changing it changes the meaning of the program, a wire
protocol, or a domain concept. It may be a Go constant.
2. **Runtime setting** — an operator, identity, domain, plugin, or deployment
may legitimately choose a different value. It is typed configuration owned by
the affected capability.
3. **Policy value** — it expresses what is allowed, limited, routed, retried,
protected, or gated. Its typed definition belongs to the owning domain and it
is evaluated through the policy system.
4. **Derived value** — it is computed from other settings and is not
independently mutable.
5. **Runtime state** — it changes as the application operates, such as the
active model for a conversation. It is changed by a domain command and is not
configuration merely because it can be changed.
An unclassified behavioural literal is a defect.
`const` MUST NOT be used merely because a value currently has one default.
Constants are reserved for actual invariants: enum discriminants, protocol
versions, fixed compatibility tokens, and values whose alteration would change
the program's semantics rather than configure an installation.
In Go, a constant is a compile-time value and does not represent mutable runtime
storage. It generally has no address that can be observed or changed.
Architecturally, a constant therefore asserts that the value cannot change for
the lifetime of the application. Any value that may legitimately change while
the application is running, between application instances, or between
deployments is not a constant.
A runtime setting may have a default, but the default is not its only access
path. The owner exposes a typed settings structure, validation, and a
`DefaultSettings` constructor or equivalent. Private constants used to implement
defaults do not turn those defaults into invariants and MUST NOT be consumed
directly by runtime code.
Each runtime setting and policy value MUST declare:
- its owner;
- type, units, validation constraints, and safe bounds;
- default and derivation, if any;
- whether it is startup-only, live-reloadable, or restart-required;
- whether it may differ by installation, identity, repository, workflow,
channel, or plugin instance;
- whether it is secret, sensitive, or safe to report;
- its current source, effective value, version, and last-known-good version;
- the command and identity required to change it.
## Current configuration migration ledger
This ledger records the current meanings hidden inside `internal/config`. It is
the source inventory for dissolving that package; rows are split where the
existing structure combines different owners.
| Current values | Current location | Target owner and requirement |
| ----------------------------------------------------------------------------------------- | --------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `WorkDir`, `StateDir` | root `Config` | Workspace/storage infrastructure settings, bootstrap-only. `StateDir` holds the embedded NATS store and endpoint file, task logs and the readiness disk target. Defaults derive from the platform data directory. |
| `SkillsDir`, `PluginDir` | root `Config` | Skill and plugin infrastructure settings, independently typed. |
| `PollInterval` | root `Config` | Work-intake scheduling setting; not a daemon-wide constant. |
| `Label`, `BotUser`, `BotEmail` | root `Config` | Identity and dispatch associations. `BotEmail` may be derived from the selected forge account but remains overrideable. |
| `MaxRetries` | root `Config`, `Repo` | Retry policy owned by the operation being retried. The duplicate global/repository representation must disappear. |
| `DiffCapLines` | root `Config` | Agent-change policy value. |
| `MaxSteps`, `WallClock`, `GateMaxFailures` | `Budgets` | Workflow-execution policy, with units and zero/unlimited semantics made explicit. |
| `Class`, `APIKeyEnv`, `BaseURL` | `Provider` | Provider instance settings. Secret lookup becomes a `SecretRef`, not an environment variable name leaking into the provider domain. |
| `Mode`, `Command`, `Env` | `LegacyAgent` | Decode-only compatibility input for the removed executor selector. Delete after the config migration window; it has no runtime settings owner. |
| `Type`, `Host`, `Token` / `TokenEnv` (older form) | `Forge` | Forge adapter settings. The older `TokenEnv` input is accepted only at the loader boundary. |
| `Trigger`, `AckReaction`, label names | `Dispatch` | Work-intake and forge presentation policy. Label vocabulary is configurable per forge/identity association. |
| `Engine` | `MemoryConfig` | Memory engine selection. `internal/domain/memory` is the only engine family; per-engine settings remain owned and validated by that engine. |
| `Name`, `Transport`, `Command`, `Args`, `WorkDir`, `URL` | `MCPServer` | One typed MCP server instance specification. Transport-specific variants must reject fields belonging to other variants. |
| `MaxResultChars` | `ToolPolicy` | Tool-execution policy values, not generic daemon configuration. |
| `URL`, `TokenEnv` | `NATSConfig` | NATS transport settings with a secret reference replacing the environment-name field. |
| `Image`, `MaxConcurrency`, `MaxUptime`, `VolumeTTL`, `PullPolicy`, `Network` | `ContainerConfig` | Mandatory managed-worker infrastructure settings and resource policy. The legacy `enabled` input is decode-only. |
| model mappings, email, webhook, Telegram | `ChatConfig` | Separate channel instance settings plus channel-routing associations; there is no chat-wide settings owner. |
| `AllowedUserIDs`, `Token` / `TokenEnv` (older form), update commands | Telegram config | Telegram adapter settings and access policy. `Token` is the preferred `secret.SecretRef`; `TokenEnv` remains a backwards-compatible fallback. |
| listen/relay addresses | email config | Email adapter instance settings. |
| webhook target | `Notify` | Notification adapter instance settings. |
| web listen address | `Web` | Web transport settings. |
| `listen` under `[services.state]` and `[services.gateway]` | `ServiceConnection` | The bind address of the process that owns the service. Read only by that process, and defaulted to the address its clients dial so the pair cannot drift. |
| forge, dispatch, models, providers, containers, memory, tools and repositories | `IdentityConfig` | Existing composite duplicates unrelated settings. Replace it with associations from an `IdentityID` to independently owned configured instances. |
| owner, name, base, gate, protection, ecosystem, preflight, storage, retry and concurrency | `Repo` | Split across work intake, workspace, workflow execution, policy, gate, and scheduling as described in Repository settings. |
| `TaskConfig`, `TaskForge` | worker snapshot | Replace with the minimum immutable, versioned WorkflowExecution input assembled by the application. It is not a second configuration model. |
| `Extra` and arbitrary maps | root/provider config | Allowed only at an extension boundary whose owning plugin/provider supplies schema and validation. Core configuration never consumes an untyped catch-all. |
## Behavioural literals and incorrectly fixed values
The following current values affect useful behaviour but are not represented as
owned typed settings or policy. They MUST be classified and migrated before the
old configuration package is removed. The listed target is the architectural
decision; exact setting names are implementation details.
| Capability | Values fixed in current code | Required classification |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Chat agent | maximum steps `8` in `cmd/archied` | Workflow/chat execution policy. |
| Context compression | enabled, threshold `0.5`, context size `128000`, protect first `3` and last `20`, compression marker, token estimate of four characters per token | Model/context runtime settings. The marker is presentation; the estimate is provider/model strategy, not a universal truth. |
| Tool guardrails | escalation thresholds `3`, `5`, `10`, `2` | Tool-use policy with named meanings and bounded defaults. |
| Tool output | per-result cap `50000` characters, no aggregate turn cap, preview `500` characters | Tool-execution resource and presentation settings. Per-result spill/truncation remains; turn continuation is not character- or token-gated. |
| Pairing/access | code TTL `1h`, maximum pending `3`, rate window `10m`, failures `5`, lockout `1h`, maximum lockout `24h` | Access policy. Code length/alphabet and salt length require an explicit security-constraint decision; they are not automatically valid constants. |
| NATS daemon consumer | stream `ARCHIE_TASKS`, consumer `archie-daemon`, deduplication `2m`, poll `2s`, deliveries `3`, acknowledgement wait `5m`, inactive threshold `24h`, subjects | NATS topology settings plus delivery policy. Subject grammar or protocol headers may be invariants only if declared as versioned wire contracts. |
| NATS worker consumer | stream `ARCHIE_TASKS`, consumer `archie-agent`, deduplication `2m`, poll `5s`, acknowledgement wait `30m`, deliveries `3`, inactive threshold `24h`, queue group and retry delay `1s` | Worker transport settings and delivery/retry policy. Shared stream defaults must have one owner rather than two copies. |
| Worker readiness | readiness timeout `20s`, retry delay `250ms` | Worker lifecycle and retry policy. |
| Execution/RPC | agent execution `30m`, task-run RPC `60s`, worktree RPC `15m` | Per-operation timeout policy. |
| Plugin/tool cleanup | plugin rollback `10s`, tool-provider cleanup `10s`, MCP-provider cleanup `10s` | Lifecycle shutdown/rollback policy owned by each engine, with a shared policy vocabulary where appropriate. |
| Memory read path | per-scope record limit `20`, rendered `<memory>` block byte cap `8192` | Memory read policy owned by the engine family (`internal/domain/memory`). |
| Built-in memory store | per-file size limit `100KiB`, query result limit `100` | Split into memory resource policy, input policy, and presentation settings. |
| Memory safety scanner | compiled prompt-injection and sensitive-data patterns with fixed warn/block consequences | Versioned memory-domain policy definitions. Patterns and consequences must be inspectable and replaceable without editing scanner code. |
| MCP stdio | initial backoff `500ms`, maximum backoff `30s`, unlimited default retries, send and shutdown `5s` | MCP transport retry, request, and lifecycle policy. Unlimited retries must be explicit rather than a zero-value accident. |
| MCP SSE/HTTP | reconnect `1s` to `30s`, POST/request timeout `30s` | MCP transport settings and retry policy. |
| Message framing | MCP frame `4MiB`, worker protocol frame `8MiB`, diagnostic `64KiB`, media/base64 `64MiB` | Resource/security policy unless a published wire protocol mandates the limit. Limits must be configurable only within safe bounds. |
| Webhooks and web UI | webhook bind `0.0.0.0:8644`, webhook shutdown `5s`, web read-header `5s`, web shutdown `2s` | Transport instance and lifecycle settings. |
| Telegram | typing refresh `4s`, draft interval `700ms`, update-action TTL `10m` | Telegram adapter presentation and lifecycle settings. |
| Telegram limits | message length `4000` and callback/update prefixes | Record the upstream platform constraint and version it as an adapter compatibility limit; prefixes may remain wire constants when changing them would invalidate outstanding callbacks. |
| Containers | stop and pull timeouts `10s` and `30s` | Container lifecycle policy. |
| HTTP clients | feasibility notification timeout `10s`; other paths use `http.DefaultClient` | Adapter request policy. Every outbound client requires an explicit timeout profile. |
| Workflow routing | labels `bug`, `feature`, `bootstrap`; workflows `tdd`, `feasibility`, `bootstrap`; fallback `implement` | Agent-system routing policy. Workflow identifiers are references, not compiled routing decisions. |
| Filesystem/deployment | `.agents/skills`, `.archie/stages`, `.archie/gate.go`, `/data/worktree`, `/data/repo`, cache names/paths and prepared sentinel | Split into deployment settings, repository conventions, and genuine internal protocol markers. Paths an installation may relocate are settings. |
| Packaged release data | `/usr/share/archie/CHANGELOG.md` | Packaging/deployment settings or paths derived from an installation prefix. |
| Forge presentation | default label colour `bfd4f2` and state-label colours | Forge adapter presentation settings. |
| Fallback system prompt | compiled fallback prompt | Agent-system default content, versioned and replaceable through its owning settings; safety constraints remain policy/code. |
| Default paths and identities | config path, data paths, listen addresses, model roles and workflow names | Typed defaults belonging to their respective owners, never global constants consumed throughout the application. |
This inventory is intentionally broader than exported Go `const` declarations. A
literal hidden in a constructor, timeout, switch, retry loop, path join, prompt,
label map, or client setup restricts behaviour just as effectively as an
incorrectly used constant.
## Constants that may remain
A value may remain constant only when its owner documents why runtime variation
would be invalid. Typical valid cases are:
- domain enum values and state names;
- a versioned wire-protocol version or framing token;
- reserved internal headers and callback prefixes that peers must interpret
identically;
- compile-time mathematical relationships;
- sentinel errors and internal type identifiers.
Names such as a stream, consumer, label, workflow, file, directory, network,
model role, timeout, retry count, capacity, size limit, colour, prompt, command,
or executable are not invariants merely because the current application has only
one of them.
Architecture tests SHOULD reject exported behavioural constants outside approved
invariant packages and SHOULD detect direct consumption of private default
constants outside their owning `DefaultSettings` construction.
## Current mutation and reload ledger
The application currently changes behavioural values through unrelated paths:
| Current change seam | Current behaviour | Required target |
| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Telegram `/restart` in `cmd/archied` | Re-reads the global document and directly replaces Telegram token and allowed-user IDs; failure retains old values. | Submit a Telegram-settings candidate through the universal change protocol. Validate the complete candidate, promote atomically, audit the acting identity, and retain last-known-good. |
| Active model selection | `chatModelManager.SetActiveModel` changes a model reference. | A conversation/session command changing runtime state. Validate against configured model instances and audit it; do not rewrite configuration. |
| Active provider selection | `chatModelManager.SetActiveProvider` changes provider selection. | A conversation/session command changing runtime state, with the same distinction from provider-instance configuration. |
| Persona selection | `PersonaRegistry.SetActive` mutates an in-memory per-session choice. | Agent-system session state. Persistence and audit requirements are owned by that domain, not the configuration loader. |
| File and environment overlays | Applied while loading `internal/config`; defaults are filled by mutation in `finalize`. | Configuration-infrastructure input processing that produces separately typed candidates. Defaults and derivations remain visible in provenance. |
| SIGHUP config reload (2026-08) | Re-resolves the file config, re-applies the database layer over it, validates, then atomically republishes through `config.Holder`. A failed reload, whether the file or the control plane caused it, keeps the running config and records `last_error`/`last_error_at` in `/api/config`. | Candidate promotion with last-known-good retention: the running snapshot is untouched on failure. A bounded observation period and actor audit are not yet implemented. |
| Control-plane resource command (2026-09) | `ControlPlaneService.Command` validates a whole resource document against its owning feature, then writes it with an audit record (actor, source, request ID, expected version) under optimistic concurrency. Hosted on the State Store's gRPC server; the Web UI and messaging channels are its only clients. See `docs/prds/runtime-control-plane.md`. | Met for validate-stage-promote, actor audit and versioned history. Per-field health observation and validate-before-switch on live apply are not yet implemented. |
Any further mutation seam discovered during migration MUST be added here before
it is changed. Direct field assignment on a live settings object is prohibited.
## Universal change protocol
Changing configuration is an application command performed by an identity. It
MUST:
1. resolve the target owner and current version;
2. parse into that owner's typed settings;
3. validate syntax, semantic constraints, policy, references, and safe bounds;
4. stage a candidate without altering the active value;
5. run owner-defined readiness and health checks;
6. atomically promote the candidate and record actor, source, reason, diff,
prior version, and new version;
7. observe the affected capability for a bounded period;
8. retain the new version on success, or automatically restore last-known-good
on failure;
9. report the rejected or rolled-back candidate without terminating unaffected
capabilities.
Startup loading uses the same candidate rules. A bad user value therefore does
not partially mutate the application or make a previously healthy capability
unavailable.
Settings that cannot safely reload in-process are marked restart-required. The
change may still be validated and versioned immediately, but promotion occurs
through a controlled restart with the same health and rollback semantics.
## Implemented runtime reload and settings writes (2026-09)
Two mechanisms change behavioural values at runtime: SIGHUP re-reads the file
config, and the control plane owns every database-backed setting. The dashboard
runtime overlay that used to sit between them was deleted once the control plane
covered its surface; `-config-overlay` names a file overlay and is unrelated.
### Published snapshot: `config.Holder`
The running configuration is a published snapshot held in `config.Holder`
(`internal/config/holder.go`). Get returns a value under RLock; Set replaces the
whole snapshot. A published Config is immutable: reload constructs a fresh one
and calls Set. `config.Clone` deep-copies every reference-type field so a failed
decode cannot mutate the published snapshot's shared maps. `Holder.Get` panics
on a nil receiver — a forgotten `NewHolder` must fail loudly, not boot a daemon
that silently runs on an empty config.
### The reloadable-field criterion
The diff-and-warn on reload asks whether a changed field takes effect without a
restart. The criterion is: **a field is reloadable when every consumer re-reads
it.** That question read as "what does the daemon re-read" while the daemon owned
the only Holder; it stopped being sufficient when webui began sharing that
Holder, because webui handlers re-read on every request. The allowlist lives in
`cmd/archied/reload.go` and is deliberately a deny-by-default list: a field added
to Config later defaults to requires-restart, forcing whoever adds it to decide
deliberately. A reload that changes any non-allowlisted field logs
"requires a restart" with the field names; a fully-applied reload logs Info.
### SIGHUP reload
SIGHUP re-resolves the file config, re-applies the database layer over it
(`boot.runtimeConfig`, the same call boot makes), validates, and atomically
republishes through the shared Holder. A failed reload keeps the running config
and records `last_error`/`last_error_at` in `/api/config` so the stale state is
visible where the operator is looking. The three poll tickers re-read
`PollInterval` per iteration and reset on change, so a reloaded interval
genuinely takes effect.
### Settings writes go through the control plane
Database-backed settings are read and written through
`ControlPlaneService` on the State Store's gRPC server: catalogue, query,
command, watch. Each feature owns its resource's validation and commands;
storage writes versions and audit records only. `docs/prds/runtime-control-plane.md`
is the specification.
Two properties matter to anyone changing this area:
- **Bootstrap stays file-owned.** The daemon reads the file config first and
layers database resources over it at boot (`boot.loadRuntimeConfig`). Values
the daemon needs before it can reach the State Store — the database path,
listen addresses, credentials — stay file-only by design.
- **Reload re-reads them.** SIGHUP resolves the file document and then runs the
same `boot.runtimeConfig` layering boot does, so a reload cannot revert a
database-owned setting to its file value. A control plane that cannot answer
fails the reload rather than publishing the file's values over the running
ones. Workflow execution budgets arrive on a watch rather than in a resource
query, so boot records the last published settings and the reload re-applies
them from there.
- **Live kinds arrive on a watch.** Provider settings, model role assignments,
repository policies, scheduling policy, tool settings, plugin settings,
review settings, channel settings and container runtime policies are
`ApplyMode: live`: the daemon keeps a watch per kind
(`boot.startRuntimeResourceWatches`, `runtimeResourceKinds`) and, on a new
version, re-runs `boot.runtimeConfig` over the published snapshot and
republishes through `config.Holder`. A candidate the layered document cannot
run is refused before it is published — last-known-good keeps running and
the refusal is reported through apply status. Tool settings reconcile in this
process: the daemon diffs the stored MCP server set against the running
providers — connecting added servers, disconnecting removed ones and
reconnecting changed ones while an unchanged server keeps running — and
rebuilds the `web_fetch` and `minimax` entries, whose config was captured at
construction (`boot.reconcileToolSettings`). Container runtime policies
join the live set because their consumers re-read the published config: the
container pool reads image, pull policy, network, max uptime and concurrency
cap on every acquire and the daemon resizes its running task dispatcher from
the same publish; the fields the document cannot carry, `registry_auth`
above all, stay boot-resolved and remain requires-restart. A kind whose
consumer lives in another process reconciles there too: `archie-messaging`
re-reads the stored channel settings on the apply-status restamp interval
and restarts only the channel whose transport settings changed, while the
listen addresses it has bound and the set of channels it composed stay
process bindings that take effect on restart. A kind joins the live list
only with a consumer that re-reads it; one whose startup-built consumer
never does stays restart-required, and the model/provider half of the live
set also rebuilds the gateway chat runtime's provider set and the chat model
list the chat surfaces offer.
## Completion criteria
The configuration rearchitecture is complete only when:
- `internal/config` no longer exists;
- every behavioural value has one classification and owner;
- every current field and hard-coded value in the ledgers has a recorded
disposition;
- domains and plugins receive only their typed settings;
- all changes use semantic commands and the universal change protocol;
- active, candidate, rejected, rolled-back, and last-known-good versions are
queryable with secret-safe provenance;
- generated documentation lists every external key, default, constraint,
mutability class, owner, and deprecation;
- architecture tests prevent a new central runtime configuration model, direct
live-setting mutation, and incorrectly fixed behavioural values.
## Startup policy: missing credential degrades, invalid config is fatal
Decided 2026-07-30. Recovered 2026-08-09 from the pre-migration issue tracker.
A missing **credential** disables a capability. Only an **invalid config** stops
the daemon. "Forge is a feature, not a requirement."
Before `518a1a0`, an unresolvable forge token did `return 1` in
`cmd/archied/main.go`, so a chat-only user who never configured GitHub got no
chat, no gateway, nothing — and under a systemd unit with `Restart=on-failure`
and no start limit it crash-looped every five seconds with the error scrolling
past unread. Forge construction now lives in `resolveForge`, shared by the
primary forge and every configured identity, and degrades to `forge.NewNoop`
with a warning. The identity path had the same defect and was worse: one
identity's missing credential killed all the others.
Malformed configuration still fails fast in `configuration.Validate`, well
before this point. That distinction is the whole design.
Apply the same reasoning to any future capability credential, LLM keys
especially: start, report the capability as unavailable, let the operator see it.
Guarded by `TestResolveForgeDegradesInsteadOfFailing`.
**Known consequence, tracked separately:** `worktree.Manager` still receives the
empty token, so pushes fail late rather than at startup.
## Config generation belongs to `archied setup`, not `install.sh`
Decided 2026-07-30 ([#368](https://github.com/samcharles93/archie-core/issues/368)).
Recovered 2026-08-09 from the pre-migration issue tracker.
`install.sh` must stop generating `config.toml`; `archied setup` owns it. The
installer hand-rolling TOML has already drifted from the schema once: the
generated-config branch hardcoded `key = ARCHIE_GITHUB_TOKEN` and
`host = ${GITEA_URL}` regardless of the answers given, so choosing Gitea produced
a config naming a token the installer never wrote (archied then exited 1), and
choosing GitHub pointed `host` at `gitea.example.com`. `61a5b35` patched this
with a `forge_block` shell helper shared by both config paths — that helper is a
**workaround**, deleted by
[#72](https://github.com/samcharles93/archie-core/issues/72). The durable fix is
that the code writing the config is the code that reads it.
Why Go and not Python: the installer must run where nothing is installed yet, and
`python3` with `tomllib` means 3.11+, which is not safe on LTS distros. `archied`
is already being built two steps earlier.
**Key constraint for the port:** `BurntSushi/toml` does **not** survive a
decode/encode round trip with comments intact, and `config.example.toml` carries
documentation users are meant to hand-edit. Decide the write strategy
([#412](https://github.com/samcharles93/archie-core/issues/412)) before writing
any prompting code. Do not port a separate `config.yaml`/`auth.yaml` secret
split — Archie already has `secret.SecretRef{engine,key}`, so setup writes the
reference to TOML and the value to the secret engine.
@@ -1,39 +0,0 @@
# The dashboard's tools for an in-browser agent
The dashboard registers in-browser tools an agent can call through the page's model
context. Four are read-only — `list_tasks`, `get_task`, `recent_events`,
`daemon_health` — and three recover stuck work: `retry_task`, `stop_task`,
`cancel_task`. Each wraps the same `ui/src/lib/api.ts` client the dashboard itself
calls, so an agent and a person exercise one path rather than two.
The four judgement verbs are withheld for the reason `identity.md` gives: an agent
that can approve can approve its own work.
## What a tool call can be attributed to
A page can invoke its own tools, so an agent's call and a page script's call reach
the server identically — the difference does not exist on the wire, and no header
recovers it. A tool call is therefore attributed to the signed-in identity the
request presented, with its source recorded as a hint; it never records that an
agent acted, and it never records that a human approved. An agent's action is
attributable only on a surface where the agent presents its own credential.
## Confirmation is a signal, not a control
The three recovery tools require an explicit `confirm: true`, which makes a
consequential call deliberate rather than incidental. It is not a security control:
an agent can trivially satisfy it, and the browser cannot enforce
`consequentialHint` at all — Chrome accepts it at registration and omits it from
`getTools()`, so no client can see what the browser does not surface.
The boundary that holds is the session. These tools cannot exceed what the operator
signed in at the provider is already permitted to do.
## Two ways the surface fails silently
- **A secure context is required.** On a plain-HTTP origin `document.modelContext` is
absent even with the flag enabled, and nothing reports why. `mkcert` covers local
development.
- **The dashboard embeds `ui/dist` into its binary.** Rebuilding the distribution is
not deploying it: a running process can serve a bundle without tools while the
built one has them, or serve a bundle older than its own binary.
@@ -1,71 +0,0 @@
# Dependencies and Contracts
**Status:** Approved foundation
**Date:** 2026-07-28
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Dependency direction
```text
domain and shared application contracts <- infrastructure implementations
^
|
application composition
```
The following rules are strict:
1. Domains MUST NOT import `internal/infrastructure`.
2. A domain defines the smallest interfaces required to perform its work.
3. Infrastructure implements those interfaces and translates external
representations at the boundary.
4. Only application composition chooses concrete implementations.
5. A domain MUST NOT manipulate another domain's state or call its internal
services.
6. Cross-domain work uses an explicitly designed command, event, or approved
shared contract.
7. Implementation difficulty is not permission to violate a boundary.
Broker messages, database rows, SDK response types, and configuration DTOs MUST
NOT leak into domain models.
## Commands and events
- An event records something that happened and is owned by its publishing
domain.
- A command requests an action and is owned by the domain expected to handle it.
- Consumers do not redefine an event's meaning.
- Senders obey the receiving domain's command contract.
- There is no generic package containing unrelated application messages.
## Event bus
`internal/eventbus` is an approved shared application contract. It defines only
the messaging behaviour Archie requires, including publication, subscription,
delivery outcomes, and required lifecycle semantics.
It MUST remain broker-neutral. NATS subjects, JetStream configuration, consumer
groups, acknowledgements, reconnection, and serialisation belong under
`internal/infrastructure/eventbus/nats` unless Archie explicitly requires a
semantic guarantee in the shared contract.
Message schemas stay with their owning domains. The event bus transports
messages; it does not own their meaning.
## Wire contracts and generation
Canonical worker and service wire contracts and their authoritative generation
inputs are owned by the domain or capability that defines their meaning. They
MUST NOT be centralised in `internal/infrastructure/spec` or another generic
schema package.
Infrastructure owns:
- generic contract-generation machinery;
- transport-specific adapters and generated implementations;
- RPC, REST, NATS, and other external encoding and delivery concerns.
For example, agent-worker requests and results belong to task execution.
Subprocess, NATS, or HTTP representations are infrastructure implementations of
that contract. The same rule applies independently to forge, persistence,
workspace, and other service contracts.
@@ -1,439 +0,0 @@
# Generated Documentation
**Status:** Data generation lives here; rendering and publishing live in the external Astro website
**Date:** 2026-07-28 (revised 2026-09-25)
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Purpose
Archie's documentation-generation approach is:
- production Go code, registries, configuration, and CLI behaviour remain the
source of truth for published contracts;
- a repository-local Go generator extracts and normalises documentation data;
- the generator writes deterministic JSON/data files and protocol schemas;
- the external Astro website consumes generated data and serves the public
documentation at `offloaded.dev/docs/`.
Hugo is not part of the target architecture.
The documentation system is rooted at:
```text
tools/
go.mod
go.sum
docsgen/
main.go
docs/
data/generated/
public/schemas/
*.md
```
### Rendering and publishing — external Astro website
Superseded 2026-09-12. The repository previously carried a VitePress site
(`docs/.vitepress/config.mts`, `docs/package.json`, a 1620-line
`docs/pnpm-lock.yaml`, `docs/pnpm-workspace.yaml`) built and deployed to GitHub
Pages by `.github/workflows/docs.yml`. It was removed as an unnecessary build
step: the published site was never stood up, and the Pages target is not
configured.
The Astro website is maintained outside this repository. This repository owns
the Markdown source and generated JSON artifacts; it does not build, preview, or
deploy the site. The external site owns page rendering, navigation, and
publishing.
The current boundaries are:
| Concern | Owner |
| --------------------------------------- | -------------------------------------------------------------------- |
| Reference-page rendering and publishing | External Astro website |
| Documentation source and generated data | This repository |
| Generated-data drift detection | `task docs:check`, `task docs:artifact:check`, and `task news:check` |
| Navigation data | `docs/data/generated/docs.json` and `dev-docs.json` |
Changes to an artifact contract must be coordinated with the external Astro
consumer. This repository does not validate the website's rendered links or
routes.
## Single source of truth
Every published capability has one authoritative machine-readable definition
owned by its domain or application boundary. Generated documentation derives
from those definitions.
Generated reference includes:
- domain commands and events;
- Messages and typed message content;
- Agent and Workflow contracts;
- WorkflowSteps and Workflow plugin capability contracts;
- policies and their typed inputs and outcomes;
- tools and capabilities;
- CLI commands, arguments, flags, defaults, and help;
- runtime settings, types, defaults, validation, and secret metadata;
- public worker and transport contracts;
- indexes of registered functionality;
- deprecation information.
Handwritten documents contain:
- architecture decisions and rationale;
- tutorials and operational guides;
- examples and walkthroughs;
- migration guidance;
- conceptual explanations.
Handwritten documents link to generated reference rather than copying
authoritative tables.
## Target generation architecture
`tools/docsgen` is Archie's documentation extractor and normalizer. It produces
structured documentation data and protocol specifications. It does not own
page layout and MUST NOT generate Markdown pages or fragments.
The generator is divided internally into reusable stages:
```text
load registries and types
-> normalize documentation model
-> validate ownership and identifiers
-> serialize data and protocol artifacts
-> compare or write output
```
The normalised documentation model prevents each output renderer from
independently interpreting Go types. It contains stable documentation IDs,
owners, names, descriptions, source references, versions, deprecations, fields,
defaults, validation, secret classifications, and relationships.
Initial generator targets:
```text
docsgen data
docsgen asyncapi
docsgen all
docsgen check
```
- `data` writes the normalised JSON reference data.
- `asyncapi` writes protocol schemas and envelopes.
- `all` generates every committed artifact.
- `check` generates into a temporary directory and fails on drift.
The command may use subcommands or an equivalent explicit `--target` flag. It
MUST retain one normalisation and validation path.
## Target output
During adaptation, `docs` remains the staging site. Generated outputs live in
a visibly owned subtree:
```text
docs/
data/
generated/
catalog.json
contracts.json
docs.json
dev-docs.json
cli.json
configuration.json
messaging.json
agents.json
workflows.json
policies.json
plugins.json
tools.json
public/
schemas/
asyncapi-header.yaml
archie.yaml
.tmp/
```
All files under `data/generated/` and `public/schemas/` carry generated
ownership metadata where their format permits it and MUST NOT be edited
manually. `.tmp/` is generator-owned, ignored, and never committed.
`catalog.json` is the deterministic machine-readable index used for:
- reference navigation and route inputs;
- duplicate-ID and duplicate-route validation;
- coverage checks;
- source-to-data drift diagnostics;
- future external consumers.
These files are consumed at render time by whichever renderer is chosen (see
"Rendering and publishing"); the generator's contract is the committed JSON, not
any particular loader. A renderer reads `data/generated/*.json` directly — Archie
does not use `createContentLoader`-style Markdown collection scanning, because
the authoritative inputs are JSON.
The final move from `docs/` to `docs/` occurs only after Archie content
contains intentional Archie pages and the current architecture documents have an
intentional destination. The staging name MUST NOT leak into public URLs.
## Generation steps
### Step 1: maintain the Archie tools module
Keep `tools/go.mod` isolated from the runtime module:
```go
module github.com/samcharles93/archie-core/tools
require github.com/samcharles93/archie-core v0.0.0-00010101000000-000000000000
replace github.com/samcharles93/archie-core => ../
```
Keep generator-only dependencies such as `invopop/jsonschema` and any future
protocol-schema serializer in the nested tools module. They MUST NOT enter the
root module.
`docsgen` imports Archie-owned contracts and writes normalised Archie data and
protocol artifacts.
### Step 2: establish authoritative registries
The generator consumes domain-owned registries rather than scanning arbitrary
packages for anything exported.
Each published definition supplies:
- stable documentation ID;
- owning domain or boundary;
- name and description;
- version when versioned;
- the Go type or declarative definition;
- lifecycle and deprecation metadata;
- source reference.
Registries remain executable application definitions used by production code. A
documentation-only duplicate registry is prohibited.
Where the migration has not yet created a final domain registry, the generator
may use a narrow compatibility adapter over the current registry. That adapter
has explicit deletion criteria.
The initial agent-execution and messaging schema set is such an adapter. It is
deleted when those domains expose their production-owned documentation
registries; adding another hardcoded type list to `docsgen` is prohibited.
### Step 3: generate AsyncAPI
Use Archie's messaging and worker wire registries as the authoritative inputs.
The static header continues to own:
- AsyncAPI version;
- service and protocol description;
- servers;
- channels;
- operations;
- message envelope placement.
The generator owns:
- component schemas;
- discriminated concrete message lists;
- generated envelopes;
- rewritten schema references;
- stable ordering.
The generated protocol artifact becomes:
```text
docs/public/schemas/archie.yaml
```
The final owner of each wire registry is the domain or capability defining its
meaning. `docsgen` renders the contract; it does not own the message semantics.
### Step 4: add generated documentation data
Add extractors for the missing reference categories one vertical slice at a
time.
Recommended implementation order:
1. CLI commands and flags;
2. runtime configuration/settings;
3. Messaging commands, events, and message types;
4. Agent definitions and public commands;
5. Workflow definitions, WorkflowSteps, lifecycle, and plugin contracts;
6. policy definitions and typed outcomes;
7. tools and capability contracts;
8. worker and external wire contracts.
Each category extractor contributes:
- stable IDs, owners, routes, and display ordering;
- fields, types, defaults, and validation metadata;
- source references;
- version and deprecation information;
- relationships to commands, events, policies, and contracts.
The first vertical slice proves the normalised model and deterministic JSON
serialisation. Later categories reuse it rather than introducing
category-specific ad hoc output formats.
### Step 5: external Astro renderer
The Astro website reads `data/generated/*.json`, validates it, and renders
reference views. Build and deployment remain owned by the website repository.
Navigation and routes derive from `catalog.json`; they MUST NOT be duplicated by
hand in renderer configuration.
### Step 6: implement deterministic drift checking
`docsgen check`:
1. generates all artifacts into a temporary directory;
2. normalises line endings and file modes;
3. compares the complete expected data and schema trees with committed outputs;
4. reports missing, changed, and obsolete files;
5. identifies the authoritative definition associated with each mismatch;
6. exits non-zero without modifying the working tree.
Generation MUST exclude:
- wall-clock timestamps;
- absolute filesystem paths;
- map iteration order;
- environment-specific values;
- secrets and resolved credentials.
Two consecutive `docsgen all` runs MUST be byte-identical.
### Step 7: Astro renderer — external consumer
The external Astro website consumes the committed generated JSON artifacts and
serves the documentation under `/docs/` and `/dev/`. Its build and deployment
are owned by that repository. The consumer MUST:
- read `data/generated/*.json` rather than re-deriving from source;
- validate internal links, with dead-link failures enabled (no blanket
ignore list);
- state its own local preview and build commands;
- keep `node_modules/` and any build output out of source control.
### Step 8: developer commands
`task docs:generate` writes the committed artifact; `task docs:check` verifies
it. `task check` runs `docs:check`, so generated drift is gated rather than
advisory: a stale artifact fails the gate and names the authoritative Go
definition behind each mismatch.
```sh
task docs:generate
task docs:check
```
Both wrap the generator, which can still be run directly:
```sh
go -C tools run -mod=readonly ./docsgen --repo-root ..
go -C tools run -mod=readonly ./docsgen check --repo-root ..
```
`docsgen all` is still target-only: `docsgen data` and `docsgen asyncapi` do not
exist. Two artifacts are generated today: `contracts.json` from the Go
contract types (`docsgen`) and, from the Markdown sources, `docs.json` and
`dev-docs.json` (`docsite`, one artifact per published set: the public set a
reader of the product gets, and the development set of architecture and design
records) -- see `task docs:artifact`.
### Step 9: validation and CI
`task check` validates generated contracts and Markdown-derived documentation
artifacts. The Astro site's rendered routes and deployment are validated in its
own repository.
### Step 10: content migration
The Astro site consumes generated artifacts. Remaining content work is to:
Still standing from the original cutover list:
- remove Markdown, examples, specs, generated schemas, and assets that do not
describe Archie;
- adapt retained content and prove it against Archie code;
- update `docs.go` and its tests to embed only intentional runtime
documentation;
- decide which current `docs/prds` remain published architecture pages and which
remain repository-only planning documents — all of them are repository-only
now, so the distinction is retired.
Documents MUST describe Archie. Publishing is a separate, undecided concern.
## Hook and CI policy
Generated documentation is committed.
No pre-commit hook is installed in this repository, and no CI step runs the
generator. Step 3 below is enforced by `task check`; steps 1, 2, and 4 still
rely on the author, because nothing observes a commit:
1. detects authoritative definition or generator changes;
2. runs the generator;
3. runs `docsgen check` — enforced by `task check`;
4. refuses the commit when generated changes are unstaged or validation fails.
A commit MUST NOT be created while generated documentation is stale.
## Validation requirements
Generator tests cover:
- stable ordering;
- schema reference rewriting;
- `$defs` flattening;
- duplicate IDs and routes;
- registry coverage;
- comments and descriptions;
- secret redaction;
- obsolete-file removal;
- byte-identical repeated generation;
- check-mode diagnostics.
Repository-documentation validation covers:
- internal links resolve on the filesystem (repository-relative paths);
- absence of unrelated product names and URLs;
- absence of committed build artifacts and installed dependencies.
Renderer validation (frozen dependency installation, production build, expected
output routes) is added with the renderer decision and is currently unenforced.
The root module remains free of generator-only dependencies.
## Completion criteria
The documentation migration is complete when:
- `tools` belongs to Archie and builds against the working tree;
- `docsgen` consumes Archie-owned registries and types;
- AsyncAPI output describes Archie;
- required reference categories are generated as committed deterministic data;
- `catalog.json` matches the generated definitions and rendered routes;
- two consecutive generations are byte-identical;
- `docsgen check` detects changed, missing, and obsolete artifacts;
- build artifacts and installed dependencies are absent from source control;
- `task docs:generate` and `task docs:check` work from a clean checkout;
- every document describes Archie and every internal link resolves.
Renderer-dependent criteria (rendered reference pages, local authoring server,
deployable build, published site) are removed pending the renderer decision.
## Implementation references
- [GitHub-flavoured Markdown specification](https://github.github.com/gfm/) —
the dialect repository documentation is written in
- [pnpm](https://pnpm.io/) — required only if a future renderer chooses a
Node-based toolchain
-352
View File
@@ -1,352 +0,0 @@
# Identity
**Status:** Approved foundation; lifecycle details are deferred
**Date:** 2026-07-28
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Purpose
Identity answers which persistent actor owns or performed an action. It supplies
stable cross-domain attribution and lifecycle semantics.
Identity kinds include:
- the Archie system identity, such as `System` or `archied`;
- agent or bot identities;
- service-account identities;
- future user identities.
A user is another kind of identity rather than a separate foundation concept.
## Ownership
`internal/domain/identity` owns:
- immutable canonical `IdentityID` values;
- identity kind;
- lifecycle state;
- ownership and attribution semantics;
- identity-related commands and events.
Domains may record an identity reference on their own state and events when
ownership or attribution is required. They MUST NOT receive a complete
per-identity application configuration bundle.
Persona and communication style are separate from identity.
Every Agent has its own immutable acting `IdentityID`. Agent actions use that
identity for ownership and attribution in the same way an organisation records
which user accessed a resource, changed a permission, or performed another
auditable action.
Agent and Identity remain separate aggregates. Identity supplies the stable
actor reference; Agent owns assistant behaviour, memory, specialisation,
conversations, and capability context.
Agent identities MUST NOT be shared between Agents. Automated WorkflowExecutions
MAY eventually act through a dedicated service-account identity when a specific
unattended automation requires it. Such use is an explicit execution decision
and audit principal, not the default for Agents or a substitute for recording
the initiating user when one exists.
A Workflow is owned by an IdentityID and executes as its owner by default.
Future delegated execution MAY explicitly assign a different `RunAsIdentityID`,
including a user or service-account identity. Ownership, effective execution
identity, initiating identity, and delegation provenance remain distinct audit
facts.
## Canonical identity
Every identity has an immutable `IdentityID`. It is the only value used for
cross-domain ownership, attribution, routing, persistence, commands, and events.
Identity kind is explicit:
- system;
- bot;
- service account;
- user.
Display names are mutable and MUST NOT be used as identifiers. Forge usernames,
channel bot names, Git authors, provider account names, and other external
identifiers are bindings associated with an identity rather than identity
itself.
`System` is represented by a real identity and `IdentityID`. The empty string
MUST NOT retain special meaning as a legacy system identity.
Configuration refers to identities by `IdentityID` and supplies external
bindings and capability settings separately. Renaming an identity or changing an
external account MUST NOT change ownership or historical attribution.
Secret-bearing channel bindings remain configuration concerns rather than
identity data. In particular, `[chat.telegram].token` is a
`secret.SecretRef` resolved by the application through the configured secret
registry. It does not change the identity that owns or performs a chat action.
## Persistence
Identity records are durable domain state. The Identity domain's repository is
the source of truth; infrastructure implements its persistence contract.
Configuration MAY bootstrap a missing identity through an explicit, audited
creation operation and MAY propose runtime capability bindings for an existing
`IdentityID`. Configuration is not the identity registry.
Omitting an identity from configuration stops assembling the omitted runtime
capabilities. It MUST NOT delete the identity record, erase history, or make
historical references unresolvable.
Disabling or retiring an identity requires an explicit Identity-domain command.
Retired identities remain resolvable for historical attribution. A failed
external binding affects capability availability without destroying or silently
replacing the identity.
## Lifecycle
Identity lifecycle is deliberately small:
- `active`: may participate in runtime composition;
- `suspended`: deliberately prevented from initiating new work while ownership
and history remain;
- `retired`: terminal, unable to initiate work, and permanently retained for
attribution.
Allowed transitions are:
```text
create -> active
active -> suspended
suspended -> active
active -> retired
suspended -> retired
```
`retired` has no outgoing transition.
Capability health is separate from identity lifecycle. Forge, model, channel,
workspace, and other bindings report health independently. An active identity
may be partially degraded without becoming suspended or retired. Runtime
supervision isolates and restores affected bindings through the safe-change and
recovery protocol.
## System identity
Archie has exactly one built-in system identity. It is created during initial
store bootstrap, is strictly always active, and cannot be suspended or retired.
Its `IdentityID` and kind are immutable.
Startup, migration, supervision, remediation, and rollback actions performed by
the application use the system identity. The system identity MUST NOT be
delegated to individual identities. Every user, bot, service account, or other
actor mutation records the identity that actually performed it.
System capabilities may independently become unhealthy or unavailable without
changing the system identity.
## Target placement and contracts
The Identity domain lives at `internal/domain/identity`.
It owns:
- `IdentityID`, identity kind, display name, lifecycle, version, and audit
timestamps;
- create, rename, suspend, reactivate, and retire commands;
- corresponding lifecycle events;
- the repository contract required for durable identity records;
- lookup of current and historical identities.
External account bindings and capability settings remain with the domains that
use them and reference `IdentityID`.
## Migration constraints
Migration from the current string model MUST:
- bootstrap the permanent system identity;
- assign stable IDs to configured identities without losing their names;
- replace empty-string legacy ownership with the system identity;
- migrate tasks and sessions to canonical identity references;
- include identity where task uniqueness and transport deduplication require
independent ownership;
- route container RPC through the task owner's capability bindings;
- retain historical resolution after rename, suspension, or retirement;
- remove identity-string equality from authentication or access semantics.
This completes the foundation required to restructure the current Identity
behaviour. Exact storage schemas and Go method signatures belong to
implementation design, not this architecture review.
## Lifecycle
Identity lifecycle is deliberately small:
- `active`: may participate in runtime composition;
- `suspended`: deliberately prevented from initiating new work while ownership
and history remain;
- `retired`: terminal, unable to initiate work, and permanently retained for
attribution.
Allowed transitions are:
```text
create -> active
active -> suspended
suspended -> active
active -> retired
suspended -> retired
```
`retired` has no outgoing transition.
Capability health is separate from identity lifecycle. Forge, model, channel,
workspace, and other bindings report health independently. An active identity
may be partially degraded without becoming suspended or retired. Runtime
supervision isolates and restores affected bindings through the safe-change and
recovery protocol.
## Explicit non-responsibilities
Identity is not authentication and is not access control.
The current architecture does not require authentication or authorisation. Those
capabilities MAY be introduced later if deployment or product needs justify
them. They MUST remain separate from the identity model.
An identity reference therefore proves attribution within Archie's trusted
system model; it does not by itself prove credentials or permission.
## Per-identity configuration
Values selected for an identity remain external configuration values. At
composition time they are split into the runtime settings owned by the affected
domains and correlated by identity reference.
The existing `IdentityConfig` aggregate MUST be dissolved. Forge accounts,
repositories, models, providers, workspace behaviour, polling, budgets,
notifications, and transport namespaces retain their respective owners.
## Audit
Configuration changes and other state changes are actions attributed to an
identity. System-initiated changes use the system identity. Their audit records
MUST preserve the acting identity, the target, and the resulting change.
The command ownership and persistence mechanism for configuration changes is a
separate configuration-management decision.
## Current implementation
Identity is not currently implemented as a domain. It is a collection of string
fields and process-local associations:
- `config.IdentityConfig.Name` is the daemon routing key.
- `config.IdentityConfig.BotUser` is the external forge and Git author name.
- `daemon.IdentityRunner` bundles the configured name with a forge client,
worktree manager, repository list, configuration subset, logger, and polling
goroutine.
- `store.Task.Identity` persists the configured name on tasks.
- NATS task messages copy the same configured name.
- gateway routing accepts an identity name and uses it to select a repository
profile.
- gateway sessions persist `BotUser`, not the configured identity name.
There is no identity registry, identity record, identity lifecycle state,
identity persistence, or identity command/event model. Removing an identity from
configuration makes existing task ownership unresolvable.
An empty identity string selects the legacy single-identity path. This gives the
empty string behavioural meaning rather than representing a real system
identity.
## Current enforcement and isolation
## Withheld judgement verbs
`approve`, `reject`, `abandon` and `archive` are not exposed to an agent. An agent
that can approve can approve its own work, and the one control this surface exists
to keep is a human accepting it.
The constraint is attribution, not capability: a task action records the acting
identity and the authorising principal, so exposing the verbs requires that an
agent's action be recorded as an agent's and the authority it used recorded
separately. Until a surface carries both, the verbs stay withheld. This is the
reason the four verbs are absent from the dashboard's in-browser tools, and it is
why releasing them is a change to this boundary rather than a change to the tools.
The current implementation uses identity equality as an authorisation check for
chat task approval and cancellation. This conflicts with the approved rule that
identity is attribution rather than authentication or access control and must be
reassigned to an appropriate task-ownership or future access policy.
Focused tests verify that:
- a task resolves the forge client and repository list associated with its
configured identity name;
- cross-identity repository profiles do not leak;
- chat task creation propagates the selected identity;
- task persistence retains the identity string;
- chat task control rejects a different identity string.
## Current hazards
- Task uniqueness is `(owner, repo, issue_number)` and excludes identity.
Two identities discovering the same forge issue cannot own distinct task
records.
- NATS deduplication uses `owner/repo/issue` and excludes identity, so discovery
by a second identity can be discarded as a duplicate.
- Container-mode forge and worktree RPC servers are wired to the root clients,
not the task owner's clients. The source documents this as an unresolved
identity leak.
- The shared task queue claims the oldest task without identity partitioning and
relies on later string lookup to recover the correct runner.
- Sessions use forge bot usernames where tasks use configured identity names, so
there is no canonical cross-domain identity reference.
- Identity lifecycle is process lifetime only; there is no disabled, degraded,
retired, or unavailable state and no audit history.
The focused identity tests pass. Broader daemon and NATS suites could not open
embedded listener ports in the current sandbox; their failures occurred before
identity behaviour executed.
## Three-layer identity model
Agreed 2026-07-30; the frame for SOUL
([#68](https://github.com/samcharles93/archie-core/issues/68)) and the curator
([#435](https://github.com/samcharles93/archie-core/issues/435)).
Recovered 2026-08-09 from the pre-migration issue tracker.
**Layer 1 — invariants.** Instruction precedence, core rules, and the `<tools>`
and `<env>` blocks live in `internal/gateway/templates/archie.md.tpl` and are
unreachable at runtime by anyone.
**Layer 2 — SOUL.** User-authored identity: agent name, register, warmth.
Editable without a rebuild.
**Enforcing the Layer 1 / Layer 2 boundary.** SOUL is rendered as the
`Persona` field of `SystemPromptConfig` (`internal/gateway/prompt.go`) into a
`<soul purpose="identity_and_style" trust="data">` block, XML-escaped through
the same `xml` template helper used for tool and env metadata, and placed
_before_ `<instruction_precedence>` in `archie.md.tpl`. Escaping means SOUL
text can never forge a live `<core_rules>`, `<instruction_precedence>`,
`<tools>` or `<env>` tag -- an attempt renders as inert escaped text
(`&lt;core_rules&gt;...`), and `<instruction_precedence>` explicitly tells the
model the `<soul>` block is reference data, not an authority. This is
guarded by `TestBuildSystemPromptSoulCannotOverrideInvariants` in
`internal/gateway/prompt_test.go`, which renders a hostile SOUL that attempts
to countermand `core_rules` and asserts the real invariant tags stay singular
and their text stays intact. Keep this test in sync if the template's escaping
or block structure changes -- do not relax it to make a future SOUL feature
(e.g. curator-proposed edits) fit.
**Layer 3 — representation.** Curator-derived knowledge about the user. It may
only **propose** changes to SOUL and never apply them. If derived conclusions can
silently rewrite tone, personality drifts and the user loses the control SOUL
exists to give them. A proposal queue also makes the visibility requirement fall
out for free, since pending conclusions are inherently reviewable.
**Why SOUL comes first:** tone currently lives in Go string constants
(`DefaultPersonas` in `internal/gateway/persona.go`), so fixing a rude reply on
2026-07-29 required editing Go and rebuilding. SOUL is small, fixes a real
defect, and defines the boundary the curator must respect.
-16
View File
@@ -1,16 +0,0 @@
# Architecture
Archie is a personal agent platform built around six domain boundaries:
- Identity tracks users and other actors responsible for actions.
- Agent owns persistent assistants, specialisation, and continuity.
- Messaging owns conversations, messages, branches, and channel correlation.
- Workflow owns reusable, versioned behaviour definitions and their executions.
- Work Intake admits optional durable work without constraining ordinary agent
conversation or direct capability use.
- Plugin owns generic extension discovery and lifecycle; each capability family
owns its typed plugin contract.
The detailed architecture and migration decisions are maintained under
`docs/architecture/` in the repository while this generated site is being
assembled.
@@ -1,334 +0,0 @@
# Messaging and Work Intake
**Status:** Current state researched; foundation decisions in progress
**Date:** 2026-07-28
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Purpose
Archie is a personal assistant and general agentic system. Its interactions
include conversation, questions, notes, reminders, goals, message handling,
troubleshooting, infrastructure operations, server management, source changes,
and open-ended future capabilities.
A message to an agent is therefore not inherently a work request, and invoking
an agent is not inherently a WorkflowExecution.
Messaging and work intake are separate from the Agent System's durable workflow
execution model:
- messaging preserves interactions with people and external systems;
- an agent turn interprets and responds to an interaction using its available
capabilities;
- work intake handles the optional promotion of an interaction into durable,
workflow-backed work;
- the Agent System owns Workflow definitions and creates WorkflowExecutions.
Forge issues, Jira issues, Telegram messages, emails, webhooks, and future
channels remain peer external message or artifact sources. None becomes an
execution model merely because it can lead to work.
## Confirmed boundary
Work intake MUST NOT create a WorkflowExecution directly.
Inbound interactions normally route to the Agent selected by the channel
binding. The selected Agent retains its own memory, user knowledge, conversation
continuity, specialisation, and capability context. This continuity is
independent of the underlying model or provider.
Each selected Agent acts through its own immutable IdentityID. Interaction and
resulting action records preserve both that acting identity and the initiating
user identity when one exists.
Agent memory is private by default. Interaction context MAY additionally use
user-wide memory and intentionally global shared memory, but another Agent's
agent-wide memory is not part of the selected Agent's context.
Multiple users may interact with the same Agent. The channel binding and inbound
message MUST resolve both AgentID and initiating User IdentityID before
conversation or memory context is loaded. Sharing an Agent MUST NOT implicitly
share one user's private memory with another user.
An interaction may assemble memory from four scopes: global shared, the selected
Agent's agent-wide memory, the initiating user's authorised user-wide memory,
and the private Agent-user relationship memory addressed by both IDs.
## Conversation identity
Every conversation is identified by the complete tuple:
```text
AgentID
+ UserIdentityID
+ ChannelBindingID
+ ExternalConversationID
+ ThreadID
```
`ThreadID` has an explicit empty value for channels without threads. No element
of this key may be replaced by a display name, configured bot username, channel
type, or other mutable label.
Agent and user memory continue across conversations according to their memory
scope. Immediate conversation history and delivery correlation remain isolated
to the identified channel conversation or thread. Moving between Telegram,
email, or another channel does not create a new Agent or user, but it does
create a distinct conversation unless an explicit linking operation relates
them.
Conversation and message events support projections for channel-entry metrics,
use cases, volumes, outcomes, latency, capability usage, and other product or
operational analysis. Metrics are derived read models; they MUST NOT become
mutable counters embedded in the conversation aggregate or change message
routing semantics.
## Canonical messages
Every inbound, assistant, tool-call, and tool-result message has an immutable
application-generated MessageID. Platform identifiers are external correlation,
not substitutes for the canonical ID.
Messages are addressable because an interaction is more than text. A message may
contain assistant content, reasoning data subject to its retention policy, one
or more tool calls, a tool result with authoritative execution metadata,
attachments, reply relationships, edits, or other typed content. Stable
MessageIDs also allow sessions to branch from an exact prior point.
The canonical session and message implementation must supply:
- application-generated stable message IDs;
- user, assistant, and tool roles;
- assistant tool calls and correlated tool-result messages;
- authoritative tool-result status, timing, error, truncation, and size
metadata;
- session lifecycle and active-request state;
- session-to-agent-instance and parent-session lineage;
- durable database round trips and timestamp validation.
These semantics must use the confirmed Agent, user, channel-binding, and
conversation ownership model.
The canonical message store MUST preserve messages as immutable records and
represent later edits, deletions, and branches through related records or
events.
Archie requires exact branch-point correlation using stable MessageIDs.
## Conversation branches
A branch is a continuation of a previous conversation at an exact message. A
child conversation records:
```text
ParentConversationID
ForkMessageID
```
Messages remain an append-only linear sequence within each conversation. The
child's effective initial context is the parent's history through
`ForkMessageID`; messages after that point in the parent are not inherited.
After the fork, parent and child are isolated:
- child messages, tool calls, tool results, capability actions, and errors do
not appear in the parent conversation;
- later parent messages do not silently enter the child;
- returning to the parent resumes its unchanged history;
- the child may itself be branched using the same rules;
- branch lineage remains queryable for navigation, audit, and metrics.
This supports building substantial context about a subject and then performing
one or more contextual subtasks without polluting the original conversation. For
example, a user may branch from a project discussion, create Jira issues in the
child using inherited context, and then return to the project discussion without
adding the Jira tool transcript to the parent.
Branching does not copy mutable message rows. History is resolved through the
immutable parent conversation and fork MessageID, followed by the child's own
message sequence.
Branch isolation applies to conversation history, not to Agent learning or
memory. A memory action performed in a branch has exactly the same semantics as
the same action performed in any other conversation. It writes to its selected
global, agent-wide, user-wide, or Agent-user relationship scope.
Memory provenance MAY retain the source ConversationID and MessageIDs for
explanation and audit. Retrieval and effect are determined by memory scope and
access rules, not by the conversation from which the memory originated.
Returning to a parent does not insert the child's tool transcript into the
parent history, but scoped memories learned in the child remain available to
future retrieval wherever that scope is visible.
Changing sessions or branching therefore controls immediate conversational
context without preventing the Agent from learning durable knowledge.
## Target ownership
The Messaging domain lives at `internal/domain/messaging`. It owns:
- canonical Messages and typed message content;
- Conversations, branches, and lineage;
- channel bindings and external source correlation;
- replies, acknowledgements, and outbound delivery attempts;
- message and conversation lifecycle events;
- domain-defined repository and delivery service contracts;
- projections required for conversation navigation and metrics.
Work intake is a separate cohesive domain at `internal/domain/workintake`. It
owns admission, validation, deterministic routing, and accepted work requests
for the optional transition into durable workflow-backed execution.
Telegram, email, webhook, forge, Jira, and future messaging systems are
infrastructure adapters implementing Messaging contracts. They are users of the
domain; they do not own Messages, Conversations, work admission, or
WorkflowExecution semantics.
The Agent decides whether an ordinary interaction is answered directly, uses a
capability, changes or retrieves Agent-owned information, or proposes durable
workflow-backed work.
Explicitly configured automation MAY enter work intake without a conversational
Agent turn when the external trigger and admission rule already unambiguously
request durable work. This avoids spending an LLM turn to rediscover a
deterministic routing decision.
When an interaction requires durable workflow-backed execution:
1. a channel adapter produces a channel-neutral inbound message;
2. the acting agent handles or interprets the interaction;
3. work intake validates, admits, and routes a proposed work request;
4. work intake emits an accepted work request with its source correlation,
acting identity, requested outcome, inputs, and routing evidence;
5. the Agent System consumes that request, selects a specific Workflow version,
and creates the WorkflowExecution.
The accepted work request is a cross-domain handoff, not an alternate execution
aggregate. The Agent System is the sole authority that creates a valid
WorkflowExecution.
An interaction MAY instead be completed directly by an agent turn, delegated to
a tool or capability, recorded as a note or reminder, answered conversationally,
or retained for later context. Those paths MUST NOT require a Workflow or
WorkflowExecution.
A Workflow MAY add reusable, versioned structure to any of those behaviours.
Scheduled personal-assistant routines, message triage, reminders, infrastructure
operations, and other capability sequences are valid Workflow definitions. The
distinction is whether durable structured execution is useful, not whether the
subject originated from a forge.
## Canonical execution language
- **Workflow**: reusable, versioned behaviour definition.
- **WorkflowExecution**: durable execution of a specific Workflow version.
- **WorkflowStep**: a defined operation in a Workflow.
- **StepExecution**: the recorded execution and outcome of a WorkflowStep.
- **Attempt**: a retry within the same WorkflowExecution.
External issues, messages, requests, goals, and notes are not synonyms for these
concepts.
## Current implementation
Current intake is fragmented:
- Telegram, email, and webhook adapters translate payloads into
`gateway.Message`, while an unused richer `MessageEvent` contract exists
alongside it.
- `gateway.Router` combines local channel commands, conversational LLM routing,
and direct task lifecycle operations.
- Telegram is the only channel with production LLM and durable conversation
wiring. Email and webhook free text currently have no LLM responder.
- Forge polling bypasses the gateway and directly enqueues store rows or NATS
task messages.
- Chat `/spawn` directly creates a `store.Task` and invents a synthetic forge
issue number to satisfy the existing persistence key.
- Forge replies and chat approval commands implement separate waiting-human
paths.
- Message delivery, acknowledgement, retry, deduplication, and source
correlation are platform-specific side effects rather than one durable model.
- `store.Task` collapses an external source reference and durable execution
state.
## Intake provenance
A task's origin determines which enqueue path created it, though every origin
converges on the same `tasks` table and the same `Route`/`Run` lifecycle once
queued.
- Forge-sourced work -- discovered by polling or, in single-identity
deployments, delivered by the forge webhook receiver (`internal/forge/webhook`)
-- enqueues through the same `workintake.TaskEnvelope` and `PublishTask` path.
`TaskEnvelope.IdempotencyKey` is keyed on `owner/repo/number` and not on the
delivery source, so a webhook-delivered issue and a later poll of the same
issue dedup through `PublishUnique` instead of double-enqueuing.
- Chat-spawned and playbook-binding-dispatched work enqueues through
`EnqueueChatTask`/`EnqueueBindingTask` (`internal/infrastructure/postgres`), stamped with
`binding_id`/`binding_version` for provenance.
Webhook intake is opt-in per deployment (`Forge.Intake` = `poll` (default),
`webhook`, or `both`) and single-identity only: a config naming
`webhook`/`both` alongside `[[identities]]`, or setting intake on a
`[identities.forge]` entry, is rejected at validation rather than started with
the setting ignored. One receiver binds one secret and one dispatch predicate,
so it cannot judge a second identity's events by the right rules. A
multi-identity deployment polls per identity until per-identity intake lands.
The decided contract is `docs/prds/event-sources-and-reactions.md`; the binding
model and its threat model are `docs/architecture/bindings.md`.
## Current hazards
- Treating every agent interaction as a work request would remove Archie's
personal-assistant role and force conversation and immediate capability use
through an inappropriate workflow lifecycle.
- Treating every accepted work request as a WorkflowExecution would let intake
or channel code select versions and construct invalid execution state outside
the Agent System.
- Source identity is incomplete: sessions use configured bot usernames, tasks
use identity strings, and external message IDs are generally absent.
- Database and NATS deduplication are based on forge coordinates rather than a
channel-neutral source-message reference.
- Replies and acknowledgements have no durable delivery-attempt lifecycle, so
partial success and retry behaviour differ by adapter.
- Production code has two competing channel-neutral message contracts.
- The existing Archie session implementation lacks the required tool-call
semantics and exact branch lineage and MUST be brought to the canonical
contract.
## Decisions still required
- the cohesive owner and final location of messaging behaviour;
- the cohesive owner and final location of work-intake admission and routing;
- the canonical inbound message, conversation, and source-correlation model;
- the boundary between an agent turn, direct capability use, and a proposed
durable work request;
- the exact relationship between an Agent, its acting IdentityID, its user, and
its channel bindings;
- outbound response, acknowledgement, delivery-attempt, retry, deduplication,
and failure semantics;
- the smallest accepted-work-request contract consumed by the Agent System;
- migration of forge polling, replies, chat commands, email, webhook, Telegram,
and Jira integrations.
## Non-goal: semantic search over chat messages
Semantic/vector search over chat messages is an **explicit non-goal** until usage
data shows a real need.
Message search is lexical only: session-scoped PostgreSQL full-text queries paged via
`MessageQuery{Query,Limit,Offset}` → `MessagePage`. Do not add embeddings
configuration or vector columns to message records.
The rationale is cost without a demonstrated use case. Measured 2026-08-03 with
`embeddinggemma:300m` — note this was never an infrastructure problem, the model
was already pulled and `ai-sdk/provider/ollama` already has `embed.go`:
- 121 ms median warm per message on the write path, 12.5 s cold;
- 768 dims = 3072 bytes per vector, roughly 15× a typical message payload;
- chronological reads would carry vector data they do not use on the hot path
of every turn;
- similarity search requires an explicit indexing and retention design.
If this is revisited, vectors belong in a sibling table so chronological reads
never load them.
-823
View File
@@ -1,823 +0,0 @@
# Architecture Migration Decisions
**Status:** Active migration inventory
**Date:** 2026-07-28
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Purpose
This document records what remains to be decided before Archie's current
implementation can be migrated into the approved domain-oriented structure.
The product and core domain model are not being redesigned. Existing Archie
behaviour and the existing session implementation are the migration
baseline. Remaining decisions MUST be grounded in current packages, consumers,
tests, persistence, and runtime wiring.
## Confirmed domain packages
```text
internal/domain/
identity/ (approved, not yet materialised as a package)
agent/ (approved, not yet materialised as a package)
workflow/
messaging/ (canonical Message/Conversation types only; gateway migration pending, see section 2)
workintake/
plugin/ (approved, not yet materialised as a package)
curator/
mapping/
scheduling/
```
- `identity` owns persistent actors, lifecycle, ownership, attribution, and
audit identity.
- `agent` owns persistent assistants, specialisation, instructions,
model-independent continuity, capability context, and associations with
identity and memory.
- `workflow` is a separate domain. It owns reusable, versioned Workflow
definitions, WorkflowSteps, WorkflowExecutions, StepExecutions, Attempts,
outcomes, and typed Workflow plugin contracts.
- `messaging` owns canonical Messages, Conversations, branches, channel and
source correlation, replies, acknowledgements, delivery attempts, events, and
projections.
- `workintake` owns admission, validation, deterministic routing, and accepted
work requests for the optional transition into durable workflow-backed
execution.
- `plugin` owns generic plugin identity, discovery, compatibility, and lifecycle
mechanics. It remains metadata-only; capability semantics and typed
registration belong to the owning domain.
- `curator` owns the curator engine family: long-running agent loops that
reason over memory and perform maintenance tasks on a declared shape
(check-in interval, tool set, attached memory engine). See epic
archie-core-yp9.
- `mapping` owns the payload field-mapping vocabulary: binding named fields to
JSON paths inside a captured webhook payload, and detecting drift. See
`docs/prds/payload-field-mapping.md`.
- `scheduling` owns the ticker engine: deciding when a scheduled job runs and
with what concurrency. It declares `JobSource`/`Runner` contracts and owns
no storage or delivery. See epic archie-core-1786637496320-249-be6d9a20.
**Reconciliation (2026-08-31):** `curator`, `mapping`, and `scheduling` existed
in the tree without being added to this list when their epics landed. They are
confirmed as legitimate, narrowly-scoped domains under the same rules as the
original six — each owns one capability family, declares typed contracts, and
has no cross-domain reach. This list was out of date, not the tree.
Conversely, `identity`, `agent`, `messaging`, and `plugin` are approved target
domains that do not yet exist as packages. Their behaviour currently lives in
pre-migration packages (see "Complete package destination map" below for the
full inventory). Do **not** create empty stub packages for them ahead of an
actual migration PR — an unused stub is dead code and gives no test coverage.
Each materialises when its corresponding migration decision below is resolved
and implemented in the same change.
Memory's final package placement remains undecided pending focused review of the
existing implementation.
The following are approved shared or composition packages, not domains:
```text
internal/eventbus/
internal/policy/
internal/infrastructure/
internal/app/archied/
internal/app/agentworker/
```
## Remaining migration decisions
### 1. Complete package destination map
Every current package MUST receive one explicit disposition:
- move into a confirmed domain;
- move under infrastructure as an implementation of a domain-owned contract;
- move into application composition;
- merge with an identified duplicate;
- remain as an approved shared application contract;
- move to a plugin, extra, deployment, example, or generated artifact;
- be deleted after its replacement is proven.
The largest unreviewed areas include memory, tools and capabilities, workspace
and worktree behaviour, gates, storage, events, web UI, containers, RPC
packages, release management, and scheduling.
The destination matrix MUST name the behaviour owner, target path, dependencies
to remove, state and contracts to preserve, migration prerequisites, and
deletion criteria.
**`internal/webui` / UI Service — RATIFIED Phase 3 disposition (2026-09-07).**
The current owner is the in-process HTTP/SSE dashboard: SPA hosting, operator
authentication, UI response projection, configuration reads and mutations,
task/control APIs, and direct adapters to State Store, channel, event/log,
memory, curator, workflow, forge, and Gateway runtime values. The target owner
is a standalone UI application process; `internal/webui` remains its HTTP
transport adapter, while Gateway, State Store, configuration, Work Intake,
Messaging, and other capability owners expose the contracts behind those
routes. The migration preserves retained route schemas, auth/CSRF behaviour,
task/capture/mapping/binding/session continuity, SSE replay semantics, and
committed generated SPA assets. Prerequisites are the ratified UI boundary,
route-owner inventory, narrow remote adapters, configuration/auth/readiness
contracts, and process/conformance tests. Remove the shared live
`config.Holder`, direct event/log bus, daemon stopper, forge client, channel
manager, capability registries, composite store access, and in-process UI
listener only after the focused criteria in
[`docs/prds/ui-service-boundary.md`](../prds/ui-service-boundary.md) pass in
production composition. The old construction and listener are deleted in the
same cutover change; no second UI authority remains.
### 2. Session and Messaging migration
The existing session implementation is the migration baseline. The migration must
decide:
- which session and message components are retained or adapted;
- how Agent, user, channel, Conversation, and branch ownership are added;
- how Archie's parallel gateway session implementation is replaced;
- how canonical Messages become immutable persisted records;
- how existing sessions and messages are migrated;
- how outbound delivery, retry, acknowledgement, deduplication, and failure
semantics are represented;
- how current Telegram, email, webhook, forge, and Jira integrations migrate to
Messaging infrastructure adapters.
The following are already decided and MUST NOT be reopened without contradictory
implementation evidence:
- the composite Conversation identity;
- immutable MessageIDs;
- typed tool-call and tool-result messages;
- exact branch lineage through ParentConversationID and ForkMessageID;
- parent and child transcript isolation;
- normal scoped-memory behaviour regardless of the originating Conversation;
- Messaging and Work Intake ownership.
**Decision (2026-08-31), resolving the open questions above:**
`internal/gateway/` is the "parallel gateway session implementation" this
section names. It is retained as-is for now — a big-bang rewrite of live
session/compression/approval/branch logic across Telegram, web UI, email, and
webhook channels in one change is exactly the "convoluted to satisfy edge
cases" failure mode CLAUDE.md's Revert-on-Flail rule warns about, and would
risk silent behavioural regressions in the one path every user-facing message
travels through.
Instead, `internal/domain/messaging/` is materialised now with the pieces
that are already decided and don't require touching gateway: the canonical
`Message` and `Conversation` types (composite Conversation identity, immutable
`MessageID`, typed tool-call/tool-result message variants, branch lineage via
`ParentConversationID`/`ForkMessageID`). These are pure domain types with no
gateway dependency — a new package, not a rewrite of an existing one.
Migrating `internal/gateway/`'s session, compression, approval, and branch
logic onto these types is real, cross-channel-risk work and is **not** done in
this pass. It is tracked as separate, appropriately-scoped bd issues (see
`bd list --label messaging-migration`), sequenced channel-by-channel so each
lands with its own behavioural verification instead of one large diff no one
can safely review.
**Amended 2026-09-15.** `internal/infrastructure/gatewayrpc.StoreClient` is the
adapter this migration will need: it implements `messaging.SessionStore` over
the chat service's session-store RPCs and is proven by
`TestStoreClientPreservesCanonicalRecords`. It is deliberately unwired.
Production `archied` dials the standalone gateway for `ChatContract` only
(`composeChatContract` → `gatewayrpc.Dial` returns a `*Client`, not a
`*StoreClient`), and the Gateway's session store is PostgreSQL via
`gateway.NewPostgresSessionStore`. The test comment that says it mirrors production
describes the target, not today's tree. Kept rather than deleted because the
migration it serves is deferred by this very section, and re-deriving a tested
wire adapter once that lands is pure cost.
**Phase 4 Messaging Service extraction (2026-09-19, `archie-core-8cda.6.1`).**
The process boundary for external channels (Telegram, email, webhook) is ratified
in [`docs/prds/messaging-service-boundary.md`](../prds/messaging-service-boundary.md).
Messaging is extracted into `cmd/archie-messaging` / `internal/app/archiemessaging`,
calling Gateway's `messaging.ChatContract` exclusively over gRPC. Channel frontends
hold no direct database handles, daemon state, or model runtimes.
**Telegram operator surface after extraction (2026-09-19, `archie-core-8cda.6.6`).**
`setupTelegramGateway` wired eight `telegram.Gateway` seams the daemon could
satisfy from its own process. Each is resolved by where the fact it needs is
actually owned, not by where it used to be built:
| Seam | Resolution |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Version` | Sourced from the Gateway via `ChatSnapshot.Version`. The Messaging Service never renders its own build into `/version`; `cmd/archie-messaging` does carry a `buildinfo` release stamp (added by `archie-core-k94o`, see the amendment below) for the updater's skew check and update verification, but `/version` still shows the Gateway's block so a partially upgraded deployment cannot report itself as matched. |
| `Updates` (`/update`) | Built in the Messaging Service from `[chat.telegram].update_check_command` / `update_install_command` — its own configuration. `Enrich` is dropped: `componentInstallTypeEnricher` reads `[nats]`, which this service must not decode, so the check command's own reported install type stands unmodified. |
| `UpdateReportPath` | A local state file under `work_dir`, keyed by the same `sha256(bot_user)[:8]` scheme the daemon used, so a pending report is found rather than written afresh. |
| `ReleaseAnnouncements` | **Still left nil**, but no longer for the `RunningVersions` reason (that seam now self-reports — see the amendment below). `releaseannounce.Announcer` announces nothing unless each `Component` carries a parseable version, and the only version this process can vouch for is its own daemon-release stamp, not the agent's. Wiring the announcer without them yields a no-op that reads as configured, so it stays unwired until component self-reporting exists. |
| `SetShowToolCalls` | Projected from `[chat].show_tool_calls`. |
| `Reload` | Local: re-resolves the token and allowlist from this service's own config file and overlay. Reload was never a daemon fact. |
| `RunningVersions` | **Wired from this process's own release stamp** (`archie-core-ot33`; see the amendment below). `archie-messaging` is one of the processes in the archied release set (the installer's `GATEWAY_SERVICES`), built from the same `archied/v*` tag and stamped with `buildinfo.Version` by every build site, so its compiled-in build is evidence that the release the installer claims actually reached this host. It reports `daemon = buildinfo.Version` and reports nothing for `agent` (task-scoped, observed only through `daemon.AgentStatus`), leaving the agent Unverified. The Gateway's rendered block is deliberately not used: that is a different process's stamp. |
| `Dangerous` | Stays nil. No daemon composition ever set it; `/rollback` and `/stop` reported "not configured" before the extraction and still do. |
The Messaging Service consequently reads `work_dir`, `bot_user`, `[chat]` and
`[health]` in addition to the PRD's `[chat.*]` / `[services.gateway]` list.
`[health]` is the daemon's health URL, which `releaseupdate.CommandInstaller`
polls from outside to confirm an update came back up; the rest of the PRD's
prohibition list is untouched.
**Amended 2026-10-02 (`archie-core-ot33`, Telegram `RunningVersions`).** The
2026-09-19 decision left `RunningVersions` nil because it judged this process
could obtain only another binary's stamp. That was true when written and stopped
being true three days later: `ec0f17a7` (`archie-core-k94o`) gave every host
binary, `archie-messaging` included, a `buildinfo.Version` self-report so the
updater could detect per-binary skew. `cmd/archie-messaging` now registers
`buildinfo`'s `-version`, and every build site (`install.sh`,
`scripts/archie-update-install`, `.github/workflows/deploy.yml`, `Taskfile.yml`)
stamps it with the same `archied/v*` release as the rest of `GATEWAY_SERVICES`.
The messaging process therefore vouches for the `daemon` component from
`buildinfo.Version` — its own compiled-in build, never the Gateway's rendered
block — and reports nothing for the agent. A relayed update report can now
confirm the daemon and still names the agent as unchecked, while a binary the
update did not replace reads as drift. `ReleaseAnnouncements` stays nil: it needs
a version for every component, and this process can vouch only for itself.
**Phase 4 messaging severance: what must move, and the decision the PRD does
not cover (2026-09-22, `archie-core-1ng1`).** The PRD's deletion gate cannot
pass today. `cmd/archie-messaging/architecture_test.go` does not exist, and the
check that section specifies -- `go list -deps ./cmd/archie-messaging` links
zero banned runtime packages -- reported four at the time (the task store was
then `internal/store` over `modernc.org/sqlite`; the gate now bans
`modernc.org/sqlite`, `github.com/jackc/pgx` and
`internal/infrastructure/postgres` in its place):
| banned package | PRD category |
| -------------------------- | -------------------------------------------------------- |
| `modernc.org/sqlite` | State Store |
| `internal/store` | State Store |
| `internal/domain/workflow` | Workflow engine |
| `internal/agentexec` | Workflow engine, via `internal/domain/workflow/agent.go` |
All four arrive through one import: `internal/app/archiemessaging/run.go`
imports `internal/app/controlplane`, whose own dependency set is exactly those
four. The Messaging Service uses three symbols from that package
(`NewRPCClient`, `RuntimeChatConfig`, `ChannelSettingsKind`); the package also
carries the store-backed `ResourceStore` server, the `Definition` registry and
the workflow step vocabulary. Sever the package. Amending the gate to tolerate
`modernc.org/sqlite` and `internal/store` is rejected: a boundary you whitelist
around is no longer a boundary.
**What moves.**
- Every kind constant. They are strings with no dependency, and the client names
them.
- The channel-settings vocabulary and its decode: `channelSettings`,
`telegramSettings`, `webhookChannelSettings`, `emailSettings`,
`rateLimitSettings`, `channelDuration`, and `decodeRenamingLegacyKeys`.
- The generic client: `Client`, `NewRPCClient`, `RuntimeConfig` with
`runtimeConfigFrom`, `runtimeChatConfigFrom`, the other `runtime*From`
projections, and the `resourceReader` interface.
- The persona watch (`WatchPersonas`, `AppliedPersonas`), which needs only
`internal/domain/agent`.
- `executionSettingsDocument`, the document alone.
**What stays, and why.**
- The store-backed server: `Server`, `NewServer`, `ResourceStore`,
`ImportConfig`, `SeedSkip`, the `Definition` registry, and every other kind's
seed, validator and `Normalize` hook.
- `WorkflowDefinitionsClient` and `stepRegistry`, which decode through
`internal/domain/workflow`.
- `WatchWorkflowExecutionSettings` and `decodeSettings`: `decodeSettings`
returns and validates `workflow.ExecutionSettings`, so any package holding it
links the workflow domain and therefore `internal/agentexec`. This is why the
client cannot move as one package -- see open question 2.
- The schedules document, whose type is `scheduling.JobSpec` in
`internal/domain/scheduling` -- the vocabulary moved there when the legacy
file-backed cronstore was deleted, which is also what satisfies the rule
that a domain vocabulary package may not import infrastructure.
- The schema derivation, which describes the documents the server advertises.
**Placement as landed (2026-09-22, `archie-core-1ng1`).** One new package,
`internal/infrastructure/controlplanerpc`, holding both the vocabulary (kinds, the
channel-settings document and its decode) and the client
(`NewRPCClient`, `Query`, `RuntimeChatConfig`, the exported `ResourceReader`, the
wire sentinels and `ClientError`). A second `internal/domain/controlplane` package
for the vocabulary was planned and then measured out of the design: the vocabulary
has exactly one consumer, the client that projects it, and the store-backed side
reads the same definitions through type aliases rather than a copy -- so a separate
domain package would have been a package with one consumer and a second name for
one thing. What made that safe is a measurement, not a preference:
`internal/app/controlplane` was the ONLY direct import of the Messaging Service
that dragged a banned runtime (`gatewayrpc`, `staterpc`, `applystatus`, `messaging`,
`configuration`, `readiness` and `health` were all clean), so severing that one
dependency is sufficient, and the severance needed no third package. Promoting the
vocabulary to a domain package stays open for the day a second consumer appears.
**Settled by the implementation.** Two of the four open questions this decision
originally left are answered, in both cases by measuring rather than by preference:
- The client did NOT become two packages. `WatchWorkflowExecutionSettings` and
`WatchPersonas` stayed on `internal/app/controlplane`'s `Client`, which now
_embeds_ the new one, so the daemon's validated watch is still defined once and
the read path still has one implementation -- which is what the second package
was for -- with one fewer package to keep in step.
- The schedules and workflow documents stayed put, and
`internal/domain/workflow/task` is linked deliberately: it carries the Task
status and view vocabulary, its own dependency set holds none of the banned
runtimes, and `cmd/archie-messaging/architecture_test.go` carries it as an
exception checked in both directions (the same entry, for the same reason, as
`cmd/archie-ui/architecture_test.go`).
**Still open.**
1. Does the server also leave `internal/app/`? `organisation.md` reserves
`internal/app/` for wiring and composition, and a store-backed gRPC server is
infrastructure -- but the gate does not require the move, and it would multiply
the diff across archied's wiring and the State Store binary. Tracked as
`archie-core-8f4n`.
2. Does `internal/domain/workflow`'s contract/engine split happen, and when? A
contract type (`WorkflowDefinitionCollection`) drags `internal/agentexec` only
because `agent.go` sits beside it. Independent of this severance, tracked as
`archie-core-inh6`, and the shape `archie-core-8cda.7` will meet again.
3. Does the vocabulary move to a domain package when a second consumer appears?
**Both consumers keep compiling.** archied imports the new vocabulary for the
kinds it names and the new client package for `RuntimeConfig` and the persona
watch, and keeps `internal/app/controlplane` for the server, the registry,
`ErrVersionConflict` and the workflow-aware pieces. The State Store binary
continues to call `NewServer` and `ResourceStore` unchanged. The Messaging
Service then imports only `internal/infrastructure/controlplanerpc`,
`gatewayrpc` and `staterpc`, so `go list -deps ./cmd/archie-messaging` loses all
four banned packages and the gate can land green.
**Channel state to the dashboard: one administrative surface, following the
config-snapshot precedent (2026-09-22, `archie-core-8cda.6.8`).** The Messaging
Service now records its channels' lifecycle -- `internal/channels/status.Manager`,
one entry per composed channel, written by each channel's own report through
`channels.Lifecycle` -- and nothing reads that across a process boundary.
`/api/channels` answers with nothing because `webui.Server.Channels` has no
production source, and POST `/api/channels/{id}/reload` answers 501 for the same
reason. The carrier is the State Store, and the shape is the one
`archie-core-ymut` already established for config snapshots
(`docs/prds/state-store-contract.md`, "the one surface whose writer is the daemon
and whose reader is the UI process"): a pair of administrative RPCs, deny-by-default
under `authorizesTaskScopedCall`, so a task-scoped grant reaches neither.
What that decides, so the implementation need not invent it:
- A channel's state is **runtime** state, not a settings document. It does not
belong in the `ControlPlaneService` resource kinds, which are validated,
versioned documents seeded from config; a channel that is failed is not a
document anybody edits.
- The reader is the UI process, which already dials the State Store and pumps its
cursor, so the surface needs no new transport in either direction.
- Adding the pair changes the contract's RPC count, so
`docs/prds/state-store-contract.md`'s grouped table gains a group in the same
change that adds the RPCs -- the table is the contract's own index, and a
surface it does not list is a surface nobody finds.
**Reload gets its own surface, with its own lifetime (decided 2026-09-22).** Reload
runs the other way -- the UI asks the service to reload a channel -- and the two
candidates were a request surface the service observes and clears, or a field on
the status surface the service watches. It is the first. The reasoning, recorded
because it would look arbitrary later:
- A request queue and a status report do not share a lifetime, so they should not
share a surface. A pending request is transient and has an outcome; a channel's
state is durable and has a current value.
- A "please reload" field on the status resource makes READING status capable of
RETRIGGERING an action, and makes a transient request indistinguishable from
state the moment anything polls it.
- It would also invert the writer/reader relationship the precedent establishes:
the service would have to clear a field on an object whose whole contract is
that the service reports it.
So the status surface stays writer-is-service, and the request carrier is its own
object with its own states.
`archie-core-8cda.6.9`'s component self-report is the **same shape**: a process
reporting something about itself for the UI to read. Whether it shares this
surface or gets its own is a decision for `6.9`, and the one outcome to avoid is
two homes for "what a component reports about itself".
### 3. Identity data migration
The migration must define:
- the durable identity schema and repository implementation;
- bootstrap of the permanent system identity;
- stable IdentityIDs for existing configured Agents;
- migration from configured identity names, empty-string ownership, and bot
usernames;
- preservation of historical attribution;
- identity-aware uniqueness and transport deduplication;
- correction of container and RPC capability resolution so execution uses the
owning identity's bindings;
- removal of identity-string equality from access-control behaviour.
Exact schema and method signatures are implementation decisions. The approved
Identity lifecycle and attribution semantics are fixed migration constraints.
### 4. Workflow migration
The current implementation must be transformed deliberately:
```text
store.Task -> WorkflowExecution
mutable Stage -> StepExecution history
RetryCount / Attempt -> Attempt records
workflow.Registry -> versioned Workflow definitions
current stages -> WorkflowStep definitions or Workflow plugins
```
The migration must decide:
- Workflow definition and version persistence;
- the smallest accepted-work-request contract consumed from Work Intake;
- the enforced WorkflowExecution state machine (proposed in
`docs/prds/execution-tree-state-machine.md`);
- atomic state and domain-event persistence;
- migration of existing task rows and transition history;
- disposition of current skill, Yaegi, and stage-plugin implementations;
- the versioned worker-handoff contract;
- scheduler, claim, retry, crash-recovery, and waiting-human cutover.
Workflow remains a separate domain from Agent. A user or Agent may define or
invoke a Workflow, but Workflow semantics and plugins remain Workflow-owned.
### 5. Memory placement and storage
The four required scopes are fixed:
- global shared;
- Agent-wide;
- user-wide;
- Agent-user relationship.
A focused review of `internal/memory`, its providers, consumers, persistence,
and tests had these decisions:
- `internal/domain/memory` versus ownership within the Agent domain — settled
(2026-09-02, below);
- the authoritative memory record and revision model — settled by the PRD
(2026-09-16, below);
- provider and infrastructure boundaries — settled by the PRD (2026-09-16,
below);
- retrieval and access enforcement — settled by the PRD (2026-09-16, below);
ranked retrieval remains open (below);
- migration of existing memory data — open: existing data is not migrated;
- provenance representation — settled by the PRD (2026-09-16, below).
Conversation branches do not create another memory scope. A memory action has
the same scoped effect regardless of which Conversation originated it.
**`internal/domain/memory` ownership — DECIDED (2026-09-02).** The typed
engine family lives at `internal/domain/memory`
(archie-core-1786637490069-11-e245c170), mirroring `internal/domain/curator`'s
contract/registrar/registry split. Not owned within the Agent domain: memory
is consumed by more than agent turns (curators, per archie-core-1786637499636)
and the plugin engine rule requires its own family, not a capability bolted
onto another domain's contract.
**Authoritative record and revision model for the builtin engine — DECIDED
(2026-09-02),** scoped to unblock archie-core-1786637499480 (ship the
file-writing store as the default engine). This decides only the builtin
engine's mapping onto the new `Record{ID}`/`Forget(id)` contract, not the
memory model in general or a future non-file engine's model:
- `internal/memory/builtin.Store` is unchanged. It has no concept of a
stable per-block ID — blocks are addressed by content substring — and nothing
in this decision requires changing that; existing `internal/memory` tests
keep passing unmodified, per that issue's acceptance criteria.
- A new infrastructure adapter (`internal/infrastructure/memory`, per
`organisation.md`'s "infrastructure implements domain contracts" rule — not
under `internal/domain/memory`, which stays contract-only) wraps one
`builtin.Store` per identity.
- **Identity → directory:** `hex(sha256(identity))`, not the identity string
itself. Closes the path-traversal question without an allowlist regex, and
sidesteps collisions from identities that differ only in characters a
filesystem treats as equivalent.
- **Record ID:** assigned once at `Write`, independent of content, so a later
edit elsewhere in the file can never orphan a `Forget`. Realised as a
leading marker line (`<!--mem:<ulid>-->`) on the block `builtin.Store.Add`
writes; `Query`/`List` strip it back out of `Record.Content` before
returning, and `Forget(id)` locates the block by that unique marker via the
store's existing substring-based `Remove`. The marker is a pragmatic,
reversible choice — plain-text records stay human-readable and
human-editable, at the cost of one marker line an operator editing the file
by hand should leave alone. Revisit if/when provenance representation
(still open, below) settles on something richer.
- **Kind → section:** `Observation.Kind` (default `"general"` when empty) is
the section name, reusing `builtin.ValidateSectionName` — so an
invalid `Kind` fails `Write` with the same validation error `memory_edit`
already returns for an invalid section today, not a new error shape.
**Memory engine: scopes, CRUD with retained revisions, and store placement —
DECIDED (2026-09-16).** Supersedes the 2026-09-02 "Authoritative record and
revision model for the builtin engine" entry above, whose `<!--mem:<ulid>-->`
live marker cannot carry provenance. Authority:
[`docs/prds/memory-engine-unification.md`](../prds/memory-engine-unification.md)
(Approved); the contract is `internal/domain/memory/contract.go`. This register
supersedes; it does not erase.
- **Four typed scopes, caller-named.** `internal/domain/memory` is addressed by
`Scope{Kind, Agent, User}` over `global`, `agent`, `user` and `agent-user`,
with `Validate` rejecting a component present where it is not required. A
caller names the read and write sets (`Subject.Scopes()` /
`WritableScopes()`; global is never model-writable) and the engine applies no
policy of its own: **access control is naming a scope, and nothing else.** An
engine that enforced policy would need to know about channels, sessions and
bindings, and every backend would reimplement it. `Scope.Key()` length-prefixes
each component, so two scopes can never share a key even when an opaque
channel-native id embeds the separator.
- **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 is supplied per channel by the composition. A webhook's sender id is
a route path, not a person, and treating it as one would give a URL an
identity. An absent user id yields global and agent scopes only: "show none of
it", never a wider fallback.
- **CRUD supersedes, never overwrites.** `Store` is `Create`/`Get`/`Query`/
`List`/`Update`/`Forget`/`Revisions` over the four scopes. `Update` appends the
superseded state to the scope's `HISTORY.md` before replacing the live block;
`Update.Expected` names the revision being replaced and returns
`ErrStaleRevision` on mismatch, making a lost update between two processes
sharing one scope file detectable. `Forget` records a deleted revision before
removing the live block, so a record's provenance outlives its content; `Get`
and `Forget` take a scope, because an id alone does not locate one.
- **Provenance representation.** The live marker becomes JSON, since a
`<!--mem:<ulid>-->` line cannot carry provenance, and `Record` retains the
provenance `agent-system.md` requires — scope, author, originating user,
source, and revision history. `Metadata` is dropped: it never round-tripped.
- **Store and scanner placement.** The markdown store relocates to
`internal/infrastructure/memory/builtin`, its correct home under
`organisation.md`'s "a package owns its on-disk format end-to-end". The content
scanner moves into `internal/domain/memory` and is applied in `Create` and
`Update` — the single choke point every producer crosses, so curator-extracted
content is covered too.
**Open in this section.** Ranked retrieval is deferred: `Query.Text` stays in
the contract, unused by the prompt path. Existing memory data is not migrated:
`<workDir>/memory` and `<workDir>/memory-engine` are left on disk, unreferenced.
The PRD leaves these undetermined and they remain open here: group-chat
extraction, where the curator fails closed on mixed-sender sessions; two
processes (`archied` and `archie-gateway`) holding one scope file, where
`Update.Expected` detects but does not prevent a lost block; unbounded
`HISTORY.md` with no compaction policy; whether the per-scope size bound is
right; and whether the dashboard should carry a user identity.
### 6. Runtime and process boundaries — DECIDED
`archied` is the native resident orchestration and interactive-chat process.
Every autonomous repository workflow crosses one full-task core-NATS handoff
into a task-scoped `archie-agent` container. Embedded versus external NATS
changes broker deployment only; it never selects an executor. The former host
in-process runner, per-stage NATS protocol, and subprocess runner are removed.
Forge, store, and worktree authority remains in `archied` and is exposed to the
task container through scoped RPC services. The worker runs the workflow and
its worker-local ai-sdk loop; it does not receive forge credentials or direct
store access. See `docs/prds/embedded-nats.md`.
**UI Service boundary — RATIFIED (2026-09-07).** Phase 3 has a focused
authority record in [`docs/prds/ui-service-boundary.md`](../prds/ui-service-boundary.md).
The UI Service owns HTTP/SPA delivery, UI DTOs, browser authentication, and
its own endpoint/credential/readiness settings. It consumes Gateway and State
Store contracts and does not receive `config.Holder`, daemon pointers, SQL or
store implementations, workflow registries, forge/channel/model runtimes, or
resolved secrets. The current `internal/webui` implementation remains inside
`archied` until the ratified migration gates prove route parity, adapter
selection, failure/readiness behaviour, and deletion of the shared-holder and
direct-access paths. The extraction cutover removes the in-process UI
listener in the same change; there is no dual-live UI authority.
**Dashboard live event delivery — DECIDED (2026-09-09, `archie-core-za9f`).**
The extracted UI receives live activity by polling the State Store's existing
`EventsSince` cursor, not by a new push-subscription RPC. No proto change, no
contract amendment beyond this record.
The UI process runs one event pump. It primes its watermark by paging
`EventsSince` to the end at startup without delivering, then polls
`EventsSince(watermark, limit)` on an interval and hands each new event to
`webui.Server.Broadcast`, exactly where `internal/app/archied/main.go`'s
`persistAndBroadcastEvents` hands events to it today. One pump serves every
connected browser, so cost is one indexed query per interval regardless of
viewer count, and `Broadcast` is a no-op when nobody is watching.
Three properties make the cursor sufficient, and a push hub unnecessary:
- **The cursor cannot skip.** `internal/infrastructure/postgres` takes an
advisory event-append lock around each insert (`TestEventInsertsCommitInIDOrder`),
so a row's `id` is assigned in commit order. There is no window in which a lower id becomes visible after a
higher one, which is the failure mode that normally rules out polling an
autoincrement cursor. SSE catch-up already depends on this same property.
- **A broadcast is a wakeup, not the payload.** `sseStream.drain` treats each
broadcast event as a signal to fill the persisted gap ahead of it via
`catchUp`, then delivers the event only if catch-up did not already cover
it, deduplicating on the `since` watermark. Substituting a poller for the
in-process bus therefore changes no SSE semantics, and needs no change to
`internal/webui/sse.go`. It also means a broadcast dropped to a stalled
client self-heals on the next one.
- **The table is the only complete fan-out point.** Events reach the store
through several paths that never touch the daemon's bus, including the
audit event `store.ArchiveTask` writes inside its transaction
(`internal/infrastructure/postgres/store.go`) and the binding-dispatch failure
`internal/daemon/daemon.go` inserts directly. A push hub would have to be
hooked at every write site and at post-commit, and would silently miss any
site added later that forgets to notify. Reading the table misses nothing.
The cost is one poll interval of latency on the activity feed, default 1s and
operator-tunable. That is accepted: the feed reports task lifecycle history,
and an operator action already gets its own synchronous HTTP response.
This resolves the `/events` row of the route-owner inventory in
[`ui-service-boundary.md`](../prds/ui-service-boundary.md). `/api/logs` and
`/api/logs/stream` are not resolved by it, they read the daemon's in-process
diagnostic feed and remain host-local (see `archie-core-8cda.5.4`).
Revisit only if sub-second feed latency becomes a requirement, or if a second
consumer needs the same stream, at which point the fan-out belongs in the State
Store process behind a `SubscribeEvents` RPC and this record is superseded.
**Dashboard configuration page — DECIDED (2026-09-09, `archie-core-ymut`).**
The configuration page becomes read-only in the UI process for Phase 3. Reads
cross the boundary as a published snapshot; writes are descoped, not
contracted. This amends the ratified boundary, which assumed a single admin
contract carrying both.
**Reads.** `webui.ConfigView` is already the whole answer. It is a UI-owned,
secret-free value projection built in `handleConfig`: `ProviderView` carries
the API key's environment variable name and a `Configured` boolean, never a
value, and `RepoView` is repository metadata only. It is already the exact
shape the browser receives. So the daemon publishes that projection, plus
provenance, reload status and the overridden-key list, as a snapshot the UI
reads; nothing new has to be designed, only moved. Two State Store RPCs carry
it, a `PutConfigSnapshot` restricted to the administrative token and a
`GetConfigSnapshot` the UI calls. The daemon republishes on boot and after
each successful reload, which is precisely when the projection changes.
The State Store is the right holder because a published configuration snapshot
is shared state, it is already dialled by the UI, and it costs no new listener,
port, token or interceptor. The alternative, a config admin service on
`archied`, would make the daemon a gRPC server for the first time. Today it is
purely a client of Gateway and State Store; `grpc.NewServer` appears only in
`RunGateway` and `RunStateStore`, which are the standalone binaries' entry
points, not the daemon's.
**Writes.** `PATCH /api/config`, `POST /api/config/reset` and
`PATCH /api/config/repos/{owner}/{name}` answer 503 in the UI process, and the
SPA hides those controls rather than offering a button that fails. Editing is
`config.toml` plus reload, which is already the only path for every setting
outside the runtime-tunable allowlist.
This is a deliberate feature reduction and worth naming as one. The write path
is not hard because of the transport; it is hard because the policy is
daemon-local and stays that way: `installUpdateConfigHandler` denies
non-runtime-tunable keys, applies a dotted overlay to a clone of the published
config, validates the materialised result, writes overlay rows, and rebuilds
provenance. Contracting that means either moving the policy, which the
boundary forbids, or exposing it verbatim as remote procedure calls, which
builds a Configuration Service inside a migration bead. Neither is work this
phase should be doing to keep one page's buttons alive.
Revisit when dashboard configuration editing is picked up as a feature in its
own right (`archie-core-1786637498420-327`, still open). At that point it gets
an admin contract designed as a feature, and the Configuration Service this
document already anticipates is its natural owner. Until then the UI renders
configuration and does not write it, which is what the boundary always said
about ownership even when it assumed a wider contract.
Amended 2026-09-11. This descope is a deferral, not a decision that the
dashboard should be read-only. Name it that way in review: the daemon-side
policy was built and tested, then deleted by the cutover (`e037b95` removed
`internal/app/archied/config_update.go` and its tests), so reviving it is
recoverable work, not a rewrite. `archie-core-j28m` carries the remaining
question -- which process serves the policy and what transport carries the
write -- and blocks the feature bead. The handlers, their error sentinels and
the `UpdateConfig`/`ResetConfig`/`UpdateRepoField` seams on `webui.Server` are
kept deliberately for it; `ConfigView.Editable` follows whichever process holds
`UpdateConfig`, so wiring that one field makes the page editable
(`archie-core-ml30`).
Implementation belongs to `archie-core-8cda.5.4`, the cutover that removes the
daemon's own dashboard. Nothing here is built yet.
**Superseded 2026-09-21 by the runtime control plane.** The open question this
descope left -- which process serves the policy and what transport carries the
write -- was answered by `docs/prds/runtime-control-plane.md`: neither a daemon
admin service nor a revival of the daemon-local policy. `ControlPlaneService` on
the State Store's existing gRPC server owns every database-backed setting, and
each feature validates its own resource, so there is no daemon-local policy left
to contract. `archie-core-j28m` is closed.
Consequently the three write seams described above no longer exist.
`PATCH /api/config`, `POST /api/config/reset` and
`PATCH /api/config/repos/{owner}/{name}`, the `UpdateConfig`/`ResetConfig`/
`UpdateRepoField` fields on `webui.Server`, and `ConfigView.Editable` were
deleted in `31622ec5` along with the runtime overlay store they wrote to.
`GET /api/config` remains a read of the published projection, as this decision
always intended.
### 7. Shared mechanics
The following cross-domain mechanics require exact contracts before dependent
packages migrate:
- event-bus delivery and failure semantics;
- policy evaluation API, composition, and precedence;
- configuration candidate preparation, health validation, atomic promotion,
observation, and rollback;
- service-specific health, bounded remediation, isolation, and escalation;
- changelog association and grouping.
These shared mechanisms do not acquire ownership of domain meaning. Domains
continue to own their commands, events, policies, settings, and consequences.
The Go documentation generator, its output placement, and drift checking are
defined in `generated-documentation.md`. The external Astro website consumes
the committed documentation and release JSON artifacts and serves them under
`offloaded.dev/docs/`. This repository owns the source and artifact checks; the
website repository owns rendering and deployment. The generators and
Archie's normalised documentation model remain migration work rather than open
product architecture.
**Amended 2026-09-15.** `internal/infrastructure/servicediscovery/nats`
implements the `servicediscovery.ServiceRegistry` contract (Connect, Register,
Resolve, Watch) over NATS KV and is fully tested, but no production code
constructs it and no config surface exposes it. This is a deliberate deferral,
not an oversight: service-to-service addressing belongs to the runtime and
process boundary work in section 6, which currently pins container addressing
by injecting the daemon's startup NATS URL rather than resolving through a
registry. The scaffold is kept for that work; re-derive it only if the
addressing model changes.
### 8. Cutover sequence
The final migration plan must order:
- compatibility adapters;
- schema migrations and data backfills;
- any required dual-read or transitional paths;
- domain-by-domain package replacement;
- production wiring changes;
- legacy package removal;
- architecture tests preventing dependency regression;
- focused, integration, race, and full quality gates.
Each legacy package requires objective removal criteria. No compatibility path
may become an indefinite second implementation.
## Completion criteria
Migration design is complete when:
- every current package has one approved owner and destination;
- every mutable record has one authoritative owner and migration path;
- all external and cross-process contracts have versioned owners;
- existing behaviour and data have explicit parity requirements;
- process boundaries have evidence-backed justification;
- the cutover order preserves a working application;
- legacy deletion criteria and deterministic architecture tests are defined;
- no unresolved decision requires an implementer to invent domain semantics.
Exact Go APIs, SQL statements, and mechanical refactoring steps MAY be finalized
during implementation when they do not change these semantics.
## Recorded migration position (2026-07-29)
Recovered 2026-08-09 from the pre-migration issue tracker. This section records
decisions the maintainer approved that the repository did not otherwise capture.
**Completed:** `internal/infrastructure/eventbus/nats` (rebuilt, not relocated);
`internal/infrastructure/configuration` (loading moved out of `internal/config`,
which is now types-only and does no I/O); `internal/eventbus` (broker-neutral
contract); `internal/domain/workintake` (the first `internal/domain/` package,
owning `TaskEnvelope`, the routing `Kind`, the label vocabulary, and task
subjects).
**DECISION — private input DTO deferred (approved).**
`configuration.Document.Config` is still `internal/config.Config` rather than the
private per-domain input DTO this document mandates. Building an ~800-line
parallel type tree while every consumer still reads `config.Config` would mean
two shapes kept in sync by hand, with no consumer for the new one. It is named as
a field so the compromise is visible at each use site, with the deletion
condition recorded in that package's `doc.go`. Do this **with** the
`internal/config` dissolution, not ahead of it.
**Agreed next: `internal/app/{archied,agentworker}`.** `run()` in
`cmd/archied/main.go` is ~460 lines, against `organisation.md`'s rule that
`cmd/*` must not contain substantive wiring or act as a service locator. It is
also the last non-infrastructure holder of the NATS SDK, and it is where the
config DTO translation will land, so it unblocks the dissolution above.
**Method constraint.** Do not write a separate recorded package-review document
per area when the decisions are already dictated by
`dependencies-and-contracts.md`. That is the ceremony pattern this project
deliberately avoids.
## OPEN — `[chat.*]` config section naming
`configuration.md:160` already states the position: `ChatConfig` holds "separate
channel instance settings... there is no chat-wide settings owner". The config
section name has not followed, so a settings block named for a product surface
owns what the architecture calls channel state.
Two candidates, neither settled: `[channel.*]` and `[messaging.channel.*]`. The
second reads as a domain path, and no config section in this repo is currently
named after a domain package, so adopting it sets a precedent for every other
section rather than fixing one name.
Blocked on a maintainer decision, not on evidence. This is a rename with an
operator-visible TOML break, so it should land with the `internal/config`
dissolution recorded above rather than on its own.
-337
View File
@@ -1,337 +0,0 @@
# Task Observability
**Status:** Implemented. The per-run detail surface was added on 2026-09-18 and
is described below.
**Date:** 2026-08-09 (revised 2026-09-18)
## Historical problem
archied's own daemon logging (`internal/logging/`) was already solid: a
rotating file sink, a live `Feed` the dashboard subscribes to, and a reader
the `/api/logs` endpoint serves from. Before this implementation, none of
that reached inside a task.
A task's actual work happens in a task-scoped `archie-agent` container,
dispatched as one complete workflow over NATS.
Before this design was implemented, five things destroyed the evidence of what
that container did:
1. **Worker startup** constructed an stderr-only logger and never replaced its
handler after discovering a dedicated boot task, so runtime records could
not leave the container.
2. **`internal/container/pool.go`** creates every task container with
`AutoRemove: true`. The container — and its stderr — is gone at exit,
success or failure alike.
3. **`internal/domain/workflow/implement.go`, `StageBaselineGate`** captures
`go build`/`go vet`/`go test` output via `cmd.CombinedOutput()`, then
clips it to 200 characters into a `Warn` log line and discards the rest.
The eventual park reason is built from `res.Status` alone — the actual
compiler error is never persisted anywhere a human or Archie's own chat
tools can read it back.
4. **`agentexec.Result`** (`internal/agentexec/protocol.go`) carries only
`Summary`/`Detail` — no step-by-step transcript (tool calls, durations,
errors). There is no transcript to recover even in principle.
5. **`agentexec.SubjectForSystem`** is documented as the return channel for
exactly this — _"log dumps, health, and PII warnings... the daemon reads
these for observability and never forwards them"_ — but has no publisher
and no consumer anywhere in the codebase except a subject-format
assertion in `nats_test.go`. The designed return path was never wired.
The practical consequence: a task parks with
`stage baseline: baseline red -- go build ./... fails and builder could not
auto-fix (status: parked)` and there is no way — not from the dashboard, not
from Telegram chat, not by SSH'ing into the deployment host — to see _why_
`go build` failed. The container that knew is already gone.
This matters beyond debugging convenience: supported deployments can combine
a resident daemon with ephemeral Docker containers that run unattended for
weeks between operator logins, and the system is
intended to be usable by people other than the original operator. A system
that is only debuggable by an operator who happens to be watching `docker ps`
in real time does not meet that bar.
## Decision: NATS is the sole autonomous handoff
The agent image must reach NATS in every deployment, because the broker is the
only autonomous task handoff and the only channel carrying task results back
to the daemon. `archied` has no workflow runner or host fallback. A container
that dies before establishing a NATS connection is a distinct, narrower
failure (connectivity/config) from the one this document addresses (a connected
container's own output being unrecoverable), and is out of scope here.
## Implemented design
The key property: **logs leave the container while it is alive**, so its
death at `AutoRemove` no longer matters. Persistence happens in the daemon
process, which already owns durable state.
### Sink: extend `internal/logging`, not a new package
`internal/logging` already owns its on-disk format end to end per
`organisation.md` ("a package owns its own format end to end"). Add a
task-scoped writer producing the same `logging.Entry` JSONL shape at
`<state_dir>/logs/tasks/<task_id>/attempt-<n>.jsonl`. `logging.Tail`,
`logging.Query`, and `logging.Components` operate on this unchanged;
`internal/webui/api_logs.go` stays transport-only, as it does today.
### Agent side: make the designed subject real
`internal/app/agentworker` replaces the stderr-only `slog.Handler` with one
that tees to stderr (kept for container-level operator debugging when a
shell is attached) and publishes each record to
`agentexec.SubjectForSystem(taskID)`, which already exists for this purpose.
The application layer obtains only a narrow publisher from
`internal/infrastructure/agenttransport/nats`; raw core-NATS types remain in
infrastructure. `internal/infrastructure/agentboot.TaskID` reads the task ID
from `<worktree>/.git/task.json` per the container/pool.go trap documented in
`CLAUDE.md`. Publishing is fire-and-forget: log shipping must never block or
fail the run it is reporting on.
### Daemon side
`cmd/archied/main.go` registers `subscribeSystemLogs` once at startup on
`agentexec.SubjectSystemWildcard`. It demultiplexes by task ID, appends to that task's
sink, and publishes into the existing `logging.Feed` so live task output
appears on the dashboard exactly like daemon output. The approved target is
for this composition to move to `internal/app/archied`; that package does not
yet exist, so this document does not claim the migration is complete.
The daemon is also a writer in its own right for the decisions only it makes.
Every park records its reason into that attempt's sink (`daemon.recordPark`),
on the daemon side after the guarded transition lands and in
`workflow.park` on the agent side, because "why did this park?" is the question
the log exists to answer and the container path cannot answer a run that never
reached a container. The entry is written only once the park actually
happened, so a transition another actor won does not leave a log claiming an
outcome the task board contradicts.
### Gate output: stop discarding it
`StageBaselineGate` and the equivalent TDD-stage gate runs write full
`cmd.CombinedOutput()` to the task's sink under a `gate` component, and put a
bounded tail (~2KB, not 200 bytes) into the park reason. This is the cheapest
fix and independently valuable — it alone would have made the `go build`
failure diagnosable without any NATS plumbing.
### Transcript
Step-level events (tool name, argument digest, duration, error) are emitted
as log entries on the same NATS system subject rather than added as new
fields on `agentexec.Result`. This keeps the wire protocol
(`internal/agentexec/protocol.go`) stable and the transcript lands in the
sink automatically, with no separate delivery path to keep consistent.
### Retention
Reuse the existing rotation (`MaxSizeMB`/`Keep`) semantics per task
directory. Prune a task's log directory when `store.ArchiveTask` archives
it, so task logs share the task's own
lifecycle rather than accumulating independently.
### Surfaces
- `/api/tasks/{id}/logs`, built on `logging.Reader` the same way
`/api/logs` is today.
- A chat tool so Archie can answer "why did task 4 park?" directly from
Telegram or the webui chat — this is the surface that actually matters
for the deployment model in `CLAUDE.md`, where an operator may not be
looking at a dashboard at all.
- The per-attempt read surface described in the next section, on top of the
same task-scoped stream.
## Per-run task detail (attempts, stages, changes, config)
**Status:** landed, together with the change set that carries this revision
(workflow run `76f8e877`). The provenance half is in the tree: `events.Event.Attempt`,
the `changes_captured` and `config_captured` event kinds, and the two protobuf field
additions. So is the read half: the three per-attempt endpoints
(`/api/tasks/{id}/attempts`, `/changes`, `/debug`) and the dashboard run-detail page
that consumes them. The decision record, the rejected alternatives and the honest
limits are `docs/prds/task-run-detail.md`.
The task log surface above answers _why did this park?_. This surface answers
_what did this run actually do?_, per attempt.
### Attempt attribution
One task can run many times, and the task's event stream is the durable record
of all of them. `events.Event.Attempt` attributes each event to one run; `0`
means **not attributable** — every event written before this change, plus the
deliberately task-agnostic producers. An unattributed event is reported as a
count and is never presented as an attempt.
Attribution is a column, not a fold over `task_queued`/`task_retried`: a fold
would have to guess which side of a boundary an event belongs to across a daemon
restart, a stale-run recovery, or two interleaved attempts, and a guess rendered
as structure is exactly the false fidelity this surface exists to avoid.
The column is part of the events table in
`internal/infrastructure/postgres/migrations/0001_state_store.sql`, and nothing
is backfilled.
### Read surface
The routes are registered beside the existing task routes in
`internal/webui`'s `registerTaskRoutes` and all resolve the task through the
store's `TaskByID`; a task that does not exist is a `404`, never a `200` with an
empty body.
- `GET /api/tasks/{id}/attempts` — every attempt with its stages inline, so the
rail and the attempt selector can never disagree. Stages are ordered by
occurrence within their attempt. An attempt with no stages is legitimate and
renders as "no stages recorded", never as an unexplained empty rail.
- `GET /api/tasks/{id}/changes?attempt=N` — the change captures for one
attempt, ordered by capture time; more than one per attempt is normal (a
mid-workflow commit such as TDD's `commit-repro`, then `commit-push`, then a
final `open-pr` capture that carries the pull-request number).
`found: false` means no capture was recorded for that attempt, which is
**not** "no files changed"; a capture that was recorded but could not be read
is reported as exactly that, and never as a diffstat of zeroes.
- `GET /api/tasks/{id}` — unchanged: the raw event array, each event now
carrying `attempt`. The per-attempt configuration is read from this response,
selected by kind **and** attempt.
- `GET /api/tasks/{id}/logs` — gains `stage` beside its existing filters. The
match is exact and case-insensitive, and an entry that records no stage never
matches (see `logging.Query.Stage`).
- `GET /api/tasks/{id}/debug?attempt=N` — the stored task record and the task's
events, deliberately unfiltered, so an operator can attribute everything the
task did even when a panel has nothing to show.
The `attempt` parameter follows one rule on every route: absent or `0` selects
the task's current attempt, and the resolved attempt is echoed in the response.
### Stage status
`stage_start` and `stage_finish` are the only inputs, so the derivation is
explicit and each case is pinned by a test:
| Events seen for the stage | Reported |
| ------------------------------------------------------------------------- | -------------------------------------------------- |
| `stage_finish` with `data.error` | `failed`, with the error text |
| `stage_finish` with `data.interrupted` | `interrupted` |
| `stage_finish`, neither | `ok` — "returned without error" |
| `stage_start` unmatched, and this is the task's current in-flight attempt | `running` |
| `stage_start` unmatched on any dead attempt | `interrupted` — the run ended without finishing it |
| `stage_finish` with no matching start | the stage, with no start time invented |
| no stage information at all for that attempt | `unknown` |
**There is no exit code.** `stage_finish` carries a duration and an optional
error string and nothing else, so no stage can be shown as pass/fail and the
page must not imply verification. A stage that finished cleanly and then parked
stays `ok` on a failed task, which is why the attempt status is read together
with the task status rather than on its own.
### Changed files
The change an attempt produced is read from the worktree at the moment it is
committed or pushed, and persisted as a `changes_captured` durable event — plus
one final capture when `OpenPR` records the pull-request number, which is the
only point at which a capture can carry one. It has to be captured there: the
worktree is deleted on merge, close and no-PR terminal states, a retry resets
the branch onto its base, and no forge contract exposes a changed-file read.
`internal/domain/workflow/task/changes.go` owns the value types and the status
strings they persist.
- One capture carries per-file `added`/`modified`/`deleted`/`renamed`/
`typechange` status with added and deleted line counts, and totals.
- Each capture names its schema (`archie/task-changes@1`, in `internal/events`)
and a reader refuses a payload whose schema or key set it does not know,
rather than rendering the zero value of every field it could not find. That
refusal surfaces as "a capture was recorded but could not be read", which is
a different statement from "no capture was recorded".
- `base_sha` is the merge base the file list was diffed against, not the base
branch's tip, so the pair describes one change set even when the base branch
moved during the run.
- `files` is capped; `totals` always covers the **full** set, and a truncated
capture says so rather than silently dropping entries.
- `binary` means "no textual hunks" — never a claim about the file's type on
disk — and a path the repository recorded as a rename pair is reported as the
repository recorded it.
- Capture **degrades and never parks**: an implementation without the capture
seam captures nothing, logs, and lets the run continue.
### Per-attempt configuration
The effective configuration an attempt ran under is persisted as a once-per-
attempt `config_captured` durable event carrying the schema constant
`archie/task-config@1` and the non-secret task-runtime subset from
`config.Config.ForTask()`. It is not stored in a table and has no endpoint of
its own: the dashboard reads it out of the events response it already fetches.
The single-row `config_snapshot` table is left alone — it answers what the
running configuration is now and is replaced on every publish.
Redaction is proven positively by a test that builds a full configuration
containing canary values and asserts none of them survive serialising, rather
than being inferred from the producer's contract. The timeline carries one
human line for this kind; the document itself is rendered by the panel.
**Trust boundary, stated honestly.** 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 could in principle write its own `config_captured` event. This widens no
capability, because 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.
### The wire
The whole wire change is two fields on existing messages: `Event.attempt`
(field 11) and `ReadTaskLogRequest.stage` (field 9) in
`proto/state/v1/state.proto`. No RPC, no table and no configuration field was
added, so the ratified state-store contract in
`docs/prds/state-store-contract.md` rev 2c is unchanged.
Version skew degrades instead of failing, and each degrade is a statement the
page has to make rather than hide: an old server makes `attempt` read as `0` and
`stage` match nothing, so the page says it cannot attribute events to attempts
instead of labelling the whole stream "attempt 1"; an old client sees
`config_captured` as an unfamiliar kind, and the panel must then say it cannot
read per-run configuration — a different claim from "not captured for this
attempt".
### Rules the surface keeps
- "No record" and "this deployment cannot read this" stay different answers,
for logs and for configuration alike.
- No run-duration figure is shown. A run can spend days in `waiting_human`, so
one number would understate wall time; per-stage durations only.
- No duration is invented for a stage with no start; it reads "not recorded".
- The stage filter is a narrowing, not a coverage claim: agent and tool output
carries no stage and is never matched, and the pane says so beside the
control.
- An attempt predating the change shows "not captured for this run" for its
configuration and its change capture, never an empty view that implies
defaults applied or nothing changed.
### Failure and rollback
Every part is additive. A capture or a configuration emit that cannot happen
leaves the run alone — reporting must never park a task. Reverting the change
set removes the endpoints and the page; the extra column and the extra event
kinds are inert to the previous revision (a column no statement names is
ignored, and an unfamiliar event kind already renders as unfamiliar), and there is
no data transformation to undo.
## Dependency direction
`internal/logging` remains cross-cutting per `organisation.md` — it imports
no domain, infrastructure, or app package, so extending it to be task-scoped
does not change its classification. The workflow domain writes through the
cross-cutting logging contract. On the agent side,
`internal/app/agentworker` composes the narrow publisher supplied by
`internal/infrastructure/agenttransport/nats`. On the daemon side,
`cmd/archied/main.go` currently composes the NATS subscription with the task
sink until the approved `internal/app/archied` migration is implemented.
## Implementation sequence (completed)
1. Gate-output capture (~30 lines, no NATS changes) — fixes the immediate
symptom that prompted this document.
2. Task log sink in `internal/logging`.
3. Agent-side publisher on `SubjectForSystem`.
4. Daemon-side subscriber + `logging.Feed` integration + retention on
archive.
5. `/api/tasks/{id}/logs` + chat tool.
Tracked as GitHub epic/subtasks per the issue list linked from this
document's PR.
-101
View File
@@ -1,101 +0,0 @@
# Repository Organisation
**Status:** Approved
**Date:** 2026-07-28
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Target structure
Archie MUST be organised around cohesive application responsibilities:
```tree
cmd/
archied/
archie-agent/
internal/
domain/
<area>/
eventbus/
policy/
infrastructure/
configuration/
eventbus/
nats/
forge/
persistence/
<external-service>/
app/
archied/
agentworker/
plugins/
<plugin>/
deployments/
<supported-assembly>/
docs/
guides/
examples/
<copyable-example>/
extras/
<optional-extension>/
```
Domain names are chosen from application behaviour during package review.
Existing names MUST NOT be retained merely to reduce migration work.
## Domain areas
A domain owns one cohesive job performed by Archie. It contains that job's
language, state, rules, operations, commands, events, policy implementations,
runtime settings, and required service contracts.
Code that changes together SHOULD live together. Empty or ceremonial `entities`,
`repositories`, or `services` layers are prohibited.
## Application composition
`internal/app`:
- constructs domains and infrastructure implementations;
- translates external configuration into domain and plugin settings;
- connects commands, events, and shared contracts;
- starts services in dependency order;
- owns health aggregation and shutdown ordering.
`cmd/*` parses only process-level input and invokes the relevant application
composition package. It MUST NOT contain substantive wiring or act as a service
locator.
## Process boundaries
Archie begins as a modular monolith even when capabilities run in separate
processes. A domain becomes a separately deployed service only for a concrete
need such as security isolation, independent scaling, failure containment, or
independent operation.
Possible future extraction does not justify premature network protocols or
duplicated service scaffolding.
A new command is not a reason for a new binary. `cmd/` entries are process
boundaries: a binary earns its place when its surface fails independently of the
fleet, or when one process may need to run in more than one location, such as a
high-availability pair or across a NAT boundary. Operational commands over a
surface an existing binary already owns are subcommands of that binary. Offline
database maintenance belongs to `archie-state-store`, which owns the file and
its path layout, not to a new recovery binary.
## Optional and operational material
- `extras/<extension>` contains a maintained optional extension with real
behaviour. Core Archie MUST NOT import it, and removing `extras/` MUST NOT
prevent the core application from building or running.
- `deployments/<assembly>` contains a supported assembly, including deployment
definitions and concise operational instructions.
- `docs/guides/` contains handwritten explanation and links to generated
reference material.
- `examples/` contains copyable samples with explicit purpose, prerequisites,
and support expectations.
Supported assemblies SHOULD demonstrate that capabilities can be selected
independently.
-70
View File
@@ -1,70 +0,0 @@
# Domain and Feature Review Procedure
**Status:** Active
**Date:** 2026-07-28
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Purpose
Architecture work proceeds one domain or feature at a time. Before any design
question, the selected area is researched across its complete live
implementation, consumers, tests, state, configuration, and runtime wiring.
Existing packages are evidence, not the unit that drives the interview.
Placement follows behaviour and ownership, not the existing directory name.
No restructuring implementation begins until the relevant package decisions
are agreed and recorded in the focused domain or requirement document.
## Required research
Before design questions, the current-state report MUST identify:
- entry points and runtime composition;
- state, persistence, and lifecycle;
- public and internal contracts;
- commands, events, and policy enforcement;
- configuration and defaults;
- all consumers and cross-domain interactions;
- process and infrastructure boundaries;
- tests, failure behaviour, and known invariants;
- duplicated or conflicting implementations;
- documentation that disagrees with live code.
Discoverable facts MUST be investigated rather than presented to the user as
design questions.
## Required decisions
Each package review records:
| Decision | Required result |
| --------------------- | ---------------------------------------------------------------- |
| Owned behaviour | The cohesive job the code performs |
| Domain ownership | The owner of the behaviour and vocabulary |
| Final location | Its target path |
| Public contracts | The smallest interfaces, commands, and events exposed |
| Required services | Domain-defined interfaces implemented by infrastructure |
| State ownership | The owner of each mutable record and transition |
| Dependencies | Allowed imports and dependencies to remove |
| Duplication | Code to consolidate, delete, or keep separate |
| Plugin status | Core domain, shared contract, infrastructure, plugin, or extra |
| Process boundary | In-process, or the concrete reason for isolation |
| Configuration | Settings owned by the domain or plugin |
| Policy | Definitions, evaluators, consequences, and shared mechanics used |
| Documentation | Authoritative definitions and generated reference |
| Migration constraints | Behaviour and data that must remain correct |
## Interview method
For every selected domain or feature:
1. Declare the single area under review.
2. Complete the current-state research.
3. Explain actual behaviour in plain technical language.
4. Separate facts from design decisions and concerns.
5. Resolve obvious consequences directly and ask only questions whose answer
materially changes behaviour or structure.
6. Record each confirmed decision in its focused document.
7. Complete that area's handoff before selecting another.
8. Keep unrelated domains outside the implementation scope.
-188
View File
@@ -1,188 +0,0 @@
# Plugins and Extensions
**Status:** Approved foundation
**Date:** 2026-07-28
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Plugin framework
The core plugin domain lives under `internal/domain/plugin`. It owns:
- plugin identity and metadata;
- discovery and registration contracts;
- lifecycle rules;
- capability registration;
- validation and compatibility rules.
The generic plugin contract remains metadata-only. Functionality is exposed
through narrow typed capability contracts with an owning registry or manager.
Workflow plugins belong to the Workflow capability family. The Workflow domain
at `internal/domain/workflow` owns their typed registration, validation,
versioning, definition, and execution contracts. The generic plugin domain may
provide plugin identity, discovery, compatibility, and lifecycle mechanics, but
it MUST NOT define Workflow semantics or expose untyped Workflow hooks.
## Plugin engine rule (strict)
“Engine” is reserved for a typed, lifecycle-managed capability family. It is not
a synonym for a generic plugin hook. Every new plugin engine must satisfy all of
these invariants:
1. **Typed domain contract.** The engine interface exposes real
capability-specific operations in addition to identity metadata. Examples are
resolving a secret, delivering a message, or running an agent. A plugin that
only exposes `Name` and `Version` is metadata, not an engine.
2. **Owning family manager.** The capability package owns a `Registry` or
`Manager` that controls provider registration and discovery, initialisation,
or access. Providers do not register arbitrary callbacks directly on the
daemon.
3. **Lifecycle and health.** When an implementation owns resources or background
work, its typed family contract must expose start, health, and stop
semantics. The owning manager invokes them and defines failure isolation and
shutdown ordering. Stateless providers may make these operations explicit
no-ops.
4. **Narrow host access.** Plugins receive the typed family registrar and only
the host services their declared capability requires. They never receive
`*daemon.Daemon`, a service locator, or an untyped hook map.
5. **Metadata-only generic plugin contract.** `plugin.Plugin` remains limited to
`Name()` and `Version()`. Domain hooks belong on typed engine interfaces;
adding capability methods to the generic interface is forbidden.
6. **Trust boundary stays explicit.** Explicitly trusted, operator-installed
plugins—including third-party secret-engine plugins the operator chooses to
trust—may run in-process and have daemon privileges. Repository-supplied code
runs in the task container. Integrations that are not trusted as daemon code
run out of process through MCP or a versioned protocol and, when a
confidentiality or integrity boundary is required, inside a real container
sandbox. A subprocess boundary alone is not a security sandbox, and calling
Yaegi-loaded code a plugin does not isolate it.
`internal/plugin/architecture_test.go` enforces the mechanically testable parts
of this rule: the generic plugin method set, the shared agent-instruction
source, and the requirement that engine interfaces have domain behaviour plus an
owning registry or manager.
### Memory engine family
One engine, addressed by four typed scopes -- `ScopeGlobal`, `ScopeAgent`,
`ScopeUser`, `ScopeAgentUser` (`internal/domain/memory`, `Scope`/`ScopeKind`).
A caller names exactly the scopes it may read or write; the engine applies no
access policy of its own, so isolation falls out mechanically because
`ScopeAgent{a}` and `ScopeAgent{b}` are different storage keys. See
`docs/prds/memory-engine-unification.md` for the decision this contract
implements; it superseded `internal/memory` (`MemoryProvider`/`Manager`),
deleted in that PRD's slice 5.
`MemoryEngine` (`internal/domain/memory/contract.go`) is the typed family
contract: `Create`, `Get`, `Query`, `List`, `Update`, `Forget`, `Revisions` --
CRUD with revisions retained, not just create/read/delete. `Update` supersedes
rather than overwrites: the superseded state is appended to the scope's
`HISTORY.md` before the live block is replaced, and `Update` carries no
`Scope` field, so a record can never change scope. The family's content
scanner (prompt-injection / sensitive-data patterns) is applied inside
`Create` and `Update`, the single choke point every producer crosses.
`internal/domain/memory.Registry` is the owning family registry: registration,
start/health/stop, shutdown ordering, and failure isolation, following the
plugin engine rule above. `internal/infrastructure/memory.NewBuiltinEngine` is
the only registered engine today; it persists through
`internal/infrastructure/memory/builtin`, a markdown store (`MEMORY.md`-shaped
per-scope files) that owns its on-disk format end-to-end.
Two per-turn seams in `internal/gateway` connect a chat turn to the engine,
each narrowed to exactly the operations it needs:
- **Read** (`turn_memory.go`, `MemoryStore`): `prepareTurn` runs a
scope-only `Query` over the resolved `Subject`'s readable scopes,
synchronously and before the prompt is built. It never returns an error --
a panicking or failing engine degrades to an empty `<memory>` block rather
than failing the turn -- and is bounded by a per-scope record limit and a
byte cap on the rendered block.
- **Write** (`turn_memory_tool.go`, `MemoryWriteStore`): four tools --
`memory_create`, `memory_update`, `memory_delete`, `memory_list` -- built
per turn onto the resolved `Subject`'s writable scopes, not registered once
at boot. The model chooses the scope kind; it never chooses the agent or
user id, which come from the turn's resolved `Subject` and have no schema
field to override. `ScopeGlobal` is never model-writable.
`boot.setupMemoryEngine` (`internal/app/archied/bootstrap.go`) registers and
starts the engine and must run before `setupGatewayChat`, which constructs the
only chat turn runner in production and captures the engine at construction
time (`internal/app/archied/composition_order_test.go` pins the ordering), and
before `setupCurators`, whose `Registrar` captures the engine registry. The
session curator (`internal/infrastructure/sessioncurator`) writes derived
records onto `ScopeAgentUser`, making it the engine's other live producer
besides the chat write path.
## Plugin implementations
First-party plugins are self-contained vertical modules under
`plugins/<plugin>`.
A plugin:
- owns its implementation, settings, templates, assets, and tests;
- receives only explicitly supplied contracts and services;
- MUST NOT receive daemon internals, a service locator, or unrestricted
application access;
- MUST NOT import arbitrary infrastructure or application composition code;
- MAY use approved domain and shared application contracts;
- MUST remain removable without changes to unrelated domains.
Plugins may be internally cohesive like small services. They do not become
network services without a concrete security or operational reason.
## Event sources and reactions
`archie-core-7d5u.1` asked whether extensions should react to events
in-process through typed capability families (this document's model) or
out-of-process like a generic `DispatchEvent` dispatcher. Decided 2026-08-22
in `docs/prds/event-sources-and-reactions.md`: in-process typed families,
confirming this document's model rather than amending it. The forge webhook
receiver (`internal/forge/webhook`; see "Intake provenance" in
`docs/architecture/messaging-and-work-intake.md`) and the EDA playbook engine's
Module action position
(`docs/prds/eda-playbook-engine.md`, `internal/domain/eda/module`) are the
shipped instances of that decision -- each is a narrow typed contract with an
owning registry, not a generic event hook. The playbook engine's Channel and
Forge action positions are designed but not yet implemented (open
investigation `archie-core-t2db.19`); when they land they follow the same
model, not a new one.
## Curator surprisal sampling
**Decided 2026-08-05, wave 1 landed 2026-09-05** — the curator engine family
(epic [#435](https://github.com/samcharles93/archie-core/issues/435)) selects which memories deserve agentic attention via
surprisal-based sampling: score memories by how surprising they are and
spend the sampled reasoner's agentic budget on the most surprising items.
The prerequisites are built: the embeddings capability
([#436](https://github.com/samcharles93/archie-core/issues/436), `internal/domain/embedding` contract +
`internal/infrastructure/embedding` implementation, config-driven via
`models.embedding`) and the wave-1 `Sampler` strategy seam
(`internal/domain/sampling` -- not `internal/curator`, see
`docs/prds/curator-sampler-wave1.md` for the settled design and tracking)
with four
cheap, embedding-free strategies (recency, random, all, staleness proxy).
No curator consumes a `Sampler` yet, and the embeddings client is likewise
deliberately inert: `setupEmbeddings` constructs it at boot and holds it on
`b.embeddings`, but no production code reads that field yet, so a resolved
`models.embedding` role currently produces a client whose only observable
effect is a boot log line. Both are prerequisites waiting on #437, not
unwired defects.
Still deferred: [#437](https://github.com/samcharles93/archie-core/issues/437), the embedding-backed surprisal strategy, which
depends on the above and on [#407](https://github.com/samcharles93/archie-core/issues/407). Requirements for that deferred work,
so it can be picked up without re-deriving the design:
- A `Sampler` implementation behind the same interface as the cheap
strategies; selection deterministic given fixed inputs.
- Algorithm: sample up to a candidate cap; build a k-NN graph over embedding
vectors; row-normalise the adjacency with self-loops; power-iterate to the
stationary distribution; surprisal = −log(stationary probability of the
nearest point); select the highest-surprisal items.
- Degradation: content without an embedding is skipped; an embedding failure
aborts sampling and falls back to free exploration — a sampling failure
must never fail or crash a curator pass.
- Cost bound: the graph build is quadratic in the candidate cap; the cap must
be a named constant with a documented bound.
-52
View File
@@ -1,52 +0,0 @@
# Policy System
**Status:** Approved foundation; exact API is deferred
**Date:** 2026-07-28
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Purpose
Retry limits, authorisation, gates, commands, protected paths, tool
availability, and similar rules define or constrain what Archie may do. They
need consistent consumption, composition, evidence, and audit without erasing
their different domain meanings.
## Ownership
`internal/policy` is an explicitly approved shared application contract. It is
not infrastructure and it is not a generic domain that owns every rule.
The shared policy system owns:
- policy identity, version, scope, and applicability;
- typed evaluation invocation;
- deterministic composition and precedence;
- common evaluation states such as satisfied, violated, indeterminate, and not
applicable;
- reasons and evidence;
- evaluation audit records;
- registration, discovery, and lifecycle.
Each consuming domain owns:
- its policy vocabulary and typed inputs;
- its concrete policy definitions;
- its evaluators;
- the meaning and consequence of an evaluation.
Access therefore owns principals, resources, actions, and authorisation
consequences. Task lifecycle owns retry eligibility and exhaustion. Task
execution owns gate requirements. Workspace mutation owns protected-path
effects. Tool execution owns tool and command constraints.
These policies use consistent evaluation mechanics without pretending their
decisions are semantically interchangeable.
## Infrastructure
Infrastructure MAY load, persist, distribute, and audit external policy
representations. It MUST NOT define what Archie allows or assign the meaning of
a domain policy result.
The exact Go API, composition operators, precedence rules, and representation
format require a focused policy design pass.
@@ -1,213 +0,0 @@
# Safe Change and Recovery
**Status:** Requirements approved; mechanics are under design. Database-backed settings are implemented through the control plane (2026-09): see the degrade/recovery section below, which records a gap rather than a solution. The full runtime-supervision protocol (bounded observation, versioned audit trail) remains under design.
**Date:** 2026-07-28
**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)
## Purpose
Archie is built and improved by agents as well as humans. The architecture MUST
make a change easy to locate, understand, test, audit, extend, and reverse
without requiring its author to understand unrelated parts of the application.
Separation of concerns is therefore an operational safety boundary, not only a
code-organisation preference.
## Required outcomes
- An agent can improve a focused feature without receiving authority over
unrelated domains.
- Every event, function, action, setting, and policy has an identifiable owner
and provenance.
- Source and runtime changes pass deterministic checks outside the actor making
the change.
- A rejected or unhealthy candidate cannot replace the last known working
version.
- Invalid user configuration does not terminate an otherwise healthy
application.
- Configuration and service failures are observable, attributed, and eligible
for bounded remediation or rollback.
- The application continues serving unaffected capabilities when one
capability is misconfigured or unhealthy.
- Recovery failure is reported and contained rather than hidden in an
unbounded retry loop.
## Source changes
Agent-authored source changes occur through the task-execution boundary in an
isolated workspace. The agent does not directly mutate the running
installation.
Promotion is controlled by deterministic repository-owned policy, including
tests, generated-reference drift checks, protected paths, change scope, and
other required gates. The actor proposing a change cannot waive these checks.
Repository and domain separation SHOULD allow a task to load and modify only
the governing requirements and code for its declared scope.
## Runtime changes
Configuration and other runtime changes are proposed as candidates rather than
mutating the active state in place.
The affected domain owns:
- the command describing the semantic change;
- validation of its typed settings;
- health signals that demonstrate correct operation;
- domain-specific remediation and rollback consequences.
Shared policy supplies consistent evaluation, evidence, and audit mechanics.
Identity supplies actor attribution. Infrastructure supplies external
configuration storage, service control, and other operational adapters.
## Runtime change protocol
Last-known-good preservation and candidate promotion are the universal runtime
change protocol.
1. An identity proposes an immutable candidate version.
2. Infrastructure parses it without changing active state.
3. Each affected domain validates its typed settings.
4. Shared policy evaluates cross-cutting constraints.
5. Each affected capability prepares the candidate without destroying its
active instance.
6. Capability-specific health checks prove the candidate works.
7. Runtime supervision atomically promotes the candidate.
8. A bounded observation period watches for delayed failure.
9. Failure restores the last-known-good version and records the reason,
evidence, actor, and involved versions.
10. Repeated remediation failure stops retrying, isolates the capability, and
reports the fault.
The affected domain owns the semantic change command, typed validation, health
signals, and remediation consequences. Shared runtime supervision owns the
promotion transaction. Infrastructure performs storage and service-control
operations.
The protocol's exact Go contracts, storage model, atomicity boundary, and
observation rules require a focused runtime-supervision design pass.
## Failure isolation
Invalid input MUST leave the active valid configuration unchanged and produce a
diagnostic record.
A capability that cannot start or reload SHOULD fail independently where its
absence does not violate a declared application invariant. Unaffected
capabilities continue operating.
Remediation MUST be bounded, observable, and policy-driven. Recovery MUST NOT
silently oscillate between versions or retry forever.
## Database settings: degrade paths and recovery (2026-09)
The control plane owns runtime-tunable settings and stores them in the State
Store's PostgreSQL database.
This replaced a dashboard overlay store that degraded to file config on any
failure and had three documented ways back. The replacement has none, and the
posture is the opposite: **the daemon fails closed.**
### Degrade paths
| Failure | Boot behaviour | Where the operator sees it |
| --------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------ |
| State Store unreachable | `boot.loadRuntimeConfig` returns the dial error and `archied` exits non-zero | stderr: `runtime settings unavailable` |
| A stored resource fails validation | Same: `validate database settings` wraps the error and the daemon exits | Same |
| SIGHUP reload with a bad file, or a control plane that cannot be read | Running config is kept; the reload records `last_error` / `last_error_at`. The reload re-applies the database layer, so it never publishes file values over the running database-owned ones | `/api/config` → `reload.last_error` → dashboard banner |
Failing closed is deliberate for settings the database owns: falling back to the
file values would restore the second source of truth the control plane exists to
remove. The cost is that a bad stored value stops the daemon starting, and the
value can only be corrected through the daemon's own API.
### Serving from Postgres
The State Store, the daemon and the Gateway serve from `database_url` only; an
empty value is a startup error. The embedded NATS store, its endpoint file and
task logs live under `state_dir` (default: the data home's `archie` directory).
The Gateway holds a Postgres serve-ownership claim for its whole life, so a
second Gateway against the same database refuses to start (its turn recovery
would fail the first one's in-flight turns). The State Store holds its own.
### Recovery: offline commands on the State Store
Nothing skips the control plane at boot, and the only writer for a resource is
`ControlPlaneService.Command` on a running State Store -- which is exactly what
the daemon fails closed without. `archie-state-store` therefore carries the
offline recovery commands (`archie-core-6zw0`). They work on the PostgreSQL
database the configuration's `database_url` names
(`internal/app/archied/state_store_recovery_postgres.go`,
`internal/infrastructure/postgres/maintenance.go`) and need neither `archied`
nor the Web UI running: `validate` reads the configuration file the daemon
boots with, which is what makes its verdict the daemon's verdict. One database
backs every service, so the scope is always the whole database.
| Command | What it does | Serving processes |
| -------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- |
| `backup -out F` | runs `pg_dump --format=custom`, reads the archive back with `pg_restore --list` and only then replaces `F` | may be running |
| `restore -from F` | drops tables the snapshot does not hold and runs `pg_restore --clean --single-transaction`; every write made after the snapshot is lost | every one must be stopped |
| `validate [-config C]` | refuses a schema newer than the binary's highest migration; every stored resource decodes under the definition that owns it; and `configuration.Validate` accepts the settings the daemon would read -- the stored ones, or the seed the State Store writes for a kind the database does not hold yet -- layered onto `C`, the check the daemon reports as `validate database settings` | may be running |
| `rollback -kind K [-revision N]` | replays an earlier revision of a stored resource through the ordinary replace, recording the rollback as a new revision | the State Store must be stopped |
The two validation layers `validate` reports are not the same check, and it
reports both rather than merging them: the write path's own decode is stricter
about shape (it rejects unknown fields boot's decode ignores), while boot is
stricter about meaning (only boot checks `dispatch.trigger`, and a positive
`poll_interval`). Either one refusing is a store somebody has to look at.
No rollback RPC exists and none is needed: a revision carries its own value, so
restoring one is the same replace the dashboard and the channels already use.
The offline command is that operation with the store stopped -- the one state in
which the daemon's own API cannot serve it.
"Must be stopped" is checked rather than assumed. Each serving process holds a
Postgres ownership lock for its whole life. `rollback` holds the `state-store`
claim for the replay. `restore` claims every service role's lock (`state-store`
and `gateway`) without waiting and refuses if any is held or the check cannot
complete. The read-only commands -- `backup` and `validate` -- take no claim and
are meant to run against a serving database: `backup` because the update
installer runs inside the process it is replacing and cannot stop the State
Store, and `validate` because an operator checks a running deployment with it.
`scripts/archie-update-install` takes its pre-flight snapshot through this
subcommand, so the installer and an operator run one implementation.
`rollback` is the surgical route back from a bad stored value; `restore` is the
blunt one, and is also the way back from a schema migration a release cannot
grow out of.
There is no automatic schema rollback. goose `Down` drops tables, so it is data
loss, not a rollback. `scripts/archie-update-install` refuses a daemon update
it cannot snapshot first, and on a failed update `scripts/archie-update-watchdog`
rolls the binaries back, leaves the database alone and prints the `restore`
command for the pre-update snapshot. Whether to run it is the operator's call.
## Gateway restart: two constraints learned the hard way
Telegram `/restart` (`internal/channels/telegram/restart.go` plus the `Start`
supervisor loop). Recovered 2026-08-09 from the pre-migration issue tracker.
Both constraints must survive any refactor.
**1. Deadlock.** The `/restart` handler runs _on_ the bot instance the supervisor
is about to stop. Tearing down inline from the handler deadlocks the restart it
just asked for. So the handler sends on a **buffered** channel (`restartCh`,
capacity 1) and returns immediately; the supervisor loop in `Start` does the
teardown. Duplicate requests hit the default branch and are dropped, not queued.
**2. Lockout.** A failed config reload must **not** be fatal. It logs and
relaunches with the previous in-memory settings. If a bad config edit killed the
gateway, it would also destroy the only means of fixing it remotely — which is
the entire reason `/restart` exists.
**Scope is gateway-only by design.** The daemon keeps running so in-flight agent
tasks survive. Exiting the process would also restart under a `unless-stopped`
policy, but would kill running work. `Reload` (supplied by `cmd/archied/main.go`)
re-reads config from disk and refreshes **only** the token and `AllowedUserIDs`;
everything else is wired into the daemon at construction and still needs a full
restart.
**Authorisation is inherited:** `authorizedMessage` rejects non-allowlisted
senders before any handler runs, so all gateway commands are admin-only by
construction. Do not add per-command auth without checking that invariant still
holds.
-39
View File
@@ -1,39 +0,0 @@
{
"$comment": [
"Contract-conformance declarations. Every entry here is a declared-unconsumed",
"surface: a capability that exists, that no client reaches, and that is",
"deliberately left that way. It must match reality exactly -- a missing entry",
"is an undeclared finding and an entry that is no longer true is a stale one,",
"and both fail a -strict run. See docs/prds/contract-conformance-audit.md.",
"",
"Managed by tools/contractaudit, an ADVISORY report that task check does not",
"run. Reasons state the consequence, not 'TODO': this file is the only place",
"the debt is legible."
],
"surfaces": {
"proto/state/v1/state.proto": {
"StateStoreService/ListCaptures": {
"reason": "Superseded by StreamCaptures. The remote adapter's ListCaptures method (staterpc/client.go) calls StreamCaptures, not this unary RPC, so no production client reaches it. The server keeps it implemented as a compatibility surface for callers of the raw proto.",
"tracker": "archie-core-8cda.4"
},
"StateStoreService/ListUndispatchedCaptures": {
"reason": "Superseded by StreamUndispatchedCaptures, on the same terms as ListCaptures: the remote adapter's ListUndispatchedCaptures calls the streaming variant, leaving this unary RPC reachable only through the raw proto.",
"tracker": "archie-core-8cda.4"
}
}
},
"blindSpots": [
{
"surface": "internal/webui",
"reason": "Extraction is textual, which is why this report is not gated. A path counts as a consumer only when it is the first argument of a call in code, so a bare constant, a dead array, an object property, or a commented-out call does not count; the calling function need not be named, so a rename is survivable. Limits: a path passed as any argument other than the first is not seen (accepting a comma would start crediting array elements); a request inside a template-literal interpolation is not seen; a path built from a bare /api fragment is reported as unparsable rather than silently contributing nothing; and a route is credited to every HTTP verb, so a route whose specific verb has no caller reads as consumed. Routes whose consumer is outside the dashboard (the asset mount, the health probes, the capture-intake webhook) are excluded from this surface by design: they have different consumers and are not part of the dashboard API contract."
},
{
"surface": "proto/state/v1/state.proto",
"reason": "Consumption is derived by scanning adapter bodies for calls through the generated client, so an RPC reached only through runtime-loaded code (Yaegi) or reflection would read as unconsumed. The scan also keys on the generated client field being named 'client'; renaming that field would report every RPC as unconsumed. No such path exists today."
},
{
"surface": "proto/gateway/v1/chat.proto",
"reason": "As above. Note that gatewayrpc is served by archie-gateway and consumed by archied and archie-ui; a consumer living outside this repository would be invisible here."
}
]
}
-494
View File
@@ -1,494 +0,0 @@
{
"generatedBy": "tools/docsgen",
"schemas": {
"AgentExecutionRequest": {
"additionalProperties": false,
"description": "Request is the complete, serializable input for one agent stage.",
"properties": {
"attempt": {
"type": "integer"
},
"budget": {
"$ref": "#/schemas/Budget"
},
"capture_tools": {
"items": {
"$ref": "#/schemas/CaptureTool"
},
"type": "array"
},
"context_window": {
"type": "integer"
},
"extra_rules": {
"type": "string"
},
"gate": {
"$ref": "#/schemas/Gate"
},
"harness": {
"$ref": "#/schemas/HarnessSpec",
"description": "Harness, when set, runs the stage on an external coding-agent CLI\ninstead of the built-in loop. The worker in a Kit container is the\ndaemon's own archie-agent build, so it always understands this field."
},
"mission": {
"type": "string"
},
"model": {
"type": "string"
},
"notes": {
"type": "string"
},
"plugins": {
"description": "Plugins are bundled Yaegi plugins from the skill's plugins/\ndirectory. Each entry carries the name and source so the agent\ncan register them as tools. PRD section 5 Layer 1.",
"items": {
"$ref": "#/schemas/PluginSpec"
},
"type": "array"
},
"preflight": {
"items": {
"$ref": "#/schemas/Command"
},
"type": "array"
},
"protection": {
"$ref": "#/schemas/Protection"
},
"read_only": {
"type": "boolean"
},
"stage": {
"type": "string"
},
"task_id": {
"type": "integer"
},
"version": {
"type": "integer"
},
"workflow": {
"type": "string"
}
},
"required": [
"version",
"task_id",
"attempt",
"stage",
"model",
"mission",
"budget",
"gate",
"protection"
],
"type": "object"
},
"AgentExecutionResult": {
"additionalProperties": false,
"description": "Result is the serializable outcome of one agent stage.",
"properties": {
"appended_notes": {
"items": {
"type": "string"
},
"type": "array"
},
"attempt": {
"type": "integer"
},
"captures": {
"additionalProperties": {
"items": true,
"type": "array"
},
"type": "object"
},
"changes": {
"items": {
"type": "string"
},
"type": "array"
},
"detail": {
"type": "string"
},
"iterations": {
"type": "integer"
},
"stage": {
"type": "string"
},
"status": {
"type": "string"
},
"stop_reason": {
"type": "string"
},
"summary": {
"type": "string"
},
"task_id": {
"type": "integer"
},
"tokens_used": {
"type": "integer"
},
"usage": {
"$ref": "#/schemas/Usage"
},
"version": {
"type": "integer"
}
},
"required": [
"version",
"task_id",
"attempt",
"stage",
"status",
"usage"
],
"type": "object"
},
"Budget": {
"additionalProperties": false,
"description": "Budget bounds one autonomous execution.",
"properties": {
"max_steps": {
"type": "integer"
},
"wall_clock": {
"type": "integer"
}
},
"type": "object"
},
"CaptureTool": {
"additionalProperties": false,
"description": "CaptureTool declares a structured-output tool whose calls are returned to the daemon as data.",
"properties": {
"boolean_fields": {
"items": {
"type": "string"
},
"type": "array"
},
"description": {
"type": "string"
},
"max_calls": {
"type": "integer"
},
"name": {
"type": "string"
},
"non_empty_strings": {
"items": {
"type": "string"
},
"type": "array"
},
"parameters": true,
"required_fields": {
"items": {
"type": "string"
},
"type": "array"
},
"required_when_true": {
"additionalProperties": {
"items": {
"type": "string"
},
"type": "array"
},
"description": "RequiredWhenTrue makes fields required only when a boolean field in\nthe same call is true, keyed by that boolean's name. It exists because\na flat RequiredFields entry cannot express \"name a workflow, but only\nwhen you have said one is needed\": the alternatives were forcing a\nmeaningless answer on the other branch, or accepting the omission and\ndefaulting it, which lets the model skip the decision entirely.\nA named field must also be a non-empty string when the trigger is true.",
"type": "object"
}
},
"required": [
"name"
],
"type": "object"
},
"Command": {
"additionalProperties": false,
"description": "Command is one executable gate or preflight command.",
"properties": {
"argv": {
"items": {
"type": "string"
},
"type": "array"
},
"expect_failure": {
"type": "boolean"
},
"name": {
"type": "string"
}
},
"required": [
"name",
"argv"
],
"type": "object"
},
"Gate": {
"additionalProperties": false,
"description": "Gate is the quality gate an agent must satisfy.",
"properties": {
"commands": {
"items": {
"$ref": "#/schemas/Command"
},
"type": "array"
},
"max_consecutive_failures": {
"type": "integer"
}
},
"type": "object"
},
"HarnessSpec": {
"additionalProperties": false,
"description": "HarnessSpec is how to drive a Kit's agent headlessly: its launch argv (image entrypoint and cmd) and the agent-sessions@1 verb tails appended to it.",
"properties": {
"adapter": {
"description": "Adapter names the output adapter reading the CLI's stream; empty is\na CLI with none.",
"type": "string"
},
"continue": {
"items": {
"type": "string"
},
"type": "array"
},
"env": {
"description": "Env is the invocation's entire environment. Nothing is inherited from\nthe worker, whose environment carries its credentials.",
"items": {
"type": "string"
},
"type": "array"
},
"launch": {
"items": {
"type": "string"
},
"type": "array"
},
"mcp_config": {
"description": "MCPConfig registers archie's MCP server with the CLI: an argv tail\ncarrying {{.MCPConfig}}, the path of a standard mcpServers config.\nA stage with capture tools needs it.",
"items": {
"type": "string"
},
"type": "array"
},
"prompt": {
"items": {
"type": "string"
},
"type": "array"
},
"resume": {
"items": {
"type": "string"
},
"type": "array"
},
"user": {
"description": "User is the Kit's user, a name or \"uid[:gid]\", that every invocation\nruns as. It is never root: the worker's credentials live in the same\ncontainer, readable only by the worker's user.",
"type": "string"
}
},
"required": [
"launch",
"prompt"
],
"type": "object"
},
"MediaAttachment": {
"additionalProperties": false,
"description": "MediaAttachment describes a file attached to a message.",
"properties": {
"data": {
"contentEncoding": "base64",
"description": "Data carries the attachment bytes in-process. An inbound path sets\nit after downloading the file; outbound senders never set it and\nread Path or URL instead. It crosses the wire in one direction only:\nthe inbound request from a channel frontend to the Gateway process\nthat runs the turn, because that process never holds the platform\ncredential. It is never persisted, and the stored-history and\noutbound-event directions strip it.",
"type": "string"
},
"duration": {
"description": "Duration is the play time in seconds for audio and video.",
"type": "integer"
},
"file_id": {
"description": "FileID is the platform-assigned identifier for download APIs.",
"type": "string"
},
"file_name": {
"description": "FileName is the original file name when known.",
"type": "string"
},
"file_size": {
"description": "FileSize is the attachment size in bytes. nil means unknown.",
"type": "integer"
},
"height": {
"description": "Height is the pixel height for images and video. nil means unknown\nor not applicable.",
"type": "integer"
},
"mime_type": {
"description": "MIMEType is the content type (e.g. \"image/png\", \"audio/ogg\").",
"type": "string"
},
"path": {
"description": "Path is a local filesystem path on the host that produced the\nattachment. It is the alternative to URL for outbound delivery: a\nURL is fetched by the platform, a Path is uploaded by us. A file the\nagent wrote has no URL and never gets one -- publishing it would\ntrade a delivery problem for a hosting and access-control one -- so\nsenders that support upload must read this.\n\nExactly one of URL and Path is meaningful for an outbound send.",
"type": "string"
},
"raw": {
"description": "Raw carries platform-specific fields the common vocabulary does not\ncover, so adapters never need a second attachment type.",
"type": "object"
},
"type": {
"description": "Type is \"image\", \"video\", \"audio\", \"voice\", or \"document\".",
"type": "string"
},
"url": {
"description": "URL is a direct download URL when available. May be empty for\nplatforms that require a download API call.",
"type": "string"
},
"width": {
"description": "Width is the pixel width for images and video. nil means unknown\nor not applicable.",
"type": "integer"
}
},
"required": [
"type",
"file_id"
],
"type": "object"
},
"MessageEvent": {
"additionalProperties": false,
"description": "MessageEvent is the rich message model for gateway channels.",
"properties": {
"callback_data": {
"type": "string"
},
"channel_id": {
"type": "string"
},
"edited_from": {
"type": "string"
},
"id": {
"type": "string"
},
"media": {
"items": {
"$ref": "#/schemas/MediaAttachment"
},
"type": "array"
},
"platform": {
"type": "string"
},
"raw": {
"type": "object"
},
"reacted_to_id": {
"type": "string"
},
"reaction": {
"type": "string"
},
"reply_to_id": {
"type": "string"
},
"sender_id": {
"type": "string"
},
"sender_name": {
"type": "string"
},
"text": {
"type": "string"
},
"thread_id": {
"type": "string"
},
"timestamp": {
"type": "integer"
},
"type": {
"type": "string"
}
},
"required": [
"type",
"channel_id",
"platform",
"sender_id"
],
"type": "object"
},
"PluginSpec": {
"additionalProperties": false,
"description": "PluginSpec is a bundled Yaegi plugin passed from daemon to agent.",
"properties": {
"name": {
"type": "string"
},
"src": {
"type": "string"
}
},
"required": [
"name",
"src"
],
"type": "object"
},
"Protection": {
"additionalProperties": false,
"description": "Protection describes paths the agent may read but not mutate.",
"properties": {
"globs": {
"items": {
"type": "string"
},
"type": "array"
},
"suffixes": {
"items": {
"type": "string"
},
"type": "array"
}
},
"type": "object"
},
"Usage": {
"additionalProperties": false,
"description": "Usage preserves provider-reported token economics for evaluation.",
"properties": {
"cache_creation_tokens": {
"type": "integer"
},
"cached_tokens": {
"type": "integer"
},
"completion_tokens": {
"type": "integer"
},
"prompt_tokens": {
"type": "integer"
},
"total_tokens": {
"type": "integer"
}
},
"type": "object"
}
}
}
-935
View File
@@ -1,935 +0,0 @@
{
"pages": [
{
"url": "/dev/architecture/",
"title": "Architecture",
"section": "Architecture",
"body": "# Architecture\n\nArchie is a personal agent platform built around six domain boundaries:\n\n- Identity tracks users and other actors responsible for actions.\n- Agent owns persistent assistants, specialisation, and continuity.\n- Messaging owns conversations, messages, branches, and channel correlation.\n- Workflow owns reusable, versioned behaviour definitions and their executions.\n- Work Intake admits optional durable work without constraining ordinary agent\n conversation or direct capability use.\n- Plugin owns generic extension discovery and lifecycle; each capability family\n owns its typed plugin contract.\n\nThe detailed architecture and migration decisions are maintained under\n`docs/architecture/` in the repository while this generated site is being\nassembled.\n"
},
{
"url": "/dev/architecture/agent-system/",
"title": "Agent System",
"section": "Architecture",
"body": "# Agent System\n\n**Status:** Current-state investigation in progress \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Domain framing\n\nThe domain is the Agent System.\n\n`Task` is not a core Agent System concept. Forge tasks, forge issues, Jira\nissues, email, Telegram messages, webhooks, and future external inputs are\nchannel-specific messages. Channels translate those messages into requests to\nthe Agent System; external issue or task models MUST NOT shape execution state.\n\nThe current `store.Task` is a persisted workflow execution. Treating that row as\na task-domain aggregate would incorrectly turn Archie into an agentic issue\nboard.\n\n## Canonical agent interaction model\n\nAn **Agent** is a persistent assistant selected for an interaction. It is not a\nmodel invocation and is not a WorkflowExecution.\n\nEach Agent has its own:\n\n- immutable acting `IdentityID` for ownership and audit;\n- durable memory and learned information about the user;\n- perspective, specialisation, instructions, and communication behaviour;\n- conversation history and channel bindings;\n- available tools, capabilities, and policy;\n- continuity across model or provider changes.\n\nThe underlying model is a replaceable runtime dependency. Changing a model,\nprovider, or model version MUST NOT create a new Agent, discard its memory, or\nchange ownership of its history.\n\nA user MAY create multiple Agents. Each Agent develops its own memory and view\nof the user from the interactions and responsibilities assigned to it. Memories\nMUST NOT be silently pooled merely because Agents belong to the same user or\napplication.\n\nAgent and Identity are separate aggregates. Every Agent references exactly one\nacting IdentityID, and no two Agents share an agent identity. User, system, and\nservice-account identities may exist without an Agent.\n\nAn action initiated through an Agent records the Agent's acting IdentityID and,\nwhen applicable, the initiating user's IdentityID. A future fully automated\nWorkflowExecution MAY use an explicitly selected service-account identity for a\nconcrete unattended use case; this is not the default execution identity.\n\n## Workflow execution identity\n\nA Workflow is owned by an IdentityID. By default, every WorkflowExecution acts\nas the Workflow owner's identity.\n\nFuture delegated execution MAY add an explicit `RunAsIdentityID` assignment to a\nWorkflow. This allows a Workflow owner to select another user or service-account\nidentity for execution without changing Workflow ownership. Until that\ncapability is deliberately introduced, owner identity and execution identity are\nthe same.\n\nWorkflowExecution audit records MUST preserve the Workflow owner, effective\nexecution identity, initiating user when one exists, and any explicit delegation\nthat selected a different run-as identity.\n\n## Memory scopes\n\nThe Agent System requires four distinct durable memory scopes:\n\n- **global shared memory**: information intentionally available across the\n Archie application;\n- **agent-wide memory**: general expertise, operating knowledge, and perspective\n owned by one Agent and safe for that Agent to use across users;\n- **user-wide memory**: information associated with one user and available to\n authorised Agents serving that user;\n- **Agent-user relationship memory**: private history and learned context from\n one particular Agent's relationship with one particular user.\n\nAgent-wide memory is private to its owning Agent by default. Another Agent MUST\nNOT read, inherit, search, or mutate it implicitly.\n\nAgent-user relationship memory is addressed by both AgentID and User IdentityID.\nNeither another Agent serving the same user nor another user speaking to the\nsame Agent may access it implicitly.\n\nArchie is a multi-user system even when initially deployed for one person.\nMultiple users, including family members, may interact with the same configured\nAgents. Per-user memory is therefore an isolation and personalisation boundary,\nnot merely an attribution tag on the primary user's records.\n\nAn Agent MUST resolve the initiating user before assembling memory context.\nMemory belonging to one user MUST NOT become visible to another user merely\nbecause both users interact with the same Agent.\n\nShared memory does not erase provenance. Every memory record retains its scope,\nauthor or acting identity, originating user when applicable, source, and\nrevision history. The rules for selecting a write scope, granting access\nto global and user-wide memory, and authorising explicit cross-scope sharing are\nsettled by [`docs/prds/memory-engine-unification.md`](/dev/prds/memory-engine-unification/)\nand recorded in [`migration-decisions.md`](/dev/architecture/migration-decisions/#5-memory-placement-and-storage)\nsection 5.\n\nAn Agent interaction may answer conversationally, use a tool or capability, read\norLine truncated
},
{
"url": "/dev/architecture/bindings/",
"title": "Playbook bindings: model and threat model",
"section": "Architecture",
"body": "# Playbook bindings: model and threat model\n\n**Status:** Approved foundation (documents shipped code: `archie-core-t2db.1`\nthrough `.5`, `.7`, `.9`-`.15`)\n**Date:** 2026-09-03\n\nThis document covers the binding model and the intake threat model portion\nof `archie-core-t2db.6`. It does not cover the task-lifecycle provenance rule\n(`messaging-and-work-intake.md`'s \"Intake provenance\") or the operator\nwalkthrough -- that walkthrough remains an open piece of the same ticket.\n\n## What a binding is\n\nA `binding` (`internal/domain/binding.Binding`) ties four things together:\na **matcher** (which captured events it applies to), a **mapping**\n(`internal/domain/mapping.Mapping`, how fields are pulled out of a payload),\na **workflow** (which registered workflow runs on a match), and a **state\nmachine** governing whether it is live.\n\n```go\ntype Binding struct {\n ID, Name // identity\n Matcher // { Source string } -- the webhook path segment, e.g. \"sentry\"\n MappingID // which Mapping resolves payload fields; its event type is the binding's\n Filter // optional CEL over the mapping's parameters\n Workflow // registered workflow name to dispatch to\n Version // bumped on every edit\n Status // pending_approval | armed\n Secret // HMAC-SHA256 shared secret, encrypted at rest, never returned by GET\n}\n```\n\nBindings live in the store (PostgreSQL), not `config.toml` -- operators author\nthem from the dashboard while the daemon runs, without a restart.\n\n### Matching\n\nA binding applies to a capture when the capture arrived on `Matcher.Source`,\nwas identified as the event type its mapping belongs to, and passes its\n`Filter` (`binding.CompileFilter`, checked against the mapping's parameters on\nsave). Any number of bindings may share a source; each dispatches a capture at\nmost once, claimed in `binding_dispatches` keyed by (binding, capture) before\nits task is enqueued. An event signed with any armed binding's secret on the\nsource is authenticated.\n\n### Mapping\n\n`mapping.Resolve(fields, payload)` walks a captured JSON payload against a\nlist of typed `Field`s (name, JSON path, expected type), returning resolved\nvalues plus a `[]Failure` for anything that didn't parse or type-match. A\nmapping belongs to an event type, and `mapping.CheckSchema` refuses a field\nwhose path or type the type's inferred schema lacks. Each capture a mapping\nresolves at dispatch is counted once in `mapping_matches`, read back as\n`MatchCount` and `LastMatchedAt`.\n\n### Versioning\n\n`Version` increments on every `UpdateBinding` call. This exists so an\neditor's later change can never silently rewrite the historical provenance\nof a task that already fired -- a dispatched task's binding reference is\npinned to the version that was armed when it fired, not \"whatever the\nbinding currently says.\"\n\n### State machine\n\n```\ncreate ---\u003e pending_approval ---\u003e armed\n ^ |\n +----------------+\n (any edit to an armed binding drops it back to pending_approval)\n```\n\nA binding is created `pending_approval`, so the operator who creates one can\napprove it immediately. Bindings stored as `draft` by an earlier version are\nmoved to `pending_approval` when the EDA store opens.\n\nModelled directly on Telegram's existing `dangerousAction`/`pendingApproval`\nflow (`internal/channels/telegram/dangerous.go`, `approval.go`) -- not a new\napproval mechanism invented for this feature. **Only `armed` evaluates\nagainst incoming events** (`binding.Matches`, `internal/domain/binding/\nbinding.go`); a `pending_approval` binding is inert. An edit to\nan already-armed binding cannot bypass approval by silent mutation -- it\ndrops back to `pending_approval` and requires an explicit `Approve` call to\nre-arm.\n\n## The threat model\n\nThis is a public, unauthenticated-by-default intake surface whose output is\nan agent with a repo, a worktree, and tool access. The design brief\n(`archie-core-t2db.5`, `docs/prds/webhook-intake-security.md`) named five\nnon-negotiables; each is verified below against the actual shipped code,\nnot the design intent.\n\n### 1. Per-source authentication\n\nReuses `internal/channels/webhook`'s existing HMAC-SHA256 scheme --\ncapture accepts unsigned events (visible in the dashboard, marked\nunauthenticated), but **only authenticated events can ever match a\nbinding**. `binding.Matches`' doc comment states this plainly: \"an\nunauthenticated event can never trigger a binding, no matter how well it\nwould otherwise match.\" Enforced structurally at two points, not just\nconvention:\n\n- `captures.authenticated` is a real column\n (`internal/infrastructure/postgres/migrations/0002_edastore.sql`), set at\n capture time.\n- `dispatchBindings` (`internal/daemon/daemon.go:479`) walks **authenticated\n captures whose soLine truncated
},
{
"url": "/dev/architecture/configuration/",
"title": "Configuration",
"section": "Architecture",
"body": "# Configuration\n\n**Status:** Approved; existing-type assignment is ongoing \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Ownership\n\nConfiguration has two separate responsibilities:\n\n1. `internal/infrastructure/configuration` loads files, environment variables,\n secret references, overlays, and compatibility representations.\n2. Each domain and plugin owns the typed runtime settings required for its\n behaviour.\n\n`internal/app` translates external input into those settings, validates\ncross-capability combinations, and supplies each component only its own\nsettings.\n\nThe following are prohibited:\n\n- passing complete application configuration into a domain;\n- making a domain depend on TOML, YAML, environment-variable names, secret\n references, or a configuration library;\n- defining a central runtime configuration type imported across the system;\n- placing plugin options in an unrelated global configuration model.\n\n## Private input document\n\n`internal/infrastructure/configuration` MAY use a complete decoded document\nwhile discovering files, decoding sections, and applying overlays. It is an\ninput-boundary DTO only.\n\nThe document:\n\n- remains private to the configuration infrastructure;\n- is composed from separately defined feature sections;\n- is immediately translated by application composition;\n- is never returned as the application's runtime model;\n- is never passed through runtime components.\n\nExternal DTOs and domain runtime settings are separate types.\n\nPlugins supply external configuration definitions through a narrow extension\ncontract. The core loader MUST NOT gain a field or recognised filename for every\nplugin.\n\nInvalid configuration input MUST NOT replace active valid settings or terminate\nunaffected capabilities. Configuration changes use the candidate validation,\npromotion, audit, and recovery requirements in\n[safe-change-and-recovery.md](/dev/architecture/safe-change-and-recovery/).\n\n## Dissolution of `internal/config`\n\n`internal/config` has no target location. It MUST be dissolved and MUST NOT\nsurvive as a shared package, configuration domain, or renamed global model.\n\nIts loading behaviour moves to `internal/infrastructure/configuration`. Existing\ntypes and methods are reassigned by behaviour. Repository execution policy,\ndispatch policy, retry policy, ecosystem defaults, tool policy, memory settings,\nprovider settings, and channel settings move to their\nrespective owners.\n\n## Repository settings\n\nThe existing `config.Repo` MUST NOT move intact into a repository domain or\nshared settings package. A managed repository is an application association:\n\n- work intake owns which repository references an identity monitors;\n- task execution owns gates, preflight, test protection, ecosystem behaviour,\n and change limits;\n- task lifecycle owns retry behaviour;\n- scheduling owns concurrency policy;\n- workspace management owns base branch and persistent-storage requirements.\n\nApplication composition correlates these settings by repository reference. No\ndomain receives a universal repository profile.\n\n## Documentation\n\nGenerated configuration reference describes external sections and their owning\ncapabilities. It MUST NOT establish a global Go configuration structure as the\npublic contract.\n\n## Value classification rule\n\nEvery value that controls behaviour MUST have an explicit owner and MUST be\nclassified as exactly one of:\n\n1. **Invariant** — changing it changes the meaning of the program, a wire\n protocol, or a domain concept. It may be a Go constant.\n2. **Runtime setting** — an operator, identity, domain, plugin, or deployment\n may legitimately choose a different value. It is typed configuration owned by\n the affected capability.\n3. **Policy value** — it expresses what is allowed, limited, routed, retried,\n protected, or gated. Its typed definition belongs to the owning domain and it\n is evaluated through the policy system.\n4. **Derived value** — it is computed from other settings and is not\n independently mutable.\n5. **Runtime state** — it changes as the application operates, such as the\n active model for a conversation. It is changed by a domain command and is not\n configuration merely because it can be changed.\n\nAn unclassified behavioural literal is a defect.\n\n`const` MUST NOT be used merely because a value currently has one default.\nConstants are reserved for actual invariants: enum discriminants, protocol\nversions, fixed compatibility tokens, and values whose alteration would change\nthe program's semantics rather than configure an installation.\n\nIn Go, a constant is a compile-time value and does not represent mutable runtime\nstorage. It generally has no address that can be observed or changed.\nArchitecturally, a constant therefore asserts that the value cannot change for\nthe lifetiLine truncated
},
{
"url": "/dev/architecture/dashboard-agent-tools/",
"title": "The dashboard's tools for an in-browser agent",
"section": "Architecture",
"body": "# The dashboard's tools for an in-browser agent\n\nThe dashboard registers in-browser tools an agent can call through the page's model\ncontext. Four are read-only — `list_tasks`, `get_task`, `recent_events`,\n`daemon_health` — and three recover stuck work: `retry_task`, `stop_task`,\n`cancel_task`. Each wraps the same `ui/src/lib/api.ts` client the dashboard itself\ncalls, so an agent and a person exercise one path rather than two.\n\nThe four judgement verbs are withheld for the reason `identity.md` gives: an agent\nthat can approve can approve its own work.\n\n## What a tool call can be attributed to\n\nA page can invoke its own tools, so an agent's call and a page script's call reach\nthe server identically — the difference does not exist on the wire, and no header\nrecovers it. A tool call is therefore attributed to the signed-in identity the\nrequest presented, with its source recorded as a hint; it never records that an\nagent acted, and it never records that a human approved. An agent's action is\nattributable only on a surface where the agent presents its own credential.\n\n## Confirmation is a signal, not a control\n\nThe three recovery tools require an explicit `confirm: true`, which makes a\nconsequential call deliberate rather than incidental. It is not a security control:\nan agent can trivially satisfy it, and the browser cannot enforce\n`consequentialHint` at all — Chrome accepts it at registration and omits it from\n`getTools()`, so no client can see what the browser does not surface.\n\nThe boundary that holds is the session. These tools cannot exceed what the operator\nsigned in at the provider is already permitted to do.\n\n## Two ways the surface fails silently\n\n- **A secure context is required.** On a plain-HTTP origin `document.modelContext` is\n absent even with the flag enabled, and nothing reports why. `mkcert` covers local\n development.\n- **The dashboard embeds `ui/dist` into its binary.** Rebuilding the distribution is\n not deploying it: a running process can serve a bundle without tools while the\n built one has them, or serve a bundle older than its own binary.\n"
},
{
"url": "/dev/architecture/dependencies-and-contracts/",
"title": "Dependencies and Contracts",
"section": "Architecture",
"body": "# Dependencies and Contracts\n\n**Status:** Approved foundation \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Dependency direction\n\n```text\ndomain and shared application contracts \u003c- infrastructure implementations\n ^\n |\n application composition\n```\n\nThe following rules are strict:\n\n1. Domains MUST NOT import `internal/infrastructure`.\n2. A domain defines the smallest interfaces required to perform its work.\n3. Infrastructure implements those interfaces and translates external\n representations at the boundary.\n4. Only application composition chooses concrete implementations.\n5. A domain MUST NOT manipulate another domain's state or call its internal\n services.\n6. Cross-domain work uses an explicitly designed command, event, or approved\n shared contract.\n7. Implementation difficulty is not permission to violate a boundary.\n\nBroker messages, database rows, SDK response types, and configuration DTOs MUST\nNOT leak into domain models.\n\n## Commands and events\n\n- An event records something that happened and is owned by its publishing\n domain.\n- A command requests an action and is owned by the domain expected to handle it.\n- Consumers do not redefine an event's meaning.\n- Senders obey the receiving domain's command contract.\n- There is no generic package containing unrelated application messages.\n\n## Event bus\n\n`internal/eventbus` is an approved shared application contract. It defines only\nthe messaging behaviour Archie requires, including publication, subscription,\ndelivery outcomes, and required lifecycle semantics.\n\nIt MUST remain broker-neutral. NATS subjects, JetStream configuration, consumer\ngroups, acknowledgements, reconnection, and serialisation belong under\n`internal/infrastructure/eventbus/nats` unless Archie explicitly requires a\nsemantic guarantee in the shared contract.\n\nMessage schemas stay with their owning domains. The event bus transports\nmessages; it does not own their meaning.\n\n## Wire contracts and generation\n\nCanonical worker and service wire contracts and their authoritative generation\ninputs are owned by the domain or capability that defines their meaning. They\nMUST NOT be centralised in `internal/infrastructure/spec` or another generic\nschema package.\n\nInfrastructure owns:\n\n- generic contract-generation machinery;\n- transport-specific adapters and generated implementations;\n- RPC, REST, NATS, and other external encoding and delivery concerns.\n\nFor example, agent-worker requests and results belong to task execution.\nSubprocess, NATS, or HTTP representations are infrastructure implementations of\nthat contract. The same rule applies independently to forge, persistence,\nworkspace, and other service contracts.\n"
},
{
"url": "/dev/architecture/generated-documentation/",
"title": "Generated Documentation",
"section": "Architecture",
"body": "# Generated Documentation\n\n**Status:** Data generation lives here; rendering and publishing live in the external Astro website\n**Date:** 2026-07-28 (revised 2026-09-25)\n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchie's documentation-generation approach is:\n\n- production Go code, registries, configuration, and CLI behaviour remain the\n source of truth for published contracts;\n- a repository-local Go generator extracts and normalises documentation data;\n- the generator writes deterministic JSON/data files and protocol schemas;\n- the external Astro website consumes generated data and serves the public\n documentation at `offloaded.dev/docs/`.\n\nHugo is not part of the target architecture.\n\nThe documentation system is rooted at:\n\n```text\ntools/\n go.mod\n go.sum\n docsgen/\n main.go\ndocs/\n data/generated/\n public/schemas/\n *.md\n```\n\n### Rendering and publishing — external Astro website\n\nSuperseded 2026-09-12. The repository previously carried a VitePress site\n(`docs/.vitepress/config.mts`, `docs/package.json`, a 1620-line\n`docs/pnpm-lock.yaml`, `docs/pnpm-workspace.yaml`) built and deployed to GitHub\nPages by `.github/workflows/docs.yml`. It was removed as an unnecessary build\nstep: the published site was never stood up, and the Pages target is not\nconfigured.\n\nThe Astro website is maintained outside this repository. This repository owns\nthe Markdown source and generated JSON artifacts; it does not build, preview, or\ndeploy the site. The external site owns page rendering, navigation, and\npublishing.\n\nThe current boundaries are:\n\n| Concern | Owner |\n| --------------------------------------- | -------------------------------------------------------------------- |\n| Reference-page rendering and publishing | External Astro website |\n| Documentation source and generated data | This repository |\n| Generated-data drift detection | `task docs:check`, `task docs:artifact:check`, and `task news:check` |\n| Navigation data | `docs/data/generated/docs.json` and `dev-docs.json` |\n\nChanges to an artifact contract must be coordinated with the external Astro\nconsumer. This repository does not validate the website's rendered links or\nroutes.\n\n## Single source of truth\n\nEvery published capability has one authoritative machine-readable definition\nowned by its domain or application boundary. Generated documentation derives\nfrom those definitions.\n\nGenerated reference includes:\n\n- domain commands and events;\n- Messages and typed message content;\n- Agent and Workflow contracts;\n- WorkflowSteps and Workflow plugin capability contracts;\n- policies and their typed inputs and outcomes;\n- tools and capabilities;\n- CLI commands, arguments, flags, defaults, and help;\n- runtime settings, types, defaults, validation, and secret metadata;\n- public worker and transport contracts;\n- indexes of registered functionality;\n- deprecation information.\n\nHandwritten documents contain:\n\n- architecture decisions and rationale;\n- tutorials and operational guides;\n- examples and walkthroughs;\n- migration guidance;\n- conceptual explanations.\n\nHandwritten documents link to generated reference rather than copying\nauthoritative tables.\n\n## Target generation architecture\n\n`tools/docsgen` is Archie's documentation extractor and normalizer. It produces\nstructured documentation data and protocol specifications. It does not own\npage layout and MUST NOT generate Markdown pages or fragments.\n\nThe generator is divided internally into reusable stages:\n\n```text\nload registries and types\n -\u003e normalize documentation model\n -\u003e validate ownership and identifiers\n -\u003e serialize data and protocol artifacts\n -\u003e compare or write output\n```\n\nThe normalised documentation model prevents each output renderer from\nindependently interpreting Go types. It contains stable documentation IDs,\nowners, names, descriptions, source references, versions, deprecations, fields,\ndefaults, validation, secret classifications, and relationships.\n\nInitial generator targets:\n\n```text\ndocsgen data\ndocsgen asyncapi\ndocsgen all\ndocsgen check\n```\n\n- `data` writes the normalised JSON reference data.\n- `asyncapi` writes protocol schemas and envelopes.\n- `all` generates every committed artifact.\n- `check` generates into a temporary directory and fails on drift.\n\nThe command may use subcommands or an equivalent explicit `--target` flag. It\nMUST retain one normalisation and validation path.\n\n## Target output\n\nDuring adaptation, `docs` remains the staging site. Generated outputs live in\na visibly owned subtree:\n\n```text\ndocs/\n data/\n geLine truncated
},
{
"url": "/dev/architecture/identity/",
"title": "Identity",
"section": "Architecture",
"body": "# Identity\n\n**Status:** Approved foundation; lifecycle details are deferred \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nIdentity answers which persistent actor owns or performed an action. It supplies\nstable cross-domain attribution and lifecycle semantics.\n\nIdentity kinds include:\n\n- the Archie system identity, such as `System` or `archied`;\n- agent or bot identities;\n- service-account identities;\n- future user identities.\n\nA user is another kind of identity rather than a separate foundation concept.\n\n## Ownership\n\n`internal/domain/identity` owns:\n\n- immutable canonical `IdentityID` values;\n- identity kind;\n- lifecycle state;\n- ownership and attribution semantics;\n- identity-related commands and events.\n\nDomains may record an identity reference on their own state and events when\nownership or attribution is required. They MUST NOT receive a complete\nper-identity application configuration bundle.\n\nPersona and communication style are separate from identity.\n\nEvery Agent has its own immutable acting `IdentityID`. Agent actions use that\nidentity for ownership and attribution in the same way an organisation records\nwhich user accessed a resource, changed a permission, or performed another\nauditable action.\n\nAgent and Identity remain separate aggregates. Identity supplies the stable\nactor reference; Agent owns assistant behaviour, memory, specialisation,\nconversations, and capability context.\n\nAgent identities MUST NOT be shared between Agents. Automated WorkflowExecutions\nMAY eventually act through a dedicated service-account identity when a specific\nunattended automation requires it. Such use is an explicit execution decision\nand audit principal, not the default for Agents or a substitute for recording\nthe initiating user when one exists.\n\nA Workflow is owned by an IdentityID and executes as its owner by default.\nFuture delegated execution MAY explicitly assign a different `RunAsIdentityID`,\nincluding a user or service-account identity. Ownership, effective execution\nidentity, initiating identity, and delegation provenance remain distinct audit\nfacts.\n\n## Canonical identity\n\nEvery identity has an immutable `IdentityID`. It is the only value used for\ncross-domain ownership, attribution, routing, persistence, commands, and events.\n\nIdentity kind is explicit:\n\n- system;\n- bot;\n- service account;\n- user.\n\nDisplay names are mutable and MUST NOT be used as identifiers. Forge usernames,\nchannel bot names, Git authors, provider account names, and other external\nidentifiers are bindings associated with an identity rather than identity\nitself.\n\n`System` is represented by a real identity and `IdentityID`. The empty string\nMUST NOT retain special meaning as a legacy system identity.\n\nConfiguration refers to identities by `IdentityID` and supplies external\nbindings and capability settings separately. Renaming an identity or changing an\nexternal account MUST NOT change ownership or historical attribution.\n\nSecret-bearing channel bindings remain configuration concerns rather than\nidentity data. In particular, `[chat.telegram].token` is a\n`secret.SecretRef` resolved by the application through the configured secret\nregistry. It does not change the identity that owns or performs a chat action.\n\n## Persistence\n\nIdentity records are durable domain state. The Identity domain's repository is\nthe source of truth; infrastructure implements its persistence contract.\n\nConfiguration MAY bootstrap a missing identity through an explicit, audited\ncreation operation and MAY propose runtime capability bindings for an existing\n`IdentityID`. Configuration is not the identity registry.\n\nOmitting an identity from configuration stops assembling the omitted runtime\ncapabilities. It MUST NOT delete the identity record, erase history, or make\nhistorical references unresolvable.\n\nDisabling or retiring an identity requires an explicit Identity-domain command.\nRetired identities remain resolvable for historical attribution. A failed\nexternal binding affects capability availability without destroying or silently\nreplacing the identity.\n\n## Lifecycle\n\nIdentity lifecycle is deliberately small:\n\n- `active`: may participate in runtime composition;\n- `suspended`: deliberately prevented from initiating new work while ownership\n and history remain;\n- `retired`: terminal, unable to initiate work, and permanently retained for\n attribution.\n\nAllowed transitions are:\n\n```text\ncreate -\u003e active\nactive -\u003e suspended\nsuspended -\u003e active\nactive -\u003e retired\nsuspended -\u003e retired\n```\n\n`retired` has no outgoing transition.\n\nCapability health is separate from identity lifecycle. Forge, model, channel,\nworkspace, and other bindings report health independently. An active identity\nmay be partially degraded without becoming suspended or reLine truncated
},
{
"url": "/dev/architecture/messaging-and-work-intake/",
"title": "Messaging and Work Intake",
"section": "Architecture",
"body": "# Messaging and Work Intake\n\n**Status:** Current state researched; foundation decisions in progress \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchie is a personal assistant and general agentic system. Its interactions\ninclude conversation, questions, notes, reminders, goals, message handling,\ntroubleshooting, infrastructure operations, server management, source changes,\nand open-ended future capabilities.\n\nA message to an agent is therefore not inherently a work request, and invoking\nan agent is not inherently a WorkflowExecution.\n\nMessaging and work intake are separate from the Agent System's durable workflow\nexecution model:\n\n- messaging preserves interactions with people and external systems;\n- an agent turn interprets and responds to an interaction using its available\n capabilities;\n- work intake handles the optional promotion of an interaction into durable,\n workflow-backed work;\n- the Agent System owns Workflow definitions and creates WorkflowExecutions.\n\nForge issues, Jira issues, Telegram messages, emails, webhooks, and future\nchannels remain peer external message or artifact sources. None becomes an\nexecution model merely because it can lead to work.\n\n## Confirmed boundary\n\nWork intake MUST NOT create a WorkflowExecution directly.\n\nInbound interactions normally route to the Agent selected by the channel\nbinding. The selected Agent retains its own memory, user knowledge, conversation\ncontinuity, specialisation, and capability context. This continuity is\nindependent of the underlying model or provider.\n\nEach selected Agent acts through its own immutable IdentityID. Interaction and\nresulting action records preserve both that acting identity and the initiating\nuser identity when one exists.\n\nAgent memory is private by default. Interaction context MAY additionally use\nuser-wide memory and intentionally global shared memory, but another Agent's\nagent-wide memory is not part of the selected Agent's context.\n\nMultiple users may interact with the same Agent. The channel binding and inbound\nmessage MUST resolve both AgentID and initiating User IdentityID before\nconversation or memory context is loaded. Sharing an Agent MUST NOT implicitly\nshare one user's private memory with another user.\n\nAn interaction may assemble memory from four scopes: global shared, the selected\nAgent's agent-wide memory, the initiating user's authorised user-wide memory,\nand the private Agent-user relationship memory addressed by both IDs.\n\n## Conversation identity\n\nEvery conversation is identified by the complete tuple:\n\n```text\nAgentID\n+ UserIdentityID\n+ ChannelBindingID\n+ ExternalConversationID\n+ ThreadID\n```\n\n`ThreadID` has an explicit empty value for channels without threads. No element\nof this key may be replaced by a display name, configured bot username, channel\ntype, or other mutable label.\n\nAgent and user memory continue across conversations according to their memory\nscope. Immediate conversation history and delivery correlation remain isolated\nto the identified channel conversation or thread. Moving between Telegram,\nemail, or another channel does not create a new Agent or user, but it does\ncreate a distinct conversation unless an explicit linking operation relates\nthem.\n\nConversation and message events support projections for channel-entry metrics,\nuse cases, volumes, outcomes, latency, capability usage, and other product or\noperational analysis. Metrics are derived read models; they MUST NOT become\nmutable counters embedded in the conversation aggregate or change message\nrouting semantics.\n\n## Canonical messages\n\nEvery inbound, assistant, tool-call, and tool-result message has an immutable\napplication-generated MessageID. Platform identifiers are external correlation,\nnot substitutes for the canonical ID.\n\nMessages are addressable because an interaction is more than text. A message may\ncontain assistant content, reasoning data subject to its retention policy, one\nor more tool calls, a tool result with authoritative execution metadata,\nattachments, reply relationships, edits, or other typed content. Stable\nMessageIDs also allow sessions to branch from an exact prior point.\n\nThe canonical session and message implementation must supply:\n\n- application-generated stable message IDs;\n- user, assistant, and tool roles;\n- assistant tool calls and correlated tool-result messages;\n- authoritative tool-result status, timing, error, truncation, and size\n metadata;\n- session lifecycle and active-request state;\n- session-to-agent-instance and parent-session lineage;\n- durable database round trips and timestamp validation.\n\nThese semantics must use the confirmed Agent, user, channel-binding, and\nconversation ownership model.\n\nThe canonical message store MUST preserve messages as immutable records and\nrepresent later edits, deletionLine truncated
},
{
"url": "/dev/architecture/migration-decisions/",
"title": "Architecture Migration Decisions",
"section": "Architecture",
"body": "# Architecture Migration Decisions\n\n**Status:** Active migration inventory \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nThis document records what remains to be decided before Archie's current\nimplementation can be migrated into the approved domain-oriented structure.\n\nThe product and core domain model are not being redesigned. Existing Archie\nbehaviour and the existing session implementation are the migration\nbaseline. Remaining decisions MUST be grounded in current packages, consumers,\ntests, persistence, and runtime wiring.\n\n## Confirmed domain packages\n\n```text\ninternal/domain/\n identity/ (approved, not yet materialised as a package)\n agent/ (approved, not yet materialised as a package)\n workflow/\n messaging/ (canonical Message/Conversation types only; gateway migration pending, see section 2)\n workintake/\n plugin/ (approved, not yet materialised as a package)\n curator/\n mapping/\n scheduling/\n```\n\n- `identity` owns persistent actors, lifecycle, ownership, attribution, and\n audit identity.\n- `agent` owns persistent assistants, specialisation, instructions,\n model-independent continuity, capability context, and associations with\n identity and memory.\n- `workflow` is a separate domain. It owns reusable, versioned Workflow\n definitions, WorkflowSteps, WorkflowExecutions, StepExecutions, Attempts,\n outcomes, and typed Workflow plugin contracts.\n- `messaging` owns canonical Messages, Conversations, branches, channel and\n source correlation, replies, acknowledgements, delivery attempts, events, and\n projections.\n- `workintake` owns admission, validation, deterministic routing, and accepted\n work requests for the optional transition into durable workflow-backed\n execution.\n- `plugin` owns generic plugin identity, discovery, compatibility, and lifecycle\n mechanics. It remains metadata-only; capability semantics and typed\n registration belong to the owning domain.\n- `curator` owns the curator engine family: long-running agent loops that\n reason over memory and perform maintenance tasks on a declared shape\n (check-in interval, tool set, attached memory engine). See epic\n archie-core-yp9.\n- `mapping` owns the payload field-mapping vocabulary: binding named fields to\n JSON paths inside a captured webhook payload, and detecting drift. See\n `docs/prds/payload-field-mapping.md`.\n- `scheduling` owns the ticker engine: deciding when a scheduled job runs and\n with what concurrency. It declares `JobSource`/`Runner` contracts and owns\n no storage or delivery. See epic archie-core-1786637496320-249-be6d9a20.\n\n**Reconciliation (2026-08-31):** `curator`, `mapping`, and `scheduling` existed\nin the tree without being added to this list when their epics landed. They are\nconfirmed as legitimate, narrowly-scoped domains under the same rules as the\noriginal six — each owns one capability family, declares typed contracts, and\nhas no cross-domain reach. This list was out of date, not the tree.\n\nConversely, `identity`, `agent`, `messaging`, and `plugin` are approved target\ndomains that do not yet exist as packages. Their behaviour currently lives in\npre-migration packages (see \"Complete package destination map\" below for the\nfull inventory). Do **not** create empty stub packages for them ahead of an\nactual migration PR — an unused stub is dead code and gives no test coverage.\nEach materialises when its corresponding migration decision below is resolved\nand implemented in the same change.\n\nMemory's final package placement remains undecided pending focused review of the\nexisting implementation.\n\nThe following are approved shared or composition packages, not domains:\n\n```text\ninternal/eventbus/\ninternal/policy/\ninternal/infrastructure/\ninternal/app/archied/\ninternal/app/agentworker/\n```\n\n## Remaining migration decisions\n\n### 1. Complete package destination map\n\nEvery current package MUST receive one explicit disposition:\n\n- move into a confirmed domain;\n- move under infrastructure as an implementation of a domain-owned contract;\n- move into application composition;\n- merge with an identified duplicate;\n- remain as an approved shared application contract;\n- move to a plugin, extra, deployment, example, or generated artifact;\n- be deleted after its replacement is proven.\n\nThe largest unreviewed areas include memory, tools and capabilities, workspace\nand worktree behaviour, gates, storage, events, web UI, containers, RPC\npackages, release management, and scheduling.\n\nThe destination matrix MUST name the behaviour owner, target path, dependencies\nto remove, state and contracts to preserve, migration prerequisites, and\ndeletion criteria.\n\n**`internal/webui` / UI Service — RATIFIED Phase 3 disposition (2026-09-07).**\nThe current owner is the in-process HTTP/SSE dashboard: SPA hosting, operator\nauthLine truncated
},
{
"url": "/dev/architecture/observability/",
"title": "Task Observability",
"section": "Architecture",
"body": "# Task Observability\n\n**Status:** Implemented. The per-run detail surface was added on 2026-09-18 and\nis described below.\n**Date:** 2026-08-09 (revised 2026-09-18)\n\n## Historical problem\n\narchied's own daemon logging (`internal/logging/`) was already solid: a\nrotating file sink, a live `Feed` the dashboard subscribes to, and a reader\nthe `/api/logs` endpoint serves from. Before this implementation, none of\nthat reached inside a task.\n\nA task's actual work happens in a task-scoped `archie-agent` container,\ndispatched as one complete workflow over NATS.\nBefore this design was implemented, five things destroyed the evidence of what\nthat container did:\n\n1. **Worker startup** constructed an stderr-only logger and never replaced its\n handler after discovering a dedicated boot task, so runtime records could\n not leave the container.\n2. **`internal/container/pool.go`** creates every task container with\n `AutoRemove: true`. The container — and its stderr — is gone at exit,\n success or failure alike.\n3. **`internal/domain/workflow/implement.go`, `StageBaselineGate`** captures\n `go build`/`go vet`/`go test` output via `cmd.CombinedOutput()`, then\n clips it to 200 characters into a `Warn` log line and discards the rest.\n The eventual park reason is built from `res.Status` alone — the actual\n compiler error is never persisted anywhere a human or Archie's own chat\n tools can read it back.\n4. **`agentexec.Result`** (`internal/agentexec/protocol.go`) carries only\n `Summary`/`Detail` — no step-by-step transcript (tool calls, durations,\n errors). There is no transcript to recover even in principle.\n5. **`agentexec.SubjectForSystem`** is documented as the return channel for\n exactly this — _\"log dumps, health, and PII warnings... the daemon reads\n these for observability and never forwards them\"_ — but has no publisher\n and no consumer anywhere in the codebase except a subject-format\n assertion in `nats_test.go`. The designed return path was never wired.\n\nThe practical consequence: a task parks with\n`stage baseline: baseline red -- go build ./... fails and builder could not\nauto-fix (status: parked)` and there is no way — not from the dashboard, not\nfrom Telegram chat, not by SSH'ing into the deployment host — to see _why_\n`go build` failed. The container that knew is already gone.\n\nThis matters beyond debugging convenience: supported deployments can combine\na resident daemon with ephemeral Docker containers that run unattended for\nweeks between operator logins, and the system is\nintended to be usable by people other than the original operator. A system\nthat is only debuggable by an operator who happens to be watching `docker ps`\nin real time does not meet that bar.\n\n## Decision: NATS is the sole autonomous handoff\n\nThe agent image must reach NATS in every deployment, because the broker is the\nonly autonomous task handoff and the only channel carrying task results back\nto the daemon. `archied` has no workflow runner or host fallback. A container\nthat dies before establishing a NATS connection is a distinct, narrower\nfailure (connectivity/config) from the one this document addresses (a connected\ncontainer's own output being unrecoverable), and is out of scope here.\n\n## Implemented design\n\nThe key property: **logs leave the container while it is alive**, so its\ndeath at `AutoRemove` no longer matters. Persistence happens in the daemon\nprocess, which already owns durable state.\n\n### Sink: extend `internal/logging`, not a new package\n\n`internal/logging` already owns its on-disk format end to end per\n`organisation.md` (\"a package owns its own format end to end\"). Add a\ntask-scoped writer producing the same `logging.Entry` JSONL shape at\n`\u003cstate_dir\u003e/logs/tasks/\u003ctask_id\u003e/attempt-\u003cn\u003e.jsonl`. `logging.Tail`,\n`logging.Query`, and `logging.Components` operate on this unchanged;\n`internal/webui/api_logs.go` stays transport-only, as it does today.\n\n### Agent side: make the designed subject real\n\n`internal/app/agentworker` replaces the stderr-only `slog.Handler` with one\nthat tees to stderr (kept for container-level operator debugging when a\nshell is attached) and publishes each record to\n`agentexec.SubjectForSystem(taskID)`, which already exists for this purpose.\nThe application layer obtains only a narrow publisher from\n`internal/infrastructure/agenttransport/nats`; raw core-NATS types remain in\ninfrastructure. `internal/infrastructure/agentboot.TaskID` reads the task ID\nfrom `\u003cworktree\u003e/.git/task.json` per the container/pool.go trap documented in\n`CLAUDE.md`. Publishing is fire-and-forget: log shipping must never block or\nfail the run it is reporting on.\n\n### Daemon side\n\n`cmd/archied/main.go` registers `subscribeSystemLogs` once at startup on\n`agentexec.SubjectSystemWildcard`. It demultiplexes by task ID, appends to that task's\nsink, and pLine truncated
},
{
"url": "/dev/architecture/organisation/",
"title": "Repository Organisation",
"section": "Architecture",
"body": "# Repository Organisation\n\n**Status:** Approved \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Target structure\n\nArchie MUST be organised around cohesive application responsibilities:\n\n```tree\ncmd/\n archied/\n archie-agent/\n\ninternal/\n domain/\n \u003carea\u003e/\n eventbus/\n policy/\n infrastructure/\n configuration/\n eventbus/\n nats/\n forge/\n persistence/\n \u003cexternal-service\u003e/\n app/\n archied/\n agentworker/\n\nplugins/\n \u003cplugin\u003e/\ndeployments/\n \u003csupported-assembly\u003e/\ndocs/\n guides/\nexamples/\n \u003ccopyable-example\u003e/\nextras/\n \u003coptional-extension\u003e/\n```\n\nDomain names are chosen from application behaviour during package review.\nExisting names MUST NOT be retained merely to reduce migration work.\n\n## Domain areas\n\nA domain owns one cohesive job performed by Archie. It contains that job's\nlanguage, state, rules, operations, commands, events, policy implementations,\nruntime settings, and required service contracts.\n\nCode that changes together SHOULD live together. Empty or ceremonial `entities`,\n`repositories`, or `services` layers are prohibited.\n\n## Application composition\n\n`internal/app`:\n\n- constructs domains and infrastructure implementations;\n- translates external configuration into domain and plugin settings;\n- connects commands, events, and shared contracts;\n- starts services in dependency order;\n- owns health aggregation and shutdown ordering.\n\n`cmd/*` parses only process-level input and invokes the relevant application\ncomposition package. It MUST NOT contain substantive wiring or act as a service\nlocator.\n\n## Process boundaries\n\nArchie begins as a modular monolith even when capabilities run in separate\nprocesses. A domain becomes a separately deployed service only for a concrete\nneed such as security isolation, independent scaling, failure containment, or\nindependent operation.\n\nPossible future extraction does not justify premature network protocols or\nduplicated service scaffolding.\n\nA new command is not a reason for a new binary. `cmd/` entries are process\nboundaries: a binary earns its place when its surface fails independently of the\nfleet, or when one process may need to run in more than one location, such as a\nhigh-availability pair or across a NAT boundary. Operational commands over a\nsurface an existing binary already owns are subcommands of that binary. Offline\ndatabase maintenance belongs to `archie-state-store`, which owns the file and\nits path layout, not to a new recovery binary.\n\n## Optional and operational material\n\n- `extras/\u003cextension\u003e` contains a maintained optional extension with real\n behaviour. Core Archie MUST NOT import it, and removing `extras/` MUST NOT\n prevent the core application from building or running.\n- `deployments/\u003cassembly\u003e` contains a supported assembly, including deployment\n definitions and concise operational instructions.\n- `docs/guides/` contains handwritten explanation and links to generated\n reference material.\n- `examples/` contains copyable samples with explicit purpose, prerequisites,\n and support expectations.\n\nSupported assemblies SHOULD demonstrate that capabilities can be selected\nindependently.\n"
},
{
"url": "/dev/architecture/package-review/",
"title": "Domain and Feature Review Procedure",
"section": "Architecture",
"body": "# Domain and Feature Review Procedure\n\n**Status:** Active \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchitecture work proceeds one domain or feature at a time. Before any design\nquestion, the selected area is researched across its complete live\nimplementation, consumers, tests, state, configuration, and runtime wiring.\n\nExisting packages are evidence, not the unit that drives the interview.\nPlacement follows behaviour and ownership, not the existing directory name.\n\nNo restructuring implementation begins until the relevant package decisions\nare agreed and recorded in the focused domain or requirement document.\n\n## Required research\n\nBefore design questions, the current-state report MUST identify:\n\n- entry points and runtime composition;\n- state, persistence, and lifecycle;\n- public and internal contracts;\n- commands, events, and policy enforcement;\n- configuration and defaults;\n- all consumers and cross-domain interactions;\n- process and infrastructure boundaries;\n- tests, failure behaviour, and known invariants;\n- duplicated or conflicting implementations;\n- documentation that disagrees with live code.\n\nDiscoverable facts MUST be investigated rather than presented to the user as\ndesign questions.\n\n## Required decisions\n\nEach package review records:\n\n| Decision | Required result |\n| --------------------- | ---------------------------------------------------------------- |\n| Owned behaviour | The cohesive job the code performs |\n| Domain ownership | The owner of the behaviour and vocabulary |\n| Final location | Its target path |\n| Public contracts | The smallest interfaces, commands, and events exposed |\n| Required services | Domain-defined interfaces implemented by infrastructure |\n| State ownership | The owner of each mutable record and transition |\n| Dependencies | Allowed imports and dependencies to remove |\n| Duplication | Code to consolidate, delete, or keep separate |\n| Plugin status | Core domain, shared contract, infrastructure, plugin, or extra |\n| Process boundary | In-process, or the concrete reason for isolation |\n| Configuration | Settings owned by the domain or plugin |\n| Policy | Definitions, evaluators, consequences, and shared mechanics used |\n| Documentation | Authoritative definitions and generated reference |\n| Migration constraints | Behaviour and data that must remain correct |\n\n## Interview method\n\nFor every selected domain or feature:\n\n1. Declare the single area under review.\n2. Complete the current-state research.\n3. Explain actual behaviour in plain technical language.\n4. Separate facts from design decisions and concerns.\n5. Resolve obvious consequences directly and ask only questions whose answer\n materially changes behaviour or structure.\n6. Record each confirmed decision in its focused document.\n7. Complete that area's handoff before selecting another.\n8. Keep unrelated domains outside the implementation scope.\n"
},
{
"url": "/dev/architecture/plugins-and-extensions/",
"title": "Plugins and Extensions",
"section": "Architecture",
"body": "# Plugins and Extensions\n\n**Status:** Approved foundation \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Plugin framework\n\nThe core plugin domain lives under `internal/domain/plugin`. It owns:\n\n- plugin identity and metadata;\n- discovery and registration contracts;\n- lifecycle rules;\n- capability registration;\n- validation and compatibility rules.\n\nThe generic plugin contract remains metadata-only. Functionality is exposed\nthrough narrow typed capability contracts with an owning registry or manager.\n\nWorkflow plugins belong to the Workflow capability family. The Workflow domain\nat `internal/domain/workflow` owns their typed registration, validation,\nversioning, definition, and execution contracts. The generic plugin domain may\nprovide plugin identity, discovery, compatibility, and lifecycle mechanics, but\nit MUST NOT define Workflow semantics or expose untyped Workflow hooks.\n\n## Plugin engine rule (strict)\n\n“Engine” is reserved for a typed, lifecycle-managed capability family. It is not\na synonym for a generic plugin hook. Every new plugin engine must satisfy all of\nthese invariants:\n\n1. **Typed domain contract.** The engine interface exposes real\n capability-specific operations in addition to identity metadata. Examples are\n resolving a secret, delivering a message, or running an agent. A plugin that\n only exposes `Name` and `Version` is metadata, not an engine.\n2. **Owning family manager.** The capability package owns a `Registry` or\n `Manager` that controls provider registration and discovery, initialisation,\n or access. Providers do not register arbitrary callbacks directly on the\n daemon.\n3. **Lifecycle and health.** When an implementation owns resources or background\n work, its typed family contract must expose start, health, and stop\n semantics. The owning manager invokes them and defines failure isolation and\n shutdown ordering. Stateless providers may make these operations explicit\n no-ops.\n4. **Narrow host access.** Plugins receive the typed family registrar and only\n the host services their declared capability requires. They never receive\n `*daemon.Daemon`, a service locator, or an untyped hook map.\n5. **Metadata-only generic plugin contract.** `plugin.Plugin` remains limited to\n `Name()` and `Version()`. Domain hooks belong on typed engine interfaces;\n adding capability methods to the generic interface is forbidden.\n6. **Trust boundary stays explicit.** Explicitly trusted, operator-installed\n plugins—including third-party secret-engine plugins the operator chooses to\n trust—may run in-process and have daemon privileges. Repository-supplied code\n runs in the task container. Integrations that are not trusted as daemon code\n run out of process through MCP or a versioned protocol and, when a\n confidentiality or integrity boundary is required, inside a real container\n sandbox. A subprocess boundary alone is not a security sandbox, and calling\n Yaegi-loaded code a plugin does not isolate it.\n\n`internal/plugin/architecture_test.go` enforces the mechanically testable parts\nof this rule: the generic plugin method set, the shared agent-instruction\nsource, and the requirement that engine interfaces have domain behaviour plus an\nowning registry or manager.\n\n### Memory engine family\n\nOne engine, addressed by four typed scopes -- `ScopeGlobal`, `ScopeAgent`,\n`ScopeUser`, `ScopeAgentUser` (`internal/domain/memory`, `Scope`/`ScopeKind`).\nA caller names exactly the scopes it may read or write; the engine applies no\naccess policy of its own, so isolation falls out mechanically because\n`ScopeAgent{a}` and `ScopeAgent{b}` are different storage keys. See\n`docs/prds/memory-engine-unification.md` for the decision this contract\nimplements; it superseded `internal/memory` (`MemoryProvider`/`Manager`),\ndeleted in that PRD's slice 5.\n\n`MemoryEngine` (`internal/domain/memory/contract.go`) is the typed family\ncontract: `Create`, `Get`, `Query`, `List`, `Update`, `Forget`, `Revisions` --\nCRUD with revisions retained, not just create/read/delete. `Update` supersedes\nrather than overwrites: the superseded state is appended to the scope's\n`HISTORY.md` before the live block is replaced, and `Update` carries no\n`Scope` field, so a record can never change scope. The family's content\nscanner (prompt-injection / sensitive-data patterns) is applied inside\n`Create` and `Update`, the single choke point every producer crosses.\n\n`internal/domain/memory.Registry` is the owning family registry: registration,\nstart/health/stop, shutdown ordering, and failure isolation, following the\nplugin engine rule above. `internal/infrastructure/memory.NewBuiltinEngine` is\nthe only registered engine today; it persists through\n`internal/infrastructure/memory/builtin`, a markdown store (`MEMORY.md`-shaped\nper-scope files) that owns its on-dLine truncated
},
{
"url": "/dev/architecture/policy/",
"title": "Policy System",
"section": "Architecture",
"body": "# Policy System\n\n**Status:** Approved foundation; exact API is deferred \n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nRetry limits, authorisation, gates, commands, protected paths, tool\navailability, and similar rules define or constrain what Archie may do. They\nneed consistent consumption, composition, evidence, and audit without erasing\ntheir different domain meanings.\n\n## Ownership\n\n`internal/policy` is an explicitly approved shared application contract. It is\nnot infrastructure and it is not a generic domain that owns every rule.\n\nThe shared policy system owns:\n\n- policy identity, version, scope, and applicability;\n- typed evaluation invocation;\n- deterministic composition and precedence;\n- common evaluation states such as satisfied, violated, indeterminate, and not\n applicable;\n- reasons and evidence;\n- evaluation audit records;\n- registration, discovery, and lifecycle.\n\nEach consuming domain owns:\n\n- its policy vocabulary and typed inputs;\n- its concrete policy definitions;\n- its evaluators;\n- the meaning and consequence of an evaluation.\n\nAccess therefore owns principals, resources, actions, and authorisation\nconsequences. Task lifecycle owns retry eligibility and exhaustion. Task\nexecution owns gate requirements. Workspace mutation owns protected-path\neffects. Tool execution owns tool and command constraints.\n\nThese policies use consistent evaluation mechanics without pretending their\ndecisions are semantically interchangeable.\n\n## Infrastructure\n\nInfrastructure MAY load, persist, distribute, and audit external policy\nrepresentations. It MUST NOT define what Archie allows or assign the meaning of\na domain policy result.\n\nThe exact Go API, composition operators, precedence rules, and representation\nformat require a focused policy design pass.\n"
},
{
"url": "/dev/architecture/safe-change-and-recovery/",
"title": "Safe Change and Recovery",
"section": "Architecture",
"body": "# Safe Change and Recovery\n\n**Status:** Requirements approved; mechanics are under design. Database-backed settings are implemented through the control plane (2026-09): see the degrade/recovery section below, which records a gap rather than a solution. The full runtime-supervision protocol (bounded observation, versioned audit trail) remains under design.\n**Date:** 2026-07-28 \n**Tracking issue:** [#73](https://github.com/samcharles93/archie-core/issues/73)\n\n## Purpose\n\nArchie is built and improved by agents as well as humans. The architecture MUST\nmake a change easy to locate, understand, test, audit, extend, and reverse\nwithout requiring its author to understand unrelated parts of the application.\n\nSeparation of concerns is therefore an operational safety boundary, not only a\ncode-organisation preference.\n\n## Required outcomes\n\n- An agent can improve a focused feature without receiving authority over\n unrelated domains.\n- Every event, function, action, setting, and policy has an identifiable owner\n and provenance.\n- Source and runtime changes pass deterministic checks outside the actor making\n the change.\n- A rejected or unhealthy candidate cannot replace the last known working\n version.\n- Invalid user configuration does not terminate an otherwise healthy\n application.\n- Configuration and service failures are observable, attributed, and eligible\n for bounded remediation or rollback.\n- The application continues serving unaffected capabilities when one\n capability is misconfigured or unhealthy.\n- Recovery failure is reported and contained rather than hidden in an\n unbounded retry loop.\n\n## Source changes\n\nAgent-authored source changes occur through the task-execution boundary in an\nisolated workspace. The agent does not directly mutate the running\ninstallation.\n\nPromotion is controlled by deterministic repository-owned policy, including\ntests, generated-reference drift checks, protected paths, change scope, and\nother required gates. The actor proposing a change cannot waive these checks.\n\nRepository and domain separation SHOULD allow a task to load and modify only\nthe governing requirements and code for its declared scope.\n\n## Runtime changes\n\nConfiguration and other runtime changes are proposed as candidates rather than\nmutating the active state in place.\n\nThe affected domain owns:\n\n- the command describing the semantic change;\n- validation of its typed settings;\n- health signals that demonstrate correct operation;\n- domain-specific remediation and rollback consequences.\n\nShared policy supplies consistent evaluation, evidence, and audit mechanics.\nIdentity supplies actor attribution. Infrastructure supplies external\nconfiguration storage, service control, and other operational adapters.\n\n## Runtime change protocol\n\nLast-known-good preservation and candidate promotion are the universal runtime\nchange protocol.\n\n1. An identity proposes an immutable candidate version.\n2. Infrastructure parses it without changing active state.\n3. Each affected domain validates its typed settings.\n4. Shared policy evaluates cross-cutting constraints.\n5. Each affected capability prepares the candidate without destroying its\n active instance.\n6. Capability-specific health checks prove the candidate works.\n7. Runtime supervision atomically promotes the candidate.\n8. A bounded observation period watches for delayed failure.\n9. Failure restores the last-known-good version and records the reason,\n evidence, actor, and involved versions.\n10. Repeated remediation failure stops retrying, isolates the capability, and\n reports the fault.\n\nThe affected domain owns the semantic change command, typed validation, health\nsignals, and remediation consequences. Shared runtime supervision owns the\npromotion transaction. Infrastructure performs storage and service-control\noperations.\n\nThe protocol's exact Go contracts, storage model, atomicity boundary, and\nobservation rules require a focused runtime-supervision design pass.\n\n## Failure isolation\n\nInvalid input MUST leave the active valid configuration unchanged and produce a\ndiagnostic record.\n\nA capability that cannot start or reload SHOULD fail independently where its\nabsence does not violate a declared application invariant. Unaffected\ncapabilities continue operating.\n\nRemediation MUST be bounded, observable, and policy-driven. Recovery MUST NOT\nsilently oscillate between versions or retry forever.\n\n## Database settings: degrade paths and recovery (2026-09)\n\nThe control plane owns runtime-tunable settings and stores them in the State\nStore's PostgreSQL database.\nThis replaced a dashboard overlay store that degraded to file config on any\nfailure and had three documented ways back. The replacement has none, and the\nposture is the opposite: **the daemon fails closed.**\n\n### Degrade paths\n\n| Failure Line truncated
},
{
"url": "/dev/development/",
"title": "Development guides",
"section": "Development",
"body": "# Development guides\n\nChecklists for changing Archie, one page per area. Each names every place a\nchange must reach, so a feature that works in one layer does not silently stop\nat the next. A change that spans areas starts on the page for the area it\nbegins in, which points to the others. The pages point at the documents that\nown the design (`docs/architecture/`, the PRDs, `CLAUDE.md`) rather than\nrestating them.\n\n| Area | Covers |\n| ---------------------------------------------- | -------------------------------------------------------------------------------- |\n| [Frontend UI](/dev/development/frontend-ui/) | Anything under `ui/`, and the dashboard's API routes |\n| [Agent](/dev/development/agent/) | The agent container, its image, profiles, tools and workspace |\n| [Workflows](/dev/development/workflows/) | Workflow definitions and step types |\n| [Daemon](/dev/development/daemon/) | Task statuses, fields and the brief; sources, event types, mappings and bindings |\n| [State Store](/dev/development/state-store/) | Stored fields, tables, RPCs and errors |\n| [Control plane and settings](/dev/development/control-plane/) | Settings in `config.toml` or the dashboard |\n| [Processes and wiring](/dev/development/wiring/) | Where code goes, processes, plugin engines, channels, NATS subjects |\n| [Merging work](/dev/development/merging-work/) | Merging a lane or a branch |\n\n## Every change\n\n- Write the failing test first for anything with logic, branching or a\n contract, and check it fails on an assertion, not a compile error.\n- Test through the path production uses. A test that sets a value directly on\n the consumer proves nothing about the layers that normally deliver it.\n- Run `task check` and let its exit status decide the commit:\n `task check \u0026\u0026 git commit ...`. `task test` passes `-short`, which skips the\n process and Postgres tests, so run `go test -count=1 ./cmd/... ./internal/...`\n too when a change crosses a process or the database.\n- Regenerate, never hand-edit, generated output: `task proto:generate`,\n `go -C tools tool sqlc generate -f $PWD/internal/infrastructure/postgres/sqlc.yaml`,\n `task ui`, `task docs:artifact`. `task proto:check` compares against the git\n index, so stage regenerated contracts before running it.\n- Stage by path, or read `git status` before `git add -A`. Tests that start\n embedded NATS or write logs must use `t.TempDir()`; anything they leave in the\n tree gets committed. `task check` writes no module file on a consistent tree,\n root or `tools/` (verified at HEAD with `GOFLAGS` unset and with `-mod=mod`):\n a stale `go.mod` or `go.sum` fails it, with `missing go.sum entry` or\n `updates to go.mod needed`, rather than being repaired. Only a global\n `GOFLAGS=-mod=mod` in `go env` re-enables that repair, which is why the\n `go -C tools` steps pass `-mod=readonly`; if `go.sum` goes dirty, run\n `go mod tidy` and commit the result on its own.\n- A change to `docs/prds/`, `docs/architecture/` **or `docs/development/`**\n carries the regenerated `docs/data/generated/dev-docs.json`: run\n `task docs:artifact` (not `task docs:check`, which checks contracts only).\n PRD edits also follow `docs/prds/RULES.md` and pass `task docs:prds`.\n"
},
{
"url": "/dev/development/agent/",
"title": "Agent",
"section": "Development",
"body": "# Agent\n\nAuthority: `docs/architecture/agent-system.md` (execution boundary, the model\nnever runs git) and the Deployment Model section of `CLAUDE.md`.\n\nThe daemon prepares a workspace, starts one container per task from a profile's\nimage, and hands the whole task to `archie-agent` over NATS in one\n`taskrun.Request`. The agent reaches the State Store, forge and worktree push\nonly through the daemon's RPC servers, using task-scoped credentials.\n\n## Giving the agent something new\n\n- **Data about the task** goes in `taskrun.Request` or the task brief\n (`container.TaskPayload`), never in an environment variable. Add a test that\n the request carries it (`TestRunViaAgentSendsMCPServers` is the pattern).\n- **A credential** is scoped to the task and revoked when it ends, like the\n State Store grant and the worktree publication grant. The daemon's own\n administrative token never enters a container.\n- **A tool** reaches the agent through the central registry, MCP, a repository\n script or a skill plugin. A profile's `tools` list filters those; ai-sdk\n agentloop's built-in file tools are outside it. A tool that must stay inside\n the workspace uses the agent loop's confinement, not its own path handling.\n\n## Changing the agent image or a profile image\n\n1. The agent image is `Dockerfile`; example profile images live in\n `examples/profiles/`, each with a build-only service in\n `docker-compose.yml` (`profiles: [\"build\"]`, so `up -d` never starts it).\n2. Anything the agent runs must be in the image. The container gets no\n package manager at run time beyond what the image ships.\n3. A locally built image needs `containers.pull_policy = \"missing\"`;\n `\"always\"` tries to pull it and fails.\n4. Profiles are configured under `[containers.profiles.\u003cname\u003e]` and resolved\n by the daemon before the container starts (`pinTaskProfile`). An unknown\n profile parks the task; it never falls back to the default image.\n\n## Changing how a task runs\n\n- Workspace preparation happens in the daemon (`prepareWorkspace`) before the\n container starts, because the container binds the directory. Clones need the\n daemon's forge credential; the agent never clones.\n- A task with no repository gets `worktree.Manager.ScratchDir`, which is\n removed when the task ends.\n- The agent runs as root in the container. Anything it writes into the\n bind-mounted workspace is handed back to the daemon's UID\n (`restoreWorktreeOwnership`); a new write path must stay inside that\n workspace.\n- NATS rules are in `CLAUDE.md`: task responses use `msg.Respond`, a responder\n is flushed after it registers, and `ARCHIE_TASKS` is a work queue.\n"
},
{
"url": "/dev/development/control-plane/",
"title": "Control plane and settings",
"section": "Development",
"body": "# Control plane and settings\n\nAuthority: `docs/architecture/configuration.md`. The wiring matrix, the\ndecoded-but-unwired ledger and the three shapes an unwired field takes are in\n`.agents/skills/archie-config-and-flags`.\n\nA field that parses is not a field that works. Before adding one, name the code\nthat reads it and the path the value takes to get there.\n\n## Decide what kind of setting it is\n\n- **Bootstrap-only** (read once at process start: `database_url`, `state_dir`,\n `work_dir`). It stays in the file, is checked by `validateBootstrap` in\n `internal/infrastructure/configuration/validate.go`, and the runtime overlay\n refuses changes to it.\n- **Database-owned** (repository policies, scheduling, tools, plugins,\n channels, containers). The file only seeds it. Once the State Store holds the\n control-plane resource, the stored document is layered over the file\n (`controlplane.Client.RuntimeConfig`) and the file key stops mattering. It is\n checked by `validateDatabaseOwned` and by the resource's validator. A stored\n value is refreshed from the file only when the store has no value for the kind\n at all; a kind that ships a document of its own (workflow definitions,\n personas) is refreshed whenever the seed itself wrote the stored copy, since\n that copy is a previous release's document rather than an operator's\n (`controlplane.Server.seedKind`).\n- **Worker-carried.** A value the agent container needs travels in\n `config.TaskConfig` (`Config.ForTask`) or on `taskrun.Request`. Never pass it\n as an environment variable the daemon did not already define, and never carry\n a secret this way.\n\n## Adding a database-owned field\n\n1. Add it to the wire-shape type the resource's `Document` names — a dedicated\n struct in `internal/app/controlplane/` with explicit snake_case json tags\n (`channel_settings.go`, `tool_settings.go`, `container_settings.go` are the\n precedents), never the internal config struct itself. A struct fed straight\n into the document falls back to Go field names (`Window`, `MaxRequests`),\n and a bare `time.Duration` marshals as nanoseconds — both render unusable\n in the Web UI. The resource's JSON schema and the dashboard's Advanced\n settings editor are generated from that type, so no UI work is needed for\n the editor itself.\n2. Map to and from the internal config type at the resource boundary (`Seed`,\n the layering in `runtime_config.go`, and the validator all use the same\n mapping). Durations in the document are a string-marshalling type\n (`config.Duration` or a document-local one), never a bare `time.Duration`.\n3. A document stored before the shape existed carries Go-cased keys. Read them\n with `controlplanerpc.DecodeRenamingLegacyKeys` (an `UnmarshalJSON` on the\n wire type) while keeping `DisallowUnknownFields` — dropping unknown keys\n would decode a misspelling as \"unset\" — and register a `Normalize` on the\n `Definition` that re-encodes the document, so a legacy document converges\n the next time it is written. A map or a nested struct needs its layering\n checked: a stored map replaces the file's, not merges into it, and a field\n the stored document omits keeps the file's value. Add a case to\n `internal/app/controlplane/runtime_config_test.go` for both.\n4. Validate it in one function both sides call, and add a case to\n `TestResourceValidatorsRejectWhatEffectiveValidationRejects` in\n `validators_agree_test.go`, so the file and the resource cannot disagree.\n5. Decide whether it reloads: it does only if every consumer re-reads it from\n `config.Holder`. The allowlist is `internal/app/archied/reload.go`; anything\n not on it requires a restart.\n6. If the settings page shows it as a plain field, add it to\n `internal/webui/config_schema.go` and the view in `api_config.go`.\n7. A generic catalog resource (`replace` command, not domain-managed, no\n query service) is watched **once per archie-ui process** by `webui.RunLive`,\n then published to every browser through `/api/stream`. Do not add an\n EventSource per resource to a settings store or a gRPC Watch per HTTP client.\n The control-plane server polls `Resource` every 250ms per upstream Watch;\n verify watch count is independent of client count and that late clients get\n the hub's current value (`internal/webui/live_hub_test.go`, real server over\n bufconn). Reopens resume after the last delivered version and charge failed\n attempts; accepting a gRPC stream does not establish its health.\n\n## Every new field\n\n- Test through the layering: build the effective config the way boot does,\n not by setting the field on the consumer.\n- Add a commented example to `config.example.toml`. Touch `deployments/*.toml`\n only when a profile there needs a value different from the default.\n- Update the wiring matrix in `.agents/skills/archie-config-and-flags`.\n- Secrets are `SecretRef`s resolved throLine truncated
},
{
"url": "/dev/development/daemon/",
"title": "Daemon",
"section": "Development",
"body": "# Daemon\n\nThe daemon claims and runs tasks, and turns captured events into tasks through\nbindings. This page covers both.\n\n## Task lifecycle\n\nAuthority: `docs/architecture/agent-system.md`. The status vocabulary lives in\n`internal/taskstate`, which imports no internal package.\n\n### Adding a status\n\n1. Add the constant to `internal/taskstate/taskstate.go` and place it in\n `Terminal`, `Actions` and `Statuses`. Its value is stored, so renaming it\n later is a migration.\n2. Alias it in `internal/domain/workflow/task/task.go` and\n `internal/domain/workflow/task_aliases.go`.\n3. Add it to the default catalogue in `ui/src/lib/task-meta.ts`. The server\n catalogue replaces the defaults when it loads, but the defaults render first.\n4. Find every hand-written status list in SQL:\n `grep -rn \"'merged'\" internal/infrastructure/postgres/queries`.\n `ClearTerminalTasks` must match `taskstate.Terminal`, which\n `TestClearTerminalTasksMatchesTaskstate` enforces. The stats queries count\n outcomes by name; decide whether the new status counts.\n5. Extend the table in `taskstate_test.go`.\n\n### Adding a task field\n\nFollow [State Store](/dev/development/state-store/) for the\ncolumn and the wire. Then decide who writes it: `UpdateTask` writes a fixed\ncolumn set, so a field set at enqueue belongs in the insert that creates the\nrow (as `InsertChatTask` does for inputs), or in its own statement when only\nsome producers set it (as `StampTaskBinding` does for binding provenance).\n\n### Changing what the agent receives\n\n- The task brief is `container.TaskPayload`, written to\n `\u003cworkspace\u003e/.git/task.json` by `WriteTaskJSON`. Never write it to the\n workspace root: the commit stage stages everything there.\n- The run request is `taskrun.Request`. `Validate` rejects a request that\n cannot run; a new requirement goes there.\n- Parking always carries a class (`taskstate.ParkTransient`,\n `ParkNeedsHuman`, `ParkTerminal`) chosen by the code that parks. Pick the one\n that says what an operator must do.\n- A task with no repository (`Task.HasRepository`) runs in a scratch workspace\n with no worktree grant. Code that assumes an owner and repo must check first.\n\n## Event automation\n\nAuthority: `docs/prds/event-automation.md` (the model: source, event type,\nmapping, binding, workflow, profile) and `docs/architecture/bindings.md`\n(threat model).\n\n### Where each check lives\n\nA binding is checked twice, and a new rule usually belongs in both places:\n\n- **On save**, in `checkedBinding` (`internal/webui/api_binding.go`), so the\n operator sees the problem while editing. It calls the domain checks\n `binding.Validate`, `binding.CompileFilter` and `Binding.CheckWorkflow`.\n- **At dispatch**, in `dispatchOneBinding` and `resolveBindingTarget`\n (`internal/daemon`), because the workflow or mapping may have changed since\n the save. A refusal is recorded with `recordDispatchFailure` and starts no\n task.\n\nPut the rule itself in `internal/domain/binding` or\n`internal/domain/workflow/task` and call it from both, rather than writing it\ntwice.\n\n### Adding a binding field\n\n1. Domain type and `Validate` in `internal/domain/binding`.\n2. Column, queries, store mapping, wire field, `newColumns`\n ([State Store](/dev/development/state-store/)).\n3. The request type and `checkedBinding` in `api_binding.go`.\n4. The draft, payload and editor in `ui/src/bindings/`\n ([Frontend UI](/dev/development/frontend-ui/)).\n5. Its effect at dispatch, with a case in\n `internal/daemon/dispatch_inputs_test.go` or `dispatch_bindings_test.go`.\n\n### Rules that must hold\n\n- Signing belongs to the source. Intake verifies the HMAC against the source's\n secret before the payload is parsed.\n- An event must be identified as an event type before anything dispatches it,\n and a binding applies only to its mapping's event type. Dispatch test\n fixtures therefore create an event type before inserting captures.\n- The dispatch ledger is claimed before the task is enqueued (at most once).\n- Anything an event supplies that selects what the agent acts on, such as a\n repository, must be checked against configuration. An event never widens\n what an agent can reach.\n"
},
{
"url": "/dev/development/frontend-ui/",
"title": "Frontend UI",
"section": "Development",
"body": "# Frontend UI\n\nAuthority: `.agents/skills/archie-web-ui` (stack facts, design-system rules,\ntone and accessibility). This page covers what a change must reach, not how it\nshould look.\n\n## Adding or changing a feature\n\n1. The feature lives in `ui/src/\u003cfeature\u003e/`. Move a helper to `ui/src/base/`\n only when a second feature needs it.\n2. Keep wire shapes, draft state and payload building in a plain `.ts` module\n beside the components (`ui/src/bindings/binding-draft.ts` is the pattern),\n and test it in `ui/test/*.test.ts`. Components stay thin.\n3. Every mutation goes through `api.*` in `ui/src/lib/api`, which sends the\n CSRF and Content-Type headers the server's mutation guard requires. A bare\n `fetch` is refused.\n4. A value the server also describes (task statuses, actions, workflow inputs)\n comes from the server. Keep a local default only so the first render works,\n and keep it in step (`ui/src/lib/task-meta.ts`).\n5. Run `task ui`, `task test:ui` and `cd ui \u0026\u0026 npm run typecheck`. Commit the\n regenerated `ui/dist/`; the Go binaries embed it. A fresh git worktree has\n no ignored `ui/node_modules`: run `cd ui \u0026\u0026 npm ci` before these commands.\n6. **One long-lived browser connection:** `ui/src/lib/api.ts` has the only\n `new EventSource`, owned by `stores/live-updates.ts`. Feature stores consume\n topics with `live.subscribe(topic, callback)`; do not open a page-owned SSE\n stream. Logs alone opt in while mounted, replacing that same EventSource\n with `?topics=logs\u0026since=\u003clast cursor\u003e`; a browser's `Last-Event-ID` only\n survives its own automatic reconnect, not a newly constructed EventSource.\n Task and log topics resume by cursor; control-plane, identity and apply-status\n topics replay the latest snapshot. Test a fetch and same-origin navigation\n after visiting Settings and Logs: the UI process serves HTTP/1.1 and six\n persistent streams can starve every later browser request.\n\n## Testing the dashboard\n\nAuthority: the runner itself is `ui/package.json`'s `test` script: `node --test\n--experimental-strip-types test/*.test.ts` over `ui/test/*.test.ts`. It runs\npure TypeScript modules with `node`'s type stripping — no SFC loader, no DOM,\nno second dependency beyond what the app already carries. That is the standard,\nand a decision record for when it is deliberately not enough:\n\n- **Test archie's logic in a module; leave SFC wiring alone.** Wire shapes,\n draft state, copy conditions, filters and payload building live in plain\n `.ts` files beside the components and are tested in `ui/test/`. Components\n stay thin, so there is normally nothing in an SFC that is archie logic.\n- **A dashboard rule that mirrors a server rule is pinned by a shared\n fixture, not two independent tests.** `ui/src/settings/validation.ts`\n hand-mirrors three control-plane validators, and the model-role rule had\n already drifted because nothing tied the two sides together. Each case now\n lives once in `internal/app/controlplane/testdata/dashboard-validators.json`:\n a Go test in that package runs the real server validators over it, and\n `ui/test/control-plane-validator-parity.test.ts` runs the real dashboard\n validators over the same cases. Changing one rule alone fails the other\n side's test. Add a case to the fixture, never to one side only.\n- **Installed primitives are upstream-tested, not re-tested here.**\n `reka-ui` (2.10.5 here) maintains colocated tests per component in its own\n repo (Vitest/jsdom + axe: Switch, TagsInput, NumberField, Select, the\n arrow-navigation composables). The npm package ships none of those files, so\n this coverage is inherited through the version bound, not the tarball —\n `grep -l test node_modules/reka-ui` finds nothing. Duplicating them as local\n mount tests would test a dependency.\n- **A `.vue` import cannot run under the module runner.** `node --test` fails\n such a module with `ERR_UNKNOWN_FILE_EXTENSION: .vue` and the runner has no\n built-in loader for SFCs. A file under `ui/test/` that imports a `.vue` is\n therefore a broken test, not a weak one.\n- **If a DOM mount harness is ever needed** (a page-level accessibility\n contract, cross-component interaction, focus behaviour): `happy-dom` +\n `@vue/test-utils` + `vitest` scoped to a separate DOM test glob, keeping the\n module runner for everything else. Measured on the ui tree (vitest 5.0.2,\n happy-dom 20.14.5, @vue/test-utils 2.5.1): they add 24 top-level\n `node_modules` entries and 27 MB on a 296 MB install, a working 2-test mount\n suite (role=radiogroup vs role=switch, aria-label, click activation against\n the real SFCs) runs in 1.2 s on top of the current 0.5 s module suite, and\n `vue-tsc` (7.4 s) dominates `task test:ui` either way. The single-runner\n alternative (absorbing the existing suite into vitest) was measured\n infeasible as-is: all 29 existing files impLine truncated
},
{
"url": "/dev/development/merging-work/",
"title": "Merging work",
"section": "Development",
"body": "# Merging work\n\nParallel lanes (see `.agents/skills/archie-agent-fleet`) merge into an\nintegration branch before `main`. Each merge is a change in its own right and\npasses the same gate.\n\n## Resolving conflicts\n\n- **Generated files** (`*.pb.go`, `postgresdb/*.go`, `ui/dist/`,\n `docs/data/generated/*.json`): take either side, then regenerate. Never merge\n them by hand.\n- **One side deletes a file, the other edits it**: the deletion wins when the\n deleting lane replaced the thing the file served. Move the other side's\n change onto its replacement.\n- **One side changes how code is built (a new store, renamed packages), the\n other what it does**: take the behaviour side's version and reapply the\n mechanical change to it. That is usually cleaner than merging line by line.\n- **Error sentinels** are rows in `wireErrors`, not switch cases.\n\n## After resolving\n\n1. Search for leftovers of anything the other side removed: the old package\n path, the old type, and comments describing the old behaviour.\n2. Tests written against one side's semantics may pass there and fail after\n the merge. A test that used to pass on the old store may be asserting a rule\n the other side deliberately changed. Fix the test's setup to the merged\n rule; do not loosen the rule to the test.\n3. Run the full suite without `-short`, then `task check`, then commit. Check\n `git status` for files a test wrote into the tree before staging.\n4. **A merge can surface a bug neither lane's own tests exposed alone.** Two\n real cases from 2026-09-26: a test that dialled no NATS URL passed on a\n machine with an ambient dev server running and failed the moment it landed\n on a clean CI runner (start an ephemeral server per test, never rely on a\n default port resolving to something); and a cycle-detector that walked a\n Go map in range order reported the same cycle two different ways from run\n to run, invisible until enough fresh (uncached) runs hit the unlucky\n ordering. Both looked like \"the merge broke a passing test\" but were\n latent defects the merge only had the opportunity to expose. Fix the\n defect the failure is pointing at, not the assertion that caught it — see\n CLAUDE.md's test-quality bar before writing the replacement.\n5. `go test`'s cache reuses a package's last result when nothing in its\n dependency graph changed. A merge that touches one package can leave a\n sibling's flaky test silently cached \"pass\" locally while CI runs it\n fresh. `task check` passing on your machine is not proof a merge is\n clean — rerun anything nondeterminism-prone with `-count=1` before\n trusting it, and let CI's from-scratch run be the tiebreaker it is.\n"
},
{
"url": "/dev/development/state-store/",
"title": "State Store",
"section": "Development",
"body": "# State Store\n\nAuthority: `docs/prds/state-store-contract.md` and the State Store section of\n`CLAUDE.md`. All persistence is PostgreSQL behind the standalone State Store\nprocess; nothing else opens the database.\n\n## Adding a column\n\n1. Write the next migration in `internal/infrastructure/postgres/migrations/`\n (`00NN_name.sql`, goose Up and Down). Give the column a `NOT NULL DEFAULT`\n that is correct for existing rows.\n2. Update the queries in `internal/infrastructure/postgres/queries/` and\n regenerate with sqlc. A query that lists columns (`ListTaskSummaries`, the\n binding selects) does not pick the new one up; `SELECT *` queries do.\n3. Map it in the store (`taskFromRow`, `bindingValue` and friends). If the\n column holds encoded data, the package that owns the type owns the encoding\n (`task.EncodeInputs`), and the store and the wire both use it.\n4. Carry it over the wire (next section) if any process other than the State\n Store reads it.\n\n## Adding a field to a wire message\n\n1. Add it to `proto/state/v1/state.proto` with a new field number. Never reuse\n a number; retire one with `deprecated = true`.\n2. `task proto:generate`, then map it both ways in\n `internal/infrastructure/staterpc/values.go`.\n3. `TestTaskProtoCarriesEveryDomainField` fills every `task.Task` field and\n fails on one the mapping forgets. If it cannot fill the field's kind, extend\n it. Other messages have no such test, so add a round trip to\n `conformance_test.go`.\n\n## Adding an RPC or a store method\n\n1. Put the Go method on the narrow consumer interface in\n `internal/domain/storecontract` (keep each at eight methods or fewer) and add\n the matching RPC. A Go method without an RPC does not cross the process.\n2. Implement it in the Postgres store, in `staterpc.Client` (with its `var _`\n assertion) and in `staterpc.server`. A missing dependency answers\n `codes.Unavailable`, never a fabricated default.\n3. Wire the dependency in every composition that serves or consumes it:\n `stateStoreDeps` in `internal/app/archied/state_store.go`, the daemon's\n assertions in `bootstrap.go`, and `internal/app/archieui/compose.go` for the\n dashboard process.\n4. Task-scoped tokens may call only `Update`, `Transition` and `InsertEvent` on\n their own task (`staterpc.TaskGrants`). A new RPC is admin-only unless it is\n added there deliberately.\n5. Add it to `conformance_test.go`, which runs every surface over a real gRPC\n connection.\n\n## Adding an error sentinel\n\nAdd the sentinel to `storecontract`, a row to `wireErrors` in `values.go`, and\na case to `error_test.go`. The canonical message is part of the wire contract:\nchanging it breaks `errors.Is` on the client silently.\n\n## Harness OAuth secrets\n\n`HarnessSecretStore` stores token sets by org and credential service through\nadmin-only State Store RPCs. The EDA store seals them with the binding cipher's\nkeyring and a separate `HarnessSecretDomain`. OAuth writes require a configured\nbinding encryption key; the legacy binding plaintext fallback does not apply.\nThe daemon's egress proxy (`internal/infrastructure/egress/oauth.go`) is the\nonly daemon consumer: for a run granted the service it swaps sentinels for the\nstored tokens and writes every refresh back. The setup terminal is a separate\nharness slice.\n"
},
{
"url": "/dev/development/wiring/",
"title": "Processes and wiring",
"section": "Development",
"body": "# Processes and wiring\n\nAuthority: `docs/architecture/organisation.md` (layers, process boundaries),\n`docs/architecture/dependencies-and-contracts.md` (dependency direction, wire\ncontracts) and `docs/architecture/plugins-and-extensions.md` (the plugin engine\nrule).\n\n## Placing new code\n\n- Domain logic, entities and the interfaces it needs go in\n `internal/domain/\u003carea\u003e/`, which imports no infrastructure or app package.\n- Implementations of those interfaces go in `internal/infrastructure/\u003cservice\u003e/`.\n- Construction and wiring go in `internal/app/\u003capplication\u003e/`; `cmd/` only\n parses flags and calls it.\n- `logging`, `events`, `eventbus`, `policy` and `taskstate` import no internal\n package. There is no `shared/`, `utils/` or `common/` package.\n- A behaviour has one authoritative path. Before adding a second way to do\n something, remove or redirect the first.\n\n## Adding a capability to a process\n\n1. Decide which process owns it. A new binary is justified only when the\n surface must fail, scale or run somewhere independently.\n2. Wire it at that process's composition root. An optional capability\n degrades: a missing provider logs a warning and marks health degraded\n rather than stopping the process (MCP providers are the model).\n3. Every process that reaches the capability through the State Store gets it\n through a `storecontract` interface asserted on the client\n ([State Store](/dev/development/state-store/)).\n4. The architecture tests (`cmd/archie-ui/architecture_test.go`,\n `cmd/archie-messaging/architecture_test.go`, `TestOpenStoresNeverOwnsTaskDB`)\n pin what each binary may link. A failure there means the placement is wrong,\n not the test.\n\n## Adding a plugin engine\n\nSatisfy every invariant in \"Plugin engine rule (strict)\" in\n`plugins-and-extensions.md`: typed domain contract, an owning manager,\nlifecycle and health, narrow host access, and an explicit trust boundary.\n`internal/plugin/architecture_test.go` checks the parts that can be checked.\n\n## Adding a channel or a NATS subject\n\n- Channel rules (Telegram's pending-update drop, command scopes) are in\n `CLAUDE.md` under Per-Package Invariants.\n- A subject is part of the wire contract. Its payload type belongs to the\n domain that defines its meaning, and the transport code lives in\n infrastructure.\n"
},
{
"url": "/dev/development/workflows/",
"title": "Workflows",
"section": "Development",
"body": "# Workflows\n\nAuthority: `docs/architecture/agent-system.md` for the lifecycle,\n`docs/prds/event-automation.md` for inputs, repository modes and profiles.\n\nWorkflow definitions are YAML stored as a control-plane resource. The State\nStore validates them and the agent compiles them, each against the step\nvocabulary it registers, so both must see the same step types.\n\n## Adding a step type\n\n1. Write the factory in `internal/domain/workflow` as a `StepType`. It decodes\n and validates its settings and returns an error for anything it cannot\n honour. The factory runs when a definition is saved and again when it is\n compiled, so a bad definition is refused on save.\n2. Register it through a provider in\n `internal/infrastructure/workflowsteps/workflowsteps.go`. That one list is\n what every process registers, which is how the validating and executing\n sides agree.\n3. An agent-driven step builds on `AgentStage`; do not start a second path to\n the agent runner.\n4. A step that needs no repository goes in `repoFreeStepTypes` in\n `definition.go`, or workflows declaring `repository: none` or `optional`\n cannot use it. A step that needs one may assume `tc.Dir` holds a worktree\n only when the workflow's repository is `required`.\n5. A step that ends the workflow sets `tc.Outcome`. A workflow that runs out of\n steps without an outcome is parked as a definition bug.\n6. Add a parse test (settings accepted and refused) and a run test with fake\n `Trees` and agent runner.\n\n## Retiring a step type\n\nA step word cannot simply be deleted. A stored or pinned definition is\nvalidated as a whole collection, so one unknown word fails EVERY workflow's\ndefinition to decode and the workflow-definitions resource becomes unreadable.\nRetire a stage by removing it from its workflow's `Stages` and adding it to\n`retiredSteps` in `definition.go`, which keeps the word resolving as an inert\nstage. The retired stage must do nothing: the behaviour it used to perform now\nbelongs to whatever layer took it over (the remediate workflow's in-container\nresume moved to daemon worktree preparation, `archie-core-866m`; the workflow\nstill binds the daemon-prepared directory and the PR branch in a `prepare`\nstage before any agent work).\n\n## Changing the definition format\n\n- The fields a caller needs without the engine (inputs, repository, profile)\n live in `task.WorkflowInterface`, because the dashboard process must not\n import the workflow engine (`cmd/archie-ui/architecture_test.go`). Anything a\n binding or the dashboard checks goes there.\n- The YAML decoder rejects unknown keys. Existing stored definitions must keep\n parsing, so a new key is optional with a default that preserves today's\n behaviour.\n- A declared `outputs:` entry is written through a capture tool, so it forces\n the captures need: `task.WorkflowInterface.Needs` resolves that from the\n declaration rather than the author also writing `needs.captures`. A Kit\n profile whose harness serves no capture tools is refused before dispatch.\n- Examples in `examples/workflows/` are parsed against the registered\n vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.\n\n## Enabling and disabling\n\nThe `workflow-enablement` control-plane resource lists, per org, the workflows\nthat org has disabled; anything unlisted is enabled. Its readers are the\ndaemon's binding dispatch (a disabled workflow's binding is skipped like an\nunarmed one), the dashboard's binding save (refused) and binding list\n(`workflow_disabled`), and work requests. A new reader of \"may this org run\nthis workflow\" goes through `task.WorkflowEnablement.Enabled`, never a second\nlist. The dashboard acts in the default org until access resolves a caller's\nown.\n\n## Starting a workflow from chat\n\n`task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards\ninputs through the task creation contract; it does not interpret individual\nworkflows. The daemon checks inputs against the pinned `WorkflowInterface`\nbefore acquiring a container and parks invalid requests with the reason.\n"
},
{
"url": "/dev/prds/01-project-management/",
"title": "Architecture Decision Index",
"section": "PRDs",
"body": "# Architecture Decision Index\n\n**Status:** Approved \n**Date:** 2026-07-28 \n**Beads issue:** `archie-core-5d7`\n\n## Purpose\n\nThis file is the navigation point for Archie's target architecture. It is\ndeliberately short. Architectural decisions are separated by domain or\nrequirement so an implementation task can load only the rules governing its\nscope.\n\nImplementers MUST read the decision document for the domain or requirement they\nare changing. They MUST NOT infer permission to change neighbouring domains from\na broader restructuring objective.\n\n## Global invariants\n\n- Organise code around cohesive application responsibilities, not generic\n technical mechanisms.\n- Domains own their behaviour, vocabulary, state, commands, events, policy\n implementations, runtime settings, and required service contracts.\n- Domains do not depend on infrastructure or manipulate another domain.\n- `internal/app` owns composition; `cmd/*` remains thin.\n- Cross-domain work uses an explicitly owned command, event, or approved shared\n contract.\n- Process boundaries are deployment choices and do not determine source-code\n ownership.\n- Existing package names and boundaries have no presumption of survival.\n\nThe words **MUST**, **MUST NOT**, **SHOULD**, and **MAY** are normative.\n\n## Decision documents\n\n| Scope | Authoritative document |\n| --------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |\n| Repository layout, domains, composition, deployments, and optional material | [architecture/organisation.md](/dev/architecture/organisation/) |\n| Dependency direction, domain contracts, infrastructure, commands, events, and wire contracts | [architecture/dependencies-and-contracts.md](/dev/architecture/dependencies-and-contracts/) |\n| External configuration, runtime settings, and dissolution of `internal/config` | [architecture/configuration.md](/dev/architecture/configuration/) |\n| Persistent actor identity, ownership, lifecycle, and attribution | [architecture/identity.md](/dev/architecture/identity/) |\n| Agent definitions, workflows, workflow executions, tools, and worker boundaries | [architecture/agent-system.md](/dev/architecture/agent-system/) |\n| Personal-assistant interactions, messaging channels, and optional promotion into durable work | [architecture/messaging-and-work-intake.md](/dev/architecture/messaging-and-work-intake/) |\n| Shared policy evaluation and domain-owned policy semantics | [architecture/policy.md](/dev/architecture/policy/) |\n| Safe source/configuration changes, health supervision, and recovery | [architecture/safe-change-and-recovery.md](/dev/architecture/safe-change-and-recovery/) |\n| Plugin framework, plugin implementations, and extension isolation | [architecture/plugins-and-extensions.md](/dev/architecture/plugins-and-extensions/) |\n| Generated references, deprecations, and changelog generation | [architecture/generated-documentation.md](/dev/architecture/generated-documentation/) |\n| Remaining package destinations, data migrations, runtime cutover, and completion criteria | [architecture/migration-decisions.md](/dev/architecture/migration-decisions/) |\n| Domain/feature research, design interview, and required handoff | [architecture/package-review.md](/dev/architecture/package-review/) |\n\n## Deferred decisions\n\nThe remaining package-placement, data-migration, shared-mechanics, process-\nboundary, and cutover decisions are maintained in\n[architecture/migration-decisions.md](/dev/architecture/migration-decisions/).\n\nEach decision is made in its focused document after code-grounded review.\n"
},
{
"url": "/dev/prds/RULES/",
"title": "PRD writing rules",
"section": "PRDs",
"body": "# PRD writing rules\n\nThese rules apply to every file in `docs/prds/`.\n\n- Search existing PRDs, issues, architecture records, and code first. Do not ask\n the maintainer to repeat recorded requirements.\n- A newer maintainer decision overrides an older design. Mark the old design as\n superseded instead of preserving or defending it.\n- Write plain English. Use a technical term only when the reader needs that\n exact contract or concept.\n- Use the shortest direct sentence. Write “When upgraded, existing instances\n are migrated to the database,” not a description of an importer seeding\n absent resources.\n- State each fact once. Do not repeat a heading, summarise a list before showing\n it, or restate a decision afterward.\n- Every sentence must add a decision, requirement, constraint, evidence, or\n verification step. Delete narration and explanations of obvious text.\n- Do not turn a requested outcome into extra product features. Keep inferences\n open until the maintainer or repository evidence settles them.\n- Do not create a process for a logical boundary. Add one only when it must\n deploy, scale, start, secure, or fail separately.\n- Describe working behaviour, not explanatory UI around missing behaviour. State\n what users can do and how success is proved.\n- Before approval, use independent read-only reviewers to check a cross-cutting\n PRD for missing behaviour and exaggerated claims. Verify and synthesise their\n findings; do not copy their prose.\n- Before requesting approval, review every sentence for complexity, repetition,\n and unsupported scope.\n- Write nothing whose truth expires. No `file.go:123` citations (cite the file\n and the symbol), no progress reports on the work being designed, no dated\n status claims, and no record of how a finding was produced. A phased plan is\n durable design; which phase is finished is not. Do not refer to what this\n document used to say: the reader cannot see it. A supersede marker is fine\n when it names a file, a section or a symbol they can find. `task docs:prds`\n enforces this.\n- Every PRD carries one of three statuses, and nothing else in that field.\n `Draft` until the maintainer explicitly approves it, `Approved` once they\n have and while the work is being built, `Finalised` when the work is\n complete. A finalised PRD does not change; supersede it with a new one\n instead. A revision number belongs in `**Revision:**`, a pointer to the\n authoritative document in `**Authority:**`, and what a past revision changed\n belongs in git.\n"
},
{
"url": "/dev/prds/action-playbook-run/",
"title": "Running action playbooks",
"section": "PRDs",
"body": "# Running action playbooks\n\n**Status:** Approved\n**Date:** 2026-09-23\n**Parent:** `docs/prds/multi-action-playbooks.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-t2db.31`\n\n## Why this exists\n\nAn action playbook loads and type-checks but never runs: `Store.Dispatch`\nskips it and the daemon logs a warning at boot (`multi-action-playbooks.md`,\nD1). This document defines when it runs, what each action does, and how the\n`playbook_dispatches` ledger gates it.\n\n## When a playbook runs\n\nThe daemon runs action playbooks at the point it pins a task's workflow\ndefinition (`Daemon.resolveWorkflowID`), using the same `DispatchInput` the\nworkflow playbooks use. The definition is pinned once per task, so the run\nhappens once per task.\n\n- Every action playbook whose trigger matches runs, in load order. A workflow\n playbook stops at the first match because it chooses one workflow; action\n playbooks choose nothing, so no match suppresses another.\n- A run never changes routing. The task is pinned by the workflow playbooks\n and bindings exactly as when no action playbook exists.\n- An action or playbook failure never parks or fails the task. It is logged\n at warning level with the playbook, the action and the task.\n- A task that already names a workflow (the approval requeue) is skipped, as\n it is for workflow playbooks.\n- Actions run synchronously in the pin path, bounded by the daemon's context.\n The only Module kind, `log`, returns immediately. A slow kind must bring its\n own timeout.\n\n## What one action does\n\nActions run in order against one evaluation context whose `actions` map\nstarts empty.\n\n1. Evaluate `when`. False or an evaluation error skips the action (J3). A\n skipped action records nothing and produces no result.\n2. Evaluate every `args` value. An evaluation error stops the playbook.\n3. Call `playbook.InvokeOnce` with the Module invoke as its function. The\n ledger row is written first. A duplicate row skips the invoke.\n4. An invoke error stops the playbook. The row stays, so the action is not\n retried: the ledger promises at most once, not at least once.\n5. On success, `ModuleRegistry.DecodeResult` converts the result, and it is\n stored as `actions.\u003cid\u003e.result` when the action declares an id.\n\nThe event id in the ledger key is `DispatchInput.TaskID`, the issue's\nidempotency key (`owner/repo/number`). An action therefore runs at most once\nper issue for each playbook version. Editing a playbook changes its version\nand lets it run again for issues it already handled.\n\nA skipped duplicate has no result. A later action that reads it sees a\nmissing field: its `when` evaluates false, or its args fail and the playbook\nstops. This only happens when the same issue is pinned twice under one\nplaybook version.\n\n## Wiring\n\n- `storecontract.PlaybookDispatcher` is lifted onto the daemon from the State\n Store client in `internal/app/archied/bootstrap.go`, the same way\n `BindingDispatcher` is.\n- The daemon's `Playbooks` dependency gains the run method. The Module\n registry is passed to the playbook store at load, so the daemon needs no\n new dependency for it.\n- With no `PlaybookDispatcher` wired, action playbooks do not run, and the\n boot warning names each one. They never run without the ledger.\n- The boot warning that action playbooks do not execute is removed when the\n ledger is wired.\n\n## Verification\n\n- A matching two-action `log` playbook runs both actions in order, and the\n second reads the first's result.\n- Pinning the same task twice under one playbook version invokes each action\n once.\n- A `when` that evaluates false skips that action and the run continues.\n- An invoke error stops the playbook. The task is still pinned to the same\n workflow it would get with no action playbook.\n- A non-matching trigger runs nothing.\n- With no ledger wired, nothing runs and the warning names the playbook.\n"
},
{
"url": "/dev/prds/agent2agent-protocol/",
"title": "Agent2Agent as archie's agent-to-agent protocol — decision",
"section": "PRDs",
"body": "# Agent2Agent as archie's agent-to-agent protocol — decision\n\n**Status:** Draft\n**Date:** 2026-09-22\n**Authority:** the A2A Protocol Specification v1.0.0 (`a2a-protocol.org`) for the\nprotocol, `docs/architecture/organisation.md` for package placement, and\n`docs/architecture/migration-decisions.md` §2 for session and messaging design.\n\n## Decision\n\nA2A is the protocol archie speaks to other agents. It carries agent-to-agent\nwork: discovery of what a remote agent offers, delegation of a unit of work to it,\nprogress on that work, and the artifacts it produces.\n\n## Layers\n\n**MCP stays the tool layer.** MCP connects a model to tools and data; A2A connects\nagents to agents. They are complementary and archie runs both:\n`internal/tools/provider` registers MCP providers as optional capabilities, so an\nA2A call and an MCP tool call are different kinds of traffic with different\nowners.\n\n**A2A rides archie's existing transports.** A2A's canonical data model is\nProtocol Buffer messages and it defines a gRPC binding, so archie speaks A2A over\nthe gRPC and NATS it already runs. A second wire format, a second broker, or a\nbespoke protocol for agent-to-agent traffic is a requirement not to introduce.\n\n## Where A2A stops\n\nA2A is not a general replacement for either of the two protocols archie already\nhas, and each boundary is a requirement rather than a preference.\n\n- **`internal/domain/messaging` stays the human and channel layer.** A\n Conversation is a ChannelID and a ThreadID, its participants are people on\n Telegram, email, webhook and the dashboard, and its records are what a curator\n reads. An A2A peer is not a channel participant and does not address a\n Conversation.\n- **`internal/agentexec` stays the daemon-to-worker execution protocol.** It\n carries a Request, a Result, gate and budget policy, and capture tools between\n the daemon and the agent container it owns. An A2A peer never receives that\n protocol, and A2A never carries gate, budget or protection policy.\n\nA2A is therefore an edge protocol: it exchanges work with peers outside archie's\nown process boundary, and it composes with the two protocols above rather than\nreplacing or abstracting them.\n\n## A2A Task mapping\n\n**Decision: archie's work lifecycle is mapped to A2A's, not expressed in it. An\nA2A Task is a view over archie's own task, and archie's status remains the record\nof truth.**\n\nThis is the load-bearing decision, because A2A's Task carries its own state\nmachine and archie's lifecycle is the on-disk format of its task store, whose\nstatus strings a rename migrates rather than changes.\n\nThe mapping is partial, and each gap is a case where archie knows something A2A's\nstates do not carry:\n\n- **Completion by another system.** A2A's terminal states describe what the agent\n did (`completed`, `failed`, `canceled`, `rejected`). archie's `merged` and\n `rejected` describe what a forge did to a pull request after archie finished\n its work. There is no A2A state for \"an external system accepted this\", so a\n completed A2A task cannot express the outcome that matters most to the caller.\n- **Handing work to a reviewer.** archie's `pr_open` means the work left\n archie's hands for human review. A2A's `input-required` is the nearest state,\n but it means the _client_ must send more input, and a reviewer is not the\n client.\n- **Operator decisions.** `declined`, `parked` and `dead` are outcomes of\n archie's own policy and operator actions. A2A has no state for \"the operator\n refused this\" or \"a budget ran out and an operator must decide\".\n\nA WorkflowExecution is the unit an A2A task maps onto, because it is the attempt\nthat runs, streams and produces artifacts, and a follow-up attempt is a new\nexecution. A2A's own model agrees that a task is immutable once terminal and that\na refinement is a new task sharing the `contextId`, which is why archie's\nper-attempt executions and A2A's per-request tasks correspond.\n\n**Requirement:** the A2A state a peer sees is derived from archie's status by one\nmapping, and archie's status is carried on the task so a peer can read what the\nderivation lost. The mapping is total in the direction that matters -- every\narchie status has an A2A state -- and deliberately not injective, because the\ngaps above are facts A2A cannot hold.\n\n**Requirement:** adopting A2A's state names as archie's persisted task status is\nrejected. It would migrate the task store, and it would drop the forge outcomes\nthat tell a caller whether the work was accepted.\n\n## What an A2A agent is\n\n**An A2A agent is an archie Identity.** The Agent Card describes a durable,\naddressable actor with an endpoint, capabilities and authentication requirements,\nand an Identity is the actor archie persists, versions, suspends and scopes\ncredentials to.\n\nAn `agent.Persona` is not an A2A agent: a persona is prompt text selected for a\nturn, and it has no endpLine truncated
},
{
"url": "/dev/prds/artifact-sender/",
"title": "Artifact sender",
"section": "PRDs",
"body": "# Artifact sender\n\n**Status:** Approved\n**Revision:** 1\n**Authority:** this document\n\n## Purpose\n\narchie-core publishes artifacts — design documents, review reports, research briefs,\nrunnable pages — to the offloaded.dev collaborative editor. A person reads the\nartifact, comments on it, and the artifact page is the shared surface for iteration.\n\nThe receiving contract is owned by the editor: `POST /api/artifacts` with a bearer\nservice token, a closed field set, and server-side idempotency on `requestId` plus\nlast-write-wins on `sentAt`. This document owns only what archie-core sends.\n\n## Scope\n\nVersion one publishes one-way: archie-core sends, the editor receives. The first\nproducer is the pull-request adversarial review: a completed `ReviewReport` is\nrendered to markdown and published after the review completes.\n\nChat-surface tools (`create_artifact`, `update_artifact`), comment read-back, share\ntokens, and runnable-format producers (`html`, `react`, `vue`) are later slices. The\nreceiving contract already carries them; version one does not exercise them.\n\n## Configuration\n\n- New `[artifacts]` section: `base_url` (site origin), `token` (`SecretRef`) with\n `token_env` fallback naming `WORKSPACE_INGEST_TOKEN`.\n- An empty `base_url` disables the sender: no client is constructed, nothing is\n registered, and publishing degrades to a log line.\n- The token is runtime configuration. It is never baked at build time.\n\n## Sender\n\n- New package `internal/infrastructure/artifactsync` exposing one method,\n `Publish(ctx, Artifact) (string, error)`, where the string is the artifact URL.\n One-method injected seam, concrete client constructed by the boot path when the\n configuration resolves — the `crondelivery.Courier` posture.\n- The client POSTs the frozen contract body. Each publish sends the complete\n source: versions of record are full snapshots, never diffs.\n- A `503` response is retried three times with backoff. `401` and `400` are not\n retried; they are logged with the field reason the response names.\n- `requestId` is `artifact:\u003ctask-id\u003e:\u003cversion\u003e` when the producer is task-backed,\n otherwise `artifact:\u003cidentity\u003e:\u003csentAt-utc\u003e`. Sending the same `requestId` with\n an equal or older `sentAt` must be a server-side no-op, which makes sender-side\n retry safe.\n\n## Report rendering\n\n- `ReviewReport` gains a pure markdown renderer in `internal/domain/workflow`:\n the summary as the lede, one finding per subsection with file, line, verdict,\n level and the failure scenario, and the verified properties as a \"checked\n clean\" list. Findings carry their disposition when present.\n- The renderer performs no I/O and imports no infrastructure.\n\n## Attribution\n\n- `actor`: the producing identity. The reviewer publishes as `system:pr-reviewer`\n when no task identity resolves; otherwise the task's identity name.\n- `source`: the producing subsystem, `pr-review` for version one.\n- `task`: owner, repository and issue number from the task when one exists.\n\n## Failure behaviour\n\n- Publishing never fails the producing work. A failed publish is logged with its\n status and reason; the artifact is republished on the next production of the\n same artifact.\n- A successful publish records the artifact URL in the run report, so the PR\n description or task log links to the readable artifact.\n- The published URL is the editor deep link for the artifact, keyed on its\n immutable id. archie-core never mints share links; sharing is an\n account-holder decision made in the editor.\n\n## Verification\n\n- Client tests against a test server cover 201, 401, 400 with a field reason,\n and 503 retry behaviour.\n- The report renderer test covers a report with findings, checks, dispositions\n and a not-run status.\n- Configuration tests cover the disabled case, the `SecretRef` path and the\n `token_env` fallback.\n"
},
{
"url": "/dev/prds/binding-secret-encryption/",
"title": "Binding secret at-rest encryption -- decision",
"section": "PRDs",
"body": "# Binding secret at-rest encryption -- decision\n\n**Status:** Approved\n**Date:** 2026-09-02\n**Beads issue:** `archie-core-t2db.7` (P2), parent `archie-core-t2db`\n\n## Problem\n\n\u003e Storage superseded: every store now lives in PostgreSQL behind\n\u003e `internal/domain/storecontract`, implemented in `internal/infrastructure/postgres`\n\u003e (`docs/prds/state-store-contract.md`). SQLite names below describe the\n\u003e original design.\n\n`binding.Binding.Secret` (the per-source HMAC shared secret) is persisted as\nplaintext in the `bindings.secret TEXT` column. Anyone with read access to the\nSQLite file -- the same access level as `captured_events.body` and `tasks.body`\n-- sees sender-side shared secrets. A leaked database file leaks secrets even\nwhen the filesystem ACLs were correct at rest.\n\n## Decision\n\nEncrypt the `secret` column at rest with **AES-256-GCM** (stdlib\n`crypto/aes` + `crypto/cipher`, no new dependency), transparently inside the\nstore: encrypt on write, decrypt on read. The store is the data boundary; its\nconsumers (dispatch loop, HMAC verification) receive the plaintext secret\nexactly as and the webui already blanks `Secret` on every response.\n\n### Cipher parameters\n\n- **AEAD:** AES-256-GCM, 12-byte random nonce (`crypto/rand`), tag appended.\n- **Key length:** 32 bytes, derived as `SHA-256(resolved_material)`. Kept as\n SHA-256 (no Argon2id) because the source is a **32-byte high-entropy** value\n resolved through the secret registry, so re-deriving to 32 bytes merely\n re-shapes entropy rather than defending a weak passphrase.\n- **AAD:** a static domain separator, `[]byte(\"arcie-binding-secret\")`, so a\n ciphertext cannot be relocated to a different field/column and still\n authenticate. AAD is intentionally **not** row-bound: binding secrets are\n random HMAC keys and are never used as lookup keys, so cross-row swap is not\n a meaningful attack here.\n\n### Envelope format\n\n```\narcie-binding:v1:\u003ckeyFingerprint\u003e:\u003cbase64url(nonce || ciphertext || tag)\u003e\n```\n\n- `arcie-binding` -- domain marker\n- `v1` -- format version (future cipher/KDF change is a new version, old rows\n stay readable)\n- `\u003ckeyFingerprint\u003e` -- `hex(SHA-256(material))[:16]`, the identity of the key\n that sealed the row, enabling rotation without a one-shot rewrite\n- payload -- `base64url` of `nonce ‖ GCM.Seal(plaintext, aad)`\n\n### Key source (confirmed with maintainer)\n\nResolved through the existing secret registry (`internal/secret`), the\nestablished `SecretRef` pattern already used for `forge.webhook_secret`:\n\n```toml\n[bindings]\nencryption_key = { engine = \"env\", key = \"ARCHIE_BINDING_KEY\" }\n# Rotation: after swapping encryption_key to a new value, retain the previous\n# material so rows sealed under the old key still decrypt.\nprevious_encryption_keys = [ { engine = \"env\", key = \"ARCHIE_BINDING_KEY_OLD\" } ]\n```\n\nThe active key encrypts new writes; `previous_encryption_keys` are retained for\ndecrypt-only. Key identity is intrinsic to the material (the fingerprint), so\nno manual key IDs are configured.\n\n### Rotation story\n\nRotate by changing `encryption_key`, moving the old material into\n`previous_encryption_keys`. Rows sealed under the old key still decrypt via\ntheir embedded fingerprint; new writes use the new active key. Once no\nremaining row references an old fingerprint, remove it from the config. Losing\na fingerprint's material before all its rows are rewritten makes those rows\nunreadable -- the same operational rule as any key rotation, and the reason the\nold material must be retained.\n\n## Non-goals / deferred\n\n- **`captured_events.body` redaction hardening** was completed alongside this\n work (not deferred): `webhookguard.RedactPayload` now redacts an expanded set\n of secret key markers (compound names like `access_token`, `client_secret`,\n `signing_key`, `x_api_key`, …) as well as unambiguous value shapes (compact\n JWTs, PEM private-key blocks) under any key. `gateway.sensitiveParameterKey`\n was broadened identically to preserve the documented agreement. It remains\n best-effort per `docs/prds/webhook-intake-security.md` point 5 -- a sender\n that picks a name the heuristic misses is still captured.\n- **Key re-derivation on config reload** is a startup concern: the store holds\n the cipher for its lifetime, so a reload that changes `[bindings]` keys\n requires a daemon restart to take effect. Documented, accepted.\n\n## Wiring\n\n- `internal/config`: add `BindingsConfig` (`encryption_key SecretRef`,\n `previous_encryption_keys []SecretRef`) on `Config.Bindings`.\n- `internal/app/archied/bootstrap.go` `openStores`: resolve both refs through\n the already-built `secrets` registry, pass the material to `store.Open` via a\n new option `store.WithBindingCipher(cipher)`.\n- `internal/infrastructure/bindingcipher`: the `BindingCipher` interface and\n concrLine truncated
},
{
"url": "/dev/prds/channel-forge-positions/",
"title": "Channel and Forge action positions (resolves `t2db.19`)",
"section": "PRDs",
"body": "# Channel and Forge action positions (resolves `t2db.19`)\n\n**Status:** Approved\n**Date:** 2026-09-03\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Blocked on:** `archie-core-t2db.24` (the `playbook_dispatches` ledger) for\nimplementation of either position. Both are side-effecting, and `t2db.17`\nresolved the keying scheme in design only.\n\n## Forge\n\n`internal/forge.Forge` is already exactly the shape a native-Go action position\nneeds -- a real, typed, general-purpose interface, not something that needs a\nYaegi/Module-style schema-generation detour:\n\n```go\ntype Forge interface {\n IssueForge // AssignedIssues, IssuesWithLabel, CloseIssue, ...\n PullRequestForge // CreatePR, PRState\n RepoForge // AcceptInvitations, VerifyPush, LinkBranch, ...\n}\n```\n\n**Typed contract shape: native-Go-by-name, not a Module-kind.** Module's whole\nreason to exist is giving _Yaegi-authored, operator-supplied_ code a typed\ncontract to implement. `Forge` is already a typed Go interface with real, tested\nimplementations (GitHub, Gitea) selected at daemon startup by `forge.New(...)`.\nWrapping it in a Module-kind schema/`go:generate` detour would duplicate a\ncontract that already exists. A Forge action position should be: a small set of\nnamed operations (e.g. `close-issue`, `create-pr`, `link-branch`), each with a\ntyped `Args`/`Result` struct mirroring the matching method's parameters/return.\n\nThe dispatch target is `internal/domain/workflow.Forger`\n(`CloseIssue`/`CreatePR`/`LinkBranch` -- already exists, already exactly these\nthree operations), **not** `internal/forge.Forge` directly. `organisation.md`'s\ntarget structure places `forge/` under `internal/infrastructure/forge/`; the flat\n`internal/forge` is a flat, unmigrated legacy package in the same position\n`internal/workflow` was in before its own migration. A new domain package\ndepending on the flat package directly would create a domain-to-infrastructure\ndependency that breaks the moment `forge` migrates. `workflow.Forger` is the\nnarrow, already-domain-owned contract that exists for exactly this reason -- the\ndaemon's real `forge.Forge` client satisfies it at the wiring layer.\nDepend on `Forger`, not on `internal/forge`.\n\n**Operation scope for a first slice:** `close-issue` and `link-branch`\n(single-call, cleanly idempotent by event+issue identity) are the safe starting\nset. `create-pr` is explicitly a heavier case -- opening a PR is a\nharder-to-reverse action with its own dedup shape beyond \"did this event fire\nbefore\" (a redelivered event must not open a second PR for the same logical\nchange) -- defer it to a follow-up slice once the keying scheme is proven on the\nsimpler operations, don't design it blind now.\n\n**Host access:** the coordinator needs the same `Forge` instance\n`internal/daemon`'s poller already holds (constructed once at startup via\n`forge.New`). This is a daemon-composition wiring question (pass the existing\ninstance into the coordinator's constructor), not a new extensibility mechanism.\n\n## Channel\n\n### Constraints this satisfies\n\nMessaging is the root, Channel is the integration layer, an implementation such\nas Telegram sits under Channel. A channel is added by implementing one reusable\ninterface, and every channel must implement it. A notification mechanism belongs\nunder Messaging, and `channels.Channel` must not reach across into it.\n\n### Notification is a Messaging contract, not a channel type\n\nThe contract lives in `internal/domain/messaging`. A channel implementation\nsatisfies it by importing its own parent, which it already does, so the\ndependency stays `channels -\u003e messaging` and nothing points back.\n\n`channels.Channel` does not change. It gains no notification method and no\nimport, so the interface every channel must implement stays the lifecycle and\nconfig contract it is. `internal/channels/telegram` satisfying both\ncontracts is an implementation choosing to, not the Channel layer knowing about\nnotification.\n\nA notification is not a channel type because it has no lifecycle to start and\nstop, no inbound direction, and no configuration schema of its own. Modelling it\nas one would force `Start`/`Stop`/`ConfigSchema` onto something with no meaning\nfor them, and make every real channel declare whether it is a notification.\n\n### Destinations are configured, never named by a playbook\n\n`[notify]` becomes a set of named destinations. Each binds a name the operator\nchooses to a channel already registered in the Messaging composition\n(`internal/app/archiemessaging/compose.go` registers `telegram`, `email`,\n`webhook`) plus that channel's own address, such as a Telegram chat id. The\nexisting single-webhook form keeps working as a destination named `webhook`.\n\nA playbook action names a destination. It never names an address. Playbook\ntriggers are reachable from a public, unauthenticated intake surface, soLine truncated
},
{
"url": "/dev/prds/code-graph-mcp/",
"title": "Code graph over MCP (`tools/codegraph`)",
"section": "PRDs",
"body": "# Code graph over MCP (`tools/codegraph`)\n\n**Status:** Draft\n**Supersedes:** `symbol-reference-index.md`, which scoped only the data layer.\n\n## The problem\n\nEstablishing what a change touches costs an agent eight to fifteen\ngreps, and the answers are wrong in specific ways. `grep -rn \"Register(\"`\ncannot separate `plugin.Registry.Register` from `captureintake.Receiver.Register`\nfrom `forgerpc.Server.Register`, all of which exist here. It also matches the\nsibling checkouts under `.worktrees/`, which are near-complete copies of the\nmodule, so every count is silently inflated.\n\nThat cost lands hardest in investigation, triage and the TDD loop, where the\nfirst question is always \"what does this touch\".\n\n## Decision: exact analysis, not semantic retrieval\n\nTools like Greptile parse with tree-sitter, summarise each node, embed the\nsummaries, and retrieve semantically. That design exists because they must\nserve any language. This repository is one Go module, and Go's type checker is\nground truth:\n\n| Question | Source of truth |\n| --------------------------- | ------------------------------------------------ |\n| Who references this symbol? | `go/packages` + `go/types`, resolved by identity |\n| What calls what? | `callgraph` RTA over SSA |\n| What imports what? | `go list -deps` |\n\nNo vector database, no embedding cost, no edges invented by a summary that\ndrifted from the code. For a single-language repository this is both cheaper\nand strictly more accurate. Copy the interface those tools expose, not their\narchitecture.\n\n**A code graph does not power a documentation chatbot.** It answers structural\nquestions about Go symbols. Answering \"how do I configure a second identity\"\nmeans retrieving prose from markdown, which needs chunking, embedding and\nsimilarity search over a different corpus entirely. That remains a separate\ncapability with its own design. Conflating the two would build one system that\ndoes neither well.\n\n## Interface: an MCP server\n\n`archied` already consumes MCP as a client (`internal/app/agentworker`\nstarts providers) and serves none. Exposing the graph over MCP reaches Claude\nCode, pi, codex and Archie's own agents through one surface, with no coupling\nto the daemon: it is configured like any other entry in `[[mcp_servers]]`.\n\nFour tools, each returning JSON with file:line citations:\n\n- `references(symbol)` — every reference site, classified `prod` / `test` /\n `generated` / `dynamic`\n- `callers(symbol, depth)` — inbound call edges\n- `callees(symbol, depth)` — outbound call edges\n- `blast_radius(file | symbol)` — the transitive neighbourhood a change reaches,\n which is the single call meant to replace the grep sequence\n\nDiagrams are deliberately not a tool. A model given an accurate subgraph writes\nits own Mermaid; a diagram endpoint would only fix the rendering of something\nthe model already has.\n\n## Decisions\n\n**Every answer declares what it could not see.** RTA over-approximates\ninterface dispatch, and reflection is invisible: every `reflect.ValueOf` entry\nin `wfextract`, `gateextract`, `pluginextract`, `secretextract` and\n`logextract` makes a symbol look reachable whether or not anything calls it.\nEach response carries a `dynamic_edges` field naming those boundaries. An agent\ntrusting a confident wrong graph is worse off than one that greps, so the graph\nstates its own limits rather than implying completeness.\n\n**Warm in memory, keyed on HEAD, never persisted to disk.** `deadcode` does\nwhole-program RTA in under seven seconds; this does less work. The server\nrebuilds when HEAD changes and refuses its cache outright when the tree is\ndirty. Nothing is written to disk, because a persisted index becomes a rendered\nview that outlives its evidence. That is the failure that made `STATUS.md`\nreport 90 of 91 findings re-verified while most statuses were 77 commits stale,\nand the same one that made `reachaudit` serve a previous tree's analysis from\n`/tmp` until its cache was keyed on HEAD.\n\n**`tools/codegraph`, not `internal/`.** It is developer tooling, not daemon\nruntime, so it belongs beside `docsgen`, `contractaudit` and `reachaudit` in\nthe `tools` module, which `task test:tools` already covers. Start as a single\nGo file; split only when it earns it.\n\n**No new dependency.** `golang.org/x/tools` is already in `go.sum` at v0.49.0.\n\n## How it is verified\n\nRed first. Table-driven tests against small fixture modules built in\n`t.TempDir()`, asserting the behaviour that distinguishes this from grep:\n\n1. Two methods spelled `Register` on different types resolve to two separate\n records, and a reference to one does not increment the other.\n2. A symbol referenced only from `_test.go` reports zero `prod` references.\n3. A symbol referenced only from a `reflect.VLine truncated
},
{
"url": "/dev/prds/config-example-drift/",
"title": "Example-config and generated-config drift — decision",
"section": "PRDs",
"body": "# Example-config and generated-config drift — decision\n\n**Status:** Approved\n**Date:** 2026-09-15\n**Closes:** the checked-in-config half of audit findings `config-1` and\n`repo-root-deployment-2`; strengthens `doc-drift` findings generally.\n**Authority:** extends `docs/architecture/generated-documentation.md` and\n`docs/prds/config-schema.md`; does not replace either.\n\n## Question\n\nShould `config.example.toml` and `deployments/*.toml` be _generated_, so they\ncannot drift from the config code?\n\n## Decision\n\n**No — do not generate them. Gate them instead.** Neither file is a projection\nof the schema, and generating either would destroy the thing that makes it\nuseful. Three verified reasons, in order of weight:\n\n1. **`config.example.toml`'s value is its comments.** It documents **137 keys**\n (measured: active _and_ commented-out), and those hand-written comments are\n the file's purpose — `docs/architecture/configuration.md` states outright\n that \"`config.example.toml` carries documentation users are meant to\n hand-edit\". TOML round-tripping does not preserve comments, which is exactly\n why `tomlwrite` does line-oriented edits rather than decode/encode. A\n generator would emit a correct file with the documentation deleted.\n2. **`docs/prds/config-schema.md` forbids building on `config.Config`.** That PRD\n rejects \"a reflection-based schema over `config.Config`\" because the struct is\n \"scheduled for dissolution\". A generator deriving the example from its struct\n tags would build on a foundation this repo has already decided to remove.\n3. **`docs/architecture/generated-documentation.md` prohibits it.** \"Adding\n another hardcoded type list to `docsgen` is prohibited\" — so any generator\n must consume a domain-owned registry, which does not exist for configuration\n yet. Creating one is the config-domain migration's job, not this change's.\n\nThe deployment profiles are also not a projection: they set **3-46 keys** against\nthe example's 137, and they are curated overlays (\"a complete config, not an\noverlay\", per their own headers), not near-duplicates. Generating them would add\nmachinery to remove duplication that largely is not there.\n\n## The gap that is real\n\n**Unknown config keys are silently ignored.** Verified at\n`internal/infrastructure/configuration/decode.go`:\n\n```go\nif _, err := toml.DecodeFile(path, target); err != nil {\n```\n\nThere is no `MetaData.Undecoded()` check, so a typo — `max_concurrancy = 4` —\nparses clean, validates clean, and does nothing. That is the same failure shape\nthis repo's audit found repeatedly: a setting that looks applied and is not. It\nis also detectable **without any hand-maintained list**, because `BurntSushi/toml`\nreports exactly which keys the target did not consume.\n\nNote the second, separate gap already admitted in writing:\n`generated-documentation.md` — \"`task check` does not run `docs:check`, so\ngenerated drift is ungated.\"\n\n## What to build\n\n**1. Unknown-key detection at the loader (behaviour).** Decode with metadata and\ncollect `Undecoded()`. Report it as a warning at startup listing the offending\nkeys, and expose it so tests can assert emptiness.\n\n**Deliberately a warning, not a fatal error.** `configuration.md`'s settled\nstartup policy is \"a missing credential disables a capability; only an invalid\nconfig stops the daemon\". A stray key is far more likely to be an operator typo\nin a file they are otherwise happy with than a reason to refuse to boot, and\n`[web]` is documented as landing in a _different_ binary\n(`internal/app/archieui`), so a key unknown to one process is legitimately known\nto another. Failing closed here would break working deployments on upgrade.\n\n**2. A checked-in-config contract test (gate).** Load `config.example.toml` and\nevery `deployments/*.toml` through the real loader and assert `Undecoded()` is\nempty, with an explicit allowlist for keys another binary owns. This is the\nmechanism that would have caught a renamed key left behind in an example, and it\nneeds no inventory.\n\n**3. Gate generated data in `task check`.** Done. `task docs:check` runs in the\ngate, closing the admitted \"generated drift is ungated\" hole. The\ncheck mode did not exist when this was written; it was added for issue #855,\nwhich also made the check non-destructive so the gate can never rewrite the\nartifact it is judging.\n\n**4. Explicitly NOT now: a generated key inventory.** `configuration.md`'s\ncompletion criteria want \"generated documentation lists every external key,\ndefault, constraint, mutability class, owner\". That is a real target and it is\nthe config domain's, once a domain-owned registry exists — the prohibition above\nmeans it cannot be bootstrapped from a list inside `docsgen`. Recorded as\ndeferred, not rejected.\n\n## Non-goals\n\n- No generation of `config.example.toml` or `deployments/*.toml`.\n- No reflection-baLine truncated
},
{
"url": "/dev/prds/config-schema/",
"title": "Backend-owned configuration schema for the webui -- decision",
"section": "PRDs",
"body": "# Backend-owned configuration schema for the webui -- decision\n\n**Status:** Approved\n**Date:** 2026-09-02\n**Beads issue:** `archie-core-b6ew` (epic), with children `.1`-`.5`\n\n## Decision\n\nThe dashboard's Configuration page keeps reading a secret-free,\nhand-picked view of `config.Config` -- that allowlist is a safety\nboundary and stays exactly as it is. What changes is who defines the\npage around it: `ui/src/settings/settings.js` and\n`config-row.js` hardcode every row's label, section, type, and\neditability by hand; after this, the backend attaches that metadata to\neach field it already allows through, and the frontend renders\nsections and fields generically from what the backend sends.\n\nThis is **not** a reflection-based schema over `config.Config`.\n`internal/config/config.go`'s own package doc states it is \"scheduled\nfor dissolution: its types and methods are to be reassigned to the\ndomains whose behaviour they describe\" -- building a generic\nschema-from-struct-tags mechanism over a struct on its way out would be\nbuilding on a foundation this repo has already decided to remove.\nInstead, every field already in `ConfigView` (`internal/webui/api_config.go`)\ngot there because someone deliberately vetted it as safe to show; the\nschema adds a hand-authored descriptor to that same deliberate act,\nnot a new mechanism that re-derives safety automatically.\n\n## Why now\n\nTask #6's investigation (`/9/26`) found the concrete failure this\nproduces: `Repo.AllowConcurrent` and `Repo.MaxRetries` already reach\n`GET /api/config` (`RepoView` in `api_config.go`), but the\nrepositories card renders a static read-only table that never shows\nthem, so the fix for \"why isn't a second agent running\" required an\nagent tracing Go source instead of a checkbox on the dashboard.\n`Repo.ReviewEnabled` is worse: it never reaches the API at all. Both\nare symptoms of the same root cause -- the frontend decides what a\nfield means and whether it's shown, and nothing keeps that in sync\nwith what the backend actually allows.\n\n## Shape\n\n```go\n// internal/webui/config_schema.go (new)\n\ntype ConfigFieldType string\n\nconst (\n FieldString ConfigFieldType = \"string\"\n FieldInt ConfigFieldType = \"int\"\n FieldBool ConfigFieldType = \"bool\"\n FieldDuration ConfigFieldType = \"duration\"\n FieldEnum ConfigFieldType = \"enum\"\n FieldStructured ConfigFieldType = \"structured\" // repositories, models, providers\n)\n\ntype ConfigField struct {\n Key string `json:\"key\"` // dotted path, matches UpdateConfig's key space\n Label string `json:\"label\"`\n Description string `json:\"description,omitempty\"`\n Type ConfigFieldType `json:\"type\"`\n Value any `json:\"value\"`\n Editable bool `json:\"editable\"`\n LockedReason string `json:\"locked_reason,omitempty\"`\n Overridden bool `json:\"overridden\"`\n Options []string `json:\"options,omitempty\"` // enum only\n RestartRequired bool `json:\"restart_required\"`\n}\n\ntype ConfigSection struct {\n ID string `json:\"id\"`\n Label string `json:\"label\"`\n Fields []ConfigField `json:\"fields\"`\n}\n```\n\n`handleConfig` builds `[]ConfigSection` from the existing per-field\nvalues it already assembles, plus `overlay.DeniedKeys` for\n`LockedReason` and the existing `Overridden` list -- both already\ncomputed just re-attached per field instead of returned as\nside-channel maps the frontend cross-references by key string.\n`Locked`/`Overridden`/`Reload`/`Provenance` stay as top-level\n`ConfigView` fields; they describe runtime state (what happened on\nthe last reload, which keys the overlay refuses), not the field\ncatalogue, and duplicating that logic per-field would be the same drift\nrisk this change exists to remove.\n\n`FieldStructured` fields (repositories, models, providers) carry\n`Value` as structured JSON and are rendered by dedicated\neditors, not the generic renderer -- see \"What this does not do\".\n\n## Sections\n\nMatches the cards the settings page already has: `identity`,\n`repositories`, `models`, `providers`, `budgets`, `storage`,\n`containers`, `web`. No new sections; this is metadata on existing\nrows, not new configuration surface.\n\n## Frontend\n\n`config-row.js`'s `row(label, value, opts)` becomes the renderer's\nprivate implementation detail, called generically:\n\n```js\nfor (const section of schema.sections) {\n const rows = section.fields\n .filter((f) =\u003e f.type !== \"structured\")\n .map((f) =\u003e\n row(f.label, f.value, {\n key: f.key,\n type: f.type,\n options: f.options,\n locked: f.locked_reason,\n overridden: f.overridden,\n restartRequired: f.restart_required,\n }),\n );\n // structured fLine truncated
},
{
"url": "/dev/prds/contract-conformance-audit/",
"title": "Contract conformance audit — decision",
"section": "PRDs",
"body": "# Contract conformance audit — decision\n\n**Status:** Finalised\n**Scope:** an **advisory** report, deliberately **not** part of `task check`.\n**Date:** 2026-09-15\n**Authority:** sibling to `archie-core-06ag` (standing reachability audit) and\n`docs/architecture/dependencies-and-contracts.md`. Replaces neither.\n**Open:** withdraw it, or rebuild it structurally. See \"Open decision\" — not to\nbe resolved by hardening the regexes.\n\n## Question\n\nDoes every declared contract surface have a consumer, or an explicit declaration\nthat it has none?\n\nReachability (`tools/reachaudit`) asks the complementary question — _is this code\nin a shipped binary?_ — and cannot see a capability that is **reachable and\nunconsumed**. `ratelimit` was in the binary closure and called by nothing\n(`archie-core-6wxb`); reachability would not have found that.\n\n## Decision\n\nYes, as an advisory survey. `tools/contractaudit` classifies each subject of each\nsurface:\n\n| Classification | Meaning | Fails `--strict`? |\n| ----------------------- | ----------------------------------------------------------------------------- | ----------------- |\n| `CONSUMED` | a call site exercises it | no |\n| `DECLARED-UNCONSUMED` | allowlisted in `docs/contract-declarations.json`, with a reason and a tracker | no |\n| `UNDECLARED-UNCONSUMED` | nobody reaches it, nobody declared it | **yes** |\n| `STALE-DECLARATION` | an allowlist entry that is no longer true | **yes** |\n\nThere are **four** classes and **two** of them fail. The allowlist must match\nreality exactly, and it fails in both directions: a missing entry is a finding,\nand an entry that outlived its subject is a finding, because a stale allowlist is\nhow a check quietly stops checking anything.\n\n**Not gated.** `task contract` is advisory and `task check` does not run it,\nmatching `tools/reachaudit`. The surfaces are discovered by scanning source text,\nso a rename or a reformat elsewhere in the tree can change the output with nothing\nactually wrong. It has already produced 16 false \"unconsumed\" readings once, when\nthe dashboard's request helper was renamed. A check that can fail for reasons\nunrelated to what it measures must not be able to break a build.\n\n## Surfaces actually built — three, not five\n\n| Surface | Subjects | \"Consumed\" means |\n| ------------------------------------ | ------------- | -------------------------------------------------------- |\n| `proto/state/v1` `StateStoreService` | **45 RPCs** | an adapter body calls `client.\u003cRpc\u003e(...)` |\n| `proto/gateway/v1` `ChatService` | **21 RPCs** | same |\n| `internal/webui` dashboard routes | **49 routes** | a path literal appears as a call argument under `ui/src` |\n\nConsumption for the gRPC surfaces is established by **scanning adapter source\ntext** for calls through the generated client, not by reflection. See the errata\nbelow: the first revision of this document claimed reflection, and the first\nimplementation did use it, but the shipped mechanism is a regex and the document\nwas not updated to match.\n\n## What this audit has actually found\n\n**Nothing actionable.** On the current tree it reports 0 undeclared and 0 stale.\nIts only allowlisted entries are two RPCs superseded by their streaming variants\n(`ListCaptures`, `ListUndispatchedCaptures`), which were already known from the\nsource comment on `staterpc.Client.ListCaptures`.\n\nEvery real defect found in the session that produced this tool was found by other\nmeans:\n\n- the three 415 refusals, by reading `authorizeTaskMutation` and reproducing the\n browser's exact headers against the real handler;\n- the dashboard client's duplicated request plumbing, by reading the module.\n\nRecorded plainly because a survey that has never found anything is evidence about\nthe survey, not about the tree.\n\n## Errata — claims in the first revision of this document that were false\n\n- **\"RPC coverage is derived by reflection over the exported client type.\"**\n It is not. `proto.go` regex-scans adapter bodies for `client.Method(` calls.\n The reflection version was replaced and the document was not updated. The unused\n `google.golang.org/grpc` family in `tools/go.mod` was residue from that\n iteration; `go mod tidy` removed it on 2026-09-15.\n- **Surface sizes of \"43 / 12 / 52\".** The real counts are 45 / 21 / 49.\n- **\"Three classifications, and the third is the only finding.\"** Four classes,\n two of which fail.\n- **\"Raw `fetch()` calls caused 401s to render as `refused`/`brokLine truncated
},
{
"url": "/dev/prds/control-plane-apply-status/",
"title": "Control-plane apply status",
"section": "PRDs",
"body": "# Control-plane apply status\n\n**Status:** Approved\n**Date:** 2026-09-21\n**Tracking:** `archie-core-pskb`, and `archie-core-nwa0` which depends on it\n\n## Outcome\n\nAn operator who edits a control-plane resource can see which processes are\nrunning that version, which are still on an older one, which rejected it, and\nwhich have stopped reporting.\n\n`docs/prds/runtime-control-plane.md` requires this and does not say where the\nreport goes. This decides that.\n\n## Where the report goes\n\nApply status is a State Store contract surface. `ControlPlaneService` is the\nsurface for editing a resource, and a status report is not an edit. The\nprecedent is the config snapshot pair: a process publishes what it knows, the\nUI process reads it, and both RPCs are administrative, so a task-scoped grant\nreaches neither. That denial needs no new rule: `authorizesTaskScopedCall`\nnames three methods and denies everything else.\n\n`docs/prds/state-store-contract.md` gains the pair in its inventory, and its\nRPC count at two places moves from 45 to 47.\n\nThe read returns all records as a list, including an empty one. The\n`found=false` convention for absent single rows does not apply.\n\n## What is reported\n\nOne record per process and resource kind, replaced in place. It holds the\nprocess name, the resource kind, the version applied, the error if the process\ncould not apply it, and the time it reported.\n\nEach process re-stamps its records every 30 seconds. A record is stale once it\nis older than 90 seconds, and a stale record means the process that wrote it is\nno longer running. The report time is therefore a liveness signal, not only a\nwrite timestamp.\n\nA process reports at the point it applies a resource, so the record says what\nhappened rather than what was intended. Nothing probes.\n\nProcess names come from one shared constant naming `archied`, `archie-gateway`\nand `archie-messaging`. A deployment runs at most one of each. Writer and\nreader are bound to that constant by test, because a drifted name is\nindistinguishable from a process that never reported.\n\n## Which processes report\n\n- `archied` and `archie-gateway` apply every restart-required kind through\n `boot.runtimeConfig`, at boot and on SIGHUP.\n- `archied` also applies the live kinds it watches, and reports each update it\n applies.\n- `archie-messaging` applies channel settings at startup and reports that kind.\n\n## What can be reported, and what cannot\n\nA process reaches its apply point only after the State Store has answered it.\nAt startup, when the State Store is unreachable, the process exits or refuses\nto start and writes no record. A live watcher that loses its established\ncontrol-plane stream reports the connection failure against its last applied\nversion while it retries. Re-establishing the stream clears that outage record\nwithout clearing a versioned document rejection. A transport failure is not a\ndocument rejection; it reports that live delivery is unavailable.\n\nAbsence has two meanings and the UI never collapses them: no process applies\nthis kind, or a process that applies other kinds has not reported this one.\n\n## Relationship to the reload status\n\nApply status covers control-plane resource kinds. `ReloadStatus` covers the\nfile document and stays the only report for a SIGHUP that failed to resolve or\nvalidate it. Neither is derived from the other.\n\nWriting a record is best-effort. On the SIGHUP path it takes its own bounded\ncontext, separate from the budget the reload spends reading the control plane,\nand a failed write is logged rather than turned into a failed reload.\n\n## What the UI shows\n\nThe settings page shows, per resource, the stored version beside each process's\napplied version, error, and report time. A process on an older version of a\nrestart-required resource is pending a restart. A process with an error is\nfailed, with the error beside it. A process whose record is stale is unknown,\nnever current.\n\n## A record outlives the process that wrote it\n\nRecords are replaced in place, so a process that applies a version and then\nstops would otherwise leave a record asserting that version indefinitely, and\nthe settings page would show a dead process as current.\n`docs/prds/status-health-surface.md` faced the same choice and stamped the start\nof a poll pass so a wedged poller reads as stale rather than healthy.\n\nSettled: the re-stamp above. The alternatives considered were\ncarrying the instance identity generated at process start, which detects a\nrestart but not a death, and accepting the limitation with the page saying so.\n\n## Verification\n\n- A process that applies a resource writes a record carrying that version.\n- A process whose apply fails validation writes a record carrying the error and\n no new version.\n- A live watch outage is reported against the last applied version until the\n stream is re-established; re-establishment preserves any outstanLine truncated
},
{
"url": "/dev/prds/curator-sampler-wave1/",
"title": "Curator sampler wave 1: `Sampler` interface + four cheap strategies -- decision",
"section": "PRDs",
"body": "# Curator sampler wave 1: `Sampler` interface + four cheap strategies -- decision\n\n**Status:** Approved\n**Date:** 2026-09-05\n**Beads issue:** bead `archie-core-1786637500776-416-600a66e5` / GitHub #437\ncovers the embedding-backed follow-on strategy only. This PRD covers the\nprerequisite interface and the cheap strategies.\n**Parent epic:** `archie-core-1786637500725` (curator engine)\n**Depends on:** nothing shipped (this is itself a prerequisite)\n**Blocks:** the embedding-backed surprisal strategy (GitHub #437), which\nimplements this same interface once the embeddings capability\n(`internal/domain/embedding`, this change) lands\n\n## Problem\n\nA future curator that reviews a large body of content (memories, sessions,\nskills) cannot always afford to run its agentic budget over every candidate\nevery pass. It needs to pick a bounded subset first. GitHub #437's acceptance\ncriteria requires that subset-picking to sit \"behind a `Sampler` interface\nthat wave 1 of the curator epic ships (cheap strategies: recency, random,\nall, staleness proxy)\" and that the embedding-backed strategy implement \"the\nsame interface\" later. No such interface, and none of the four cheap\nstrategies, exist anywhere in the codebase (bead 434e5bb9's closure\nwithout a linked PR was the tracker being wrong, not the code existing) --\nthis PRD is the one-page settled design for it, per this repo's Scope\nDiscipline rule.\n\n## Decision\n\nA `Sampler` is a pure, call-scoped selection function: given a fixed slice of\ncandidates and a request, it returns a subset. No lifecycle, no host access,\nno I/O for the four wave-1 strategies -- they are computation only, so they\nlive directly in `internal/domain/sampling` (a domain package, not\n`internal/infrastructure/*`) alongside the contract, the same way\n`curator/activity.go`'s pure ring buffer sits next to `curator/contract.go`\nrather than in an infrastructure package.\n\n```go\n// Package sampling is the curator sampler family: given a bounded set of\n// candidates, pick a subset to spend a curator pass's agentic budget on.\n// See docs/prds/curator-sampler-wave1.md.\npackage sampling\n\n// Candidate is one item eligible for sampling. It is deliberately narrow:\n// an opaque identifier, the timestamp the timestamp-based strategies score\n// against, and an open Metadata bag for whatever a future strategy needs\n// (e.g. the embedding-backed surprisal strategy's vector) without widening\n// this struct for every strategy that comes after wave 1.\ntype Candidate struct {\n ID string\n At time.Time\n Metadata map[string]any\n}\n\n// Request carries the knobs every strategy shares: a selection cap and a\n// deterministic seed. Both are optional -- Cap 0 means unlimited (the \"all\"\n// strategy relies on this), Seed 0 is a valid seed, not \"unset\".\ntype Request struct {\n Cap int\n Seed int64\n}\n\n// Sampler selects a subset of candidates to spend a curator pass's agentic\n// budget on. Every implementation -- the four here and the future\n// embedding-backed surprisal strategy (GitHub #437) -- must be\n// deterministic given the same candidates and Request: same inputs, same\n// output, every time. That is what makes a pass reproducible and testable,\n// and is GitHub #437's stated acceptance criterion for the strategy it\n// adds behind this same interface.\ntype Sampler interface {\n // Name identifies the strategy for logging/attribution (e.g.\n // \"recency\", \"random\", \"all\", \"staleness\", later \"surprisal\").\n Name() string\n // Sample selects from candidates per req. Implementations must not\n // mutate candidates or rely on anything but candidates and req --\n // determinism depends on that.\n Sample(ctx context.Context, candidates []Candidate, req Request) ([]Candidate, error)\n}\n```\n\n### The four wave-1 strategies\n\nAll four are `internal/domain/sampling` types constructed with `NewX(...)`,\neach implementing `Sampler`:\n\n- **`recency`** (`NewRecency()`): sorts candidates newest-`At`-first (stable\n sort, ties keep input order so output is deterministic even when two\n candidates share a timestamp), then truncates to `req.Cap` (0 = all).\n- **`staleness`** (`NewStaleness()`): the mirror of recency -- sorts oldest-\n `At`-first, then truncates to `req.Cap`. This is explicitly a _proxy_:\n \"hasn't been touched in the longest time\" using whatever timestamp the\n caller populated `Candidate.At` with (created, updated, or\n last-reviewed -- the caller's choice, not this package's), never the\n embedding-based surprisal calculation GitHub #437 owns.\n- **`all`** (`NewAll()`): no filtering. Returns candidates in input order,\n truncated to `req.Cap` (0 = every candidate). Input order is the only\n order this strategy has an opinion about, and preserving it is what makes\n it deterministic.\n- **`random`** (`NewRandom()`): a uniform-random subset, sized to\n `req.Cap` (0 = every canLine truncated
},
{
"url": "/dev/prds/dashboard-aware-chat-navigation/",
"title": "Dashboard-aware chat: Archie sees the page, and points the operator there",
"section": "PRDs",
"body": "# Dashboard-aware chat: Archie sees the page, and points the operator there\n\n**Status:** Approved\n**Date:** 2026-08-26\n**Compound:** the \"chat available on any page\" surface work (global chat presence)\n\n## Decision\n\nMake the web chat **dashboard-aware**: the agent is told which dashboard page\nthe operator has _open_, knows what each page is for, and can **point**\nthe operator to the relevant page with a **clickable destination chip** the UI\nrenders and follows - Option B (context + navigate), not just \"tell me in text.\"\n\nThree seams, each an existing extension point, one new tool and one message field:\n\n1. **Current page, into the prompt.** The browser sends its route with every\n chat message; the gateway threads it into the system prompt's runtime-metadata\n env block. Archie always knows where the operator is looking.\n2. **Page index.** A page_index tool lists the dashboard pages and what each one\n shows, so Archie knows what to point at - the agent \"has the map\".\n3. **Navigate.** A dashboard_navigate tool returns a structured path/label; the web\n UI renders it as a clickable chip that routes the operator there. This is the\n \"plenty of resources\" the requirement named.\n\nWe deliberately keep the agent's answer honest: the chip is _evidence_ it can\nvalidly produce because dashboard_navigate is a real tool whose result is\nrendered, not a markdown link the model invents.\n\n## Why now\n\nThis is the natural next step of the \"chat on any page\" work, and the original\nrequest named it explicitly: _\"archie should be able to see what page you're on\ntoo. and point out where to go. so it needs plenty of resources.\"_ The chat\nis a full-page route with no knowledge of the rest of the dashboard; the agent\ncannot see which page the operator is on and cannot reliably direct them anywhere.\nThe critique of the chat UI already identified \"chat is not available on any page\"\nas the largest structural gap (P1). This design is the capability that makes that\ngap worth closing.\n\n## Shape of the API\n\n### Message field (gateway.go)\n\nAdd Page to Message:\n\n```go\n// Page is the dashboard route the operator is on when they sent this message\n// (e.g. \"/tasks\", \"/logs\"). Empty for non-web channels, which have no page\n// context. It is per-message, not per-session: the operator navigates freely\n// while a conversation stays open.\nPage string\n```\n\n### Web request (api_chat.go)\n\nchatMessageRequest gains Page, decoded into Message.Page in decodeChatMessage.\n\n### System prompt config (prompt.go)\n\nSystemPromptConfig gains Page; BuildSystemPrompt passes it through to the template.\nThe env block of archie.md.tpl renders the current page when set.\n\n### Page index (dashboard_tools.go, new)\n\nA package-level registry mapping route to {Label, Description}. page_index returns\nthe list so the model knows what each page shows:\n\n```go\ntype DashboardPage struct {\n\tPath string // \"/tasks\"\n\tLabel string // \"Tasks\"\n\tDescription string // \"Issues Archie picked up, and where they stand.\"\n}\n```\n\n### Navigation tool (dashboard_tools.go)\n\ndashboard_navigate validates its path against the registry and returns the resolved\npath/label. Unknown path means a clear error, not a guess. The model must call the\ntool (not invent a link) to produce a chip, so the chip is honest.\n\n### Tool wiring (turn.go)\n\nextraTools already merges TaskTools + SessionTools. Add the dashboard tools alongside\nthem, gated on the channel being the web UI. The tool list is built from the same\nregistry the prompt's page line comes from, so the agent never points at a page it\nwas not told about.\n\n### Web UI (chat-render.js, chat-tools.js)\n\nA dashboard_navigate tool call renders as a **clickable chip**: an anchor with\nhref=\"/tasks\" and the label. The chip is a\nreal link that works from any page once the chat is a global presence. The chip is\nstyled as an action, not a code line, so it visibly invites a click.\n\n### Route transfer (chat.js)\n\nEach sendMessage includes the current location.hash route as page in the stream\nrequest body, so the backend gets the operator's live position.\n\n## What we deliberately do NOT do\n\n- **No navigation from a markdown link.** The model must use dashboard_navigate; a\n bare \"click here\" is not rendered as a trusted route.\n- **No full-page route hijack from the chat.** The chip sets location.hash.\n- **No page index for non-web channels.** Telegram/discord have no dashboard.\n- **No automatic history annotation.** Page is per-message from the browser.\n- **No change to the dangerous-action approval flow.** Separately tracked.\n\n## Acceptance criteria\n\n1. Chat messages from any page carry the current page to the agent's prompt.\n2. page_index returns every dashboard page with a plain-language description.\n3. dashboard_navigate renders a clickable chip that routes to the target page.\n4. dashboard_navLine truncated
},
{
"url": "/dev/prds/dashboard-live-state/",
"title": "Dashboard live state",
"section": "PRDs",
"body": "# Dashboard live state\n\n**Status:** Approved\n\n## Decision\n\nThe dashboard must not require passive **Refresh** buttons. One app-wide Pinia\nstore owns the existing `/api/stream` EventSource and translates backend events\ninto resource revision counters. Pages load their authoritative HTTP projection\non entry and re-read it when the relevant revision changes. Event payloads are\ninvalidation signals, not substitute read models.\n\nSSE remains the transport. Dashboard updates are server-to-client only, and the\nexisting stream already provides replay, reconnect, and persisted ordering; a\nWebSocket would add a second transport without adding a capability.\n\nThe first slice covers resources for which the backend already emits a truthful\nsignal:\n\n- task events invalidate the dashboard, task board, workflow statistics, and\n the matching task-run page;\n- capture events invalidate the capture list;\n- curator events invalidate curator status, and curator actions also invalidate\n the skill catalogue;\n- update reports invalidate System status;\n- opening a page always loads its resource, and reopening the SSE stream\n invalidates mounted projections after a connection loss.\n\nLogs retain their dedicated SSE tail. Local mutations continue to re-read their\nown resource after success. Configuration, channels, and catalogues that have no\nbackend change event load on route entry; future write contracts must emit an\nowner-specific event rather than introduce polling or restore a button.\n\n## Boundaries\n\nThe Pinia store owns browser connection state and invalidation only. It does not\nbecome an alternate backend cache or copy domain state into a generic global\nobject. Existing feature modules continue to own their DTOs and API reads.\n\nOperational commands are not refresh controls. Channel **Reload** remains an\nexplicit adapter lifecycle action. Authentication recovery is also not a data\nrefresh: a 401 moves the application into shared authentication state; reloading\nthe same URL cannot restore Archie's missing or rotated token and must not be\noffered as a fix.\n\n## Verification\n\n- No passive page action renders the label **Refresh** or **Retry** for a read.\n- Only one shared `/api/stream` EventSource is opened by the application.\n- Resource classification tests distinguish task, capture, curator, skill, and\n update invalidations.\n- UI tests, type checking, generated asset freshness, and `task check` pass.\n"
},
{
"url": "/dev/prds/dashboard-port-brief/",
"title": "Dashboard port: what the agent delivers",
"section": "PRDs",
"body": "# Dashboard port: what the agent delivers\n\n**Status:** Approved\n**Date:** 2026-09-20\n**Beads:** `archie-core-tavn` (epic), `archie-core-ocfm` (navigation)\n**Reads with:** `docs/prds/vue-migration-checklist.md` (the item-by-item)\n\nThis is the standard the port is held to. The checklist says what to port; this\nsays how, and what counts as done. It exists because the first attempt ported\nthe flat topbar verbatim and invented a palette, both of which had already been\ndecided elsewhere.\n\n## The deliverable\n\nThe Preact dashboard, rebuilt in Vue 3 with shadcn-vue, feature complete\nagainst the checklist, gate clean, with `ui/dist` rebuilt and committed in the\nsame commit as the source it was built from.\n\n## Non-negotiables\n\n- **Vue 3 + shadcn-vue (Reka UI, Tailwind v4, Lucide).** A component that\n exists in shadcn-vue is not hand-rolled. Add it with the CLI\n (`npx shadcn-vue@latest add \u003cname\u003e`), do not paste it in.\n- **History routing.** `createWebHistory`, `base: \"/\"`. No hash routing.\n `src/legacy-hash-redirect.ts` handles old `#/path` links and stays.\n- **No test port.** 43 Preact test files are deliberately dropped.\n `task test:ui` is a `vue-tsc` typecheck. Write a test when there is a real\n failure to pin, not to re-assert a port.\n- **Do not downgrade TypeScript.** The target is TS 7 native, not TS 5.\n- **`ui/dist` is law.** Never hand-edit it, never omit it, never revert it.\n- **`task check` is the gate.** Not an assembled substitute for it.\n- **Beads, not markdown TODOs**, for anything that outlives the change.\n- **Conventional commits**, scoped `feat(webui):`. Commit gate-clean work\n without asking. Do not push without being told.\n\n## Componentisation\n\nOne component, one job, one file. A surface is composed from named components,\nnot assembled inside a single large file. The topbar is the worked example and\nthe required shape:\n\n```\ncomponents/topbar/\n Topbar.vue composes the header, owns nothing else\n Brand.vue Logo + BrandName, links to /\n Logo.vue\n BrandName.vue\n Nav.vue reads the nav model, renders links and groups\n NavTrigger.vue the shared top-level control, link or dropdown trigger\n NavGroup.vue one dropdown\n NavItem.vue one item inside a dropdown, with its tooltip\n SearchBar.vue\n SupportLink.vue\n ThemeToggle.vue\n ProfileDropdown.vue\n```\n\nThe same rule applies to every page ported after it. If a file is doing the\nwork of four named things, it is four files. Data and behaviour that more than\none component needs lives in `src/lib/`, not passed down through a chain of\nprops.\n\n## Ordering\n\nBuild the navigation restructure during the port, not after it. Porting the\nflat eleven-item bar first and restructuring later means writing the topbar\ntwice and touching the Go route registry twice. The approved design is five\ntop-level items (Dashboard, Work, Agent, Events, System), items renamed because\ntheir group carries the context, per-item descriptions shown as hover tooltips,\nConfiguration split into `/system/*`, `/settings` kept as a redirect, and Logs\nfinally given a nav entry.\n\n## Design authority\n\n- The approved documents win. Where a document decides something, implement it\n rather than re-deciding it.\n- **Do not invent a visual direction.** Palette, typography and density are the\n maintainer's call. A palette change is its own request, never a side effect\n of a port.\n- Contrast is AA against every surface the foreground lands on, hover states\n included. The corrected values (`--fg-subtle`, the dark\n `--primary-foreground`) came from a measured failure and must survive.\n- `color-scheme` follows the theme so the UA paints controls, scrollbars and\n overscroll to match.\n\n## Code style\n\nComment the non-obvious why: an invariant, a trap, a measurement, a contract\nanother file depends on. Do not narrate what the code plainly does, do not\nexplain a choice that was never in question, and do not write migration phase\nhistory into a diff. That history belongs in the commit message.\n\n## Done, per surface\n\n1. Renders with real data against `task dev`, not just typechecks.\n2. Keyboard reachable, focus visible, and the nav announces where you are.\n3. Works at 1440x900 and at 720px wide, with nothing clipped and no horizontal\n page scroll.\n4. Empty, loading, failed and unconfigured (501) states all say something true.\n A section that cannot load says so; it does not render blank.\n5. `task check` passes, `ui/dist` rebuilt, committed together.\n"
},
{
"url": "/dev/prds/dashboard-vocabulary/",
"title": "One source for the dashboard's server vocabularies",
"section": "PRDs",
"body": "# One source for the dashboard's server vocabularies\n\n**Status:** Finalised\n\n## Problem\n\nThe dashboard kept its own copies of two vocabularies the daemon owns:\n\n- the changed-file statuses (`added`, `modified`, `deleted`, `renamed`,\n `typechange`), which are the `Change*` constants in\n `internal/domain/workflow/task`;\n- the schema stamp on a `config_captured` payload, `events.ConfigCapturedSchema`.\n\nNothing derived one side from the other, while `/api/task-meta` already served\nthe status and action vocabularies for exactly this reason.\n\n## Decision\n\n`GET /api/task-meta` also serves `change_statuses` (id and label) and\n`config_schema`. `buildTaskMeta` in `internal/webui/api_task_meta.go` takes the\nids from the `Change*` constants and the stamp from `events.ConfigCapturedSchema`.\n\nThe dashboard renders `ui/src/lib/task-meta-snapshot.ts` until the served\ncatalogue arrives, or when archied is unreachable. `loadTaskMeta` replaces only\nthe keys the payload carries, so a server without the new keys leaves the\nsnapshot in place. `changeStatusLabel` and `configSchema` in\n`ui/src/lib/task-meta.ts` are the only readers; an unknown status renders as\nits id.\n\n## Verification\n\n- `TestTaskMetaChangeStatusesAreDeliberate` fails when a `Change*` constant is\n added without a label.\n\nA rename on one side therefore fails a test on the other.\n\n## Rejected\n\nDeleting `/api/task-meta` and accepting hand-copied constants. The endpoint is\nlive, and deleting it would still leave the two copies this document removes.\n"
},
{
"url": "/dev/prds/deep-research-capability/",
"title": "Deep research capability — design",
"section": "PRDs",
"body": "# Deep research capability — design\n\n**Status:** Draft\n**Date:** 2026-09-14\n**Scope:** A deep-research capability in archie-core: an orchestrator that\nspawns 1..N subagents to explore and research in parallel, collates their\nfindings, and returns one cited report. Grounded in web search and web fetch.\n**Beads issue:** none yet (this document is the input to it)\n**Depends on:** nothing shipped for slice 1; slice 2 depends on slice 1.\n\n## §0 Implementation status\n\nEvery claim in this document is mapped to what exists in the tree.\n\n| Claim | Status | Where it stands |\n| ---------------------------------------------------------------------- | -------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| `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` |\n| **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 |\n| `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 |\n| 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 |\n| A **delegate/subagent tool** on the chat surface | **Aspirational — zero code** | No `subagent`/`delegate` tool name is registered anywhere |\n| **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 |\n| 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 |\n| Per-result caps + spill-to-disk | **Implemented** Line truncated
},
{
"url": "/dev/prds/dynamic-curators/",
"title": "Dynamically-defined curators -- decision",
"section": "PRDs",
"body": "# Dynamically-defined curators -- decision\n\n**Status:** Approved\n**Date:** 2026-09-12\n**GitHub epic:** [#789](https://github.com/samcharles93/archie-core/issues/789)\n**Parent epic (curator engine):** [#435](https://github.com/samcharles93/archie-core/issues/435) (closed)\n**Depends on:** nothing shipping; this resolves the open question that epic #435's\n\"registered and configured declaratively, not hardcoded\" criterion left open.\n\n## §0 Implementation status\n\nEvery claim in this document is mapped to what exists in the tree.\n\n| Claim | Status | Where it stands |\n| --------------------------------------------------------------------------------------------------------------------- | ----------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| Curator engine family: typed contract, owning registry, start/health/stop, narrow host access | **Implemented** | `internal/domain/curator/{contract,registry,runtime,registrar,activity,wake}.go` |\n| Curator declared shape (`Manifest`: interval, cooldown, on_input, tools, skills, memory engine, conversations, model) | **Implemented** | `internal/domain/curator/contract.go`; `Validate()` requires `Interval \u003e 0` |\n| Two reference curators run through the registry | **Implemented** | `internal/infrastructure/skillcurator`, `internal/infrastructure/sessioncurator` |\n| Curator definitions as persisted, API-editable data | **Aspirational -- zero code** | No table, no entity, no RPC, no config block |\n| Generic definition-driven engine that executes a declared tool set + free-form instructions | **Aspirational -- zero code** | Only the two code-registered curators exist |\n| `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 |\n| 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\"` |\n| 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 |\n| Dynamic registration / removal (no restart) | **Aspirational -- zero code** | `Registry` has `Register`, no `Unregister`; `Runtime` has `Start`/`Nudge`/`Stop`, no `Add`/`Remove`; `Start()` snapshots membership |\n| Curator definition CRUD over REST | **Partial** | `GET /api/curators` read-only (`internal/webui/server.go`); no write routes |\n| Curator definition config | **Aspirational -- zero code** | No `[curator]` block in `intLine truncated
},
{
"url": "/dev/prds/dynamic-workflow-triage/",
"title": "Dynamic workflow triage",
"section": "PRDs",
"body": "# Dynamic workflow triage\n\n**Status:** Finalised\n\nEpic: archie-core-enfj. Scope: give `workflow.Route()` a real, content-aware\nfallback instead of unconditionally defaulting every unlabelled task to the\nheaviest workflow.\n\n## Problem\n\n`Route()` (`internal/domain/workflow/workflow.go`) has exactly two real\nsignals: an explicit `t.Workflow`, and label matches via\n`workflowForLabels` (`routing.go`, `bug`→tdd, `feature`→feasibility,\nbootstrap→bootstrap). Anything else — which is every chat-spawned task,\nsince `task_spawn` rarely sets labels — falls straight through to\n`reg[\"implement\"]`, the full `prepare → baseline → plan → build →\ncommit-push → review → open-pr` pipeline, regardless of what the task\nactually asks for.\n\n`task_spawn`'s own tool schema overpromises: _\"workflow: … Omit to let the\ndaemon route it\"_ (`internal/gateway/task_tools.go`) implies real\nrouting exists. It doesn't — \"route\" means \"check labels, then\ngive up and run the heaviest workflow anyway.\"\n\nConfirmed in production: a chat-spawned task whose\nentire content was \"this is just a test, close it when you receive it\" ran\nthe full `implement` pipeline end to end — 669,421 tokens, ~7 minutes —\nwhen nothing about the request needed a worktree-driven build at all. The\n`plan` stage's own LLM output _correctly_ concluded no code change was\nneeded, but that conclusion arrives two expensive stages (`baseline`,\n`plan`) too late to save anything.\n\n## Decision\n\nAdd a **`triage` workflow**: cheap, classifies once, then either closes the\ntask immediately or hands off to the workflow the task actually needs.\n`Route()`'s final fallback (`reg[\"implement\"]`) becomes\n`reg[\"triage\"]` when a `triage` entry is registered, else the existing\n`implement` fallback — a two-line change, fully backward compatible when\n`triage` isn't wired up.\n\nTriage does **not** replace label-based routing. A labelled task\n(`bug`/`feature`/bootstrap) already has a free, reliable signal and goes\nstraight to its known workflow unchanged — spending a classification\ncall there would be pure waste. Triage only fires in the gap that\ndefaults to `implement` blindly: no explicit workflow, no label match.\n\n### Triage workflow shape\n\n```\nStagePrepareWorktree() -- still needed: AgentStage mounts tc.Dir into the\n agent container: internal/domain/workflow/agent.go:74\n passes tc.Dir straight through. No cheaper\n primitive exists in this codebase for a\n directory-less classification call.\nAgentStage \"classify\" -- ReadOnly, ONE cheap agent turn, no exploration\n tools required beyond what ReadOnly already\n grants. Mirrors feasibility.go's decideCaptureTools\n pattern: a structured capture tool, called\n exactly once, MaxCalls: 1.\n```\n\nMission: read the task's title/body/labels (already in `taskPromptBlock`)\nand decide, via a captured `decide` tool call:\n\n```json\n{\"needs_code_change\": bool, \"workflow\": \"implement\" | \"tdd\" | \"feasibility\", \"reasons\": \"...\"}\n```\n\n`needs_code_change: false` → close path: reuse `closeNoChangesIssue`\n(`steps.go`) directly — issue closed if forge-backed, task marked\n`StatusMerged`/`\"completed -- no changes required\"` otherwise. No baseline,\nno plan, no build, no commit, no PR. This is the actual fix for the\nproduction incident: a no-op request now costs one classification call\n(low thousands of tokens) instead of 669,421.\n\n`needs_code_change: true` → sets `tc.Task.Workflow` to the classifier's\nchosen workflow (`implement`/`tdd`/`feasibility`, defaulting to\n`implement` if the field is missing or unrecognised) and an Outcome that\nrequeues the task under it, the same requeue mechanism\n`chatTaskControllerAdapter.ApproveChatTask` already uses\n(`main.go`, `requeue(ctx, taskID, fromStatus, workflow)`). The task then\nre-enters `Route()` on its next claim with `t.Workflow` now set, and takes\nthe normal path for that workflow from there — triage never runs its\nclassification twice for the same task.\n\n### Non-goals (v1)\n\n- Full bug/feature intent classification quality — the classifier only\n needs to be _directionally_ right; a wrong `tdd` vs `implement` call\n still produces a working PR, just via a slightly less-tailored pipeline.\n Tightening this is a follow-up, not a blocker.\n- Any change to label-based routing, `Route()`'s explicit-workflow branch,\n or `Bootstrap()`/`Feasibility()`/`TDD()` themselves.\n- Triage for forge-sourced (real GitHub issue) tasks with no labels —\n in scope structurally (same fallback branch), but the dominant case this\n fixes is chat-spawned tasks, which essentially never carry labels.\n\n## Testing\n\n- `workflow_test.go`: `Route()` picks `rLine truncated
},
{
"url": "/dev/prds/eda-playbook-engine/",
"title": "EDA playbook engine -- design",
"section": "PRDs",
"body": "# EDA playbook engine -- design\n\n**Status:** Draft\n**Date:** 2026-09-03\n**Beads epic:** `archie-core-t2db`\n\n## Problem\n\n\"Which workflow runs for which trigger\" is hardcoded Go: a literal\nlabel vocabulary (`workintake.labelKinds`) and a literal label-\u003eworkflow map\n(`workflow/routing.go`), extended only by adding a Go case or shipping a\nskill whose `metadata.archie.workflow` overrides one _named_ built-in\nworkflow. Extending the system to a new trigger, a new action, or a new\nevent source means a feature branch, a code change in a hardcoded\npath, and new Go tests -- for every addition. That is the barrier this\ndocument exists to remove.\n\nThe goal: triggers, the actions they run, and the\nconditions that connect them should be **drop-in and load**, not **drop-in\nand touch application code**. Yaegi-evaluated Go is the unit of imperative\n\"do a thing\" logic; YAML playbooks are pure orchestration data -- no logic,\njust \"on this event, with this data, call these actions, in this order,\nunder these conditions.\" The daemon's event coordinator doesn't know what a\n`bugfix` or `image-gen` action does, it resolves the name against a\nregistry and pipes typed data through.\n\nThis is explicitly **not** scoped to code-generation workflows. A playbook\naction can be any registered capability -- run a codegen workflow, send a\nmessage on a channel, open something on a forge, generate an image -- so\nlong as it's implemented behind one of the typed engine families below.\n\n## Relationship to existing decisions\n\n- `docs/prds/event-sources-and-reactions.md` ruled\n that reactions in the two epics it covers are **producer-only** (no veto,\n no mutation of in-flight work) and explicitly rejected a single generic\n `Source` interface as \"the untyped-hook shape the plugin engine rule\n exists to prevent.\" **This document extends that scope**: playbooks can\n dispatch to multiple typed action kinds, not just \"produce a\n `TaskEnvelope`.\" It does not relitigate producer-only-ness (still no\n veto/mutation of in-flight work here) and it does not introduce one\n generic interface -- see \"Typed positions, not one generic hook\" below,\n which is how it stays compliant with the plugin engine rule instead of\n reopening that document's #4.\n- `docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict`\n governs every extension point\n introduced here. Every position below is a typed domain contract with an\n owning registry, not a generic callback map. This is a hard constraint,\n confirmed against the existing rule text before writing this doc.\n- Yaegi is already a proven in-process extension mechanism\n (`internal/plugin`, `internal/domain/workflow/wfeval/yaegi.go`,\n `internal/gate/gateeval/yaegi.go`, `internal/skill/plugin.go`) -- this\n design generalises its existing role, it does not introduce a new\n execution mechanism.\n- `internal/domain/workflow/skillbuild.BuildRegistry` already composes a\n `workflow.Registry` from a skills catalogue, plugin-defined overriding\n built-in. The playbook loader described here supersedes label routing\n specifically; it does not replace `skillbuild`'s workflow-composition role,\n it becomes an additional input the daemon composes at startup.\n- Webhook event intake is a separate design. This\n document defines the router each webhook-sourced event should be able to\n reach; it does not redesign webhook receipt itself.\n\n## Shape: four logic positions, each a typed engine family\n\nEvery entrypoint kind (mechanism, action, loop, schedule, route, trigger) is itself a schema emitter: defining a new kind produces the\ngenerated contract downstream tooling consumes. The kinds slot into a fixed\nhierarchy of logic positions:\n\n```\nWorkflow -\u003e Module -\u003e Channel (telegram/whatsapp/email/...)\n -\u003e Forge (GitHub/Gitea/GitLab/...)\n```\n\nEach position is its own typed engine family per the plugin engine rule:\nidentity + capability-specific operations, an owning `Registry`/`Manager`,\nexplicit lifecycle where the implementation owns resources, narrow host\naccess. Concretely:\n\n- **Workflow** -- already exists (`internal/domain/workflow`). A playbook\n action of kind `workflow` invokes a registered `workflow.Registry` entry\n by name, unchanged from the existing execution path.\n- **Module** -- the new general-purpose action position. A `Module` is a\n Yaegi-evaluated implementation of a generated interface (args in, typed\n result out) for one declared action kind (e.g. `image-gen`, `notify`,\n `open-pr-comment`). This is the position that makes actions \"not\n restricted to code-generation.\" Full design (schema-per-kind, the\n registry shape, the trust boundary, the recommended first slice):\n `docs/prds/module-position.md`.\n- **Channel** -- already exists as `channels.Channel` (telegram, email,\n webhook). A playbook action of kind `channel` sends througLine truncated
},
{
"url": "/dev/prds/embedded-nats/",
"title": "Embedded NATS execution -- decision",
"section": "PRDs",
"body": "# Embedded NATS execution -- decision\n\n**Status:** Finalised\n\n**Date:** 2026-08-24\n\n**Beads epic:** `archie-core-q15y`\n\nThis decision supersedes the position that embedded NATS was only a\ndistribution mechanism and could not be an agent-execution topology. That was\ntrue only because the embedded listener was unauthenticated loopback. It left a\nsecond production architecture in which `archied` ran autonomous workflows in\nits own process, weakening the isolation boundary that managed task containers\nexist to provide.\n\n## One execution architecture, two broker deployments\n\nEvery autonomous repository workflow is handed over as one complete task via\nNATS and runs in a task-scoped `archie-agent` container. `archied` remains a\nnative, long-lived orchestration and interactive-chat process; its operator\nconfigured host filesystem access is unchanged. It owns task admission,\nstate, forge and worktree operations, container lifecycle, and the broker when\nthe embedded deployment is selected. It does not run an autonomous model loop.\n\nNATS has two supported deployment shapes:\n\n| mode | meaning |\n| ---------- | --------------------------------------------------------- |\n| `embedded` | `archied` owns an in-process JetStream server (default). |\n| `external` | `archied` and workers connect to the configured NATS URL. |\n\nBoth shapes have identical task semantics: one container and one full-task\nrequest per workflow. Broker placement must not select a different executor.\nThe legacy `agent` section and `containers.enabled` key remain decode-only\nmigration inputs. `nats.mode = \"off\"`, per-stage NATS, in-process execution,\nand subprocess execution are not production choices.\n\nSQLite remains authoritative for task state. NATS is the sole autonomous work\nhandoff. SQLite recovery may identify work that needs republishing, but it must\nnot cause `archied` to call `workflow.Run` locally.\n\n## Embedded reachability and authentication\n\nAn embedded listener uses a cryptographically random bearer token generated for\neach daemon start. The token exists only in process memory and the environment\nof managed worker containers; it is never written to config or logs.\n\nFor a native daemon with managed containers, startup resolves the Docker bridge\nthe workers will join. The listener binds only to that bridge's host gateway\naddress on a random port. Both the native daemon and workers use that same\nreachable endpoint, and every client supplies the generated token. Binding a\nDocker bridge address keeps the listener off ordinary LAN interfaces without\npublishing a host port. A configured user bridge is respected; otherwise the\nDocker default bridge is used. A network without a usable local IPv4 gateway is\na startup error for autonomous execution.\n\nIf Docker is unavailable, interactive chat may still start and embedded NATS\nmay remain loopback-only, but autonomous tasks park with an explicit container\ncapability failure. They never fall back to host execution.\n\n## Ownership and lifecycle\n\n- `internal/infrastructure/eventbus/nats` owns the authenticated embedded\n server and exposes its runtime endpoint, not the server implementation.\n- `internal/container` resolves the worker bridge and gateway and owns task\n container lifecycle.\n- `internal/app` composition selects embedded or external broker deployment,\n freezes the connected runtime endpoint for worker environments, and wires the\n full-task handoff.\n- `cmd/archied` remains process input only as the domain migration reaches this\n composition path.\n\nThe daemon starts the embedded server before its client, closes clients before\nthe server, and keeps JetStream data beneath the daemon data directory. NATS URL\nand token are startup-built values: a reload cannot send new workers to a broker\ndifferent from the one the daemon is using.\n"
},
{
"url": "/dev/prds/event-automation/",
"title": "Event automation: identified events, typed parameters, purpose-built agents",
"section": "PRDs",
"body": "# Event automation: identified events, typed parameters, purpose-built agents\n\n**Status:** Approved\n**Date:** 2026-09-23\n**Parent:** epic `archie-core-t2db`\n\n## Why this exists\n\nArchie is an event-driven automation system. Any system that can send a\nwebhook (a forge, an error tracker, a firewall, a monitoring stack) should be\nable to start an agent built for that job. The shape this replaces cannot:\n\n- A binding matches only the URL segment an event was posted to, and a source\n may have one binding. Two kinds of event from one sender cannot go to\n different workflows.\n- A mapping is a list of JSON paths written against one example payload.\n Nothing recognises what kind of event arrived.\n- Mapped values reach the task only as `key=value` lines in its body text.\n- Every task needs a repository and runs in a git worktree.\n- Every agent runs the same image with the same forwarded keys.\n\n## The model\n\n```\nsource ─▶ event type ─▶ mapping ─▶ binding ─▶ workflow ─▶ agent profile\n (identified) (params) (+ filter, (inputs, (image, tools)\n repo) profile)\n```\n\n### Sources\n\nA source is the endpoint one sender posts to. Its path is a generated UUIDv7\n(`/webhooks/capture/0199…`), so an endpoint cannot be guessed or collide. The\noperator may replace it with a custom path for a sender that cannot use that\nformat; a custom path must be unique and URL-safe, and is refused otherwise.\nA source owns the signing setting:\n\n- **Signed** (default). Archie generates the secret. Only events with a valid\n `X-Hub-Signature-256` or `X-Signature-256` HMAC are dispatched.\n- **Unsigned.** The operator turns signing off for a sender that cannot sign.\n The source and every event from it are marked unsigned in the inspector,\n the binding list and the task timeline. Turning signing off needs the same\n approval as arming a binding.\n\nUnauthenticated events on a signed source are captured and never\ndispatched.\n\n### Event types\n\nAn event type is a named kind of event from one source, such as\n`github / pull_request.opened` or `firewall / blocked_connection`. It is\ndefined by a match rule:\n\n- header equality (`X-GitHub-Event = pull_request`), and\n- payload conditions (`action = \"opened\"`, or a path being present).\n\nAn event type can be created two ways:\n\n- **From an example payload.** The operator pastes a payload (and optionally\n its headers), and archie converts it to the type's schema. No event needs to\n have arrived.\n- **From captures.** Archie proposes types from what has arrived, as below.\n\nEither way, archie infers the schema, not the operator:\n\n- Each capture gets a structural signature: the set of JSON paths with their\n value types, plus the headers that look like discriminators (`*-Event`,\n `*-Type`, `Content-Type`).\n- Captures from one source that share a signature are grouped. The inspector\n shows each group as a proposed event type, with its inferred schema, its\n number of events and a sample, until the operator names it or dismisses it.\n- The proposed match rule is the set of discriminators that separates the\n group from its siblings. The operator can edit it before saving.\n- A capture that matches no named type is shown as unidentified. It is never\n dispatched.\n\nTwo event types on one source whose rules can match the same event are\nrefused when the second one is saved.\n\n### Mappings\n\nA mapping belongs to an event type. It maps payload paths to named, typed\nparameters, and it is checked against the type's inferred schema, so a path\nthe type does not have is refused when the mapping is saved. Any number of\nbindings may reuse one mapping.\n\nEach mapping shows how many events it has matched, with the time of the most\nrecent, so an operator can see which mappings are live and which have never\nfired.\n\n### Workflows declare inputs\n\nA workflow definition declares its inputs:\n\n```yaml\nid: firewall-investigate\ninputs:\n src_ip: { type: string, required: true }\n severity: { type: string }\nrepository: none # none | optional | required\nprofile: network-investigator\nsteps: ...\n```\n\n- `repository: none` runs the agent in a scratch workspace with no clone.\n `required`, the default, gives the agent a worktree of the task's\n repository. `optional` gives it a worktree when the binding names a\n repository and a scratch workspace when it does not.\n- A workflow whose `repository` is not `required` may use only steps that need\n no repository. `agent.run` is one: it runs one agent mission and finishes\n the task as done, with no pull request.\n- The declared inputs reach the agent as structured data in the task brief\n and in the agent's context. They are not body text.\n- A workflow may declare `outputs`, the structured result it returns when it\n finishes.\n\n### Workflows call workflows\n\nA workflow step can call another workflow.Line truncated
},
{
"url": "/dev/prds/event-capture-storage/",
"title": "Event capture storage -- decision",
"section": "PRDs",
"body": "# Event capture storage -- decision\n\n**Status:** Finalised\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-t2db.1`\n\n`webhook-intake-security.md` decided points 1-5 (auth split, approval gate,\nrate limits, blast radius, retention/redaction) and explicitly left the\nstorage mechanism open, forward-pointing at \"`7d5u.2`, embedded NATS.\" That\npointer predates `7d5u.3`'s 2026-08-22 narrowing, which assigned capture\nstorage to this bead by name and told it to decide NATS-vs-SQLite itself\nrather than inherit an answer. This document is that decision.\n\n## Decision: SQLite, not NATS JetStream\n\nCaptured events are stored in archied's existing SQLite database, in a new\n`captured_events` table following the same shape as `internal/store/events.go`\n(`internal/store`, `*Store`, SQL migrations inline in Go). No JetStream\nstream is introduced for capture.\n\n### Why\n\n**NATS availability does not make capture a broker concern.** NATS is now\nunconditional for autonomous workflow handoff, including embedded mode, but\ncapture is also used by deployments with no repository workflow configured.\nSQLite is guaranteed present because it backs daemon state, and keeps\ncapture inspection independent of broker retention and consumer lifecycle.\nThe original version of this decision cited optional NATS as an additional\nreason; that premise was superseded by `archie-core-q15y`, while the storage\nfit and independence arguments remain.\n\n**Capture's access pattern doesn't need what JetStream is for.** JetStream\nearns its complexity for reaction delivery (`7d5u.2`) because multiple\nindependent consumers need fan-out, at-least-once redelivery, and Ack/Nak\nsemantics -- exactly the trap `CLAUDE.md` documents about `WorkQueuePolicy`\nand overlapping consumers. Capture has exactly one writer (the HTTP handler)\nand one reader (a human via the dashboard inspector, `t2db.2`). There is no\ncompeting-consumer problem to solve and no redelivery semantics to get right,\nso JetStream's core value proposition doesn't apply here. A bounded SQL\ntable is a better fit on the merits, not merely as a fallback.\n\n**Reusing `7d5u.2`'s stream, once it exists, would still be wrong.** That\nstream is provisioned for fan-out reaction delivery with its own retention\npolicy decision. Capture's retention need -- age- and count-bounded, prune\non write, no replay -- is a different shape. Building a second stream just\nfor capture, gated on an unrelated bead landing first, would trade a small\namount of duplication now for a hard dependency on `7d5u.2`'s timeline that\nthis bead's own acceptance criteria say not to accrue by accident.\n\nThis does not foreclose NATS later. If cross-daemon capture sharing or\ndurable replay becomes a real requirement, that is a new decision made\nagainst a real need, not now against a speculative one.\n\n## Storage shape\n\n`captured_events` table (`internal/store/captures.go`, mirrors\n`internal/store/events.go`'s pattern):\n\n| column | type | notes |\n| ------------- | ------- | ------------------------------------------------------------------ |\n| id | INTEGER | primary key, autoincrement |\n| received_at | TEXT | RFC3339Nano |\n| source | TEXT | opaque path segment chosen by the sender's operator |\n| remote_addr | TEXT | `RemoteAddr` at capture time |\n| content_type | TEXT | `Content-Type` header |\n| headers | TEXT | JSON, redacted |\n| body | TEXT | JSON, redacted (`webhookguard.RedactPayload`) |\n| authenticated | INTEGER | 0/1; always 0 until a source registers a secret (future: `t2db.4`) |\n\nIndexed on `(source, id)` for per-source listing and pruning, and `id` alone\nfor the global cap.\n\n## Disk-bound mechanics\n\nThree independent bounds, composed, per `webhook-intake-security.md` point 5\nand this bead's own \"capture cannot exhaust disk\" criterion:\n\n1. **Per-request size cap.** The HTTP handler reads the body through\n `http.MaxBytesReader` (256 KiB default, configurable). A single oversized\n POST is rejected (413) before redaction or storage sees it.\n2. **Per-remote-address rate limit.** `webhookguard.RateLimiter`, keyed by\n the request's remote address, applied before the body is even read.\n _Not_ keyed by the `source` path segment: `RateLimiter`'s own doc comment\n states its bucket map assumes a bounded, operator-registered key space,\n never evicted. `source` is exactly the opposite here -- an unregistered,\n attacker-chosen URL segment, since capturing senders with no registration\n yet is this endpoint's entire purpose. Keying on it would let one sendLine truncated
},
{
"url": "/dev/prds/event-sources-and-reactions/",
"title": "Event sources and reactions -- decision",
"section": "PRDs",
"body": "# Event sources and reactions -- decision\n\n**Status:** Approved\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-7d5u.1`, blocks `7d5u.2/.3/.4/.5`\n\nAnswers the four questions in `7d5u.1`'s description. Investigated against\nthe actual tree, not designed from scratch: three mechanisms already in this\ncodebase answer most of this, and the job here is picking the right one for\neach question and saying which packages change.\n\n## 1. In-process typed families, not out-of-process dispatch\n\nArchie has no out-of-process extension mechanism. The plugin engine\nrule (`docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict`,\nmechanically checked by\n`internal/plugin/architecture_test.go`) keeps every capability family\nin-process behind a narrow typed registrar; NATS RPC exists for\ndaemon\u003c-\u003eagentexec, a different actor with a different trust boundary (task\nexecution, not third-party extension code), not a precedent for generic\nplugin dispatch. Neither epic's near-term payoff -- react to a labelled\nissue, bind a captured webhook to a workflow -- needs extension code in\nanother language or process. Building out-of-process dispatch now would be\ndesigning for a requirement neither epic states.\n\n`docs/architecture/plugins-and-extensions.md` does **not** need amending.\nThe line that looked like a blanket ban on hooks (`archie-core-7d5u`'s notes\nrecord the correction) is scoped to Workflow semantics specifically, and\nnothing decided here touches Workflow's ownership of its own contracts.\n\n## 2. Reaction delivery: `internal/eventbus`'s contract, a NEW stream\n\n`internal/eventbus.Publisher`/`Consumer` already has everything a reaction\nneeds: `PublishUnique(subject, idempotencyKey, payload)` for at-least-once\nwithout duplicate enqueue, `Ack`/`Nak` with \"a handler returning an error\ncauses redelivery.\" Do not design new delivery semantics; use this contract.\n\n**Do not reuse the existing `nats.Client` as-is.** `Config.StreamName` and\n`Config.Subjects` are already composition-supplied (\"the bus must not know\nwhich subjects belong to which domain,\" `config.go`), but the\nretention policy is not parameterised: `New` hardcodes\n`Retention: jetstream.WorkQueuePolicy` (`client.go`), the competing-consumer\npolicy correct for `ARCHIE_TASKS` task distribution -- one message, claimed by\nexactly one consumer -- and wrong for reactions. Two independent reactions\nboth wanting to see the same event under `WorkQueuePolicy` hit exactly the\ntrap `CLAUDE.md` already documents: overlapping filter subjects on a\nwork-queue stream mean the second consumer silently gets nothing. Reactions\nneed fan-out, not claim-once, so the client needs retention made a `Config`\nfield (defaulting to `WorkQueuePolicy` so `ARCHIE_TASKS` is\nunaffected), and a second stream (`ARCHIE_REACTIONS` or similar) configured\nunder a fan-out-capable policy, alongside the existing task-distribution\nstream -- not instead of it.\n\nThis is where `7d5u.2`'s embedded-vs-external axis attaches: whichever NATS\ninstance backs `ARCHIE_TASKS` also backs the reaction stream. NATS is not\noptional as a technology -- the choice is only\nwhether it runs as an external server or embedded in-process\n(`github.com/nats-io/nats-server/v2` is already a direct, test-proven\ndependency, just never wired into production startup). `7d5u.2` wires that;\nthis document does not re-decide it.\n\n## 3. Reactions in these two epics are producer-only\n\nNo veto, no mutation of in-flight work. Two existing shapes cover everything\neither epic actually needs, and neither is a hook that can block something\nelse:\n\n- **Cheap wake, no payload.** `internal/domain/curator/wake.go`'s\n `WakeOnPrimaryInput` subscribes to the lossy `events.Bus` and nudges a\n runtime to check sooner; a dropped event only delays a check-in, never\n loses work, because the trigger decision is a deterministic state read at\n pass time, not the event payload. Model any \"check something sooner\"\n reaction on this, unchanged.\n- **Produce new work, real payload.** `daemon.go`'s existing `pollNATS` -\u003e\n `publishTask` path is already exactly a reaction that observes forge state\n and produces a `workintake.TaskEnvelope`. A webhook source is a second\n producer into the same path, not a new capability -- see question 4.\n\nA reaction that can veto or mutate an _in-flight_ task (block a PR from\nopening, alter a running stage) is a different, harder problem with its own\nordering and failure semantics, and belongs to `archie-core-h019` (adversarial\nself-review) if and when that epic needs one -- not here. Do not build a\ngeneral block-capable hook mechanism for either epic; nothing in their stated\nscope requires it, and it would duplicate whatever h019 eventually needs.\n\n## 4. No single generic intake interface; each domain keeps its own\n\nA `Source` interface generic enough to cover a forge issue, a chat message,\nand a cron tick wouldLine truncated
},
{
"url": "/dev/prds/execution-tree-state-machine/",
"title": "Execution tree and enforced state machine",
"section": "PRDs",
"body": "# Execution tree and enforced state machine\n\n**Status:** Approved\n**Authority:** `docs/architecture/agent-system.md` (canonical workflow model);\nsettles the \"enforced WorkflowExecution state machine\" item in\n`docs/architecture/migration-decisions.md` section 4.\n**Compounds with:** `docs/prds/task-run-detail.md` (attempt attribution),\n`docs/prds/state-store-contract.md` (wire contract and task-scoped grants).\n\n## Decision\n\nA WorkflowExecution becomes the root of a tree of StepExecutions. Every stage\nrun, and every agent call a stage makes, is its own durable record with a\nparent, an attempt, a status and an outcome. Both levels move only through a\ndeclared transition table, enforced by the State Store in the same transaction\nthat writes the audit row and the domain event.\n\n## Problem\n\n- A run is one `tasks` row. The only per-step record is the mutable `stage`\n column, overwritten as `workflow.Run` advances, plus observability events.\n A failed attempt cannot say which step failed or what its children did\n without replaying the event stream.\n- `Store.Transition` guards on the expected `from` status, but any `from` to\n any `to` is accepted. A `queued` to `merged` write succeeds.\n- Stop cancels one context in `daemon.runningTasks`. Nothing persisted says\n which work was in flight, so an agent call that outlives its stage (a\n reviewer, a container) is invisible to the store.\n- `workflow.Run` writes `tc.Store.Update` and discards the error, then emits\n `KindStageStart` separately. State and events can diverge.\n\n## Model\n\n```text\nWorkflowExecution (tasks row, id E)\n└── attempt N\n ├── StepExecution stage \"plan\" depth 0\n ├── StepExecution stage \"implement\" depth 0\n │ └── StepExecution agent \"implement\" depth 1\n └── StepExecution stage \"review\" depth 0\n ├── StepExecution agent \"review:1\" depth 1\n └── StepExecution agent \"review:2\" depth 1\n```\n\n- A StepExecution belongs to exactly one WorkflowExecution and one attempt.\n `parent_id` is null for a stage and names the enclosing StepExecution\n otherwise. Depth is derived from the parent, never supplied by the caller.\n- `kind` is `stage`, `agent` or `call`. A new kind needs a named consumer\n before it is added.\n- A `workflow.call` step (`docs/prds/event-automation.md`) is a `call`\n StepExecution in the caller's tree. The callee is its own\n WorkflowExecution, with its own tree, acting as its own identity, and the\n `call` step records the callee's execution ID. Trees never nest across\n executions, so each run's tree stays inside that run's authority.\n- A retry starts a new attempt. Earlier attempts' StepExecutions are never\n rewritten.\n\n## Transition tables\n\nWorkflowExecution statuses are the existing `taskstate` constants, persisted\nstrings unchanged. `taskstate` gains the one table every writer checks:\n\n| From | To |\n| --------------- | ---------------------------------------------------------- |\n| `queued` | `running`, `closed_wont_do` |\n| `running` | `queued` (crash recovery), `waiting_human`, `pr_open`, `completed`, `parked`, `closed_wont_do` |\n| `waiting_human` | `queued` (approve), `closed_wont_do` |\n| `parked` | `queued` (retry), `dead` (abandon), `closed_wont_do` |\n| `pr_open` | `merged`, `rejected`, `queued` (remediation), `closed_wont_do` |\n| terminal | none |\n\nStepExecution statuses:\n\n| From | To |\n| --------- | ------------------------------------------------------ |\n| `pending` | `running`, `cancelled` |\n| `running` | `succeeded`, `failed`, `cancelled`, `interrupted` |\n| terminal | none |\n\n`interrupted` means the process running the step died or shut down. It is\ndistinct from `cancelled`, which an operator or a parent asked for, and from\n`failed`, which the step reported.\n\nA StepExecution cannot reach `running` while its WorkflowExecution is not\n`running`, and cannot start under a terminal parent.\n\n## Enforcement\n\n- The table lives in `taskstate` (no dependencies), so the store, daemon and\n gateway share one copy.\n- Every store method that changes `tasks.status` checks the table and writes\n the audit and event rows, not only `Transition`. That includes the claim,\n `ParkTask`, `Requeue`, `RetryTask`, `BeginRemediation` and `RecoverStale`\n paths, several of which change status without an audit row.\n- The State Store rejects an illegal transition with a new sentinel,\n `ErrIllegalTransition`, carried across the wire through `mapError` like\n `ErrStaleTransition`. ALine truncated
},
{
"url": "/dev/prds/extensions-center/",
"title": "Extensions centre",
"section": "PRDs",
"body": "# Extensions centre\n\n**Status:** Draft\n\n\u003e Superseded by `docs/prds/store.md`.\n\nEpic: `archie-core-1786637490708-35-38424ead` / GitHub `#56` (\"Replace Skills\nwith a bundled Extensions centre\").\n\nSkills, Workflows, and Tools/MCP already exist as separate, working\ninventories with their own APIs (`api_skills.go`, `api_workflows.go`,\nconfig-driven MCP servers) and their own family-owned controller pattern\n(`curator.Registry`, `health.Registry`, `image.Registry`,\n`workflow.Registry` all already prove this shape). `plugin.Plugin`\n(`internal/plugin/plugin.go`) is already metadata-only, per\n`docs/architecture/plugins-and-extensions.md`. None of that is rebuilt here.\nWhat's missing, confirmed by grep, is: any config schema for enabling or\ndisabling a capability, any \"pending restart\" state tracking, and any single\ninventory that reconciles configured/bundled/discovered/active state across\nfamilies. This document decides those three things and the UI surface that\npresents them. It extends `plugins-and-extensions.md` rather than replacing\nit — that doc's decisions (metadata-only `Plugin`, typed capability\nfamilies, no generic dispatch) are unchanged.\n\nOut of scope: any remote or arbitrary-URL plugin installation path (the\nepic's own acceptance criteria forbid this, and `plugin.LoadDir`\n(`plugin.go`) already only reads `~/.config/archie/plugins/*.go` — this\ndocument does not add a fetch-by-URL variant to it).\n\n## Problem\n\n`internal/config/config.go`'s `MCPServer` and `ToolsConfig` structs have no\n`enabled` field (confirmed by the investigation grep). `api_config.go`'s\n`UpdateConfig`/`handleConfigUpdate` seam persists changes but has no state\ndistinguishing \"saved, takes effect now\" from \"saved, needs restart\" — the\nonly existing reload path (`ReloadChannel`, `server.go`) is\nchannel-specific and explicitly does not cover plugins or MCP servers.\n`server.go` already wires five separate optional inventories\n(Workflows, Skills, Curators, Channels, Captures/Mappings/Bindings) as\nindependent fields with no unifying type — an operator has no single\nplace to see \"what's available, what's enabled, what's actually running,\nand what's degraded\" across all of them. `ui/src/` has `settings/`,\n`skills/`, and `workflows/` directories already; there is no\n`ui/src/extensions/`.\n\n## Design\n\n### Unified inventory type\n\n```go\npackage extensions // internal/domain/extensions — new, app-level aggregator\n\ntype State string\n\nconst (\n StateAvailable State = \"available\" // bundled, not configured\n StateEnabled State = \"enabled\" // configured on, not yet live\n StateActive State = \"active\" // configured on and running\n StateDegraded State = \"degraded\" // active but unhealthy\n StateSkipped State = \"skipped\" // optional, disabled by config\n StatePendingRestart State = \"pending_restart\" // config changed, not yet live\n)\n\ntype Entry struct {\n Family string // \"skill\" | \"workflow\" | \"tool\" | \"plugin\" | \"integration\"\n Name string\n Core bool // non-disableable\n State State\n Health string // reuses whatever the family's own registry already reports\n}\n\ntype Inventory interface {\n List(ctx context.Context) ([]Entry, error)\n}\n```\n\n**Decision.** `extensions.Inventory` is a read-only aggregator, not a new\ndomain that owns state. It queries each family's existing registry\n(`curator.Registry`, `health.Registry`, `workflow.Registry`, the MCP client\nset, `plugin.LoadDir`'s result) for live state, and compares that against\nthe config-desired state (below) to compute `StatePendingRestart` — the diff\nis computed on read, not persisted, so there is no new durable state to keep\nconsistent with the registries themselves. This follows\n`migration-decisions.md`'s rule that cross-cutting aggregation composes\nexisting domain-owned contracts rather than duplicating their state.\n\n**Call site.** New package `internal/domain/extensions/inventory.go`.\nComposed in `internal/app/archied` (wherever `server.go`'s other optional\nfields — Workflows, Skills, Curators — are wired) since it needs\nreferences to every family's registry, which only application-layer\ncomposition has.\n\n### Config-backed enablement\n\n**Decision.** Add `enabled bool` (default `true` for pre-existing configured\nentries, so no upgrade silently disables anything already configured) to\neach family's config element: `MCPServer.Enabled`, and equivalent fields on\nwhatever config types back skills/workflows/plugins if they don't already\nhave an on/off switch. Core capabilities (identity, workflow engine, State\nStore connectivity — named in `organisation.md`'s cross-cutting packages)\nhave no `enabled` field at all; a config value can't be added to something\nthat doesn't expose the toggle, which is the \"non-disaLine truncated
},
{
"url": "/dev/prds/external-agent-harness/",
"title": "External agent harnesses",
"section": "PRDs",
"body": "# External agent harnesses\n\n**Status:** Approved\n**Authority:** `docs/architecture/agent-system.md` (agent execution as a data\nboundary); settles the harness non-goal deferred by\n`docs/prds/service-decomposition.md`.\n**Compounds with:** `docs/prds/execution-tree-state-machine.md` (a harness\nrun is one `agent` StepExecution), `docs/prds/binding-secret-encryption.md`\n(the at-rest envelope reused for harness credentials).\n\n## Decision\n\nA workflow stage can run on an external coding-agent CLI instead of the\nbuilt-in agent loop: Claude Code, Codex, Pi, OMP, GitHub Copilot CLI, or any\nother CLI packaged as a Docker Sandbox Kit v3. Each authenticates with an API\nkey or the operator's subscription login, and can carry the operator's own\nskills, plugins, subagents and instructions.\n\nTwo boundaries hold regardless of what the harness does:\n\n- **The real credential never enters the container.** The container sees\n sentinel values; archie's egress proxy substitutes the real credential on\n outbound requests and performs OAuth refresh on the host.\n- **Archie's workflow guarantees are enforced outside the harness.** Git,\n protected paths, read-only stages, gates and budgets are checked by archie\n around the process and against the worktree afterwards.\n\n## Kits\n\nA harness is packaged as a Kit v3 image: an OCI image whose\n`vnd.docker.sandbox.kit.descriptor` manifest annotation declares what the\nharness needs. Archie reads descriptors with the published\n`github.com/docker/sandbox-kit-spec/v3/spec` package and does not maintain\nits own descriptor format. Published Kits run unmodified.\n\nArchie is a partial Kit runtime. It implements these capability types:\n\n| Type | Archie behaviour |\n| ------------------- | ----------------------------------------------------------------------------------------- |\n| `credential@1` | Proxy-managed only, described below. |\n| `network-policy@1` | Enforced by the egress proxy. |\n| `volume@1` | A Docker volume keyed by WorkflowExecution, deleted with it. |\n| `lifecycle@1` | Install and startup hooks run on container create. |\n| `agent-sessions@1` | The headless `prompt` and `resume` invocations for the stage. |\n| `agent-skills@1` | The operator's skills store (`skills_dir`), mounted read-only whatever the Kit asks. |\n| `agent-context@1` | The workload's profile file beside the workspace, indexing each Kit's guidance. |\n| `resources@1` | Container CPU and memory limits. |\n\nEvery other type fails closed: a required entry refuses the launch, an\noptional one is skipped and recorded on the step. `credential@1` with\n`passthrough: true` and any credential for a forge service are refused.\n\nThe operator's own setup (plugins, subagents, instructions, settings) is a\nmixin Kit, published with the harness Kit as a Kit set: the set merges their\nlayers into one image. It is versioned image content, rewritten on every\ncreate, never state a run can modify.\n\n## Contract\n\nA harness run is a second implementation of `agentexec.Runner`. It takes the\nsame `Request` and returns the same `Result`, so workflows, the daemon and\nthe State Store do not know which runner ran a stage.\n\n`agent-sessions@1` supplies the invocation. Archie supplies, per CLI, an\noutput adapter that translates the CLI's JSON output stream into\n`ToolCallReporter` calls, `Usage` and a session ID. A CLI with no adapter can\nrun stages with no capture tools, reporting no usage; its token budget falls\nback to wall clock.\n\nWorkflow definition validation rejects, at load time, a stage whose needs the\nselected harness cannot meet: capture tools without an adapter, or a gate\nretry without a `resume` verb.\n\n## Selection\n\nA harness is an agent profile. `docs/prds/event-automation.md` defines a\nprofile as the execution environment a workflow selects; a harness profile\nnames one Kit pinned by digest, a workload Kit or a published Kit set, in\nplace of a container image. Archie runs that Kit's image and composes no Kits\nitself; a bare mixin is refused. Everything else about profiles\nholds: a workflow names its profile, a stage may name a different one, and a\nprofile holds no secrets.\n\n`archie-agent` builds the stage's runner from the stage's profile: the\nai-sdk agent loop for an image profile, the harness runner for a Kit\nprofile. Image profiles, and every workflow already written against them,\nare unchanged. A Kit profile named by no workflow is a validation error.\n\nA stage naming a different profile than its workflow's is a separate run,\nnot a mid-container runnLine truncated
},
{
"url": "/dev/prds/identity-decision/",
"title": "Identity for users, agents and external agents — decision",
"section": "PRDs",
"body": "# Identity for users, agents and external agents — decision\n\n**Status:** Draft\n**Date:** 2026-09-22\n**Authority:** `docs/architecture/organisation.md` for placement;\n`docs/architecture/migration-decisions.md` §3 for the attribution semantics this\ndocument implements; `docs/prds/agent2agent-protocol.md` for the A2A surface that\nconsumes it.\n\n## Decision\n\nOne identity record covers every actor archie has: users, agents, external agents,\nservice accounts and the system. Authentication is delegated to the estate's OIDC\nprovider, and attribution stays archie's.\n\nAuthentication and authorisation are OSS archie integrates; a design that\nhand-rolls either fails this document.\n\n## The provider\n\n**Authelia is the only identity provider**, because the estate already runs it in\nfront of the dashboard and it issues credentials for both kinds of caller: humans\nuse the authorisation code flow, and machines use the `client_credentials` grant,\nwhich yields a token whose subject is the client's own identifier.\n\n**Each agent is its own provider client.** A shared client would make two agents\nindistinguishable in the audit trail and revocable only together, which is the\nproperty attribution needs and the reason per-client registration is a\nrequirement.\n\n**A person's client and an agent's client are registered separately**, because the\ntwo token shapes differ and a shared registration would collapse the distinction\nthe attribution rests on. A person's token names them in `sub`. A machine's token\ncarries no `sub` at all and names its client instead, so a machine identity is keyed\non its client registration and exists one per client. A token asserting neither is\nrefused.\n\n**A person's token requests the audience at the authorisation endpoint**, not only\nat the token endpoint. A provider that otherwise returns the audience empty\nproduces a valid token archie must refuse, and that refusal looks like a signing\nfault rather than a missing request parameter.\n\n**SPIFFE/SPIRE is not adopted.** It is adopted and maintained, and its attestation\nis strictly stronger than a secret: a workload proves what it is rather than what\nit holds. It is rejected here on operational fit, not on quality: it adds a\ncontrol plane archie does not have, and the property it buys — identity attested\nfrom the platform rather than from a presented secret — answers a threat archie\ndoes not face, because archie's agents run as containers the operator launches and\nalready receive their credentials from the daemon that owns them. It is the right\nanswer when agents run on infrastructure the operator does not control.\n\n## What archie owns\n\n- **The identity record.** `internal/domain/identity` survives as archie's own\n record of an actor and is not replaced by the provider's directory, because the\n record carries what the directory does not: the lifecycle, the bindings and the\n attribution below.\n- **The lifecycle.** Active, suspended and retired, with rename, suspend,\n reactivate and retire, remain archie's. Suspending an identity must stop it\n acting whether or not the provider still authenticates it.\n- **The subject binding.** An identity that proves itself is bound to the provider\n subject that asserts it. This is the same bridge `identity_aliases` already\n provides from a legacy name to an identity, so the second binding is the same\n mechanism rather than a new one.\n- **Attribution.** Who acted, and under whose authority.\n- **The audit trail of identity changes**, which already records an actor, a source\n and a request identifier for every mutation.\n\n## What archie never owns\n\nA credential, a password, a session, a token, a signing key, a second-factor\nenrolment, or a permission rule.\n\n## How an agent proves who it is\n\n**An agent authenticates by presenting a token the provider issued to its own\nclient**, and archie validates it against the provider's published signing keys and\ntakes its subject as the acting identity. The agent holds a client secret; archie\nholds only the public keys, so a compromised archie cannot mint an identity.\n\n**A WebMCP tool call is not a proof of agent identity and cannot be made one.** A\npage can invoke its own tools, so an agent's call and a page script's call arrive\nat archie identically. No field, header or convention distinguishes them, because\nthe difference does not exist on the wire.\n\n**A WebMCP tool call is therefore attributed to the identity the request\npresented, with its source recorded as a hint.** It may record that the request\ncame from the dashboard; it never records that an agent acted, and it never\nrecords that a human approved. A tool call that a page script can forge must not\nbe the thing an audit trail rests on.\n\n**Agent-initiated action therefore arrives on a surface that carries a credential**\n— the A2A surface, or an authenticated agent call — because that is the only place\nan agent's Line truncated
},
{
"url": "/dev/prds/image-capability-contract/",
"title": "Image capability contract and configuration",
"section": "PRDs",
"body": "# Image capability contract and configuration\n\n**Status:** Approved\n\nEpic: archie-core-1786748942120-1-6636e629 / GitHub #496 (\"Image generation\ncapability: hosted API baseline plus local GPU workflows\").\n\nThe contract and configuration (#497) shipped first and is settled — see\n\"Package: `internal/domain/image`\" below. This document now covers the full\nfeature set: hosted provider (#498), local GPU provider (#499), `/image`\nrouting and clarification (#500), delivery through channels and web (#501).\nDocumentation (#502) and the cross-cutting test matrix (#503) are execution\nwork against the design below, not open design questions, so they are not\ngiven their own sections — each preceding section states its own test\nobligations inline.\n\n## Problem\n\nArchie needs a provider-neutral boundary for image generation/editing so a\nhosted API (gpt-image-2-class) and a future local GPU backend can both\nimplement it without either one leaking into the domain contract. Nothing\nin the repo defines this (`grep -ri image` over `internal/domain` and\n`internal/config` returns nothing image-specific).\n\n## Design\n\nFollows the plugin engine family shape already established by\n`internal/domain/curator` and `internal/domain/memory`\n(`docs/architecture/plugins-and-extensions.md#plugin-engine-rule-strict`): a\ntyped contract with real domain operations,\nan owning `Registry` (register/get/names, no start/stop lifecycle — see\nbelow), and narrow host access via a `Registrar`.\n\n### Package: `internal/domain/image`\n\n**Why no `Lifecycle` (`Start/Health/Stop`)**: curator and memory engines are\nlong-running — they hold a background cadence or a persistent connection\nworth health-checking. An image provider is call-scoped: it either serves a\n`Generate`/`Edit` request or it does not. Health here means \"is this\nprovider usable at call time\", which is exactly what `Generate`/`Edit`\nreturning a typed `ErrUnavailable` already communicates — a separate\n`Health()` poll would just duplicate that. `Registry` still owns\nregistration and lookup, so provider selection is testable with fakes per\nthe acceptance criteria, but there is no `Start`/`Stop` to orchestrate.\n\n```go\n// Capability declares what one provider supports, discoverable before a\n// request is built so a caller can reject an unsupported combination (e.g.\n// edit-with-mask on a generate-only provider) instead of sending it and\n// parsing a provider-specific error back out.\ntype Capability struct {\n Generate bool\n Edit bool // edit requires at least one input image\n Mask bool // edit supports a mask restricting the edited region\n MaxInputs int // 0 = Edit unsupported\n Sizes []string // provider-declared output sizes, e.g. \"1024x1024\"\n}\n\n// Provider is the typed contract every image backend implements — hosted\n// (gpt-image-2-class) or local (GPU recipe). No Lifecycle: a provider is\n// call-scoped, not long-running (see design doc rationale).\ntype Provider interface {\n Name() string\n // Class distinguishes hosted (spends money/quota per call) from local\n // (spends host GPU/time). Selection logic and config validation key off\n // this, never off Name, so a new provider cannot silently slip through\n // the hosted-cost gate under an unrecognized name.\n Class() ProviderClass\n Capability() Capability\n Generate(ctx context.Context, req GenerateRequest) (Result, error)\n Edit(ctx context.Context, req EditRequest) (Result, error)\n}\n\ntype ProviderClass string\n\nconst (\n ClassHosted ProviderClass = \"hosted\"\n ClassLocal ProviderClass = \"local\"\n)\n```\n\nRequest/result types (provider-neutral, no OpenAI types):\n\n```go\ntype GenerateRequest struct {\n Prompt string\n Size string // \"\" = provider default\n N int // number of images; 0 = 1\n Options map[string]string // provider-specific overflow (e.g. \"quality\"),\n // deliberately untyped so the contract does not\n // grow a field per provider\n}\n\ntype EditRequest struct {\n Prompt string\n Inputs []ImageData // 1..Capability.MaxInputs\n Mask *ImageData // nil unless Capability.Mask\n Size string\n N int\n Options map[string]string\n}\n\n// ImageData carries image bytes in-process, never a path or URL: the\n// domain layer must not assume a filesystem or a fetchable location (mirrors\n// why curator's Registrar never receives *daemon.Daemon — no ambient host\n// access smuggled in through a \"just a string\" field).\ntype ImageData struct {\n Bytes []byte\n MIMEType string\n}\n\ntype Result struct {\n Images []ImageData\n Provider string\n Model string\n CreatedAt time.Time\n}\n```\n\n### Error taxonomy\n\n```go\nvar (\n ErrUnavailable = errors.New(\"image provider unavailable\") // missing credential, backLine truncated
},
{
"url": "/dev/prds/inline-review/",
"title": "Inline review -- decision",
"section": "PRDs",
"body": "# Inline review -- decision\n\n**Status:** Finalised\n**Beads issue:** `archie-core-q9au`\n**Builds on:** `archie-core-h019` (adversarial self-review)\n\n## Problem\n\nFindings reach the operator only as a flat list in the PR body\n(`renderPRReviewSection`, h019.6): ``- `file.go` (confirmed, error): \u003cdefect\u003e\n— \u003cscenario\u003e``. That is a report _about_ the code, not a review _of_ it. A real\nreviewer anchors each finding to the line it is about, so the author sees it in\ncontext — and, when the fix is mechanical, attaches the replacement so it can be\napplied in one click.\n\nBoth halves are missing:\n\n- **No line-anchored comment.** `forge.Forge.Comment` posts to the PR\n _conversation_ (`Issues.CreateComment`); nothing creates a review comment at\n `path` + `line`.\n- **No suggested fix.** `ReviewFinding` carries `File`/`Line`/`Defect`/\n `FailureScenario`/`Verdict`/`Level`/`Category` — no replacement code, so even\n an anchored comment could only describe the fix, not offer it.\n\n## Decisions\n\n### 1. A narrow, type-asserted write surface\n\nThe set of comments travels in one call, so a forge that can only carry them on\na submitted review needs one request rather than one per finding:\n\n```go\ntype ReviewCommentWriter interface {\n CreateReviewComments(ctx context.Context, owner, repo string, number int,\n comments []InlineReviewComment) error\n}\n```\n\nType-asserted like `PullRequestReader`/`PullRequestReviewReader`, so a forge\nthat cannot do it is skipped rather than faked. The stage reaches it through\n`workflow.Forger`, whose production implementation is `forgerpc.Client` — the\nworker holds no forge credentials, so the daemon's forgerpc server type-asserts\n`forge.ReviewCommentWriter` and answers an incapable forge with an error the\nbest-effort stage logs.\n\nThe comment's line is anchored to the pull request's **current head revision**,\nresolved inside each implementation rather than passed in by the caller: it is\nthe revision the comments are attached to, and the caller that produced the line\nnumbers holds no forge credentials to read it. The caller does pass the revision\nthose line numbers were **measured on** (`TaskContext.ReviewedHeadSHA`,\nrecorded when `StageOpenPR` opens the pull request), and the implementation\nposts only while the head it read still matches it — see §4.\n\nPer-forge reality, verified against the SDKs:\n\n- **GitHub** — direct: `PullRequests.CreateComment` with\n `{Body, Path, Line, Side: \"RIGHT\", CommitID}`.\n- **Gitea** — no direct inline-comment call. Inline comments ride on a submitted\n review (`CreatePullReview` with `Comments` and a `COMMENT` state). The Gitea\n implementation therefore submits a single `COMMENT`-state review carrying the\n findings, or the capability is simply absent (the type assertion skips it).\n Decided: implement Gitea as a `COMMENT`-state review; do not block the feature\n on it.\n\n### 2. `Suggestion`, and only on confirmed findings\n\n`ReviewFinding` gains an optional `Suggestion string` — the replacement text for\nthe anchored line, rendered as a fenced `suggestion` block (GitHub's one-click\n\"Commit suggestion\").\n\n**Only `confirmed` findings may carry one.** A wrong suggestion is a\none-click path to breaking code a reviewer then has to notice; `confirmed` is by\ndefinition the verdict the reviewer traced and can state the failure for. A\n`plausible` finding is a worry, and a worry gets a sentence, not a patch. This is\nthe h019.5 calibration rule reused, not a new one.\n\n`Suggestion` replaces the anchored line exactly, and is only rendered when\n`Verdict == confirmed`. Single-line only in this cut;\nmulti-line (GitHub's `StartLine`/`StartSide`) is a follow-up, because a\nmulti-line suggestion that is off by one line silently corrupts the file. The\nrule is enforced in `ReviewFinding.Validate` — an embedded newline is rejected\nthere, so the `record_finding` tool refuses it with feedback the model can act\non, rather than the renderer silently posting a fence that applies only its\nfirst line.\n\n### 3. Which findings are posted inline\n\nOnly findings that are **line-anchored** (`Line \u003e 0`). A whole-file finding\n(`Line == 0`, e.g. \"README.md is stale\") has no line to attach to and stays in\nthe PR-body list. The body section keeps listing everything, so it remains the\ncomplete record and the fallback.\n\nFindings that block never reach this path: a surviving blocking finding parks\nthe task before `StageOpenPR`, so there is no PR to comment on. Inline comments\nare the non-blocking, line-anchored subset — which is exactly the set that would\notherwise be a body-only list the author has to map back to lines by hand.\n\n### 4. A best-effort stage after `StageOpenPR`\n\nNew `StagePostReviewComments`, after `StageOpenPR`:\n\n1. Read the report stashed by `StageReview` (`tc.ReviewReport`, h019.6).\n2. Post each line-anchored finding as an inlLine truncated
},
{
"url": "/dev/prds/mcp-tool-completion/",
"title": "MCP client and tool-guardrail completion",
"section": "PRDs",
"body": "# MCP client and tool-guardrail completion\n\n**Status:** Approved\n\nEpic: `archie-core-1786637493439-140-2cee2e9b` / GitHub `#161` (\"[EPIC] Tools:\ncentral registry, MCP client, guardrails\").\n\nThis document is scoped to five sub-features of that epic: MCP\nserver-initiated sampling, the per-server parallel-tool-calls flag, sandboxed\nMCP tool servers, a Firecracker sandbox backend, and sequential dispatch with\nper-result previews.\n\nOut of scope, and not to be touched: the central registry\n(`internal/tools/registry.go`), all three MCP transports (stdio/HTTP/SSE,\n`internal/tools/mcp/transport*.go`), reconnect-with-backoff\n(`transport.go`), guardrail loop detection\n(`internal/tools/guardrail.go`), idempotent/mutating classification\n(`internal/tools/classification.go`), concurrent tool dispatch (`#183`), and\nprogressive disclosure wiring (`internal/app/archied`). These are settled and\nproduction-wired.\n\n## Problem\n\n`bd search \"MCP client\"` shows five closed transport beads and one open:\nserver-initiated sampling (`#151`). `internal/tools/mcp/client.go`\nholds a single `callMu *sync.Mutex` that serialises every `tools/call`\nregardless of server — `ParallelToolCalls` does not exist on the `MCPServer`\nconfig struct (`internal/config/config.go`), confirming `#177` is a\nreal gap, not a stale bead. `#178` (wire MCP tool servers for the chat agent,\nsandboxed) and `#179` (Firecracker substrate) have no corresponding code —\nMCP servers run as whatever the config's `Command`/`Args` launches,\nunsandboxed. `#182` (sequential tool dispatch with per-result previews) is\nopen; concurrent dispatch (`#183`) is closed, so there are two dispatch paths\nand this PRD decides how they coexist.\n\n## Design\n\nSub-features are independent; there is no new shared type this document\nintroduces. Each section below stands alone.\n\n## MCP server-initiated sampling (`#151`)\n\n**Decision.** Implement as a callback on `mcp.Client`, not a second\ntransport. The MCP spec's `sampling/createMessage` request flows server→client\nover the same connection each transport already maintains\n(`transport.go`'s stdio/HTTP/SSE all multiplex request and response frames).\nAdd a `SamplingHandler func(context.Context, SamplingRequest) (SamplingResult, error)`\nfield to the client's config struct next to the existing transport fields,\ndefaulting to nil (server sampling requests get a JSON-RPC \"not supported\"\nerror when unset — never a silent drop).\n\n**Call site.** `internal/tools/mcp/client.go` — add the handler field and a\ndispatch branch in whatever function demuxes incoming server\nmessages by method name (the same switch that already routes\n`notifications/*`). Wire a concrete handler in\n`internal/app/archied/main.go` that routes the sampling request through the\nsame chat-model call path `chatGenerateOptions` already uses, so a\nserver-initiated sample gets the daemon's configured model, not a second\nprovider client. The agent worker hosts the same configured MCP servers on the\ntask path and runs its own model runtime, so `internal/app/agentworker` wires\nthe same seam from the task's builder model: a server that samples succeeds\ninside a chat turn and inside a task, never one and not the other. The message\nmapping and the token bound are shared (`internal/agentexec`, next to the\nruntime both paths call models through) so both paths bound a sample\nidentically.\n\n**Reuse check.** The chat model invocation path already exists\n(`chatGenerateOptions`, `main.go`) and the task model path already exists\n(`agentexec.NewRuntime`, the runtime an agent stage runs on); this reuses both\nrather than adding a parallel model-calling path for MCP sampling.\n\n**Failure mapping.**\n\n| condition | contract error |\n| ------------------------------- | ------------------------------------------------------------------------------------------ |\n| no `SamplingHandler` configured | JSON-RPC method-not-found, per spec |\n| handler returns error | JSON-RPC internal error, message from handler |\n| handler timeout | JSON-RPC timeout error; use the transport's existing request-timeout config, not a new one |\n\n**Testing.** Fakeable entirely — a stub `SamplingHandler` and a fake\ntransport that emits a `sampling/createMessage` frame. No real backend\nneeded; belongs in `task check`.\n\n## Per-server parallel-tool-calls flag (`#177`)\n\n**Decision.** `ParallelToolCalls bool` (default `false`) goes on `MCPServer`\nin `internal/config/config.go`, next to `Transport`/`Command`. The\nmutex in `client.go` becomes per-server: when `ParallelToolCalls` is\nfalse (default, and the only behaviour), keep the single `callMu`\nserialising that server's calls exactly as now; when true, drop the muLine truncated
},
{
"url": "/dev/prds/memory-engine-unification/",
"title": "Memory engine unification: four scopes, CRUD, and one write path -- decision",
"section": "PRDs",
"body": "# Memory engine unification: four scopes, CRUD, and one write path -- decision\n\n**Status:** Approved\n**Date:** 2026-09-16\n**Findings:** `memory-4` and its dependants in the adversarial sweep\n(`.local/issue-tracker`); the real defect is the split described below, for\nwhich `memory-4` is a symptom\n**Supersedes:** the draft `memory-turn-context.md` (its synchronous-read\nargument survives and is reused; its `Manager` method and consumer-owned port do\nnot)\n**Settles:** four open items in `docs/architecture/migration-decisions.md#5`\n(listed at the end)\n\n## Problem\n\nThere are **two live memory stores for one assistant**, split by which component\nwrites them, and the chat turn reads neither.\n\n| Family | Written by | Root | Format |\n| ----------------------------------------------------------- | ----------------------------------------------------------------------------- | ------------------------- | ----------------------- |\n| `internal/memory` (`Manager`, `builtin.Provider`) | the chat agent's `memory_edit` tool via `memorytoolprovider` (`bootstrap.go`) | `\u003cworkDir\u003e/memory` | `MEMORY.md` / `USER.md` |\n| `internal/domain/memory` + `internal/infrastructure/memory` | the session curator (`sessioncurator.go`) | `\u003cworkDir\u003e/memory-engine` | identity-keyed blocks |\n\nThey share no code, no format and no scope vocabulary. Neither reaches a prompt:\n`Manager.SystemPromptBlock` (`internal/memory/manager.go`) has no production\ncaller anywhere, so the agent can write memory through a tool and never read it\nback.\n\nThree further defects fall out of the same split:\n\n1. **The engine's contract is not CRUD.** `Store` is `Write`/`Query`/`List`/\n `Forget` — create, read, delete, and **no Update**. The retired file provider\n _does_ have `handleAdd`/`handleReplace`/`handleRemove`, so the family being\n deleted is operationally richer than its replacement.\n2. **There is no scope model.** The contract carries one opaque `Identity\nstring`, and the curator fills it with a **session id** (`sessioncurator.go`)\n — which is none of the four scopes `docs/architecture/agent-system.md`\n requires, and stops meaning anything when the session ends.\n3. **The chat turn has no user identity on half the channels.** Telegram and\n email populate `SenderID` with a person; the dashboard populates it with\n nothing, and a webhook populates it with nothing either — a route path names\n a source, not a person, so `webhook.go` leaves `SenderID` empty and carries\n the route in `Inbound.BudgetKey` for rate limiting. `sender_id` is persisted\n (`session_store_postgres.go`), so whatever a channel puts there reaches the\n consumers that read it.\n\n`agent-system.md` says the write-scope selection and cross-scope sharing\nrules \"require a focused memory design decision\". This is that decision.\n\n## Decision\n\n### 1. One engine, addressed by four typed scopes\n\n`internal/domain/memory` is the only memory engine. `Observation.Identity`,\n`Query.Identity`, `Record.Identity` and `List(identity)` are deleted, not\nextended: a field whose meaning depends on the caller cannot carry a scope.\n\n```go\ntype ScopeKind string\n\nconst (\n ScopeGlobal ScopeKind = \"global\" // shared across the application\n ScopeAgent ScopeKind = \"agent\" // private to one Agent\n ScopeUser ScopeKind = \"user\" // one user, across their Agents\n ScopeAgentUser ScopeKind = \"agent-user\" // one Agent's relationship with one user\n)\n\ntype Scope struct {\n Kind ScopeKind\n Agent AgentID // required for ScopeAgent, ScopeAgentUser\n User IdentityID // required for ScopeUser, ScopeAgentUser\n}\n\nfunc (s Scope) Validate() error // rejects a component present where it is not required\nfunc (s Scope) Key() string // canonical, collision-free storage key\n```\n\n`AgentID` and `IdentityID` are opaque. This package never resolves or\ncanonicalises them.\n\nA turn's resolved identity is one value:\n\n```go\ntype Subject struct {\n AgentID AgentID\n UserID IdentityID // \"\" when the channel carries no per-person identity\n}\n\nfunc (s Subject) Scopes() []Scope // readable, most specific first\nfunc (s Subject) WritableScopes() []Scope // never includes ScopeGlobal\n```\n\n**Access control is naming a scope, and nothing else.** The read path names\nexactly the scopes of the resolved `Subject`; the engine never unions beyond what\nit is handed and applies no policy of its own. An engine that enforced policy\nwould need to know about channels, sessions and bindings, and every backend would\nreimplement it. \"Agent-wide is private to its owning Agent by default\"\n(`agent-system.md`) falls out mechanically, because `SLine truncated
},
{
"url": "/dev/prds/messaging-service-boundary/",
"title": "Messaging Service boundary and transport design",
"section": "PRDs",
"body": "# Messaging Service boundary and transport design\n\n**Status:** Approved\n**Revision:** 1 \n**Date:** 2026-09-19 \n**Beads issue:** `archie-core-8cda.6.1` \n**Parent:** [`service-decomposition.md`](/dev/prds/service-decomposition/) \n**Prerequisites:** Gateway contract extraction (Phase 1), State Store extraction (Phase 2), UI extraction (Phase 3)\n\nThis 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.\n\n## Decision\n\nThe 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`.\n\nIt is a peer service to the UI Service and the daemon:\n\n- It serves external chat participants across configured communication platforms.\n- It consumes Gateway's `messaging.ChatContract` exclusively for chat turn execution, streaming, session queries, cancellation, persona selection, and task control actions.\n- 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.\n\n## Boundary and Ownership\n\n| Concern | Messaging Service owns | Messaging Service consumes | Messaging Service must not own or link |\n| ---------------------- | ------------------------------------------------------------------------------- | ------------------------------------------------------------------ | ------------------------------------------------------------------ |\n| **Channel transports** | Telegram bot long-polling, Email IMAP/SMTP loops, Inbound Webhook HTTP listener | Gateway `ChatContract` | Direct LLM providers, model runtimes, tokenizer libraries |\n| **Turn dispatch** | Inbound message packaging, typing indicators, live streaming updates | `ChatContract.Route`, `ChatContract.Stream` | `gateway.Router`, `runtime.Runtime`, agent prompt builders |\n| **Sessions \u0026 History** | Platform-to-session key mapping, conversation thread ID translation | `ChatContract.GetSession`, `RecentMessages`, `RecentTurns` | store implementations, `SessionStore` database handles |\n| **Control \u0026 Actions** | Platform command parsing (`/status`, `/tasks`, `/cancel`, `/stop`, `/persona`) | `ChatContract.Snapshot`, `ApplyTaskAction`, `Cancel`, `SetPersona` | `daemon.Daemon`, workflow execution engine, worktree operations |\n| **Task Approvals** | Channel interactive keyboards, approval callbacks | `ChatContract.ApplyTaskAction` | Direct task status mutations, forge comment posters |\n| **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 |\n| **Readiness** | Messaging process liveness, channel connectivity, Gateway probe | Gateway `ChatContract.Snapshot` | Internal daemon subsystem probes |\n\n## Target Service Shape\n\n1. **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`.\n2. **Application composition**: `internal/app/archiemessaging/` wires:\n - Config loading scoped strictly to `[chat.*]` and `[services.gateway]`.\n - Secret resolution for channel credentials (e.g. Telegram bot token).\n - Gateway gRPC client (`internal/infrastructure/gatewayrpc.Client`).\n - Channel lifecycle managers (`internal/channels/status`).\n - Channel instances (`internal/channels/telegram`, `email`, `webhook`).\n3. **Turn and Stream Execution**:\n - Channels adapt inbound platform messages to `messaging.Inbound`.\n - Streaming channels (Telegram) consume `ChatContract.Stream(ctx, inbound)` which returns `\u003c-chan messaging.ChatEvent`, mapping `started`, `delta`, `tool`, `media`, `done`, and `error` events directly to live message frames.\n - Non-streaming channels (email, synchronous webhooks) consume `ChatContract.Route(ctx, inbound)`.\n\n## Load-Bearing Channel Invariants\n\nThe Messaging Service preserves existing invariants defined in `AGENTS.md` and channel documentation:\n\n1. **Telegram long-polliLine truncated
},
{
"url": "/dev/prds/module-position/",
"title": "Module position -- design",
"section": "PRDs",
"body": "# Module position -- design\n\n**Status:** Draft\n**Date:** 2026-09-03\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n\n## Problem\n\n`eda-playbook-engine.md` names four logic positions a playbook action can\ntarget: Workflow, Module, Channel, Forge. Workflow (`t2db.9`/`.10`/`.11`)\nand the standalone lint tool (`t2db.12`) are shipped. Module -- the\nposition that makes an action \"not restricted to code-generation\" -- has\nnot started, because it needs a schema-generation mechanism the parent\ndoc deliberately deferred: \"This document does not attempt to design the\nfull generator.\" This is that design.\n\n## Do not invent a new mechanism -- generalise the one used three times\n\nYaegi-interpreted extension code with a fixed, resolved-by-name exported\nfunction already exists in this codebase for three surfaces, and all three\nfollow the identical shape:\n\n| Surface | Fixed signature | Export path | Symbol table |\n| ----------------------------------------- | --------------------------------------- | -------------- | --------------------- |\n| Custom gate (`internal/gate/gateeval`) | `func(gate.GateContext) []gate.Finding` | `\"gate.Check\"` | `gateextract.Symbols` |\n| Workflow stage plugin (`skillbuild`) | stage-specific | skill-declared | `wfextract.Symbols` |\n| Skill plugin (`internal/skill/plugin.go`) | `func(string) string` | `\"main.Run\"` | none (stdlib only) |\n\nEach is: read a `.go` file -\u003e `yaegiutil.New` with that surface's symbol\ntable -\u003e `yaegiutil.Resolve[T](i, src, exportPath)` -\u003e call the resolved\nfunction wrapped in `yaegiutil.Safe` for panic recovery. **Module is a\nfourth instance of this same shape**, parameterised by action kind instead\nof hardcoded to one fixed signature. No new interpreter construction, no\nnew panic-recovery mechanism, no new symbol-table generation tool --\n`go generate ... yaegi extract` is already how `wfextract`/`gateextract`\nare produced that way (see their `//go:generate` directives), and Module\nschema generation reuses that exact command.\n\n## No generic `Module` interface -- one typed contract per action kind\n\nThe plugin engine rule's invariant 1 requires \"real capability-specific\noperations,\" and invariant 5 forbids adding capability methods to a\ngeneric interface. A single `Module` interface with `Run(args any) (any,\nerror)` would be exactly the untyped hook the rule (and\n`event-sources-and-reactions.md`'s rejection of a generic `Source`\ninterface) exists to prevent -- restating the mistake the whole EDA\ndocument was written to move away from (`wfextract`'s hardcoded\n`reflect.ValueOf(workflow.Implement)` table is what a closed, un-typed-per-\ncase system already looks like in this repo).\n\nInstead, **each action kind is its own tiny package with its own\ngenerated contract**, exactly like `gate.GateContext`/`gate.Finding` are\none hand-written Go file that `gateextract` turns into a Yaegi symbol\ntable:\n\n```go\n// internal/domain/eda/module/notify/types.go (hand-written, the schema source)\npackage notify\n\n// SchemaVersion is independent of a playbook's own workflow_version, per\n// eda-playbook-engine.md's schema-versioning point.\nconst SchemaVersion = 1\n\ntype Args struct {\n Channel string\n Message string\n}\n\ntype Result struct {\n Delivered bool\n}\n\n//go:generate go run github.com/traefik/yaegi/cmd/yaegi extract -name notifyextract github.com/samcharles93/archie-core/internal/domain/eda/module/notify\n```\n\nA Yaegi module implementing this kind exports a fixed function name\nagainst these generated types, resolved the same way `gate.Check` is:\n\n```go\n// operator's notify.go, interpreted at load\npackage notify\n\nfunc Run(a notify.Args) notify.Result { ... }\n```\n\n`internal/domain/eda/module/notify` is the schema; `notifyextract.Symbols`\nis its generated Yaegi bridge; the operator's file is the implementation.\nThis is the same three-way split `internal/gate` / `gateextract` /\n`.archie/gate.go` already has.\n\n## The registry: `ModuleRegistry`, keyed by kind, not a service locator\n\nPer invariant 2 (owning family manager) and invariant 4 (narrow host\naccess): a `ModuleRegistry` in `internal/domain/eda/module` maps a kind\nname (`\"notify\"`, `\"image-gen\"`) to a resolved, type-erased invoker --\nthe same `map[string]reflect.Value`-shaped erasure `wfextract.Symbols`\nalready uses to bridge Yaegi and Go, not a new pattern and not exposed as\nthe plugin's contract with the daemon (the plugin still writes and is\nchecked against a fully typed `func(Args) Result`; the registry's\ninternal storage is the only place erasure appears, exactly as it already\ndoes inside `wfextract`).\n\n```go\ntype ModuleRegistry struct {\n // kind -\u003e (validate args against generated schema, invoke, marshal result)\n}\n\nfunc (r *MoLine truncated
},
{
"url": "/dev/prds/multi-action-playbooks/",
"title": "Multi-action playbooks and typed action results",
"section": "PRDs",
"body": "# Multi-action playbooks and typed action results\n\n**Status:** Approved\n**Date:** 2026-09-22\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-nx30` (unblocks `archie-core-t2db.27` and `archie-core-t2db.31`)\n\n## Why this exists\n\n`eda-playbook-engine.md`'s hard boundary rejects any playbook that is not\nexactly one `workflow` action, so the parent document's data-flow, Module and\nChannel/Forge decisions have no loadable shape to attach to. The boundary's own\nstated condition is now met: both execution-time gaps are resolved\n(`eda-playbook-engine.md`, \"Execution-time gaps\"; the `playbook_dispatches`\nledger). This document designs the relaxation.\n\n## A playbook is one of two shapes\n\n- A **workflow playbook** is exactly one `workflow` action. Unchanged: it names\n a workflow definition and is routed by the daemon's definition pin.\n- An **action playbook** is one or more `module` actions in order. Each action\n has an optional `id`, a `kind` naming a registered Module kind, `args`, and an\n optional `when`.\n\nOne playbook does not mix the two shapes.\n\n```yaml\ntrigger: { kind: bug }\nactions:\n - id: build\n position: module\n kind: log\n args: { message: '\"build started\"' }\n - id: done\n position: module\n kind: log\n args: { message: '\"done: \" + string(actions.build.result.written)' }\n when: actions.build.result.written == true\n```\n\nThe first Module kind is the side-effect-free `log` kind\n(`module-position.md`, \"Recommended first slice\"). A Module kind with an\nexternal side effect, and the Channel and Forge positions, are out of scope.\n\n## A result type is the kind's generated Result struct\n\nEach Module kind owns a hand-written `Args` and `Result` struct\n(`internal/domain/eda/module/log` is the worked example); `ModuleRegistry.Invoke`\nreturns the result as a flat `map[string]any`. `ModuleRegistry.DecodeResult`\n(`internal/domain/eda/module`) is the single site that converts that map into\nthe kind's `Result` struct before a later expression reads it, so the value the\nchecker validates and the value the run reads have one definition.\n\n`actions.\u003cid\u003e` is typed by the kind of the action that declares `\u003cid\u003e`:\n`{ result: \u003cKindResult\u003e }`. `event` stays `dyn` (J4,\n`playbook-expression-syntax.md`).\n\n## Reject-at-load, preserved\n\nRelaxing the boundary must not make a bad reference resolvable. The load fails,\nnaming the playbook and the offending action, for:\n\n- an `id` missing where a later action references it, duplicated, or outside\n its shape's grammar: a workflow action id keeps the shared\n stable-identifier grammar (J1, already enforced), while a module action id\n must be a lowercase CEL field name writable as `actions.\u003cid\u003e` (so a CEL\n keyword such as `in`, `true`, `false`, or `null` is rejected at load);\n- an `actions.\u003cid\u003e` read of an id no earlier action declares;\n- an `actions` read that is not statically resolvable to an id (any map index,\n literal or dynamic, `in`, a comprehension): the typed `actions` root is an\n object type, so only field selection `actions.\u003cid\u003e` resolves and the\n `actions[\"id\"]` spelling is not accepted;\n- a `result` field the referenced kind's `Result` does not define;\n- a reference to an earlier action that produces no result;\n- an unknown `position`, an unknown `kind`, or a `module` action with no `kind`;\n- a field belonging to the other shape (`kind` on a `workflow` action, or\n `workflow` on a `module` action);\n- an arg KEY the kind's `Args` schema does not define;\n- an arg value whose checked CEL type cannot fill its `Args` field (`'123'`\n for a string field). A `dyn` value, such as an `event` read, passes: its\n type is known only per event, and the module decode refuses a bad one at\n run.\n\nDeclaring the kind's `Result` schema to CEL at load makes a result-field typo a\nload failure rather than a dispatch failure. Matching arg keys against the\nkind's `Args` schema makes an arg-key typo or a wrongly typed value a load\nfailure.\n\n## The environment is per playbook\n\nResult typing depends on the ids a playbook declares and the kind each id runs,\nso the CEL environment is built from one playbook's action list rather than once\nper `Store`, and `expr.NewEnv` takes that list: each declared id becomes a field\nof the `actions` object typed by its kind's `Result`.\n\n## Running an action playbook is out of scope\n\nThis document makes an action playbook load and its references type-check.\nRunning one is designed in `docs/prds/action-playbook-run.md`.\n\n## Decisions\n\n**D1 — dispatch before `t2db.31`.** Superseded by\n`docs/prds/action-playbook-run.md`. Was: an action playbook loads and\nvalidates but is not routed; the definition-pin dispatch reports no match for it,\nand the daemon logs a visible warning naming it.\n\n**D2 — mixing positions.*Line truncated
},
{
"url": "/dev/prds/news-and-releases/",
"title": "Public news and per-version release notes",
"section": "PRDs",
"body": "# Public news and per-version release notes\n\n**Status:** Approved\n**Date:** 2026-09-21\n**Beads issue:** `archie-core-2ncm.2`\n**Superseded in part:** `docs/prds/release-stream-and-commit-rules.md` defines the\nsingle release stream. `CHANGELOG.md` carries every release and one `vX.Y.Z` tag\nnames each release.\n\nThe Astro website renders public news and per-version release notes from the\nartifacts generated here. Both derive from `CHANGELOG.md`, so publishing a\nrelease adds no writing.\n\n## Source of truth\n\nRelease notes come from the frozen sections in `CHANGELOG.md`:\n`tools/release.sh --prepare` writes a section, and `--tag` refuses to tag a\nversion without it. The generated artifact has one entry per release version.\n\nTags and raw commits are not the source. The changelog is the edited release\nrecord, and its `## [\u003cversion\u003e] - \u003cdate\u003e` headings provide the version and date.\n\n## Release data\n\nThe generator skips `## [Unreleased]`. Any other `## [` heading that is not\n`[version] - date` stops generation. A relative Markdown link in a changelog\nbody also stops generation because the Astro site must be able to render the\ncontent without depending on repository-relative paths.\n\n`archied` and `archie-agent` version independently. Each\n`docs/news/releases.json` entry carries the tag prefix (`archied`, `archie`),\nproduct name (`archied`, `archie-agent`), version, date, and changelog body.\n`docs/news/redirects.json` maps retired per-component news URLs to each unified\nrelease route. The Astro site must apply this table so previously published\nrelease URLs continue to resolve.\n\nBoth JSON files are committed generated artifacts. `task news` regenerates\nthem, `task news:check` detects drift, and `tools/release.sh --tag` regenerates\nand stages them with the release commit. The Astro site renders from these\nartifacts rather than re-parsing `CHANGELOG.md`.\n\n## Site ownership\n\nThe Astro website is maintained outside this repository and serves the\ndocumentation at `offloaded.dev/docs/`. This repository generates and validates\nthe news and documentation data artifacts; it does not build, preview, or\ndeploy the Astro site.\n\n## Not in scope\n\n- Generated summaries, categories, or section headings; the changelog has no\n structured summary field to derive one from.\n- Per-release download or install links; where to get the artifacts is\n documented once, not restated for every release.\n- Hand-written news items.\n- Changes to `infra/ansible` or to the external Astro website repository.\n\n## Verification\n\n- `go test ./tools/newsgen/...` covers parsing, ordering, artifact generation,\n heading and link refusals, and check-mode drift.\n- `task news:check` passes inside `task check`.\n- `task docs:artifact:check` verifies the generated documentation data against\n its Markdown sources.\n"
},
{
"url": "/dev/prds/orgs-and-access/",
"title": "Orgs, workspaces and access control",
"section": "PRDs",
"body": "# Orgs, workspaces and access control\n\n**Status:** Approved\n**Date:** 2026-09-24\n**Parent:** `docs/prds/event-automation.md`, epic `archie-core-t2db`\n\n## Why this exists\n\nArchie has no tenant boundary and no access control: one operator, one shared\ntoken, and no org on any record. The event automation design needs orgs to own\nsources, bindings, workflows and agents, and an agent's reach must be decided\nby the policies over it, never by the event that started it.\n\n## Concepts\n\n- **Org.** The tenant boundary. An instance admin creates an org and adds its\n first owner. An owner or admin adds further members by the sign-in\n provider's subject or email.\n- **Workspace.** A division of an org, named freely (`networking-prd`,\n `service-desk-dev`), with an optional `environment` attribute (any string)\n that policies can test. Sources, event types, mappings, bindings and runs\n belong to a workspace.\n- **Identity.** Every principal is an identity (`internal/domain/identity`):\n - a person is an identity of kind `user`, bound to the sign-in provider\n through the existing subject binding;\n - an agent is an identity of kind `bot` or `service_account`, assigned to\n one org and granted access, secrets and permissions the way a user is.\n\n Signing in and verifying credentials stay separate from identity; identity\n is who acts. Memberships, roles, grants and audit records all reference the\n identity ID.\n\n- **Instance admin.** Operates the installation: orgs, the sign-in provider,\n instance policies. Instance admins see an org's resources only as members\n of it.\n\n## What belongs where\n\n| Level | Owns |\n| --------- | ---------------------------------------------------------------------------------------------------------------- |\n| Instance | the shipped workflow catalogue, instance policies |\n| Org | members, identities and their grants, secrets, agent profiles, workspaces, org workflows and their enabled state |\n| Workspace | sources, event types, mappings, bindings, runs, captures, run events and logs, chat sessions, memory |\n\nEvery owned record carries its `org_id`, and workspace records also carry their\n`workspace_id`. An identity, secret or profile is used in a workspace only\nafter the org grants it to that workspace.\n\nA secret is granted to an identity. An agent profile holds the container\nimage, tools and network access, and no secrets; this supersedes the secret\nreferences in `event-automation.md`'s agent profiles.\n\nA workflow names the identity it runs as. A workflow called by another runs\nas its own identity, and the caller's identity must be permitted `run` on it.\n\n## Access decisions\n\n### Where it lives\n\n- `internal/domain/access` owns the policy schema, the action list, how\n principals and resources are turned into policy entities, and the\n `Authorizer` contract.\n- The Cedar implementation, using `github.com/cedar-policy/cedar-go`, lives in\n `internal/infrastructure/access`; `internal/app` wires it.\n- Exactly two places call the `Authorizer`: the dashboard and API request\n path, and dispatch. Every other service verifies a credential and never\n evaluates policy.\n\n### The model\n\n- **Principal:** an identity, with its memberships, roles and grants.\n- **Resource:** the record acted on, with its workspace and org as parents,\n its type, owner and state.\n- **Action:** one of `read`, `create`, `update`, `delete`, `approve`, `run`,\n `read_logs`, `read_secret`, `manage_members`, `manage_identities`,\n `manage_policies`.\n- **Context:** the event's signature result, the address it came from, the\n time, and the run and step when the principal is an agent.\n\n### The policy chain\n\n```\ninstance (+ network rules) ─▶ org ─▶ workspace ─▶ identity + workflow ─▶ object\n```\n\n- **Instance** policies hold across every org. They include network rules:\n which addresses may deliver events to any source on the instance.\n- **Object** policies attach to one object (an event source, a secret, an\n identity, a binding, a workflow): \"only `soc-responder` may read this\n secret\", \"this source accepts events only from 10.20.0.0/16\".\n- A request is allowed only if every level with policies for it permits it. A\n lower level narrows and never widens; a forbid at any level wins; with no\n permit the request is denied.\n- The shipped role policies mean the org level always has policies, so an\n object or workspace policy alone can never grant access.\n- Archie ships an instance policy, which no org can remove, forbidding any\n principal to act on a resource outside the orgs it belongs to.\n\n### Storing and changing policies\n\n- Policies are stored in the State Store per level, versioned, and every\n changeLine truncated
},
{
"url": "/dev/prds/payload-field-mapping/",
"title": "Payload field mapping -- decision",
"section": "PRDs",
"body": "# Payload field mapping -- decision\n\n**Status:** Approved\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-t2db.3`, depends on `t2db.1`, blocks `t2db.4`\n\nAnswers what a \"mapping\" is, where it lives, and what \"resolve against a\nreal event\" means precisely enough to implement. `t2db.4` (binding: matcher\n\n- mapping + workflow) is out of scope -- this bead ships the mapping\n concept and its preview only, as a standalone entity `t2db.4` will later\n reference by ID.\n\n## Decision: a new `internal/domain/mapping` package, SQLite storage\n\n\u003e Storage superseded: every store now lives in PostgreSQL behind\n\u003e `internal/domain/storecontract`, implemented in `internal/infrastructure/postgres`\n\u003e (`docs/prds/state-store-contract.md`). SQLite names below describe the\n\u003e original design.\n\n`internal/domain/mapping` owns the mapping vocabulary and the pure\nresolve/preview rule; `internal/store` persists it (mirrors\n`captures.go`'s shape exactly -- inline schema const, narrow store\ninterface, `*store.Store` implementation); `internal/webui/api_mapping.go`\nis the transport. This follows `docs/prds/event-capture-storage.md`'s own\nplacement precedent: `internal/store` is where this daemon's persistence\nalready lives, not `internal/infrastructure` (that layer holds\ncross-domain services -- config, eventbus, modelcatalog -- not this\ndaemon's primary store).\n\n### Why a domain package and not just a store table\n\nResolving a path against a payload and deciding \"missing vs null vs\ntype-changed\" is a rule, not a query -- CLAUDE.md's domain layer owns\n\"language, state, rules, operations\" precisely so this logic is testable\nwithout a database and reusable by `t2db.4`'s runtime trigger path without\neither package importing the other's transport concerns.\n\n## Mapping shape\n\n```go\ntype Mapping struct {\n\tID int64\n\tName string\n\tSourceHint string // free-text label (e.g. \"sentry\"), organisational only -- not enforced against Capture.Source\n\tFields []Field\n\tCreatedAt time.Time\n\tUpdatedAt time.Time\n}\n\ntype Field struct {\n\tName string // the name the workflow receives\n\tPath string // dot/bracket path into the payload, see below\n\tType FieldType // expected type, checked at resolve time\n\tRequired bool // Required=false + missing is not a failure; Required=false + wrong type still is\n}\n\ntype FieldType string // \"string\" | \"number\" | \"bool\" | \"object\" | \"array\" | \"any\"\n```\n\n`SourceHint` is advisory only: an operator authors a mapping by clicking\nthrough one example capture, but the mapping is not pinned to that\ncapture's exact source string, because `t2db.4`'s matcher (not this bead)\ndecides which events a binding applies to. Pinning here would duplicate\nthat decision in the wrong layer.\n\n## Path syntax\n\nDot-separated keys with `[N]` for array indices: `data.items[0].id`. No\nwildcards, no filters, no external library -- the grammar is exactly what a\nclick-through UI needs to express (this key, then this key, then this\nindex), and every path in a mapping was generated by clicking a value in a\nreal payload, never hand-written against a spec. A hand-rolled parser\n(~30 lines: split on `.`, strip `[N]` suffixes) is less risk than a new\ndependency for a grammar this small.\n\n## Resolve semantics (the preview AND the future runtime path)\n\n```go\nfunc Resolve(fields []Field, payload []byte) (values map[string]any, failures []Failure)\n\ntype Failure struct {\n\tFieldName string\n\tPath string\n\tReason string // \"missing\" | \"null\" | \"type_mismatch\"\n}\n```\n\nDecode with `json.Decoder.UseNumber()` (matches `webhookguard.RedactPayload`'s\nexisting convention) so int/float distinction survives for type checking.\nWalk each field's path independently -- one field's failure does not stop\nresolution of the others, because the whole point of preview is showing\nthe operator every problem at once, not the first one.\n\n- Path segment doesn't exist, or indexes past an array's length -\u003e `missing`\n- Path resolves to JSON `null` -\u003e `null`\n- Path resolves to a value whose JSON type doesn't match `Field.Type`\n (`\"any\"` always matches) -\u003e `type_mismatch`\n- `Required: false` suppresses `missing` only, never `null` or\n `type_mismatch` -- a field that's present but the wrong shape is always\n worth surfacing, since silently coercing it is exactly the \"agent\n confabulates around a blank field\" failure this bead exists to prevent.\n\n**This is the same function both consumers use.** `t2db.3`'s preview calls\nit against an operator-picked capture and renders every result, pass or\nfail, in the UI -- that satisfies this bead's \"fail loudly\" acceptance\ncriterion, because at this stage the only runtime consumer of a mapping\n_is_ the human previewing it. `t2db.4` will call the identical function\nwhen a live event triggers a binding and turn any nonLine truncated
},
{
"url": "/dev/prds/playbook-expression-syntax/",
"title": "Playbook data-flow and condition syntax",
"section": "PRDs",
"body": "# Playbook data-flow and condition syntax\n\n**Status:** Approved\n**Date:** 2026-09-03\n**Parent:** `docs/prds/eda-playbook-engine.md`, epic `archie-core-t2db`\n**Beads issue:** `archie-core-t2db.14` (expression environment).\n\n**Decision:** CEL via `cel.dev/cel-go` (v0.32.0), pinned. One expression\nmechanism covers both an action's `when` condition and its `args` values.\n\n## The requirement, stated directly\n\nA playbook action is gated and parametrised by runtime data: (a) a condition\ndeciding whether the action runs; (b) a later action's `args` values referencing\nan earlier action's `Result` and the triggering event's fields. Both are **CEL\nexpressions**, evaluated against one evaluation context. There is no separate\ninterpolation syntax: CEL reads nested maps and fields natively, so `args`\nvalues that need data are written as CEL, and only plain literal args remain\nplain YAML scalars.\n\nBoth halves are read-only: expressions may read context values and compute a\nresult from them, never mutate, never call host functions, never perform I/O.\nCEL enforces this structurally (no side effects, linear evaluation when macros\nare bounded, cost-limited).\n\n```yaml\nactions:\n - id: build\n position: module\n kind: log\n args:\n message: '\"build finished\"' # literal\n when: 'event.label == \"bugfix\"' # gate on event field\n - position: module\n kind: log\n args:\n message: '\"done: \" + string(actions.build.result.written)'\n when: \"actions.build.result.written == true\"\n```\n\n## Trust boundary of the expression\n\nA playbook YAML is **operator-installed, in-process, daemon-privileged** -- the\nsame tier as `ModuleDir`/`PluginDir`/`SecretEngineDir` (module-position.md's\ntrust-boundary section): loaded from a configured directory at startup, never\nfrom a webhook body or task worktree. The schema-by-example flow uses live\nevents to _design against_; the saved playbook is operator-authored file content\nin an operator-configured location.\n\nTwo consequences:\n\n1. The expression string is **trusted**. Operator-authored config, not attacker\n input; no sandboxing against a hostile expression string is required. If a\n future playbook source is less trusted (auto-generated bindings from\n unauthenticated captures), that is the playbook-file trust tier moving -- the\n loader's acceptance check is the right place, not the evaluator.\n2. The **data the expression reads is NOT trusted** (decoded webhook body, prior\n results through the same pipeline). Robustness against hostile data is\n required: no panic on wrong-typed/missing fields, no unbounded cost on\n deep/cyclic maps, bounded evaluation time. CEL provides this structurally\n (cost limits, linear non-Turing-complete evaluation, error values instead of\n panics -- verified in the vetting record below).\n\n## The gate precedent is deliberately NOT copied\n\n`internal/gate/gateeval` evaluates arbitrary interpreted Go (`.archie/gate.go`)\nas the repo's conditional-logic precedent. That is the wrong precedent for\nplaybook conditions because this document's premise is: **YAML is pure\norchestration data; Yaegi is where imperative logic lives** (Problem section;\nmodule-position.md's \"no generic hook\" section). Yaegi snippets in YAML would\nmove imperative logic into the data layer -- the inversion this design exists to\nprevent -- and make playbooks un-lintable.\n\nThe line: conditions are **declarative predicates over runtime data, not\nprograms**. CEL is non-Turing-complete and side-effect-free, so it cannot become\na program; a condition that needs real logic gets a Module kind (Yaegi),\nreferenced by the action, not a stronger expression body.\n\n## Plugin-engine-rule interaction\n\nThe plugin engine rule forbids a generic `Module` interface with an `any`\npayload; it exists to keep static implementation contracts typed. Evaluating CEL\nagainst runtime `map[string]any` is **not the same problem**: the rule concerns\n_implementation contracts_ (static operations a capability family exposes), not\n_runtime data values_ (legitimately dynamic -- an event payload's shape is\nunknown until it arrives). The Module contract stays fully typed (generated\n`Args`/`Result` schemas); CEL is a read-only data reader under the playbook\nengine family, not a new capability contract. Stated once.\n\n## Minimum viable evaluation context (what expressions see)\n\nOne flat context, namespaced from the playbook run, built at dispatch time:\n\n| Name | Type | Source |\n| --------- | ------------------------ | ---------------------------------------------------------------------------------Line truncated
},
{
"url": "/dev/prds/plugin-settings-live/",
"title": "Plugin settings reconcile live",
"section": "PRDs",
"body": "# Plugin settings reconcile live\n\n**Status:** Draft\n**Revision:** 2\n**Tracking:** GitHub [#1154](https://github.com/samcharles93/archie-core/issues/1154), epic [#998](https://github.com/samcharles93/archie-core/issues/998)\n**Authority:** `docs/prds/runtime-control-plane.md` decides each feature owns how\nits changes take effect; `docs/architecture/plugins-and-extensions.md` owns the\nplugin engine rule; `docs/prds/control-plane-apply-status.md` owns where apply\nreports go.\n\n## Outcome\n\nAn operator drops a plugin, module or secret-engine file into a configured\ndirectory while archied runs, and the daemon loads it without a restart. An\nedit to an installed file replaces what is running. A delete never stops running\ncode; apply status says so. A stored `plugin-settings` change applies live for\n`plugin_dir`, `module_dir` and `secret_engine_dir`; a change to `skills_dir` is\nrefused.\n\n## Triggers\n\n`PluginSettingsKind` joins `runtimeResourceKinds` in\n`internal/app/archied/control_plane.go`, and its descriptor `ApplyMode` becomes\n`live` in `internal/app/controlplane/operational_settings.go`.\n\nA poller reconciles on the apply-status restamp interval, so a dropped file\nloads without a filesystem watch. Each tick re-runs both halves the boot path\nruns, against the directories in the running config: the directory loads\n(`secret.Registry.LoadDir`, `ModuleRegistry.Register`, `plugin.LoadDir`) and the\nlayering (`boot.runtimeConfig`), which re-resolves provider credentials. A\nprovider disabled at boot for an unresolvable engine is re-resolved on the first\ntick that finds it; a changed directory retargets the next tick without a\nrestart.\n\n## Rules\n\n- Adding and changing load; removing never unloads. Yaegi interpreters are not\n reclaimed while a caller still exists and there is no unload path; the running\n set can only grow. A removal stays outstanding in the apply-status error until\n the process restarts.\n- Each file is loaded through a fresh interpreter (the boot pattern) and\n content-hashed, so only new and changed files load.\n- A file that fails to load is skipped and reported; already-running code keeps\n running, the degrade-and-skip convention `plugin.LoadDir` and\n `Registry.LoadDir` already apply at boot. Boot keeps its reject-at-load rule\n for the module directory; a broken file at runtime skips without aborting.\n- A directory that does not exist reconciles to an empty set.\n\n## The three registries\n\n- **Secret engines** (`internal/secret`). Reconciliation re-runs\n `Registry.LoadDir` against the live directory. `Register` replaces by name, so\n an edited engine takes effect for the next resolution and a dropped engine\n resolves on the next tick. A deleted engine stays registered: existing\n references keep resolving through it until restart. Engines are stateless\n resolvers, so a swap needs no lifecycle step.\n- **Modules** (`internal/domain/eda/module`). Reconciliation re-runs\n `ModuleRegistry.Register` for the kind's file. Playbook dispatch resolves\n through the registry at invoke time, so the swap reaches a running playbook\n store unchanged; a deleted file leaves the old invoker in place, running.\n- **Plugins** (`internal/plugin`). `Host` grows running-state operations beside\n `Register`, `Start` and `Stop`, and `Register` keeps its rule that\n registration is allowed only before the first `Start`, so these are new host\n methods rather than a relaxed `Register`. One adds a single module while the\n host is running: inserted in dependency order, started alone, and rolled back\n alone on failure, leaving every previously started module running. The other\n replaces a module whose manifest id matches: stop it, start the new one, and\n restart the old one when the new start fails; replacing a module another\n running module depends on is refused. A module's `Start` is its only check\n (`plugin.Module` has no probe, and one manifest id cannot be registered\n twice), so a replacement checks by starting and keeps a rollback rather than\n switching first. These operations obey the plugin engine rule: the host\n invokes start and stop itself and isolates the failure to one module. A\n deleted file makes no host call: the module runs on.\n\n## `skills_dir`\n\n`skills_dir` is not part of this change. The daemon refuses a `plugin-settings`\ndocument whose `skills_dir` differs from the value in force. The check is a\npre-layer comparison on the live path (`boot.applyRuntimeResourceUpdate` in\n`internal/app/archied/control_plane.go`), not an addition to\n`validatePluginSettings` in `internal/app/controlplane/operational_settings.go`,\nwhich stays value-agnostic per the #1143 decision recorded there: a\nchange-immutability rule needs the running config, and #1143's validates-nothing\nstill holds for values. The write lands, the store keeps the version, the daemon\npublishes nothing, the refusal is reported against that stored versLine truncated
},
{
"url": "/dev/prds/pr-review-agent/",
"title": "PR review agent",
"section": "PRDs",
"body": "# PR review agent\n\n**Status:** Approved\n**Authority:** `docs/architecture/agent-system.md`; supersedes the earlier\nreviewer executor and blocking rule.\n**Compounds with:** `docs/prds/execution-tree-state-machine.md` (every agent\ncall is a StepExecution), `docs/prds/external-agent-harness.md` (any agent\nstep may run on a harness), `docs/prds/inline-review.md` (posting),\n`docs/prds/pr-review-remediation.md` (consumes the findings).\n\n## Decision\n\nArchie ships a pull request reviewer as its first end-to-end product. It\nreviews any pull request on a watched repository, a PR an operator names, and\narchie's own PRs before they open.\n\nThe reviewer is a fixed pipeline, not a single agent. The review strategy is\ngenerated per PR: three lens agents propose review dimensions from the PR's\ncontent, one reviewer definition runs once per dimension, and later agents\nverify, challenge and combine the findings. Everything that can be computed\nis code: diff parsing, clustering, blast radius, evidence extraction,\nscoring, deduplication, line mapping and the review event.\n\nThe pipeline is **recall-first**. It posts every evidenced finding above the\nconfidence threshold, up to the comment cap. A precision gate exists as an\noperator dial and is off by default.\n\nAcceptance is measured, not asserted: see Verification.\n\n## Pipeline\n\nEach numbered phase is a stage of the `pr-review` workflow. Each agent call is\nan `agent` StepExecution; fan-out phases record one child per call.\n\n1. **Intake.** Code reads the PR metadata and diff statistics: type,\n complexity, languages, areas touched, risk signals. Depth comes from lines\n changed: under 100 is `quick` (at most 3 dimensions), under 500 is\n `standard` (6), otherwise `deep` (12). An operator may set depth\n explicitly.\n2. **Anatomy.** Code parses the diff into files and hunks, clusters related\n files, and computes the blast radius: unchanged files that import or are\n imported by changed files. One agent writes the PR narrative, risk\n surfaces, changes that do not fit the narrative, and gaps between the\n description and the diff.\n3. **Dimension selection.** Three lens agents run in parallel over the intake\n (including its machine-written score), anatomy and diff, each able to read\n the repository. A PR that intake scores as likely machine-written adds a\n hallucination-check dimension: claims, citations and behaviour the diff\n does not actually implement.\n - **behaviour:** where the old and new code diverge for any input; API\n contracts, concurrency and state, security, error handling, data flow;\n - **mechanics:** whether the code runs at the language and framework\n level; types, signatures and every caller, decorators and middleware,\n framework contracts, imports;\n - **fit:** patterns, complexity, abstraction, test adequacy, documentation\n that no longer matches, dependencies, migration completeness.\n\n Each lens returns review dimensions: a name, a reviewer prompt written for\n this PR, target files, context files and a priority. Code merges them,\n drops duplicates and keeps the highest-priority dimensions up to the\n depth's cap.\n4. **Review.** One reviewer definition runs once per dimension, in parallel,\n at most 8 at a time. Each reads its target and context files and may\n follow references. Each finding carries file, line range, severity\n (`critical`, `important`, `suggestion`, `nitpick`), title, body, an\n optional suggested fix, quoted evidence, confidence and tags. A reviewer\n that exhausts its turn cap or deadline before its terminal tool call\n records a distinct StepExecution status from a reviewer that completed\n and found nothing; synthesis and the posted review treat the two\n differently (the former is unreviewed, the latter is reviewed-clean).\n5. **Verification layer**, over the review findings:\n - code extracts an evidence package per finding: the code at the cited\n lines and snippets from its callers;\n - an evidence verifier checks high-priority findings against their\n packages;\n - an adversary confirms or challenges each finding, looks for issues every\n reviewer missed, and is more sceptical when intake scores the PR as\n likely machine-written;\n - a compound agent looks, within each cluster of confirmed findings, for\n defects that only exist in combination.\n6. **Coverage and consistency**, in parallel:\n - a coverage gate checks every cluster and high-exposure blast-radius file\n was reviewed, and runs gap reviewers for what was not, at most 2 rounds;\n - consistency verification lists every cross-location obligation the\n changed code creates (what must be true elsewhere for this line to be\n correct), then verifies each by reading both ends. A broken obligation\n becomes a finding.\n7. **Synthesis**, code only:\n - score = severity weight (1.0, 0.7, 0.3, 0.1) ×Line truncated
},
{
"url": "/dev/prds/pr-review-operator-response/",
"title": "PR review: the operator's answer to the approval gate",
"section": "PRDs",
"body": "# PR review: the operator's answer to the approval gate\n\n**Status:** Draft\n**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.\n**Compounds with:** `docs/prds/execution-tree-state-machine.md` (a run cannot resume partway through its stage list).\n\n## Decision 1 — where the operator answers\n\nThe 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.\n\n`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.\n\nThe 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.\n\nA 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\".\n\n### The review the operator answers\n\nThe 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.\n\nThe 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.\n\nThis 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.\n\n## Decision 2 — the cap\n\nThe 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.\n\n`Task.Attempt` cannot carry the count, because it counts every requeue. The two alternatives are worse.\n\n- 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.\n- `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.\n\n`RemediationRounds` is the precedent: one writer, one reader, one meaning, kept separate from `RetryCount` so unrelated retries cannot draw a budget down.\n\nThe write crosses the State Store. A goose migration adds the column; `Line truncated
},
{
"url": "/dev/prds/pr-review-remediation/",
"title": "PR review comment remediation -- decision",
"section": "PRDs",
"body": "# PR review comment remediation -- decision\n\n**Status:** Approved\n**Date:** 2026-09-10, amended and ratified 2026-09-19\n**Beads issue:** (filed as `archie-core-…`, parent: `archie-core-7d5u` event sources and typed reactions)\n\nAnswers: how archie reacts to review comments on a PR it opened, from a human\nor from another review bot, and remediates them. Built on two settled decisions — the review pipeline's\nisolation contract (`docs/prds/pr-review-agent.md`, \"Isolation\") and the\nevent-sources decision (`docs/prds/event-sources-and-reactions.md`) — plus the\nwebhook intake security contract (`docs/prds/webhook-intake-security.md`).\nNothing here re-decides those; it names the one concrete reaction each one's\nmachinery was built to carry.\n\n## Problem\n\nArchie opens a PR (`pr_open`) and then never learns what a human said about\nit. `forge.Forge` has no method to list PR reviews or review comments; the\ndaemon poll loop finds only new issues; the forge webhook receiver\n(`internal/forge/webhook/receiver.go`) decodes only `issues` events and\nexplicitly ignores `pull_request` events. A \"requested changes\" review, or an\ninline comment on a line, is invisible work.\n\n## Decisions\n\n### 1. Read surface: a narrow `PullRequestReviewReader`, type-asserted\n\nA new forge interface, implemented by GitHub and Gitea, not folded into the\nfat `Forge` interface (the h019.8 `PullRequestReader` precedent — the noop\nforge cannot honestly provide it):\n\n```go\ntype ReviewComment struct { ID int64; Author, Body, Path string; Line int; InReplyTo int64; CreatedAt time.Time }\ntype Review struct { ID int64; Author, State string /* requested_changes | approved | commented | dismissed */; SubmittedAt time.Time }\n\ntype PullRequestReviewReader interface {\n ListReviews(ctx, owner, repo string, number, sinceID int64) ([]Review, error)\n ListReviewComments(ctx, owner, repo string, number, sinceID int64) ([]ReviewComment, error)\n // ReplyToReview posts a reply to a review or comment thread.\n ReplyToReview(ctx, owner, repo string, number, inReplyTo int64, body string) error\n}\n```\n\nGitHub: `pulls/{n}/reviews` + `pulls/{n}/comments`; reply via\n`pulls/{n}/comments/{id}/replies`. Gitea: `pulls/{n}/reviews` +\n`pulls/{n}/comments`; reply via `pulls/{n}/comments/{id}`. `sinceID` is the\ncursor for both poll and webhook dedup.\n\n### 2. Event source: webhook first, poll as the universal backstop\n\n- **Webhook (GitHub, low latency):** extend `receiver.go` to also decode\n `pull_request_review` and `pull_request_review_comment` events, behind the\n existing HMAC verification, producing the same reaction as the poller. The\n receiver stays a forge-intake surface — not the generic chat webhook, not a\n new generic receiver (7d5u decision 4).\n- **Poll (both forges, no webhook dependency):** a periodic scan of `pr_open`\n tasks calls `ListReviews`/`ListReviewComments` with a persisted `sinceID`\n cursor per task. This is the Gitea path and the deployment-without-webhook\n path; it must stay first-class, not a legacy fallback (the repo's own\n webhook-intake rule). It is **one shared scan over all `pr_open` tasks**,\n not a scan inside each identity's poll loop, and it calls the forge client\n the scanned task's own identity owns. This is `reconcilePRs`'s shape\n exactly (`internal/daemon/daemon.go`: `Store.OpenPRs` then `forgeFor(\u0026t)`).\n A per-identity scan would call one identity's forge client against another\n identity's PR.\n\nBoth paths emit the **same** typed reaction, so `PublishUnique` dedups them\nfor free — the `TaskEnvelope.IdempotencyKey` pattern (7d5u decision 4) applied\nto reviews.\n\n### 3. Reaction contract: producer-only, resolves to an existing task\n\nA new `workintake.ReviewCommentEnvelope{Owner, Repo, PRNumber, Kind, CommentID,\nReviewID, Author, State, Body, Path, Line}`. Idempotency key is\n`owner/repo/pr-number/kind/id` — source-independent, so a webhook delivery\nand a poll of the same comment collapse.\n\n`Kind` (`review` or `comment`) is part of the key because a review ID and a\nreview-comment ID come from independent forge sequences. Keying on the bare id\nlets a review and an inline comment on the same PR collide, silently dropping\none of the two. This is a producer-only reaction\n(7d5u decision 3): it never vetoes or mutates in-flight work; the target task\nis idle (`pr_open`).\n\nThe daemon resolves `PRNumber` → the task that owns it. An unmatched PR (not\nan archie task) is dropped with a counter — a public webhook must not be able\nto start an agent against an arbitrary repository. A PR whose task is merged,\nclosed or archived is dropped through the same counter: the reaction is only\never work against a PR archie itself opened _and still owns_.\n\nThat lookup does not exist. `pr_number` is written by\n`internal/infrastructure/postgres/store.go` and never read in a `WHERE` clause, so this needs a\n`TaskStore` method keyeLine truncated
},
{
"url": "/dev/prds/progressive-tool-disclosure/",
"title": "Progressive tool disclosure (bridge tools) — wiring",
"section": "PRDs",
"body": "# Progressive tool disclosure (bridge tools) — wiring\n\n**Status:** Finalised\n**Date:** 2026-08-15\n**Compound:** the \"keep the LLM tool schema small, give full access on demand\" work (issue #167)\n\n## Decision\n\nThe bridge-tool pattern is **implemented and tested** in\n`internal/tools/disclosure.go` (`tool_search`, `tool_describe`, `tool_call`\n\n- `ContextPressureGate` + `DisclosureMode`, section 17.14/17.15) — but it is\n **never wired into the daemon**. `BridgeTools` and `ContextPressureGate` are\n referenced only in `disclosure_test.go`. This task is therefore a **wiring**\n task, not a feature build.\n\nWire the existing bridge into the per-chat-turn toolset:\n\n1. **Compose a per-turn registry** seeded from the base registry plus the\n per-turn extra tools, register the bridge tools into it, and hand it to both\n the bridge handlers and the `ContextPressureGate`.\n2. **Run the gate in `chatGenerateOptions`** (`internal/app/archied/main.go`)\n so it decides full-vs-bridge disclosure per turn, and build the\n `core.ToolSet` from the gate's filtered output.\n3. **Thread the model's context window** into the preparation seam so the gate\n has a real `ContextWindowSize` (it disables itself at 0, falling back to\n full disclosure).\n\n## Why the naive \"register extras into the base registry\" is wrong\n\n`BuildToolSetFrom` (`internal/agentexec/toolset.go`) documents the invariant:\n\n\u003e the task tools carry the calling gateway's identity, so there is one set of\n\u003e them per gateway and they **cannot live in the process-wide registry**.\n\nThis is confirmed by wiring: gateways are per-channel\n(`telegram_setup.go` build a `TurnRunner` per channel), and the extra\ntools (`task_*`, `session_*`, `dashboard_*`) close over that channel's identity\nvia `TurnRunnerConfig` (`turn.go`). Registering them into `b.toolReg` would\nlet channel A's session/identity-bound tools be invoked by channel B — a real\ncross-channel privilege bug. The bridge handlers iterate `reg.All()`\n(`disclosure.go`), so the extras must be discoverable; the fix is a\n**per-turn composed registry**, not a mutation of the process-wide one.\n\n## Shape of the change\n\n### 1. Per-turn composed registry + gate inside `chatGenerateOptions`\n\nReplace the current base-set + extra-set merge (`main.go`) with a single\ncomposed-registry pass:\n\n```go\n// new helper, in internal/tools/disclosure.go or the archied wiring package\nfunc ComposeForTurn(reg *tools.Registry, extra []tools.ToolEntry) (*tools.Registry, error) {\n composed := tools.NewRegistry()\n for _, e := range reg.All() {\n if err := composed.Register(e); err != nil { return nil, err }\n }\n for _, e := range extra {\n if err := composed.Register(e); err != nil { return nil, err }\n }\n if _, err := composed.RegisterBatch(tools.BridgeTools(composed)); err != nil {\n return nil, err\n }\n return composed, nil\n}\n```\n\n`chatGenerateOptions` then:\n\n```go\ncomposed, err := ComposeForTurn(registry, extra)\n// ...\ngate := tools.NewContextPressureGate(contextWindow)\ngate.SetAlwaysVisible(...) // e.g. session/session_resume, task/task_list\ndisclosed := gate.FilterTools(composed)\ntoolSet, err := agentexec.BuildToolSetFrom(disclosed, toolOpts)\n```\n\n`FilterTools` (`disclosure.go`) already returns `all` in full mode and\n`bridge + always-visible` in bridge mode, and `BuildToolSetFrom` re-applies\navailability/approval/schema rules, so the two layers compose cleanly.\n\n### 2. Thread context window through the preparation seam\n\n`ContextPressureGate` disables at `ContextWindowSize == 0`. The model context\nwindow is resolved in `TurnRunner.prepareTurn` (`turn.go`) but is not\npassed to `TurnModel.Prepare`. Extend the seam:\n\n```go\ntype TurnPrepareContext struct {\n Model string\n Extra []tools.ToolEntry\n ContextWindow int // model's context window in tokens; 0 = gate disabled\n}\n```\n\n`TurnModel.Prepare(ctx, context TurnPrepareContext)`; `prepareTurn` fills\n`ContextWindow` from `modelDetails.ContextWindow`. This touches one interface\n(`turn.go`), one production impl (`chat_turn_model.go`), and the test\nmock (`turn_test.go`).\n\n### 3. Bridge-handler parity note\n\n`bridgeCallHandler` calls `e.Handler` directly (`disclosure.go`), bypassing\n`toolExecute` — so a `tool_call` invocation does **not** apply `CapPayload` /\n`MaxResultSizeChars` spilling or `OnToolCall` reporting, and it pre-refuses\n`RequiresApproval` tools (`disclosure.go`). This is acceptable for the\nfirst wiring (the bridge is read-discover/describe plus a guarded call), but a\nlater hardening should route the invoked tool through the same\ncap/approval path the model's direct call uses. Recorded as a follow-up, not a\nblocker for this task.\n\n## Files touched\n\n- `internal/app/archied/main.go` — `chatGenerateOptions` composes + gates.\n- `internal/app/archied/chat_turn_model.go` Line truncated
},
{
"url": "/dev/prds/public-and-dev-docs/",
"title": "Public and development documentation -- design",
"section": "PRDs",
"body": "# Public and development documentation -- design\n\n**Status:** Draft\n**Date:** 2026-09-22\n\n## Problem\n\nOne published set carries both kinds of document. A reader who wants to know\nwhat Archie is and how to point an event at it lands in a sidebar that also\nholds the repository organisation rules, the migration decision register, the\npackage review procedure and five PRDs. The PRDs are there for a reason that\nhas nothing to do with the reader: settled architecture cites them, and the\ngenerator refuses a link whose target it holds back, so publishing them was the\nonly way to keep those citations alive.\n\nMixing them is not an exposure problem. Every one of these documents can be\npublic. It is a navigation problem: a customer reading the site meets\ncontributor material with no signal that it is not for them.\n\n## Decision\n\nOne source tree, two published sets, two artifacts, two URL bases.\n\n| Set | Holds | Served under | Artifact |\n| ----------- | ------------------------ | ------------ | ----------------------------------- |\n| Public | `index.md`, `guides/` | `/docs/` | `docs/data/generated/docs.json` |\n| Development | `architecture/`, `prds/` | `/dev/` | `docs/data/generated/dev-docs.json` |\n\n`archive/`, `inspiration/`, `news/` and `github-token.md` stay out of both, for\nthe reasons the generator already records.\n\nThe two artifacts have the same shape. A renderer reads a second file and\nserves it under a second base; it needs no new field and no set discriminator,\nbecause the file a page arrived in is the set it belongs to.\n\n## Consequences the design depends on\n\n**Every PRD publishes.** Selective PRD publication existed to keep citations\nfrom settled architecture working. With both cited and citing documents in the\ndevelopment set, that pressure is gone, and the rule that produced it goes with\nit: `prds/` is a development tree, not a list of exceptions.\n\n**Cross-set links resolve.** A link from a public page to an architecture page\nrewrites to the development set's absolute path, and the reverse works the same\nway. Both sets are generated in one pass over one url map, so a link and its\ntarget cannot disagree about where the target lives. The generator's refusal\nstill fires, now only for a target genuinely in neither set.\n\n**Assets keep the public base.** `docs/public/` is one file set, referenced\nfrom either set, and serving one file under two paths would invent a second\nlocation for it.\n\n**The sidebar stays derived from the directory layout**, per set. A page added\nunder a directory appears without a second edit, which is the property the\ncurrent generator has and the reason its tree mirrors the tree on disk.\n\n## The public set is thin, and that is the honest state\n\nTwo pages: the landing page and the playbook guide. Nothing is lost by the\nsplit, because a reader was never served by the seventeen architecture pages\nnext to them. The pages a public site needs (installation, configuration\nreference, the event sources, the actions a playbook can run) are written into\n`guides/` and a `reference/` tree as they are written, and each lands in the\npublic set with no generator change.\n\n## Verification\n\n- `task docs:artifact` writes both files; `task docs:artifact:check` fails on a\n stale copy of either, without touching the tree.\n- A link from the public set to a development page, and a link the other way,\n each resolve to the other set's base path in the generated body.\n- A link to a page in neither set fails the generator, naming the file, the\n line and the target.\n- `docsgen` accounts for both artifacts, so neither tool reports the other's\n file as unowned.\n"
},
{
"url": "/dev/prds/release-stream-and-commit-rules/",
"title": "One release stream, one page per version, and commit rules — decision",
"section": "PRDs",
"body": "# One release stream, one page per version, and commit rules — decision\n\n**Status:** Draft\n**Date:** 2026-09-22\n**Authority:** `RELEASING.md` for the process this changes, `AGENTS.md` for the\ncommit rules it enforces, and `tools/newsgen` for the artifact shape.\n\n**Supersedes:** `docs/prds/news-and-releases.md`, sections \"Source of truth\" and\n\"Two components\" — one changelog replaces two, and one page per version replaces\none page per component. Its remaining decisions stand.\n\n## Decision\n\n**A release is one version covering whatever changed.** One changelog holds every\nrelease section, one generated page holds every version's notes, and an operator\ncutting a release names one version.\n\n## One changelog\n\nEvery release section lives in `CHANGELOG.md`, newest first. `CHANGELOG.archied.md`\nand `CHANGELOG.archie.md` are deleted, and `CHANGELOG.md` stops being a pointer to\nthem. The changelog is the only source of release prose, and tags are not a source:\nCI and deployment check out shallow, so tags are absent from a site build while the\nchangelog is always present.\n\n### The merged history\n\nTwo version streams become one file, so a version that both components released\ncarries one heading and one date: **the newest date among that version's sections**,\nbecause a version's date is when the last part of it shipped. Where a component's own\ndate differs from it, that component's section label carries its own date, so the\nper-component fact survives the merge rather than being collapsed into the heading.\n\nThe merged history holds 65 versions: 33 that both components released, 31 only\n`archied`, and one only `archie`, from 64 and 34 sections respectively, so 98\npublished pages become 65. `## [Unreleased]` is not a release -- it carries no\nversion and gets no page -- but it stays at the top of the file, because it is\nthe one place unfinished work is recorded. Counting `##` headings rather than\nreleases overcounts by one.\n\nThis ambiguity is historical only. One version stream with one tag gives a version\nexactly one date, so the rule represents the merged past rather than a design that has\nto hold.\n\nThe merge is verified by content, not by the generator succeeding: the section count\nper source, the merged version set equal to the union of both sources with nothing\nextra, and every section title still present. A generator that agrees with the file it\njust wrote is evidence of nothing.\n\n## One version stream\n\n**`GATEWAY` and `RUNTIME` stop being release inputs.** `release:prepare` and\n`release:tag` take one version, and `tools/release.sh` loses the two flags.\n\nThey may stay as build-time stamps, because a binary must still report what it\ncontains. A release that must name three versions forces an operator to pass skip\nvalues for components that did not change, and that ceremony is what this decision\nremoves — along with the drift it allows, where two components' tags fall a release\napart.\n\n**Per-component detail stays, as sections inside the release.** A reader still needs\nto know whether `archied` or the agent changed; what goes away is the separate\nnumbers and the separate pages, not the information.\n\n**History is not re-tagged.** Existing tags keep their names, because tags are not a\nsource and nothing reads them to build a page. A future reader must not \"fix\" the\nunified changelog by rewriting tags to match it.\n\n## One release page per version\n\n`docs/news/\u003cversion\u003e.md` replaces `docs/news/\u003ccomponent\u003e/\u003cversion\u003e.md`, carrying the\nrelease's per-component sections inside it.\n\n**Every release URL already published keeps working.** `/news/archied/\u003cversion\u003e` and\n`/news/archie/\u003cversion\u003e` route to the unified page for that version. The generator\nemits the redirect table beside the pages so it cannot drift from them; if the\nrenderer needs the table in its own repository, that is a change in that repository\nrather than a hand-maintained list here.\n\n## The reviewer runs between prepare and tag\n\nRelease notes are prose, and the review agent exists to review prose. **`release:tag`\nrefuses to tag when the review has not been run for that version, or when it reports\nat the level.**\n\nThe invocation is verified rather than assumed. `tl rules --lint` reports `corpus ok`\nand exits 0. `tl review \u003cpath\u003e --deadline \u003cms\u003e --max-turns \u003cn\u003e` reports\n`0 findings (0 high, 0 medium) · 1/1 files reviewed · clean` and exits 0 on\n`docs/news/archied/1.36.0.md`.\n\n**`--fail-on` must be passed explicitly.** It defaults to `never`, so an invocation\nwithout it cannot refuse anything and the step would be decorative. `--fail-on high`\nis the level: a medium finding in a release note is worth acting on, and it should not\nstop a release on its own.\n\n**The rule is stated once.** It belongs in the reviewer's own rule set, which\n`tl rules --from-doc` can draft frLine truncated
},
{
"url": "/dev/prds/review-settings-resource/",
"title": "Review settings resource",
"section": "PRDs",
"body": "# Review settings resource\n\n**Status:** Draft\n**Beads issue:** `archie-core-0ry6`\n**Authority:** `docs/prds/runtime-control-plane.md` for the resource model,\n`docs/architecture/configuration.md` for ownership, and\n`docs/prds/pr-review-agent.md` for what the two dials do.\n\n## Decision\n\n`review.precision_gate` and `review.approve_before_post` are one control-plane\nresource, `review-settings`. The file's `[review]` section seeds it, the stored\ndocument outranks the file from then on, and the dashboard writes it through the\nsame settings machinery as every other resource.\n\nThe resource is deployment-wide, like every definition the State Store seeds\n(`storecontract.DefaultOrgID`): not per-repository, per-identity, or per-run.\n\n## Why its own kind\n\nThe two dials are pr-review policy — what a review may post, and whether a human\ndecides — not a limit on a task run. The document that carries task limits\nbelongs to that feature. `runtime-control-plane.md` splits settings by feature\nand refuses documents unrelated features share; `configuration.md` puts a typed\nruntime setting with the domain whose behaviour it describes. One document per\nfeature is the rule, not one document per settings page.\n\nA new kind also has no legacy documents. Its first value is the seed derived\nfrom the file, so \"the store outranks the file\" begins from an explicit copy of\nboth fields rather than from a document that predates them.\n\n## Document\n\nNew file `internal/app/controlplane/review_settings.go`:\n\n```go\nconst ReviewSettingsKind = \"review-settings\"\n\ntype reviewSettings struct {\n PrecisionGate bool `json:\"precision_gate\"`\n ApproveBeforePost bool `json:\"approve_before_post\"`\n}\n```\n\nIts `Definition` sets `ApplyMode: \"live\"`, `Document: reviewSettings{}`, and a\n`Seed` returning `reviewSettings{cfg.Review.PrecisionGate, cfg.Review.ApproveBeforePost}`,\nand a `Validate` wrapping `validateAs`: both fields are free booleans with no cross-field\nrule, so the validator is a named place to put one rather than an inline no-op\n(`validatePluginSettings` is the precedent). No `Normalize`, because the kind\nhas no second wire shape to converge.\n\n## Seeding\n\n`ImportConfig`/`seededValues` write the seed for a kind the store does not hold,\nso a deployment that never edited the dials runs the values in `[review]`. Once\na document is stored, the file key stops mattering, which is the rule for every\ndatabase-owned setting.\n\n## Apply\n\n`runtimeConfigFrom` in `internal/app/controlplane/runtime_config.go` layers the\nstored document over the file's `Review`, assigning `out.Review.PrecisionGate`\nand `out.Review.ApproveBeforePost` field by field. Field-by-field, not\n`out.Review = ...`: a field added to `config.Review` later keeps the file's value\nuntil the document carries it.\n\n`ReviewSettingsKind` joins `runtimeResourceKinds` in\n`internal/app/archied/control_plane.go`, so a new stored version re-runs the\nlayering and republishes through `config.Holder`. Live rather than\nrestart-required, because every consumer re-reads it: `Review` is on\n`reloadableFields` in `internal/app/archied/reload.go`, and the value reaches a\nrun through `Daemon.configFor` → `Config.ForTask` → `TaskConfig.ToConfig` →\n`TaskContext.Cfg`, which `stagePRPrecisionGate` and `stagePROperatorApproval`\nread. The next task run uses the new value; a run in flight keeps the value it\nstarted with.\n\n## Projection and page\n\n`BuildConfigView` gains a plain `Review` field carrying both values out of\n`cfg.Review`, the way `BudgetsView` carries the layered budgets, so the published\nconfig snapshot tells any reader what is in force. The Review page renders the\ntwo toggles from the control-plane store's draft for `review-settings` — the\nshape `SystemTasksPage.vue` uses for `workflow-execution-settings` — and shows\nthe projected value beside them; a Settings route plus a `PAGE_RESOURCES` entry\n(`ui/src/stores/control-plane.ts`) bind the page to the kind.\n\nNothing else re-advertises them. `configFieldDescriptors` and `ConfigView.Schema`\ngain no `review.*` row: the config catalog's generic renderer was deleted, so a\ndescriptor row adds a field nothing can edit, which is the shape `becb0b5e`\nremoved.\n\n## What the test proves\n\n`internal/app/controlplane/runtime_config_test.go` adds the round trip that\nbuilds the effective config the way boot does: seed the kind from a file config\nwith both dials set one way, store a document with both flipped, layer it\nthrough `runtimeConfigFrom`, and assert the effective `cfg.Review` equals the\nstored document. A second case covers the absent kind, where the file's values\nstay in effect. The assertion is on `cfg.Review` — the value `TaskContext.Cfg`\ncarries into the two stages — not on a struct the test set directly.\n`TestRuntimeResourceKindsApplyLive` gains `review-settings` as live. The\nvalidator needs no `validators_agree_test.goLine truncated
},
{
"url": "/dev/prds/runtime-control-plane/",
"title": "Runtime control plane",
"section": "PRDs",
"body": "# Runtime control plane\n\n**Status:** Approved \n**Date:** 2026-09-20 \n**Tracking:** `archie-core-j28m`, `archie-core-1786637498420-327-bacadaae`\n\n## Outcome\n\nArchie can be managed from the Web UI or a messaging channel. Both use the same\nAPI.\n\n## Model\n\nEach feature owns its settings and commands. The database stores them. There is\nno global configuration document.\n\nThis includes:\n\n- workflows;\n- identities and bindings;\n- providers and models;\n- repository policies;\n- channels and schedules;\n- capture mappings and bindings;\n- tool settings;\n- prompts and personas;\n- plugin settings.\n\nPlugin code remains installed code. Only its settings are stored in the\ndatabase.\n\nEach feature defines its data, validation, permissions, editor fields, and how\nchanges take effect. Each feature also defines its allowed actions. For example,\nidentities can be created, suspended, and retired.\n\nRepository and identity settings remain separate. They are not stored as large\nrecords that unrelated features must share.\n\nThe State Store process hosts the control-plane API on its existing gRPC server.\nNo new process is added. Feature code validates changes. Storage code only\nwrites versions and audit records.\n\nEvery write records who made it, where it came from, a request ID, and the\nversion being edited. The API layer sets the actor; the request body cannot.\nThe server validates the change, then writes it with its audit record. It rejects\nedits to an old version.\n\nThe request ID is the write's idempotency key, and it is scoped per org and\nper kind, never global. The key is `(org_id, kind, request_id)` — the unique\nindex `idx_resource_history_org_kind_request` (migration `0021_resources_per_org.sql`)\n— so replaying a request ID is the same org's prior write of the same kind, and\na request ID reused across orgs or across kinds is a separate write. This is the\nsame scoping as the task idempotency key `org/identity/owner/repo/number`\n(`docs/prds/orgs-and-access.md`).\n\n## API\n\nThe API has four operations:\n\n1. **Catalogue** tells clients what can be viewed or changed and how to edit it.\n2. **Query** reads data and versions without exposing secrets.\n3. **Command** asks the owning feature to make a change.\n4. **Watch** streams changes and errors to clients.\n\nComplex features can use custom screens. They still use the same commands.\n\nA dashboard session or channel sender must map to an Archie identity before it\ncan run a command. Messaging syntax maps to the same commands as the Web UI.\n\n`archie-ui` receives only an API client. It does not receive a database handle,\ndaemon pointer, global configuration object, or secret value.\n\nThe database stores the requested settings. Each process reports the version it\nis using or why it failed. The UI shows both.\n\nSome changes require a restart. The UI shows them as pending. When a live change\nreplaces a running component, Archie starts and checks the new one before\nswitching. If the check fails, the old one keeps running.\n\n## Bootstrap, migration, and recovery\n\nBootstrap contains only the database path, listen addresses, credentials, TLS,\nand encryption-key references. State Store and control-plane RPCs use the same\nendpoint.\n\nWhen upgraded, existing instances are migrated to the database. Existing\ndatabase values are not overwritten, with one exception: a resource whose\ndocument the build ships is refreshed when the seed itself wrote the stored\ncopy, because that copy is a previous release's document rather than an\noperator's. After migration, settings in TOML are ignored and cannot block\nState Store startup.\n\nThe Web UI remains available when `archied` or Gateway is down. It shows failed\nchanges and can correct or roll them back.\n\nOffline commands can back up, restore, validate, and roll back the database.\nRecovery does not require `archied` or the Web UI. The database stores secret\nreferences, not secret values.\n\n## Workflows\n\nUsers create and edit workflows in the Web UI. Workflows are stored as versioned\nYAML. Built-in workflows can be overridden and restored.\n\nA workflow is a list of steps. Each step has a known type and its own settings.\nA step type is part of the build's step vocabulary, contributed as a provider at\nthe composition root; interpreted plugins contribute none\n(`docs/prds/workflow-step-vocabulary.md`). Each run keeps the workflow version it\nstarted with.\n\nYaegi, `.archie/stages/*.go`, and `.archie/gate.go` will be removed. Their useful\nbehaviour must first be available as normal workflow steps.\n\n## First implementation\n\nThe first implementation makes task limits editable: maximum model steps,\nmaximum runtime, and maximum consecutive gate failures.\n\nIt includes:\n\n- validated task-limit fields;\n- version history and audit records;\n- the four API operations;\n- authenticated Web UI and messaging access;\n- live updates and apply status;\n- a PiLine truncated
},
{
"url": "/dev/prds/self-update-transaction/",
"title": "Self-update: artifact install, topology migration, journaled transaction",
"section": "PRDs",
"body": "# Self-update: artifact install, topology migration, journaled transaction\n\n**Status:** Draft\n\nEpic: `archie-core-hj1t` / GitHub `#804` (\"[EPIC] Self-update: artifact\ninstall, topology migration, journaled transaction\").\n\nThe update _contract_ (`internal/releaseupdate`: `Catalog.Check`,\n`Installer.Install`, plus defer/watchdog/verify) is settled and unchanged by\nthis document — it stays a thin Go interface shelling out to\n`CommandCatalog`/`CommandInstaller`. This document decides what the reference\nadapter scripts (`scripts/archie-update-{check,install,watchdog}`) and\n`install.sh` do behind that contract, and settles the one thing the epic's\nown description got wrong: the dist-zip **is** already attached to GitHub\nReleases (`.github/workflows/deploy.yml`, `gh release upload`), not\nActions-artifact-only. Artifact install is therefore a smaller change than\nthe epic assumed — pointing the installer at an existing asset, not standing\nup new CI publishing. Topology migration and the journaled transaction are\ngenuinely greenfield: no topology-detection or transaction-journal code\nexists anywhere in the tree.\n\nOut of scope: rewriting the `internal/releaseupdate` Go interfaces\nthemselves, and any UI for triggering updates (channel dispatch, e.g.\nTelegram `/update`, is unaffected — this only changes what happens once an\ninstall is triggered).\n\n## Problem\n\n`scripts/archie-update-install:139-160` clones and compiles from source on\nevery update — the only path that exists. `deploy.yml` already publishes a\nper-platform archive plus (implicitly) checksums as a release asset, so the\nscript not using it is a missed-reuse gap, not a missing-CI gap.\n`install.sh:414-445` writes only `archied.service` while every shipped\ndeployment profile (`deployments/*.toml`) declares `[services.state]` and\n`[services.gateway]` sections needing their own units — a fresh install\nalready reproduces the broken single-unit shape `deployment_contract_test.go`\ndoesn't even catch, because that test only checks profile\nsyntax, not installed topology. No code anywhere enumerates which systemd\nunits exist on a host or compares that against what a release requires — the\ndaemon fails at `bootstrap.go`'s `[services.state].target` check with no\nprior diagnosis. The self-refresh trap is confirmed at\n`scripts/archie-update-install:195-199`: new adapter copies land on disk but\nbash keeps executing the in-memory copy, so a pre-flight check added to the\nscript only protects the _next_ update.\n\n## Design\n\n### Artifact install (`#804` item 1)\n\n**Decision.** `CommandInstaller`'s default script downloads the per-platform\narchive plus `SHA256SUMS` from the GitHub Release that `Catalog.Check`\nresolved (the same release `deploy.yml` already publishes to), verifies the\nchecksum, and stages it — it does not clone/compile. Source build\n(`scripts/archie-update-install`'s current clone+compile body) is kept as an\nopt-in path selected by an explicit `--from-source` flag or\n`ARCHIE_UPDATE_SOURCE_BUILD=1` env var, never the default, since a compile-on\nevery-host update is strictly slower and has a larger failure surface than\ndownloading a signed asset that CI already produced.\n\n**Call site.** `scripts/archie-update-install` — replace the clone+compile\nbody with a download-and-verify step; move the existing\nclone+compile body behind the opt-in flag rather than deleting it.\n`internal/releaseupdate/command.go` (`CommandInstaller`) is unchanged —\nit already just shells out.\n\n**Reuse check.** `deploy.yml` already builds and publishes the\narchive and uploads it as both an Actions artifact and a release asset; no\nnew CI work is needed, only pointing the installer at what exists.\n\n**Testing.** Checksum-verification logic is a shell function, testable with\na fixture archive + `SHA256SUMS` pair — add to whatever test harness already\ncovers `scripts/`. Full download-from-real-release is a manual smoke command\n(document the exact `archie-update-check`/`--dry-run` invocation once built),\nnot `task check`.\n\n### Topology migration (`#804` item 2)\n\n**Decision.** Add a topology _observer_ to the daemon, not the shell\nadapter — CLAUDE.md's own \"known trap\" note says the shell copy is defence\nin depth only, and the daemon is what \"knows the deployment and holds the\napproved snapshot.\" The observer inspects which systemd user units exist\n(`systemctl --user list-unit-files 'archie*.service'` or equivalent) and\nwhich config sections are present (`[services.state]`, `[services.gateway]`,\nUI service config), producing an `ObservedTopology` value with one field per\nunit: present/absent, and the config sections backing it. Each release's\n`release.json` (already produced by `deploy.yml` per the artifact-install\nwork above) gains a `required_topology` field naming the units and config\nsections that release's binaries need. `Catalog.Check` compares observed\nagainst requireLine truncated
},
{
"url": "/dev/prds/service-decomposition/",
"title": "Service decomposition -- decision",
"section": "PRDs",
"body": "# Service decomposition -- decision\n\n**Status:** Draft\n**Date:** 2026-09-05\n**Beads epic:** archie-core-8cda\n**Prior art:** `docs/inspiration/2026-09-05-awx-service-decomposition-and-ansible-task-model.md`,\n`docs/inspiration/module-reference-awx-decomposition-vs-archie.md`,\n`docs/inspiration/service-discovery-research-2026-09-05.md`,\n`/work/artefacts/archie-core-current-state-archify.html`,\n`/work/artefacts/archie-core-ideal-state-archify.html`\n\nThe Phase 3 UI boundary and configuration decision is ratified in\n[`ui-service-boundary.md`](/dev/prds/ui-service-boundary/). That focused document is\nthe implementation authority for `archie-core-8cda.5.2`; this parent remains\nthe broader service-distribution proposal.\n\n## Decision\n\narchie-core moves from one Go binary (`archied`) hosting every domain\nin-process to a set of independently deployable services, each exposing\nexactly one typed contract. Consumers depend on the contract; they never\nreach into another service's internal types, session state, or config.\ngRPC is the synchronous transport; NATS remains for asynchronous fan-out\n(status, telemetry) rather than being replaced.\n\nThis is a **distribution decision**, not a rewrite of Archie's domain\nmodel. The six-domain split already approved in\n`docs/architecture/index.md` and `docs/architecture/organisation.md`\n(Identity, Agent, Messaging, Workflow, Work Intake, Plugin) is unchanged;\nthis PRD is about how the _processes_ running that domain logic get\npackaged, contracted, and discovered -- not about redrawing domain\nboundaries.\n\n### Target services\n\n| Service | Contract it owns | Existing code it replaces/wraps |\n| --------------------- | -------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |\n| 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) |\n| Gateway Service | routing / turn / session contract | `internal/gateway` |\n| Messaging Service | channel-plugin contract (Telegram, email, Discord, Teams, ...) | `internal/channels` |\n| Curator Service | curator contract; **optional**, installs as a Gateway plugin | `internal/domain/curator` |\n| Scheduler Service | cron/ticker contract | `internal/domain/scheduling` |\n| Execution Environment | execution-dispatch contract | `internal/domain/workflow`, task dispatch paths |\n| Runner | isolated worktree/container execution | `internal/container`, `internal/agentexec`, `internal/worktree` |\n| State Store | state-access contract | `internal/infrastructure/postgres` |\n\n### Discovery\n\nPer `docs/inspiration/service-discovery-research-2026-09-05.md`:\n\n- **Primary:** Kubernetes-native discovery (Service + headless-Service/DNS\n - EndpointSlice, served by CoreDNS), delivered as a Helm chart + Operator,\n on k3s for single-host installs and a real cluster for multi-host or a\n hosted offering.\n- **Fallback:** NATS-based discovery (micro `$SRV` announce + JetStream KV\n registry) for no-K8s single-host installs, with a custom gRPC resolver\n reading `host:port` from the KV bucket.\n- Both implementations sit behind one internal interface:\n\n ```go\n type ServiceRegistry interface {\n Resolve(service string) []Endpoint\n Watch(service string) \u003c-chan Event // join/leave\n }\n ```\n\n- An optional service (Curator; others later) that is not installed\n must resolve to a distinct `NotInstalled` outcome, never a `Down`/\n `Unhealthy` one. Under K8s this falls out of DNS returning no record;\n under the NATS fallback it requires an explicit \"installed\" marker in the\n KV registry, not just absence-implies-down.\n\n### Distribution model this supports\n\nBoth self-hosted (customer runs the Helm chart or the NATS-fallback\nbinaries themselves) and a managed/hosted offering (we run the same Helm\nchart) are in scope -- this is the RHELine truncated
},
{
"url": "/dev/prds/service-registry/",
"title": "Service registry — one declaration per service",
"section": "PRDs",
"body": "# Service registry — one declaration per service\n\n**Status:** Draft\n**Supersedes:** `state-store-contract.md` §10's `State ServiceConnection`\nstruct-field instruction.\n\n**Base:** the `listen` field, `internal/app/archied/listen.go`, and the listen defaults cited\nbelow exist on `feat/attempt-attribution`, not on `main`. This design therefore lands on top of\nthat branch: `RegisterService`'s `listen` argument has nothing to carry without it.\n\n## Problem\n\nA service is already one Go type, `config.ServiceConnection`. What is duplicated is its\n**name**, in three layers:\n\n| Layer | Location | What is hard-coded |\n| ----------- | -------------------------------------------------------------------------------------------------- | ---------------------------------------------------------- |\n| Declaration | `internal/config/services.go` | `Gateway` and `State` as struct fields |\n| Defaulting | `internal/infrastructure/configuration/defaults.go` | three `if cfg.Services.X.Y == \"\"` branches |\n| Consumption | `internal/app/archied/{bootstrap.go,state_store.go,gateway.go}`, `internal/app/archieui/config.go` | `cfg.Services.State` / `cfg.Services.Gateway` field access |\n\nAdding a service means editing all three. The drift this permits is already visible:\n`stateStoreResolvedToken` (`state_store_client.go`) and `gatewayResolvedToken`\n(`chat_service.go`) are byte-identical apart from the env var name, and\n`gateway.Target` is defaulted while `state.Target` is a startup error, with nothing\nstating that asymmetry in one place.\n\n`resolveServiceListen(service, flagValue, configured)` (`listen.go`) is already\nname-parameterised. It is the shape the rest should follow.\n\n## Decision\n\n**Key services by name, and carry per-service asymmetry as registration data.**\n\n### 1. Declaration collapses to a map\n\n```go\n// internal/config/services.go\ntype Services map[string]ServiceConnection\n```\n\n`ServiceConnection` is unchanged. The TOML shape is unchanged, so no deployment profile,\n`config.example.toml`, or `install.sh` edit is required. An unrecognised `[services.foo]`\ndecodes without a code edit, satisfying criterion 5.\n\n### 2. Registration is the single entry point\n\n```go\n// internal/config/servicespec.go\nfunc RegisterService(context, name, target, listen, tokenEnv string)\n```\n\nregistered once per service, at package init in `internal/config`:\n\n```go\nRegisterService(\"both\", \"gateway\", \"127.0.0.1:8585\", \"127.0.0.1:8585\", \"GATEWAY_TOKEN\")\nRegisterService(\"client\", \"state\", \"\", \"127.0.0.1:9090\", \"STATE_STORE_TOKEN\")\n```\n\nPositional, five strings, as the story specifies. Each argument is data the current code\nstates in prose or in a branch:\n\n- `context` is `client`, `server`, or `both`, and decides which fields must resolve\n non-empty. `RegisterService` enforces it: an unknown context, or a hosted service with\n no default `listen`, panics at registration. Registrations come from this repository's\n own `init()`, never from operator input, so an invalid one is a programming error with\n no caller positioned to handle an error return. A documented-but-unread `Context` would\n be worse than no field at all.\n- `target` is the **default**, and an empty default means the operator must supply one.\n That single convention replaces the `state.target` required / `gateway.target` defaulted\n asymmetry with no branch: `state` registers `\"\"`, `gateway` registers an address.\n- `listen` is the default listen address, feeding the existing\n flag → `[services.\u003cname\u003e].listen` → default precedence unchanged.\n- `tokenEnv` names the fallback env var, replacing the two copied resolvers with one.\n\n### 3. Defaulting and consumption become loops and lookups\n\n`applyDefaults` iterates the registry instead of naming services. Consumers read\n`cfg.Services.Get(\"state\")`, returning a `ServiceConnection` plus the spec, so\n`stateStoreResolvedToken` and `gatewayResolvedToken` collapse into\n`Services.ResolvedToken(name, secrets)`.\n\n## Criteria satisfied\n\n1. Declared once, in the `RegisterService` call.\n2. No second location can contradict it; the map has no per-service fields to disagree with.\n3. Registration is the entry point, with the five fields a service has.\n4. A new service is one `RegisterService` line: no field, no default branch, no consumer edit.\n5. The set of services is registry data, not a struct definition.\n\n## Scope and risk\n\n- `state-store-contract.md` §10 must be revised in the same change, or the tree contradicts\n its own ratified authority. Its summary (`:7`) already says `[services.\u003cname\u003e]`.\nLine truncated
},
{
"url": "/dev/prds/session-memory-curator/",
"title": "Persistent session-memory curator (reference implementation) -- decision",
"section": "PRDs",
"body": "# Persistent session-memory curator (reference implementation) -- decision\n\n**Status:** Approved\n**Date:** 2026-09-02\n**Beads issue:** `archie-core-1786637499114`\n**Parent epic:** `archie-core-1786637500725` (curator engine)\n**Depends on:** `archie-core-1786637499636` (bind curators to memory\nengines, shipped) and the `domain/memory` engine family (shipped)\n\n## Decision\n\nEach pass: find sessions with activity since the last pass, ask the\nmodel to extract a short list of durable observations from each one's\nrecent messages, and write each through the curator's bound memory\nengine. Extraction is **scoped to one session** -- `Observation.Identity`\nis the session ID, not a user or cross-session identity. No\nconsolidation across sessions, no forgetting, no rewriting a prior\nextraction: every pass only adds.\n\nThis is the second contract consumer the epic asks for, and the one that\nexercises the curator/memory-engine binding\n(`archie-core-1786637499636`) for real, unlike the skill curator, which\ndeclares no memory engine at all.\n\n## Why session-scoped, not user- or agent-wide\n\n`docs/architecture/migration-decisions.md#5` lists the four required\nmemory scopes (global, agent-wide, user-wide, agent-user relationship)\nas **still open** -- there is no decided mapping yet from a chat session\nto a durable identity that would outlive that session (a Telegram chat\nID is not necessarily \"the same person\" as a web session; per-platform\nidentity resolution does not exist as a memory concern). Choosing\nsession-as-identity sidesteps a decision this issue has no business\nmaking unilaterally: it is the narrowest scope that is unambiguous\n(`gateway.SessionContext.SessionID` already exists, is already unique,\nand already has no cross-platform identity claim attached to it), and\nit is forward-compatible -- widening to a resolved user identity later\nis a change to what `Identity` is populated with, not to the\nextraction or write path.\n\n## Why a new `curator.ConversationSource`, not `gateway.SessionStore` directly\n\n`internal/domain/curator` is a domain package; `internal/gateway` is not\none of `internal/domain/*`'s dependencies by convention, and\n`gateway.SessionStore`'s full CRUD surface (branch, fork, replace,\nsearch) is far more than a curator needs or should be able to reach --\nthe same reasoning `ToolBuilder`/`SkillStore`/`MemoryEngineSource`\nalready established for every other host service this package depends\non. `curator.ConversationSource` is a two-method read-only interface;\n`internal/app/archied` adapts the real `gateway.SessionStore` to it, the\nsame shape `MemoryEngineSource` already uses for\n`domain/memory.Registry`.\n\n```go\n// ConversationSource is read-only conversation history, narrowed to\n// what a curator needs to review recent activity -- never the full\n// session CRUD/branch/search surface a chat gateway exposes.\ntype ConversationSource interface {\n // RecentSessions returns every session touched at or after since,\n // newest first.\n RecentSessions(ctx context.Context, since time.Time) ([]SessionSummary, error)\n // Messages returns the most recent n messages of one session, in\n // chronological order.\n Messages(ctx context.Context, sessionID string, n int) ([]ConversationMessage, error)\n}\n\ntype SessionSummary struct {\n ID string\n LastActive time.Time\n}\n\ntype ConversationMessage struct {\n Role string // \"user\" or \"assistant\"\n Content string\n At time.Time\n}\n```\n\n`Manifest` gains `Conversations bool`, gated exactly like `Skills`:\n`Registry.validateDeclared` requires a `ConversationSource` on the host\nwhen declared, `Registry.filter` clears it from a curator's view when\nnot. Role is derived the same way `gateway.compressTurnHistory` already\ndoes (`message.From == botUser` -\u003e `\"assistant\"`, else `\"user\"`) --\ncopied logic, not shared code, since the source type\n(`gateway.Message`) is exactly the thing this package must not import.\n\n## Extraction shape\n\n`Pass`:\n\n1. `Conversations.RecentSessions(ctx, effectiveSince(in.Since))` -- see\n below for the zero-`Since` default.\n2. For each session, `Conversations.Messages(ctx, id, 40)` -- the last\n 40 messages, not the full history. A session accumulates far more\n history than a skill file accumulates content; unlike the skill\n curator's \"re-read everything, it's cheap,\" a full-history read here\n is not cheap and is not needed -- durable facts worth keeping surface\n in recent exchanges, and a 40-message tail is deliberately generous\n against the model's own context rather than tuned tightly, since\n getting this number exactly right is not this issue's job.\n3. One model call per session: the message tail, plus an instruction to\n return a JSON array of short strings, each one fact/preference/\n correction worth keeping, or `[]` if nothing is. Capped at 5 items\n per session per passLine truncated
},
{
"url": "/dev/prds/skill-curator/",
"title": "Skill curator (reference implementation) -- decision",
"section": "PRDs",
"body": "# Skill curator (reference implementation) -- decision\n\n**Status:** Approved\n**Date:** 2026-09-02\n**Beads issue:** `archie-core-1786637499206`\n**Parent epic:** `archie-core-1786637500725` (curator engine)\n\n## Decision\n\nThe skill curator's v1 scope is **mechanical validation and safe\nnormalisation only** -- it never rewrites skill prose, never deletes a\nskill, and never calls the model. Each pass:\n\n1. Lists every skill under one configured root.\n2. Reads each `SKILL.md` and attempts to parse its frontmatter\n (`internal/skill.Parse`).\n3. Records an `Action` for any structural problem: a parse failure, or a\n missing `name`/`description` in the frontmatter that parsed.\n4. Normalises trivial whitespace (trailing whitespace per line, exactly\n one trailing newline) and writes back **only** when normalisation\n actually changes the bytes, recording an `Action` for that write.\n\nNothing here needs judgement. \"Review, prune, and improve\" -- the epic's\nframing -- is real for v1 but deliberately narrow: review is structural\nvalidation, improve is whitespace normalisation, and prune is _reporting_\na problem, never removing a skill. `Manifest.Skills = true` still marks\nthis curator agentic (existing `agentic()` rule), so it receives model\naccess from the registrar -- unused but nothing about the contract\nor the runtime needs to change to let a later version reason about\ncontent quality using it.\n\n## Why this scope, not more\n\nAn autonomous process that rewrites or deletes a user's skill content\nis a real risk with no undo path (no draft/approval flow for\ncurator writes exists yet, unlike the workflow engine's PR-based review).\nThe epic's own stated purpose for this issue is proving the curator\ncontract holds for a second, structurally different consumer than the\nsession-memory curator (files-as-skills vs. observations-as-memory), not\nsolving \"what makes a skill good.\" Mechanical validation is real,\nuseful, safe to run unattended, and fully exercises\nList/Read/Write -- every method `curator.SkillStore` declares except\n`Delete`, which this curator's Pass never has a safe reason to call in\nv1 (kept implemented on the store adapter regardless, since the\ninterface requires it and a future consumer may).\n\n## Why `internal/skill` isn't `curator.SkillStore` directly\n\n`internal/skill.Discover` parses every `SKILL.md` under a root and\nreturns an error for the **whole** call if any one of them fails to\nparse -- the read side was built for \"load the catalogue to start the\ndaemon,\" where one bad skill failing the whole boot is arguably correct,\nnot for \"review each skill and report what's wrong with it\nindividually.\" A per-skill parse failure must become one `Action`, not\nabort the pass before any skill is reviewed. So\n`internal/infrastructure/skillcurator` gets its own thin store adapter\nthat lists raw directory names and reads/writes raw `SKILL.md` bytes\nper name; the skill curator itself calls `internal/skill.Parse` on each\none, isolated per skill.\n\n## Root scope\n\nOne root only, resolved the same way `loadWorkflows` already resolves\n`skillsBase` (`cfg.SkillsDir`, falling back to `cfg.WorkDir`) -- not\nevery root `skill.CatalogRoots`/`DefaultRoots` would read for a model\n(which layers a shared dir over the per-profile one). Write and Delete\nneed one unambiguous target; a curator that could write into a shared,\nmulti-tenant skills directory is a bigger decision than this issue\ncovers. The model still sees the full multi-root catalogue through the\nexisting read path -- this curator only maintains the local one.\n\n## Shape\n\n### `internal/infrastructure/skillcurator/store.go`\n\n```go\n// Store implements curator.SkillStore over one root directory's\n// .agents/skills/*/SKILL.md files, tolerating a per-skill parse failure\n// as the curator's problem to report rather than this store's problem\n// to abort on.\ntype Store struct { root string }\n\nfunc NewStore(root string) *Store\n\nfunc (s *Store) List(ctx context.Context) ([]curator.SkillRef, error)\nfunc (s *Store) Read(ctx context.Context, name string) (curator.Skill, error)\nfunc (s *Store) Write(ctx context.Context, sk curator.Skill) error\nfunc (s *Store) Delete(ctx context.Context, name string) error\n```\n\n`Read` best-effort parses frontmatter for `Skill.Description` (empty on\nparse failure -- not this method's job to report that; `Pass` does, via\nits own `skill.Parse` call on `Skill.Content`). `Write` rejects a name\nthat does not already exist as a directory (this store curates existing\nskills; creating a new one is out of scope). `Delete` removes the whole\nskill directory, matching \"delete a skill,\" not just `SKILL.md`.\n\n### `internal/infrastructure/skillcurator/skillcurator.go`\n\n```go\n// Curator implements domain/curator.CuratorEngine. See\n// docs/prds/skill-curator.md for what a pass does and why.\ntype Curator struct { /* unexported: registrar view, interval *Line truncated
},
{
"url": "/dev/prds/soul/",
"title": "SOUL: an agent's user-authored personality",
"section": "PRDs",
"body": "# SOUL: an agent's user-authored personality\n\n**Status:** Draft\n**Authority:** `docs/architecture/identity.md`, “Three-layer identity model”;\n`docs/prds/orgs-and-access.md` for identity and org ownership.\n\n## Decision\n\nSOUL supplies an agent's name, register and warmth. It belongs to the agent's\nimmutable `IdentityID`, not its session, model, installation or container\nprofile. Rename preserves it; changing a profile does not change who acts.\nSOUL never changes attribution, credentials, grants or identity lifecycle.\n`config.AgentProfile` remains an execution environment, not another identity.\n\nUse the existing three layers: invariants, user-authored SOUL, and curator-derived\nrepresentation. Curators may propose SOUL changes but never apply them.\n\n## Files and ownership\n\nThe config directory is `${XDG_CONFIG_HOME:-~/.config}/archie`, or the directory\nof an explicitly selected config file. The default/root agent uses `SOUL.md`\ndirectly there; additional agents use `agents/\u003cidentity-id\u003e/SOUL.md`. The root is\nthe identity selected by application composition, never the initiating user or\na session's personality selection. No file creates or selects an identity.\n\nThe common case keeps a human-friendly filename; additional agents get separate\nasset directories, following `.agents/skills/\u003cname\u003e/SKILL.md` without confusing\nthese directories with `[containers.profiles.\u003cname\u003e]`. Reject display-name or\nslug directories: rename and same-name agents across orgs would require another\nname-resolution rule. Immutable IDs avoid both problems without an org directory.\n\nWhen a file-owned agent's file is absent, create the shipped default with\nexclusive creation. Never overwrite an existing file, including an empty one.\nA creation failure still permits the turn using the embedded shipped default.\nShip that document independently of `agent.ShippedPersonas`, so deleting personas\ncannot delete the fallback.\n\nResolve once at the start of every new generation:\n\n1. A stored SOUL entry for the acting identity is authoritative.\n2. Without an entry, read that identity's file again.\n3. An absent, empty, unreadable or invalid selected source uses the shipped default.\n\nThe first explicit dashboard/API save takes ownership permanently. Thereafter\nfile edits are ignored: emit one ownership notice and show the owning stored\nversion in the dashboard. Restoring the shipped default writes a stored value;\nit does not remove ownership. Refuse writes that remove an owned entry.\n\nThis ownership boundary is the design's one stateful rule. Files seed the\neditable value, not an automatic durable import. Reject seed-once import because\nit breaks next-message file editing; reject file-always-wins because it makes\ndashboard saves ineffective. Neither a restart nor an upgrade overwrites an\nowned value, following the precedence of `controlplane.AgentProfileKind` without\ncopying its startup import timing.\n\n## Prompt and failure contract\n\nKeep `archie.md.tpl`'s XML-escaped\n`\u003csoul purpose=\"identity_and_style\" trust=\"data\"\u003e` block before\n`\u003cinstruction_precedence\u003e`. SOUL is style reference data; the invariant sections,\ntool inventory and runtime metadata remain authoritative and uneditable.\nPreserve `TestBuildSystemPromptSoulCannotOverrideInvariants`.\n\nAccept UTF-8 plain Markdown with at most 8 KiB in its XML-escaped body. This bounds\npersonality to a small prompt contribution; count the complete rendered prompt\nin the turn's context budget and never truncate invariant sections. Bound file\nreads before decoding; reject oversize input rather than truncating instructions.\nFile and stored writes use the same validator; an invalid save leaves the stored\nversion unchanged. The shipped default must pass that validator.\n\nRead and creation errors never fail a turn. Log once per identity/source failure\nepisode, retry on the next turn, and allow a new warning after recovery. If the\nstore cannot establish whether an owned entry exists, use the shipped default,\nnot a potentially shadowed file. Do not log SOUL text. Each turn keeps its resolved\nsnapshot; edits affect the next generation without restart or SIGHUP.\n\n## Cross-layer delivery\n\n- `internal/domain/agent` owns SOUL content validation and the identity-keyed read\n contract; `internal/domain/identity` remains the actor/lifecycle authority.\n- The configuration infrastructure resolves the config directory and handles\n file discovery, exclusive default creation and bounded per-turn reads.\n Application composition resolves the acting `IdentityID` through the existing\n identity repository/bindings and supplies it to the gateway.\n- Register `SoulKind` (`agent-souls`) in the control plane with a live descriptor\n and an org-scoped document mapping identity IDs to `{text}`. Persist it through\n the State Store's existing resource/history contracts, not a new table,\nLine truncated
},
{
"url": "/dev/prds/state-store-contract/",
"title": "State Store — contract boundary \u0026 transport (ratification)",
"section": "PRDs",
"body": "# State Store — contract boundary \u0026 transport (ratification)\n\n**Status:** Approved\n**Revision:** 2e\n**Date:** 2026-09-06\n\nThis is the pre-implementation design document that Phase 2 subtasks `.4.2` (generalise\n`storerpc` as the State Store gRPC contract) and `.4.3` (stand up `archie-state-store`)\nimplement against.\n**Beads milestone:** archie-core-8cda.4.1\n**Parent:** `docs/prds/service-decomposition.md` (open-question Q4 **RESOLVED**)\n\nThis document fixes the **contract boundary** and **transport** for the State Store service.\nIt does not redesign Archie's domain model, does not invent a second store, and does **not**\nsplit `archie.db`. It records method ownership, DTO/wire representation, error semantics,\nlimits, mode/config shape, local-adapter compatibility, and cutover/deletion rules so that\n`.4.2` and `.4.3` have exactly one authoritative surface to build against.\n\n\u003e **Storage superseded.** The store behind this contract is PostgreSQL:\n\u003e `internal/infrastructure/postgres` implements the producer-owned interfaces in\n\u003e `internal/domain/storecontract` and `workflow.Store`, over the database\n\u003e `database_url` names. `internal/store`, the SQLite file and the local adapter\n\u003e are gone; where this document says `archie.db`, `*store.Store` or\n\u003e `internal/store`, read the State Store's PostgreSQL database and\n\u003e `internal/infrastructure/postgres`. The contract, ownership split, error\n\u003e semantics and cutover rules stand.\n\n\u003e **Current state — read before `.4.2` starts.** The §12 step 2 relocation (`archie-core-8cda.\n4.8`) has landed: `Task`/`Status*`/`Source*` and the 3-method `workflow.Store` now live in\n\u003e `internal/domain/workflow`, the six production workflow files import no `internal/store`\n\u003e symbol, and `storerpc`/the NATS transport assert against `workflow.Store` instead of\n\u003e `store.WorkflowStore`. The broader Phase 2 acceptance criterion (State Store as its own\n\u003e service behind gRPC) is still open — that is what `.4.2`/`.4.3` build next.\n\n\u003e **Relationship to migration-decisions §4 — not replaced.** `docs/architecture/\nmigration-decisions.md` §4 (`store.Task → WorkflowExecution`, `mutable Stage →\nStepExecution history`, `RetryCount/Attempt → Attempt records`, versioned Workflow defs)\n\u003e **remains the authoritative, open document for the long-term Workflow migration.** This PRD\n\u003e does **not** replace it. It only pulls the minimal `Task`/`Status`/`Source` type + interface\n\u003e relocation forward as a Phase 2 prerequisite (because the acceptance criterion requires it);\n\u003e the rest of §4 stays its own migration and stays open.\n\n---\n\n## 1. Decision (the invariant everything follows)\n\nArchie is composed such that a single **`archie-state-store`** service owns the one existing\nSQLite file (`archie.db`) and exposes it over **gRPC behind narrow typed contracts**. There is\nexactly one store, one file, one service. No database-per-service, no distributed\ntransactions, no second store abstraction.\n\nTwo adapter families satisfy the contract interfaces:\n\n- **Local adapter** — `*store.Store` (the in-process SQLite implementation).\n- **Remote adapter** — `*staterpc.Client` (wraps the generated gRPC client).\n\nEach adapter carries an explicit compile-time assertion against the contract interfaces it\nserves. Composition picks local vs. remote by the presence of `[services.state].target`\n(empty = local; set = dial the gRPC service). Default is **local** (the State Store is not yet\nextracted), which is the PRD §3 posture; it differs from the gateway's remote-default only\nbecause the gateway is already a separate deployment and the State Store is not.\n\n\u003e **Contract-ownership fork, decided (rev. 2c — resolves the domain contradiction).**\n\u003e Ownership splits by the consumer's _layer_, per the dependency contract's rule #2\n\u003e (\"a domain defines the smallest interfaces required to perform its work\") and rule #7\n\u003e (\"database rows … MUST NOT leak into domain models\"):\n\u003e\n\u003e - The **workflow domain** (`internal/domain/workflow`) is the only domain-layer consumer of\n\u003e store state. It defines its own **consumer-owned** narrow `Store` interface\n\u003e (Update/Transition/InsertEvent) and its own **domain-owned** `Task` type plus\n\u003e `Status`/`Source` vocabulary. It imports **zero** `internal/store` symbols — satisfying the\n\u003e Phase 2 acceptance criterion. This is the minimal bound of migration-decisions §4\n\u003e (`store.Task → WorkflowExecution`), pulled forward **because** the acceptance criterion\n\u003e requires it.\n\u003e - The **daemon / webui / intake** store surfaces (`TaskStore`, `CaptureStore`,\n\u003e `MappingStore`, `BindingStore`, `BindingDispatcher`, `BindingTaskCreator`) stay\n\u003e **producer-owned** in `internal/store`, because those consumers are application Line truncated
},
{
"url": "/dev/prds/status-health-surface/",
"title": "/status health surface",
"section": "PRDs",
"body": "# /status health surface\n\n**Status:** Finalised\n**Beads issue:** `archie-core-wp9s`\n\nA reported field must have a truthful source. `/status` reports broker\nconnectivity and the last chat-model call; the container pool, last poll and\nchannel state have no source in the process that answers the command, so they\nare left out rather than faked.\n\n## Background\n\n`archie-core-wp9s` (\"/status and /tasks have the wrong division of labour\")\nasked for two things: `/tasks` owning the live per-task work view, and\n`/status` owning daemon health -- \"broker connectivity, provider\nreachability, channel state, container pool, queue depth, last poll,\nversion\" -- with neither duplicating the other or static config available\nelsewhere (`/model` already lists active provider/model).\n\n## Phase 1\n\n- `/tasks`: new command, `gateway.ChatTaskSummary` extended with\n `Stage`/`Attempt`/`ParkReason`/`UpdatedAt` (all already persisted on\n `store.Task`, zero new instrumentation), sorted actionable-first.\n- `/status`: itemised per-status task counts replaced with one aggregate\n `Queue: N in flight (...)` line (running/waiting/parked only -- queued and\n terminal states excluded as not a health concern). Runtime\n (provider/model) is temporarily left in place; see \"Runtime (provider/model)\"\n under Phase 2's \"Truthful or absent\" for where that stands now.\n\nNot touched: `/agents` (`gateway.AgentReader`/`Router.Agents`) is a separate,\npre-existing command that already has the right shape for \"list active\nwork\" but is never wired to a real implementation in any composition-root\ncall site (`bootstrap.go`, `telegram_setup.go`) -- it always answers \"Agent\nlisting is not configured.\" in production. That is a standalone bug\n(`archie-core-mxls`), not folded into this work: deciding whether to wire\nit, repurpose it, or delete it in favour of `/tasks` is Sam's call, not\nsomething to resolve by implication here.\n\n## Phase 2 -- health checks, verified against the actual tree\n\nEach bullet below was checked against real code before being called cheap\nor not; nothing here is guessed. Both open questions were settled (see \"The two\ndecisions\"). The health section reports the broker connection and the last\nchat-model call; the three facts the answering process cannot see are covered\nunder \"Truthful or absent\".\n\n### Verified as cheap against the tree\n\n- **Broker connectivity.** `internal/infrastructure/eventbus/nats.Client`\n already exposes `CoreConn() (*nats.Conn, error)`\n (`client.go`). The underlying `nats.Conn` (nats.go) has its own\n `Status()`/`IsConnected()`. A `Client.Connected() bool` wrapper is a few\n lines.\n- **Container pool.** `container.Pool` already tracks `active int` under\n its own mutex (`pool.go`) but has no public accessor. A\n `Pool.Active() int` getter is a few lines.\n- **Last poll.** Nothing tracks this. The daemon's poll loop\n (`internal/daemon`) needs one `lastPollAt time.Time` field (atomic or\n mutex-guarded, matching the pool's own pattern) set at the top of each\n poll tick, with a getter.\n- **Queue depth.** Covered by Phase 1.\n\n### The two decisions\n\n- **Provider reachability is last-known outcome, never a live probe.** A chat\n command must not perform a blocking network call in its handler, and a probe\n reports the probe's reachability rather than the daemon's. `/status` therefore\n prints what actually happened -- the last chat-model call's model, age and\n error, or \"no calls attempted yet\" when there has been none. Implemented as\n `providerOutcomeRecorder`, written once in `sendChatTurn` (the single point\n every chat-model call in the process passes through) and read back by\n `newStatusHealth`. Nothing on this path dials a provider. The existing live\n model reachability check (`readiness.go`'s `modelReachProbe`) is unchanged and\n stays where it belongs: on `/health/detailed`, off the chat path.\n- **Channel state comes from the existing ChannelManager.** `/status` reads\n `status.Manager.Snapshot()` -- the same ledger the dashboard and the readiness\n probe already use -- rather than re-deriving channel health from each adapter.\n No method was added to the `Channel`/`Gateway` contract.\n\n### Phase 2\n\n- **Broker connectivity.** `internal/infrastructure/eventbus/nats.Client` gained\n `Connected() bool`, which reads the connection the process already holds. The\n standalone Gateway (which dials NATS itself for task actions) reports the same\n fact from that connection.\n- **Container pool.** `container.Pool.Active()` and `Pool.Cap()` read the pool's\n own counter and configured `max_concurrency` -- not a Docker listing, which\n would include containers this pool does not own. A cap of zero means\n unlimited, so `/status` renders the count alone rather than \"1/0 active\".\n- **Last poll.** `daemon.Daemon.LastPollAt()` reports when the most recent poll\n pass _began_; both poll paths (`poll` for sLine truncated
},
{
"url": "/dev/prds/store/",
"title": "Store",
"section": "PRDs",
"body": "# Store\n\n**Status:** Approved\n**Authority:** `docs/architecture/plugins-and-extensions.md`; supersedes\n`docs/prds/extensions-center.md`, whose installed-inventory states are\nadopted below.\n**Compounds with:** `docs/prds/external-agent-harness.md` (harness Kits),\n`docs/prds/pr-review-agent.md` (the first package).\n\n## Decision\n\nOperators get capabilities from a store: browse, install, update and remove\npackages from the dashboard, with no config file editing. A package is an\nOCI image in a registry. A store catalogue is a list of package references.\nInstalling pins a digest. Every package declares the authority it needs, and\nan update that asks for more stops for the operator's approval.\n\n## Packages\n\nTwo kinds, both ordinary OCI images:\n\n- **Harness Kits.** Kit v3 images, resolved as\n `docs/prds/external-agent-harness.md` decides. Their authority is their\n Kit permission surface.\n- **Archie packages.** An image whose manifest annotation\n `dev.archie.package.v1` carries the descriptor and whose single layer\n carries files. A package contributes any of: workflow definitions,\n prompts, skills, MCP server definitions, and default settings for them.\n\nArchie packages are declarative. They carry no Go, Yaegi or script code that\narchie executes on the host. Anything that runs code ships as a Kit and runs\nin a sandbox. An archie package that references a Kit names it by digest,\nand installing the package installs the Kit.\n\nThe descriptor declares: display name, description, version, the families\nit contributes, the packages it requires, and its authority.\n\n## Authority\n\nA package's authority is the set of grants it needs to work:\n\n- credential services (from its Kits and MCP servers);\n- egress hosts (from its Kits);\n- forge permissions its workflows use: read, comment, review, push, open\n pull request;\n- triggers it registers: watched-repository events, schedules;\n- tools it enables for agents.\n\nInstall shows this list and records the operator's acceptance against the\ndigest. An update whose authority is equal or narrower applies under the\npackage's update policy. An update whose authority is wider waits for\napproval, showing only what widened. Nothing a package does at runtime can\nexceed its accepted authority: archie checks forge actions, triggers and\ntool grants against it, and the egress proxy enforces the Kit's grants.\n\n## Catalogues\n\nA catalogue is an OCI artifact listing package references with digests,\nsigned by the catalogue's key. Archie ships with the default catalogue and\nits public key configured. An operator can add catalogues, for example a\nprivate registry, by reference and public key. A catalogue without a key is\nrefused unless the operator marks it unsigned, which the dashboard shows on\nevery package it supplies.\n\nInstall and update verify the catalogue signature and the package digest.\nArchie never installs a tag it has not resolved to a digest through a\nverified catalogue.\n\n## Organisations\n\n`docs/prds/orgs-and-access.md` is the boundary, and the store follows its\nsplit between the instance and each org.\n\n- **Instance.** Catalogues and their keys are instance configuration, set by\n instance admins. Every org browses the same catalogues.\n- **Org.** Installing, updating, removing, accepting authority and setting the\n update policy are org actions. An installed package, its pinned digest and\n its accepted authority belong to one org. Two orgs can run different\n versions of one package.\n- **Contributions** become org resources: workflows are org workflows,\n profiles are org profiles, and credential bindings name org secrets. A\n workspace uses them only once the org grants them to it.\n- **Authority is an upper bound, not a grant.** Accepting a package's\n authority permits the package to ask; the workflow's identity must still\n hold each grant. A package never creates, grants to or widens an identity.\n- Install and authority acceptance are the `create` and `approve` actions on\n the package, decided by the Authorizer. Org approval policy decides who may\n accept, and no member accepts authority they asked for.\n\n## Install, update, remove\n\n- Installed packages, their pinned digests, accepted authority and update\n policy are org resources in the State Store. They apply without a restart.\n- **Update policy** per package: `manual` (default) or `auto`. `auto` applies\n non-widening updates when the catalogue lists them; widening updates always\n wait.\n- **Setup.** A package whose authority includes a credential with no binding\n installs as `needs_setup`, and links to the binding form or the harness\n setup terminal. Its triggers do not fire until setup completes.\n- **Remove** stops its triggers, removes its contributions, and leaves any\n credential bindings for the operator to delete. A package another\n installed package requires cannot be removed first.\n- Rolling back reinLine truncated
},
{
"url": "/dev/prds/task-logs-pagination/",
"title": "task_logs pagination and bounded retrieval -- decision",
"section": "PRDs",
"body": "# task_logs pagination and bounded retrieval -- decision\n\n**Status:** Approved\n**Date:** 2026-08-26\n**Beads issue:** `archie-core-vq92`\n**Compounds with:** `archie-core-p1bl` (errors serialise as `{}`)\n\n## Decision\n\n`task_logs` becomes a _cursor-paginated, filterable_ bounded read, not a\none-shot head-of-file window. The reader in `internal/logging` gains a\nsecond entry point (`Page`) that walks the file forward from a byte\noffset; the tool schema in `internal/gateway/task_tools.go` surfaces\nlevel, time-range and cursor parameters; the response carries an explicit\n\"more available\" signal so a model can either keep paging or hand the\nrest to `send_file` when the operator wants a complete archive.\n\nWe do NOT add an unbounded read path. A single response is still capped at\n`MaxTailLines` (2000) entries. What changes is that pagination makes the\ncap reachable in practice instead of silently terminal.\n\n## Why now\n\n`archie-core-vq92` is the right place to fix this: the chat tool is the\nuser-visible failure mode, but the same defect propagates to every caller\nof `internal/logging.Tail` (`internal/webui/api_logs.go` and the\n`chatTaskLogReaderAdapter` in `cmd/archied/main.go`). Patching the\nreader and the tool together is one change in two layers, not two\nchanges; CLAUDE.md's \"package owns its format end-to-end\" rule means the\nreader is the right place for cursor support regardless.\n\nThe compound with `p1bl` matters: a truncated window of uninformative\nerrors leaves an operator with nothing. Cursor pagination lets the model\nwalk the whole file when a level filter does not narrow enough, and the\nresponse's \"more available\" signal means it can honestly say \"I read N of\nM and stopped there\" instead of presenting the head as complete.\n\n## Shape of the API\n\n### Reader (`internal/logging`)\n\nAdd a second entry point next to `Tail`:\n\n```go\n// Page walks the log forward from cursor (a byte offset; 0 starts at\n// the beginning of the scanned window), applying the same filters as\n// Tail. PageResult.Cursor is the file offset just past the last line\n// the walk returned; pass it back as Cursor to continue, and stop when\n// MoreAvailable is false.\nfunc Page(path string, q Query, cursor int64) (PageResult, error)\n```\n\n`PageResult` carries `Entries`, `Truncated` (the existing meaning --\nolder entries exist that were not examined within `maxScanBytes`),\n`Cursor` (the byte offset the next page should resume from), and\n`MoreAvailable` (true iff the scan saw more matching entries beyond the\nreturned page within the same call).\n\n`Cursor` is a byte offset rather than an entry ID for two reasons.\nFirst, `TaskSink` writes JSONL through `slog.NewJSONHandler` directly --\nwithout routing through `FeedHandler` -- so the on-disk entries carry no\n`id` field and a per-task attempt monotonic counter would require\neither a sink-side change or a reader-side reconstruction that is\nbrittle against rotation. Second, the byte offset uniquely identifies\n\"the next unread position\" in a sequential scan, which is exactly what\nthe call pattern needs. A cursor that points at or past the file's\ncurrent size is treated as end-of-stream (empty page, `MoreAvailable`\nfalse).\n\nThe implementation is `readWindow` (reads the tail-most `maxScanBytes`\ninto a single in-memory buffer) plus `readLines` (clamps the cursor into\nthe window, drops a partial first line on the size-cap seek, then\ndelegates) plus `walkWindow` (walks the buffer line-by-line by exact\nslice offset). Offsets are into one contiguous buffer, so they are\ntrivially correct -- unlike an incremental reader over the file, whose\n`bufio.Reader` buffer-ahead would make its underlying file position\nunusable as a cursor.\n\n`Tail` is NOT a wrapper over `Page`: it keeps its legacy ring-buffer\nsemantics (newest `Limit` matches, oldest dropped, `Truncated` set on\nring overflow). They share `readWindow`/`walkWindow` but stay separate\nentry points precisely so Tail's established behaviour is unchanged.\n\n### `Query` gains two optional fields\n\n```go\nSince time.Time // inclusive lower bound on entry.Time\nUntil time.Time // inclusive upper bound on entry.Time\n```\n\n`Levels`, `Component`, `Contains`, `Limit` are unchanged. The existing\nfilter logic and tests move unchanged.\n\n### Tool schema (`internal/gateway/task_tools.go`)\n\n`ChatTaskLogQuery` gains three fields:\n\n- `Level []string` (forwarded to `Query.Levels`)\n- `Since time.Time` / `Until time.Time` (forwarded as `Query.Since/Until`)\n- `AfterID int64` (the cursor; 0 to start at the beginning)\n\n`ChatTaskLogResult` gains two fields:\n\n- `Cursor int64` -- highest ID in this page; pass back as `AfterID` to continue\n- `MoreAvailable bool` -- true iff the scan saw more matching entries that\n did not fit in this page\n\nThe tool description is updated to teach the model the pagination\nprotocol in one sentence: \"pass the previous `cursor` back as `Line truncated
},
{
"url": "/dev/prds/task-run-detail/",
"title": "Per-run task detail: attempts, stages, changes, config, debug",
"section": "PRDs",
"body": "# Per-run task detail: attempts, stages, changes, config, debug\n\n**Status:** Approved\n**Authority:** the surface contract itself is\n`docs/architecture/observability.md`.\n**Date:** 2026-09-18\n**Compounds with:** `docs/prds/task-logs-pagination.md` (a bounded read says\nwhat it does not show), `docs/prds/status-health-surface.md` (no surface that\nanswers something already answered elsewhere).\n\n## Decision\n\nA task gets one detail page that answers \"what did this run actually do?\" per\n**attempt**: an ordered stage rail, the change each commit/push produced, the\neffective configuration the attempt ran under, the attempt's log, and the raw\nrecord behind all of it.\n\nThe single organising idea is **attempt attribution**. The dashboard\nrenders a task's whole event stream as one flat timeline, so a retried task\nreads as one long run with two of everything. Every new panel is scoped to one\nattempt and says which one.\n\nThe second organising idea is **provenance, not re-derivation**. What a run\nproduced is captured at the producer, while the evidence exists, and persisted\ndurably. Nothing in this surface tries to reconstruct a past run from state\nthat has since moved on.\n\n## The requirement set\n\n| # | Requirement | Mechanism |\n| --- | --------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------- |\n| 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` |\n| R2 | Events carry an attempt, migrated safely and carried on the wire | `events.attempt` column + presence-gated migrator arm; `Event.attempt = 11` |\n| 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` |\n| 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 |\n| 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 |\n| 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 |\n| R7 | Raw JSON of the task record and its events for the selected attempt | `GET /api/tasks/{id}/debug` |\n| 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=...` |\n| R9 | Design polish: hierarchy, tokens, both themes, responsive rail, a11y, loading/empty/error states | UI lane; measured at 480px and 700px in both themes |\n| R10 | Documentation of record | This document plus `docs/architecture/observability.md` |\n| 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 |\n\n## Attempt attribution: a column, not a guess\n\n`events.Event.Attempt`, persisted as the `events.attempt` column\n(`internal/infrastructure/postgres/migrations/0001_state_store.sql`), is a real column,\n`NOT NULL DEFAULT 0`. It was chosen over segmenting the stream on `task_queued` /\n`task_retried` because a fold would have to guess which side of a boundary an\nevent belongs to when the daemon restarts mid-attempt, when `RecoverStale`\nrequeues, or when two attempts interleave across a crash. A guess rendered as\nstrucLine truncated
},
{
"url": "/dev/prds/task-run-master-detail/",
"title": "Task run detail as a master-detail split pane",
"section": "PRDs",
"body": "# Task run detail as a master-detail split pane\n\n**Status:** Approved\n**Authority:** the panel contracts stay as ratified in\n`docs/prds/task-run-detail.md`; this document changes only the run page's\narrangement of them.\n**Compounds with:** `docs/prds/task-run-detail.md` (attempt attribution, the\nlog stage filter, the per-panel honesty rules).\n\n## Decision\n\nThe run page's five tabs become two panes. The stage rail is the **master**,\nalways visible on the left. The four context panels — log, changed files,\nconfiguration, debug — are the **inspector** on the right, and their tab bar\nmoves into the inspector. The \"Stages\" tab stops existing.\n\nSelecting a stage switches the inspector to the log tab and sets the log\npane's stage filter to that stage. Changing the filter afterwards is the\noperator's choice and is not overridden; rail selection never touches the\nlevel filter. Clicking the selected stage again returns the filter to all\nstages. A stage with no name is rendered but not selectable.\n\nSwitching attempts resets the stage filter to all stages: a selection was\ncommanded on the attempt it was made on, and a different attempt presents a\ndifferent stage list. Changed files, configuration and debug stay\nattempt-scoped; a stage selection never scopes them.\n\n## What does not change\n\n- No new endpoint, RPC, table or configuration field. Every read is one the\n page already makes.\n- The URL contract: `tab` and `attempt` ride in the query string and survive\n a reload. Log filters are not part of the URL; a reload returns the log to\n all stages. `tab=stages` stays a valid URL and renders the log tab; the\n page never generates it again.\n- Attempt attribution, the log stage filter's coverage limit and every\n honesty rule in `task-run-detail.md` still apply: each pane states what it\n cannot show under that document's rendering rules.\n- The task header and the attempt selector sit above both panes.\n\n## Arrangement\n\n- Left pane: fixed-width rail (20rem) with the attempt's stage rows. Status,\n duration, error, the stage's agent report, the attempt's status badge and\n start time, and the attempt-attribution footnotes render in the rail.\n- Right pane: the inspector's tab bar plus the selected panel, filling the\n remaining width.\n- Below the shell's 900px frame breakpoint the rail stacks above the\n inspector; neither pane is hidden.\n- Keyboard: the rail keeps its list semantics and each stage row is a real\n button, so selection and deselection work without a pointer; the inspector\n keeps the WAI-ARIA tabs pattern the tab bar already provides.\n\n## Acceptance\n\n1. The rail is visible without opening any tab, and no \"Stages\" trigger exists.\n2. Clicking a stage opens the log filtered to that stage; clicking it again\n shows all stages.\n3. After a stage selection, a filter change made by the operator is kept, and\n the level filter survives the selection.\n4. Switching attempts resets the stage filter to all stages, and no rail row\n on the new attempt renders as selected unless the operator selected it\n there.\n5. `tab=stages` loads and renders the log tab.\n6. Every inspector tab and attempt deep-link survives a reload.\n7. A stage is selectable and deselectable by keyboard, and the selection\n mirrors the log pane's stage filter.\n8. Below 900px the rail stacks above the inspector.\n9. `task check` passes clean and `ui/dist` matches the sources.\n"
},
{
"url": "/dev/prds/ui-service-boundary/",
"title": "UI Service boundary and configuration ownership",
"section": "PRDs",
"body": "# UI Service boundary and configuration ownership\n\n**Status:** Approved\n**Revision:** 1\n**Date:** 2026-09-07\n**Beads issue:** `archie-core-8cda.5.1`\n**Parent:** [`service-decomposition.md`](/dev/prds/service-decomposition/)\n**Prerequisites:** Gateway contract extraction and State Store contract ratification\n\nThis document is the authority for Phase 3 UI Service implementation. It fixes\nthe process boundary, configuration ownership, client contracts, security\nposture, readiness behaviour, and migration evidence required by\n`archie-core-8cda.5.2` and later UI extraction work.\n\n## Decision\n\nThe UI Service owns the operator-facing HTTP surface and the compiled SPA. It\nserves `ui/dist` and exposes UI-specific JSON DTOs for dashboard views and\nactions. It does not own conversations, task state, workflow execution,\nchannel lifecycle, forge access, or the daemon's runtime configuration.\n\nThe UI Service consumes two typed remote capabilities:\n\n- Gateway's `gateway.ChatContract` through the versioned Gateway gRPC\n contract, for chat snapshots, messages, turns, streaming, persona changes,\n cancellation, and Gateway task actions.\n- State Store's narrow read/write contracts through the versioned State Store\n gRPC contract, for task views, events, captures, mappings, bindings, and\n configuration data explicitly projected for the dashboard.\n\nThe UI process may compose local adapters during the migration seam, but the\nadapter implements the same wire-safe contract as the remote client. The\nproduction extraction cutover removes the in-process adapter in the same\nchange; a dual-live UI authority is not permitted.\n\n## Boundary and ownership\n\n| Concern | UI Service owns | UI Service may consume | UI Service must not own or receive |\n| ------------------ | -------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------ |\n| HTTP and SPA | routes, auth middleware, UI DTOs, assets, HTTP lifecycle | contract results and health snapshots | domain entities or infrastructure handles |\n| Chat | request validation and response projection | Gateway `ChatContract` | `gateway.Router`, `SessionStore`, turn runner, model/provider runtime |\n| 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 |\n| 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 |\n| Readiness | UI process liveness and dependency readiness aggregation | bounded health results from Gateway and State Store | direct probing of private databases or providers |\n\nEvery value crossing the process boundary is a versioned DTO or scalar contract\nvalue. `internal/webui` may retain temporary Go-side adapters while the\nmigration is in progress, but handlers must map Gateway/State Store values to\nUI-owned response types at the HTTP edge. A constructor accepting a concrete\nGateway, State Store, daemon, or `config.Holder` is not an approved final\nboundary.\n\nThe existing UI routes remain behaviourally compatible during extraction,\nincluding task actions, SSE event delivery, config views, chat streaming,\ncapture intake, mappings, bindings, update reporting, and health endpoints.\nCompatibility preserves status codes, authentication requirements, redaction,\npagination/limits, event ordering, and failure degradation unless a separately\nratified contract changes them.\n\nThe route families have these target owners. This is the required inventory for\nthe implementation children; a route without an owner is not eligible for\ncutover.\n\n| Route family | Target owner consumed by UI | Migration status Line truncated
},
{
"url": "/dev/prds/vue-migration-checklist/",
"title": "Preact → Vue 3 + shadcn-vue migration checklist",
"section": "PRDs",
"body": "# Preact → Vue 3 + shadcn-vue migration checklist\n\n**Status:** Approved\n**Date:** 2026-09-20\n**Bead:** `archie-core-tavn` (epic), `archie-core-ocfm` (navigation restructure)\n**Bootstrap commit:** `e18fb8b2`\n\nThe Preact dashboard was deleted, not ported incrementally. This is the list of\nwhat has to exist again, what must not be lost on the way, and the contracts\nthat break silently if missed.\n\nDeleted source is recoverable at `git show e18fb8b2^:ui/src/\u003cpath\u003e`. Every\nclaim below was cross-checked against that tree; where a number is a live\nmeasurement rather than something recoverable from git, it says so.\n\n## Invariants that outlive the framework\n\nThese are not features; they are things other processes depend on. Breaking one\ndoes not show up as a broken page.\n\n- [ ] **Embed contract.** `ui/embed.go` embeds a committed `ui/dist`. The build\n must keep unhashed `assets/index.{js,css}`: dist/ lives in git, and\n hashed names orphan a file on every rebuild.\n- [ ] **Route registry.** `internal/gateway/dashboard_tools.go` hand-copies the\n route table and `TestDashboardPagesRegistryCoversEveryRoute` parses\n `ui/src/router/index.ts` to hold them in step. The parser needs\n `const routes = [` on its own line, `path: \"...\"` on a single line per\n route, and `nav: false` on any entry the registry should skip. That guard\n caught a stale `/chat` entry earlier.\n- [ ] **Mutation headers.** Every POST/PATCH/DELETE must send **both**\n `X-Archie-CSRF: 1` and `Content-Type: application/json`. The server\n returns 403 without the first and 415 without the second\n (`internal/webui/api_tasks.go`, `authorizeTaskMutation`). GET sends\n neither. This is the single most likely thing to silently break every\n write after the port.\n- [x] **History routing.** `createWebHistory`, `base: \"/\"`. Legacy `#/path`\n links are rewritten by `src/legacy-hash-redirect.ts`. The chat navigate\n chip should emit `/tasks`; the Go side already stores bare paths.\n- [ ] **Capability gating.** `GET /api/capabilities`\n (`internal/webui/api_capabilities.go`) returns a `sections` map of ten\n booleans: chat, logs, skills, curators, channels, captures, mappings,\n bindings, and workflows/settings which are always true. A route whose\n section is false must be hidden, not rendered empty. **Fail open**: on a\n failed or null response hide nothing — the old client used a bare\n `.catch(() =\u003e {})` for exactly this. A page that says \"unavailable\" is\n recoverable; a nav entry that vanished is not.\n- [ ] **`LOG_LEVELS`** in `base/log-row.jsx` is a wire contract, not a display\n list: the CSV level filter is matched server-side by `splitCSV` in\n `internal/webui/api_tasks_logs.go`. A value mismatch breaks filtering\n with no error.\n- [ ] **SSE lifecycle.** Three streams, all `id: \u003cn\u003e\\ndata: \u003cjson\u003e\\n\\n` except\n chat which omits the id:\n `/events` (task lifecycle, `sse.go`, supports `?since=` and\n `Last-Event-ID` resume), `/api/logs/stream` (`api_logs.go`, same\n resume protocol), `/api/chat/stream` (`api_chat.go`, frames typed\n delta/tool/media/navigate). Each must be closed on unmount or the app\n leaks a connection per navigation. Preact used an `archie:teardown`\n event; Vue should use `onUnmounted`.\n\n\u003e **On tests.** Per Sam's call, the 43-file suite was not ported and tests\n\u003e return when there is behaviour worth pinning. Flagging one exception for when\n\u003e that moment comes: the deleted `ui/test/api-client.test.js` classified every\n\u003e API method as mutation/read/stream/url and asserted the right headers per\n\u003e class. It is the only cheap guard on the CSRF contract above. (It did **not**\n\u003e text-scan for a second `fetch()` — that check was deliberately removed\n\u003e upstream for testing the file's wording rather than its behaviour.)\n\n## Phase 1 — Foundation\n\n- [x] **Theme.** `css/tokens.css` was a complete two-theme semantic token set\n (`--fg-subtle`, `--accent`, `--ok/warn/danger`, surfaces, shadows). Mapped\n onto Tailwind v4's `@theme` in `src/style.css`; the second system was not\n kept.\n- [x] **`color-scheme`.** `[data-theme=\"dark\"] { color-scheme: dark }` and the\n light equivalent. Without it the UA paints light scrollbars and light\n native controls inside the dark app. Fixed; trivially lost.\n- [x] **Contrast values.** The violet palette moved these off the values pinned\n here, so they were recomputed against its own backgrounds instead of\n carried: `--fg-subtle` `#A99DBD` dark (7.67:1, AAA) / `#6E6577` light\n (4.87:1, AA), and `--fg-muted` `#B9AECB` / `#635B6B` (9.28:1 and 5.70:1).\n The invariant the pin existed for holds; the values are the palette's.\n- [x] **API client** (`base/api.jsx` → `src/lib/api.tLine truncated
},
{
"url": "/dev/prds/webhook-intake-security/",
"title": "Webhook intake security -- decision",
"section": "PRDs",
"body": "# Webhook intake security -- decision\n\n**Status:** Approved\n**Date:** 2026-08-22\n**Beads issue:** `archie-core-t2db.5`, blocks `archie-core-t2db.4`\n\n## Why this is decided ahead of the code it constrains\n\n`archie-core-t2db` (no-code playbooks) and `archie-core-7d5u` (typed event\nsources) both land a public intake surface whose eventual output is an agent\nwith tool access and a repo. Neither capture (`t2db.1`) nor the intake family\n(`7d5u.3`) has shipped yet, so this decision exists to be a contract the two\nepics build against, not a retrofit once the surface exists. A webhook URL\nthat can start an agent is remote code execution with extra steps if any of\nthe five points below is missing on day one.\n\n## 1. Per-source authentication\n\nReuse the per-route HMAC-SHA256 scheme already in\n`internal/channels/webhook/webhook.go` (`validateHMAC`), unchanged: a source\nregisters with a shared secret; the signature is checked against the raw\nbody. Do not invent a second scheme for intake.\n\n**Capture and triggering split at the signature, not at a separate flag.** An\nevent with a missing or invalid signature is still captured (visible in the\ninspector, marked unauthenticated) so an operator can diagnose a\nmisconfigured sender -- but an unauthenticated event can never be matched\nagainst a binding. Authentication is what promotes an event from \"something\narrived\" to \"something that can run a workflow.\"\n\n## 2. Human approval before a binding arms\n\nA binding has three states: `draft -\u003e pending_approval -\u003e armed`. Only\n`armed` bindings are evaluated against incoming events. Creating or editing a\nbinding's matcher, mapping, or target workflow always sets it to\n`pending_approval`, including edits to an already-armed binding -- an edit is\nnot silently re-armed, or the approval gate is decorative. Approval requires\nan authenticated dashboard session; there is no unattended approval path.\n\nModel: `internal/channels/telegram`'s dangerous-command approval flow\n(`dangerousAction` / `pendingApproval` in `dangerous.go` / `approval.go`) is\nthe existing precedent for \"a human decision gates code from running\" in this\ncodebase -- follow its shape rather than designing a new approval primitive.\n\n## 3. Rate and volume limits, per source\n\nA token-bucket limiter keyed by source ID, not global -- one noisy or hostile\nsender must not exhaust another source's capture budget. Precedent for\nper-key volume capping: `internal/pairing/store.go`'s `MaxPendingPerPlatform`.\n\nOn limit exceeded, the request is rejected (HTTP 429), not silently dropped.\nA silently dropped event is indistinguishable from a sender that never fired\n-- the same invisible-failure shape the update-verification work\n(`archie-core-522`) exists to prevent. The rejection itself is observable in\nthe inspector as a distinct outcome from \"not received.\"\n\n## 4. Blast radius bounded by code, not by prompt wording\n\nA playbook-triggered task runs through exactly the same enforcement as every\nother task: the `[[repos.gate]]` quality gate, `diff_cap_lines`, the\nsandboxed per-task container (`internal/container`), worktree isolation, and\n\"the model never runs git.\" No new relaxation is introduced for\nplaybook-triggered work, and none is needed -- the existing constraints are\nthe control.\n\nMapped payload fields are treated as ordinary user-controlled text inside an\nagent prompt, exactly like an inbound chat message never as trusted\ninstructions. \"The agent should ignore instructions in the payload\" is not a\ncontrol and must not appear as one anywhere in this feature -- per the\nenvironmental-enforcement principle (`docs/architecture/agent-system.md`,\n\"Existing invariants to preserve\"), the boundary is the gate and the sandbox,\nnot a sentence in the system prompt.\n\n## 5. Retention and redaction of captured payloads\n\n**Retention:** captured events (bound or not) are purged after 7 days,\nconfigurable per deployment. Unbound events exist to be mapped against; nothing\njustifies keeping them indefinitely once that window has passed, and an\nunbounded capture store is the same disk-exhaustion risk item 3 addresses at\nthe request-rate level.\n\n**Redaction:** before a captured payload is persisted, apply the same\nkey-name heuristic `internal/gateway/stream.go`'s `sensitiveParameterKey`\nalready uses for tool-call parameters (matches `token`, `secret`, `password`,\n`passwd`, `api_key`, `apikey`, `authorization`, `credential`, `cookie`,\n`private_key` against normalised JSON keys) and replace matching values with\nthe same `[redacted]` marker. This is best-effort, not a guarantee -- a\nsender that names a secret field something the heuristic misses will still\nhave it captured. Document that limitation where captured payloads are\ndisplayed, rather than implying the redaction is complete.\n\n**Visibility:** captured payloads, redacted or not, are visible only to an\nauthenticated dashboarLine truncated
},
{
"url": "/dev/prds/workflow-call-outputs/",
"title": "Declared outputs of a workflow run",
"section": "PRDs",
"body": "# Declared outputs of a workflow run\n\n**Status:** Draft\n**Date:** 2026-09-30\n**Bead:** `archie-core-t2db.43`\n**Authority:** `docs/prds/event-automation.md` for what a declared output is,\n`docs/prds/workflow-calls.md` for the call and its grants,\n`docs/prds/state-store-contract.md` for the State Store contract the wire\nchange must satisfy.\n**Supersedes:** `docs/prds/workflow-calls.md`, \"Waiting on the callee\": the\ncallee's transition detail is the human summary, not the stand-in for\nstructured outputs.\n\nA workflow declares named, typed outputs. A run writes each one once. A\n`wait: true` caller receives them, and may publish one as its own.\n\n## Where outputs are declared\n\n`outputs:` on the workflow definition, beside `inputs:`, decoded into\n`task.WorkflowInterface.Outputs map[string]OutputSpec` where\n`OutputSpec{Type, Required}`:\n\n```yaml\nid: firewall-contain\noutputs:\n contained: { type: bool, required: true }\n summary: { type: string }\n```\n\nNames and types are the input grammar: the same identifier shape, the same\ntype set, and the same check in `WorkflowInterface.Validate`, which both\n`ParseDefinition` and `ParseWorkflowInterface` call.\n\n**Forced by:** `ParseDefinition` decodes with `KnownFields(true)`, so a key no\ndecoded struct declares is refused — the declaration must live on\n`WorkflowInterface` for an author to write it at all, and that is where\n`docs/development/workflows.md` puts every field a process without the engine\nmust read. The type set is the shared value vocabulary: `TypeAccepts` and\n`ValueType` already check a mapped parameter and an input with it. `required`\ndefaults to false, and the generated YAML for a builtin that declares no\noutputs is unchanged, because a definition's digest pins a run.\n\n**Rejected:** outputs per step, or per call step, because a workflow returns a\nresult as itself rather than as one of its stages. Also `task.Definition`\ngaining outputs: no reader needs them — a binding offers inputs, and a call's\noutputs assignment is checked against the callee's YAML in the same\ncollection — and a declared field with no reader parses and does nothing.\n\n## How a run writes one\n\nEach declared output is offered to the run's agent stages as a capture tool\nnamed after the output, whose arguments are `{\"value\": ...}`; the accepted\ncall's `value` member is the output's value. The engine holds the accepted\nvalues on the task context and writes them into its own task row in the\n`Store.Update` call the run already makes. A deterministic stage may set the\nsame values in Go, and the run's finish check validates them identically.\n\n**Forced by:** a run's only structured results are capture calls\n(`agentexec.CaptureTool`, `Result.Captures`), and the workflow interface\nalready declares when a stage needs them (`task.WorkflowNeeds.Captures`).\n`WorkflowInterface.Needs` reports `captures` for a non-empty `Outputs`, so\ndeclaring an output alone requires the capability and a Kit profile that\nserves no capture tools is refused before dispatch.\nDeriving the tools from the declaration means an output cannot be written\nunder a name nobody declared, and it keeps one route to structured agent\noutput rather than adding a second beside the capture path. The row write is\nthe run's existing write: the task row is where a run's own state lives, and\nthe container already holds `Update` on its own row.\n\nThe tool is offered with `MaxCalls: 1`, and a stage is not offered an output\nthe run has written, so a run writes each output once: a repeat within a stage\nis answered with the tool's rejection and the agent carries on, and a later\nstage cannot overwrite a value. A stage's own capture tool may not share a\nname with a declared output, because the value would otherwise be ambiguous.\n\n**Rejected:** a `workflow.output` step type, because assigning the run's\nresult from a step needs a grammar for \"the previous stage's result\" that does\nnot exist, and a step that reaches the agent would be the second path\n`docs/development/workflows.md` forbids. Also a write RPC of its own: the\ncontainer's `Update` already reaches its own row, and a second write verb for\none column is a second thing to keep in step.\n\n## How a caller receives one\n\nOn a successful `wait: true` call the caller's stage holds the callee's\noutputs as a `map[string]any`. A call step's `outputs:` setting publishes one\nas one of the caller's own outputs:\n\n```yaml\nsteps:\n - type: workflow.call\n workflow: firewall-contain\n wait: true\n inputs: { src_ip: inputs.src_ip }\n outputs: { contained: outputs.contained }\n```\n\nThe key names the callee's declared name; the value names one of the caller's\nown with the prefix the call's `inputs:` already uses. A published value joins\nthe caller's output set for its run, so a caller returns its callee's result to\nits own caller, and a run may publish a callee's output and write its own\notheLine truncated
},
{
"url": "/dev/prds/workflow-calls/",
"title": "Workflows calling workflows",
"section": "PRDs",
"body": "# Workflows calling workflows\n\n**Status:** Draft\n**Date:** 2026-09-26\n**Bead:** `archie-core-t2db.41`\n**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)\n\n## The call, end to end\n\n```\ncaller run (in agent container)\n workflow.call step ──StartCall──▶ State Store EnqueueCallTask(caller, workflow, inputs)\n │ callee task row: org/identity/owner/repo\n │ derived from the caller row server-side\n ▼\n callee task (queued, org of the caller)\n │ daemon claims, pins the callee's OWN\n │ definition → its OWN agent profile\n ▼\n callee run (its own container, own tree)\n wait: true ──poll──▶ State Store WorkflowCallStatus(caller, callee)\n wait: false ──continue\n```\n\nA `workflow.call` step starts the callee as a first-class task and, with\n`wait: true`, waits for its terminal state. The callee is never run \"inside\"\nthe caller: it gets its own task row, its own pinned definition, its own\nprofile, its own container, and its own outcome on its own run\n(`execution-tree-state-machine.md`).\n\n## Save-time checks (the collection is the authority)\n\nAll semantic checks run in `workflow.ValidateDefinitionCollection`, the gate\nevery save and load of the `workflow-definitions` resource passes through.\nA single-definition parse cannot see callees, so it validates shape only.\n\n- **Callee exists.** A call to a workflow outside the collection is refused.\n- **Inputs checked.** A call value is a literal or a reference\n (`inputs.\u003cname\u003e`) to the calling workflow's declared input. References must\n name a declared input; the resolved type must satisfy the callee's declared\n type; unknown callee inputs are refused; a required callee input must be\n assigned.\n- **Self-calls refused.** The call graph over the collection is walked from\n every workflow; a workflow that reaches itself, directly or through other\n workflows, is refused with the cycle path. (Cycles can otherwise deadlock:\n `wait: true` callers hold their containers.)\n- **Repository.** `workflow.call` needs no repository, so it is legal in a\n `repository: none` workflow: the callee inherits the caller's task record\n (owner/repo/identity/org), and the callee's own `repository` mode decides\n whether its run clones.\n- **Org enablement** (bead `archie-core-t2db.42`): the single\n instance-wide collection the current model serves is what \"enabled for\n the caller's org\" resolves against — an undefined callee parks. The\n callee's org is derived from the caller's row, so a callee is never\n visible outside its caller's org. The per-org enable/disable catalogue\n lands with `archie-core-t2db.42` and becomes the one source of this\n predicate.\n\n## Runtime\n\n**Depth limit.** `workflow.MaxCallDepth` (5). The calling stage refuses a call\nthat would exceed it; the store re-checks on insert (callee depth = caller\ndepth + 1), so no path can enqueue past the limit.\n\n**Starting the callee.** The caller runs inside a container whose task-scoped\nState Store grant authorizes only `Update`/`Transition`/`InsertEvent` on its\nown task — it can neither enqueue a task nor read another one. One new\ncontract RPC starts the callee:\n\n- `EnqueueCallTask(caller_task_id, workflow, inputs_json) → task`\n — the store reads the caller row, refuses a caller that is not `running`,\n refuses past the depth limit, and inserts the callee row deriving org,\n workspace, identity, owner, repo and a fresh synthetic issue number from\n the caller (the same org COALESCE `EnqueueIssue`/`InsertChatTask` use). The\n callee row carries `call_parent_task_id` and `call_depth`.\n\n**Waiting on the callee.** One new read RPC returns a call's callee:\n\n- `WorkflowCallStatus(caller_task_id, call_task_id) → (status, detail)` — the\n handler verifies `call_parent_task_id` matches, so a caller reads only its\n own callees, and returns the callee's status plus its latest transition\n detail (the callee's summary — the wait:true \"outputs\" until a structured\n outputs model lands).\n\nBoth RPCs are admitted to task-scoped grants on `caller_task_id == granted\ntask ID` (`authorizesTaskScopedCall` gains two request-shape cases). This is\nthe one sanctioned widening of a task grant: the callee is the caller's child,\nand starting it is the mechanism by which one event becomes several runs. The\nwidenings stay request-shape checks; the parent-child authorization is a\nhandler-side row check, so the interceptor never reads the database.\n\n**Schema.** `tasks` gains Line truncated
},
{
"url": "/dev/prds/workflow-step-vocabulary/",
"title": "Workflow step vocabulary: what a step type is and how binaries agree on it",
"section": "PRDs",
"body": "# Workflow step vocabulary: what a step type is and how binaries agree on it\n\n**Status:** Draft\n**Date:** 2026-09-29\n**Beads:** `archie-core-m7oc` (agreement between separately deployed binaries), `archie-core-ze7y` (the deleted `.archie/stages/*.go` equivalent)\n**Extends:** `docs/architecture/plugins-and-extensions.md` (plugin engine rule), `docs/prds/event-automation.md` (the workflow model step types serve)\n\n**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.\n\n## Decision\n\nA workflow step type is a named Go factory: the word a YAML workflow writes in\na step's `type` field, plus the factory that builds its stage. The name is a\nstable identifier; the identity also declares what plugin family claims it,\nso a contribution that shadows a shipped stage is refused instead of\noverriding it.\n\nThe Workflow domain owns the typed family contract — `StepTypeProvider` for a\ncontribution and `Manager` as the owning registry. A provider contributes a\nwhole set of step types under its own stable-identifier name; the manager\nvalidates the entire contribution before applying any of it (named provider,\nwell-formed step-type names, non-nil factories, no step type claimed twice,\nno claim on a name another provider holds) and applies it atomically. The\ngeneric `plugin.Plugin` contract stays metadata-only.\n\nThe vocabulary is a compiled-in, closed set. `internal/infrastructure/workflowsteps`\nis the one place a step type is bundled into any binary that resolves one: the\nshipped workflow stages, the repository-hook replacements (`gate.diff-rules`)\nand the repository-free event steps each arrive as one provider, and adding a\nstep type means adding a provider to that set. Interpreted plugin sources\ncannot contribute step types: the Yaegi plugin host satisfies only the\nmetadata contract, and no bridge to `StepFactory` exists.\n\nEvery binary that resolves a step type builds its manager from that same\nprovider set at its composition root, before its first resolution, and\ninjects the manager everywhere it resolves definitions. Agreement is per\nbuild: the State Store, the daemon's workflow-definitions client and the agent\nworker built from the same source register identical vocabularies by\nconstruction; binaries built from different sources can disagree, and only a\nmatching deploy fixes that.\n\nAn unknown step type is refused twice, and never degraded. The validator\n`ParseDefinition` refuses a definition naming an unregistered type at save\ntime, on the validating side the composition root built (the State Store's\nworkflow-definitions resource validates there before anything is stored). The\ncompiler refuses the same definition at run, so a binary handed a definition\nwritten against a vocabulary it does not have fails that run loudly instead of\nsilently skipping steps. Both checks live in the Workflow domain against the\ninjected manager, which is why no binary can opt out of the check by\nsubstituting its own registry.\n\n## Relationship between the questions\n\n`archie-core-ze7y` is the same question seen from the deleted\nrepository-authored stages: those `.archie/stages/*.go` files held arbitrary\nstages, and their gate half landed as `gate.diff-rules` settings rather\nthan interpreted Go. No interpreted-Go stage type is built, and nothing\napproximates one: the maintainer's trust decision (`archie-core-ndm8`) allows a\ncommand step type instead, and it arrives as a provider in the compiled-in set\nunder the rules above — a new contributor of exactly one step type at a named\nprovider (`command.run`, contributed by `command`). It is not a plugin\ncontribution mechanism and it changes no other answer in this document. The\nrefusal of `.archie/stages/*.go` therefore names `command.run` as its migration\ntarget, and each command it runs is the operator's own repository policy\nexpressed as argv.\n\n## Rejected alternatives\n\n- **A vocabulary version or hash on the wire.** The executing side already\n refuses an unknown step type at its first compile, which is the mismatch\n detector, and it fails closed. A wire field would only narrow the\n deploy-skew window that a matching deploy closes, at the cost of a new\n contract field.\n- **A Yaegi-plugin-to-`StepFactory` bridge.** It would run repository-supplied\n interpreted code inside the daemon's process with daemon privileges. The\n trust boundary invariant requires repository-authored code to run in the\n task container, not in an interpreter embeddable into any binary.\n- **A package-level process-global registrar.** Global mutable registry state\n is unreadable at the composition root, collides with itself when one\n process builds the vocabulary twice, and is what made the first attempt at\n this question worse instead of better.\n- **Degrading on an unknown step type.** A run that Line truncated
}
],
"nav": [
{
"title": "Architecture",
"url": "/dev/architecture/",
"items": [
{
"title": "Agent System",
"url": "/dev/architecture/agent-system/"
},
{
"title": "Playbook bindings: model and threat model",
"url": "/dev/architecture/bindings/"
},
{
"title": "Configuration",
"url": "/dev/architecture/configuration/"
},
{
"title": "The dashboard's tools for an in-browser agent",
"url": "/dev/architecture/dashboard-agent-tools/"
},
{
"title": "Dependencies and Contracts",
"url": "/dev/architecture/dependencies-and-contracts/"
},
{
"title": "Generated Documentation",
"url": "/dev/architecture/generated-documentation/"
},
{
"title": "Identity",
"url": "/dev/architecture/identity/"
},
{
"title": "Messaging and Work Intake",
"url": "/dev/architecture/messaging-and-work-intake/"
},
{
"title": "Architecture Migration Decisions",
"url": "/dev/architecture/migration-decisions/"
},
{
"title": "Task Observability",
"url": "/dev/architecture/observability/"
},
{
"title": "Repository Organisation",
"url": "/dev/architecture/organisation/"
},
{
"title": "Domain and Feature Review Procedure",
"url": "/dev/architecture/package-review/"
},
{
"title": "Plugins and Extensions",
"url": "/dev/architecture/plugins-and-extensions/"
},
{
"title": "Policy System",
"url": "/dev/architecture/policy/"
},
{
"title": "Safe Change and Recovery",
"url": "/dev/architecture/safe-change-and-recovery/"
}
]
},
{
"title": "Development guides",
"url": "/dev/development/",
"items": [
{
"title": "Agent",
"url": "/dev/development/agent/"
},
{
"title": "Control plane and settings",
"url": "/dev/development/control-plane/"
},
{
"title": "Daemon",
"url": "/dev/development/daemon/"
},
{
"title": "Frontend UI",
"url": "/dev/development/frontend-ui/"
},
{
"title": "Merging work",
"url": "/dev/development/merging-work/"
},
{
"title": "State Store",
"url": "/dev/development/state-store/"
},
{
"title": "Processes and wiring",
"url": "/dev/development/wiring/"
},
{
"title": "Workflows",
"url": "/dev/development/workflows/"
}
]
},
{
"title": "PRDs",
"items": [
{
"title": "Architecture Decision Index",
"url": "/dev/prds/01-project-management/"
},
{
"title": "PRD writing rules",
"url": "/dev/prds/RULES/"
},
{
"title": "Running action playbooks",
"url": "/dev/prds/action-playbook-run/"
},
{
"title": "Agent2Agent as archie's agent-to-agent protocol — decision",
"url": "/dev/prds/agent2agent-protocol/"
},
{
"title": "Artifact sender",
"url": "/dev/prds/artifact-sender/"
},
{
"title": "Binding secret at-rest encryption -- decision",
"url": "/dev/prds/binding-secret-encryption/"
},
{
"title": "Channel and Forge action positions (resolves `t2db.19`)",
"url": "/dev/prds/channel-forge-positions/"
},
{
"title": "Code graph over MCP (`tools/codegraph`)",
"url": "/dev/prds/code-graph-mcp/"
},
{
"title": "Example-config and generated-config drift — decision",
"url": "/dev/prds/config-example-drift/"
},
{
"title": "Backend-owned configuration schema for the webui -- decision",
"url": "/dev/prds/config-schema/"
},
{
"title": "Contract conformance audit — decision",
"url": "/dev/prds/contract-conformance-audit/"
},
{
"title": "Control-plane apply status",
"url": "/dev/prds/control-plane-apply-status/"
},
{
"title": "Curator sampler wave 1: `Sampler` interface + four cheap strategies -- decision",
"url": "/dev/prds/curator-sampler-wave1/"
},
{
"title": "Dashboard-aware chat: Archie sees the page, and points the operator there",
"url": "/dev/prds/dashboard-aware-chat-navigation/"
},
{
"title": "Dashboard live state",
"url": "/dev/prds/dashboard-live-state/"
},
{
"title": "Dashboard port: what the agent delivers",
"url": "/dev/prds/dashboard-port-brief/"
},
{
"title": "One source for the dashboard's server vocabularies",
"url": "/dev/prds/dashboard-vocabulary/"
},
{
"title": "Deep research capability — design",
"url": "/dev/prds/deep-research-capability/"
},
{
"title": "Dynamically-defined curators -- decision",
"url": "/dev/prds/dynamic-curators/"
},
{
"title": "Dynamic workflow triage",
"url": "/dev/prds/dynamic-workflow-triage/"
},
{
"title": "EDA playbook engine -- design",
"url": "/dev/prds/eda-playbook-engine/"
},
{
"title": "Embedded NATS execution -- decision",
"url": "/dev/prds/embedded-nats/"
},
{
"title": "Event automation: identified events, typed parameters, purpose-built agents",
"url": "/dev/prds/event-automation/"
},
{
"title": "Event capture storage -- decision",
"url": "/dev/prds/event-capture-storage/"
},
{
"title": "Event sources and reactions -- decision",
"url": "/dev/prds/event-sources-and-reactions/"
},
{
"title": "Execution tree and enforced state machine",
"url": "/dev/prds/execution-tree-state-machine/"
},
{
"title": "Extensions centre",
"url": "/dev/prds/extensions-center/"
},
{
"title": "External agent harnesses",
"url": "/dev/prds/external-agent-harness/"
},
{
"title": "Identity for users, agents and external agents — decision",
"url": "/dev/prds/identity-decision/"
},
{
"title": "Image capability contract and configuration",
"url": "/dev/prds/image-capability-contract/"
},
{
"title": "Inline review -- decision",
"url": "/dev/prds/inline-review/"
},
{
"title": "MCP client and tool-guardrail completion",
"url": "/dev/prds/mcp-tool-completion/"
},
{
"title": "Memory engine unification: four scopes, CRUD, and one write path -- decision",
"url": "/dev/prds/memory-engine-unification/"
},
{
"title": "Messaging Service boundary and transport design",
"url": "/dev/prds/messaging-service-boundary/"
},
{
"title": "Module position -- design",
"url": "/dev/prds/module-position/"
},
{
"title": "Multi-action playbooks and typed action results",
"url": "/dev/prds/multi-action-playbooks/"
},
{
"title": "Public news and per-version release notes",
"url": "/dev/prds/news-and-releases/"
},
{
"title": "Orgs, workspaces and access control",
"url": "/dev/prds/orgs-and-access/"
},
{
"title": "Payload field mapping -- decision",
"url": "/dev/prds/payload-field-mapping/"
},
{
"title": "Playbook data-flow and condition syntax",
"url": "/dev/prds/playbook-expression-syntax/"
},
{
"title": "Plugin settings reconcile live",
"url": "/dev/prds/plugin-settings-live/"
},
{
"title": "PR review agent",
"url": "/dev/prds/pr-review-agent/"
},
{
"title": "PR review: the operator's answer to the approval gate",
"url": "/dev/prds/pr-review-operator-response/"
},
{
"title": "PR review comment remediation -- decision",
"url": "/dev/prds/pr-review-remediation/"
},
{
"title": "Progressive tool disclosure (bridge tools) — wiring",
"url": "/dev/prds/progressive-tool-disclosure/"
},
{
"title": "Public and development documentation -- design",
"url": "/dev/prds/public-and-dev-docs/"
},
{
"title": "One release stream, one page per version, and commit rules — decision",
"url": "/dev/prds/release-stream-and-commit-rules/"
},
{
"title": "Review settings resource",
"url": "/dev/prds/review-settings-resource/"
},
{
"title": "Runtime control plane",
"url": "/dev/prds/runtime-control-plane/"
},
{
"title": "Self-update: artifact install, topology migration, journaled transaction",
"url": "/dev/prds/self-update-transaction/"
},
{
"title": "Service decomposition -- decision",
"url": "/dev/prds/service-decomposition/"
},
{
"title": "Service registry — one declaration per service",
"url": "/dev/prds/service-registry/"
},
{
"title": "Persistent session-memory curator (reference implementation) -- decision",
"url": "/dev/prds/session-memory-curator/"
},
{
"title": "Skill curator (reference implementation) -- decision",
"url": "/dev/prds/skill-curator/"
},
{
"title": "SOUL: an agent's user-authored personality",
"url": "/dev/prds/soul/"
},
{
"title": "State Store — contract boundary \u0026 transport (ratification)",
"url": "/dev/prds/state-store-contract/"
},
{
"title": "/status health surface",
"url": "/dev/prds/status-health-surface/"
},
{
"title": "Store",
"url": "/dev/prds/store/"
},
{
"title": "task_logs pagination and bounded retrieval -- decision",
"url": "/dev/prds/task-logs-pagination/"
},
{
"title": "Per-run task detail: attempts, stages, changes, config, debug",
"url": "/dev/prds/task-run-detail/"
},
{
"title": "Task run detail as a master-detail split pane",
"url": "/dev/prds/task-run-master-detail/"
},
{
"title": "UI Service boundary and configuration ownership",
"url": "/dev/prds/ui-service-boundary/"
},
{
"title": "Preact → Vue 3 + shadcn-vue migration checklist",
"url": "/dev/prds/vue-migration-checklist/"
},
{
"title": "Webhook intake security -- decision",
"url": "/dev/prds/webhook-intake-security/"
},
{
"title": "Declared outputs of a workflow run",
"url": "/dev/prds/workflow-call-outputs/"
},
{
"title": "Workflows calling workflows",
"url": "/dev/prds/workflow-calls/"
},
{
"title": "Workflow step vocabulary: what a step type is and how binaries agree on it",
"url": "/dev/prds/workflow-step-vocabulary/"
}
]
}
]
}
-41
View File
@@ -1,41 +0,0 @@
{
"pages": [
{
"url": "/docs/",
"title": "Archie",
"section": "",
"body": "# Archie\n\n**Event-driven Agentic Automation**\n\nArchie connects events from your systems to agents that can investigate, reason,\nand act. Define what an event means, map its data into a workflow, and give that\nworkflow an agent equipped for the job: its own execution environment, tools,\nand identity.\n\nThe aim is to automate work across system administration, incident response,\nnetwork operations, service management, and software delivery. You define the\nprocess and the access it requires; agents work through its stages, using the\ncontext of each event to decide how to accomplish the task.\n\nArchie is under active development. The model below describes the project's\napproved direction, with implementation progressing across event automation and\norganisation access control. The\n[event automation design](/dev/prds/event-automation/) and\n[organisations and access design](/dev/prds/orgs-and-access/) describe those\ncapabilities and their delivery stages.\n\n## From an event to an outcome\n\n```text\nEvent source → Event type → Mapping → Binding → Workflow → Agent\n```\n\n| Concept | Purpose |\n| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |\n| **Source** | Receive events from a system such as a firewall, monitoring stack, service desk, or forge. Configure its endpoint and signing requirements. |\n| **Event type** | Identify which kind of event arrived from its headers and payload. Infer a schema from captured events or a pasted example. |\n| **Mapping** | Extract named, typed parameters from the event. Reuse a mapping across bindings and see how often it matches. |\n| **Binding** | Select a workflow, filter the events that should trigger it, and supply its inputs from mapped values or constants. |\n| **Workflow** | Define the stages of work, their inputs and outputs, and the agent profile to use. Call other workflows when work needs another specialist or process. |\n| **Agent** | Execute the work in a container with the tools for its purpose, acting under its own identity and granted permissions. |\n\nA single source can produce several event types. An event type can feed several\nbindings, and each binding can apply its own conditions. This lets the same\nincoming data drive different responses without building a custom integration\nfor every workflow.\n\nFor example, a firewall sends a blocked-connection event. Archie identifies the\nevent type and maps the source address and severity into an investigation\nworkflow. A network investigator gathers evidence, assesses the activity, and\nreturns its findings. The workflow could then call a separate containment\nworkflow, subject to the permissions and approvals configured for that action.\n\nThe same model supports other processes:\n\n- **Infrastructure operations:** A monitoring alert starts a diagnostic workflow\n to inspect a service, collect evidence, and propose or perform an authorised\n recovery action.\n- **Service management:** An incoming request supplies the parameters for a\n triage, investigation, or fulfilment workflow.\n- **Software delivery:** A forge event starts a review or implementation\n workflow with the repository's toolchain, validation steps, and pull request\n as its output.\n\nThese are examples of workflows you can build. Their behaviour comes from the\nworkflow, tools, and access you configure.\n\n## Agents equipped for their work\n\nAn agent profile selects the container image and available tools. You can supply\nimages with the software needed for a particular environment: network utilities\nfor an investigator, operational tooling for a systems agent, or a language\nruntime and test framework for repository work.\n\nWorkflows declare structured inputs and can return structured outputs. They can\nrun with a scratch workspace, require a repository, or accept one optionally. An\ninvestigation can finish with a report; a maintenance workflow can finish with\nan operational result; a coding workflow can finish with a pull request.\n\nWorkflows can also call other workflows and pass data between them. Each called\nworkflow has its own run and agent profile. A caller can wait for the result or\ncontinue while the called workflow runs independently.\n\nSee the\n[firewall investigation example](https://github.com/samcharles93/archie-core/blob/main/examples/workflows/firewall-investigate.yaml)\nfor a workflow that uses typed inputs, a network investigator profile, and no\nrepository.\n\n## Organisations, identities, and controlled execution\n\nThe approved access modLine truncated
},
{
"url": "/docs/guides/first-playbook/",
"title": "Building your first playbook binding",
"section": "Guides",
"body": "# Building your first playbook binding\n\nThis walks through the whole no-code path the event-capture epic promises:\npoint an external app's webhook at archie, see the real payload it sends,\nmap the fields you care about, bind them to a workflow, and watch the next\nmatching event turn into a task -- no code, no redeploy, no restart. See\n`docs/architecture/bindings.md` for the model and threat model behind each\nstep below.\n\n## 1. Send a test event\n\nPoint whatever external app you want archie to react to at:\n\n```\nPOST http://\u003cyour-archied-host\u003e:8484/webhooks/capture/\u003csource\u003e\n```\n\n`\u003csource\u003e` is a name you choose for this sender (e.g. `sentry`, `github-ci`,\n`stripe`) -- it's just a URL path segment, not a preset list. Send one real\nevent however is easiest for a first test, e.g.:\n\n```bash\ncurl -X POST http://localhost:8484/webhooks/capture/sentry \\\n -H \"Content-Type: application/json\" \\\n -d '{\"issue\": {\"title\": \"NullPointerException in checkout\"}, \"level\": \"error\"}'\n```\n\nThis event isn't signed yet, so it's captured but marked **unauthenticated**\n-- visible for you to design against, but incapable of triggering anything\n(`docs/architecture/bindings.md`'s threat-model section explains why: an\nunauthenticated event can never match a binding, no matter how it looks).\n\n## 2. Inspect the captured payload\n\nOpen the dashboard's **Event inspector** (`/captures`). Your test event\nappears there with its real body -- this is schema-by-example: you're\nlooking at an actual payload from the actual sender, not guessing at a\nschema in advance.\n\n## 3. Map the fields you care about\n\nOpen **Field mappings** (`/mappings`) → **New mapping**. Pick your captured\nevent from the dropdown, then click through its payload tree on the right --\nevery key and value is clickable. Clicking a value binds it as a field\n(name, JSON path, and an inferred type you can change). Add whichever fields\nyour workflow needs (e.g. the issue title), mark the ones that must be\npresent as **Required**, hit **Preview** to confirm they resolve correctly\nagainst the real payload, then **Save**.\n\n## 4. Create the binding\n\nOpen **Playbook bindings** (`/bindings`) → **New binding**:\n\n- **Name** -- anything descriptive.\n- **Source** -- the same `\u003csource\u003e` segment from step 1 (e.g. `sentry`).\n- **Field mapping** -- the one you just saved.\n- **Workflow** -- which registered workflow should run on a match.\n- **Repo pin** (optional) -- leave both blank to use the single configured\n repo; set owner/repo explicitly if you run a multi-repo deployment.\n- **Shared secret** -- a real secret (16+ bytes), never `test1234`. The\n sender signs every request body with this via HMAC-SHA256 so archie can\n tell a genuine event from anyone who finds the URL.\n\nSave. The binding starts in **draft** -- nothing fires yet.\n\n## 5. Approve it\n\nA **draft** or freshly-**edited** binding needs an explicit human approval\nbefore it can ever match a live event -- this is deliberate, not a missing\nstep: an operator authoring a binding is a considered act, an event arriving\nis not, and nothing should self-arm (`docs/architecture/bindings.md`'s\nthreat-model section, point 2). Click **Approve**. Status becomes **armed**.\n\n## 6. Fire it for real\n\nSend the same kind of event again, this time **signed** with the binding's\nsecret:\n\n```bash\nBODY='{\"issue\": {\"title\": \"NullPointerException in checkout\"}, \"level\": \"error\"}'\nSECRET=\"the-secret-you-set-in-step-4\"\nSIG=$(printf '%s' \"$BODY\" | openssl dgst -sha256 -hmac \"$SECRET\" | sed 's/^.* //')\n\ncurl -X POST http://localhost:8484/webhooks/capture/sentry \\\n -H \"Content-Type: application/json\" \\\n -H \"X-Hub-Signature-256: sha256=$SIG\" \\\n -d \"$BODY\"\n```\n\nThis event is captured as **authenticated**, matched against your armed\nbinding, and dispatched into a new task through the exact same\ngate/worktree/sandbox pipeline every other task goes through -- see\n`docs/architecture/messaging-and-work-intake.md`'s \"Intake provenance\". Check\nthe **Tasks** page; a new task should appear, its body built from the fields\nyour mapping resolved.\n\n## Editing a live binding\n\nAny edit to an armed binding -- even a typo fix -- drops it back to\n**pending_approval** automatically. This can't be bypassed by editing; it\nhas to be re-approved. When editing, leave the **Shared secret** field blank\nto keep the existing secret; only fill it in if you're deliberately\nrotating it.\n"
},
{
"url": "/docs/guides/pr-review-benchmark/",
"title": "PR review benchmark",
"section": "Guides",
"body": "# PR review benchmark\n\nRun `scripts/pr-review-benchmark.sh` with `PRBENCH_REVIEW_MODEL` and\n`PRBENCH_CLASSIFICATION_MODEL` set to configured `provider/model` references.\nThe judge defaults to `anthropic/claude-sonnet-4.6`; set\n`PRBENCH_JUDGE_MODEL` to another configured model when needed. The script uses\n`~/.config/archie/config.toml` for providers and `GH_TOKEN` or `GITHUB_TOKEN`\nfor read access to the benchmark pull requests. It posts no forge review.\n\nThe default run reviews the 38 runnable Martian pull requests once each at\n`deep`, judges the comments against 102 golden comments, and writes\n`bin/prbench-results/run.json`, `summary.json`, and one JSON result per pull\nrequest. That output directory is ignored by git. A completed full run fails\nwhen any problem fails or golden micro-recall is below 0.70. Golden-only\nprecision is reported alongside recall. Set `PRBENCH_OUT` to keep separate\nruns; `-problems ID` limits a smoke run to one pull request. Completed results\nare saved as each PR finishes. Pass `-resume DIR` to reuse completed results\nfrom a run with the same models; each reused problem must match the current\nbenchmark entry, and failed problems are rerun.\nA smoke run alone is not the acceptance run.\n\nThe benchmark passes only each problem's ID and pull request URL to the\nreviewer. The judge receives the golden comments after the review has ended.\nThe runner uses the production decision phases through the merge gate,\nincluding scoring and the 25-comment cap, then stops before polish and forge\nposting. A reviewer that fails to finish makes that problem fail. The results\nrecord budget-skipped phases and the selected models. Model substitutions do\nnot satisfy the PRD's named-model criterion even if recall clears the threshold.\n"
}
],
"nav": [
{
"title": "Archie",
"url": "/docs/"
},
{
"title": "Guides",
"items": [
{
"title": "Building your first playbook binding",
"url": "/docs/guides/first-playbook/"
},
{
"title": "PR review benchmark",
"url": "/docs/guides/pr-review-benchmark/"
}
]
}
]
}
-34
View File
@@ -1,34 +0,0 @@
# Prompt for Claude Code
Unzip this bundle into the repo at `docs/design/ui-redesign/`, then paste the prompt below.
---
The design handoff for the Archie UI redesign is in `docs/design/ui-redesign/`. It covers a new theme, a new
top-level navigation, the Settings pages (Channels moves in there), and the Dashboard, Task detail, Workflows,
New task dialog and Events pages.
Read `README.md` in full, then look at every PNG in `screenshots/`. The `00-current-*.png` files show how the
pages look today; `P0-navigation-map.png` shows what moves where. The static HTML in `mockups/` has the exact
CSS if you need it. `tokens/tokens.css` holds the colours, fonts and sizes.
Treat the spec as a hypothesis to check against the code, not a spec to copy exactly.
Before changing anything:
1. Find how the UI is built: framework, router, component library, where styles and theme colours live,
and where the purple comes from.
2. Map today's routes and the Work / System menus to the proposed navigation in README §2. List every
page that isn't covered and where you'd put it.
3. For Settings and Channels: find how each section loads and saves config, how "Restart required",
"Version", "History" and the audit log work, and where "Connecting" comes from. Map every field in
README §5 to its real config key and type.
4. Answer the backend questions in README §5.2 and §9.
5. Check what data the Dashboard, Task detail and Workflows pages already get, and list anything the
mockups show that isn't available.
Then write a short migration plan using the PR sequence in README §8. Adjust it to what you found and
list anything the mockups assume that the backend doesn't support. Stop and show me the plan before you
write code.
When I approve, do PR 1 only (theme tokens across the whole app, no layout changes) on a new branch, with
before/after screenshots of each page.
-277
View File
@@ -1,277 +0,0 @@
# Archie UI Redesign — Handoff
A redesign of the Archie web UI:
- a calmer **"Graphite" theme** that replaces the purple
- a **new navigation**: five top-level places, with all configuration moved under Settings
- new layouts for **Settings** (every section, plus Channels moved in), the **Dashboard**,
**Task detail**, **Workflows**, a **New task** dialog and **Events**
This folder is self-contained. Read this file first, then look at the screenshots.
```
README.md ← this spec (read it all before planning)
CLAUDE_PROMPT.md ← the prompt to paste into Claude Code
tokens/tokens.css ← theme as CSS custom properties (source of truth)
tokens/tokens.json ← same values as JSON (for Tailwind / JS themes)
screenshots/
00-current-*.png ← how each page looks TODAY
P0-navigation-map ← today → proposed navigation, and what moves where
P1…P5 ← app pages: dashboard, task detail, workflows, new task, events
S1…S5 ← settings: sidebar + rows, personas, tools & MCP, review drawer, channels
T-theme-components ← palette, type, buttons, pills, toggles, inputs
mockups/*.html ← static HTML of each screenshot; open in a browser, inspect for exact CSS
source/*.dc.html ← original design-canvas sources (reference only, needs a runtime that isn't included)
```
> **How to treat this.** The mockups are a target, not a pixel spec. They are static HTML
> written by hand; the app's framework, component library, router and data model win. Where the
> mockups assume something the backend doesn't have, flag it rather than faking it.
> Text in `[square brackets]` in a mockup is a placeholder for real data.
---
## 1. Problems being fixed (all pages)
1. **Purple everywhere.** Purple-tinted backgrounds, borders, buttons, checkboxes, bars and links all compete for attention.
2. **Repeated chrome.** Every settings card has its own "Connecting" pill, "Restart required" pill, "Version 1",
"Save changes" and "History". Workflows and Channels repeat the pattern.
3. **Raw config shapes leak through.** Durations as Go strings (`1h0m0s`, `0s`), bytes as `2000000`,
maps as key/value boxes, secret refs as two separate Engine/Key text fields, booleans as bare checkboxes with no explanation.
4. **No descriptions.** Almost no field says what it does.
5. **Things live in the wrong place.** Channels (configuration) sits under Work; "Start work" sits inside the
workflow editor page; the Channels audit table only covers Channels; workflow analytics mix every workflow together.
6. **The most important information isn't first.** The Dashboard opens with quality gates; the "3 need you" count is a small button.
## 2. Navigation (screenshot `P0-navigation-map.png`)
**Top bar (every page):** logo · **Dashboard · Tasks · Workflows · Events · Settings** · spacer ·
"Jump to…" search (⌘K) · **New task** button · connection pill · account avatar.
The Work and System dropdowns go away. The floating chat button stays, restyled (neutral fill, accent icon).
| Place | Job | Contains |
|---|---|---|
| Dashboard | What needs me right now | Needs-you queue, live activity, health (quality gates, tokens) |
| Tasks | The work | Task list (filter by state), task detail |
| Workflows | How work runs | List with runs/success/cost, definition editor, Performance and Runs tabs |
| Events | What comes in | Inspector, Mappings, Bindings |
| Settings | Everything you configure | **Agents:** Personas, Schedules, Scheduling policy · **Integrations:** Channels, Tools & MCP, Plugins · **Runtime:** Container runtime · **History** |
What moves:
| What | Moves to | Why |
|---|---|---|
| Start work card (Workflows page) | **New task** dialog from the top bar and ⌘K | Starting work isn't editing a workflow |
| Channels (Work menu) | Settings › Integrations › Channels | It's configuration; gets the shared setting rows and save flow |
| Audit table (Channels page) | Settings › History, filterable by section | One change log for all settings; replaces per-card History links |
| Per workflow table | Columns in the Workflows list | Stats next to the workflow you're about to open |
| Slowest stages · Most failures | Workflow › Performance tab | Scoped to the selected workflow |
| Connecting / Version pills on every card | One connection status in the top bar | Connection is global |
| Settings "Managed elsewhere" row | Removed; those are the Events tabs | They already live there |
| Task "Attempt 2 is not recorded" column | Attempts list in the task side rail | Shows every attempt and its outcome |
The dropdown contents of today's Work and System menus were inferred from screenshots. **Check the router** and
place any page not covered here using the same rule: configure → Settings, act on → where the work is.
## 3. Theme
All values are in `tokens/tokens.css`. Rules that matter more than the hex values:
- **One accent, used sparingly.** Default sage `#86b5a0`. Only for: active nav/list item (2px inset left bar + raised background),
active tab underline, focus borders/rings, "edited" dots and counts, toggle "on" track, primary button fill, success text,
the "live"/"running"/"connected" dot, and positive bars. Never for backgrounds, headings or borders at rest.
- Keep the accent a **single variable** so it can be swapped (sage / steel `#8aa4c2` / sand `#d4a373` / muted violet `#a397c9`).
- **Neutral, slightly warm greys**, no hue tint on surfaces and no background gradients. Hierarchy comes from surface steps and borders.
- **Amber = needs attention** (parked, awaiting reply, applies after restart, connecting). **Red = failed / destructive / risky**
(errors, delete, unrestricted filesystem). No other hues except the agent state swatches in the tokens.
- **Fonts:** IBM Plex Sans for UI; **IBM Plex Mono for every machine value**: config values, IDs, keys, env var names,
image refs, durations, paths, event names, task numbers, log lines, counts in tables.
- Text contrast: `--text-3` is the dimmest text allowed, and only for hints and captions.
## 4. Components (screenshot `T-theme-components.png`)
Build these once and reuse everywhere. Heights are 36px unless noted.
| Component | Spec |
|---|---|
| **Button** | primary (accent fill, `--text-on-accent`), secondary (`--raised` + `--border-button`), ghost (transparent, `--text-2`), destructive (red text, transparent). 13px/500, radius 6. Small variant 30px/12px. **One primary per view.** |
| **Text input** | `--bg` fill, `--border-input`, radius 6, mono 13px. Focus: accent border + 3px `--accent-ring`. Invalid: red border + 12px red message. |
| **Input with unit** | input + attached suffix (`MB`, `sec`, `chars`) or unit `<select>`. |
| **Duration input** | number + unit select. Convert to/from Go durations (`30s`, `1m0s`, `72h0m0s`) only at the API boundary. |
| **Byte size input** | number + `MB`; store bytes (2,000,000 bytes = 2 MB, decimal). |
| **Stepper** | − / value / + for small integers. |
| **Toggle** | 36×20 track. On = accent (or red for risky settings), off = `--border-input`. Always labelled; risky ones sit in a bordered row with a one-line consequence. Real checkbox / `role="switch"` underneath. |
| **Segmented control** | 2–4 exclusive options, radiogroup with arrow keys. Selected segment `--raised-2`. |
| **Tabs** | 44px, 13px, `--text-3`; active = `--text` + 2px accent underline. Left-aligned, sized to content (not stretched full width). Optional mono count chip. |
| **Secret reference** | one row: lock icon · engine (mono, dim) · `/` · key (mono) · "Change". Status line below: accent ✓ "Credential resolved by Archie" or red "Credential not found". Replaces separate Engine/Key inputs and the "Credential configured" checkbox. |
| **Chip input** | for lists of IDs (Telegram allowed users): mono chips with × plus an inline input. |
| **Status pill** | radius 999, 12px. Neutral with coloured dot (connection, running, listening), warn (parked, awaiting reply, applies after restart), accent outline (edited count, default), danger (invalid). |
| **Card** | `--surface`, `--border-card`, radius 10. Header row: optional 32px icon tile · title (15px/500) + hint · right-side status/action. |
| **Stat strip** | one card split into equal cells by 1px dividers: label (12px dim), value (30px/600), sub (12px dim). |
| **Data table** | uppercase 11px headers, 13px rows, 1px `--border-subtle` dividers, mono for machine values, long text truncates with ellipsis. |
| **Progress bar** | 4–6px track `--raised-2`, fill accent (good) or red (failing). |
| **Empty state** | icon tile + title + one-line hint + the action (a button, or a copyable value). |
| **Alert banner** | amber or red tinted box: icon · title · mono detail · one action on the right. |
| **Nav item** (sidebars) | 34–36px, radius 6, 13px `--text-2`. Active: `--raised` + 2px inset accent bar. |
| **Dialog** | 640px, `--surface-2`, radius 12, header (title + hint + close), body, footer (shortcut hint · Cancel · primary). Dim backdrop. |
Icons: 2px-stroke line icons. Use the app's existing icon set if it has one (e.g. Lucide).
## 5. Settings
### 5.1 Settings shell (`S1-settings-sidebar-setting-rows*.png`)
- **Left sidebar (248–264px)** with grouped nav: AGENTS (Personas, Schedules, Scheduling policy), INTEGRATIONS (Channels, Tools & MCP, Plugins),
RUNTIME (Container runtime), divider, History. Optional mono counts (Personas `6`). A section with unsaved edits shows an accent dot.
- **Content column** max ~920–980px. Section header: 24px title, 14px description, amber "Applies after restart" pill when relevant.
- **Groups** inside a section: 13px uppercase eyebrow.
- **Setting row:** 2-column grid `260–280px | 1fr`, gap 32px, 16–20px vertical padding, 1px top border.
Left: label (13px/500) + hint (12px dim). Right: the control.
- Sidebar items are links (route or hash per section).
### 5.2 Save model (`S1` save bar + `S4-settings-review-drawer.png`)
Replace every per-card Save button with one page-level flow:
1. Track edits per field against the loaded config. Edited inputs get an accent border and a "was `old`" hint.
2. When anything is dirty, a **sticky save bar** appears: accent dot · "N unsaved change(s)" · field names · **Discard** · primary
**"Save & restart"** if any dirty field needs a restart, otherwise **"Save"**.
3. The primary button opens the **Review drawer** (480px, right, dim backdrop): "Review N changes", "Saved together as config version N+1",
amber restart callout (optionally with running agent count), changes grouped by section as cards with **Revert** and a mono diff
(red `− old`, green `+ new`), footer Discard all · Save only · Save & restart.
4. Personas keep their own save footer in the editor panel but still feed the page dirty state.
**Backend questions to answer first:** can several sections be saved atomically (or will saves be sequential with partial-failure handling)?
Is "restart required" known per field or per section? Is there a restart action? If not, "Save & restart" becomes "Save" plus a
persistent "Restart pending" banner.
### 5.3 Personas (`S2-settings-personas.png`)
- Left: filter + New; list rows = name + one-line prompt; default persona has an accent-outline **default** pill; selected row = raised + accent bar.
- Right: editor. Header: name + default pill · Duplicate · Delete. Body: Name (mono) and **Default persona** toggle; **System prompt** as a large
mono textarea with "N chars · ~N tokens". Footer: "Saved · version N · History" · Discard · Save persona.
- The old separate "Default" field becomes the per-persona toggle (setting one unsets the others).
- The "try this persona" preview row is optional/future.
- The mockup uses **top tabs** for section navigation; that's the narrow-width fallback. Use the sidebar shell on desktop.
### 5.4 Schedules
Not mocked. Card empty state ("No schedules yet" + "Add schedule"); populated = list rows like Personas.
### 5.5 Scheduling policy (`S1`)
- DISPATCH: *Trigger* segmented Assignee / Label (show the Label input only when Label is chosen); *Ack reaction* mono input.
- STATE LABELS: bordered table `STATE | LABEL | ⌫` with coloured state swatch, mono label input, trash button, "+ Add state".
Today's UI shows display name ("Dead"), key (`dead`) and value (`agent:dead`); the mockup merges name and key.
If the key must stay editable, keep a small mono input in the State column.
- RETRIES & POLLING: *Max retries* stepper; *Poll interval* duration input.
### 5.6 Channels (moved from Work; `S5-settings-channels.png`, today `00-current-channels.png`)
- One card per channel. **Configured** channels are expanded with setting rows; **unconfigured** ones collapse to a single row
(icon · name · one-line purpose · "Not set up" pill · **Set up** button that expands the fields).
- **Telegram** (running): header status pill "Running" (accent). Rows: *Bot token* = secret reference (`env / HEYARCHIE_TELEGRAM_BOT_TOKEN`) + resolved line;
*Allowed users* = chip input of numeric IDs, hint "Everyone else is ignored."
- **Email** (collapsed): expands to *Listen address*, *Relay address*.
- **Webhook** (collapsed): expands to *Deliver to*, *Path*, *Template*, *Signing secret* (secret reference), and *Webhook address*
(today's top-level "Webhook addr" belongs here if it only serves the webhook channel; confirm).
- **CHAT SESSION DEFAULTS · ALL CHANNELS** card with setting rows: *Workspace* (mono path), *Filesystem access* (Unrestricted filesystem toggle in a
**red** bordered row: "On: agents can read and write anywhere this user can."), *Show tool calls* toggle, *Max steps*
("0 = no limit": **confirm the real semantics**), *Rate limit* as "[n] requests per [n] [unit]" ("Off while either value is 0": confirm),
*Models*, *Operator*.
- Footer line: "Version N · N fields set by `actor` N ago · View in History". The audit table itself moves to Settings › History.
- Channel status (running / stopped / error) must come from the backend, not from whether it's configured.
### 5.7 Tools & MCP (`S3-settings-tools-mcp.png`)
- Header action **Add MCP server**. MCP servers card (full width): empty state offering "stdio command" / "HTTP / SSE endpoint"
(only the transports the backend supports); populated rows = name, transport, enabled toggle, edit/delete.
- **MiniMax** card: header "Enabled" toggle; API key as secret reference (`bws / MINIMAX_API_KEY`) + resolved line.
- **Web fetch** card: "Enabled" toggle; *Max download* (bytes as MB); *Timeout* (duration, sec); *Allow private networks* as a bordered
toggle row. Disable the fields when the card is off.
- **Tool output policy** card: *Max result length* (`chars`, hint "About N tokens per tool call", ~4 chars/token), *Spill directory*.
### 5.8 Plugins
Not mocked. Setting rows for *Module dir*, *Plugin dir*, *Secret engine dir*, *Skills dir* (mono, placeholder = effective default if exposed).
### 5.9 Container runtime (left side of `S4`)
*Image* (full width, mono), *Max concurrency* (stepper), *Max uptime* (duration), *Network* (mono),
*Pull policy* (select: If missing / Always / Never → `missing` / `always` / `never`), *Volume TTL* (duration), *Profiles* (mono).
### 5.10 History (new, not mocked)
The Channels audit table generalised to all settings: When · Section · Field (mono) · Old → New (mono, truncated, expandable) ·
Version · Changed by. Filters: section, actor, date. Every "History" link elsewhere deep-links here with the section filter applied.
## 6. App pages
### 6.1 Dashboard (`P1-dashboard.png`, today `00-current-dashboard.png`)
- Header: "Good morning" + a one-line summary that **names the action** ("Nothing is running. 3 tasks need you." with the count in amber). Logs button on the right.
- **Stat strip**: Working now / Needs you (amber value) / Delivered / Tokens used, with the same subtitles as today.
- Two columns: main (1fr) and right rail (380px).
- Main, first: **Needs you** card (count pill). One row per task: state pill (Parked / Awaiting reply) · title (link) ·
mono meta line (`repo #issue · workflow · reason or last message`, truncated) · **Open** (ghost) + the next action
(**Start new run** for parked, **Reply** for awaiting). "All tasks" link in the header.
- Main, second: **Live activity** table: Event (mono, small colour square by kind, `×N` chip when consecutive identical events are grouped) · Task (mono) ·
Detail (truncated) · When. Header: live pill + segmented filter All / Tasks / System.
- Right rail: **Quality gates** (big pass rate, one row per gate with `passed / runs` and a bar: red when failing, accent when passing) and
**Token outlook** (Today, "Next 30 days at this rate", a 7-day mini bar chart, and a note when history is shorter than a week).
Today's full-width purple bar that shows nothing is removed.
### 6.2 Task detail (`P2-task-detail.png`, today `00-current-task-detail.png`)
- Breadcrumb `Tasks / #1`, title, meta row: status pill · workflow (mono) · `repo #issue` link. Actions: **Archive** (ghost), **Start a new run** (primary).
- **Alert banner** for parked/failed tasks: plain-language title ("Parked: couldn't prepare the worktree"), mono error detail, "Jump to log line".
- Two columns: main card with tabs **Log · Changed files (count) · Configuration · Debug**; right rail (320px).
- Log tab: toolbar = level select, stage select, search, Download. Log lines in mono: time · level (ERROR in red) · message with tag chips
(`component=daemon`, `task=1`). Error lines get a faint red background and red left border. Footer "End of attempt N · N lines".
- Right rail: **Attempts** list (dot colour = outcome; selected attempt highlighted; unrecorded attempts shown dimmed) and
**Details** list (Status, Workflow link, Repository, Issue ↗, plus Persona, Tokens, Started if available).
### 6.3 Workflows (`P3-workflows.png`, today `00-current-workflows.png`)
- Header: title + description ("Success rate is merged tasks over all runs"), **Restore shipped** (ghost), **New workflow**.
- Left (420px): list = name + id (mono) · runs · success (`n of m` + bar) · avg tokens (compact: 4.7M, 282k). Selected = raised + accent bar.
- Right: editor card. Header: name + origin pill (e.g. "shipped · edited"; derive from the real origin field) + run count.
Tabs **Definition · Performance · Runs**.
- Definition: *ID* input; *Steps* read-only preview (mono step chips joined by arrows, parsed from YAML);
*YAML* editor with line numbers, mono, light syntax colouring, live "✓ Valid" / error indicator.
Footer: "Version N · History" · Remove (destructive ghost) · Restore this workflow · **Validate & save**.
- Performance (not mocked): today's **Slowest stages** and **Most failures**, filtered to this workflow.
- Runs (not mocked): tasks that used this workflow, linking to Task detail.
- The **Start work** card leaves this page (see 6.4).
### 6.4 New task dialog (`P4-new-task-dialog.png`)
Replaces the Start work card. Opened from the top bar button, ⌘K, and optionally from a workflow ("Start task with this workflow").
- Fields: *Repository* (mono, hint with recent repos), *Workflow* as a 3-column card radiogroup showing each workflow's runs and merge rate,
*Title*, *Instructions* (textarea), and **Identity** tucked into an "Advanced · run as identity" disclosure.
- Footer: "⌘↵ to start" · Cancel · **Start task**. On success, go to the new task's detail page.
### 6.5 Events (`P5-events.png`, today `00-current-events.png`)
- Header with description ("Webhooks come in, get mapped to event types, and bindings turn them into work.") and a **Listening** pill.
- Left-aligned tabs **Inspector · Mappings · Bindings** with count chips. (Reordered to follow the flow; keep the old order if you prefer.)
- Inspector: a 3-step strip **Capture → Map → Bind** with counts; then **Recent captures** (empty state with the copyable endpoint
`/webhooks/capture/<source>` and a Copy button) and **Event types** ("From payload" action, empty state explaining proposals).
## 7. Behaviour and accessibility
- Real `<button>`, `<a href>`, `<input>`, `<select>`, `<label for>`; icon-only buttons get `aria-label`. Toggles use checkbox/`role="switch"`.
Segmented controls and workflow cards are radiogroups with arrow-key support. Dialogs trap focus and close on Esc.
- Visible focus everywhere (accent ring). Touch targets ≥36px (44px on mobile).
- Validate on blur; invalid fields block Save and are listed in the save bar.
- Unsaved-changes guard on route leave.
- Skeleton rows while loading; the top-bar connection pill reflects the socket/API state (Connecting amber, Connected accent, Disconnected red).
- Live tables (activity, captures) insert new rows without layout jump; group consecutive identical events.
- Narrow widths (<960px): settings sidebar → top tabs; two-column layouts stack; drawers and dialogs go full-width.
## 8. Suggested PR sequence
1. **Theme tokens only.** Swap purple for Graphite across the whole app. No layout changes. *Done when no purple remains.*
2. **Shared components** from §4.
3. **Top bar + navigation** (§2): new top-level items, New task button (can open the existing Start work form at first), one connection pill, route moves/redirects.
4. **Settings shell** (sidebar groups, setting rows) and move Channels into it. Sections still save the old way.
5. **Settings sections**: Scheduling policy, Plugins, Container runtime, Tools & MCP, Channels, Personas.
6. **Unified save bar + review drawer + Settings › History** (needs the §5.2 backend decisions). Remove per-card save buttons and pills.
7. **Dashboard.**
8. **Task detail.**
9. **Workflows** (list + editor + Performance tab) and **New task dialog**; remove the Start work card.
10. **Events.**
Each PR: before/after screenshots and a note of anything deferred or unsupported.
## 9. Open questions / out of scope
- Real meaning of `max_steps = 0` and a zero rate limit (the mockup assumes "no limit" / "off").
- Whether "Webhook addr" is webhook-channel-only or global.
- Where the Dashboard's Needs-you reasons and last agent message come from.
- Persona preview, light theme, user-facing accent picker (nice to have).
- Atomic multi-section save and "restart now" (see §5.2).
@@ -1,95 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Proposed navigation</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a}
.eyebrow{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:#8f8c85;font-weight:500}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.node{display:flex;align-items:baseline;gap:10px;font-size:14px;font-weight:500}
.sub{font-size:12px;color:#8f8c85;font-weight:400}
.kid{margin:6px 0 0 18px;padding-left:14px;border-left:1px solid #2e3034;display:flex;flex-direction:column;gap:6px;font-size:13px;color:#a6a39b}
.mono{font-family:'IBM Plex Mono',monospace}
.tbl{width:100%;border-collapse:collapse;font-size:13px}
.tbl th{text-align:left;font-weight:500;font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:#8f8c85;padding:10px 14px;border-bottom:1px solid #2a2c30}
.tbl td{padding:10px 14px;border-bottom:1px solid #202225;vertical-align:top;line-height:1.45}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 1120px; box-sizing: border-box; padding: 48px 56px; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; display: flex; flex-direction: column; gap: 28px">
<div>
<h1 style="margin: 0; font-size: 28px; font-weight: 600; letter-spacing: -0.01em">Navigation: today → proposed</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">Five top-level places, each with one job. Anything you configure lives in Settings; anything you act on lives where the work is.</p>
</div>
<div style="display: grid; grid-template-columns: 380px minmax(0, 1fr); gap: 24px">
<section class="card" style="padding: 24px; display: flex; flex-direction: column; gap: 16px">
<div class="eyebrow">Today</div>
<div class="node" style="color: #a6a39b">Dashboard</div>
<div><div class="node" style="color: #a6a39b">Work <span class="sub">dropdown</span></div>
<div class="kid"><span>Tasks</span><span>Workflows <span class="sub">editor + start work + stats</span></span><span>Channels <span class="sub">settings + audit</span></span></div></div>
<div><div class="node" style="color: #a6a39b">Events</div>
<div class="kid"><span>Inspector · Bindings · Mappings</span></div></div>
<div><div class="node" style="color: #a6a39b">System <span class="sub">dropdown</span></div>
<div class="kid"><span>Advanced <span class="sub">6 cards, 6 save buttons</span></span></div></div>
<p class="hint" style="margin: 8px 0 0">Dropdown contents are inferred from the screenshots; confirm against the router.</p>
</section>
<section class="card" style="padding: 24px">
<div class="eyebrow" style="margin-bottom: 16px; color: #86b5a0">Proposed</div>
<div style="display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 24px 32px">
<div><div class="node">Dashboard <span class="sub">what needs me</span></div>
<div class="kid"><span>Needs you queue</span><span>Live activity</span><span>Health: gates, tokens</span></div></div>
<div><div class="node">Tasks <span class="sub">the work</span></div>
<div class="kid"><span>Task list <span class="sub">filter by state</span></span><span>Task detail <span class="sub">log · files · config · debug</span></span><span>Attempts in a side rail</span></div></div>
<div><div class="node">Workflows <span class="sub">how work runs</span></div>
<div class="kid"><span>List with success + cost</span><span>Definition editor</span><span>Performance tab <span class="sub">stages, failures</span></span></div></div>
<div><div class="node">Events <span class="sub">what comes in</span></div>
<div class="kid"><span>Inspector</span><span>Bindings</span><span>Mappings</span></div></div>
<div style="grid-column: span 2"><div class="node">Settings <span class="sub">everything you configure, one save flow</span></div>
<div class="kid" style="display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px 24px">
<span><span style="color: #e8e6e1">Agents</span><br>Personas · Schedules · Scheduling policy</span>
<span><span style="color: #e8e6e1">Integrations</span><br>Channels · Tools &amp; MCP · Plugins</span>
<span><span style="color: #e8e6e1">Runtime</span><br>Container runtime · History</span>
</div></div>
</div>
<div style="margin-top: 24px; padding-top: 16px; border-top: 1px solid #232529; display: flex; gap: 24px; font-size: 13px; color: #a6a39b">
<span><span style="color: #e8e6e1; font-weight: 500">Always in the top bar:</span> New task · ⌘K Jump to · connection status</span>
</div>
</section>
</div>
<section class="card" style="overflow: hidden">
<table class="tbl">
<thead><tr><th style="width: 290px">What</th><th style="width: 280px">Moves to</th><th>Why</th></tr></thead>
<tbody>
<tr><td style="color: #e8e6e1">Start work card (Workflows)</td><td><span style="color: #86b5a0">→</span> New task dialog, from the top bar</td><td style="color: #a6a39b">Starting work is not editing a workflow. One entry point from any page, and from ⌘K.</td></tr>
<tr><td style="color: #e8e6e1">Channels (Work menu)</td><td><span style="color: #86b5a0">→</span> Settings › Integrations › Channels</td><td style="color: #a6a39b">It is configuration. It gets the same setting rows, secret fields and save flow as the rest.</td></tr>
<tr><td style="color: #e8e6e1">Audit table (Channels page)</td><td><span style="color: #86b5a0">→</span> Settings › History</td><td style="color: #a6a39b">One change log for every setting, filterable by section. Replaces six History links.</td></tr>
<tr><td style="color: #e8e6e1">Per workflow table</td><td><span style="color: #86b5a0">→</span> Workflows list columns</td><td style="color: #a6a39b">Runs, success and cost sit next to the workflow you are about to open.</td></tr>
<tr><td style="color: #e8e6e1">Slowest stages · Most failures</td><td><span style="color: #86b5a0">→</span> Workflow › Performance tab</td><td style="color: #a6a39b">Scoped to the selected workflow instead of mixing every workflow in one table.</td></tr>
<tr><td style="color: #e8e6e1">Connecting · Version pills on every card</td><td><span style="color: #86b5a0">→</span> One status in the top bar</td><td style="color: #a6a39b">Connection is global. Version shows once per page, in History.</td></tr>
<tr><td style="color: #e8e6e1">Settings "Managed elsewhere" row</td><td><span style="color: #86b5a0">→</span> Events tabs</td><td style="color: #a6a39b">Captured events, mappings and bindings already live there.</td></tr>
<tr><td style="color: #e8e6e1">Task "Attempt 2 is not recorded" column</td><td><span style="color: #86b5a0">→</span> Attempts list in the task side rail</td><td style="color: #a6a39b">Shows every attempt with its outcome; the empty column goes away.</td></tr>
<tr><td style="color: #e8e6e1">Dashboard stat cards and health</td><td><span style="color: #86b5a0">→</span> Stat strip + right rail</td><td style="color: #a6a39b">"Needs you" becomes the first thing on the page, with actions inline.</td></tr>
</tbody>
</table>
</section>
</div>
</body>
</html>
@@ -1,187 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dashboard</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.btn-ghost{background:transparent;border-color:transparent;color:#a6a39b}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column;min-width:0}
.card-h{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid #232529}
.card-t{font-size:15px;font-weight:500}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.eyebrow{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:#8f8c85;font-weight:500}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0}
.warn{color:#d9a45b;border-color:rgba(217,164,91,.3);background:rgba(217,164,91,.08)}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.nav a.on{color:#e8e6e1;background:#1e2023}
.tbl{width:100%;border-collapse:collapse;font-size:13px}
.tbl th{text-align:left;font-weight:500;font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:#8f8c85;padding:10px 20px;border-bottom:1px solid #2a2c30}
.tbl td{padding:10px 20px;border-bottom:1px solid #202225;vertical-align:middle}
.chip{font:11px 'IBM Plex Mono',monospace;color:#8f8c85;background:#1e2023;border-radius:4px;padding:1px 6px;margin-left:6px}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 1080px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden; position: relative">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#86b5a0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#" class="on">Dashboard</a><a href="#">Tasks</a><a href="#">Workflows</a><a href="#">Events</a><a href="#">Settings</a></nav>
<div style="flex-grow: 1"></div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 220px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%"><span class="mono" style="font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span></label>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: #86b5a0"></span>Connected</span>
<span aria-label="Account" style="width: 28px; height: 28px; border-radius: 50%; background: #26282c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b">A</span>
</header>
<main style="flex-grow: 1; padding: 32px 48px; display: flex; flex-direction: column; gap: 24px; min-height: 0">
<div style="display: flex; align-items: flex-end; gap: 16px">
<div style="flex-grow: 1">
<h1 style="margin: 0; font-size: 28px; font-weight: 600; letter-spacing: -0.01em">Good morning</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">Nothing is running. <span style="color: #d9a45b">3 tasks need you.</span></p>
</div>
<button class="btn"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 6h16M4 12h10M4 18h13"></path></svg>Logs</button>
</div>
<section class="card" style="flex-direction: row">
<div style="flex: 1 1 0; padding: 18px 22px; border-right: 1px solid #232529">
<div class="hint">Working now</div>
<div style="font-size: 30px; font-weight: 600; margin-top: 6px; color: #e8e6e1">0</div>
<div class="hint" style="margin-top: 2px">0 waiting to start</div>
</div>
<div style="flex: 1 1 0; padding: 18px 22px; border-right: 1px solid #232529">
<div class="hint">Needs you</div>
<div style="font-size: 30px; font-weight: 600; margin-top: 6px; color: #d9a45b">3</div>
<div class="hint" style="margin-top: 2px">Parked or awaiting a reply</div>
</div>
<div style="flex: 1 1 0; padding: 18px 22px; border-right: 1px solid #232529">
<div class="hint">Delivered</div>
<div style="font-size: 30px; font-weight: 600; margin-top: 6px; color: #e8e6e1">1</div>
<div class="hint" style="margin-top: 2px">25% of all tasks</div>
</div>
<div style="flex: 1 1 0; padding: 18px 22px; border-right: 1px solid #232529">
<div class="hint">Tokens used</div>
<div style="font-size: 30px; font-weight: 600; margin-top: 6px; color: #e8e6e1">14.5M</div>
<div class="hint" style="margin-top: 2px">Across 1 day</div>
</div>
</section>
<div style="display: grid; grid-template-columns: minmax(0, 1fr) 380px; gap: 24px; min-height: 0; flex-grow: 1">
<div style="display: flex; flex-direction: column; gap: 24px; min-width: 0">
<section class="card">
<div class="card-h"><span class="card-t">Needs you</span><span class="pill warn">3</span><div style="flex-grow: 1"></div><a href="#" class="hint" style="text-decoration: underline">All tasks</a></div>
<div style="display: grid; grid-template-columns: 120px minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 14px 20px; border-bottom: 1px solid #202225">
<span class="pill warn" style="justify-self: start">Parked</span>
<div style="min-width: 0">
<a href="#" style="font-size: 14px; font-weight: 500">changes_captured key-set validation is top-level only</a>
<div class="mono" style="font-size: 12px; color: #8f8c85; margin-top: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">archie-core #868 · tdd · worktree prepare failed: fetch origin: http transport…</div>
</div>
<div style="display: flex; gap: 8px"><button class="btn btn-sm btn-ghost">Open</button><button class="btn btn-sm">Start new run</button></div>
</div>
<div style="display: grid; grid-template-columns: 120px minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 14px 20px; border-bottom: 1px solid #202225">
<span class="pill warn" style="justify-self: start">Awaiting reply</span>
<div style="min-width: 0">
<a href="#" style="font-size: 14px; font-weight: 500">[Task title]</a>
<div class="mono" style="font-size: 12px; color: #8f8c85; margin-top: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">[repo #issue] · [workflow] · [last agent message]</div>
</div>
<div style="display: flex; gap: 8px"><button class="btn btn-sm btn-ghost">Open</button><button class="btn btn-sm">Reply</button></div>
</div>
<div style="display: grid; grid-template-columns: 120px minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 14px 20px; border-bottom: 1px solid #202225">
<span class="pill warn" style="justify-self: start">Awaiting reply</span>
<div style="min-width: 0">
<a href="#" style="font-size: 14px; font-weight: 500">[Task title]</a>
<div class="mono" style="font-size: 12px; color: #8f8c85; margin-top: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">[repo #issue] · [workflow] · [last agent message]</div>
</div>
<div style="display: flex; gap: 8px"><button class="btn btn-sm btn-ghost">Open</button><button class="btn btn-sm">Reply</button></div>
</div>
</section>
<section class="card" style="flex-grow: 1; overflow: hidden">
<div class="card-h"><span class="card-t">Live activity</span><span class="pill" style="color: #86b5a0; border-color: #86b5a0"><span class="dot" style="background: #86b5a0"></span>live</span><div style="flex-grow: 1"></div>
<div role="radiogroup" aria-label="Filter activity" style="display: inline-flex; padding: 2px; border: 1px solid #2e3034; border-radius: 7px"><button style="height: 26px; padding: 0 10px; border: 0; border-radius: 5px; background: #26282c; color: #e8e6e1; font: 500 12px 'IBM Plex Sans', sans-serif">All</button><button style="height: 26px; padding: 0 10px; border: 0; border-radius: 5px; background: transparent; color: #8f8c85; font: 500 12px 'IBM Plex Sans', sans-serif">Tasks</button><button style="height: 26px; padding: 0 10px; border: 0; border-radius: 5px; background: transparent; color: #8f8c85; font: 500 12px 'IBM Plex Sans', sans-serif">System</button></div>
</div>
<table class="tbl">
<thead><tr><th>Event</th><th style="width: 70px">Task</th><th>Detail</th><th style="width: 110px">When</th></tr></thead>
<tbody>
<tr><td class="mono" style="font-size: 12px"><span style="display: inline-block; width: 7px; height: 7px; border-radius: 2px; margin-right: 8px; background: #6f6c66"></span>curator_run</td><td class="mono" style="font-size: 12px; color: #a6a39b">—</td><td style="color: #a6a39b; max-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">session-memory</td><td class="hint">19 mins ago</td></tr>
<tr><td class="mono" style="font-size: 12px"><span style="display: inline-block; width: 7px; height: 7px; border-radius: 2px; margin-right: 8px; background: #8aa4c2"></span>task_archive_requested</td><td class="mono" style="font-size: 12px; color: #a6a39b">#5</td><td style="color: #a6a39b; max-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">archive requested with no recorded actor</td><td class="hint">1 hr ago</td></tr>
<tr><td class="mono" style="font-size: 12px"><span style="display: inline-block; width: 7px; height: 7px; border-radius: 2px; margin-right: 8px; background: #d9776b"></span>task_abandoned</td><td class="mono" style="font-size: 12px; color: #a6a39b">#5</td><td style="color: #a6a39b; max-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">abandoned with no recorded actor</td><td class="hint">1 hr ago</td></tr>
<tr><td class="mono" style="font-size: 12px"><span style="display: inline-block; width: 7px; height: 7px; border-radius: 2px; margin-right: 8px; background: #6f6c66"></span>curator_run<span class="chip">×6</span></td><td class="mono" style="font-size: 12px; color: #a6a39b">—</td><td style="color: #a6a39b; max-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">session-memory</td><td class="hint">1 hr ago</td></tr>
<tr><td class="mono" style="font-size: 12px"><span style="display: inline-block; width: 7px; height: 7px; border-radius: 2px; margin-right: 8px; background: #8aa4c2"></span>stage_start<span class="chip">×4</span></td><td class="mono" style="font-size: 12px; color: #a6a39b">#5</td><td style="color: #a6a39b; max-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis"></td><td class="hint">1 hr ago</td></tr>
<tr><td class="mono" style="font-size: 12px"><span style="display: inline-block; width: 7px; height: 7px; border-radius: 2px; margin-right: 8px; background: #8aa4c2"></span>stage_start<span class="chip">×5</span></td><td class="mono" style="font-size: 12px; color: #a6a39b">#4</td><td style="color: #a6a39b; max-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis"></td><td class="hint">7 hrs ago</td></tr>
<tr><td class="mono" style="font-size: 12px"><span style="display: inline-block; width: 7px; height: 7px; border-radius: 2px; margin-right: 8px; background: #86b5a0"></span>agent_finish</td><td class="mono" style="font-size: 12px; color: #a6a39b">#4</td><td style="color: #a6a39b; max-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">Problem surface for samcharles93/archie-core issue 836 ("Updater cannot detect o…</td><td class="hint">7 hrs ago</td></tr>
<tr><td class="mono" style="font-size: 12px"><span style="display: inline-block; width: 7px; height: 7px; border-radius: 2px; margin-right: 8px; background: #86b5a0"></span>agent_finish</td><td class="mono" style="font-size: 12px; color: #a6a39b">#4</td><td style="color: #a6a39b; max-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">Root cause</td><td class="hint">7 hrs ago</td></tr>
<tr><td class="mono" style="font-size: 12px"><span style="display: inline-block; width: 7px; height: 7px; border-radius: 2px; margin-right: 8px; background: #8aa4c2"></span>stage_start<span class="chip">×6</span></td><td class="mono" style="font-size: 12px; color: #a6a39b">#4</td><td style="color: #a6a39b; max-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis"></td><td class="hint">8 hrs ago</td></tr>
</tbody>
</table>
</section>
</div>
<div style="display: flex; flex-direction: column; gap: 24px">
<section class="card">
<div class="card-h"><span class="card-t">Quality gates</span><div style="flex-grow: 1"></div><span class="hint">last 4 runs</span></div>
<div style="padding: 20px; display: flex; flex-direction: column; gap: 16px">
<div style="display: flex; align-items: baseline; gap: 10px"><span style="font-size: 30px; font-weight: 600">25%</span><span class="hint">pass rate</span></div>
<div>
<div style="display: flex; font-size: 13px; margin-bottom: 6px"><span class="mono">tdd</span><span style="margin-left: auto; color: #a6a39b" class="mono">0 / 3</span></div>
<div style="height: 6px; border-radius: 3px; background: #26282c"><div style="height: 6px; border-radius: 3px; width: 2%; background: #d9776b"></div></div>
</div>
<div>
<div style="display: flex; font-size: 13px; margin-bottom: 6px"><span class="mono">triage</span><span style="margin-left: auto; color: #a6a39b" class="mono">1 / 1</span></div>
<div style="height: 6px; border-radius: 3px; background: #26282c"><div style="height: 6px; border-radius: 3px; width: 100%; background: #86b5a0"></div></div>
</div>
</div>
</section>
<section class="card">
<div class="card-h"><span class="card-t">Token outlook</span></div>
<div style="padding: 20px; display: flex; flex-direction: column; gap: 14px">
<div style="display: flex; gap: 24px">
<div><div class="hint">Today</div><div style="font-size: 22px; font-weight: 600; margin-top: 2px">14.5M</div></div>
<div><div class="hint">Next 30 days at this rate</div><div style="font-size: 22px; font-weight: 600; margin-top: 2px">≈ 434M</div></div>
</div>
<div aria-label="Tokens per day, last 7 days" style="display: flex; align-items: flex-end; gap: 6px; height: 64px">
<div style="flex: 1 1 0; display: flex; flex-direction: column; align-items: center; gap: 4px"><div style="width: 100%; height: 3px; border-radius: 3px; background: #26282c"></div><span class="mono" style="font-size: 10px; color: #8f8c85">M</span></div><div style="flex: 1 1 0; display: flex; flex-direction: column; align-items: center; gap: 4px"><div style="width: 100%; height: 3px; border-radius: 3px; background: #26282c"></div><span class="mono" style="font-size: 10px; color: #8f8c85">T</span></div><div style="flex: 1 1 0; display: flex; flex-direction: column; align-items: center; gap: 4px"><div style="width: 100%; height: 3px; border-radius: 3px; background: #26282c"></div><span class="mono" style="font-size: 10px; color: #8f8c85">W</span></div><div style="flex: 1 1 0; display: flex; flex-direction: column; align-items: center; gap: 4px"><div style="width: 100%; height: 3px; border-radius: 3px; background: #26282c"></div><span class="mono" style="font-size: 10px; color: #8f8c85">T</span></div><div style="flex: 1 1 0; display: flex; flex-direction: column; align-items: center; gap: 4px"><div style="width: 100%; height: 48px; border-radius: 3px; background: #86b5a0"></div><span class="mono" style="font-size: 10px; color: #8f8c85">F</span></div><div style="flex: 1 1 0; display: flex; flex-direction: column; align-items: center; gap: 4px"><div style="width: 100%; height: 3px; border-radius: 3px; background: #26282c"></div><span class="mono" style="font-size: 10px; color: #8f8c85">S</span></div><div style="flex: 1 1 0; display: flex; flex-direction: column; align-items: center; gap: 4px"><div style="width: 100%; height: 3px; border-radius: 3px; background: #26282c"></div><span class="mono" style="font-size: 10px; color: #8f8c85">S</span></div>
</div>
<div class="hint">Only 1 day of history. The projection steadies after a week of runs.</div>
</div>
</section>
</div>
</div>
</main>
<button aria-label="Chat with Archie" style="position: absolute; right: 24px; bottom: 24px; width: 48px; height: 48px; border-radius: 50%; border: 1px solid #34373c; background: #1e2023; color: #86b5a0; display: flex; align-items: center; justify-content: center; box-shadow: 0 8px 24px rgba(0,0,0,.4); cursor: pointer"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12Z"></path></svg></button>
</div>
</body>
</html>
@@ -1,127 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task detail</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.btn-ghost{background:transparent;border-color:transparent;color:#a6a39b}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column;min-width:0}
.card-h{display:flex;align-items:center;gap:12px;padding:14px 20px;border-bottom:1px solid #232529}
.card-t{font-size:14px;font-weight:500}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0}
.warn{color:#d9a45b;border-color:rgba(217,164,91,.3);background:rgba(217,164,91,.08)}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.nav a.on{color:#e8e6e1;background:#1e2023}
.tab{height:44px;display:flex;align-items:center;font-size:13px;color:#8f8c85;border-bottom:2px solid transparent}
.sel{height:32px;box-sizing:border-box;padding:0 10px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:13px 'IBM Plex Sans',sans-serif}
.kv{display:grid;grid-template-columns:96px minmax(0,1fr);gap:10px;font-size:13px;padding:8px 0;border-bottom:1px solid #202225}
.kv dt{color:#8f8c85}.kv dd{margin:0}
.tag{font:11px 'IBM Plex Mono',monospace;color:#a6a39b;background:#1e2023;border-radius:4px;padding:1px 6px}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 1000px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#86b5a0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#">Dashboard</a><a href="#" class="on">Tasks</a><a href="#">Workflows</a><a href="#">Events</a><a href="#">Settings</a></nav>
<div style="flex-grow: 1"></div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 220px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%"><span class="mono" style="font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span></label>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: #86b5a0"></span>Connected</span>
<span aria-label="Account" style="width: 28px; height: 28px; border-radius: 50%; background: #26282c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b">A</span>
</header>
<main style="flex-grow: 1; padding: 24px 48px 32px; display: flex; flex-direction: column; gap: 20px; min-height: 0">
<div>
<div class="hint"><a href="#" style="color: #a6a39b">Tasks</a> / <span class="mono">#1</span></div>
<div style="display: flex; align-items: flex-start; gap: 16px; margin-top: 8px">
<div style="flex-grow: 1; min-width: 0">
<h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">changes_captured key-set validation is top-level only</h1>
<div style="display: flex; align-items: center; gap: 12px; margin-top: 8px; font-size: 13px; color: #a6a39b">
<span class="pill warn"><span class="dot" style="background: #d9a45b"></span>Parked</span>
<span class="mono">tdd</span><span style="color: #4a4c50">·</span>
<a href="#" class="mono" style="color: #a6a39b; text-decoration: underline">samcharles93/archie-core #868</a>
</div>
</div>
<button class="btn btn-ghost">Archive</button>
<button class="btn btn-primary"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-3-6.7L21 8"></path><path d="M21 3v5h-5"></path></svg>Start a new run</button>
</div>
</div>
<div role="alert" style="display: flex; gap: 12px; padding: 14px 16px; border-radius: 8px; background: rgba(217,164,91,0.08); border: 1px solid rgba(217,164,91,0.25)">
<svg style="flex-shrink: 0; margin-top: 2px" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#d9a45b" stroke-width="2"><path d="M12 3 2 20h20L12 3Z"></path><path d="M12 10v4M12 17h.01"></path></svg>
<div style="min-width: 0; flex-grow: 1">
<div style="font-size: 14px; font-weight: 500; color: #e3c08f">Parked: couldn’t prepare the worktree</div>
<div class="mono" style="font-size: 12px; color: #a6a39b; margin-top: 4px; line-height: 1.6; word-break: break-all">fetch origin: http transport: Get "https://github.com/samcharles93/archie-core.git/info/refs?service=git-upload-pack": terminated signal received</div>
</div>
<button class="btn btn-sm" style="align-self: flex-start">Jump to log line</button>
</div>
<div style="display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 24px; flex-grow: 1; min-height: 0">
<section class="card" style="overflow: hidden">
<nav style="display: flex; gap: 28px; padding: 0 20px; border-bottom: 1px solid #232529">
<a class="tab" href="#" style="color: #e8e6e1; border-bottom-color: #86b5a0">Log</a>
<a class="tab" href="#">Changed files <span class="hint" style="margin-left: 6px">0</span></a>
<a class="tab" href="#">Configuration</a>
<a class="tab" href="#">Debug</a>
</nav>
<div style="display: flex; align-items: center; gap: 8px; padding: 12px 20px; border-bottom: 1px solid #232529">
<select aria-label="Level" class="sel"><option>All levels</option></select>
<select aria-label="Stage" class="sel"><option>All stages</option></select>
<label style="display: flex; align-items: center; gap: 8px; height: 32px; width: 260px; padding: 0 10px; box-sizing: border-box; border: 1px solid #2e3034; border-radius: 6px; color: #8f8c85"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Search log" placeholder="Search log" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: 13px 'IBM Plex Sans', sans-serif; width: 100%"></label>
<div style="flex-grow: 1"></div>
<button class="btn btn-sm btn-ghost"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 4v11M7 10l5 5 5-5M5 20h14"></path></svg>Download</button>
</div>
<div class="mono" style="font-size: 12px; line-height: 1.7; flex-grow: 1; background: #121314">
<div style="display: grid; grid-template-columns: 72px 56px minmax(0, 1fr); gap: 12px; padding: 10px 20px; background: rgba(217,119,107,0.06); border-left: 2px solid #d9776b">
<span style="color: #8f8c85">08:38:49</span>
<span style="color: #e0a39a">ERROR</span>
<div style="min-width: 0">
<div style="word-break: break-all">task parked: worktree prepare failed: fetch origin: http transport: Get "https://github.com/samcharles93/archie-core.git/info/refs?service=git-upload-pack": terminated signal received</div>
<div style="display: flex; gap: 6px; margin-top: 6px"><span class="tag">component=daemon</span><span class="tag">task=1</span></div>
</div>
</div>
<div style="padding: 16px 20px; color: #8f8c85; font-family: 'IBM Plex Sans', sans-serif; font-size: 12px">End of attempt 1 · 1 line</div>
</div>
</section>
<aside style="display: flex; flex-direction: column; gap: 20px">
<section class="card">
<div class="card-h"><span class="card-t">Attempts</span></div>
<div style="padding: 8px 12px">
<a href="#" style="display: flex; align-items: center; gap: 10px; padding: 10px 8px; border-radius: 6px; background: #1e2023; box-shadow: inset 2px 0 0 #86b5a0">
<span class="dot" style="background: #d9a45b"></span><span style="font-size: 13px; flex-grow: 1">Attempt 1</span><span class="hint">parked · 08:38</span></a>
<div style="display: flex; align-items: center; gap: 10px; padding: 10px 8px; color: #8f8c85">
<span class="dot" style="background: transparent; border: 1px dashed #4a4c50; box-sizing: border-box"></span><span style="font-size: 13px; flex-grow: 1">Attempt 2</span><span class="hint">not recorded</span></div>
</div>
</section>
<section class="card">
<div class="card-h"><span class="card-t">Details</span></div>
<dl style="margin: 0; padding: 4px 20px 12px">
<div class="kv"><dt>Status</dt><dd style="color: #d9a45b">Parked</dd></div>
<div class="kv"><dt>Workflow</dt><dd><a href="#" class="mono" style="text-decoration: underline">tdd</a></dd></div>
<div class="kv"><dt>Repository</dt><dd class="mono" style="font-size: 12px">samcharles93/archie-core</dd></div>
<div class="kv"><dt>Issue</dt><dd><a href="#" style="text-decoration: underline">#868</a> ↗</dd></div>
<div class="kv"><dt>Persona</dt><dd class="mono" style="font-size: 12px">[persona]</dd></div>
<div class="kv"><dt>Tokens</dt><dd class="mono" style="font-size: 12px">[tokens]</dd></div>
<div class="kv" style="border: 0"><dt>Started</dt><dd>[date · time]</dd></div>
</dl>
</section>
</aside>
</div>
</main>
</div>
</body>
</html>
@@ -1,152 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Workflows</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.btn-ghost{background:transparent;border-color:transparent;color:#a6a39b}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column;min-width:0}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.lbl{font-size:13px;font-weight:500}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.nav a.on{color:#e8e6e1;background:#1e2023}
.tab{height:44px;display:flex;align-items:center;font-size:13px;color:#8f8c85;border-bottom:2px solid transparent}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.step{font:12px 'IBM Plex Mono',monospace;padding:6px 10px;border:1px solid #2e3034;border-radius:6px;background:#121314;white-space:nowrap}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 1080px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#86b5a0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#">Dashboard</a><a href="#">Tasks</a><a href="#" class="on">Workflows</a><a href="#">Events</a><a href="#">Settings</a></nav>
<div style="flex-grow: 1"></div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 220px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%"><span class="mono" style="font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span></label>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: #86b5a0"></span>Connected</span>
<span aria-label="Account" style="width: 28px; height: 28px; border-radius: 50%; background: #26282c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b">A</span>
</header>
<main style="flex-grow: 1; padding: 32px 48px; display: flex; flex-direction: column; gap: 24px; min-height: 0">
<div style="display: flex; align-items: flex-end; gap: 12px">
<div style="flex-grow: 1">
<h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Workflows</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">The step sequences agents follow. Success rate is merged tasks over all runs.</p>
</div>
<button class="btn btn-ghost"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 12a9 9 0 1 0 3-6.7L3 8"></path><path d="M3 3v5h5"></path></svg>Restore shipped</button>
<button class="btn"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New workflow</button>
</div>
<div style="display: grid; grid-template-columns: 420px minmax(0, 1fr); gap: 24px; flex-grow: 1; min-height: 0">
<section class="card" style="overflow: hidden">
<div style="display: grid; grid-template-columns: minmax(0, 1fr) 56px 110px 72px; gap: 12px; padding: 10px 16px; font-size: 11px; letter-spacing: .06em; text-transform: uppercase; color: #8f8c85; border-bottom: 1px solid #2a2c30"><span>Workflow</span><span>Runs</span><span>Success</span><span style="text-align: right">Avg tok</span></div>
<a href="#" style="display: grid; grid-template-columns: minmax(0, 1fr) 56px 110px 72px; gap: 12px; align-items: center; padding: 14px 16px; border-bottom: 1px solid #202225; background: #1e2023; box-shadow: inset 2px 0 0 #86b5a0">
<span><span style="font-size: 14px; font-weight: 500; display: block">Bootstrap</span><span class="mono" style="font-size: 11px; color: #8f8c85">bootstrap</span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b">0</span>
<span style="display: flex; flex-direction: column; gap: 4px"><span class="mono" style="font-size: 12px">—</span><span style="height: 4px; border-radius: 2px; background: #26282c; width: 100%"><span style="display: block; height: 4px; border-radius: 2px; width: 0%; background: #86b5a0"></span></span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b; text-align: right">—</span>
</a>
<a href="#" style="display: grid; grid-template-columns: minmax(0, 1fr) 56px 110px 72px; gap: 12px; align-items: center; padding: 14px 16px; border-bottom: 1px solid #202225; background: transparent; box-shadow: none">
<span><span style="font-size: 14px; font-weight: 500; display: block">Feasibility check</span><span class="mono" style="font-size: 11px; color: #8f8c85">feasibility</span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b">0</span>
<span style="display: flex; flex-direction: column; gap: 4px"><span class="mono" style="font-size: 12px">—</span><span style="height: 4px; border-radius: 2px; background: #26282c; width: 100%"><span style="display: block; height: 4px; border-radius: 2px; width: 0%; background: #86b5a0"></span></span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b; text-align: right">—</span>
</a>
<a href="#" style="display: grid; grid-template-columns: minmax(0, 1fr) 56px 110px 72px; gap: 12px; align-items: center; padding: 14px 16px; border-bottom: 1px solid #202225; background: transparent; box-shadow: none">
<span><span style="font-size: 14px; font-weight: 500; display: block">Implement</span><span class="mono" style="font-size: 11px; color: #8f8c85">implement</span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b">0</span>
<span style="display: flex; flex-direction: column; gap: 4px"><span class="mono" style="font-size: 12px">—</span><span style="height: 4px; border-radius: 2px; background: #26282c; width: 100%"><span style="display: block; height: 4px; border-radius: 2px; width: 0%; background: #86b5a0"></span></span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b; text-align: right">—</span>
</a>
<a href="#" style="display: grid; grid-template-columns: minmax(0, 1fr) 56px 110px 72px; gap: 12px; align-items: center; padding: 14px 16px; border-bottom: 1px solid #202225; background: transparent; box-shadow: none">
<span><span style="font-size: 14px; font-weight: 500; display: block">Remediate</span><span class="mono" style="font-size: 11px; color: #8f8c85">remediate</span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b">0</span>
<span style="display: flex; flex-direction: column; gap: 4px"><span class="mono" style="font-size: 12px">—</span><span style="height: 4px; border-radius: 2px; background: #26282c; width: 100%"><span style="display: block; height: 4px; border-radius: 2px; width: 0%; background: #86b5a0"></span></span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b; text-align: right">—</span>
</a>
<a href="#" style="display: grid; grid-template-columns: minmax(0, 1fr) 56px 110px 72px; gap: 12px; align-items: center; padding: 14px 16px; border-bottom: 1px solid #202225; background: transparent; box-shadow: none">
<span><span style="font-size: 14px; font-weight: 500; display: block">TDD</span><span class="mono" style="font-size: 11px; color: #8f8c85">tdd</span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b">3</span>
<span style="display: flex; flex-direction: column; gap: 4px"><span class="mono" style="font-size: 12px">0 of 3</span><span style="height: 4px; border-radius: 2px; background: #26282c; width: 100%"><span style="display: block; height: 4px; border-radius: 2px; width: 2%; background: #d9776b"></span></span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b; text-align: right">4.7M</span>
</a>
<a href="#" style="display: grid; grid-template-columns: minmax(0, 1fr) 56px 110px 72px; gap: 12px; align-items: center; padding: 14px 16px; border-bottom: 1px solid #202225; background: transparent; box-shadow: none">
<span><span style="font-size: 14px; font-weight: 500; display: block">Triage</span><span class="mono" style="font-size: 11px; color: #8f8c85">triage</span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b">1</span>
<span style="display: flex; flex-direction: column; gap: 4px"><span class="mono" style="font-size: 12px">1 of 1</span><span style="height: 4px; border-radius: 2px; background: #26282c; width: 100%"><span style="display: block; height: 4px; border-radius: 2px; width: 100%; background: #86b5a0"></span></span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b; text-align: right">282k</span>
</a>
</section>
<section class="card" style="overflow: hidden">
<div style="display: flex; align-items: center; gap: 12px; padding: 18px 24px 0">
<h2 style="margin: 0; font-size: 18px; font-weight: 600">Bootstrap</h2>
<span class="pill">shipped · edited</span>
<div style="flex-grow: 1"></div>
<span class="hint">0 runs yet</span>
</div>
<nav style="display: flex; gap: 28px; padding: 0 24px; border-bottom: 1px solid #232529">
<a class="tab" href="#" style="color: #e8e6e1; border-bottom-color: #86b5a0">Definition</a>
<a class="tab" href="#">Performance</a>
<a class="tab" href="#">Runs</a>
</nav>
<div style="padding: 20px 24px; display: flex; flex-direction: column; gap: 18px; flex-grow: 1; min-height: 0">
<div style="display: grid; grid-template-columns: 280px minmax(0, 1fr); gap: 24px">
<div style="display: flex; flex-direction: column; gap: 6px"><label class="lbl" for="wid">ID</label><input id="wid" class="inp" value="bootstrap"></div>
<div style="display: flex; flex-direction: column; gap: 6px"><span class="lbl">Steps</span>
<div style="display: flex; align-items: center; gap: 6px; height: 36px; flex-wrap: nowrap; overflow: hidden">
<span class="step">prepare</span><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#4a4c50" stroke-width="2"><path d="M5 12h14M13 6l6 6-6 6"></path></svg><span class="step">apply</span><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#4a4c50" stroke-width="2"><path d="M5 12h14M13 6l6 6-6 6"></path></svg><span class="step">commit-push</span><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#4a4c50" stroke-width="2"><path d="M5 12h14M13 6l6 6-6 6"></path></svg><span class="step">diff-cap</span><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#4a4c50" stroke-width="2"><path d="M5 12h14M13 6l6 6-6 6"></path></svg><span class="step">open-pr</span>
</div></div>
</div>
<div style="display: flex; flex-direction: column; gap: 6px; flex-grow: 1; min-height: 0">
<div style="display: flex; align-items: baseline"><span class="lbl">YAML</span><span class="hint" style="margin-left: auto; color: #86b5a0">✓ Valid</span></div>
<div class="mono" style="flex-grow: 1; display: grid; grid-template-columns: 44px minmax(0, 1fr); border: 1px solid #2e3034; border-radius: 8px; background: #121314; font-size: 13px; line-height: 1.75; overflow: hidden">
<div style="padding: 14px 0; text-align: right; padding-right: 12px; color: #4f5156; border-right: 1px solid #232529; background: #141517; white-space: pre-line">1
2
3
4
5
6
7</div>
<div style="padding: 14px 16px; white-space: pre"><span style="color: #a6a39b">id:</span> bootstrap
<span style="color: #a6a39b">steps:</span>
- <span style="color: #a6a39b">type:</span> <span style="color: #86b5a0">bootstrap.prepare</span>
- <span style="color: #a6a39b">type:</span> <span style="color: #86b5a0">bootstrap.apply</span>
- <span style="color: #a6a39b">type:</span> <span style="color: #86b5a0">bootstrap.commit-push</span>
- <span style="color: #a6a39b">type:</span> <span style="color: #86b5a0">bootstrap.diff-cap</span>
- <span style="color: #a6a39b">type:</span> <span style="color: #86b5a0">bootstrap.open-pr</span></div>
</div>
</div>
</div>
<div style="display: flex; align-items: center; gap: 10px; padding: 14px 24px; border-top: 1px solid #2a2c30; background: #17181a">
<span class="hint">Version 1 · <a href="#" style="color: #a6a39b; text-decoration: underline">History</a></span>
<div style="flex-grow: 1"></div>
<button class="btn btn-ghost" style="color: #d9776b">Remove</button>
<button class="btn">Restore this workflow</button>
<button class="btn btn-primary">Validate &amp; save</button>
</div>
</section>
</div>
</main>
</div>
</body>
</html>
@@ -1,77 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>New task dialog</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.btn-ghost{background:transparent;border-color:transparent;color:#a6a39b}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.lbl{font-size:13px;font-weight:500}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.inp{box-sizing:border-box;height:38px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.field{display:flex;flex-direction:column;gap:6px}
.opt{display:flex;flex-direction:column;gap:2px;padding:10px 12px;border:1px solid #2e3034;border-radius:8px;cursor:pointer}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 900px; box-sizing: border-box; position: relative; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#86b5a0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#">Dashboard</a><a href="#">Tasks</a><a href="#">Workflows</a><a href="#">Events</a><a href="#">Settings</a></nav>
<div style="flex-grow: 1"></div>
<button class="btn btn-sm" style="border-color: #86b5a0"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: #86b5a0"></span>Connected</span>
</header>
<div style="padding: 32px 48px"><div style="font-size: 28px; font-weight: 600; color: #3a3c40">Good morning</div></div>
<div style="position: absolute; inset: 0; background: rgba(8,9,10,0.6)"></div>
<section role="dialog" aria-modal="true" aria-labelledby="nt-title" style="position: absolute; left: 50%; top: 88px; transform: translateX(-50%); width: 640px; box-sizing: border-box; background: #17181a; border: 1px solid #2a2c30; border-radius: 12px; box-shadow: 0 24px 64px rgba(0,0,0,0.5); display: flex; flex-direction: column">
<div style="display: flex; align-items: flex-start; padding: 22px 24px 18px; border-bottom: 1px solid #232529">
<div style="flex-grow: 1"><h2 id="nt-title" style="margin: 0; font-size: 18px; font-weight: 600">New task</h2><div class="hint" style="margin-top: 2px">Goes into Archie’s normal task queue.</div></div>
<button aria-label="Close" style="width: 32px; height: 32px; border: 0; background: transparent; color: #8f8c85; cursor: pointer"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 6l12 12M18 6 6 18"></path></svg></button>
</div>
<div style="padding: 20px 24px; display: flex; flex-direction: column; gap: 18px">
<div class="field"><label class="lbl" for="repo">Repository</label><input id="repo" class="inp" value="samcharles93/archie-core"><span class="hint">owner/repository · recent: archie-core</span></div>
<div class="field"><span class="lbl">Workflow</span>
<div role="radiogroup" aria-label="Workflow" style="display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px">
<label class="opt" style="border-color: #86b5a0; background: #1e2023"><span style="font-size: 13px; font-weight: 500">TDD</span><span class="hint">3 runs · 0% merged</span></label>
<label class="opt" style="border-color: #2e3034; background: transparent"><span style="font-size: 13px; font-weight: 500">Triage</span><span class="hint">1 run · 100% merged</span></label>
<label class="opt" style="border-color: #2e3034; background: transparent"><span style="font-size: 13px; font-weight: 500">Implement</span><span class="hint">no runs yet</span></label>
<label class="opt" style="border-color: #2e3034; background: transparent"><span style="font-size: 13px; font-weight: 500">Remediate</span><span class="hint">no runs yet</span></label>
<label class="opt" style="border-color: #2e3034; background: transparent"><span style="font-size: 13px; font-weight: 500">Feasibility check</span><span class="hint">no runs yet</span></label>
<label class="opt" style="border-color: #2e3034; background: transparent"><span style="font-size: 13px; font-weight: 500">Bootstrap</span><span class="hint">no runs yet</span></label>
</div></div>
<div class="field"><label class="lbl" for="ttl">Title</label><input id="ttl" class="inp" placeholder="What should Archie do?" style="font-family: 'IBM Plex Sans', sans-serif"></div>
<div class="field"><label class="lbl" for="ins">Instructions</label><textarea id="ins" placeholder="Context, acceptance criteria, files to look at…" style="min-height: 120px; box-sizing: border-box; padding: 12px; background: #121314; border: 1px solid #2e3034; border-radius: 6px; color: #e8e6e1; font: 13px/1.6 'IBM Plex Sans', sans-serif; resize: vertical; outline: none"></textarea></div>
<details style="font-size: 13px; color: #a6a39b"><summary style="cursor: pointer">Advanced · run as identity</summary></details>
</div>
<div style="display: flex; align-items: center; gap: 10px; padding: 14px 24px; border-top: 1px solid #232529">
<span class="hint"><span class="mono" style="padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘↵</span> to start</span>
<div style="flex-grow: 1"></div>
<button class="btn btn-ghost">Cancel</button>
<button class="btn btn-primary">Start task</button>
</div>
</section>
</div>
</body>
</html>
@@ -1,102 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Events</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column;min-width:0}
.card-h{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid #232529}
.card-t{font-size:15px;font-weight:500}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.nav a.on{color:#e8e6e1;background:#1e2023}
.tab{height:44px;display:flex;align-items:center;gap:8px;font-size:13px;color:#8f8c85;border-bottom:2px solid transparent}
.count{font:11px 'IBM Plex Mono',monospace;color:#8f8c85;background:#1e2023;border-radius:4px;padding:0 6px}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 900px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#86b5a0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#">Dashboard</a><a href="#">Tasks</a><a href="#">Workflows</a><a href="#" class="on">Events</a><a href="#">Settings</a></nav>
<div style="flex-grow: 1"></div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 220px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%"><span class="mono" style="font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span></label>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: #86b5a0"></span>Connected</span>
<span aria-label="Account" style="width: 28px; height: 28px; border-radius: 50%; background: #26282c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b">A</span>
</header>
<main style="flex-grow: 1; padding: 32px 48px; display: flex; flex-direction: column; gap: 24px">
<div>
<div style="display: flex; align-items: flex-end; gap: 12px">
<div style="flex-grow: 1"><h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Events</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">Webhooks come in, get mapped to event types, and bindings turn them into work.</p></div>
<span class="pill" style="color: #86b5a0; border-color: #86b5a0"><span class="dot" style="background: #86b5a0"></span>Listening</span>
</div>
<nav style="display: flex; gap: 28px; margin-top: 16px; border-bottom: 1px solid #232529">
<a class="tab" href="#" style="color: #e8e6e1; border-bottom-color: #86b5a0">Inspector</a>
<a class="tab" href="#">Mappings <span class="count">0</span></a>
<a class="tab" href="#">Bindings <span class="count">0</span></a>
</nav>
</div>
<section class="card" style="flex-direction: row">
<div style="flex: 1 1 0; display: flex; align-items: center; gap: 14px; padding: 18px 22px; border-right: 1px solid #232529">
<span class="mono" style="width: 28px; height: 28px; border-radius: 50%; border: 1px solid #34373c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b; flex-shrink: 0">1</span>
<div style="flex-grow: 1"><div style="font-size: 14px; font-weight: 500">Capture</div><div class="hint">Webhooks received</div></div>
<span class="mono" style="font-size: 20px; color: #8f8c85">0</span>
</div>
<div style="flex: 1 1 0; display: flex; align-items: center; gap: 14px; padding: 18px 22px; border-right: 1px solid #232529">
<span class="mono" style="width: 28px; height: 28px; border-radius: 50%; border: 1px solid #34373c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b; flex-shrink: 0">2</span>
<div style="flex-grow: 1"><div style="font-size: 14px; font-weight: 500">Map</div><div class="hint">Payloads → event types</div></div>
<span class="mono" style="font-size: 20px; color: #8f8c85">0</span>
</div>
<div style="flex: 1 1 0; display: flex; align-items: center; gap: 14px; padding: 18px 22px; border-right: 1px solid #232529">
<span class="mono" style="width: 28px; height: 28px; border-radius: 50%; border: 1px solid #34373c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b; flex-shrink: 0">3</span>
<div style="flex-grow: 1"><div style="font-size: 14px; font-weight: 500">Bind</div><div class="hint">Event types → work</div></div>
<span class="mono" style="font-size: 20px; color: #8f8c85">0</span>
</div>
</section>
<div style="display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap: 24px">
<section class="card">
<div class="card-h"><div style="flex-grow: 1"><div class="card-t">Recent captures</div><div class="hint">Headers and payloads are redacted before they’re stored.</div></div></div>
<div style="padding: 40px 32px; display: flex; flex-direction: column; align-items: center; gap: 12px; text-align: center">
<div style="width: 40px; height: 40px; border-radius: 10px; background: #1e2023; display: flex; align-items: center; justify-content: center"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#a6a39b" stroke-width="2"><path d="M22 12h-6l-2 3h-4l-2-3H2"></path><path d="M5.5 5h13L22 12v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-6Z"></path></svg></div>
<div style="font-size: 14px; font-weight: 500">No captures yet</div>
<div class="hint">Point a webhook at this endpoint and it shows up here live.</div>
<div style="display: flex; align-items: center; gap: 8px; margin-top: 6px; padding: 4px 4px 4px 14px; border: 1px solid #2e3034; border-radius: 8px; background: #121314">
<span class="mono" style="font-size: 13px">/webhooks/capture/<span style="color: #86b5a0">&lt;source&gt;</span></span>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="8" y="8" width="12" height="12" rx="2"></rect><path d="M16 8V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3"></path></svg>Copy</button>
</div>
</div>
</section>
<section class="card">
<div class="card-h"><div style="flex-grow: 1"><div class="card-t">Event types</div><div class="hint">Named shapes that mappings produce.</div></div>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9l-6-6Z"></path><path d="M12 12v6M9 15h6"></path></svg>From payload</button></div>
<div style="padding: 40px 32px; display: flex; flex-direction: column; align-items: center; gap: 8px; text-align: center">
<div style="font-size: 14px; font-weight: 500">No event types or proposals</div>
<div class="hint">Paste a sample payload and Archie proposes a type for it. Proposals from real captures appear here too.</div>
</div>
</section>
</div>
</main>
</div>
</body>
</html>
@@ -1,176 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Settings – sidebar layout</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none}
.inp:focus{border-color:var(--accent)}
.btn{height:36px;padding:0 16px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.icon-btn{width:36px;height:36px;display:flex;align-items:center;justify-content:center;border-radius:6px;border:1px solid transparent;background:transparent;color:#8f8c85;cursor:pointer}
.icon-btn:hover{background:#1e2023;color:#e8e6e1}
.nav-item{display:flex;align-items:center;gap:10px;height:36px;padding:0 12px;border-radius:6px;color:#a6a39b;font-size:13px}
.row{display:grid;grid-template-columns:280px minmax(0,1fr);gap:32px;padding:20px 0;border-top:1px solid #232529}
.lbl{font-size:13px;font-weight:500;color:#e8e6e1}
.hint{font-size:12px;color:#8f8c85;margin-top:4px;line-height:1.5}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 1040px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; position: relative; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 28px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#86b5a0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>
Archie
</div>
<nav style="display: flex; gap: 4px; font-size: 13px">
<a href="#" style="padding: 8px 12px; color: #a6a39b">Dashboard</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Tasks</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Workflows</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Events</a>
<a href="#" style="padding: 8px 12px; color: #e8e6e1; background: #1e2023; border-radius: 6px">Settings</a>
</nav>
<div style="flex-grow: 1"></div>
<div style="display: flex; align-items: center; gap: 8px; font-size: 12px; color: #a6a39b; padding: 6px 10px; border: 1px solid #2a2c30; border-radius: 999px">
<span style="width: 7px; height: 7px; border-radius: 50%; background: #d9a45b"></span>
Connecting to archie-core…
</div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 240px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg>
<input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%">
<span style="font-family: 'IBM Plex Mono', monospace; font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span>
</label>
</header>
<div style="display: flex; flex-grow: 1; min-height: 0">
<aside style="width: 264px; flex-shrink: 0; box-sizing: border-box; padding: 24px 16px; border-right: 1px solid #232529; display: flex; flex-direction: column; gap: 2px">
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 0 12px 8px">Agents</div>
<a class="nav-item" href="#">Personas<span style="margin-left: auto; font-family: 'IBM Plex Mono', monospace; font-size: 11px; color: #8f8c85">6</span></a>
<a class="nav-item" href="#">Schedules<span style="margin-left: auto; font-family: 'IBM Plex Mono', monospace; font-size: 11px; color: #8f8c85">0</span></a>
<a class="nav-item" href="#" style="background: #1e2023; color: #e8e6e1; box-shadow: inset 2px 0 0 #86b5a0">Scheduling policy<span style="margin-left: auto; width: 6px; height: 6px; border-radius: 50%; background: #86b5a0" title="Unsaved changes"></span></a>
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 18px 12px 8px">Integrations</div>
<a class="nav-item" href="#">Channels</a>
<a class="nav-item" href="#">Tools &amp; MCP</a>
<a class="nav-item" href="#">Plugins</a>
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 18px 12px 8px">Runtime</div>
<a class="nav-item" href="#">Container runtime</a>
<div style="height: 1px; background: #232529; margin: 16px 12px"></div>
<a class="nav-item" href="#">History</a>
<div style="flex-grow: 1"></div>
<div style="font-size: 12px; color: #8f8c85; padding: 12px; line-height: 1.5; border: 1px solid #232529; border-radius: 8px">Config version 1 · last saved by <span style="color: #a6a39b">admin</span><br><a href="#" style="color: #86b5a0">View history</a></div>
</aside>
<main style="flex-grow: 1; overflow: hidden; padding: 40px 56px 120px">
<div style="max-width: 920px">
<div style="display: flex; align-items: flex-start; gap: 16px">
<div style="flex-grow: 1">
<h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Scheduling policy</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">How Archie picks up work items and labels them as they move through states.</p>
</div>
<span style="display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: #d9a45b; background: rgba(217,164,91,0.1); border: 1px solid rgba(217,164,91,0.25); padding: 4px 10px; border-radius: 999px">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-3-6.7L21 8"></path><path d="M21 3v5h-5"></path></svg>
Applies after restart</span>
</div>
<h2 style="margin: 36px 0 4px; font-size: 13px; font-weight: 600; color: #a6a39b; text-transform: uppercase; letter-spacing: 0.06em">Dispatch</h2>
<div class="row">
<div><div class="lbl">Trigger</div><div class="hint">What causes a work item to be dispatched to an agent.</div></div>
<div style="display: flex; flex-direction: column; gap: 12px">
<div role="radiogroup" aria-label="Trigger" style="display: inline-flex; align-self: flex-start; padding: 3px; background: #121314; border: 1px solid #2e3034; border-radius: 8px">
<button style="height: 30px; padding: 0 14px; border: 0; border-radius: 5px; background: #26282c; color: #e8e6e1; font: 500 13px 'IBM Plex Sans', sans-serif">Assignee</button>
<button style="height: 30px; padding: 0 14px; border: 0; border-radius: 5px; background: transparent; color: #8f8c85; font: 500 13px 'IBM Plex Sans', sans-serif">Label</button>
</div>
<div class="hint" style="margin: 0">Dispatches when Archie is assigned. Choose <span style="color: #a6a39b">Label</span> to set a trigger label instead.</div>
</div>
</div>
<div class="row">
<div><label class="lbl" for="ack">Ack reaction</label><div class="hint">Reaction posted when a work item is picked up.</div></div>
<div><input id="ack" class="inp" value="eyes" style="width: 220px"></div>
</div>
<h2 style="margin: 36px 0 4px; font-size: 13px; font-weight: 600; color: #a6a39b; text-transform: uppercase; letter-spacing: 0.06em">State labels</h2>
<div class="row">
<div><div class="lbl">Labels by state</div><div class="hint">Label applied to the ticket as the agent moves between states.</div></div>
<div style="border: 1px solid #2a2c30; border-radius: 8px; overflow: hidden">
<div style="display: grid; grid-template-columns: 140px minmax(0, 1fr) 44px; gap: 12px; padding: 8px 12px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: #8f8c85; background: #17181a; border-bottom: 1px solid #2a2c30"><span>State</span><span>Label</span><span></span></div>
<div style="display: grid; grid-template-columns: 140px minmax(0, 1fr) 44px; gap: 12px; align-items: center; padding: 6px 12px; border-bottom: 1px solid #202225">
<span style="display: flex; align-items: center; gap: 8px; font-size: 13px"><span style="width: 8px; height: 8px; border-radius: 2px; background: #8f8c85"></span>queued</span>
<input class="inp" aria-label="queued label" value="agent:queued" style="width: 100%; height: 32px">
<button class="icon-btn" aria-label="Remove queued"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"></path></svg></button>
</div>
<div style="display: grid; grid-template-columns: 140px minmax(0, 1fr) 44px; gap: 12px; align-items: center; padding: 6px 12px; border-bottom: 1px solid #202225">
<span style="display: flex; align-items: center; gap: 8px; font-size: 13px"><span style="width: 8px; height: 8px; border-radius: 2px; background: #8aa4c2"></span>working</span>
<input class="inp" aria-label="working label" value="agent:working" style="width: 100%; height: 32px">
<button class="icon-btn" aria-label="Remove working"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"></path></svg></button>
</div>
<div style="display: grid; grid-template-columns: 140px minmax(0, 1fr) 44px; gap: 12px; align-items: center; padding: 6px 12px; border-bottom: 1px solid #202225">
<span style="display: flex; align-items: center; gap: 8px; font-size: 13px"><span style="width: 8px; height: 8px; border-radius: 2px; background: #d9a45b"></span>waiting</span>
<input class="inp" aria-label="waiting label" value="agent:waiting" style="width: 100%; height: 32px">
<button class="icon-btn" aria-label="Remove waiting"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"></path></svg></button>
</div>
<div style="display: grid; grid-template-columns: 140px minmax(0, 1fr) 44px; gap: 12px; align-items: center; padding: 6px 12px; border-bottom: 1px solid #202225">
<span style="display: flex; align-items: center; gap: 8px; font-size: 13px"><span style="width: 8px; height: 8px; border-radius: 2px; background: #86b5a0"></span>pr</span>
<input class="inp" aria-label="pr label" value="agent:pr" style="width: 100%; height: 32px">
<button class="icon-btn" aria-label="Remove pr"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"></path></svg></button>
</div>
<div style="display: grid; grid-template-columns: 140px minmax(0, 1fr) 44px; gap: 12px; align-items: center; padding: 6px 12px; border-bottom: 1px solid #202225">
<span style="display: flex; align-items: center; gap: 8px; font-size: 13px"><span style="width: 8px; height: 8px; border-radius: 2px; background: #6f6c66"></span>parked</span>
<input class="inp" aria-label="parked label" value="agent:parked" style="width: 100%; height: 32px">
<button class="icon-btn" aria-label="Remove parked"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"></path></svg></button>
</div>
<div style="display: grid; grid-template-columns: 140px minmax(0, 1fr) 44px; gap: 12px; align-items: center; padding: 6px 12px; border-bottom: 1px solid #202225">
<span style="display: flex; align-items: center; gap: 8px; font-size: 13px"><span style="width: 8px; height: 8px; border-radius: 2px; background: #d9776b"></span>dead</span>
<input class="inp" aria-label="dead label" value="agent:dead" style="width: 100%; height: 32px">
<button class="icon-btn" aria-label="Remove dead"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"></path></svg></button>
</div>
<button style="display: flex; align-items: center; gap: 6px; width: 100%; height: 38px; padding: 0 12px; border: 0; background: transparent; color: #a6a39b; font: 500 13px 'IBM Plex Sans', sans-serif; cursor: pointer"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>Add state</button>
</div>
</div>
<h2 style="margin: 36px 0 4px; font-size: 13px; font-weight: 600; color: #a6a39b; text-transform: uppercase; letter-spacing: 0.06em">Retries &amp; polling</h2>
<div class="row">
<div><label class="lbl" for="retries">Max retries</label><div class="hint">Attempts before an item is labelled dead.</div></div>
<div style="display: inline-flex; align-self: flex-start; border: 1px solid #2e3034; border-radius: 6px; overflow: hidden; width: fit-content">
<button class="icon-btn" aria-label="Decrease" style="border-radius: 0">−</button>
<input id="retries" class="inp" value="3" style="width: 56px; border: 0; border-radius: 0; text-align: center; border-left: 1px solid #2e3034; border-right: 1px solid #2e3034">
<button class="icon-btn" aria-label="Increase" style="border-radius: 0">+</button>
</div>
</div>
<div class="row">
<div><label class="lbl" for="poll">Poll interval</label><div class="hint">How often the tracker is checked for new work.</div></div>
<div style="display: flex; align-items: center; gap: 10px">
<div style="display: flex">
<input id="poll" class="inp" value="30" style="width: 80px; border-radius: 6px 0 0 6px; border-color: #86b5a0">
<select aria-label="Poll unit" class="inp" style="border-radius: 0 6px 6px 0; border-left: 0; font-family: 'IBM Plex Sans', sans-serif"><option>seconds</option><option>minutes</option></select>
</div>
<span style="font-size: 12px; color: #8f8c85">was <span style="font-family: 'IBM Plex Mono', monospace; text-decoration: line-through">1m0s</span></span>
</div>
</div>
</div>
</main>
</div>
<div style="position: absolute; left: 264px; right: 0; bottom: 0; height: 72px; box-sizing: border-box; padding: 0 56px; display: flex; align-items: center; gap: 12px; background: #17181a; border-top: 1px solid #2a2c30">
<span style="width: 8px; height: 8px; border-radius: 50%; background: #86b5a0"></span>
<span style="font-size: 13px">1 unsaved change</span>
<span style="font-size: 13px; color: #8f8c85">· Poll interval</span>
<div style="flex-grow: 1"></div>
<button class="btn" style="background: transparent; border-color: transparent; color: #a6a39b">Discard</button>
<button class="btn btn-primary">Save &amp; restart</button>
</div>
</div>
</body>
</html>
@@ -1,154 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Settings – personas</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none}
.btn{height:36px;padding:0 16px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.tab{height:44px;display:flex;align-items:center;padding:0 2px;font-size:13px;color:#8f8c85;border-bottom:2px solid transparent}
.lbl{font-size:13px;font-weight:500;color:#e8e6e1}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 1040px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 28px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#86b5a0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>
Archie
</div>
<nav style="display: flex; gap: 4px; font-size: 13px">
<a href="#" style="padding: 8px 12px; color: #a6a39b">Dashboard</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Work</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Events</a>
<a href="#" style="padding: 8px 12px; color: #e8e6e1; background: #1e2023; border-radius: 6px">System</a>
</nav>
<div style="flex-grow: 1"></div>
<div style="display: flex; align-items: center; gap: 8px; font-size: 12px; color: #a6a39b; padding: 6px 10px; border: 1px solid #2a2c30; border-radius: 999px">
<span style="width: 7px; height: 7px; border-radius: 50%; background: #86b5a0"></span>
Connected · v1
</div>
</header>
<div style="padding: 32px 48px 0; border-bottom: 1px solid #232529; flex-shrink: 0">
<div style="font-size: 12px; color: #8f8c85">System / Advanced</div>
<h1 style="margin: 6px 0 20px; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Advanced settings</h1>
<nav style="display: flex; gap: 28px">
<a class="tab" href="#" style="color: #e8e6e1; border-bottom-color: #86b5a0">Personas</a>
<a class="tab" href="#">Schedules</a>
<a class="tab" href="#">Scheduling policy</a>
<a class="tab" href="#">Tools &amp; MCP</a>
<a class="tab" href="#">Plugins</a>
<a class="tab" href="#">Container runtime</a>
</nav>
</div>
<div style="display: flex; flex-grow: 1; min-height: 0; padding: 32px 48px 40px; gap: 32px">
<section aria-label="Persona list" style="width: 340px; flex-shrink: 0; display: flex; flex-direction: column; gap: 12px">
<div style="display: flex; align-items: center; gap: 8px">
<label style="flex-grow: 1; display: flex; align-items: center; gap: 8px; height: 36px; padding: 0 12px; border: 1px solid #2e3034; border-radius: 6px; color: #8f8c85">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg>
<input aria-label="Filter personas" placeholder="Filter personas" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: 13px 'IBM Plex Sans', sans-serif; width: 100%">
</label>
<button class="btn" aria-label="New persona" style="padding: 0 12px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New</button>
</div>
<div style="border: 1px solid #2a2c30; border-radius: 10px; overflow: hidden; background: #16171a">
<a href="#" style="display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border-bottom: 1px solid #222428; background: #1e2023; box-shadow: inset 2px 0 0 #86b5a0">
<span style="display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500">archie
<span style="font-size: 11px; font-weight: 500; color: #86b5a0; border: 1px solid #86b5a0; border-radius: 999px; padding: 1px 8px">default</span>
</span>
<span style="font-size: 12px; color: #8f8c85; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">You are Archie, a capable coding and project assistant. Be direct without being brusque…</span>
</a>
<a href="#" style="display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border-bottom: 1px solid #222428; background: transparent; box-shadow: none">
<span style="display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500">helpful
</span>
<span style="font-size: 12px; color: #8f8c85; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">You are a helpful, friendly AI assistant.</span>
</a>
<a href="#" style="display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border-bottom: 1px solid #222428; background: transparent; box-shadow: none">
<span style="display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500">concise
</span>
<span style="font-size: 12px; color: #8f8c85; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">You are a concise assistant. Keep responses brief and to the point.</span>
</a>
<a href="#" style="display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border-bottom: 1px solid #222428; background: transparent; box-shadow: none">
<span style="display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500">technical
</span>
<span style="font-size: 12px; color: #8f8c85; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">You are a technical expert. Provide detailed, accurate technical information.</span>
</a>
<a href="#" style="display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border-bottom: 1px solid #222428; background: transparent; box-shadow: none">
<span style="display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500">creative
</span>
<span style="font-size: 12px; color: #8f8c85; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">You are a creative assistant. Think outside the box and offer innovative solutions.</span>
</a>
<a href="#" style="display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border-bottom: 1px solid #222428; background: transparent; box-shadow: none">
<span style="display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500">teacher
</span>
<span style="font-size: 12px; color: #8f8c85; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">You are a patient teacher. Explain concepts clearly with examples.</span>
</a>
</div>
<div class="hint">Personas are system prompts an agent can adopt. The default is used when a work item doesn't specify one.</div>
</section>
<section aria-label="Edit persona" style="flex-grow: 1; display: flex; flex-direction: column; border: 1px solid #2a2c30; border-radius: 10px; background: #16171a; overflow: hidden">
<div style="display: flex; align-items: center; gap: 12px; padding: 18px 24px; border-bottom: 1px solid #2a2c30">
<h2 style="margin: 0; font-size: 18px; font-weight: 600">archie</h2>
<span style="font-size: 11px; color: #86b5a0; border: 1px solid #86b5a0; border-radius: 999px; padding: 1px 8px">default</span>
<div style="flex-grow: 1"></div>
<button class="btn" style="background: transparent">Duplicate</button>
<button class="btn" style="background: transparent; color: #d9776b; border-color: #3a2a28">Delete</button>
</div>
<div style="display: flex; flex-direction: column; gap: 24px; padding: 24px; flex-grow: 1">
<div style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px">
<div style="display: flex; flex-direction: column; gap: 8px">
<label class="lbl" for="pname">Name</label>
<input id="pname" class="inp" value="archie">
<span class="hint">Lowercase, used as the persona key.</span>
</div>
<div style="display: flex; flex-direction: column; gap: 8px">
<span class="lbl">Default persona</span>
<label style="display: flex; align-items: center; gap: 10px; height: 36px; font-size: 13px; color: #a6a39b">
<span style="width: 36px; height: 20px; border-radius: 999px; background: #86b5a0; position: relative; display: inline-block"><span style="position: absolute; right: 2px; top: 2px; width: 16px; height: 16px; border-radius: 50%; background: #121314"></span></span>
Use when no persona is specified
</label>
</div>
</div>
<div style="display: flex; flex-direction: column; gap: 8px; flex-grow: 1">
<div style="display: flex; align-items: baseline"><label class="lbl" for="prompt">System prompt</label><span class="hint" style="margin-left: auto; font-family: 'IBM Plex Mono', monospace">312 chars · ~70 tokens</span></div>
<textarea id="prompt" style="flex-grow: 1; min-height: 320px; box-sizing: border-box; padding: 16px; background: #121314; border: 1px solid #2e3034; border-radius: 8px; color: #e8e6e1; font: 400 13px/1.7 'IBM Plex Mono', monospace; resize: vertical; outline: none">You are Archie, a capable coding and project assistant. Be direct without being brusque, grounded in the actual workspace state, and use available tools when asked. Do not claim tools, files, memories, actions, or results you have not verified. Do not impersonate another assistant, provider, or vendor.</textarea>
</div>
<div style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border: 1px dashed #2e3034; border-radius: 8px">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#8f8c85" stroke-width="2"><path d="M4 12h12M12 6l6 6-6 6"></path></svg>
<span style="font-size: 13px; color: #a6a39b; flex-grow: 1">Try this persona against a sample message before saving</span>
<button class="btn">Open preview</button>
</div>
</div>
<div style="display: flex; align-items: center; gap: 12px; padding: 16px 24px; border-top: 1px solid #2a2c30; background: #17181a">
<span style="font-size: 12px; color: #8f8c85">Saved · version 1 · <a href="#" style="color: #a6a39b; text-decoration: underline">History</a></span>
<div style="flex-grow: 1"></div>
<button class="btn" style="background: transparent; border-color: transparent; color: #a6a39b">Discard</button>
<button class="btn btn-primary">Save persona</button>
</div>
</section>
</div>
</div>
</body>
</html>
@@ -1,144 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Settings – tools and MCP</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column}
.card-h{display:flex;align-items:center;gap:12px;padding:18px 20px;border-bottom:1px solid #232529}
.card-b{padding:20px;display:flex;flex-direction:column;gap:18px}
.lbl{font-size:13px;font-weight:500;color:#e8e6e1}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.field{display:flex;flex-direction:column;gap:6px}
.sw{width:36px;height:20px;border-radius:999px;position:relative;display:inline-block;flex-shrink:0}
.sw i{position:absolute;top:2px;width:16px;height:16px;border-radius:50%}
.nav-item{display:flex;align-items:center;gap:10px;height:36px;padding:0 12px;border-radius:6px;color:#a6a39b;font-size:13px}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 1080px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 28px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#86b5a0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>
Archie
</div>
<nav style="display: flex; gap: 4px; font-size: 13px">
<a href="#" style="padding: 8px 12px; color: #a6a39b">Dashboard</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Tasks</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Workflows</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Events</a>
<a href="#" style="padding: 8px 12px; color: #e8e6e1; background: #1e2023; border-radius: 6px">Settings</a>
</nav>
<div style="flex-grow: 1"></div>
<div style="display: flex; align-items: center; gap: 8px; font-size: 12px; color: #a6a39b; padding: 6px 10px; border: 1px solid #2a2c30; border-radius: 999px">
<span style="width: 7px; height: 7px; border-radius: 50%; background: #86b5a0"></span>
Connected · v1
</div>
</header>
<div style="display: flex; flex-grow: 1; min-height: 0">
<aside style="width: 232px; flex-shrink: 0; box-sizing: border-box; padding: 24px 12px; border-right: 1px solid #232529; display: flex; flex-direction: column; gap: 2px">
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 0 12px 8px">Agents</div>
<a class="nav-item" href="#">Personas</a>
<a class="nav-item" href="#">Schedules</a>
<a class="nav-item" href="#">Scheduling policy</a>
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 18px 12px 8px">Integrations</div>
<a class="nav-item" href="#">Channels</a>
<a class="nav-item" href="#" style="background: #1e2023; color: #e8e6e1; box-shadow: inset 2px 0 0 #86b5a0">Tools &amp; MCP</a>
<a class="nav-item" href="#">Plugins</a>
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 18px 12px 8px">Runtime</div>
<a class="nav-item" href="#">Container runtime</a>
<div style="height: 1px; background: #232529; margin: 16px 12px"></div>
<a class="nav-item" href="#">History</a>
</aside>
<main style="flex-grow: 1; padding: 36px 48px; overflow: hidden">
<div style="display: flex; align-items: flex-end; gap: 16px; margin-bottom: 28px">
<div style="flex-grow: 1">
<h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Tools &amp; MCP</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">External tools, model providers and fetch limits available to agents.</p>
</div>
<button class="btn btn-primary"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>Add MCP server</button>
</div>
<div style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px">
<section class="card" style="grid-column: span 2">
<div class="card-h">
<div style="width: 32px; height: 32px; border-radius: 8px; background: #1e2023; display: flex; align-items: center; justify-content: center"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a6a39b" stroke-width="2"><rect x="3" y="4" width="18" height="6" rx="1"></rect><rect x="3" y="14" width="18" height="6" rx="1"></rect><path d="M7 7h.01M7 17h.01"></path></svg></div>
<div style="flex-grow: 1"><div class="lbl" style="font-size: 15px">MCP servers</div><div class="hint">Model Context Protocol servers agents can call.</div></div>
</div>
<div style="display: flex; align-items: center; gap: 20px; padding: 28px 20px">
<div style="flex-grow: 1">
<div style="font-size: 14px; color: #e8e6e1">No MCP servers yet</div>
<div class="hint" style="margin-top: 4px">Add a stdio command or an HTTP endpoint. Agents see its tools on next restart.</div>
</div>
<button class="btn">stdio command</button>
<button class="btn">HTTP / SSE endpoint</button>
</div>
</section>
<section class="card">
<div class="card-h">
<div style="width: 32px; height: 32px; border-radius: 8px; background: #1e2023; display: flex; align-items: center; justify-content: center; font: 600 13px 'IBM Plex Mono', monospace; color: #a6a39b">Mx</div>
<div style="flex-grow: 1"><div class="lbl" style="font-size: 15px">MiniMax</div><div class="hint">Model provider</div></div>
<label style="display: flex; align-items: center; gap: 8px; font-size: 12px; color: #a6a39b">Enabled<span class="sw" style="background: #86b5a0"><i style="right: 2px; background: #121314"></i></span></label>
</div>
<div class="card-b">
<div class="field">
<span class="lbl">API key</span>
<div style="display: flex; align-items: center; gap: 10px; height: 40px; padding: 0 12px; border: 1px solid #2e3034; border-radius: 6px; background: #121314">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#8f8c85" stroke-width="2"><rect x="4" y="10" width="16" height="10" rx="2"></rect><path d="M8 10V7a4 4 0 0 1 8 0v3"></path></svg>
<span style="font: 12px 'IBM Plex Mono', monospace; color: #8f8c85">bws</span>
<span style="color: #4a4c50">/</span>
<span style="font: 13px 'IBM Plex Mono', monospace">MINIMAX_API_KEY</span>
<div style="flex-grow: 1"></div>
<button class="btn" style="height: 28px; padding: 0 10px; font-size: 12px; background: transparent">Change</button>
</div>
<div style="display: flex; align-items: center; gap: 6px; font-size: 12px; color: #86b5a0"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="m5 12 5 5 9-10"></path></svg>Credential resolved by Archie</div>
</div>
</div>
</section>
<section class="card">
<div class="card-h">
<div style="width: 32px; height: 32px; border-radius: 8px; background: #1e2023; display: flex; align-items: center; justify-content: center"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a6a39b" stroke-width="2"><circle cx="12" cy="12" r="9"></circle><path d="M3 12h18M12 3c3 3 3 15 0 18M12 3c-3 3-3 15 0 18"></path></svg></div>
<div style="flex-grow: 1"><div class="lbl" style="font-size: 15px">Web fetch</div><div class="hint">Let agents download pages and files</div></div>
<label style="display: flex; align-items: center; gap: 8px; font-size: 12px; color: #a6a39b">Enabled<span class="sw" style="background: #86b5a0"><i style="right: 2px; background: #121314"></i></span></label>
</div>
<div class="card-b">
<div style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px">
<div class="field"><label class="lbl" for="mb">Max download</label><div style="display: flex"><input id="mb" class="inp" value="2" style="border-radius: 6px 0 0 6px"><span style="display: flex; align-items: center; padding: 0 12px; border: 1px solid #2e3034; border-left: 0; border-radius: 0 6px 6px 0; font-size: 12px; color: #8f8c85">MB</span></div></div>
<div class="field"><label class="lbl" for="to">Timeout</label><div style="display: flex"><input id="to" class="inp" value="30" style="border-radius: 6px 0 0 6px"><span style="display: flex; align-items: center; padding: 0 12px; border: 1px solid #2e3034; border-left: 0; border-radius: 0 6px 6px 0; font-size: 12px; color: #8f8c85">sec</span></div></div>
</div>
<label style="display: flex; align-items: flex-start; gap: 12px; padding: 12px; border: 1px solid #2a2c30; border-radius: 8px">
<span class="sw" style="background: #2e3034; margin-top: 2px"><i style="left: 2px; background: #8f8c85"></i></span>
<span><span class="lbl">Allow private networks</span><span class="hint" style="display: block">Off: requests to 10.x, 192.168.x and localhost are blocked.</span></span>
</label>
</div>
</section>
<section class="card" style="grid-column: span 2">
<div class="card-h">
<div style="flex-grow: 1"><div class="lbl" style="font-size: 15px">Tool output policy</div><div class="hint">Large tool results are truncated or spilled to disk.</div></div>
</div>
<div class="card-b" style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px">
<div class="field"><label class="lbl" for="mrc">Max result length</label><div style="display: flex"><input id="mrc" class="inp" value="50,000" style="border-radius: 6px 0 0 6px"><span style="display: flex; align-items: center; padding: 0 12px; border: 1px solid #2e3034; border-left: 0; border-radius: 0 6px 6px 0; font-size: 12px; color: #8f8c85; white-space: nowrap">chars</span></div><span class="hint">About 12k tokens per tool call.</span></div>
<div class="field"><label class="lbl" for="spill">Spill directory</label><input id="spill" class="inp" placeholder="Not set — results over the limit are truncated"><span class="hint">Full output is written here and the agent gets a path.</span></div>
</div>
</section>
</div>
</main>
</div>
</div>
</body>
</html>
@@ -1,124 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Settings – review changes</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.btn{height:36px;padding:0 16px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.acc{display:flex;align-items:center;gap:14px;padding:16px 20px;border:1px solid #2a2c30;border-radius:10px;background:#16171a}
.lbl{font-size:13px;font-weight:500;color:#e8e6e1}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.sum{font:12px 'IBM Plex Mono',monospace;color:#8f8c85}
.field{display:flex;flex-direction:column;gap:6px}
.chev{color:#8f8c85}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 1080px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden; position: relative">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 28px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#86b5a0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>
Archie
</div>
<nav style="display: flex; gap: 4px; font-size: 13px">
<a href="#" style="padding: 8px 12px; color: #a6a39b">Dashboard</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Work</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Events</a>
<a href="#" style="padding: 8px 12px; color: #e8e6e1; background: #1e2023; border-radius: 6px">System</a>
</nav>
</header>
<main style="width: 880px; padding: 36px 0 0 64px; display: flex; flex-direction: column; gap: 12px">
<h1 style="margin: 0 0 4px; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Advanced settings</h1>
<p style="margin: 0 0 16px; font-size: 14px; color: #a6a39b">Collapsed sections show their current values at a glance.</p>
<div class="acc"><svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 6 6 6-6 6"></path></svg><span class="lbl" style="width: 180px">Personas</span><span class="sum" style="flex-grow: 1">6 personas · default archie</span></div>
<div class="acc"><svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 6 6 6-6 6"></path></svg><span class="lbl" style="width: 180px">Schedules</span><span class="sum" style="flex-grow: 1">none</span></div>
<div class="acc" style="border-color: #3a3f3c"><svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 6 6 6-6 6"></path></svg><span class="lbl" style="width: 180px">Scheduling policy</span><span class="sum" style="flex-grow: 1">trigger assignee · 3 retries · poll 30s</span><span style="font-size: 11px; color: #86b5a0">1 edited</span></div>
<div class="acc"><svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 6 6 6-6 6"></path></svg><span class="lbl" style="width: 180px">Tools &amp; MCP</span><span class="sum" style="flex-grow: 1">0 MCP · MiniMax on · web fetch on</span></div>
<div class="acc"><svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 6 6 6-6 6"></path></svg><span class="lbl" style="width: 180px">Plugins</span><span class="sum" style="flex-grow: 1">all directories default</span></div>
<section style="border: 1px solid #3a3f3c; border-radius: 10px; background: #16171a">
<div style="display: flex; align-items: center; gap: 14px; padding: 16px 20px; border-bottom: 1px solid #232529">
<svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m6 9 6 6 6-6"></path></svg>
<span class="lbl" style="flex-grow: 1">Container runtime</span>
<span style="font-size: 11px; color: #86b5a0">2 edited</span>
</div>
<div style="padding: 20px; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px 24px">
<div class="field" style="grid-column: span 2"><label class="lbl" for="img">Image</label><input id="img" class="inp" value="ghcr.io/samcharles93/archie-agent:latest"></div>
<div class="field"><label class="lbl" for="mc">Max concurrency</label><input id="mc" class="inp" value="6" style="border-color: #86b5a0"></div>
<div class="field"><label class="lbl" for="mu">Max uptime</label><input id="mu" class="inp" value="2h" style="border-color: #86b5a0"></div>
<div class="field"><label class="lbl" for="net">Network</label><input id="net" class="inp" value="archie-core_default"></div>
<div class="field"><label class="lbl" for="pp">Pull policy</label><select id="pp" class="inp" style="font-family: 'IBM Plex Sans', sans-serif"><option>If missing</option><option>Always</option><option>Never</option></select></div>
<div class="field"><label class="lbl" for="vt">Volume TTL</label><input id="vt" class="inp" value="72h"></div>
<div class="field"><label class="lbl" for="pr">Profiles</label><input id="pr" class="inp" placeholder="None"></div>
</div>
</section>
</main>
<div style="position: absolute; left: 0; top: 56px; right: 0; bottom: 0; background: rgba(8,9,10,0.55)"></div>
<aside aria-label="Review changes" style="position: absolute; top: 56px; right: 0; bottom: 0; width: 480px; box-sizing: border-box; background: #17181a; border-left: 1px solid #2a2c30; display: flex; flex-direction: column; box-shadow: -24px 0 48px rgba(0,0,0,0.35)">
<div style="display: flex; align-items: center; padding: 20px 24px; border-bottom: 1px solid #2a2c30">
<div style="flex-grow: 1"><h2 style="margin: 0; font-size: 17px; font-weight: 600">Review 3 changes</h2><div class="hint" style="margin-top: 2px">Saved together as config version 2</div></div>
<button aria-label="Close" style="width: 36px; height: 36px; border: 0; background: transparent; color: #8f8c85; cursor: pointer"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 6l12 12M18 6 6 18"></path></svg></button>
</div>
<div style="flex-grow: 1; padding: 20px 24px; display: flex; flex-direction: column; gap: 20px">
<div style="display: flex; gap: 10px; padding: 12px 14px; border-radius: 8px; background: rgba(217,164,91,0.08); border: 1px solid rgba(217,164,91,0.25); color: #e3c08f; font-size: 13px; line-height: 1.5">
<svg style="flex-shrink: 0; margin-top: 2px" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-3-6.7L21 8"></path><path d="M21 3v5h-5"></path></svg>
<span>All three need an archie-core restart. 2 agents are running; they'll finish before the restart.</span>
</div>
<div style="display: flex; flex-direction: column; gap: 8px">
<div style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: #8f8c85">Scheduling policy</div>
<div style="border: 1px solid #2a2c30; border-radius: 8px; overflow: hidden">
<div style="display: flex; align-items: center; padding: 10px 14px; font-size: 13px; font-weight: 500"><span style="flex-grow: 1">Poll interval</span><a href="#" style="font-size: 12px; font-weight: 400; color: #8f8c85; text-decoration: underline">Revert</a></div>
<div style="font: 12px/1.9 'IBM Plex Mono', monospace; border-top: 1px solid #232529">
<div style="padding: 0 14px; background: rgba(217,119,107,0.08); color: #e0a39a">− 1m0s</div>
<div style="padding: 0 14px; background: rgba(134,181,160,0.10); color: #a9d1bf">+ 30s</div>
</div>
</div>
</div>
<div style="display: flex; flex-direction: column; gap: 8px">
<div style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: #8f8c85">Container runtime</div>
<div style="border: 1px solid #2a2c30; border-radius: 8px; overflow: hidden">
<div style="display: flex; align-items: center; padding: 10px 14px; font-size: 13px; font-weight: 500"><span style="flex-grow: 1">Max concurrency</span><a href="#" style="font-size: 12px; font-weight: 400; color: #8f8c85; text-decoration: underline">Revert</a></div>
<div style="font: 12px/1.9 'IBM Plex Mono', monospace; border-top: 1px solid #232529">
<div style="padding: 0 14px; background: rgba(217,119,107,0.08); color: #e0a39a">− 4</div>
<div style="padding: 0 14px; background: rgba(134,181,160,0.10); color: #a9d1bf">+ 6</div>
</div>
</div>
<div style="border: 1px solid #2a2c30; border-radius: 8px; overflow: hidden">
<div style="display: flex; align-items: center; padding: 10px 14px; font-size: 13px; font-weight: 500"><span style="flex-grow: 1">Max uptime</span><a href="#" style="font-size: 12px; font-weight: 400; color: #8f8c85; text-decoration: underline">Revert</a></div>
<div style="font: 12px/1.9 'IBM Plex Mono', monospace; border-top: 1px solid #232529">
<div style="padding: 0 14px; background: rgba(217,119,107,0.08); color: #e0a39a">− 1h0m0s</div>
<div style="padding: 0 14px; background: rgba(134,181,160,0.10); color: #a9d1bf">+ 2h0m0s</div>
</div>
</div>
</div>
</div>
<div style="display: flex; align-items: center; gap: 12px; padding: 16px 24px; border-top: 1px solid #2a2c30">
<button class="btn" style="background: transparent; border-color: transparent; color: #a6a39b">Discard all</button>
<div style="flex-grow: 1"></div>
<button class="btn">Save only</button>
<button class="btn btn-primary">Save &amp; restart</button>
</div>
</aside>
</div>
</body>
</html>
@@ -1,155 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Settings – channels</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.btn-ghost{background:transparent;border-color:transparent;color:#a6a39b}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column;min-width:0}
.card-h{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid #232529}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.lbl{font-size:13px;font-weight:500}
.eyebrow{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:#8f8c85;font-weight:500}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.nav a.on{color:#e8e6e1;background:#1e2023}
.nav-item{display:flex;align-items:center;gap:10px;height:34px;padding:0 12px;border-radius:6px;color:#a6a39b;font-size:13px}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.row{display:grid;grid-template-columns:260px minmax(0,1fr);gap:32px;padding:16px 20px;border-top:1px solid #232529}
.sw{width:36px;height:20px;border-radius:999px;position:relative;display:inline-block;flex-shrink:0}
.sw i{position:absolute;top:2px;width:16px;height:16px;border-radius:50%}
.icon{width:32px;height:32px;border-radius:8px;background:#1e2023;display:flex;align-items:center;justify-content:center;flex-shrink:0}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 1300px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="#86b5a0" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#">Dashboard</a><a href="#">Tasks</a><a href="#">Workflows</a><a href="#">Events</a><a href="#" class="on">Settings</a></nav>
<div style="flex-grow: 1"></div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 220px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%"><span class="mono" style="font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span></label>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: #86b5a0"></span>Connected</span>
<span aria-label="Account" style="width: 28px; height: 28px; border-radius: 50%; background: #26282c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b">A</span>
</header>
<div style="display: flex; flex-grow: 1; min-height: 0">
<aside style="width: 248px; flex-shrink: 0; box-sizing: border-box; padding: 24px 14px; border-right: 1px solid #232529; display: flex; flex-direction: column; gap: 2px">
<div class="eyebrow" style="padding: 0 12px 8px">Agents</div>
<a class="nav-item" href="#">Personas</a><a class="nav-item" href="#">Schedules</a><a class="nav-item" href="#">Scheduling policy</a>
<div class="eyebrow" style="padding: 18px 12px 8px">Integrations</div>
<a class="nav-item" href="#" style="background: #1e2023; color: #e8e6e1; box-shadow: inset 2px 0 0 #86b5a0">Channels<span class="dot" style="margin-left: auto; background: #86b5a0" title="1 running"></span></a>
<a class="nav-item" href="#">Tools &amp; MCP</a><a class="nav-item" href="#">Plugins</a>
<div class="eyebrow" style="padding: 18px 12px 8px">Runtime</div>
<a class="nav-item" href="#">Container runtime</a>
<div style="height: 1px; background: #232529; margin: 16px 12px"></div>
<a class="nav-item" href="#"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"></circle><path d="M12 7v5l3 2"></path></svg>History</a>
</aside>
<main style="flex-grow: 1; padding: 36px 56px; display: flex; flex-direction: column; gap: 24px; min-width: 0">
<div style="display: flex; align-items: flex-start; gap: 16px; max-width: 980px">
<div style="flex-grow: 1">
<h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Channels</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">Where you talk to Archie, and how chat sessions behave.</p>
</div>
<span class="pill" style="color: #d9a45b; border-color: rgba(217,164,91,.3); background: rgba(217,164,91,.08)">Applies after restart</span>
</div>
<div style="max-width: 980px; display: flex; flex-direction: column; gap: 16px">
<section class="card">
<div class="card-h">
<div class="icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a6a39b" stroke-width="2"><path d="m22 3-9.5 18-2.5-8-8-2.5L22 3Z"></path></svg></div>
<div style="flex-grow: 1"><div style="font-size: 15px; font-weight: 500">Telegram</div><div class="hint">Talk to Archie and approve its work from your phone.</div></div>
<span class="pill" style="color: #86b5a0; border-color: #86b5a0"><span class="dot" style="background: #86b5a0"></span>Running</span>
</div>
<div class="row" style="border-top: 0">
<div><div class="lbl">Bot token</div><div class="hint">Secret reference for the Telegram bot.</div></div>
<div>
<div style="display: flex; align-items: center; gap: 10px; height: 38px; padding: 0 12px; border: 1px solid #2e3034; border-radius: 6px; background: #121314">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#8f8c85" stroke-width="2"><rect x="4" y="10" width="16" height="10" rx="2"></rect><path d="M8 10V7a4 4 0 0 1 8 0v3"></path></svg>
<span class="mono" style="font-size: 12px; color: #8f8c85">env</span><span style="color: #4a4c50">/</span><span class="mono" style="font-size: 13px">HEYARCHIE_TELEGRAM_BOT_TOKEN</span>
<div style="flex-grow: 1"></div><button class="btn btn-sm" style="height: 26px; background: transparent">Change</button>
</div>
<div style="display: flex; align-items: center; gap: 6px; font-size: 12px; color: #86b5a0; margin-top: 6px"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="m5 12 5 5 9-10"></path></svg>Credential resolved by Archie</div>
</div>
</div>
<div class="row">
<div><div class="lbl">Allowed users</div><div class="hint">Telegram user IDs that may talk to Archie. Everyone else is ignored.</div></div>
<div style="display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 6px; border: 1px solid #2e3034; border-radius: 6px; background: #121314; min-height: 38px; box-sizing: border-box">
<span style="display: inline-flex; align-items: center; gap: 6px; height: 26px; padding: 0 6px 0 10px; border-radius: 4px; background: #1e2023; font: 12px 'IBM Plex Mono', monospace">1312197967<button aria-label="Remove 1312197967" style="width: 20px; height: 20px; border: 0; background: transparent; color: #8f8c85; cursor: pointer">×</button></span>
<input aria-label="Add user ID" placeholder="Add user ID…" style="flex-grow: 1; min-width: 140px; background: transparent; border: 0; outline: none; color: #e8e6e1; font: 12px 'IBM Plex Mono', monospace">
</div>
</div>
</section>
<section class="card" style="flex-direction: row; align-items: center; gap: 12px; padding: 16px 20px">
<div class="icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#8f8c85" stroke-width="2"><path d="M3 6h18v12H3zM3 6l9 7 9-7"></path></svg></div>
<div style="flex-grow: 1"><div style="font-size: 15px; font-weight: 500">Email</div><div class="hint">Listen for mail and relay replies.</div></div>
<span class="pill">Not set up</span>
<button class="btn btn-sm">Set up</button>
</section>
<section class="card" style="flex-direction: row; align-items: center; gap: 12px; padding: 16px 20px">
<div class="icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#8f8c85" stroke-width="2"><path d="M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1"></path></svg></div>
<div style="flex-grow: 1"><div style="font-size: 15px; font-weight: 500">Webhook</div><div class="hint">Deliver agent output to a URL, with a signing secret and template.</div></div>
<span class="pill">Not set up</span>
<button class="btn btn-sm">Set up</button>
</section>
<div class="eyebrow" style="margin-top: 16px">Chat session defaults · all channels</div>
<section class="card">
<div class="row" style="border-top: 0">
<div><label class="lbl" for="ws">Workspace</label><div class="hint">Directory chat sessions start in.</div></div>
<input id="ws" class="inp" value="/home/sam">
</div>
<div class="row">
<div><div class="lbl">Filesystem access</div><div class="hint">Outside the workspace.</div></div>
<div style="display: flex; align-items: flex-start; gap: 12px; padding: 12px; border: 1px solid rgba(217,119,107,.35); background: rgba(217,119,107,.06); border-radius: 8px">
<span class="sw" style="background: #d9776b; margin-top: 2px"><i style="right: 2px; background: #121314"></i></span>
<span><span class="lbl">Unrestricted filesystem</span><span class="hint" style="display: block; color: #e0a39a">On: agents can read and write anywhere this user can.</span></span>
</div>
</div>
<div class="row">
<div><div class="lbl">Show tool calls</div><div class="hint">Post each tool call into the chat.</div></div>
<label style="display: flex; align-items: center; gap: 10px; font-size: 13px; color: #a6a39b"><span class="sw" style="background: #86b5a0"><i style="right: 2px; background: #121314"></i></span>On</label>
</div>
<div class="row">
<div><label class="lbl" for="ms">Max steps</label><div class="hint">Per chat turn. 0 = no limit.</div></div>
<input id="ms" class="inp" value="0" style="width: 120px">
</div>
<div class="row">
<div><div class="lbl">Rate limit</div><div class="hint">Off while either value is 0.</div></div>
<div style="display: flex; align-items: center; gap: 10px; font-size: 13px; color: #a6a39b"><input aria-label="Max requests" class="inp" value="0" style="width: 90px"> requests per <input aria-label="Window" class="inp" value="0" style="width: 80px"><select aria-label="Window unit" class="inp" style="width: 110px; font-family: 'IBM Plex Sans', sans-serif"><option>minutes</option></select></div>
</div>
<div class="row">
<div><label class="lbl" for="md">Models</label><div class="hint">Models chat sessions may use.</div></div>
<input id="md" class="inp" placeholder="Default">
</div>
<div class="row">
<div><label class="lbl" for="op">Operator</label><div class="hint">Who Archie treats as its operator.</div></div>
<input id="op" class="inp" placeholder="Not set">
</div>
</section>
<div style="display: flex; align-items: center; gap: 10px; font-size: 12px; color: #8f8c85">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"></circle><path d="M12 7v5l3 2"></path></svg>
Version 1 · 11 fields set by <span class="mono">system:migration</span> 8 hrs ago · <a href="#" style="color: #a6a39b; text-decoration: underline">View in History</a>
</div>
</div>
</main>
</div>
</div>
</body>
</html>
@@ -1,138 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Theme and components</title>
<!-- Static snapshot of the design mockup (accent = sage #86b5a0). Generated from the matching file in source/. -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.btn{height:36px;padding:0 16px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.h{font-size:11px;text-transform:uppercase;letter-spacing:0.08em;color:#8f8c85;margin:0 0 14px;font-weight:500}
.panel{border:1px solid #2a2c30;border-radius:10px;background:#16171a;padding:24px}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:4px 10px;border-radius:999px;border:1px solid}
.dot{width:7px;height:7px;border-radius:50%}
.sw{width:36px;height:20px;border-radius:999px;position:relative;display:inline-block}
.sw i{position:absolute;top:2px;width:16px;height:16px;border-radius:50%}
.lbl{font-size:13px;font-weight:500;color:#e8e6e1}
.hint{font-size:12px;color:#8f8c85}
</style>
</head>
<body>
<div style="--accent: #86b5a0; width: 1440px; height: 980px; box-sizing: border-box; padding: 48px 56px; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; display: flex; flex-direction: column; gap: 24px">
<div>
<h1 style="margin: 0; font-size: 28px; font-weight: 600; letter-spacing: -0.01em">Graphite theme</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">Warm neutral greys carry the page; one low-chroma accent marks the active item, focus and primary action.</p>
</div>
<div style="display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 24px">
<section class="panel">
<h2 class="h">Palette</h2>
<div style="display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px">
<div style="display: flex; flex-direction: column; gap: 6px">
<div style="height: 44px; border-radius: 6px; background: #121314; border: 1px solid #2e3034"></div>
<span style="font-size: 12px">Ground</span>
<span style="font: 11px 'IBM Plex Mono', monospace; color: #8f8c85">#121314</span>
</div>
<div style="display: flex; flex-direction: column; gap: 6px">
<div style="height: 44px; border-radius: 6px; background: #16171a; border: 1px solid #2e3034"></div>
<span style="font-size: 12px">Surface</span>
<span style="font: 11px 'IBM Plex Mono', monospace; color: #8f8c85">#16171a</span>
</div>
<div style="display: flex; flex-direction: column; gap: 6px">
<div style="height: 44px; border-radius: 6px; background: #1e2023; border: 1px solid #2e3034"></div>
<span style="font-size: 12px">Raised</span>
<span style="font: 11px 'IBM Plex Mono', monospace; color: #8f8c85">#1e2023</span>
</div>
<div style="display: flex; flex-direction: column; gap: 6px">
<div style="height: 44px; border-radius: 6px; background: #2a2c30; border: 1px solid #2e3034"></div>
<span style="font-size: 12px">Border</span>
<span style="font: 11px 'IBM Plex Mono', monospace; color: #8f8c85">#2a2c30</span>
</div>
<div style="display: flex; flex-direction: column; gap: 6px">
<div style="height: 44px; border-radius: 6px; background: #e8e6e1; border: 1px solid #2e3034"></div>
<span style="font-size: 12px">Text</span>
<span style="font: 11px 'IBM Plex Mono', monospace; color: #8f8c85">#e8e6e1</span>
</div>
<div style="display: flex; flex-direction: column; gap: 6px">
<div style="height: 44px; border-radius: 6px; background: #8f8c85; border: 1px solid #2e3034"></div>
<span style="font-size: 12px">Muted</span>
<span style="font: 11px 'IBM Plex Mono', monospace; color: #8f8c85">#8f8c85</span>
</div>
<div style="display: flex; flex-direction: column; gap: 6px">
<div style="height: 44px; border-radius: 6px; background: #86b5a0; border: 1px solid #2e3034"></div>
<span style="font-size: 12px">Accent</span>
<span style="font: 11px 'IBM Plex Mono', monospace; color: #8f8c85">#86b5a0</span>
</div>
<div style="display: flex; flex-direction: column; gap: 6px">
<div style="height: 44px; border-radius: 6px; background: #d9a45b; border: 1px solid #2e3034"></div>
<span style="font-size: 12px">Warn</span>
<span style="font: 11px 'IBM Plex Mono', monospace; color: #8f8c85">#d9a45b</span>
</div>
</div>
<h2 class="h" style="margin-top: 24px">Type</h2>
<div style="display: flex; flex-direction: column; gap: 8px">
<span style="font-size: 24px; font-weight: 600">IBM Plex Sans 600 · 24</span>
<span style="font-size: 14px; color: #a6a39b">IBM Plex Sans 400 · 14 body</span>
<span style="font: 13px 'IBM Plex Mono', monospace">IBM Plex Mono · values, keys, durations</span>
</div>
</section>
<section class="panel">
<h2 class="h">Buttons</h2>
<div style="display: flex; gap: 10px; flex-wrap: wrap">
<button class="btn btn-primary">Save &amp; restart</button>
<button class="btn">Secondary</button>
<button class="btn" style="background: transparent; border-color: transparent; color: #a6a39b">Discard</button>
<button class="btn" style="background: transparent; color: #d9776b; border-color: #3a2a28">Delete</button>
</div>
<h2 class="h" style="margin-top: 24px">Status</h2>
<div style="display: flex; gap: 8px; flex-wrap: wrap">
<span class="pill" style="color: #a6a39b; border-color: #2e3034"><span class="dot" style="background: #86b5a0"></span>Connected</span>
<span class="pill" style="color: #a6a39b; border-color: #2e3034"><span class="dot" style="background: #d9a45b"></span>Connecting…</span>
<span class="pill" style="color: #d9a45b; border-color: rgba(217,164,91,0.3); background: rgba(217,164,91,0.08)">Applies after restart</span>
<span class="pill" style="color: #86b5a0; border-color: #86b5a0">2 edited</span>
<span class="pill" style="color: #e0a39a; border-color: rgba(217,119,107,0.35); background: rgba(217,119,107,0.08)">Invalid duration</span>
</div>
<h2 class="h" style="margin-top: 24px">Toggles &amp; choice</h2>
<div style="display: flex; align-items: center; gap: 20px">
<label style="display: flex; align-items: center; gap: 8px; font-size: 13px"><span class="sw" style="background: #86b5a0"><i style="right: 2px; background: #121314"></i></span>On</label>
<label style="display: flex; align-items: center; gap: 8px; font-size: 13px; color: #a6a39b"><span class="sw" style="background: #2e3034"><i style="left: 2px; background: #8f8c85"></i></span>Off</label>
<div style="display: inline-flex; padding: 3px; background: #121314; border: 1px solid #2e3034; border-radius: 8px">
<button style="height: 28px; padding: 0 12px; border: 0; border-radius: 5px; background: #26282c; color: #e8e6e1; font: 500 12px 'IBM Plex Sans', sans-serif">Assignee</button>
<button style="height: 28px; padding: 0 12px; border: 0; border-radius: 5px; background: transparent; color: #8f8c85; font: 500 12px 'IBM Plex Sans', sans-serif">Label</button>
</div>
</div>
</section>
<section class="panel" style="display: flex; flex-direction: column; gap: 16px">
<h2 class="h" style="margin: 0">Inputs</h2>
<div style="display: flex; flex-direction: column; gap: 6px"><label class="lbl" for="c1">Text</label><input id="c1" class="inp" value="archie-core_default"></div>
<div style="display: flex; flex-direction: column; gap: 6px"><label class="lbl" for="c2">Focused</label><input id="c2" class="inp" value="ghcr.io/…/archie-agent:latest" style="border-color: #86b5a0; box-shadow: 0 0 0 3px rgba(134,181,160,0.15)"></div>
<div style="display: flex; flex-direction: column; gap: 6px"><label class="lbl" for="c3">Duration with unit</label>
<div style="display: flex"><input id="c3" class="inp" value="72" style="border-radius: 6px 0 0 6px"><select aria-label="Unit" class="inp" style="width: 110px; border-radius: 0 6px 6px 0; border-left: 0; font-family: 'IBM Plex Sans', sans-serif"><option>hours</option></select></div></div>
<div style="display: flex; flex-direction: column; gap: 6px"><label class="lbl" for="c4">Error</label><input id="c4" class="inp" value="1hr" style="border-color: #d9776b"><span style="font-size: 12px; color: #e0a39a">Use a number and a unit, e.g. 1h or 90m</span></div>
<div style="display: flex; flex-direction: column; gap: 6px"><span class="lbl">Secret reference</span>
<div style="display: flex; align-items: center; gap: 8px; height: 36px; padding: 0 12px; border: 1px solid #2e3034; border-radius: 6px">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#8f8c85" stroke-width="2"><rect x="4" y="10" width="16" height="10" rx="2"></rect><path d="M8 10V7a4 4 0 0 1 8 0v3"></path></svg>
<span style="font: 12px 'IBM Plex Mono', monospace; color: #8f8c85">bws /</span><span style="font: 13px 'IBM Plex Mono', monospace">MINIMAX_API_KEY</span>
<span style="margin-left: auto; font-size: 12px; color: #86b5a0">resolved</span>
</div></div>
</section>
</div>
</div>
</body>
</html>
@@ -1,103 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Proposed navigation</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a}
.eyebrow{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:#8f8c85;font-weight:500}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.node{display:flex;align-items:baseline;gap:10px;font-size:14px;font-weight:500}
.sub{font-size:12px;color:#8f8c85;font-weight:400}
.kid{margin:6px 0 0 18px;padding-left:14px;border-left:1px solid #2e3034;display:flex;flex-direction:column;gap:6px;font-size:13px;color:#a6a39b}
.mono{font-family:'IBM Plex Mono',monospace}
.tbl{width:100%;border-collapse:collapse;font-size:13px}
.tbl th{text-align:left;font-weight:500;font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:#8f8c85;padding:10px 14px;border-bottom:1px solid #2a2c30}
.tbl td{padding:10px 14px;border-bottom:1px solid #202225;vertical-align:top;line-height:1.45}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 1120px; box-sizing: border-box; padding: 48px 56px; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; display: flex; flex-direction: column; gap: 28px">
<div>
<h1 style="margin: 0; font-size: 28px; font-weight: 600; letter-spacing: -0.01em">Navigation: today → proposed</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">Five top-level places, each with one job. Anything you configure lives in Settings; anything you act on lives where the work is.</p>
</div>
<div style="display: grid; grid-template-columns: 380px minmax(0, 1fr); gap: 24px">
<section class="card" style="padding: 24px; display: flex; flex-direction: column; gap: 16px">
<div class="eyebrow">Today</div>
<div class="node" style="color: #a6a39b">Dashboard</div>
<div><div class="node" style="color: #a6a39b">Work <span class="sub">dropdown</span></div>
<div class="kid"><span>Tasks</span><span>Workflows <span class="sub">editor + start work + stats</span></span><span>Channels <span class="sub">settings + audit</span></span></div></div>
<div><div class="node" style="color: #a6a39b">Events</div>
<div class="kid"><span>Inspector · Bindings · Mappings</span></div></div>
<div><div class="node" style="color: #a6a39b">System <span class="sub">dropdown</span></div>
<div class="kid"><span>Advanced <span class="sub">6 cards, 6 save buttons</span></span></div></div>
<p class="hint" style="margin: 8px 0 0">Dropdown contents are inferred from the screenshots; confirm against the router.</p>
</section>
<section class="card" style="padding: 24px">
<div class="eyebrow" style="margin-bottom: 16px; color: {{accent}}">Proposed</div>
<div style="display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 24px 32px">
<div><div class="node">Dashboard <span class="sub">what needs me</span></div>
<div class="kid"><span>Needs you queue</span><span>Live activity</span><span>Health: gates, tokens</span></div></div>
<div><div class="node">Tasks <span class="sub">the work</span></div>
<div class="kid"><span>Task list <span class="sub">filter by state</span></span><span>Task detail <span class="sub">log · files · config · debug</span></span><span>Attempts in a side rail</span></div></div>
<div><div class="node">Workflows <span class="sub">how work runs</span></div>
<div class="kid"><span>List with success + cost</span><span>Definition editor</span><span>Performance tab <span class="sub">stages, failures</span></span></div></div>
<div><div class="node">Events <span class="sub">what comes in</span></div>
<div class="kid"><span>Inspector</span><span>Bindings</span><span>Mappings</span></div></div>
<div style="grid-column: span 2"><div class="node">Settings <span class="sub">everything you configure, one save flow</span></div>
<div class="kid" style="display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 6px 24px">
<span><span style="color: #e8e6e1">Agents</span><br>Personas · Schedules · Scheduling policy</span>
<span><span style="color: #e8e6e1">Integrations</span><br>Channels · Tools &amp; MCP · Plugins</span>
<span><span style="color: #e8e6e1">Runtime</span><br>Container runtime · History</span>
</div></div>
</div>
<div style="margin-top: 24px; padding-top: 16px; border-top: 1px solid #232529; display: flex; gap: 24px; font-size: 13px; color: #a6a39b">
<span><span style="color: #e8e6e1; font-weight: 500">Always in the top bar:</span> New task · ⌘K Jump to · connection status</span>
</div>
</section>
</div>
<section class="card" style="overflow: hidden">
<table class="tbl">
<thead><tr><th style="width: 290px">What</th><th style="width: 280px">Moves to</th><th>Why</th></tr></thead>
<tbody>
<sc-for list="{{moves}}" as="m" hint-placeholder-count="9">
<tr><td style="color: #e8e6e1">{{m.what}}</td><td><span style="color: {{accent}}">→</span> {{m.to}}</td><td style="color: #a6a39b">{{m.why}}</td></tr>
</sc-for>
</tbody>
</table>
</section>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":1120}}'>
class Component extends DCLogic {
renderVals() {
return {
accent: this.props.accent ?? '#86b5a0',
moves: [
{ what: 'Start work card (Workflows)', to: 'New task dialog, from the top bar', why: 'Starting work is not editing a workflow. One entry point from any page, and from ⌘K.' },
{ what: 'Channels (Work menu)', to: 'Settings › Integrations › Channels', why: 'It is configuration. It gets the same setting rows, secret fields and save flow as the rest.' },
{ what: 'Audit table (Channels page)', to: 'Settings › History', why: 'One change log for every setting, filterable by section. Replaces six History links.' },
{ what: 'Per workflow table', to: 'Workflows list columns', why: 'Runs, success and cost sit next to the workflow you are about to open.' },
{ what: 'Slowest stages · Most failures', to: 'Workflow › Performance tab', why: 'Scoped to the selected workflow instead of mixing every workflow in one table.' },
{ what: 'Connecting · Version pills on every card', to: 'One status in the top bar', why: 'Connection is global. Version shows once per page, in History.' },
{ what: 'Settings "Managed elsewhere" row', to: 'Events tabs', why: 'Captured events, mappings and bindings already live there.' },
{ what: 'Task "Attempt 2 is not recorded" column', to: 'Attempts list in the task side rail', why: 'Shows every attempt with its outcome; the empty column goes away.' },
{ what: 'Dashboard stat cards and health', to: 'Stat strip + right rail', why: '"Needs you" becomes the first thing on the page, with actions inline.' }
]
};
}
}
</script>
</body>
</html>
@@ -1,172 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Dashboard</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.btn-ghost{background:transparent;border-color:transparent;color:#a6a39b}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column;min-width:0}
.card-h{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid #232529}
.card-t{font-size:15px;font-weight:500}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.eyebrow{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:#8f8c85;font-weight:500}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0}
.warn{color:#d9a45b;border-color:rgba(217,164,91,.3);background:rgba(217,164,91,.08)}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.nav a.on{color:#e8e6e1;background:#1e2023}
.tbl{width:100%;border-collapse:collapse;font-size:13px}
.tbl th{text-align:left;font-weight:500;font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:#8f8c85;padding:10px 20px;border-bottom:1px solid #2a2c30}
.tbl td{padding:10px 20px;border-bottom:1px solid #202225;vertical-align:middle}
.chip{font:11px 'IBM Plex Mono',monospace;color:#8f8c85;background:#1e2023;border-radius:4px;padding:1px 6px;margin-left:6px}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 1080px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden; position: relative">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="{{accent}}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#" class="on">Dashboard</a><a href="#">Tasks</a><a href="#">Workflows</a><a href="#">Events</a><a href="#">Settings</a></nav>
<div style="flex-grow: 1"></div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 220px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%"><span class="mono" style="font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span></label>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: {{accent}}"></span>Connected</span>
<span aria-label="Account" style="width: 28px; height: 28px; border-radius: 50%; background: #26282c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b">A</span>
</header>
<main style="flex-grow: 1; padding: 32px 48px; display: flex; flex-direction: column; gap: 24px; min-height: 0">
<div style="display: flex; align-items: flex-end; gap: 16px">
<div style="flex-grow: 1">
<h1 style="margin: 0; font-size: 28px; font-weight: 600; letter-spacing: -0.01em">Good morning</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">Nothing is running. <span style="color: #d9a45b">3 tasks need you.</span></p>
</div>
<button class="btn"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 6h16M4 12h10M4 18h13"></path></svg>Logs</button>
</div>
<section class="card" style="flex-direction: row">
<sc-for list="{{stats}}" as="s" hint-placeholder-count="4">
<div style="flex: 1 1 0; padding: 18px 22px; border-right: 1px solid #232529">
<div class="hint">{{s.label}}</div>
<div style="font-size: 30px; font-weight: 600; margin-top: 6px; color: {{s.color}}">{{s.value}}</div>
<div class="hint" style="margin-top: 2px">{{s.sub}}</div>
</div>
</sc-for>
</section>
<div style="display: grid; grid-template-columns: minmax(0, 1fr) 380px; gap: 24px; min-height: 0; flex-grow: 1">
<div style="display: flex; flex-direction: column; gap: 24px; min-width: 0">
<section class="card">
<div class="card-h"><span class="card-t">Needs you</span><span class="pill warn">3</span><div style="flex-grow: 1"></div><a href="#" class="hint" style="text-decoration: underline">All tasks</a></div>
<sc-for list="{{needs}}" as="n" hint-placeholder-count="3">
<div style="display: grid; grid-template-columns: 120px minmax(0, 1fr) auto; gap: 16px; align-items: center; padding: 14px 20px; border-bottom: 1px solid #202225">
<span class="pill warn" style="justify-self: start">{{n.state}}</span>
<div style="min-width: 0">
<a href="#" style="font-size: 14px; font-weight: 500">{{n.title}}</a>
<div class="mono" style="font-size: 12px; color: #8f8c85; margin-top: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">{{n.meta}}</div>
</div>
<div style="display: flex; gap: 8px"><button class="btn btn-sm btn-ghost">Open</button><button class="btn btn-sm">{{n.action}}</button></div>
</div>
</sc-for>
</section>
<section class="card" style="flex-grow: 1; overflow: hidden">
<div class="card-h"><span class="card-t">Live activity</span><span class="pill" style="color: {{accent}}; border-color: {{accent}}"><span class="dot" style="background: {{accent}}"></span>live</span><div style="flex-grow: 1"></div>
<div role="radiogroup" aria-label="Filter activity" style="display: inline-flex; padding: 2px; border: 1px solid #2e3034; border-radius: 7px"><button style="height: 26px; padding: 0 10px; border: 0; border-radius: 5px; background: #26282c; color: #e8e6e1; font: 500 12px 'IBM Plex Sans', sans-serif">All</button><button style="height: 26px; padding: 0 10px; border: 0; border-radius: 5px; background: transparent; color: #8f8c85; font: 500 12px 'IBM Plex Sans', sans-serif">Tasks</button><button style="height: 26px; padding: 0 10px; border: 0; border-radius: 5px; background: transparent; color: #8f8c85; font: 500 12px 'IBM Plex Sans', sans-serif">System</button></div>
</div>
<table class="tbl">
<thead><tr><th>Event</th><th style="width: 70px">Task</th><th>Detail</th><th style="width: 110px">When</th></tr></thead>
<tbody>
<sc-for list="{{activity}}" as="a" hint-placeholder-count="8">
<tr><td class="mono" style="font-size: 12px"><span style="display: inline-block; width: 7px; height: 7px; border-radius: 2px; margin-right: 8px; background: {{a.color}}"></span>{{a.event}}<sc-if value="{{a.count}}" hint-placeholder-val="{{false}}"><span class="chip">×{{a.count}}</span></sc-if></td><td class="mono" style="font-size: 12px; color: #a6a39b">{{a.task}}</td><td style="color: #a6a39b; max-width: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">{{a.detail}}</td><td class="hint">{{a.when}}</td></tr>
</sc-for>
</tbody>
</table>
</section>
</div>
<div style="display: flex; flex-direction: column; gap: 24px">
<section class="card">
<div class="card-h"><span class="card-t">Quality gates</span><div style="flex-grow: 1"></div><span class="hint">last 4 runs</span></div>
<div style="padding: 20px; display: flex; flex-direction: column; gap: 16px">
<div style="display: flex; align-items: baseline; gap: 10px"><span style="font-size: 30px; font-weight: 600">25%</span><span class="hint">pass rate</span></div>
<sc-for list="{{gates}}" as="g" hint-placeholder-count="2">
<div>
<div style="display: flex; font-size: 13px; margin-bottom: 6px"><span class="mono">{{g.name}}</span><span style="margin-left: auto; color: #a6a39b" class="mono">{{g.score}}</span></div>
<div style="height: 6px; border-radius: 3px; background: #26282c"><div style="height: 6px; border-radius: 3px; width: {{g.pct}}; background: {{g.color}}"></div></div>
</div>
</sc-for>
</div>
</section>
<section class="card">
<div class="card-h"><span class="card-t">Token outlook</span></div>
<div style="padding: 20px; display: flex; flex-direction: column; gap: 14px">
<div style="display: flex; gap: 24px">
<div><div class="hint">Today</div><div style="font-size: 22px; font-weight: 600; margin-top: 2px">14.5M</div></div>
<div><div class="hint">Next 30 days at this rate</div><div style="font-size: 22px; font-weight: 600; margin-top: 2px">≈ 434M</div></div>
</div>
<div aria-label="Tokens per day, last 7 days" style="display: flex; align-items: flex-end; gap: 6px; height: 64px">
<sc-for list="{{days}}" as="d" hint-placeholder-count="7"><div style="flex: 1 1 0; display: flex; flex-direction: column; align-items: center; gap: 4px"><div style="width: 100%; height: {{d.h}}; border-radius: 3px; background: {{d.color}}"></div><span class="mono" style="font-size: 10px; color: #8f8c85">{{d.label}}</span></div></sc-for>
</div>
<div class="hint">Only 1 day of history. The projection steadies after a week of runs.</div>
</div>
</section>
</div>
</div>
</main>
<button aria-label="Chat with Archie" style="position: absolute; right: 24px; bottom: 24px; width: 48px; height: 48px; border-radius: 50%; border: 1px solid #34373c; background: #1e2023; color: {{accent}}; display: flex; align-items: center; justify-content: center; box-shadow: 0 8px 24px rgba(0,0,0,.4); cursor: pointer"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a8 8 0 0 1-11.6 7.1L4 20l1-4.6A8 8 0 1 1 21 12Z"></path></svg></button>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":1080}}'>
class Component extends DCLogic {
renderVals() {
const accent = this.props.accent ?? '#86b5a0';
const sys = '#6f6c66', task = '#8aa4c2', bad = '#d9776b', ok = accent;
return {
accent,
stats: [
{ label: 'Working now', value: '0', sub: '0 waiting to start', color: '#e8e6e1' },
{ label: 'Needs you', value: '3', sub: 'Parked or awaiting a reply', color: '#d9a45b' },
{ label: 'Delivered', value: '1', sub: '25% of all tasks', color: '#e8e6e1' },
{ label: 'Tokens used', value: '14.5M', sub: 'Across 1 day', color: '#e8e6e1' }
],
needs: [
{ state: 'Parked', title: 'changes_captured key-set validation is top-level only', meta: 'archie-core #868 · tdd · worktree prepare failed: fetch origin: http transport…', action: 'Start new run' },
{ state: 'Awaiting reply', title: '[Task title]', meta: '[repo #issue] · [workflow] · [last agent message]', action: 'Reply' },
{ state: 'Awaiting reply', title: '[Task title]', meta: '[repo #issue] · [workflow] · [last agent message]', action: 'Reply' }
],
activity: [
{ event: 'curator_run', task: '—', detail: 'session-memory', when: '19 mins ago', color: sys, count: 0 },
{ event: 'task_archive_requested', task: '#5', detail: 'archive requested with no recorded actor', when: '1 hr ago', color: task, count: 0 },
{ event: 'task_abandoned', task: '#5', detail: 'abandoned with no recorded actor', when: '1 hr ago', color: bad, count: 0 },
{ event: 'curator_run', task: '—', detail: 'session-memory', when: '1 hr ago', color: sys, count: 6 },
{ event: 'stage_start', task: '#5', detail: '', when: '1 hr ago', color: task, count: 4 },
{ event: 'stage_start', task: '#4', detail: '', when: '7 hrs ago', color: task, count: 5 },
{ event: 'agent_finish', task: '#4', detail: 'Problem surface for samcharles93/archie-core issue 836 ("Updater cannot detect o…', when: '7 hrs ago', color: ok, count: 0 },
{ event: 'agent_finish', task: '#4', detail: 'Root cause', when: '7 hrs ago', color: ok, count: 0 },
{ event: 'stage_start', task: '#4', detail: '', when: '8 hrs ago', color: task, count: 6 }
],
gates: [
{ name: 'tdd', score: '0 / 3', pct: '2%', color: '#d9776b' },
{ name: 'triage', score: '1 / 1', pct: '100%', color: accent }
],
days: ['M','T','W','T','F','S','S'].map((l, i) => ({ label: l, h: i === 4 ? '48px' : '3px', color: i === 4 ? accent : '#26282c' }))
};
}
}
</script>
</body>
</html>
@@ -1,138 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Task detail</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.btn-ghost{background:transparent;border-color:transparent;color:#a6a39b}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column;min-width:0}
.card-h{display:flex;align-items:center;gap:12px;padding:14px 20px;border-bottom:1px solid #232529}
.card-t{font-size:14px;font-weight:500}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0}
.warn{color:#d9a45b;border-color:rgba(217,164,91,.3);background:rgba(217,164,91,.08)}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.nav a.on{color:#e8e6e1;background:#1e2023}
.tab{height:44px;display:flex;align-items:center;font-size:13px;color:#8f8c85;border-bottom:2px solid transparent}
.sel{height:32px;box-sizing:border-box;padding:0 10px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:13px 'IBM Plex Sans',sans-serif}
.kv{display:grid;grid-template-columns:96px minmax(0,1fr);gap:10px;font-size:13px;padding:8px 0;border-bottom:1px solid #202225}
.kv dt{color:#8f8c85}.kv dd{margin:0}
.tag{font:11px 'IBM Plex Mono',monospace;color:#a6a39b;background:#1e2023;border-radius:4px;padding:1px 6px}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 1000px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="{{accent}}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#">Dashboard</a><a href="#" class="on">Tasks</a><a href="#">Workflows</a><a href="#">Events</a><a href="#">Settings</a></nav>
<div style="flex-grow: 1"></div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 220px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%"><span class="mono" style="font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span></label>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: {{accent}}"></span>Connected</span>
<span aria-label="Account" style="width: 28px; height: 28px; border-radius: 50%; background: #26282c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b">A</span>
</header>
<main style="flex-grow: 1; padding: 24px 48px 32px; display: flex; flex-direction: column; gap: 20px; min-height: 0">
<div>
<div class="hint"><a href="#" style="color: #a6a39b">Tasks</a> / <span class="mono">#1</span></div>
<div style="display: flex; align-items: flex-start; gap: 16px; margin-top: 8px">
<div style="flex-grow: 1; min-width: 0">
<h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">changes_captured key-set validation is top-level only</h1>
<div style="display: flex; align-items: center; gap: 12px; margin-top: 8px; font-size: 13px; color: #a6a39b">
<span class="pill warn"><span class="dot" style="background: #d9a45b"></span>Parked</span>
<span class="mono">tdd</span><span style="color: #4a4c50">·</span>
<a href="#" class="mono" style="color: #a6a39b; text-decoration: underline">samcharles93/archie-core #868</a>
</div>
</div>
<button class="btn btn-ghost">Archive</button>
<button class="btn btn-primary"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-3-6.7L21 8"></path><path d="M21 3v5h-5"></path></svg>Start a new run</button>
</div>
</div>
<div role="alert" style="display: flex; gap: 12px; padding: 14px 16px; border-radius: 8px; background: rgba(217,164,91,0.08); border: 1px solid rgba(217,164,91,0.25)">
<svg style="flex-shrink: 0; margin-top: 2px" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#d9a45b" stroke-width="2"><path d="M12 3 2 20h20L12 3Z"></path><path d="M12 10v4M12 17h.01"></path></svg>
<div style="min-width: 0; flex-grow: 1">
<div style="font-size: 14px; font-weight: 500; color: #e3c08f">Parked: couldn’t prepare the worktree</div>
<div class="mono" style="font-size: 12px; color: #a6a39b; margin-top: 4px; line-height: 1.6; word-break: break-all">fetch origin: http transport: Get "https://github.com/samcharles93/archie-core.git/info/refs?service=git-upload-pack": terminated signal received</div>
</div>
<button class="btn btn-sm" style="align-self: flex-start">Jump to log line</button>
</div>
<div style="display: grid; grid-template-columns: minmax(0, 1fr) 320px; gap: 24px; flex-grow: 1; min-height: 0">
<section class="card" style="overflow: hidden">
<nav style="display: flex; gap: 28px; padding: 0 20px; border-bottom: 1px solid #232529">
<a class="tab" href="#" style="color: #e8e6e1; border-bottom-color: {{accent}}">Log</a>
<a class="tab" href="#">Changed files <span class="hint" style="margin-left: 6px">0</span></a>
<a class="tab" href="#">Configuration</a>
<a class="tab" href="#">Debug</a>
</nav>
<div style="display: flex; align-items: center; gap: 8px; padding: 12px 20px; border-bottom: 1px solid #232529">
<select aria-label="Level" class="sel"><option>All levels</option></select>
<select aria-label="Stage" class="sel"><option>All stages</option></select>
<label style="display: flex; align-items: center; gap: 8px; height: 32px; width: 260px; padding: 0 10px; box-sizing: border-box; border: 1px solid #2e3034; border-radius: 6px; color: #8f8c85"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Search log" placeholder="Search log" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: 13px 'IBM Plex Sans', sans-serif; width: 100%"></label>
<div style="flex-grow: 1"></div>
<button class="btn btn-sm btn-ghost"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 4v11M7 10l5 5 5-5M5 20h14"></path></svg>Download</button>
</div>
<div class="mono" style="font-size: 12px; line-height: 1.7; flex-grow: 1; background: #121314">
<div style="display: grid; grid-template-columns: 72px 56px minmax(0, 1fr); gap: 12px; padding: 10px 20px; background: rgba(217,119,107,0.06); border-left: 2px solid #d9776b">
<span style="color: #8f8c85">08:38:49</span>
<span style="color: #e0a39a">ERROR</span>
<div style="min-width: 0">
<div style="word-break: break-all">task parked: worktree prepare failed: fetch origin: http transport: Get "https://github.com/samcharles93/archie-core.git/info/refs?service=git-upload-pack": terminated signal received</div>
<div style="display: flex; gap: 6px; margin-top: 6px"><span class="tag">component=daemon</span><span class="tag">task=1</span></div>
</div>
</div>
<div style="padding: 16px 20px; color: #8f8c85; font-family: 'IBM Plex Sans', sans-serif; font-size: 12px">End of attempt 1 · 1 line</div>
</div>
</section>
<aside style="display: flex; flex-direction: column; gap: 20px">
<section class="card">
<div class="card-h"><span class="card-t">Attempts</span></div>
<div style="padding: 8px 12px">
<a href="#" style="display: flex; align-items: center; gap: 10px; padding: 10px 8px; border-radius: 6px; background: #1e2023; box-shadow: inset 2px 0 0 {{accent}}">
<span class="dot" style="background: #d9a45b"></span><span style="font-size: 13px; flex-grow: 1">Attempt 1</span><span class="hint">parked · 08:38</span></a>
<div style="display: flex; align-items: center; gap: 10px; padding: 10px 8px; color: #8f8c85">
<span class="dot" style="background: transparent; border: 1px dashed #4a4c50; box-sizing: border-box"></span><span style="font-size: 13px; flex-grow: 1">Attempt 2</span><span class="hint">not recorded</span></div>
</div>
</section>
<section class="card">
<div class="card-h"><span class="card-t">Details</span></div>
<dl style="margin: 0; padding: 4px 20px 12px">
<div class="kv"><dt>Status</dt><dd style="color: #d9a45b">Parked</dd></div>
<div class="kv"><dt>Workflow</dt><dd><a href="#" class="mono" style="text-decoration: underline">tdd</a></dd></div>
<div class="kv"><dt>Repository</dt><dd class="mono" style="font-size: 12px">samcharles93/archie-core</dd></div>
<div class="kv"><dt>Issue</dt><dd><a href="#" style="text-decoration: underline">#868</a> ↗</dd></div>
<div class="kv"><dt>Persona</dt><dd class="mono" style="font-size: 12px">[persona]</dd></div>
<div class="kv"><dt>Tokens</dt><dd class="mono" style="font-size: 12px">[tokens]</dd></div>
<div class="kv" style="border: 0"><dt>Started</dt><dd>[date · time]</dd></div>
</dl>
</section>
</aside>
</div>
</main>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":1000}}'>
class Component extends DCLogic {
renderVals() {
return { accent: this.props.accent ?? '#86b5a0' };
}
}
</script>
</body>
</html>
@@ -1,142 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Workflows</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.btn-ghost{background:transparent;border-color:transparent;color:#a6a39b}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column;min-width:0}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.lbl{font-size:13px;font-weight:500}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.nav a.on{color:#e8e6e1;background:#1e2023}
.tab{height:44px;display:flex;align-items:center;font-size:13px;color:#8f8c85;border-bottom:2px solid transparent}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.step{font:12px 'IBM Plex Mono',monospace;padding:6px 10px;border:1px solid #2e3034;border-radius:6px;background:#121314;white-space:nowrap}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 1080px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="{{accent}}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#">Dashboard</a><a href="#">Tasks</a><a href="#" class="on">Workflows</a><a href="#">Events</a><a href="#">Settings</a></nav>
<div style="flex-grow: 1"></div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 220px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%"><span class="mono" style="font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span></label>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: {{accent}}"></span>Connected</span>
<span aria-label="Account" style="width: 28px; height: 28px; border-radius: 50%; background: #26282c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b">A</span>
</header>
<main style="flex-grow: 1; padding: 32px 48px; display: flex; flex-direction: column; gap: 24px; min-height: 0">
<div style="display: flex; align-items: flex-end; gap: 12px">
<div style="flex-grow: 1">
<h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Workflows</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">The step sequences agents follow. Success rate is merged tasks over all runs.</p>
</div>
<button class="btn btn-ghost"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 12a9 9 0 1 0 3-6.7L3 8"></path><path d="M3 3v5h5"></path></svg>Restore shipped</button>
<button class="btn"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New workflow</button>
</div>
<div style="display: grid; grid-template-columns: 420px minmax(0, 1fr); gap: 24px; flex-grow: 1; min-height: 0">
<section class="card" style="overflow: hidden">
<div style="display: grid; grid-template-columns: minmax(0, 1fr) 56px 110px 72px; gap: 12px; padding: 10px 16px; font-size: 11px; letter-spacing: .06em; text-transform: uppercase; color: #8f8c85; border-bottom: 1px solid #2a2c30"><span>Workflow</span><span>Runs</span><span>Success</span><span style="text-align: right">Avg tok</span></div>
<sc-for list="{{flows}}" as="f" hint-placeholder-count="6">
<a href="#" style="display: grid; grid-template-columns: minmax(0, 1fr) 56px 110px 72px; gap: 12px; align-items: center; padding: 14px 16px; border-bottom: 1px solid #202225; background: {{f.bg}}; box-shadow: {{f.shadow}}">
<span><span style="font-size: 14px; font-weight: 500; display: block">{{f.name}}</span><span class="mono" style="font-size: 11px; color: #8f8c85">{{f.id}}</span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b">{{f.runs}}</span>
<span style="display: flex; flex-direction: column; gap: 4px"><span class="mono" style="font-size: 12px">{{f.rate}}</span><span style="height: 4px; border-radius: 2px; background: #26282c; width: 100%"><span style="display: block; height: 4px; border-radius: 2px; width: {{f.pct}}; background: {{f.barColor}}"></span></span></span>
<span class="mono" style="font-size: 12px; color: #a6a39b; text-align: right">{{f.tokens}}</span>
</a>
</sc-for>
</section>
<section class="card" style="overflow: hidden">
<div style="display: flex; align-items: center; gap: 12px; padding: 18px 24px 0">
<h2 style="margin: 0; font-size: 18px; font-weight: 600">Bootstrap</h2>
<span class="pill">shipped · edited</span>
<div style="flex-grow: 1"></div>
<span class="hint">0 runs yet</span>
</div>
<nav style="display: flex; gap: 28px; padding: 0 24px; border-bottom: 1px solid #232529">
<a class="tab" href="#" style="color: #e8e6e1; border-bottom-color: {{accent}}">Definition</a>
<a class="tab" href="#">Performance</a>
<a class="tab" href="#">Runs</a>
</nav>
<div style="padding: 20px 24px; display: flex; flex-direction: column; gap: 18px; flex-grow: 1; min-height: 0">
<div style="display: grid; grid-template-columns: 280px minmax(0, 1fr); gap: 24px">
<div style="display: flex; flex-direction: column; gap: 6px"><label class="lbl" for="wid">ID</label><input id="wid" class="inp" value="bootstrap"></div>
<div style="display: flex; flex-direction: column; gap: 6px"><span class="lbl">Steps</span>
<div style="display: flex; align-items: center; gap: 6px; height: 36px; flex-wrap: nowrap; overflow: hidden">
<sc-for list="{{steps}}" as="s" hint-placeholder-count="5"><span class="step">{{s.name}}</span><sc-if value="{{s.more}}" hint-placeholder-val="{{true}}"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#4a4c50" stroke-width="2"><path d="M5 12h14M13 6l6 6-6 6"></path></svg></sc-if></sc-for>
</div></div>
</div>
<div style="display: flex; flex-direction: column; gap: 6px; flex-grow: 1; min-height: 0">
<div style="display: flex; align-items: baseline"><span class="lbl">YAML</span><span class="hint" style="margin-left: auto; color: {{accent}}">✓ Valid</span></div>
<div class="mono" style="flex-grow: 1; display: grid; grid-template-columns: 44px minmax(0, 1fr); border: 1px solid #2e3034; border-radius: 8px; background: #121314; font-size: 13px; line-height: 1.75; overflow: hidden">
<div style="padding: 14px 0; text-align: right; padding-right: 12px; color: #4f5156; border-right: 1px solid #232529; background: #141517; white-space: pre-line">{{lineNos}}</div>
<div style="padding: 14px 16px; white-space: pre"><span style="color: #a6a39b">id:</span> bootstrap
<span style="color: #a6a39b">steps:</span>
- <span style="color: #a6a39b">type:</span> <span style="color: {{accent}}">bootstrap.prepare</span>
- <span style="color: #a6a39b">type:</span> <span style="color: {{accent}}">bootstrap.apply</span>
- <span style="color: #a6a39b">type:</span> <span style="color: {{accent}}">bootstrap.commit-push</span>
- <span style="color: #a6a39b">type:</span> <span style="color: {{accent}}">bootstrap.diff-cap</span>
- <span style="color: #a6a39b">type:</span> <span style="color: {{accent}}">bootstrap.open-pr</span></div>
</div>
</div>
</div>
<div style="display: flex; align-items: center; gap: 10px; padding: 14px 24px; border-top: 1px solid #2a2c30; background: #17181a">
<span class="hint">Version 1 · <a href="#" style="color: #a6a39b; text-decoration: underline">History</a></span>
<div style="flex-grow: 1"></div>
<button class="btn btn-ghost" style="color: #d9776b">Remove</button>
<button class="btn">Restore this workflow</button>
<button class="btn btn-primary">Validate &amp; save</button>
</div>
</section>
</div>
</main>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":1080}}'>
class Component extends DCLogic {
renderVals() {
const accent = this.props.accent ?? '#86b5a0';
const rows = [
['Bootstrap', 'bootstrap', '0', '—', '0%', '—'],
['Feasibility check', 'feasibility', '0', '—', '0%', '—'],
['Implement', 'implement', '0', '—', '0%', '—'],
['Remediate', 'remediate', '0', '—', '0%', '—'],
['TDD', 'tdd', '3', '0 of 3', '2%', '4.7M'],
['Triage', 'triage', '1', '1 of 1', '100%', '282k']
];
const steps = ['prepare', 'apply', 'commit-push', 'diff-cap', 'open-pr'];
return {
accent,
flows: rows.map(([name, id, runs, rate, pct, tokens], i) => ({
name, id, runs, rate, pct, tokens,
barColor: rate === '0 of 3' ? '#d9776b' : accent,
bg: i === 0 ? '#1e2023' : 'transparent',
shadow: i === 0 ? 'inset 2px 0 0 ' + accent : 'none'
})),
steps: steps.map((name, i) => ({ name, more: i < steps.length - 1 })),
lineNos: '1\n2\n3\n4\n5\n6\n7'
};
}
}
</script>
</body>
</html>
@@ -1,83 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>New task dialog</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.btn-ghost{background:transparent;border-color:transparent;color:#a6a39b}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.lbl{font-size:13px;font-weight:500}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.inp{box-sizing:border-box;height:38px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.field{display:flex;flex-direction:column;gap:6px}
.opt{display:flex;flex-direction:column;gap:2px;padding:10px 12px;border:1px solid #2e3034;border-radius:8px;cursor:pointer}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 900px; box-sizing: border-box; position: relative; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="{{accent}}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#">Dashboard</a><a href="#">Tasks</a><a href="#">Workflows</a><a href="#">Events</a><a href="#">Settings</a></nav>
<div style="flex-grow: 1"></div>
<button class="btn btn-sm" style="border-color: {{accent}}"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: {{accent}}"></span>Connected</span>
</header>
<div style="padding: 32px 48px"><div style="font-size: 28px; font-weight: 600; color: #3a3c40">Good morning</div></div>
<div style="position: absolute; inset: 0; background: rgba(8,9,10,0.6)"></div>
<section role="dialog" aria-modal="true" aria-labelledby="nt-title" style="position: absolute; left: 50%; top: 88px; transform: translateX(-50%); width: 640px; box-sizing: border-box; background: #17181a; border: 1px solid #2a2c30; border-radius: 12px; box-shadow: 0 24px 64px rgba(0,0,0,0.5); display: flex; flex-direction: column">
<div style="display: flex; align-items: flex-start; padding: 22px 24px 18px; border-bottom: 1px solid #232529">
<div style="flex-grow: 1"><h2 id="nt-title" style="margin: 0; font-size: 18px; font-weight: 600">New task</h2><div class="hint" style="margin-top: 2px">Goes into Archie’s normal task queue.</div></div>
<button aria-label="Close" style="width: 32px; height: 32px; border: 0; background: transparent; color: #8f8c85; cursor: pointer"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 6l12 12M18 6 6 18"></path></svg></button>
</div>
<div style="padding: 20px 24px; display: flex; flex-direction: column; gap: 18px">
<div class="field"><label class="lbl" for="repo">Repository</label><input id="repo" class="inp" value="samcharles93/archie-core"><span class="hint">owner/repository · recent: archie-core</span></div>
<div class="field"><span class="lbl">Workflow</span>
<div role="radiogroup" aria-label="Workflow" style="display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 8px">
<sc-for list="{{flows}}" as="f" hint-placeholder-count="6">
<label class="opt" style="border-color: {{f.border}}; background: {{f.bg}}"><span style="font-size: 13px; font-weight: 500">{{f.name}}</span><span class="hint">{{f.sub}}</span></label>
</sc-for>
</div></div>
<div class="field"><label class="lbl" for="ttl">Title</label><input id="ttl" class="inp" placeholder="What should Archie do?" style="font-family: 'IBM Plex Sans', sans-serif"></div>
<div class="field"><label class="lbl" for="ins">Instructions</label><textarea id="ins" placeholder="Context, acceptance criteria, files to look at…" style="min-height: 120px; box-sizing: border-box; padding: 12px; background: #121314; border: 1px solid #2e3034; border-radius: 6px; color: #e8e6e1; font: 13px/1.6 'IBM Plex Sans', sans-serif; resize: vertical; outline: none"></textarea></div>
<details style="font-size: 13px; color: #a6a39b"><summary style="cursor: pointer">Advanced · run as identity</summary></details>
</div>
<div style="display: flex; align-items: center; gap: 10px; padding: 14px 24px; border-top: 1px solid #232529">
<span class="hint"><span class="mono" style="padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘↵</span> to start</span>
<div style="flex-grow: 1"></div>
<button class="btn btn-ghost">Cancel</button>
<button class="btn btn-primary">Start task</button>
</div>
</section>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":900}}'>
class Component extends DCLogic {
renderVals() {
const accent = this.props.accent ?? '#86b5a0';
const list = [['TDD', '3 runs · 0% merged'], ['Triage', '1 run · 100% merged'], ['Implement', 'no runs yet'], ['Remediate', 'no runs yet'], ['Feasibility check', 'no runs yet'], ['Bootstrap', 'no runs yet']];
return {
accent,
flows: list.map(([name, sub], i) => ({ name, sub, border: i === 0 ? accent : '#2e3034', bg: i === 0 ? '#1e2023' : 'transparent' }))
};
}
}
</script>
</body>
</html>
@@ -1,108 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Events</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column;min-width:0}
.card-h{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid #232529}
.card-t{font-size:15px;font-weight:500}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.nav a.on{color:#e8e6e1;background:#1e2023}
.tab{height:44px;display:flex;align-items:center;gap:8px;font-size:13px;color:#8f8c85;border-bottom:2px solid transparent}
.count{font:11px 'IBM Plex Mono',monospace;color:#8f8c85;background:#1e2023;border-radius:4px;padding:0 6px}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 900px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="{{accent}}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#">Dashboard</a><a href="#">Tasks</a><a href="#">Workflows</a><a href="#" class="on">Events</a><a href="#">Settings</a></nav>
<div style="flex-grow: 1"></div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 220px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%"><span class="mono" style="font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span></label>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: {{accent}}"></span>Connected</span>
<span aria-label="Account" style="width: 28px; height: 28px; border-radius: 50%; background: #26282c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b">A</span>
</header>
<main style="flex-grow: 1; padding: 32px 48px; display: flex; flex-direction: column; gap: 24px">
<div>
<div style="display: flex; align-items: flex-end; gap: 12px">
<div style="flex-grow: 1"><h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Events</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">Webhooks come in, get mapped to event types, and bindings turn them into work.</p></div>
<span class="pill" style="color: {{accent}}; border-color: {{accent}}"><span class="dot" style="background: {{accent}}"></span>Listening</span>
</div>
<nav style="display: flex; gap: 28px; margin-top: 16px; border-bottom: 1px solid #232529">
<a class="tab" href="#" style="color: #e8e6e1; border-bottom-color: {{accent}}">Inspector</a>
<a class="tab" href="#">Mappings <span class="count">0</span></a>
<a class="tab" href="#">Bindings <span class="count">0</span></a>
</nav>
</div>
<section class="card" style="flex-direction: row">
<sc-for list="{{flow}}" as="f" hint-placeholder-count="3">
<div style="flex: 1 1 0; display: flex; align-items: center; gap: 14px; padding: 18px 22px; border-right: 1px solid #232529">
<span class="mono" style="width: 28px; height: 28px; border-radius: 50%; border: 1px solid #34373c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b; flex-shrink: 0">{{f.n}}</span>
<div style="flex-grow: 1"><div style="font-size: 14px; font-weight: 500">{{f.title}}</div><div class="hint">{{f.sub}}</div></div>
<span class="mono" style="font-size: 20px; color: #8f8c85">{{f.count}}</span>
</div>
</sc-for>
</section>
<div style="display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 2fr); gap: 24px">
<section class="card">
<div class="card-h"><div style="flex-grow: 1"><div class="card-t">Recent captures</div><div class="hint">Headers and payloads are redacted before they’re stored.</div></div></div>
<div style="padding: 40px 32px; display: flex; flex-direction: column; align-items: center; gap: 12px; text-align: center">
<div style="width: 40px; height: 40px; border-radius: 10px; background: #1e2023; display: flex; align-items: center; justify-content: center"><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#a6a39b" stroke-width="2"><path d="M22 12h-6l-2 3h-4l-2-3H2"></path><path d="M5.5 5h13L22 12v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-6Z"></path></svg></div>
<div style="font-size: 14px; font-weight: 500">No captures yet</div>
<div class="hint">Point a webhook at this endpoint and it shows up here live.</div>
<div style="display: flex; align-items: center; gap: 8px; margin-top: 6px; padding: 4px 4px 4px 14px; border: 1px solid #2e3034; border-radius: 8px; background: #121314">
<span class="mono" style="font-size: 13px">/webhooks/capture/<span style="color: {{accent}}">&lt;source&gt;</span></span>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="8" y="8" width="12" height="12" rx="2"></rect><path d="M16 8V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3"></path></svg>Copy</button>
</div>
</div>
</section>
<section class="card">
<div class="card-h"><div style="flex-grow: 1"><div class="card-t">Event types</div><div class="hint">Named shapes that mappings produce.</div></div>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M14 3H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V9l-6-6Z"></path><path d="M12 12v6M9 15h6"></path></svg>From payload</button></div>
<div style="padding: 40px 32px; display: flex; flex-direction: column; align-items: center; gap: 8px; text-align: center">
<div style="font-size: 14px; font-weight: 500">No event types or proposals</div>
<div class="hint">Paste a sample payload and Archie proposes a type for it. Proposals from real captures appear here too.</div>
</div>
</section>
</div>
</main>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":900}}'>
class Component extends DCLogic {
renderVals() {
return {
accent: this.props.accent ?? '#86b5a0',
flow: [
{ n: '1', title: 'Capture', sub: 'Webhooks received', count: '0' },
{ n: '2', title: 'Map', sub: 'Payloads → event types', count: '0' },
{ n: '3', title: 'Bind', sub: 'Event types → work', count: '0' }
]
};
}
}
</script>
</body>
</html>
@@ -1,167 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Settings – sidebar layout</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none}
.inp:focus{border-color:var(--accent)}
.btn{height:36px;padding:0 16px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.icon-btn{width:36px;height:36px;display:flex;align-items:center;justify-content:center;border-radius:6px;border:1px solid transparent;background:transparent;color:#8f8c85;cursor:pointer}
.icon-btn:hover{background:#1e2023;color:#e8e6e1}
.nav-item{display:flex;align-items:center;gap:10px;height:36px;padding:0 12px;border-radius:6px;color:#a6a39b;font-size:13px}
.row{display:grid;grid-template-columns:280px minmax(0,1fr);gap:32px;padding:20px 0;border-top:1px solid #232529}
.lbl{font-size:13px;font-weight:500;color:#e8e6e1}
.hint{font-size:12px;color:#8f8c85;margin-top:4px;line-height:1.5}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 1040px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; position: relative; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 28px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="{{accent}}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>
Archie
</div>
<nav style="display: flex; gap: 4px; font-size: 13px">
<a href="#" style="padding: 8px 12px; color: #a6a39b">Dashboard</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Tasks</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Workflows</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Events</a>
<a href="#" style="padding: 8px 12px; color: #e8e6e1; background: #1e2023; border-radius: 6px">Settings</a>
</nav>
<div style="flex-grow: 1"></div>
<div style="display: flex; align-items: center; gap: 8px; font-size: 12px; color: #a6a39b; padding: 6px 10px; border: 1px solid #2a2c30; border-radius: 999px">
<span style="width: 7px; height: 7px; border-radius: 50%; background: #d9a45b"></span>
Connecting to archie-core…
</div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 240px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg>
<input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%">
<span style="font-family: 'IBM Plex Mono', monospace; font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span>
</label>
</header>
<div style="display: flex; flex-grow: 1; min-height: 0">
<aside style="width: 264px; flex-shrink: 0; box-sizing: border-box; padding: 24px 16px; border-right: 1px solid #232529; display: flex; flex-direction: column; gap: 2px">
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 0 12px 8px">Agents</div>
<a class="nav-item" href="#">Personas<span style="margin-left: auto; font-family: 'IBM Plex Mono', monospace; font-size: 11px; color: #8f8c85">6</span></a>
<a class="nav-item" href="#">Schedules<span style="margin-left: auto; font-family: 'IBM Plex Mono', monospace; font-size: 11px; color: #8f8c85">0</span></a>
<a class="nav-item" href="#" style="background: #1e2023; color: #e8e6e1; box-shadow: inset 2px 0 0 {{accent}}">Scheduling policy<span style="margin-left: auto; width: 6px; height: 6px; border-radius: 50%; background: {{accent}}" title="Unsaved changes"></span></a>
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 18px 12px 8px">Integrations</div>
<a class="nav-item" href="#">Channels</a>
<a class="nav-item" href="#">Tools &amp; MCP</a>
<a class="nav-item" href="#">Plugins</a>
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 18px 12px 8px">Runtime</div>
<a class="nav-item" href="#">Container runtime</a>
<div style="height: 1px; background: #232529; margin: 16px 12px"></div>
<a class="nav-item" href="#">History</a>
<div style="flex-grow: 1"></div>
<div style="font-size: 12px; color: #8f8c85; padding: 12px; line-height: 1.5; border: 1px solid #232529; border-radius: 8px">Config version 1 · last saved by <span style="color: #a6a39b">admin</span><br><a href="#" style="color: {{accent}}">View history</a></div>
</aside>
<main style="flex-grow: 1; overflow: hidden; padding: 40px 56px 120px">
<div style="max-width: 920px">
<div style="display: flex; align-items: flex-start; gap: 16px">
<div style="flex-grow: 1">
<h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Scheduling policy</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">How Archie picks up work items and labels them as they move through states.</p>
</div>
<span style="display: inline-flex; align-items: center; gap: 6px; font-size: 12px; color: #d9a45b; background: rgba(217,164,91,0.1); border: 1px solid rgba(217,164,91,0.25); padding: 4px 10px; border-radius: 999px">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-3-6.7L21 8"></path><path d="M21 3v5h-5"></path></svg>
Applies after restart</span>
</div>
<h2 style="margin: 36px 0 4px; font-size: 13px; font-weight: 600; color: #a6a39b; text-transform: uppercase; letter-spacing: 0.06em">Dispatch</h2>
<div class="row">
<div><div class="lbl">Trigger</div><div class="hint">What causes a work item to be dispatched to an agent.</div></div>
<div style="display: flex; flex-direction: column; gap: 12px">
<div role="radiogroup" aria-label="Trigger" style="display: inline-flex; align-self: flex-start; padding: 3px; background: #121314; border: 1px solid #2e3034; border-radius: 8px">
<button style="height: 30px; padding: 0 14px; border: 0; border-radius: 5px; background: #26282c; color: #e8e6e1; font: 500 13px 'IBM Plex Sans', sans-serif">Assignee</button>
<button style="height: 30px; padding: 0 14px; border: 0; border-radius: 5px; background: transparent; color: #8f8c85; font: 500 13px 'IBM Plex Sans', sans-serif">Label</button>
</div>
<div class="hint" style="margin: 0">Dispatches when Archie is assigned. Choose <span style="color: #a6a39b">Label</span> to set a trigger label instead.</div>
</div>
</div>
<div class="row">
<div><label class="lbl" for="ack">Ack reaction</label><div class="hint">Reaction posted when a work item is picked up.</div></div>
<div><input id="ack" class="inp" value="eyes" style="width: 220px"></div>
</div>
<h2 style="margin: 36px 0 4px; font-size: 13px; font-weight: 600; color: #a6a39b; text-transform: uppercase; letter-spacing: 0.06em">State labels</h2>
<div class="row">
<div><div class="lbl">Labels by state</div><div class="hint">Label applied to the ticket as the agent moves between states.</div></div>
<div style="border: 1px solid #2a2c30; border-radius: 8px; overflow: hidden">
<div style="display: grid; grid-template-columns: 140px minmax(0, 1fr) 44px; gap: 12px; padding: 8px 12px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: #8f8c85; background: #17181a; border-bottom: 1px solid #2a2c30"><span>State</span><span>Label</span><span></span></div>
<sc-for list="{{labels}}" as="l" hint-placeholder-count="6">
<div style="display: grid; grid-template-columns: 140px minmax(0, 1fr) 44px; gap: 12px; align-items: center; padding: 6px 12px; border-bottom: 1px solid #202225">
<span style="display: flex; align-items: center; gap: 8px; font-size: 13px"><span style="width: 8px; height: 8px; border-radius: 2px; background: {{l.color}}"></span>{{l.state}}</span>
<input class="inp" aria-label="{{l.state}} label" value="{{l.label}}" style="width: 100%; height: 32px">
<button class="icon-btn" aria-label="Remove {{l.state}}"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M4 7h16M10 11v6M14 11v6M6 7l1 13h10l1-13M9 7V4h6v3"></path></svg></button>
</div>
</sc-for>
<button style="display: flex; align-items: center; gap: 6px; width: 100%; height: 38px; padding: 0 12px; border: 0; background: transparent; color: #a6a39b; font: 500 13px 'IBM Plex Sans', sans-serif; cursor: pointer"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>Add state</button>
</div>
</div>
<h2 style="margin: 36px 0 4px; font-size: 13px; font-weight: 600; color: #a6a39b; text-transform: uppercase; letter-spacing: 0.06em">Retries &amp; polling</h2>
<div class="row">
<div><label class="lbl" for="retries">Max retries</label><div class="hint">Attempts before an item is labelled dead.</div></div>
<div style="display: inline-flex; align-self: flex-start; border: 1px solid #2e3034; border-radius: 6px; overflow: hidden; width: fit-content">
<button class="icon-btn" aria-label="Decrease" style="border-radius: 0">−</button>
<input id="retries" class="inp" value="3" style="width: 56px; border: 0; border-radius: 0; text-align: center; border-left: 1px solid #2e3034; border-right: 1px solid #2e3034">
<button class="icon-btn" aria-label="Increase" style="border-radius: 0">+</button>
</div>
</div>
<div class="row">
<div><label class="lbl" for="poll">Poll interval</label><div class="hint">How often the tracker is checked for new work.</div></div>
<div style="display: flex; align-items: center; gap: 10px">
<div style="display: flex">
<input id="poll" class="inp" value="30" style="width: 80px; border-radius: 6px 0 0 6px; border-color: {{accent}}">
<select aria-label="Poll unit" class="inp" style="border-radius: 0 6px 6px 0; border-left: 0; font-family: 'IBM Plex Sans', sans-serif"><option>seconds</option><option>minutes</option></select>
</div>
<span style="font-size: 12px; color: #8f8c85">was <span style="font-family: 'IBM Plex Mono', monospace; text-decoration: line-through">1m0s</span></span>
</div>
</div>
</div>
</main>
</div>
<div style="position: absolute; left: 264px; right: 0; bottom: 0; height: 72px; box-sizing: border-box; padding: 0 56px; display: flex; align-items: center; gap: 12px; background: #17181a; border-top: 1px solid #2a2c30">
<span style="width: 8px; height: 8px; border-radius: 50%; background: {{accent}}"></span>
<span style="font-size: 13px">1 unsaved change</span>
<span style="font-size: 13px; color: #8f8c85">· Poll interval</span>
<div style="flex-grow: 1"></div>
<button class="btn" style="background: transparent; border-color: transparent; color: #a6a39b">Discard</button>
<button class="btn btn-primary">Save &amp; restart</button>
</div>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":1040}}'>
class Component extends DCLogic {
renderVals() {
return {
accent: this.props.accent ?? '#86b5a0',
labels: [
{ state: 'queued', label: 'agent:queued', color: '#8f8c85' },
{ state: 'working', label: 'agent:working', color: '#8aa4c2' },
{ state: 'waiting', label: 'agent:waiting', color: '#d9a45b' },
{ state: 'pr', label: 'agent:pr', color: '#86b5a0' },
{ state: 'parked', label: 'agent:parked', color: '#6f6c66' },
{ state: 'dead', label: 'agent:dead', color: '#d9776b' }
]
};
}
}
</script>
</body>
</html>
@@ -1,146 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Settings – personas</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none}
.btn{height:36px;padding:0 16px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.tab{height:44px;display:flex;align-items:center;padding:0 2px;font-size:13px;color:#8f8c85;border-bottom:2px solid transparent}
.lbl{font-size:13px;font-weight:500;color:#e8e6e1}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 1040px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 28px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="{{accent}}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>
Archie
</div>
<nav style="display: flex; gap: 4px; font-size: 13px">
<a href="#" style="padding: 8px 12px; color: #a6a39b">Dashboard</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Work</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Events</a>
<a href="#" style="padding: 8px 12px; color: #e8e6e1; background: #1e2023; border-radius: 6px">System</a>
</nav>
<div style="flex-grow: 1"></div>
<div style="display: flex; align-items: center; gap: 8px; font-size: 12px; color: #a6a39b; padding: 6px 10px; border: 1px solid #2a2c30; border-radius: 999px">
<span style="width: 7px; height: 7px; border-radius: 50%; background: {{accent}}"></span>
Connected · v1
</div>
</header>
<div style="padding: 32px 48px 0; border-bottom: 1px solid #232529; flex-shrink: 0">
<div style="font-size: 12px; color: #8f8c85">System / Advanced</div>
<h1 style="margin: 6px 0 20px; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Advanced settings</h1>
<nav style="display: flex; gap: 28px">
<a class="tab" href="#" style="color: #e8e6e1; border-bottom-color: {{accent}}">Personas</a>
<a class="tab" href="#">Schedules</a>
<a class="tab" href="#">Scheduling policy</a>
<a class="tab" href="#">Tools &amp; MCP</a>
<a class="tab" href="#">Plugins</a>
<a class="tab" href="#">Container runtime</a>
</nav>
</div>
<div style="display: flex; flex-grow: 1; min-height: 0; padding: 32px 48px 40px; gap: 32px">
<section aria-label="Persona list" style="width: 340px; flex-shrink: 0; display: flex; flex-direction: column; gap: 12px">
<div style="display: flex; align-items: center; gap: 8px">
<label style="flex-grow: 1; display: flex; align-items: center; gap: 8px; height: 36px; padding: 0 12px; border: 1px solid #2e3034; border-radius: 6px; color: #8f8c85">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg>
<input aria-label="Filter personas" placeholder="Filter personas" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: 13px 'IBM Plex Sans', sans-serif; width: 100%">
</label>
<button class="btn" aria-label="New persona" style="padding: 0 12px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New</button>
</div>
<div style="border: 1px solid #2a2c30; border-radius: 10px; overflow: hidden; background: #16171a">
<sc-for list="{{personas}}" as="p" hint-placeholder-count="6">
<a href="#" style="display: flex; flex-direction: column; gap: 4px; padding: 14px 16px; border-bottom: 1px solid #222428; background: {{p.bg}}; box-shadow: {{p.shadow}}">
<span style="display: flex; align-items: center; gap: 8px; font-size: 14px; font-weight: 500">{{p.name}}
<sc-if value="{{p.isDefault}}" hint-placeholder-val="{{false}}"><span style="font-size: 11px; font-weight: 500; color: {{accent}}; border: 1px solid {{accent}}; border-radius: 999px; padding: 1px 8px">default</span></sc-if>
</span>
<span style="font-size: 12px; color: #8f8c85; white-space: nowrap; overflow: hidden; text-overflow: ellipsis">{{p.prompt}}</span>
</a>
</sc-for>
</div>
<div class="hint">Personas are system prompts an agent can adopt. The default is used when a work item doesn't specify one.</div>
</section>
<section aria-label="Edit persona" style="flex-grow: 1; display: flex; flex-direction: column; border: 1px solid #2a2c30; border-radius: 10px; background: #16171a; overflow: hidden">
<div style="display: flex; align-items: center; gap: 12px; padding: 18px 24px; border-bottom: 1px solid #2a2c30">
<h2 style="margin: 0; font-size: 18px; font-weight: 600">archie</h2>
<span style="font-size: 11px; color: {{accent}}; border: 1px solid {{accent}}; border-radius: 999px; padding: 1px 8px">default</span>
<div style="flex-grow: 1"></div>
<button class="btn" style="background: transparent">Duplicate</button>
<button class="btn" style="background: transparent; color: #d9776b; border-color: #3a2a28">Delete</button>
</div>
<div style="display: flex; flex-direction: column; gap: 24px; padding: 24px; flex-grow: 1">
<div style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px">
<div style="display: flex; flex-direction: column; gap: 8px">
<label class="lbl" for="pname">Name</label>
<input id="pname" class="inp" value="archie">
<span class="hint">Lowercase, used as the persona key.</span>
</div>
<div style="display: flex; flex-direction: column; gap: 8px">
<span class="lbl">Default persona</span>
<label style="display: flex; align-items: center; gap: 10px; height: 36px; font-size: 13px; color: #a6a39b">
<span style="width: 36px; height: 20px; border-radius: 999px; background: {{accent}}; position: relative; display: inline-block"><span style="position: absolute; right: 2px; top: 2px; width: 16px; height: 16px; border-radius: 50%; background: #121314"></span></span>
Use when no persona is specified
</label>
</div>
</div>
<div style="display: flex; flex-direction: column; gap: 8px; flex-grow: 1">
<div style="display: flex; align-items: baseline"><label class="lbl" for="prompt">System prompt</label><span class="hint" style="margin-left: auto; font-family: 'IBM Plex Mono', monospace">312 chars · ~70 tokens</span></div>
<textarea id="prompt" style="flex-grow: 1; min-height: 320px; box-sizing: border-box; padding: 16px; background: #121314; border: 1px solid #2e3034; border-radius: 8px; color: #e8e6e1; font: 400 13px/1.7 'IBM Plex Mono', monospace; resize: vertical; outline: none">You are Archie, a capable coding and project assistant. Be direct without being brusque, grounded in the actual workspace state, and use available tools when asked. Do not claim tools, files, memories, actions, or results you have not verified. Do not impersonate another assistant, provider, or vendor.</textarea>
</div>
<div style="display: flex; align-items: center; gap: 12px; padding: 14px 16px; border: 1px dashed #2e3034; border-radius: 8px">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#8f8c85" stroke-width="2"><path d="M4 12h12M12 6l6 6-6 6"></path></svg>
<span style="font-size: 13px; color: #a6a39b; flex-grow: 1">Try this persona against a sample message before saving</span>
<button class="btn">Open preview</button>
</div>
</div>
<div style="display: flex; align-items: center; gap: 12px; padding: 16px 24px; border-top: 1px solid #2a2c30; background: #17181a">
<span style="font-size: 12px; color: #8f8c85">Saved · version 1 · <a href="#" style="color: #a6a39b; text-decoration: underline">History</a></span>
<div style="flex-grow: 1"></div>
<button class="btn" style="background: transparent; border-color: transparent; color: #a6a39b">Discard</button>
<button class="btn btn-primary">Save persona</button>
</div>
</section>
</div>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":1040}}'>
class Component extends DCLogic {
renderVals() {
const accent = this.props.accent ?? '#86b5a0';
const list = [
['archie', 'You are Archie, a capable coding and project assistant. Be direct without being brusque…', true],
['helpful', 'You are a helpful, friendly AI assistant.', false],
['concise', 'You are a concise assistant. Keep responses brief and to the point.', false],
['technical', 'You are a technical expert. Provide detailed, accurate technical information.', false],
['creative', 'You are a creative assistant. Think outside the box and offer innovative solutions.', false],
['teacher', 'You are a patient teacher. Explain concepts clearly with examples.', false]
];
return {
accent,
personas: list.map(([name, prompt, isDefault], i) => ({
name, prompt, isDefault,
bg: i === 0 ? '#1e2023' : 'transparent',
shadow: i === 0 ? 'inset 2px 0 0 ' + accent : 'none'
}))
};
}
}
</script>
</body>
</html>
@@ -1,155 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Settings – tools and MCP</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column}
.card-h{display:flex;align-items:center;gap:12px;padding:18px 20px;border-bottom:1px solid #232529}
.card-b{padding:20px;display:flex;flex-direction:column;gap:18px}
.lbl{font-size:13px;font-weight:500;color:#e8e6e1}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.field{display:flex;flex-direction:column;gap:6px}
.sw{width:36px;height:20px;border-radius:999px;position:relative;display:inline-block;flex-shrink:0}
.sw i{position:absolute;top:2px;width:16px;height:16px;border-radius:50%}
.nav-item{display:flex;align-items:center;gap:10px;height:36px;padding:0 12px;border-radius:6px;color:#a6a39b;font-size:13px}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 1080px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 28px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="{{accent}}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>
Archie
</div>
<nav style="display: flex; gap: 4px; font-size: 13px">
<a href="#" style="padding: 8px 12px; color: #a6a39b">Dashboard</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Tasks</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Workflows</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Events</a>
<a href="#" style="padding: 8px 12px; color: #e8e6e1; background: #1e2023; border-radius: 6px">Settings</a>
</nav>
<div style="flex-grow: 1"></div>
<div style="display: flex; align-items: center; gap: 8px; font-size: 12px; color: #a6a39b; padding: 6px 10px; border: 1px solid #2a2c30; border-radius: 999px">
<span style="width: 7px; height: 7px; border-radius: 50%; background: {{accent}}"></span>
Connected · v1
</div>
</header>
<div style="display: flex; flex-grow: 1; min-height: 0">
<aside style="width: 232px; flex-shrink: 0; box-sizing: border-box; padding: 24px 12px; border-right: 1px solid #232529; display: flex; flex-direction: column; gap: 2px">
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 0 12px 8px">Agents</div>
<a class="nav-item" href="#">Personas</a>
<a class="nav-item" href="#">Schedules</a>
<a class="nav-item" href="#">Scheduling policy</a>
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 18px 12px 8px">Integrations</div>
<a class="nav-item" href="#">Channels</a>
<a class="nav-item" href="#" style="background: #1e2023; color: #e8e6e1; box-shadow: inset 2px 0 0 {{accent}}">Tools &amp; MCP</a>
<a class="nav-item" href="#">Plugins</a>
<div style="font-size: 11px; letter-spacing: 0.08em; text-transform: uppercase; color: #8f8c85; padding: 18px 12px 8px">Runtime</div>
<a class="nav-item" href="#">Container runtime</a>
<div style="height: 1px; background: #232529; margin: 16px 12px"></div>
<a class="nav-item" href="#">History</a>
</aside>
<main style="flex-grow: 1; padding: 36px 48px; overflow: hidden">
<div style="display: flex; align-items: flex-end; gap: 16px; margin-bottom: 28px">
<div style="flex-grow: 1">
<h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Tools &amp; MCP</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">External tools, model providers and fetch limits available to agents.</p>
</div>
<button class="btn btn-primary"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>Add MCP server</button>
</div>
<div style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 20px">
<section class="card" style="grid-column: span 2">
<div class="card-h">
<div style="width: 32px; height: 32px; border-radius: 8px; background: #1e2023; display: flex; align-items: center; justify-content: center"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a6a39b" stroke-width="2"><rect x="3" y="4" width="18" height="6" rx="1"></rect><rect x="3" y="14" width="18" height="6" rx="1"></rect><path d="M7 7h.01M7 17h.01"></path></svg></div>
<div style="flex-grow: 1"><div class="lbl" style="font-size: 15px">MCP servers</div><div class="hint">Model Context Protocol servers agents can call.</div></div>
</div>
<div style="display: flex; align-items: center; gap: 20px; padding: 28px 20px">
<div style="flex-grow: 1">
<div style="font-size: 14px; color: #e8e6e1">No MCP servers yet</div>
<div class="hint" style="margin-top: 4px">Add a stdio command or an HTTP endpoint. Agents see its tools on next restart.</div>
</div>
<button class="btn">stdio command</button>
<button class="btn">HTTP / SSE endpoint</button>
</div>
</section>
<section class="card">
<div class="card-h">
<div style="width: 32px; height: 32px; border-radius: 8px; background: #1e2023; display: flex; align-items: center; justify-content: center; font: 600 13px 'IBM Plex Mono', monospace; color: #a6a39b">Mx</div>
<div style="flex-grow: 1"><div class="lbl" style="font-size: 15px">MiniMax</div><div class="hint">Model provider</div></div>
<label style="display: flex; align-items: center; gap: 8px; font-size: 12px; color: #a6a39b">Enabled<span class="sw" style="background: {{accent}}"><i style="right: 2px; background: #121314"></i></span></label>
</div>
<div class="card-b">
<div class="field">
<span class="lbl">API key</span>
<div style="display: flex; align-items: center; gap: 10px; height: 40px; padding: 0 12px; border: 1px solid #2e3034; border-radius: 6px; background: #121314">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#8f8c85" stroke-width="2"><rect x="4" y="10" width="16" height="10" rx="2"></rect><path d="M8 10V7a4 4 0 0 1 8 0v3"></path></svg>
<span style="font: 12px 'IBM Plex Mono', monospace; color: #8f8c85">bws</span>
<span style="color: #4a4c50">/</span>
<span style="font: 13px 'IBM Plex Mono', monospace">MINIMAX_API_KEY</span>
<div style="flex-grow: 1"></div>
<button class="btn" style="height: 28px; padding: 0 10px; font-size: 12px; background: transparent">Change</button>
</div>
<div style="display: flex; align-items: center; gap: 6px; font-size: 12px; color: {{accent}}"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="m5 12 5 5 9-10"></path></svg>Credential resolved by Archie</div>
</div>
</div>
</section>
<section class="card">
<div class="card-h">
<div style="width: 32px; height: 32px; border-radius: 8px; background: #1e2023; display: flex; align-items: center; justify-content: center"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a6a39b" stroke-width="2"><circle cx="12" cy="12" r="9"></circle><path d="M3 12h18M12 3c3 3 3 15 0 18M12 3c-3 3-3 15 0 18"></path></svg></div>
<div style="flex-grow: 1"><div class="lbl" style="font-size: 15px">Web fetch</div><div class="hint">Let agents download pages and files</div></div>
<label style="display: flex; align-items: center; gap: 8px; font-size: 12px; color: #a6a39b">Enabled<span class="sw" style="background: {{accent}}"><i style="right: 2px; background: #121314"></i></span></label>
</div>
<div class="card-b">
<div style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px">
<div class="field"><label class="lbl" for="mb">Max download</label><div style="display: flex"><input id="mb" class="inp" value="2" style="border-radius: 6px 0 0 6px"><span style="display: flex; align-items: center; padding: 0 12px; border: 1px solid #2e3034; border-left: 0; border-radius: 0 6px 6px 0; font-size: 12px; color: #8f8c85">MB</span></div></div>
<div class="field"><label class="lbl" for="to">Timeout</label><div style="display: flex"><input id="to" class="inp" value="30" style="border-radius: 6px 0 0 6px"><span style="display: flex; align-items: center; padding: 0 12px; border: 1px solid #2e3034; border-left: 0; border-radius: 0 6px 6px 0; font-size: 12px; color: #8f8c85">sec</span></div></div>
</div>
<label style="display: flex; align-items: flex-start; gap: 12px; padding: 12px; border: 1px solid #2a2c30; border-radius: 8px">
<span class="sw" style="background: #2e3034; margin-top: 2px"><i style="left: 2px; background: #8f8c85"></i></span>
<span><span class="lbl">Allow private networks</span><span class="hint" style="display: block">Off: requests to 10.x, 192.168.x and localhost are blocked.</span></span>
</label>
</div>
</section>
<section class="card" style="grid-column: span 2">
<div class="card-h">
<div style="flex-grow: 1"><div class="lbl" style="font-size: 15px">Tool output policy</div><div class="hint">Large tool results are truncated or spilled to disk.</div></div>
</div>
<div class="card-b" style="display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 24px">
<div class="field"><label class="lbl" for="mrc">Max result length</label><div style="display: flex"><input id="mrc" class="inp" value="50,000" style="border-radius: 6px 0 0 6px"><span style="display: flex; align-items: center; padding: 0 12px; border: 1px solid #2e3034; border-left: 0; border-radius: 0 6px 6px 0; font-size: 12px; color: #8f8c85; white-space: nowrap">chars</span></div><span class="hint">About 12k tokens per tool call.</span></div>
<div class="field"><label class="lbl" for="spill">Spill directory</label><input id="spill" class="inp" placeholder="Not set — results over the limit are truncated"><span class="hint">Full output is written here and the agent gets a path.</span></div>
</div>
</section>
</div>
</main>
</div>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":1080}}'>
class Component extends DCLogic {
renderVals() {
return { accent: this.props.accent ?? '#86b5a0' };
}
}
</script>
</body>
</html>
@@ -1,123 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Settings – review changes</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.btn{height:36px;padding:0 16px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.acc{display:flex;align-items:center;gap:14px;padding:16px 20px;border:1px solid #2a2c30;border-radius:10px;background:#16171a}
.lbl{font-size:13px;font-weight:500;color:#e8e6e1}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.sum{font:12px 'IBM Plex Mono',monospace;color:#8f8c85}
.field{display:flex;flex-direction:column;gap:6px}
.chev{color:#8f8c85}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 1080px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden; position: relative">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 28px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px">
<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="{{accent}}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>
Archie
</div>
<nav style="display: flex; gap: 4px; font-size: 13px">
<a href="#" style="padding: 8px 12px; color: #a6a39b">Dashboard</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Work</a>
<a href="#" style="padding: 8px 12px; color: #a6a39b">Events</a>
<a href="#" style="padding: 8px 12px; color: #e8e6e1; background: #1e2023; border-radius: 6px">System</a>
</nav>
</header>
<main style="width: 880px; padding: 36px 0 0 64px; display: flex; flex-direction: column; gap: 12px">
<h1 style="margin: 0 0 4px; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Advanced settings</h1>
<p style="margin: 0 0 16px; font-size: 14px; color: #a6a39b">Collapsed sections show their current values at a glance.</p>
<div class="acc"><svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 6 6 6-6 6"></path></svg><span class="lbl" style="width: 180px">Personas</span><span class="sum" style="flex-grow: 1">6 personas · default archie</span></div>
<div class="acc"><svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 6 6 6-6 6"></path></svg><span class="lbl" style="width: 180px">Schedules</span><span class="sum" style="flex-grow: 1">none</span></div>
<div class="acc" style="border-color: #3a3f3c"><svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 6 6 6-6 6"></path></svg><span class="lbl" style="width: 180px">Scheduling policy</span><span class="sum" style="flex-grow: 1">trigger assignee · 3 retries · poll 30s</span><span style="font-size: 11px; color: {{accent}}">1 edited</span></div>
<div class="acc"><svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 6 6 6-6 6"></path></svg><span class="lbl" style="width: 180px">Tools &amp; MCP</span><span class="sum" style="flex-grow: 1">0 MCP · MiniMax on · web fetch on</span></div>
<div class="acc"><svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m9 6 6 6-6 6"></path></svg><span class="lbl" style="width: 180px">Plugins</span><span class="sum" style="flex-grow: 1">all directories default</span></div>
<section style="border: 1px solid #3a3f3c; border-radius: 10px; background: #16171a">
<div style="display: flex; align-items: center; gap: 14px; padding: 16px 20px; border-bottom: 1px solid #232529">
<svg class="chev" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m6 9 6 6 6-6"></path></svg>
<span class="lbl" style="flex-grow: 1">Container runtime</span>
<span style="font-size: 11px; color: {{accent}}">2 edited</span>
</div>
<div style="padding: 20px; display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 18px 24px">
<div class="field" style="grid-column: span 2"><label class="lbl" for="img">Image</label><input id="img" class="inp" value="ghcr.io/samcharles93/archie-agent:latest"></div>
<div class="field"><label class="lbl" for="mc">Max concurrency</label><input id="mc" class="inp" value="6" style="border-color: {{accent}}"></div>
<div class="field"><label class="lbl" for="mu">Max uptime</label><input id="mu" class="inp" value="2h" style="border-color: {{accent}}"></div>
<div class="field"><label class="lbl" for="net">Network</label><input id="net" class="inp" value="archie-core_default"></div>
<div class="field"><label class="lbl" for="pp">Pull policy</label><select id="pp" class="inp" style="font-family: 'IBM Plex Sans', sans-serif"><option>If missing</option><option>Always</option><option>Never</option></select></div>
<div class="field"><label class="lbl" for="vt">Volume TTL</label><input id="vt" class="inp" value="72h"></div>
<div class="field"><label class="lbl" for="pr">Profiles</label><input id="pr" class="inp" placeholder="None"></div>
</div>
</section>
</main>
<div style="position: absolute; left: 0; top: 56px; right: 0; bottom: 0; background: rgba(8,9,10,0.55)"></div>
<aside aria-label="Review changes" style="position: absolute; top: 56px; right: 0; bottom: 0; width: 480px; box-sizing: border-box; background: #17181a; border-left: 1px solid #2a2c30; display: flex; flex-direction: column; box-shadow: -24px 0 48px rgba(0,0,0,0.35)">
<div style="display: flex; align-items: center; padding: 20px 24px; border-bottom: 1px solid #2a2c30">
<div style="flex-grow: 1"><h2 style="margin: 0; font-size: 17px; font-weight: 600">Review 3 changes</h2><div class="hint" style="margin-top: 2px">Saved together as config version 2</div></div>
<button aria-label="Close" style="width: 36px; height: 36px; border: 0; background: transparent; color: #8f8c85; cursor: pointer"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 6l12 12M18 6 6 18"></path></svg></button>
</div>
<div style="flex-grow: 1; padding: 20px 24px; display: flex; flex-direction: column; gap: 20px">
<div style="display: flex; gap: 10px; padding: 12px 14px; border-radius: 8px; background: rgba(217,164,91,0.08); border: 1px solid rgba(217,164,91,0.25); color: #e3c08f; font-size: 13px; line-height: 1.5">
<svg style="flex-shrink: 0; margin-top: 2px" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-3-6.7L21 8"></path><path d="M21 3v5h-5"></path></svg>
<span>All three need an archie-core restart. 2 agents are running; they'll finish before the restart.</span>
</div>
<sc-for list="{{groups}}" as="g" hint-placeholder-count="2">
<div style="display: flex; flex-direction: column; gap: 8px">
<div style="font-size: 11px; text-transform: uppercase; letter-spacing: 0.06em; color: #8f8c85">{{g.section}}</div>
<sc-for list="{{g.items}}" as="c" hint-placeholder-count="2">
<div style="border: 1px solid #2a2c30; border-radius: 8px; overflow: hidden">
<div style="display: flex; align-items: center; padding: 10px 14px; font-size: 13px; font-weight: 500"><span style="flex-grow: 1">{{c.field}}</span><a href="#" style="font-size: 12px; font-weight: 400; color: #8f8c85; text-decoration: underline">Revert</a></div>
<div style="font: 12px/1.9 'IBM Plex Mono', monospace; border-top: 1px solid #232529">
<div style="padding: 0 14px; background: rgba(217,119,107,0.08); color: #e0a39a">− {{c.from}}</div>
<div style="padding: 0 14px; background: rgba(134,181,160,0.10); color: #a9d1bf">+ {{c.to}}</div>
</div>
</div>
</sc-for>
</div>
</sc-for>
</div>
<div style="display: flex; align-items: center; gap: 12px; padding: 16px 24px; border-top: 1px solid #2a2c30">
<button class="btn" style="background: transparent; border-color: transparent; color: #a6a39b">Discard all</button>
<div style="flex-grow: 1"></div>
<button class="btn">Save only</button>
<button class="btn btn-primary">Save &amp; restart</button>
</div>
</aside>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":1080}}'>
class Component extends DCLogic {
renderVals() {
return {
accent: this.props.accent ?? '#86b5a0',
groups: [
{ section: 'Scheduling policy', items: [{ field: 'Poll interval', from: '1m0s', to: '30s' }] },
{ section: 'Container runtime', items: [
{ field: 'Max concurrency', from: '4', to: '6' },
{ field: 'Max uptime', from: '1h0m0s', to: '2h0m0s' }
] }
]
};
}
}
</script>
</body>
</html>
@@ -1,165 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Settings – channels</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
a{color:#e8e6e1;text-decoration:none}a:hover{color:#ffffff}
.btn{height:36px;padding:0 14px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px;white-space:nowrap}
.btn-sm{height:30px;padding:0 10px;font-size:12px}
.btn-ghost{background:transparent;border-color:transparent;color:#a6a39b}
.card{border:1px solid #2a2c30;border-radius:10px;background:#16171a;display:flex;flex-direction:column;min-width:0}
.card-h{display:flex;align-items:center;gap:12px;padding:16px 20px;border-bottom:1px solid #232529}
.hint{font-size:12px;color:#8f8c85;line-height:1.5}
.lbl{font-size:13px;font-weight:500}
.eyebrow{font-size:11px;letter-spacing:.08em;text-transform:uppercase;color:#8f8c85;font-weight:500}
.mono{font-family:'IBM Plex Mono',monospace}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:2px 9px;border-radius:999px;border:1px solid #2e3034;color:#a6a39b;white-space:nowrap}
.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0}
.nav a{padding:8px 12px;color:#a6a39b;border-radius:6px}
.nav a.on{color:#e8e6e1;background:#1e2023}
.nav-item{display:flex;align-items:center;gap:10px;height:34px;padding:0 12px;border-radius:6px;color:#a6a39b;font-size:13px}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.row{display:grid;grid-template-columns:260px minmax(0,1fr);gap:32px;padding:16px 20px;border-top:1px solid #232529}
.sw{width:36px;height:20px;border-radius:999px;position:relative;display:inline-block;flex-shrink:0}
.sw i{position:absolute;top:2px;width:16px;height:16px;border-radius:50%}
.icon{width:32px;height:32px;border-radius:8px;background:#1e2023;display:flex;align-items:center;justify-content:center;flex-shrink:0}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 1300px; box-sizing: border-box; display: flex; flex-direction: column; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; overflow: hidden">
<header style="height: 56px; flex-shrink: 0; display: flex; align-items: center; gap: 24px; padding: 0 24px; border-bottom: 1px solid #232529; background: #151618">
<div style="display: flex; align-items: center; gap: 10px; font-weight: 600; font-size: 15px"><svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="{{accent}}" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 20 12 4l8 16"></path><path d="M8 14h8"></path></svg>Archie</div>
<nav class="nav" style="display: flex; gap: 2px; font-size: 13px"><a href="#">Dashboard</a><a href="#">Tasks</a><a href="#">Workflows</a><a href="#">Events</a><a href="#" class="on">Settings</a></nav>
<div style="flex-grow: 1"></div>
<label style="display: flex; align-items: center; gap: 8px; height: 34px; width: 220px; padding: 0 12px; box-sizing: border-box; border: 1px solid #2a2c30; border-radius: 6px; color: #8f8c85; font-size: 13px"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="7"></circle><path d="m20 20-3.5-3.5"></path></svg><input aria-label="Jump to" placeholder="Jump to…" style="background: transparent; border: 0; outline: none; color: #e8e6e1; font: inherit; width: 100%"><span class="mono" style="font-size: 11px; padding: 1px 5px; border: 1px solid #2e3034; border-radius: 4px">⌘K</span></label>
<button class="btn btn-sm"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 5v14M5 12h14"></path></svg>New task</button>
<span class="pill"><span class="dot" style="background: {{accent}}"></span>Connected</span>
<span aria-label="Account" style="width: 28px; height: 28px; border-radius: 50%; background: #26282c; display: flex; align-items: center; justify-content: center; font-size: 12px; color: #a6a39b">A</span>
</header>
<div style="display: flex; flex-grow: 1; min-height: 0">
<aside style="width: 248px; flex-shrink: 0; box-sizing: border-box; padding: 24px 14px; border-right: 1px solid #232529; display: flex; flex-direction: column; gap: 2px">
<div class="eyebrow" style="padding: 0 12px 8px">Agents</div>
<a class="nav-item" href="#">Personas</a><a class="nav-item" href="#">Schedules</a><a class="nav-item" href="#">Scheduling policy</a>
<div class="eyebrow" style="padding: 18px 12px 8px">Integrations</div>
<a class="nav-item" href="#" style="background: #1e2023; color: #e8e6e1; box-shadow: inset 2px 0 0 {{accent}}">Channels<span class="dot" style="margin-left: auto; background: {{accent}}" title="1 running"></span></a>
<a class="nav-item" href="#">Tools &amp; MCP</a><a class="nav-item" href="#">Plugins</a>
<div class="eyebrow" style="padding: 18px 12px 8px">Runtime</div>
<a class="nav-item" href="#">Container runtime</a>
<div style="height: 1px; background: #232529; margin: 16px 12px"></div>
<a class="nav-item" href="#"><svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"></circle><path d="M12 7v5l3 2"></path></svg>History</a>
</aside>
<main style="flex-grow: 1; padding: 36px 56px; display: flex; flex-direction: column; gap: 24px; min-width: 0">
<div style="display: flex; align-items: flex-start; gap: 16px; max-width: 980px">
<div style="flex-grow: 1">
<h1 style="margin: 0; font-size: 24px; font-weight: 600; letter-spacing: -0.01em">Channels</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">Where you talk to Archie, and how chat sessions behave.</p>
</div>
<span class="pill" style="color: #d9a45b; border-color: rgba(217,164,91,.3); background: rgba(217,164,91,.08)">Applies after restart</span>
</div>
<div style="max-width: 980px; display: flex; flex-direction: column; gap: 16px">
<section class="card">
<div class="card-h">
<div class="icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#a6a39b" stroke-width="2"><path d="m22 3-9.5 18-2.5-8-8-2.5L22 3Z"></path></svg></div>
<div style="flex-grow: 1"><div style="font-size: 15px; font-weight: 500">Telegram</div><div class="hint">Talk to Archie and approve its work from your phone.</div></div>
<span class="pill" style="color: {{accent}}; border-color: {{accent}}"><span class="dot" style="background: {{accent}}"></span>Running</span>
</div>
<div class="row" style="border-top: 0">
<div><div class="lbl">Bot token</div><div class="hint">Secret reference for the Telegram bot.</div></div>
<div>
<div style="display: flex; align-items: center; gap: 10px; height: 38px; padding: 0 12px; border: 1px solid #2e3034; border-radius: 6px; background: #121314">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#8f8c85" stroke-width="2"><rect x="4" y="10" width="16" height="10" rx="2"></rect><path d="M8 10V7a4 4 0 0 1 8 0v3"></path></svg>
<span class="mono" style="font-size: 12px; color: #8f8c85">env</span><span style="color: #4a4c50">/</span><span class="mono" style="font-size: 13px">HEYARCHIE_TELEGRAM_BOT_TOKEN</span>
<div style="flex-grow: 1"></div><button class="btn btn-sm" style="height: 26px; background: transparent">Change</button>
</div>
<div style="display: flex; align-items: center; gap: 6px; font-size: 12px; color: {{accent}}; margin-top: 6px"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="m5 12 5 5 9-10"></path></svg>Credential resolved by Archie</div>
</div>
</div>
<div class="row">
<div><div class="lbl">Allowed users</div><div class="hint">Telegram user IDs that may talk to Archie. Everyone else is ignored.</div></div>
<div style="display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 6px; border: 1px solid #2e3034; border-radius: 6px; background: #121314; min-height: 38px; box-sizing: border-box">
<span style="display: inline-flex; align-items: center; gap: 6px; height: 26px; padding: 0 6px 0 10px; border-radius: 4px; background: #1e2023; font: 12px 'IBM Plex Mono', monospace">1312197967<button aria-label="Remove 1312197967" style="width: 20px; height: 20px; border: 0; background: transparent; color: #8f8c85; cursor: pointer">×</button></span>
<input aria-label="Add user ID" placeholder="Add user ID…" style="flex-grow: 1; min-width: 140px; background: transparent; border: 0; outline: none; color: #e8e6e1; font: 12px 'IBM Plex Mono', monospace">
</div>
</div>
</section>
<sc-for list="{{inactive}}" as="c" hint-placeholder-count="2">
<section class="card" style="flex-direction: row; align-items: center; gap: 12px; padding: 16px 20px">
<div class="icon"><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#8f8c85" stroke-width="2"><path d="{{c.icon}}"></path></svg></div>
<div style="flex-grow: 1"><div style="font-size: 15px; font-weight: 500">{{c.name}}</div><div class="hint">{{c.sub}}</div></div>
<span class="pill">Not set up</span>
<button class="btn btn-sm">Set up</button>
</section>
</sc-for>
<div class="eyebrow" style="margin-top: 16px">Chat session defaults · all channels</div>
<section class="card">
<div class="row" style="border-top: 0">
<div><label class="lbl" for="ws">Workspace</label><div class="hint">Directory chat sessions start in.</div></div>
<input id="ws" class="inp" value="/home/sam">
</div>
<div class="row">
<div><div class="lbl">Filesystem access</div><div class="hint">Outside the workspace.</div></div>
<div style="display: flex; align-items: flex-start; gap: 12px; padding: 12px; border: 1px solid rgba(217,119,107,.35); background: rgba(217,119,107,.06); border-radius: 8px">
<span class="sw" style="background: #d9776b; margin-top: 2px"><i style="right: 2px; background: #121314"></i></span>
<span><span class="lbl">Unrestricted filesystem</span><span class="hint" style="display: block; color: #e0a39a">On: agents can read and write anywhere this user can.</span></span>
</div>
</div>
<div class="row">
<div><div class="lbl">Show tool calls</div><div class="hint">Post each tool call into the chat.</div></div>
<label style="display: flex; align-items: center; gap: 10px; font-size: 13px; color: #a6a39b"><span class="sw" style="background: {{accent}}"><i style="right: 2px; background: #121314"></i></span>On</label>
</div>
<div class="row">
<div><label class="lbl" for="ms">Max steps</label><div class="hint">Per chat turn. 0 = no limit.</div></div>
<input id="ms" class="inp" value="0" style="width: 120px">
</div>
<div class="row">
<div><div class="lbl">Rate limit</div><div class="hint">Off while either value is 0.</div></div>
<div style="display: flex; align-items: center; gap: 10px; font-size: 13px; color: #a6a39b"><input aria-label="Max requests" class="inp" value="0" style="width: 90px"> requests per <input aria-label="Window" class="inp" value="0" style="width: 80px"><select aria-label="Window unit" class="inp" style="width: 110px; font-family: 'IBM Plex Sans', sans-serif"><option>minutes</option></select></div>
</div>
<div class="row">
<div><label class="lbl" for="md">Models</label><div class="hint">Models chat sessions may use.</div></div>
<input id="md" class="inp" placeholder="Default">
</div>
<div class="row">
<div><label class="lbl" for="op">Operator</label><div class="hint">Who Archie treats as its operator.</div></div>
<input id="op" class="inp" placeholder="Not set">
</div>
</section>
<div style="display: flex; align-items: center; gap: 10px; font-size: 12px; color: #8f8c85">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"></circle><path d="M12 7v5l3 2"></path></svg>
Version 1 · 11 fields set by <span class="mono">system:migration</span> 8 hrs ago · <a href="#" style="color: #a6a39b; text-decoration: underline">View in History</a>
</div>
</div>
</main>
</div>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":1300}}'>
class Component extends DCLogic {
renderVals() {
return {
accent: this.props.accent ?? '#86b5a0',
inactive: [
{ name: 'Email', sub: 'Listen for mail and relay replies.', icon: 'M3 6h18v12H3zM3 6l9 7 9-7' },
{ name: 'Webhook', sub: 'Deliver agent output to a URL, with a signing secret and template.', icon: 'M10 13a5 5 0 0 0 7 0l3-3a5 5 0 0 0-7-7l-1 1M14 11a5 5 0 0 0-7 0l-3 3a5 5 0 0 0 7 7l1-1' }
]
};
}
}
</script>
</body>
</html>
@@ -1,120 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Theme and components</title>
<script src="./support.js"></script>
</head>
<body>
<x-dc>
<helmet>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&amp;family=IBM+Plex+Sans:wght@400;500;600&amp;display=swap" rel="stylesheet">
<style>
body{margin:0;background:#121314}
.inp{box-sizing:border-box;height:36px;padding:0 12px;background:#121314;border:1px solid #2e3034;border-radius:6px;color:#e8e6e1;font:400 13px 'IBM Plex Mono',monospace;outline:none;width:100%}
.btn{height:36px;padding:0 16px;border-radius:6px;font:500 13px 'IBM Plex Sans',sans-serif;cursor:pointer;border:1px solid #34373c;background:#1e2023;color:#e8e6e1;display:inline-flex;align-items:center;gap:8px}
.btn-primary{background:var(--accent);border-color:var(--accent);color:#101412}
.h{font-size:11px;text-transform:uppercase;letter-spacing:0.08em;color:#8f8c85;margin:0 0 14px;font-weight:500}
.panel{border:1px solid #2a2c30;border-radius:10px;background:#16171a;padding:24px}
.pill{display:inline-flex;align-items:center;gap:6px;font-size:12px;padding:4px 10px;border-radius:999px;border:1px solid}
.dot{width:7px;height:7px;border-radius:50%}
.sw{width:36px;height:20px;border-radius:999px;position:relative;display:inline-block}
.sw i{position:absolute;top:2px;width:16px;height:16px;border-radius:50%}
.lbl{font-size:13px;font-weight:500;color:#e8e6e1}
.hint{font-size:12px;color:#8f8c85}
</style>
</helmet>
<div style="--accent: {{accent}}; width: 1440px; height: 980px; box-sizing: border-box; padding: 48px 56px; background: #121314; color: #e8e6e1; font-family: 'IBM Plex Sans', sans-serif; display: flex; flex-direction: column; gap: 24px">
<div>
<h1 style="margin: 0; font-size: 28px; font-weight: 600; letter-spacing: -0.01em">Graphite theme</h1>
<p style="margin: 6px 0 0; font-size: 14px; color: #a6a39b">Warm neutral greys carry the page; one low-chroma accent marks the active item, focus and primary action.</p>
</div>
<div style="display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 24px">
<section class="panel">
<h2 class="h">Palette</h2>
<div style="display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 10px">
<sc-for list="{{swatches}}" as="s" hint-placeholder-count="8">
<div style="display: flex; flex-direction: column; gap: 6px">
<div style="height: 44px; border-radius: 6px; background: {{s.hex}}; border: 1px solid #2e3034"></div>
<span style="font-size: 12px">{{s.name}}</span>
<span style="font: 11px 'IBM Plex Mono', monospace; color: #8f8c85">{{s.hex}}</span>
</div>
</sc-for>
</div>
<h2 class="h" style="margin-top: 24px">Type</h2>
<div style="display: flex; flex-direction: column; gap: 8px">
<span style="font-size: 24px; font-weight: 600">IBM Plex Sans 600 · 24</span>
<span style="font-size: 14px; color: #a6a39b">IBM Plex Sans 400 · 14 body</span>
<span style="font: 13px 'IBM Plex Mono', monospace">IBM Plex Mono · values, keys, durations</span>
</div>
</section>
<section class="panel">
<h2 class="h">Buttons</h2>
<div style="display: flex; gap: 10px; flex-wrap: wrap">
<button class="btn btn-primary">Save &amp; restart</button>
<button class="btn">Secondary</button>
<button class="btn" style="background: transparent; border-color: transparent; color: #a6a39b">Discard</button>
<button class="btn" style="background: transparent; color: #d9776b; border-color: #3a2a28">Delete</button>
</div>
<h2 class="h" style="margin-top: 24px">Status</h2>
<div style="display: flex; gap: 8px; flex-wrap: wrap">
<span class="pill" style="color: #a6a39b; border-color: #2e3034"><span class="dot" style="background: {{accent}}"></span>Connected</span>
<span class="pill" style="color: #a6a39b; border-color: #2e3034"><span class="dot" style="background: #d9a45b"></span>Connecting…</span>
<span class="pill" style="color: #d9a45b; border-color: rgba(217,164,91,0.3); background: rgba(217,164,91,0.08)">Applies after restart</span>
<span class="pill" style="color: {{accent}}; border-color: {{accent}}">2 edited</span>
<span class="pill" style="color: #e0a39a; border-color: rgba(217,119,107,0.35); background: rgba(217,119,107,0.08)">Invalid duration</span>
</div>
<h2 class="h" style="margin-top: 24px">Toggles &amp; choice</h2>
<div style="display: flex; align-items: center; gap: 20px">
<label style="display: flex; align-items: center; gap: 8px; font-size: 13px"><span class="sw" style="background: {{accent}}"><i style="right: 2px; background: #121314"></i></span>On</label>
<label style="display: flex; align-items: center; gap: 8px; font-size: 13px; color: #a6a39b"><span class="sw" style="background: #2e3034"><i style="left: 2px; background: #8f8c85"></i></span>Off</label>
<div style="display: inline-flex; padding: 3px; background: #121314; border: 1px solid #2e3034; border-radius: 8px">
<button style="height: 28px; padding: 0 12px; border: 0; border-radius: 5px; background: #26282c; color: #e8e6e1; font: 500 12px 'IBM Plex Sans', sans-serif">Assignee</button>
<button style="height: 28px; padding: 0 12px; border: 0; border-radius: 5px; background: transparent; color: #8f8c85; font: 500 12px 'IBM Plex Sans', sans-serif">Label</button>
</div>
</div>
</section>
<section class="panel" style="display: flex; flex-direction: column; gap: 16px">
<h2 class="h" style="margin: 0">Inputs</h2>
<div style="display: flex; flex-direction: column; gap: 6px"><label class="lbl" for="c1">Text</label><input id="c1" class="inp" value="archie-core_default"></div>
<div style="display: flex; flex-direction: column; gap: 6px"><label class="lbl" for="c2">Focused</label><input id="c2" class="inp" value="ghcr.io/…/archie-agent:latest" style="border-color: {{accent}}; box-shadow: 0 0 0 3px rgba(134,181,160,0.15)"></div>
<div style="display: flex; flex-direction: column; gap: 6px"><label class="lbl" for="c3">Duration with unit</label>
<div style="display: flex"><input id="c3" class="inp" value="72" style="border-radius: 6px 0 0 6px"><select aria-label="Unit" class="inp" style="width: 110px; border-radius: 0 6px 6px 0; border-left: 0; font-family: 'IBM Plex Sans', sans-serif"><option>hours</option></select></div></div>
<div style="display: flex; flex-direction: column; gap: 6px"><label class="lbl" for="c4">Error</label><input id="c4" class="inp" value="1hr" style="border-color: #d9776b"><span style="font-size: 12px; color: #e0a39a">Use a number and a unit, e.g. 1h or 90m</span></div>
<div style="display: flex; flex-direction: column; gap: 6px"><span class="lbl">Secret reference</span>
<div style="display: flex; align-items: center; gap: 8px; height: 36px; padding: 0 12px; border: 1px solid #2e3034; border-radius: 6px">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="#8f8c85" stroke-width="2"><rect x="4" y="10" width="16" height="10" rx="2"></rect><path d="M8 10V7a4 4 0 0 1 8 0v3"></path></svg>
<span style="font: 12px 'IBM Plex Mono', monospace; color: #8f8c85">bws /</span><span style="font: 13px 'IBM Plex Mono', monospace">MINIMAX_API_KEY</span>
<span style="margin-left: auto; font-size: 12px; color: {{accent}}">resolved</span>
</div></div>
</section>
</div>
</div>
</x-dc>
<script type="text/x-dc" data-dc-script data-props='{"accent":{"editor":"color","default":"#86b5a0","options":["#86b5a0","#8aa4c2","#d4a373","#a397c9"]},"$preview":{"width":1440,"height":980}}'>
class Component extends DCLogic {
renderVals() {
const accent = this.props.accent ?? '#86b5a0';
return {
accent,
swatches: [
{ name: 'Ground', hex: '#121314' },
{ name: 'Surface', hex: '#16171a' },
{ name: 'Raised', hex: '#1e2023' },
{ name: 'Border', hex: '#2a2c30' },
{ name: 'Text', hex: '#e8e6e1' },
{ name: 'Muted', hex: '#8f8c85' },
{ name: 'Accent', hex: accent },
{ name: 'Warn', hex: '#d9a45b' }
]
};
}
}
</script>
</body>
</html>
-84
View File
@@ -1,84 +0,0 @@
/*
* Archie "Graphite" theme tokens.
* Warm neutral greys carry the page; ONE low-chroma accent marks the active
* nav item, focus rings, "edited" markers and the primary action. Nothing else
* uses the accent. Map these onto whatever styling system the app already uses
* (Tailwind theme, CSS modules, styled-components…) rather than adding a
* parallel system.
*/
@import url("https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500&family=IBM+Plex+Sans:wght@400;500;600&display=swap");
:root {
/* Surfaces (darkest → lightest) */
--bg: #121314; /* page ground, input fill */
--bg-header: #151618; /* app top bar */
--surface: #16171a; /* cards, panels, list containers */
--surface-2: #17181a; /* sticky save bar, drawer, table header */
--raised: #1e2023; /* active nav item, secondary button, hover */
--raised-2: #26282c; /* selected segment in a segmented control */
/* Lines */
--border-subtle: #202225; /* row dividers inside tables */
--border: #232529; /* section dividers, header/sidebar edges */
--border-card: #2a2c30; /* card and panel outlines */
--border-input: #2e3034; /* inputs, toggles off-track */
--border-button: #34373c; /* secondary button outline */
--border-edited: #3a3f3c; /* outline of a section with unsaved edits */
/* Text */
--text: #e8e6e1; /* primary */
--text-2: #a6a39b; /* secondary, nav items, descriptions of sections */
--text-3: #8f8c85; /* hints, captions, placeholders, table headers (≥4.5:1 on --surface) */
--text-on-accent:#101412; /* text on accent-filled buttons */
/* Accent — one at a time. Default sage; alternatives kept for a theme picker. */
--accent: #86b5a0; /* sage (default) */
--accent-ring: rgba(134, 181, 160, 0.15); /* focus halo */
/* --accent: #8aa4c2; steel */
/* --accent: #d4a373; sand */
/* --accent: #a397c9; muted violet (closest to the old purple) */
/* Status */
--warn: #d9a45b; /* "applies after restart", "connecting" dot */
--warn-text: #e3c08f;
--warn-bg: rgba(217, 164, 91, 0.08);
--warn-border: rgba(217, 164, 91, 0.25);
--danger: #d9776b; /* delete, invalid input border, dead state */
--danger-text: #e0a39a;
--danger-bg: rgba(217, 119, 107, 0.08);
--danger-border: #3a2a28;
--diff-add-bg: rgba(134, 181, 160, 0.10);
--diff-add-text: #a9d1bf;
--diff-del-bg: rgba(217, 119, 107, 0.08);
--diff-del-text: #e0a39a;
/* Agent state colours (label table swatches, and anywhere states are shown) */
--state-queued: #8f8c85;
--state-working: #8aa4c2;
--state-waiting: #d9a45b;
--state-pr: #86b5a0;
--state-parked: #6f6c66;
--state-dead: #d9776b;
/* Type */
--font-sans: "IBM Plex Sans", system-ui, sans-serif;
--font-mono: "IBM Plex Mono", ui-monospace, monospace; /* ALL config values, keys, durations, image refs */
--fs-page-title: 24px; /* weight 600, letter-spacing -0.01em */
--fs-card-title: 15px; /* weight 500 */
--fs-body: 14px;
--fs-control: 13px; /* inputs, buttons, nav, labels (label weight 500) */
--fs-hint: 12px; /* line-height 1.5 */
--fs-eyebrow: 11px; /* uppercase, letter-spacing 0.06–0.08em, --text-3 */
/* Shape & spacing */
--radius-sm: 4px; /* kbd hints */
--radius: 6px; /* inputs, buttons, nav items */
--radius-md: 8px; /* segmented control, callouts, diff cards */
--radius-lg: 10px; /* cards, panels */
--radius-pill: 999px;
--control-h: 36px; /* inputs, buttons, nav items */
--header-h: 56px;
--sidebar-w: 264px;
--content-max: 920px;
--row-label-w: 280px; /* left column of a setting row */
}
@@ -1,45 +0,0 @@
{
"name": "Archie Graphite",
"color": {
"bg": "#121314",
"bgHeader": "#151618",
"surface": "#16171a",
"surface2": "#17181a",
"raised": "#1e2023",
"raised2": "#26282c",
"borderSubtle": "#202225",
"border": "#232529",
"borderCard": "#2a2c30",
"borderInput": "#2e3034",
"borderButton": "#34373c",
"borderEdited": "#3a3f3c",
"text": "#e8e6e1",
"text2": "#a6a39b",
"text3": "#8f8c85",
"textOnAccent": "#101412",
"accent": "#86b5a0",
"accentRing": "rgba(134,181,160,0.15)",
"accentAlternatives": { "sage": "#86b5a0", "steel": "#8aa4c2", "sand": "#d4a373", "mutedViolet": "#a397c9" },
"warn": "#d9a45b",
"warnText": "#e3c08f",
"warnBg": "rgba(217,164,91,0.08)",
"warnBorder": "rgba(217,164,91,0.25)",
"danger": "#d9776b",
"dangerText": "#e0a39a",
"dangerBg": "rgba(217,119,107,0.08)",
"dangerBorder": "#3a2a28",
"diffAddBg": "rgba(134,181,160,0.10)",
"diffAddText": "#a9d1bf",
"diffDelBg": "rgba(217,119,107,0.08)",
"diffDelText": "#e0a39a",
"state": { "queued": "#8f8c85", "working": "#8aa4c2", "waiting": "#d9a45b", "pr": "#86b5a0", "parked": "#6f6c66", "dead": "#d9776b" }
},
"font": {
"sans": "\"IBM Plex Sans\", system-ui, sans-serif",
"mono": "\"IBM Plex Mono\", ui-monospace, monospace",
"size": { "pageTitle": 24, "cardTitle": 15, "body": 14, "control": 13, "hint": 12, "eyebrow": 11 },
"weight": { "regular": 400, "medium": 500, "semibold": 600 }
},
"radius": { "sm": 4, "base": 6, "md": 8, "lg": 10, "pill": 999 },
"size": { "controlHeight": 36, "headerHeight": 56, "sidebarWidth": 264, "contentMax": 920, "rowLabelWidth": 280 }
}
-49
View File
@@ -1,49 +0,0 @@
# Agent
Authority: `docs/architecture/agent-system.md` (execution boundary, the model
never runs git) and the Deployment Model section of `CLAUDE.md`.
The daemon prepares a workspace, starts one container per task from a profile's
image, and hands the whole task to `archie-agent` over NATS in one
`taskrun.Request`. The agent reaches the State Store, forge and worktree push
only through the daemon's RPC servers, using task-scoped credentials.
## Giving the agent something new
- **Data about the task** goes in `taskrun.Request` or the task brief
(`container.TaskPayload`), never in an environment variable. Add a test that
the request carries it (`TestRunViaAgentSendsMCPServers` is the pattern).
- **A credential** is scoped to the task and revoked when it ends, like the
State Store grant and the worktree publication grant. The daemon's own
administrative token never enters a container.
- **A tool** reaches the agent through the central registry, MCP, a repository
script or a skill plugin. A profile's `tools` list filters those; ai-sdk
agentloop's built-in file tools are outside it. A tool that must stay inside
the workspace uses the agent loop's confinement, not its own path handling.
## Changing the agent image or a profile image
1. The agent image is `Dockerfile`; example profile images live in
`examples/profiles/`, each with a build-only service in
`docker-compose.yml` (`profiles: ["build"]`, so `up -d` never starts it).
2. Anything the agent runs must be in the image. The container gets no
package manager at run time beyond what the image ships.
3. A locally built image needs `containers.pull_policy = "missing"`;
`"always"` tries to pull it and fails.
4. Profiles are configured under `[containers.profiles.<name>]` and resolved
by the daemon before the container starts (`pinTaskProfile`). An unknown
profile parks the task; it never falls back to the default image.
## Changing how a task runs
- Workspace preparation happens in the daemon (`prepareWorkspace`) before the
container starts, because the container binds the directory. Clones need the
daemon's forge credential; the agent never clones.
- A task with no repository gets `worktree.Manager.ScratchDir`, which is
removed when the task ends.
- The agent runs as root in the container. Anything it writes into the
bind-mounted workspace is handed back to the daemon's UID
(`restoreWorktreeOwnership`); a new write path must stay inside that
workspace.
- NATS rules are in `CLAUDE.md`: task responses use `msg.Respond`, a responder
is flushed after it registers, and `ARCHIE_TASKS` is a work queue.
-83
View File
@@ -1,83 +0,0 @@
# Control plane and settings
Authority: `docs/architecture/configuration.md`. The wiring matrix, the
decoded-but-unwired ledger and the three shapes an unwired field takes are in
`.agents/skills/archie-config-and-flags`.
A field that parses is not a field that works. Before adding one, name the code
that reads it and the path the value takes to get there.
## Decide what kind of setting it is
- **Bootstrap-only** (read once at process start: `database_url`, `state_dir`,
`work_dir`). It stays in the file, is checked by `validateBootstrap` in
`internal/infrastructure/configuration/validate.go`, and the runtime overlay
refuses changes to it.
- **Database-owned** (repository policies, scheduling, tools, plugins,
channels, containers). The file only seeds it. Once the State Store holds the
control-plane resource, the stored document is layered over the file
(`controlplane.Client.RuntimeConfig`) and the file key stops mattering. It is
checked by `validateDatabaseOwned` and by the resource's validator. A stored
value is refreshed from the file only when the store has no value for the kind
at all; a kind that ships a document of its own (workflow definitions,
personas) is refreshed whenever the seed itself wrote the stored copy, since
that copy is a previous release's document rather than an operator's
(`controlplane.Server.seedKind`).
- **Worker-carried.** A value the agent container needs travels in
`config.TaskConfig` (`Config.ForTask`) or on `taskrun.Request`. Never pass it
as an environment variable the daemon did not already define, and never carry
a secret this way.
## Adding a database-owned field
1. Add it to the wire-shape type the resource's `Document` names — a dedicated
struct in `internal/app/controlplane/` with explicit snake_case json tags
(`channel_settings.go`, `tool_settings.go`, `container_settings.go` are the
precedents), never the internal config struct itself. A struct fed straight
into the document falls back to Go field names (`Window`, `MaxRequests`),
and a bare `time.Duration` marshals as nanoseconds — both render unusable
in the Web UI. The resource's JSON schema and the dashboard's Advanced
settings editor are generated from that type, so no UI work is needed for
the editor itself.
2. Map to and from the internal config type at the resource boundary (`Seed`,
the layering in `runtime_config.go`, and the validator all use the same
mapping). Durations in the document are a string-marshalling type
(`config.Duration` or a document-local one), never a bare `time.Duration`.
3. A document stored before the shape existed carries Go-cased keys. Read them
with `controlplanerpc.DecodeRenamingLegacyKeys` (an `UnmarshalJSON` on the
wire type) while keeping `DisallowUnknownFields` — dropping unknown keys
would decode a misspelling as "unset" — and register a `Normalize` on the
`Definition` that re-encodes the document, so a legacy document converges
the next time it is written. A map or a nested struct needs its layering
checked: a stored map replaces the file's, not merges into it, and a field
the stored document omits keeps the file's value. Add a case to
`internal/app/controlplane/runtime_config_test.go` for both.
4. Validate it in one function both sides call, and add a case to
`TestResourceValidatorsRejectWhatEffectiveValidationRejects` in
`validators_agree_test.go`, so the file and the resource cannot disagree.
5. Decide whether it reloads: it does only if every consumer re-reads it from
`config.Holder`. The allowlist is `internal/app/archied/reload.go`; anything
not on it requires a restart.
6. If the settings page shows it as a plain field, add it to
`internal/webui/config_schema.go` and the view in `api_config.go`.
7. A generic catalog resource (`replace` command, not domain-managed, no
query service) is watched **once per archie-ui process** by `webui.RunLive`,
then published to every browser through `/api/stream`. Do not add an
EventSource per resource to a settings store or a gRPC Watch per HTTP client.
The control-plane server polls `Resource` every 250ms per upstream Watch;
verify watch count is independent of client count and that late clients get
the hub's current value (`internal/webui/live_hub_test.go`, real server over
bufconn). Reopens resume after the last delivered version and charge failed
attempts; accepting a gRPC stream does not establish its health.
## Every new field
- Test through the layering: build the effective config the way boot does,
not by setting the field on the consumer.
- Add a commented example to `config.example.toml`. Touch `deployments/*.toml`
only when a profile there needs a value different from the default.
- Update the wiring matrix in `.agents/skills/archie-config-and-flags`.
- Secrets are `SecretRef`s resolved through the secret registry. Never inspect
a resolved value, even in a test.
- Reject a configuration that sets a field with no consumer rather than
accepting and ignoring it (per-identity `forge.intake` is the precedent).
-91
View File
@@ -1,91 +0,0 @@
# Daemon
The daemon claims and runs tasks, and turns captured events into tasks through
bindings. This page covers both.
## Task lifecycle
Authority: `docs/architecture/agent-system.md`. The status vocabulary lives in
`internal/taskstate`, which imports no internal package.
### Adding a status
1. Add the constant to `internal/taskstate/taskstate.go` and place it in
`Terminal`, `Actions` and `Statuses`. Its value is stored, so renaming it
later is a migration.
2. Alias it in `internal/domain/workflow/task/task.go` and
`internal/domain/workflow/task_aliases.go`.
3. Add it to the default catalogue in `ui/src/lib/task-meta.ts`. The server
catalogue replaces the defaults when it loads, but the defaults render first.
4. Find every hand-written status list in SQL:
`grep -rn "'merged'" internal/infrastructure/postgres/queries`.
`ClearTerminalTasks` must match `taskstate.Terminal`, which
`TestClearTerminalTasksMatchesTaskstate` enforces. The stats queries count
outcomes by name; decide whether the new status counts.
5. Extend the table in `taskstate_test.go`.
### Adding a task field
Follow [State Store](state-store.md) for the
column and the wire. Then decide who writes it: `UpdateTask` writes a fixed
column set, so a field set at enqueue belongs in the insert that creates the
row (as `InsertChatTask` does for inputs), or in its own statement when only
some producers set it (as `StampTaskBinding` does for binding provenance).
### Changing what the agent receives
- The task brief is `container.TaskPayload`, written to
`<workspace>/.git/task.json` by `WriteTaskJSON`. Never write it to the
workspace root: the commit stage stages everything there.
- The run request is `taskrun.Request`. `Validate` rejects a request that
cannot run; a new requirement goes there.
- Parking always carries a class (`taskstate.ParkTransient`,
`ParkNeedsHuman`, `ParkTerminal`) chosen by the code that parks. Pick the one
that says what an operator must do.
- A task with no repository (`Task.HasRepository`) runs in a scratch workspace
with no worktree grant. Code that assumes an owner and repo must check first.
## Event automation
Authority: `docs/prds/event-automation.md` (the model: source, event type,
mapping, binding, workflow, profile) and `docs/architecture/bindings.md`
(threat model).
### Where each check lives
A binding is checked twice, and a new rule usually belongs in both places:
- **On save**, in `checkedBinding` (`internal/webui/api_binding.go`), so the
operator sees the problem while editing. It calls the domain checks
`binding.Validate`, `binding.CompileFilter` and `Binding.CheckWorkflow`.
- **At dispatch**, in `dispatchOneBinding` and `resolveBindingTarget`
(`internal/daemon`), because the workflow or mapping may have changed since
the save. A refusal is recorded with `recordDispatchFailure` and starts no
task.
Put the rule itself in `internal/domain/binding` or
`internal/domain/workflow/task` and call it from both, rather than writing it
twice.
### Adding a binding field
1. Domain type and `Validate` in `internal/domain/binding`.
2. Column, queries, store mapping, wire field, `newColumns`
([State Store](state-store.md)).
3. The request type and `checkedBinding` in `api_binding.go`.
4. The draft, payload and editor in `ui/src/bindings/`
([Frontend UI](frontend-ui.md)).
5. Its effect at dispatch, with a case in
`internal/daemon/dispatch_inputs_test.go` or `dispatch_bindings_test.go`.
### Rules that must hold
- Signing belongs to the source. Intake verifies the HMAC against the source's
secret before the payload is parsed.
- An event must be identified as an event type before anything dispatches it,
and a binding applies only to its mapping's event type. Dispatch test
fixtures therefore create an event type before inserting captures.
- The dispatch ledger is claimed before the task is enqueued (at most once).
- Anything an event supplies that selects what the agent acts on, such as a
repository, must be checked against configuration. An event never widens
what an agent can reach.
-108
View File
@@ -1,108 +0,0 @@
# Frontend UI
Authority: `.agents/skills/archie-web-ui` (stack facts, design-system rules,
tone and accessibility). This page covers what a change must reach, not how it
should look.
## Adding or changing a feature
1. The feature lives in `ui/src/<feature>/`. Move a helper to `ui/src/base/`
only when a second feature needs it.
2. Keep wire shapes, draft state and payload building in a plain `.ts` module
beside the components (`ui/src/bindings/binding-draft.ts` is the pattern),
and test it in `ui/test/*.test.ts`. Components stay thin.
3. Every mutation goes through `api.*` in `ui/src/lib/api`, which sends the
CSRF and Content-Type headers the server's mutation guard requires. A bare
`fetch` is refused.
4. A value the server also describes (task statuses, actions, workflow inputs)
comes from the server. Keep a local default only so the first render works,
and keep it in step (`ui/src/lib/task-meta.ts`).
5. Run `task ui`, `task test:ui` and `cd ui && npm run typecheck`. Commit the
regenerated `ui/dist/`; the Go binaries embed it. A fresh git worktree has
no ignored `ui/node_modules`: run `cd ui && npm ci` before these commands.
6. **One long-lived browser connection:** `ui/src/lib/api.ts` has the only
`new EventSource`, owned by `stores/live-updates.ts`. Feature stores consume
topics with `live.subscribe(topic, callback)`; do not open a page-owned SSE
stream. Logs alone opt in while mounted, replacing that same EventSource
with `?topics=logs&since=<last cursor>`; a browser's `Last-Event-ID` only
survives its own automatic reconnect, not a newly constructed EventSource.
Task and log topics resume by cursor; control-plane, identity and apply-status
topics replay the latest snapshot. Test a fetch and same-origin navigation
after visiting Settings and Logs: the UI process serves HTTP/1.1 and six
persistent streams can starve every later browser request.
## Testing the dashboard
Authority: the runner itself is `ui/package.json`'s `test` script: `node --test
--experimental-strip-types test/*.test.ts` over `ui/test/*.test.ts`. It runs
pure TypeScript modules with `node`'s type stripping — no SFC loader, no DOM,
no second dependency beyond what the app already carries. That is the standard,
and a decision record for when it is deliberately not enough:
- **Test archie's logic in a module; leave SFC wiring alone.** Wire shapes,
draft state, copy conditions, filters and payload building live in plain
`.ts` files beside the components and are tested in `ui/test/`. Components
stay thin, so there is normally nothing in an SFC that is archie logic.
- **A dashboard rule that mirrors a server rule is pinned by a shared
fixture, not two independent tests.** `ui/src/settings/validation.ts`
hand-mirrors three control-plane validators, and the model-role rule had
already drifted because nothing tied the two sides together. Each case now
lives once in `internal/app/controlplane/testdata/dashboard-validators.json`:
a Go test in that package runs the real server validators over it, and
`ui/test/control-plane-validator-parity.test.ts` runs the real dashboard
validators over the same cases. Changing one rule alone fails the other
side's test. Add a case to the fixture, never to one side only.
- **Installed primitives are upstream-tested, not re-tested here.**
`reka-ui` (2.10.5 here) maintains colocated tests per component in its own
repo (Vitest/jsdom + axe: Switch, TagsInput, NumberField, Select, the
arrow-navigation composables). The npm package ships none of those files, so
this coverage is inherited through the version bound, not the tarball —
`grep -l test node_modules/reka-ui` finds nothing. Duplicating them as local
mount tests would test a dependency.
- **A `.vue` import cannot run under the module runner.** `node --test` fails
such a module with `ERR_UNKNOWN_FILE_EXTENSION: .vue` and the runner has no
built-in loader for SFCs. A file under `ui/test/` that imports a `.vue` is
therefore a broken test, not a weak one.
- **If a DOM mount harness is ever needed** (a page-level accessibility
contract, cross-component interaction, focus behaviour): `happy-dom` +
`@vue/test-utils` + `vitest` scoped to a separate DOM test glob, keeping the
module runner for everything else. Measured on the ui tree (vitest 5.0.2,
happy-dom 20.14.5, @vue/test-utils 2.5.1): they add 24 top-level
`node_modules` entries and 27 MB on a 296 MB install, a working 2-test mount
suite (role=radiogroup vs role=switch, aria-label, click activation against
the real SFCs) runs in 1.2 s on top of the current 0.5 s module suite, and
`vue-tsc` (7.4 s) dominates `task test:ui` either way. The single-runner
alternative (absorbing the existing suite into vitest) was measured
infeasible as-is: all 29 existing files import `node:test`, which vitest
cannot collect ("No test suite found in file" for every one), so it would be
a rewrite of the whole suite, and its runtime was not measured. Nothing in
`ui/dist` or CI changes either way; happy-dom is pure JS, no browser binary.
- **What the module standard does not verify:** whether a call site passes an
`aria-label` or which `v-if` branch shows. Those live in SFC templates and
are only visible with a mount. If a page's accessible-name wiring is the
risk, say so in the page's task and reach for the harness decision above
rather than quietly growing mount tests. Never suppress a lint rule or a
test to keep SFC behaviour out of the gate.
## Adding an API route
1. The handler goes in the `internal/webui/api_<concern>.go` file for its
concern. Check the request fully on the server; the UI's checks are only a
convenience.
2. A mutation calls `authorizeTaskMutation` first.
3. A route whose store is not configured answers 503, and
`internal/app/archieui/degraded_routes_test.go` pins what each route
returns without its contract. Add the route there.
4. The dashboard runs in its own process (`archie-ui`) and must not link the
daemon or the workflow engine (`cmd/archie-ui/architecture_test.go`). Reach
stored data through `storecontract` interfaces wired in
`internal/app/archieui/compose.go`.
5. Settings that live in a control-plane resource need no new route: the
Advanced settings page edits every resource from its generated schema.
6. For a new live topic, add one process-wide producer to `internal/webui`'s
`RunLive` and fan it through the `/api/stream` hub; `internal/app/archieui/run.go`
starts the producers with the process context. Never create an upstream
watch or poller in an HTTP handler. A slow client must reconnect for cursor
and snapshot repair rather than silently lose an update. Prove the producer
with several browser clients against the real peer, not just a scripted
stream; `live_hub_test.go` is the example.
-47
View File
@@ -1,47 +0,0 @@
# Development guides
Checklists for changing Archie, one page per area. Each names every place a
change must reach, so a feature that works in one layer does not silently stop
at the next. A change that spans areas starts on the page for the area it
begins in, which points to the others. The pages point at the documents that
own the design (`docs/architecture/`, the PRDs, `CLAUDE.md`) rather than
restating them.
| Area | Covers |
| ---------------------------------------------- | -------------------------------------------------------------------------------- |
| [Frontend UI](frontend-ui.md) | Anything under `ui/`, and the dashboard's API routes |
| [Agent](agent.md) | The agent container, its image, profiles, tools and workspace |
| [Workflows](workflows.md) | Workflow definitions and step types |
| [Daemon](daemon.md) | Task statuses, fields and the brief; sources, event types, mappings and bindings |
| [State Store](state-store.md) | Stored fields, tables, RPCs and errors |
| [Control plane and settings](control-plane.md) | Settings in `config.toml` or the dashboard |
| [Processes and wiring](wiring.md) | Where code goes, processes, plugin engines, channels, NATS subjects |
| [Merging work](merging-work.md) | Merging a lane or a branch |
## Every change
- Write the failing test first for anything with logic, branching or a
contract, and check it fails on an assertion, not a compile error.
- Test through the path production uses. A test that sets a value directly on
the consumer proves nothing about the layers that normally deliver it.
- Run `task check` and let its exit status decide the commit:
`task check && git commit ...`. `task test` passes `-short`, which skips the
process and Postgres tests, so run `go test -count=1 ./cmd/... ./internal/...`
too when a change crosses a process or the database.
- Regenerate, never hand-edit, generated output: `task proto:generate`,
`go -C tools tool sqlc generate -f $PWD/internal/infrastructure/postgres/sqlc.yaml`,
`task ui`, `task docs:artifact`. `task proto:check` compares against the git
index, so stage regenerated contracts before running it.
- Stage by path, or read `git status` before `git add -A`. Tests that start
embedded NATS or write logs must use `t.TempDir()`; anything they leave in the
tree gets committed. `task check` writes no module file on a consistent tree,
root or `tools/` (verified at HEAD with `GOFLAGS` unset and with `-mod=mod`):
a stale `go.mod` or `go.sum` fails it, with `missing go.sum entry` or
`updates to go.mod needed`, rather than being repaired. Only a global
`GOFLAGS=-mod=mod` in `go env` re-enables that repair, which is why the
`go -C tools` steps pass `-mod=readonly`; if `go.sum` goes dirty, run
`go mod tidy` and commit the result on its own.
- A change to `docs/prds/`, `docs/architecture/` **or `docs/development/`**
carries the regenerated `docs/data/generated/dev-docs.json`: run
`task docs:artifact` (not `task docs:check`, which checks contracts only).
PRD edits also follow `docs/prds/RULES.md` and pass `task docs:prds`.
-46
View File
@@ -1,46 +0,0 @@
# Merging work
Parallel lanes (see `.agents/skills/archie-agent-fleet`) merge into an
integration branch before `main`. Each merge is a change in its own right and
passes the same gate.
## Resolving conflicts
- **Generated files** (`*.pb.go`, `postgresdb/*.go`, `ui/dist/`,
`docs/data/generated/*.json`): take either side, then regenerate. Never merge
them by hand.
- **One side deletes a file, the other edits it**: the deletion wins when the
deleting lane replaced the thing the file served. Move the other side's
change onto its replacement.
- **One side changes how code is built (a new store, renamed packages), the
other what it does**: take the behaviour side's version and reapply the
mechanical change to it. That is usually cleaner than merging line by line.
- **Error sentinels** are rows in `wireErrors`, not switch cases.
## After resolving
1. Search for leftovers of anything the other side removed: the old package
path, the old type, and comments describing the old behaviour.
2. Tests written against one side's semantics may pass there and fail after
the merge. A test that used to pass on the old store may be asserting a rule
the other side deliberately changed. Fix the test's setup to the merged
rule; do not loosen the rule to the test.
3. Run the full suite without `-short`, then `task check`, then commit. Check
`git status` for files a test wrote into the tree before staging.
4. **A merge can surface a bug neither lane's own tests exposed alone.** Two
real cases from 2026-09-26: a test that dialled no NATS URL passed on a
machine with an ambient dev server running and failed the moment it landed
on a clean CI runner (start an ephemeral server per test, never rely on a
default port resolving to something); and a cycle-detector that walked a
Go map in range order reported the same cycle two different ways from run
to run, invisible until enough fresh (uncached) runs hit the unlucky
ordering. Both looked like "the merge broke a passing test" but were
latent defects the merge only had the opportunity to expose. Fix the
defect the failure is pointing at, not the assertion that caught it — see
CLAUDE.md's test-quality bar before writing the replacement.
5. `go test`'s cache reuses a package's last result when nothing in its
dependency graph changed. A merge that touches one package can leave a
sibling's flaky test silently cached "pass" locally while CI runs it
fresh. `task check` passing on your machine is not proof a merge is
clean — rerun anything nondeterminism-prone with `-count=1` before
trusting it, and let CI's from-scratch run be the tiebreaker it is.
-65
View File
@@ -1,65 +0,0 @@
# State Store
Authority: `docs/prds/state-store-contract.md` and the State Store section of
`CLAUDE.md`. All persistence is PostgreSQL behind the standalone State Store
process; nothing else opens the database.
## Adding a column
1. Write the next migration in `internal/infrastructure/postgres/migrations/`
(`00NN_name.sql`, goose Up and Down). Give the column a `NOT NULL DEFAULT`
that is correct for existing rows.
2. Update the queries in `internal/infrastructure/postgres/queries/` and
regenerate with sqlc. A query that lists columns (`ListTaskSummaries`, the
binding selects) does not pick the new one up; `SELECT *` queries do.
3. Map it in the store (`taskFromRow`, `bindingValue` and friends). If the
column holds encoded data, the package that owns the type owns the encoding
(`task.EncodeInputs`), and the store and the wire both use it.
4. Carry it over the wire (next section) if any process other than the State
Store reads it.
## Adding a field to a wire message
1. Add it to `proto/state/v1/state.proto` with a new field number. Never reuse
a number; retire one with `deprecated = true`.
2. `task proto:generate`, then map it both ways in
`internal/infrastructure/staterpc/values.go`.
3. `TestTaskProtoCarriesEveryDomainField` fills every `task.Task` field and
fails on one the mapping forgets. If it cannot fill the field's kind, extend
it. Other messages have no such test, so add a round trip to
`conformance_test.go`.
## Adding an RPC or a store method
1. Put the Go method on the narrow consumer interface in
`internal/domain/storecontract` (keep each at eight methods or fewer) and add
the matching RPC. A Go method without an RPC does not cross the process.
2. Implement it in the Postgres store, in `staterpc.Client` (with its `var _`
assertion) and in `staterpc.server`. A missing dependency answers
`codes.Unavailable`, never a fabricated default.
3. Wire the dependency in every composition that serves or consumes it:
`stateStoreDeps` in `internal/app/archied/state_store.go`, the daemon's
assertions in `bootstrap.go`, and `internal/app/archieui/compose.go` for the
dashboard process.
4. Task-scoped tokens may call only `Update`, `Transition` and `InsertEvent` on
their own task (`staterpc.TaskGrants`). A new RPC is admin-only unless it is
added there deliberately.
5. Add it to `conformance_test.go`, which runs every surface over a real gRPC
connection.
## Adding an error sentinel
Add the sentinel to `storecontract`, a row to `wireErrors` in `values.go`, and
a case to `error_test.go`. The canonical message is part of the wire contract:
changing it breaks `errors.Is` on the client silently.
## Harness OAuth secrets
`HarnessSecretStore` stores token sets by org and credential service through
admin-only State Store RPCs. The EDA store seals them with the binding cipher's
keyring and a separate `HarnessSecretDomain`. OAuth writes require a configured
binding encryption key; the legacy binding plaintext fallback does not apply.
The daemon's egress proxy (`internal/infrastructure/egress/oauth.go`) is the
only daemon consumer: for a run granted the service it swaps sentinels for the
stored tokens and writes every refresh back. The setup terminal is a separate
harness slice.
-48
View File
@@ -1,48 +0,0 @@
# Processes and wiring
Authority: `docs/architecture/organisation.md` (layers, process boundaries),
`docs/architecture/dependencies-and-contracts.md` (dependency direction, wire
contracts) and `docs/architecture/plugins-and-extensions.md` (the plugin engine
rule).
## Placing new code
- Domain logic, entities and the interfaces it needs go in
`internal/domain/<area>/`, which imports no infrastructure or app package.
- Implementations of those interfaces go in `internal/infrastructure/<service>/`.
- Construction and wiring go in `internal/app/<application>/`; `cmd/` only
parses flags and calls it.
- `logging`, `events`, `eventbus`, `policy` and `taskstate` import no internal
package. There is no `shared/`, `utils/` or `common/` package.
- A behaviour has one authoritative path. Before adding a second way to do
something, remove or redirect the first.
## Adding a capability to a process
1. Decide which process owns it. A new binary is justified only when the
surface must fail, scale or run somewhere independently.
2. Wire it at that process's composition root. An optional capability
degrades: a missing provider logs a warning and marks health degraded
rather than stopping the process (MCP providers are the model).
3. Every process that reaches the capability through the State Store gets it
through a `storecontract` interface asserted on the client
([State Store](state-store.md)).
4. The architecture tests (`cmd/archie-ui/architecture_test.go`,
`cmd/archie-messaging/architecture_test.go`, `TestOpenStoresNeverOwnsTaskDB`)
pin what each binary may link. A failure there means the placement is wrong,
not the test.
## Adding a plugin engine
Satisfy every invariant in "Plugin engine rule (strict)" in
`plugins-and-extensions.md`: typed domain contract, an owning manager,
lifecycle and health, narrow host access, and an explicit trust boundary.
`internal/plugin/architecture_test.go` checks the parts that can be checked.
## Adding a channel or a NATS subject
- Channel rules (Telegram's pending-update drop, command scopes) are in
`CLAUDE.md` under Per-Package Invariants.
- A subject is part of the wire contract. Its payload type belongs to the
domain that defines its meaning, and the transport code lives in
infrastructure.
-76
View File
@@ -1,76 +0,0 @@
# Workflows
Authority: `docs/architecture/agent-system.md` for the lifecycle,
`docs/prds/event-automation.md` for inputs, repository modes and profiles.
Workflow definitions are YAML stored as a control-plane resource. The State
Store validates them and the agent compiles them, each against the step
vocabulary it registers, so both must see the same step types.
## Adding a step type
1. Write the factory in `internal/domain/workflow` as a `StepType`. It decodes
and validates its settings and returns an error for anything it cannot
honour. The factory runs when a definition is saved and again when it is
compiled, so a bad definition is refused on save.
2. Register it through a provider in
`internal/infrastructure/workflowsteps/workflowsteps.go`. That one list is
what every process registers, which is how the validating and executing
sides agree.
3. An agent-driven step builds on `AgentStage`; do not start a second path to
the agent runner.
4. A step that needs no repository goes in `repoFreeStepTypes` in
`definition.go`, or workflows declaring `repository: none` or `optional`
cannot use it. A step that needs one may assume `tc.Dir` holds a worktree
only when the workflow's repository is `required`.
5. A step that ends the workflow sets `tc.Outcome`. A workflow that runs out of
steps without an outcome is parked as a definition bug.
6. Add a parse test (settings accepted and refused) and a run test with fake
`Trees` and agent runner.
## Retiring a step type
A step word cannot simply be deleted. A stored or pinned definition is
validated as a whole collection, so one unknown word fails EVERY workflow's
definition to decode and the workflow-definitions resource becomes unreadable.
Retire a stage by removing it from its workflow's `Stages` and adding it to
`retiredSteps` in `definition.go`, which keeps the word resolving as an inert
stage. The retired stage must do nothing: the behaviour it used to perform now
belongs to whatever layer took it over (the remediate workflow's in-container
resume moved to daemon worktree preparation, `archie-core-866m`; the workflow
still binds the daemon-prepared directory and the PR branch in a `prepare`
stage before any agent work).
## Changing the definition format
- The fields a caller needs without the engine (inputs, repository, profile)
live in `task.WorkflowInterface`, because the dashboard process must not
import the workflow engine (`cmd/archie-ui/architecture_test.go`). Anything a
binding or the dashboard checks goes there.
- The YAML decoder rejects unknown keys. Existing stored definitions must keep
parsing, so a new key is optional with a default that preserves today's
behaviour.
- A declared `outputs:` entry is written through a capture tool, so it forces
the captures need: `task.WorkflowInterface.Needs` resolves that from the
declaration rather than the author also writing `needs.captures`. A Kit
profile whose harness serves no capture tools is refused before dispatch.
- Examples in `examples/workflows/` are parsed against the registered
vocabulary by `TestExampleWorkflowsParse`. Add one for a new capability.
## Enabling and disabling
The `workflow-enablement` control-plane resource lists, per org, the workflows
that org has disabled; anything unlisted is enabled. Its readers are the
daemon's binding dispatch (a disabled workflow's binding is skipped like an
unarmed one), the dashboard's binding save (refused) and binding list
(`workflow_disabled`), and work requests. A new reader of "may this org run
this workflow" goes through `task.WorkflowEnablement.Enabled`, never a second
list. The dashboard acts in the default org until access resolves a caller's
own.
## Starting a workflow from chat
`task_spawn` accepts `workflow` and an `inputs` object. The gateway forwards
inputs through the task creation contract; it does not interpret individual
workflows. The daemon checks inputs against the pinned `WorkflowInterface`
before acquiring a container and parks invalid requests with the reason.
+4 -10
View File
@@ -3,9 +3,7 @@
This walks through the whole no-code path the event-capture epic promises:
point an external app's webhook at archie, see the real payload it sends,
map the fields you care about, bind them to a workflow, and watch the next
matching event turn into a task -- no code, no redeploy, no restart. See
`docs/architecture/bindings.md` for the model and threat model behind each
step below.
matching event turn into a task -- no code, no redeploy, no restart.
## 1. Send a test event
@@ -26,9 +24,7 @@ curl -X POST http://localhost:8484/webhooks/capture/sentry \
```
This event isn't signed yet, so it's captured but marked **unauthenticated**
-- visible for you to design against, but incapable of triggering anything
(`docs/architecture/bindings.md`'s threat-model section explains why: an
unauthenticated event can never match a binding, no matter how it looks).
-- visible for you to design against, but incapable of triggering anything: an unauthenticated event can never match a binding.
## 2. Inspect the captured payload
@@ -68,8 +64,7 @@ Save. The binding starts in **draft** -- nothing fires yet.
A **draft** or freshly-**edited** binding needs an explicit human approval
before it can ever match a live event -- this is deliberate, not a missing
step: an operator authoring a binding is a considered act, an event arriving
is not, and nothing should self-arm (`docs/architecture/bindings.md`'s
threat-model section, point 2). Click **Approve**. Status becomes **armed**.
is not, and nothing should self-arm. Click **Approve**. Status becomes **armed**.
## 6. Fire it for real
@@ -89,8 +84,7 @@ curl -X POST http://localhost:8484/webhooks/capture/sentry \
This event is captured as **authenticated**, matched against your armed
binding, and dispatched into a new task through the exact same
gate/worktree/sandbox pipeline every other task goes through -- see
`docs/architecture/messaging-and-work-intake.md`'s "Intake provenance". Check
gate/worktree/sandbox pipeline every other task goes through. Check
the **Tasks** page; a new task should appear, its body built from the fields
your mapping resolved.
-28
View File
@@ -1,28 +0,0 @@
# PR review benchmark
Run `scripts/pr-review-benchmark.sh` with `PRBENCH_REVIEW_MODEL` and
`PRBENCH_CLASSIFICATION_MODEL` set to configured `provider/model` references.
The judge defaults to `anthropic/claude-sonnet-4.6`; set
`PRBENCH_JUDGE_MODEL` to another configured model when needed. The script uses
`~/.config/archie/config.toml` for providers and `GH_TOKEN` or `GITHUB_TOKEN`
for read access to the benchmark pull requests. It posts no forge review.
The default run reviews the 38 runnable Martian pull requests once each at
`deep`, judges the comments against 102 golden comments, and writes
`bin/prbench-results/run.json`, `summary.json`, and one JSON result per pull
request. That output directory is ignored by git. A completed full run fails
when any problem fails or golden micro-recall is below 0.70. Golden-only
precision is reported alongside recall. Set `PRBENCH_OUT` to keep separate
runs; `-problems ID` limits a smoke run to one pull request. Completed results
are saved as each PR finishes. Pass `-resume DIR` to reuse completed results
from a run with the same models; each reused problem must match the current
benchmark entry, and failed problems are rerun.
A smoke run alone is not the acceptance run.
The benchmark passes only each problem's ID and pull request URL to the
reviewer. The judge receives the golden comments after the review has ended.
The runner uses the production decision phases through the merge gate,
including scoring and the 25-comment cap, then stops before polish and forge
posting. A reviewer that fails to finish makes that problem fail. The results
record budget-skipped phases and the selected models. Model substitutions do
not satisfy the PRD's named-model criterion even if recall clears the threshold.
-130
View File
@@ -1,130 +0,0 @@
# Archie
**Event-driven Agentic Automation**
Archie connects events from your systems to agents that can investigate, reason,
and act. Define what an event means, map its data into a workflow, and give that
workflow an agent equipped for the job: its own execution environment, tools,
and identity.
The aim is to automate work across system administration, incident response,
network operations, service management, and software delivery. You define the
process and the access it requires; agents work through its stages, using the
context of each event to decide how to accomplish the task.
Archie is under active development. The model below describes the project's
approved direction, with implementation progressing across event automation and
organisation access control. The
[event automation design](prds/event-automation.md) and
[organisations and access design](prds/orgs-and-access.md) describe those
capabilities and their delivery stages.
## From an event to an outcome
```text
Event source → Event type → Mapping → Binding → Workflow → Agent
```
| Concept | Purpose |
| -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Source** | Receive events from a system such as a firewall, monitoring stack, service desk, or forge. Configure its endpoint and signing requirements. |
| **Event type** | Identify which kind of event arrived from its headers and payload. Infer a schema from captured events or a pasted example. |
| **Mapping** | Extract named, typed parameters from the event. Reuse a mapping across bindings and see how often it matches. |
| **Binding** | Select a workflow, filter the events that should trigger it, and supply its inputs from mapped values or constants. |
| **Workflow** | Define the stages of work, their inputs and outputs, and the agent profile to use. Call other workflows when work needs another specialist or process. |
| **Agent** | Execute the work in a container with the tools for its purpose, acting under its own identity and granted permissions. |
A single source can produce several event types. An event type can feed several
bindings, and each binding can apply its own conditions. This lets the same
incoming data drive different responses without building a custom integration
for every workflow.
For example, a firewall sends a blocked-connection event. Archie identifies the
event type and maps the source address and severity into an investigation
workflow. A network investigator gathers evidence, assesses the activity, and
returns its findings. The workflow could then call a separate containment
workflow, subject to the permissions and approvals configured for that action.
The same model supports other processes:
- **Infrastructure operations:** A monitoring alert starts a diagnostic workflow
to inspect a service, collect evidence, and propose or perform an authorised
recovery action.
- **Service management:** An incoming request supplies the parameters for a
triage, investigation, or fulfilment workflow.
- **Software delivery:** A forge event starts a review or implementation
workflow with the repository's toolchain, validation steps, and pull request
as its output.
These are examples of workflows you can build. Their behaviour comes from the
workflow, tools, and access you configure.
## Agents equipped for their work
An agent profile selects the container image and available tools. You can supply
images with the software needed for a particular environment: network utilities
for an investigator, operational tooling for a systems agent, or a language
runtime and test framework for repository work.
Workflows declare structured inputs and can return structured outputs. They can
run with a scratch workspace, require a repository, or accept one optionally. An
investigation can finish with a report; a maintenance workflow can finish with
an operational result; a coding workflow can finish with a pull request.
Workflows can also call other workflows and pass data between them. Each called
workflow has its own run and agent profile. A caller can wait for the result or
continue while the called workflow runs independently.
See the
[firewall investigation example](https://github.com/samcharles93/archie-core/blob/main/examples/workflows/firewall-investigate.yaml)
for a workflow that uses typed inputs, a network investigator profile, and no
repository.
## Organisations, identities, and controlled execution
The approved access model organises automation into **organisations** and
**workspaces**. An organisation owns its members, agent identities, secrets,
profiles, and workflows. Workspaces group sources, mappings, bindings, and runs
by team responsibility or environment, such as network operations in production.
Each organisation can enable the default workflows it needs and add its own.
Agents act as their own identities. A workflow names the identity it runs as;
secrets and permissions are granted to that identity. Starting an agent is an
audited action, with a record of the workflow and the event or member that
initiated it.
The design combines roles for routine administration with attribute-based
policies for resources and execution context. Policies apply from the instance
through the organisation, workspace, identity, workflow, and individual object.
Lower levels can narrow access, and a denial takes precedence. Organisation and
workspace policy also determines which actions require approval from another
member.
Authorised runs receive credentials scoped to their identity, workspace, and
work. Event data supplies the task's inputs; it cannot grant additional access.
The [organisations and access design](prds/orgs-and-access.md) defines this
model; it remains an active implementation area.
## Building and operating automations
The dashboard brings together event inspection, mappings, bindings, workflows,
and task activity. The intended authoring path starts with a real payload or an
example: identify its structure, map the fields you need, select a workflow, and
approve the binding.
Sources default to signed delivery. The event automation design also allows an
explicitly approved unsigned source for systems that cannot sign payloads, with
that status visible to operators. Binding changes require re-approval before
they can dispatch work.
Playbooks and extension points provide additional orchestration through
workflows, modules, channels, and forges. The
[playbook engine design](prds/eda-playbook-engine.md) describes how
registered capabilities become actions that event rules can call.
## Start here
- [First playbook](guides/first-playbook.md) — connect an event source to a workflow.
- [Deployment examples](https://github.com/samcharles93/archie-core/blob/main/deployments/README.md) — configure and run Archie.
- [Architecture](architecture/index.md) — domain boundaries and settled design.
- [Development guides](development/index.md) — contribute to Archie.
-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.
Loaded 100 of 190 files, more files were not shown because too many files have changed in this diff. Show more