refactor: format markdown files using prettier, fix spelling concerns, reduce Taskfile bloat

This commit is contained in:
sam committed 2026-09-25 01:10:28 +10:00
1 parent 2051ca94d2
commit 2e00777f07
608 files changed
+63317 -10219

No files matched your search

+2 -2
View File
@@ -70,8 +70,8 @@ Effort is the per-stage `MaxSteps` budget, mapped onto `Subagent.MaxSteps`
## Operator-triggered review
The same reviewer runs against an *existing* PR via the channel-neutral
The same reviewer runs against an _existing_ PR via the channel-neutral
`review_pr` chat command: fetch the PR's head, snapshot it, run the isolated
reviewer, and return the structured findings. Authorization is identity-scoped
reviewer, and return the structured findings. Authorisation is identity-scoped
to the operator's configured repositories; duplicate or concurrent reviews of
the same PR are deduplicated.
+29 -29
View File
@@ -73,7 +73,7 @@ The Agent System requires four distinct durable memory scopes:
- **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
authorized Agents serving that user;
authorised Agents serving that user;
- **Agent-user relationship memory**: private history and learned context from
one particular Agent's relationship with one particular user.
@@ -86,7 +86,7 @@ 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 personalization boundary,
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.
@@ -96,7 +96,7 @@ 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 authorizing explicit cross-scope sharing are
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.
@@ -214,30 +214,30 @@ The behaviour is divided across technical packages:
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. |
| 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 serialization 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. |
| `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
@@ -283,7 +283,7 @@ preserved or deliberately 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 |
| 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
@@ -294,7 +294,7 @@ 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;
- serialize same-repository execution where policy requires it;
- 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;
@@ -342,7 +342,7 @@ implemented in different packages:
- Agent execution crosses a versioned data boundary.
- Forge, persistence, workspace, transport, container, and model runtimes remain
replaceable infrastructure.
- Work from the same repository is serialized by default.
- Work from the same repository is serialised by default.
## Required migration
+1 -1
View File
@@ -74,7 +74,7 @@ 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.
Modeled directly on Telegram's existing `dangerousAction`/`pendingApproval`
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/
+42 -42
View File
@@ -42,7 +42,7 @@ The document:
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 recognized filename for every
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
@@ -139,34 +139,34 @@ 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. |
| 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
@@ -187,8 +187,8 @@ decision; exact setting names are implementation details.
| 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 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. |
@@ -200,7 +200,7 @@ decision; exact setting names are implementation details.
| 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. |
| 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. |
@@ -235,15 +235,15 @@ constants outside their owning `DefaultSettings` construction.
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. |
| 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.
@@ -316,7 +316,7 @@ 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: catalog, query,
`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.
@@ -45,7 +45,7 @@ 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 serialization belong under
groups, acknowledgements, reconnection, and serialisation belong under
`internal/infrastructure/eventbus/nats` unless Archie explicitly requires a
semantic guarantee in the shared contract.
@@ -56,7 +56,7 @@ messages; it does not own their meaning.
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 centralized in `internal/infrastructure/spec` or another generic
MUST NOT be centralised in `internal/infrastructure/spec` or another generic
schema package.
Infrastructure owns:
+40 -59
View File
@@ -1,7 +1,7 @@
# Generated Documentation
**Status:** Generator scaffold in place; renderer and publishing removed
**Date:** 2026-07-28 (revised 2026-09-12)
**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
@@ -10,11 +10,10 @@ 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 normalizes documentation data;
- a repository-local Go generator extracts and normalises documentation data;
- the generator writes deterministic JSON/data files and protocol schemas;
- the rendering and publishing surface is an **open decision** — the VitePress
site and its Pages deployment were removed on 2026-09-12 as an unnecessary
build step (see "Rendering and publishing" below).
- the external Astro website consumes generated data and serves the public
documentation at `offloaded.dev/docs/`.
Hugo is not part of the target architecture.
@@ -32,7 +31,7 @@ docs/
*.md
```
### Rendering and publishing — OPEN
### 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
@@ -41,24 +40,23 @@ 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.
`docs/` is now repository documentation only — markdown read in the repository,
an editor, or a forge's file view. Nothing in the repository builds, renders, or
publishes it.
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 renderer for the generated `data/generated/*.json` is therefore **undecided**.
Consequences that follow, and their current state:
The current boundaries are:
| Concern | State after removal |
| --- | --- |
| Reference-page rendering | Undecided; `data/generated/contracts.json` is committed but unrendered |
| Internal link validation | Not enforced by any build; links are repository-relative (`../architecture/...`) and resolve on the filesystem |
| Generated-data drift detection | Unchanged — `docsgen check` compares committed output, independent of any renderer |
| Navigation/sidebar | The authoritative index is `docs/prds/01-project-management.md` |
| Local authoring server | None; read markdown directly |
| 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` |
A future renderer MUST NOT reintroduce a dead-link-blind build: VitePress
previously validated internal links during its production build, and no
replacement currently does.
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
@@ -107,7 +105,7 @@ load registries and types
-> compare or write output
```
The normalized documentation model prevents each output renderer from
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.
@@ -121,13 +119,13 @@ docsgen all
docsgen check
```
- `data` writes the normalized JSON reference data.
- `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 normalization and validation path.
MUST retain one normalisation and validation path.
## Target output
@@ -197,7 +195,7 @@ 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 normalized Archie data and
`docsgen` imports Archie-owned contracts and writes normalised Archie data and
protocol artifacts.
### Step 2: establish authoritative registries
@@ -280,26 +278,24 @@ Each category extractor contributes:
- version and deprecation information;
- relationships to commands, events, policies, and contracts.
The first vertical slice proves the normalized model and deterministic JSON
serialization. Later categories reuse it rather than introducing
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: render data (pending renderer decision)
### Step 5: external Astro renderer
Blocks on "Rendering and publishing" above. Once a renderer is chosen, it reads
`data/generated/*.json`, validates it, and renders reference views.
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.
No renderer is chosen, so this step is unstarted.
### Step 6: implement deterministic drift checking
`docsgen check`:
1. generates all artifacts into a temporary directory;
2. normalizes line endings and file modes;
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;
@@ -315,11 +311,11 @@ Generation MUST exclude:
Two consecutive `docsgen all` runs MUST be byte-identical.
### Step 7: renderer adaptation — blocked
### Step 7: Astro renderer — external consumer
Was "adapt the VitePress site". No renderer is chosen; this step is unstarted.
When a renderer is selected it MUST:
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
@@ -353,30 +349,15 @@ contract types (`docsgen`) and, from the Markdown sources, `docs.json` and
reader of the product gets, and the development set of architecture and design
records) -- see `task docs:artifact`.
### Step 9: CI
### Step 9: validation and CI
The original documentation workflow was deleted on 2026-09-12. `deploy.yml` still
does not reference `docs/**`.
`task check` validates generated contracts and Markdown-derived documentation
artifacts. The Astro site's rendered routes and deployment are validated in its
own repository.
`.github/workflows/docs.yml` (added 2026-09-18) builds the MkDocs site with
`mkdocs build --strict` on changes to `docs/**` or `mkdocs.yml`, so a dead
internal link fails before it reaches a deploy. It deliberately does no more
than that: it does not run `docsgen`, does not regenerate `contracts.json`, and
does not publish. Deployment is a separate path, run from the Ansible control
node by the `vectislabs.automation` `docs_site` role.
### Step 10: content migration
Generated-artifact drift is therefore still gated locally, by `task check`
running `docs:check`, and not in CI. That split is the point. A CI job that
regenerated output would be able to paper over uncommitted differences instead
of failing on them, which is the failure this section exists to prevent, so any
future documentation workflow MUST check generated output rather than produce
it.
### Step 10: cutover — done, in reverse
The site cutover is moot: the site was removed rather than published. The
generator's outputs (`docs/data/generated/`, `docs/public/schemas/`) remain
committed and are the durable artifacts.
The Astro site consumes generated artifacts. Remaining content work is to:
Still standing from the original cutover list:
+3 -4
View File
@@ -210,7 +210,7 @@ recovery protocol.
Identity is not authentication and is not access control.
The current architecture does not require authentication or authorization. Those
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.
@@ -275,8 +275,7 @@ 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 authorization check for
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.
@@ -329,7 +328,7 @@ Editable without a rebuild.
`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
_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
@@ -51,7 +51,7 @@ 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 authorized user-wide memory,
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
+25 -27
View File
@@ -114,7 +114,7 @@ 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 behavior,
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
@@ -200,16 +200,16 @@ hold no direct database handles, daemon state, or model runtimes.
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 stamps or infers a build version; `cmd/archie-messaging` deliberately takes no version ldflags, so it cannot report a partial upgrade as a matched one. |
| `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` | **Deliberately left nil**, for the same reason as `RunningVersions`. `releaseannounce.Announcer` announces nothing unless each `Component` carries a parseable version, and the only versions this service can obtain are the Gateway's own build stamps, not archied'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` | **Deliberately left nil.** It exists to turn an installer's claim into a checked one, and only a component's own compiled-in build can vouch for it. The Messaging Service knows neither archied's build nor the observed archie-agent version (`daemon.AgentStatus`), and the Gateway's own `gatewayVersion` is a different binary's stamp — reporting it as the daemon's would manufacture exactly the false success the check exists to catch. Update reports therefore relay as unverified claims until a component self-report contract exists. |
| `Dangerous` | Stays nil. No daemon composition ever set it; `/rollback` and `/stop` reported "not configured" before the extraction and still do. |
| Seam | Resolution |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Version` | Sourced from the Gateway via `ChatSnapshot.Version`. The Messaging Service never stamps or infers a build version; `cmd/archie-messaging` deliberately takes no version ldflags, so it cannot report a partial upgrade as a matched one. |
| `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` | **Deliberately left nil**, for the same reason as `RunningVersions`. `releaseannounce.Announcer` announces nothing unless each `Component` carries a parseable version, and the only versions this service can obtain are the Gateway's own build stamps, not archied'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` | **Deliberately left nil.** It exists to turn an installer's claim into a checked one, and only a component's own compiled-in build can vouch for it. The Messaging Service knows neither archied's build nor the observed archie-agent version (`daemon.AgentStatus`), and the Gateway's own `gatewayVersion` is a different binary's stamp — reporting it as the daemon's would manufacture exactly the false success the check exists to catch. Update reports therefore relay as unverified claims until a component self-report contract exists. |
| `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.
@@ -226,12 +226,12 @@ 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` |
| 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
@@ -294,7 +294,7 @@ originally left are answered, in both cases by measuring rather than by preferen
- 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
_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
@@ -473,7 +473,7 @@ memory model in general or a future non-file engine's model:
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`. Realized as a
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
@@ -561,7 +561,7 @@ 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 behavior, and deletion of the shared-holder and
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.
@@ -708,12 +708,11 @@ 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 VitePress site and its Pages
deployment were removed on 2026-09-12 as an unnecessary build step; `docs/` is
repository documentation only. The rendering and publishing surface is an open
decision, and so are the renderer's page templates and any developer commands
or CI sequence that would accompany one. Adapting the generator and implementing
Archie's normalized documentation model remain migration work rather than open
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`
@@ -742,7 +741,6 @@ The final migration plan must order:
Each legacy package requires objective removal criteria. No compatibility path
may become an indefinite second implementation.
## Completion criteria
Migration design is complete when:
+14 -14
View File
@@ -32,15 +32,15 @@ that container did:
`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
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*
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
@@ -149,8 +149,8 @@ additions. So is the read half: the three per-attempt endpoints
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.
The task log surface above answers _why did this park?_. This surface answers
_what did this run actually do?_, per attempt.
### Attempt attribution
@@ -205,15 +205,15 @@ the task's current attempt, and the resolved attempt is echoed in the response.
`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` |
| 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
+16 -16
View File
@@ -38,22 +38,22 @@ design questions.
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 |
| 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
+3 -3
View File
@@ -34,7 +34,7 @@ these invariants:
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, initialization,
`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
@@ -59,7 +59,7 @@ these invariants:
`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 behavior plus an
source, and the requirement that engine interfaces have domain behaviour plus an
owning registry or manager.
### Memory engine family
@@ -178,7 +178,7 @@ 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-normalize the adjacency with self-loops; power-iterate to the
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
+2 -2
View File
@@ -6,7 +6,7 @@
## Purpose
Retry limits, authorization, gates, commands, protected paths, tool
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.
@@ -34,7 +34,7 @@ Each consuming domain owns:
- its evaluators;
- the meaning and consequence of an evaluation.
Access therefore owns principals, resources, actions, and authorization
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.
+11 -11
View File
@@ -110,10 +110,10 @@ 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 |
| 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
@@ -144,12 +144,12 @@ 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 |
| 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
@@ -189,7 +189,7 @@ 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
**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
+5 -4
View File
@@ -1,23 +1,24 @@
# archied -- design notes
# archied -- design notes
Archie is a resident daemon that keeps personal projects moving: it polls GitHub for issues labelled
`archie`, works each one in an isolated fresh-clone worktree through a routed **workflow**, and opens a
pull request for human review. Sam reviews and merges; the machine grinds in between.
Guiding principle: **environmental constraints over prompt instructions.** Agents don't get asked nicely
to write good code -- the quality gate (vet/build/test/lint, configurable per repo and per workflow stage)
to write good code -- the quality gate (vet/build/test/lint, configurable per repo and per workflow stage)
refuses to let a run succeed until it passes. The gate mechanics live in `ai-sdk/agentloop`; this repo
owns orchestration only.
## Workflows, not a pipeline
`internal/workflow` is the engine: a Workflow is an ordered list of stages over a shared TaskContext;
stages are deterministic steps (worktree, gate, diff cap, PR, comments -- the shared step library in
stages are deterministic steps (worktree, gate, diff cap, PR, comments -- the shared step library in
`steps.go`) or agent stages (`agentloop.Run` with a stage-specific mission/toolset/gate). Routing is
label-driven (`bug` → tdd, `feature` → feasibility, default → implement), refinable by an LLM triage
stage. Adding a workflow must never require touching the engine or reimplementing steps.
Planned workflows:
- **bootstrap** (registered): deterministic marker-file PR proving invites/clone/push/PR plumbing.
- **implement**: planner (read-only agentloop, plan posted to the issue) → builder (full toolset,
repo gate) → diff cap → PR.
@@ -31,7 +32,7 @@ Planned workflows:
`queued → running(workflow:stage) → waiting_human | pr_open → merged | parked | rejected | closed_wont_do`
SQLite (`internal/store`), WAL, one row per issue with a transitions audit table. Crash recovery:
`running` tasks re-queue on startup with attempt++. Parks are never silent -- every park comments on the
`running` tasks re-queue on startup with attempt++. Parks are never silent -- every park comments on the
issue with the reason and gate output.
## Security posture
+21 -21
View File
@@ -2,7 +2,7 @@
**Author:** Archie
**Date:** 2026-07-21 (implementation status updated 2026-07-22)
**Status:** Final (substantially implemented -- remaining aspirational items are pluggable storage backends and Layer 2 daemon plugin loader)
**Status:** Final (substantially implemented -- remaining aspirational items are pluggable storage backends and Layer 2 daemon plugin loader)
---
@@ -10,22 +10,22 @@
This document describes a target end state. The table below is the ground truth; read it before treating any section as already built.
| Area | Status | What actually exists today (post-e4d11b1) |
|---|---|---|
| Daemon/agent binary split | **Implemented** | `cmd/archied` and `cmd/archie-agent` both exist. `archie-agent` is a 189-line NATS-connected per-task worker that subscribes to task subjects, runs the full multi-stage workflow, and reports results. Workflow routing and sequencing (`workflow.Route`, `workflow.Run`) now run inside the agent, not the daemon. Three agent modes: `inprocess`, `subprocess`, `nats`. |
| Sandbox / "daemon never runs untrusted code" | **Partial** | Default mode is still `inprocess` for development. Docker sandbox mode (`agent.mode = "nats"` + `containers.enabled = true`) runs each task in an ephemeral Docker container with workspace bind-mounted at `/workspace`. `internal/container/pool.go` manages full lifecycle: pull, create, start, release, orphan recovery. Daemon dispatch and container lifecycle both enforce `max_concurrency`; same-repo tasks remain serialized. |
| NATS / JetStream messaging | **Implemented** | `internal/nats/client.go`: JetStream connect, stream creation (WorkQueue retention, file storage), pull consumer (durable, ack-wait 5min, max-deliver 3, dedup by Msg-Id), `PublishTask`, `Fetch`, `NewReplyInbox`, and optional token authentication. Subject hierarchy lives in `internal/nats/subjects.go`; `internal/agentexec/nats.go` implements request/reply agent execution. |
| Docker container sandbox | **Implemented** | `internal/container/pool.go` (210 lines): Docker API client, image pull (always/missing/never), container create with workspace bind mount, start, release (stop+remove), orphan recovery on daemon restart. `Dockerfile` at repo root builds archie-agent fat image. `[containers]` config block: enabled, image, max_concurrency, max_uptime, pull_policy. `agent.mode = "nats"` required when containers enabled. |
| `/data/` volume, `task.json` | **Partial** | `container.WriteTaskJSON()` writes task payload to the worktree before container acquire. The container pool bind-mounts the isolated task worktree at `/data/worktree`; configured repos also receive a persistent `/data/repo` Docker volume. Task payload travels over NATS as the primary channel; `/data/task.json` is a boot-time brief for the container. |
| `[containers]` config block | **Implemented** | `ContainerConfig` struct in config.go: enabled, image, max_concurrency, max_uptime, pull_policy. Validated on load. |
| Yaegi extensibility (gates, custom stages, skill scripts) | **Implemented** | Three surfaces: `.archie/gate.go`, `.archie/stages/*.go`, skill scripts via `run_go_script` tool. All in-process via Yaegi with generated symbol tables and panic recovery. Full detail in `docs/prds/yaegi-plugin-system.md`. |
| Layer 1: skill-bundled plugins | **Implemented** | `skill.DiscoverPlugins()` scans `.agents/skills/<name>/plugins/*.go`. `skill.Plugin.Run()` executes them via Yaegi. `skillbuild.BuildWorkflow()` constructs `workflow.Workflow` from plugin-defined stages. `TaskContext.SkillPlugins` makes them available during stage execution. `skillbuild.BuildRegistry()` replaces the hardcoded `workflow.Registry` with catalog-driven construction -- skills define workflows, plugins define stages. |
| Layer 2: core daemon plugins | **Partial** | `internal/plugin/plugin.go`: `Plugin` interface (`Name()`, `Version()`), `Registry` type, `LoadDir()` using Yaegi to interpret `.go` files. No `~/.config/archie/plugins/` loader wired into `cmd/archied/main.go` yet -- the interface and registry exist but are not connected to the daemon's startup. |
| Skills (agentskills.io spec) | **Implemented** | `internal/skill/skill.go`: parses SKILL.md YAML frontmatter, discovers skills from `.agents/skills/*/SKILL.md`, extracts body. Skills follow `archie-wf-*` naming convention. Progressive disclosure: `Catalog()` (Tier 1 -- frontmatter-only scan, ~100 tokens per entry), `LoadBody()` (Tier 2 -- full body on activation), `Discover()` (Tier 3 -- full parse with plugins). `metadata.archie.workflow` declares skill→workflow affinity. `skill.SkillForWorkflow()` is catalog-driven, no hardcoded maps. `skillbuild.BuildRegistry()` constructs the daemon's workflow registry from the catalog. |
| Worktree/repo management | **Implemented** | Each issue keeps an isolated worktree. Repos with `persistent_storage = true` use a per-repo bare Git object cache to avoid repeated full network clones; caches and Archie-owned repo volumes expire via `containers.volume_ttl`. |
| Config schema | **Closer to sec.4** | `[agent]` block: mode (inprocess/subprocess/nats) + command + env. `[nats]` block: url + token_env. `[containers]` block: enabled, image, max_concurrency, max_uptime, volume_ttl, pull_policy. Per-repo `persistent_storage` is supported as a boolean Docker-volume/Git-cache opt-in. |
| Area | Status | What actually exists today (post-e4d11b1) |
| --------------------------------------------------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Daemon/agent binary split | **Implemented** | `cmd/archied` and `cmd/archie-agent` both exist. `archie-agent` is a 189-line NATS-connected per-task worker that subscribes to task subjects, runs the full multi-stage workflow, and reports results. Workflow routing and sequencing (`workflow.Route`, `workflow.Run`) now run inside the agent, not the daemon. Three agent modes: `inprocess`, `subprocess`, `nats`. |
| Sandbox / "daemon never runs untrusted code" | **Partial** | Default mode is still `inprocess` for development. Docker sandbox mode (`agent.mode = "nats"` + `containers.enabled = true`) runs each task in an ephemeral Docker container with workspace bind-mounted at `/workspace`. `internal/container/pool.go` manages full lifecycle: pull, create, start, release, orphan recovery. Daemon dispatch and container lifecycle both enforce `max_concurrency`; same-repo tasks remain serialised. |
| NATS / JetStream messaging | **Implemented** | `internal/nats/client.go`: JetStream connect, stream creation (WorkQueue retention, file storage), pull consumer (durable, ack-wait 5min, max-deliver 3, dedup by Msg-Id), `PublishTask`, `Fetch`, `NewReplyInbox`, and optional token authentication. Subject hierarchy lives in `internal/nats/subjects.go`; `internal/agentexec/nats.go` implements request/reply agent execution. |
| Docker container sandbox | **Implemented** | `internal/container/pool.go` (210 lines): Docker API client, image pull (always/missing/never), container create with workspace bind mount, start, release (stop+remove), orphan recovery on daemon restart. `Dockerfile` at repo root builds archie-agent fat image. `[containers]` config block: enabled, image, max_concurrency, max_uptime, pull_policy. `agent.mode = "nats"` required when containers enabled. |
| `/data/` volume, `task.json` | **Partial** | `container.WriteTaskJSON()` writes task payload to the worktree before container acquire. The container pool bind-mounts the isolated task worktree at `/data/worktree`; configured repos also receive a persistent `/data/repo` Docker volume. Task payload travels over NATS as the primary channel; `/data/task.json` is a boot-time brief for the container. |
| `[containers]` config block | **Implemented** | `ContainerConfig` struct in config.go: enabled, image, max_concurrency, max_uptime, pull_policy. Validated on load. |
| Yaegi extensibility (gates, custom stages, skill scripts) | **Implemented** | Three surfaces: `.archie/gate.go`, `.archie/stages/*.go`, skill scripts via `run_go_script` tool. All in-process via Yaegi with generated symbol tables and panic recovery. Full detail in `docs/prds/yaegi-plugin-system.md`. |
| Layer 1: skill-bundled plugins | **Implemented** | `skill.DiscoverPlugins()` scans `.agents/skills/<name>/plugins/*.go`. `skill.Plugin.Run()` executes them via Yaegi. `skillbuild.BuildWorkflow()` constructs `workflow.Workflow` from plugin-defined stages. `TaskContext.SkillPlugins` makes them available during stage execution. `skillbuild.BuildRegistry()` replaces the hardcoded `workflow.Registry` with catalogue-driven construction -- skills define workflows, plugins define stages. |
| Layer 2: core daemon plugins | **Partial** | `internal/plugin/plugin.go`: `Plugin` interface (`Name()`, `Version()`), `Registry` type, `LoadDir()` using Yaegi to interpret `.go` files. No `~/.config/archie/plugins/` loader wired into `cmd/archied/main.go` yet -- the interface and registry exist but are not connected to the daemon's startup. |
| Skills (agentskills.io spec) | **Implemented** | `internal/skill/skill.go`: parses SKILL.md YAML frontmatter, discovers skills from `.agents/skills/*/SKILL.md`, extracts body. Skills follow `archie-wf-*` naming convention. Progressive disclosure: `Catalog()` (Tier 1 -- frontmatter-only scan, ~100 tokens per entry), `LoadBody()` (Tier 2 -- full body on activation), `Discover()` (Tier 3 -- full parse with plugins). `metadata.archie.workflow` declares skill→workflow affinity. `skill.SkillForWorkflow()` is catalogue-driven, no hardcoded maps. `skillbuild.BuildRegistry()` constructs the daemon's workflow registry from the catalogue. |
| Worktree/repo management | **Implemented** | Each issue keeps an isolated worktree. Repos with `persistent_storage = true` use a per-repo bare Git object cache to avoid repeated full network clones; caches and Archie-owned repo volumes expire via `containers.volume_ttl`. |
| Config schema | **Closer to sec.4** | `[agent]` block: mode (inprocess/subprocess/nats) + command + env. `[nats]` block: url + token_env. `[containers]` block: enabled, image, max_concurrency, max_uptime, volume_ttl, pull_policy. Per-repo `persistent_storage` is supported as a boolean Docker-volume/Git-cache opt-in. |
**Net read post-1dca419:** Phases 1, 2, and 3 are substantially implemented. NATS, Docker sandbox, skill parsing, skill-bundled plugins (Layer 1), skill progressive disclosure, and catalog-driven workflow construction (`skillbuild.BuildRegistry()`) all landed. The remaining aspirational work is Layer 2 daemon plugin loader (interface exists, not wired), pluggable storage backends, and per-worktree dynamic registry augmentation.
**Net read post-1dca419:** Phases 1, 2, and 3 are substantially implemented. NATS, Docker sandbox, skill parsing, skill-bundled plugins (Layer 1), skill progressive disclosure, and catalogue-driven workflow construction (`skillbuild.BuildRegistry()`) all landed. The remaining aspirational work is Layer 2 daemon plugin loader (interface exists, not wired), pluggable storage backends, and per-worktree dynamic registry augmentation.
---
@@ -313,7 +313,7 @@ metadata:
Per the agentskills.io spec:
1. **Catalog** (~100 tokens): `name` + `description` loaded at workflow start
1. **Catalogue** (~100 tokens): `name` + `description` loaded at workflow start
2. **Instructions** (<5000 tokens): Full `SKILL.md` body when the skill is activated
3. **Resources** (as needed): References, scripts, and bundled plugins loaded on demand
@@ -453,7 +453,7 @@ The agent writes whatever it wants to `response`. The daemon reviews it. No agen
- ~~Persistent volumes with TTL~~ -- **done**: configured repos receive a persistent Docker volume plus a per-repo Git
object cache; both are automatically reaped using `containers.volume_ttl`.
- ~~`max_concurrency` enforcement~~ -- **done**: SQLite and NATS drains dispatch different repositories concurrently
up to `[containers].max_concurrency`; same-repo tasks remain serialized by default.
up to `[containers].max_concurrency`; same-repo tasks remain serialised by default.
- Grace period `max_uptime` -- not started
- **Groundwork already in place:** `agentexec.Runner` (`InProcessRunner`/`SubprocessRunner`) is an interface designed,
per its own doc comments, to be swapped for a container-backed runner without touching workflow orchestration --
@@ -504,9 +504,9 @@ The agent writes whatever it wants to `response`. The daemon reviews it. No agen
lifetime with `max_total_uptime` (e.g. 4 hours) to prevent infinite hanging. `max_uptime` = grace after inactivity,
`max_total_uptime` = absolute kill switch.
5. **Concurrent agents on the same repo:** ~~Resolved.~~ Serialized by default (dispatcher chains tasks per
5. **Concurrent agents on the same repo:** ~~Resolved.~~ Serialised by default (dispatcher chains tasks per
`owner/repo`). `[[repos]]` now supports `allow_concurrent = true` (`config.Repo.AllowConcurrent`) to opt a repo out
of that serialization; the global `[containers].max_concurrency` slot limit still applies. Worktrees are already
of that serialisation; the global `[containers].max_concurrency` slot limit still applies. Worktrees are already
keyed per issue number (`worktree.Manager.Dir`), so opted-in repos don't collide on disk.
6. **Plugin architecture reconciliation:** Extend the existing Yaegi surfaces (`internal/gate/gateeval`,
@@ -515,5 +515,5 @@ The agent writes whatever it wants to `response`. The daemon reviews it. No agen
3/4.
7. **Skill loading scope:** "Parse frontmatter, inject body into system prompt" is sufficient for v2. The gap is that
nothing reads SKILL.md today -- closing that gap is the value. Full progressive disclosure (catalog -> activate ->
nothing reads SKILL.md today -- closing that gap is the value. Full progressive disclosure (catalogue -> activate ->
resources) is deferred to a later phase.
+46 -37
View File
@@ -1,4 +1,4 @@
# archie-core Skills System -- PRD
# archie-core Skills System -- PRD
**Author:** Archie
**Date:** 2026-07-18
@@ -41,15 +41,15 @@ project:
# How archie-core connects to this project
connection:
interfaces:
- github # respond to assigned issues
- linear # respond to labelled tickets
- webhook # respond to HTTP POSTs
- github # respond to assigned issues
- linear # respond to labelled tickets
- webhook # respond to HTTP POSTs
github:
repo: sam/my-go-service
issue_labels:
ready: "archie:ready" # issues with this label get claimed
claimed: "archie:claimed" # archie sets this when working
done: "archie:done" # archie sets this after PR
ready: "archie:ready" # issues with this label get claimed
claimed: "archie:claimed" # archie sets this when working
done: "archie:done" # archie sets this after PR
pr:
base: main
draft: false
@@ -57,10 +57,10 @@ connection:
# Skills -- playbooks archie-core loads to know how to work
skills:
paths:
- .archie/skills/ # project-local skills
- ~/.archie/skills/ # per-user skills
- .archie/skills/ # project-local skills
- ~/.archie/skills/ # per-user skills
remotes:
- github.com/sam/archie-skills@v1 # shared skill library
- github.com/sam/archie-skills@v1 # shared skill library
# Sandbox -- what's available in the container
sandbox:
@@ -155,9 +155,11 @@ metadata:
# Go Quality Gate
## When to use
Before committing any Go change. After implementing a feature or fix.
## Procedure
Run in this exact order. If any step fails, fix the issue before continuing.
1. `gofumpt -w .`
@@ -167,28 +169,30 @@ Run in this exact order. If any step fails, fix the issue before continuing.
5. `task deadcode`
## Verification
All five steps must exit 0. If `task deadcode` fails on unrelated packages,
scope it to only changed packages: `golangci-lint run --tests=false --enable-only=unused,staticcheck ./changed/pkg/...`
## Common failures
- `golangci-lint`: unused function -- remove it or add `//nolint:unused` comment
- `go test -race`: data race -- protect with mutex or channel
- `task deadcode`: pre-existing dead code in unrelated package -- scope to changed packages
- `golangci-lint`: unused function -- remove it or add `//nolint:unused` comment
- `go test -race`: data race -- protect with mutex or channel
- `task deadcode`: pre-existing dead code in unrelated package -- scope to changed packages
```
### 2.3 Skill metadata (arcie-specific)
Skills carry archie-specific metadata under `metadata.archie`:
| Field | Purpose |
|---|---|
| `gates` | Which gates from `archie.yaml` this skill covers |
| `tools` | Sandbox tools this skill needs |
| `engine` | Preferred execution engine |
| `model` | Preferred model for this skill |
| `budget_usd` | Max spend ceiling |
| `timeout` | Max seconds |
| `worktree` | Whether to create isolated worktree |
| Field | Purpose |
| ------------ | ------------------------------------------------ |
| `gates` | Which gates from `archie.yaml` this skill covers |
| `tools` | Sandbox tools this skill needs |
| `engine` | Preferred execution engine |
| `model` | Preferred model for this skill |
| `budget_usd` | Max spend ceiling |
| `timeout` | Max seconds |
| `worktree` | Whether to create isolated worktree |
### 2.4 Progressive disclosure
@@ -245,6 +249,7 @@ This is the core loop. When an issue lands with the configured label:
### 3.6 On failure
If any gate fails irrecoverably:
1. Leave issue as `archie:claimed`
2. Comment with exact blocker, failed command, and worktree path
3. Preserve worktree for inspection
@@ -258,12 +263,12 @@ arcie-core can delegate implementation to different LLM engines. The workflow fi
```yaml
engines:
- type: claude # Claude Code CLI -- full agent loop
- type: claude # Claude Code CLI -- full agent loop
model: sonnet
budget_usd: 5.00
- type: codex # OpenAI Codex CLI
- type: codex # OpenAI Codex CLI
model: gpt-5.1-codex-max
- type: raw # Direct LLM -- no agent loop, single prompt
- type: raw # Direct LLM -- no agent loop, single prompt
model: gpt-4o-mini
```
@@ -281,7 +286,7 @@ For skills that need a specific engine, the skill metadata overrides:
```yaml
metadata:
archie:
engine: claude # this skill only works with Claude
engine: claude # this skill only works with Claude
```
---
@@ -312,7 +317,6 @@ metadata:
tools: [docker, trivy]
engine: any
---
## Procedure
1. `trivy image --severity HIGH,CRITICAL <image>`
2. If findings exist, report each CVE with package, version, and fixed version
@@ -323,34 +327,37 @@ metadata:
## 6. Comparison: archie-core vs existing systems
| | archie-core | Claude Code | Codex CLI | GitHub Actions | External Agent |
|---|---|---|---|---|---|
| **How it receives work** | GitHub issue assignment, Linear label, webhook | Chat, slash commands | Chat, slash commands | YAML triggers (push, PR, schedule) | Chat, cron, webhooks |
| **What it does** | Analyse → implement → gate → PR | Analyse → implement → gate → PR | Analyse → implement → gate → PR | Run arbitrary shell commands | Analyse → implement → gate → PR |
| **Skills** | SKILL.md (agentskills.io) | SKILL.md (native) | SKILL.md (agentskills.io) | Composite actions | SKILL.md (native) |
| **Gates** | Named checkpoints in archie.yaml | Ad-hoc (CLAUDE.md + lint) | Ad-hoc | Steps in jobs | Skills with gates |
| **Engine pluggable** | Yes | No (fixed to Claude) | No (fixed to Codex) | No (fixed to GitHub) | Yes (provider config) |
| **Worktree isolation** | Yes | Yes (`--worktree`) | No | No (ephemeral runner) | No |
| **Blueprint/cron** | Export externally | No | No | Schedule trigger | Native |
| **Where it runs** | Docker sandbox | Host | Host or sandbox | GitHub runner | Host, Docker, Modal, SSH |
| | archie-core | Claude Code | Codex CLI | GitHub Actions | External Agent |
| ------------------------ | ---------------------------------------------- | ------------------------------- | ------------------------------- | ---------------------------------- | ------------------------------- |
| **How it receives work** | GitHub issue assignment, Linear label, webhook | Chat, slash commands | Chat, slash commands | YAML triggers (push, PR, schedule) | Chat, cron, webhooks |
| **What it does** | Analyse → implement → gate → PR | Analyse → implement → gate → PR | Analyse → implement → gate → PR | Run arbitrary shell commands | Analyse → implement → gate → PR |
| **Skills** | SKILL.md (agentskills.io) | SKILL.md (native) | SKILL.md (agentskills.io) | Composite actions | SKILL.md (native) |
| **Gates** | Named checkpoints in archie.yaml | Ad-hoc (CLAUDE.md + lint) | Ad-hoc | Steps in jobs | Skills with gates |
| **Engine pluggable** | Yes | No (fixed to Claude) | No (fixed to Codex) | No (fixed to GitHub) | Yes (provider config) |
| **Worktree isolation** | Yes | Yes (`--worktree`) | No | No (ephemeral runner) | No |
| **Blueprint/cron** | Export externally | No | No | Schedule trigger | Native |
| **Where it runs** | Docker sandbox | Host | Host or sandbox | GitHub runner | Host, Docker, Modal, SSH |
---
## 7. Implementation phases
### Phase 1: Workflow file and gates (current MVP)
- `archie.yaml` parser
- Gate runner executing shell commands and checking exit codes
- Skill discovery from project and user paths
- GitHub interface: claim issues, create worktrees, open PRs
### Phase 2: Skills
- SKILL.md progressive disclosure (advertise → activate → resources)
- archie-specific metadata parsing
- Skill chaining: skills that depend on other skills
- `archie skills list/install` CLI
### Phase 3: Engine abstraction
- Engine interface definition
- Claude Code adapter
- Raw LLM adapter
@@ -358,12 +365,14 @@ metadata:
- Per-skill engine preferences
### Phase 4: Advanced features
- Gate overrides per skill
- Skill templates for project scaffolding (`archie init --skill go-service`)
- Remote skill libraries (git repos as skill sources)
- Blueprint export to an external scheduler
### Phase 5: Additional interfaces
- Linear webhook integration
- Generic webhook interface for arbitrary sources
- CLI command interface (`archie run <command>`)
+54 -49
View File
@@ -1,4 +1,4 @@
# archie-core Workflows & Skills -- Product Requirements Document
# archie-core Workflows & Skills -- Product Requirements Document
**Author:** Archie
**Date:** 2026-07-18
@@ -40,20 +40,20 @@ project:
# Available skills (directories or individual files)
skills:
paths:
- .archie/skills/ # project-local skills
- ~/.archie/skills/ # per-user skills
- github.com/org/shared-skills@v1 # remote skill repo
- .archie/skills/ # project-local skills
- ~/.archie/skills/ # per-user skills
- github.com/org/shared-skills@v1 # remote skill repo
skills:
- go-testing # named skill from any path
- go-testing # named skill from any path
- security-audit
# Execution engines in preference order
engines:
- type: claude # Claude Code CLI
- type: claude # Claude Code CLI
model: sonnet
- type: codex # OpenAI Codex
- type: pi # Pi agent harness
- type: raw # Direct LLM without agent wrapper
- type: codex # OpenAI Codex
- type: pi # Pi agent harness
- type: raw # Direct LLM without agent wrapper
# Sandbox definition (what the Docker container provides)
sandbox:
@@ -90,7 +90,7 @@ gates:
description: "No vet warnings"
deadcode:
run: task deadcode
optional: true # non-blocking gate
optional: true # non-blocking gate
description: "Dead code check (advisory)"
# Quality pipeline -- ordered sequence of gate groups
@@ -105,7 +105,7 @@ quality:
# Commit conventions
commit:
format: conventional # conventional commits
format: conventional # conventional commits
signoff: false
template: "feat({scope}): {description}"
@@ -142,15 +142,15 @@ commands:
### 1.3 Design decisions (with rationale)
| Decision | Rationale |
|---|---|
| YAML over TOML/JSON | Already dominant in CI (GitHub Actions, GitLab CI, Taskfile). Human-readable with comments. |
| Single file over multi-file | Task discovery (like `Taskfile.yml`), devcontainer conventions. Avoids directory sprawl. |
| Gates as named checkpoints | GitHub Actions job model. Gates can be composed into quality pipelines, selected individually, or skipped with `--skip`. |
| Engines as ordered preference list | Supports deterministic fallback between available engines. Each engine declares its own tool surface. |
| Skills as paths + references | Matches devcontainer features (paths resolve to directories) and skills.sh (namespaced references). |
| Commands section for direct invocation | Arnie can `archie run test` without an agent turn. Thin wrapper over the sandbox. |
| Quality pipeline groups gates | Pre-commit vs pre-push vs pre-merge distinction. Some gates are required, some advisory. |
| Decision | Rationale |
| -------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| YAML over TOML/JSON | Already dominant in CI (GitHub Actions, GitLab CI, Taskfile). Human-readable with comments. |
| Single file over multi-file | Task discovery (like `Taskfile.yml`), devcontainer conventions. Avoids directory sprawl. |
| Gates as named checkpoints | GitHub Actions job model. Gates can be composed into quality pipelines, selected individually, or skipped with `--skip`. |
| Engines as ordered preference list | Supports deterministic fallback between available engines. Each engine declares its own tool surface. |
| Skills as paths + references | Matches devcontainer features (paths resolve to directories) and skills.sh (namespaced references). |
| Commands section for direct invocation | Arnie can `archie run test` without an agent turn. Thin wrapper over the sandbox. |
| Quality pipeline groups gates | Pre-commit vs pre-push vs pre-merge distinction. Some gates are required, some advisory. |
---
@@ -179,9 +179,9 @@ description: >
version: 1.0.0
metadata:
archie:
gates: [test] # gates this skill requires
tools: [go, golangci-lint] # sandbox tools it needs
engine: any # engine preference
gates: [test] # gates this skill requires
tools: [go, golangci-lint] # sandbox tools it needs
engine: any # engine preference
compatibility: Requires Go 1.22+
---
```
@@ -201,13 +201,13 @@ Skills can carry archie-specific frontmatter under `metadata.archie`:
```yaml
metadata:
archie:
gates: [test, lint] # must-pass gates before skill runs
tools: [go, docker] # sandbox tools required
engine: any # preferred engine
model: gpt-4o # preferred model
budget_usd: 2.00 # max spend ceiling
timeout: 600 # max seconds
worktree: true # create isolated worktree
gates: [test, lint] # must-pass gates before skill runs
tools: [go, docker] # sandbox tools required
engine: any # preferred engine
model: gpt-4o # preferred model
budget_usd: 2.00 # max spend ceiling
timeout: 600 # max seconds
worktree: true # create isolated worktree
```
### 2.4 Skill sources (inspired by devcontainer features + Dagger modules)
@@ -241,12 +241,12 @@ Engine interface:
### 3.2 Supported engines
| Engine | Type | What it provides |
|---|---|---|
| `claude` | Claude Code CLI | Full agent loop, tool use, worktrees, subagents |
| `codex` | OpenAI Codex CLI | Agentic coding with sandbox |
| `pi` | Pi agent harness | Minimalist coding agent, stdio protocol |
| `raw` | Direct LLM call | Single-turn prompt, no agent loop. For simple scripts. |
| Engine | Type | What it provides |
| -------- | ---------------- | ------------------------------------------------------ |
| `claude` | Claude Code CLI | Full agent loop, tool use, worktrees, subagents |
| `codex` | OpenAI Codex CLI | Agentic coding with sandbox |
| `pi` | Pi agent harness | Minimalist coding agent, stdio protocol |
| `raw` | Direct LLM call | Single-turn prompt, no agent loop. For simple scripts. |
### 3.3 Engine selection logic
@@ -302,15 +302,15 @@ metadata:
archie:
gates:
test:
run: go test -short ./... # override: faster test for this skill
lint: skip # skip lint for this skill
run: go test -short ./... # override: faster test for this skill
lint: skip # skip lint for this skill
```
Three override modes: `override` (replace command), `skip` (omit gate), `add` (add new gate requirement).
### 4.4 Skill templates (scaffolding)
Skills can carry an `assets/` directory with templates. When archie-core initializes a new project, it can apply skill templates:
Skills can carry an `assets/` directory with templates. When archie-core initialises a new project, it can apply skill templates:
```
skill-name/
@@ -342,45 +342,50 @@ The export produces a `SKILL.md` with scheduler metadata. The blueprint's prompt
## 5. Comparison to Existing Systems
| Feature | archie-core | GitHub Actions | Dagger | Taskfile | devcontainer | External Skills |
|---|---|---|---|---|---|---|
| Language | YAML | YAML | Go/Python/TS | YAML | JSON | Markdown |
| Gates | Named + composable | Steps in jobs | Functions | Tasks | Lifecycle scripts | N/A |
| Engine abstraction | First-class | GitHub only | Dagger Engine | Shell only | None | Provider |
| Skills | agentskills.io spec | Composite actions | Dagger Modules | Includes | Features | SKILL.md |
| Worktree isolation | Built-in | No | Containers | No | Container | No |
| Blueprint export | To external cron | No | No | No | No | Native |
| Multi-engine fallback | Yes (ordered list) | No | No | No | No | Provider config |
| Progressive disclosure | Yes (skill spec) | No | No | No | Feature metadata | Yes |
| Feature | archie-core | GitHub Actions | Dagger | Taskfile | devcontainer | External Skills |
| ---------------------- | ------------------- | ----------------- | -------------- | ---------- | ----------------- | --------------- |
| Language | YAML | YAML | Go/Python/TS | YAML | JSON | Markdown |
| Gates | Named + composable | Steps in jobs | Functions | Tasks | Lifecycle scripts | N/A |
| Engine abstraction | First-class | GitHub only | Dagger Engine | Shell only | None | Provider |
| Skills | agentskills.io spec | Composite actions | Dagger Modules | Includes | Features | SKILL.md |
| Worktree isolation | Built-in | No | Containers | No | Container | No |
| Blueprint export | To external cron | No | No | No | No | Native |
| Multi-engine fallback | Yes (ordered list) | No | No | No | No | Provider config |
| Progressive disclosure | Yes (skill spec) | No | No | No | Feature metadata | Yes |
---
## 6. Implementation Phases
### Phase 1: Core workflow file
- `archie.yaml` parser and schema validation
- Gate runner (test, lint, format, vet)
- `archie run <command>` CLI
- Sandbox Docker integration
### Phase 2: Skills
- SKILL.md discovery and progressive disclosure
- Skill metadata with gate/tool/engine requirements
- `archie skills list/install/search`
### Phase 3: Engine abstraction
- Engine interface definition
- Claude Code adapter
- Raw LLM adapter
- Engine fallback chain
### Phase 4: Advanced features
- Worktree isolation
- Skill chaining (dependency DAG)
- Gate overrides
- Blueprint export
### Phase 5: Ecosystem
- Public skill registry
- `archie init --skill <name>` scaffolding
- Community skill contributions
File diff suppressed because it is too large. Load diff
+23 -22
View File
@@ -7,7 +7,7 @@ changing anything that contradicts a prior decision.
---
## 2026-08-24 -- Turn continuation is never output-volume or token gated
## 2026-08-24 -- Turn continuation is never output-volume or token gated
**Decision**: A turn is never stopped because an aggregate token count or
aggregate tool-result character count was reached. `max_tokens` and
@@ -24,14 +24,14 @@ used to terminate the multi-step turn.
**Context**: GitHub #604 showed full file and module listings followed by four
identical read failures and a shell failure at the old 200,000-character cap.
The renderer now summarizes those legacy events for replay, while current
The renderer now summarises those legacy events for replay, while current
dispatch never creates them. Find and grep are confined to the active
workspace/worktree; the Go module cache remains readable only by explicit
path, not by discovery.
---
## 2026-07-23 -- Forge-agnostic issue creation via CreateIssue
## 2026-07-23 -- Forge-agnostic issue creation via CreateIssue
**Decision**: Add `CreateIssue(ctx, owner, repo, title, body, labels)
(int, error)` to the `forge.Forge` interface. Every forge backend
@@ -45,11 +45,11 @@ calls one method regardless of the underlying ticketing system.
**Future**: A `beads` forge backend will implement `CreateIssue` by
calling `bd create`. This makes beads the internal/default issue tracker
while Gitea/GitHub are external forges. The agent doesn't know which
it's talking to -- the daemon resolves the forge from repo config.
it's talking to -- the daemon resolves the forge from repo config.
---
## 2026-07-23 -- Dolt and Beads for agent-native issue tracking
## 2026-07-23 -- Dolt and Beads for agent-native issue tracking
**Decision**: Install dolt (version-controlled SQL) and beads (`bd`,
a graph-based issue tracker for AI agents) as the foundation for
@@ -59,19 +59,19 @@ multi-repo scaling and multi-agent coordination.
class dependency tracking, JSON output for programmatic use, and hash-
based IDs that prevent merge conflicts in multi-agent workflows. It's
built on Dolt which gives cell-level merge, native branching, and
remote sync -- the same primitives git gives code but applied to issues.
remote sync -- the same primitives git gives code but applied to issues.
**Context**: Gas Town (`~/gt/`) is cloned for reference -- it implements
**Context**: Gas Town (`~/gt/`) is cloned for reference -- it implements
a multi-agent workspace on top of beads. The archie-core scaling
strategy will follow a similar model: a coordinator daemon with per-repo
agents, all sharing a beads-backed task graph.
**Current state**: dolt 2.2.2, beads 1.1.0 installed. Beads initialized
**Current state**: dolt 2.2.2, beads 1.1.0 installed. Beads initialised
in archie-core (`.beads/`). Six issues seeded for the scaling roadmap.
---
## 2026-07-23 -- Token budgets must be generous, not predictive
## 2026-07-23 -- Token budgets must be generous, not predictive
> **Superseded by the 2026-08-24 decision above.** There is no configured
> aggregate token cap; model token usage remains accounting only.
@@ -88,7 +88,7 @@ proportionally more.
**Context**: The planner burned 357K tokens just to discover a fix
already existed. The builder hit 1M at step 25 of 90. Neither task was
unreasonable -- they were just exploring a large codebase.
unreasonable -- they were just exploring a large codebase.
**Future**: Track actual token consumption per workflow/stage/repo. Use
that data to set informed limits. Build compaction or checkpointing so
@@ -96,7 +96,7 @@ a killed agent can resume rather than restart.
---
## 2026-07-23 -- baseline-fix: auto-repair pre-existing gate failures
## 2026-07-23 -- baseline-fix: auto-repair pre-existing gate failures
**Decision**: When `StageBaselineGate` detects a red gate (gofumpt, go
vet, etc. failing on clean main), launch the builder to fix the
@@ -104,7 +104,7 @@ failures via TDD rather than parking. Only park if the builder cannot
fix them.
**Reasoning**: A red baseline means the repo was broken before archie
touched it. Parking creates an infinite loop -- the next retry hits the
touched it. Parking creates an infinite loop -- the next retry hits the
same failure. The agent should fix pre-existing issues, not fail on them.
**Implementation**: `StageBaselineGate` now calls `tc.Agent.Run()` with
@@ -113,7 +113,7 @@ this required wiring `tc.Agent` (the runner) through the stage context.
---
## 2026-07-23 -- No hardcoded MaxSteps in workflow stages
## 2026-07-23 -- No hardcoded MaxSteps in workflow stages
**Decision**: Remove all hardcoded `MaxSteps` values from workflow
stages. Every stage inherits from `[budgets].max_steps` in the config.
@@ -126,14 +126,14 @@ repos. The config should be the single source of truth.
---
## 2026-07-23 -- No-op detection: close issues when build has 0 changes
## 2026-07-23 -- No-op detection: close issues when build has 0 changes
**Decision**: When the builder completes with `StatusPassed` and 0 file
changes, close the issue with a comment rather than parking on "worktree
has no changes to commit".
**Reasoning**: A builder that passes with 0 changes means the fix
already exists or the issue is a no-op. The old behavior parked in an
already exists or the issue is a no-op. The old behaviour parked in an
infinite loop (commit-push fails because nothing changed, task re-queues,
builder runs again, same result).
@@ -147,7 +147,7 @@ sets `Outcome = Merged` to stop the workflow.
---
## 2026-07-23 -- assignee trigger over label trigger
## 2026-07-23 -- assignee trigger over label trigger
**Decision**: Default to `trigger = "assignee"` instead of `trigger =
"label"`. The daemon only claims issues explicitly assigned to the bot
@@ -159,7 +159,7 @@ promiscuous for repos shared between humans and agents.
---
## 2026-07-23 -- DeepSeek v4 Pro as primary model
## 2026-07-23 -- DeepSeek v4 Pro as primary model
**Decision**: Use `deepseek/deepseek-v4-pro` as the planner and builder
model. Qwythos-9B (local llama.cpp) is the fallback for offline/cheap
@@ -174,7 +174,7 @@ env var from Bitwarden Secrets Manager (bws).
---
## 2026-07-22 -- v1.0.0 tagged
## 2026-07-22 -- v1.0.0 tagged
**Decision**: Tagged `v1.0.0` at commit incorporating the daemon/agent
split, NATS JetStream, Docker sandbox, Yaegi plugins, agentskills.io
@@ -182,12 +182,13 @@ skills, and Gitea forge support.
---
## 2026-07-22 -- Docker Compose stack with NATS + containers
## 2026-07-22 -- Docker Compose stack with NATS + containers
**Decision**: The production deployment uses `docker-compose.yml` with
NATS, archied, and archie-agent containers. Config at `config.docker.toml`.
**Key fixes**:
- NATS healthcheck uses `wget localhost:8222/healthz` (not `nats-server check`)
- `host.docker.internal:host-gateway` extra_hosts for Linux
- Config mount path: `config.docker.toml` → `/etc/archie/config.toml`
@@ -195,10 +196,10 @@ NATS, archied, and archie-agent containers. Config at `config.docker.toml`.
---
## 2026-07-22 -- Worktree Prepare before Container Acquire
## 2026-07-22 -- Worktree Prepare before Container Acquire
**Decision**: Clone the worktree (`Trees.Prepare()`) before acquiring
a Docker container. Made `Prepare()` idempotent -- skips if `.git`
a Docker container. Made `Prepare()` idempotent -- skips if `.git`
already exists.
**Reasoning**: Docker bind-mounts fail with "bind source path does not
@@ -208,7 +209,7 @@ didn't exist on the host.
---
## 2026-07-22 -- Gofumpt and Go tools must be on PATH
## 2026-07-22 -- Gofumpt and Go tools must be on PATH
**Decision**: The daemon's `exec.Command` for gate checks inherits the
process PATH. `~/go/bin` (where `gofumpt`, `golangci-lint`, etc. live)
@@ -1,7 +1,7 @@
# Multi-Agent Collaboration -- PRD
**Status:** Draft (discovery interview complete, 2026-07-25)
**Author:** Discovery interview (archie-core-abg.1), synthesized from Sam's answers
**Author:** Discovery interview (archie-core-abg.1), synthesised from Sam's answers
**Parent epic:** archie-core-abg
---
@@ -80,7 +80,7 @@ implementation slice -- see section 5.
## 3. Constraints from existing architecture
From `ARCHITECTURE.md` and `docs/prds/archie-core-v2-architecture.md`
(read in full before implementation; summarized here):
(read in full before implementation; summarised here):
- **`Config.BotUser` is a single global field** (`internal/config`) -- the
root blocker for daemon-side multi-identity. Becomes a per-identity field
@@ -93,7 +93,7 @@ From `ARCHITECTURE.md` and `docs/prds/archie-core-v2-architecture.md`
(e.g. `archie.<identity>.task.<type>`) but that's a design decision, not
yet made.
- **Dispatch is `daemon.Run()` polling per configured forge/repo list**,
serialized per `owner/repo` by default (`AllowConcurrent` opts out).
serialised per `owner/repo` by default (`AllowConcurrent` opts out).
Multi-identity daemon means multiple poll loops (or one loop iterating
multiple identity configs) feeding the same NATS/container dispatch
machinery.
@@ -109,7 +109,7 @@ From `ARCHITECTURE.md` and `docs/prds/archie-core-v2-architecture.md`
- **The daemon gatekeeps all agent output** -- "no agent output reaches a
human without daemon review" (`archie-core-v2-architecture.md` sec.7).
Chat channels must respect this: a chat message that triggers a spawn goes
through the same review/labeling machinery PRs and comments do today, not
through the same review/labelling machinery PRs and comments do today, not
a side channel that bypasses it.
- **Environmental constraints over prompt rules** (`ARCHITECTURE.md` design
decision #1) -- chat-triggered actions (spawn, approve, cancel) should be
@@ -119,7 +119,7 @@ From `ARCHITECTURE.md` and `docs/prds/archie-core-v2-architecture.md`
## 4. Identity model (design direction, not yet finalized)
Confirmed requirement: within one daemon, identities differ by bot identity,
repo list, *and* model/provider config (per the archie/winter diff). Proposed
repo list, _and_ model/provider config (per the archie/winter diff). Proposed
shape -- **not yet approved, needs a follow-up design pass before
implementation**:
@@ -139,6 +139,7 @@ forge = { type = "gitea", host = "...", token_env = "..." }
models = { triage = "...", planner = "...", builder = "..." }
repos = [ ... ]
```
```
**Design answer (2026-07-25): per-identity goroutine, shared infrastructure.**
@@ -231,3 +232,4 @@ on.
identity).
- [ ] Broken into scoped, dependency-ordered beads issues under
`archie-core-abg`, the way the 5zh epic was. (Next step, this session.)
```
+127 -121
View File
@@ -1,4 +1,4 @@
# archie-core TypeScript Plugin Engine -- PRD
# archie-core TypeScript Plugin Engine -- PRD
**Author:** Archie
**Date:** 2026-07-21
@@ -8,7 +8,7 @@
## Summary
A TypeScript-based plugin engine that lets repositories ship interpreted, dynamically-loaded workflow extensions. Plugins are `.ts` files placed in `.archie/workflows/`. archie-core discovers them on its next poll cycle, transpiles them to JavaScript via esbuild, and executes them in an embedded [goja](https://github.com/dop251/goja) runtime -- a pure-Go ECMAScript interpreter with zero CGO dependencies.
A TypeScript-based plugin engine that lets repositories ship interpreted, dynamically-loaded workflow extensions. Plugins are `.ts` files placed in `.archie/workflows/`. archie-core discovers them on its next poll cycle, transpiles them to JavaScript via esbuild, and executes them in an embedded [goja](https://github.com/dop251/goja) runtime -- a pure-Go ECMAScript interpreter with zero CGO dependencies.
---
@@ -19,22 +19,24 @@ A TypeScript-based plugin engine that lets repositories ship interpreted, dynami
TypeScript is the most widely understood language among developers writing automation, CI, and workflow scripts. It already ships in most projects. Gate authors already know it. The ecosystem for linting, formatting, and type-checking is mature and free.
Having a TypeScript-native plugin engine means:
- Plugin authors get familiar syntax, type safety, and IDE support
- No separate toolchain -- just `.ts` files in a folder
- No separate toolchain -- just `.ts` files in a folder
- Skills, gates, and workflow stages share the same language
### Why goja
| Competitor | Problem |
|---|---|
| V8 CGO bindings | Requires CGO, ~50MB static libraries, platform-specific builds |
| QuickJS CGO | Requires CGO, smaller than V8 but still a C dependency |
| QJS (Wazero) | Pure Go WASM, but sandboxed -- can't expose Go functions efficiently |
| Ramune | Heavy dependency, bundles an entire TypeScript 7 compiler |
| Node.js subprocess | Process overhead per execution, IPC serialization cost |
| Competitor | Problem |
| ------------------ | -------------------------------------------------------------------- |
| V8 CGO bindings | Requires CGO, ~50MB static libraries, platform-specific builds |
| QuickJS CGO | Requires CGO, smaller than V8 but still a C dependency |
| QJS (Wazero) | Pure Go WASM, but sandboxed -- can't expose Go functions efficiently |
| Ramune | Heavy dependency, bundles an entire TypeScript 7 compiler |
| Node.js subprocess | Process overhead per execution, IPC serialisation cost |
goja is a pure-Go ECMAScript 5.1+ interpreter at ~20k lines. It:
- Has **zero CGO** -- cross-compiles everywhere Go does
- Has **zero CGO** -- cross-compiles everywhere Go does
- Passes nearly all TC39 Test262 tests for ES5.1 + significant ES6 coverage
- Can run Babel and the TypeScript compiler itself (proven capability)
- Provides direct Go↔JS interop via `Set()`/`Get()`/`Runtime.RunString()`
@@ -61,7 +63,7 @@ During the poll cycle, archie-core scans each repo's worktree for `.archie/workf
```
.archie/workflows/
├── custom-gate.ts # gate functions: exported `check()`
├── custom-gate.ts # gate functions: exported `check()`
├── db-migration.ts # custom stage: exported `stage()`
└── notify-slack.ts # skill script: exported `run()`
```
@@ -72,11 +74,11 @@ Each file is a self-contained module. No `package.json`, no `node_modules`, no e
A plugin declares its role via an exported symbol:
| Export | Role | When called |
|---|---|---|
| `export function check(ctx: GateContext): Finding[]` | Gate function | After shell-based gate, before commit |
| `export function stage(): Stage` | Workflow stage | When a workflow references the stage name |
| `export function run(ctx: ScriptContext): void` | Skill script | When a skill's instructions invoke the script |
| Export | Role | When called |
| ---------------------------------------------------- | -------------- | --------------------------------------------- |
| `export function check(ctx: GateContext): Finding[]` | Gate function | After shell-based gate, before commit |
| `export function stage(): Stage` | Workflow stage | When a workflow references the stage name |
| `export function run(ctx: ScriptContext): void` | Skill script | When a skill's instructions invoke the script |
arcie-core discovers the role by checking which exports exist. A file can export multiple roles.
@@ -86,54 +88,54 @@ arcie-core discovers the role by checking which exports exist. A file can export
// .archie/workflows/custom-gate.ts
interface GateContext {
diff: string; // unified diff of changes
changedFiles: string[]; // list of changed file paths
dir: string; // absolute worktree path
repo: string; // "owner/name"
baseRef: string; // "origin/main"
diff: string; // unified diff of changes
changedFiles: string[]; // list of changed file paths
dir: string; // absolute worktree path
repo: string; // "owner/name"
baseRef: string; // "origin/main"
}
interface Finding {
level: "error" | "warn";
file?: string;
line?: number;
message: string;
level: "error" | "warn";
file?: string;
line?: number;
message: string;
}
interface Block {
name: string;
message: string;
name: string;
message: string;
}
export function check(ctx: GateContext): Finding[] {
const findings: Finding[] = [];
const findings: Finding[] = [];
// Rule: no new panic() calls
for (const line of ctx.diff.split("\n")) {
if (line.startsWith("+") && !line.startsWith("+++")) {
if (line.includes("panic(")) {
findings.push({
level: "error",
message: "new panic() call -- use error returns instead"
});
}
}
// Rule: no new panic() calls
for (const line of ctx.diff.split("\n")) {
if (line.startsWith("+") && !line.startsWith("+++")) {
if (line.includes("panic(")) {
findings.push({
level: "error",
message: "new panic() call -- use error returns instead",
});
}
}
}
// Rule: no time.Sleep in non-test files
for (const file of ctx.changedFiles) {
if (file.endsWith("_test.go")) continue;
const content = archie.readFile(`${ctx.dir}/${file}`);
if (content.includes("time.Sleep")) {
findings.push({
level: "warn",
file: file,
message: "time.Sleep in non-test code -- use time.Ticker instead"
});
}
// Rule: no time.Sleep in non-test files
for (const file of ctx.changedFiles) {
if (file.endsWith("_test.go")) continue;
const content = archie.readFile(`${ctx.dir}/${file}`);
if (content.includes("time.Sleep")) {
findings.push({
level: "warn",
file: file,
message: "time.Sleep in non-test code -- use time.Ticker instead",
});
}
}
return findings;
return findings;
}
```
@@ -145,21 +147,21 @@ After transpilation and execution, archie-core calls `check(ctx)` via goja. Erro
// .archie/workflows/run-migrations.ts
export function stage(): Stage {
return {
name: "db-migration",
run: (ctx: TaskContext): string | null => {
// Check if migrations directory exists
const hasMigrations = archie.fileExists(`${ctx.dir}/migrations`);
if (!hasMigrations) return null; // nothing to do
return {
name: "db-migration",
run: (ctx: TaskContext): string | null => {
// Check if migrations directory exists
const hasMigrations = archie.fileExists(`${ctx.dir}/migrations`);
if (!hasMigrations) return null; // nothing to do
// Run migration tests
const result = archie.exec("go", ["test", "./migrations/..."]);
if (result.exitCode !== 0) {
return `migration tests failed: ${result.stderr}`;
}
return null; // success
}
};
// Run migration tests
const result = archie.exec("go", ["test", "./migrations/..."]);
if (result.exitCode !== 0) {
return `migration tests failed: ${result.stderr}`;
}
return null; // success
},
};
}
```
@@ -169,11 +171,11 @@ export function stage(): Stage {
// .archie/workflows/security-audit.ts
export function run(ctx: ScriptContext): void {
const result = archie.exec("gitleaks", ["detect", "--no-git"]);
if (result.exitCode !== 0) {
archie.log("warn", `gitleaks found secrets:\n${result.stdout}`);
}
archie.log("info", "security audit complete");
const result = archie.exec("gitleaks", ["detect", "--no-git"]);
if (result.exitCode !== 0) {
archie.log("warn", `gitleaks found secrets:\n${result.stdout}`);
}
archie.log("info", "security audit complete");
}
```
@@ -183,33 +185,33 @@ arcie-core exposes a `archie` global in the goja runtime:
```typescript
interface Archie {
// File operations (scoped to worktree)
readFile(path: string): string;
fileExists(path: string): boolean;
listDir(path: string): string[];
walkDir(path: string): string[];
// Shell execution
exec(command: string, args?: string[]): ExecResult;
// Logging
log(level: string, message: string): void;
// Path utilities
resolve(...parts: string[]): string;
ext(path: string): string;
// Environment
env(key: string): string;
// HTTP (optional, gated)
fetch(url: string, options?: FetchOptions): FetchResult;
// File operations (scoped to worktree)
readFile(path: string): string;
fileExists(path: string): boolean;
listDir(path: string): string[];
walkDir(path: string): string[];
// Shell execution
exec(command: string, args?: string[]): ExecResult;
// Logging
log(level: string, message: string): void;
// Path utilities
resolve(...parts: string[]): string;
ext(path: string): string;
// Environment
env(key: string): string;
// HTTP (optional, gated)
fetch(url: string, options?: FetchOptions): FetchResult;
}
interface ExecResult {
stdout: string;
stderr: string;
exitCode: number;
stdout: string;
stderr: string;
exitCode: number;
}
```
@@ -217,7 +219,7 @@ All file operations are **jailed to the worktree**. `archie.readFile("/etc/passw
### Reload cycle
Plugins are loaded fresh on every poll cycle -- archie-core already fresh-clones per task. No hot-reload complexity, no cache invalidation. The worktree is the source of truth.
Plugins are loaded fresh on every poll cycle -- archie-core already fresh-clones per task. No hot-reload complexity, no cache invalidation. The worktree is the source of truth.
For the rare case where a plugin errors at parse/transpile time, archie-core comments on the issue with the diagnostic and parks the task. The plugin author fixes the `.ts` file and requeues.
@@ -377,18 +379,18 @@ if gatePlugin := tc.Plugins.Gate(); gatePlugin != nil {
goja natively supports ES5.1 with significant ES6 features. Modern syntax like `async/await`, `??`, `?.`, or `class` fields may not parse. The transpile step (esbuild targeting ES2017) handles most of this, but there will be edge cases:
| Feature | Status |
|---|---|
| Arrow functions | ✅ via transpile |
| Template literals | ✅ via transpile |
| Destructuring | ✅ via transpile |
| `const`/`let` | ✅ via transpile |
| `async/await` | ❌ not supported (goja is synchronous) |
| `Promise` | ❌ requires `goja_nodejs` event loop |
| Generators | ❌ not supported |
| `Proxy` | ❌ not supported |
| Feature | Status |
| ----------------- | -------------------------------------- |
| Arrow functions | ✅ via transpile |
| Template literals | ✅ via transpile |
| Destructuring | ✅ via transpile |
| `const`/`let` | ✅ via transpile |
| `async/await` | ❌ not supported (goja is synchronous) |
| `Promise` | ❌ requires `goja_nodejs` event loop |
| Generators | ❌ not supported |
| `Proxy` | ❌ not supported |
For gate scripts, this is fine -- gates are synchronous by nature. If async is genuinely needed later, the Bun backend (via `tsgo`) is the escape hatch.
For gate scripts, this is fine -- gates are synchronous by nature. If async is genuinely needed later, the Bun backend (via `tsgo`) is the escape hatch.
### Performance
@@ -402,44 +404,48 @@ Plugins can't `import` from npm or other files. They're self-contained modules.
## Comparison: Yaegi vs goja
| | Yaegi (Go) | goja + esbuild (TypeScript) |
|---|---|---|
| **Language** | Go | TypeScript |
| **Pure Go** | ✅ | ✅ (goja + esbuild both pure Go) |
| **CGO** | None | None |
| **Transpile step** | None (interpreted directly) | esbuild TS→JS (~3ms) |
| **Author audience** | Go developers | Anyone who knows TypeScript |
| **Type annotations** | N/A (Go is typed) | Stripped by esbuild (no type-check at runtime) |
| **Interop** | Direct Go↔Go via `Use()` | Bridge via `archie` global |
| **Performance** | Interpreted Go (~10x slower than compiled) | Interpreted JS (~50x slower than V8, fine for gates) |
| **Maturity** | 8k stars, used by Traefik for plugins | 7k stars, used by k6, goja is battle-tested |
| **File extension** | `.go` | `.ts` |
| **Plugin folder** | `.archie/workflows/` | `.archie/workflows/` |
| **Best for** | Custom stages needing Go's stdlib, tight daemon integration | Custom gates and scripts where author familiarity matters |
| | Yaegi (Go) | goja + esbuild (TypeScript) |
| -------------------- | ----------------------------------------------------------- | --------------------------------------------------------- |
| **Language** | Go | TypeScript |
| **Pure Go** | ✅ | ✅ (goja + esbuild both pure Go) |
| **CGO** | None | None |
| **Transpile step** | None (interpreted directly) | esbuild TS→JS (~3ms) |
| **Author audience** | Go developers | Anyone who knows TypeScript |
| **Type annotations** | N/A (Go is typed) | Stripped by esbuild (no type-check at runtime) |
| **Interop** | Direct Go↔Go via `Use()` | Bridge via `archie` global |
| **Performance** | Interpreted Go (~10x slower than compiled) | Interpreted JS (~50x slower than V8, fine for gates) |
| **Maturity** | 8k stars, used by Traefik for plugins | 7k stars, used by k6, goja is battle-tested |
| **File extension** | `.go` | `.ts` |
| **Plugin folder** | `.archie/workflows/` | `.archie/workflows/` |
| **Best for** | Custom stages needing Go's stdlib, tight daemon integration | Custom gates and scripts where author familiarity matters |
**Recommendation: support both.** They solve different problems. Yaegi for repo owners who want full Go power in their custom stages. goja for repo owners who want to write gates and scripts in TypeScript. Both load from `.archie/workflows/` -- archie-core discovers which engine to use by file extension (`.go` → Yaegi, `.ts` → goja+esbuild).
**Recommendation: support both.** They solve different problems. Yaegi for repo owners who want full Go power in their custom stages. goja for repo owners who want to write gates and scripts in TypeScript. Both load from `.archie/workflows/` -- archie-core discovers which engine to use by file extension (`.go` → Yaegi, `.ts` → goja+esbuild).
---
## Implementation phases
### Phase 1: goja runtime + esbuild
- Add `github.com/dop251/goja` and `github.com/evanw/esbuild` as dependencies
- Build `internal/plugins/` with loader, runtime pool, bridge
- Wire gate plugin discovery into the implement and TDD workflows
- Gate plugins run after shell-based gate, before commit
### Phase 2: Custom stages
- Stage plugins discovered and registered alongside built-in stages
- `config.toml` can reference plugin stages by name
- TaskContext exposed to JS plugins
### Phase 3: Skill scripts
- Skill SKILL.md can reference `scripts/security-audit.ts`
- archie-core loads, transpiles, and evaluates when the skill activates
- Script stdout captured and returned to the agent as tool output
### Phase 4: Yaegi side-by-side
- Go plugin files (`.go`) loaded via Yaegi from the same `.archie/workflows/` directory
- Same discovery pattern, different interpreter
- archie-core chooses engine by file extension
+6 -29
View File
@@ -137,14 +137,7 @@
"type": "integer"
}
},
"required": [
"version",
"task_id",
"attempt",
"stage",
"status",
"usage"
],
"required": ["version", "task_id", "attempt", "stage", "status", "usage"],
"type": "object"
},
"Budget": {
@@ -203,9 +196,7 @@
"type": "object"
}
},
"required": [
"name"
],
"required": ["name"],
"type": "object"
},
"Command": {
@@ -225,10 +216,7 @@
"type": "string"
}
},
"required": [
"name",
"argv"
],
"required": ["name", "argv"],
"type": "object"
},
"Gate": {
@@ -296,10 +284,7 @@
"type": "integer"
}
},
"required": [
"type",
"file_id"
],
"required": ["type", "file_id"],
"type": "object"
},
"MessageEvent": {
@@ -358,12 +343,7 @@
"type": "string"
}
},
"required": [
"type",
"channel_id",
"platform",
"sender_id"
],
"required": ["type", "channel_id", "platform", "sender_id"],
"type": "object"
},
"PluginSpec": {
@@ -377,10 +357,7 @@
"type": "string"
}
},
"required": [
"name",
"src"
],
"required": ["name", "src"],
"type": "object"
},
"Protection": {
+44 -44
View File
@@ -10,25 +10,25 @@
"url": "/dev/architecture/adversarial-review/",
"title": "Adversarial self-review",
"section": "Architecture",
"body": "# Adversarial self-review\n\nArchie runs a fresh adversarial review of the diff before it opens a pull\nrequest, so a PR arrives with a findings record rather than an unreviewed\nclaim. The reviewer provably cannot see the implementer's context: it reviews a\n`.git`-free snapshot of the committed tree, not the worktree, the commit\nhistory, or the implementer's transcript.\n\nPromoted from `docs/prds/adversarial-self-review.md` (the design decision;\n`archie-core-h019`). Describes the stage as shipped.\n\n## Contract (`internal/domain/workflow`)\n\nThe workflow domain owns the contract and the blocking decision; it never names\nthe executor.\n\n- `Reviewer.Review(ctx, ReviewRequest) ReviewReport` — the interface the\n workflow stage consumes.\n- `ReviewRequest` is the reviewer's entire input: `SnapshotDir` (a `.git`-free\n export of the reviewed commit), `Diff` (base...head), `IssueText` (the\n originating issue title/body), and `MaxSteps`.\n- `ReviewFinding` / `ReviewReport` are the structured result. The load-bearing\n rule is `Blocking() == (Verdict == confirmed \u0026\u0026 Level == error)`: only a\n confirmed error-level finding blocks; a plausible finding never blocks\n however severe it claims to be.\n\n`ReviewReport` distinguishes `not_run`, `skipped`, and `completed` (zero\nfindings) structurally, so \"ran and found nothing\" is not the same as \"never\nran\" — collapsing them would make an outage indistinguishable from a clean\nreview.\n\n## Execution (`internal/app/agentworker`)\n\nThe executor is an ai-sdk `agent.Subagent`: a nested synchronous generation in\nthe same worker process, with its own model, system prompt, toolset and step\nbudget.\n\n- **Conversation isolation is structural.** `Subagent.Run` sends only a prompt\n string, never the implementer's message history.\n- **Workspace isolation is the `.git`-free snapshot.** The reviewer's toolset is\n read-only (`read`, `grep`, `find`) and rooted at `SnapshotDir` — never the\n worker's own toolset, which carries the `worktreerpc` publication grant.\n- **Findings return through a typed capture tool** (`record_finding`), validated\n on the way in, so the reviewer reports through the contract rather than free\n text the caller regexes.\n- **Fail-closed.** A reviewer that errors, truncates, or reaches no conclusion\n yields `ReviewStatusNotRun`, which the stage treats as a park — never a silent\n \"PR opened unreviewed\".\n\n## Lifecycle effect\n\n`StageReview` runs in the implement workflow after the deterministic gates and\nbefore `StageOpenPR`, gated by `repo.review_enabled` (opt-in, default off). A\nsurviving blocking finding — or a review that failed to run — parks the task\n(`StatusParked`, not `waiting_human`) with the findings rendered into the park\nreason; `StageOpenPR` never runs. Warn/plausible findings and the zero-finding\ncase leave the outcome unset, so the PR opens with a findings section rendered\nonto its body. `StagePostReviewComments` then runs after `StageOpenPR` and posts\nthe **line-anchored** findings as inline review comments, carrying a one-click\nsuggestion on a confirmed finding the reviewer could state a fix for. That stage\nis best-effort — a comment that fails to post is logged, never a park — because\nthe body section already lists every finding, and it is the record a whole-file\nfinding (no line to anchor to) only ever appears in.\n\n## Model and budget\n\nThe reviewer model is `models.reviewer`, falling back to `models.builder`.\nEffort is the per-stage `MaxSteps` budget, mapped onto `Subagent.MaxSteps`\n(default 10).\n\n## Operator-triggered review\n\nThe same reviewer runs against an *existing* PR via the channel-neutral\n`review_pr` chat command: fetch the PR's head, snapshot it, run the isolated\nreviewer, and return the structured findings. Authorization is identity-scoped\nto the operator's configured repositories; duplicate or concurrent reviews of\nthe same PR are deduplicated.\n"
"body": "# Adversarial self-review\n\nArchie runs a fresh adversarial review of the diff before it opens a pull\nrequest, so a PR arrives with a findings record rather than an unreviewed\nclaim. The reviewer provably cannot see the implementer's context: it reviews a\n`.git`-free snapshot of the committed tree, not the worktree, the commit\nhistory, or the implementer's transcript.\n\nPromoted from `docs/prds/adversarial-self-review.md` (the design decision;\n`archie-core-h019`). Describes the stage as shipped.\n\n## Contract (`internal/domain/workflow`)\n\nThe workflow domain owns the contract and the blocking decision; it never names\nthe executor.\n\n- `Reviewer.Review(ctx, ReviewRequest) ReviewReport` — the interface the\n workflow stage consumes.\n- `ReviewRequest` is the reviewer's entire input: `SnapshotDir` (a `.git`-free\n export of the reviewed commit), `Diff` (base...head), `IssueText` (the\n originating issue title/body), and `MaxSteps`.\n- `ReviewFinding` / `ReviewReport` are the structured result. The load-bearing\n rule is `Blocking() == (Verdict == confirmed \u0026\u0026 Level == error)`: only a\n confirmed error-level finding blocks; a plausible finding never blocks\n however severe it claims to be.\n\n`ReviewReport` distinguishes `not_run`, `skipped`, and `completed` (zero\nfindings) structurally, so \"ran and found nothing\" is not the same as \"never\nran\" — collapsing them would make an outage indistinguishable from a clean\nreview.\n\n## Execution (`internal/app/agentworker`)\n\nThe executor is an ai-sdk `agent.Subagent`: a nested synchronous generation in\nthe same worker process, with its own model, system prompt, toolset and step\nbudget.\n\n- **Conversation isolation is structural.** `Subagent.Run` sends only a prompt\n string, never the implementer's message history.\n- **Workspace isolation is the `.git`-free snapshot.** The reviewer's toolset is\n read-only (`read`, `grep`, `find`) and rooted at `SnapshotDir` — never the\n worker's own toolset, which carries the `worktreerpc` publication grant.\n- **Findings return through a typed capture tool** (`record_finding`), validated\n on the way in, so the reviewer reports through the contract rather than free\n text the caller regexes.\n- **Fail-closed.** A reviewer that errors, truncates, or reaches no conclusion\n yields `ReviewStatusNotRun`, which the stage treats as a park — never a silent\n \"PR opened unreviewed\".\n\n## Lifecycle effect\n\n`StageReview` runs in the implement workflow after the deterministic gates and\nbefore `StageOpenPR`, gated by `repo.review_enabled` (opt-in, default off). A\nsurviving blocking finding — or a review that failed to run — parks the task\n(`StatusParked`, not `waiting_human`) with the findings rendered into the park\nreason; `StageOpenPR` never runs. Warn/plausible findings and the zero-finding\ncase leave the outcome unset, so the PR opens with a findings section rendered\nonto its body. `StagePostReviewComments` then runs after `StageOpenPR` and posts\nthe **line-anchored** findings as inline review comments, carrying a one-click\nsuggestion on a confirmed finding the reviewer could state a fix for. That stage\nis best-effort — a comment that fails to post is logged, never a park — because\nthe body section already lists every finding, and it is the record a whole-file\nfinding (no line to anchor to) only ever appears in.\n\n## Model and budget\n\nThe reviewer model is `models.reviewer`, falling back to `models.builder`.\nEffort is the per-stage `MaxSteps` budget, mapped onto `Subagent.MaxSteps`\n(default 10).\n\n## Operator-triggered review\n\nThe same reviewer runs against an *existing* PR via the channel-neutral\n`review_pr` chat command: fetch the PR's head, snapshot it, run the isolated\nreviewer, and return the structured findings. Authorisation is identity-scoped\nto the operator's configured repositories; duplicate or concurrent reviews of\nthe same PR are deduplicated.\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 authorized 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 personalization 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 authorizing 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
"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\nModeled 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 souLine truncated
"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 recognized 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
"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/",
@@ -40,31 +40,31 @@
"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 serialization 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 centralized 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"
"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:** Generator scaffold in place; renderer and publishing removed\n**Date:** 2026-07-28 (revised 2026-09-12)\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 normalizes documentation data;\n- the generator writes deterministic JSON/data files and protocol schemas;\n- the rendering and publishing surface is an **open decision** — the VitePress\n site and its Pages deployment were removed on 2026-09-12 as an unnecessary\n build step (see \"Rendering and publishing\" below).\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 — OPEN\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\n`docs/` is now repository documentation only — markdown read in the repository,\nan editor, or a forge's file view. Nothing in the repository builds, renders, or\npublishes it.\n\nThe renderer for the generated `data/generated/*.json` is therefore **undecided**.\nConsequences that follow, and their current state:\n\n| Concern | State after removal |\n| --- | --- |\n| Reference-page rendering | Undecided; `data/generated/contracts.json` is committed but unrendered |\n| Internal link validation | Not enforced by any build; links are repository-relative (`../architecture/...`) and resolve on the filesystem |\n| Generated-data drift detection | Unchanged — `docsgen check` compares committed output, independent of any renderer |\n| Navigation/sidebar | The authoritative index is `docs/prds/01-project-management.md` |\n| Local authoring server | None; read markdown directly |\n\nA future renderer MUST NOT reintroduce a dead-link-blind build: VitePress\npreviously validated internal links during its production build, and no\nreplacement currently does.\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 normalized 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 normalized 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 normalization 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 generated/\n cataloLine truncated
"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 generated/\n catalog.json\n contracts.json\n docs.json\n dev-docs.json\n cli.json\n configuration.json\n messaging.json\n agents.json\n workflows.json\n policies.json\n plugins.json\n tools.json\n public/\n schemas/\n asyncapi-header.yaml\n archie.yaml\n .tmp/\n```\n\nAllLine 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
"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 authorized 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
"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
"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/",
@@ -88,13 +88,13 @@
"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, initialization,\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 behavior 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-diLine truncated
"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, authorization, 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 authorization\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"
"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/",
@@ -124,7 +124,7 @@
"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 catalog in `ui/src/lib/task-meta.ts`. The server\n catalog 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 needs its own statement (as\n`StampTaskBinding` does for binding provenance and inputs).\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"
"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 needs its own statement (as\n`StampTaskBinding` does for binding provenance and inputs).\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/",
@@ -166,7 +166,7 @@
"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, summarize 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 behavior, not explanatory UI around missing behavior. 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 behavior and exaggerated claims. Verify and synthesize 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"
"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/",
@@ -184,7 +184,7 @@
"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
"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/",
@@ -202,7 +202,7 @@
"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
"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/",
@@ -220,7 +220,7 @@
"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\ncatalog, 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 row(f.label, f.value, {\n key: f.key, type: f.type, options: f.options,\n locked: f.locked_reason, overridden: f.overridden,\n restartRequired: f.restart_required,\n }));\n // structured fields render through their dedicated editor (b6ew.4)\n}Line truncated
"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 row(f.label, f.value, {\n key: f.key, type: f.type, options: f.options,\n locked: f.locked_reason, overridden: f.overridden,\n restartRequired: f.restart_required,\n }));\n // structured fields render through their dedicated editor (b6ew.4)\Line truncated
},
{
"url": "/dev/prds/contract-conformance-audit/",
@@ -268,7 +268,7 @@
"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\ncatalog 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- `TestTaskMetaPayloadMatchesFixture` requires the handler to serve\n `internal/webui/testdata/task_meta.json` byte for byte. Regenerate it with\n `go test ./internal/webui -run TestTaskMetaPayloadMatchesFixture -update`.\n- `ui/test/task-meta-snapshot.test.ts` requires the snapshot to equal that\n fixture.\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"
"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- `TestTaskMetaPayloadMatchesFixture` requires the handler to serve\n `internal/webui/testdata/task_meta.json` byte for byte. Regenerate it with\n `go test ./internal/webui -run TestTaskMetaPayloadMatchesFixture -update`.\n- `ui/test/task-meta-snapshot.test.ts` requires the snapshot to equal that\n fixture.\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/",
@@ -286,13 +286,13 @@
"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 unlabeled 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 labeled 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 unrecognized) 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 `regLine truncated
"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 generalizes 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 catalog, 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 through Line truncated
"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/",
@@ -316,25 +316,25 @@
"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 parameterized: `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
"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/extensions-center/",
"title": "Extensions center",
"title": "Extensions centre",
"section": "PRDs",
"body": "# Extensions center\n\n**Status:** Draft\n\nEpic: `archie-core-1786637490708-35-38424ead` / GitHub `#56` (\"Replace Skills\nwith a bundled Extensions center\").\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-disableable\" property\nenforced structurally rathLine truncated
"body": "# Extensions centre\n\n**Status:** Draft\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-disableable\" property\nenforced structurally rathLine 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 authorization 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\nenrollment, 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'sLine truncated
"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
"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/",
@@ -346,7 +346,7 @@
"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 serializes 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.\n\n**Reuse check.** The chat model invocation path already exists\n(`chatGenerateOptions`, `main.go`); this reuses it rather than adding a\nparallel 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 behavior), keep the single `callMu`\nserializing that server's calls exactly as now; when true, drop the mutex for\nthat server's `Client` instance entirely and let the caller's own\nconcurrency (already proven by the closed concurrent-dispatch bead, `#183`)\nhandle it. This is additive — no server's behavior changes unless an operator\nopts in.\n\n**Call site.** `internal/config/config.go` (struct field),\n`internal/tools/mcp/client.go` (make the mutex conditional on the\nfield), and wherever `MCPServer` configs are turned into `Client` instances\nat daemon startup (the constructor that reads `internal/config`'s MCP block).\n`config.example.toml`'s commented MCP block gets the new field documented\nwith its default.\n\n**Testing.** Unit test asserting two concurrent `Call`s to the same\n`Client` block on each other when the flag is false and don't when true —\nfakeable with a slow fake transport. `task check`.\n\n## Sandboxed MCP tool servers for the chat agent (`#178`) and Firecracker substLine truncated
"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.\n\n**Reuse check.** The chat model invocation path already exists\n(`chatGenerateOptions`, `main.go`); this reuses it rather than adding a\nparallel 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 mutex for\nthat server's `Client` instance entirely and let the caller's own\nconcurrency (already proven by the closed concurrent-dispatch bead, `#183`)\nhandle it. This is additive — no server's behaviour changes unless an operator\nopts in.\n\n**Call site.** `internal/config/config.go` (struct field),\n`internal/tools/mcp/client.go` (make the mutex conditional on the\nfield), and wherever `MCPServer` configs are turned into `Client` instances\nat daemon startup (the constructor that reads `internal/config`'s MCP block).\n`config.example.toml`'s commented MCP block gets the new field documented\nwith its default.\n\n**Testing.** Unit test asserting two concurrent `Call`s to the same\n`Client` block on each other when the flag is false and don't when true —\nfakeable with a slow fake transport. `task check`.\n\n## Sandboxed MCP tool servers for the chat agent (`#178`) and Firecracker subLine truncated
},
{
"url": "/dev/prds/memory-engine-unification/",
@@ -358,13 +358,13 @@
"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 behavior, 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- 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:\n1. **Telegram long-polling**: Must call `dropPendingUpdates(ctx, b)` before `b.Start(ctx)` and on `/restart`.\n2. **Telegram command menus**: Must register command menus simultaneously to `default`, `all_private_chats`, and `all_group_chats` via `commands.go` to prevent menu shadowing.\n3. **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`.\n4. **Sender Confinement**: Telegram sender checks against `allowed_user_ids` must continue to fail closed before initiating any turn dispatch.\n\n## Configuration Ownership\n\n`cmd/archie-messaging` reads only:\n- `[services.gateway].target` and `[services.gateway].target_token` (or CLI flags).\n- `[chaLine truncated
"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- 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:\n1. **Telegram long-polling**: Must call `dropPendingUpdates(ctx, b)` before `b.Start(ctx)` and on `/restart`.\n2. **Telegram command menus**: Must register command menus simultaneously to `default`, `all_private_chats`, and `all_group_chats` via `commands.go` to prevent menu shadowing.\n3. **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`.\n4. **Sender Confinement**: Telegram sender checks against `allowed_user_ids` must continue to fail closed before initiating any turn dispatch.\n\n## Configuration Ownership\n\n`cmd/archie-messaging` reads only:\n- `[services.gateway].target` and `[services.gateway].target_token` (or CLI flags).\n- `[chLine 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 -- generalize 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**, parameterized 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 *ModuleRegistry) Register(kind string, dir string) error // discovers \u003ckind\u003e.go, resolves against that kind's generated symbols\nfunc (r *ModuleRegistry) Invoke(ctx context.Context, kind string, rawArgs map[string]any) (map[string]aLine truncated
"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 *ModuleRegistry) Register(kind string, dir string) error // discovers \u003ckind\u003e.go, resolves against that kind's generated symbols\nfunc (r *ModuleRegistry) Invoke(ctx context.Context, kind string, rawArgs map[string]any) (map[string]aLine truncated
},
{
"url": "/dev/prds/multi-action-playbooks/",
@@ -374,15 +374,15 @@
},
{
"url": "/dev/prds/news-and-releases/",
"title": "Public news and per-version release notes -- decision",
"title": "Public news and per-version release notes",
"section": "PRDs",
"body": "# Public news and per-version release notes -- decision\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` supersedes the\nsections \"Source of truth\" and \"Two components\" below. There is now one release\nstream: a single `CHANGELOG.md` carries every release section, the per-component\n`CHANGELOG.archied.md` and `CHANGELOG.archie.md` are deleted, and one `vX.Y.Z` tag\nnames a release. The rest of this document still holds.\n\nA public news page and a release-notes page for every version. Both are derived\nfrom the changelogs the release process already produces, so publishing a\nrelease adds no writing. Part A is the derivation and the artifact any renderer\nconsumes; it is not tied to MkDocs. Part B is the MkDocs rendering that\npublishes them at `offloaded.dev/news/`.\n\n## Part A -- release facts and their derivation\n\n### Source of truth\n\nRelease notes come from `CHANGELOG.archied.md` and `CHANGELOG.archie.md`. Those\nare the release process's frozen notes: `tools/release.sh --prepare` writes a\nsection, the maintainer edits it, and `--tag` refuses to tag a version without\nits section. A page exists exactly for a release the process cut, and no second\ncopy of release prose can drift from the changelog.\n\nTags are not the source. CI and deployment check out shallow, so tags are absent\nfrom a site build; the changelogs are always present and their\n`## [\u003cversion\u003e] - \u003cdate\u003e` headings carry the same version and date the tags\ncarry. Raw commits are not the source either: the changelog is the edited text,\nnot the commit list.\n\n### What a version's notes contain\n\nThe version and date parsed from the section heading, and the section body\nunchanged. The body keeps the maintainer's headings and bullets; the generator\ndoes not regroup them into feature and fix categories, because those categories\nexist only on commits the edited changelog does not preserve.\n\n`## [Unreleased]` is skipped. Any other `## [` heading that is not\n`[version] - date` stops generation, so a malformed heading cannot silently drop\na release. A relative Markdown link in a body stops generation too: a rendered\npage sits at a different depth from the changelog, and a host's link checking\nwould fail on the dead link. Absolute links pass through.\n\n### Two components\n\n`archied` and `archie-agent` version independently and either can be held back,\nso the data carries the tag prefix (`archied`, `archie`), the product name\n(`archied`, `archie-agent`), and the version as separate fields. A release that\nmoved one component is one entry. The generator never pairs two component\nversions or invents a combined product version.\n\n### The canonical artifact\n\n`docs/news/releases.json` is the host hand-off: a committed, generated,\nnewest-first array of `{component, name, version, date, body}`. Every adapter\nrenders from this file rather than re-parsing a changelog. The JSON is the\ncontract; a host adapter may add markup, but not facts.\n\n### Zero per-release maintenance\n\n`task news` regenerates the JSON and the MkDocs pages from the changelogs.\n`task news:check` regenerates them in a temporary directory and fails when the\ncommitted files differ; it runs in `task check`, so a changelog edit cannot land\nwithout its regeneration. `tools/release.sh --tag` regenerates and stages them\nin the release commit, so a tag's tree carries its own facts.\n\nThe generator owns `docs/news/releases.json`, `docs/news/index.md` and the two\ncomponent directories end-to-end: it rewrites expected files and reports an\nunexpected file in a component directory as drift. It leaves every other file\nunder `docs/news/` alone, so a future hand-written announcement is not its\nbusiness.\n\n## Part B -- publishing\n\nMkDocs is the host. `docs/news/index.md` is the news page: date-grouped, newest\nfirst, one entry per release carrying the component, the version, and a link to\nits notes. `docs/news/archied/\u003cversion\u003e.md` and `docs/news/archie/\u003cversion\u003e.md`\nhold the notes. `site_url` is `https://offloaded.dev/`, so the pages are served\nat `offloaded.dev/news/`.\n\nThe version pages stay out of the derived navigation (`not_in_nav` in\n`mkdocs.yml`) while remaining published; the news page is their entry point, so\na version list that grows with every release cannot push the architecture tree\noff the screen.\n\nA different renderer would read `docs/news/releases.json` instead of these\nMarkdown files. That is a separate change in that renderer's repository and\ndoes not alter Part A; the JSON, not the Markdown, is the reusable half.\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 eveLine truncated
"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/operator-pr-review/",
"title": "Operator-triggered PR review",
"section": "PRDs",
"body": "# Operator-triggered PR review\n\n**Status:** Draft\n**Beads issue:** `archie-core-h019.8`\n\nThis PRD reuses the adversarial-self-review contract\n(`docs/prds/adversarial-self-review.md`) and the `workflow.Reviewer` /\n`workflow.ReviewReport` types from `internal/domain/workflow`. It decides\nonly what is new: how an operator asks for a review of an *existing* PR, and\nhow that PR's content reaches the reviewer.\n\n## Problem\n\nThe adversarial reviewer (`StageReview`) runs automatically before `StageOpenPR`\nand reviews the task's own worktree HEAD. There is no way to review a PR that\nalready exists: one archie opened, a human opened, or one whose findings the\noperator wants re-checked after a push.\n\n## Shape\n\nOne channel-neutral command — `review_pr` — accepts a repository and PR number\nand returns the structured `ReviewReport`. The Web UI chat and Telegram invoke\nthe same command; neither duplicates review behaviour. The reviewer model is\n`models.reviewer` (falling back to `models.builder`), already the rule the\nworkflow stage uses, so an operator configures it independently of\nplanner/builder.\n\n## Decisions\n\n1. **Forge read.** `GetPullRequest(owner, repo, number)` returns a\n forge-neutral `PullRequest{Number, Title, Body, HeadRef, BaseRef, HeadSHA,\n BaseSHA, State}`. Declared as a narrow `PullRequestReader` interface,\n implemented by GitHub and Gitea; the noop forge does not implement it, so\n the composition root type-asserts and refuses review with \"forge does not support PR\n review\". Adding to the fat `Forge` interface would churn every test fake for\n a capability the noop forge cannot honestly provide.\n\n2. **Materialisation.** `worktree.Manager.CheckoutPR(owner, repo, headRef,\n baseRef)` clones the repository fully and checks out `origin/\u003cheadRef\u003e`.\n `Diff(dir, baseRef)` and `Snapshot(dir, destDir)` then work unchanged:\n `Diff` resolves `origin/\u003cbaseRef\u003e` via the existing `resolveBase`, and\n `Snapshot` strips `.git` exactly as the workflow stage does. The head must\n already be pushed to the same repository — archie's own PRs always are; a\n cross-repo or deleted head is refused with that reason, not half-reviewed.\n\n3. **Reviewer reuse.** `agentworker.NewOperatorReviewer(models, providers)`\n builds the same `subagentReviewer` the stage uses, from daemon-level config\n rather than a `taskrun.Request`. It drops only the `Repo.ReviewEnabled`\n gate (the operator asked explicitly) and the task-run scaffolding.\n\n4. **Command.** A gateway tool `review_pr` (toolset `tasks`) bound to the\n channel's identity at construction — the model never names an identity,\n matching `task_spawn`/`task_action`. The Gateway process serves it: it\n composes the worktree manager it needs to materialise the PR head, and the\n composition root supplies `ChatPRReviewer`, a narrow gateway interface\n whose adapter maps `workflow.ReviewReport` into a gateway-owned result\n shape (gateway states what it needs, the composition root adapts — the\n `ChatTaskActor` pattern).\n\n5. **Authorization.** Identity-scoped repository allow-list, the\n `task_spawn` rule: a chat identity may only review a repo in its\n `TaskProfile.Repos`. `identity == nil` denotes an authenticated dashboard\n operator who may review any configured repository.\n\n6. **Determinism.** One review per (owner, repo, number) at a time: the\n Gateway holds an in-flight set; a concurrent request for the same PR returns\n \"review already in progress\" rather than launching a second reviewer and\n racing on the snapshot.\n\n## Files\n\n- `internal/forge/forge.go`, `github.go`, `gitea.go` — `PullRequest`,\n `PullRequestReader`, `GetPullRequest`.\n- `internal/worktree/worktree.go` — `CheckoutPR`.\n- `internal/app/agentworker/review.go` — `NewOperatorReviewer`.\n- `internal/gateway/review_tools.go` — `ChatPRReviewer`, result shape, `review_pr`.\n- `internal/gateway/turn.go`, `gateway.go` — tool wiring into the turn.\n- `internal/app/archied/pr_review.go` — the `ChatPRReviewer` adapter.\n- `internal/app/archied/{bootstrap.go,gateway.go,main.go}` — composition.\n\n## Not in scope\n\n- Surfacing findings on the PR body or the dashboard (h019.6).\n- Reviewer model per-invocation override: configuration via `models.reviewer`\n is the selection surface; a per-call override is a later knob.\n"
"body": "# Operator-triggered PR review\n\n**Status:** Draft\n**Beads issue:** `archie-core-h019.8`\n\nThis PRD reuses the adversarial-self-review contract\n(`docs/prds/adversarial-self-review.md`) and the `workflow.Reviewer` /\n`workflow.ReviewReport` types from `internal/domain/workflow`. It decides\nonly what is new: how an operator asks for a review of an *existing* PR, and\nhow that PR's content reaches the reviewer.\n\n## Problem\n\nThe adversarial reviewer (`StageReview`) runs automatically before `StageOpenPR`\nand reviews the task's own worktree HEAD. There is no way to review a PR that\nalready exists: one archie opened, a human opened, or one whose findings the\noperator wants re-checked after a push.\n\n## Shape\n\nOne channel-neutral command — `review_pr` — accepts a repository and PR number\nand returns the structured `ReviewReport`. The Web UI chat and Telegram invoke\nthe same command; neither duplicates review behaviour. The reviewer model is\n`models.reviewer` (falling back to `models.builder`), already the rule the\nworkflow stage uses, so an operator configures it independently of\nplanner/builder.\n\n## Decisions\n\n1. **Forge read.** `GetPullRequest(owner, repo, number)` returns a\n forge-neutral `PullRequest{Number, Title, Body, HeadRef, BaseRef, HeadSHA,\n BaseSHA, State}`. Declared as a narrow `PullRequestReader` interface,\n implemented by GitHub and Gitea; the noop forge does not implement it, so\n the composition root type-asserts and refuses review with \"forge does not support PR\n review\". Adding to the fat `Forge` interface would churn every test fake for\n a capability the noop forge cannot honestly provide.\n\n2. **Materialisation.** `worktree.Manager.CheckoutPR(owner, repo, headRef,\n baseRef)` clones the repository fully and checks out `origin/\u003cheadRef\u003e`.\n `Diff(dir, baseRef)` and `Snapshot(dir, destDir)` then work unchanged:\n `Diff` resolves `origin/\u003cbaseRef\u003e` via the existing `resolveBase`, and\n `Snapshot` strips `.git` exactly as the workflow stage does. The head must\n already be pushed to the same repository — archie's own PRs always are; a\n cross-repo or deleted head is refused with that reason, not half-reviewed.\n\n3. **Reviewer reuse.** `agentworker.NewOperatorReviewer(models, providers)`\n builds the same `subagentReviewer` the stage uses, from daemon-level config\n rather than a `taskrun.Request`. It drops only the `Repo.ReviewEnabled`\n gate (the operator asked explicitly) and the task-run scaffolding.\n\n4. **Command.** A gateway tool `review_pr` (toolset `tasks`) bound to the\n channel's identity at construction — the model never names an identity,\n matching `task_spawn`/`task_action`. The Gateway process serves it: it\n composes the worktree manager it needs to materialise the PR head, and the\n composition root supplies `ChatPRReviewer`, a narrow gateway interface\n whose adapter maps `workflow.ReviewReport` into a gateway-owned result\n shape (gateway states what it needs, the composition root adapts — the\n `ChatTaskActor` pattern).\n\n5. **Authorisation.** Identity-scoped repository allow-list, the\n `task_spawn` rule: a chat identity may only review a repo in its\n `TaskProfile.Repos`. `identity == nil` denotes an authenticated dashboard\n operator who may review any configured repository.\n\n6. **Determinism.** One review per (owner, repo, number) at a time: the\n Gateway holds an in-flight set; a concurrent request for the same PR returns\n \"review already in progress\" rather than launching a second reviewer and\n racing on the snapshot.\n\n## Files\n\n- `internal/forge/forge.go`, `github.go`, `gitea.go` — `PullRequest`,\n `PullRequestReader`, `GetPullRequest`.\n- `internal/worktree/worktree.go` — `CheckoutPR`.\n- `internal/app/agentworker/review.go` — `NewOperatorReviewer`.\n- `internal/gateway/review_tools.go` — `ChatPRReviewer`, result shape, `review_pr`.\n- `internal/gateway/turn.go`, `gateway.go` — tool wiring into the turn.\n- `internal/app/archied/pr_review.go` — the `ChatPRReviewer` adapter.\n- `internal/app/archied/{bootstrap.go,gateway.go,main.go}` — composition.\n\n## Not in scope\n\n- Surfacing findings on the PR body or the dashboard (h019.6).\n- Reviewer model per-invocation override: configuration via `models.reviewer`\n is the selection surface; a per-call override is a later knob.\n"
},
{
"url": "/dev/prds/orgs-and-access/",
@@ -400,13 +400,13 @@
"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).\nUnbuilt decisions: `archie-core-t2db.25` (J1 action ids),\n`archie-core-t2db.26` (J2 args as CEL),\n`archie-core-t2db.27` (Result schemas declared to CEL).\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\ncondition deciding whether the action runs; (b) a later action's `args`\nvalues referencing an earlier action's `Result` and the triggering\nevent's fields. Both are **CEL expressions**, evaluated against one\nevaluation context. There is no separate interpolation syntax: CEL\nreads nested maps and fields natively, so `args` values that need data\nare written as CEL, and only plain literal args remain plain YAML\nscalars.\n\nBoth halves are read-only: expressions may read context values and\ncompute a result from them, never mutate, never call host functions,\nnever perform I/O. CEL enforces this structurally (no side effects,\nlinear evaluation when macros are 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**\n-- the same tier as `ModuleDir`/`PluginDir`/`SecretEngineDir`\n(module-position.md's trust-boundary section): loaded from a configured\ndirectory at startup, never from a webhook body or task worktree. The\nschema-by-example flow uses live events to *design against*; the saved\nplaybook is operator-authored file content in an operator-configured\nlocation.\n\nTwo consequences:\n\n1. The expression string is **trusted**. Operator-authored config, not\n attacker input; no sandboxing against a hostile expression string is\n required. If a future playbook source is less trusted (auto-generated\n bindings from unauthenticated captures), that is the playbook-file\n trust tier moving -- the loader's acceptance check is the right\n place, not the evaluator.\n2. The **data the expression reads is NOT trusted** (decoded webhook\n body, prior results through the same pipeline). Robustness against\n hostile data is required: no panic on wrong-typed/missing fields,\n no unbounded cost on deep/cyclic maps, bounded evaluation time. CEL\n provides this structurally (cost limits, linear non-Turing-complete\n evaluation, error values instead of panics -- verified in the\n vetting record below).\n\n## The gate precedent is deliberately NOT copied\n\n`internal/gate/gateeval` evaluates arbitrary interpreted Go\n(`.archie/gate.go`) as the repo's conditional-logic precedent. That is\nthe wrong precedent for playbook conditions because this document's\npremise is: **YAML is pure orchestration data; Yaegi is where\nimperative logic lives** (Problem section; module-position.md's\n\"no generic hook\" section). Yaegi snippets in YAML would move\nimperative logic into the data layer -- the inversion this design\nexists to prevent -- and make playbooks un-lintable.\n\nThe line: conditions are **declarative predicates over runtime data,\nnot programs**. CEL is non-Turing-complete and side-effect-free, so it\ncannot become a program; a condition that needs real logic gets a\nModule kind (Yaegi), referenced by the action, not a stronger\nexpression body.\n\n## Plugin-engine-rule interaction\n\nThe plugin engine rule forbids a generic `Module` interface with an\n`any` payload; it exists to keep static implementation contracts\ntyped. Evaluating CEL against runtime `map[string]any` is **not the\nsame problem**: the rule concerns *implementation contracts* (static\noperations a capability family exposes), not *runtime data values*\n(legitimately dynamic -- an event payload's shape is unknown until it\narrives). The Module contract stays fully typed (generated\n`Args`/`Result` schemas); CEL is a read-only data reader under the\nplaybook engine 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\ntime:\n\n| Name | Type | Source |\n|---|---|---|\n| `event` | `map(string, dyn)` | The triggering event's decoded payload (webhook body / forge issue / schedule tick). Field access via `event.\u003cfield\u003e`, map access via `event[\"field\"]`, presence via `has(eventLine truncated
"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).\nUnbuilt decisions: `archie-core-t2db.25` (J1 action ids),\n`archie-core-t2db.26` (J2 args as CEL),\n`archie-core-t2db.27` (Result schemas declared to CEL).\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\ncondition deciding whether the action runs; (b) a later action's `args`\nvalues referencing an earlier action's `Result` and the triggering\nevent's fields. Both are **CEL expressions**, evaluated against one\nevaluation context. There is no separate interpolation syntax: CEL\nreads nested maps and fields natively, so `args` values that need data\nare written as CEL, and only plain literal args remain plain YAML\nscalars.\n\nBoth halves are read-only: expressions may read context values and\ncompute a result from them, never mutate, never call host functions,\nnever perform I/O. CEL enforces this structurally (no side effects,\nlinear evaluation when macros are 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**\n-- the same tier as `ModuleDir`/`PluginDir`/`SecretEngineDir`\n(module-position.md's trust-boundary section): loaded from a configured\ndirectory at startup, never from a webhook body or task worktree. The\nschema-by-example flow uses live events to *design against*; the saved\nplaybook is operator-authored file content in an operator-configured\nlocation.\n\nTwo consequences:\n\n1. The expression string is **trusted**. Operator-authored config, not\n attacker input; no sandboxing against a hostile expression string is\n required. If a future playbook source is less trusted (auto-generated\n bindings from unauthenticated captures), that is the playbook-file\n trust tier moving -- the loader's acceptance check is the right\n place, not the evaluator.\n2. The **data the expression reads is NOT trusted** (decoded webhook\n body, prior results through the same pipeline). Robustness against\n hostile data is required: no panic on wrong-typed/missing fields,\n no unbounded cost on deep/cyclic maps, bounded evaluation time. CEL\n provides this structurally (cost limits, linear non-Turing-complete\n evaluation, error values instead of panics -- verified in the\n vetting record below).\n\n## The gate precedent is deliberately NOT copied\n\n`internal/gate/gateeval` evaluates arbitrary interpreted Go\n(`.archie/gate.go`) as the repo's conditional-logic precedent. That is\nthe wrong precedent for playbook conditions because this document's\npremise is: **YAML is pure orchestration data; Yaegi is where\nimperative logic lives** (Problem section; module-position.md's\n\"no generic hook\" section). Yaegi snippets in YAML would move\nimperative logic into the data layer -- the inversion this design\nexists to prevent -- and make playbooks un-lintable.\n\nThe line: conditions are **declarative predicates over runtime data,\nnot programs**. CEL is non-Turing-complete and side-effect-free, so it\ncannot become a program; a condition that needs real logic gets a\nModule kind (Yaegi), referenced by the action, not a stronger\nexpression body.\n\n## Plugin-engine-rule interaction\n\nThe plugin engine rule forbids a generic `Module` interface with an\n`any` payload; it exists to keep static implementation contracts\ntyped. Evaluating CEL against runtime `map[string]any` is **not the\nsame problem**: the rule concerns *implementation contracts* (static\noperations a capability family exposes), not *runtime data values*\n(legitimately dynamic -- an event payload's shape is unknown until it\narrives). The Module contract stays fully typed (generated\n`Args`/`Result` schemas); CEL is a read-only data reader under the\nplaybook engine 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\ntime:\n\n| Name | Type | Source |\n|---|---|---|\n| `event` | `map(string, dyn)` | The triggering event's decoded payload (webhook body / forge issue / schedule tick). Field access via `event.\u003cfield\u003e`, map access via `event[\"field\"]`, presence via `has(eventLine 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 adversarial review\nepic's isolation contract (`docs/prds/adversarial-self-review.md`) 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 keyLine truncated
"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 adversarial review\nepic's isolation contract (`docs/prds/adversarial-self-review.md`) 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 keyLine truncated
},
{
"url": "/dev/prds/progressive-tool-disclosure/",
@@ -436,19 +436,19 @@
"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\n## API\n\nThe API has four operations:\n\n1. **Catalog** 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. After migration, settings in TOML are\nignored and cannot block State 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.\nPlugins can add step types. Each run keeps the workflow version it started with.\n\nYaegi, `.archie/stages/*.go`, and `.archie/gate.go` will be removed. Their useful\nbehavior 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 Pinia-backed editor in the Web UI;\n- a messaging command using the same API;\n- migration of existing `[budgets]` values;\n- an end-to-end restart test.\n\nRunning tasks keep the limits they started with. New tasks use the latest applied\nversion. This replaces the old settings overlay instead of extending it.\n\n## Not included in the first implementation\n\n- Moving bootstrap or secret values into normal settings.\n- A generic JSON editor.\n- Rebuilding every settings screen at once.\n- Changing the limits of a running task.\n"
"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\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. After migration, settings in TOML are\nignored and cannot block State 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.\nPlugins can add step types. Each run keeps the workflow version it started 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 Pinia-backed editor in the Web UI;\n- a messaging command using the same API;\n- migration of existing `[budgets]` values;\n- an end-to-end restart test.\n\nRunning tasks keep the limits they started with. New tasks use the latest applied\nversion. This replaces the old settings overlay instead of extending it.\n\n## Not included in the first implementation\n\n- Moving bootstrap or secret values into normal settings.\n- A generic JSON editor.\n- Rebuilding every settings screen at once.\n- Changing the limits of a running task.\n"
},
{
"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
"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 RHEL / Ansible Automation Platform\nmodel: one architecture, sold both ways. This PRD does not decide the\nbusiness model; it decides that the architecture must not foreclose\neither shape.\n\n## Why this shape\n\n`docs/inspiration/module-reference-awx-decomposition-vs-archie.md`\nestablished that Archie's existing domain split already does what AWX's\nservice-decomposition post argues for -- boundaries exist. What didn't\nexist was deployability: `internal/webui` was not a passive frontend. The\nre-baselined coupling inventory is below, and the ratified boundary is\n[`ui-service-boundary.md`](/dev/prds/ui-service-boundary/).\n\n- Telegram task actions now call Gateway's `ChatContract` directly through\n `chatTaskActorAdapter`; the old Telegram-to-webui HTTP detour is historical.\n- `internal/webui/api_chat.go` now holds `gateway.ChatContract`; direct\n `SessionStore`, `Router`, and `TurnHistory` access is historical.\n- The third coupling is closed. UI extraction shipped (`archie-core-8cda.5`,\n closed 2026-09-11): `cmd/archie-ui` serves the dashboard against remote\n Gateway and State StoreLine truncated
"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 RHEL / Ansible Automation Platform\nmodel: one architecture, sold both ways. This PRD does not decide the\nbusiness model; it decides that the architecture must not foreclose\neither shape.\n\n## Why this shape\n\n`docs/inspiration/module-reference-awx-decomposition-vs-archie.md`\nestablished that Archie's existing domain split already does what AWX's\nservice-decomposition post argues for -- boundaries exist. What didn't\nexist was deployability: `internal/webui` was not a passive frontend. The\nre-baselined coupling inventory is below, and the ratified boundary is\n[`ui-service-boundary.md`](/dev/prds/ui-service-boundary/).\n\n- Telegram task actions now call Gateway's `ChatContract` directly through\n `chatTaskActorAdapter`; the old Telegram-to-webui HTTP detour is historical.\n- `internal/webui/api_chat.go` now holds `gateway.ChatContract`; direct\n `SessionStore`, `Router`, and `TurnHistory` access is historical.\n- The third coupling is closed. UI extraction shipped (`archie-core-8cda.5`,\n closed 2026-09-11): `cmd/archie-ui` serves the dashboard against remote\n Gateway and State StoreLine truncated
},
{
"url": "/dev/prds/service-registry/",
@@ -460,25 +460,25 @@
"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
"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\nnormalization 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. Normalizes trivial whitespace (trailing whitespace per line, exactly\n one trailing newline) and writes back **only** when normalization\n actually changes the bytes, recording an `Action` for that write.\n\nNothing here needs judgment. \"Review, prune, and improve\" -- the epic's\nframing -- is real for v1 but deliberately narrow: review is structural\nvalidation, improve is whitespace normalization, 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 catalog 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 catalog 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
"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/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` (generalize\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.\n\u003e 4.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/\n\u003e migration-decisions.md` §4 (`store.Task → WorkflowExecution`, `mutable Stage →\n\u003e StepExecution 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 consuLine truncated
"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.\n\u003e 4.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/\n\u003e migration-decisions.md` §4 (`store.Task → WorkflowExecution`, `mutable Stage →\n\u003e StepExecution 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 consuLine 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`: itemized 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 favor 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 siLine truncated
"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/task-logs-pagination/",
@@ -490,7 +490,7 @@
"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\nstructure is exactly the false fidelity this surface exists to avoid; a column\nis durable, queryable and ordered by construction.\n\n**`0` means \"not attributable\".** It is every row written before this change\nplus the deliberately task-agnostic producers. It is not an attempt number and\nis never rendered as one. The attempts endpoint reports the count of\nunattributed events so the page can say so instead of presenting old history as\nattempt 1.\n\n## Migration against an existing `archie.db`\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\nThe store's migrator (`migrateTasks` in `internal/store/store.go`) already reads\n`PRAGMA table_info` through `tableColumns` and applies a presence-gated\n`ALTER TABLE ... ADD COLUMN` list. This change adds an `events` arm: a\n`tableColumns(ctx, tx, \"events\")` read beside the other two, and the entry\n`ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`.\n\nThree consequences a future maintainer must not get wrong:\n\n- `eventsSchema` is `CREATE TABLE IF NOT EXISTS` (`Line truncated
"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\nstructure is exactly the false fidelity this surface exists to avoid; a column\nis durable, queryable and ordered by construction.\n\n**`0` means \"not attributable\".** It is every row written before this change\nplus the deliberately task-agnostic producers. It is not an attempt number and\nis never rendered as one. The attempts endpoint reports the count of\nunattributed events so the page can say so instead of presenting old history as\nattempt 1.\n\n## Migration against an existing `archie.db`\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\nThe store's migrator (`migrateTasks` in `internal/store/store.go`) already reads\n`PRAGMA table_info` through `tableColumns` and applies a presence-gated\n`ALTER TABLE ... ADD COLUMN` list. This change adds an `events` arm: a\n`tableColumns(ctx, tx, \"events\")` read beside the other two, and the entry\n`ALTER TABLE events ADD COLUMN attempt INTEGER NOT NULL DEFAULT 0`.\n\nThree consequences a future maintainer must not get wrong:\n\n- `eventsSchema` is `CREATE TABLE IF NOT EXISTS` (`Line truncated
},
{
"url": "/dev/prds/task-run-master-detail/",
@@ -502,7 +502,7 @@
"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 behavior, 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 behaviorally 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 |\n|---|---|---|\n| `/api/chat/*` | Gateway `ChatContract` and its versioned client | contract seam exists; DTO and stream parity remain |\n| `/api/tasks/*`, `/api/workflows`, `/api/setup` | State Store read/action contracts plus an explicit execution/admin action contract | State Store adapter exists; UI-facing narrow surface remains |\n| `/events` | State Store `EventsSince`, polled by one UI-process pump feeding `Server.Broadcast` | RESOLVED (`archie-core-za9f`): see migration-decisions, \"Dashboard live event delivery\". No new RPC; replay cursor and drop-recovery are the existing `since` watermark in `sse.go` |\n| `/api/logs`, `/api/logs/stream` | daemon diagnostic feed, host-local | unresolved: `logging.Feed` is in-process on the daemon host and has no contract. The per-task log routes moved off this row: see `/api/tasks/*` above |\n| `/api/tasks/{id}/logs`, `/api/tasks/{id}/logs/download` | State Store task-log read contract (`TaskLogStore`: `ReadTaskLog` + `StreamTaskLogContent`), read by the UI process from the service that owns the state directory | RESOLVED (`archie-core-iaqx`): the UI process composes `TaskLogStore` from its own State Store client and serves the attempt Line truncated
"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 |\n|---|---|---|\n| `/api/chat/*` | Gateway `ChatContract` and its versioned client | contract seam exists; DTO and stream parity remain |\n| `/api/tasks/*`, `/api/workflows`, `/api/setup` | State Store read/action contracts plus an explicit execution/admin action contract | State Store adapter exists; UI-facing narrow surface remains |\n| `/events` | State Store `EventsSince`, polled by one UI-process pump feeding `Server.Broadcast` | RESOLVED (`archie-core-za9f`): see migration-decisions, \"Dashboard live event delivery\". No new RPC; replay cursor and drop-recovery are the existing `since` watermark in `sse.go` |\n| `/api/logs`, `/api/logs/stream` | daemon diagnostic feed, host-local | unresolved: `logging.Feed` is in-process on the daemon host and has no contract. The per-task log routes moved off this row: see `/api/tasks/*` above |\n| `/api/tasks/{id}/logs`, `/api/tasks/{id}/logs/download` | State Store task-log read contract (`TaskLogStore`: `ReadTaskLog` + `StreamTaskLogContent`), read by the UI process from the service that owns the state directory | RESOLVED (`archie-core-iaqx`): the UI process composes `TaskLogStore` from its own State Store client and serves the attempLine truncated
},
{
"url": "/dev/prds/vue-migration-checklist/",
@@ -514,7 +514,7 @@
"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 normalized 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
"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
}
],
"nav": [
@@ -738,7 +738,7 @@
"url": "/dev/prds/event-sources-and-reactions/"
},
{
"title": "Extensions center",
"title": "Extensions centre",
"url": "/dev/prds/extensions-center/"
},
{
@@ -774,7 +774,7 @@
"url": "/dev/prds/multi-action-playbooks/"
},
{
"title": "Public news and per-version release notes -- decision",
"title": "Public news and per-version release notes",
"url": "/dev/prds/news-and-releases/"
},
{
+1 -1
View File
@@ -4,7 +4,7 @@
"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 behavior 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 modeLine truncated
"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/",
+2 -2
View File
@@ -15,8 +15,8 @@ Authority: `docs/architecture/agent-system.md`. The status vocabulary lives in
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 catalog in `ui/src/lib/task-meta.ts`. The server
catalog replaces the defaults when it loads, but the defaults render first.
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
+10 -10
View File
@@ -7,16 +7,16 @@ 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 |
| 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
+6
View File
@@ -7,7 +7,9 @@ This guide walks you through creating a GitHub Personal Access Token (PAT) for A
---
## Why Archie Core Needs a GitHub Token
Archie Core uses the GitHub API to:
1. Poll assigned or labelled issues (`archie:queued`).
2. Update issue labels as tasks transition (`archie:working`, `archie:pr`, `archie:parked`).
3. Post status comments and emoji reactions.
@@ -34,17 +36,21 @@ Archie Core uses the GitHub API to:
Save your token using any of the following methods:
### Method A: Environment File (Default XDG Location)
Add your token to `${XDG_CONFIG_HOME:-~/.config}/archie/env`:
```bash
ARCHIE_GITHUB_TOKEN="ghp_YOUR_CLASSIC_TOKEN_HERE"
```
### Method B: Environment Variable in Current Shell
```bash
export ARCHIE_GITHUB_TOKEN="ghp_YOUR_CLASSIC_TOKEN_HERE"
```
### Method C: Directly in Configuration File (`~/.config/archie/config.toml`)
```toml
[forge]
type = "github"
+1 -1
View File
@@ -56,7 +56,7 @@ The same model supports other processes:
workflow with the repository's toolchain, validation steps, and pull request
as its output.
These are examples of workflows you can build. Their behavior comes from the
These are examples of workflows you can build. Their behaviour comes from the
workflow, tools, and access you configure.
## Agents equipped for their work
@@ -1,6 +1,6 @@
# Sam's message, verbatim (2026-09-05)
Source: chat message pasting an AWX forum post (AWX modernization series,
Source: chat message pasting an AWX forum post (AWX modernisation series,
"Refactoring AWX into a Pluggable, Service-Oriented Architecture") plus a
terminal transcript and a follow-up message including Ansible's
`ansible/playbook/task.py`. Preserved verbatim below for later reference.
@@ -10,25 +10,28 @@ reproduced, since this file is text-only.
---
[01:09:53] sam@helix /work/clones
> git clone https://github.com/ansible/ansible.git
Cloning into 'ansible'...
remote: Enumerating objects: 644471, done.
remote: Counting objects: 100% (21/21), done.
remote: Compressing objects: 100% (21/21), done.
remote: Total 644471 (delta 5), reused 2 (delta 0), pack-reused 644450 (from 3)
Receiving objects: 100% (644471/644471), 251.86 MiB | 9.60 MiB/s, done.
Resolving deltas: 100% (427812/427812), done.
[01:12:50] sam@helix /work/clones
> Cloning into 'ansible'...
> remote: Enumerating objects: 644471, done.
> remote: Counting objects: 100% (21/21), done.
> remote: Compressing objects: 100% (21/21), done.
> remote: Total 644471 (delta 5), reused 2 (delta 0), pack-reused 644450 (from 3)
> Receiving objects: 100% (644471/644471), 251.86 MiB | 9.60 MiB/s, done.
> Resolving deltas: 100% (427812/427812), done.
> [01:12:50] sam@helix /work/clones
> git clone https://github.com/ansible/awx.git
Cloning into 'awx'...
remote: Enumerating objects: 331428, done.
remote: Counting objects: 100% (399/399), done.
remote: Compressing objects: 100% (256/256), done.
remote: Total 331428 (delta 259), reused 153 (delta 143), pack-reused 331029 (from 3)
Receiving objects: 100% (331428/331428), 346.81 MiB | 12.94 MiB/s, done.
Resolving deltas: 100% (254095/254095), done.
[01:14:59] sam@helix /work/clones
> Cloning into 'awx'...
> remote: Enumerating objects: 331428, done.
> remote: Counting objects: 100% (399/399), done.
> remote: Compressing objects: 100% (256/256), done.
> remote: Total 331428 (delta 259), reused 153 (delta 143), pack-reused 331029 (from 3)
> Receiving objects: 100% (331428/331428), 346.81 MiB | 12.94 MiB/s, done.
> Resolving deltas: 100% (254095/254095), done.
> [01:14:59] sam@helix /work/clones
---
[Image #2]
Hi folks,
@@ -86,9 +89,9 @@ Links in this AWX update series
Refactoring AWX into a Pluggable, Service-Oriented Architecture (this post)
Upcoming changes to AWX Operator installation methods
AWX UI and credential types transitioning to the new pluggable architecture
AWX modernization: Moving forward
AWX modernization: Ansible UI
AWX modernization: Ansible Jewel
AWX modernisation: Moving forward
AWX modernisation: Ansible UI
AWX modernisation: Ansible Jewel
Useful links
@@ -96,7 +99,9 @@ Useful links
2024-07-01 Streamlining AWX Releases
The Forum: AWX topics
The Forum: Newsletter Category
---
Taking a look at this, How could we reframe ourselves to capture some of this market?
Archie is already a beast of a project, I think that it would be an excellent idea to think about cleaning up, simplifying, and unifying many of it's layers down to cleaner interfaces and even if it's starting at the most basic layers such as splitting the UI from the backend, turning the agent into a core runner, or even having 2 separate agent definitions, an AI agent and an agent runner. or. even better, an agent runner which utilises an open source project like Pi as the AI harness instead of having to code our own one.
@@ -106,18 +111,19 @@ I have Pi running now, with an immensely fast and capable model (deepseek-v4-fla
the idea of everything being pluggable services - making the entire solution modular, is exactly the goal I've had from the start. and it's already heading that way, but it's missing some guidance, assistance and care. I believe that a multi-agent system could help me get there, where I talk to an agent like claude, which spawns subagents to start implementation in isolation, and another agent monitors the work, assists, and carefully merges as the migration is in progress.
[01:23:10] sam@helix /work/apps/archie-core
> tree
(directory tree of archie-core omitted here -- see repository working tree at
the time of writing for the full listing; top-level shape was: AGENTS.md,
ARCHITECTURE.md, cmd/{archie-agent,archied,archie-playbooks}, deployments/,
docs/{architecture,archive,data,guides,prds,public}, examples/, extras/,
internal/{agentexec,app,channels,config,container,daemon,domain,eventbus,
events,forge,forgerpc,gate,gateway,indexing,infrastructure,installtype,
logging,memory,natsrpc,pairing,plugin,ratelimit,releaseannounce,
releaseupdate,secret,skill,skillscript,storage,store,storerpc,taskrun,
taskstate,tools,webhookguard,webui,worktree,worktreerpc,yaegiutil}, scripts/,
tools/, ui/{dist,src,test})
[01:23:12] sam@helix /work/apps/archie-core
> (directory tree of archie-core omitted here -- see repository working tree at
> the time of writing for the full listing; top-level shape was: AGENTS.md,
> ARCHITECTURE.md, cmd/{archie-agent,archied,archie-playbooks}, deployments/,
> docs/{architecture,archive,data,guides,prds,public}, examples/, extras/,
> internal/{agentexec,app,channels,config,container,daemon,domain,eventbus,
> events,forge,forgerpc,gate,gateway,indexing,infrastructure,installtype,
> logging,memory,natsrpc,pairing,plugin,ratelimit,releaseannounce,
> releaseupdate,secret,skill,skillscript,storage,store,storerpc,taskrun,
> taskstate,tools,webhookguard,webui,worktree,worktreerpc,yaegiutil}, scripts/,
> tools/, ui/{dist,src,test})
> [01:23:12] sam@helix /work/apps/archie-core
---
@@ -8,6 +8,7 @@ already have vs. what AWX/Ansible are describing." See
source material this is built from.
Two follow-on artifacts extend this line of exploration:
- Two Archify diagrams contrasting current vs. an ideal service-oriented
shape: `/work/artefacts/archie-core-current-state-archify.html` and
`/work/artefacts/archie-core-ideal-state-archify.html`. The current-state
@@ -35,26 +36,26 @@ stay two different tracks:
earlier and at a different grain (domain boundaries in one Go module +
NATS transport, not separate deployable services). The gap isn't "do we
need boundaries," it's "are the boundaries clean and are they enforced."
2. **Ansible's `Task`/module system** is a request for a *content* format:
2. **Ansible's `Task`/module system** is a request for a _content_ format:
let users write YAML tasks against a stable action vocabulary and have
Archie interpret them, the way Ansible interprets `- name: ... action:
module: args`. Archie has the skeleton of this already (EDA playbook
module: args`. Archie has the skeleton of this already (EDA playbook
engine, Module action position) but it's deliberately narrow today.
## AWX decomposition tree -> Archie's existing domains
| AWX node | Archie equivalent today | Location |
|---|---|---|
| Auth (RBAC / SSO / Policy-ABAC) | `internal/domain/binding` (task-to-identity/config binding) + `internal/policy` (cross-cutting, zero internal imports) + forge/channel auth (Telegram pairing, webhook HMAC) | `internal/domain/binding/`, `internal/policy/`, `internal/pairing/`, `internal/webhookguard/` |
| Communication / Inter-Service | NATS (`ARCHIE_TASKS` JetStream work queue, core-NATS RPC via `_INBOX.*`) | `internal/infrastructure/eventbus/nats/`, `internal/natsrpc/`, `internal/eventbus/` (contract, zero internal imports) |
| Execution (mesh) | Container pool running isolated agent worktrees over NATS, not a mesh of remote execution nodes (Ansible's Receptor equivalent doesn't exist -- Archie's "remote execution" is a Docker container, not a fleet) | `internal/container/pool.go`, `internal/agentexec/`, `internal/worktree/` |
| Runtime / Scheduler | `internal/domain/scheduling` (ticker contract) + cron-driven work intake | `internal/domain/scheduling/`, `internal/infrastructure/cronstore/` |
| Content / Projects | Nearest analogue is the **EDA playbook + module system** (below) plus `internal/skill` (skill catalog) -- Archie has no "project" = git-checkout-of-automation-content concept the way AWX does | `internal/domain/eda/playbook/`, `internal/domain/eda/module/`, `internal/skill/` |
| Telemetry | `internal/logging` (task sink, feed, registry) + `internal/events` | `internal/logging/`, `internal/events/` |
| Inventory | No direct equivalent. Closest is forge-side repo/identity config (`[[identities]]`, `internal/forge`) -- Archie targets one identity acting across a small set of forge repos, not a dynamic inventory of managed hosts | `internal/forge/`, `internal/config/` |
| Credentials | `internal/secret` (engine host, env/age/sops/vault engines) | `internal/secret/`, `internal/secret/enginehost/` |
| Subscription/Billing | No equivalent -- Archie is self-hosted, single-tenant; this AWX node doesn't map to anything and shouldn't | -- |
| UI split from backend | Already true: `internal/webui` (Go API server) serves a separately built SPA from `ui/dist` (Vite/React-ish, `ui/src/<feature>/`) over HTTP/SSE. There is no shared-process coupling to undo. | `internal/webui/`, `ui/src/` |
| AWX node | Archie equivalent today | Location |
| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| Auth (RBAC / SSO / Policy-ABAC) | `internal/domain/binding` (task-to-identity/config binding) + `internal/policy` (cross-cutting, zero internal imports) + forge/channel auth (Telegram pairing, webhook HMAC) | `internal/domain/binding/`, `internal/policy/`, `internal/pairing/`, `internal/webhookguard/` |
| Communication / Inter-Service | NATS (`ARCHIE_TASKS` JetStream work queue, core-NATS RPC via `_INBOX.*`) | `internal/infrastructure/eventbus/nats/`, `internal/natsrpc/`, `internal/eventbus/` (contract, zero internal imports) |
| Execution (mesh) | Container pool running isolated agent worktrees over NATS, not a mesh of remote execution nodes (Ansible's Receptor equivalent doesn't exist -- Archie's "remote execution" is a Docker container, not a fleet) | `internal/container/pool.go`, `internal/agentexec/`, `internal/worktree/` |
| Runtime / Scheduler | `internal/domain/scheduling` (ticker contract) + cron-driven work intake | `internal/domain/scheduling/`, `internal/infrastructure/cronstore/` |
| Content / Projects | Nearest analogue is the **EDA playbook + module system** (below) plus `internal/skill` (skill catalogue) -- Archie has no "project" = git-checkout-of-automation-content concept the way AWX does | `internal/domain/eda/playbook/`, `internal/domain/eda/module/`, `internal/skill/` |
| Telemetry | `internal/logging` (task sink, feed, registry) + `internal/events` | `internal/logging/`, `internal/events/` |
| Inventory | No direct equivalent. Closest is forge-side repo/identity config (`[[identities]]`, `internal/forge`) -- Archie targets one identity acting across a small set of forge repos, not a dynamic inventory of managed hosts | `internal/forge/`, `internal/config/` |
| Credentials | `internal/secret` (engine host, env/age/sops/vault engines) | `internal/secret/`, `internal/secret/enginehost/` |
| Subscription/Billing | No equivalent -- Archie is self-hosted, single-tenant; this AWX node doesn't map to anything and shouldn't | -- |
| UI split from backend | Already true: `internal/webui` (Go API server) serves a separately built SPA from `ui/dist` (Vite/React-ish, `ui/src/<feature>/`) over HTTP/SSE. There is no shared-process coupling to undo. | `internal/webui/`, `ui/src/` |
**Read on "reframe to capture market":** the honest gap next to AWX/AAP isn't
domain boundaries -- Archie already has those, arguably cleaner (env-enforced
@@ -74,16 +75,16 @@ Ansible's `task.py` is the runtime representation of one YAML task after
renders Jinja2. Archie's nearest shipped analogue is the EDA playbook engine,
which is **intentionally much narrower right now**:
| Ansible concept | Archie's current shape | Gap / what porting the idea would mean |
|---|---|---|
| `Task` (one step, `action` + `args`) | `playbook.Action` (`internal/domain/eda/playbook/playbook.go`) -- but **exactly one action per playbook, position must be `"workflow"`**, hard-rejected at load otherwise | Multi-action, multi-position playbooks are the literal ask ("use existing ansible playbooks... within archie") but are explicitly blocked today on unresolved execution-time gaps: mid-run failure semantics, idempotency for non-workflow actions (see the package doc comment and `docs/architecture/plugins-and-extensions.md`'s Event sources section). This is a known, named boundary, not an oversight. |
| Module (`ansible.builtin.*`, arbitrary Python) | `module.Kind` registry, Yaegi-interpreted `.go` files against a generated per-kind symbol table (`internal/domain/eda/module/`) -- **one shipped kind: `log`** | Ansible modules are dynamically loaded from a huge ecosystem; Archie's Module position is closed-registry-of-named-kinds, each with its own hand-written contract package (`internal/domain/eda/module/<kind>`). Adding "run a shell command," "call a forge API," "send a channel message" module kinds is possible under the existing pattern but each is new work, not automatic from having the mechanism. |
| `when:` conditional | `Action.When`, compiled CEL (`internal/domain/eda/expr`), not Jinja2 | Already decided: CEL over Jinja2 (open question 1 in the playbook engine PRD, resolved). Don't reopen. |
| `register` / fact accumulation across tasks | Not present -- `DispatchInput.Event` is a flat map exposed to CEL, there's no cross-action result chaining because there's only one action | Needed before multi-action playbooks are meaningful; tracked implicitly by the same "unresolved execution-time gaps" blocker above. |
| `loop` / `until`/`retries`/`delay` | Not present | Same -- follows from allowing more than one action per playbook. |
| Field-attribute inheritance (task -> block -> play) | No block/parent chain -- a playbook is flat: one `Trigger` + one `Action` | Ansible's play/block/role hierarchy has no Archie counterpart yet; would only matter once multi-action/roles are in scope. |
| Roles (reusable task bundles) | Nearest is `internal/skill` (skill catalog, frontmatter, tool defs) -- conceptually closer to Claude Skills than Ansible roles | Not a role system; skills are agent-facing capability bundles, not declarative task sequences. |
| Channel / Forge action positions | Named and designed but explicitly **not implemented** (`docs/architecture/plugins-and-extensions.md`: "Channel and Forge action positions are designed but not yet implemented," open investigation `archie-core-t2db.19`) | This is the direct next step toward "playbooks that do things," independent of the Ansible-compatibility idea. |
| Ansible concept | Archie's current shape | Gap / what porting the idea would mean |
| --------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `Task` (one step, `action` + `args`) | `playbook.Action` (`internal/domain/eda/playbook/playbook.go`) -- but **exactly one action per playbook, position must be `"workflow"`**, hard-rejected at load otherwise | Multi-action, multi-position playbooks are the literal ask ("use existing ansible playbooks... within archie") but are explicitly blocked today on unresolved execution-time gaps: mid-run failure semantics, idempotency for non-workflow actions (see the package doc comment and `docs/architecture/plugins-and-extensions.md`'s Event sources section). This is a known, named boundary, not an oversight. |
| Module (`ansible.builtin.*`, arbitrary Python) | `module.Kind` registry, Yaegi-interpreted `.go` files against a generated per-kind symbol table (`internal/domain/eda/module/`) -- **one shipped kind: `log`** | Ansible modules are dynamically loaded from a huge ecosystem; Archie's Module position is closed-registry-of-named-kinds, each with its own hand-written contract package (`internal/domain/eda/module/<kind>`). Adding "run a shell command," "call a forge API," "send a channel message" module kinds is possible under the existing pattern but each is new work, not automatic from having the mechanism. |
| `when:` conditional | `Action.When`, compiled CEL (`internal/domain/eda/expr`), not Jinja2 | Already decided: CEL over Jinja2 (open question 1 in the playbook engine PRD, resolved). Don't reopen. |
| `register` / fact accumulation across tasks | Not present -- `DispatchInput.Event` is a flat map exposed to CEL, there's no cross-action result chaining because there's only one action | Needed before multi-action playbooks are meaningful; tracked implicitly by the same "unresolved execution-time gaps" blocker above. |
| `loop` / `until`/`retries`/`delay` | Not present | Same -- follows from allowing more than one action per playbook. |
| Field-attribute inheritance (task -> block -> play) | No block/parent chain -- a playbook is flat: one `Trigger` + one `Action` | Ansible's play/block/role hierarchy has no Archie counterpart yet; would only matter once multi-action/roles are in scope. |
| Roles (reusable task bundles) | Nearest is `internal/skill` (skill catalogue, frontmatter, tool defs) -- conceptually closer to Claude Skills than Ansible roles | Not a role system; skills are agent-facing capability bundles, not declarative task sequences. |
| Channel / Forge action positions | Named and designed but explicitly **not implemented** (`docs/architecture/plugins-and-extensions.md`: "Channel and Forge action positions are designed but not yet implemented," open investigation `archie-core-t2db.19`) | This is the direct next step toward "playbooks that do things," independent of the Ansible-compatibility idea. |
**What porting real Ansible playbooks would actually require**, in rough
dependency order, if this becomes a real proposal later:
@@ -100,8 +101,8 @@ dependency order, if this becomes a real proposal later:
than "runs unmodified Ansible YAML" -- the latter also drags in Jinja2,
the module_utils Python runtime, and inventory/host-targeting concepts
Archie has no use for (Archie targets git repos and forge issues, not
fleets of managed hosts). Recommend treating "Ansible-*inspired* syntax,
not Ansible-*compatible* execution" as the working assumption if/when a
fleets of managed hosts). Recommend treating "Ansible-_inspired_ syntax,
not Ansible-_compatible_ execution" as the working assumption if/when a
PRD gets written -- it avoids importing Ansible's inventory/host model,
which doesn't fit Archie's single-repo-per-task execution shape at all.
@@ -26,7 +26,7 @@ Repositioning note: the PRD's own text floats a hypothesis ("Gateway
Service's `ChatContract` should exist before UI Service is extracted").
This document **confirms that hypothesis with code archaeology and
strengthens it**, and it is the single most important finding: archie-core's
Gateway is both the *stickiest* capability and the one with an already-
Gateway is both the _stickiest_ capability and the one with an already-
clean seam and already-isolated data. The generic "extract a leaf /
read-only thing first" advice does not apply here, and I say so with the
reason why.
@@ -35,13 +35,13 @@ reason why.
## Summary of the five recommendations
| # | Question | Recommendation (one line) |
|---|---|---|
| 1 | Extraction order | **Gateway Service first**, then State Store, then UI, then Messaging, then Execution/Runner/Scheduler, then Curator (optional) — preceded by an in-process "contract seams" phase (modular monolith) that is #2's real prerequisite. |
| 2 | Contract definition mechanism | **buf v2 + protoc-gen-go + protoc-gen-go-grpc** (grpc-go, not connect-go), one committed `proto/<service>/v1/` tree generating into `internal/contracts/<service>/v1/`, directory-versioned, `buf breaking` gated in `task check` and mirrored into CI. |
| 3 | In-process vs. out-of-process during migration | **Multiplexed in-process is the migration default**: one wire-safe Go contract interface per service, a local adapter and a generated gRPC client adapter, composition (not `ServiceRegistry`) picks which one, and the flip to a real process is a same-commit deletion of the in-process path — no dual-live window. |
| 4 | State Store's contract shape | **One State Store service owns a single SQLite file behind narrow typed contracts** (the existing `internal/store` split already does the ownership; the gap is enforcement). No physical database-per-service at this scale, and no distributed-transaction problem, because there is still one store. Gateway keeps its own already-separate session SQLite. |
| 5 | Helm chart / Operator scoping | **Three charts** (a `library` chart of the shared contract templates, one `archie` chart for the 7 core services, one `archie-curator` chart + a Curator Operator) — and the smallest first milestone is a **single Curator CR that the Operator reconciles into a Deployment + Service, with Gateway resolving `curator` via the `ServiceRegistry`**. |
| # | Question | Recommendation (one line) |
| --- | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1 | Extraction order | **Gateway Service first**, then State Store, then UI, then Messaging, then Execution/Runner/Scheduler, then Curator (optional) — preceded by an in-process "contract seams" phase (modular monolith) that is #2's real prerequisite. |
| 2 | Contract definition mechanism | **buf v2 + protoc-gen-go + protoc-gen-go-grpc** (grpc-go, not connect-go), one committed `proto/<service>/v1/` tree generating into `internal/contracts/<service>/v1/`, directory-versioned, `buf breaking` gated in `task check` and mirrored into CI. |
| 3 | In-process vs. out-of-process during migration | **Multiplexed in-process is the migration default**: one wire-safe Go contract interface per service, a local adapter and a generated gRPC client adapter, composition (not `ServiceRegistry`) picks which one, and the flip to a real process is a same-commit deletion of the in-process path — no dual-live window. |
| 4 | State Store's contract shape | **One State Store service owns a single SQLite file behind narrow typed contracts** (the existing `internal/store` split already does the ownership; the gap is enforcement). No physical database-per-service at this scale, and no distributed-transaction problem, because there is still one store. Gateway keeps its own already-separate session SQLite. |
| 5 | Helm chart / Operator scoping | **Three charts** (a `library` chart of the shared contract templates, one `archie` chart for the 7 core services, one `archie-curator` chart + a Curator Operator) — and the smallest first milestone is a **single Curator CR that the Operator reconciles into a Deployment + Service, with Gateway resolving `curator` via the `ServiceRegistry`**. |
---
@@ -67,10 +67,10 @@ The PRD's three cited couplings are real; I re-checked the call sites:
direct route to the gateway today — it must detour through a UI HTTP
handler to apply a pause/resume/abandon action.
2. **UI reaches directly into gateway internals.**
`internal/webui/api_chat.go`'s `ChatService` is *literally* `Router
*gateway.Router`, `Sessions gateway.SessionStore`, `Turns
*gateway.Turns` plus `Models gateway.ModelManager` and `Personas
*gateway.PersonaRegistry`, and it calls `chat.Sessions.(gateway.TurnHistory)`
`internal/webui/api_chat.go`'s `ChatService` is _literally_ `Router
*gateway.Router`, `Sessions gateway.SessionStore`, `Turns
*gateway.Turns` plus `Models gateway.ModelManager` and `Personas
*gateway.PersonaRegistry`, and it calls `chat.Sessions.(gateway.TurnHistory)`
at line 198 and `chat.Router.Route`/`ResolveSessionKey` at 256/261.
This is not "a UI calling a Gateway API" — it is the UI holding the
Gateway's internal objects and calling their methods in-process.
@@ -87,22 +87,22 @@ Two further facts the PRD does not foreground but that decide the order:
(`StatusReader`, `TaskCreator`, `TaskLister`, `TaskController`,
`AgentReader`) that `internal/app/archied` adapts. This is a ready seam.
- **The Gateway already owns an isolated session store.**
`internal/gateway/session_store_sqlite.go` is a *separate* SQLite DB
`internal/gateway/session_store_sqlite.go` is a _separate_ SQLite DB
(`OpenSQLiteSessionStore`, own `sqliteSessionSchema`) from
`internal/store`. Chat session/turn/message data is **already** separate
from task/work-intake data.
### What the research says about sequencing
The canonical guidance is Fowler / Dehghani's *How to break a Monolith
into Microservices*. Its explicit sequencing principles are: **warm up
The canonical guidance is Fowler / Dehghani's _How to break a Monolith
into Microservices_. Its explicit sequencing principles are: **warm up
with a simple and fairly decoupled capability**; **minimise dependency
back to the monolith**; **split sticky capabilities early**; **decouple
vertically and release the data early**; **decouple what is important to
the business and changes frequently**; **go macro first, then micro**;
**migrate in atomic evolutionary steps**. The popular-strangler-fig
commentary (YuSMP, Md Sanwar Hossain, CloudRPS) adds a pragmatic
variant: improve the monolith into a *modular monolith* first, create a
variant: improve the monolith into a _modular monolith_ first, create a
routing facade, extract the **low-coupling / leaf / read-heavy** context
first, defer auth and the core "sticky" engines to later, and treat the
first extraction as an **operations dry-run** (build pipeline, contract
@@ -136,7 +136,7 @@ So the deciding question is not "which is the safest to cut first?" It is
stands up the product's primary contract?" The answer is the Gateway.
This **confirms** the PRD hypothesis, and adds a reason the PRD did not
state: the Gateway is extractable *now*, on its own, with zero store
state: the Gateway is extractable _now_, on its own, with zero store
migration, because it is already store-decoupled and already owns its
session DB. UI is **not** extractable first — it is trapped behind the
Gateway's internals and can only become a thin client once
@@ -217,7 +217,7 @@ Install as a Gateway plugin (its current shape is already a contract /
registrar / registry family) and prove the latest-order discovery path +
the optional-service `NotInstalled` semantic. This is deliberately last:
it is the proof-of-optionality and the Q5 exercise, not a load-bearing
first step. (The K8s Operator to *deploy* it is Q5's concern and can be
first step. (The K8s Operator to _deploy_ it is Q5's concern and can be
built on the Q1 timeline once the base chart exists.)
### What this doesn't settle
@@ -229,9 +229,9 @@ built on the Q1 timeline once the base chart exists.)
collapses into Phase 1 for the Gateway.
- **Whether Gateway should also host a "chat gateway" that owns the
Session Store contract** vs. delegating chat state to a future concern.
Decided *not* to move session data into State Store here — it is already
Decided _not_ to move session data into State Store here — it is already
isolated and Gateway-owned; moving it would be churn with no benefit.
- **Exact cadence / whether Curator can be extracted earlier.** It *can*,
- **Exact cadence / whether Curator can be extracted earlier.** It _can_,
but only as the operator/optionality exercise; keeping it last avoids
spending the "warm-up learning budget" on an optional component when the
base services are not yet on the contract.
@@ -239,6 +239,7 @@ built on the Q1 timeline once the base chart exists.)
---
<a id="2"></a>
## Question #2 — Contract definition mechanism
### The question
@@ -278,7 +279,7 @@ Helm chart service names). Generated Go is **committed** at
(`go_package_prefix`) plus `paths=source_relative`. This satisfies
`docs/architecture/dependencies-and-contracts.md:55`'s "Wire contracts and
generation" rule — wire contracts are partitioned per owning domain, never
centralized in a generic schema package.
centralised in a generic schema package.
### Versioning: directory versioning, enforced by `buf breaking`
@@ -327,6 +328,7 @@ local `main` ref to diff against; CI needs `fetch-depth: 0` or an explicit
---
<a id="3"></a>
## Question #3 — In-process vs. out-of-process during migration
### The question
@@ -356,7 +358,7 @@ architecture-wide.
the interface. If a type can't become a proto message, it can't appear
in the contract signature.
2. **Two adapters per contract.** A **local adapter** (in-process, calls
straight through, zero serialization — not a test fake, a real
straight through, zero serialisation — not a test fake, a real
production adapter) and a **generated gRPC client adapter**. Both
satisfy the same interface, verified with a compile-time assertion in
the existing repo idiom: `var _ store.WorkflowStore = (*Client)(nil)`
@@ -377,7 +379,7 @@ architecture-wide.
`mode = "inproc" | "remote"` config value, defaulting to `inproc`.
4. **Per-contract conformance suite.** Reuse the existing conformance-test
idiom — `runSessionStoreSuite(t, newStore func(t *testing.T)
SessionStore)` at `internal/gateway/sessionstore_conformance_test.go:65`
SessionStore)` at `internal/gateway/sessionstore_conformance_test.go:65`
— and run it against both the local adapter and a real gRPC server over
`bufconn`. This is the "always test the wire shape" discipline, kept for
tests only; production traffic in `inproc` mode never touches gRPC.
@@ -436,7 +438,7 @@ was needed — Q1 already anticipated exactly this shape.
- `internal/servicediscovery/servicediscovery.go:8-14,71-81` —
`ErrNotInstalled` semantics and the `ServiceRegistry` interface.
- `internal/storerpc/storerpc.go:136` — `var _ store.WorkflowStore =
(*Client)(nil)`, the compile-time contract-conformance idiom reused for
(*Client)(nil)`, the compile-time contract-conformance idiom reused for
the local/remote adapter pair; `internal/forgerpc`, `internal/worktreerpc`,
and `internal/infrastructure/agenttransport/nats/transport.go:101,111`
as the existing one-contract-two-transports precedent in production.
@@ -445,8 +447,8 @@ was needed — Q1 already anticipated exactly this shape.
local-vs-remote adapter testing.
- `internal/webui/api_chat.go:22-26` — `ChatService`'s struct fields
(`Router *gateway.Router`, `Sessions gateway.SessionStore`, `Turns
*gateway.Turns`, `Models gateway.ModelManager`, `Personas
*gateway.PersonaRegistry`) — the concrete seam Q2/Q3's `ChatContract`
*gateway.Turns`, `Models gateway.ModelManager`, `Personas
*gateway.PersonaRegistry`) — the concrete seam Q2/Q3's `ChatContract`
needs to cross.
- `internal/installtype/installtype.go` — precedent that deployment-shape
facts are stated config, never runtime-probed.
@@ -467,16 +469,16 @@ was needed — Q1 already anticipated exactly this shape.
`proto/gateway/v1/chat.proto` (package `gateway.v1`, service
`ChatService`) passed once request/response types followed the
`XRequest`/`XResponse` naming buf's STANDARD lint enforces. `buf
generate` (v2, managed `go_package_prefix`, `paths=source_relative`)
generate` (v2, managed `go_package_prefix`, `paths=source_relative`)
produced `chat.pb.go` (206 lines) and `chat_grpc.pb.go` (121 lines),
which compiled cleanly against `google.golang.org/grpc v1.83.2` in a
scratch module. `buf breaking --against
'.git#branch=main,subdir=.'` after deleting an RPC and renaming a field
'.git#branch=main,subdir=.'` after deleting an RPC and renaming a field
correctly reported "Previously present RPC Send deleted," "field 2 user
deleted," "field 3 changed name," exit 100 — confirming the mechanism
works against a real git ref. A parallel connect-go run (installing
`protoc-gen-connect-go` v1.19.1; note the `github.com/connectrpc/
connect-go` module path is dead, use `connectrpc.com/connect`) generated
connect-go` module path is dead, use `connectrpc.com/connect`) generated
a sibling `net/http`-based package, confirming the resolver-plumbing gap
cited above. `gofumpt -l` on the freshly generated output was clean, so
`task fmt`'s `gofumpt -w .` won't fight regenerated code.
@@ -524,8 +526,8 @@ The research (microservices.io, Microsoft Learn data-sovereignty, AWS
Prescriptive Guidance) is emphatic that the database-per-service pattern is
**about ownership and enforcement, not about physically provisioning one
database cluster per service.** microservices.io names three ways to keep a
service's data private — *private-tables-per-service*,
*schema-per-service*, and *database-server-per-service* — and says the
service's data private — _private-tables-per-service_,
_schema-per-service_, and _database-server-per-service_ — and says the
first two have "the lowest overhead," and that a shared MySQL instance with
per-service logical databases and per-service credentials is a legitimate
instance of the pattern. Microsoft's guidance and the ownership-over-
@@ -540,7 +542,7 @@ The decisive variable everywhere is **team topology**, not technology.
DevStarSJ's 2026 comparison gives the rule of thumb: 1–5 engineers →
shared DB (monolith is fine); 5–20 → shared DB with strict ownership
boundaries; 20–50 → hybrid; 50+ → database per service. The argument,
across all sources, is that database-per-service's *benefits* are team
across all sources, is that database-per-service's _benefits_ are team
autonomy, independent deploy cadence, and failure blast-radius isolation —
three things that are **largely absent for a solo maintainer**. You still
pay the full "distributed data tax" (no cross-service joins → sagas or
@@ -563,9 +565,9 @@ its own already-separate session SQLite (it is Gateway-private chat state
and already isolated; moving it is churn).
This is "less isolation, less migration risk" chosen deliberately — it is
the *honest* choice for a solo maintainer per the team-topology rule of
the _honest_ choice for a solo maintainer per the team-topology rule of
thumb, and it matches the store's existing interface decomposition (the
ownership is already correct — the *enforcement* is the gap: webui and
ownership is already correct — the _enforcement_ is the gap: webui and
workflow import `internal/store` directly across a would-be service
boundary).
@@ -578,7 +580,7 @@ would introduce the distributed-data tax — cross-store joins for the
dashboard's combined task/event/capture views, sagas for intake→workflow
transitions, m×n data-store operations — with no corresponding autonomy
gain for a single maintainer. It is also the single most common source of
a *distributed monolith*, which the sources call the failure mode to
a _distributed monolith_, which the sources call the failure mode to
avoid.
### Concrete migration path from the current single SQLite store
@@ -623,9 +625,9 @@ avoid.
recommendation is to not pre-split.
- **Whether the Gateway's session store stays Gateway-owned or moves to
State Store.** Decided: stays Gateway-owned (already isolated, high
-frequency chat state; moving it has no benefit).
-frequency chat state; moving it has no benefit).
- **The exact gRPC contract schema / versioning.** That is #2's
mechanism. The contract *surface* is decided here; the wire schema is
mechanism. The contract _surface_ is decided here; the wire schema is
not.
- **Migration of the `storerpc` NATS path.** The `archie-agent` container
still calls `storerpc` today. Under the PRD the Execution/Runner
@@ -672,38 +674,38 @@ disappears. Two facts shape the chart design:
### Decision: three charts (library + core services + Curator-with-Operator)
- **`archie-library`** — a Helm **library chart** (`type: library`,
only `_*.tpl` files). Holds the shared resource templates: the
Deployment template, the Service template, readiness/liveness probe
helper, container-port naming, the label/selector block
(`app.kubernetes.io/name`, `instance`, `managed-by`, `component`), and
the `ServiceRegistry`-relevant named ports (`grpc`, `http`, `ssr`,
`nats`). This keeps the per-service charts declarative and consistent.
only `_*.tpl` files). Holds the shared resource templates: the
Deployment template, the Service template, readiness/liveness probe
helper, container-port naming, the label/selector block
(`app.kubernetes.io/name`, `instance`, `managed-by`, `component`), and
the `ServiceRegistry`-relevant named ports (`grpc`, `http`, `ssr`,
`nats`). This keeps the per-service charts declarative and consistent.
- **`archie`** — the chart for the **7 core services**: UI, Gateway,
Messaging, Scheduler, Execution Environment, Runner, State Store. One
`values.yaml` with a `services:` map; each service resolves to a small
template from the library chart. It also lands the base **ConfigMaps
/ Secrets** that replace `config.toml` (a phased concern flagged in the
discovery research — the chart should *reference* config as a separate
concern, not block on relocating it). It must make each service's
`Service` a **named-port** Service so gRPC resolution works, and each
a **ClusterIP** Service (no headless needed for the base sync path; a
headless/SRV Service is an optional addition the Gateway resolver can
consume but is not required for the DNS A-record flow).
Messaging, Scheduler, Execution Environment, Runner, State Store. One
`values.yaml` with a `services:` map; each service resolves to a small
template from the library chart. It also lands the base **ConfigMaps
/ Secrets** that replace `config.toml` (a phased concern flagged in the
discovery research — the chart should _reference_ config as a separate
concern, not block on relocating it). It must make each service's
`Service` a **named-port** Service so gRPC resolution works, and each
a **ClusterIP** Service (no headless needed for the base sync path; a
headless/SRV Service is an optional addition the Gateway resolver can
consume but is not required for the DNS A-record flow).
- **`archie-curator`** — the chart for the **optional Curator**, plus the
**Curator Operator**. Operator chart installs the CRD, the
controller Deployment (with the ServiceAccount / ClusterRole /
ClusterRoleBinding the reconciler needs), and the RBAC markers; the
Curator chart installs the sample `Curator` CR. Because Curator is
optional, this chart is **not** deployed by default with `archie` — the
whole point is that a customer installs it later and the fleet
auto-aligns.
**Curator Operator**. Operator chart installs the CRD, the
controller Deployment (with the ServiceAccount / ClusterRole /
ClusterRoleBinding the reconciler needs), and the RBAC markers; the
Curator chart installs the sample `Curator` CR. Because Curator is
optional, this chart is **not** deployed by default with `archie` — the
whole point is that a customer installs it later and the fleet
auto-aligns.
### What the Curator Operator's reconcile loop actually needs to do
This is a textbook Kubebuilder / Operator-SDK controller. The reconcile
loop (per the Kubebuilder book and the multi-resource reconciliation
pattern) is **level-triggered, not status-triggered**: it must always
converge the *whole* desired set, never react to a specific event. Per
converge the _whole_ desired set, never react to a specific event. Per
`Curator` CR, the loop:
1. **Fetch the CR.** `r.Get(ctx, req.NamespacedName, &curator)`; treat
@@ -828,7 +830,7 @@ from here, as the task asks):
identical; the choice of kubebuilder scaffolding vs. Operator SDK is a
tooling preference that does not change the M1 scope. Kubebuilder is the
documented norm and is assumed here.
- **Whether the Operator should manage the *base* services too.** The
- **Whether the Operator should manage the _base_ services too.** The
first milestone only has an Operator for Curator (the optional one).
A "fleet Operator" that reconciles all services is a larger, later
idea; the base services can be plain chart templates for now.
@@ -837,19 +839,19 @@ from here, as the task asks):
## Sources (primary, fetched during this pass)
- Zhamak Dehghani, *How to break a Monolith into Microservices* (Martin
- Zhamak Dehghani, _How to break a Monolith into Microservices_ (Martin
Fowler site) — https://martinfowler.com/articles/break-monolith-into-microservices.html
- microservices.io, *Pattern: Database per service* —
- microservices.io, _Pattern: Database per service_ —
https://microservices.io/patterns/data/database-per-service.html
- Microsoft Learn, *.NET microservices: Data sovereignty per microservice* —
- Microsoft Learn, _.NET microservices: Data sovereignty per microservice_ —
https://learn.microsoft.com/en-us/dotnet/architecture/microservices/architect-microservice-container-applications/data-sovereignty-per-microservice
- Kubebuilder Book, *Getting Started* —
- Kubebuilder Book, _Getting Started_ —
https://www.kubebuilder.io/getting-started.html
- Kubebuilder Book, *Resources Managed by the Operator* —
- Kubebuilder Book, _Resources Managed by the Operator_ —
https://book-v3.book.kubebuilder.io/reference/watching-resources/operator-managed
- Kubebuilder Book, *Owned Resources* —
- Kubebuilder Book, _Owned Resources_ —
https://kubebuilder.io/reference/watching-resources/secondary-owned-resources
- Helm, *Charts* — https://helm.sh/docs/topics/charts/
- Helm, _Charts_ — https://helm.sh/docs/topics/charts/
- (Supporting synthesis from the deep-search lanes: YuSMP strangler-fig
guide, Md Sanwar Hossain strangler-fig, CloudRPS strangler-fig,
Mobisoft first-microservice-to-extract, StackAuthority
@@ -2,160 +2,155 @@
Status: exploratory research, not a settled decision. This backs the "ideal
state" service-oriented sketch in
[[module-reference-awx-decomposition-vs-archie]] and its two Archify
diagrams (`/work/artefacts/archie-core-current-state-archify.html`,
[[module-reference-awx-decomposition-vs-archie]] and its two Archify diagrams
(`/work/artefacts/archie-core-current-state-archify.html`,
`/work/artefacts/archie-core-ideal-state-archify.html`). Nothing here commits
the codebase to anything; if the service decomposition itself gets approved,
this is the input to the actual `docs/architecture/migration-decisions.md`
entry and/or a `docs/prds/` design doc, not a substitute for either.
this is the input to the actual `docs/architecture/migration-decisions.md` entry
and/or a `docs/prds/` design doc, not a substitute for either.
Produced by an external research pass (Pi subagents plus supervisor-run
`deep_search_exa` queries against primary sources: NATS discovery, K8s-native
discovery, Consul operational footprint, gRPC/xDS/mesh weight). The K8s lane
detached mid-flight and was recovered via supervisor reply, covered from
fetched Kubernetes docs (Service/EndpointSlice/CoreDNS/Operator + k3s Helm).
Reproduced here close to verbatim as the record of that research; light
formatting only.
detached mid-flight and was recovered via supervisor reply, covered from fetched
Kubernetes docs (Service/EndpointSlice/CoreDNS/Operator + k3s Helm). Reproduced
here close to verbatim as the record of that research; light formatting only.
Business framing this research was scoped against, per Sam (2026-09-05): the
decomposition is being evaluated as a real product distribution strategy —
possibly sold self-hosted, possibly as a managed/hosted offering (the
RHEL/Ansible Automation Platform model: same product, sold both ways), not
ruled to either shape. Evaluate infrastructure choices on technical merit for
that audience, not through the lens of Sam's own homelab deployment
preferences (see `feedback_dont_project_homelab_prefs_onto_product` in
Claude's project memory). "Cost" in this document means operational
complexity, never dollar price — pricing and SaaS-plan questions are
explicitly out of scope here.
RHEL/Ansible Automation Platform model: same product, sold both ways), not ruled
to either shape. Evaluate infrastructure choices on technical merit for that
audience, not through the lens of Sam's own homelab deployment preferences (see
`feedback_dont_project_homelab_prefs_onto_product` in Claude's project memory).
"Cost" in this document means operational complexity, never dollar price —
pricing and SaaS-plan questions are explicitly out of scope here.
---
## 1. Candidate mechanisms
| # | Mechanism | Who stands it up | Health-aware endpoints? | "Install → auto-join" mechanics | Single-host fit | Multi-host fit |
|---|---|---|---|---|---|---|
| 1 | **Kubernetes-native** (Service + EndpointSlice + CoreDNS), delivered via Helm chart + Operator, on k3s (single-node) or a real cluster | A whole (even if small) control plane: api-server, etcd, scheduler, controller-manager, CoreDNS, kube-proxy. k3s packages this into a ~one-command install | Yes, free — readiness probes gate which pods land in an EndpointSlice | Deploy/helm install a Service (or an Operator reconciles a CR) → CoreDNS serves the name → existing services dial it | Strong (k3s is ~½ GB RAM) | Good (real cluster, or k3s server+agents) |
| 2 | **NATS-based discovery** (micro `$SRV` announce + JetStream KV registry) | NATS broker — already a hard dependency, so nothing new to stand up | No — only connection liveness; you write heartbeat+TTL for KV | Service connects to the bus on start, publishes/announces → peers observe the join | Excellent | Workable but requires a real NATS cluster / leaf nodes (TLS/NKey/JWT weight) |
| 3 | **Consul** (registry + agent + DNS) | A second control plane: 3–5 Raft servers + a client agent on every node | Yes (TCP/HTTP/gRPC/TTL) | Agent registers with server; peers resolve via Consul DNS | OK (one server + agents) | Good (multi-DC, WAN federation) but per-node agent burden |
| 4 | **etcd** (discovery substrate) | A Raft KV cluster you operate | Not natively — you own catalog/health semantics | Lease registration + prefix watch | OK (embeddable) | Good (R3 replication) but you build the semantics |
| 5 | **gRPC xDS / service mesh** (Istio/Linkerd/Traffic Director, proxyless gRPC) | A control plane (+ per-pod sidecar if mesh) | Yes (xDS health) | Register with control plane → EDS pushed to subscribed clients | Heavy / overkill | Heavy; K8s-first; sidecar cost (~0.2 vCPU + 60 MB/pod @1k rps in Istio-sidecar-land) |
| 6 | **DNS-SRV / mDNS** | Nothing new | No native health; TTL caching breaks fast failover | Register a record | mDNS yes (but link-local); DNS-SRV needs a resolver you control | mDNS fails at the first router/VLAN; DNS-SRV needs your own resolver + a custom gRPC resolver (grpc-go doesn't consume SRV natively) |
| # | Mechanism | Who stands it up | Health-aware endpoints? | "Install → auto-join" mechanics | Single-host fit | Multi-host fit |
| --- | -------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
| 1 | **Kubernetes-native** (Service + EndpointSlice + CoreDNS), delivered via Helm chart + Operator, on k3s (single-node) or a real cluster | A whole (even if small) control plane: api-server, etcd, scheduler, controller-manager, CoreDNS, kube-proxy. k3s packages this into a ~one-command install | Yes, free — readiness probes gate which pods land in an EndpointSlice | Deploy/helm install a Service (or an Operator reconciles a CR) → CoreDNS serves the name → existing services dial it | Strong (k3s is ~½ GB RAM) | Good (real cluster, or k3s server+agents) |
| 2 | **NATS-based discovery** (micro `$SRV` announce + JetStream KV registry) | NATS broker — already a hard dependency, so nothing new to stand up | No — only connection liveness; you write heartbeat+TTL for KV | Service connects to the bus on start, publishes/announces → peers observe the join | Excellent | Workable but requires a real NATS cluster / leaf nodes (TLS/NKey/JWT weight) |
| 3 | **Consul** (registry + agent + DNS) | A second control plane: 3–5 Raft servers + a client agent on every node | Yes (TCP/HTTP/gRPC/TTL) | Agent registers with server; peers resolve via Consul DNS | OK (one server + agents) | Good (multi-DC, WAN federation) but per-node agent burden |
| 4 | **etcd** (discovery substrate) | A Raft KV cluster you operate | Not natively — you own catalogue/health semantics | Lease registration + prefix watch | OK (embeddable) | Good (R3 replication) but you build the semantics |
| 5 | **gRPC xDS / service mesh** (Istio/Linkerd/Traffic Director, proxyless gRPC) | A control plane (+ per-pod sidecar if mesh) | Yes (xDS health) | Register with control plane → EDS pushed to subscribed clients | Heavy / overkill | Heavy; K8s-first; sidecar cost (~0.2 vCPU + 60 MB/pod @1k rps in Istio-sidecar-land) |
| 6 | **DNS-SRV / mDNS** | Nothing new | No native health; TTL caching breaks fast failover | Register a record | mDNS yes (but link-local); DNS-SRV needs a resolver you control | mDNS fails at the first router/VLAN; DNS-SRV needs your own resolver + a custom gRPC resolver (grpc-go doesn't consume SRV natively) |
## 2. What this narrows to
Six candidates surfaced, but the field collapses to two real finalists once
three filters specific to archie-core apply: (a) the fleet is ~7 Go
services, (b) a gRPC-sync + NATS-async mix is already the working
assumption, and (c) the defining requirement is "customer installs a
service, the fleet auto-aligns, no redeploy/reconfig."
three filters specific to archie-core apply: (a) the fleet is ~7 Go services,
(b) a gRPC-sync + NATS-async mix is already the working assumption, and (c) the
defining requirement is "customer installs a service, the fleet auto-aligns, no
redeploy/reconfig."
- **Consul / etcd are dominated by K8s-native.** Consul adds a whole second
control plane (Raft server quorum + a client agent on every node you don't
control) — redundant if the fleet lives in K8s (buying a second control
plane to replace one you already have), heavy if it doesn't. etcd makes
you own catalog + health semantics, which is exactly what K8s-native and
NATS each give for free in different ways. Both remain viable, just not
better.
- **gRPC xDS / service mesh is the wrong tool at this scale.** Field
consensus (multiple 2026 sources): don't adopt a mesh until 20+ services;
archie-core is at ~7, single-language (Go), with resilience logic already
in Go. xDS/proxyless-gRPC earns its keep only with locality-aware routing
/ canary / circuit-breaking across hosts, which nothing here signals. The
durable takeaway isn't "use xDS"; it's that gRPC is resolver plumbing, not
a registry — whatever registry gets picked feeds gRPC through a resolver
(DNS resolver, or a custom one).
control) — redundant if the fleet lives in K8s (buying a second control plane
to replace one you already have), heavy if it doesn't. etcd makes you own
catalogue + health semantics, which is exactly what K8s-native and NATS each
give for free in different ways. Both remain viable, just not better.
- **gRPC xDS / service mesh is the wrong tool at this scale.** Field consensus
(multiple 2026 sources): don't adopt a mesh until 20+ services; archie-core is
at ~7, single-language (Go), with resilience logic already in Go.
xDS/proxyless-gRPC earns its keep only with locality-aware routing / canary /
circuit-breaking across hosts, which nothing here signals. The durable
takeaway isn't "use xDS"; it's that gRPC is resolver plumbing, not a registry
— whatever registry gets picked feeds gRPC through a resolver (DNS resolver,
or a custom one).
- **DNS-SRV / mDNS are insufficient.** mDNS is link-local (dies at
router/VLAN/container boundaries), so it can't span routed multi-host;
DNS-SRV has no health and grpc-go's default resolver doesn't consume SRV
natively anyway.
router/VLAN/container boundaries), so it can't span routed multi-host; DNS-SRV
has no health and grpc-go's default resolver doesn't consume SRV natively
anyway.
So the genuine decision is K8s-native vs. reuse-NATS.
## 3. K8s-native vs. NATS: an honest weigh
**Where K8s-native wins decisively:**
- The only mechanism that delivers "install a service → the fleet
auto-aligns" at the infrastructure layer, with health-filtered endpoints,
where the customer's install is a straightforward "apply a Deployment +
Service" (or a Helm chart, or an Operator reconciling a CR). This is the
single hardest, most product-defining requirement, and K8s solves it
natively.
- Delivers, as a side effect, almost everything a 7-service fleet needs
anyway: health (readiness/liveness probes), orchestration
(restart/scale), config (ConfigMaps/Secrets), rollouts, clean external
exposure (Ingress/Gateway). Not extra weight for its own sake — buying
pieces that would otherwise be hand-built.
- The hosted/managed path is free. If the product is ever run for customers
(the "sold both ways" shape kept open above), K8s runs anyway.
K8s-native discovery makes self-hosted and hosted deployments use
identical discovery semantics — one codebase, no divergence. This is the
RHEL/Ansible Automation Platform lesson: same product, sold both ways,
same internal architecture.
- The only mechanism that delivers "install a service → the fleet auto-aligns"
at the infrastructure layer, with health-filtered endpoints, where the
customer's install is a straightforward "apply a Deployment + Service" (or a
Helm chart, or an Operator reconciling a CR). This is the single hardest, most
product-defining requirement, and K8s solves it natively.
- Delivers, as a side effect, almost everything a 7-service fleet needs anyway:
health (readiness/liveness probes), orchestration (restart/scale), config
(ConfigMaps/Secrets), rollouts, clean external exposure (Ingress/Gateway). Not
extra weight for its own sake — buying pieces that would otherwise be
hand-built.
- The hosted/managed path is free. If the product is ever run for customers (the
"sold both ways" shape kept open above), K8s runs anyway. K8s-native discovery
makes self-hosted and hosted deployments use identical discovery semantics —
one codebase, no divergence. This is the RHEL/Ansible Automation Platform
lesson: same product, sold both ways, same internal architecture.
**Where NATS wins:**
- Zero new infrastructure. NATS is already a hard dependency and already in
the deployment (embedded, or the existing `docker-nats-stack.toml`). For
the lowest-end single-host customer who wants "one binary dropped on a
box," NATS discovery means no cluster, no K8s — just the bus already
running.
- Genuinely idiomatic: a service connects, announces via the micro `$SRV`
tree (PING/INFO/STATS) or a JetStream KV record, and disappears the
moment its connection closes. Re-join = "open the connection and
publish." No per-service config, no sidecar, no hand registration.
- Zero new infrastructure. NATS is already a hard dependency and already in the
deployment (embedded, or the existing `docker-nats-stack.toml`). For the
lowest-end single-host customer who wants "one binary dropped on a box," NATS
discovery means no cluster, no K8s — just the bus already running.
- Genuinely idiomatic: a service connects, announces via the micro `$SRV` tree
(PING/INFO/STATS) or a JetStream KV record, and disappears the moment its
connection closes. Re-join = "open the connection and publish." No per-service
config, no sidecar, no hand registration.
**Where NATS genuinely falls short for this product:**
1. It's a NATS service locator, not a gRPC endpoint registry. The `$SRV`
framework and the KV bucket hand you names/responders, not `host:port`
gRPC endpoints. Each service's `host:port` has to be carried in
metadata/KV and a custom gRPC resolver hand-written; gRPC's built-in
resolver/health model won't "just work." Real integration work owned in
the sync path — now the product's primary contract.
2. No native health. NATS has no last-will or probe. Heartbeat+TTL (KV)
must be implemented to distinguish "installed but unhealthy" from "not
installed," and stale entries are your problem. K8s readiness probes do
this for free.
3. Discovery is coupled to broker availability. If NATS is down, every
service looks down (a hard SPOF unless NATS is itself clustered).
Multi-host is where the cost shows: a real NATS cluster or leaf nodes,
with TLS/NKey/JWT credential management — operator weight, not "just
works."
The balance: NATS is a legitimate fallback and a genuine part of the
answer; it is not a substitute for the registry that resolves gRPC
endpoints with health. If the product's sync path is gRPC, the registry
serving it should be K8s-native (DNS → resolver, headless-Service SRV for
ports, EndpointSlice health) rather than a hand-built NATS registry.
1. It's a NATS service locator, not a gRPC endpoint registry. The `$SRV`
framework and the KV bucket hand you names/responders, not `host:port` gRPC
endpoints. Each service's `host:port` has to be carried in metadata/KV and a
custom gRPC resolver hand-written; gRPC's built-in resolver/health model
won't "just work." Real integration work owned in the sync path — now the
product's primary contract.
2. No native health. NATS has no last-will or probe. Heartbeat+TTL (KV) must be
implemented to distinguish "installed but unhealthy" from "not installed,"
and stale entries are your problem. K8s readiness probes do this for free.
3. Discovery is coupled to broker availability. If NATS is down, every service
looks down (a hard SPOF unless NATS is itself clustered). Multi-host is where
the cost shows: a real NATS cluster or leaf nodes, with TLS/NKey/JWT
credential management — operator weight, not "just works."
The balance: NATS is a legitimate fallback and a genuine part of the answer; it
is not a substitute for the registry that resolves gRPC endpoints with health.
If the product's sync path is gRPC, the registry serving it should be K8s-native
(DNS → resolver, headless-Service SRV for ports, EndpointSlice health) rather
than a hand-built NATS registry.
## 4. Recommendation
**Primary:** Kubernetes-native service discovery (Service +
headless-Service/DNS + EndpointSlice, served by CoreDNS), delivered as a
Helm chart + Operator, on k3s for single-host customers and a real cluster
for multi-host / hosted.
headless-Service/DNS + EndpointSlice, served by CoreDNS), delivered as a Helm
chart + Operator, on k3s for single-host customers and a real cluster for
multi-host / hosted.
**Fallback:** NATS-based discovery (micro `$SRV` announce + JetStream KV
registry) for no-K8s single-host installs, using a custom gRPC resolver
that reads `host:port` from the KV bucket.
registry) for no-K8s single-host installs, using a custom gRPC resolver that
reads `host:port` from the KV bucket.
**Rationale, short version:**
- K8s-native is the only candidate that solves the hardest requirement —
"install a service and the rest of the system joins in to align" — at
the infrastructure layer with health-filtered endpoints and a
"install a service and the rest of the system joins in to align" — at the
infrastructure layer with health-filtered endpoints and a
customer-comprehensible install. Not extra weight for its own sake; it
replaces a stack of pieces a 7-service product needs anyway, and makes
the multi-host + hosted paths free from one codebase.
replaces a stack of pieces a 7-service product needs anyway, and makes the
multi-host + hosted paths free from one codebase.
- k3s packages the control plane into a ~one-command install a customer can
stand up, and the Operator/Helm/CRD pattern is exactly the "install
Curator, Gateway picks it up" product story.
- NATS is not discarded — it stays in the fleet for async fan-out, and
becomes the second discovery implementation so the smallest no-K8s
customer keeps "one binary on a box." The fallback is the honest
acknowledgment that a full K8s cluster is genuinely heavy for the very
smallest single-node customer.
stand up, and the Operator/Helm/CRD pattern is exactly the "install Curator,
Gateway picks it up" product story.
- NATS is not discarded — it stays in the fleet for async fan-out, and becomes
the second discovery implementation so the smallest no-K8s customer keeps "one
binary on a box." The fallback is the honest acknowledgment that a full K8s
cluster is genuinely heavy for the very smallest single-node customer.
Why not NATS-only: it's a service locator needing hand-built gRPC endpoint
resolution + health, and it couples discovery to broker availability. Why
not Consul/etcd: a redundant second control plane (if K8s) or "you own the
resolution + health, and it couples discovery to broker availability. Why not
Consul/etcd: a redundant second control plane (if K8s) or "you own the
semantics" (etcd), with per-node agents. Why not a mesh: overkill at ~7 Go
services; consensus is 20+.
@@ -171,128 +166,126 @@ type ServiceRegistry interface {
}
```
— with two implementations: a K8s one (DNS / EndpointSlice / custom
resolver) and a NATS one (KV / `$SRV`). The rest of the code is
registry-agnostic. This is what makes "K8s-native primary, NATS fallback" a
coherent architecture rather than a fork: business logic doesn't change,
only the registry injection point does.
— with two implementations: a K8s one (DNS / EndpointSlice / custom resolver)
and a NATS one (KV / `$SRV`). The rest of the code is registry-agnostic. This is
what makes "K8s-native primary, NATS fallback" a coherent architecture rather
than a fork: business logic doesn't change, only the registry injection point
does.
## 5. End-to-end: "install Curator, Gateway discovers it"
**Path A — K8s-native (primary):**
1. Customer installs the product (`helm install archie`, or pre-provisioned
on k3s). Base services (Gateway, UI, Messaging, Scheduler, Execution,
State Store) each deploy as a Deployment + Service; Gateway is always up
and already holds a resolver for every known service name.
2. Customer installs Curator: `helm install archie-curator`, or the
Operator watches a `Curator` Custom Resource and reconciles it — creating
a Deployment (pods) + a `curator` Service.
1. Customer installs the product (`helm install archie`, or pre-provisioned on
k3s). Base services (Gateway, UI, Messaging, Scheduler, Execution, State
Store) each deploy as a Deployment + Service; Gateway is always up and
already holds a resolver for every known service name.
2. Customer installs Curator: `helm install archie-curator`, or the Operator
watches a `Curator` Custom Resource and reconciles it — creating a Deployment
(pods) + a `curator` Service.
3. The Service's label selector matches the Curator pods; the endpoint
controller writes their IPs into an EndpointSlice. Readiness probes gate
which pods are "ready" (a Curator that only registers once healthy won't
receive traffic).
4. CoreDNS immediately serves `curator.<ns>.svc.cluster.local` (A record; a
headless Service additionally gives an SRV record with the port).
5. The Gateway resolves `curator.<ns>.svc.cluster.local` through its gRPC
DNS resolver (or a K8s-aware resolver). On the next re-resolution/update
it picks up the new endpoint. No Gateway redeploy, no Gateway config
change — and because it's DNS, the Gateway code doesn't even need to know
it's running under K8s.
6. Removal: `helm uninstall archie-curator` (or scale to 0 / delete the CR)
→ EndpointSlice empties → DNS record disappears → Gateway's resolver
drops it. Clean.
5. The Gateway resolves `curator.<ns>.svc.cluster.local` through its gRPC DNS
resolver (or a K8s-aware resolver). On the next re-resolution/update it picks
up the new endpoint. No Gateway redeploy, no Gateway config change — and
because it's DNS, the Gateway code doesn't even need to know it's running
under K8s.
6. Removal: `helm uninstall archie-curator` (or scale to 0 / delete the CR) →
EndpointSlice empties → DNS record disappears → Gateway's resolver drops it.
Clean.
**Path B — NATS fallback (single-host, no K8s):**
1. One NATS (embedded, or external via the existing compose stack) is the
shared bus; its URL is part of the base install.
2. Every service, on start, connects to that URL and either (a) registers
via the micro framework (`AddService("curator", "1.0.0", …)`), appearing
on the `$SRV` tree, or (b) writes its `host:port` + version into a
JetStream KV bucket (`archie/registry/curator/<id>`) and heartbeats it
with a TTL.
3. The Gateway holds a live roster (from `$SRV.INFO` or a KV watch) and
feeds it into a custom gRPC resolver mapping service-name → `host:port`.
4. Customer starts one Curator binary (`archie-curator`, or `docker run`
the image) with the same NATS URL in its config. It connects, announces,
and heartbeats. The Gateway's roster observes the new entry (within one
announce/heartbeat window) and starts routing to it. No Gateway restart,
no config change beyond the shared NATS URL already present in the base
install.
5. Removal: stop Curator → its connection closes → it leaves `$SRV`
immediately and its KV record expires via TTL. The Gateway routes that
capability to "not installed."
1. One NATS (embedded, or external via the existing compose stack) is the shared
bus; its URL is part of the base install.
2. Every service, on start, connects to that URL and either (a) registers via
the micro framework (`AddService("curator", "1.0.0", …)`), appearing on the
`$SRV` tree, or (b) writes its `host:port` + version into a JetStream KV
bucket (`archie/registry/curator/<id>`) and heartbeats it with a TTL.
3. The Gateway holds a live roster (from `$SRV.INFO` or a KV watch) and feeds it
into a custom gRPC resolver mapping service-name → `host:port`.
4. Customer starts one Curator binary (`archie-curator`, or `docker run` the
image) with the same NATS URL in its config. It connects, announces, and
heartbeats. The Gateway's roster observes the new entry (within one
announce/heartbeat window) and starts routing to it. No Gateway restart, no
config change beyond the shared NATS URL already present in the base install.
5. Removal: stop Curator → its connection closes → it leaves `$SRV` immediately
and its KV record expires via TTL. The Gateway routes that capability to "not
installed."
## 6. Failure-mode honesty
- **K8s-native:** pod death → readiness fails → dropped from EndpointSlice
within seconds, so the gateway stops routing to it (health-aware). DNS
TTL caching is mostly harmless because a Service's ClusterIP is stable
and all churn lives behind it in the EndpointSlice. If the control plane
goes down, already-running pods keep serving and DNS still resolves from
cache; only new scheduling/propagation halts. Known gap: cross-cluster
and off-cluster consumers (client-side resolvers, a worker fleet on VMs)
need ExternalDNS or a bridge. mTLS/auth, if needed, is a separate concern
(NetworkPolicy / cert-manager), not the mesh.
- **NATS fallback:** service dies → dropped from `$SRV` immediately, KV
record lingers until heartbeat-TTL (bounded staleness). Broker
unreachable → every service appears down (hard SPOF unless NATS is
clustered). Plain subjects aren't a consensus store (split-brain across
partitions possible); JetStream KV gives Raft per stream but KV placement
across hosts needs its own decisions. Health semantics must be built by
hand.
within seconds, so the gateway stops routing to it (health-aware). DNS TTL
caching is mostly harmless because a Service's ClusterIP is stable and all
churn lives behind it in the EndpointSlice. If the control plane goes down,
already-running pods keep serving and DNS still resolves from cache; only new
scheduling/propagation halts. Known gap: cross-cluster and off-cluster
consumers (client-side resolvers, a worker fleet on VMs) need ExternalDNS or a
bridge. mTLS/auth, if needed, is a separate concern (NetworkPolicy /
cert-manager), not the mesh.
- **NATS fallback:** service dies → dropped from `$SRV` immediately, KV record
lingers until heartbeat-TTL (bounded staleness). Broker unreachable → every
service appears down (hard SPOF unless NATS is clustered). Plain subjects
aren't a consensus store (split-brain across partitions possible); JetStream
KV gives Raft per stream but KV placement across hosts needs its own
decisions. Health semantics must be built by hand.
Both paths are robust against "a service dies"; the difference is who does
the health checking — K8s readiness probes do it for free, NATS makes you
build it.
Both paths are robust against "a service dies"; the difference is who does the
health checking — K8s readiness probes do it for free, NATS makes you build it.
## 7. Addendum — recovered K8s lane, optional-service semantics
A separately recovered K8s-focused research lane landed independently on
the same verdict (K8s-native as the canonical, declarative, self-healing
fleet-discovery answer; fits multi-host and the AAP-style "sold both ways"
model best) and confirmed the same install → Operator → CoreDNS → resolver
flow above. It sharpened one point specific to archie-core's shape:
A separately recovered K8s-focused research lane landed independently on the
same verdict (K8s-native as the canonical, declarative, self-healing
fleet-discovery answer; fits multi-host and the AAP-style "sold both ways" model
best) and confirmed the same install → Operator → CoreDNS → resolver flow above.
It sharpened one point specific to archie-core's shape:
**The optional, intermittently-running Curator needs explicit "absent"
semantics under K8s.** A scaled-to-zero or not-yet-created Curator has no
ready endpoint and no DNS record — the Gateway's gRPC `dns://` resolver
gets `NXDOMAIN`/empty resolution, and this must be treated as "Curator is
disabled," not "Curator is broken." Concretely:
- Lazy, on-demand re-resolution — don't pin a dead subchannel as a hard
**The optional, intermittently-running Curator needs explicit "absent" semantics
under K8s.** A scaled-to-zero or not-yet-created Curator has no ready endpoint
and no DNS record — the Gateway's gRPC `dns://` resolver gets `NXDOMAIN`/empty
resolution, and this must be treated as "Curator is disabled," not "Curator is
broken." Concretely:
- Lazy, on-demand re-resolution — don't pin a dead subchannel as a hard failure.
- A distinct `NotInstalled` vs. `Down`/`Unhealthy` state for routing — the same
distinction the NATS path needs a KV "installed" marker to express. Under K8s,
health comes free (readiness gates the EndpointSlice), but the _presence_ of
an optional service still has to be modelled as a resolution outcome, not a
failure.
- A distinct `NotInstalled` vs. `Down`/`Unhealthy` state for routing — the
same distinction the NATS path needs a KV "installed" marker to express.
Under K8s, health comes free (readiness gates the EndpointSlice), but the
*presence* of an optional service still has to be modeled as a resolution
outcome, not a failure.
This is a new implementation requirement on both paths (`ServiceRegistry`'s
`Resolve`/`Watch` contract needs a way to express "absent" distinctly from
"unhealthy"), not a change to the primary/fallback recommendation.
Two secondary observations from that lane, noted but not verdict-changing:
- **Two discovery systems, not one.** Under K8s, sync gRPC is served by
cluster DNS/EndpointSlice, while async NATS status/telemetry is served by
NATS's own clustering. These should not be conflated — this is exactly
why the `ServiceRegistry` seam matters: it isolates the sync path and
keeps NATS purely for async fan-out, as already planned.
- **Two discovery systems, not one.** Under K8s, sync gRPC is served by cluster
DNS/EndpointSlice, while async NATS status/telemetry is served by NATS's own
clustering. These should not be conflated — this is exactly why the
`ServiceRegistry` seam matters: it isolates the sync path and keeps NATS
purely for async fan-out, as already planned.
- **Config relocation.** Moving install/run/upgrade from `config.toml` into
ConfigMaps/Secrets is a real change to how archie-core is deployed,
worth a deliberate PRD/settled-design before committing — a phased
concern, not a blocker for the discovery decision.
ConfigMaps/Secrets is a real change to how archie-core is deployed, worth a
deliberate PRD/settled-design before committing — a phased concern, not a
blocker for the discovery decision.
## Bottom line
Treat Kubernetes-native discovery (Helm chart + Operator on k3s / a real
cluster) as primary, and reuse NATS as the built-in fallback so single-host
no-K8s customers still get "install and auto-join." This is the only
ordering that satisfies the hardest requirement at the infrastructure
layer, keeps the hosted path free from one codebase, and doesn't force the
smallest customer into a full cluster. The two implementations live behind
one `ServiceRegistry` interface, so neither is a fork. The one added
implementation requirement is the optional-service "absent ≠ down"
resolution model on both paths.
no-K8s customers still get "install and auto-join." This is the only ordering
that satisfies the hardest requirement at the infrastructure layer, keeps the
hosted path free from one codebase, and doesn't force the smallest customer into
a full cluster. The two implementations live behind one `ServiceRegistry`
interface, so neither is a fork. The one added implementation requirement is the
optional-service "absent ≠ down" resolution model on both paths.
Full recovered K8s-lane transcript, for the record: session path
`.../cf1825c4-0c08-4aaa-9ea1-aac40893825f/run-0/session.jsonl` (external to
this repository; not reproduced here).
`.../cf1825c4-0c08-4aaa-9ea1-aac40893825f/run-0/session.jsonl` (external to this
repository; not reproduced here).
-13
View File
@@ -1,13 +0,0 @@
# 1.0.0
Released 2026-07-22. [All news](index.md)
### archied
- feat: ship the resident forge-polling daemon, deterministic workflow engine, isolated worktrees, quality gates, Gitea integration, Docker/NATS worker split, plugin loading, and skills support
- feat: publish `archied` and `archie-agent` container images to the Gitea registry
### archie-agent
- feat: ship the isolated agent runtime, NATS RPC boundary, workflow execution, skills, and plugin support
- feat: publish the `archie-agent` container image to the Gitea registry
-39
View File
@@ -1,39 +0,0 @@
# 1.1.0
Released 2026-07-27. [All news](index.md)
### archied
- feat: add the Telegram gateway with persistent sessions, topic-thread support, streamed rich replies, typing indicators, and Markdown rendering
- feat: add `/spawn`, `/approve`, and `/cancel` for chat-driven task control
- feat: provide a comprehensive `/help` guide whose command list stays aligned with Telegram's published menu and Archie's executable command surface
- feat: add `/provider` and provider-filtered `/model` selectors that switch the provider and model used by subsequent live chat turns
- feat: include the active provider and full model reference in `/status`
- feat: notify authorized Telegram users once when a newly tagged component release is installed
- feat: add `/restart` to reload and relaunch the Telegram gateway without interrupting in-flight daemon tasks
- feat: add deny-by-default Telegram sender authorization and native command-menu publication
- feat: connect Desktop Commander through Archie's managed MCP client so chat can use workspace file and process tools
- feat: add multi-identity daemon configuration, persona routing, an email channel, and webhook platform support
- feat: add durable task, session, message, and memory persistence
- feat: add memory synchronization, prefetch, context scrubbing, threat scanning, and built-in memory tools
- feat: add tool guardrails, classification, budgets, availability filtering, and disclosure controls
- feat: add feature-based YAML configuration with `conf.d` overlay loading
- feat: add typed secret-engine registration and Yaegi extension support
- fix: reject unknown slash commands locally instead of allowing the LLM to fabricate command behavior
- fix: publish Telegram commands to default, private-chat, and group-chat scopes so stale commands inherited with the bot token cannot shadow Archie's menu
- fix: drain the SDK's full event stream so streamed Telegram replies cannot deadlock
- fix: use standard newline-delimited JSON framing for MCP stdio clients
- fix: make MCP stdio shutdown and timeout handling race-safe
- fix: restore legacy `[forge].token_env` compatibility and required container environment passthrough
- fix: make the agent-container Docker network explicitly configurable
### archie-agent
- feat: add streamed agent execution with typed message events
- feat: add MCP client transports and managed tool-provider discovery
- feat: add memory context scrubbing and normalized memory tool schemas
- feat: add plugin metadata extraction from `metadata.archie.plugins`
- feat: add configurable container networking for daemon-launched runtimes
- fix: preserve valid UTF-8 when clipping runtime output
- fix: make MCP stdio lifecycle, retries, and timeout handling race-safe
- fix: enforce a zero-finding lint and vet baseline
-19
View File
@@ -1,19 +0,0 @@
# 1.10.0
Released 2026-08-22. [All news](index.md)
### archied
- feat(forge): GitHub webhook receiver for immediate issue dispatch
- feat(webhookguard): shared HMAC, rate-limit, and redaction mechanics
- feat(nats): run an embedded server when no external NATS is configured
- feat(capture): store unbound webhook events, retention-bounded
- feat(webui): event inspector -- see captured payloads in the dashboard
- feat(webui): payload field mapping -- bind JSON paths to named fields, preview before saving
- fix(webui): stop the capture live-event notification duplicating payloads into the unbounded events table
- fix(update): verify an update took effect instead of trusting the report (#530)
- fix(daemon): refuse to poll on an empty label-trigger match (#529)
- fix(gateway): stop persona from asserting unverified claims as fact (#528)
- fix(gateway): stop ClaimTurn's insert-race branch losing its own retry read
- fix: restore provider gate and dashboard token accounting
- fix: address simple findings from a repo-wide golangci-lint sweep
-14
View File
@@ -1,14 +0,0 @@
# 1.11.0
Released 2026-08-23. [All news](index.md)
### archied
- feat(forge): make webhook intake observable and deduplicate concurrent delivery
- fix(telegram): preserve code fences across message splits
- fix(gateway): replay completed-duplicate turns with their tool activity
- feat(storage): persist agent project state across sessions
- fix(container): persist npm cache for per-task MCP servers
- fix(worktree): bind publication to dispatch grants, reset retries to a pristine base, and reject diffs without a merge base
- feat(media): deliver generated media through Telegram with link fallback in the dashboard
- feat(tools): generate videos through MiniMax, gated by provider configuration
-8
View File
@@ -1,8 +0,0 @@
# 1.11.1
Released 2026-08-23. [All news](index.md)
### archied
- fix(update): wire Telegram personas and survive callback cancellation
- fix(webui): theme the Workflows 'Start work' form controls
-10
View File
@@ -1,10 +0,0 @@
# 1.12.0
Released 2026-08-23. [All news](index.md)
### archied
- fix(webui): give dashboard-initiated updates a phase-2 report
- feat(agent): stamp archie-agent's build and report it back to the daemon
- feat(releaseupdate): enrich components with install type and reference
- feat(webui): surface per-component update status on /api/version and Configuration
-7
View File
@@ -1,7 +0,0 @@
# 1.13.0
Released 2026-08-23. [All news](index.md)
### archied
- fix(telegram): render tool progress as bounded code blocks
-8
View File
@@ -1,8 +0,0 @@
# 1.14.0
Released 2026-08-23. [All news](index.md)
### archied
- fix(telegram): compact tool output and drop turn caps
- fix(update): install only approved components
-41
View File
@@ -1,41 +0,0 @@
# 1.15.0
Released 2026-08-24. [All news](index.md)
### archied
**Autonomous workflows now have exactly one production execution path.** Every
task is handed complete to a scoped `archie-agent` container over core NATS;
`archied` no longer runs an agent loop in-process. Embedded NATS is the
default and generates a per-start token, binding to the resolved Docker bridge
so managed workers can reach it; external NATS changes only broker placement.
The legacy `[agent]` section and `containers.enabled` still decode for
migration but can no longer select an execution path, and a reloaded
`nats.url` is logged as requiring a restart. Operators upgrading from a
`agent.mode = inprocess` configuration get the managed-worker topology
automatically; see `deployments/` for the supported profiles.
- feat(nats): expose the embedded broker to managed task containers behind a
generated per-start credential
- fix(daemon): park before worktree access when the container pool or task
transport is unavailable, rather than silently executing locally
- refactor(agentexec): remove the in-process, subprocess and single-stage
execution paths
- fix(worktree): report a successful push as successful even when writing
local upstream tracking metadata afterwards fails, so a published branch no
longer parks the task as failed
- fix(worktree): honour context cancellation in `CommitAll`, so a cancelled
task can no longer stage or commit
- fix(daemon): remove the worktree when a task completes with no changes,
which previously leaked a full clone per no-change task; parked worktrees
are still retained for post-mortems
- fix(worktree): derive the branch prefix from the issue title before falling
back to labels, matching the documented contract
- fix(worktree): clean untracked files when `.git` is a gitdir file
- fix(agentexec): recover agents that end a turn without the required finish
call
- feat(scheduling): ticker engine with a configurable interval and pools
- fix(telegram): keep tool-call context when compacting tool output (#609)
- feat(workflow): add the adversarial-review findings contract, where only a
confirmed finding blocks and "review found nothing" is distinct from
"review did not run" (contract only; no review stage runs yet)
-78
View File
@@ -1,78 +0,0 @@
# 1.16.0
Released 2026-08-25. [All news](index.md)
### archied
**The agent can hand you a file, and the dashboard works behind a reverse
proxy.** Media delivery was fetch-by-URL only, so a file the agent produced
locally — a transcript, a log dump, a screenshot — was passed to Telegram as
a URL it could not fetch: the send did nothing and reported success. The new
`send_file` tool plus upload-by-reader delivery closes that, and every layer
that cannot deliver now says so rather than staying silent. Dashboard
mutations behind a TLS-terminating proxy were refused as cross-origin;
forwarded headers are now honoured, but only under an explicit opt-in that is
off by default.
- feat(telegram): deliver a local file as an uploaded attachment, choosing
upload-by-reader or fetch-by-URL per attachment; `send_file` resolves paths
under the same confinement policy the read tool applies, so sending cannot
reach what reading cannot
- feat(gateway): `task_action` chat tool for operator task management —
abandon, archive, retry, stop, cancel, approve and reject from chat, on the
same action path and state machine as the dashboard
- fix(webui): validate mutation `Origin` against the effective external
scheme and host. `X-Forwarded-Proto`/`-Host` are honoured only when
`web.trust_forwarded_headers` is set, which is off by default and safe only
behind a proxy that overwrites or strips untrusted forwarded headers
- fix(webui): report a local file the dashboard chat cannot upload as
undelivered instead of dropping the event, which had reproduced the exact
silent non-delivery `send_file` was built to end
- fix(daemon): detach terminal state transitions and cleanup from a cancelled
context, so a stopped task still records its outcome
### archie-agent
**Version realigned with `archied`.** This release jumps from 1.9.9 to 1.16.0
to put the two components on matching numbers; there are no 1.10-1.15 agent
releases. It clears the accumulated runtime backlog in one cut rather than
bundling it as a rider on a later change, so the list below spans several
weeks of work rather than one session's.
Highlights:
- feat(nats): run an embedded server when no external NATS is configured, and
expose the embedded broker to managed task workers
- feat(deployment): default to managed NATS workers; the daemon requires a
full-task worker handoff and the legacy in-process, subprocess and
single-stage execution paths are gone
- feat(forge): GitHub webhook receiver for immediate issue dispatch, with
dedup regression proof; unbound webhook events are stored retention-bounded
- feat(webui): payload field mapping -- bind JSON paths to named fields and
preview before saving
- feat(scheduling): ticker engine with configurable interval and pools
- feat(storage): persist agent project state
- feat(agent): stamp archie-agent's build and report it back to the daemon
- feat(tools): `generate_video` via MiniMax, gated behind config, and
`MultimodalResult.URLs` for remote-hosted media
- feat(workflow): define the adversarial-review findings contract
Fixes:
- fix(worktree): bind publication to dispatch grants; reset retries to a
pristine base; reject diffs without a merge base; clean untracked files when
`.git` is a gitdir file; post-push metadata resilience, cancellation and
branch naming
- fix(container): persist the npm cache for per-task MCP servers
- fix(agentexec): recover omitted finish calls
- fix(agentworker): move JSONL decode into storage, unblocking CI
- fix(telegram): compact tool output and drop turn caps
- fix(webui): give dashboard-initiated updates a phase-2 report; restore the
provider gate and dashboard token accounting
- refactor: remove dead `BasePlatformAdapter` code and legacy execution paths
Shared with archied 1.16.0 (these packages are in both closures):
- feat(telegram): send local files as uploads, not fetchable URLs
- fix(webui,sendfile): close three holes the adversarial review found
- fix(webui): validate mutation Origin against the effective external scheme
-7
View File
@@ -1,7 +0,0 @@
# 1.16.1
Released 2026-08-25. [All news](index.md)
### archie-agent
- fix(agentworker): reconcile task clone ownership after commits
-15
View File
@@ -1,15 +0,0 @@
# 1.17.0
Released 2026-08-25. [All news](index.md)
### archied
- fix(webui): add nil receiver guard to Server.trustForwardedHeaders
- fix(chat): restore transcript and update replay
### archie-agent
- Compact task history against the selected model's real context capacity without imposing a token cap.
- Preserve completed steps and billed usage when a later provider call fails; failed compaction now keeps the original history and continues.
- Persist detailed agent-stage usage through the daemon-owned store before lossy live event fan-out.
- Apply configured or forge-derived author and committer identity to sandboxed task commits.
-8
View File
@@ -1,8 +0,0 @@
# 1.17.1
Released 2026-08-25. [All news](index.md)
### archied
- fix(update): remove source checkout dependency
- fix(gateway): make UUIDv7 session references unambiguous
-15
View File
@@ -1,15 +0,0 @@
# 1.18.0
Released 2026-08-28. [All news](index.md)
### archied (released 2026-08-25)
- Fix concurrent chat-turn claims so SQLite writer contention no longer leaks as `SQLITE_BUSY`.
- Make task timelines operationally useful with stage outcomes, durations, retry context, and durable per-stage token economics.
- Return canonical repository, issue, and pull-request URLs for each task's owning GitHub or Gitea identity.
- Preserve per-identity commit attribution and real model context limits across daemon-to-worker dispatch.
### archie-agent
- feat(logging): cursor pagination and filtering for task_logs
- build(deps): upgrade github.com/samcharles93/ai-sdk to v0.1.29
-8
View File
@@ -1,8 +0,0 @@
# 1.19.0
Released 2026-08-28. [All news](index.md)
### archied
- feat(logging): cursor pagination and filtering for task_logs
- build(deps): upgrade github.com/samcharles93/ai-sdk to v0.1.29
-7
View File
@@ -1,7 +0,0 @@
# 1.19.1
Released 2026-08-27. [All news](index.md)
### archied
- fix(telegram): keep Markdown headings/lists as blocks and strip Markdown on plain fallback
-7
View File
@@ -1,7 +0,0 @@
# 1.19.10
Released 2026-09-02. [All news](index.md)
### archied
- feat(curator): session-memory curator reference implementation
-7
View File
@@ -1,7 +0,0 @@
# 1.19.2
Released 2026-08-28. [All news](index.md)
### archied
- feat(tasks): allow rejecting a task from any non-terminal state
-8
View File
@@ -1,8 +0,0 @@
# 1.19.3
Released 2026-08-28. [All news](index.md)
### archied
- feat(tasks): serve the lifecycle presentation catalog from /api/task-meta
- feat(dashboard): render task actions, statuses and filters from the server catalog
-7
View File
@@ -1,7 +0,0 @@
# 1.19.4
Released 2026-08-28. [All news](index.md)
### archied
- refactor(telegram): render replies as structured rich blocks
-45
View File
@@ -1,45 +0,0 @@
# 1.19.5
Released 2026-09-01. [All news](index.md)
### archied
- feat(webui): dashboard-aware chat — Archie sees the page, points you there
- fix(telegram): drop retry_after bandaid, bump go-telegram/bot to v1.24.0
- feat(curator): track and expose recent activity per curator
- fix: go.mod bumped to 1.27.0 and stupid tests removed
- refactor: remove unnecessary AI-generated scaffolding
- refactor: go modernisation fixes
- refactor: remove unused Operator param.
- fix(gateway): fix broken system prompt template and scrub real telegram ID from tests
- fix(plugin): add missing CLAUDE.md reference to plugin engine rule
- fix(app): repoint archied wiring contract test at internal/app/archied
- refactor(agentexec): use ai-sdk NewTypedTool for pluginToolSet and scriptToolSet
- fix(config): standardize Provenance to pointer receivers (recvcheck)
- refactor(lint): reduce cyclomatic/cognitive complexity in tools, workflow, webui
- fix(app): repoint capability-host wiring contract test at internal/app/archied
- refactor(lint): extract more helpers to clear nestif/gocyclo findings
- refactor(lint): split AgentStage.Stage into resolveModel/buildRequest/handleResult
- refactor(lint): split TurnRunner.Run and dispatchLocal further
- refactor(lint): extract markdownBlockParser and list/quote helpers in richblocks.go
- refactor(lint): extract Apply/findWalkVisitor helpers; go fix modernization
- fix(lint): noctx fixes and dead-code cleanup
- feat(workflow): adversarial self-review stage before PR open
### archie-agent
- feat(tasks): allow rejecting a task from any non-terminal state
- feat(tasks): serve the lifecycle presentation catalog from /api/task-meta
- fix: go.mod bumped to 1.27.0 and stupid tests removed
- refactor: go modernisation fixes
- refactor: remove unused Operator param.
- fix(plugin): add missing CLAUDE.md reference to plugin engine rule
- fix(app): repoint archied wiring contract test at internal/app/archied
- refactor(agentexec): use ai-sdk NewTypedTool for pluginToolSet and scriptToolSet
- refactor(lint): reduce cyclomatic/cognitive complexity in tools, workflow, webui
- fix(app): repoint capability-host wiring contract test at internal/app/archied
- refactor(lint): extract more helpers to clear nestif/gocyclo findings
- refactor(lint): split AgentStage.Stage into resolveModel/buildRequest/handleResult
- refactor(lint): extract Apply/findWalkVisitor helpers; go fix modernization
- fix(lint): noctx fixes and dead-code cleanup
- feat(workflow): adversarial self-review stage before PR open
-7
View File
@@ -1,7 +0,0 @@
# 1.19.6
Released 2026-09-02. [All news](index.md)
### archied
- fix(build): stamp gatewayVersion/runtimeVersion in the right package
-11
View File
@@ -1,11 +0,0 @@
# 1.19.7
Released 2026-09-02. [All news](index.md)
### archied
- fix(logging): make Tail/Page allocation bound explicit for CodeQL
### archie-agent
- fix(logging): make Tail/Page allocation bound explicit for CodeQL
-9
View File
@@ -1,9 +0,0 @@
# 1.19.8
Released 2026-09-02. [All news](index.md)
### archied
- fix(update): drop dev-facing wording from the unconfirmed-update message
- fix(telegram): stop adjacent rich blocks from rendering glued together
- fix(telegram): send undelivered-media fallback after finalize as its own message
-17
View File
@@ -1,17 +0,0 @@
# 1.19.9
Released 2026-09-02. [All news](index.md)
### archied
- feat(memory): typed memory engine contract, registry, and registrar
- feat(memory): builtin engine implementing the domain/memory contract
- feat(config): config surface for memory engine selection
- feat(daemon): wire the domain/memory engine registry at boot
- feat(curator): bind curators to memory engines
- fix(config): reject memory.provider instead of silently ignoring it
- feat(curator): skill curator reference implementation
### archie-agent
- feat(config): config surface for memory engine selection
-68
View File
@@ -1,68 +0,0 @@
# 1.2.0
Released 2026-07-31. [All news](index.md)
### archied
- feat: add MCP client capabilities to archied and archie-agent
- fix: handleSummary ignores errors from WorkflowStats/StageStats/TokensByDay
- feat: establish Archie identity and use stable callback tokens
- refactor(telegram): keep one model selector command
- fix: handleSSE silently swallows EventsSince backlog fetch errors
- fix: Transition() ignores `from` status guard, allowing lost updates
- fix: skillscript.Run ignores context, cannot be canceled/timed out
- feat(telegram): report installed component versions
- feat(telegram): add approved component updates
- fix: LoadDir: no timeout around Yaegi Eval can hang daemon startup
- feat(chat): real system prompt for Archie — identity, tools, env
- feat(indexing): port tau's codesearch workspace index
- fix(indexing): surface index config properly and stop silent degradation
- refactor(worktree): replace git shell-out with go-git v6
- fix(worktreerpc): bound handler contexts and drop the git binary from tests
- refactor(nats): rebuild as infrastructure/eventbus/nats with real boundaries
- refactor: route tasks on a typed kind, not forge labels
- fix(natsrpc): make RegisterAll wait for the server to see subscriptions
- refactor(config): move loading into infrastructure/configuration
- fix(telegram): publish all executable session commands in menu and help
- fix(telegram): publish the restored gateway commands
- refactor: add internal/eventbus as the broker-neutral messaging contract
- fix(chat): operator name from config, session wiring, prompt rules
- feat(tools): lift tau's file and shell tools into the tool registry
- feat: make /stop cancel the running chat turn
- fix: kill the whole process group when a shell command is cancelled
- feat: refuse unrecoverable shell commands
- feat: make /stop reach running agent tasks
- fix(chat): temper prompt brevity rules with warmth
- fix: use errors.Is/As for context errors and cleanup
- fix(grep): distinguish ripgrep exit 1 from a failed search
- fix(archied): disable the forge on a missing credential, not the daemon
- fix: restore /model parsing and close the 6d4e0be autofix audit
- feat: embed config.example.toml and add comment-preserving TOML writer
- fix(docker): install unzip and Node 24 so MCP servers can start
- fix(docker): slim both images and repair unreachable Go tooling
- fix(container): write the task boot brief under .git
- fix(telegram): drop pending updates before long polling
### archie-agent
- feat: add MCP client capabilities to archied and archie-agent
- fix: Transition() ignores `from` status guard, allowing lost updates
- fix: skillscript.Run ignores context, cannot be canceled/timed out
- fix: LoadDir: no timeout around Yaegi Eval can hang daemon startup
- fix(indexing): surface index config properly and stop silent degradation
- refactor(worktree): replace git shell-out with go-git v6
- fix(worktreerpc): bound handler contexts and drop the git binary from tests
- refactor(nats): rebuild as infrastructure/eventbus/nats with real boundaries
- refactor: route tasks on a typed kind, not forge labels
- fix(natsrpc): make RegisterAll wait for the server to see subscriptions
- refactor(config): move loading into infrastructure/configuration
- refactor: add internal/eventbus as the broker-neutral messaging contract
- feat(tools): lift tau's file and shell tools into the tool registry
- feat: make /stop cancel the running chat turn
- fix: kill the whole process group when a shell command is cancelled
- feat: refuse unrecoverable shell commands
- feat: make /stop reach running agent tasks
- fix: use errors.Is/As for context errors and cleanup
- fix(grep): distinguish ripgrep exit 1 from a failed search
- fix(docker): slim both images and repair unreachable Go tooling
- fix(container): write the task boot brief under .git
-39
View File
@@ -1,39 +0,0 @@
# 1.20.0
Released 2026-09-03. [All news](index.md)
### archied
- fix: baseline gate repair (go test ./... -count=1)
- fix(logging): propagate bound slog attrs to wrapped handler in FeedHandler
- feat(image): define provider-neutral image capability contract and config
- fix(channels): call MarkRunning once a channel is actually up
- fix(workflow): stop discarding baseline-fix commits as 'no changes'
- fix(webui): wire the Logs page to per-task attempt-log detail
- fix(workflow): net cache hits from token totals, trim gate-retry output
- feat(workflow): dynamic triage instead of defaulting every task to implement
- fix(gateway): stop SOUL from forging the prompt invariant tags
- fix(curator): stop curator actions from serializing a zero timestamp
- feat(webui): hand-author the configuration field descriptor catalog
- feat(webui): attach the config field schema to GET /api/config
- feat(webui): render scalar config sections generically from the schema
- feat(webui): surface allow_concurrent/max_retries/review_enabled on the repositories card
- feat(webui): inline editing for per-repo allow_concurrent/max_retries/review_enabled
- feat(webui): playbook bindings -- matcher + mapping + workflow, HMAC-gated
- fix: resolve golangci-lint funlen, nilerr, and empty branch issues
- feat(store): encrypt playbook binding secrets at rest
- feat(webhook): harden captured payload redaction
- fix(store): satisfy makezero when building cipher payload
- feat(webui): refactor chat module to Preact component and add unit tests
### archie-agent
- fix: baseline gate repair (go test ./... -count=1)
- fix(logging): propagate bound slog attrs to wrapped handler in FeedHandler
- feat(image): define provider-neutral image capability contract and config
- fix(workflow): stop discarding baseline-fix commits as 'no changes'
- fix(workflow): net cache hits from token totals, trim gate-retry output
- feat(workflow): dynamic triage instead of defaulting every task to implement
- feat(webui): playbook bindings -- matcher + mapping + workflow, HMAC-gated
- feat(store): encrypt playbook binding secrets at rest
- fix(store): satisfy makezero when building cipher payload
-35
View File
@@ -1,35 +0,0 @@
# 1.21.0
Released 2026-09-03. [All news](index.md)
### archied
- feat(workflow): make kind-to-workflow routing YAML-overridable
- feat(workflow): route arbitrary forge labels to workflows via playbook YAML
- feat(workflow): load kind/label bindings from multiple playbook directories
- fix(extract): regenerate stale Yaegi symbol tables; fix wfextract directive
- feat(eda): Module position first slice -- registry + side-effect-free log kind
- feat(eda): CEL expression environment (compile/validate at load, evaluate at dispatch)
- feat(eda): playbook document + event coordinator, single-action workflow-kind dispatch
- fix(skillcurator): document and scope the intentional nilerr in reviewOne
- fix(binding): add Owner/Repo pin, fixing multi-repo dispatch
- feat(webui): bindings dashboard UI; fix app-wide Preact render regression
- fix(binding): split ValidateForUpdate so edits can preserve the secret
- refactor(ui): extract Pill to ui/src/base/, closing archie-core-mlro
- refactor(eda): extract helpers to satisfy cyclop/gocognit gates
- fix(webui): stretch HEALTH row cards to equal height
- fix(eda): make playbook key collision reporting deterministic
- fix(gateway): split /status (health) and /tasks (work) apart
### archie-agent
- feat(workflow): make kind-to-workflow routing YAML-overridable
- feat(workflow): route arbitrary forge labels to workflows via playbook YAML
- feat(workflow): load kind/label bindings from multiple playbook directories
- fix(extract): regenerate stale Yaegi symbol tables; fix wfextract directive
- feat(eda): Module position first slice -- registry + side-effect-free log kind
- feat(eda): playbook document + event coordinator, single-action workflow-kind dispatch
- fix(binding): add Owner/Repo pin, fixing multi-repo dispatch
- fix(binding): split ValidateForUpdate so edits can preserve the secret
- refactor(eda): extract helpers to satisfy cyclop/gocognit gates
- fix(eda): make playbook key collision reporting deterministic
-11
View File
@@ -1,11 +0,0 @@
# 1.22.0
Released 2026-09-03. [All news](index.md)
### archied
- feat(telegram): support secret refs for bot tokens (#705)
- fix(update): make daemon rollback schema-safe (#704)
- fix(archied): preserve ephemeral gateway ports (#707)
- fix(webui): bound log limit parsing and add endpoint regression coverage (#706)
- fix(deps): upgrade x/crypto to v0.56.0 for security fixes (#708)
-110
View File
@@ -1,110 +0,0 @@
# 1.23.0
Released 2026-09-12. [All news](index.md)
### archied
Archied is no longer a single process. The State Store (`archie-state-store`)
now owns `archie.db` outright, the Gateway serves its contract over
authenticated gRPC, and the dashboard ships as a standalone UI Service
(`archie-ui`). Upgrading is not a binary swap: these processes must be running
and addressable before `archied` will start clean. See `deployments/` for the
supported profiles.
### archied — Service decomposition
- feat(contracts): add gateway service seams and protobuf toolchain
- feat(gateway): extract ChatContract service
- feat(gateway): delete in-process ChatContract path, make remote the only mode
- feat(gateway): authenticate the gRPC contract and allow off-loopback listeners
- fix(gateway): drop services.gateway.mode, remote is the only transport
- feat(state-store): generalize storerpc as the State Store gRPC contract (#770)
- feat(state-store): stand up archie-state-store binary and own archie.db (#771)
- refactor(state-store): migrate capture/mapping/binding consumers to State Store (#772)
- refactor(state-store): migrate workflow/intake/task lifecycle consumers to State Store (#773)
- refactor(state-store): cut daemon/Gateway over to the remote State Store (#774)
- fix(state-store): task-scope container credentials, stream large capture lists, validate Update
- feat(archieui): standalone UI process over remote Gateway and State Store
- refactor(archied): cut the dashboard over to the archie-ui process
- refactor(ui): sever the archie-ui binary from every daemon runtime package
- refactor(archied): move the update relay to the process that owns updates
- refactor(archied): move webhook capture intake to the process that owns work intake
- feat(archieui): mount the capture intake receiver over the State Store
- refactor(workflow): relocate Task/Status/Source and define workflow.Store (#754)
- refactor(store): move the producer-owned contracts to internal/contracts/store/v1
- feat(messaging): migrate gateway session persistence onto domain types
- feat(gateway): flip channel boundary onto messaging.Message
### archied — Pull request review
- feat(gateway): operator-triggered PR review with selectable reviewer model
- feat(forge): pull request review read surface (ListReviews/ListReviewComments/ReplyToReview)
- feat(workflow): surface adversarial review findings on the PR body
- feat(workflow): review calibration, checked properties and style nits out of contract
- fix(archied): share one PR reviewer across channels; harden forge and worktree
- fix(workflow): order findings before footer; test the report stash
### archied — Dashboard
- feat(webui): render configuration from a published snapshot
- feat(staterpc): carry the dashboard's configuration snapshot
- refactor(webui): take configuration off the dashboard server
- feat(webui): report which dashboard sections a process can serve
- feat(webui): deliver live dashboard events by polling the State Store cursor
- feat(webui): route dashboard task actions through the Gateway contract
- feat(gateway): give the dashboard operator its own task-action contract
- feat(webui): add /health and /health/detailed readiness endpoints (#717)
- fix(webui): distinguish refused vs broken task actions, handle 401 (#753)
### archied — Daemon, gateway and workflow
- feat(archied): add shutdown watchdog that force-exits a hung graceful shutdown (#716)
- feat(archied): serve the daemon's own health endpoint
- feat(drain): honour external drain marker with instantiation epoch (#718)
- feat(gateway): wire progressive tool disclosure (bridge tools)
- feat(gateway): render workspace, managed repos and operator into chat env
- feat(gateway): add session_transcript tool for full JSON export
- feat(gateway): consolidate task actions and repair daemon default path
- feat(eda): thread Playbook ID/Version and DispatchInput task identity
- feat(worktree): Resume re-syncs a worktree onto its branch tip
- fix(staterpc): attach the bearer token to State Store streams
- fix(archieui): resolve service tokens from env, without requiring a config file
- fix(archied): initialize conversation persistence on daemon startup
- fix(archied): preserve channel turn ledger with remote gateway
- fix(gateway): share NATS and session ownership
- fix(update): probe the dashboard's real address after a self-update
- fix(store): migrate binding owner and repo columns
### archie-agent
The agent runtime now reaches task state through the State Store gRPC contract
(`STATE_STORE_URL`/`STATE_STORE_TOKEN`, injected by the daemon) instead of the
NATS `storerpc` transport, which is deleted. Credentials handed to a task
container are scoped to that task rather than being the daemon's own token.
Running a 1.23.0 daemon against an older agent image will not work; rebuild or
pull the `archie-agent` image with this release.
- feat(state-store): generalize storerpc as the State Store gRPC contract (#770)
- feat(state-store): stand up archie-state-store binary and own archie.db (#771)
- refactor(state-store): cut daemon/Gateway over to the remote State Store (#774)
- fix(state-store): task-scope container credentials, stream large capture lists, validate Update
- fix(staterpc): attach the bearer token to State Store streams
- feat(staterpc): carry the dashboard's configuration snapshot
- refactor(workflow): relocate Task/Status/Source and define workflow.Store (#754)
- refactor(store): move the producer-owned contracts to internal/contracts/store/v1
- feat(contracts): add gateway service seams and protobuf toolchain
- fix(gateway): drop services.gateway.mode, remote is the only transport
- feat(forge): pull request review read surface (ListReviews/ListReviewComments/ReplyToReview)
- feat(gateway): operator-triggered PR review with selectable reviewer model
- feat(workflow): surface adversarial review findings on the PR body
- feat(workflow): review calibration, checked properties and style nits out of contract
- fix(workflow): order findings before footer; test the report stash
- fix(archied): share one PR reviewer across channels; harden forge and worktree
- feat(worktree): Resume re-syncs a worktree onto its branch tip
- feat(telegram): support secret refs for bot tokens (#705)
- feat(gateway): wire progressive tool disclosure (bridge tools)
- feat(archied): serve the daemon's own health endpoint
- feat(archieui): standalone UI process over remote Gateway and State Store
- refactor(archied): move webhook capture intake to the process that owns work intake
- refactor(ui): sever the archie-ui binary from every daemon runtime package
- fix(archieui): resolve service tokens from env, without requiring a config file
-25
View File
@@ -1,25 +0,0 @@
# 1.24.0
Released 2026-09-12. [All news](index.md)
### archied
Makes 1.23.0 deployable. That release split archied into separate processes,
but the self-updater still installed only the `archied` binary and restarted
only `archied.service`, so updating to it left the State Store, Gateway and UI
on the previous release. archied cannot boot without a reachable State Store,
so the update failed its health check and rolled back. Update to this release
rather than to 1.23.0.
If your host does not yet run the four units in
`deployments/systemd-user-service.md`, create them first: the updater now
refuses, naming what is missing, instead of installing binaries onto a host it
would leave broken.
- fix(update): install and cycle every process in the release
- fix(telegram): stop the relay corrupting identifiers and code
Also in this release, though outside the version-stamped package closure:
- ci(deploy): produce a complete distribution zip on every release. No zip was
built for v1.23.0 at all, and the zip omitted `archie-ui`.
-21
View File
@@ -1,21 +0,0 @@
# 1.25.0
Released 2026-09-15. [All news](index.md)
### archied
- fix(update): resolve releases without a checkout, and fail loudly when it cannot
- fix(update): back up the task store the daemon actually uses, or refuse
- fix(update): build each component from its own approved release tag
Components are independently versioned, so the newest `archied/v*` and
`archie/v*` tags usually sit on different commits. The installer required both
tags to resolve to one commit whenever both components changed, which refused
every update once the two newest releases diverged -- a deployment stuck on
1.22.0 could not take any update. Each component now builds from its own
approved tag.
### archie-agent
- chore: no user-facing changes; versioned so the 1.25.0 release tags both
components at the same commit
-133
View File
@@ -1,133 +0,0 @@
# 1.26.0
Released 2026-09-17. [All news](index.md)
### archied
- fix(webui): publish per-identity forges so multi-identity task rows keep their links
- feat(config): add [scheduling] config block
- feat(configuration): translate [scheduling] into scheduling.EngineConfig
- feat(cronevents): adapt the events bus to scheduling.Sink
- fix(webui): count every chat front-end in the published projection
- fix(scheduling): respect configuration ownership
- feat(ratelimit): wire per-identity inbound rate limiting into the gateway
- fix(tools): judge the rm guard by base name so absolute paths cannot bypass it
- fix(store): keep an empty binding secret empty so a partial edit cannot erase it
- fix(archied): stop advertising review_pr when no reviewer can run
- fix(daemon): carry kind/label routing bindings to the process that routes
- feat(configuration): add archied setup, the caller the first-run flow was built for
- fix(configuration): stop letting a secret value be set from the command line
- feat(configuration): let setup reference a secret without carrying its value
- fix(archied): disable a provider whose credential is missing instead of refusing to boot
- refactor(install): install.sh delegates config generation, and tests stop reading hand-written configs
- fix(daemon): guard binding dispatch loop against nil dispatcher/creator
- fix(webui): enforce CSRF/origin gate on binding and mapping mutations
- fix(secret): recover a panicking secret engine instead of crashing
- fix(config): deep-copy Image.Hosted/Image.Local in Config.Clone
- fix(email): stop dropping the first paragraph of plain-text bodies
- fix(logging): keep the live descriptor open across a failed rotation
- feat(configuration): report config keys no decode target consumed
- feat(archied): warn at boot when the config file has unrecognised keys
- feat(archied): wire the scheduling ticker engine at boot
- fix(agentworker): wire configured tool-result policy into worker's LoopRunner
- refactor(staterpc): delete the superseded single-token auth interceptor
- refactor(memory): delete the unreachable <memory> fence scrubber
- fix(channels): delete unreachable Telegram webhook delivery mode
- fix(gateway): delete unwired Router.Dangerous approval path
- refactor(gateway): delete orphaned SessionState goal/steer/queue machinery
- refactor(archied): delete the daemon's unused webui.Server and UI adapters
- refactor(tools): delete unreachable dispatch/gating engine
- feat(channels): wire chat.webhook route config through to the gateway
- refactor(tools): delete unreachable AST-based tool discovery
- refactor(tools): delete unused plugin-tool registration API from builtin.Registry
- feat(channels): wire ConfigSchema/ValidateConfig into a startup validation loop
- refactor(state): delete the dead IncrementRetryCount RPC (breaking change, accepted)
- fix(curator): populate PassInput.Since with the prior pass time
- fix(memory): install the threat scanner the composition root never wired
- fix(staterpc): preserve marshal_error marker in eventDataJSON
- fix(gate): validate finding level and share the blocking threshold
- fix(scheduling): record a completed run so a recurring job stops re-firing every tick
- fix(releaseupdate): don't treat empty available as deferred
- fix(tools/provider/mcp): preserve MCP binary tool results for delivery
- refactor(gateway): share sensitive-key markers with webhookguard
- refactor(daemon): remove unreachable SQLite poll/drain path
- refactor(tools/mcp): delete unreachable MCP adaptation path
- fix(taskactions): resolve max_retries from the task's owning identity
- fix(daemon): forward configured MCP servers to task agents
- refactor(skill): delete dead Discover/DiscoverPlugins/Skill path
- refactor(skillbuild): delete dead AugmentRegistry path
- fix(builtin): bound read/edit filesystem work by DefaultToolTimeout
- refactor(binding): delete dead Matcher.Overlaps method
- refactor(forge): delete dead CreateIssue surface
- fix(mcp): cancel in-flight SSE reconnect on Stop
- fix(container): enforce MaxUptime lifetime cap with a timer
- refactor(store): use taskstate status constants in SQL
- fix(ui): unbreak binding approve and the two deletes, and centralise the client
- fix(tools): stop testing on the text of other files, and ungate contractaudit
- refactor(forge): delete the unwired RepliesAfter surface
- refactor(config): delete the two decoded-but-unread policy fields
This release is dominated by dead-code removal and the completion of the
scheduling capability. Roughly half the commits delete surfaces that no longer
had a caller: the unreachable SQLite poll/drain path, the unwired MCP
adaptation path, the AST-based tool discovery, the superseded single-token auth
interceptor, and several dead forge and binding methods. The
`IncrementRetryCount` State Store RPC is gone with them -- a breaking change to
the wire contract, accepted because nothing called it.
The cron/scheduling epic lands its remaining slices: the `[scheduling]` config
block, its translation into the engine's own settings, the events-bus sink
adapter, and the boot wiring that starts the ticker. A recurring job now records
a completed run, so it stops re-firing on every tick.
Operator-facing work: `archied setup` gives the first-run flow the caller it was
built for, configuration no longer accepts a secret value from the command line,
and a provider whose credential is missing is disabled rather than refusing to
boot. A secret engine that panics is now recovered instead of crashing the
daemon.
### archie-agent
- feat(config): add [scheduling] config block
- fix(webui): count every chat front-end in the published projection
- fix(scheduling): respect configuration ownership
- feat(ratelimit): wire per-identity inbound rate limiting into the gateway
- fix(tools): judge the rm guard by base name so absolute paths cannot bypass it
- fix(daemon): carry kind/label routing bindings to the process that routes
- fix(config): deep-copy Image.Hosted/Image.Local in Config.Clone
- fix(logging): keep the live descriptor open across a failed rotation
- fix(agentworker): wire configured tool-result policy into worker's LoopRunner
- refactor(staterpc): delete the superseded single-token auth interceptor
- refactor(tools): delete unreachable dispatch/gating engine
- feat(channels): wire chat.webhook route config through to the gateway
- refactor(tools): delete unreachable AST-based tool discovery
- refactor(tools): delete unused plugin-tool registration API from builtin.Registry
- refactor(state): delete the dead IncrementRetryCount RPC (breaking change, accepted)
- fix(staterpc): preserve marshal_error marker in eventDataJSON
- fix(gate): validate finding level and share the blocking threshold
- fix(tools/provider/mcp): preserve MCP binary tool results for delivery
- refactor(tools/mcp): delete unreachable MCP adaptation path
- refactor(skill): delete dead Discover/DiscoverPlugins/Skill path
- refactor(skillbuild): delete dead AugmentRegistry path
- fix(builtin): bound read/edit filesystem work by DefaultToolTimeout
- refactor(binding): delete dead Matcher.Overlaps method
- refactor(forge): delete dead CreateIssue surface
- fix(mcp): cancel in-flight SSE reconnect on Stop
- fix(container): enforce MaxUptime lifetime cap with a timer
- refactor(forge): delete the unwired RepliesAfter surface
- refactor(config): delete the two decoded-but-unread policy fields
The runtime carries a smaller, more focused set of changes than the same
version's archied entry: agent-side tool-result policy is now wired into the
worker's loop, MCP binary tool results survive to delivery, the container
`MaxUptime` lifetime cap is enforced with a timer, and a scheduled run records
completion so it does not re-fire each tick.
Note that several bullets above name config, webui and ratelimit packages. Those
are attributed here by the release tool's package-closure rule (`go list -deps`
over the agent binary), not because the agent owns them; the substantive
runtime changes are the worker, MCP, container and scheduling fixes.
This entry also confirms the removal of the dead `IncrementRetryCount` State
Store RPC, which the agent reaches through `staterpc` rather than by calling it
directly.
-50
View File
@@ -1,50 +0,0 @@
# 1.27.0
Released 2026-09-17. [All news](index.md)
### archied — Dashboard task logs
- Task logs are readable from the dashboard again, through a new State Store
read contract (`ReadTaskLog`, `StreamTaskLogContent`) rather than the UI
process reaching into the daemon's log files. Wired server-side by the
standalone state-store process.
- Added `GET /api/tasks/{id}/logs/download`, serving an attempt's raw log as a
`task-<id>-attempt-<n>.log` attachment.
- A process that cannot read logs and an attempt that recorded no log are now
distinguishable ("cannot read" answers 503, "no log" answers 404) instead of
both rendering as a claim about a configuration setting.
### archied — Telegram output
- Tool results are summarised rather than quoted: a search reports how many
matches came back, a truncated result reports the tool's own total. The
renderer no longer states a count it computed from its own truncated sample.
- Repeated successful tool calls collapse into one counted entry.
- The tool-activity block is capped to a third of the live frame, keeps the
newest lines, and marks what it dropped with a `+N earlier` indicator. Every
line that fits is kept.
- Every clamped answer marks its cut with an ellipsis, including the opening
frame, which previously appeared to begin mid-sentence.
- An error response from the log download no longer ships as a `.log` file.
### archied — Readiness and shutdown
- The disk probe reports per-filesystem results and checks the root filesystem
as well as the work directory, so a full root is no longer invisible.
- A path shared by several disk targets keeps the strictest requirement any
target places on it, so an optional target can no longer mask a required one.
- The shutdown-watchdog test no longer races the Go scheduler, which was
intermittently failing the quality gate and parking work unrelated to it.
### archied — Other
- Messages persist the channel-native sender id.
- go-telegram/bot bumped to v1.27.0, fixing a streaming bug where the multipart
body could not be replayed and `sendMessage`/`editMessageText` failed until
the connection dropped.
### archie-agent
- The per-task runtime picks up the new State Store task-log read contract, so
the sandboxed agents share one log-reading path with the daemon and the
dashboard.
-79
View File
@@ -1,79 +0,0 @@
# 1.28.0
Released 2026-09-19. [All news](index.md)
### archied — Task detail and attempt attribution
- New per-run task detail page, showing each attempt's own events, changes and
configuration rather than a single merged view.
- Events, changes and config are attributed to the attempt that produced them;
`Event` carries `attempt` and `ReadTaskLogRequest` carries `stage`.
- The task detail page remounts when the task id changes, so switching tasks
does not leave the previous one's data on screen.
### archied — Configuration
- Services are keyed by name through a registry, so the State Store and Gateway
listen addresses are configurable rather than fixed.
- A partial overlay no longer clears the fields it omits — an overlay that set
one key was wiping the rest.
- The Services map is cloned on publish, so an overlay can no longer mutate the
snapshot other readers are holding.
- The service context is enforced at registration.
### archied — Logging and park reasons
- A parked run's reason is recorded in its own attempt log, in both the daemon
and the workflow, so "why did this park?" is answerable from the task itself.
- `TaskRegistry.Write` takes the caller's context.
### archied — Worktrees and containers
- Retries recover from path-type conflicts instead of failing opaquely, and the
underlying cause is no longer masked.
- The worktree is handed back on every sandbox exit.
- A container's max-uptime reaper is cancelled on release, the cap stays active
through the grace period, and teardown is claimed once rather than by
cancelling a timer.
### archied — Daemon and startup
- Every identity's forge and repos are swept at startup, including the root
forge.
- A cancelled startup is no longer reported as an exhausted sweep budget; an
exhausted budget names itself as the cause.
### archied — Other
- `grep` can use the workspace codesearch index.
- Forge labels are matched when namespaced, so label-driven routing works for
namespaced labels.
- Triage is given criteria for choosing between workflows, and a workflow is
required when a code change is needed.
- The Telegram adapter restart callback is wired into the chat router.
- The `ARCHIE_REACTIONS` fan-out stream is provisioned and bounded by age.
- `archie-ui` exits cleanly when graceful shutdown overruns its deadline.
- The dashboard's event pump retries priming until the State Store answers.
- The update writer emits the agent version sidecar with a real newline.
- The UI finishes its Preact port; the imperative DOM layer is deleted.
- Collection fields decoded over the State Store gRPC contract are never nil
slices, so an empty collection marshals as `[]` rather than `null`.
### archie-agent
- The sandboxed runtime picks up the attempt-attribution contract, so the events
and changes an agent produces are recorded against the attempt that produced
them.
- `grep` can use the workspace codesearch index.
- A worktree is handed back on every sandbox exit, and container teardown is
claimed once — a released container's reaper is cancelled rather than
re-firing during the grace period.
- Retries recover from worktree path-type conflicts instead of failing
opaquely.
- A parked workflow run records its park reason in its own log.
- Triage criteria distinguish the workflows, and a workflow is required when a
code change is needed.
- Namespaced forge labels match when routing by kind.
- The `ARCHIE_REACTIONS` fan-out stream is provisioned.
- Collection fields decoded over the State Store gRPC contract are never nil
slices, so an empty collection marshals as `[]` rather than `null`.
-65
View File
@@ -1,65 +0,0 @@
# 1.29.0
Released 2026-09-19. [All news](index.md)
### archied — Security
- `google.golang.org/grpc` bumped past `v1.84.0` to patch
[GO-2026-6443](https://pkg.go.dev/vuln/GO-2026-6443), a server panic via a
missing `:authority`/`Host` header reachable through `archied`'s gRPC
gateway server. No stable release carries the fix yet, so this pins the
pre-release commit that does (`v1.85.0-dev.0.20260825072537-93e31b48545e`)
until `grpc-go` cuts `v1.85.0`.
### archied — Memory engine unification
One memory engine, addressed by four typed scopes (global, agent, user,
agent-user), replaces the two disconnected stores that previously existed:
a chat-tool-written store nothing ever read back, and a curator-written store
with no scope model.
- `internal/domain/memory` is a CRUD contract (`Create`/`Get`/`Query`/`List`/
`Update`/`Forget`/`Revisions`) with retained revisions; updates supersede
rather than overwrite, so a crash mid-write leaves a recoverable extra
history entry, never a lost prior state (#886).
- The chat turn reads its subject's scopes synchronously before the prompt is
built, rendering recalled records into a `<memory>` block; a failing or
panicking engine degrades to no memory block rather than failing the turn
(#887).
- The model writes memory through four id-addressed tools
(`memory_create`/`update`/`delete`/`list`), scoped to the turn's own
resolved identity -- the model chooses the scope kind, never the ids, so it
has no path to write into another user's memory (#888).
- The session curator now derives the agent-user scope from the session's own
user-role messages, instead of keying facts by a session id that stops
meaning anything once the session ends.
- A channel with no resolvable user (dashboard, webhook) reads and writes only
global and agent scope; a webhook's route path is never treated as a user
identity.
- Fixed a review finding on the read path: the per-scope record limit was
being applied as one shared total across all scopes rather than per scope,
and the rendered block's byte cap was checked before template escaping
rather than after, letting the escaped block exceed it.
### archied — Work intake
- feat(workintake): define review reaction envelope
- feat(workintake): authorize review reactions by owned PR
### archied — Cleanup
- Deleted the unwired plugin capability-host health surface
(`Host.Health`/`Host.Manifests`/`ModuleStatus`) and the `Module.Health`
chain it fed -- including the `mcp`/`builtin` tool-provider health
implementations and their aggregation in `tools/provider.Registry` -- none
of which had ever had a production caller (#882).
### archie-agent
- The sandboxed runtime picks up the review-reaction envelope and its
owned-PR authorization, so an agent can only react to reviews on pull
requests it opened itself.
- `google.golang.org/grpc` bumped past `v1.84.0` to patch
[GO-2026-6443](https://pkg.go.dev/vuln/GO-2026-6443) (shared dependency
with `archied`; the pre-release commit is pinned pending a stable
`v1.85.0`).
-24
View File
@@ -1,24 +0,0 @@
# 1.3.0
Released 2026-08-08. [All news](index.md)
### archied (released 2026-07-31)
- fix(memory): replace framework-specific names with generic equivalents
- feat: unify provider and model selection
### archie-agent
- feat(curator): engine family contract, registry, and runtime
- feat(curator): trigger accounting — primary-input wake path
- feat(logging): optional rotating log file
- feat(daemon): identity-scoped isolation
- fix(secrets): wire provider credentials through engines
- fix(store): surface task timestamps and tag the summary structs
- fix(tools): let an optional provider fail without taking the daemon down
- fix(tools): report a cancelled find walk as an error, not empty results
- fix(worktree): name the missing forge credential when a push fails
- fix: close the duplicate-work loop and the dead paths around it
- perf(tools): drop the embedded ripgrep binaries
- refactor: one definition of what approving or declining a task means
- refactor: move workflow into its own domain
-7
View File
@@ -1,7 +0,0 @@
# 1.3.1
Released 2026-07-31. [All news](index.md)
### archied
- fix(telegram): omit empty model picker markup
-131
View File
@@ -1,131 +0,0 @@
# 1.30.0
Released 2026-09-20. [All news](index.md)
### archied — Messaging Service extraction completed
Telegram, email and webhook no longer run inside the daemon. They run in
`archie-messaging` and reach the daemon through the Gateway's `ChatContract`
over gRPC; the daemon builds no channel and no `gateway.Router` (#899).
- The operator surface is re-wired in the extracted service: `/update` (built
from its own `[chat.telegram]` commands), the update-report relay, the
`show_tool_calls` projection, and `/restart`'s config reload, which
re-resolves the token and allowlist from this service's own file and refuses
a reload that resolves to an empty token.
- `/version` is sourced from the Gateway through a new `ChatSnapshot.Version`
field. `cmd/archie-messaging` deliberately takes no version ldflags, so it
cannot report a partial upgrade as a matched one.
- Channel configuration is validated at composition, so a configured-but-
invalid front-end fails the service instead of being silently dropped.
- The inbound rate limiter moves to the Gateway, which now owns the only
Router and is therefore the one place a per-sender budget can apply to every
channel's turns.
`RunningVersions` and `ReleaseAnnouncements` are deliberately left unwired:
both need a component's real running version, and the only versions this
process can obtain are another binary's stamps. See
`docs/architecture/migration-decisions.md`.
### archied — Configuration
- `diff_cap_lines = 0` now switches the cap off, as the dashboard and the
workflow step have always documented. It was a plain `int`, so the defaults
pass could not tell an absent key from an explicit `0` and rewrote both to
400 -- the documented way to disable the cap was unreachable. **Behaviour
change:** a config that set `0` was silently getting 400 and will now get no
cap.
- The same ambiguity was failing open per identity: `configForIdentity`
assigned the identity's value unconditionally, so an identity that merely
omitted `diff_cap_lines` overwrote the shared cap with the zero value and
disabled the safety rail entirely. An identity now overrides only when it
sets the key.
- A diff-cap park no longer tells the operator to "approve manually". A parked
task's actions are retry, abandon and reject, so there is no approve path out
of diff-cap; it now names the two things that work.
- `[health].dependency_timeout` makes the daemon's readiness probe timeout
configurable, matching the extracted services.
### archied — Chat rendering
- `/status` and `/tasks` are line-oriented reports but separated lines with a
plain newline, which is CommonMark's soft wrap: the Telegram renderer joined
them into one run-on paragraph. The renderer implements CommonMark's hard
line break and the reports use it. Ordinary prose still soft-wraps.
- A park reason is capped to its first line in the `/tasks` list. It carries
whatever the failing stage reported, which for a lint gate is a whole tool
log; unbounded, one parked task pushed every other task out of the reply. The
full reason is unchanged on the task, in `task_list` and on the dashboard.
### archied — Review
- Review findings are posted as line-anchored PR comments with suggested fixes,
and a suggestion must be single-line -- GitHub applies a multi-line suggestion
only up to its first line, silently corrupting the file (#891).
- The remediate workflow handles PR review comments and requested changes.
### archied — /status health surface
`/status` reports the live broker connection and the last-known outcome of this
process's chat-model calls, alongside the queue depth and runtime block (#892).
- A provider error is flattened and capped, so a multiline or oversized error
cannot break the one-line-per-fact layout.
- Concurrent model calls no longer reorder: the completion time is taken before
the lock, so the newer outcome wins rather than whichever goroutine stored
last.
- Curator model calls are recorded too. They bypass the chat path, so a daemon
whose only recent model traffic was curator work reported "no calls attempted
yet" while the provider was demonstrably reachable.
- Title generation does not record health. It runs detached under its own
bound and its error is swallowed, so a cosmetic timeout was overwriting the
line with "failed".
**Known limitation:** the container, poll and channel sections cannot render.
Those facts live in the daemon, but the only Router lives in the Gateway
process, which has no container pool and no poll loop. The command description
says what actually appears; restoring the rest needs a cross-process health
contract.
### archied — Dashboard and containers
- The served lifecycle vocabulary reaches an already-painted page, the page
registry matches the routes, and the build verifies `ui/dist` is fresh
instead of never looking at it (#890, #898).
- The container reaper no longer deletes teardown bookkeeping early, so a
released container is not torn down twice (#893).
### archied — Build
- `task fmt` runs `golangci-lint fmt` -- the same engine and configuration the
gate checks with. Standalone `gofumpt` cannot reproduce gci's import
grouping, so formatting and linting could not converge and no command
satisfied the gate (#901).
- `goimports` is deliberately absent from the formatter set: it re-reads and
re-parses the module index once per file, ~135s across this tree.
### archied — Fixed
- `Config.Clone` left the new diff-cap pointers aliased, so a clone could write
through to the published snapshot (#902).
- A curator asking for a completion on a daemon with no configured provider
panicked the process; it now returns an error.
### archie-agent
- The sandboxed runtime picks up line-anchored review comments: a finding is
posted against the line it is about, with a suggested fix where it has one,
and a suggestion is rejected unless it is single-line -- GitHub applies a
multi-line suggestion only up to its first line, silently corrupting the
file (#891).
- `diff_cap_lines` is an optional value in the shared config the runtime
reconstructs, so an explicit `0` means "no cap" rather than being rewritten
to the default. **Behaviour change** for a repo that set `0` expecting
unlimited and was silently getting 400 (#899).
- A diff-cap park names a remedy that exists: a parked task's actions are
retry, abandon and reject, so the reason no longer says "approve manually".
- A released container is not torn down twice -- the reaper no longer deletes
teardown bookkeeping before `Release` is finished with it (#893).
- Build toolchain: `gofumpt` and `golangci-lint` are pinned as one matched
pair, and `task fmt` uses the same engine the gate checks with, so the
runtime's own gate is satisfiable (#901).
-149
View File
@@ -1,149 +0,0 @@
# 1.31.0
Released 2026-09-22. [All news](index.md)
### archied — Dashboard replaced: Preact -> Vue 3 + shadcn-vue
The dashboard is now a Vue 3 application built on shadcn-vue. This is the
large piece of this release; it touches every page.
- History routing, a grouped topbar built from components, the violet palette
with self-hosted Geist, and a command palette with live tasks.
- Chat is a FAB-opened panel that behaves like a chat window and scrolls its
transcript with `MessageScroller`.
- Task actions and dangerous approvals are deliberate; the task detail page is
a single head strip with honest states; the run page settles its head around
an attempts pager, which is hidden for zero or one attempt.
- Appearance and System navigation were refined, with a four-column appearance
grid on wide screens.
- A copy pass removed redundant tails and restating descriptions, empty states
derive their own titles, and a stuck log read surfaces as an error rather
than eternal loading.
- The capture pane is bound to the list it sits beside and reads beside it,
not over it.
### archied — Events is one page with three tabs
- Inspector, Bindings and Mappings are now tabs of a single **Events** page.
- The nav entry is always live, the tabs prune by capability, and the three old
paths survive as bookmarks that redirect to their tab.
- Tab selection lives in one module (`ui/src/events/tab-selection.ts`) that the
page uses, rather than a copy of it.
- `feat(tools)`: a capture-intake sender exists for exercising the Events
surfaces.
### archied — The channel travels with the message
`SessionSource.Platform` -- the first component of the session natural key, and
the column `GetByChannel` filters on -- was a constant `"web"`, because one
Router serves every channel and named itself after its own. Two things followed:
the per-user identity policy was real code that no production call site reached
with a real channel name, and a curator pass's write to agent-user memory could
not be read back by the turn that wrote it, because that turn resolved no
`UserID`.
- The frontends now name the channel they carry (`telegram`, `email`,
`webhook`, `web`), the channel rides the message, and the Gateway stamps the
session from it -- falling back to its own name when a sender names none,
which is what every existing row holds.
- Identity resolution reads the platform off the inbound, so `carriesPersonIdentity`
decides something in production: telegram and email resolve a person, the
dashboard and a webhook resolve nothing, and an unknown platform fails closed.
- **Behaviour change:** a chat whose active session came from `/new` or
`/branch` re-resolves once, because session lookup now filters on the
channel's real name. A chat without `/new` re-resolves onto the same
deterministic id and heals silently.
- Deliberately unchanged: `TurnRunnerConfig.Channel` still keys tool
availability, so no channel gains or loses a tool in this release.
### archied — Control plane: runtime administration, history, and derived schemas
- The State Store's gRPC server now carries runtime administration, and each
process reports which settings version it is running; the dashboard shows it.
- Resource history is exposed so edits can be reviewed and rolled back, and
resource schemas are derived from the documents they describe -- the document
editor reads the derived schema (labels from `title`, `format: duration` ->
`1m0s`, hints from `doc`), and the abandoned schema-driven card is deleted.
- A live settings replacement is checked before it is switched to, the daemon's
state surfaces are folded into one boot step, and a SIGHUP reload re-applies
database-owned settings.
- Forge intake settings that nothing reads are now rejected at load.
### archied — Configuration: judged where it is owned
- The runtime config overlay is deleted; database-owned settings are judged at
the layer that owns them rather than on the file load path.
- A file overlay no longer drops the fields it omits inside a map entry, and a
kind with no stored value leaves the file's value in force.
- The default config path is resolved in one place, and the channel document
has its own shape.
### archied — State Store: offline backup, restore, validate and rollback
- New offline backup / restore / validate / rollback path.
- `validate` runs boot's own gate; it no longer replaces the database, reads a
kind the store does not hold as its seed, or touches the daemon's log.
- The recovery control-plane server is built on the shared step vocabulary.
### archied — Workflow: one step vocabulary and a `gate.diff-rules` replacement
- The step vocabulary is owned by a family manager registered at each
composition root, replacing `.archie/gate.go` with `gate.diff-rules`, which
fails closed on a change it never read.
- Workflow roots are pinned and the dead vocabulary is removed; the workflow pin
crosses the wire.
- The schedules resource skips the legacy cron jobs it cannot hold, and the
scheduling policy carries the label its trigger pairs with.
### archied — EDA: the playbook coordinator reaches production selection
- The playbook coordinator is wired into production workflow selection, so a
matching playbook decides a real task's workflow at the daemon's definition
pin, inheriting idempotency from `TaskEnvelope`.
### archied — Reliability and operations
- `cronstore` writes a schedule interval as a duration, not nanoseconds -- a
persisted `1m` no longer round-trips as `60000000000`.
- Worktrees are cut from the mapped base branch, and the Gateway's worktree
manager is built so it serves `review_pr`.
- A late max-uptime callback no longer resurrects teardown state.
- The state store dial installs client keepalive, and its server policy accepts
the dialer's pings; control-plane watch streams re-establish themselves after
they end.
- `/status` serves only the health facts a reply can carry; the daemon reports
systemd readiness and loop-driven watchdog heartbeats.
- A webhook route path no longer becomes a sender identity.
- A chat session compresses when a turn crosses its context budget.
- The MCP client supports per-server `parallel_tool_calls`, carried through the
tool-settings projection.
- Resource request-ID idempotency keys are scoped to their kind.
- The session curator addresses memory by the deployment's bot user.
### archie-agent
The sandboxed runtime links the same shared packages as archied, so this
release carries the control-plane and workflow changes alongside it:
- Runtime administration over the State Store's gRPC server, resource history,
and control-plane apply status on the store contract.
- The shared step vocabulary, owned by a family manager registered at each
composition root, and `gate.diff-rules` in place of `.archie/gate.go`
(fails closed on a change it never read).
- The workflow pin crosses the wire.
Runtime-specific changes:
- `refactor(plugin)`: the unused `Registry` type is deleted.
- `yaegiutil` refuses incomplete Yaegi interface wrappers at load rather than
running them.
- The runtime config overlay is deleted.
- The state store dial installs client keepalive, and the server policy accepts
the dialer's pings.
- The MCP client supports per-server `parallel_tool_calls`.
- A late max-uptime callback no longer resurrects teardown state.
- A webhook route path no longer becomes a sender identity.
Note: the `archie-agent` image is rebuilt by this tag through CI
(`.github/workflows/deploy.yml`); a gateway-only release would not have rebuilt
it. `docker compose pull agent` is required to pick it up.
-38
View File
@@ -1,38 +0,0 @@
# 1.32.0
Released 2026-09-22. [All news](index.md)
### archied — EDA: playbook action ids, and a dispatch idempotency ledger
- **Action ids (J1).** Every action a later action references must now carry an `id`. Ids are
validated at load -- unique and stable-identifier-shaped -- and a `when`/`args` expression
naming an unknown `actions.<id>` is a **load failure**, not a runtime miss, the same
reject-at-load rule already applied to a binding collision.
- **Reference classification is strict at load.** A map-index reference (`actions[expr]`), a
non-literal index, and a reference to an unknown prior id are all rejected when the playbook
loads; references are classified by identifier versus static access, and the when-compilation
helper is shared between the load-time and runtime paths.
- **Dispatch idempotency ledger.** A `playbook_dispatches` row records a dispatch against
`(playbook_id, playbook_version, event_id, action_id)`, written with `INSERT OR IGNORE` and
surfaced through the shared `store.ErrAlreadyDispatched` sentinel. Module, channel and forge
action positions are therefore at-most-once, which is what unblocks the side-effecting
positions that were previously rejected at load.
- **The ledger is wired into production.** `stateStoreDeps` constructs `Deps.PlaybookDispatcher`,
so the ledger RPCs no longer answer `Unavailable` in a running daemon. This defect was found
by the pre-release review of this change rather than by its tests.
**Behaviour change:** a playbook whose actions reference `actions.<id>` without declaring that
id, declare a duplicate id, or index `actions` with a non-literal value now fails to load
instead of failing at dispatch time.
### archie-agent
The sandboxed runtime links `storecontract` and `staterpc`, so it carries the dispatch-ledger
contract alongside archied:
- The shared `store.ErrAlreadyDispatched` sentinel now describes both dedup ledgers --
`binding_dispatches` per `(binding_id, capture_id)`, and `playbook_dispatches` per
`(playbook_id, playbook_version, event_id, action_id)`. Each is an at-most-once guarantee.
- `RecordPlaybookDispatch` is part of the store contract the runtime builds against.
archied and archie-agent move together in this release.
-24
View File
@@ -1,24 +0,0 @@
# 1.32.1
Released 2026-09-22. [All news](index.md)
### archied — Host packaging: `archie-messaging` now ships and updates
- `cmd/archie-messaging` is included in the distribution zip, and `scripts/archie-update-install`
installs and restarts it.
- **Why this mattered.** v1.30.0 moved Telegram, email and webhook out of `archied` and into
`archie-messaging`, but nothing packaged the new binary. A host install that upgraded across
v1.30.0 therefore ran on with **no messaging process at all**: `archied` logged that it stopped
serving the telegram gateway, nothing replaced it, and Telegram stayed dead — with no error
logged anywhere, because nothing was failing. The process simply did not exist.
- The host component set was enumerated in four places — the zip's build loop, the zip's copy list,
the installer's service list, and the installer's binary list — and `archie-messaging` was missing
from all four. The duplication was the defect: a single test now derives the host-run commands
from `cmd/` and asserts that all four lists agree with it, so adding or extracting a process fails
until it is packaged.
- `deployments/systemd-user-service.md` gains the messaging unit. That is load-bearing rather than
cosmetic: the updater refuses an update when a service unit is missing and tells the operator to
create one from that document, which previously had nothing to offer.
**Upgrade note:** a host that reached v1.30.0 without a messaging unit has been running with no
Telegram, email or webhook. Updating to this release installs and starts `archie-messaging`.
-24
View File
@@ -1,24 +0,0 @@
# 1.33.0
Released 2026-09-22. [All news](index.md)
### archied — EDA: playbook action arguments are compiled at load (J2)
- A playbook action may now declare `args`, compiled as CEL expressions when the playbook loads.
`args` and `when` share one compilation path and one evaluation context, so an expression written
for one works in the other.
- **Behaviour change:** an `args` expression that does not compile is a **load failure**, not a
runtime miss — the same reject-at-load rule already applied to a binding collision and to an
unknown `actions.<id>`. In practice, a daemon loading a playbook with a malformed `args` block
fails at startup rather than part-way through a dispatch.
- Compiling several arguments now reports the **first** bad key deterministically (keys are sorted).
Previously it ranged a map, so the reported bad key could differ between runs and the failure was
not reproducible.
- `args` is deliberately **inert** for now: parsed, compiled and stored, but no shipped position
consumes it yet. A consumer arrives with the first side-effecting position.
**Not yet decided:** how an `args` evaluation failure behaves at dispatch. The `when` predicate rule
(error, skip, log) does not obviously transfer, because `args` is data rather than a predicate, and
silently skipping an action whose arguments failed to evaluate would be a silent failure of exactly
the kind this release train has been removing. It currently propagates the error to the caller, and
that asymmetry is documented at the code. Ratifying it against a real consumer is tracked separately.
-22
View File
@@ -1,22 +0,0 @@
# 1.34.0
Released 2026-09-22. [All news](index.md)
### archied — Dashboard: an actionable authentication failure state
- An unauthenticated **document** request now receives a self-contained HTML page with a
paste-the-token form, instead of plain text. Previously the whole dashboard -- `index.html`, the
bundle and every asset -- sat behind the token check, so a bookmarked bare URL returned a
`text/plain` "unauthorised: open the dashboard URL archied logged at startup", the SPA never ran,
and none of the dashboard's existing failure surfaces were reachable at all.
- The response is still **401**, with `Cache-Control: no-store` and a CSP. It is deliberately not a
200: a login page served as success would be cacheable, would read as healthy to anything that
checks status alone, and a shared cache could hand it to the wrong person.
- API and stream callers are unaffected. `application/json`, `*/*` and `text/event-stream` requests
keep the plain-text 401, with a test pinning that split so an XHR or an `EventSource` reconnect can
never start receiving a page.
- The auth banner gains a **Retry** action that re-runs the dashboard's bootstrap reads, so a
recovered session is actionable without a browser-level reload. It deliberately does not re-drive
the SSE stream, which already reports its own reconnect state.
- The page's guidance stays generic: it points at the dashboard URL the daemon logs rather than
naming where the token is stored, so the HTTP layer is not coupled to the token file's location.
-56
View File
@@ -1,56 +0,0 @@
# 1.35.0
Released 2026-09-22. [All news](index.md)
### archied — The Messaging Service is severed from the store and workflow runtime
- `cmd/archie-messaging` no longer links `modernc.org/sqlite`, `internal/store`,
`internal/domain/workflow` or `internal/agentexec`. All four arrived through a single import of
`internal/app/controlplane`; the client half now lives in
`internal/infrastructure/controlplanerpc`, and the app package keeps the server, the registry, the
seeds, the validators and the schema derivation.
- The resource documents are type-aliased back into the app package, so there is one definition read
under two names rather than a copy per side.
### archied — Channel lifecycle reaches the dashboard
- The Messaging Service reports each channel's state, recorded **per channel**: one channel's failure
marks only itself, a channel that cannot start is marked failed **with its reason** rather than only
logged, and one that returns is marked stopped. `internal/channels/status.Manager` reports each channel's state.
- `PutChannelStatus`/`ListChannelStatus` carry that to the dashboard, following the config-snapshot
split. The store **replaces the reported set**, so a channel the reporter stops mentioning is
deleted rather than left as a stale `running`; an empty report clears the table, because hosting no
channels is a fact worth reporting; and an id-less row is refused, since it could never be replaced
or removed by a later report.
- `Service.ReloadChannel` routes to the channel's own seam and refuses a channel that cannot reload
with a reason rather than accepting and ignoring it. `ReloadSupported` was previously declared **by
name**, so a channel could advertise reload with nothing behind it; one function now decides both.
### archied — Action playbooks: a second playbook shape, with typed results
- A playbook is now one of two shapes: a **workflow playbook** (exactly one `workflow` action,
unchanged) or an **action playbook** (one or more `module` actions in order). A playbook does not
mix them.
- `args` and `when` share one compilation path and one evaluation context, and `actions.<id>` is typed
by the kind that action runs, so a misspelled result field, an unknown id, a map index, `in`, a
comprehension, or a shape-foreign key (`kind` on a `workflow` action, `workflow` on a `module`
action) is a **load failure** rather than a dispatch failure.
- **Action playbooks load but do not run yet.** Routing arrives with the first side-effecting
position; the daemon warns at load rather than accepting them silently.
- The CEL environment is built per playbook, because result typing depends on the ids a playbook
declares.
- `ModuleRegistry.DecodeResult` turns a kind's flat map result into its typed `Result` before a later
expression reads it. Without it a typed read evaluated against a shape the run never produces, and
so silently read null.
### archie-agent
The sandboxed runtime links the same shared packages as archied, so this release carries the
channel-lifecycle store contract and the stricter action-load errors with it:
- The channel-status store contract (`PutChannelStatus`/`ListChannelStatus`) and its replace-the-set
semantics.
- Authoritative module ids and stricter action load errors: a misspelled result field, an unknown id,
or a dynamic `actions` read now fails the playbook load rather than the dispatch.
archied and archie-agent move together in this release.
-23
View File
@@ -1,23 +0,0 @@
# 1.36.0
Released 2026-09-22. [All news](index.md)
### archied — The dashboard declares tools an in-browser agent can call
- The dashboard registers **seven WebMCP tools**. Read-only: `list_tasks`, `get_task`,
`recent_events`, `daemon_health`. Recovery: `retry_task`, `stop_task`, `cancel_task`. An agent
operating the dashboard now reads structured state and recovers stuck work instead of scraping the
UI.
- Every tool 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.
- `archie-ui` cannot be attributed to the agent that called it: a page can invoke its own tools, so an
agent's call and a page script's call reach the server identically. Tools therefore record the
signed-in identity and a source, and **never** that an agent acted.
### archied — Binaries built by the development build task can be updated
- `task build` passed the `installtype` stamp for three of six commands, so `archie-messaging`,
`archie-state-store` and `archie-ui` were built without it. An unstamped binary reports `unknown`
and the self-update path **refuses rather than guesses**, which is how an operator ends up unable to
update with `install type is unknown` and no way forward. All six are stamped now, and a test reads
the build task and fails naming any command line that omits it.
-44
View File
@@ -1,44 +0,0 @@
# 1.37.0
Released 2026-09-22. [All news](index.md)
### archied — A request is attributed to the identity that made it
- **A browser can sign in, and an action taken through it records the person.** The dashboard validates a
provider-issued token, resolves it to an identity, and attaches it to the request; the task-action record
then names the actor. `Authenticate` and the sign-in callback share one resolver, so a browser sign-in
cannot be accepted on terms a presented token would be refused on.
- **archie issues no session.** The callback stores the provider's own token in an HttpOnly cookie and every
later request re-verifies it, so nothing archie holds can outlive the provider's decision and there is no
session table to expire, revoke or get wrong.
- **The event kind describes the actor.** A person's approval records `human_approved` as that person; an
agent's records `agent_approved`; an action with no authorising principal records `task_approved` with the
attribution fields **empty**. Nothing is credited to an identity that did not act, and an unattributed
action is recorded as unattributed rather than guessed.
- The acting identity is derived from the presented credential and **never** from a request field: a body
carrying `actor`, `actor_id`, `identity` and an `X-Archie-Actor` header still cannot choose it.
### archied — A host install now works, and an update refuses a host it cannot keep consistent
- `install.sh` writes and enables **all five** host units; previously it seeded only `archied.service`, so a
fresh host ran one service of five and an operator applied the rest by hand from a runbook. The runbook is
a description again: it names the units and points at `systemctl --user cat`.
- **Every host binary reports its version**, and the updater reads all of them **before it can report
"nothing to install"**. A host whose binaries disagree is refused, naming each one: a newer messaging
binary beside an older state store crash-loops against a service the older store does not serve, and that
install previously looked healthy from the updater's point of view.
- The packaged, installer and updater command lists are pinned by a test, so a service added to one and not
the others fails the gate instead of shipping a partial install.
### archied — A release image can be traced to a commit
- The publish step derives the commit by **dereferencing the ref** rather than reading `github.sha`, because
every release tag in this repository is annotated and a tag's object id is not a commit. An immutable
`sha-<commit>` tag is published alongside `:latest`, and a build with no release tag is stamped
`dev+<short sha>` rather than a bare `dev` that identified nothing.
### archied — Curator definitions are data, not a second registry
- Curator definitions may come from configuration or code and run through **one** engine into the existing
registry — no parallel authority and no second config reader. A definition declares its tools, and an
unknown tool name fails rather than widening the set silently.
-34
View File
@@ -1,34 +0,0 @@
# 1.37.1
Released 2026-09-22. [All news](index.md)
### archied — A recorded event names the actor in its own fields
- **Event attribution survives the trip to the State Store.** The acting
identity, its kind, and the authorising principal are carried on the event
itself, so an audit query finds the actor in its own fields rather than only in
the event's prose. An approval taken through the dashboard is the case that
exposed the gap.
### archied — A chat reply that contains code renders the way it was written
- **A code fence closes only on a run of the same character that is at least as
long as the one that opened it.** A four-backtick fence, a tilde fence, or a
reply that wraps its own code in a longer fence now arrives as code instead of
as a broken language tag or paragraphs of leaked text.
### archied — A tool call is one line with its own icon
- **A tool call takes a single line instead of a label plus a fenced block.**
Telegram draws a fenced block as a full code widget — language header, copy
button and panel — and the block parser inserts a spacer before it, so a
handful of calls filled the screen to show a few word counts. Each call now
shows the icon its own tool declares, and a tool that declares none renders
without one.
- **The status word prints only when the outcome is not success.** Every tool
line previously read "done", including the ones that had not finished.
### archied — Runtime dependencies updated
- **Runtime dependencies updated**, including the OpenID Connect and OAuth
libraries.
-81
View File
@@ -1,81 +0,0 @@
# 1.38.0
Released 2026-09-23. [All news](index.md)
### archied — Event capture, mappings and bindings are PocketBase records
- **Captured events, field mappings and playbook bindings live in PocketBase
collections instead of SQLite tables.** They are ordinary records, which is
what lets a binding be changed at runtime rather than by editing a database.
- **A read-only operator surface over the task database ships with the State
Store** (`archie-state-store -admin-addr`). It serves view collections over
tasks, transitions, events, identities and resources, and refuses
`/api/backups` and `POST /api/sql`, so it cannot rewrite state or hand out the
database file.
- **A binding cannot go live without approval.** It moves draft → pending
approval → armed; one binding per source is enforced on insert, on edit and
on approval; and an edit always returns it to pending approval. A secret left
blank on an edit keeps the stored one rather than disarming a live binding.
- **The workspace code-search indexer is gone.** No deployment configured it,
and it was one more resident writer over the workspace.
### archied — Editing a binding or a mapping shows on the activity stream
- **A dashboard edit no longer needs a manual refresh.** A successful binding or
mapping write announces itself on the same activity path a captured event
already uses. The announcement carries the record id and the action and the
dashboard refetches the record, so the signal cannot go stale.
### archied — Cron schedules fire
- **A cron job computes its next run and fires.** Until this release a cron
schedule was accepted at creation and then refused at run time with
`ErrScheduleUnsupported`, so a cron job never ran.
- **The dialect is PocketBase's, and it differs from Vixie cron on one point.**
Day-of-month and day-of-week are combined with AND rather than Vixie's OR, so
`0 0 1 * 1` means Monday the 1st, not "the 1st, or any Monday". The
`@daily`-style macros behave as usual. An expression that can never match,
such as `0 0 30 2 *`, is rejected instead of being left to run forever.
### archied — Tool calls are queryable
- **Every completed tool call is a row in the `tool_calls` collection**, not
only a line in the on-disk task log. The row carries the task, the attempt,
the tool, its result or its error, and when it ran.
- **A failed projection never fails the task.** The event is the record and the
collection is a transcript of it, so a copy that could not be written is
logged and counted rather than propagated.
### archied — A task whose identity no longer resolves parks instead of acting as root
- **A task naming an identity archie no longer knows — renamed, retired or
removed in the control plane — no longer falls back to the root forge's
credential.** It parks with the reason recorded. A task arriving over NATS
with such an identity is refused before it is enqueued. A task with no
identity is the single-identity root path and is unchanged.
### archied — The PR review is published as a readable artifact
- **A completed review is rendered to markdown and published to the
collaborative editor**, so a person reads it and comments on it instead of
reading a wall of text in a pull-request comment.
- **Publishing never fails the review.** With `[artifacts] base_url` unset the
sender is not constructed and publishing is a log line; a publish that fails
is logged with its status and the same review is republished the next time it
completes. Set `[artifacts] token` (or `WORKSPACE_INGEST_TOKEN`) to enable it.
### archied — The activity feed no longer depends on row ids being monotonic
- **The feed's resume cursor is opaque, and a malformed or pre-upgrade cursor
degrades to "from the beginning" rather than failing the stream.** One
consequence on upgrade: a browser holding a cursor issued before this release
replays the backlog once.
### archie-agent
- **The runtime image is rebuilt by this release, and a host must pull it**
(`docker compose pull agent`). The shared State Store contract changed shape
in the sections above — task and event-capture id fields are strings now — and
the two halves are versioned together, so an agent image built before this
release does not speak to the new State Store. There are no agent behaviour
changes of its own in this release.
-25
View File
@@ -1,25 +0,0 @@
# 1.39.0
Released 2026-09-23. [All news](index.md)
### archied
- **Archie now acts on review comments left on its own pull requests.** A
requested-changes review (or a standalone comment) on a PR Archie opened
dispatches a remediation run: the smallest change that satisfies the
feedback, committed to the same PR branch and answered in the review
thread. Approved reviews never remediate, each reaction is its own round,
and the exchange is bounded by the repo's `max_retries` before Archie stops
and says so on the PR.
- **The task run page is a master-detail view.** The run's stage rail and
detail panels sit beside the run list, so one run's timeline is visible
without leaving the page.
- **Live activity groups related updates instead of stacking them by event
kind**, so a burst of progress on one task reads as one story, and the
stage filter resets when you switch attempts.
- Contrast fixes on the info and subtle text tokens clear WCAG AA.
### archie-agent
- The review-reaction remediation path is part of this image; a host that
runs the agent should `docker compose pull agent` to pick it up.
-28
View File
@@ -1,28 +0,0 @@
# 1.4.0
Released 2026-08-10. [All news](index.md)
### archied (released 2026-07-31)
- fix(secrets): wire provider credentials through engines
### archie-agent
- feat(gateway): tool-approval gate, session tools for chat, and /delete command
- feat(gateway): make chat turns durable and idempotent
- feat(webui): lifecycle-safe task controls with atomic retry and archive
- feat(logging,workflow): daemon log feed and executable workflow registry
- fix(store,gateway): taskstate constants and mobile jump-to search
- feat(webui,gateway): wire config, channel, log-feed, and work-intake seams
- fix(build): install ripgrep where grep.go actually needs it on PATH
- fix(workflow): carry gate output into the baseline park error
- feat(logging): add a per-task log sink
- feat(agentexec): publish agent-side logs to the task's system subject
- feat(daemon): consume agent system logs into per-task sinks and the dashboard feed
- feat(webui,gateway): add /api/tasks/{id}/logs endpoint and task_logs chat tool
- refactor(store): replace legacy persistence with SQLite
- refactor(daemon,webui): make Daemon.Cfg and webui.Server.Cfg reload-safe
- feat(config): SIGHUP-triggered reload with requires-restart warnings
- feat(config): surface overlay state, shadowed keys, and per-row reset
- fix(config): close review blocker on the PATCH path; deep-copy snapshots; atomics for shared state
- fix(config): preserve nil slices in Clone to avoid spurious reload warnings
-7
View File
@@ -1,7 +0,0 @@
# 1.4.1
Released 2026-07-31. [All news](index.md)
### archied
- fix(catalog): match SDK provider fallback
-27
View File
@@ -1,27 +0,0 @@
# 1.40.0
Released 2026-09-23. [All news](index.md)
### archied
- **Every park now says what kind of intervention it needs.** A parked task
is classified as `needs you` (a decision or fix only an operator can
supply), `transient` (an environment problem -- container pool, storage,
transport -- retry once it is fixed), or `terminal` (the repository or
identity cannot act; retrying cannot succeed). The class shows beside the
Parked badge on the dashboard, so "needs you" reads as a request rather
than a failure.
- **Operator retries and review-remediation rounds now have separate
budgets.** An operator's manual retries no longer draw down the rounds
Archie may spend addressing review feedback on its pull requests, and a
round-cap park no longer makes a later retry re-park immediately.
- **`latest` now names the newest release. A push to `main` that is not a
release publishes `edge` and `sha-<commit>` instead. A host that was
following `main` by pulling `latest` stops advancing at this release --
switch it to `edge` to keep tracking `main`, or leave it on `latest` to
follow releases.**
### archie-agent
- The park-classification wire format is part of this image; a host that
runs the agent should `docker compose pull agent` to pick it up.
-35
View File
@@ -1,35 +0,0 @@
# 1.5.0
Released 2026-08-08. [All news](index.md)
### archied
- feat(curator): engine family contract, registry, and runtime
- feat(curator): trigger accounting — primary-input wake path
- feat(setup): interactive setup steps with a TTY-gated prompter
- feat(webui): rebuild the dashboard and add chat
- feat(daemon): identity-scoped isolation plus gateway session titles and /delete
- feat(logging): optional rotating log file
- feat(configuration): export Validate for the setup flow
- fix(gateway): durable message identity with a SQLite store
- fix(gateway): consistent message ordering and paged search
- fix(gateway): stop /compress destroying history it should have kept
- fix(gateway): do not answer a redelivered message twice
- fix(gateway): claim the session slot before writing it, not after
- fix(gateway): keep /topic off from poisoning the session cache
- fix(gateway): resolve the most recently active session, not an arbitrary one
- fix(gateway): give branch-inherited messages their own identity
- fix(gateway): make both backends agree on newest-first
- fix(store): honour the transition guard in production persistence
- fix(store): move ID counters away from the reserved metadata namespace
- fix(store): surface task timestamps and tag the summary structs
- fix(telegram): pause the update loop when rate limited
- fix(memory): fail startup on an unusable memory directory
- fix(tools): let an optional provider fail without taking the daemon down
- fix(tools): report a cancelled find walk as an error, not empty results
- fix(worktree): name the missing forge credential when a push fails
- fix(tomlwrite): recognise table headers carrying a trailing comment
- fix: close the duplicate-work loop and the dead paths around it
- perf(tools): drop the embedded ripgrep binaries
- refactor: one definition of what approving or declining a task means
- refactor: move workflow into its own domain
-15
View File
@@ -1,15 +0,0 @@
# 1.6.0
Released 2026-08-09. [All news](index.md)
### archied
- feat(gateway): tool-approval gate, session tools for chat, and /delete command
- fix(webui): close open-redirect in dashboard token-exchange handler
- feat(gateway): make chat turns durable and idempotent
- feat(webui): lifecycle-safe task controls with atomic retry and archive
- feat(config,channels): format-neutral config resolution and truthful channel state
- feat(logging,workflow): daemon log feed and executable workflow registry
- fix(store,gateway): taskstate constants and mobile jump-to search
- feat(webui,gateway): wire config, channel, log-feed, and work-intake seams
- fix(ui): hide inactive chat command menu
-29
View File
@@ -1,29 +0,0 @@
# 1.7.0
Released 2026-08-10. [All news](index.md)
### archied
- fix(build): install ripgrep where grep.go actually needs it on PATH
- fix(webui): Send button no longer passes its click event to sendMessage
- feat(webui): Enter sends, Shift+Enter inserts a newline
- fix(chat): stop showing raw 501 banner for unconfigured update-check
- fix(chat): give chat page a real height budget instead of a floor
- fix(workflow): carry gate output into the baseline park error
- feat(logging): add a per-task log sink
- feat(agentexec): publish agent-side logs to the task's system subject
- feat(daemon): consume agent system logs into per-task sinks and the dashboard feed
- feat(webui,gateway): add /api/tasks/{id}/logs endpoint and task_logs chat tool
- refactor(gateway): persist conversations in sqlite
- refactor(store): replace legacy persistence with SQLite
- fix(webui): tighten configuration KV row spacing
- fix(gateway): harden session recovery paths
- refactor(daemon,webui): make Daemon.Cfg and webui.Server.Cfg reload-safe
- feat(config): SIGHUP-triggered reload with requires-restart warnings
- fix(config): share one config Holder between daemon and dashboard; re-apply model catalog on reload
- fix(config): complete the reloadable allowlist and pin it against ForTask
- feat(config): runtime config overlay store, PATCH /api/config, and the `--no-config-overlay` recovery flag
- feat(webui): inline config editing on the Configuration page
- feat(config): surface overlay state, shadowed keys, and per-row reset
- fix(config): close review blocker on the PATCH path; deep-copy snapshots; atomics for shared state
- fix(config): preserve nil slices in Clone to avoid spurious reload warnings
-18
View File
@@ -1,18 +0,0 @@
# 1.8.0
Released 2026-08-15. [All news](index.md)
### archied
- feat(archied): add -version so the installed build can be read from a shell
- fix(webui): rebuild the Configuration page layout so values stop colliding
- fix(webui): size Configuration key/value lists to their own content
- fix(webui): keep Configuration rows full width, hug only the label column
- fix(webui): cap and centre the Configuration page instead of its lists
- fix(webui): preserve encoded redirect path characters
- feat(chat): show tool calls inline and stream replies into one message
- fix(chat): harden inline tool call streaming
- refactor(agent): move worker runtime into application layer
- fix(telegram): harden live-reply delivery against /stop and multi-byte content
- fix(telegram): keep tool activity visible and mark failed/empty turns
- fix(config): de-duplicate disabled-forge predicate, export ForgeDisabled
-20
View File
@@ -1,20 +0,0 @@
# 1.9.0
Released 2026-08-15. [All news](index.md)
### archied
- fix(webui): style tool-call failure from a structured field, not a string prefix
- fix(config,webui): make show_tool_calls one cross-channel setting
- fix(telegram): guarantee no message is stranded on gateway stop/restart
- fix(telegram): use NewRequestWithContext to satisfy noctx
- refactor(webui): decompose handleSSE to cut cognitive complexity
### archie-agent
- fix(agent): resolve git dubious-ownership in sandbox containers
- feat(agent): mark the mounted worktree as a git safe directory
- fix(agent): route git safe.directory setup through markWorktreeSafe
- feat(chat): show tool calls inline and stream replies into one message
- refactor(agent): move worker runtime into application layer
- fix(config,webui): make show_tool_calls one cross-channel setting
-13
View File
@@ -1,13 +0,0 @@
# 1.9.1
Released 2026-08-15. [All news](index.md)
### archied
- fix(agentworker): forward workflow events across the NATS worker boundary
- fix(webui): filter turn_completed noise from the Live Activity SSE feed
- feat(releaseupdate): stamp install type at build time, fail closed on unknown
### archie-agent
- fix(agentworker): forward workflow events across the NATS worker boundary
-7
View File
@@ -1,7 +0,0 @@
# 1.9.10
Released 2026-08-19. [All news](index.md)
### archied
- feat(update): `/update` now streams live progress while an update installs, reports a clear version summary (previous/installed, daemon/agent) once the build succeeds, and automatically rolls back and reports the outcome if the restarted daemon fails its post-update health check
-7
View File
@@ -1,7 +0,0 @@
# 1.9.11
Released 2026-08-19. [All news](index.md)
### archied
- fix(mcp): persist npx package cache across daemon restarts
-11
View File
@@ -1,11 +0,0 @@
# 1.9.2
Released 2026-08-15. [All news](index.md)
### archied
- fix(worktree): force checkout so retry recovers from a dirty worktree
### archie-agent
- fix(worktree): force checkout so retry recovers from a dirty worktree
-15
View File
@@ -1,15 +0,0 @@
# 1.9.3
Released 2026-08-15. [All news](index.md)
### archied
- fix(webui): scroll selected command into view on keyboard navigation
- fix(logging): resolve error attrs to their message string, not {}
- feat(agentexec,workflow): surface tool calls on the task timeline
### archie-agent
- fix(logging): resolve error attrs to their message string, not {}
- fix(agentworker): back off before refetching a nak'd stage message
- feat(agentexec,workflow): surface tool calls on the task timeline
-12
View File
@@ -1,12 +0,0 @@
# 1.9.4
Released 2026-08-15. [All news](index.md)
### archied
- feat(gateway): polish /status command response format
- fix(telegram): preserve URL boundaries in responses
### archie-agent
- chore: no user-facing changes
-20
View File
@@ -1,20 +0,0 @@
# 1.9.5
Released 2026-08-16. [All news](index.md)
### archied
- refactor(archied): decompose the daemon bootstrap into phased wiring (no behaviour change; splits the ~950-line run() into focused setup phases so complexity linting passes)
- refactor(archied): extract the config overlay boot helper and thread context through chat gateway setup
- refactor(tools): split the read executor and flatten nested config/tool fallback logic to lower complexity
- fix(tools): avoid predeclared `max` names
- fix(email): use context-aware test networking
- fix(indexing): remove the unused code search test runner
- fix(tests): use contexts and type assertions in overlay and gateway tests
- docs(architecture): document the memory engine family
### archie-agent
- refactor: decompose the daemon bootstrap into phased wiring (no behaviour change; complexity-driven restructure)
- refactor(tools): split the read executor and flatten nested config/tool fallback logic to lower complexity
- fix(tools): avoid predeclared `max` names
-11
View File
@@ -1,11 +0,0 @@
# 1.9.6
Released 2026-08-16. [All news](index.md)
### archied
- fix(update): stamp install type and bound retry backoff
### archie-agent
- chore: no user-facing changes
-11
View File
@@ -1,11 +0,0 @@
# 1.9.7
Released 2026-08-17. [All news](index.md)
### archied
- chore: no user-facing changes
### archie-agent
- chore: no user-facing changes
Loaded 100 of 608 files, more files were not shown because too many files have changed in this diff. Show more